prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|># Copyright (c) 2008 Joost Cassee # Licensed under the terms of the MIT License (see LICENSE.txt) """ This TinyMCE widget was copied and extended from this code by John D'Agostino: http://code.djangoproject.com/wiki/CustomWidgetsTinyMCE """ from django import forms from django.conf import settings from django.contrib.admin import widgets as admin_widgets from django.core.urlresolvers import reverse from django.forms.widgets import flatatt from django.utils.encoding import smart_unicode from django.utils.html import escape from django.utils import simplejson from django.utils.datastructures import SortedDict from django.utils.safestring import mark_safe from django.utils.translation import get_language, ugettext as _ import tinymce.settings class TinyMCE(forms.Textarea): """ TinyMCE widget. Set settings.TINYMCE_JS_URL to set the location of the javascript file. Default is "MEDIA_URL + 'js/tiny_mce/tiny_mce.js'". You can customize the configuration with the mce_attrs argument to the constructor. In addition to the standard configuration you can set the 'content_language' parameter. It takes the value of the 'language' parameter by default. In addition to the default settings from settings.TINYMCE_DEFAULT_CONFIG, this widget sets the 'language', 'directionality' and 'spellchecker_languages' parameters by default. The first is derived from the current Django language, the others from the 'content_language' parameter. """ def __init__(self, content_language=None, attrs=None, mce_attrs={}): super(TinyMCE, self).__init__(attrs) self.mce_attrs = mce_attrs if content_language is None: content_language = mce_attrs.get('language', None) self.content_language = content_language def render(self, name, value, attrs=None): if value is None: value = '' value = smart_unicode(value) final_attrs = self.build_attrs(attrs) final_attrs['name'] = name assert 'id' in final_attrs, "TinyMCE widget attributes must contain 'id'" mce_config = tinymce.settings.DEFAULT_CONFIG.copy() mce_config.update(get_language_config(self.content_language)) if tinymce.settings.USE_FILEBROWSER: mce_config['file_browser_callback'] = "djangoFileBrowser" mce_config.update(self.mce_attrs) mce_config['mode'] = 'exact' mce_config['elements'] = final_attrs['id'] mce_config['strict_loading_mode'] = 1 mce_json = simplejson.dumps(mce_config) html = [u'<textarea%s>%s</textarea>' % (flatatt(final_attrs), escape(value))] if tinymce.settings.USE_COMPRESSOR: compressor_config = { 'plugins': mce_config.get('plugins', ''), 'themes': mce_config.get('theme', 'advanced'), 'languages': mce_config.get('language', ''), 'diskcache': True, 'debug': False, } compressor_json = simplejson.dumps(compressor_config) html.append(u'<script type="text/javascript">tinyMCE_GZ.init(%s)</script>' % compressor_json) html.append(u'<script type="text/javascript">tinyMCE.init(%s)</script>' % mce_json) return mark_safe(u'\n'.join(html)) def _media(self): if tinymce.settings.USE_COMPRESSOR: js = [reverse('tinymce-compressor')] else: js = [tinymce.settings.JS_URL] if tinymce.settings.USE_FILEBROWSER: js.append(reverse('tinymce-filebrowser')) return forms.Media(js=js) media = property(_media) class AdminTinyMCE(admin_widgets.AdminTextareaWidget, TinyMCE): pass def get_language_config(content_language=None): language = get_language()[:2] if content_language: content_language = content_language[:2] else: content_language = language config = {} config['language'] = language lang_names = SortedDict() for lang, name in settings.LANGUAGES: if lang[:2] not in lang_names: lang_names[lang[:2]] = [] lang_names[lang[:2]].append(_(name)) sp_langs = []<|fim▁hole|> default = '+' else: default = '' sp_langs.append(u'%s%s=%s' % (default, ' / '.join(names), lang)) config['spellchecker_languages'] = ','.join(sp_langs) if content_language in settings.LANGUAGES_BIDI: config['directionality'] = 'rtl' else: config['directionality'] = 'ltr' if tinymce.settings.USE_SPELLCHECKER: config['spellchecker_rpc_url'] = reverse('tinymce.views.spell_check') return config<|fim▁end|>
for lang, names in lang_names.items(): if lang == content_language:
<|file_name|>cache-plugin.js<|end_file_name|><|fim▁begin|>version https://git-lfs.github.com/spec/v1 oid sha256:5b06c8bb34dea0d08a98bb98d8fc80c43e4c6e36f6051a72b41fd447afd37cfc<|fim▁hole|><|fim▁end|>
size 1253
<|file_name|>train.py<|end_file_name|><|fim▁begin|># Example implementing 5 layer encoder # Original code taken from # https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/autoencoder.py # The model trained here is restored in load.py from __future__ import division, print_function, absolute_import # Import MNIST data # from tensorflow.examples.tutorials.mnist import input_data # data_set = input_data.read_data_sets("/tmp/data/", one_hot=True) # Import libraries import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import sys import scipy.io as sio sys.path.insert(0, '../..') # Add path to where TF_Model.py is, if not in the same dir from TF_Model import * from utils import * # 01 thumb # 10 pinky action_map = {} action_map[1] = [0,1] action_map[2] = [1,0]<|fim▁hole|># thumb up mat_contents_t0 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_pinky_Jan5_0.mat') mat_contents_t1 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_pinky_Jan5_1.mat') mat_contents_test0 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_pinky_jan5_2.mat') data_t0 = mat_contents_t0['EMGdata'] data_t1 = mat_contents_t1['EMGdata'] data_test0 = mat_contents_test0['EMGdata'] batch_y_t0, batch_x_t0 = get_batch_from_raw_data_new_format(data_t0, action_map, [0]) batch_y_t1, batch_x_t1 = get_batch_from_raw_data_new_format(data_t1, action_map, [0]) batch_y_test0, batch_x_test0 = get_batch_from_raw_data_new_format(data_test0, action_map, [0]) # pinky up mat_contents_p0 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_thumb_Jan5_0.mat') mat_contents_p1 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_thumb_Jan5_1.mat') mat_contents_test1 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_thumb_Jan5_2.mat') data_p0 = mat_contents_p0['EMGdata'] data_p1 = mat_contents_p1['EMGdata'] data_test1 = mat_contents_test1['EMGdata'] batch_y_p0, batch_x_p0 = get_batch_from_raw_data_new_format(data_p0, action_map, [0]) batch_y_p1, batch_x_p1 = get_batch_from_raw_data_new_format(data_p1, action_map, [0]) batch_y_test1, batch_x_test1 = get_batch_from_raw_data_new_format(data_test1, action_map, [0]) print("done reading data") # Create TF_Model, a wrapper for models created using tensorflow # Note that the configuration file 'config.txt' must be present in the directory model = TF_Model('model') # Parameters learning_rate = 0.05 training_epochs = 200 batch_size = 256 display_step = 1 examples_to_show = 10 # total_batch = int(data_set.train.num_examples/batch_size) dropout = tf.placeholder(tf.float32) # Create variables for inputs, outputs and predictions x = tf.placeholder(tf.float32, [None, 1000]) y = tf.placeholder(tf.float32, [None, 2]) y_true = y y_pred = model.predict(x) # Cost function cost = tf.reduce_mean(tf.pow(y_true - y_pred, 2)) optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost) # Initializing the variables init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) model_output = model.predict(x) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(model_output), reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(model_output,1), tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # Train for epoch in range(training_epochs): _, c = sess.run([optimizer, cost], feed_dict={x: batch_x_t0, y: batch_y_t0}) _, c = sess.run([optimizer, cost], feed_dict={x: batch_x_t1, y: batch_y_t1}) _, c = sess.run([optimizer, cost], feed_dict={x: batch_x_p0, y: batch_y_p0}) _, c = sess.run([optimizer, cost], feed_dict={x: batch_x_p1, y: batch_y_p1}) # Display logs per epoch step print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c)) print(sess.run(accuracy, feed_dict={x: batch_x_test0, y: batch_y_test0})) print(sess.run(accuracy, feed_dict={x: batch_x_test1, y: batch_y_test1})) print("===final===") print(sess.run(accuracy, feed_dict={x: batch_x_test0, y: batch_y_test0})) print(sess.run(accuracy, feed_dict={x: batch_x_test1, y: batch_y_test1})) # Save model.save(sess, 'example_3')<|fim▁end|>
<|file_name|>main.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """rds-create-cpu-alarms Script used to create CPUUtilization alarms in AWS CloudWatch for all RDS instances. A upper-limit threshold needs to be defined. Usage: rds-create-cpu-alarms [options] <threshold> <sns_topic_arn> <region> rds-create-cpu-alarms -h | --help Options: -h --help Show this screen. --debug Don't send data to AWS """ import boto.ec2 import boto.rds2 from docopt import docopt from boto.ec2.cloudwatch import MetricAlarm from .constants import VERSION DEBUG = False def get_rds_instances(region): """ Retrieves the list of all RDS instances Args: region (str) Returns: (list) List of valid state RDS instances """ assert isinstance(region, str) rds = boto.rds2.connect_to_region(region) response = rds.describe_db_instances() rds_instances = (response[u'DescribeDBInstancesResponse'] [u'DescribeDBInstancesResult'] [u'DBInstances'] ) return rds_instances def get_existing_cpuutilization_alarm_names(aws_cw_connect): """ Creates a CPUUtilization alarm for all RDS instances Args: aws_cw_connect (CloudWatchConnection) Returns: (set) Existing CPUUtilization alarm names """ assert isinstance(aws_cw_connect, boto.ec2.cloudwatch.CloudWatchConnection) existing_alarms = aws_cw_connect.describe_alarms() existing_alarm_names = set() for existing_alarm in existing_alarms: existing_alarm_names.add(existing_alarm.name) return existing_alarm_names <|fim▁hole|> sns_topic_arn): """ Creates a CPUUtilization alarm for all RDS instances Args: rds_instances (list) List of all RDS instances threshold (int) The upper limit after which alarm activates aws_cw_connect (CloudWatchConnection) sns_topic_arn (str) Returns: (set) All CPUUtilization alarms that will be created """ assert isinstance(rds_instances, list) assert isinstance(aws_cw_connect, boto.ec2.cloudwatch.CloudWatchConnection) assert isinstance(threshold, int) assert isinstance(sns_topic_arn, str) alarms_to_create = set() existing_alarms = get_existing_cpuutilization_alarm_names(aws_cw_connect) for instance in rds_instances: # initiate a CPUUtilization MetricAlarm object for each RDS instance cpu_utilization_alarm = MetricAlarm( name=u'RDS-{}-High-CPUUtilization'.format( instance[u'DBInstanceIdentifier'] ), namespace=u'AWS/RDS', metric=u'CPUUtilization', statistic='Average', comparison=u'>', threshold=threshold, period=60, evaluation_periods=50, alarm_actions=[sns_topic_arn], dimensions={u'DBInstanceIdentifier': instance[u'DBInstanceIdentifier'] } ) if cpu_utilization_alarm.name not in existing_alarms: alarms_to_create.add(cpu_utilization_alarm) return alarms_to_create def main(): args = docopt(__doc__, version=VERSION) global DEBUG if args['--debug']: DEBUG = True region = args['<region>'] sns_topic_arn = args['<sns_topic_arn>'] rds_instances = get_rds_instances(region) aws_cw_connect = boto.ec2.cloudwatch.connect_to_region(region) alarms_to_create = get_cpuutilization_alarms_to_create( rds_instances, int(args['<threshold>']), aws_cw_connect, sns_topic_arn ) if alarms_to_create: if DEBUG: for alarm in alarms_to_create: print('DEBUG:', alarm) else: print('New RDS CPUUtilization Alarms created:') for alarm in alarms_to_create: print(alarm) aws_cw_connect.create_alarm(alarm) if __name__ == '__main__': main()<|fim▁end|>
def get_cpuutilization_alarms_to_create(rds_instances, threshold, aws_cw_connect,
<|file_name|>stack.py<|end_file_name|><|fim▁begin|># Stack implementation class Stack (object): def __init__ (self): self.stack = [] def push (self, data): self.stack.append(data) def peek (self):<|fim▁hole|> return None return self.stack[-1] def pop (self): if self.isEmpty(): return None return self.stack.pop() def isEmpty (self): return len(self.stack) == 0 def __str__ (self): return ' '.join(str(x) for x in self.stack)<|fim▁end|>
if self.isEmpty():
<|file_name|>_generate-readme.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python # -*- coding: utf-8 -*- import subprocess import os def path(*path_segments): return os.path.join(os.getcwd(), *path_segments) def open_file(*path_segments): file_path = path(*path_segments) open(file_path, 'w').close() return open(file_path, 'a') header = open(path('README_header.rst'), 'r') readme = open_file('README.rst') sphinx = open_file('doc', 'source', 'cli.rst') sphinx_header = ( 'Comande line interface\n', '======================\n', '\n', '.. code-block:: text\n', '\n', ) for line in sphinx_header: sphinx.write(str(line)) footer = open(path('README_footer.rst'), 'r') <|fim▁hole|>for line in header: readme.write(line) audiorenamer = subprocess.Popen('audiorenamer --help', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) readme.write('\n') for line in audiorenamer.stdout: indented_line = ' ' + line.decode('utf-8') readme.write(indented_line) sphinx.write(indented_line) audiorenamer.wait() for line in footer: readme.write(line) readme.close() sphinx.close()<|fim▁end|>
<|file_name|>aaspi_file.py<|end_file_name|><|fim▁begin|>#!/bin/env python #========================================================================== # (c) 2004 Total Phase, Inc. #-------------------------------------------------------------------------- # Project : Aardvark Sample Code # File : aaspi_file.c #-------------------------------------------------------------------------- # Configure the device as an SPI master and send data. #-------------------------------------------------------------------------- # Redistribution and use of this file in source and binary forms, with # or without modification, are permitted. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. #========================================================================== #========================================================================== # IMPORTS #========================================================================== import sys from aardvark_py import * #========================================================================== # CONSTANTS #========================================================================== BUFFER_SIZE = 2048 SPI_BITRATE = 1000 #========================================================================== # FUNCTIONS #========================================================================== def blast_bytes (handle, filename): # Open the file try: f=open(filename, 'rb') except: print "Unable to open file '" + filename + "'" return trans_num = 0 while 1: # Read from the file filedata = f.read(BUFFER_SIZE) if (len(filedata) == 0): break # Write the data to the bus data_out = array('B', filedata) data_in = array_u08(len(data_out)) (count, data_in) = aa_spi_write(handle, data_out, data_in) if (count < 0): print "error: %s" % aa_status_string(count) break elif (count != len(data_out)): print "error: only a partial number of bytes written" print " (%d) instead of full (%d)" % (count, num_write) sys.stdout.write("*** Transaction #%02d\n" % trans_num) sys.stdout.write("Data written to device:") for i in range(count): if ((i&0x0f) == 0): sys.stdout.write("\n%04x: " % i) sys.stdout.write("%02x " % (data_out[i] & 0xff)) if (((i+1)&0x07) == 0): sys.stdout.write(" ") sys.stdout.write("\n\n") sys.stdout.write("Data read from device:") for i in range(count): if ((i&0x0f) == 0): sys.stdout.write("\n%04x: " % i) sys.stdout.write("%02x " % (data_in[i] & 0xff)) if (((i+1)&0x07) == 0): sys.stdout.write(" ") sys.stdout.write("\n\n") trans_num = trans_num + 1 # Sleep a tad to make sure slave has time to process this request aa_sleep_ms(10) f.close() #========================================================================== # MAIN PROGRAM #========================================================================== if (len(sys.argv) < 4): print "usage: aaspi_file PORT MODE filename" print " mode 0 : pol = 0, phase = 0" print " mode 1 : pol = 0, phase = 1" print " mode 2 : pol = 1, phase = 0" print " mode 3 : pol = 1, phase = 1" print "" print " 'filename' should contain data to be sent" print " to the downstream spi device" sys.exit() port = int(sys.argv[1]) mode = int(sys.argv[2]) filename = sys.argv[3] handle = aa_open(port) if (handle <= 0): print "Unable to open Aardvark device on port %d" % port print "Error code = %d" % handle sys.exit() # Ensure that the SPI subsystem is enabled aa_configure(handle, AA_CONFIG_SPI_I2C) # Enable the Aardvark adapter's power supply. # This command is only effective on v2.0 hardware or greater. # The power pins on the v1.02 hardware are not enabled by default. aa_target_power(handle, AA_TARGET_POWER_BOTH) # Setup the clock phase aa_spi_configure(handle, mode >> 1, mode & 1, AA_SPI_BITORDER_MSB) # Set the bitrate bitrate = aa_spi_bitrate(handle, SPI_BITRATE) print "Bitrate set to %d kHz" % bitrate<|fim▁hole|> # Close the device aa_close(handle)<|fim▁end|>
blast_bytes(handle, filename)
<|file_name|>Spinner.py<|end_file_name|><|fim▁begin|>import sublime from . import SblmCmmnFnctns <|fim▁hole|> SYMBOLS_BOX = u'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏' def __init__(self, symbols, view, startStr, endStr): self.symbols = symbols self.length = len(symbols) self.position = 0 self.stopFlag = False self.view = view self.startStr = startStr self.endStr = endStr def __next__(self): self.position = self.position + 1 return self.startStr + self.symbols[self.position % self.length] + self.endStr def start(self): if not self.stopFlag: self.view.set_status(SblmCmmnFnctns.SUBLIME_STATUS_SPINNER, self.__next__()) sublime.set_timeout(lambda: self.start(), 300) def stop(self): self.view.erase_status(SblmCmmnFnctns.SUBLIME_STATUS_SPINNER) self.stopFlag = True<|fim▁end|>
class Spinner: SYMBOLS_ROW = u'←↑→↓'
<|file_name|>file-matcher.js<|end_file_name|><|fim▁begin|>/* Copyright (c) 2012, Yahoo! Inc. All rights reserved. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ var fileset = require('fileset'), path = require('path'), seq = 0; function filesFor(options, callback) { if (!callback && typeof options === 'function') {<|fim▁hole|> var root = options.root, includes = options.includes, excludes = options.excludes, relative = options.relative, opts; root = root || process.cwd(); includes = includes && Array.isArray(includes) ? includes : [ '**/*.js' ]; excludes = excludes && Array.isArray(excludes) ? excludes : [ '**/node_modules/**' ]; opts = { cwd: root }; seq += 1; opts['x' + seq + new Date().getTime()] = true; //cache buster for minimatch cache bug fileset(includes.join(' '), excludes.join(' '), opts, function (err, files) { if (err) { return callback(err); } if (!relative) { files = files.map(function (file) { return path.resolve(root, file); }); } callback(err, files); }); } function matcherFor(options, callback) { if (!callback && typeof options === 'function') { callback = options; options = null; } options = options || {}; options.relative = false; //force absolute paths filesFor(options, function (err, files) { var fileMap = {}, matchFn; if (err) { return callback(err); } files.forEach(function (file) { fileMap[file] = true; }); matchFn = function (file) { return fileMap[file]; }; matchFn.files = Object.keys(fileMap); return callback(null, matchFn); }); } module.exports = { filesFor: filesFor, matcherFor: matcherFor };<|fim▁end|>
callback = options; options = null; } options = options || {};
<|file_name|>Image.cpp<|end_file_name|><|fim▁begin|>/* * Copyright 2011 Matthias Fuchs * * 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. */ #include <stromx/runtime/Data.h> #include <stromx/runtime/Image.h> #include <stromx/cvsupport/Image.h> #include <memory> #include <boost/python.hpp> using namespace boost::python; using namespace stromx::runtime; namespace<|fim▁hole|> { return std::auto_ptr<stromx::cvsupport::Image>(new stromx::cvsupport::Image(width, height, pixelType)); } std::auto_ptr<stromx::cvsupport::Image> allocateFromFile(const std::string & filename) { return std::auto_ptr<stromx::cvsupport::Image>(new stromx::cvsupport::Image(filename)); } std::auto_ptr<stromx::cvsupport::Image> allocateFromFileWithAccess(const std::string & filename, const stromx::cvsupport::Image::Conversion access) { return std::auto_ptr<stromx::cvsupport::Image>(new stromx::cvsupport::Image(filename, access)); } } void exportImage() { scope in_Operator = class_<stromx::cvsupport::Image, bases<stromx::runtime::Image>, std::auto_ptr<stromx::cvsupport::Image> >("Image", no_init) .def("__init__", make_constructor(&allocateFromFile)) .def("__init__", make_constructor(&allocateFromDimension)) .def("__init__", make_constructor(&allocateFromFileWithAccess)) .def<void (stromx::cvsupport::Image::*)(const std::string &) const>("save", &stromx::cvsupport::Image::save) .def<void (stromx::cvsupport::Image::*)(const std::string &)>("open", &stromx::cvsupport::Image::open) .def<void (stromx::cvsupport::Image::*)(const std::string &, const stromx::cvsupport::Image::Conversion)>("open", &stromx::cvsupport::Image::open) .def<void (stromx::cvsupport::Image::*)(const unsigned int, const unsigned int, const Image::PixelType)>("resize", &stromx::cvsupport::Image::resize) ; enum_<stromx::cvsupport::Image::Conversion>("Conversion") .value("UNCHANGED", stromx::cvsupport::Image::UNCHANGED) .value("GRAYSCALE", stromx::cvsupport::Image::GRAYSCALE) .value("COLOR", stromx::cvsupport::Image::COLOR) ; implicitly_convertible< std::auto_ptr<stromx::cvsupport::Image>, std::auto_ptr<Data> >(); }<|fim▁end|>
{ std::auto_ptr<stromx::cvsupport::Image> allocateFromDimension(const unsigned int width, const unsigned int height, const Image::PixelType pixelType)
<|file_name|>test_with_shap.py<|end_file_name|><|fim▁begin|>import numpy as np import xgboost as xgb import pytest try: import shap except ImportError: shap = None<|fim▁hole|> pass pytestmark = pytest.mark.skipif(shap is None, reason="Requires shap package") # Check integration is not broken from xgboost side # Changes in binary format may cause problems def test_with_shap(): from sklearn.datasets import fetch_california_housing X, y = fetch_california_housing(return_X_y=True) dtrain = xgb.DMatrix(X, label=y) model = xgb.train({"learning_rate": 0.01}, dtrain, 10) explainer = shap.TreeExplainer(model) shap_values = explainer.shap_values(X) margin = model.predict(dtrain, output_margin=True) assert np.allclose(np.sum(shap_values, axis=len(shap_values.shape) - 1), margin - explainer.expected_value, 1e-3, 1e-3)<|fim▁end|>
<|file_name|>test_label_semantic_roles.py<|end_file_name|><|fim▁begin|># Copyright (c) 2018 PaddlePaddle 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. import contextlib import math import numpy as np import os import time import unittest import paddle import paddle.dataset.conll05 as conll05 import paddle.fluid as fluid word_dict, verb_dict, label_dict = conll05.get_dict() word_dict_len = len(word_dict) label_dict_len = len(label_dict) pred_dict_len = len(verb_dict) mark_dict_len = 2 word_dim = 32 mark_dim = 5 hidden_dim = 512 depth = 8 mix_hidden_lr = 1e-3 IS_SPARSE = True PASS_NUM = 10 BATCH_SIZE = 10 embedding_name = 'emb' def load_parameter(file_name, h, w): with open(file_name, 'rb') as f: f.read(16) # skip header. return np.fromfile(f, dtype=np.float32).reshape(h, w) def db_lstm(word, predicate, ctx_n2, ctx_n1, ctx_0, ctx_p1, ctx_p2, mark, **ignored): # 8 features predicate_embedding = fluid.layers.embedding( input=predicate, size=[pred_dict_len, word_dim], dtype='float32', is_sparse=IS_SPARSE, param_attr='vemb') mark_embedding = fluid.layers.embedding( input=mark, size=[mark_dict_len, mark_dim], dtype='float32', is_sparse=IS_SPARSE) word_input = [word, ctx_n2, ctx_n1, ctx_0, ctx_p1, ctx_p2] emb_layers = [ fluid.layers.embedding( size=[word_dict_len, word_dim], input=x, param_attr=fluid.ParamAttr( name=embedding_name, trainable=False)) for x in word_input ] emb_layers.append(predicate_embedding) emb_layers.append(mark_embedding) hidden_0_layers = [ fluid.layers.fc(input=emb, size=hidden_dim, act='tanh') for emb in emb_layers ] hidden_0 = fluid.layers.sums(input=hidden_0_layers) lstm_0 = fluid.layers.dynamic_lstm( input=hidden_0, size=hidden_dim, candidate_activation='relu', gate_activation='sigmoid', cell_activation='sigmoid') # stack L-LSTM and R-LSTM with direct edges input_tmp = [hidden_0, lstm_0] for i in range(1, depth): mix_hidden = fluid.layers.sums(input=[ fluid.layers.fc(input=input_tmp[0], size=hidden_dim, act='tanh'), fluid.layers.fc(input=input_tmp[1], size=hidden_dim, act='tanh') ]) lstm = fluid.layers.dynamic_lstm( input=mix_hidden, size=hidden_dim, candidate_activation='relu', gate_activation='sigmoid', cell_activation='sigmoid', is_reverse=((i % 2) == 1)) input_tmp = [mix_hidden, lstm] feature_out = fluid.layers.sums(input=[ fluid.layers.fc(input=input_tmp[0], size=label_dict_len, act='tanh'), fluid.layers.fc(input=input_tmp[1], size=label_dict_len, act='tanh') ]) return feature_out def to_lodtensor(data, place): seq_lens = [len(seq) for seq in data] cur_len = 0 lod = [cur_len] for l in seq_lens: cur_len += l lod.append(cur_len) flattened_data = np.concatenate(data, axis=0).astype("int64") flattened_data = flattened_data.reshape([len(flattened_data), 1]) res = fluid.LoDTensor() res.set(flattened_data, place) res.set_lod([lod]) return res def create_random_lodtensor(lod, place, low, high): data = np.random.random_integers(low, high, [lod[-1], 1]).astype("int64") res = fluid.LoDTensor() res.set(data, place) res.set_lod([lod]) return res def train(use_cuda, save_dirname=None, is_local=True): # define network topology word = fluid.layers.data( name='word_data', shape=[1], dtype='int64', lod_level=1) predicate = fluid.layers.data( name='verb_data', shape=[1], dtype='int64', lod_level=1) ctx_n2 = fluid.layers.data( name='ctx_n2_data', shape=[1], dtype='int64', lod_level=1) ctx_n1 = fluid.layers.data( name='ctx_n1_data', shape=[1], dtype='int64', lod_level=1) ctx_0 = fluid.layers.data( name='ctx_0_data', shape=[1], dtype='int64', lod_level=1) ctx_p1 = fluid.layers.data( name='ctx_p1_data', shape=[1], dtype='int64', lod_level=1) ctx_p2 = fluid.layers.data( name='ctx_p2_data', shape=[1], dtype='int64', lod_level=1) mark = fluid.layers.data( name='mark_data', shape=[1], dtype='int64', lod_level=1) feature_out = db_lstm(**locals()) target = fluid.layers.data( name='target', shape=[1], dtype='int64', lod_level=1) crf_cost = fluid.layers.linear_chain_crf( input=feature_out, label=target, param_attr=fluid.ParamAttr( name='crfw', learning_rate=mix_hidden_lr)) avg_cost = fluid.layers.mean(crf_cost) # TODO(qiao) # check other optimizers and check why out will be NAN sgd_optimizer = fluid.optimizer.SGD( learning_rate=fluid.layers.exponential_decay( learning_rate=0.01, decay_steps=100000,<|fim▁hole|> # TODO(qiao) # add dependency track and move this config before optimizer crf_decode = fluid.layers.crf_decoding( input=feature_out, param_attr=fluid.ParamAttr(name='crfw')) train_data = paddle.batch( paddle.reader.shuffle( paddle.dataset.conll05.test(), buf_size=8192), batch_size=BATCH_SIZE) place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace() feeder = fluid.DataFeeder( feed_list=[ word, ctx_n2, ctx_n1, ctx_0, ctx_p1, ctx_p2, predicate, mark, target ], place=place) exe = fluid.Executor(place) def train_loop(main_program): exe.run(fluid.default_startup_program()) embedding_param = fluid.global_scope().find_var( embedding_name).get_tensor() embedding_param.set( load_parameter(conll05.get_embedding(), word_dict_len, word_dim), place) start_time = time.time() batch_id = 0 for pass_id in xrange(PASS_NUM): for data in train_data(): cost = exe.run(main_program, feed=feeder.feed(data), fetch_list=[avg_cost]) cost = cost[0] if batch_id % 10 == 0: print("avg_cost:" + str(cost)) if batch_id != 0: print("second per batch: " + str((time.time( ) - start_time) / batch_id)) # Set the threshold low to speed up the CI test if float(cost) < 60.0: if save_dirname is not None: # TODO(liuyiqun): Change the target to crf_decode fluid.io.save_inference_model(save_dirname, [ 'word_data', 'verb_data', 'ctx_n2_data', 'ctx_n1_data', 'ctx_0_data', 'ctx_p1_data', 'ctx_p2_data', 'mark_data' ], [feature_out], exe) return batch_id = batch_id + 1 if is_local: train_loop(fluid.default_main_program()) else: port = os.getenv("PADDLE_INIT_PORT", "6174") pserver_ips = os.getenv("PADDLE_INIT_PSERVERS") # ip,ip... eplist = [] for ip in pserver_ips.split(","): eplist.append(':'.join([ip, port])) pserver_endpoints = ",".join(eplist) # ip:port,ip:port... trainers = int(os.getenv("TRAINERS")) current_endpoint = os.getenv("POD_IP") + ":" + port trainer_id = int(os.getenv("PADDLE_INIT_TRAINER_ID")) training_role = os.getenv("TRAINING_ROLE", "TRAINER") t = fluid.DistributeTranspiler() t.transpile(trainer_id, pservers=pserver_endpoints, trainers=trainers) if training_role == "PSERVER": pserver_prog = t.get_pserver_program(current_endpoint) pserver_startup = t.get_startup_program(current_endpoint, pserver_prog) exe.run(pserver_startup) exe.run(pserver_prog) elif training_role == "TRAINER": train_loop(t.get_trainer_program()) def infer(use_cuda, save_dirname=None): if save_dirname is None: return place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace() exe = fluid.Executor(place) inference_scope = fluid.core.Scope() with fluid.scope_guard(inference_scope): # Use fluid.io.load_inference_model to obtain the inference program desc, # the feed_target_names (the names of variables that will be feeded # data using feed operators), and the fetch_targets (variables that # we want to obtain data from using fetch operators). [inference_program, feed_target_names, fetch_targets] = fluid.io.load_inference_model(save_dirname, exe) lod = [0, 4, 10] word = create_random_lodtensor( lod, place, low=0, high=word_dict_len - 1) pred = create_random_lodtensor( lod, place, low=0, high=pred_dict_len - 1) ctx_n2 = create_random_lodtensor( lod, place, low=0, high=word_dict_len - 1) ctx_n1 = create_random_lodtensor( lod, place, low=0, high=word_dict_len - 1) ctx_0 = create_random_lodtensor( lod, place, low=0, high=word_dict_len - 1) ctx_p1 = create_random_lodtensor( lod, place, low=0, high=word_dict_len - 1) ctx_p2 = create_random_lodtensor( lod, place, low=0, high=word_dict_len - 1) mark = create_random_lodtensor( lod, place, low=0, high=mark_dict_len - 1) # Construct feed as a dictionary of {feed_target_name: feed_target_data} # and results will contain a list of data corresponding to fetch_targets. assert feed_target_names[0] == 'word_data' assert feed_target_names[1] == 'verb_data' assert feed_target_names[2] == 'ctx_n2_data' assert feed_target_names[3] == 'ctx_n1_data' assert feed_target_names[4] == 'ctx_0_data' assert feed_target_names[5] == 'ctx_p1_data' assert feed_target_names[6] == 'ctx_p2_data' assert feed_target_names[7] == 'mark_data' results = exe.run(inference_program, feed={ feed_target_names[0]: word, feed_target_names[1]: pred, feed_target_names[2]: ctx_n2, feed_target_names[3]: ctx_n1, feed_target_names[4]: ctx_0, feed_target_names[5]: ctx_p1, feed_target_names[6]: ctx_p2, feed_target_names[7]: mark }, fetch_list=fetch_targets, return_numpy=False) print(results[0].lod()) np_data = np.array(results[0]) print("Inference Shape: ", np_data.shape) def main(use_cuda, is_local=True): if use_cuda and not fluid.core.is_compiled_with_cuda(): return # Directory for saving the trained model save_dirname = "label_semantic_roles.inference.model" train(use_cuda, save_dirname, is_local) infer(use_cuda, save_dirname) class TestLabelSemanticRoles(unittest.TestCase): def test_cuda(self): with self.scope_prog_guard(): main(use_cuda=True) def test_cpu(self): with self.scope_prog_guard(): main(use_cuda=False) @contextlib.contextmanager def scope_prog_guard(self): prog = fluid.Program() startup_prog = fluid.Program() scope = fluid.core.Scope() with fluid.scope_guard(scope): with fluid.program_guard(prog, startup_prog): yield if __name__ == '__main__': unittest.main()<|fim▁end|>
decay_rate=0.5, staircase=True)) sgd_optimizer.minimize(avg_cost)
<|file_name|>internal.go<|end_file_name|><|fim▁begin|>package internal import ( "bufio" "crypto/rand" "crypto/tls" "crypto/x509" "errors" "fmt" "io/ioutil" "os" "strings" "time" "unicode" ) const alphanum string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" // Duration just wraps time.Duration type Duration struct { Duration time.Duration } // UnmarshalTOML parses the duration from the TOML config file func (d *Duration) UnmarshalTOML(b []byte) error { dur, err := time.ParseDuration(string(b[1 : len(b)-1])) if err != nil { return err } d.Duration = dur return nil } var NotImplementedError = errors.New("not implemented yet") // ReadLines reads contents from a file and splits them by new lines. // A convenience wrapper to ReadLinesOffsetN(filename, 0, -1). func ReadLines(filename string) ([]string, error) { return ReadLinesOffsetN(filename, 0, -1) } // ReadLines reads contents from file and splits them by new line. // The offset tells at which line number to start. // The count determines the number of lines to read (starting from offset): // n >= 0: at most n lines // n < 0: whole file func ReadLinesOffsetN(filename string, offset uint, n int) ([]string, error) { f, err := os.Open(filename) if err != nil { return []string{""}, err } defer f.Close() var ret []string r := bufio.NewReader(f) for i := 0; i < n+int(offset) || n < 0; i++ { line, err := r.ReadString('\n') if err != nil { break } if i < int(offset) { continue } ret = append(ret, strings.Trim(line, "\n")) } return ret, nil } // RandomString returns a random string of alpha-numeric characters func RandomString(n int) string { var bytes = make([]byte, n) rand.Read(bytes) for i, b := range bytes { bytes[i] = alphanum[b%byte(len(alphanum))] } return string(bytes) } // GetTLSConfig gets a tls.Config object from the given certs, key, and CA files. // you must give the full path to the files. // If all files are blank and InsecureSkipVerify=false, returns a nil pointer. func GetTLSConfig( SSLCert, SSLKey, SSLCA string, InsecureSkipVerify bool,<|fim▁hole|> return nil, nil } t := &tls.Config{ InsecureSkipVerify: InsecureSkipVerify, } if SSLCA != "" { caCert, err := ioutil.ReadFile(SSLCA) if err != nil { return nil, errors.New(fmt.Sprintf("Could not load TLS CA: %s", err)) } caCertPool := x509.NewCertPool() caCertPool.AppendCertsFromPEM(caCert) t.RootCAs = caCertPool } if SSLCert != "" && SSLKey != "" { cert, err := tls.LoadX509KeyPair(SSLCert, SSLKey) if err != nil { return nil, errors.New(fmt.Sprintf( "Could not load TLS client key/certificate: %s", err)) } t.Certificates = []tls.Certificate{cert} t.BuildNameToCertificate() } // will be nil by default if nothing is provided return t, nil } // SnakeCase converts the given string to snake case following the Golang format: // acronyms are converted to lower-case and preceded by an underscore. func SnakeCase(in string) string { runes := []rune(in) length := len(runes) var out []rune for i := 0; i < length; i++ { if i > 0 && unicode.IsUpper(runes[i]) && ((i+1 < length && unicode.IsLower(runes[i+1])) || unicode.IsLower(runes[i-1])) { out = append(out, '_') } out = append(out, unicode.ToLower(runes[i])) } return string(out) }<|fim▁end|>
) (*tls.Config, error) { if SSLCert == "" && SSLKey == "" && SSLCA == "" && !InsecureSkipVerify {
<|file_name|>pendingRst.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright 2017 ProjectV 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. from flask_restful import Resource from flask import request, g from v.tools.exception import ExceptionRest from v.tools.v import processing_rest_exception, processing_rest_success, \ type_of_insert_rest, type_of_update_rest from v.tools.validate import validate_rest from v.buy.model.pendingMdl import PendingMdl class PendingListRst(Resource, PendingMdl): def get(self): try: _qrg = """ SELECT array_to_json(array_agg(row_to_json(t) )) as collection FROM ( SELECT id, name, description, completed_at FROM %s WHERE deleted_at IS NULL AND completed_at is NULL AND create_id=%s )t; """ % (self._table, g.user.id,) g.db_conn.execute(_qrg) if g.db_conn.count() > 0: _collection = g.db_conn.one()[0] if _collection: _data = {self._table: _collection} _get = processing_rest_success(data=_data) else: raise ExceptionRest(status_code=404, message="No se han encontrado resultados") else: raise ExceptionRest(status_code=404, message="No se han encontrado resultados") except (Exception, ExceptionRest), e: _get = processing_rest_exception(e) return _get def post(self): _request = request.json try: _errors = validate_rest(fields=self._fields, request=_request) if not _errors: _col, _val = type_of_insert_rest(self._fields, _request) _qrp = """ INSERT INTO %s (create_id , %s ) VALUES (%s, %s) RETURNING (select row_to_json(collection) FROM (VALUES(id)) collection(id)); """ % (self._table, _col, g.user.id, _val) g.db_conn.execute(_qrp) if g.db_conn.count() > 0: _data = {self._table: g.db_conn.one()} _post = processing_rest_success(data=_data, message='Fue creado correctamente', status_code=201) else: raise ExceptionRest(status_code=500, message='No se ha podido registrar') else: raise ExceptionRest(status_code=400, errors=_errors) except (Exception, ExceptionRest), e: _post = processing_rest_exception(e) return _post class PendingRst(Resource, PendingMdl): def get(self, id): try: _qrg = """ SELECT array_to_json(array_agg(row_to_json(t) )) as collection FROM ( SELECT id, name, description, completed_at FROM %s WHERE deleted_at IS NULL AND completed_at is NULL and create_id=%s and id = %s)t; """ % (self._table, g.user.id, id,) g.db_conn.execute(_qrg) if g.db_conn.count() > 0: _collection = g.db_conn.one()[0] if _collection: _data = {self._table: _collection} _get = processing_rest_success(data=_data) else:<|fim▁hole|> _get = processing_rest_exception(e) return _get def put(self, id): _request = request.json try: _errors = validate_rest(fields=self._fields, request=_request, method='put') if not _errors: _val = type_of_update_rest(self._fields, _request) _qrp = "UPDATE %s SET %s WHERE id=%s;" % (self._table, _val, id,) g.db_conn.execute(_qrp) if g.db_conn.count() > 0: _put = processing_rest_success(status_code=201, message="El registro fue actualizado correctamente") else: raise ExceptionRest(status_code=404, message="No se ha podido encontrar el registro, para actualizar.") else: raise ExceptionRest(status_code=400, errors=_errors) except (Exception, ExceptionRest), e: _put = processing_rest_exception(e) return _put def delete(self, id): try: _qrd = "UPDATE %s SET deleted_at=current_timestamp WHERE id=%s;" % (self._table, id,) g.db_conn.execute(_qrd) if g.db_conn.count() > 0: _delete = processing_rest_success(status_code=201, message="El registro fue eliminado correctamente") else: raise ExceptionRest(status_code=404, message="No se ha podido encontrar el registro, para eliminar.") except (Exception, ExceptionRest), e: _delete = processing_rest_exception(e) return _delete<|fim▁end|>
raise ExceptionRest(status_code=404, message="No se han encontrado resultados") else: raise ExceptionRest(status_code=404, message="No se han encontrado resultados") except (Exception, ExceptionRest), e:
<|file_name|>bmp280.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # Author: Jon Trulson <[email protected]> # Copyright (c) 2016 Intel Corporation. # # 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 time, sys, signal, atexit import pyupm_bmp280 as sensorObj # Instantiate a BMP280 instance using default i2c bus and address sensor = sensorObj.BMP280() # For SPI, bus 0, you would pass -1 as the address, and a valid pin for CS: # BMP280(0, -1, 10); ## Exit handlers ## # This function stops python from printing a stacktrace when you hit control-C def SIGINTHandler(signum, frame): raise SystemExit # This function lets you run code on exit def exitHandler(): print "Exiting" sys.exit(0) # Register exit handlers atexit.register(exitHandler)<|fim▁hole|>signal.signal(signal.SIGINT, SIGINTHandler) while (1): sensor.update() print "Compensation Temperature:", sensor.getTemperature(), "C /", print sensor.getTemperature(True), "F" print "Pressure: ", sensor.getPressure(), "Pa" print "Computed Altitude:", sensor.getAltitude(), "m" print time.sleep(1)<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ------------------------------------------------------------------------------------------------ # Software: Stem Applier (staply) # Description: Applies inflections to stem morphemes # Version: 0.0.1a<|fim▁hole|># Module: Main # # Author: Frederic Bayer # Email: [email protected] # Institution: University of Aberdeen # # Copyright: (c) Frederic S. Bayer 2015 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # 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, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-13SA. # ----------------------------------------------------------------------------------------------- __author__ = 'Frederic Bayer'<|fim▁end|>
<|file_name|>_load_balancers_operations.py<|end_file_name|><|fim▁begin|># coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class LoadBalancersOperations: """LoadBalancersOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2016_09_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def _delete_initial( self, resource_group_name: str, load_balancer_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2016-09-01" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}'} # type: ignore async def begin_delete( self, resource_group_name: str, load_balancer_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes the specified load balancer. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param load_balancer_name: The name of the load balancer. :type load_balancer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, load_balancer_name=load_balancer_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}'} # type: ignore async def get( self, resource_group_name: str, load_balancer_name: str, expand: Optional[str] = None, **kwargs: Any ) -> "_models.LoadBalancer": """Gets the specified load balancer. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param load_balancer_name: The name of the load balancer. :type load_balancer_name: str :param expand: Expands referenced resources. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: LoadBalancer, or the result of cls(response) :rtype: ~azure.mgmt.network.v2016_09_01.models.LoadBalancer :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.LoadBalancer"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2016-09-01" accept = "application/json, text/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') if expand is not None: query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('LoadBalancer', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}'} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, load_balancer_name: str, parameters: "_models.LoadBalancer", **kwargs: Any ) -> "_models.LoadBalancer": cls = kwargs.pop('cls', None) # type: ClsType["_models.LoadBalancer"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2016-09-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json, text/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'LoadBalancer') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('LoadBalancer', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('LoadBalancer', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}'} # type: ignore async def begin_create_or_update( self, resource_group_name: str, load_balancer_name: str, parameters: "_models.LoadBalancer", **kwargs: Any ) -> AsyncLROPoller["_models.LoadBalancer"]: """Creates or updates a load balancer. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param load_balancer_name: The name of the load balancer. :type load_balancer_name: str :param parameters: Parameters supplied to the create or update load balancer operation. :type parameters: ~azure.mgmt.network.v2016_09_01.models.LoadBalancer :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either LoadBalancer or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2016_09_01.models.LoadBalancer] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.LoadBalancer"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, load_balancer_name=load_balancer_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None)<|fim▁hole|> deserialized = self._deserialize('LoadBalancer', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}'} # type: ignore def list_all( self, **kwargs: Any ) -> AsyncIterable["_models.LoadBalancerListResult"]: """Gets all the load balancers in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LoadBalancerListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2016_09_01.models.LoadBalancerListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.LoadBalancerListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2016-09-01" accept = "application/json, text/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_all.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('LoadBalancerListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_all.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/loadBalancers'} # type: ignore def list( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.LoadBalancerListResult"]: """Gets all the load balancers in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LoadBalancerListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2016_09_01.models.LoadBalancerListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.LoadBalancerListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2016-09-01" accept = "application/json, text/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('LoadBalancerListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers'} # type: ignore<|fim▁end|>
def get_long_running_output(pipeline_response):
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls.defaults import patterns from django.conf import settings # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover()<|fim▁hole|> urlpatterns = patterns('', ( r'^$', 'statserver.stats.views.browse' ), ( r'^stats/addnode$', 'statserver.stats.views.addnode' ), ( r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )<|fim▁end|>
<|file_name|>package-info.java<|end_file_name|><|fim▁begin|>/** * Server-side support classes for WebSocket requests. */ @NonNullApi<|fim▁hole|> import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;<|fim▁end|>
@NonNullFields package org.springframework.web.reactive.socket.server.support;
<|file_name|>config.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- #------------------------------------------------------------ # Gestión de parámetros de configuración - xbmc #------------------------------------------------------------ # tvalacarta # http://blog.tvalacarta.info/plugin-xbmc/tvalacarta/ #------------------------------------------------------------ # Creado por: Jesús ([email protected]) # Licencia: GPL (http://www.gnu.org/licenses/gpl-3.0.html) #------------------------------------------------------------ import sys import os import xbmcplugin import xbmc PLATFORM_NAME = "xbmc-plugin" PLUGIN_NAME = "pelisalacarta" def get_platform(): return PLATFORM_NAME def is_xbmc(): return True def get_library_support(): return True def get_system_platform(): """ fonction: pour recuperer la platform que xbmc tourne """ import xbmc platform = "unknown" if xbmc.getCondVisibility( "system.platform.linux" ): platform = "linux" elif xbmc.getCondVisibility( "system.platform.xbox" ): platform = "xbox" elif xbmc.getCondVisibility( "system.platform.windows" ): platform = "windows" elif xbmc.getCondVisibility( "system.platform.osx" ): platform = "osx" return platform def open_settings(): xbmcplugin.openSettings( sys.argv[ 0 ] ) def get_setting(name): return xbmcplugin.getSetting(name) def set_setting(name,value): try: xbmcplugin.setSetting(name,value) except: pass def get_localized_string(code): dev = xbmc.getLocalizedString( code ) try: dev = dev.encode ("utf-8") #This only aplies to unicode strings. The rest stay as they are. except: pass return dev def get_library_path(): #return os.path.join( get_data_path(), 'library' ) default = os.path.join( get_data_path(), 'library' ) value = get_setting("librarypath") if value=="": value=default return value def get_temp_file(filename): return xbmc.translatePath( os.path.join( "special://temp/", filename )) def get_runtime_path(): return os.getcwd() def get_data_path(): devuelve = xbmc.translatePath( os.path.join("special://home/","userdata","plugin_data","video",PLUGIN_NAME) ) # XBMC en modo portable if devuelve.startswith("special:"): devuelve = xbmc.translatePath( os.path.join("special://xbmc/","userdata","plugin_data","video",PLUGIN_NAME) ) # Plex 8 if devuelve.startswith("special:"): devuelve = os.getcwd() return devuelve def get_cookie_data(): import os ficherocookies = os.path.join( get_data_path(), 'cookies.dat' ) cookiedatafile = open(ficherocookies,'r') cookiedata = cookiedatafile.read() cookiedatafile.close(); return cookiedata # Test if all the required directories are created def verify_directories_created(): import logger import os logger.info("pelisalacarta.core.config.verify_directories_created") # Force download path if empty download_path = get_setting("downloadpath") if download_path=="": download_path = os.path.join( get_data_path() , "downloads") set_setting("downloadpath" , download_path) # Force download list path if empty download_list_path = get_setting("downloadlistpath") if download_list_path=="": download_list_path = os.path.join( get_data_path() , "downloads" , "list") set_setting("downloadlistpath" , download_list_path) # Force bookmark path if empty bookmark_path = get_setting("bookmarkpath") if bookmark_path=="": bookmark_path = os.path.join( get_data_path() , "bookmarks") set_setting("bookmarkpath" , bookmark_path) # Create data_path if not exists if not os.path.exists(get_data_path()): logger.debug("Creating data_path "+get_data_path()) try: os.mkdir(get_data_path()) except: pass # Create download_path if not exists if not download_path.lower().startswith("smb") and not os.path.exists(download_path): logger.debug("Creating download_path "+download_path) try: os.mkdir(download_path) except: pass # Create download_list_path if not exists if not download_list_path.lower().startswith("smb") and not os.path.exists(download_list_path): logger.debug("Creating download_list_path "+download_list_path) try: os.mkdir(download_list_path) except: pass # Create bookmark_path if not exists if not bookmark_path.lower().startswith("smb") and not os.path.exists(bookmark_path): logger.debug("Creating bookmark_path "+bookmark_path) try: os.mkdir(bookmark_path) except: pass # Create library_path if not exists if not get_library_path().lower().startswith("smb") and not os.path.exists(get_library_path()): logger.debug("Creating library_path "+get_library_path()) try: os.mkdir(get_library_path()) except: pass # Checks that a directory "xbmc" is not present on platformcode<|fim▁hole|> logger.debug("Removing old platformcode.xbmc directory") try: import shutil shutil.rmtree(old_xbmc_directory) except: pass<|fim▁end|>
old_xbmc_directory = os.path.join( get_runtime_path() , "platformcode" , "xbmc" ) if os.path.exists( old_xbmc_directory ):
<|file_name|>game.rs<|end_file_name|><|fim▁begin|>use nom::branch::alt; use nom::bytes::complete::{is_a, is_not, tag, take}; use nom::character::complete::{anychar, digit1, one_of}; use nom::combinator::{map, map_res, opt, value}; use nom::multi::{count, many0, separated_list0}; use nom::sequence::{delimited, preceded, separated_pair, terminated, tuple}; use nom::*; use std::str; use std::time::Duration; use super::time::{datetime, timelimit}; use crate::value::*; fn line_sep(input: &[u8]) -> IResult<&[u8], &[u8]> { is_a("\r\n,")(input) } fn not_line_sep(input: &[u8]) -> IResult<&[u8], &[u8]> { is_not("\r\n,")(input) } fn comment(input: &[u8]) -> IResult<&[u8], &[u8]> { preceded(tag("'"), not_line_sep)(input) } fn comment_line(input: &[u8]) -> IResult<&[u8], &[u8]> { terminated(comment, line_sep)(input) } fn color(input: &[u8]) -> IResult<&[u8], Color> { map(one_of("+-"), |s| match s { '+' => Color::Black, _ => Color::White, })(input) } fn decimal(input: &[u8]) -> IResult<&[u8], Duration> { map_res(digit1, |s| { str::from_utf8(s) .map(|s| s.parse::<u64>().unwrap()) .map(Duration::from_secs) })(input) } fn fu(input: &[u8]) -> IResult<&[u8], PieceType> { value(PieceType::Pawn, tag("FU"))(input) } fn ky(input: &[u8]) -> IResult<&[u8], PieceType> { value(PieceType::Lance, tag("KY"))(input) } fn ke(input: &[u8]) -> IResult<&[u8], PieceType> { value(PieceType::Knight, tag("KE"))(input) } fn gi(input: &[u8]) -> IResult<&[u8], PieceType> { value(PieceType::Silver, tag("GI"))(input) } fn ki(input: &[u8]) -> IResult<&[u8], PieceType> { value(PieceType::Gold, tag("KI"))(input) } fn ka(input: &[u8]) -> IResult<&[u8], PieceType> { value(PieceType::Bishop, tag("KA"))(input) } fn hi(input: &[u8]) -> IResult<&[u8], PieceType> { value(PieceType::Rook, tag("HI"))(input) } fn ou(input: &[u8]) -> IResult<&[u8], PieceType> { value(PieceType::King, tag("OU"))(input) } fn to(input: &[u8]) -> IResult<&[u8], PieceType> { value(PieceType::ProPawn, tag("TO"))(input) } fn ny(input: &[u8]) -> IResult<&[u8], PieceType> { value(PieceType::ProLance, tag("NY"))(input) } fn nk(input: &[u8]) -> IResult<&[u8], PieceType> { value(PieceType::ProKnight, tag("NK"))(input) } fn ng(input: &[u8]) -> IResult<&[u8], PieceType> { value(PieceType::ProSilver, tag("NG"))(input) } fn um(input: &[u8]) -> IResult<&[u8], PieceType> { value(PieceType::Horse, tag("UM"))(input) } fn ry(input: &[u8]) -> IResult<&[u8], PieceType> { value(PieceType::Dragon, tag("RY"))(input) } fn al(input: &[u8]) -> IResult<&[u8], PieceType> { value(PieceType::All, tag("AL"))(input) } fn piece_type(input: &[u8]) -> IResult<&[u8], PieceType> { alt((fu, ky, ke, gi, ki, ka, hi, ou, to, ny, nk, ng, um, ry, al))(input) } fn one_digit(input: &[u8]) -> IResult<&[u8], u8> { map(one_of("0123456789"), |c: char| { c.to_digit(10).unwrap() as u8 })(input) } fn square(input: &[u8]) -> IResult<&[u8], Square> { map(tuple((one_digit, one_digit)), |(file, rank)| { Square::new(file, rank) })(input) } fn version(input: &[u8]) -> IResult<&[u8], &[u8]> { preceded(tag("V"), alt((tag("2.1"), tag("2.2"), tag("2"))))(input) } fn black_player(input: &[u8]) -> IResult<&[u8], &[u8]> { preceded(tag("N+"), not_line_sep)(input) } fn white_player(input: &[u8]) -> IResult<&[u8], &[u8]> { preceded(tag("N-"), not_line_sep)(input) } fn game_text_attr(input: &[u8]) -> IResult<&[u8], GameAttribute> { map(map_res(not_line_sep, str::from_utf8), |s: &str| { GameAttribute::Str(s.to_string()) })(input) } fn game_time_attr(input: &[u8]) -> IResult<&[u8], GameAttribute> { map(datetime, GameAttribute::Time)(input) } fn game_timelimit_attr(input: &[u8]) -> IResult<&[u8], GameAttribute> { map(timelimit, GameAttribute::TimeLimit)(input) } fn game_attr(input: &[u8]) -> IResult<&[u8], (String, GameAttribute)> { preceded( tag("$"), separated_pair( map_res(is_not(":"), |s: &[u8]| String::from_utf8(s.to_vec())), tag(":"), alt((game_time_attr, game_timelimit_attr, game_text_attr)), ), )(input) } fn handicap(input: &[u8]) -> IResult<&[u8], Vec<(Square, PieceType)>> { preceded(tag("PI"), many0(tuple((square, piece_type))))(input) } fn grid_piece(input: &[u8]) -> IResult<&[u8], Option<(Color, PieceType)>> { let (input, result) = anychar(input)?; match result { '+' => map(piece_type, |pt| Some((Color::Black, pt)))(input), '-' => map(piece_type, |pt| Some((Color::White, pt)))(input), _ => value(None, take(2usize))(input), } } type GridRow = [Option<(Color, PieceType)>; 9]; type Grid = [GridRow; 9]; fn grid_row(input: &[u8]) -> IResult<&[u8], GridRow> { let (input, vec) = count(grid_piece, 9)(input)?; // TODO: Convert into an array instead of copying. let mut array = [None; 9]; array.clone_from_slice(&vec); Ok((input, array)) } fn grid(input: &[u8]) -> IResult<&[u8], Grid> { let (input, r1) = delimited(tag("P1"), grid_row, line_sep)(input)?; let (input, r2) = delimited(tag("P2"), grid_row, line_sep)(input)?; let (input, r3) = delimited(tag("P3"), grid_row, line_sep)(input)?; let (input, r4) = delimited(tag("P4"), grid_row, line_sep)(input)?; let (input, r5) = delimited(tag("P5"), grid_row, line_sep)(input)?; let (input, r6) = delimited(tag("P6"), grid_row, line_sep)(input)?; let (input, r7) = delimited(tag("P7"), grid_row, line_sep)(input)?; let (input, r8) = delimited(tag("P8"), grid_row, line_sep)(input)?; let (input, r9) = preceded(tag("P9"), grid_row)(input)?; Ok((input, [r1, r2, r3, r4, r5, r6, r7, r8, r9])) } fn piece_placement(input: &[u8]) -> IResult<&[u8], Vec<(Color, Square, PieceType)>> { let (input, _) = tag("P")(input)?; let (input, c) = color(input)?; let (input, pcs) = many0(tuple((square, piece_type)))(input)?; Ok(( input, pcs.iter().map(|&(sq, pt)| (c, sq, pt)).collect::<Vec<_>>(), )) } fn normal_move(input: &[u8]) -> IResult<&[u8], Action> { let (input, c) = color(input)?; let (input, from) = square(input)?; let (input, to) = square(input)?; let (input, pt) = piece_type(input)?; Ok((input, Action::Move(c, from, to, pt))) } fn special_move(input: &[u8]) -> IResult<&[u8], Action> { preceded( tag("%"), alt(( value(Action::Toryo, tag("TORYO")), value(Action::Matta, tag("MATTA")), value(Action::Tsumi, tag("TSUMI")), value(Action::Error, tag("ERROR")), value(Action::Kachi, tag("KACHI")), value(Action::Chudan, tag("CHUDAN")), value(Action::Fuzumi, tag("FUZUMI")), value(Action::Jishogi, tag("JISHOGI")), value(Action::Hikiwake, tag("HIKIWAKE")), value(Action::Sennichite, tag("SENNICHITE")), )), )(input) } fn move_record(input: &[u8]) -> IResult<&[u8], MoveRecord> { let (input, action) = alt((normal_move, special_move))(input)?; let (input, time) = opt(preceded(line_sep, preceded(tag("T"), decimal)))(input)?; Ok((input, MoveRecord { action, time })) } pub fn game_record(input: &[u8]) -> IResult<&[u8], GameRecord> { let (input, _) = many0(comment_line)(input)?; let (input, _) = opt(terminated(version, line_sep))(input)?; let (input, _) = many0(comment_line)(input)?; let (input, black_player) = opt(map_res(terminated(black_player, line_sep), |b| { str::from_utf8(b) }))(input)?; let (input, _) = many0(comment_line)(input)?; let (input, white_player) = opt(map_res(terminated(white_player, line_sep), |b| { str::from_utf8(b) }))(input)?; let (input, _) = many0(comment_line)(input)?; let (input, attrs) = map( opt(terminated( separated_list0(line_sep, preceded(many0(comment_line), game_attr)), line_sep, )), |v: Option<Vec<(String, GameAttribute)>>| v.unwrap_or_default(), )(input)?; let (input, _) = many0(comment_line)(input)?; let (input, drop_pieces) = opt(terminated(handicap, line_sep))(input)?; let (input, _) = many0(comment_line)(input)?; let (input, bulk) = opt(terminated(grid, line_sep))(input)?; let (input, _) = many0(comment_line)(input)?; let (input, add_pieces) = many0(terminated(piece_placement, line_sep))(input)?; let (input, _) = many0(comment_line)(input)?; let (input, side_to_move) = terminated(color, line_sep)(input)?; let (input, _) = many0(comment_line)(input)?; let (input, moves) = many0(terminated(move_record, line_sep))(input)?; let (input, _) = many0(comment_line)(input)?; Ok(( input, GameRecord { black_player: black_player.map(|s| s.to_string()), white_player: white_player.map(|s| s.to_string()), event: attrs .iter() .find(|pair| pair.0 == "EVENT") .map(|pair| pair.1.to_string()), site: attrs .iter() .find(|pair| pair.0 == "SITE") .map(|pair| pair.1.to_string()), start_time: attrs.iter().find(|pair| pair.0 == "START_TIME").and_then( |pair| match pair.1 { GameAttribute::Time(ref t) => Some(t.clone()), _ => None, }, ), end_time: attrs .iter() .find(|pair| pair.0 == "END_TIME") .and_then(|pair| match pair.1 { GameAttribute::Time(ref t) => Some(t.clone()), _ => None, }), time_limit: attrs.iter().find(|pair| pair.0 == "TIME_LIMIT").and_then( |pair| match pair.1 { GameAttribute::TimeLimit(ref t) => Some(t.clone()), _ => None, }, ), opening: attrs .iter() .find(|pair| pair.0 == "OPENING") .map(|pair| pair.1.to_string()), start_pos: Position { drop_pieces: drop_pieces.unwrap_or_else(Vec::new), bulk, add_pieces: add_pieces.into_iter().flatten().collect(), side_to_move, }, moves, }, )) } //////////////////////////////////////////////////////////////////////////////// #[cfg(test)] mod tests { use super::*; use time::{Date as NativeDate, Time as NativeTime}; #[test] fn parse_comment() { assert_eq!( comment(b"'this is a comment"), Result::Ok((&b""[..], &b"this is a comment"[..])) ); } #[test] fn parse_piece_type() { assert_eq!(piece_type(b"FU"), Result::Ok((&b""[..], PieceType::Pawn))); assert_eq!(piece_type(b"KY"), Result::Ok((&b""[..], PieceType::Lance))); assert_eq!(piece_type(b"KE"), Result::Ok((&b""[..], PieceType::Knight))); assert_eq!(piece_type(b"GI"), Result::Ok((&b""[..], PieceType::Silver))); assert_eq!(piece_type(b"KI"), Result::Ok((&b""[..], PieceType::Gold))); assert_eq!(piece_type(b"KA"), Result::Ok((&b""[..], PieceType::Bishop))); assert_eq!(piece_type(b"HI"), Result::Ok((&b""[..], PieceType::Rook))); assert_eq!(piece_type(b"OU"), Result::Ok((&b""[..], PieceType::King))); assert_eq!( piece_type(b"TO"), Result::Ok((&b""[..], PieceType::ProPawn)) ); assert_eq!( piece_type(b"NY"), Result::Ok((&b""[..], PieceType::ProLance)) ); assert_eq!( piece_type(b"NK"), Result::Ok((&b""[..], PieceType::ProKnight)) ); assert_eq!( piece_type(b"NG"), Result::Ok((&b""[..], PieceType::ProSilver)) ); assert_eq!(piece_type(b"UM"), Result::Ok((&b""[..], PieceType::Horse))); assert_eq!(piece_type(b"RY"), Result::Ok((&b""[..], PieceType::Dragon))); } #[test] fn parse_one_digit() { assert_eq!(one_digit(b"0"), Result::Ok((&b""[..], 0))); assert_eq!(one_digit(b"1"), Result::Ok((&b""[..], 1))); assert_eq!(one_digit(b"2"), Result::Ok((&b""[..], 2))); assert_eq!(one_digit(b"3"), Result::Ok((&b""[..], 3))); assert_eq!(one_digit(b"4"), Result::Ok((&b""[..], 4))); assert_eq!(one_digit(b"5"), Result::Ok((&b""[..], 5))); assert_eq!(one_digit(b"6"), Result::Ok((&b""[..], 6))); assert_eq!(one_digit(b"7"), Result::Ok((&b""[..], 7))); assert_eq!(one_digit(b"8"), Result::Ok((&b""[..], 8))); assert_eq!(one_digit(b"9"), Result::Ok((&b""[..], 9))); assert_eq!(one_digit(b"10"), Result::Ok((&b"0"[..], 1))); } #[test] fn parse_square() { assert_eq!(square(b"00"), Result::Ok((&b""[..], Square::new(0, 0)))); assert_eq!(square(b"99"), Result::Ok((&b""[..], Square::new(9, 9)))); } #[test] fn parse_version() { assert_eq!(version(b"V2"), Result::Ok((&b""[..], &b"2"[..]))); assert_eq!(version(b"V2.1"), Result::Ok((&b""[..], &b"2.1"[..]))); assert_eq!(version(b"V2.2"), Result::Ok((&b""[..], &b"2.2"[..]))); } #[test] fn parse_players() { assert_eq!( black_player(b"N+black player"), Result::Ok((&b""[..], &b"black player"[..])) ); assert_eq!( white_player(b"N-white player"), Result::Ok((&b""[..], &b"white player"[..])) ); } #[test] fn parse_game_attr() { assert_eq!( game_attr(b"$EVENT:event"), Result::Ok(( &b""[..], ("EVENT".to_string(), GameAttribute::Str("event".to_string())) )) ); assert_eq!( game_attr(b"$START_TIME:2002/01/01 19:00:00"), Result::Ok(( &b""[..], ( "START_TIME".to_string(), GameAttribute::Time(Time { date: NativeDate::from_calendar_date(2002, time::Month::January, 1) .unwrap(), time: Some(NativeTime::from_hms(19, 0, 0).unwrap()) }) ) )) ); } #[test] fn parse_handicap() { assert_eq!(handicap(b"PI"), Result::Ok((&b""[..], vec![]))); assert_eq!( handicap(b"PI82HI22KA"), Result::Ok(( &b""[..], vec![ (Square::new(8, 2), PieceType::Rook), (Square::new(2, 2), PieceType::Bishop) ] )) ); } #[test] fn parse_grid() { let grid_str = b"\ P1-KY-KE-GI-KI-OU-KI-GI-KE-KY P2 * -HI * * * * * -KA * P3-FU-FU-FU-FU-FU-FU-FU-FU-FU P4 * * * * * * * * * P5 * * * * * * * * * P6 * * * * * * * * * P7+FU+FU+FU+FU+FU+FU+FU+FU+FU P8 * +KA * * * * * +HI * P9+KY+KE+GI+KI+OU+KI+GI+KE+KY"; let initial_pos = [ [ Some((Color::White, PieceType::Lance)), Some((Color::White, PieceType::Knight)), Some((Color::White, PieceType::Silver)), Some((Color::White, PieceType::Gold)), Some((Color::White, PieceType::King)), Some((Color::White, PieceType::Gold)), Some((Color::White, PieceType::Silver)), Some((Color::White, PieceType::Knight)), Some((Color::White, PieceType::Lance)), ], [ None, Some((Color::White, PieceType::Rook)), None, None, None, None, None, Some((Color::White, PieceType::Bishop)), None, ], [ Some((Color::White, PieceType::Pawn)), Some((Color::White, PieceType::Pawn)), Some((Color::White, PieceType::Pawn)), Some((Color::White, PieceType::Pawn)), Some((Color::White, PieceType::Pawn)), Some((Color::White, PieceType::Pawn)), Some((Color::White, PieceType::Pawn)), Some((Color::White, PieceType::Pawn)), Some((Color::White, PieceType::Pawn)), ], [None, None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None, None], [ Some((Color::Black, PieceType::Pawn)), Some((Color::Black, PieceType::Pawn)), Some((Color::Black, PieceType::Pawn)), Some((Color::Black, PieceType::Pawn)), Some((Color::Black, PieceType::Pawn)), Some((Color::Black, PieceType::Pawn)), Some((Color::Black, PieceType::Pawn)), Some((Color::Black, PieceType::Pawn)), Some((Color::Black, PieceType::Pawn)), ], [ None, Some((Color::Black, PieceType::Bishop)), None, None, None, None, None, Some((Color::Black, PieceType::Rook)), None, ], [ Some((Color::Black, PieceType::Lance)), Some((Color::Black, PieceType::Knight)), Some((Color::Black, PieceType::Silver)), Some((Color::Black, PieceType::Gold)), Some((Color::Black, PieceType::King)), Some((Color::Black, PieceType::Gold)), Some((Color::Black, PieceType::Silver)), Some((Color::Black, PieceType::Knight)), Some((Color::Black, PieceType::Lance)), ], ]; assert_eq!(grid(grid_str), Result::Ok((&b""[..], initial_pos))); } #[test] fn parse_piece_placement() { assert_eq!( piece_placement(b"P+99KY89KE"), Result::Ok(( &b""[..], vec![ (Color::Black, Square::new(9, 9), PieceType::Lance), (Color::Black, Square::new(8, 9), PieceType::Knight), ] )) ); assert_eq!( piece_placement(b"P-00AL"), Result::Ok(( &b""[..], vec![(Color::White, Square::new(0, 0), PieceType::All),] )) ); } #[test] fn parse_normal_move() { assert_eq!( normal_move(b"+2726FU"), Result::Ok(( &b""[..], Action::Move( Color::Black, Square::new(2, 7), Square::new(2, 6), PieceType::Pawn ) )) ); assert_eq!( normal_move(b"-3334FU"), Result::Ok(( &b""[..], Action::Move( Color::White, Square::new(3, 3), Square::new(3, 4), PieceType::Pawn ) )) ); } #[test] fn parse_special_move() { assert_eq!( special_move(b"%TORYO"), Result::Ok((&b""[..], Action::Toryo))<|fim▁hole|> ); assert_eq!( special_move(b"%TSUMI"), Result::Ok((&b""[..], Action::Tsumi)) ); assert_eq!( special_move(b"%ERROR"), Result::Ok((&b""[..], Action::Error)) ); assert_eq!( special_move(b"%KACHI"), Result::Ok((&b""[..], Action::Kachi)) ); assert_eq!( special_move(b"%CHUDAN"), Result::Ok((&b""[..], Action::Chudan)) ); assert_eq!( special_move(b"%FUZUMI"), Result::Ok((&b""[..], Action::Fuzumi)) ); assert_eq!( special_move(b"%JISHOGI"), Result::Ok((&b""[..], Action::Jishogi)) ); assert_eq!( special_move(b"%HIKIWAKE"), Result::Ok((&b""[..], Action::Hikiwake)) ); assert_eq!( special_move(b"%SENNICHITE"), Result::Ok((&b""[..], Action::Sennichite)) ); } #[test] fn parse_move_record() { assert_eq!( move_record(b"+2726FU\nT5"), Result::Ok(( &b""[..], MoveRecord { action: Action::Move( Color::Black, Square::new(2, 7), Square::new(2, 6), PieceType::Pawn ), time: Some(Duration::from_secs(5)) } )) ); assert_eq!( move_record(b"+2726FU"), Result::Ok(( &b""[..], MoveRecord { action: Action::Move( Color::Black, Square::new(2, 7), Square::new(2, 6), PieceType::Pawn ), time: None } )) ); assert_eq!( move_record(b"%TORYO\nT5"), Result::Ok(( &b""[..], MoveRecord { action: Action::Toryo, time: Some(Duration::from_secs(5)) } )) ); assert_eq!( move_record(b"%TORYO"), Result::Ok(( &b""[..], MoveRecord { action: Action::Toryo, time: None } )) ); } #[test] fn parse_game_record() { let csa = "\ '----------棋譜ファイルの例\"example.csa\"----------------- 'バージョン V2.2 '対局者名 N+NAKAHARA N-YONENAGA '棋譜情報 '棋戦名 $EVENT:13th World Computer Shogi Championship '対局場所 $SITE:KAZUSA ARC '開始日時 $START_TIME:2003/05/03 10:30:00 '終了日時 $END_TIME:2003/05/03 11:11:05 '持ち時間:25分、切れ負け $TIME_LIMIT:00:25+00 '戦型:矢倉 $OPENING:YAGURA '平手の局面 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY P2 * -HI * * * * * -KA * P3-FU-FU-FU-FU-FU-FU-FU-FU-FU P4 * * * * * * * * * P5 * * * * * * * * * P6 * * * * * * * * * P7+FU+FU+FU+FU+FU+FU+FU+FU+FU P8 * +KA * * * * * +HI * P9+KY+KE+GI+KI+OU+KI+GI+KE+KY '先手番 + '指し手と消費時間 +2726FU T12 -3334FU T6 %CHUDAN '--------------------------------------------------------- "; let initial_pos = [ [ Some((Color::White, PieceType::Lance)), Some((Color::White, PieceType::Knight)), Some((Color::White, PieceType::Silver)), Some((Color::White, PieceType::Gold)), Some((Color::White, PieceType::King)), Some((Color::White, PieceType::Gold)), Some((Color::White, PieceType::Silver)), Some((Color::White, PieceType::Knight)), Some((Color::White, PieceType::Lance)), ], [ None, Some((Color::White, PieceType::Rook)), None, None, None, None, None, Some((Color::White, PieceType::Bishop)), None, ], [ Some((Color::White, PieceType::Pawn)), Some((Color::White, PieceType::Pawn)), Some((Color::White, PieceType::Pawn)), Some((Color::White, PieceType::Pawn)), Some((Color::White, PieceType::Pawn)), Some((Color::White, PieceType::Pawn)), Some((Color::White, PieceType::Pawn)), Some((Color::White, PieceType::Pawn)), Some((Color::White, PieceType::Pawn)), ], [None, None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None, None], [None, None, None, None, None, None, None, None, None], [ Some((Color::Black, PieceType::Pawn)), Some((Color::Black, PieceType::Pawn)), Some((Color::Black, PieceType::Pawn)), Some((Color::Black, PieceType::Pawn)), Some((Color::Black, PieceType::Pawn)), Some((Color::Black, PieceType::Pawn)), Some((Color::Black, PieceType::Pawn)), Some((Color::Black, PieceType::Pawn)), Some((Color::Black, PieceType::Pawn)), ], [ None, Some((Color::Black, PieceType::Bishop)), None, None, None, None, None, Some((Color::Black, PieceType::Rook)), None, ], [ Some((Color::Black, PieceType::Lance)), Some((Color::Black, PieceType::Knight)), Some((Color::Black, PieceType::Silver)), Some((Color::Black, PieceType::Gold)), Some((Color::Black, PieceType::King)), Some((Color::Black, PieceType::Gold)), Some((Color::Black, PieceType::Silver)), Some((Color::Black, PieceType::Knight)), Some((Color::Black, PieceType::Lance)), ], ]; assert_eq!( game_record(csa.as_bytes()), Result::Ok(( &b""[..], GameRecord { black_player: Some("NAKAHARA".to_string()), white_player: Some("YONENAGA".to_string()), event: Some("13th World Computer Shogi Championship".to_string()), site: Some("KAZUSA ARC".to_string()), start_time: Some(Time { date: NativeDate::from_calendar_date(2003, time::Month::May, 3).unwrap(), time: Some(NativeTime::from_hms(10, 30, 0).unwrap()) }), end_time: Some(Time { date: NativeDate::from_calendar_date(2003, time::Month::May, 3).unwrap(), time: Some(NativeTime::from_hms(11, 11, 5).unwrap()) }), time_limit: Some(TimeLimit { main_time: Duration::from_secs(1500), byoyomi: Duration::from_secs(0) }), opening: Some("YAGURA".to_string()), start_pos: Position { drop_pieces: vec![], bulk: Some(initial_pos), add_pieces: vec![], side_to_move: Color::Black, }, moves: vec![ MoveRecord { action: Action::Move( Color::Black, Square::new(2, 7), Square::new(2, 6), PieceType::Pawn ), time: Some(Duration::from_secs(12)) }, MoveRecord { action: Action::Move( Color::White, Square::new(3, 3), Square::new(3, 4), PieceType::Pawn ), time: Some(Duration::from_secs(6)) }, MoveRecord { action: Action::Chudan, time: None } ], } )) ) } }<|fim▁end|>
); assert_eq!( special_move(b"%MATTA"), Result::Ok((&b""[..], Action::Matta))
<|file_name|>input_test.rs<|end_file_name|><|fim▁begin|>//! Example that just prints out all the input events. use ggez::event::{self, Axis, Button, GamepadId, KeyCode, KeyMods, MouseButton}; use ggez::graphics::{self, Color, DrawMode}; use ggez::{conf, input}; use ggez::{Context, GameResult}; use glam::*; struct MainState { pos_x: f32, pos_y: f32, mouse_down: bool, } impl MainState { fn new() -> MainState { MainState { pos_x: 100.0, pos_y: 100.0, mouse_down: false, } } } impl event::EventHandler<ggez::GameError> for MainState { fn update(&mut self, ctx: &mut Context) -> GameResult { if input::keyboard::is_key_pressed(ctx, KeyCode::A) { println!("The A key is pressed"); if input::keyboard::is_mod_active(ctx, input::keyboard::KeyMods::SHIFT) { println!("The shift key is held too."); } println!( "Full list of pressed keys: {:?}", input::keyboard::pressed_keys(ctx) ); } Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult { graphics::clear(ctx, [0.1, 0.2, 0.3, 1.0].into()); let rectangle = graphics::Mesh::new_rectangle( ctx, DrawMode::fill(), graphics::Rect { x: self.pos_x, y: self.pos_y, w: 400.0, h: 300.0, }, Color::WHITE, )?; graphics::draw(ctx, &rectangle, (glam::Vec2::new(0.0, 0.0),))?; graphics::present(ctx)?; Ok(()) } fn mouse_button_down_event(&mut self, _ctx: &mut Context, button: MouseButton, x: f32, y: f32) { self.mouse_down = true; println!("Mouse button pressed: {:?}, x: {}, y: {}", button, x, y); } fn mouse_button_up_event(&mut self, _ctx: &mut Context, button: MouseButton, x: f32, y: f32) { self.mouse_down = false; println!("Mouse button released: {:?}, x: {}, y: {}", button, x, y); } fn mouse_motion_event(&mut self, _ctx: &mut Context, x: f32, y: f32, xrel: f32, yrel: f32) { if self.mouse_down { // Mouse coordinates are PHYSICAL coordinates, but here we want logical coordinates.<|fim▁hole|> // If you simply use the initial coordinate system, then physical and logical // coordinates are identical. self.pos_x = x; self.pos_y = y; // If you change your screen coordinate system you need to calculate the // logical coordinates like this: /* let screen_rect = graphics::screen_coordinates(_ctx); let size = graphics::window(_ctx).inner_size(); self.pos_x = (x / (size.width as f32)) * screen_rect.w + screen_rect.x; self.pos_y = (y / (size.height as f32)) * screen_rect.h + screen_rect.y; */ } println!( "Mouse motion, x: {}, y: {}, relative x: {}, relative y: {}", x, y, xrel, yrel ); } fn mouse_wheel_event(&mut self, _ctx: &mut Context, x: f32, y: f32) { println!("Mousewheel event, x: {}, y: {}", x, y); } fn key_down_event( &mut self, _ctx: &mut Context, keycode: KeyCode, keymod: KeyMods, repeat: bool, ) { println!( "Key pressed: {:?}, modifier {:?}, repeat: {}", keycode, keymod, repeat ); } fn key_up_event(&mut self, _ctx: &mut Context, keycode: KeyCode, keymod: KeyMods) { println!("Key released: {:?}, modifier {:?}", keycode, keymod); } fn text_input_event(&mut self, _ctx: &mut Context, ch: char) { println!("Text input: {}", ch); } fn gamepad_button_down_event(&mut self, _ctx: &mut Context, btn: Button, id: GamepadId) { println!("Gamepad button pressed: {:?} Gamepad_Id: {:?}", btn, id); } fn gamepad_button_up_event(&mut self, _ctx: &mut Context, btn: Button, id: GamepadId) { println!("Gamepad button released: {:?} Gamepad_Id: {:?}", btn, id); } fn gamepad_axis_event(&mut self, _ctx: &mut Context, axis: Axis, value: f32, id: GamepadId) { println!( "Axis Event: {:?} Value: {} Gamepad_Id: {:?}", axis, value, id ); } fn focus_event(&mut self, _ctx: &mut Context, gained: bool) { if gained { println!("Focus gained"); } else { println!("Focus lost"); } } } pub fn main() -> GameResult { let cb = ggez::ContextBuilder::new("input_test", "ggez").window_mode( conf::WindowMode::default() .fullscreen_type(conf::FullscreenType::Windowed) .resizable(true), ); let (ctx, event_loop) = cb.build()?; // remove the comment to see how physical mouse coordinates can differ // from logical game coordinates when the screen coordinate system changes // graphics::set_screen_coordinates(&mut ctx, Rect::new(20., 50., 2000., 1000.)); // alternatively, resizing the window also leads to screen coordinates // and physical window size being out of sync let state = MainState::new(); event::run(ctx, event_loop, state) }<|fim▁end|>
<|file_name|>small_objects_stress.rs<|end_file_name|><|fim▁begin|>extern crate stopwatch; use stopwatch::Stopwatch; extern crate mo_gc; use mo_gc::{GcThread, GcRoot, Trace, StatsLogger}; const THING_SIZE: usize = 8; const THING_COUNT: i64 = 2500000; struct Thing { _data: [u64; THING_SIZE], } impl Thing { fn new() -> Thing { Thing { _data: [0; THING_SIZE] } } } unsafe impl Trace for Thing {} fn app() { let sw = Stopwatch::start_new(); for _ in 0..THING_COUNT { let _new = GcRoot::new(Thing::new()); } let per_second = (THING_COUNT * 1000) / sw.elapsed_ms(); println!("app allocated {} objects at {} objects per second", THING_COUNT, per_second);<|fim▁hole|>fn main() { let gc = GcThread::spawn_gc(); let app_handle1 = gc.spawn(|| app()); let app_handle2 = gc.spawn(|| app()); let logger = gc.join().expect("gc failed"); logger.dump_to_stdout(); app_handle1.join().expect("app failed"); app_handle2.join().expect("app failed"); }<|fim▁end|>
println!("app finished in {}ms", sw.elapsed_ms()); }
<|file_name|>auth.go<|end_file_name|><|fim▁begin|>// mgo - MongoDB driver for Go // // Copyright (c) 2010-2012 - Gustavo Niemeyer <[email protected]> // // All rights reserved. // // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package mgo import ( "crypto/md5" "crypto/sha1" "encoding/hex" "errors" "fmt" "sync" "github.com/kylemclaren/mongo-transporter/Godeps/_workspace/src/gopkg.in/mgo.v2/bson" "github.com/kylemclaren/mongo-transporter/Godeps/_workspace/src/gopkg.in/mgo.v2/internal/scram" ) type authCmd struct { Authenticate int Nonce string User string Key string } type startSaslCmd struct { StartSASL int `bson:"startSasl"` } type authResult struct { ErrMsg string Ok bool } type getNonceCmd struct { GetNonce int } type getNonceResult struct { Nonce string Err string "$err" Code int } type logoutCmd struct { Logout int } type saslCmd struct { Start int `bson:"saslStart,omitempty"` Continue int `bson:"saslContinue,omitempty"` ConversationId int `bson:"conversationId,omitempty"` Mechanism string `bson:"mechanism,omitempty"` Payload []byte } type saslResult struct { Ok bool `bson:"ok"` NotOk bool `bson:"code"` // Server <= 2.3.2 returns ok=1 & code>0 on errors (WTF?) Done bool ConversationId int `bson:"conversationId"` Payload []byte ErrMsg string } type saslStepper interface { Step(serverData []byte) (clientData []byte, done bool, err error) Close() } func (socket *mongoSocket) getNonce() (nonce string, err error) { socket.Lock() for socket.cachedNonce == "" && socket.dead == nil { debugf("Socket %p to %s: waiting for nonce", socket, socket.addr) socket.gotNonce.Wait() } if socket.cachedNonce == "mongos" { socket.Unlock() return "", errors.New("Can't authenticate with mongos; see http://j.mp/mongos-auth") } debugf("Socket %p to %s: got nonce", socket, socket.addr) nonce, err = socket.cachedNonce, socket.dead socket.cachedNonce = "" socket.Unlock() if err != nil { nonce = "" } return } func (socket *mongoSocket) resetNonce() { debugf("Socket %p to %s: requesting a new nonce", socket, socket.addr) op := &queryOp{} op.query = &getNonceCmd{GetNonce: 1} op.collection = "admin.$cmd" op.limit = -1 op.replyFunc = func(err error, reply *replyOp, docNum int, docData []byte) { if err != nil { socket.kill(errors.New("getNonce: "+err.Error()), true) return } result := &getNonceResult{} err = bson.Unmarshal(docData, &result) if err != nil { socket.kill(errors.New("Failed to unmarshal nonce: "+err.Error()), true) return } debugf("Socket %p to %s: nonce unmarshalled: %#v", socket, socket.addr, result) if result.Code == 13390 { // mongos doesn't yet support auth (see http://j.mp/mongos-auth) result.Nonce = "mongos" } else if result.Nonce == "" { var msg string if result.Err != "" { msg = fmt.Sprintf("Got an empty nonce: %s (%d)", result.Err, result.Code) } else { msg = "Got an empty nonce" } socket.kill(errors.New(msg), true) return } socket.Lock() if socket.cachedNonce != "" { socket.Unlock() panic("resetNonce: nonce already cached") } socket.cachedNonce = result.Nonce socket.gotNonce.Signal() socket.Unlock() } err := socket.Query(op) if err != nil { socket.kill(errors.New("resetNonce: "+err.Error()), true) } } func (socket *mongoSocket) Login(cred Credential) error { socket.Lock() if cred.Mechanism == "" && socket.serverInfo.MaxWireVersion >= 3 { cred.Mechanism = "SCRAM-SHA-1" } for _, sockCred := range socket.creds { if sockCred == cred { debugf("Socket %p to %s: login: db=%q user=%q (already logged in)", socket, socket.addr, cred.Source, cred.Username) socket.Unlock() return nil } } if socket.dropLogout(cred) { debugf("Socket %p to %s: login: db=%q user=%q (cached)", socket, socket.addr, cred.Source, cred.Username) socket.creds = append(socket.creds, cred) socket.Unlock() return nil } socket.Unlock() debugf("Socket %p to %s: login: db=%q user=%q", socket, socket.addr, cred.Source, cred.Username) var err error switch cred.Mechanism { case "", "MONGODB-CR", "MONGO-CR": // Name changed to MONGODB-CR in SERVER-8501. err = socket.loginClassic(cred) case "PLAIN": err = socket.loginPlain(cred) case "MONGODB-X509": err = socket.loginX509(cred) default: // Try SASL for everything else, if it is available. err = socket.loginSASL(cred) } if err != nil { debugf("Socket %p to %s: login error: %s", socket, socket.addr, err) } else { debugf("Socket %p to %s: login successful", socket, socket.addr) } return err } func (socket *mongoSocket) loginClassic(cred Credential) error { // Note that this only works properly because this function is // synchronous, which means the nonce won't get reset while we're // using it and any other login requests will block waiting for a // new nonce provided in the defer call below. nonce, err := socket.getNonce() if err != nil { return err } defer socket.resetNonce() psum := md5.New() psum.Write([]byte(cred.Username + ":mongo:" + cred.Password)) ksum := md5.New() ksum.Write([]byte(nonce + cred.Username)) ksum.Write([]byte(hex.EncodeToString(psum.Sum(nil)))) key := hex.EncodeToString(ksum.Sum(nil)) cmd := authCmd{Authenticate: 1, User: cred.Username, Nonce: nonce, Key: key} res := authResult{} return socket.loginRun(cred.Source, &cmd, &res, func() error { if !res.Ok { return errors.New(res.ErrMsg) } socket.Lock() socket.dropAuth(cred.Source) socket.creds = append(socket.creds, cred) socket.Unlock() return nil }) } type authX509Cmd struct { Authenticate int User string Mechanism string } func (socket *mongoSocket) loginX509(cred Credential) error { cmd := authX509Cmd{Authenticate: 1, User: cred.Username, Mechanism: "MONGODB-X509"} res := authResult{} return socket.loginRun(cred.Source, &cmd, &res, func() error { if !res.Ok { return errors.New(res.ErrMsg) } socket.Lock() socket.dropAuth(cred.Source) socket.creds = append(socket.creds, cred) socket.Unlock() return nil }) } func (socket *mongoSocket) loginPlain(cred Credential) error { cmd := saslCmd{Start: 1, Mechanism: "PLAIN", Payload: []byte("\x00" + cred.Username + "\x00" + cred.Password)} res := authResult{} return socket.loginRun(cred.Source, &cmd, &res, func() error { if !res.Ok { return errors.New(res.ErrMsg) } socket.Lock() socket.dropAuth(cred.Source) socket.creds = append(socket.creds, cred) socket.Unlock() return nil }) } func (socket *mongoSocket) loginSASL(cred Credential) error { var sasl saslStepper var err error if cred.Mechanism == "SCRAM-SHA-1" { // SCRAM is handled without external libraries. sasl = saslNewScram(cred) } else if len(cred.ServiceHost) > 0 { sasl, err = saslNew(cred, cred.ServiceHost) } else { sasl, err = saslNew(cred, socket.Server().Addr) } if err != nil {<|fim▁hole|> defer sasl.Close() // The goal of this logic is to carry a locked socket until the // local SASL step confirms the auth is valid; the socket needs to be // locked so that concurrent action doesn't leave the socket in an // auth state that doesn't reflect the operations that took place. // As a simple case, imagine inverting login=>logout to logout=>login. // // The logic below works because the lock func isn't called concurrently. locked := false lock := func(b bool) { if locked != b { locked = b if b { socket.Lock() } else { socket.Unlock() } } } lock(true) defer lock(false) start := 1 cmd := saslCmd{} res := saslResult{} for { payload, done, err := sasl.Step(res.Payload) if err != nil { return err } if done && res.Done { socket.dropAuth(cred.Source) socket.creds = append(socket.creds, cred) break } lock(false) cmd = saslCmd{ Start: start, Continue: 1 - start, ConversationId: res.ConversationId, Mechanism: cred.Mechanism, Payload: payload, } start = 0 err = socket.loginRun(cred.Source, &cmd, &res, func() error { // See the comment on lock for why this is necessary. lock(true) if !res.Ok || res.NotOk { return fmt.Errorf("server returned error on SASL authentication step: %s", res.ErrMsg) } return nil }) if err != nil { return err } if done && res.Done { socket.dropAuth(cred.Source) socket.creds = append(socket.creds, cred) break } } return nil } func saslNewScram(cred Credential) *saslScram { credsum := md5.New() credsum.Write([]byte(cred.Username + ":mongo:" + cred.Password)) client := scram.NewClient(sha1.New, cred.Username, hex.EncodeToString(credsum.Sum(nil))) return &saslScram{cred: cred, client: client} } type saslScram struct { cred Credential client *scram.Client } func (s *saslScram) Close() {} func (s *saslScram) Step(serverData []byte) (clientData []byte, done bool, err error) { more := s.client.Step(serverData) return s.client.Out(), !more, s.client.Err() } func (socket *mongoSocket) loginRun(db string, query, result interface{}, f func() error) error { var mutex sync.Mutex var replyErr error mutex.Lock() op := queryOp{} op.query = query op.collection = db + ".$cmd" op.limit = -1 op.replyFunc = func(err error, reply *replyOp, docNum int, docData []byte) { defer mutex.Unlock() if err != nil { replyErr = err return } err = bson.Unmarshal(docData, result) if err != nil { replyErr = err } else { // Must handle this within the read loop for the socket, so // that concurrent login requests are properly ordered. replyErr = f() } } err := socket.Query(&op) if err != nil { return err } mutex.Lock() // Wait. return replyErr } func (socket *mongoSocket) Logout(db string) { socket.Lock() cred, found := socket.dropAuth(db) if found { debugf("Socket %p to %s: logout: db=%q (flagged)", socket, socket.addr, db) socket.logout = append(socket.logout, cred) } socket.Unlock() } func (socket *mongoSocket) LogoutAll() { socket.Lock() if l := len(socket.creds); l > 0 { debugf("Socket %p to %s: logout all (flagged %d)", socket, socket.addr, l) socket.logout = append(socket.logout, socket.creds...) socket.creds = socket.creds[0:0] } socket.Unlock() } func (socket *mongoSocket) flushLogout() (ops []interface{}) { socket.Lock() if l := len(socket.logout); l > 0 { debugf("Socket %p to %s: logout all (flushing %d)", socket, socket.addr, l) for i := 0; i != l; i++ { op := queryOp{} op.query = &logoutCmd{1} op.collection = socket.logout[i].Source + ".$cmd" op.limit = -1 ops = append(ops, &op) } socket.logout = socket.logout[0:0] } socket.Unlock() return } func (socket *mongoSocket) dropAuth(db string) (cred Credential, found bool) { for i, sockCred := range socket.creds { if sockCred.Source == db { copy(socket.creds[i:], socket.creds[i+1:]) socket.creds = socket.creds[:len(socket.creds)-1] return sockCred, true } } return cred, false } func (socket *mongoSocket) dropLogout(cred Credential) (found bool) { for i, sockCred := range socket.logout { if sockCred == cred { copy(socket.logout[i:], socket.logout[i+1:]) socket.logout = socket.logout[:len(socket.logout)-1] return true } } return false }<|fim▁end|>
return err }
<|file_name|>regiment.js<|end_file_name|><|fim▁begin|>'use strict'; const os = require('os'); const cluster = require('cluster'); const DEFAULT_DEADLINE_MS = 30000; function makeWorker(workerFunc) { var server = workerFunc(cluster.worker.id); server.on('close', function() { process.exit(); }); process.on('SIGTERM', function() { server.close();<|fim▁hole|> }); return server; } const Regiment = function(workerFunc, options) { if (cluster.isWorker) return makeWorker(workerFunc); options = options || {}; const numCpus = os.cpus().length; let running = true; const deadline = options.deadline || DEFAULT_DEADLINE_MS; const numWorkers = options.numWorkers || numCpus; const logger = options.logger || console; function messageHandler(msg) { if (running && msg.cmd && msg.cmd === 'need_replacement') { const workerId = msg.workerId; const replacement = spawn(); logger.log(`Replacing worker ${workerId} with worker ${replacement.id}`); replacement.on('listening', (address) => { logger.log(`Replacement ${replacement.id} is listening, killing ${workerId}`); kill(cluster.workers[workerId]); }) } } function spawn() { const worker = cluster.fork(); worker.on('message', messageHandler); return worker; } function fork() { for (var i=0; i<numWorkers; i++) { spawn(); } } function kill(worker) { logger.log(`Killing ${worker.id}`); worker.process.kill(); ensureDeath(worker); } function ensureDeath(worker) { setTimeout(() => { logger.log(`Ensured death of ${worker.id}`); worker.kill(); }, deadline).unref(); worker.disconnect(); } function respawn(worker, code, signal) { if (running && !worker.exitedAfterDisconnect) { logger.log(`Respawning ${worker.id} after it exited`); spawn(); } } function listen() { process.on('SIGINT', shutdown); process.on('SIGTERM', shutdown); cluster.on('exit', respawn); } function shutdown() { running = false; logger.log(`Shutting down!`); for (var id in cluster.workers) { kill(cluster.workers[id]); } } listen(); fork(); } Regiment.middleware = require('./middleware'); module.exports = Regiment;<|fim▁end|>
<|file_name|>test__socket_timeout.py<|end_file_name|><|fim▁begin|>import sys import gevent from gevent import socket import greentest class Test(greentest.TestCase): def start(self): self.server = socket.socket() self.server.bind(('127.0.0.1', 0)) self.server.listen(1) self.server_port = self.server.getsockname()[1] self.acceptor = gevent.spawn(self.server.accept) def stop(self): self.server.close() self.acceptor.kill() del self.acceptor del self.server def test(self): self.start() try: sock = socket.socket() sock.connect(('127.0.0.1', self.server_port)) try:<|fim▁hole|> result = sock.recv(1024) raise AssertionError('Expected timeout to be raised, instead recv() returned %r' % (result, )) except socket.error: ex = sys.exc_info()[1] self.assertEqual(ex.args, ('timed out',)) self.assertEqual(str(ex), 'timed out') self.assertEqual(ex[0], 'timed out') finally: sock.close() finally: self.stop() if __name__ == '__main__': greentest.main()<|fim▁end|>
sock.settimeout(0.1) try:
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.contrib.contenttypes.models import ContentType import json from django.http import Http404, HttpResponse from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required, user_passes_test <|fim▁hole|>from guardian.shortcuts import get_objects_for_user from account.models import DepartmentGroup from backend.tasks import TestConnectionTask from event.models import NotificationPreferences from .models import Application, Department, Environment, Server, ServerRole from task.models import Execution @login_required def index(request): data = {} executions = Execution.objects.filter(task__application__department_id=request.current_department_id) if not executions.count(): return redirect(reverse('first_steps_page')) return render(request, 'page/index.html', data) @permission_required('core.view_application', (Application, 'id', 'application_id')) def application_page(request, application_id): data = {} data['application'] = get_object_or_404(Application, pk=application_id) return render(request, 'page/application.html', data) @permission_required('core.view_environment', (Environment, 'id', 'environment_id')) def environment_page(request, environment_id): data = {} data['environment'] = get_object_or_404(Environment, pk=environment_id) data['servers'] = list(Server.objects.filter(environment_id=environment_id).prefetch_related('roles')) return render(request, 'page/environment.html', data) @permission_required('core.view_environment', (Environment, 'servers__id', 'server_id')) def server_test(request, server_id): data = {} data['server'] = get_object_or_404(Server, pk=server_id) data['task_id'] = TestConnectionTask().delay(server_id).id return render(request, 'partial/server_test.html', data) @login_required def server_test_ajax(request, task_id): data = {} task = TestConnectionTask().AsyncResult(task_id) if task.status == 'SUCCESS': status, output = task.get() data['status'] = status data['output'] = output elif task.status == 'FAILED': data['status'] = False else: data['status'] = None return HttpResponse(json.dumps(data), content_type="application/json") @login_required def first_steps_page(request): data = {} return render(request, 'page/first_steps.html', data) @login_required def settings_page(request, section='user', subsection='profile'): data = {} data['section'] = section data['subsection'] = subsection data['department'] = Department(pk=request.current_department_id) data['on_settings'] = True handler = '_settings_%s_%s' % (section, subsection) if section == 'system' and request.user.is_superuser is not True: return redirect('index') if section == 'department' and not request.user.has_perm('core.change_department', obj=data['department']): return redirect('index') if handler in globals(): data = globals()[handler](request, data) else: raise Http404 return render(request, 'page/settings.html', data) def _settings_account_profile(request, data): data['subsection_template'] = 'partial/account_profile.html' from account.forms import account_create_form form = account_create_form('user_profile', request, request.user.id) form.fields['email'].widget.attrs['readonly'] = True data['form'] = form if request.method == 'POST': if form.is_valid(): form.save() data['user'] = form.instance messages.success(request, 'Saved') return data def _settings_account_password(request, data): data['subsection_template'] = 'partial/account_password.html' from account.forms import account_create_form form = account_create_form('user_password', request, request.user.id) data['form'] = form if request.method == 'POST': if form.is_valid(): user = form.save(commit=False) user.set_password(user.password) user.save() data['user'] = form.instance messages.success(request, 'Saved') return data def _settings_account_notifications(request, data): data['subsection_template'] = 'partial/account_notifications.html' data['applications'] = get_objects_for_user(request.user, 'core.view_application') content_type = ContentType.objects.get_for_model(Application) if request.method == 'POST': for application in data['applications']: key = 'notification[%s]' % application.id notification, created = NotificationPreferences.objects.get_or_create( user=request.user, event_type='ExecutionFinish', content_type=content_type, object_id=application.id) if notification.is_active != (key in request.POST): notification.is_active = key in request.POST notification.save() messages.success(request, 'Saved') data['notifications'] = NotificationPreferences.objects.filter( user=request.user, event_type='ExecutionFinish', content_type=content_type.id).values_list('object_id', 'is_active') data['notifications'] = dict(data['notifications']) return data def _settings_department_applications(request, data): data['subsection_template'] = 'partial/application_list.html' data['applications'] = Application.objects.filter(department_id=request.current_department_id) data['empty'] = not bool(data['applications'].count()) return data def _settings_department_users(request, data): data['subsection_template'] = 'partial/user_list.html' from guardian.shortcuts import get_users_with_perms department = Department.objects.get(pk=request.current_department_id) data['users'] = get_users_with_perms(department).prefetch_related('groups__departmentgroup').order_by('name') data['department_user_list'] = True data['form_name'] = 'user' return data def _settings_department_groups(request, data): data['subsection_template'] = 'partial/group_list.html' data['groups'] = DepartmentGroup.objects.filter(department_id=request.current_department_id) return data def _settings_department_serverroles(request, data): data['subsection_template'] = 'partial/serverrole_list.html' data['serverroles'] = ServerRole.objects.filter(department_id=request.current_department_id) data['empty'] = not bool(data['serverroles'].count()) return data @user_passes_test(lambda u: u.is_superuser) def _settings_system_departments(request, data): data['subsection_template'] = 'partial/department_list.html' data['departments'] = Department.objects.all() return data @user_passes_test(lambda u: u.is_superuser) def _settings_system_users(request, data): data['subsection_template'] = 'partial/user_list.html' data['users'] = get_user_model().objects.exclude(id=-1).prefetch_related('groups__departmentgroup__department').order_by('name') data['form_name'] = 'usersystem' return data def department_switch(request, id): department = get_object_or_404(Department, pk=id) if request.user.has_perm('core.view_department', department): request.session['current_department_id'] = int(id) else: messages.error(request, 'Access forbidden') return redirect('index') def handle_403(request): print 'aaaaaaaa' messages.error(request, 'Access forbidden') return redirect('index')<|fim▁end|>
from django.core.urlresolvers import reverse from django.shortcuts import get_object_or_404, redirect, render from guardian.decorators import permission_required
<|file_name|>72.py<|end_file_name|><|fim▁begin|>class Solution: def minDistance(self, word1, word2):<|fim▁hole|> :type word1: str :type word2: str :rtype: int """ l1 = len(word1) l2 = len(word2) if l1 == 0 and l2 != 0: return l2 if l1 != 0 and l2 == 0: return l1 matrix = [[0]*(l2+1) for i in range(0, l1+1)] for i in range(0, l1+1): for j in range(0, l2+1): if i == 0: matrix[i][j] = j elif j == 0: matrix[i][j] = i else: if word1[i-1] == word2[j-1]: matrix[i][j] = matrix[i-1][j-1] else: matrix[i][j] = min(matrix[i][j-1], matrix[i-1][j], matrix[i-1][j-1]) + 1 return matrix[l1][l2]<|fim▁end|>
"""
<|file_name|>no_command.py<|end_file_name|><|fim▁begin|>from difflib import get_close_matches import os from pathlib import Path def _safe(fn, fallback): try: return fn() except OSError: return fallback def _get_all_bins(): return [exe.name for path in os.environ.get('PATH', '').split(':')<|fim▁hole|> def match(command, settings): return 'not found' in command.stderr and \ bool(get_close_matches(command.script.split(' ')[0], _get_all_bins())) def get_new_command(command, settings): old_command = command.script.split(' ')[0] new_command = get_close_matches(old_command, _get_all_bins())[0] return ' '.join([new_command] + command.script.split(' ')[1:])<|fim▁end|>
for exe in _safe(lambda: list(Path(path).iterdir()), []) if not _safe(exe.is_dir, True)]
<|file_name|>machine.go<|end_file_name|><|fim▁begin|>package main import ( "errors" "fmt" "strings" "sync" . "github.com/tendermint/go-common" "github.com/codegangsta/cli" ) //-------------------------------------------------------------------------------- func cmdSsh(c *cli.Context) { args := c.Args() machines := ParseMachines(c.String("machines")) cmdBase(args, machines, sshCmd) } func cmdScp(c *cli.Context) { args := c.Args() machines := ParseMachines(c.String("machines")) fmt.Println(args, machines) cmdBase(args, machines, scpCmd) } func cmdBase(args, machines []string, cmd func(string, []string) error) { var wg sync.WaitGroup for _, mach := range machines { wg.Add(1) go func(mach string) { maybeSleep(len(machines), 2000) defer wg.Done() cmd(mach, args) }(mach) } wg.Wait() } func sshCmd(mach string, args []string) error { args = []string{"ssh", mach, strings.Join(args, " ")} if !runProcess("ssh-cmd-"+mach, "docker-machine", args, true) { return errors.New("Failed to exec ssh command on machine " + mach) } return nil } func scpCmd(mach string, args []string) error { if len(args) != 2 { return errors.New("scp expects exactly two args") } args = []string{"scp", args[0], mach + ":" + args[1]} if !runProcess("ssh-cmd-"+mach, "docker-machine", args, true) { return errors.New("Failed to exec ssh command on machine " + mach) } return nil } //-------------------------------------------------------------------------------- func cmdCreate(c *cli.Context) { args := c.Args() machines := ParseMachines(c.String("machines")) errs := createMachines(machines, args) if len(errs) > 0 { Exit(Fmt("There were %v errors", len(errs))) } else { fmt.Println(Fmt("Successfully created %v machines", len(machines))) } } func createMachines(machines []string, args []string) (errs []error) { var wg sync.WaitGroup for _, mach := range machines { wg.Add(1) go func(mach string) { maybeSleep(len(machines), 2000) defer wg.Done() err := createMachine(args, mach) if err != nil { errs = append(errs, err) // TODO: make thread safe } }(mach) } wg.Wait() return errs } func createMachine(args []string, mach string) error { args = append([]string{"create"}, args...) args = append(args, mach) if !runProcess("create-"+mach, "docker-machine", args, true) { return errors.New("Failed to create machine " + mach) } return nil } //-------------------------------------------------------------------------------- func cmdDestroy(c *cli.Context) { machines := ParseMachines(c.String("machines")) // Destroy each machine. var wg sync.WaitGroup for _, mach := range machines { wg.Add(1) go func(mach string) { defer wg.Done() err := removeMachine(mach) if err != nil { fmt.Println(Red(err.Error())) } }(mach) } wg.Wait() fmt.Println("Success!") } //-------------------------------------------------------------------------------- func cmdProvision(c *cli.Context) { args := c.Args() machines := ParseMachines(c.String("machines")) errs := provisionMachines(machines, args) if len(errs) > 0 { Exit(Fmt("There were %v errors", len(errs))) } else { fmt.Println(Fmt("Successfully created %v machines", len(machines))) } } func provisionMachines(machines []string, args []string) (errs []error) { var wg sync.WaitGroup for _, mach := range machines { wg.Add(1) go func(mach string) { maybeSleep(len(machines), 2000) defer wg.Done() err := provisionMachine(args, mach) if err != nil { errs = append(errs, err) } }(mach) } wg.Wait() return errs } func provisionMachine(args []string, mach string) error { args = append([]string{"provision"}, args...) args = append(args, mach) if !runProcess("provision-"+mach, "docker-machine", args, true) { return errors.New("Failed to provision machine " + mach) } return nil } //-------------------------------------------------------------------------------- // Stop a machine // mach: name of machine func stopMachine(mach string) error { args := []string{"stop", mach} if !runProcess("stop-"+mach, "docker-machine", args, true) { return errors.New("Failed to stop machine " + mach) } return nil<|fim▁hole|>// Remove a machine // mach: name of machine func removeMachine(mach string) error { args := []string{"rm", "-f", mach} if !runProcess("remove-"+mach, "docker-machine", args, true) { return errors.New("Failed to remove machine " + mach) } return nil } // List machine names that match prefix func listMachines(prefix string) ([]string, error) { args := []string{"ls", "--quiet"} output, ok := runProcessGetResult("list-machines", "docker-machine", args, true) if !ok { return nil, errors.New("Failed to list machines") } output = strings.TrimSpace(output) if len(output) == 0 { return nil, nil } machines := strings.Split(output, "\n") matched := []string{} for _, mach := range machines { if strings.HasPrefix(mach, prefix+"-") { matched = append(matched, mach) } } return matched, nil } // Get ip of a machine // mach: name of machine func getMachineIP(mach string) (string, error) { args := []string{"ip", mach} output, ok := runProcessGetResult("get-ip-"+mach, "docker-machine", args, true) if !ok { return "", errors.New("Failed to get ip of machine" + mach) } return strings.TrimSpace(output), nil }<|fim▁end|>
}
<|file_name|>ops.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. //! Overloadable operators //! //! Implementing these traits allows you to get an effect similar to //! overloading operators. //! //! Some of these traits are imported by the prelude, so they are available in //! every Rust program. //! //! Many of the operators take their operands by value. In non-generic //! contexts involving built-in types, this is usually not a problem. //! However, using these operators in generic code, requires some //! attention if values have to be reused as opposed to letting the operators //! consume them. One option is to occasionally use `clone()`. //! Another option is to rely on the types involved providing additional //! operator implementations for references. For example, for a user-defined //! type `T` which is supposed to support addition, it is probably a good //! idea to have both `T` and `&T` implement the traits `Add<T>` and `Add<&T>` //! so that generic code can be written without unnecessary cloning. //! //! # Examples //! //! This example creates a `Point` struct that implements `Add` and `Sub`, and then //! demonstrates adding and subtracting two `Point`s. //! //! ```rust //! use std::ops::{Add, Sub}; //! //! #[derive(Debug)] //! struct Point { //! x: i32, //! y: i32 //! } //! //! impl Add for Point { //! type Output = Point; //! //! fn add(self, other: Point) -> Point { //! Point {x: self.x + other.x, y: self.y + other.y} //! } //! } //! //! impl Sub for Point { //! type Output = Point; //! //! fn sub(self, other: Point) -> Point { //! Point {x: self.x - other.x, y: self.y - other.y} //! } //! } //! fn main() { //! println!("{:?}", Point {x: 1, y: 0} + Point {x: 2, y: 3}); //! println!("{:?}", Point {x: 1, y: 0} - Point {x: 2, y: 3}); //! } //! ``` //! //! See the documentation for each trait for a minimum implementation that prints //! something to the screen. #![stable(feature = "rust1", since = "1.0.0")] use marker::Sized; use option::Option; use fmt; /// The `Drop` trait is used to run some code when a value goes out of scope. This /// is sometimes called a 'destructor'. /// /// # Examples /// /// A trivial implementation of `Drop`. The `drop` method is called when `_x` goes /// out of scope, and therefore `main` prints `Dropping!`. /// /// ``` /// struct HasDrop; /// /// impl Drop for HasDrop { /// fn drop(&mut self) { /// println!("Dropping!"); /// } /// } /// /// fn main() { /// let _x = HasDrop; /// } /// ``` #[lang="drop"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Drop { /// The `drop` method, called when the value goes out of scope. #[stable(feature = "rust1", since = "1.0.0")] fn drop(&mut self); } // implements the unary operator "op &T" // based on "op T" where T is expected to be `Copy`able macro_rules! forward_ref_unop { (impl $imp:ident, $method:ident for $t:ty) => { #[unstable(feature = "core", reason = "recently added, waiting for dust to settle")] impl<'a> $imp for &'a $t { type Output = <$t as $imp>::Output; #[inline] fn $method(self) -> <$t as $imp>::Output { $imp::$method(*self) } } } } // implements binary operators "&T op U", "T op &U", "&T op &U" // based on "T op U" where T and U are expected to be `Copy`able macro_rules! forward_ref_binop { (impl $imp:ident, $method:ident for $t:ty, $u:ty) => { #[unstable(feature = "core", reason = "recently added, waiting for dust to settle")] impl<'a> $imp<$u> for &'a $t { type Output = <$t as $imp<$u>>::Output; #[inline] fn $method(self, other: $u) -> <$t as $imp<$u>>::Output { $imp::$method(*self, other) } } #[unstable(feature = "core", reason = "recently added, waiting for dust to settle")] impl<'a> $imp<&'a $u> for $t { type Output = <$t as $imp<$u>>::Output; #[inline] fn $method(self, other: &'a $u) -> <$t as $imp<$u>>::Output { $imp::$method(self, *other) } } #[unstable(feature = "core", reason = "recently added, waiting for dust to settle")] impl<'a, 'b> $imp<&'a $u> for &'b $t { type Output = <$t as $imp<$u>>::Output; #[inline] fn $method(self, other: &'a $u) -> <$t as $imp<$u>>::Output { $imp::$method(*self, *other) } } } } /// The `Add` trait is used to specify the functionality of `+`. /// /// # Examples /// /// A trivial implementation of `Add`. When `Foo + Foo` happens, it ends up /// calling `add`, and therefore, `main` prints `Adding!`. /// /// ``` /// use std::ops::Add; /// /// #[derive(Copy, Clone)] /// struct Foo; /// /// impl Add for Foo { /// type Output = Foo; /// /// fn add(self, _rhs: Foo) -> Foo { /// println!("Adding!"); /// self /// } /// } /// /// fn main() { /// Foo + Foo; /// } /// ``` #[lang="add"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Add<RHS=Self> { /// The resulting type after applying the `+` operator #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the `+` operator #[stable(feature = "rust1", since = "1.0.0")] fn add(self, rhs: RHS) -> Self::Output; } macro_rules! add_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl Add for $t { type Output = $t; #[inline] fn add(self, other: $t) -> $t { self + other } } forward_ref_binop! { impl Add, add for $t, $t } )*) } add_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 } /// The `Sub` trait is used to specify the functionality of `-`. /// /// # Examples /// /// A trivial implementation of `Sub`. When `Foo - Foo` happens, it ends up /// calling `sub`, and therefore, `main` prints `Subtracting!`. /// /// ``` /// use std::ops::Sub; /// /// #[derive(Copy, Clone)] /// struct Foo; /// /// impl Sub for Foo { /// type Output = Foo; /// /// fn sub(self, _rhs: Foo) -> Foo { /// println!("Subtracting!"); /// self /// } /// } /// /// fn main() { /// Foo - Foo; /// } /// ``` #[lang="sub"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Sub<RHS=Self> { /// The resulting type after applying the `-` operator #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the `-` operator #[stable(feature = "rust1", since = "1.0.0")] fn sub(self, rhs: RHS) -> Self::Output; } macro_rules! sub_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl Sub for $t { type Output = $t; #[inline] fn sub(self, other: $t) -> $t { self - other } } forward_ref_binop! { impl Sub, sub for $t, $t } )*) } sub_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 } /// The `Mul` trait is used to specify the functionality of `*`. /// /// # Examples /// /// A trivial implementation of `Mul`. When `Foo * Foo` happens, it ends up /// calling `mul`, and therefore, `main` prints `Multiplying!`. /// /// ``` /// use std::ops::Mul; /// /// #[derive(Copy, Clone)] /// struct Foo; /// /// impl Mul for Foo { /// type Output = Foo; /// /// fn mul(self, _rhs: Foo) -> Foo { /// println!("Multiplying!"); /// self /// } /// } /// /// fn main() { /// Foo * Foo; /// } /// ``` #[lang="mul"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Mul<RHS=Self> { /// The resulting type after applying the `*` operator #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the `*` operator #[stable(feature = "rust1", since = "1.0.0")] fn mul(self, rhs: RHS) -> Self::Output; } macro_rules! mul_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl Mul for $t { type Output = $t; #[inline] fn mul(self, other: $t) -> $t { self * other } } forward_ref_binop! { impl Mul, mul for $t, $t } )*) } mul_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 } /// The `Div` trait is used to specify the functionality of `/`. /// /// # Examples /// /// A trivial implementation of `Div`. When `Foo / Foo` happens, it ends up /// calling `div`, and therefore, `main` prints `Dividing!`. /// /// ``` /// use std::ops::Div; /// /// #[derive(Copy, Clone)] /// struct Foo; /// /// impl Div for Foo { /// type Output = Foo; /// /// fn div(self, _rhs: Foo) -> Foo { /// println!("Dividing!"); /// self /// } /// } /// /// fn main() { /// Foo / Foo; /// } /// ``` #[lang="div"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Div<RHS=Self> { /// The resulting type after applying the `/` operator #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the `/` operator #[stable(feature = "rust1", since = "1.0.0")] fn div(self, rhs: RHS) -> Self::Output; } use num::wrapping::OverflowingOps; macro_rules! div_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl Div for $t { type Output = $t; #[inline] fn div(self, other: $t) -> $t { self.overflowing_div(other).0 } } forward_ref_binop! { impl Div, div for $t, $t } )*) } macro_rules! div_impl_float { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl Div for $t { type Output = $t; #[inline] fn div(self, other: $t) -> $t { self / other } } forward_ref_binop! { impl Div, div for $t, $t } )*) } div_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 } div_impl_float! { f32 f64 } /// The `Rem` trait is used to specify the functionality of `%`. /// /// # Examples /// /// A trivial implementation of `Rem`. When `Foo % Foo` happens, it ends up /// calling `rem`, and therefore, `main` prints `Remainder-ing!`. /// /// ``` /// use std::ops::Rem; /// /// #[derive(Copy, Clone)] /// struct Foo; /// /// impl Rem for Foo { /// type Output = Foo; /// /// fn rem(self, _rhs: Foo) -> Foo {<|fim▁hole|>/// } /// } /// /// fn main() { /// Foo % Foo; /// } /// ``` #[lang="rem"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Rem<RHS=Self> { /// The resulting type after applying the `%` operator #[stable(feature = "rust1", since = "1.0.0")] type Output = Self; /// The method for the `%` operator #[stable(feature = "rust1", since = "1.0.0")] fn rem(self, rhs: RHS) -> Self::Output; } macro_rules! rem_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl Rem for $t { type Output = $t; #[inline] fn rem(self, other: $t) -> $t { self.overflowing_rem(other).0 } } forward_ref_binop! { impl Rem, rem for $t, $t } )*) } macro_rules! rem_float_impl { ($t:ty, $fmod:ident) => { #[stable(feature = "rust1", since = "1.0.0")] impl Rem for $t { type Output = $t; #[inline] fn rem(self, other: $t) -> $t { extern { fn $fmod(a: $t, b: $t) -> $t; } unsafe { $fmod(self, other) } } } forward_ref_binop! { impl Rem, rem for $t, $t } } } rem_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 } rem_float_impl! { f32, fmodf } rem_float_impl! { f64, fmod } /// The `Neg` trait is used to specify the functionality of unary `-`. /// /// # Examples /// /// A trivial implementation of `Neg`. When `-Foo` happens, it ends up calling /// `neg`, and therefore, `main` prints `Negating!`. /// /// ``` /// use std::ops::Neg; /// /// #[derive(Copy, Clone)] /// struct Foo; /// /// impl Neg for Foo { /// type Output = Foo; /// /// fn neg(self) -> Foo { /// println!("Negating!"); /// self /// } /// } /// /// fn main() { /// -Foo; /// } /// ``` #[lang="neg"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Neg { /// The resulting type after applying the `-` operator #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the unary `-` operator #[stable(feature = "rust1", since = "1.0.0")] fn neg(self) -> Self::Output; } macro_rules! neg_impl_core { ($id:ident => $body:expr, $($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] #[allow(unsigned_negation)] impl Neg for $t { #[stable(feature = "rust1", since = "1.0.0")] type Output = $t; #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn neg(self) -> $t { let $id = self; $body } } forward_ref_unop! { impl Neg, neg for $t } )*) } macro_rules! neg_impl_numeric { ($($t:ty)*) => { neg_impl_core!{ x => -x, $($t)*} } } macro_rules! neg_impl_unsigned { ($($t:ty)*) => { neg_impl_core!{ x => { #[cfg(stage0)] use ::num::wrapping::WrappingOps; !x.wrapping_add(1) }, $($t)*} } } // neg_impl_unsigned! { usize u8 u16 u32 u64 } neg_impl_numeric! { isize i8 i16 i32 i64 f32 f64 } /// The `Not` trait is used to specify the functionality of unary `!`. /// /// # Examples /// /// A trivial implementation of `Not`. When `!Foo` happens, it ends up calling /// `not`, and therefore, `main` prints `Not-ing!`. /// /// ``` /// use std::ops::Not; /// /// #[derive(Copy, Clone)] /// struct Foo; /// /// impl Not for Foo { /// type Output = Foo; /// /// fn not(self) -> Foo { /// println!("Not-ing!"); /// self /// } /// } /// /// fn main() { /// !Foo; /// } /// ``` #[lang="not"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Not { /// The resulting type after applying the `!` operator #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the unary `!` operator #[stable(feature = "rust1", since = "1.0.0")] fn not(self) -> Self::Output; } macro_rules! not_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl Not for $t { type Output = $t; #[inline] fn not(self) -> $t { !self } } forward_ref_unop! { impl Not, not for $t } )*) } not_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 } /// The `BitAnd` trait is used to specify the functionality of `&`. /// /// # Examples /// /// A trivial implementation of `BitAnd`. When `Foo & Foo` happens, it ends up /// calling `bitand`, and therefore, `main` prints `Bitwise And-ing!`. /// /// ``` /// use std::ops::BitAnd; /// /// #[derive(Copy, Clone)] /// struct Foo; /// /// impl BitAnd for Foo { /// type Output = Foo; /// /// fn bitand(self, _rhs: Foo) -> Foo { /// println!("Bitwise And-ing!"); /// self /// } /// } /// /// fn main() { /// Foo & Foo; /// } /// ``` #[lang="bitand"] #[stable(feature = "rust1", since = "1.0.0")] pub trait BitAnd<RHS=Self> { /// The resulting type after applying the `&` operator #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the `&` operator #[stable(feature = "rust1", since = "1.0.0")] fn bitand(self, rhs: RHS) -> Self::Output; } macro_rules! bitand_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl BitAnd for $t { type Output = $t; #[inline] fn bitand(self, rhs: $t) -> $t { self & rhs } } forward_ref_binop! { impl BitAnd, bitand for $t, $t } )*) } bitand_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 } /// The `BitOr` trait is used to specify the functionality of `|`. /// /// # Examples /// /// A trivial implementation of `BitOr`. When `Foo | Foo` happens, it ends up /// calling `bitor`, and therefore, `main` prints `Bitwise Or-ing!`. /// /// ``` /// use std::ops::BitOr; /// /// #[derive(Copy, Clone)] /// struct Foo; /// /// impl BitOr for Foo { /// type Output = Foo; /// /// fn bitor(self, _rhs: Foo) -> Foo { /// println!("Bitwise Or-ing!"); /// self /// } /// } /// /// fn main() { /// Foo | Foo; /// } /// ``` #[lang="bitor"] #[stable(feature = "rust1", since = "1.0.0")] pub trait BitOr<RHS=Self> { /// The resulting type after applying the `|` operator #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the `|` operator #[stable(feature = "rust1", since = "1.0.0")] fn bitor(self, rhs: RHS) -> Self::Output; } macro_rules! bitor_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl BitOr for $t { type Output = $t; #[inline] fn bitor(self, rhs: $t) -> $t { self | rhs } } forward_ref_binop! { impl BitOr, bitor for $t, $t } )*) } bitor_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 } /// The `BitXor` trait is used to specify the functionality of `^`. /// /// # Examples /// /// A trivial implementation of `BitXor`. When `Foo ^ Foo` happens, it ends up /// calling `bitxor`, and therefore, `main` prints `Bitwise Xor-ing!`. /// /// ``` /// use std::ops::BitXor; /// /// #[derive(Copy, Clone)] /// struct Foo; /// /// impl BitXor for Foo { /// type Output = Foo; /// /// fn bitxor(self, _rhs: Foo) -> Foo { /// println!("Bitwise Xor-ing!"); /// self /// } /// } /// /// fn main() { /// Foo ^ Foo; /// } /// ``` #[lang="bitxor"] #[stable(feature = "rust1", since = "1.0.0")] pub trait BitXor<RHS=Self> { /// The resulting type after applying the `^` operator #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the `^` operator #[stable(feature = "rust1", since = "1.0.0")] fn bitxor(self, rhs: RHS) -> Self::Output; } macro_rules! bitxor_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl BitXor for $t { type Output = $t; #[inline] fn bitxor(self, other: $t) -> $t { self ^ other } } forward_ref_binop! { impl BitXor, bitxor for $t, $t } )*) } bitxor_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 } /// The `Shl` trait is used to specify the functionality of `<<`. /// /// # Examples /// /// A trivial implementation of `Shl`. When `Foo << Foo` happens, it ends up /// calling `shl`, and therefore, `main` prints `Shifting left!`. /// /// ``` /// use std::ops::Shl; /// /// #[derive(Copy, Clone)] /// struct Foo; /// /// impl Shl<Foo> for Foo { /// type Output = Foo; /// /// fn shl(self, _rhs: Foo) -> Foo { /// println!("Shifting left!"); /// self /// } /// } /// /// fn main() { /// Foo << Foo; /// } /// ``` #[lang="shl"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Shl<RHS> { /// The resulting type after applying the `<<` operator #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the `<<` operator #[stable(feature = "rust1", since = "1.0.0")] fn shl(self, rhs: RHS) -> Self::Output; } macro_rules! shl_impl { ($t:ty, $f:ty) => ( #[stable(feature = "rust1", since = "1.0.0")] impl Shl<$f> for $t { type Output = $t; #[inline] fn shl(self, other: $f) -> $t { self << other } } forward_ref_binop! { impl Shl, shl for $t, $f } ) } macro_rules! shl_impl_all { ($($t:ty)*) => ($( shl_impl! { $t, u8 } shl_impl! { $t, u16 } shl_impl! { $t, u32 } shl_impl! { $t, u64 } shl_impl! { $t, usize } shl_impl! { $t, i8 } shl_impl! { $t, i16 } shl_impl! { $t, i32 } shl_impl! { $t, i64 } shl_impl! { $t, isize } )*) } shl_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize } /// The `Shr` trait is used to specify the functionality of `>>`. /// /// # Examples /// /// A trivial implementation of `Shr`. When `Foo >> Foo` happens, it ends up /// calling `shr`, and therefore, `main` prints `Shifting right!`. /// /// ``` /// use std::ops::Shr; /// /// #[derive(Copy, Clone)] /// struct Foo; /// /// impl Shr<Foo> for Foo { /// type Output = Foo; /// /// fn shr(self, _rhs: Foo) -> Foo { /// println!("Shifting right!"); /// self /// } /// } /// /// fn main() { /// Foo >> Foo; /// } /// ``` #[lang="shr"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Shr<RHS> { /// The resulting type after applying the `>>` operator #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the `>>` operator #[stable(feature = "rust1", since = "1.0.0")] fn shr(self, rhs: RHS) -> Self::Output; } macro_rules! shr_impl { ($t:ty, $f:ty) => ( impl Shr<$f> for $t { type Output = $t; #[inline] fn shr(self, other: $f) -> $t { self >> other } } forward_ref_binop! { impl Shr, shr for $t, $f } ) } macro_rules! shr_impl_all { ($($t:ty)*) => ($( shr_impl! { $t, u8 } shr_impl! { $t, u16 } shr_impl! { $t, u32 } shr_impl! { $t, u64 } shr_impl! { $t, usize } shr_impl! { $t, i8 } shr_impl! { $t, i16 } shr_impl! { $t, i32 } shr_impl! { $t, i64 } shr_impl! { $t, isize } )*) } shr_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize } /// The `Index` trait is used to specify the functionality of indexing operations /// like `arr[idx]` when used in an immutable context. /// /// # Examples /// /// A trivial implementation of `Index`. When `Foo[Bar]` happens, it ends up /// calling `index`, and therefore, `main` prints `Indexing!`. /// /// ``` /// use std::ops::Index; /// /// #[derive(Copy, Clone)] /// struct Foo; /// struct Bar; /// /// impl Index<Bar> for Foo { /// type Output = Foo; /// /// fn index<'a>(&'a self, _index: Bar) -> &'a Foo { /// println!("Indexing!"); /// self /// } /// } /// /// fn main() { /// Foo[Bar]; /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub trait Index<Idx> { /// The returned type after indexing #[stable(feature = "rust1", since = "1.0.0")] type Output: ?Sized; /// This method indexes, returning an option, and performs all checks fn index_checked<'a>(&'a self, index: Idx) -> Option<&'a Self::Output>; /// This method indexes unsafely, without any checks unsafe fn index_unchecked<'a>(&'a self, index: Idx) -> &'a Self::Output; } /// The `IndexMut` trait is used to specify the functionality of indexing /// operations like `arr[idx]`, when used in a mutable context. /// /// # Examples /// /// A trivial implementation of `IndexMut`. When `Foo[Bar]` happens, it ends up /// calling `index_mut`, and therefore, `main` prints `Indexing!`. /// /// ``` /// use std::ops::{Index, IndexMut}; /// /// #[derive(Copy, Clone)] /// struct Foo; /// struct Bar; /// /// impl Index<Bar> for Foo { /// type Output = Foo; /// /// fn index<'a>(&'a self, _index: Bar) -> &'a Foo { /// self /// } /// } /// /// impl IndexMut<Bar> for Foo { /// fn index_mut<'a>(&'a mut self, _index: Bar) -> &'a mut Foo { /// println!("Indexing!"); /// self /// } /// } /// /// fn main() { /// &mut Foo[Bar]; /// } /// ``` pub trait IndexMut<Idx>: Index<Idx> { /// Performs all checks, and is the same as index_safe but for mutability fn index_checked_mut<'a>(&'a mut self, index: Idx) -> Option<&'a mut Self::Output>; /// Same as index_unchecked, but mutable unsafe fn index_unchecked_mut<'a>(&'a mut self, index: Idx) -> &'a mut Self::Output; } /// An unbounded range. #[derive(Copy, Clone, PartialEq, Eq)] #[lang="range_full"] #[stable(feature = "rust1", since = "1.0.0")] pub struct RangeFull; #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for RangeFull { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "..") } } /// A (half-open) range which is bounded at both ends. #[derive(Clone, PartialEq, Eq)] #[lang="range"] #[stable(feature = "rust1", since = "1.0.0")] pub struct Range<Idx> { /// The lower bound of the range (inclusive). #[stable(feature = "rust1", since = "1.0.0")] pub start: Idx, /// The upper bound of the range (exclusive). #[stable(feature = "rust1", since = "1.0.0")] pub end: Idx, } #[stable(feature = "rust1", since = "1.0.0")] impl<Idx: fmt::Debug> fmt::Debug for Range<Idx> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{:?}..{:?}", self.start, self.end) } } /// A range which is only bounded below. #[derive(Clone, PartialEq, Eq)] #[lang="range_from"] #[stable(feature = "rust1", since = "1.0.0")] pub struct RangeFrom<Idx> { /// The lower bound of the range (inclusive). #[stable(feature = "rust1", since = "1.0.0")] pub start: Idx, } #[stable(feature = "rust1", since = "1.0.0")] impl<Idx: fmt::Debug> fmt::Debug for RangeFrom<Idx> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{:?}..", self.start) } } /// A range which is only bounded above. #[derive(Copy, Clone, PartialEq, Eq)] #[lang="range_to"] #[stable(feature = "rust1", since = "1.0.0")] pub struct RangeTo<Idx> { /// The upper bound of the range (exclusive). #[stable(feature = "rust1", since = "1.0.0")] pub end: Idx, } #[stable(feature = "rust1", since = "1.0.0")] impl<Idx: fmt::Debug> fmt::Debug for RangeTo<Idx> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "..{:?}", self.end) } } /// The `Deref` trait is used to specify the functionality of dereferencing /// operations like `*v`. /// /// # Examples /// /// A struct with a single field which is accessible via dereferencing the /// struct. /// /// ``` /// use std::ops::Deref; /// /// struct DerefExample<T> { /// value: T /// } /// /// impl<T> Deref for DerefExample<T> { /// type Target = T; /// /// fn deref<'a>(&'a self) -> &'a T { /// &self.value /// } /// } /// /// fn main() { /// let x = DerefExample { value: 'a' }; /// assert_eq!('a', *x); /// } /// ``` #[lang="deref"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Deref { /// The resulting type after dereferencing #[stable(feature = "rust1", since = "1.0.0")] type Target: ?Sized; /// The method called to dereference a value #[stable(feature = "rust1", since = "1.0.0")] fn deref<'a>(&'a self) -> &'a Self::Target; } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T: ?Sized> Deref for &'a T { type Target = T; fn deref(&self) -> &T { *self } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T: ?Sized> Deref for &'a mut T { type Target = T; fn deref(&self) -> &T { *self } } /// The `DerefMut` trait is used to specify the functionality of dereferencing /// mutably like `*v = 1;` /// /// # Examples /// /// A struct with a single field which is modifiable via dereferencing the /// struct. /// /// ``` /// use std::ops::{Deref, DerefMut}; /// /// struct DerefMutExample<T> { /// value: T /// } /// /// impl<T> Deref for DerefMutExample<T> { /// type Target = T; /// /// fn deref<'a>(&'a self) -> &'a T { /// &self.value /// } /// } /// /// impl<T> DerefMut for DerefMutExample<T> { /// fn deref_mut<'a>(&'a mut self) -> &'a mut T { /// &mut self.value /// } /// } /// /// fn main() { /// let mut x = DerefMutExample { value: 'a' }; /// *x = 'b'; /// assert_eq!('b', *x); /// } /// ``` #[lang="deref_mut"] #[stable(feature = "rust1", since = "1.0.0")] pub trait DerefMut: Deref { /// The method called to mutably dereference a value #[stable(feature = "rust1", since = "1.0.0")] fn deref_mut<'a>(&'a mut self) -> &'a mut Self::Target; } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T: ?Sized> DerefMut for &'a mut T { fn deref_mut(&mut self) -> &mut T { *self } } /// A version of the call operator that takes an immutable receiver. #[lang="fn"] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_paren_sugar] #[fundamental] // so that regex can rely that `&str: !FnMut` pub trait Fn<Args> : FnMut<Args> { /// This is called when the call operator is used. extern "rust-call" fn call(&self, args: Args) -> Self::Output; } /// A version of the call operator that takes a mutable receiver. #[lang="fn_mut"] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_paren_sugar] #[fundamental] // so that regex can rely that `&str: !FnMut` pub trait FnMut<Args> : FnOnce<Args> { /// This is called when the call operator is used. extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output; } /// A version of the call operator that takes a by-value receiver. #[lang="fn_once"] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_paren_sugar] #[fundamental] // so that regex can rely that `&str: !FnMut` pub trait FnOnce<Args> { /// The returned type after the call operator is used. type Output; /// This is called when the call operator is used. extern "rust-call" fn call_once(self, args: Args) -> Self::Output; } #[cfg(not(stage0))] mod impls { use marker::Sized; use super::{Fn, FnMut, FnOnce}; impl<'a,A,F:?Sized> Fn<A> for &'a F where F : Fn<A> { extern "rust-call" fn call(&self, args: A) -> F::Output { (**self).call(args) } } impl<'a,A,F:?Sized> FnMut<A> for &'a F where F : Fn<A> { extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output { (**self).call(args) } } impl<'a,A,F:?Sized> FnOnce<A> for &'a F where F : Fn<A> { type Output = F::Output; extern "rust-call" fn call_once(self, args: A) -> F::Output { (*self).call(args) } } impl<'a,A,F:?Sized> FnMut<A> for &'a mut F where F : FnMut<A> { extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output { (*self).call_mut(args) } } impl<'a,A,F:?Sized> FnOnce<A> for &'a mut F where F : FnMut<A> { type Output = F::Output; extern "rust-call" fn call_once(mut self, args: A) -> F::Output { (*self).call_mut(args) } } }<|fim▁end|>
/// println!("Remainder-ing!"); /// self
<|file_name|>test_init.py<|end_file_name|><|fim▁begin|>import __builtin__ import etcd from etcd import Client import importlib import inspect import maps from mock import MagicMock from mock import patch import os import pkgutil import pytest import yaml from tendrl.commons import objects import tendrl.commons.objects.node_context as node from tendrl.commons import TendrlNS from tendrl.commons.utils import etcd_utils @patch.object(etcd, "Client") @patch.object(Client, "read") @patch.object(node.NodeContext, '_get_node_id') @patch.object(etcd_utils, 'read') @patch.object(node.NodeContext, 'load') def init(patch_node_load, patch_etcd_utils_read, patch_get_node_id, patch_read, patch_client): patch_get_node_id.return_value = 1 patch_read.return_value = etcd.Client() patch_client.return_value = etcd.Client() setattr(__builtin__, "NS", maps.NamedDict()) setattr(NS, "_int", maps.NamedDict()) NS._int.etcd_kwargs = { 'port': 1, 'host': 2, 'allow_reconnect': True} NS._int.client = etcd.Client(**NS._int.etcd_kwargs) NS["config"] = maps.NamedDict() NS.config["data"] = maps.NamedDict() NS.config.data['tags'] = "test" patch_etcd_utils_read.return_value = maps.NamedDict( value='{"status": "UP",' '"pkey": "tendrl-node-test",' '"node_id": "test_node_id",' '"ipv4_addr": "test_ip",' '"tags": "[\\"my_tag\\"]",' '"sync_status": "done",' '"locked_by": "fd",' '"fqdn": "tendrl-node-test",' '"last_sync": "date"}') patch_node_load.return_value = node.NodeContext tendrlNS = TendrlNS() return tendrlNS def test_constructor(): with patch.object(TendrlNS, 'setup_common_objects') as \ mocked_method: mocked_method.return_value = None tendrlNS = TendrlNS() tendrlNS = init() # Default Parameter Testing assert tendrlNS.ns_name == "tendrl" assert tendrlNS.ns_src == "tendrl.commons" # Check for existance and right data type assert isinstance(NS, maps.NamedDict) # Testing _list_modules_in_package_path def test_list_modules_in_package_path(): tendrlNS = init() modules = [ ('alert', 'tendrl.commons.objects.alert'), ('block_device', 'tendrl.commons.objects.block_device'), ('cluster', 'tendrl.commons.objects.cluster'), ('cluster_alert', 'tendrl.commons.objects.cluster_alert'), ('cluster_alert_counters', 'tendrl.commons.objects.cluster_alert_counters'), ('cluster_node_alert_counters', 'tendrl.commons.objects.cluster_node_alert_counters'), ('cluster_node_context', 'tendrl.commons.objects.cluster_node_context'), ('cluster_tendrl_context', 'tendrl.commons.objects.cluster_tendrl_context'), ('cpu', 'tendrl.commons.objects.cpu'), ('definition', 'tendrl.commons.objects.definition'), ('detected_cluster', 'tendrl.commons.objects.detected_cluster'), ('disk', 'tendrl.commons.objects.disk'), ('geo_replication_session', 'tendrl.commons.objects.geo_replication_session'), ('global_details', 'tendrl.commons.objects.global_details'), ('gluster_brick', 'tendrl.commons.objects.gluster_brick'), ('gluster_volume', 'tendrl.commons.objects.gluster_volume'), ('gluster_peer', 'tendrl.commons.objects.gluster_peer'), ('job', 'tendrl.commons.objects.job'), ('memory', 'tendrl.commons.objects.memory'), ('node', 'tendrl.commons.objects.node'), ('node_alert', 'tendrl.commons.objects.node_alert'), ('node_context', 'tendrl.commons.objects.node_context'), ('node_network', 'tendrl.commons.objects.node_network'), ('notification_only_alert', 'tendrl.commons.objects.notification_only_alert'), ('os', 'tendrl.commons.objects.os'), ('platform', 'tendrl.commons.objects.platform'), ('service', 'tendrl.commons.objects.service'), ('tendrl_context', 'tendrl.commons.objects.tendrl_context'), ('virtual_disk', 'tendrl.commons.objects.virtual_disk') ] ns_objects_path = os.path.join(os.path.dirname(os.path.abspath(__file__)). rsplit('/', 1)[0], "objects") ns_objects_prefix = "tendrl.commons.objects." ret = tendrlNS._list_modules_in_package_path(ns_objects_path, ns_objects_prefix) # TO-DISCUSS : modules is hard coded and might change in future if len(ret) != len(modules): raise AssertionError() ret = tendrlNS._list_modules_in_package_path("test", "test") assert len(ret) == 0 # Testing _register_subclasses_to_ns def test_register_subclasses_to_ns(monkeypatch): tendrlNS = init() tendrlNS._register_subclasses_to_ns() assert len(getattr(NS.tendrl, "objects")) > 0 assert len(getattr(NS.tendrl, "flows")) > 0 ns_objects_path = os.path.join( os.path.dirname( os.path.abspath(__file__)).rsplit( '/', 1)[0], "objects") ns_objects_prefix = "tendrl.commons.objects." modules = tendrlNS._list_modules_in_package_path(ns_objects_path, ns_objects_prefix) for mode_name, mod_cls in modules: assert hasattr(NS.tendrl.objects, mode_name.title().replace('_', '')) \ is True def list_package(self_obj, package_path, prefix): if "flows" in prefix: return [ ('ImportCluster', 'tendrl.commons.flows.import_cluster'), ('UnmanageCluster', 'tendrl.commons.flows.unmanage_cluster') ] else: modules = [] for importer, name, ispkg in pkgutil.walk_packages( path=[package_path]): modules.append((name, prefix + name)) return modules monkeypatch.setattr(TendrlNS, '_list_modules_in_package_path', list_package) tendrlNS._register_subclasses_to_ns() assert len(getattr(NS.tendrl, "objects")) > 0 # Testing _add_object def test_add_object(): tendrlNS = init() obj_name = "test_obj" obj = importlib.import_module( "tendrl.commons.objects.cluster_node_context") current_ns = tendrlNS._get_ns() obj_cls = "" for obj_cls in inspect.getmembers(obj, inspect.isclass): tendrlNS._add_object(obj_name, obj_cls[1]) break assert isinstance(getattr(current_ns.objects, "_test_obj")['atoms'], maps.NamedDict) assert isinstance(getattr(current_ns.objects, "_test_obj")['flows'], maps.NamedDict) with patch.object(TendrlNS, "_get_ns") as mock_add_obj: mock_add_obj.return_value = maps.NamedDict( objects=maps.NamedDict(_Service=maps.NamedDict( atoms=maps.NamedDict()))) tendrlNS._add_object("Service", obj_cls[1]) with patch.object(TendrlNS, "_get_ns") as mock_add_obj: mock_add_obj.return_value = maps.NamedDict( objects=maps.NamedDict( _Service=maps.NamedDict( flows=maps.NamedDict()))) tendrlNS._add_object("Service", obj_cls[1]) # Testing _get_objects def test_get_objects(): path = os.path.join(os.path.dirname( os.path.dirname(os.path.abspath(__file__))), "objects") objects_list = [d.title().replace('_', '') for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))] tendrlNS = init() ret = tendrlNS._get_objects() assert isinstance(objects_list, list) assert ret is not None # TO-DISCUSS : object_list is hard coded and might change in future assert set(ret) == set(objects_list) # Testing _get_object def test_get_object(): tendrlNS = init() ret = tendrlNS._get_object("NodeNetwork") assert (inspect.isclass(ret)) is True assert (issubclass(ret, objects.BaseObject)) is True path = os.path.join(os.path.dirname(os.path.dirname( os.path.abspath(__file__))), "objects", "definition") with open(os.path.join(path, "master.yaml"), 'r') as f: definition = yaml.safe_load(f) def_obj = definition["namespace.tendrl"]["objects"]["NodeNetwork"]["attrs"] # Creating instance of the class temp_instance = ret() # Comparing attributes of object from actual definition for k, v in def_obj.items(): assert hasattr(temp_instance, k.lower()) # Testing _get_ns(): def test_get_ns(): tendrlNS = init() assert isinstance(tendrlNS._get_ns(), maps.NamedDict) is True tendrlNS.ns_name = "integrations" tendrlNS._create_ns() assert isinstance(tendrlNS._get_ns(), maps.NamedDict) is True # Testing get_obj_definition def test_get_obj_definition(): tendrlNS = init() ret = tendrlNS.get_obj_definition("Service") assert ret is not None assert isinstance(ret, maps.NamedDict) is True assert hasattr(ret, "attrs") is True NS["compiled_definitions"] = tendrlNS.current_ns.definitions ret = tendrlNS.get_obj_definition("Service") assert ret is not None assert isinstance(ret, maps.NamedDict) is True assert hasattr(ret, "attrs") is True # Testing get_obj_flow_definition def test_get_obj_flow_definition(): tendrlNS = init() with pytest.raises(KeyError): tendrlNS.get_obj_flow_definition("Service", "test") # Testing get_flow_definiiton() def test_get_flow_definition(): tendrlNS = init() with pytest.raises(KeyError): tendrlNS.get_flow_definition("BaseFlow") NS["compiled_definitions"] = tendrlNS.current_ns.definitions tendrlNS.get_flow_definition("ImportCluster") # Testing get_atom_definition def test_get_atom_definition(): tendrlNS = init() ret = tendrlNS.get_atom_definition("Service", "CheckServiceStatus") assert ret is not None assert isinstance(ret, maps.NamedDict) is True assert hasattr(ret, "inputs") is True # Testing add_atom def test_add_atom(): tendrlNS = init() obj_name = "Service" current_ns = tendrlNS._get_ns() obj = importlib.import_module( "tendrl.commons.objects.service.atoms.check_service_status") atom_class = "" for atom_cls in inspect.getmembers(obj, inspect.isclass): tendrlNS._add_atom(obj_name, "test_atom", atom_cls[1]) atom_class = atom_cls[1] break assert hasattr(current_ns.objects["_Service"]['atoms'], "test_atom") assert current_ns.objects["_Service"]['atoms']["test_atom"] == atom_class # Testing setup_definitions def test_setup_definitions(): tendrlNS = init() tendrlNS.setup_definitions() assert tendrlNS.current_ns is not None assert isinstance(tendrlNS.current_ns, maps.NamedDict) is True # Testing add_flow def test_add_flow(): tendrlNS = init() flow_class = "" flow = importlib.import_module("tendrl.commons.flows.import_cluster") for flow_cls in inspect.getmembers(flow, inspect.isclass): tendrlNS._add_flow("test_flow", flow_cls[1]) flow_class = flow_cls[1] break current_ns = tendrlNS._get_ns() assert hasattr(current_ns.flows, "test_flow") is True assert current_ns.flows["test_flow"] is flow_class # Testing get_flow def test_get_flow(): tendrlNS = init() ret = tendrlNS.get_flow("ImportCluster") assert ret is not None # Testing add_obj_flow def test_add_obj_flow(): tendrlNS = init() flow = importlib.import_module("tendrl.commons.flows") for flow_cls in inspect.getmembers(flow, inspect.isclass): tendrlNS._add_obj_flow("Node", "AtomExecutionFailedError", flow_cls[1]) break ret = tendrlNS.get_obj_flow("Node", "AtomExecutionFailedError") assert ret is not None assert (inspect.isclass(ret)) is True # Testing get_obj_flow def test_get_obj_flow(): tendrlNS = init() flow = importlib.import_module("tendrl.commons.flows") for flow_cls in inspect.getmembers(flow, inspect.isclass): tendrlNS._add_obj_flow("Node", "AtomExecutionFailedError", flow_cls[1]) break ret = tendrlNS.get_obj_flow("Node", "AtomExecutionFailedError") assert ret is not None assert (inspect.isclass(ret)) is True # Testing get_obj_flows def test_get_obj_flows(): tendrlNS = init() flow = importlib.import_module("tendrl.commons.flows") for flow_cls in inspect.getmembers(flow, inspect.isclass): tendrlNS._add_obj_flow("Node", "AtomExecutionFailedError", flow_cls[1]) break ret = tendrlNS._get_obj_flows("Node") assert ret is not None assert isinstance(ret, maps.NamedDict) # Testing get_atom def test_get_atom(): tendrlNS = init() ret = tendrlNS.get_atom("Node", "Cmd") assert ret is not None assert (inspect.isclass(ret)) is True # Testing get_atoms def test_get_atoms(): tendrlNS = init() ret = tendrlNS._get_atoms("Node") assert ret is not None assert isinstance(ret, maps.NamedDict) # Testing _create_ns() def test_create_ns(): tendrlNS = init() assert getattr(NS, "tendrl") tendrlNS.ns_name = "integrations" tendrlNS._create_ns() assert getattr(NS, "integrations") tendrlNS._create_ns() # Testing_validate_ns_flow_definitions def test_validate_ns_flow_definitions(): tendrlNS = init() raw_ns = "namespace.tendrl" defs = tendrlNS.current_ns.definitions.get_parsed_defs()[raw_ns] defs["flows"]["test"] = maps.NamedDict() with pytest.raises(Exception): tendrlNS._validate_ns_flow_definitions(raw_ns, defs) tendrlNS.current_ns.flows["Test"] = "Test Flow" with pytest.raises(Exception): tendrlNS._validate_ns_flow_definitions(raw_ns, defs) tendrlNS.current_ns.flows = None defs = maps.NamedDict()<|fim▁hole|> # Testing _validate_ns_obj_definitions def test_validate_ns_obj_definitions(): tendrlNS = init() raw_ns = "namespace.tendrl" defs = tendrlNS.current_ns.definitions.get_parsed_defs()[raw_ns] defs_temp = defs defs_temp["objects"]["TestObject"] = maps.NamedDict() with pytest.raises(Exception): tendrlNS._validate_ns_obj_definitions(raw_ns, defs_temp) tendrlNS.current_ns.objects["_Node"]["atoms"]["Test"] = \ "Test atom class" with pytest.raises(Exception): tendrlNS._validate_ns_obj_definitions(raw_ns, defs) tendrlNS_temp = init() tendrlNS_temp.current_ns.objects["_Node"]["flows"]["Test"] = \ "Test flow class" with pytest.raises(Exception): tendrlNS_temp._validate_ns_obj_definitions(raw_ns, defs) tendrlNS.current_ns.objects["Test"] = "Test Object" with pytest.raises(Exception): tendrlNS._validate_ns_obj_definitions(raw_ns, defs) tendrlNS_temp = init() defs = tendrlNS_temp.current_ns.definitions.get_parsed_defs()[raw_ns] defs["objects"]["Node"]["atoms"]["Test"] = \ "Test atom class" with pytest.raises(Exception): tendrlNS_temp._validate_ns_obj_definitions(raw_ns, defs) defs = tendrlNS_temp.current_ns.definitions.get_parsed_defs()[raw_ns] defs["objects"]["Node"]["flows"] = maps.NamedDict() defs["objects"]["Node"]["flows"]["Test"] = "Test flow class" with pytest.raises(Exception): tendrlNS_temp._validate_ns_obj_definitions(raw_ns, defs) defs = maps.NamedDict() tendrlNS.current_ns.objects = None tendrlNS._validate_ns_obj_definitions(raw_ns, defs) # Testing _validate_ns_definitions def test_validate_ns_definitions(): tendrlNS = init() tendrlNS._validate_ns_obj_definitions = MagicMock(return_value=None) tendrlNS._validate_ns_definitions() raw_ns = "namespace.tendrl" defs = tendrlNS.current_ns.definitions.get_parsed_defs()[raw_ns] tendrlNS._validate_ns_obj_definitions.assert_called_with(raw_ns, defs) tendrlNS._validate_ns_flow_definitions = MagicMock(return_value=None) tendrlNS._validate_ns_definitions() tendrlNS._validate_ns_flow_definitions.assert_called_with(raw_ns, defs) tendrlNS.current_ns.definitions = maps.NamedDict() with pytest.raises(Exception): tendrlNS._validate_ns_definitions() # Testing setup_common_objects def test_setup_common_objects(monkeypatch): tendrlNS = init() obj = importlib.import_module("tendrl.commons.tests.fixtures.config") for obj_cls in inspect.getmembers(obj, inspect.isclass): tendrlNS.current_ns.objects["Config"] = obj_cls[1] with patch.object(etcd, "Client", return_value=etcd.Client()) as client: tendrlNS.current_ns.objects.pop("NodeContext") tendrlNS.setup_common_objects() assert NS._int.client is not None assert NS._int.wclient is not None etcd.Client.assert_called_with(host=1, port=1) tendrlNS.current_ns.objects.pop("TendrlContext") tendrlNS.setup_common_objects() def client(**param): raise Exception monkeypatch.setattr(etcd, 'Client', client) with pytest.raises(Exception): tendrlNS.setup_common_objects()<|fim▁end|>
tendrlNS._validate_ns_flow_definitions(raw_ns, defs)
<|file_name|>KIconDialog.py<|end_file_name|><|fim▁begin|># encoding: utf-8 # module PyKDE4.kio # from /usr/lib/python3/dist-packages/PyKDE4/kio.cpython-34m-x86_64-linux-gnu.so # by generator 1.135 # no doc <|fim▁hole|>import PyKDE4.kdeui as __PyKDE4_kdeui import PyQt4.QtCore as __PyQt4_QtCore import PyQt4.QtGui as __PyQt4_QtGui class KIconDialog(__PyKDE4_kdeui.KDialog): # no doc def getIcon(self, *args, **kwargs): # real signature unknown pass def iconSize(self, *args, **kwargs): # real signature unknown pass def newIconName(self, *args, **kwargs): # real signature unknown pass def openDialog(self, *args, **kwargs): # real signature unknown pass def setCustomLocation(self, *args, **kwargs): # real signature unknown pass def setIconSize(self, *args, **kwargs): # real signature unknown pass def setStrictIconSize(self, *args, **kwargs): # real signature unknown pass def setup(self, *args, **kwargs): # real signature unknown pass def showDialog(self, *args, **kwargs): # real signature unknown pass def slotOk(self, *args, **kwargs): # real signature unknown pass def strictIconSize(self, *args, **kwargs): # real signature unknown pass def __init__(self, *args, **kwargs): # real signature unknown pass<|fim▁end|>
# imports
<|file_name|>CloseQuestionHandler.java<|end_file_name|><|fim▁begin|>/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.tem.document.web.struts; import static org.apache.commons.lang.StringUtils.isBlank; import static org.kuali.kfs.module.tem.TemConstants.CLOSE_TA_QUESTION; import static org.kuali.kfs.module.tem.TemConstants.CONFIRM_CLOSE_QUESTION; import static org.kuali.kfs.module.tem.TemConstants.CONFIRM_CLOSE_QUESTION_TEXT; import static org.kuali.kfs.sys.KFSConstants.BLANK_SPACE; import static org.kuali.kfs.sys.KFSConstants.MAPPING_BASIC; import static org.kuali.kfs.sys.KFSConstants.NOTE_TEXT_PROPERTY_NAME; import org.kuali.kfs.module.tem.TemConstants.TravelDocTypes; import org.kuali.kfs.module.tem.document.TravelAuthorizationCloseDocument; import org.kuali.kfs.module.tem.document.TravelAuthorizationDocument; import org.kuali.kfs.module.tem.document.TravelDocument; import org.kuali.kfs.module.tem.document.service.TravelAuthorizationService; import org.kuali.kfs.module.tem.util.MessageUtils; import org.kuali.rice.krad.bo.Note; import org.kuali.rice.krad.exception.ValidationException; import org.kuali.rice.krad.service.DataDictionaryService; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.ObjectUtils; /** * */ public class CloseQuestionHandler implements QuestionHandler<TravelDocument> { private DataDictionaryService dataDictionaryService; private TravelAuthorizationService travelAuthorizationService; @Override public <T> T handleResponse(final Inquisitive<TravelDocument,?> asker) throws Exception { if (asker.denied(CLOSE_TA_QUESTION)) { return (T) asker.back(); } else if (asker.confirmed(CONFIRM_CLOSE_QUESTION)) { return (T) asker.end(); // This is the case when the user clicks on "OK" in the end. // After we inform the user that the close has been rerouted, we'll redirect to the portal page. } TravelAuthorizationDocument document = (TravelAuthorizationDocument)asker.getDocument(); try { // Below used as a place holder to allow code to specify actionForward to return if not a 'success question' T returnActionForward = (T) ((StrutsInquisitor) asker).getMapping().findForward(MAPPING_BASIC); TravelAuthorizationForm form = (TravelAuthorizationForm) ((StrutsInquisitor) asker).getForm(); TravelAuthorizationCloseDocument tacDocument = travelAuthorizationService.closeAuthorization(document, form.getAnnotation(), GlobalVariables.getUserSession().getPrincipalName(), null); form.setDocTypeName(TravelDocTypes.TRAVEL_AUTHORIZATION_CLOSE_DOCUMENT); form.setDocument(tacDocument); if (ObjectUtils.isNotNull(returnActionForward)) { return returnActionForward; } else { return (T) asker.confirm(CLOSE_TA_QUESTION, MessageUtils.getMessage(CONFIRM_CLOSE_QUESTION_TEXT), true, "Could not get reimbursement total for travel id ", tacDocument.getTravelDocumentIdentifier().toString(),"",""); } } catch (ValidationException ve) { throw ve; } } <|fim▁hole|> /** * @see org.kuali.kfs.module.tem.document.web.struts.QuestionHandler#askQuestion(org.kuali.kfs.module.tem.document.web.struts.Inquisitive) */ @Override public <T> T askQuestion(final Inquisitive<TravelDocument,?> asker) throws Exception { T retval = (T) asker.confirm(CLOSE_TA_QUESTION, CONFIRM_CLOSE_QUESTION_TEXT, false); return retval; } /** * * @param notePrefix * @param reason * @return */ public String getReturnToFiscalOfficerNote(final String notePrefix, String reason) { String noteText = ""; // Have to check length on value entered. final String introNoteMessage = notePrefix + BLANK_SPACE; // Build out full message. noteText = introNoteMessage + reason; final int noteTextLength = noteText.length(); // Get note text max length from DD. final int noteTextMaxLength = dataDictionaryService.getAttributeMaxLength(Note.class, NOTE_TEXT_PROPERTY_NAME).intValue(); if (isBlank(reason) || (noteTextLength > noteTextMaxLength)) { // Figure out exact number of characters that the user can enter. int reasonLimit = noteTextMaxLength - noteTextLength; if (ObjectUtils.isNull(reason)) { // Prevent a NPE by setting the reason to a blank string. reason = ""; } } return noteText; } public void setDataDictionaryService(final DataDictionaryService dataDictionaryService) { this.dataDictionaryService = dataDictionaryService; } public void setTravelAuthorizationService(TravelAuthorizationService travelAuthorizationService) { this.travelAuthorizationService = travelAuthorizationService; } }<|fim▁end|>
<|file_name|>test-adb.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import unittest import warnings from tcdb import adb class TestADBSimple(unittest.TestCase): def setUp(self): self.adb = adb.ADBSimple() self.adb.open('*') def tearDown(self): self.adb.close() self.adb = None def test_setgetitem(self): self.adb['key'] = 'some string' self.assertEqual(self.adb['key'], 'some string') self.assertRaises(KeyError, self.adb.__getitem__, 'nonexistent key') def test_put(self): self.adb.put('key', 'some string') self.assertEqual(self.adb.get('key'), 'some string') self.assertEqual(self.adb.get('nonexistent key'), None) self.assertEqual(self.adb.get('nonexistent key', 'def'), 'def') def test_putkeep(self): self.adb.putkeep('key', 'some string') self.assertEqual(self.adb.get('key'), 'some string') self.adb.putkeep('key', 'Never stored') self.assertEqual(self.adb.get('key'), 'some string') def test_putcat(self): self.adb.putcat('key', 'some') self.adb.putcat('key', ' text') self.assertEquals(self.adb.get('key'), 'some text') def test_out_and_contains(self): self.assert_('key' not in self.adb) self.adb.put('key', 'some text') self.assert_('key' in self.adb) self.adb.out('key') self.assert_('key' not in self.adb) self.adb.put('key', 'some text') self.assert_('key' in self.adb) del self.adb['key'] self.assert_('key' not in self.adb) def test_vsiz(self): self.adb.put('key', 'some text') self.assertEqual(self.adb.vsiz('key'), len('some text')) def test_iters(self): keys = ['key1', 'key2', 'key3', 'key4', 'key5'] for key in keys: self.adb.put(key, key) self.assertEqual(len(self.adb.keys()), len(keys)) self.assertEqual(len(self.adb.values()), len(keys)) self.assertEqual(len(zip(keys, keys)), len(self.adb.items())) for key in self.adb: self.assert_(key in keys) for value in self.adb.itervalues(): self.assert_(value in keys) def test_fwmkeys(self): objs = ['aa', 'ab', 'ac', 'xx', 'ad'] for obj in objs: self.adb.put(obj, 'same value') self.assertEqual(len(self.adb.fwmkeys('a')), len(['aa', 'ab', 'ac', 'ad'])) self.assertEqual(self.adb.fwmkeys('x'), ['xx']) self.assertEqual(self.adb.fwmkeys('nonexistent key'), []) def test_admin_functions(self): keys = ['key1', 'key2', 'key3', 'key4', 'key5'] for key in keys: self.adb.put(key, key) self.assertEquals(self.adb.path(), '*') self.adb.sync() self.assertEquals(len(self.adb), 5) self.assertEquals(self.adb.size(), 525656) self.adb.vanish() self.assertEquals(self.adb.size(), 525376) # def test_transaction(self): # keys = ['key1', 'key2', 'key3', 'key4', 'key5'] # with self.adb as db: # for key in keys: # db.put(key, key) # self.assertEquals(len(self.adb), 5) # self.adb.vanish() # try: # with self.adb: # for key in keys: # self.adb.put(key, key) # self.adb['bad key'] # except KeyError: # pass # self.assertEquals(len(self.adb), 0) def test_foreach(self): keys = ['key1', 'key2', 'key3', 'key4', 'key5'] def proc(key, value, op): self.assertEquals(key, value) self.assert_(key in keys) self.assertEquals(op, 'test') return True for key in keys: self.adb.put(key, key) self.adb.foreach(proc, 'test') class TestADB(unittest.TestCase): def setUp(self): self.adb = adb.ADB() self.adb.open('*') def tearDown(self): self.adb.close() self.adb = None def test_setgetitem(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj1 in objs: self.adb['obj'] = obj1 obj2 = self.adb['obj'] self.assertEqual(obj1, obj2) self.adb[obj1] = obj1 obj2 = self.adb[obj1] self.assertEqual(obj1, obj2) self.assertRaises(KeyError, self.adb.__getitem__, 'nonexistent key') def test_put(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj1 in objs: self.adb.put(obj1, obj1) obj2 = self.adb.get(obj1) self.assertEqual(obj1, obj2) self.adb.put(obj1, obj1, raw_key=True) obj2 = self.adb.get(obj1, raw_key=True) self.assertEqual(obj1, obj2) self.assertEqual(self.adb.get('nonexistent key'), None) self.assertEqual(self.adb.get('nonexistent key', 'def'), 'def') def test_put_str(self): str1 = 'some text [áéíóú]' objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.put_str(obj, str1) str2 = self.adb.get_str(obj) self.assertEqual(str1, str2) self.adb.put_str(obj, str1, as_raw=True) str2 = self.adb.get_str(obj, as_raw=True) self.assertEqual(str1, str2) unicode1 = u'unicode text [áéíóú]' for obj in objs: self.adb.put_str(obj, unicode1.encode('utf8')) unicode2 = unicode(self.adb.get_str(obj), 'utf8') self.assertEqual(unicode1, unicode2) self.assertRaises(AssertionError, self.adb.put_str, 'key', 10) self.assertEqual(self.adb.get_str('nonexistent key'), None) self.assertEqual(self.adb.get_str('nonexistent key', 'def'), 'def') def test_put_unicode(self): unicode1 = u'unicode text [áéíóú]' objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.put_unicode(obj, unicode1) unicode2 = self.adb.get_unicode(obj) self.assertEqual(unicode1, unicode2) self.adb.put_unicode(obj, unicode1, as_raw=True) unicode2 = self.adb.get_unicode(obj, as_raw=True) self.assertEqual(unicode1, unicode2) self.assertRaises(AssertionError, self.adb.put_unicode, 'key', 10) self.assertEqual(self.adb.get_unicode('nonexistent key'), None) self.assertEqual(self.adb.get_unicode('nonexistent key', 'def'), 'def') def test_put_int(self): int1 = 10 objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.put_int(obj, int1) int2 = self.adb.get_int(obj) self.assertEqual(int1, int2) self.adb.put_int(obj, int1, as_raw=True) int2 = self.adb.get_int(obj, as_raw=True) self.assertEqual(int1, int2) self.assertRaises(AssertionError, self.adb.put_int, 'key', '10') self.assertEqual(self.adb.get_int('nonexistent key'), None) self.assertEqual(self.adb.get_int('nonexistent key', 'def'), 'def') def test_put_float(self): float1 = 10.10 objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.put_float(obj, float1) float2 = self.adb.get_float(obj) self.assertEqual(float1, float2) self.adb.put_float(obj, float1, as_raw=True) float2 = self.adb.get_float(obj, as_raw=True) self.assertEqual(float1, float2) self.assertRaises(AssertionError, self.adb.put_float, 'key', 10) self.assertEqual(self.adb.get_float('nonexistent key'), None) self.assertEqual(self.adb.get_float('nonexistent key', 'def'), 'def') def test_putkeep(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj1 in objs: self.adb.putkeep(obj1, obj1) obj2 = self.adb.get(obj1) self.assertEqual(obj1, obj2) self.adb.putkeep(obj1, 'Never stored') obj2 = self.adb.get(obj1) self.assertEqual(obj1, obj2) def test_putkeep_str(self): str1 = 'some text [áéíóú]' objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.putkeep_str(obj, str1) str2 = self.adb.get_str(obj) self.assertEqual(str1, str2) self.adb.putkeep_str(obj, 'Never stored') str2 = self.adb.get_str(obj) self.assertEqual(str1, str2) self.assertRaises(AssertionError, self.adb.putkeep_str, 'key', 10) def test_putkeep_unicode(self): unicode1 = u'unicode text [áéíóú]' objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.putkeep_unicode(obj, unicode1) unicode2 = self.adb.get_unicode(obj) self.assertEqual(unicode1, unicode2) self.adb.putkeep_unicode(obj, u'Never stored') unicode2 = self.adb.get_unicode(obj) self.assertEqual(unicode1, unicode2) self.assertRaises(AssertionError, self.adb.putkeep_unicode, 'key', 10) def test_putkeep_int(self): int1 = 10 objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.putkeep_int(obj, int1) int2 = self.adb.get_int(obj) self.assertEqual(int1, int2) self.adb.putkeep_int(obj, int1*10) int2 = self.adb.get_int(obj) self.assertEqual(int1, int2) self.assertRaises(AssertionError, self.adb.putkeep_int, 'key', '10') def test_putkeep_float(self): float1 = 10.10 objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.putkeep_float(obj, float1) float2 = self.adb.get_float(obj) self.assertEqual(float1, float2) self.adb.putkeep_float(obj, float1*10) float2 = self.adb.get_float(obj) self.assertEqual(float1, float2) self.assertRaises(AssertionError, self.adb.put_float, 'key', 10) def test_putcat_str(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.putcat_str(obj, 'some') for obj in objs: self.adb.putcat_str(obj, ' text') for obj in objs: self.assertEquals(self.adb.get_str(obj), 'some text') def test_putcat_unicode(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.putcat_unicode(obj, u'some') for obj in objs: self.adb.putcat_unicode(obj, u' text') for obj in objs: self.assertEquals(self.adb.get_unicode(obj), u'some text') def test_out_and_contains(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.put(obj, obj) self.assert_(obj in self.adb) self.adb.out(obj) self.assert_(obj not in self.adb) for obj in objs: self.adb.put(obj, obj) self.assert_(obj in self.adb) del self.adb[obj] self.assert_(obj not in self.adb) def test_vsiz(self): obj = 1+1j self.adb.put(obj, obj) vsiz = self.adb.vsiz(obj) self.assertEqual(vsiz, 48) obj = 'some text [áéíóú]' self.adb.put_str(obj, obj) vsiz = self.adb.vsiz(obj) self.assertEqual(vsiz, 22) obj = u'unicode text [áéíóú]' self.adb.put_str(obj, obj.encode('utf8')) vsiz = self.adb.vsiz(obj) self.assertEqual(vsiz, 25) obj = 10 self.adb.put_int(obj, obj) vsiz = self.adb.vsiz(obj) self.assertEqual(vsiz, 4) <|fim▁hole|> vsiz = self.adb.vsiz(obj) self.assertEqual(vsiz, 8) def test_iters(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.put(obj, obj) self.assertEqual(len(self.adb.keys()), len(objs)) self.assertEqual(len(self.adb.values()), len(objs)) for key in self.adb: with warnings.catch_warnings(): warnings.simplefilter("ignore") self.assert_(key in objs) for value in self.adb.itervalues(): with warnings.catch_warnings(): warnings.simplefilter("ignore") self.assert_(value in objs) def test_fwmkeys(self): objs = ['aa', 'ab', 'ac', 'xx', 'ad'] for obj in objs: self.adb.put(obj, 'same value', raw_key=True) self.assertEqual(len(self.adb.fwmkeys('a')), len(['aa', 'ab', 'ac', 'ad'])) self.assertEqual(self.adb.fwmkeys('x'), ['xx']) self.assertEqual(self.adb.fwmkeys('nonexistent key'), []) def test_add_int(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.put_int(obj, 10) for key in self.adb: self.adb.add_int(key, 2) for key in self.adb: self.assertEqual(self.adb.get_int(key), 12) def test_add_float(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.put_float(obj, 10.0) for key in self.adb: self.adb.add_float(key, 2.0) for key in self.adb: self.assertEqual(self.adb.get_float(key), 12.0) def test_admin_functions(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] for obj in objs: self.adb.put(obj, obj) self.assertEquals(self.adb.path(), '*') self.adb.sync() self.assertEquals(len(self.adb), 5) self.assertEquals(self.adb.size(), 525874) self.adb.vanish() self.assertEquals(self.adb.size(), 525376) # def test_transaction(self): # objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] # with self.adb as db: # for obj in objs: # db.put(obj, obj) # self.assertEquals(len(self.adb), 5) # self.adb.vanish() # try: # with self.adb: # for obj in objs: # self.adb.put(obj, obj) # self.adb.get('Not exist key') # except KeyError: # pass # self.assertEquals(len(self.adb), 0) def test_foreach(self): objs = [1+1j, 'some text [áéíóú]', u'unicode text [áéíóú]', 10, 10.0] def proc(key, value, op): self.assertEquals(key, value) with warnings.catch_warnings(): warnings.simplefilter("ignore") self.assert_(key in objs) self.assertEquals(op, 'test') return True for obj in objs: self.adb.put(obj, obj) self.adb.foreach(proc, 'test') if __name__ == '__main__': unittest.main()<|fim▁end|>
obj = 10.10 self.adb.put_float(obj, obj)
<|file_name|>datacollect.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import import time import threading from . import log <|fim▁hole|> """ pass class DataFailure(Exception): """DataError: a problem occurred while trying to collect the data, (ie, while calling module.collectData()) which prevents this collector from continuing. """ pass class DataModuleError(Exception): pass # Data collection management classes class DataModules(object): """This class keeps track of which data collection modules are required (directives request data collection modules as they are created); makes sure appropriate modules are available; and creates data collection objects as required. """ def __init__(self, osname, osver, osarch): bad_chars = ('.', '-') for c in bad_chars: osname = osname.replace(c, '_') osver = osver.replace(c, '_') osarch = osarch.replace(c, '_') osver = 'v' + osver # can't start with digit self.osname = osname self.osver = osver self.osarch = osarch # most specific to least specific self.os_search_path = [] if osname and osver and osarch: self.os_search_path.append('.'.join([osname, osver, osarch])) self.os_search_path.append('.'.join([osname, osarch, osver])) if osname and osver: self.os_search_path.append('.'.join([osname, osver])) if osname and osarch: self.os_search_path.append('.'.join([osname, osarch])) if osname: self.os_search_path.append(osname) self.collectors = {} # dictionary of collectors and their associated objects def import_module(self, module): """Return a reference to the imported module, or none if the import failed. """ modobj = None # first look for platform specific data collect module for ospath in self.os_search_path: try: modparent = __import__( '.'.join(['boristool', 'arch', ospath]), globals(), locals(), [module], ) modobj = getattr(modparent, module) break except AttributeError: pass except ImportError: pass if modobj is None: # No platform specific module, look for generic module try: modparent = __import__( '.'.join(['boristool', 'arch', 'generic']), globals(), locals(), [module], ) modobj = getattr(modparent, module) except AttributeError: pass except ImportError: pass return modobj def request(self, module, collector): """Directives request data collection objects and the modules they should be defined in. Return reference to collector object if successful; Return None if failed. """ # if collector already initiated, return reference if collector in list(self.collectors.keys()): return self.collectors[collector] log.log("<datacollect>DataModules.request(): importing module '%s' for collector '%s'" % (module, collector), 8) modobj = self.import_module(module) if modobj is None: log.log("<datacollect>DataModules.request(): error, collector '%s'/module '%s' not found or not available, os_search_path=%s" % (collector, module, self. os_search_path), 3) raise DataModuleError("Collector '%s', module '%s' not found or not available, os_search_path=%s" % (collector, module, self.os_search_path)) # initialise new collector instance if hasattr(modobj, collector): self.collectors[collector] = getattr(modobj, collector)() else: log.log("<datacollect>DataModules.request(): error, no such collector '%s' in module '%s'" % (collector, module), 3) raise DataModuleError("No such collector '%s' in module '%s'" % (collector, module)) log.log("<datacollect>DataModules.request(): collector %s/%s initialised" % (module, collector), 7) return self.collectors[collector] class Data(object): """An empty class to hold any data to be stored. Do not access this data without first acquiring DataCollect.data_semaphore for thread-safety. """ pass class DataHistory(object): """Store previous data, with up to max_level levels of history. Set max_level with setHistory() or else no data is kept. """ def __init__(self): self.max_level = 0 # how many levels of data to keep self.historical_data = [] # list of historical data (newest to oldest) def setHistory(self, level): """Set how many levels of historical data to keep track of. By default no historical data will be kept. The history level is only changed if the level is greater than the current setting. The history level is always set to the highest required by all directives. """ if level > self.max_level: self.max_level = level def __getitem__(self, num): """Overloaded [] to return the historical data, num is the age of the data. num can be 0 which is the current data; 1 is the previous data, etc. e.g., d = history[5] would assign d the Data object from 5 'collection periods' ago. """ try: data = self.historical_data[num] except IndexError: raise IndexError("DataHistory index out-of-range: index=%d" % (num)) return data def update(self, data): """Update data history by adding new data object to history list and removing oldest data from list. If max_level is 0, no history is required, so nothing is done. """ if self.max_level > 0: if len(self.historical_data) > self.max_level: # remove oldest data self.historical_data = self.historical_data[:-1] self.historical_data.insert(0, data) def length(self): """Returns the current length of the historical data list; i.e., how many samples have been collected and are stored in the list. """ # Subtract 1 from len as the first sample in list is always the current sample return len(self.historical_data) - 1 class DataCollect(object): """Provides a data collection and store class with automatic caching and refreshing of data in the cache. Public functions are fully thread-safe as they can be called from many directive threads simultaneously. Data is cached for 55 seconds by default. Assign self.refresh_rate to change this. A collectData() function must be supplied by any child class of DataCollect. This function should get data by whatever means and assign it to variables in self.data. Historical data will be automatically kept by calling setHistory(n) with n>0. n levels of historical data will then be automatically kept. If setHistory() is called multiple times, the highest n will stay in effect. Public functions are: getHash() - return a copy of a data dictionary getList() - return a copy of a data list hashKeys() - return list of data dictionary keys __getitem__() - use DataCollect object like a dictionary to fetch data refresh() - force a cache refresh setHistory(n) - set max level (n) of data history to automatically keep """ def __init__(self): self.refresh_rate = 55 # amount of time current information will be # cached before being refreshed (in seconds) self.refresh_time = 0 # information must be refreshed at first request self.history_level = 0 # how many levels of historical data to keep self.history = DataHistory() # historical data self.data_semaphore = threading.Semaphore() # lock before accessing self.data/refresh_time # Public, thread-safe, methods def getHash(self, hash='datahash'): """Return a copy of the specified data hash, datahash by default. Specify an alternate variable name to fetch it instead. TODO: it might be better to use the 'copy' module to make sure a full deep copy is made of the date... """ self._checkCache() # refresh data if necessary dh = {} self.data_semaphore.acquire() # thread-safe access to self.data exec('dh.update(self.data.%s)' % (hash)) # copy data hash self.data_semaphore.release() return(dh) def hashKeys(self): """Return the list of datahash keys. """ self._checkCache() # refresh data if necessary self.data_semaphore.acquire() # thread-safe access to self.data k = list(self.data.datahash.keys()) self.data_semaphore.release() return(k) def getList(self, listname): """Return a copy of the specified data list. The function is thread-safe and supports the built-in data caching. TODO: it might be better to use the 'copy' module to make sure a full deep copy is made of the date... """ self._checkCache() # refresh data if necessary self.data_semaphore.acquire() # thread-safe access to self.data exec('list_copy = self.data.%s[:]' % (listname)) # copy data list self.data_semaphore.release() return(list_copy) def __getitem__(self, key): """Overload '[]', eg: returns corresponding data object for given key. TODO: it might be better to use the 'copy' module to make sure a full deep copy is made of the date... """ self._checkCache() # refresh data if necessary self.data_semaphore.acquire() # thread-safe access to self.data try: r = self.data.datahash[key] except KeyError: self.data_semaphore.release() raise KeyError("Key %s not found in data hash" % (key)) self.data_semaphore.release() return r def refresh(self): """Refresh data. This function can be called publically to force a refresh. """ self.data_semaphore.acquire() # thread-safe access to self.data log.log("<datacollect>DataCollect.refresh(): forcing data refresh", 7) self._refresh() self.data_semaphore.release() def setHistory(self, level): """Set how many levels of historical data to keep track of. By default no historical data will be kept. The history level is only changed if the level is greater than the current setting. The history level is always set to the highest required by all directives. """ self.history.setHistory(level) # Private methods. Thread safety not guaranteed if not using public methods. def _checkCache(self): """Check if cached data is invalid, ie: refresh_time has been exceeded. """ self.data_semaphore.acquire() # thread-safe access to self.refresh_time and self._refresh() if time.time() > self.refresh_time: log.log("<datacollect>DataCollect._checkCache(): refreshing data", 7) self._refresh() else: log.log("<datacollect>DataCollect._checkCache(): using cached data", 7) self.data_semaphore.release() def _refresh(self): """Refresh data by calling _fetchData() and increasing refresh_time. This function must be called between data_semaphore locks. It is not thread-safe on its own. """ self._fetchData() # new refresh time is current time + refresh rate (seconds) self.refresh_time = time.time() + self.refresh_rate def _fetchData(self): """Initialise a new data collection by first resetting the current data, then calling self.collectData() - a user-supplied function, see below - then storing historical data if necessary. Derivatives of this base class must define a collectData() method which should collect any data by whatever means and store that data in the self.data object. It can be assumed all appropriate thread-locks are in place so access to self.data will be safe. """ self.data = Data() # new, empty data-store try: self.collectData() # user-supplied function to collect some data # and store in self.data except DataFailure as err: log.log("<datacollect>DataCollect._fetchData(): DataFailure, %s" % (err), 5) # TODO: need to tell the Directive that things have gone wrong? else: self.history.update(self.data) # add collected data to history<|fim▁end|>
# Exceptions class IndexError(Exception): """IndexError: a Data History index is out of range
<|file_name|>mainThreadNotebookDocuments.ts<|end_file_name|><|fim▁begin|>/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { DisposableStore, dispose } from 'vs/base/common/lifecycle'; import { ResourceMap } from 'vs/base/common/map'; import { URI, UriComponents } from 'vs/base/common/uri'; import { BoundModelReferenceCollection } from 'vs/workbench/api/browser/mainThreadDocuments'; import { NotebookCellTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookCellTextModel'; import { NotebookTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookTextModel'; import { NotebookCellsChangeType } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { INotebookEditorModelResolverService } from 'vs/workbench/contrib/notebook/common/notebookEditorModelResolverService'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';<|fim▁hole|>import { ExtHostContext, ExtHostNotebookDocumentsShape, IExtHostContext, MainThreadNotebookDocumentsShape, NotebookCellDto, NotebookCellsChangedEventDto, NotebookDataDto } from '../common/extHost.protocol'; import { MainThreadNotebooksAndEditors } from 'vs/workbench/api/browser/mainThreadNotebookDocumentsAndEditors'; import { NotebookDto } from 'vs/workbench/api/browser/mainThreadNotebookDto'; import { SerializableObjectWithBuffers } from 'vs/workbench/services/extensions/common/proxyIdentifier'; export class MainThreadNotebookDocuments implements MainThreadNotebookDocumentsShape { private readonly _disposables = new DisposableStore(); private readonly _proxy: ExtHostNotebookDocumentsShape; private readonly _documentEventListenersMapping = new ResourceMap<DisposableStore>(); private readonly _modelReferenceCollection: BoundModelReferenceCollection; constructor( extHostContext: IExtHostContext, notebooksAndEditors: MainThreadNotebooksAndEditors, @INotebookEditorModelResolverService private readonly _notebookEditorModelResolverService: INotebookEditorModelResolverService, @IUriIdentityService private readonly _uriIdentityService: IUriIdentityService ) { this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostNotebookDocuments); this._modelReferenceCollection = new BoundModelReferenceCollection(this._uriIdentityService.extUri); notebooksAndEditors.onDidAddNotebooks(this._handleNotebooksAdded, this, this._disposables); notebooksAndEditors.onDidRemoveNotebooks(this._handleNotebooksRemoved, this, this._disposables); // forward dirty and save events this._disposables.add(this._notebookEditorModelResolverService.onDidChangeDirty(model => this._proxy.$acceptDirtyStateChanged(model.resource, model.isDirty()))); this._disposables.add(this._notebookEditorModelResolverService.onDidSaveNotebook(e => this._proxy.$acceptModelSaved(e))); } dispose(): void { this._disposables.dispose(); this._modelReferenceCollection.dispose(); dispose(this._documentEventListenersMapping.values()); } private _handleNotebooksAdded(notebooks: readonly NotebookTextModel[]): void { for (const textModel of notebooks) { const disposableStore = new DisposableStore(); disposableStore.add(textModel.onDidChangeContent(event => { const eventDto: NotebookCellsChangedEventDto = { versionId: event.versionId, rawEvents: [] }; for (const e of event.rawEvents) { switch (e.kind) { case NotebookCellsChangeType.ModelChange: eventDto.rawEvents.push({ kind: e.kind, changes: e.changes.map(diff => [diff[0], diff[1], diff[2].map(cell => NotebookDto.toNotebookCellDto(cell as NotebookCellTextModel))] as [number, number, NotebookCellDto[]]) }); break; case NotebookCellsChangeType.Move: eventDto.rawEvents.push({ kind: e.kind, index: e.index, length: e.length, newIdx: e.newIdx, }); break; case NotebookCellsChangeType.Output: eventDto.rawEvents.push({ kind: e.kind, index: e.index, outputs: e.outputs.map(NotebookDto.toNotebookOutputDto) }); break; case NotebookCellsChangeType.OutputItem: eventDto.rawEvents.push({ kind: e.kind, index: e.index, outputId: e.outputId, outputItems: e.outputItems.map(NotebookDto.toNotebookOutputItemDto), append: e.append }); break; case NotebookCellsChangeType.ChangeLanguage: case NotebookCellsChangeType.ChangeCellMetadata: case NotebookCellsChangeType.ChangeCellInternalMetadata: eventDto.rawEvents.push(e); break; } } // using the model resolver service to know if the model is dirty or not. // assuming this is the first listener it can mean that at first the model // is marked as dirty and that another event is fired this._proxy.$acceptModelChanged( textModel.uri, new SerializableObjectWithBuffers(eventDto), this._notebookEditorModelResolverService.isDirty(textModel.uri) ); const hasDocumentMetadataChangeEvent = event.rawEvents.find(e => e.kind === NotebookCellsChangeType.ChangeDocumentMetadata); if (hasDocumentMetadataChangeEvent) { this._proxy.$acceptDocumentPropertiesChanged(textModel.uri, { metadata: textModel.metadata }); } })); this._documentEventListenersMapping.set(textModel.uri, disposableStore); } } private _handleNotebooksRemoved(uris: URI[]): void { for (const uri of uris) { this._documentEventListenersMapping.get(uri)?.dispose(); this._documentEventListenersMapping.delete(uri); } } async $tryCreateNotebook(options: { viewType: string, content?: NotebookDataDto }): Promise<UriComponents> { const ref = await this._notebookEditorModelResolverService.resolve({ untitledResource: undefined }, options.viewType); // untitled notebooks are disposed when they get saved. we should not hold a reference // to such a disposed notebook and therefore dispose the reference as well ref.object.notebook.onWillDispose(() => { ref.dispose(); }); // untitled notebooks are dirty by default this._proxy.$acceptDirtyStateChanged(ref.object.resource, true); // apply content changes... slightly HACKY -> this triggers a change event if (options.content) { const data = NotebookDto.fromNotebookDataDto(options.content); ref.object.notebook.reset(data.cells, data.metadata, ref.object.notebook.transientOptions); } return ref.object.resource; } async $tryOpenNotebook(uriComponents: UriComponents): Promise<URI> { const uri = URI.revive(uriComponents); const ref = await this._notebookEditorModelResolverService.resolve(uri, undefined); this._modelReferenceCollection.add(uri, ref); return uri; } async $trySaveNotebook(uriComponents: UriComponents) { const uri = URI.revive(uriComponents); const ref = await this._notebookEditorModelResolverService.resolve(uri); const saveResult = await ref.object.save(); ref.dispose(); return saveResult; } }<|fim▁end|>
<|file_name|>2111005.js<|end_file_name|><|fim▁begin|>/*@author Jvlaple *Crystal of Roots */ var status = 0; <|fim▁hole|> importPackage(net.sf.odinms.client); function start() { status = -1; action(1, 0, 0); } function action(mode, type, selection) { if (mode == -1) { cm.dispose(); } else { if (status >= 0 && mode == 0) { cm.sendOk("Ok, keep preservering!"); cm.dispose(); return; } if (mode == 1) status++; else status--; if (status == 0 ) { cm.sendYesNo("Hello I'm the Dungeon Exit NPC. Do you wish to go out from here?"); } else if (status == 1) { var eim = cm.getPlayer().getEventInstance(); cm.warp(100000000, 0); if (eim != null) { eim.unregisterPlayer(cm.getPlayer()); }cm.dispose(); } } }<|fim▁end|>
var PQItems = Array(4001087, 4001088, 4001089, 4001090, 4001091, 4001092, 4001093);
<|file_name|>settings_test.py<|end_file_name|><|fim▁begin|>from django.test.testcases import SimpleTestCase from publicweb.extra_models import (NotificationSettings, OrganizationSettings, NO_NOTIFICATIONS, FEEDBACK_MAJOR_CHANGES) from django.contrib.auth.models import User, AnonymousUser from organizations.models import Organization from django.db.models.fields.related import OneToOneField from publicweb.tests.factories import UserFactory, OrganizationFactory from mock import patch, MagicMock from django.test.client import RequestFactory from publicweb.views import UserNotificationSettings from publicweb.forms import NotificationSettingsForm from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect def create_fake_organization(**kwargs): return OrganizationFactory.build(**kwargs) class SettingsTest(SimpleTestCase): def test_notification_settings_have_user_field(self): self.assertTrue(hasattr(NotificationSettings, 'user')) def test_notification_settings_are_linked_to_user(self): self.assertEqual(NotificationSettings.user.field.rel.to, User) def test_notification_settings_have_organization_field(self): self.assertTrue(hasattr(NotificationSettings, 'organization')) def test_notification_settings_are_linked_to_organization(self): self.assertEqual( NotificationSettings.organization.field.rel.to, Organization) def test_organization_settings_have_organization_field(self): self.assertTrue(hasattr(OrganizationSettings, 'organization')) def test_organization_settings_are_linked_to_organization(self): self.assertEqual( OrganizationSettings.organization.field.rel.to, Organization) def test_each_organization_has_only_one_set_of_settings(self): self.assertIsInstance( OrganizationSettings.organization.field, OneToOneField) def test_notification_settings_are_unique_for_an_organization_and_user(self): self.assertEqual((('user', 'organization'),), NotificationSettings()._meta.unique_together) def test_notifitication_settings_default_value_is_main_items_only(self): the_settings = NotificationSettings() self.assertEqual(FEEDBACK_MAJOR_CHANGES, the_settings.notification_level) @patch('publicweb.views.Organization.objects', new=MagicMock( spec=Organization.objects, get=create_fake_organization, filter=create_fake_organization ) ) def test_notification_settings_view_uses_a_form(self): user = UserFactory.build(id=1) organization = create_fake_organization(id=2, slug='test') request = RequestFactory().get('/') request.user = user context = UserNotificationSettings.as_view()( request, org_slug=organization.slug ).context_data self.assertIn('form', context) def test_notifcation_settings_view_redirects_to_organization_list(self): notification_settings_view = UserNotificationSettings() self.assertEqual(reverse('organization_list'), notification_settings_view.get_success_url()) def test_user_notification_settings_view_context_contains_organisation(self): notification_settings_view = UserNotificationSettings() notification_settings_view.object = MagicMock(spec=NotificationSettings) notification_settings_view.organization = create_fake_organization(id=2) context = notification_settings_view.get_context_data() self.assertIn('organization', context) self.assertTrue(context['organization']) @patch('publicweb.views.Organization.objects', new=MagicMock( spec=Organization.objects, get=create_fake_organization, filter=create_fake_organization ) ) def test_notification_settings_view_uses_notification_settings_form(self): user = UserFactory.build(id=1) organization = create_fake_organization(id=2, slug='test') request = RequestFactory().get('/') request.user = user context = UserNotificationSettings.as_view()( request, org_slug=organization.slug ).context_data self.assertIsInstance(context['form'], NotificationSettingsForm) def test_notification_settings_view_requires_login(self): request = RequestFactory().get('/') user = AnonymousUser() organization = create_fake_organization(id=2) request.user = user response = UserNotificationSettings.as_view()(request, organization=organization.id) self.assertIsInstance(response, HttpResponseRedirect) @patch('publicweb.views.Organization.objects', new=MagicMock( spec=Organization.objects, get=create_fake_organization, filter=create_fake_organization ) ) @patch('publicweb.views.UserNotificationSettings.model', return_value=MagicMock( spec=NotificationSettings, _meta=MagicMock(fields=[], many_to_many=[]), root_id=None )<|fim▁hole|> ) def test_posting_valid_data_saves_settings(self, settings_obj): organization = create_fake_organization(id=2, slug='test') request = RequestFactory().post( reverse('notification_settings', args=[organization.slug]), {'notification_level': unicode(NO_NOTIFICATIONS)} ) user = UserFactory.build(id=1) request.user = user # This patch depends on the UsertNotificationSettings.model patch # It needs to return the object created by that patch, which is passed # in as a parameter. # The only way I've found to handle the dependency is to do this patch # here with patch('publicweb.views.UserNotificationSettings.model.objects', get=lambda organization, user: settings_obj): UserNotificationSettings.as_view()( request, org_slug=organization.slug ) self.assertTrue(settings_obj.save.called) @patch('publicweb.views.Organization.objects', new=MagicMock( spec=Organization.objects, get=create_fake_organization, filter=create_fake_organization ) ) @patch('publicweb.views.UserNotificationSettings.model', return_value=MagicMock( spec=NotificationSettings, _meta=MagicMock(fields=[], many_to_many=[]), root_id=None ) ) def test_posting_invalid_data_returns_form_with_errors(self, settings_obj): user = UserFactory.build(id=1) organization = create_fake_organization(id=2, slug='test') request = RequestFactory().post( reverse('notification_settings', args=[organization.id])) request.user = user # This patch depends on the UsertNotificationSettings.model patch # It needs to return the object created by that patch, which is passed # in as a parameter. # The only way I've found to handle the dependency is to do this patch # here with patch('publicweb.views.UserNotificationSettings.model.objects', get=lambda organization, user: settings_obj): response = UserNotificationSettings.as_view()( request, org_slug=organization.slug ) self.assertIn('form', response.context_data) self.assertTrue(response.context_data['form'].errors) @patch('publicweb.views.Organization.objects', new=MagicMock( spec=Organization.objects, get=create_fake_organization, filter=create_fake_organization ) ) @patch('publicweb.views.UserNotificationSettings.model', return_value=MagicMock( spec=NotificationSettings, _meta=MagicMock(fields=[], many_to_many=[]), root_id=None ) ) def test_cancel_doesnt_save_settings(self, settings_obj): user = UserFactory.build(id=1) organization = create_fake_organization(id=2, slug='test') request = RequestFactory().post( reverse('notification_settings', args=[organization.id]), { 'notification_level': unicode(NO_NOTIFICATIONS), 'submit': "Cancel" } ) request.user = user # This patch depends on the UsertNotificationSettings.model patch # It needs to return the object created by that patch, which is passed # in as a parameter. # The only way I've found to handle the dependency is to do this patch # here with patch('publicweb.views.UserNotificationSettings.model.objects', get=lambda organization, user: settings_obj): UserNotificationSettings.as_view()( request, org_slug=organization.slug ) self.assertFalse(settings_obj.save.called)<|fim▁end|>
<|file_name|>kempston_di.cpp<|end_file_name|><|fim▁begin|>// license:BSD-3-Clause // copyright-holders:Curt Coder /********************************************************************** Kempston Disk Interface emulation **********************************************************************/ #include "kempston_di.h" //************************************************************************** // DEVICE DEFINITIONS //************************************************************************** const device_type KEMPSTON_DISK_INTERFACE = &device_creator<kempston_disk_interface_t>; //------------------------------------------------- // ROM( kempston_disk_system ) //------------------------------------------------- ROM_START( kempston_disk_system ) ROM_REGION( 0x2000, "rom", 0 ) ROM_DEFAULT_BIOS("v114") ROM_SYSTEM_BIOS( 0, "v114", "v1.14" ) ROMX_LOAD( "kempston_disk_system_v1.14_1984.rom", 0x0000, 0x2000, CRC(0b70ad2e) SHA1(ff8158d25864d920f3f6df259167e91c2784692c), ROM_BIOS(1) ) ROM_END //------------------------------------------------- // rom_region - device-specific ROM region //------------------------------------------------- const tiny_rom_entry *kempston_disk_interface_t::device_rom_region() const { return ROM_NAME( kempston_disk_system ); } //************************************************************************** // LIVE DEVICE //************************************************************************** //------------------------------------------------- // kempston_disk_interface_t - constructor //------------------------------------------------- kempston_disk_interface_t::kempston_disk_interface_t(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) : device_t(mconfig, KEMPSTON_DISK_INTERFACE, "Kempston Disk Interface", tag, owner, clock, "ql_kdi", __FILE__), device_ql_expansion_card_interface(mconfig, *this) { } //------------------------------------------------- // device_start - device-specific startup //------------------------------------------------- void kempston_disk_interface_t::device_start() {<|fim▁hole|> //------------------------------------------------- // read - //------------------------------------------------- UINT8 kempston_disk_interface_t::read(address_space &space, offs_t offset, UINT8 data) { return data; } //------------------------------------------------- // write - //------------------------------------------------- void kempston_disk_interface_t::write(address_space &space, offs_t offset, UINT8 data) { }<|fim▁end|>
}
<|file_name|>shapeCircle.py<|end_file_name|><|fim▁begin|>''' Created on 13.06.2016 @author: mkennert ''' from kivy.properties import NumericProperty, ObjectProperty from kivy.uix.gridlayout import GridLayout from crossSectionView.circleView import CSCircleView from shapes.ashape import AShape import numpy as np class ShapeCircle(GridLayout, AShape): ''' represents the cross section which has the shape of a circle ''' # cross-section-view view = ObjectProperty(CSCircleView()) # information-view of the cross-section information = ObjectProperty() # diameter of the circle d = NumericProperty(0.25) ''' constructor ''' def __init__(self, **kwargs): super(ShapeCircle, self).__init__(**kwargs) self.view = CSCircleView() self.view.csShape, self.view.d = self, self.d self.view.create_graph() ''' y distance of gravity centre from upper rim ''' def _get_gravity_centre(self): return self.d / 2. ''' returns width of cross section for different vertical coordinates ''' <|fim▁hole|> x2 = np.sqrt(np.abs((self.d / 2.)**2 - (y - self.d / 2.)** 2)) + self.d / 2. return x2 - x1<|fim▁end|>
def get_width(self, y): x1 = -np.sqrt(np.abs((self.d / 2.)**2 - (y - self.d / 2.)** 2)) + self.d / 2.
<|file_name|>15.2.3.3-4-250.js<|end_file_name|><|fim▁begin|>// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set<|fim▁hole|>// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.3-4-250 description: > Object.getOwnPropertyDescriptor - returned object contains the property 'get' if the value of property 'get' is not explicitly specified when defined by Object.defineProperty. includes: [runTestCase.js] ---*/ function testcase() { var obj = {}; Object.defineProperty(obj, "property", { set: function () {}, configurable: true }); var desc = Object.getOwnPropertyDescriptor(obj, "property"); return "get" in desc; } runTestCase(testcase);<|fim▁end|>
<|file_name|>Iterator.py<|end_file_name|><|fim▁begin|># This file is part of pybliographer # # Copyright (C) 1998-2004 Frederic GOBRY # Email : [email protected] # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # 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, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # # TODO: get rid of all of this, and use standard iterators / generators <|fim▁hole|> base = None title = "Some Selection" def iterator (self): ''' loop method, so that we can for example call a method by passing indifferently a database or a database iterator... ''' return self def __iter__ (self): retval = self.first () while retval != None: yield retval retval = self.next() raise StopIteration def set_position (self, pos=0): self._position = 0 def get_position (self): return self._position def first (self): self.set_position (0) return self.next () class DBIterator (Iterator): ''' This class defines a database iterator ''' def __init__ (self, database): self.keys = database.keys () self.base = database self.database = database self.count = 0 return def __iter__ (self): self._position = 0 for k in self.keys: yield self.database [k] self._position += 1 def first (self): self.count = 0 return self.next () def next (self): try: entry = self.database [self.keys [self.count]] except IndexError: entry = None self.count = self.count + 1 return entry<|fim▁end|>
class Iterator:
<|file_name|>node.py<|end_file_name|><|fim▁begin|># (c) Copyright 2014, University of Manchester # # This file is part of PyNSim. # # PyNSim 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. # # PyNSim 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 PyNSim. If not, see <http://www.gnu.org/licenses/>. from pynsim import Node class Junction(Node): type = 'junction' _properties = dict( max_capacity=1000, ) class IrrigationNode(Node): """ A general irrigation node, with proprties demand, max and deficit. At each timestep, this node will use its internal seasonal water requirements to set a demand figure. THe allocator will then calculate deficit based on its max allowed and demand. """ type = 'irrigation' _properties = dict( #percentage max_allowed = 100, demand = 0, deficit=0, ) def setup(self, timestamp): """ Get water requirements for this timestep based on my internal requirements dictionary. """ self.demand = self._seasonal_water_req[timestamp] class CitrusFarm(IrrigationNode): _seasonal_water_req = { "2014-01-01": 100, "2014-02-01": 200, "2014-03-01": 300, "2014-04-01": 400, "2014-05-01": 500, } class VegetableFarm(IrrigationNode): _seasonal_water_req = { "2014-01-01": 150, "2014-02-01": 250, "2014-03-01": 350, "2014-04-01": 450, "2014-05-01": 550, } class SurfaceReservoir(Node): """ Node from which all the other nodes get their water. This reservoir is given its water allocation from its institution -- the ministry of water.<|fim▁hole|> release = 0, capacity = 1000, max_release = 1000, ) def setup(self, timestamp): """ The ministry of water has given me my release details, so there is no need for me to set anything up myself. """ pass<|fim▁end|>
""" type = 'surface reservoir' _properties = dict(
<|file_name|>reflection_test.py<|end_file_name|><|fim▁begin|>#! /usr/bin/python # -*- coding: utf-8 -*- # # Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # http://code.google.com/p/protobuf/ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Unittest for reflection.py, which also indirectly tests the output of the pure-Python protocol compiler. """ __author__ = '[email protected] (Will Robinson)' import copy import gc import operator import struct from google.apputils import basetest from google.protobuf import unittest_import_pb2 from google.protobuf import unittest_mset_pb2 from google.protobuf import unittest_pb2 from google.protobuf import descriptor_pb2 from google.protobuf import descriptor from google.protobuf import message from google.protobuf import reflection from google.protobuf import text_format from google.protobuf.internal import api_implementation from google.protobuf.internal import more_extensions_pb2 from google.protobuf.internal import more_messages_pb2 from google.protobuf.internal import wire_format from google.protobuf.internal import test_util from google.protobuf.internal import decoder class _MiniDecoder(object): """Decodes a stream of values from a string. Once upon a time we actually had a class called decoder.Decoder. Then we got rid of it during a redesign that made decoding much, much faster overall. But a couple tests in this file used it to check that the serialized form of a message was correct. So, this class implements just the methods that were used by said tests, so that we don't have to rewrite the tests. """ def __init__(self, bytes): self._bytes = bytes self._pos = 0 def ReadVarint(self): result, self._pos = decoder._DecodeVarint(self._bytes, self._pos) return result ReadInt32 = ReadVarint ReadInt64 = ReadVarint ReadUInt32 = ReadVarint ReadUInt64 = ReadVarint def ReadSInt64(self): return wire_format.ZigZagDecode(self.ReadVarint()) ReadSInt32 = ReadSInt64 def ReadFieldNumberAndWireType(self): return wire_format.UnpackTag(self.ReadVarint()) def ReadFloat(self): result = struct.unpack("<f", self._bytes[self._pos:self._pos+4])[0] self._pos += 4 return result def ReadDouble(self): result = struct.unpack("<d", self._bytes[self._pos:self._pos+8])[0] self._pos += 8 return result def EndOfStream(self): return self._pos == len(self._bytes) class ReflectionTest(basetest.TestCase): def assertListsEqual(self, values, others): self.assertEqual(len(values), len(others)) for i in range(len(values)): self.assertEqual(values[i], others[i]) def testScalarConstructor(self): # Constructor with only scalar types should succeed. proto = unittest_pb2.TestAllTypes( optional_int32=24, optional_double=54.321, optional_string='optional_string') self.assertEqual(24, proto.optional_int32) self.assertEqual(54.321, proto.optional_double) self.assertEqual('optional_string', proto.optional_string) def testRepeatedScalarConstructor(self): # Constructor with only repeated scalar types should succeed. proto = unittest_pb2.TestAllTypes( repeated_int32=[1, 2, 3, 4], repeated_double=[1.23, 54.321], repeated_bool=[True, False, False], repeated_string=["optional_string"]) self.assertEquals([1, 2, 3, 4], list(proto.repeated_int32)) self.assertEquals([1.23, 54.321], list(proto.repeated_double)) self.assertEquals([True, False, False], list(proto.repeated_bool)) self.assertEquals(["optional_string"], list(proto.repeated_string)) def testRepeatedCompositeConstructor(self): # Constructor with only repeated composite types should succeed. proto = unittest_pb2.TestAllTypes( repeated_nested_message=[ unittest_pb2.TestAllTypes.NestedMessage( bb=unittest_pb2.TestAllTypes.FOO), unittest_pb2.TestAllTypes.NestedMessage( bb=unittest_pb2.TestAllTypes.BAR)], repeated_foreign_message=[ unittest_pb2.ForeignMessage(c=-43), unittest_pb2.ForeignMessage(c=45324), unittest_pb2.ForeignMessage(c=12)], repeatedgroup=[ unittest_pb2.TestAllTypes.RepeatedGroup(), unittest_pb2.TestAllTypes.RepeatedGroup(a=1), unittest_pb2.TestAllTypes.RepeatedGroup(a=2)]) self.assertEquals( [unittest_pb2.TestAllTypes.NestedMessage( bb=unittest_pb2.TestAllTypes.FOO), unittest_pb2.TestAllTypes.NestedMessage( bb=unittest_pb2.TestAllTypes.BAR)], list(proto.repeated_nested_message)) self.assertEquals( [unittest_pb2.ForeignMessage(c=-43), unittest_pb2.ForeignMessage(c=45324), unittest_pb2.ForeignMessage(c=12)], list(proto.repeated_foreign_message)) self.assertEquals( [unittest_pb2.TestAllTypes.RepeatedGroup(), unittest_pb2.TestAllTypes.RepeatedGroup(a=1), unittest_pb2.TestAllTypes.RepeatedGroup(a=2)], list(proto.repeatedgroup)) def testMixedConstructor(self): # Constructor with only mixed types should succeed. proto = unittest_pb2.TestAllTypes( optional_int32=24, optional_string='optional_string', repeated_double=[1.23, 54.321], repeated_bool=[True, False, False], repeated_nested_message=[ unittest_pb2.TestAllTypes.NestedMessage( bb=unittest_pb2.TestAllTypes.FOO), unittest_pb2.TestAllTypes.NestedMessage( bb=unittest_pb2.TestAllTypes.BAR)], repeated_foreign_message=[ unittest_pb2.ForeignMessage(c=-43), unittest_pb2.ForeignMessage(c=45324), unittest_pb2.ForeignMessage(c=12)]) self.assertEqual(24, proto.optional_int32) self.assertEqual('optional_string', proto.optional_string) self.assertEquals([1.23, 54.321], list(proto.repeated_double)) self.assertEquals([True, False, False], list(proto.repeated_bool)) self.assertEquals( [unittest_pb2.TestAllTypes.NestedMessage( bb=unittest_pb2.TestAllTypes.FOO), unittest_pb2.TestAllTypes.NestedMessage( bb=unittest_pb2.TestAllTypes.BAR)], list(proto.repeated_nested_message)) self.assertEquals( [unittest_pb2.ForeignMessage(c=-43), unittest_pb2.ForeignMessage(c=45324), unittest_pb2.ForeignMessage(c=12)], list(proto.repeated_foreign_message)) def testConstructorTypeError(self): self.assertRaises( TypeError, unittest_pb2.TestAllTypes, optional_int32="foo") self.assertRaises( TypeError, unittest_pb2.TestAllTypes, optional_string=1234) self.assertRaises( TypeError, unittest_pb2.TestAllTypes, optional_nested_message=1234) self.assertRaises( TypeError, unittest_pb2.TestAllTypes, repeated_int32=1234) self.assertRaises( TypeError, unittest_pb2.TestAllTypes, repeated_int32=["foo"]) self.assertRaises( TypeError, unittest_pb2.TestAllTypes, repeated_string=1234) self.assertRaises( TypeError, unittest_pb2.TestAllTypes, repeated_string=[1234]) self.assertRaises( TypeError, unittest_pb2.TestAllTypes, repeated_nested_message=1234) self.assertRaises( TypeError, unittest_pb2.TestAllTypes, repeated_nested_message=[1234]) def testConstructorInvalidatesCachedByteSize(self): message = unittest_pb2.TestAllTypes(optional_int32 = 12) self.assertEquals(2, message.ByteSize()) message = unittest_pb2.TestAllTypes( optional_nested_message = unittest_pb2.TestAllTypes.NestedMessage()) self.assertEquals(3, message.ByteSize()) message = unittest_pb2.TestAllTypes(repeated_int32 = [12]) self.assertEquals(3, message.ByteSize()) message = unittest_pb2.TestAllTypes( repeated_nested_message = [unittest_pb2.TestAllTypes.NestedMessage()]) self.assertEquals(3, message.ByteSize()) def testSimpleHasBits(self): # Test a scalar. proto = unittest_pb2.TestAllTypes() self.assertTrue(not proto.HasField('optional_int32')) self.assertEqual(0, proto.optional_int32) # HasField() shouldn't be true if all we've done is # read the default value. self.assertTrue(not proto.HasField('optional_int32')) proto.optional_int32 = 1 # Setting a value however *should* set the "has" bit. self.assertTrue(proto.HasField('optional_int32')) proto.ClearField('optional_int32') # And clearing that value should unset the "has" bit. self.assertTrue(not proto.HasField('optional_int32')) def testHasBitsWithSinglyNestedScalar(self): # Helper used to test foreign messages and groups. # # composite_field_name should be the name of a non-repeated # composite (i.e., foreign or group) field in TestAllTypes, # and scalar_field_name should be the name of an integer-valued # scalar field within that composite. # # I never thought I'd miss C++ macros and templates so much. :( # This helper is semantically just: # # assert proto.composite_field.scalar_field == 0 # assert not proto.composite_field.HasField('scalar_field') # assert not proto.HasField('composite_field') # # proto.composite_field.scalar_field = 10 # old_composite_field = proto.composite_field # # assert proto.composite_field.scalar_field == 10 # assert proto.composite_field.HasField('scalar_field') # assert proto.HasField('composite_field') # # proto.ClearField('composite_field') # # assert not proto.composite_field.HasField('scalar_field') # assert not proto.HasField('composite_field') # assert proto.composite_field.scalar_field == 0 # # # Now ensure that ClearField('composite_field') disconnected # # the old field object from the object tree... # assert old_composite_field is not proto.composite_field # old_composite_field.scalar_field = 20 # assert not proto.composite_field.HasField('scalar_field') # assert not proto.HasField('composite_field') def TestCompositeHasBits(composite_field_name, scalar_field_name): proto = unittest_pb2.TestAllTypes() # First, check that we can get the scalar value, and see that it's the # default (0), but that proto.HasField('omposite') and # proto.composite.HasField('scalar') will still return False. composite_field = getattr(proto, composite_field_name) original_scalar_value = getattr(composite_field, scalar_field_name) self.assertEqual(0, original_scalar_value) # Assert that the composite object does not "have" the scalar. self.assertTrue(not composite_field.HasField(scalar_field_name)) # Assert that proto does not "have" the composite field. self.assertTrue(not proto.HasField(composite_field_name)) # Now set the scalar within the composite field. Ensure that the setting # is reflected, and that proto.HasField('composite') and # proto.composite.HasField('scalar') now both return True. new_val = 20 setattr(composite_field, scalar_field_name, new_val) self.assertEqual(new_val, getattr(composite_field, scalar_field_name)) # Hold on to a reference to the current composite_field object. old_composite_field = composite_field # Assert that the has methods now return true. self.assertTrue(composite_field.HasField(scalar_field_name)) self.assertTrue(proto.HasField(composite_field_name)) # Now call the clear method... proto.ClearField(composite_field_name) # ...and ensure that the "has" bits are all back to False... composite_field = getattr(proto, composite_field_name) self.assertTrue(not composite_field.HasField(scalar_field_name)) self.assertTrue(not proto.HasField(composite_field_name)) # ...and ensure that the scalar field has returned to its default. self.assertEqual(0, getattr(composite_field, scalar_field_name)) self.assertTrue(old_composite_field is not composite_field) setattr(old_composite_field, scalar_field_name, new_val) self.assertTrue(not composite_field.HasField(scalar_field_name)) self.assertTrue(not proto.HasField(composite_field_name)) self.assertEqual(0, getattr(composite_field, scalar_field_name)) # Test simple, single-level nesting when we set a scalar. TestCompositeHasBits('optionalgroup', 'a') TestCompositeHasBits('optional_nested_message', 'bb') TestCompositeHasBits('optional_foreign_message', 'c') TestCompositeHasBits('optional_import_message', 'd') def testReferencesToNestedMessage(self): proto = unittest_pb2.TestAllTypes() nested = proto.optional_nested_message del proto # A previous version had a bug where this would raise an exception when # hitting a now-dead weak reference. nested.bb = 23 def testDisconnectingNestedMessageBeforeSettingField(self): proto = unittest_pb2.TestAllTypes() nested = proto.optional_nested_message proto.ClearField('optional_nested_message') # Should disconnect from parent self.assertTrue(nested is not proto.optional_nested_message) nested.bb = 23 self.assertTrue(not proto.HasField('optional_nested_message')) self.assertEqual(0, proto.optional_nested_message.bb) def testGetDefaultMessageAfterDisconnectingDefaultMessage(self): proto = unittest_pb2.TestAllTypes() nested = proto.optional_nested_message proto.ClearField('optional_nested_message') del proto del nested # Force a garbage collect so that the underlying CMessages are freed along # with the Messages they point to. This is to make sure we're not deleting # default message instances. gc.collect() proto = unittest_pb2.TestAllTypes() nested = proto.optional_nested_message def testDisconnectingNestedMessageAfterSettingField(self): proto = unittest_pb2.TestAllTypes() nested = proto.optional_nested_message nested.bb = 5 self.assertTrue(proto.HasField('optional_nested_message')) proto.ClearField('optional_nested_message') # Should disconnect from parent self.assertEqual(5, nested.bb) self.assertEqual(0, proto.optional_nested_message.bb) self.assertTrue(nested is not proto.optional_nested_message) nested.bb = 23 self.assertTrue(not proto.HasField('optional_nested_message')) self.assertEqual(0, proto.optional_nested_message.bb) def testDisconnectingNestedMessageBeforeGettingField(self): proto = unittest_pb2.TestAllTypes() self.assertTrue(not proto.HasField('optional_nested_message')) proto.ClearField('optional_nested_message') self.assertTrue(not proto.HasField('optional_nested_message')) def testDisconnectingNestedMessageAfterMerge(self): # This test exercises the code path that does not use ReleaseMessage(). # The underlying fear is that if we use ReleaseMessage() incorrectly, # we will have memory leaks. It's hard to check that that doesn't happen, # but at least we can exercise that code path to make sure it works. proto1 = unittest_pb2.TestAllTypes() proto2 = unittest_pb2.TestAllTypes() proto2.optional_nested_message.bb = 5 proto1.MergeFrom(proto2) self.assertTrue(proto1.HasField('optional_nested_message')) proto1.ClearField('optional_nested_message') self.assertTrue(not proto1.HasField('optional_nested_message')) def testDisconnectingLazyNestedMessage(self): # This test exercises releasing a nested message that is lazy. This test # only exercises real code in the C++ implementation as Python does not<|fim▁hole|> # memory corruption and a crash. if api_implementation.Type() != 'python': return proto = unittest_pb2.TestAllTypes() proto.optional_lazy_message.bb = 5 proto.ClearField('optional_lazy_message') del proto gc.collect() def testHasBitsWhenModifyingRepeatedFields(self): # Test nesting when we add an element to a repeated field in a submessage. proto = unittest_pb2.TestNestedMessageHasBits() proto.optional_nested_message.nestedmessage_repeated_int32.append(5) self.assertEqual( [5], proto.optional_nested_message.nestedmessage_repeated_int32) self.assertTrue(proto.HasField('optional_nested_message')) # Do the same test, but with a repeated composite field within the # submessage. proto.ClearField('optional_nested_message') self.assertTrue(not proto.HasField('optional_nested_message')) proto.optional_nested_message.nestedmessage_repeated_foreignmessage.add() self.assertTrue(proto.HasField('optional_nested_message')) def testHasBitsForManyLevelsOfNesting(self): # Test nesting many levels deep. recursive_proto = unittest_pb2.TestMutualRecursionA() self.assertTrue(not recursive_proto.HasField('bb')) self.assertEqual(0, recursive_proto.bb.a.bb.a.bb.optional_int32) self.assertTrue(not recursive_proto.HasField('bb')) recursive_proto.bb.a.bb.a.bb.optional_int32 = 5 self.assertEqual(5, recursive_proto.bb.a.bb.a.bb.optional_int32) self.assertTrue(recursive_proto.HasField('bb')) self.assertTrue(recursive_proto.bb.HasField('a')) self.assertTrue(recursive_proto.bb.a.HasField('bb')) self.assertTrue(recursive_proto.bb.a.bb.HasField('a')) self.assertTrue(recursive_proto.bb.a.bb.a.HasField('bb')) self.assertTrue(not recursive_proto.bb.a.bb.a.bb.HasField('a')) self.assertTrue(recursive_proto.bb.a.bb.a.bb.HasField('optional_int32')) def testSingularListFields(self): proto = unittest_pb2.TestAllTypes() proto.optional_fixed32 = 1 proto.optional_int32 = 5 proto.optional_string = 'foo' # Access sub-message but don't set it yet. nested_message = proto.optional_nested_message self.assertEqual( [ (proto.DESCRIPTOR.fields_by_name['optional_int32' ], 5), (proto.DESCRIPTOR.fields_by_name['optional_fixed32'], 1), (proto.DESCRIPTOR.fields_by_name['optional_string' ], 'foo') ], proto.ListFields()) proto.optional_nested_message.bb = 123 self.assertEqual( [ (proto.DESCRIPTOR.fields_by_name['optional_int32' ], 5), (proto.DESCRIPTOR.fields_by_name['optional_fixed32'], 1), (proto.DESCRIPTOR.fields_by_name['optional_string' ], 'foo'), (proto.DESCRIPTOR.fields_by_name['optional_nested_message' ], nested_message) ], proto.ListFields()) def testRepeatedListFields(self): proto = unittest_pb2.TestAllTypes() proto.repeated_fixed32.append(1) proto.repeated_int32.append(5) proto.repeated_int32.append(11) proto.repeated_string.extend(['foo', 'bar']) proto.repeated_string.extend([]) proto.repeated_string.append('baz') proto.repeated_string.extend(str(x) for x in xrange(2)) proto.optional_int32 = 21 proto.repeated_bool # Access but don't set anything; should not be listed. self.assertEqual( [ (proto.DESCRIPTOR.fields_by_name['optional_int32' ], 21), (proto.DESCRIPTOR.fields_by_name['repeated_int32' ], [5, 11]), (proto.DESCRIPTOR.fields_by_name['repeated_fixed32'], [1]), (proto.DESCRIPTOR.fields_by_name['repeated_string' ], ['foo', 'bar', 'baz', '0', '1']) ], proto.ListFields()) def testSingularListExtensions(self): proto = unittest_pb2.TestAllExtensions() proto.Extensions[unittest_pb2.optional_fixed32_extension] = 1 proto.Extensions[unittest_pb2.optional_int32_extension ] = 5 proto.Extensions[unittest_pb2.optional_string_extension ] = 'foo' self.assertEqual( [ (unittest_pb2.optional_int32_extension , 5), (unittest_pb2.optional_fixed32_extension, 1), (unittest_pb2.optional_string_extension , 'foo') ], proto.ListFields()) def testRepeatedListExtensions(self): proto = unittest_pb2.TestAllExtensions() proto.Extensions[unittest_pb2.repeated_fixed32_extension].append(1) proto.Extensions[unittest_pb2.repeated_int32_extension ].append(5) proto.Extensions[unittest_pb2.repeated_int32_extension ].append(11) proto.Extensions[unittest_pb2.repeated_string_extension ].append('foo') proto.Extensions[unittest_pb2.repeated_string_extension ].append('bar') proto.Extensions[unittest_pb2.repeated_string_extension ].append('baz') proto.Extensions[unittest_pb2.optional_int32_extension ] = 21 self.assertEqual( [ (unittest_pb2.optional_int32_extension , 21), (unittest_pb2.repeated_int32_extension , [5, 11]), (unittest_pb2.repeated_fixed32_extension, [1]), (unittest_pb2.repeated_string_extension , ['foo', 'bar', 'baz']) ], proto.ListFields()) def testListFieldsAndExtensions(self): proto = unittest_pb2.TestFieldOrderings() test_util.SetAllFieldsAndExtensions(proto) unittest_pb2.my_extension_int self.assertEqual( [ (proto.DESCRIPTOR.fields_by_name['my_int' ], 1), (unittest_pb2.my_extension_int , 23), (proto.DESCRIPTOR.fields_by_name['my_string'], 'foo'), (unittest_pb2.my_extension_string , 'bar'), (proto.DESCRIPTOR.fields_by_name['my_float' ], 1.0) ], proto.ListFields()) def testDefaultValues(self): proto = unittest_pb2.TestAllTypes() self.assertEqual(0, proto.optional_int32) self.assertEqual(0, proto.optional_int64) self.assertEqual(0, proto.optional_uint32) self.assertEqual(0, proto.optional_uint64) self.assertEqual(0, proto.optional_sint32) self.assertEqual(0, proto.optional_sint64) self.assertEqual(0, proto.optional_fixed32) self.assertEqual(0, proto.optional_fixed64) self.assertEqual(0, proto.optional_sfixed32) self.assertEqual(0, proto.optional_sfixed64) self.assertEqual(0.0, proto.optional_float) self.assertEqual(0.0, proto.optional_double) self.assertEqual(False, proto.optional_bool) self.assertEqual('', proto.optional_string) self.assertEqual(b'', proto.optional_bytes) self.assertEqual(41, proto.default_int32) self.assertEqual(42, proto.default_int64) self.assertEqual(43, proto.default_uint32) self.assertEqual(44, proto.default_uint64) self.assertEqual(-45, proto.default_sint32) self.assertEqual(46, proto.default_sint64) self.assertEqual(47, proto.default_fixed32) self.assertEqual(48, proto.default_fixed64) self.assertEqual(49, proto.default_sfixed32) self.assertEqual(-50, proto.default_sfixed64) self.assertEqual(51.5, proto.default_float) self.assertEqual(52e3, proto.default_double) self.assertEqual(True, proto.default_bool) self.assertEqual('hello', proto.default_string) self.assertEqual(b'world', proto.default_bytes) self.assertEqual(unittest_pb2.TestAllTypes.BAR, proto.default_nested_enum) self.assertEqual(unittest_pb2.FOREIGN_BAR, proto.default_foreign_enum) self.assertEqual(unittest_import_pb2.IMPORT_BAR, proto.default_import_enum) proto = unittest_pb2.TestExtremeDefaultValues() self.assertEqual(u'\u1234', proto.utf8_string) def testHasFieldWithUnknownFieldName(self): proto = unittest_pb2.TestAllTypes() self.assertRaises(ValueError, proto.HasField, 'nonexistent_field') def testClearFieldWithUnknownFieldName(self): proto = unittest_pb2.TestAllTypes() self.assertRaises(ValueError, proto.ClearField, 'nonexistent_field') def testClearRemovesChildren(self): # Make sure there aren't any implementation bugs that are only partially # clearing the message (which can happen in the more complex C++ # implementation which has parallel message lists). proto = unittest_pb2.TestRequiredForeign() for i in range(10): proto.repeated_message.add() proto2 = unittest_pb2.TestRequiredForeign() proto.CopyFrom(proto2) self.assertRaises(IndexError, lambda: proto.repeated_message[5]) def testDisallowedAssignments(self): # It's illegal to assign values directly to repeated fields # or to nonrepeated composite fields. Ensure that this fails. proto = unittest_pb2.TestAllTypes() # Repeated fields. self.assertRaises(AttributeError, setattr, proto, 'repeated_int32', 10) # Lists shouldn't work, either. self.assertRaises(AttributeError, setattr, proto, 'repeated_int32', [10]) # Composite fields. self.assertRaises(AttributeError, setattr, proto, 'optional_nested_message', 23) # Assignment to a repeated nested message field without specifying # the index in the array of nested messages. self.assertRaises(AttributeError, setattr, proto.repeated_nested_message, 'bb', 34) # Assignment to an attribute of a repeated field. self.assertRaises(AttributeError, setattr, proto.repeated_float, 'some_attribute', 34) # proto.nonexistent_field = 23 should fail as well. self.assertRaises(AttributeError, setattr, proto, 'nonexistent_field', 23) def testSingleScalarTypeSafety(self): proto = unittest_pb2.TestAllTypes() self.assertRaises(TypeError, setattr, proto, 'optional_int32', 1.1) self.assertRaises(TypeError, setattr, proto, 'optional_int32', 'foo') self.assertRaises(TypeError, setattr, proto, 'optional_string', 10) self.assertRaises(TypeError, setattr, proto, 'optional_bytes', 10) def testIntegerTypes(self): def TestGetAndDeserialize(field_name, value, expected_type): proto = unittest_pb2.TestAllTypes() setattr(proto, field_name, value) self.assertTrue(isinstance(getattr(proto, field_name), expected_type)) proto2 = unittest_pb2.TestAllTypes() proto2.ParseFromString(proto.SerializeToString()) self.assertTrue(isinstance(getattr(proto2, field_name), expected_type)) TestGetAndDeserialize('optional_int32', 1, int) TestGetAndDeserialize('optional_int32', 1 << 30, int) TestGetAndDeserialize('optional_uint32', 1 << 30, int) if struct.calcsize('L') == 4: # Python only has signed ints, so 32-bit python can't fit an uint32 # in an int. TestGetAndDeserialize('optional_uint32', 1 << 31, long) else: # 64-bit python can fit uint32 inside an int TestGetAndDeserialize('optional_uint32', 1 << 31, int) TestGetAndDeserialize('optional_int64', 1 << 30, long) TestGetAndDeserialize('optional_int64', 1 << 60, long) TestGetAndDeserialize('optional_uint64', 1 << 30, long) TestGetAndDeserialize('optional_uint64', 1 << 60, long) def testSingleScalarBoundsChecking(self): def TestMinAndMaxIntegers(field_name, expected_min, expected_max): pb = unittest_pb2.TestAllTypes() setattr(pb, field_name, expected_min) self.assertEqual(expected_min, getattr(pb, field_name)) setattr(pb, field_name, expected_max) self.assertEqual(expected_max, getattr(pb, field_name)) self.assertRaises(ValueError, setattr, pb, field_name, expected_min - 1) self.assertRaises(ValueError, setattr, pb, field_name, expected_max + 1) TestMinAndMaxIntegers('optional_int32', -(1 << 31), (1 << 31) - 1) TestMinAndMaxIntegers('optional_uint32', 0, 0xffffffff) TestMinAndMaxIntegers('optional_int64', -(1 << 63), (1 << 63) - 1) TestMinAndMaxIntegers('optional_uint64', 0, 0xffffffffffffffff) pb = unittest_pb2.TestAllTypes() pb.optional_nested_enum = 1 self.assertEqual(1, pb.optional_nested_enum) def testRepeatedScalarTypeSafety(self): proto = unittest_pb2.TestAllTypes() self.assertRaises(TypeError, proto.repeated_int32.append, 1.1) self.assertRaises(TypeError, proto.repeated_int32.append, 'foo') self.assertRaises(TypeError, proto.repeated_string, 10) self.assertRaises(TypeError, proto.repeated_bytes, 10) proto.repeated_int32.append(10) proto.repeated_int32[0] = 23 self.assertRaises(IndexError, proto.repeated_int32.__setitem__, 500, 23) self.assertRaises(TypeError, proto.repeated_int32.__setitem__, 0, 'abc') # Repeated enums tests. #proto.repeated_nested_enum.append(0) def testSingleScalarGettersAndSetters(self): proto = unittest_pb2.TestAllTypes() self.assertEqual(0, proto.optional_int32) proto.optional_int32 = 1 self.assertEqual(1, proto.optional_int32) proto.optional_uint64 = 0xffffffffffff self.assertEqual(0xffffffffffff, proto.optional_uint64) proto.optional_uint64 = 0xffffffffffffffff self.assertEqual(0xffffffffffffffff, proto.optional_uint64) # TODO(robinson): Test all other scalar field types. def testSingleScalarClearField(self): proto = unittest_pb2.TestAllTypes() # Should be allowed to clear something that's not there (a no-op). proto.ClearField('optional_int32') proto.optional_int32 = 1 self.assertTrue(proto.HasField('optional_int32')) proto.ClearField('optional_int32') self.assertEqual(0, proto.optional_int32) self.assertTrue(not proto.HasField('optional_int32')) # TODO(robinson): Test all other scalar field types. def testEnums(self): proto = unittest_pb2.TestAllTypes() self.assertEqual(1, proto.FOO) self.assertEqual(1, unittest_pb2.TestAllTypes.FOO) self.assertEqual(2, proto.BAR) self.assertEqual(2, unittest_pb2.TestAllTypes.BAR) self.assertEqual(3, proto.BAZ) self.assertEqual(3, unittest_pb2.TestAllTypes.BAZ) def testEnum_Name(self): self.assertEqual('FOREIGN_FOO', unittest_pb2.ForeignEnum.Name(unittest_pb2.FOREIGN_FOO)) self.assertEqual('FOREIGN_BAR', unittest_pb2.ForeignEnum.Name(unittest_pb2.FOREIGN_BAR)) self.assertEqual('FOREIGN_BAZ', unittest_pb2.ForeignEnum.Name(unittest_pb2.FOREIGN_BAZ)) self.assertRaises(ValueError, unittest_pb2.ForeignEnum.Name, 11312) proto = unittest_pb2.TestAllTypes() self.assertEqual('FOO', proto.NestedEnum.Name(proto.FOO)) self.assertEqual('FOO', unittest_pb2.TestAllTypes.NestedEnum.Name(proto.FOO)) self.assertEqual('BAR', proto.NestedEnum.Name(proto.BAR)) self.assertEqual('BAR', unittest_pb2.TestAllTypes.NestedEnum.Name(proto.BAR)) self.assertEqual('BAZ', proto.NestedEnum.Name(proto.BAZ)) self.assertEqual('BAZ', unittest_pb2.TestAllTypes.NestedEnum.Name(proto.BAZ)) self.assertRaises(ValueError, proto.NestedEnum.Name, 11312) self.assertRaises(ValueError, unittest_pb2.TestAllTypes.NestedEnum.Name, 11312) def testEnum_Value(self): self.assertEqual(unittest_pb2.FOREIGN_FOO, unittest_pb2.ForeignEnum.Value('FOREIGN_FOO')) self.assertEqual(unittest_pb2.FOREIGN_BAR, unittest_pb2.ForeignEnum.Value('FOREIGN_BAR')) self.assertEqual(unittest_pb2.FOREIGN_BAZ, unittest_pb2.ForeignEnum.Value('FOREIGN_BAZ')) self.assertRaises(ValueError, unittest_pb2.ForeignEnum.Value, 'FO') proto = unittest_pb2.TestAllTypes() self.assertEqual(proto.FOO, proto.NestedEnum.Value('FOO')) self.assertEqual(proto.FOO, unittest_pb2.TestAllTypes.NestedEnum.Value('FOO')) self.assertEqual(proto.BAR, proto.NestedEnum.Value('BAR')) self.assertEqual(proto.BAR, unittest_pb2.TestAllTypes.NestedEnum.Value('BAR')) self.assertEqual(proto.BAZ, proto.NestedEnum.Value('BAZ')) self.assertEqual(proto.BAZ, unittest_pb2.TestAllTypes.NestedEnum.Value('BAZ')) self.assertRaises(ValueError, proto.NestedEnum.Value, 'Foo') self.assertRaises(ValueError, unittest_pb2.TestAllTypes.NestedEnum.Value, 'Foo') def testEnum_KeysAndValues(self): self.assertEqual(['FOREIGN_FOO', 'FOREIGN_BAR', 'FOREIGN_BAZ'], unittest_pb2.ForeignEnum.keys()) self.assertEqual([4, 5, 6], unittest_pb2.ForeignEnum.values()) self.assertEqual([('FOREIGN_FOO', 4), ('FOREIGN_BAR', 5), ('FOREIGN_BAZ', 6)], unittest_pb2.ForeignEnum.items()) proto = unittest_pb2.TestAllTypes() self.assertEqual(['FOO', 'BAR', 'BAZ', 'NEG'], proto.NestedEnum.keys()) self.assertEqual([1, 2, 3, -1], proto.NestedEnum.values()) self.assertEqual([('FOO', 1), ('BAR', 2), ('BAZ', 3), ('NEG', -1)], proto.NestedEnum.items()) def testRepeatedScalars(self): proto = unittest_pb2.TestAllTypes() self.assertTrue(not proto.repeated_int32) self.assertEqual(0, len(proto.repeated_int32)) proto.repeated_int32.append(5) proto.repeated_int32.append(10) proto.repeated_int32.append(15) self.assertTrue(proto.repeated_int32) self.assertEqual(3, len(proto.repeated_int32)) self.assertEqual([5, 10, 15], proto.repeated_int32) # Test single retrieval. self.assertEqual(5, proto.repeated_int32[0]) self.assertEqual(15, proto.repeated_int32[-1]) # Test out-of-bounds indices. self.assertRaises(IndexError, proto.repeated_int32.__getitem__, 1234) self.assertRaises(IndexError, proto.repeated_int32.__getitem__, -1234) # Test incorrect types passed to __getitem__. self.assertRaises(TypeError, proto.repeated_int32.__getitem__, 'foo') self.assertRaises(TypeError, proto.repeated_int32.__getitem__, None) # Test single assignment. proto.repeated_int32[1] = 20 self.assertEqual([5, 20, 15], proto.repeated_int32) # Test insertion. proto.repeated_int32.insert(1, 25) self.assertEqual([5, 25, 20, 15], proto.repeated_int32) # Test slice retrieval. proto.repeated_int32.append(30) self.assertEqual([25, 20, 15], proto.repeated_int32[1:4]) self.assertEqual([5, 25, 20, 15, 30], proto.repeated_int32[:]) # Test slice assignment with an iterator proto.repeated_int32[1:4] = (i for i in xrange(3)) self.assertEqual([5, 0, 1, 2, 30], proto.repeated_int32) # Test slice assignment. proto.repeated_int32[1:4] = [35, 40, 45] self.assertEqual([5, 35, 40, 45, 30], proto.repeated_int32) # Test that we can use the field as an iterator. result = [] for i in proto.repeated_int32: result.append(i) self.assertEqual([5, 35, 40, 45, 30], result) # Test single deletion. del proto.repeated_int32[2] self.assertEqual([5, 35, 45, 30], proto.repeated_int32) # Test slice deletion. del proto.repeated_int32[2:] self.assertEqual([5, 35], proto.repeated_int32) # Test extending. proto.repeated_int32.extend([3, 13]) self.assertEqual([5, 35, 3, 13], proto.repeated_int32) # Test clearing. proto.ClearField('repeated_int32') self.assertTrue(not proto.repeated_int32) self.assertEqual(0, len(proto.repeated_int32)) proto.repeated_int32.append(1) self.assertEqual(1, proto.repeated_int32[-1]) # Test assignment to a negative index. proto.repeated_int32[-1] = 2 self.assertEqual(2, proto.repeated_int32[-1]) # Test deletion at negative indices. proto.repeated_int32[:] = [0, 1, 2, 3] del proto.repeated_int32[-1] self.assertEqual([0, 1, 2], proto.repeated_int32) del proto.repeated_int32[-2] self.assertEqual([0, 2], proto.repeated_int32) self.assertRaises(IndexError, proto.repeated_int32.__delitem__, -3) self.assertRaises(IndexError, proto.repeated_int32.__delitem__, 300) del proto.repeated_int32[-2:-1] self.assertEqual([2], proto.repeated_int32) del proto.repeated_int32[100:10000] self.assertEqual([2], proto.repeated_int32) def testRepeatedScalarsRemove(self): proto = unittest_pb2.TestAllTypes() self.assertTrue(not proto.repeated_int32) self.assertEqual(0, len(proto.repeated_int32)) proto.repeated_int32.append(5) proto.repeated_int32.append(10) proto.repeated_int32.append(5) proto.repeated_int32.append(5) self.assertEqual(4, len(proto.repeated_int32)) proto.repeated_int32.remove(5) self.assertEqual(3, len(proto.repeated_int32)) self.assertEqual(10, proto.repeated_int32[0]) self.assertEqual(5, proto.repeated_int32[1]) self.assertEqual(5, proto.repeated_int32[2]) proto.repeated_int32.remove(5) self.assertEqual(2, len(proto.repeated_int32)) self.assertEqual(10, proto.repeated_int32[0]) self.assertEqual(5, proto.repeated_int32[1]) proto.repeated_int32.remove(10) self.assertEqual(1, len(proto.repeated_int32)) self.assertEqual(5, proto.repeated_int32[0]) # Remove a non-existent element. self.assertRaises(ValueError, proto.repeated_int32.remove, 123) def testRepeatedComposites(self): proto = unittest_pb2.TestAllTypes() self.assertTrue(not proto.repeated_nested_message) self.assertEqual(0, len(proto.repeated_nested_message)) m0 = proto.repeated_nested_message.add() m1 = proto.repeated_nested_message.add() self.assertTrue(proto.repeated_nested_message) self.assertEqual(2, len(proto.repeated_nested_message)) self.assertListsEqual([m0, m1], proto.repeated_nested_message) self.assertTrue(isinstance(m0, unittest_pb2.TestAllTypes.NestedMessage)) # Test out-of-bounds indices. self.assertRaises(IndexError, proto.repeated_nested_message.__getitem__, 1234) self.assertRaises(IndexError, proto.repeated_nested_message.__getitem__, -1234) # Test incorrect types passed to __getitem__. self.assertRaises(TypeError, proto.repeated_nested_message.__getitem__, 'foo') self.assertRaises(TypeError, proto.repeated_nested_message.__getitem__, None) # Test slice retrieval. m2 = proto.repeated_nested_message.add() m3 = proto.repeated_nested_message.add() m4 = proto.repeated_nested_message.add() self.assertListsEqual( [m1, m2, m3], proto.repeated_nested_message[1:4]) self.assertListsEqual( [m0, m1, m2, m3, m4], proto.repeated_nested_message[:]) self.assertListsEqual( [m0, m1], proto.repeated_nested_message[:2]) self.assertListsEqual( [m2, m3, m4], proto.repeated_nested_message[2:]) self.assertEqual( m0, proto.repeated_nested_message[0]) self.assertListsEqual( [m0], proto.repeated_nested_message[:1]) # Test that we can use the field as an iterator. result = [] for i in proto.repeated_nested_message: result.append(i) self.assertListsEqual([m0, m1, m2, m3, m4], result) # Test single deletion. del proto.repeated_nested_message[2] self.assertListsEqual([m0, m1, m3, m4], proto.repeated_nested_message) # Test slice deletion. del proto.repeated_nested_message[2:] self.assertListsEqual([m0, m1], proto.repeated_nested_message) # Test extending. n1 = unittest_pb2.TestAllTypes.NestedMessage(bb=1) n2 = unittest_pb2.TestAllTypes.NestedMessage(bb=2) proto.repeated_nested_message.extend([n1,n2]) self.assertEqual(4, len(proto.repeated_nested_message)) self.assertEqual(n1, proto.repeated_nested_message[2]) self.assertEqual(n2, proto.repeated_nested_message[3]) # Test clearing. proto.ClearField('repeated_nested_message') self.assertTrue(not proto.repeated_nested_message) self.assertEqual(0, len(proto.repeated_nested_message)) # Test constructing an element while adding it. proto.repeated_nested_message.add(bb=23) self.assertEqual(1, len(proto.repeated_nested_message)) self.assertEqual(23, proto.repeated_nested_message[0].bb) def testRepeatedCompositeRemove(self): proto = unittest_pb2.TestAllTypes() self.assertEqual(0, len(proto.repeated_nested_message)) m0 = proto.repeated_nested_message.add() # Need to set some differentiating variable so m0 != m1 != m2: m0.bb = len(proto.repeated_nested_message) m1 = proto.repeated_nested_message.add() m1.bb = len(proto.repeated_nested_message) self.assertTrue(m0 != m1) m2 = proto.repeated_nested_message.add() m2.bb = len(proto.repeated_nested_message) self.assertListsEqual([m0, m1, m2], proto.repeated_nested_message) self.assertEqual(3, len(proto.repeated_nested_message)) proto.repeated_nested_message.remove(m0) self.assertEqual(2, len(proto.repeated_nested_message)) self.assertEqual(m1, proto.repeated_nested_message[0]) self.assertEqual(m2, proto.repeated_nested_message[1]) # Removing m0 again or removing None should raise error self.assertRaises(ValueError, proto.repeated_nested_message.remove, m0) self.assertRaises(ValueError, proto.repeated_nested_message.remove, None) self.assertEqual(2, len(proto.repeated_nested_message)) proto.repeated_nested_message.remove(m2) self.assertEqual(1, len(proto.repeated_nested_message)) self.assertEqual(m1, proto.repeated_nested_message[0]) def testHandWrittenReflection(self): # Hand written extensions are only supported by the pure-Python # implementation of the API. if api_implementation.Type() != 'python': return FieldDescriptor = descriptor.FieldDescriptor foo_field_descriptor = FieldDescriptor( name='foo_field', full_name='MyProto.foo_field', index=0, number=1, type=FieldDescriptor.TYPE_INT64, cpp_type=FieldDescriptor.CPPTYPE_INT64, label=FieldDescriptor.LABEL_OPTIONAL, default_value=0, containing_type=None, message_type=None, enum_type=None, is_extension=False, extension_scope=None, options=descriptor_pb2.FieldOptions()) mydescriptor = descriptor.Descriptor( name='MyProto', full_name='MyProto', filename='ignored', containing_type=None, nested_types=[], enum_types=[], fields=[foo_field_descriptor], extensions=[], options=descriptor_pb2.MessageOptions()) class MyProtoClass(message.Message): DESCRIPTOR = mydescriptor __metaclass__ = reflection.GeneratedProtocolMessageType myproto_instance = MyProtoClass() self.assertEqual(0, myproto_instance.foo_field) self.assertTrue(not myproto_instance.HasField('foo_field')) myproto_instance.foo_field = 23 self.assertEqual(23, myproto_instance.foo_field) self.assertTrue(myproto_instance.HasField('foo_field')) def testDescriptorProtoSupport(self): # Hand written descriptors/reflection are only supported by the pure-Python # implementation of the API. if api_implementation.Type() != 'python': return def AddDescriptorField(proto, field_name, field_type): AddDescriptorField.field_index += 1 new_field = proto.field.add() new_field.name = field_name new_field.type = field_type new_field.number = AddDescriptorField.field_index new_field.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL AddDescriptorField.field_index = 0 desc_proto = descriptor_pb2.DescriptorProto() desc_proto.name = 'Car' fdp = descriptor_pb2.FieldDescriptorProto AddDescriptorField(desc_proto, 'name', fdp.TYPE_STRING) AddDescriptorField(desc_proto, 'year', fdp.TYPE_INT64) AddDescriptorField(desc_proto, 'automatic', fdp.TYPE_BOOL) AddDescriptorField(desc_proto, 'price', fdp.TYPE_DOUBLE) # Add a repeated field AddDescriptorField.field_index += 1 new_field = desc_proto.field.add() new_field.name = 'owners' new_field.type = fdp.TYPE_STRING new_field.number = AddDescriptorField.field_index new_field.label = descriptor_pb2.FieldDescriptorProto.LABEL_REPEATED desc = descriptor.MakeDescriptor(desc_proto) self.assertTrue(desc.fields_by_name.has_key('name')) self.assertTrue(desc.fields_by_name.has_key('year')) self.assertTrue(desc.fields_by_name.has_key('automatic')) self.assertTrue(desc.fields_by_name.has_key('price')) self.assertTrue(desc.fields_by_name.has_key('owners')) class CarMessage(message.Message): __metaclass__ = reflection.GeneratedProtocolMessageType DESCRIPTOR = desc prius = CarMessage() prius.name = 'prius' prius.year = 2010 prius.automatic = True prius.price = 25134.75 prius.owners.extend(['bob', 'susan']) serialized_prius = prius.SerializeToString() new_prius = reflection.ParseMessage(desc, serialized_prius) self.assertTrue(new_prius is not prius) self.assertEqual(prius, new_prius) # these are unnecessary assuming message equality works as advertised but # explicitly check to be safe since we're mucking about in metaclass foo self.assertEqual(prius.name, new_prius.name) self.assertEqual(prius.year, new_prius.year) self.assertEqual(prius.automatic, new_prius.automatic) self.assertEqual(prius.price, new_prius.price) self.assertEqual(prius.owners, new_prius.owners) def testTopLevelExtensionsForOptionalScalar(self): extendee_proto = unittest_pb2.TestAllExtensions() extension = unittest_pb2.optional_int32_extension self.assertTrue(not extendee_proto.HasExtension(extension)) self.assertEqual(0, extendee_proto.Extensions[extension]) # As with normal scalar fields, just doing a read doesn't actually set the # "has" bit. self.assertTrue(not extendee_proto.HasExtension(extension)) # Actually set the thing. extendee_proto.Extensions[extension] = 23 self.assertEqual(23, extendee_proto.Extensions[extension]) self.assertTrue(extendee_proto.HasExtension(extension)) # Ensure that clearing works as well. extendee_proto.ClearExtension(extension) self.assertEqual(0, extendee_proto.Extensions[extension]) self.assertTrue(not extendee_proto.HasExtension(extension)) def testTopLevelExtensionsForRepeatedScalar(self): extendee_proto = unittest_pb2.TestAllExtensions() extension = unittest_pb2.repeated_string_extension self.assertEqual(0, len(extendee_proto.Extensions[extension])) extendee_proto.Extensions[extension].append('foo') self.assertEqual(['foo'], extendee_proto.Extensions[extension]) string_list = extendee_proto.Extensions[extension] extendee_proto.ClearExtension(extension) self.assertEqual(0, len(extendee_proto.Extensions[extension])) self.assertTrue(string_list is not extendee_proto.Extensions[extension]) # Shouldn't be allowed to do Extensions[extension] = 'a' self.assertRaises(TypeError, operator.setitem, extendee_proto.Extensions, extension, 'a') def testTopLevelExtensionsForOptionalMessage(self): extendee_proto = unittest_pb2.TestAllExtensions() extension = unittest_pb2.optional_foreign_message_extension self.assertTrue(not extendee_proto.HasExtension(extension)) self.assertEqual(0, extendee_proto.Extensions[extension].c) # As with normal (non-extension) fields, merely reading from the # thing shouldn't set the "has" bit. self.assertTrue(not extendee_proto.HasExtension(extension)) extendee_proto.Extensions[extension].c = 23 self.assertEqual(23, extendee_proto.Extensions[extension].c) self.assertTrue(extendee_proto.HasExtension(extension)) # Save a reference here. foreign_message = extendee_proto.Extensions[extension] extendee_proto.ClearExtension(extension) self.assertTrue(foreign_message is not extendee_proto.Extensions[extension]) # Setting a field on foreign_message now shouldn't set # any "has" bits on extendee_proto. foreign_message.c = 42 self.assertEqual(42, foreign_message.c) self.assertTrue(foreign_message.HasField('c')) self.assertTrue(not extendee_proto.HasExtension(extension)) # Shouldn't be allowed to do Extensions[extension] = 'a' self.assertRaises(TypeError, operator.setitem, extendee_proto.Extensions, extension, 'a') def testTopLevelExtensionsForRepeatedMessage(self): extendee_proto = unittest_pb2.TestAllExtensions() extension = unittest_pb2.repeatedgroup_extension self.assertEqual(0, len(extendee_proto.Extensions[extension])) group = extendee_proto.Extensions[extension].add() group.a = 23 self.assertEqual(23, extendee_proto.Extensions[extension][0].a) group.a = 42 self.assertEqual(42, extendee_proto.Extensions[extension][0].a) group_list = extendee_proto.Extensions[extension] extendee_proto.ClearExtension(extension) self.assertEqual(0, len(extendee_proto.Extensions[extension])) self.assertTrue(group_list is not extendee_proto.Extensions[extension]) # Shouldn't be allowed to do Extensions[extension] = 'a' self.assertRaises(TypeError, operator.setitem, extendee_proto.Extensions, extension, 'a') def testNestedExtensions(self): extendee_proto = unittest_pb2.TestAllExtensions() extension = unittest_pb2.TestRequired.single # We just test the non-repeated case. self.assertTrue(not extendee_proto.HasExtension(extension)) required = extendee_proto.Extensions[extension] self.assertEqual(0, required.a) self.assertTrue(not extendee_proto.HasExtension(extension)) required.a = 23 self.assertEqual(23, extendee_proto.Extensions[extension].a) self.assertTrue(extendee_proto.HasExtension(extension)) extendee_proto.ClearExtension(extension) self.assertTrue(required is not extendee_proto.Extensions[extension]) self.assertTrue(not extendee_proto.HasExtension(extension)) def testRegisteredExtensions(self): self.assertTrue('protobuf_unittest.optional_int32_extension' in unittest_pb2.TestAllExtensions._extensions_by_name) self.assertTrue(1 in unittest_pb2.TestAllExtensions._extensions_by_number) # Make sure extensions haven't been registered into types that shouldn't # have any. self.assertEquals(0, len(unittest_pb2.TestAllTypes._extensions_by_name)) # If message A directly contains message B, and # a.HasField('b') is currently False, then mutating any # extension in B should change a.HasField('b') to True # (and so on up the object tree). def testHasBitsForAncestorsOfExtendedMessage(self): # Optional scalar extension. toplevel = more_extensions_pb2.TopLevelMessage() self.assertTrue(not toplevel.HasField('submessage')) self.assertEqual(0, toplevel.submessage.Extensions[ more_extensions_pb2.optional_int_extension]) self.assertTrue(not toplevel.HasField('submessage')) toplevel.submessage.Extensions[ more_extensions_pb2.optional_int_extension] = 23 self.assertEqual(23, toplevel.submessage.Extensions[ more_extensions_pb2.optional_int_extension]) self.assertTrue(toplevel.HasField('submessage')) # Repeated scalar extension. toplevel = more_extensions_pb2.TopLevelMessage() self.assertTrue(not toplevel.HasField('submessage')) self.assertEqual([], toplevel.submessage.Extensions[ more_extensions_pb2.repeated_int_extension]) self.assertTrue(not toplevel.HasField('submessage')) toplevel.submessage.Extensions[ more_extensions_pb2.repeated_int_extension].append(23) self.assertEqual([23], toplevel.submessage.Extensions[ more_extensions_pb2.repeated_int_extension]) self.assertTrue(toplevel.HasField('submessage')) # Optional message extension. toplevel = more_extensions_pb2.TopLevelMessage() self.assertTrue(not toplevel.HasField('submessage')) self.assertEqual(0, toplevel.submessage.Extensions[ more_extensions_pb2.optional_message_extension].foreign_message_int) self.assertTrue(not toplevel.HasField('submessage')) toplevel.submessage.Extensions[ more_extensions_pb2.optional_message_extension].foreign_message_int = 23 self.assertEqual(23, toplevel.submessage.Extensions[ more_extensions_pb2.optional_message_extension].foreign_message_int) self.assertTrue(toplevel.HasField('submessage')) # Repeated message extension. toplevel = more_extensions_pb2.TopLevelMessage() self.assertTrue(not toplevel.HasField('submessage')) self.assertEqual(0, len(toplevel.submessage.Extensions[ more_extensions_pb2.repeated_message_extension])) self.assertTrue(not toplevel.HasField('submessage')) foreign = toplevel.submessage.Extensions[ more_extensions_pb2.repeated_message_extension].add() self.assertEqual(foreign, toplevel.submessage.Extensions[ more_extensions_pb2.repeated_message_extension][0]) self.assertTrue(toplevel.HasField('submessage')) def testDisconnectionAfterClearingEmptyMessage(self): toplevel = more_extensions_pb2.TopLevelMessage() extendee_proto = toplevel.submessage extension = more_extensions_pb2.optional_message_extension extension_proto = extendee_proto.Extensions[extension] extendee_proto.ClearExtension(extension) extension_proto.foreign_message_int = 23 self.assertTrue(extension_proto is not extendee_proto.Extensions[extension]) def testExtensionFailureModes(self): extendee_proto = unittest_pb2.TestAllExtensions() # Try non-extension-handle arguments to HasExtension, # ClearExtension(), and Extensions[]... self.assertRaises(KeyError, extendee_proto.HasExtension, 1234) self.assertRaises(KeyError, extendee_proto.ClearExtension, 1234) self.assertRaises(KeyError, extendee_proto.Extensions.__getitem__, 1234) self.assertRaises(KeyError, extendee_proto.Extensions.__setitem__, 1234, 5) # Try something that *is* an extension handle, just not for # this message... unknown_handle = more_extensions_pb2.optional_int_extension self.assertRaises(KeyError, extendee_proto.HasExtension, unknown_handle) self.assertRaises(KeyError, extendee_proto.ClearExtension, unknown_handle) self.assertRaises(KeyError, extendee_proto.Extensions.__getitem__, unknown_handle) self.assertRaises(KeyError, extendee_proto.Extensions.__setitem__, unknown_handle, 5) # Try call HasExtension() with a valid handle, but for a # *repeated* field. (Just as with non-extension repeated # fields, Has*() isn't supported for extension repeated fields). self.assertRaises(KeyError, extendee_proto.HasExtension, unittest_pb2.repeated_string_extension) def testStaticParseFrom(self): proto1 = unittest_pb2.TestAllTypes() test_util.SetAllFields(proto1) string1 = proto1.SerializeToString() proto2 = unittest_pb2.TestAllTypes.FromString(string1) # Messages should be equal. self.assertEqual(proto2, proto1) def testMergeFromSingularField(self): # Test merge with just a singular field. proto1 = unittest_pb2.TestAllTypes() proto1.optional_int32 = 1 proto2 = unittest_pb2.TestAllTypes() # This shouldn't get overwritten. proto2.optional_string = 'value' proto2.MergeFrom(proto1) self.assertEqual(1, proto2.optional_int32) self.assertEqual('value', proto2.optional_string) def testMergeFromRepeatedField(self): # Test merge with just a repeated field. proto1 = unittest_pb2.TestAllTypes() proto1.repeated_int32.append(1) proto1.repeated_int32.append(2) proto2 = unittest_pb2.TestAllTypes() proto2.repeated_int32.append(0) proto2.MergeFrom(proto1) self.assertEqual(0, proto2.repeated_int32[0]) self.assertEqual(1, proto2.repeated_int32[1]) self.assertEqual(2, proto2.repeated_int32[2]) def testMergeFromOptionalGroup(self): # Test merge with an optional group. proto1 = unittest_pb2.TestAllTypes() proto1.optionalgroup.a = 12 proto2 = unittest_pb2.TestAllTypes() proto2.MergeFrom(proto1) self.assertEqual(12, proto2.optionalgroup.a) def testMergeFromRepeatedNestedMessage(self): # Test merge with a repeated nested message. proto1 = unittest_pb2.TestAllTypes() m = proto1.repeated_nested_message.add() m.bb = 123 m = proto1.repeated_nested_message.add() m.bb = 321 proto2 = unittest_pb2.TestAllTypes() m = proto2.repeated_nested_message.add() m.bb = 999 proto2.MergeFrom(proto1) self.assertEqual(999, proto2.repeated_nested_message[0].bb) self.assertEqual(123, proto2.repeated_nested_message[1].bb) self.assertEqual(321, proto2.repeated_nested_message[2].bb) proto3 = unittest_pb2.TestAllTypes() proto3.repeated_nested_message.MergeFrom(proto2.repeated_nested_message) self.assertEqual(999, proto3.repeated_nested_message[0].bb) self.assertEqual(123, proto3.repeated_nested_message[1].bb) self.assertEqual(321, proto3.repeated_nested_message[2].bb) def testMergeFromAllFields(self): # With all fields set. proto1 = unittest_pb2.TestAllTypes() test_util.SetAllFields(proto1) proto2 = unittest_pb2.TestAllTypes() proto2.MergeFrom(proto1) # Messages should be equal. self.assertEqual(proto2, proto1) # Serialized string should be equal too. string1 = proto1.SerializeToString() string2 = proto2.SerializeToString() self.assertEqual(string1, string2) def testMergeFromExtensionsSingular(self): proto1 = unittest_pb2.TestAllExtensions() proto1.Extensions[unittest_pb2.optional_int32_extension] = 1 proto2 = unittest_pb2.TestAllExtensions() proto2.MergeFrom(proto1) self.assertEqual( 1, proto2.Extensions[unittest_pb2.optional_int32_extension]) def testMergeFromExtensionsRepeated(self): proto1 = unittest_pb2.TestAllExtensions() proto1.Extensions[unittest_pb2.repeated_int32_extension].append(1) proto1.Extensions[unittest_pb2.repeated_int32_extension].append(2) proto2 = unittest_pb2.TestAllExtensions() proto2.Extensions[unittest_pb2.repeated_int32_extension].append(0) proto2.MergeFrom(proto1) self.assertEqual( 3, len(proto2.Extensions[unittest_pb2.repeated_int32_extension])) self.assertEqual( 0, proto2.Extensions[unittest_pb2.repeated_int32_extension][0]) self.assertEqual( 1, proto2.Extensions[unittest_pb2.repeated_int32_extension][1]) self.assertEqual( 2, proto2.Extensions[unittest_pb2.repeated_int32_extension][2]) def testMergeFromExtensionsNestedMessage(self): proto1 = unittest_pb2.TestAllExtensions() ext1 = proto1.Extensions[ unittest_pb2.repeated_nested_message_extension] m = ext1.add() m.bb = 222 m = ext1.add() m.bb = 333 proto2 = unittest_pb2.TestAllExtensions() ext2 = proto2.Extensions[ unittest_pb2.repeated_nested_message_extension] m = ext2.add() m.bb = 111 proto2.MergeFrom(proto1) ext2 = proto2.Extensions[ unittest_pb2.repeated_nested_message_extension] self.assertEqual(3, len(ext2)) self.assertEqual(111, ext2[0].bb) self.assertEqual(222, ext2[1].bb) self.assertEqual(333, ext2[2].bb) def testMergeFromBug(self): message1 = unittest_pb2.TestAllTypes() message2 = unittest_pb2.TestAllTypes() # Cause optional_nested_message to be instantiated within message1, even # though it is not considered to be "present". message1.optional_nested_message self.assertFalse(message1.HasField('optional_nested_message')) # Merge into message2. This should not instantiate the field is message2. message2.MergeFrom(message1) self.assertFalse(message2.HasField('optional_nested_message')) def testCopyFromSingularField(self): # Test copy with just a singular field. proto1 = unittest_pb2.TestAllTypes() proto1.optional_int32 = 1 proto1.optional_string = 'important-text' proto2 = unittest_pb2.TestAllTypes() proto2.optional_string = 'value' proto2.CopyFrom(proto1) self.assertEqual(1, proto2.optional_int32) self.assertEqual('important-text', proto2.optional_string) def testCopyFromRepeatedField(self): # Test copy with a repeated field. proto1 = unittest_pb2.TestAllTypes() proto1.repeated_int32.append(1) proto1.repeated_int32.append(2) proto2 = unittest_pb2.TestAllTypes() proto2.repeated_int32.append(0) proto2.CopyFrom(proto1) self.assertEqual(1, proto2.repeated_int32[0]) self.assertEqual(2, proto2.repeated_int32[1]) def testCopyFromAllFields(self): # With all fields set. proto1 = unittest_pb2.TestAllTypes() test_util.SetAllFields(proto1) proto2 = unittest_pb2.TestAllTypes() proto2.CopyFrom(proto1) # Messages should be equal. self.assertEqual(proto2, proto1) # Serialized string should be equal too. string1 = proto1.SerializeToString() string2 = proto2.SerializeToString() self.assertEqual(string1, string2) def testCopyFromSelf(self): proto1 = unittest_pb2.TestAllTypes() proto1.repeated_int32.append(1) proto1.optional_int32 = 2 proto1.optional_string = 'important-text' proto1.CopyFrom(proto1) self.assertEqual(1, proto1.repeated_int32[0]) self.assertEqual(2, proto1.optional_int32) self.assertEqual('important-text', proto1.optional_string) def testCopyFromBadType(self): # The python implementation doesn't raise an exception in this # case. In theory it should. if api_implementation.Type() == 'python': return proto1 = unittest_pb2.TestAllTypes() proto2 = unittest_pb2.TestAllExtensions() self.assertRaises(TypeError, proto1.CopyFrom, proto2) def testDeepCopy(self): proto1 = unittest_pb2.TestAllTypes() proto1.optional_int32 = 1 proto2 = copy.deepcopy(proto1) self.assertEqual(1, proto2.optional_int32) proto1.repeated_int32.append(2) proto1.repeated_int32.append(3) container = copy.deepcopy(proto1.repeated_int32) self.assertEqual([2, 3], container) # TODO(anuraag): Implement deepcopy for repeated composite / extension dict def testClear(self): proto = unittest_pb2.TestAllTypes() # C++ implementation does not support lazy fields right now so leave it # out for now. if api_implementation.Type() == 'python': test_util.SetAllFields(proto) else: test_util.SetAllNonLazyFields(proto) # Clear the message. proto.Clear() self.assertEquals(proto.ByteSize(), 0) empty_proto = unittest_pb2.TestAllTypes() self.assertEquals(proto, empty_proto) # Test if extensions which were set are cleared. proto = unittest_pb2.TestAllExtensions() test_util.SetAllExtensions(proto) # Clear the message. proto.Clear() self.assertEquals(proto.ByteSize(), 0) empty_proto = unittest_pb2.TestAllExtensions() self.assertEquals(proto, empty_proto) def testDisconnectingBeforeClear(self): proto = unittest_pb2.TestAllTypes() nested = proto.optional_nested_message proto.Clear() self.assertTrue(nested is not proto.optional_nested_message) nested.bb = 23 self.assertTrue(not proto.HasField('optional_nested_message')) self.assertEqual(0, proto.optional_nested_message.bb) proto = unittest_pb2.TestAllTypes() nested = proto.optional_nested_message nested.bb = 5 foreign = proto.optional_foreign_message foreign.c = 6 proto.Clear() self.assertTrue(nested is not proto.optional_nested_message) self.assertTrue(foreign is not proto.optional_foreign_message) self.assertEqual(5, nested.bb) self.assertEqual(6, foreign.c) nested.bb = 15 foreign.c = 16 self.assertFalse(proto.HasField('optional_nested_message')) self.assertEqual(0, proto.optional_nested_message.bb) self.assertFalse(proto.HasField('optional_foreign_message')) self.assertEqual(0, proto.optional_foreign_message.c) def testOneOf(self): proto = unittest_pb2.TestAllTypes() proto.oneof_uint32 = 10 proto.oneof_nested_message.bb = 11 self.assertEqual(11, proto.oneof_nested_message.bb) self.assertFalse(proto.HasField('oneof_uint32')) nested = proto.oneof_nested_message proto.oneof_string = 'abc' self.assertEqual('abc', proto.oneof_string) self.assertEqual(11, nested.bb) self.assertFalse(proto.HasField('oneof_nested_message')) def assertInitialized(self, proto): self.assertTrue(proto.IsInitialized()) # Neither method should raise an exception. proto.SerializeToString() proto.SerializePartialToString() def assertNotInitialized(self, proto): self.assertFalse(proto.IsInitialized()) # "Partial" serialization doesn't care if message is uninitialized. proto.SerializePartialToString() def testIsInitialized(self): # Trivial cases - all optional fields and extensions. proto = unittest_pb2.TestAllTypes() self.assertInitialized(proto) proto = unittest_pb2.TestAllExtensions() self.assertInitialized(proto) # The case of uninitialized required fields. proto = unittest_pb2.TestRequired() self.assertNotInitialized(proto) proto.a = proto.b = proto.c = 2 self.assertInitialized(proto) # The case of uninitialized submessage. proto = unittest_pb2.TestRequiredForeign() self.assertInitialized(proto) proto.optional_message.a = 1 self.assertNotInitialized(proto) proto.optional_message.b = 0 proto.optional_message.c = 0 self.assertInitialized(proto) # Uninitialized repeated submessage. message1 = proto.repeated_message.add() self.assertNotInitialized(proto) message1.a = message1.b = message1.c = 0 self.assertInitialized(proto) # Uninitialized repeated group in an extension. proto = unittest_pb2.TestAllExtensions() extension = unittest_pb2.TestRequired.multi message1 = proto.Extensions[extension].add() message2 = proto.Extensions[extension].add() self.assertNotInitialized(proto) message1.a = 1 message1.b = 1 message1.c = 1 self.assertNotInitialized(proto) message2.a = 2 message2.b = 2 message2.c = 2 self.assertInitialized(proto) # Uninitialized nonrepeated message in an extension. proto = unittest_pb2.TestAllExtensions() extension = unittest_pb2.TestRequired.single proto.Extensions[extension].a = 1 self.assertNotInitialized(proto) proto.Extensions[extension].b = 2 proto.Extensions[extension].c = 3 self.assertInitialized(proto) # Try passing an errors list. errors = [] proto = unittest_pb2.TestRequired() self.assertFalse(proto.IsInitialized(errors)) self.assertEqual(errors, ['a', 'b', 'c']) @basetest.unittest.skipIf( api_implementation.Type() != 'cpp' or api_implementation.Version() != 2, 'Errors are only available from the most recent C++ implementation.') def testFileDescriptorErrors(self): file_name = 'test_file_descriptor_errors.proto' package_name = 'test_file_descriptor_errors.proto' file_descriptor_proto = descriptor_pb2.FileDescriptorProto() file_descriptor_proto.name = file_name file_descriptor_proto.package = package_name m1 = file_descriptor_proto.message_type.add() m1.name = 'msg1' # Compiles the proto into the C++ descriptor pool descriptor.FileDescriptor( file_name, package_name, serialized_pb=file_descriptor_proto.SerializeToString()) # Add a FileDescriptorProto that has duplicate symbols another_file_name = 'another_test_file_descriptor_errors.proto' file_descriptor_proto.name = another_file_name m2 = file_descriptor_proto.message_type.add() m2.name = 'msg2' with self.assertRaises(TypeError) as cm: descriptor.FileDescriptor( another_file_name, package_name, serialized_pb=file_descriptor_proto.SerializeToString()) self.assertTrue(hasattr(cm, 'exception'), '%s not raised' % getattr(cm.expected, '__name__', cm.expected)) self.assertIn('test_file_descriptor_errors.proto', str(cm.exception)) # Error message will say something about this definition being a # duplicate, though we don't check the message exactly to avoid a # dependency on the C++ logging code. self.assertIn('test_file_descriptor_errors.msg1', str(cm.exception)) def testStringUTF8Encoding(self): proto = unittest_pb2.TestAllTypes() # Assignment of a unicode object to a field of type 'bytes' is not allowed. self.assertRaises(TypeError, setattr, proto, 'optional_bytes', u'unicode object') # Check that the default value is of python's 'unicode' type. self.assertEqual(type(proto.optional_string), unicode) proto.optional_string = unicode('Testing') self.assertEqual(proto.optional_string, str('Testing')) # Assign a value of type 'str' which can be encoded in UTF-8. proto.optional_string = str('Testing') self.assertEqual(proto.optional_string, unicode('Testing')) # Try to assign a 'str' value which contains bytes that aren't 7-bit ASCII. self.assertRaises(ValueError, setattr, proto, 'optional_string', b'a\x80a') if str is bytes: # PY2 # Assign a 'str' object which contains a UTF-8 encoded string. self.assertRaises(ValueError, setattr, proto, 'optional_string', 'Тест') else: proto.optional_string = 'Тест' # No exception thrown. proto.optional_string = 'abc' def testStringUTF8Serialization(self): proto = unittest_mset_pb2.TestMessageSet() extension_message = unittest_mset_pb2.TestMessageSetExtension2 extension = extension_message.message_set_extension test_utf8 = u'Тест' test_utf8_bytes = test_utf8.encode('utf-8') # 'Test' in another language, using UTF-8 charset. proto.Extensions[extension].str = test_utf8 # Serialize using the MessageSet wire format (this is specified in the # .proto file). serialized = proto.SerializeToString() # Check byte size. self.assertEqual(proto.ByteSize(), len(serialized)) raw = unittest_mset_pb2.RawMessageSet() bytes_read = raw.MergeFromString(serialized) self.assertEqual(len(serialized), bytes_read) message2 = unittest_mset_pb2.TestMessageSetExtension2() self.assertEqual(1, len(raw.item)) # Check that the type_id is the same as the tag ID in the .proto file. self.assertEqual(raw.item[0].type_id, 1547769) # Check the actual bytes on the wire. self.assertTrue( raw.item[0].message.endswith(test_utf8_bytes)) bytes_read = message2.MergeFromString(raw.item[0].message) self.assertEqual(len(raw.item[0].message), bytes_read) self.assertEqual(type(message2.str), unicode) self.assertEqual(message2.str, test_utf8) # The pure Python API throws an exception on MergeFromString(), # if any of the string fields of the message can't be UTF-8 decoded. # The C++ implementation of the API has no way to check that on # MergeFromString and thus has no way to throw the exception. # # The pure Python API always returns objects of type 'unicode' (UTF-8 # encoded), or 'bytes' (in 7 bit ASCII). badbytes = raw.item[0].message.replace( test_utf8_bytes, len(test_utf8_bytes) * b'\xff') unicode_decode_failed = False try: message2.MergeFromString(badbytes) except UnicodeDecodeError: unicode_decode_failed = True string_field = message2.str self.assertTrue(unicode_decode_failed or type(string_field) is bytes) def testBytesInTextFormat(self): proto = unittest_pb2.TestAllTypes(optional_bytes=b'\x00\x7f\x80\xff') self.assertEqual(u'optional_bytes: "\\000\\177\\200\\377"\n', unicode(proto)) def testEmptyNestedMessage(self): proto = unittest_pb2.TestAllTypes() proto.optional_nested_message.MergeFrom( unittest_pb2.TestAllTypes.NestedMessage()) self.assertTrue(proto.HasField('optional_nested_message')) proto = unittest_pb2.TestAllTypes() proto.optional_nested_message.CopyFrom( unittest_pb2.TestAllTypes.NestedMessage()) self.assertTrue(proto.HasField('optional_nested_message')) proto = unittest_pb2.TestAllTypes() bytes_read = proto.optional_nested_message.MergeFromString(b'') self.assertEqual(0, bytes_read) self.assertTrue(proto.HasField('optional_nested_message')) proto = unittest_pb2.TestAllTypes() proto.optional_nested_message.ParseFromString(b'') self.assertTrue(proto.HasField('optional_nested_message')) serialized = proto.SerializeToString() proto2 = unittest_pb2.TestAllTypes() self.assertEqual( len(serialized), proto2.MergeFromString(serialized)) self.assertTrue(proto2.HasField('optional_nested_message')) def testSetInParent(self): proto = unittest_pb2.TestAllTypes() self.assertFalse(proto.HasField('optionalgroup')) proto.optionalgroup.SetInParent() self.assertTrue(proto.HasField('optionalgroup')) # Since we had so many tests for protocol buffer equality, we broke these out # into separate TestCase classes. class TestAllTypesEqualityTest(basetest.TestCase): def setUp(self): self.first_proto = unittest_pb2.TestAllTypes() self.second_proto = unittest_pb2.TestAllTypes() def testNotHashable(self): self.assertRaises(TypeError, hash, self.first_proto) def testSelfEquality(self): self.assertEqual(self.first_proto, self.first_proto) def testEmptyProtosEqual(self): self.assertEqual(self.first_proto, self.second_proto) class FullProtosEqualityTest(basetest.TestCase): """Equality tests using completely-full protos as a starting point.""" def setUp(self): self.first_proto = unittest_pb2.TestAllTypes() self.second_proto = unittest_pb2.TestAllTypes() test_util.SetAllFields(self.first_proto) test_util.SetAllFields(self.second_proto) def testNotHashable(self): self.assertRaises(TypeError, hash, self.first_proto) def testNoneNotEqual(self): self.assertNotEqual(self.first_proto, None) self.assertNotEqual(None, self.second_proto) def testNotEqualToOtherMessage(self): third_proto = unittest_pb2.TestRequired() self.assertNotEqual(self.first_proto, third_proto) self.assertNotEqual(third_proto, self.second_proto) def testAllFieldsFilledEquality(self): self.assertEqual(self.first_proto, self.second_proto) def testNonRepeatedScalar(self): # Nonrepeated scalar field change should cause inequality. self.first_proto.optional_int32 += 1 self.assertNotEqual(self.first_proto, self.second_proto) # ...as should clearing a field. self.first_proto.ClearField('optional_int32') self.assertNotEqual(self.first_proto, self.second_proto) def testNonRepeatedComposite(self): # Change a nonrepeated composite field. self.first_proto.optional_nested_message.bb += 1 self.assertNotEqual(self.first_proto, self.second_proto) self.first_proto.optional_nested_message.bb -= 1 self.assertEqual(self.first_proto, self.second_proto) # Clear a field in the nested message. self.first_proto.optional_nested_message.ClearField('bb') self.assertNotEqual(self.first_proto, self.second_proto) self.first_proto.optional_nested_message.bb = ( self.second_proto.optional_nested_message.bb) self.assertEqual(self.first_proto, self.second_proto) # Remove the nested message entirely. self.first_proto.ClearField('optional_nested_message') self.assertNotEqual(self.first_proto, self.second_proto) def testRepeatedScalar(self): # Change a repeated scalar field. self.first_proto.repeated_int32.append(5) self.assertNotEqual(self.first_proto, self.second_proto) self.first_proto.ClearField('repeated_int32') self.assertNotEqual(self.first_proto, self.second_proto) def testRepeatedComposite(self): # Change value within a repeated composite field. self.first_proto.repeated_nested_message[0].bb += 1 self.assertNotEqual(self.first_proto, self.second_proto) self.first_proto.repeated_nested_message[0].bb -= 1 self.assertEqual(self.first_proto, self.second_proto) # Add a value to a repeated composite field. self.first_proto.repeated_nested_message.add() self.assertNotEqual(self.first_proto, self.second_proto) self.second_proto.repeated_nested_message.add() self.assertEqual(self.first_proto, self.second_proto) def testNonRepeatedScalarHasBits(self): # Ensure that we test "has" bits as well as value for # nonrepeated scalar field. self.first_proto.ClearField('optional_int32') self.second_proto.optional_int32 = 0 self.assertNotEqual(self.first_proto, self.second_proto) def testNonRepeatedCompositeHasBits(self): # Ensure that we test "has" bits as well as value for # nonrepeated composite field. self.first_proto.ClearField('optional_nested_message') self.second_proto.optional_nested_message.ClearField('bb') self.assertNotEqual(self.first_proto, self.second_proto) self.first_proto.optional_nested_message.bb = 0 self.first_proto.optional_nested_message.ClearField('bb') self.assertEqual(self.first_proto, self.second_proto) class ExtensionEqualityTest(basetest.TestCase): def testExtensionEquality(self): first_proto = unittest_pb2.TestAllExtensions() second_proto = unittest_pb2.TestAllExtensions() self.assertEqual(first_proto, second_proto) test_util.SetAllExtensions(first_proto) self.assertNotEqual(first_proto, second_proto) test_util.SetAllExtensions(second_proto) self.assertEqual(first_proto, second_proto) # Ensure that we check value equality. first_proto.Extensions[unittest_pb2.optional_int32_extension] += 1 self.assertNotEqual(first_proto, second_proto) first_proto.Extensions[unittest_pb2.optional_int32_extension] -= 1 self.assertEqual(first_proto, second_proto) # Ensure that we also look at "has" bits. first_proto.ClearExtension(unittest_pb2.optional_int32_extension) second_proto.Extensions[unittest_pb2.optional_int32_extension] = 0 self.assertNotEqual(first_proto, second_proto) first_proto.Extensions[unittest_pb2.optional_int32_extension] = 0 self.assertEqual(first_proto, second_proto) # Ensure that differences in cached values # don't matter if "has" bits are both false. first_proto = unittest_pb2.TestAllExtensions() second_proto = unittest_pb2.TestAllExtensions() self.assertEqual( 0, first_proto.Extensions[unittest_pb2.optional_int32_extension]) self.assertEqual(first_proto, second_proto) class MutualRecursionEqualityTest(basetest.TestCase): def testEqualityWithMutualRecursion(self): first_proto = unittest_pb2.TestMutualRecursionA() second_proto = unittest_pb2.TestMutualRecursionA() self.assertEqual(first_proto, second_proto) first_proto.bb.a.bb.optional_int32 = 23 self.assertNotEqual(first_proto, second_proto) second_proto.bb.a.bb.optional_int32 = 23 self.assertEqual(first_proto, second_proto) class ByteSizeTest(basetest.TestCase): def setUp(self): self.proto = unittest_pb2.TestAllTypes() self.extended_proto = more_extensions_pb2.ExtendedMessage() self.packed_proto = unittest_pb2.TestPackedTypes() self.packed_extended_proto = unittest_pb2.TestPackedExtensions() def Size(self): return self.proto.ByteSize() def testEmptyMessage(self): self.assertEqual(0, self.proto.ByteSize()) def testSizedOnKwargs(self): # Use a separate message to ensure testing right after creation. proto = unittest_pb2.TestAllTypes() self.assertEqual(0, proto.ByteSize()) proto_kwargs = unittest_pb2.TestAllTypes(optional_int64 = 1) # One byte for the tag, one to encode varint 1. self.assertEqual(2, proto_kwargs.ByteSize()) def testVarints(self): def Test(i, expected_varint_size): self.proto.Clear() self.proto.optional_int64 = i # Add one to the varint size for the tag info # for tag 1. self.assertEqual(expected_varint_size + 1, self.Size()) Test(0, 1) Test(1, 1) for i, num_bytes in zip(range(7, 63, 7), range(1, 10000)): Test((1 << i) - 1, num_bytes) Test(-1, 10) Test(-2, 10) Test(-(1 << 63), 10) def testStrings(self): self.proto.optional_string = '' # Need one byte for tag info (tag #14), and one byte for length. self.assertEqual(2, self.Size()) self.proto.optional_string = 'abc' # Need one byte for tag info (tag #14), and one byte for length. self.assertEqual(2 + len(self.proto.optional_string), self.Size()) self.proto.optional_string = 'x' * 128 # Need one byte for tag info (tag #14), and TWO bytes for length. self.assertEqual(3 + len(self.proto.optional_string), self.Size()) def testOtherNumerics(self): self.proto.optional_fixed32 = 1234 # One byte for tag and 4 bytes for fixed32. self.assertEqual(5, self.Size()) self.proto = unittest_pb2.TestAllTypes() self.proto.optional_fixed64 = 1234 # One byte for tag and 8 bytes for fixed64. self.assertEqual(9, self.Size()) self.proto = unittest_pb2.TestAllTypes() self.proto.optional_float = 1.234 # One byte for tag and 4 bytes for float. self.assertEqual(5, self.Size()) self.proto = unittest_pb2.TestAllTypes() self.proto.optional_double = 1.234 # One byte for tag and 8 bytes for float. self.assertEqual(9, self.Size()) self.proto = unittest_pb2.TestAllTypes() self.proto.optional_sint32 = 64 # One byte for tag and 2 bytes for zig-zag-encoded 64. self.assertEqual(3, self.Size()) self.proto = unittest_pb2.TestAllTypes() def testComposites(self): # 3 bytes. self.proto.optional_nested_message.bb = (1 << 14) # Plus one byte for bb tag. # Plus 1 byte for optional_nested_message serialized size. # Plus two bytes for optional_nested_message tag. self.assertEqual(3 + 1 + 1 + 2, self.Size()) def testGroups(self): # 4 bytes. self.proto.optionalgroup.a = (1 << 21) # Plus two bytes for |a| tag. # Plus 2 * two bytes for START_GROUP and END_GROUP tags. self.assertEqual(4 + 2 + 2*2, self.Size()) def testRepeatedScalars(self): self.proto.repeated_int32.append(10) # 1 byte. self.proto.repeated_int32.append(128) # 2 bytes. # Also need 2 bytes for each entry for tag. self.assertEqual(1 + 2 + 2*2, self.Size()) def testRepeatedScalarsExtend(self): self.proto.repeated_int32.extend([10, 128]) # 3 bytes. # Also need 2 bytes for each entry for tag. self.assertEqual(1 + 2 + 2*2, self.Size()) def testRepeatedScalarsRemove(self): self.proto.repeated_int32.append(10) # 1 byte. self.proto.repeated_int32.append(128) # 2 bytes. # Also need 2 bytes for each entry for tag. self.assertEqual(1 + 2 + 2*2, self.Size()) self.proto.repeated_int32.remove(128) self.assertEqual(1 + 2, self.Size()) def testRepeatedComposites(self): # Empty message. 2 bytes tag plus 1 byte length. foreign_message_0 = self.proto.repeated_nested_message.add() # 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int. foreign_message_1 = self.proto.repeated_nested_message.add() foreign_message_1.bb = 7 self.assertEqual(2 + 1 + 2 + 1 + 1 + 1, self.Size()) def testRepeatedCompositesDelete(self): # Empty message. 2 bytes tag plus 1 byte length. foreign_message_0 = self.proto.repeated_nested_message.add() # 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int. foreign_message_1 = self.proto.repeated_nested_message.add() foreign_message_1.bb = 9 self.assertEqual(2 + 1 + 2 + 1 + 1 + 1, self.Size()) # 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int. del self.proto.repeated_nested_message[0] self.assertEqual(2 + 1 + 1 + 1, self.Size()) # Now add a new message. foreign_message_2 = self.proto.repeated_nested_message.add() foreign_message_2.bb = 12 # 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int. # 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int. self.assertEqual(2 + 1 + 1 + 1 + 2 + 1 + 1 + 1, self.Size()) # 2 bytes tag plus 1 byte length plus 1 byte bb tag 1 byte int. del self.proto.repeated_nested_message[1] self.assertEqual(2 + 1 + 1 + 1, self.Size()) del self.proto.repeated_nested_message[0] self.assertEqual(0, self.Size()) def testRepeatedGroups(self): # 2-byte START_GROUP plus 2-byte END_GROUP. group_0 = self.proto.repeatedgroup.add() # 2-byte START_GROUP plus 2-byte |a| tag + 1-byte |a| # plus 2-byte END_GROUP. group_1 = self.proto.repeatedgroup.add() group_1.a = 7 self.assertEqual(2 + 2 + 2 + 2 + 1 + 2, self.Size()) def testExtensions(self): proto = unittest_pb2.TestAllExtensions() self.assertEqual(0, proto.ByteSize()) extension = unittest_pb2.optional_int32_extension # Field #1, 1 byte. proto.Extensions[extension] = 23 # 1 byte for tag, 1 byte for value. self.assertEqual(2, proto.ByteSize()) def testCacheInvalidationForNonrepeatedScalar(self): # Test non-extension. self.proto.optional_int32 = 1 self.assertEqual(2, self.proto.ByteSize()) self.proto.optional_int32 = 128 self.assertEqual(3, self.proto.ByteSize()) self.proto.ClearField('optional_int32') self.assertEqual(0, self.proto.ByteSize()) # Test within extension. extension = more_extensions_pb2.optional_int_extension self.extended_proto.Extensions[extension] = 1 self.assertEqual(2, self.extended_proto.ByteSize()) self.extended_proto.Extensions[extension] = 128 self.assertEqual(3, self.extended_proto.ByteSize()) self.extended_proto.ClearExtension(extension) self.assertEqual(0, self.extended_proto.ByteSize()) def testCacheInvalidationForRepeatedScalar(self): # Test non-extension. self.proto.repeated_int32.append(1) self.assertEqual(3, self.proto.ByteSize()) self.proto.repeated_int32.append(1) self.assertEqual(6, self.proto.ByteSize()) self.proto.repeated_int32[1] = 128 self.assertEqual(7, self.proto.ByteSize()) self.proto.ClearField('repeated_int32') self.assertEqual(0, self.proto.ByteSize()) # Test within extension. extension = more_extensions_pb2.repeated_int_extension repeated = self.extended_proto.Extensions[extension] repeated.append(1) self.assertEqual(2, self.extended_proto.ByteSize()) repeated.append(1) self.assertEqual(4, self.extended_proto.ByteSize()) repeated[1] = 128 self.assertEqual(5, self.extended_proto.ByteSize()) self.extended_proto.ClearExtension(extension) self.assertEqual(0, self.extended_proto.ByteSize()) def testCacheInvalidationForNonrepeatedMessage(self): # Test non-extension. self.proto.optional_foreign_message.c = 1 self.assertEqual(5, self.proto.ByteSize()) self.proto.optional_foreign_message.c = 128 self.assertEqual(6, self.proto.ByteSize()) self.proto.optional_foreign_message.ClearField('c') self.assertEqual(3, self.proto.ByteSize()) self.proto.ClearField('optional_foreign_message') self.assertEqual(0, self.proto.ByteSize()) if api_implementation.Type() == 'python': # This is only possible in pure-Python implementation of the API. child = self.proto.optional_foreign_message self.proto.ClearField('optional_foreign_message') child.c = 128 self.assertEqual(0, self.proto.ByteSize()) # Test within extension. extension = more_extensions_pb2.optional_message_extension child = self.extended_proto.Extensions[extension] self.assertEqual(0, self.extended_proto.ByteSize()) child.foreign_message_int = 1 self.assertEqual(4, self.extended_proto.ByteSize()) child.foreign_message_int = 128 self.assertEqual(5, self.extended_proto.ByteSize()) self.extended_proto.ClearExtension(extension) self.assertEqual(0, self.extended_proto.ByteSize()) def testCacheInvalidationForRepeatedMessage(self): # Test non-extension. child0 = self.proto.repeated_foreign_message.add() self.assertEqual(3, self.proto.ByteSize()) self.proto.repeated_foreign_message.add() self.assertEqual(6, self.proto.ByteSize()) child0.c = 1 self.assertEqual(8, self.proto.ByteSize()) self.proto.ClearField('repeated_foreign_message') self.assertEqual(0, self.proto.ByteSize()) # Test within extension. extension = more_extensions_pb2.repeated_message_extension child_list = self.extended_proto.Extensions[extension] child0 = child_list.add() self.assertEqual(2, self.extended_proto.ByteSize()) child_list.add() self.assertEqual(4, self.extended_proto.ByteSize()) child0.foreign_message_int = 1 self.assertEqual(6, self.extended_proto.ByteSize()) child0.ClearField('foreign_message_int') self.assertEqual(4, self.extended_proto.ByteSize()) self.extended_proto.ClearExtension(extension) self.assertEqual(0, self.extended_proto.ByteSize()) def testPackedRepeatedScalars(self): self.assertEqual(0, self.packed_proto.ByteSize()) self.packed_proto.packed_int32.append(10) # 1 byte. self.packed_proto.packed_int32.append(128) # 2 bytes. # The tag is 2 bytes (the field number is 90), and the varint # storing the length is 1 byte. int_size = 1 + 2 + 3 self.assertEqual(int_size, self.packed_proto.ByteSize()) self.packed_proto.packed_double.append(4.2) # 8 bytes self.packed_proto.packed_double.append(3.25) # 8 bytes # 2 more tag bytes, 1 more length byte. double_size = 8 + 8 + 3 self.assertEqual(int_size+double_size, self.packed_proto.ByteSize()) self.packed_proto.ClearField('packed_int32') self.assertEqual(double_size, self.packed_proto.ByteSize()) def testPackedExtensions(self): self.assertEqual(0, self.packed_extended_proto.ByteSize()) extension = self.packed_extended_proto.Extensions[ unittest_pb2.packed_fixed32_extension] extension.extend([1, 2, 3, 4]) # 16 bytes # Tag is 3 bytes. self.assertEqual(19, self.packed_extended_proto.ByteSize()) # Issues to be sure to cover include: # * Handling of unrecognized tags ("uninterpreted_bytes"). # * Handling of MessageSets. # * Consistent ordering of tags in the wire format, # including ordering between extensions and non-extension # fields. # * Consistent serialization of negative numbers, especially # negative int32s. # * Handling of empty submessages (with and without "has" # bits set). class SerializationTest(basetest.TestCase): def testSerializeEmtpyMessage(self): first_proto = unittest_pb2.TestAllTypes() second_proto = unittest_pb2.TestAllTypes() serialized = first_proto.SerializeToString() self.assertEqual(first_proto.ByteSize(), len(serialized)) self.assertEqual( len(serialized), second_proto.MergeFromString(serialized)) self.assertEqual(first_proto, second_proto) def testSerializeAllFields(self): first_proto = unittest_pb2.TestAllTypes() second_proto = unittest_pb2.TestAllTypes() test_util.SetAllFields(first_proto) serialized = first_proto.SerializeToString() self.assertEqual(first_proto.ByteSize(), len(serialized)) self.assertEqual( len(serialized), second_proto.MergeFromString(serialized)) self.assertEqual(first_proto, second_proto) def testSerializeAllExtensions(self): first_proto = unittest_pb2.TestAllExtensions() second_proto = unittest_pb2.TestAllExtensions() test_util.SetAllExtensions(first_proto) serialized = first_proto.SerializeToString() self.assertEqual( len(serialized), second_proto.MergeFromString(serialized)) self.assertEqual(first_proto, second_proto) def testSerializeWithOptionalGroup(self): first_proto = unittest_pb2.TestAllTypes() second_proto = unittest_pb2.TestAllTypes() first_proto.optionalgroup.a = 242 serialized = first_proto.SerializeToString() self.assertEqual( len(serialized), second_proto.MergeFromString(serialized)) self.assertEqual(first_proto, second_proto) def testSerializeNegativeValues(self): first_proto = unittest_pb2.TestAllTypes() first_proto.optional_int32 = -1 first_proto.optional_int64 = -(2 << 40) first_proto.optional_sint32 = -3 first_proto.optional_sint64 = -(4 << 40) first_proto.optional_sfixed32 = -5 first_proto.optional_sfixed64 = -(6 << 40) second_proto = unittest_pb2.TestAllTypes.FromString( first_proto.SerializeToString()) self.assertEqual(first_proto, second_proto) def testParseTruncated(self): # This test is only applicable for the Python implementation of the API. if api_implementation.Type() != 'python': return first_proto = unittest_pb2.TestAllTypes() test_util.SetAllFields(first_proto) serialized = first_proto.SerializeToString() for truncation_point in xrange(len(serialized) + 1): try: second_proto = unittest_pb2.TestAllTypes() unknown_fields = unittest_pb2.TestEmptyMessage() pos = second_proto._InternalParse(serialized, 0, truncation_point) # If we didn't raise an error then we read exactly the amount expected. self.assertEqual(truncation_point, pos) # Parsing to unknown fields should not throw if parsing to known fields # did not. try: pos2 = unknown_fields._InternalParse(serialized, 0, truncation_point) self.assertEqual(truncation_point, pos2) except message.DecodeError: self.fail('Parsing unknown fields failed when parsing known fields ' 'did not.') except message.DecodeError: # Parsing unknown fields should also fail. self.assertRaises(message.DecodeError, unknown_fields._InternalParse, serialized, 0, truncation_point) def testCanonicalSerializationOrder(self): proto = more_messages_pb2.OutOfOrderFields() # These are also their tag numbers. Even though we're setting these in # reverse-tag order AND they're listed in reverse tag-order in the .proto # file, they should nonetheless be serialized in tag order. proto.optional_sint32 = 5 proto.Extensions[more_messages_pb2.optional_uint64] = 4 proto.optional_uint32 = 3 proto.Extensions[more_messages_pb2.optional_int64] = 2 proto.optional_int32 = 1 serialized = proto.SerializeToString() self.assertEqual(proto.ByteSize(), len(serialized)) d = _MiniDecoder(serialized) ReadTag = d.ReadFieldNumberAndWireType self.assertEqual((1, wire_format.WIRETYPE_VARINT), ReadTag()) self.assertEqual(1, d.ReadInt32()) self.assertEqual((2, wire_format.WIRETYPE_VARINT), ReadTag()) self.assertEqual(2, d.ReadInt64()) self.assertEqual((3, wire_format.WIRETYPE_VARINT), ReadTag()) self.assertEqual(3, d.ReadUInt32()) self.assertEqual((4, wire_format.WIRETYPE_VARINT), ReadTag()) self.assertEqual(4, d.ReadUInt64()) self.assertEqual((5, wire_format.WIRETYPE_VARINT), ReadTag()) self.assertEqual(5, d.ReadSInt32()) def testCanonicalSerializationOrderSameAsCpp(self): # Copy of the same test we use for C++. proto = unittest_pb2.TestFieldOrderings() test_util.SetAllFieldsAndExtensions(proto) serialized = proto.SerializeToString() test_util.ExpectAllFieldsAndExtensionsInOrder(serialized) def testMergeFromStringWhenFieldsAlreadySet(self): first_proto = unittest_pb2.TestAllTypes() first_proto.repeated_string.append('foobar') first_proto.optional_int32 = 23 first_proto.optional_nested_message.bb = 42 serialized = first_proto.SerializeToString() second_proto = unittest_pb2.TestAllTypes() second_proto.repeated_string.append('baz') second_proto.optional_int32 = 100 second_proto.optional_nested_message.bb = 999 bytes_parsed = second_proto.MergeFromString(serialized) self.assertEqual(len(serialized), bytes_parsed) # Ensure that we append to repeated fields. self.assertEqual(['baz', 'foobar'], list(second_proto.repeated_string)) # Ensure that we overwrite nonrepeatd scalars. self.assertEqual(23, second_proto.optional_int32) # Ensure that we recursively call MergeFromString() on # submessages. self.assertEqual(42, second_proto.optional_nested_message.bb) def testMessageSetWireFormat(self): proto = unittest_mset_pb2.TestMessageSet() extension_message1 = unittest_mset_pb2.TestMessageSetExtension1 extension_message2 = unittest_mset_pb2.TestMessageSetExtension2 extension1 = extension_message1.message_set_extension extension2 = extension_message2.message_set_extension proto.Extensions[extension1].i = 123 proto.Extensions[extension2].str = 'foo' # Serialize using the MessageSet wire format (this is specified in the # .proto file). serialized = proto.SerializeToString() raw = unittest_mset_pb2.RawMessageSet() self.assertEqual(False, raw.DESCRIPTOR.GetOptions().message_set_wire_format) self.assertEqual( len(serialized), raw.MergeFromString(serialized)) self.assertEqual(2, len(raw.item)) message1 = unittest_mset_pb2.TestMessageSetExtension1() self.assertEqual( len(raw.item[0].message), message1.MergeFromString(raw.item[0].message)) self.assertEqual(123, message1.i) message2 = unittest_mset_pb2.TestMessageSetExtension2() self.assertEqual( len(raw.item[1].message), message2.MergeFromString(raw.item[1].message)) self.assertEqual('foo', message2.str) # Deserialize using the MessageSet wire format. proto2 = unittest_mset_pb2.TestMessageSet() self.assertEqual( len(serialized), proto2.MergeFromString(serialized)) self.assertEqual(123, proto2.Extensions[extension1].i) self.assertEqual('foo', proto2.Extensions[extension2].str) # Check byte size. self.assertEqual(proto2.ByteSize(), len(serialized)) self.assertEqual(proto.ByteSize(), len(serialized)) def testMessageSetWireFormatUnknownExtension(self): # Create a message using the message set wire format with an unknown # message. raw = unittest_mset_pb2.RawMessageSet() # Add an item. item = raw.item.add() item.type_id = 1545008 extension_message1 = unittest_mset_pb2.TestMessageSetExtension1 message1 = unittest_mset_pb2.TestMessageSetExtension1() message1.i = 12345 item.message = message1.SerializeToString() # Add a second, unknown extension. item = raw.item.add() item.type_id = 1545009 extension_message1 = unittest_mset_pb2.TestMessageSetExtension1 message1 = unittest_mset_pb2.TestMessageSetExtension1() message1.i = 12346 item.message = message1.SerializeToString() # Add another unknown extension. item = raw.item.add() item.type_id = 1545010 message1 = unittest_mset_pb2.TestMessageSetExtension2() message1.str = 'foo' item.message = message1.SerializeToString() serialized = raw.SerializeToString() # Parse message using the message set wire format. proto = unittest_mset_pb2.TestMessageSet() self.assertEqual( len(serialized), proto.MergeFromString(serialized)) # Check that the message parsed well. extension_message1 = unittest_mset_pb2.TestMessageSetExtension1 extension1 = extension_message1.message_set_extension self.assertEquals(12345, proto.Extensions[extension1].i) def testUnknownFields(self): proto = unittest_pb2.TestAllTypes() test_util.SetAllFields(proto) serialized = proto.SerializeToString() # The empty message should be parsable with all of the fields # unknown. proto2 = unittest_pb2.TestEmptyMessage() # Parsing this message should succeed. self.assertEqual( len(serialized), proto2.MergeFromString(serialized)) # Now test with a int64 field set. proto = unittest_pb2.TestAllTypes() proto.optional_int64 = 0x0fffffffffffffff serialized = proto.SerializeToString() # The empty message should be parsable with all of the fields # unknown. proto2 = unittest_pb2.TestEmptyMessage() # Parsing this message should succeed. self.assertEqual( len(serialized), proto2.MergeFromString(serialized)) def _CheckRaises(self, exc_class, callable_obj, exception): """This method checks if the excpetion type and message are as expected.""" try: callable_obj() except exc_class as ex: # Check if the exception message is the right one. self.assertEqual(exception, str(ex)) return else: raise self.failureException('%s not raised' % str(exc_class)) def testSerializeUninitialized(self): proto = unittest_pb2.TestRequired() # Shouldn't raise exceptions. partial = proto.SerializePartialToString() proto2 = unittest_pb2.TestRequired() self.assertFalse(proto2.HasField('a')) # proto2 ParseFromString does not check that required fields are set. proto2.ParseFromString(partial) self.assertFalse(proto2.HasField('a')) proto.a = 1 # Shouldn't raise exceptions. partial = proto.SerializePartialToString() proto.b = 2 # Shouldn't raise exceptions. partial = proto.SerializePartialToString() proto.c = 3 serialized = proto.SerializeToString() # Shouldn't raise exceptions. partial = proto.SerializePartialToString() proto2 = unittest_pb2.TestRequired() self.assertEqual( len(serialized), proto2.MergeFromString(serialized)) self.assertEqual(1, proto2.a) self.assertEqual(2, proto2.b) self.assertEqual(3, proto2.c) self.assertEqual( len(partial), proto2.MergeFromString(partial)) self.assertEqual(1, proto2.a) self.assertEqual(2, proto2.b) self.assertEqual(3, proto2.c) def testSerializeUninitializedSubMessage(self): proto = unittest_pb2.TestRequiredForeign() # Sub-message doesn't exist yet, so this succeeds. proto.SerializeToString() proto.optional_message.a = 1 proto.optional_message.b = 2 proto.optional_message.c = 3 proto.SerializeToString() proto.repeated_message.add().a = 1 proto.repeated_message.add().b = 2 proto.repeated_message[0].b = 2 proto.repeated_message[0].c = 3 proto.repeated_message[1].a = 1 proto.repeated_message[1].c = 3 proto.SerializeToString() def testSerializeAllPackedFields(self): first_proto = unittest_pb2.TestPackedTypes() second_proto = unittest_pb2.TestPackedTypes() test_util.SetAllPackedFields(first_proto) serialized = first_proto.SerializeToString() self.assertEqual(first_proto.ByteSize(), len(serialized)) bytes_read = second_proto.MergeFromString(serialized) self.assertEqual(second_proto.ByteSize(), bytes_read) self.assertEqual(first_proto, second_proto) def testSerializeAllPackedExtensions(self): first_proto = unittest_pb2.TestPackedExtensions() second_proto = unittest_pb2.TestPackedExtensions() test_util.SetAllPackedExtensions(first_proto) serialized = first_proto.SerializeToString() bytes_read = second_proto.MergeFromString(serialized) self.assertEqual(second_proto.ByteSize(), bytes_read) self.assertEqual(first_proto, second_proto) def testMergePackedFromStringWhenSomeFieldsAlreadySet(self): first_proto = unittest_pb2.TestPackedTypes() first_proto.packed_int32.extend([1, 2]) first_proto.packed_double.append(3.0) serialized = first_proto.SerializeToString() second_proto = unittest_pb2.TestPackedTypes() second_proto.packed_int32.append(3) second_proto.packed_double.extend([1.0, 2.0]) second_proto.packed_sint32.append(4) self.assertEqual( len(serialized), second_proto.MergeFromString(serialized)) self.assertEqual([3, 1, 2], second_proto.packed_int32) self.assertEqual([1.0, 2.0, 3.0], second_proto.packed_double) self.assertEqual([4], second_proto.packed_sint32) def testPackedFieldsWireFormat(self): proto = unittest_pb2.TestPackedTypes() proto.packed_int32.extend([1, 2, 150, 3]) # 1 + 1 + 2 + 1 bytes proto.packed_double.extend([1.0, 1000.0]) # 8 + 8 bytes proto.packed_float.append(2.0) # 4 bytes, will be before double serialized = proto.SerializeToString() self.assertEqual(proto.ByteSize(), len(serialized)) d = _MiniDecoder(serialized) ReadTag = d.ReadFieldNumberAndWireType self.assertEqual((90, wire_format.WIRETYPE_LENGTH_DELIMITED), ReadTag()) self.assertEqual(1+1+1+2, d.ReadInt32()) self.assertEqual(1, d.ReadInt32()) self.assertEqual(2, d.ReadInt32()) self.assertEqual(150, d.ReadInt32()) self.assertEqual(3, d.ReadInt32()) self.assertEqual((100, wire_format.WIRETYPE_LENGTH_DELIMITED), ReadTag()) self.assertEqual(4, d.ReadInt32()) self.assertEqual(2.0, d.ReadFloat()) self.assertEqual((101, wire_format.WIRETYPE_LENGTH_DELIMITED), ReadTag()) self.assertEqual(8+8, d.ReadInt32()) self.assertEqual(1.0, d.ReadDouble()) self.assertEqual(1000.0, d.ReadDouble()) self.assertTrue(d.EndOfStream()) def testParsePackedFromUnpacked(self): unpacked = unittest_pb2.TestUnpackedTypes() test_util.SetAllUnpackedFields(unpacked) packed = unittest_pb2.TestPackedTypes() serialized = unpacked.SerializeToString() self.assertEqual( len(serialized), packed.MergeFromString(serialized)) expected = unittest_pb2.TestPackedTypes() test_util.SetAllPackedFields(expected) self.assertEqual(expected, packed) def testParseUnpackedFromPacked(self): packed = unittest_pb2.TestPackedTypes() test_util.SetAllPackedFields(packed) unpacked = unittest_pb2.TestUnpackedTypes() serialized = packed.SerializeToString() self.assertEqual( len(serialized), unpacked.MergeFromString(serialized)) expected = unittest_pb2.TestUnpackedTypes() test_util.SetAllUnpackedFields(expected) self.assertEqual(expected, unpacked) def testFieldNumbers(self): proto = unittest_pb2.TestAllTypes() self.assertEqual(unittest_pb2.TestAllTypes.NestedMessage.BB_FIELD_NUMBER, 1) self.assertEqual(unittest_pb2.TestAllTypes.OPTIONAL_INT32_FIELD_NUMBER, 1) self.assertEqual(unittest_pb2.TestAllTypes.OPTIONALGROUP_FIELD_NUMBER, 16) self.assertEqual( unittest_pb2.TestAllTypes.OPTIONAL_NESTED_MESSAGE_FIELD_NUMBER, 18) self.assertEqual( unittest_pb2.TestAllTypes.OPTIONAL_NESTED_ENUM_FIELD_NUMBER, 21) self.assertEqual(unittest_pb2.TestAllTypes.REPEATED_INT32_FIELD_NUMBER, 31) self.assertEqual(unittest_pb2.TestAllTypes.REPEATEDGROUP_FIELD_NUMBER, 46) self.assertEqual( unittest_pb2.TestAllTypes.REPEATED_NESTED_MESSAGE_FIELD_NUMBER, 48) self.assertEqual( unittest_pb2.TestAllTypes.REPEATED_NESTED_ENUM_FIELD_NUMBER, 51) def testExtensionFieldNumbers(self): self.assertEqual(unittest_pb2.TestRequired.single.number, 1000) self.assertEqual(unittest_pb2.TestRequired.SINGLE_FIELD_NUMBER, 1000) self.assertEqual(unittest_pb2.TestRequired.multi.number, 1001) self.assertEqual(unittest_pb2.TestRequired.MULTI_FIELD_NUMBER, 1001) self.assertEqual(unittest_pb2.optional_int32_extension.number, 1) self.assertEqual(unittest_pb2.OPTIONAL_INT32_EXTENSION_FIELD_NUMBER, 1) self.assertEqual(unittest_pb2.optionalgroup_extension.number, 16) self.assertEqual(unittest_pb2.OPTIONALGROUP_EXTENSION_FIELD_NUMBER, 16) self.assertEqual(unittest_pb2.optional_nested_message_extension.number, 18) self.assertEqual( unittest_pb2.OPTIONAL_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 18) self.assertEqual(unittest_pb2.optional_nested_enum_extension.number, 21) self.assertEqual(unittest_pb2.OPTIONAL_NESTED_ENUM_EXTENSION_FIELD_NUMBER, 21) self.assertEqual(unittest_pb2.repeated_int32_extension.number, 31) self.assertEqual(unittest_pb2.REPEATED_INT32_EXTENSION_FIELD_NUMBER, 31) self.assertEqual(unittest_pb2.repeatedgroup_extension.number, 46) self.assertEqual(unittest_pb2.REPEATEDGROUP_EXTENSION_FIELD_NUMBER, 46) self.assertEqual(unittest_pb2.repeated_nested_message_extension.number, 48) self.assertEqual( unittest_pb2.REPEATED_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER, 48) self.assertEqual(unittest_pb2.repeated_nested_enum_extension.number, 51) self.assertEqual(unittest_pb2.REPEATED_NESTED_ENUM_EXTENSION_FIELD_NUMBER, 51) def testInitKwargs(self): proto = unittest_pb2.TestAllTypes( optional_int32=1, optional_string='foo', optional_bool=True, optional_bytes=b'bar', optional_nested_message=unittest_pb2.TestAllTypes.NestedMessage(bb=1), optional_foreign_message=unittest_pb2.ForeignMessage(c=1), optional_nested_enum=unittest_pb2.TestAllTypes.FOO, optional_foreign_enum=unittest_pb2.FOREIGN_FOO, repeated_int32=[1, 2, 3]) self.assertTrue(proto.IsInitialized()) self.assertTrue(proto.HasField('optional_int32')) self.assertTrue(proto.HasField('optional_string')) self.assertTrue(proto.HasField('optional_bool')) self.assertTrue(proto.HasField('optional_bytes')) self.assertTrue(proto.HasField('optional_nested_message')) self.assertTrue(proto.HasField('optional_foreign_message')) self.assertTrue(proto.HasField('optional_nested_enum')) self.assertTrue(proto.HasField('optional_foreign_enum')) self.assertEqual(1, proto.optional_int32) self.assertEqual('foo', proto.optional_string) self.assertEqual(True, proto.optional_bool) self.assertEqual(b'bar', proto.optional_bytes) self.assertEqual(1, proto.optional_nested_message.bb) self.assertEqual(1, proto.optional_foreign_message.c) self.assertEqual(unittest_pb2.TestAllTypes.FOO, proto.optional_nested_enum) self.assertEqual(unittest_pb2.FOREIGN_FOO, proto.optional_foreign_enum) self.assertEqual([1, 2, 3], proto.repeated_int32) def testInitArgsUnknownFieldName(self): def InitalizeEmptyMessageWithExtraKeywordArg(): unused_proto = unittest_pb2.TestEmptyMessage(unknown='unknown') self._CheckRaises(ValueError, InitalizeEmptyMessageWithExtraKeywordArg, 'Protocol message has no "unknown" field.') def testInitRequiredKwargs(self): proto = unittest_pb2.TestRequired(a=1, b=1, c=1) self.assertTrue(proto.IsInitialized()) self.assertTrue(proto.HasField('a')) self.assertTrue(proto.HasField('b')) self.assertTrue(proto.HasField('c')) self.assertTrue(not proto.HasField('dummy2')) self.assertEqual(1, proto.a) self.assertEqual(1, proto.b) self.assertEqual(1, proto.c) def testInitRequiredForeignKwargs(self): proto = unittest_pb2.TestRequiredForeign( optional_message=unittest_pb2.TestRequired(a=1, b=1, c=1)) self.assertTrue(proto.IsInitialized()) self.assertTrue(proto.HasField('optional_message')) self.assertTrue(proto.optional_message.IsInitialized()) self.assertTrue(proto.optional_message.HasField('a')) self.assertTrue(proto.optional_message.HasField('b')) self.assertTrue(proto.optional_message.HasField('c')) self.assertTrue(not proto.optional_message.HasField('dummy2')) self.assertEqual(unittest_pb2.TestRequired(a=1, b=1, c=1), proto.optional_message) self.assertEqual(1, proto.optional_message.a) self.assertEqual(1, proto.optional_message.b) self.assertEqual(1, proto.optional_message.c) def testInitRepeatedKwargs(self): proto = unittest_pb2.TestAllTypes(repeated_int32=[1, 2, 3]) self.assertTrue(proto.IsInitialized()) self.assertEqual(1, proto.repeated_int32[0]) self.assertEqual(2, proto.repeated_int32[1]) self.assertEqual(3, proto.repeated_int32[2]) class OptionsTest(basetest.TestCase): def testMessageOptions(self): proto = unittest_mset_pb2.TestMessageSet() self.assertEqual(True, proto.DESCRIPTOR.GetOptions().message_set_wire_format) proto = unittest_pb2.TestAllTypes() self.assertEqual(False, proto.DESCRIPTOR.GetOptions().message_set_wire_format) def testPackedOptions(self): proto = unittest_pb2.TestAllTypes() proto.optional_int32 = 1 proto.optional_double = 3.0 for field_descriptor, _ in proto.ListFields(): self.assertEqual(False, field_descriptor.GetOptions().packed) proto = unittest_pb2.TestPackedTypes() proto.packed_int32.append(1) proto.packed_double.append(3.0) for field_descriptor, _ in proto.ListFields(): self.assertEqual(True, field_descriptor.GetOptions().packed) self.assertEqual(reflection._FieldDescriptor.LABEL_REPEATED, field_descriptor.label) class ClassAPITest(basetest.TestCase): def testMakeClassWithNestedDescriptor(self): leaf_desc = descriptor.Descriptor('leaf', 'package.parent.child.leaf', '', containing_type=None, fields=[], nested_types=[], enum_types=[], extensions=[]) child_desc = descriptor.Descriptor('child', 'package.parent.child', '', containing_type=None, fields=[], nested_types=[leaf_desc], enum_types=[], extensions=[]) sibling_desc = descriptor.Descriptor('sibling', 'package.parent.sibling', '', containing_type=None, fields=[], nested_types=[], enum_types=[], extensions=[]) parent_desc = descriptor.Descriptor('parent', 'package.parent', '', containing_type=None, fields=[], nested_types=[child_desc, sibling_desc], enum_types=[], extensions=[]) message_class = reflection.MakeClass(parent_desc) self.assertIn('child', message_class.__dict__) self.assertIn('sibling', message_class.__dict__) self.assertIn('leaf', message_class.child.__dict__) def _GetSerializedFileDescriptor(self, name): """Get a serialized representation of a test FileDescriptorProto. Args: name: All calls to this must use a unique message name, to avoid collisions in the cpp descriptor pool. Returns: A string containing the serialized form of a test FileDescriptorProto. """ file_descriptor_str = ( 'message_type {' ' name: "' + name + '"' ' field {' ' name: "flat"' ' number: 1' ' label: LABEL_REPEATED' ' type: TYPE_UINT32' ' }' ' field {' ' name: "bar"' ' number: 2' ' label: LABEL_OPTIONAL' ' type: TYPE_MESSAGE' ' type_name: "Bar"' ' }' ' nested_type {' ' name: "Bar"' ' field {' ' name: "baz"' ' number: 3' ' label: LABEL_OPTIONAL' ' type: TYPE_MESSAGE' ' type_name: "Baz"' ' }' ' nested_type {' ' name: "Baz"' ' enum_type {' ' name: "deep_enum"' ' value {' ' name: "VALUE_A"' ' number: 0' ' }' ' }' ' field {' ' name: "deep"' ' number: 4' ' label: LABEL_OPTIONAL' ' type: TYPE_UINT32' ' }' ' }' ' }' '}') file_descriptor = descriptor_pb2.FileDescriptorProto() text_format.Merge(file_descriptor_str, file_descriptor) return file_descriptor.SerializeToString() def testParsingFlatClassWithExplicitClassDeclaration(self): """Test that the generated class can parse a flat message.""" file_descriptor = descriptor_pb2.FileDescriptorProto() file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('A')) msg_descriptor = descriptor.MakeDescriptor( file_descriptor.message_type[0]) class MessageClass(message.Message): __metaclass__ = reflection.GeneratedProtocolMessageType DESCRIPTOR = msg_descriptor msg = MessageClass() msg_str = ( 'flat: 0 ' 'flat: 1 ' 'flat: 2 ') text_format.Merge(msg_str, msg) self.assertEqual(msg.flat, [0, 1, 2]) def testParsingFlatClass(self): """Test that the generated class can parse a flat message.""" file_descriptor = descriptor_pb2.FileDescriptorProto() file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('B')) msg_descriptor = descriptor.MakeDescriptor( file_descriptor.message_type[0]) msg_class = reflection.MakeClass(msg_descriptor) msg = msg_class() msg_str = ( 'flat: 0 ' 'flat: 1 ' 'flat: 2 ') text_format.Merge(msg_str, msg) self.assertEqual(msg.flat, [0, 1, 2]) def testParsingNestedClass(self): """Test that the generated class can parse a nested message.""" file_descriptor = descriptor_pb2.FileDescriptorProto() file_descriptor.ParseFromString(self._GetSerializedFileDescriptor('C')) msg_descriptor = descriptor.MakeDescriptor( file_descriptor.message_type[0]) msg_class = reflection.MakeClass(msg_descriptor) msg = msg_class() msg_str = ( 'bar {' ' baz {' ' deep: 4' ' }' '}') text_format.Merge(msg_str, msg) self.assertEqual(msg.bar.baz.deep, 4) if __name__ == '__main__': basetest.main()<|fim▁end|>
# support lazy parsing, but the current C++ implementation results in
<|file_name|>ermcfg.py<|end_file_name|><|fim▁begin|>''' Config/Settings for ER Tweet Matching Service ''' from datetime import date # GLOBAL # Maximum size a database can grow to (should be a multiple of 10MB) MAX_DB_SIZE = 10485760 * 1000 * 100 # 10MB -> 10GB -> 1TB ## ER SERVICE # Credentials ER_USER = '[email protected]' ER_PASS = '' # Log ER Requests? ER_LOG = False # Seconds to wait between consecutive page requests ER_WAIT_BETWEEN_REQUESTS = 0.5 # Database file that stores event registry url-eventid map ER_URL_DB_FILENAME = 'er.en.url.db' ER_URL_DB_FILENAME = '/media/rei/data/er_match/er.en.url.db' ER_URL_DB_FILENAME = '/media/storage/DATA/symphony/er_match/er.en.url.db' # Database file that stores date-eventid mappings ER_DATE_DB_FILENAME = 'er.en.date.db' ER_DATE_DB_FILENAME = '/media/rei/data/er_match/er.en.date.db' # Database file that stores eventid-centroid (english) mappings (Hash) ER_CENTROID_EN_DB_FILENAME = 'er.en.centroid.db' ER_CENTROID_EN_DB_FILENAME = '/media/rei/data/er_match/er.en.centroid.db' ER_CENTROID_EN_DB_FILENAME = '/media/storage/DATA/symphony/er_match/er.en.centroid.db' # Database that stores the days that have been fetched ER_STATUS_DB_FILENAME = 'er.status.db' ER_STATUS_DB_FILENAME = '/media/rei/data/er_match/er.status.db' # Start fetching (archive mode) Event Registry Events from this date<|fim▁hole|>END_DATE = date(2015, 1, 31) # Days of Event date to fetch at once in batch mode BATCH_INTERVAL = 1 # Socket timeout (seconds) SOCKET_TIMEOUT = 120.0 # Wait time between requests after a timneout REQUEST_SLEEP = 60 # Number of events-articles to fetch per request ARTICLES_BATCH_SIZE = 200 # Number of URLs to request per Page URLS_PER_PAGE = 200 # 200 should be the maximum set by the server # Number of Events to ask for the URL in online mode EVENTS_BATCH_SIZE = 40 ## TWEET SERVICE # Database that stores tweets and the archive files that have been read TWEET_DB_FILENAME = 'tweets.db' TWEET_DB_FILENAME = '/media/rei/data/er_match/tweets.db' TWEET_DB_FILENAME = '/media/storage/DATA/symphony/er_match/tweets.db' # Database that stores the loaded archive file names ARCHIVE_DB_FILENAME = 'archives.db' ARCHIVE_DB_FILENAME = '/media/rei/data/er_match/archives.db' # The directory of twitter observatory archive files (crawler archives) #ARCHIVE_DIR = '../tweets' ARCHIVE_DIR = '/media/rei/data/er_match/tweets/' ARCHIVE_DIR = '/media/storage/DATA/symphony/er_match/tweets/' # Determines how often an archive directory is checked (seconds) ARCHIVE_LOAD_INTERVAL = 60 * 2 ## MATCH SERVICE # How many days after an event can it be matched to a tweet MATCH_DAYS_BEFORE = 3 MATCH_URL_DB_FILENAME = 'match.url.db' MATCH_URL_DB_FILENAME = '/media/rei/data/er_match/match.url.db' MATCH_URL_DB_FILENAME = '/media/storage/DATA/symphony/er_match/match.url.db'<|fim▁end|>
START_DATE = date(2014, 11, 1) # End fetching (archive mode) at date #END_DATETIME = datetime.date.today()
<|file_name|>engine.js<|end_file_name|><|fim▁begin|>exports.engine = function(version){<|fim▁hole|> case '0.8.2': return require('./0.8.2').engine; default: return null; } };<|fim▁end|>
version = version || null; switch (version){ case null:
<|file_name|>trainobject.py<|end_file_name|><|fim▁begin|>from .stopper import EarlyStopper from .progbar import ProgressBar from .utils import split_arr from .data_iterator import SequentialIterator from tensorflow.python.framework import ops import tensorflow as tf import logging logging.basicConfig(format='%(module)s.%(funcName)s %(lineno)d:%(message)s', level=logging.INFO) logger = logging.getLogger(__name__) def train(session, feed_dict, train_cost_sb, valid_cost_sb, optimizer, epoch_look_back=5, max_epoch=100, percent_decrease=0, train_valid_ratio=[5,1], batchsize=64, randomize_split=False): """ Example training object for training a dataset """ train_arrs = [] valid_arrs = [] phs = [] for ph, arr in feed_dict.items():<|fim▁hole|> valid_arrs.append(valid_arr) iter_train = SequentialIterator(*train_arrs, batchsize=batchsize) iter_valid = SequentialIterator(*valid_arrs, batchsize=batchsize) es = EarlyStopper(max_epoch, epoch_look_back, percent_decrease) # required for BatchNormalization layer update_ops = ops.get_collection(ops.GraphKeys.UPDATE_OPS) with ops.control_dependencies(update_ops): train_op = optimizer.minimize(train_cost_sb) init = tf.global_variables_initializer() session.run(init) epoch = 0 while True: epoch += 1 ##############################[ Training ]############################## print('\n') logger.info('<<<<<[ epoch: {} ]>>>>>'.format(epoch)) logger.info('..training') pbar = ProgressBar(len(iter_train)) ttl_exp = 0 mean_train_cost = 0 for batches in iter_train: fd = dict(zip(phs, batches)) train_cost, _ = session.run([train_cost_sb, train_op], feed_dict=fd) mean_train_cost += train_cost * len(batches[0]) ttl_exp += len(batches[0]) pbar.update(ttl_exp) print('') mean_train_cost /= ttl_exp logger.info('..average train cost: {}'.format(mean_train_cost)) ##############################[ Validating ]############################ logger.info('..validating') pbar = ProgressBar(len(iter_valid)) ttl_exp = 0 mean_valid_cost = 0 for batches in iter_valid: fd = dict(zip(phs, batches)) valid_cost = session.run(valid_cost_sb, feed_dict=fd) mean_valid_cost += valid_cost * len(batches[0]) ttl_exp += len(batches[0]) pbar.update(ttl_exp) print('') mean_valid_cost /= ttl_exp logger.info('..average valid cost: {}'.format(mean_valid_cost)) if es.continue_learning(mean_valid_cost, epoch=epoch): logger.info('best epoch last update: {}'.format(es.best_epoch_last_update)) logger.info('best valid last update: {}'.format(es.best_valid_last_update)) else: logger.info('training done!') break<|fim▁end|>
train_arr, valid_arr = split_arr(arr, train_valid_ratio, randomize=randomize_split) phs.append(ph) train_arrs.append(train_arr)
<|file_name|>CNodeContentManager.java<|end_file_name|><|fim▁begin|>package org.cohorte.studio.eclipse.ui.node.project; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonBuilderFactory; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonWriter; import javax.json.stream.JsonGenerator; import org.cohorte.studio.eclipse.api.annotations.NonNull; import org.cohorte.studio.eclipse.api.objects.IHttpTransport; import org.cohorte.studio.eclipse.api.objects.INode; import org.cohorte.studio.eclipse.api.objects.IRuntime; import org.cohorte.studio.eclipse.api.objects.ITransport; import org.cohorte.studio.eclipse.api.objects.IXmppTransport; import org.cohorte.studio.eclipse.core.api.IProjectContentManager; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.e4.core.di.annotations.Creatable; /** * Node project content manager. * * @author Ahmad Shahwan * */ @Creatable public class CNodeContentManager implements IProjectContentManager<INode> { private static final String CONF = "conf"; //$NON-NLS-1$ private static final String RUN_JS = new StringBuilder().append(CONF).append("/run.js").toString(); //$NON-NLS-1$ @SuppressWarnings("nls") private interface IJsonKeys { String NODE = "node"; String SHELL_PORT = "shell-port"; String HTTP_PORT = "http-port"; String NAME = "name"; String TOP_COMPOSER = "top-composer"; String CONSOLE = "console"; String COHORTE_VERSION = "cohorte-version"; String TRANSPORT = "transport"; String TRANSPORT_HTTP = "transport-http"; String HTTP_IPV = "http-ipv"; String TRANSPORT_XMPP = "transport-xmpp"; String XMPP_SERVER = "xmpp-server"; String XMPP_USER_ID = "xmpp-user-jid"; String XMPP_USER_PASSWORD = "xmpp-user-password"; String XMPP_PORT = "xmpp-port"; } /** * Constructor. */ @Inject public CNodeContentManager() { } @Override public void populate(@NonNull IProject aProject, INode aModel) throws CoreException { if (!aProject.isOpen()) { aProject.open(null); } aProject.getFolder(CONF).create(true, true, null); IFile wRun = aProject.getFile(RUN_JS); StringWriter wBuffer = new StringWriter(); Map<String, Object> wProperties = new HashMap<>(1); wProperties.put(JsonGenerator.PRETTY_PRINTING, true); JsonWriter wJWriter = Json.createWriterFactory(wProperties).createWriter(wBuffer); JsonBuilderFactory wJ = Json.createBuilderFactory(null); JsonObjectBuilder wJson = wJ.createObjectBuilder() .add(IJsonKeys.NODE, wJ.createObjectBuilder() .add(IJsonKeys.SHELL_PORT, 0) .add(IJsonKeys.HTTP_PORT, 0) .add(IJsonKeys.NAME, aModel.getName()) .add(IJsonKeys.TOP_COMPOSER, aModel.isComposer()) .add(IJsonKeys.CONSOLE, true)); JsonArrayBuilder wTransports = wJ.createArrayBuilder(); for (ITransport wTransport : aModel.getTransports()) { wTransports.add(wTransport.getName()); if (wTransport instanceof IHttpTransport) { IHttpTransport wHttp = (IHttpTransport) wTransport; String wVer = wHttp.getVersion() == IHttpTransport.EVersion.IPV4 ? "4" : "6"; //$NON-NLS-1$//$NON-NLS-2$ wJson.add(IJsonKeys.TRANSPORT_HTTP, wJ.createObjectBuilder().add(IJsonKeys.HTTP_IPV, wVer)); <|fim▁hole|> JsonObjectBuilder wJsonXmpp = wJ.createObjectBuilder() .add(IJsonKeys.XMPP_SERVER, wXmpp.getHostname()) .add(IJsonKeys.XMPP_PORT, wXmpp.getPort()); if (wXmpp.getUsername() != null) { wJsonXmpp .add(IJsonKeys.XMPP_USER_ID, wXmpp.getUsername()) .add(IJsonKeys.XMPP_USER_PASSWORD, wXmpp.getPassword()); } wJson .add(IJsonKeys.TRANSPORT_XMPP, wJsonXmpp); } } wJson.add(IJsonKeys.TRANSPORT, wTransports); IRuntime wRuntime = aModel.getRuntime(); if (wRuntime != null) { wJson.add(IJsonKeys.COHORTE_VERSION, wRuntime.getVersion()); } JsonObject wRunJs = wJson.build(); wJWriter.write(wRunJs); InputStream wInStream = new ByteArrayInputStream(wBuffer.toString().getBytes()); wRun.create(wInStream, true, null); } }<|fim▁end|>
} if (wTransport instanceof IXmppTransport) { IXmppTransport wXmpp = (IXmppTransport) wTransport;
<|file_name|>sprite.py<|end_file_name|><|fim▁begin|>import pygame from ui.utils.interpolator import Interpolator class LcarsWidget(pygame.sprite.DirtySprite): """Base class for all widgets""" def __init__(self, color, pos, size, handler=None): pygame.sprite.DirtySprite.__init__(self) if self.image == None: self.image = pygame.Surface(size).convert() self.image.fill(color) self.rect = self.image.get_rect() self.rect.top = pos[0] self.rect.left = pos[1] self.size = (self.rect.width, self.rect.height) self.long_pressed = False self.pressed_time = 0 self.focussed = False self.line = None self.handler = handler def update(self, screen): if not self.visible: return if self.line != None: self.line.next() if self.rect.center == self.line.pos: self.dirty = 0 self.rect.center = self.line.pos else: self.dirty = 0 screen.blit(self.image, self.rect) def handleEvent(self, event, clock): handled = False if not self.visible: self.focussed = False return handled if event.type == pygame.MOUSEBUTTONDOWN: self.pressed_time = pygame.time.get_ticks() self.focussed = True if event.type == pygame.MOUSEMOTION: if (self.focussed and pygame.time.get_ticks() - self.pressed_time > 1000): self.long_pressed = True if self.groups()[0].UI_PLACEMENT_MODE: self.rect.top = event.pos[1] self.rect.left = event.pos[0] self.dirty = 1 if event.type == pygame.MOUSEBUTTONUP: if self.handler: self.handler(self, event, clock) handled = True if self.focussed and self.long_pressed and self.groups()[0].UI_PLACEMENT_MODE: print(event.pos[1], event.pos[0]) self.pressed_time = 0 self.long_pressed = False self.focussed = False return handled def applyColour(self, colour): """Convert non-black areas of an image to specified colour""" for x in range(0, self.size[0]): for y in range(0, self.size[1]): pixel = self.image.get_at((x, y)).r<|fim▁hole|> self.image.set_at((x, y), colour) class LcarsMoveToMouse(LcarsWidget): """For testing purposes - move a small square to last clicked position""" def __init__(self, color): self.image = None LcarsWidget.__init__(self, color, (0,0), (10,10)) self.focussed = True def handleEvent(self, event, clock): if event.type == pygame.MOUSEBUTTONDOWN: # move sprite to clicked location using interpolator fps = clock.get_fps() x, y = event.pos self.line = Interpolator( self.rect.center, (x, y), 0.5, # duration of interpolation fps, # current frames per second 1.0, # type of interpolation 0.5 # middle? ) self.dirty = 1<|fim▁end|>
if (pixel > 50):
<|file_name|>errors.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright 2007 The Closure Linter 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. """Error codes for JavaScript style checker.""" __author__ = ('[email protected] (Robert Walker)', '[email protected] (Andy Perelson)') def ByName(name): """Get the error code for the given error name. Args: name: The name of the error Returns: The error code """ return globals()[name] # "File-fatal" errors - these errors stop further parsing of a single file FILE_NOT_FOUND = -1 FILE_DOES_NOT_PARSE = -2 # Spacing EXTRA_SPACE = 1 MISSING_SPACE = 2 EXTRA_LINE = 3 MISSING_LINE = 4 ILLEGAL_TAB = 5 WRONG_INDENTATION = 6 WRONG_BLANK_LINE_COUNT = 7 # Semicolons MISSING_SEMICOLON = 10 MISSING_SEMICOLON_AFTER_FUNCTION = 11 ILLEGAL_SEMICOLON_AFTER_FUNCTION = 12 REDUNDANT_SEMICOLON = 13 # Miscellaneous ILLEGAL_PROTOTYPE_MEMBER_VALUE = 100 LINE_TOO_LONG = 110 LINE_STARTS_WITH_OPERATOR = 120 COMMA_AT_END_OF_LITERAL = 121 MULTI_LINE_STRING = 130 UNNECESSARY_DOUBLE_QUOTED_STRING = 131 UNUSED_PRIVATE_MEMBER = 132 UNUSED_LOCAL_VARIABLE = 133 # Requires, provides GOOG_REQUIRES_NOT_ALPHABETIZED = 140 GOOG_PROVIDES_NOT_ALPHABETIZED = 141 MISSING_GOOG_REQUIRE = 142 MISSING_GOOG_PROVIDE = 143 EXTRA_GOOG_REQUIRE = 144 EXTRA_GOOG_PROVIDE = 145 # JsDoc INVALID_JSDOC_TAG = 200 INVALID_USE_OF_DESC_TAG = 201 NO_BUG_NUMBER_AFTER_BUG_TAG = 202 MISSING_PARAMETER_DOCUMENTATION = 210 EXTRA_PARAMETER_DOCUMENTATION = 211 WRONG_PARAMETER_DOCUMENTATION = 212 MISSING_JSDOC_TAG_TYPE = 213 MISSING_JSDOC_TAG_DESCRIPTION = 214 MISSING_JSDOC_PARAM_NAME = 215 OUT_OF_ORDER_JSDOC_TAG_TYPE = 216 MISSING_RETURN_DOCUMENTATION = 217 UNNECESSARY_RETURN_DOCUMENTATION = 218 MISSING_BRACES_AROUND_TYPE = 219 MISSING_MEMBER_DOCUMENTATION = 220 MISSING_PRIVATE = 221 EXTRA_PRIVATE = 222 INVALID_OVERRIDE_PRIVATE = 223 INVALID_INHERIT_DOC_PRIVATE = 224 MISSING_JSDOC_TAG_THIS = 225 UNNECESSARY_BRACES_AROUND_INHERIT_DOC = 226 INVALID_AUTHOR_TAG_DESCRIPTION = 227 JSDOC_PREFER_QUESTION_TO_PIPE_NULL = 230 JSDOC_ILLEGAL_QUESTION_WITH_PIPE = 231 JSDOC_MISSING_OPTIONAL_TYPE = 232 JSDOC_MISSING_OPTIONAL_PREFIX = 233 JSDOC_MISSING_VAR_ARGS_TYPE = 234 JSDOC_MISSING_VAR_ARGS_NAME = 235 # TODO(robbyw): Split this in to more specific syntax problems. INCORRECT_SUPPRESS_SYNTAX = 250 INVALID_SUPPRESS_TYPE = 251 UNNECESSARY_SUPPRESS = 252 # File ending FILE_MISSING_NEWLINE = 300<|fim▁hole|> # Interfaces INTERFACE_CONSTRUCTOR_CANNOT_HAVE_PARAMS = 400 INTERFACE_METHOD_CANNOT_HAVE_CODE = 401 # Comments MISSING_END_OF_SCOPE_COMMENT = 500 MALFORMED_END_OF_SCOPE_COMMENT = 501 # goog.scope - Namespace aliasing # TODO(nnaze) Add additional errors here and in aliaspass.py INVALID_USE_OF_GOOG_SCOPE = 600 EXTRA_GOOG_SCOPE_USAGE = 601 # ActionScript specific errors: # TODO(user): move these errors to their own file and move all JavaScript # specific errors to their own file as well. # All ActionScript specific errors should have error number at least 1000. FUNCTION_MISSING_RETURN_TYPE = 1132 PARAMETER_MISSING_TYPE = 1133 VAR_MISSING_TYPE = 1134 PARAMETER_MISSING_DEFAULT_VALUE = 1135 IMPORTS_NOT_ALPHABETIZED = 1140 IMPORT_CONTAINS_WILDCARD = 1141 UNUSED_IMPORT = 1142 INVALID_TRACE_SEVERITY_LEVEL = 1250 MISSING_TRACE_SEVERITY_LEVEL = 1251 MISSING_TRACE_MESSAGE = 1252 REMOVE_TRACE_BEFORE_SUBMIT = 1253 REMOVE_COMMENT_BEFORE_SUBMIT = 1254 # End of list of ActionScript specific errors. NEW_ERRORS = frozenset([ # Errors added after 2.0.2: WRONG_INDENTATION, MISSING_SEMICOLON, # Errors added after 2.3.4: MISSING_END_OF_SCOPE_COMMENT, MALFORMED_END_OF_SCOPE_COMMENT, UNUSED_PRIVATE_MEMBER, # Errors added after 2.3.5: INVALID_USE_OF_GOOG_SCOPE, EXTRA_GOOG_SCOPE_USAGE, # Errors added after 2.3.9: JSDOC_MISSING_VAR_ARGS_TYPE, JSDOC_MISSING_VAR_ARGS_NAME, # Errors added after 2.3.12: ])<|fim▁end|>
FILE_IN_BLOCK = 301
<|file_name|>login.js<|end_file_name|><|fim▁begin|>$(document).ready(function() { $('#login-form').on('submit', login()); function login(){ $.ajax({ url: "http://localhost:9999/main/login", type: "GET", data: { username:$("#username-field").val(), password:$("#password-field").val() }, success: function(response) { window.location.href = "feed.php?id="+response; },<|fim▁hole|> console.log("Error"); } }); }; });<|fim▁end|>
error: function(xhr) {
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""The ReCollect Waste integration.""" from __future__ import annotations from datetime import date, timedelta from aiorecollect.client import Client, PickupEvent from aiorecollect.errors import RecollectError from homeassistant.config_entries import ConfigEntry<|fim▁hole|> from .const import CONF_PLACE_ID, CONF_SERVICE_ID, DOMAIN, LOGGER DEFAULT_NAME = "recollect_waste" DEFAULT_UPDATE_INTERVAL = timedelta(days=1) PLATFORMS = [Platform.SENSOR] async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up RainMachine as config entry.""" session = aiohttp_client.async_get_clientsession(hass) client = Client( entry.data[CONF_PLACE_ID], entry.data[CONF_SERVICE_ID], session=session ) async def async_get_pickup_events() -> list[PickupEvent]: """Get the next pickup.""" try: return await client.async_get_pickup_events( start_date=date.today(), end_date=date.today() + timedelta(weeks=4) ) except RecollectError as err: raise UpdateFailed( f"Error while requesting data from ReCollect: {err}" ) from err coordinator = DataUpdateCoordinator( hass, LOGGER, name=f"Place {entry.data[CONF_PLACE_ID]}, Service {entry.data[CONF_SERVICE_ID]}", update_interval=DEFAULT_UPDATE_INTERVAL, update_method=async_get_pickup_events, ) await coordinator.async_config_entry_first_refresh() hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = coordinator hass.config_entries.async_setup_platforms(entry, PLATFORMS) entry.async_on_unload(entry.add_update_listener(async_reload_entry)) return True async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: """Handle an options update.""" await hass.config_entries.async_reload(entry.entry_id) async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload an RainMachine config entry.""" unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) return unload_ok<|fim▁end|>
from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import aiohttp_client from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
<|file_name|>ExecuteDecisionWithAuditTrailCmd.java<|end_file_name|><|fim▁begin|>/* 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 org.flowable.dmn.engine.impl.cmd; import java.util.Map; import org.flowable.dmn.api.DecisionExecutionAuditContainer; import org.flowable.dmn.api.DmnDecisionTable; import org.flowable.dmn.engine.DmnEngineConfiguration; import org.flowable.dmn.engine.impl.ExecuteDecisionBuilderImpl; import org.flowable.dmn.engine.impl.util.CommandContextUtil; import org.flowable.dmn.model.Decision; import org.flowable.engine.common.api.FlowableIllegalArgumentException; import org.flowable.engine.common.impl.interceptor.Command;<|fim▁hole|> * @author Tijs Rademakers * @author Yvo Swillens */ public class ExecuteDecisionWithAuditTrailCmd extends AbstractExecuteDecisionCmd implements Command<DecisionExecutionAuditContainer> { private static final long serialVersionUID = 1L; public ExecuteDecisionWithAuditTrailCmd(ExecuteDecisionBuilderImpl decisionBuilder) { super(decisionBuilder); } public ExecuteDecisionWithAuditTrailCmd(String decisionKey, Map<String, Object> variables) { super(decisionKey, variables); } public ExecuteDecisionWithAuditTrailCmd(String decisionKey, String parentDeploymentId, Map<String, Object> variables) { this(decisionKey, variables); executeDecisionInfo.setParentDeploymentId(parentDeploymentId); } public ExecuteDecisionWithAuditTrailCmd(String decisionKey, String parentDeploymentId, Map<String, Object> variables, String tenantId) { this(decisionKey, parentDeploymentId, variables); executeDecisionInfo.setTenantId(tenantId); } public DecisionExecutionAuditContainer execute(CommandContext commandContext) { if (getDecisionKey() == null) { throw new FlowableIllegalArgumentException("decisionKey is null"); } DmnEngineConfiguration dmnEngineConfiguration = CommandContextUtil.getDmnEngineConfiguration(); DmnDecisionTable decisionTable = resolveDecisionTable(dmnEngineConfiguration.getDeploymentManager()); Decision decision = resolveDecision(dmnEngineConfiguration.getDeploymentManager(), decisionTable); DecisionExecutionAuditContainer executionResult = dmnEngineConfiguration.getRuleEngineExecutor().execute(decision, executeDecisionInfo); return executionResult; } }<|fim▁end|>
import org.flowable.engine.common.impl.interceptor.CommandContext; /**
<|file_name|>invoice_attachment_wizard.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- ############################################################################# # # Copyright (c) 2007 Martin Reisenhofer <[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/>. # ############################################################################## <|fim▁hole|> from openerp.addons.report_aeroo import report_aeroo from openerp.addons.at_base import util from openerp.osv import fields, osv from openerp.tools.translate import _ class inovice_attachment_wizard(osv.TransientModel): _name = "account.invoice.attachment.wizard" _description = "Invoice Attachment Wizard" def action_import(self, cr, uid, ids, context=None): wizard = self.browse(cr, uid, ids[0]) invoice_id = util.active_id(context, "account.invoice") if not invoice_id: raise osv.except_osv(_("Error!"), _("No invoice found")) report_obj = self.pool.get("ir.actions.report.xml") data=base64.decodestring(wizard.document) data = report_aeroo.fixPdf(data) if not data: raise osv.except_osv(_("Error!"), _("PDF is corrupted and unable to fix!")) if not report_obj.write_attachment(cr, uid, "account.invoice", invoice_id, report_name="account.report_invoice", datas=base64.encodestring(data), context=context, origin="account.invoice.attachment.wizard"): raise osv.except_osv(_("Error!"), _("Unable to import document (check if invoice is validated)")) return { "type" : "ir.actions.act_window_close" } _columns = { "document" : fields.binary("Document") }<|fim▁end|>
import base64
<|file_name|>tools.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python ''' Main entry to worch from a waf wscript file. Use the following in the options(), configure() and build() waf wscript methods: ctx.load('orch.tools', tooldir='.') ''' def options(opt): opt.add_option('--orch-config', action = 'store', default = 'orch.cfg', help='Give an orchestration configuration file.') opt.add_option('--orch-start', action = 'store', default = 'start', help='Set the section to start the orchestration') def configure(cfg): import orch.configure orch.configure.configure(cfg) def build(bld): import orch.build orch.build.build(bld) # the stuff below is for augmenting waf import time from orch.wafutil import exec_command from orch.util import string2list default_step_cwd = dict( download = '{download_dir}', unpack = '{source_dir}', patch = '{source_dir}', prepare = '{build_dir}', build = '{build_dir}', install = '{build_dir}', ) # Main interface to worch configuration items class WorchConfig(object): def __init__(self, **pkgcfg): self._config = pkgcfg def __getattr__(self, name): return self._config[name] def get(self, name, default = None): return self._config.get(name,default) def format(self, string, **kwds): ''' Return a string formatted with kwds and configuration items ''' d = dict(self._config, **kwds) return string.format(**d) def depends_step(self, step): ''' Return a list of steps that this step depends on ''' d = self._config.get('depends') if not d: return list() ds = [x[1] for x in [s.split(':') for s in string2list(d)] if x[0] == step] return ds def dependencies(self): ''' Return all dependencies set via "depends" configuration items return list of tuples: (mystep, package, package_step) eg: ('prepare', 'gcc', 'install') ''' ret = list() try: deps = getattr(self, 'depends', None) except KeyError: return list() for dep in string2list(deps): mystep, other = dep.split(':') pkg,pkg_step = other.split('_',1) ret.append((mystep, pkg, pkg_step)) return ret def exports(self): ''' Return all environment settings via export_* configuration items return list of tuples: (variable, value, operator) for exports eg: ('PATH', '/blah/blah', 'prepend') ''' ret = list() for key,val in self._config.items(): if not key.startswith('export_'): continue var = key[len('export_'):] oper = 'set' for maybe in ['prepend', 'append', 'set']: if val.startswith(maybe+':'): oper = maybe val = val[len(maybe)+1:] ret.append((var, val, oper)) return ret # Augment the task generator with worch-specific methods from waflib.TaskGen import taskgen_method @taskgen_method def worch_hello(self): 'Just testing' print ("%s" % self.worch.format('Hi from worch, my name is "{package}/{version}" and I am using "{dumpenv_cmd}" with extra {extra}', extra='spice')) print ('My bld.env: %s' % (self.bld.env.keys(),)) print ('My all_envs: %s' % (sorted(self.bld.all_envs.keys()),)) print ('My env: %s' % (self.env.keys(),)) print ('My groups: %s' % (self.env['orch_group_dict'].keys(),)) print ('My packages: %s' % (self.env['orch_package_list'],)) # print ('My package dict: %s' % '\n'.join(['%s=%s' %kv for kv in sorted(self.bld.env['orch_package_dict'][self.worch.package].items())])) @taskgen_method def step(self, name, rule, **kwds): ''' Make a worch installation step. This invokes the build context on the rule with the following augmentations: - the given step name is prefixed with the package name - if the rule is a string (scriptlet) then the worch exec_command is used - successful execution of the rule leads to a worch control file being produced. ''' step_name = '%s_%s' % (self.worch.package, name) # append control file as an additional output target = string2list(kwds.get('target', '')) if not isinstance(target, list): target = [target] cn = self.control_node(name) if not cn in target: target.append(cn) kwds['target'] = target kwds.setdefault('env', self.env) cwd = kwds.get('cwd') if not cwd: cwd = default_step_cwd.get(name) if cwd: cwd = self.worch.format(cwd) cwd = self.make_node(cwd) msg.debug('orch: using cwd for step "%s": %s' % (step_name, cwd.abspath())) kwds['cwd'] = cwd.abspath() depends = self.worch.depends_step(name) after = string2list(kwds.get('after',[])) + depends if after: kwds['after'] = after msg.debug('orch: run %s AFTER: %s' % (step_name, after)) # functionalize scriptlet rulefun = rule if isinstance(rule, type('')): rulefun = lambda t: exec_command(t, rule) # curry the real rule function in order to write control file if successful def runit(t): rc = rulefun(t) if not rc: msg.debug('orch: successfully ran %s' % step_name) cn.write(time.asctime(time.localtime()) + '\n') return rc # msg.debug('orch: step "%s" with %s in %s\nsource=%s\ntarget=%s' % \ # (step_name, rulefun, cwd, kwds.get('source'), kwds.get('target'))) # have to switch group each time as steps are called already asynchronously self.bld.set_group(self.worch.group) return self.bld(name=step_name, rule = runit, **kwds) @taskgen_method def control_node(self, step, package = None): ''' Return a node for the control file given step of this package or optionally another package. ''' if not package: package = self.worch.package filename = '%s_%s' % (package, step) path = self.worch.format('{control_dir}/{filename}', filename=filename) return self.path.find_or_declare(path) @taskgen_method def make_node(self, path, parent_node=None):<|fim▁hole|> parent_node = self.bld.root else: parent_node = self.bld.bldnode return parent_node.make_node(path) import waflib.Logs as msg from waflib.Build import BuildContext def worch_package(ctx, worch_config, *args, **kw): # transfer waf-specific keywords explicitly kw['name'] = worch_config['package'] kw['features'] = ' '.join(string2list(worch_config['features'])) kw['use'] = worch_config.get('use') # make the TaskGen object for the package worch=WorchConfig(**worch_config) tgen = ctx(*args, worch=worch, **kw) tgen.env = ctx.all_envs[worch.package] tgen.env.env = tgen.env.munged_env msg.debug('orch: package "%s" with features: %s' % \ (kw['name'], ', '.join(kw['features'].split()))) return tgen BuildContext.worch_package = worch_package del worch_package<|fim▁end|>
if not parent_node: if path.startswith('/'):
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>//! A simple library for parsing an XML file into an in-memory tree structure //! //! Not recommended for large XML files, as it will load the entire file into memory. //! //! ## Reading //! //! For reading XML you can use the `Element::from_reader` method which will //! parse from a given reader. Afterwards you end up with a fancy element //! tree that can be accessed in various different ways. //! //! You can use ``("ns", "tag")`` or ``{ns}tag`` to refer to fully qualified //! elements. //! //! ```rust //! # use elementtree::Element; //! let root = Element::from_reader(r#"<?xml version="1.0"?> //! <root xmlns="tag:myns" xmlns:foo="tag:otherns"> //! <list a="1" b="2" c="3"> //! <item foo:attr="foo1"/> //! <item foo:attr="foo2"/> //! <item foo:attr="foo3"/> //! </list> //! </root> //! "#.as_bytes()).unwrap(); //! let list = root.find("{tag:myns}list").unwrap(); //! for child in list.find_all("{tag:myns}item") { //! println!("attribute: {}", child.get_attr("{tag:otherns}attr").unwrap()); //! } //! ``` //! //! ## Writing //! //! Writing is easy as well but if you work with namespaces you will need to //! register them with the root. If namespaces are not used yet they will //! otherwise be registered with an empty (and once that is used a random prefix) //! on the element itself which will blow up the XML size. //! //! Most methods for modification support chaining in one form or another which //! makes modifications slightly more ergonomic. //! //! ``` //! # use elementtree::Element; //! let ns = "http://example.invalid/#myns"; //! let other_ns = "http://example.invalid/#otherns"; //! //! let mut root = Element::new((ns, "mydoc")); //! root.set_namespace_prefix(other_ns, "other"); //! //! { //! let mut list = root.append_new_child((ns, "list")); //! for x in 0..3 { //! list.append_new_child((ns, "item")) //! .set_text(format!("Item {}", x)) //! .set_attr((other_ns, "id"), x.to_string()); //! } //! } //! ``` //! //! ## Design Notes //! //! This library largely follows the ideas of Python's ElementTree but it has some //! specific changes that simplify the model for Rust. In particular nodes do not //! know about their parents or siblings. While this obviously reduces a lot of //! what would be possible with the library it significantly simplifies memory //! management and the external API. //! //! If you are coming from a DOM environment the following differences are the //! most striking: //! //! * There are no text nodes, instead text is stored either in the `text` //! attribute of a node or in the `tail` of a child node. This means that //! for most situations just working with the `text` is what you want and //! you can ignore the existence of the `tail`. //! * tags and attributes are implemented through a `QName` abstraction that //! simplifies working wiht namespaces. Most APIs just accept strings and //! will create `QName`s automatically. //! * namespace prefixes never play a role and are in fact not really exposed. //! Instead all namespaces are managed through their canonical identifier. //! //! ## Notes on Namespaces //! //! Namespaces are internally tracked in a shared map attached to elements. The //! map is not exposed but when an element is created another element can be passed //! in and the namespace map is copied over. Internally a copy on write mechanism //! is used so when changes are performed on the namespace the namespaces will be //! copied and the writer will emit them accordingly. //! //! Namespaces need to be registered or the XML generated will be malformed. use std::borrow::Cow; use std::cmp::Ord; use std::cmp::Ordering; use std::collections::btree_map::Iter as BTreeMapIter; use std::collections::BTreeMap; use std::fmt; use std::hash::{Hash, Hasher}; use std::io; use std::io::{Read, Write}; use std::mem; use std::ops::Deref; use std::rc::Rc; use std::str::Utf8Error; use string_cache::DefaultAtom as Atom; use xml::attribute::{Attribute, OwnedAttribute}; use xml::common::{Position as XmlPosition, XmlVersion}; use xml::name::{Name, OwnedName}; use xml::namespace::{Namespace as XmlNamespaceMap, NS_EMPTY_URI, NS_XMLNS_URI, NS_XML_URI}; use xml::reader::{ Error as XmlReadError, ErrorKind as XmlReadErrorKind, EventReader, ParserConfig, XmlEvent, }; use xml::writer::{Error as XmlWriteError, EventWriter, XmlEvent as XmlWriteEvent}; use xml::EmitterConfig; enum XmlAtom<'a> { Shared(Atom), Borrowed(&'a str), } impl<'a> Deref for XmlAtom<'a> { type Target = str; #[inline(always)] fn deref(&self) -> &str { match *self { XmlAtom::Shared(ref atom) => atom.deref(), XmlAtom::Borrowed(s) => s, } } } impl<'a> XmlAtom<'a> { #[inline(always)] pub fn borrow(&self) -> &str { self } } impl<'a> fmt::Debug for XmlAtom<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self.borrow()) } } impl<'a> Clone for XmlAtom<'a> { fn clone(&self) -> XmlAtom<'a> { XmlAtom::Shared(Atom::from(self.borrow())) } } impl<'a> PartialEq for XmlAtom<'a> { fn eq(&self, other: &XmlAtom<'a>) -> bool { self.borrow().eq(other.borrow()) } } impl<'a> Eq for XmlAtom<'a> {} impl<'a> PartialOrd for XmlAtom<'a> { fn partial_cmp(&self, other: &XmlAtom<'a>) -> Option<Ordering> { self.borrow().partial_cmp(other.borrow()) } } impl<'a> Ord for XmlAtom<'a> { fn cmp(&self, other: &XmlAtom<'a>) -> Ordering { self.borrow().cmp(other.borrow()) } } /// Convenience trait to get a `QName` from an object. /// /// This is used for the accessor interface on elements. pub trait AsQName<'a> { /// Returns a Cow'ed `QName` from the given object. fn as_qname(&self) -> Cow<'a, QName<'a>>; } impl<'a> AsQName<'a> for &'a QName<'a> { #[inline(always)] fn as_qname(&self) -> Cow<'a, QName<'a>> { Cow::Borrowed(self) } } impl<'a> AsQName<'a> for &'a str { #[inline(always)] fn as_qname(&self) -> Cow<'a, QName<'a>> { Cow::Owned(QName::from(self)) } } impl<'a> AsQName<'a> for (&'a str, &'a str) { #[inline(always)] fn as_qname(&self) -> Cow<'a, QName<'a>> { Cow::Owned(QName::from_ns_name(Some(self.0), self.1)) } } /// A `QName` represents a qualified name. /// /// A qualified name is a tag or attribute name that has a namespace and a /// local name. If the namespace is empty no namespace is assumed. It /// can be constructed from a qualified name string with the ``from`` /// method. /// /// ## Notes on Memory Management /// /// Qualified names that are user constructed for comparison purposes /// usually have a static lifetime because they are created from static /// strings. Creating qualified names from other strings might make /// memory management harder which is why `share()` exists which moves /// the `QName` internal strings to shared storage in which the lifetime /// changes to `'static`. /// /// Common usage examples: /// /// ```no_run /// # use elementtree::QName; /// let href = QName::from_name("href"); /// let a = QName::from("{http://www.w3.org/1999/xhtml}a"); /// ``` #[derive(Clone)] pub struct QName<'a> { ns: Option<XmlAtom<'a>>, name: XmlAtom<'a>, } impl<'a> QName<'a> { /// Creates a qualified name from a given string. /// /// Two formats are supported ``{namespace}tag`` or just ``tag``. ///<|fim▁hole|> pub fn from(s: &'a str) -> QName<'a> { let mut ns = None; let mut name = None; if s.starts_with('{') { if let Some(index) = s.find('}') { if index > 1 { ns = Some(XmlAtom::Borrowed(&s[1..index])); } name = Some(XmlAtom::Borrowed(&s[index + 1..])); } } QName { ns, name: name.unwrap_or(XmlAtom::Borrowed(s)), } } /// Creates a qualified name from a given string without namespace. /// /// This is slightly faster than using ``from()``. pub fn from_name(name: &'a str) -> QName<'a> { QName { ns: None, name: XmlAtom::Borrowed(name), } } /// Creates a qualified name from a namespace and name. pub fn from_ns_name(ns: Option<&'a str>, name: &'a str) -> QName<'a> { QName { ns: ns.map(XmlAtom::Borrowed), name: XmlAtom::Borrowed(name), } } /// Returns the name portion of the qualified name. This is the local /// tag or attribute name. pub fn name(&self) -> &str { &self.name } /// Returns the optional namespace of this element. This is the URL of /// the namespace and not the prefix. The information about the latter /// is not retained. pub fn ns(&self) -> Option<&str> { self.ns.as_ref().map(|x| x.borrow()) } /// Creates a shared `QName` with static lifetime from an already /// existing `QName`. The internal strings are interned and might /// be shared with other instances. pub fn share(&self) -> QName<'static> { QName { name: XmlAtom::Shared(Atom::from(self.name.borrow())), ns: self .ns .as_ref() .map(|x| XmlAtom::Shared(Atom::from(x.borrow()))), } } fn from_owned_name(name: OwnedName) -> QName<'static> { QName { name: XmlAtom::Shared(Atom::from(name.local_name)), ns: match name.namespace { Some(ns) => { if !ns.is_empty() { Some(XmlAtom::Shared(Atom::from(ns))) } else { None } } _ => None, }, } } } impl<'a> PartialEq for QName<'a> { fn eq(&self, other: &QName<'a>) -> bool { self.name() == other.name() && self.ns() == other.ns() } } impl<'a> fmt::Debug for QName<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "QName(\"{}\")", self) } } impl<'a> fmt::Display for QName<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(ref ns) = self.ns { write!(f, "{{{}}}", ns.borrow())?; } write!(f, "{}", self.name.borrow()) } } impl<'a> Eq for QName<'a> {} impl<'a> Hash for QName<'a> { fn hash<H: Hasher>(&self, state: &mut H) { self.name.hash(state); if let Some(ref ns) = self.ns { ns.hash(state); } } } impl<'a> PartialOrd for QName<'a> { fn partial_cmp(&self, other: &QName<'a>) -> Option<Ordering> { self.name().partial_cmp(other.name()) } } impl<'a> Ord for QName<'a> { fn cmp(&self, other: &QName<'a>) -> Ordering { self.name().cmp(other.name()) } } #[derive(Debug, Clone)] struct NamespaceMap { prefix_to_ns: BTreeMap<XmlAtom<'static>, XmlAtom<'static>>, ns_to_prefix: BTreeMap<XmlAtom<'static>, XmlAtom<'static>>, } impl NamespaceMap { pub fn new() -> NamespaceMap { NamespaceMap { prefix_to_ns: BTreeMap::new(), ns_to_prefix: BTreeMap::new(), } } pub fn get_prefix(&self, url: &str) -> Option<&str> { // same shit as with remove_attr below for the explanation. let atom = XmlAtom::Borrowed(url); let static_atom: &XmlAtom<'static> = unsafe { mem::transmute(&atom) }; self.ns_to_prefix.get(static_atom).map(|x| x.borrow()) } pub fn set_prefix(&mut self, url: &str, prefix: &str) -> Result<(), Error> { let prefix = XmlAtom::Shared(Atom::from(prefix)); if self.prefix_to_ns.contains_key(&prefix) { return Err(Error::DuplicateNamespacePrefix); } let url = XmlAtom::Shared(Atom::from(url)); if let Some(old_prefix) = self.ns_to_prefix.remove(&url) { self.prefix_to_ns.remove(&old_prefix); } self.ns_to_prefix.insert(url.clone(), prefix.clone()); self.prefix_to_ns.insert(prefix.clone(), url.clone()); Ok(()) } fn generate_prefix(&self) -> XmlAtom<'static> { let mut i = 1; loop { let random_prefix = format!("ns{}", i); if !self .prefix_to_ns .contains_key(&XmlAtom::Borrowed(&random_prefix)) { return XmlAtom::Shared(Atom::from(random_prefix)); } i += 1; } } pub fn register_if_missing(&mut self, url: &str, prefix: Option<&str>) -> bool { if self.get_prefix(url).is_some() { return false; } let stored_prefix = if let Some(prefix) = prefix { let prefix = XmlAtom::Borrowed(prefix); if self.prefix_to_ns.get(&prefix).is_some() { self.generate_prefix() } else { XmlAtom::Shared(Atom::from(prefix.borrow())) } } else { self.generate_prefix() }; let url = XmlAtom::Shared(Atom::from(url)); self.prefix_to_ns.insert(stored_prefix.clone(), url.clone()); self.ns_to_prefix.insert(url, stored_prefix); true } } /// Represents an XML element. /// /// Usually constructed from either parsing or one of the two constructors /// an element is part of a tree and represents an XML element and the /// children contained. /// /// Imagine a structure like this: /// /// ```xml /// <p>Hello <strong>World</strong>!</p> /// ``` /// /// In this case the structure is more or less represented like this: /// /// ```ignore /// Element { /// tag: "p", /// text: "Hello ", /// tail: None, /// children: [ /// Element { /// tag: "strong", /// text: "World", /// tail: Some("!") /// } /// ] /// } /// ``` /// /// Namespaces are internally managed and inherited downwards when an /// element is created. #[derive(Debug, Clone)] pub struct Element { tag: QName<'static>, attributes: BTreeMap<QName<'static>, String>, children: Vec<Element>, nsmap: Option<Rc<NamespaceMap>>, emit_nsmap: bool, text: String, tail: String, } /// An iterator over children of an element. pub struct Children<'a> { idx: usize, element: &'a Element, } /// A mutable iterator over children of an element. pub struct ChildrenMut<'a> { iter: ::std::slice::IterMut<'a, Element>, } /// An iterator over attributes of an element. pub struct Attrs<'a> { iter: BTreeMapIter<'a, QName<'a>, String>, } /// An iterator over matching children. pub struct FindChildren<'a> { tag: Cow<'a, QName<'a>>, child_iter: Children<'a>, } /// A mutable iterator over matching children. pub struct FindChildrenMut<'a> { tag: Cow<'a, QName<'a>>, child_iter: ChildrenMut<'a>, } /// Represents a position in the source. #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] pub struct Position { line: u64, column: u64, } impl Position { /// Creates a new position. pub fn new(line: u64, column: u64) -> Position { Position { line, column } } fn from_xml_position(pos: &dyn XmlPosition) -> Position { let pos = pos.position(); Position::new(pos.row, pos.column) } /// Returns the line number of the position pub fn line(&self) -> u64 { self.line } /// Returns the column of the position pub fn column(&self) -> u64 { self.column } } impl fmt::Display for Position { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}:{}", self.line, self.column) } } /// Errors that can occur parsing XML #[derive(Debug)] pub enum Error { /// The XML is invalid MalformedXml { msg: Cow<'static, str>, pos: Position, }, /// An IO Error Io(io::Error), /// A UTF-8 Error Utf8(Utf8Error), /// This library is unable to process this XML. This can occur if, for /// example, the XML contains processing instructions. UnexpectedEvent { msg: Cow<'static, str>, pos: Position, }, /// A namespace prefix was already used DuplicateNamespacePrefix, } impl Error { /// Returns the position of the error if known pub fn position(&self) -> Option<Position> { match self { Error::MalformedXml { pos, .. } => Some(*pos), Error::UnexpectedEvent { pos, .. } => Some(*pos), _ => None, } } /// Returns the line number of the error or 0 if unknown pub fn line(&self) -> u64 { self.position().map(|x| x.line()).unwrap_or(0) } /// Returns the column of the error or 0 if unknown pub fn column(&self) -> u64 { self.position().map(|x| x.column()).unwrap_or(0) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::MalformedXml { ref pos, ref msg } => { write!(f, "Malformed XML: {} ({})", msg, pos) } Error::Io(ref e) => write!(f, "{}", e), Error::Utf8(ref e) => write!(f, "{}", e), Error::UnexpectedEvent { ref msg, .. } => write!(f, "Unexpected XML event: {}", msg), Error::DuplicateNamespacePrefix => { write!(f, "Encountered duplicated namespace prefix") } } } } impl std::error::Error for Error { fn cause(&self) -> Option<&dyn std::error::Error> { match *self { Error::Io(ref e) => Some(e), Error::Utf8(ref e) => Some(e), _ => None, } } } impl From<XmlReadError> for Error { fn from(err: XmlReadError) -> Error { match *err.kind() { XmlReadErrorKind::Io(ref err) => Error::Io(io::Error::new(err.kind(), err.to_string())), XmlReadErrorKind::Utf8(err) => Error::Utf8(err), XmlReadErrorKind::UnexpectedEof => Error::Io(io::Error::new( io::ErrorKind::UnexpectedEof, "Encountered unexpected eof", )), XmlReadErrorKind::Syntax(ref msg) => Error::MalformedXml { msg: msg.clone(), pos: Position::from_xml_position(&err), }, } } } impl From<XmlWriteError> for Error { fn from(err: XmlWriteError) -> Error { match err { XmlWriteError::Io(err) => Error::Io(err), err => Err(err).unwrap(), } } } impl<'a> Iterator for Children<'a> { type Item = &'a Element; fn next(&mut self) -> Option<&'a Element> { if self.idx < self.element.children.len() { let rv = &self.element.children[self.idx]; self.idx += 1; Some(rv) } else { None } } } impl<'a> Iterator for ChildrenMut<'a> { type Item = &'a mut Element; fn next(&mut self) -> Option<&'a mut Element> { self.iter.next() } } impl<'a> Iterator for Attrs<'a> { type Item = (&'a QName<'a>, &'a str); fn next(&mut self) -> Option<(&'a QName<'a>, &'a str)> { if let Some((k, v)) = self.iter.next() { Some((k, v.as_str())) } else { None } } } impl<'a> Iterator for FindChildren<'a> { type Item = &'a Element; fn next(&mut self) -> Option<&'a Element> { use std::borrow::Borrow; loop { if let Some(child) = self.child_iter.next() { if child.tag() == self.tag.borrow() { return Some(child); } } else { return None; } } } } impl<'a> Iterator for FindChildrenMut<'a> { type Item = &'a mut Element; fn next(&mut self) -> Option<&'a mut Element> { use std::borrow::Borrow; let tag: &QName = self.tag.borrow(); self.child_iter.find(|x| x.tag() == tag) } } impl Element { /// Creates a new element without any children but a given tag. /// /// This can be used at all times to create a new element however when you /// work with namespaces it's recommended to only use this for the root /// element and then create further children through `new_with_namespaces` /// as otherwise namespaces will not be propagaged downwards properly. pub fn new<'a, Q: AsQName<'a>>(tag: Q) -> Element { Element::new_with_nsmap(&tag.as_qname(), None) } /// Creates a new element without any children but inheriting the /// namespaces from another element. /// /// This has the advantage that internally the map will be shared /// across elements for as long as no further modifications are /// taking place. pub fn new_with_namespaces<'a, Q: AsQName<'a>>(tag: Q, reference: &Element) -> Element { Element::new_with_nsmap(&tag.as_qname(), reference.nsmap.clone()) } fn new_with_nsmap(tag: &QName<'_>, nsmap: Option<Rc<NamespaceMap>>) -> Element { let mut rv = Element { tag: tag.share(), attributes: BTreeMap::new(), nsmap, emit_nsmap: false, children: vec![], text: String::new(), tail: String::new(), }; if let Some(url) = tag.ns() { let prefix = rv.get_namespace_prefix(url).unwrap_or("").to_string(); rv.register_namespace(url, Some(&prefix)); } rv } /// Parses some XML data into an `Element` from a reader. pub fn from_reader<R: Read>(r: R) -> Result<Element, Error> { let cfg = ParserConfig::new().whitespace_to_characters(true); let mut reader = cfg.create_reader(r); loop { match reader.next() { Ok(XmlEvent::StartElement { name, attributes, namespace, }) => { return Element::from_start_element( name, attributes, namespace, None, &mut reader, ); } Ok(XmlEvent::Comment(..)) | Ok(XmlEvent::Whitespace(..)) | Ok(XmlEvent::StartDocument { .. }) | Ok(XmlEvent::ProcessingInstruction { .. }) => { continue; } Ok(_) => { return Err(Error::UnexpectedEvent { msg: Cow::Borrowed("xml construct"), pos: Position::from_xml_position(&reader), }) } Err(e) => return Err(e.into()), } } } /// Dump an element as XML document into a writer. /// /// This will create an XML document with a processing instruction /// to start it. There is currently no API to only serialize a non /// standalone element. /// /// Currently the writer has no way to customize what is generated /// in particular there is no support yet for automatically indenting /// elements. The reason for this is that there is no way to ignore /// this information automatically in the absence of DTD support which /// is not really planned. pub fn to_writer<W: Write>(&self, w: W) -> Result<(), Error> { self.to_writer_with_options(w, WriteOptions::new()) } /// Dump an element as XML document into a writer with option. /// /// This will create an XML document with a processing instruction /// to start it. There is currently no API to only serialize a non /// standalone element. /// /// Currently the writer has no way to customize what is generated /// in particular there is no support yet for automatically indenting /// elements. The reason for this is that there is no way to ignore /// this information automatically in the absence of DTD support which /// is not really planned. pub fn to_writer_with_options<W: Write>( &self, w: W, options: WriteOptions, ) -> Result<(), Error> { let mut writer = EmitterConfig::new() .write_document_declaration(options.xml_prolog.is_some()) .create_writer(w); if options.xml_prolog.is_some() { writer.write(XmlWriteEvent::StartDocument { version: match options.xml_prolog.unwrap() { XmlProlog::Version10 => XmlVersion::Version10, XmlProlog::Version11 => XmlVersion::Version11, }, encoding: Some("utf-8"), standalone: None, })?; } self.dump_into_writer(&mut writer) } /// Dump an element as XML document into a string pub fn to_string(&self) -> Result<String, Error> { let mut out: Vec<u8> = Vec::new(); self.to_writer(&mut out)?; Ok(String::from_utf8(out).unwrap()) } fn get_xml_name<'a>(&'a self, qname: &'a QName<'a>) -> Name<'a> { let mut name = Name::local(qname.name()); if let Some(url) = qname.ns() { name.namespace = Some(url); if let Some(prefix) = self.get_namespace_prefix(url) { if !prefix.is_empty() { name.prefix = Some(prefix); } } } name } fn dump_into_writer<W: Write>(&self, w: &mut EventWriter<W>) -> Result<(), Error> { let name = self.get_xml_name(&self.tag); let mut attributes = Vec::with_capacity(self.attributes.len()); for (k, v) in self.attributes.iter() { attributes.push(Attribute { name: self.get_xml_name(k), value: v, }); } let mut namespace = XmlNamespaceMap::empty(); if self.emit_nsmap { if let Some(ref nsmap) = self.nsmap { for (prefix, url) in &nsmap.prefix_to_ns { namespace.put(prefix.borrow(), url.borrow()); } } } w.write(XmlWriteEvent::StartElement { name, attributes: Cow::Owned(attributes), namespace: Cow::Owned(namespace), })?; let text = self.text(); if !text.is_empty() { w.write(XmlWriteEvent::Characters(text))?; } for elem in &self.children { elem.dump_into_writer(w)?; let text = elem.tail(); if !text.is_empty() { w.write(XmlWriteEvent::Characters(text))?; } } w.write(XmlWriteEvent::EndElement { name: Some(name) })?; Ok(()) } fn from_start_element<R: Read>( name: OwnedName, attributes: Vec<OwnedAttribute>, namespace: XmlNamespaceMap, parent_nsmap: Option<Rc<NamespaceMap>>, reader: &mut EventReader<R>, ) -> Result<Element, Error> { let mut root = Element { tag: QName::from_owned_name(name), attributes: BTreeMap::new(), nsmap: parent_nsmap, emit_nsmap: false, children: vec![], text: String::new(), tail: String::new(), }; for attr in attributes { root.attributes .insert(QName::from_owned_name(attr.name), attr.value); } if !namespace.is_essentially_empty() { for (prefix, url) in namespace.0.iter() { root.register_namespace(url, Some(prefix)); } }; root.parse_children(reader)?; Ok(root) } fn parse_children<R: Read>(&mut self, reader: &mut EventReader<R>) -> Result<(), Error> { loop { match reader.next() { Ok(XmlEvent::EndElement { ref name }) => { if name.local_name == self.tag.name() && name.namespace.as_deref() == self.tag.ns() { return Ok(()); } else { return Err(Error::UnexpectedEvent { msg: Cow::Owned(format!("Unexpected end element {}", &name.local_name)), pos: Position::from_xml_position(reader), }); } } Ok(XmlEvent::StartElement { name, attributes, namespace, }) => { self.children.push(Element::from_start_element( name, attributes, namespace, self.nsmap.clone(), reader, )?); } Ok(XmlEvent::Characters(s)) => { let child_count = self.children.len(); if child_count > 0 { self.children[child_count - 1].tail = s; } else { self.text = s; } } Ok(XmlEvent::CData(s)) => { self.text = s; } Ok(XmlEvent::Comment(..)) | Ok(XmlEvent::Whitespace(..)) | Ok(XmlEvent::StartDocument { .. }) | Ok(XmlEvent::ProcessingInstruction { .. }) => { continue; } Ok(_) => { return Err(Error::UnexpectedEvent { msg: Cow::Borrowed("unknown element"), pos: Position::from_xml_position(reader), }) } Err(e) => { return Err(e.into()); } } } } /// Returns the text of a tag. /// /// Note that this does not trim or modify whitespace so the return /// value might contain structural information from the XML file. pub fn text(&self) -> &str { &self.text } /// Sets a new text value for the tag. pub fn set_text<S: Into<String>>(&mut self, value: S) -> &mut Element { self.text = value.into(); self } /// Returns the tail text of a tag. /// /// The tail is the text following an element. pub fn tail(&self) -> &str { &self.tail } /// Sets a new tail text value for the tag. pub fn set_tail<S: Into<String>>(&mut self, value: S) -> &mut Element { self.tail = value.into(); self } /// The tag of the element as qualified name. /// /// Use the `QName` functionality to extract the information from the /// tag name you care about (like the local name). pub fn tag(&self) -> &QName { &self.tag } /// Sets a new tag for the element. pub fn set_tag<'a>(&mut self, tag: &QName<'a>) -> &mut Element { self.tag = tag.share(); self } /// Returns the number of children pub fn child_count(&self) -> usize { self.children.len() } /// Returns the nth child. pub fn get_child(&self, idx: usize) -> Option<&Element> { self.children.get(idx) } /// Returns the nth child as a mutable reference. pub fn get_child_mut(&mut self, idx: usize) -> Option<&mut Element> { self.children.get_mut(idx) } /// Removes a child. /// /// This returns the element if it was removed or None if the /// index was out of bounds. pub fn remove_child(&mut self, idx: usize) -> Option<Element> { if self.children.len() > idx { Some(self.children.remove(idx)) } else { None } } /// Appends a new child and returns a reference to self. pub fn append_child(&mut self, child: Element) -> &mut Element { self.children.push(child); self } /// Appends a new child to the element and returns a reference to it. /// /// This uses ``Element::new_with_namespaces`` internally and can /// then be used like this: /// /// ``` /// use elementtree::Element; /// /// let ns = "http://example.invalid/#ns"; /// let mut root = Element::new((ns, "mydoc")); /// /// { /// let mut list = root.append_new_child((ns, "list")); /// for x in 0..3 { /// list.append_new_child((ns, "item")).set_text(format!("Item {}", x)); /// } /// } /// ``` pub fn append_new_child<'a, Q: AsQName<'a>>(&'a mut self, tag: Q) -> &'a mut Element { let child = Element::new_with_namespaces(tag, self); self.append_child(child); let idx = self.children.len() - 1; &mut self.children[idx] } /// Returns an iterator over all children. pub fn children(&self) -> Children<'_> { Children { idx: 0, element: self, } } /// Returns a mutable iterator over all children. pub fn children_mut(&mut self) -> ChildrenMut<'_> { ChildrenMut { iter: self.children.iter_mut(), } } /// Returns all children with the given name. pub fn find_all<'a, Q: AsQName<'a>>(&'a self, tag: Q) -> FindChildren<'a> { FindChildren { tag: tag.as_qname(), child_iter: self.children(), } } /// Returns all children with the given name. pub fn find_all_mut<'a, Q: AsQName<'a>>(&'a mut self, tag: Q) -> FindChildrenMut<'a> { FindChildrenMut { tag: tag.as_qname(), child_iter: self.children_mut(), } } /// Finds the first matching child pub fn find<'a, Q: AsQName<'a>>(&'a self, tag: Q) -> Option<&'a Element> { use std::borrow::Borrow; let tag = tag.as_qname(); for child in self.children() { if child.tag() == tag.borrow() { return Some(child); } } None } /// Finds the first matching child and returns a mut ref pub fn find_mut<'a, Q: AsQName<'a>>(&'a mut self, tag: Q) -> Option<&'a mut Element> { self.find_all_mut(tag).next() } /// Look up an attribute by qualified name. pub fn get_attr<'a, Q: AsQName<'a>>(&'a self, name: Q) -> Option<&'a str> { self.attributes.get(&name.as_qname()).map(|x| x.as_str()) } /// Sets a new attribute. /// /// This returns a reference to the element so you can chain the calls. pub fn set_attr<'a, Q: AsQName<'a>, S: Into<String>>( &'a mut self, name: Q, value: S, ) -> &'a mut Element { self.attributes .insert(name.as_qname().share(), value.into()); self } /// Removes an attribute and returns the stored string. pub fn remove_attr<'a, Q: AsQName<'a>>(&'a mut self, name: Q) -> Option<String> { // so this requires some explanation. We store internally QName<'static> // which means the QName has a global lifetime. This works because we // move the internal string storage into a global string cache or we are // pointing to static memory in the binary. // // However while Rust can coerce our BTreeMap from QName<'static> to // QName<'a> when reading, we can't do the same when writing. This is // to prevent us from stashing a QName<'a> into the btreemap. However on // remove that restriction makes no sense so we can unsafely transmute it // away. I wish there was a better way though. use std::borrow::Borrow; let name = name.as_qname(); let name_ref: &QName<'a> = name.borrow(); let name_ref_static: &QName<'static> = unsafe { mem::transmute(name_ref) }; self.attributes.remove(name_ref_static) } /// Returns an iterator over all attributes pub fn attrs(&self) -> Attrs<'_> { Attrs { iter: self.attributes.iter(), } } /// Count the attributes pub fn attr_count(&self) -> usize { self.attributes.len() } fn get_nsmap_mut(&mut self) -> &mut NamespaceMap { let new_map = match self.nsmap { Some(ref mut nsmap) if Rc::strong_count(nsmap) == 1 => None, Some(ref mut nsmap) => Some(Rc::new((**nsmap).clone())), None => Some(Rc::new(NamespaceMap::new())), }; if let Some(nsmap) = new_map { self.nsmap = Some(nsmap); } Rc::get_mut(self.nsmap.as_mut().unwrap()).unwrap() } /// Registers a namespace with the internal namespace map. /// /// Note that there is no API to remove namespaces from an element once /// the namespace has been set so be careful with modifying this! /// /// This optionally also registers a specific prefix however if that prefix /// is already used a random one is used instead. pub fn register_namespace(&mut self, url: &str, prefix: Option<&str>) { if self.get_namespace_prefix(url).is_none() && self.get_nsmap_mut().register_if_missing(url, prefix) { self.emit_nsmap = true; } } /// Sets a specific namespace prefix. This will also register the /// namespace if it was unknown so far. /// /// In case a prefix is set that is already set elsewhere an error is /// returned. It's recommended that this method is only used on the /// root node before other prefixes are added. pub fn set_namespace_prefix(&mut self, url: &str, prefix: &str) -> Result<(), Error> { if self.get_namespace_prefix(url) == Some(prefix) { Ok(()) } else { self.get_nsmap_mut().set_prefix(url, prefix) } } /// Returns the assigned prefix for a namespace. pub fn get_namespace_prefix(&self, url: &str) -> Option<&str> { match url { NS_EMPTY_URI => Some(""), NS_XML_URI => Some("xml"), NS_XMLNS_URI => Some("xmlns"), _ => { if let Some(ref nsmap) = self.nsmap { nsmap.get_prefix(url) } else { None } } } } /// Finds the first element that match a given path downwards pub fn navigate<'a, Q: AsQName<'a>>(&'a self, path: &[Q]) -> Option<&'a Element> { use std::borrow::Borrow; let mut node = self; 'outer: for piece in path { let reftag = piece.as_qname(); for child in node.children() { if child.tag() == reftag.borrow() { node = child; continue 'outer; } } return None; } Some(node) } } /// Xml Prolog version handle by elementtree pub enum XmlProlog { Version10, Version11, } /// A struct that define write options. pub struct WriteOptions { xml_prolog: Option<XmlProlog>, } impl Default for WriteOptions { fn default() -> WriteOptions { WriteOptions { xml_prolog: Some(XmlProlog::Version10), } } } impl WriteOptions { pub fn new() -> WriteOptions { WriteOptions { ..WriteOptions::default() } } /// Define which xml prolog will be displayed when rendering an Element. /// /// Note that prolog is optional, an XML document with a missing prolog is well-formed but not valid. /// /// See RFC: [W3C XML 26 November 2008](https://www.w3.org/TR/xml/#sec-prolog-dtd) pub fn set_xml_prolog(mut self, prolog: Option<XmlProlog>) -> Self { self.xml_prolog = prolog; self } }<|fim▁end|>
/// ``` /// # use elementtree::QName; /// let a = QName::from("{http://www.w3.org/1999/xhtml}a"); /// ```
<|file_name|>GridFilters.js<|end_file_name|><|fim▁begin|>/** * Ext.ux.grid.GridFilters v0.2.7 **/ Ext.namespace("Ext.ux.grid"); Ext.ux.grid.GridFilters = function(config){ this.filters = new Ext.util.MixedCollection(); this.filters.getKey = function(o){return o ? o.dataIndex : null}; for(var i=0, len=config.filters.length; i<len; i++) this.addFilter(config.filters[i]); this.deferredUpdate = new Ext.util.DelayedTask(this.reload, this); delete config.filters; Ext.apply(this, config); }; Ext.extend(Ext.ux.grid.GridFilters, Ext.util.Observable, { /** * @cfg {Integer} updateBuffer * Number of milisecond to defer store updates since the last filter change. */ updateBuffer: 500, /** * @cfg {String} paramPrefix * The url parameter prefix for the filters. */ paramPrefix: 'filter', /** * @cfg {String} fitlerCls * The css class to be applied to column headers that active filters. Defaults to 'ux-filterd-column' */ filterCls: 'ux-filtered-column', /** * @cfg {Boolean} local * True to use Ext.data.Store filter functions instead of server side filtering. */ local: false, /** * @cfg {Boolean} autoReload * True to automagicly reload the datasource when a filter change happens. */ autoReload: true, /** * @cfg {String} stateId * Name of the Ext.data.Store value to be used to store state information. */ stateId: undefined, /** * @cfg {Boolean} showMenu * True to show the filter menus */ showMenu: true, menuFilterText: 'Filters', init: function(grid){ if(grid instanceof Ext.grid.GridPanel){ this.grid = grid; this.store = this.grid.getStore(); if(this.local){ this.store.on('load', function(store){ store.filterBy(this.getRecordFilter()); }, this); } else { this.store.on('beforeload', this.onBeforeLoad, this); } this.grid.filters = this; this.grid.addEvents({"filterupdate": true}); grid.on("render", this.onRender, this); grid.on("beforestaterestore", this.applyState, this); grid.on("beforestatesave", this.saveState, this); } else if(grid instanceof Ext.PagingToolbar){ this.toolbar = grid; } }, /** private **/ applyState: function(grid, state){ this.suspendStateStore = true; this.clearFilters(); if(state.filters) for(var key in state.filters){ var filter = this.filters.get(key); if(filter){ filter.setValue(state.filters[key]); filter.setActive(true); } } this.deferredUpdate.cancel(); if(this.local) this.reload(); this.suspendStateStore = false; }, /** private **/ saveState: function(grid, state){ var filters = {}; this.filters.each(function(filter){ if(filter.active) filters[filter.dataIndex] = filter.getValue(); });<|fim▁hole|> /** private **/ onRender: function(){ var hmenu; if(this.showMenu){ hmenu = this.grid.getView().hmenu; this.sep = hmenu.addSeparator(); this.menu = hmenu.add(new Ext.menu.CheckItem({ text: this.menuFilterText, menu: new Ext.menu.Menu() })); this.menu.on('checkchange', this.onCheckChange, this); this.menu.on('beforecheckchange', this.onBeforeCheck, this); hmenu.on('beforeshow', this.onMenu, this); } this.grid.getView().on("refresh", this.onRefresh, this); this.updateColumnHeadings(this.grid.getView()); }, /** private **/ onMenu: function(filterMenu){ var filter = this.getMenuFilter(); if(filter){ this.menu.menu = filter.menu; this.menu.setChecked(filter.active, false); } this.menu.setVisible(filter !== undefined); this.sep.setVisible(filter !== undefined); }, /** private **/ onCheckChange: function(item, value){ this.getMenuFilter().setActive(value); }, /** private **/ onBeforeCheck: function(check, value){ return !value || this.getMenuFilter().isActivatable(); }, /** private **/ onStateChange: function(event, filter){ if(event == "serialize") return; if(filter == this.getMenuFilter()) this.menu.setChecked(filter.active, false); if(this.autoReload || this.local) this.deferredUpdate.delay(this.updateBuffer); var view = this.grid.getView(); this.updateColumnHeadings(view); this.grid.saveState(); this.grid.fireEvent('filterupdate', this, filter); }, /** private **/ onBeforeLoad: function(store, options){ options.params = options.params || {}; this.cleanParams(options.params); var params = this.buildQuery(this.getFilterData()); Ext.apply(options.params, params); }, /** private **/ onRefresh: function(view){ this.updateColumnHeadings(view); }, /** private **/ getMenuFilter: function(){ var view = this.grid.getView(); if(!view || view.hdCtxIndex === undefined) return null; return this.filters.get( view.cm.config[view.hdCtxIndex].dataIndex); }, /** private **/ updateColumnHeadings: function(view){ if(!view || !view.mainHd) return; var hds = view.mainHd.select('td').removeClass(this.filterCls); for(var i=0, len=view.cm.config.length; i<len; i++){ var filter = this.getFilter(view.cm.config[i].dataIndex); if(filter && filter.active) hds.item(i).addClass(this.filterCls); } }, /** private **/ reload: function(){ if(this.local){ this.grid.store.clearFilter(true); this.grid.store.filterBy(this.getRecordFilter()); } else { this.deferredUpdate.cancel(); var store = this.grid.store; if(this.toolbar){ var start = this.toolbar.paramNames.start; if(store.lastOptions && store.lastOptions.params && store.lastOptions.params[start]) store.lastOptions.params[start] = 0; } store.reload(); } }, /** * Method factory that generates a record validator for the filters active at the time * of invokation. * * @private */ getRecordFilter: function(){ var f = []; this.filters.each(function(filter){ if(filter.active) f.push(filter); }); var len = f.length; return function(record){ for(var i=0; i<len; i++) if(!f[i].validateRecord(record)) return false; return true; }; }, /** * Adds a filter to the collection. * * @param {Object/Ext.ux.grid.filter.Filter} config A filter configuration or a filter object. * * @return {Ext.ux.grid.filter.Filter} The existing or newly created filter object. */ addFilter: function(config){ var filter = config.menu ? config : new (this.getFilterClass(config.type))(config); this.filters.add(filter); Ext.util.Observable.capture(filter, this.onStateChange, this); return filter; }, /** * Returns a filter for the given dataIndex, if on exists. * * @param {String} dataIndex The dataIndex of the desired filter object. * * @return {Ext.ux.grid.filter.Filter} */ getFilter: function(dataIndex){ return this.filters.get(dataIndex); }, /** * Turns all filters off. This does not clear the configuration information. */ clearFilters: function(){ this.filters.each(function(filter){ filter.setActive(false); }); }, /** private **/ getFilterData: function(){ var filters = [], fields = this.grid.getStore().fields; this.filters.each(function(f){ if(f.active){ var d = [].concat(f.serialize()); for(var i=0, len=d.length; i<len; i++) filters.push({ field: f.dataIndex, data: d[i] }); } }); return filters; }, /** * Function to take structured filter data and 'flatten' it into query parameteres. The default function * will produce a query string of the form: * filters[0][field]=dataIndex&filters[0][data][param1]=param&filters[0][data][param2]=param... * * @param {Array} filters A collection of objects representing active filters and their configuration. * Each element will take the form of {field: dataIndex, data: filterConf}. dataIndex is not assured * to be unique as any one filter may be a composite of more basic filters for the same dataIndex. * * @return {Object} Query keys and values */ buildQuery: function(filters){ var p = {}; for(var i=0, len=filters.length; i<len; i++){ var f = filters[i]; var root = [this.paramPrefix, '[', i, ']'].join(''); p[root + '[field]'] = f.field; var dataPrefix = root + '[data]'; for(var key in f.data) p[[dataPrefix, '[', key, ']'].join('')] = f.data[key]; } return p; }, /** * Removes filter related query parameters from the provided object. * * @param {Object} p Query parameters that may contain filter related fields. */ cleanParams: function(p){ var regex = new RegExp("^" + this.paramPrefix + "\[[0-9]+\]"); for(var key in p) if(regex.test(key)) delete p[key]; }, /** * Function for locating filter classes, overwrite this with your favorite * loader to provide dynamic filter loading. * * @param {String} type The type of filter to load. * * @return {Class} */ getFilterClass: function(type){ return Ext.ux.grid.filter[type.substr(0, 1).toUpperCase() + type.substr(1) + 'Filter']; } });<|fim▁end|>
return state.filters = filters; },
<|file_name|>cp852.py<|end_file_name|><|fim▁begin|><<<<<<< HEAD <<<<<<< HEAD """ Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP852.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_map)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='cp852', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x0085: 0x016f, # LATIN SMALL LETTER U WITH RING ABOVE 0x0086: 0x0107, # LATIN SMALL LETTER C WITH ACUTE 0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x0088: 0x0142, # LATIN SMALL LETTER L WITH STROKE 0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x008a: 0x0150, # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE 0x008b: 0x0151, # LATIN SMALL LETTER O WITH DOUBLE ACUTE 0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x008d: 0x0179, # LATIN CAPITAL LETTER Z WITH ACUTE 0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x008f: 0x0106, # LATIN CAPITAL LETTER C WITH ACUTE 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0091: 0x0139, # LATIN CAPITAL LETTER L WITH ACUTE 0x0092: 0x013a, # LATIN SMALL LETTER L WITH ACUTE 0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x0095: 0x013d, # LATIN CAPITAL LETTER L WITH CARON 0x0096: 0x013e, # LATIN SMALL LETTER L WITH CARON 0x0097: 0x015a, # LATIN CAPITAL LETTER S WITH ACUTE 0x0098: 0x015b, # LATIN SMALL LETTER S WITH ACUTE 0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x0164, # LATIN CAPITAL LETTER T WITH CARON 0x009c: 0x0165, # LATIN SMALL LETTER T WITH CARON 0x009d: 0x0141, # LATIN CAPITAL LETTER L WITH STROKE 0x009e: 0x00d7, # MULTIPLICATION SIGN 0x009f: 0x010d, # LATIN SMALL LETTER C WITH CARON 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00a4: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK 0x00a5: 0x0105, # LATIN SMALL LETTER A WITH OGONEK 0x00a6: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x00a7: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x00a8: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK 0x00a9: 0x0119, # LATIN SMALL LETTER E WITH OGONEK 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x017a, # LATIN SMALL LETTER Z WITH ACUTE 0x00ac: 0x010c, # LATIN CAPITAL LETTER C WITH CARON 0x00ad: 0x015f, # LATIN SMALL LETTER S WITH CEDILLA 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x00b6: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00b7: 0x011a, # LATIN CAPITAL LETTER E WITH CARON 0x00b8: 0x015e, # LATIN CAPITAL LETTER S WITH CEDILLA 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x017b, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x00be: 0x017c, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x0102, # LATIN CAPITAL LETTER A WITH BREVE 0x00c7: 0x0103, # LATIN SMALL LETTER A WITH BREVE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x00a4, # CURRENCY SIGN 0x00d0: 0x0111, # LATIN SMALL LETTER D WITH STROKE 0x00d1: 0x0110, # LATIN CAPITAL LETTER D WITH STROKE 0x00d2: 0x010e, # LATIN CAPITAL LETTER D WITH CARON 0x00d3: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00d4: 0x010f, # LATIN SMALL LETTER D WITH CARON 0x00d5: 0x0147, # LATIN CAPITAL LETTER N WITH CARON 0x00d6: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x00d7: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00d8: 0x011b, # LATIN SMALL LETTER E WITH CARON 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x0162, # LATIN CAPITAL LETTER T WITH CEDILLA 0x00de: 0x016e, # LATIN CAPITAL LETTER U WITH RING ABOVE 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S 0x00e2: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00e3: 0x0143, # LATIN CAPITAL LETTER N WITH ACUTE 0x00e4: 0x0144, # LATIN SMALL LETTER N WITH ACUTE 0x00e5: 0x0148, # LATIN SMALL LETTER N WITH CARON 0x00e6: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x00e7: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x00e8: 0x0154, # LATIN CAPITAL LETTER R WITH ACUTE 0x00e9: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00ea: 0x0155, # LATIN SMALL LETTER R WITH ACUTE 0x00eb: 0x0170, # LATIN CAPITAL LETTER U WITH DOUBLE ACUTE 0x00ec: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE 0x00ed: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE 0x00ee: 0x0163, # LATIN SMALL LETTER T WITH CEDILLA 0x00ef: 0x00b4, # ACUTE ACCENT 0x00f0: 0x00ad, # SOFT HYPHEN 0x00f1: 0x02dd, # DOUBLE ACUTE ACCENT 0x00f2: 0x02db, # OGONEK 0x00f3: 0x02c7, # CARON 0x00f4: 0x02d8, # BREVE 0x00f5: 0x00a7, # SECTION SIGN 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x00b8, # CEDILLA 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x00a8, # DIAERESIS 0x00fa: 0x02d9, # DOT ABOVE 0x00fb: 0x0171, # LATIN SMALL LETTER U WITH DOUBLE ACUTE 0x00fc: 0x0158, # LATIN CAPITAL LETTER R WITH CARON 0x00fd: 0x0159, # LATIN SMALL LETTER R WITH CARON 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Decoding Table decoding_table = ( '\x00' # 0x0000 -> NULL '\x01' # 0x0001 -> START OF HEADING '\x02' # 0x0002 -> START OF TEXT '\x03' # 0x0003 -> END OF TEXT '\x04' # 0x0004 -> END OF TRANSMISSION '\x05' # 0x0005 -> ENQUIRY '\x06' # 0x0006 -> ACKNOWLEDGE '\x07' # 0x0007 -> BELL '\x08' # 0x0008 -> BACKSPACE '\t' # 0x0009 -> HORIZONTAL TABULATION '\n' # 0x000a -> LINE FEED '\x0b' # 0x000b -> VERTICAL TABULATION '\x0c' # 0x000c -> FORM FEED '\r' # 0x000d -> CARRIAGE RETURN '\x0e' # 0x000e -> SHIFT OUT '\x0f' # 0x000f -> SHIFT IN '\x10' # 0x0010 -> DATA LINK ESCAPE '\x11' # 0x0011 -> DEVICE CONTROL ONE '\x12' # 0x0012 -> DEVICE CONTROL TWO '\x13' # 0x0013 -> DEVICE CONTROL THREE '\x14' # 0x0014 -> DEVICE CONTROL FOUR '\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE '\x16' # 0x0016 -> SYNCHRONOUS IDLE '\x17' # 0x0017 -> END OF TRANSMISSION BLOCK '\x18' # 0x0018 -> CANCEL '\x19' # 0x0019 -> END OF MEDIUM '\x1a' # 0x001a -> SUBSTITUTE '\x1b' # 0x001b -> ESCAPE '\x1c' # 0x001c -> FILE SEPARATOR '\x1d' # 0x001d -> GROUP SEPARATOR '\x1e' # 0x001e -> RECORD SEPARATOR '\x1f' # 0x001f -> UNIT SEPARATOR ' ' # 0x0020 -> SPACE '!' # 0x0021 -> EXCLAMATION MARK '"' # 0x0022 -> QUOTATION MARK '#' # 0x0023 -> NUMBER SIGN '$' # 0x0024 -> DOLLAR SIGN '%' # 0x0025 -> PERCENT SIGN '&' # 0x0026 -> AMPERSAND "'" # 0x0027 -> APOSTROPHE '(' # 0x0028 -> LEFT PARENTHESIS ')' # 0x0029 -> RIGHT PARENTHESIS '*' # 0x002a -> ASTERISK '+' # 0x002b -> PLUS SIGN ',' # 0x002c -> COMMA '-' # 0x002d -> HYPHEN-MINUS '.' # 0x002e -> FULL STOP '/' # 0x002f -> SOLIDUS '0' # 0x0030 -> DIGIT ZERO '1' # 0x0031 -> DIGIT ONE '2' # 0x0032 -> DIGIT TWO '3' # 0x0033 -> DIGIT THREE '4' # 0x0034 -> DIGIT FOUR '5' # 0x0035 -> DIGIT FIVE '6' # 0x0036 -> DIGIT SIX '7' # 0x0037 -> DIGIT SEVEN '8' # 0x0038 -> DIGIT EIGHT '9' # 0x0039 -> DIGIT NINE ':' # 0x003a -> COLON ';' # 0x003b -> SEMICOLON '<' # 0x003c -> LESS-THAN SIGN '=' # 0x003d -> EQUALS SIGN '>' # 0x003e -> GREATER-THAN SIGN '?' # 0x003f -> QUESTION MARK '@' # 0x0040 -> COMMERCIAL AT 'A' # 0x0041 -> LATIN CAPITAL LETTER A 'B' # 0x0042 -> LATIN CAPITAL LETTER B 'C' # 0x0043 -> LATIN CAPITAL LETTER C 'D' # 0x0044 -> LATIN CAPITAL LETTER D 'E' # 0x0045 -> LATIN CAPITAL LETTER E 'F' # 0x0046 -> LATIN CAPITAL LETTER F 'G' # 0x0047 -> LATIN CAPITAL LETTER G 'H' # 0x0048 -> LATIN CAPITAL LETTER H 'I' # 0x0049 -> LATIN CAPITAL LETTER I 'J' # 0x004a -> LATIN CAPITAL LETTER J 'K' # 0x004b -> LATIN CAPITAL LETTER K 'L' # 0x004c -> LATIN CAPITAL LETTER L 'M' # 0x004d -> LATIN CAPITAL LETTER M 'N' # 0x004e -> LATIN CAPITAL LETTER N 'O' # 0x004f -> LATIN CAPITAL LETTER O 'P' # 0x0050 -> LATIN CAPITAL LETTER P 'Q' # 0x0051 -> LATIN CAPITAL LETTER Q 'R' # 0x0052 -> LATIN CAPITAL LETTER R 'S' # 0x0053 -> LATIN CAPITAL LETTER S 'T' # 0x0054 -> LATIN CAPITAL LETTER T 'U' # 0x0055 -> LATIN CAPITAL LETTER U 'V' # 0x0056 -> LATIN CAPITAL LETTER V 'W' # 0x0057 -> LATIN CAPITAL LETTER W 'X' # 0x0058 -> LATIN CAPITAL LETTER X 'Y' # 0x0059 -> LATIN CAPITAL LETTER Y 'Z' # 0x005a -> LATIN CAPITAL LETTER Z '[' # 0x005b -> LEFT SQUARE BRACKET '\\' # 0x005c -> REVERSE SOLIDUS ']' # 0x005d -> RIGHT SQUARE BRACKET '^' # 0x005e -> CIRCUMFLEX ACCENT '_' # 0x005f -> LOW LINE '`' # 0x0060 -> GRAVE ACCENT 'a' # 0x0061 -> LATIN SMALL LETTER A 'b' # 0x0062 -> LATIN SMALL LETTER B 'c' # 0x0063 -> LATIN SMALL LETTER C 'd' # 0x0064 -> LATIN SMALL LETTER D 'e' # 0x0065 -> LATIN SMALL LETTER E 'f' # 0x0066 -> LATIN SMALL LETTER F 'g' # 0x0067 -> LATIN SMALL LETTER G 'h' # 0x0068 -> LATIN SMALL LETTER H 'i' # 0x0069 -> LATIN SMALL LETTER I 'j' # 0x006a -> LATIN SMALL LETTER J 'k' # 0x006b -> LATIN SMALL LETTER K 'l' # 0x006c -> LATIN SMALL LETTER L 'm' # 0x006d -> LATIN SMALL LETTER M 'n' # 0x006e -> LATIN SMALL LETTER N 'o' # 0x006f -> LATIN SMALL LETTER O 'p' # 0x0070 -> LATIN SMALL LETTER P 'q' # 0x0071 -> LATIN SMALL LETTER Q 'r' # 0x0072 -> LATIN SMALL LETTER R 's' # 0x0073 -> LATIN SMALL LETTER S 't' # 0x0074 -> LATIN SMALL LETTER T 'u' # 0x0075 -> LATIN SMALL LETTER U 'v' # 0x0076 -> LATIN SMALL LETTER V 'w' # 0x0077 -> LATIN SMALL LETTER W 'x' # 0x0078 -> LATIN SMALL LETTER X 'y' # 0x0079 -> LATIN SMALL LETTER Y 'z' # 0x007a -> LATIN SMALL LETTER Z '{' # 0x007b -> LEFT CURLY BRACKET '|' # 0x007c -> VERTICAL LINE '}' # 0x007d -> RIGHT CURLY BRACKET '~' # 0x007e -> TILDE '\x7f' # 0x007f -> DELETE '\xc7' # 0x0080 -> LATIN CAPITAL LETTER C WITH CEDILLA '\xfc' # 0x0081 -> LATIN SMALL LETTER U WITH DIAERESIS '\xe9' # 0x0082 -> LATIN SMALL LETTER E WITH ACUTE '\xe2' # 0x0083 -> LATIN SMALL LETTER A WITH CIRCUMFLEX '\xe4' # 0x0084 -> LATIN SMALL LETTER A WITH DIAERESIS '\u016f' # 0x0085 -> LATIN SMALL LETTER U WITH RING ABOVE '\u0107' # 0x0086 -> LATIN SMALL LETTER C WITH ACUTE '\xe7' # 0x0087 -> LATIN SMALL LETTER C WITH CEDILLA '\u0142' # 0x0088 -> LATIN SMALL LETTER L WITH STROKE '\xeb' # 0x0089 -> LATIN SMALL LETTER E WITH DIAERESIS '\u0150' # 0x008a -> LATIN CAPITAL LETTER O WITH DOUBLE ACUTE '\u0151' # 0x008b -> LATIN SMALL LETTER O WITH DOUBLE ACUTE '\xee' # 0x008c -> LATIN SMALL LETTER I WITH CIRCUMFLEX '\u0179' # 0x008d -> LATIN CAPITAL LETTER Z WITH ACUTE '\xc4' # 0x008e -> LATIN CAPITAL LETTER A WITH DIAERESIS '\u0106' # 0x008f -> LATIN CAPITAL LETTER C WITH ACUTE '\xc9' # 0x0090 -> LATIN CAPITAL LETTER E WITH ACUTE '\u0139' # 0x0091 -> LATIN CAPITAL LETTER L WITH ACUTE '\u013a' # 0x0092 -> LATIN SMALL LETTER L WITH ACUTE '\xf4' # 0x0093 -> LATIN SMALL LETTER O WITH CIRCUMFLEX '\xf6' # 0x0094 -> LATIN SMALL LETTER O WITH DIAERESIS '\u013d' # 0x0095 -> LATIN CAPITAL LETTER L WITH CARON '\u013e' # 0x0096 -> LATIN SMALL LETTER L WITH CARON '\u015a' # 0x0097 -> LATIN CAPITAL LETTER S WITH ACUTE '\u015b' # 0x0098 -> LATIN SMALL LETTER S WITH ACUTE '\xd6' # 0x0099 -> LATIN CAPITAL LETTER O WITH DIAERESIS '\xdc' # 0x009a -> LATIN CAPITAL LETTER U WITH DIAERESIS '\u0164' # 0x009b -> LATIN CAPITAL LETTER T WITH CARON '\u0165' # 0x009c -> LATIN SMALL LETTER T WITH CARON '\u0141' # 0x009d -> LATIN CAPITAL LETTER L WITH STROKE '\xd7' # 0x009e -> MULTIPLICATION SIGN '\u010d' # 0x009f -> LATIN SMALL LETTER C WITH CARON '\xe1' # 0x00a0 -> LATIN SMALL LETTER A WITH ACUTE '\xed' # 0x00a1 -> LATIN SMALL LETTER I WITH ACUTE '\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE '\xfa' # 0x00a3 -> LATIN SMALL LETTER U WITH ACUTE '\u0104' # 0x00a4 -> LATIN CAPITAL LETTER A WITH OGONEK '\u0105' # 0x00a5 -> LATIN SMALL LETTER A WITH OGONEK '\u017d' # 0x00a6 -> LATIN CAPITAL LETTER Z WITH CARON '\u017e' # 0x00a7 -> LATIN SMALL LETTER Z WITH CARON '\u0118' # 0x00a8 -> LATIN CAPITAL LETTER E WITH OGONEK '\u0119' # 0x00a9 -> LATIN SMALL LETTER E WITH OGONEK '\xac' # 0x00aa -> NOT SIGN '\u017a' # 0x00ab -> LATIN SMALL LETTER Z WITH ACUTE '\u010c' # 0x00ac -> LATIN CAPITAL LETTER C WITH CARON '\u015f' # 0x00ad -> LATIN SMALL LETTER S WITH CEDILLA '\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK '\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK '\u2591' # 0x00b0 -> LIGHT SHADE '\u2592' # 0x00b1 -> MEDIUM SHADE '\u2593' # 0x00b2 -> DARK SHADE '\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL '\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT '\xc1' # 0x00b5 -> LATIN CAPITAL LETTER A WITH ACUTE '\xc2' # 0x00b6 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX '\u011a' # 0x00b7 -> LATIN CAPITAL LETTER E WITH CARON '\u015e' # 0x00b8 -> LATIN CAPITAL LETTER S WITH CEDILLA '\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT '\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL '\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT '\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT '\u017b' # 0x00bd -> LATIN CAPITAL LETTER Z WITH DOT ABOVE '\u017c' # 0x00be -> LATIN SMALL LETTER Z WITH DOT ABOVE '\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT '\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT '\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL '\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL '\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT '\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL '\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL '\u0102' # 0x00c6 -> LATIN CAPITAL LETTER A WITH BREVE '\u0103' # 0x00c7 -> LATIN SMALL LETTER A WITH BREVE '\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT '\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT '\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL '\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL '\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT '\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL '\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL '\xa4' # 0x00cf -> CURRENCY SIGN '\u0111' # 0x00d0 -> LATIN SMALL LETTER D WITH STROKE '\u0110' # 0x00d1 -> LATIN CAPITAL LETTER D WITH STROKE '\u010e' # 0x00d2 -> LATIN CAPITAL LETTER D WITH CARON '\xcb' # 0x00d3 -> LATIN CAPITAL LETTER E WITH DIAERESIS '\u010f' # 0x00d4 -> LATIN SMALL LETTER D WITH CARON '\u0147' # 0x00d5 -> LATIN CAPITAL LETTER N WITH CARON '\xcd' # 0x00d6 -> LATIN CAPITAL LETTER I WITH ACUTE '\xce' # 0x00d7 -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX '\u011b' # 0x00d8 -> LATIN SMALL LETTER E WITH CARON '\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT '\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT '\u2588' # 0x00db -> FULL BLOCK '\u2584' # 0x00dc -> LOWER HALF BLOCK '\u0162' # 0x00dd -> LATIN CAPITAL LETTER T WITH CEDILLA '\u016e' # 0x00de -> LATIN CAPITAL LETTER U WITH RING ABOVE '\u2580' # 0x00df -> UPPER HALF BLOCK '\xd3' # 0x00e0 -> LATIN CAPITAL LETTER O WITH ACUTE '\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S '\xd4' # 0x00e2 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX '\u0143' # 0x00e3 -> LATIN CAPITAL LETTER N WITH ACUTE '\u0144' # 0x00e4 -> LATIN SMALL LETTER N WITH ACUTE '\u0148' # 0x00e5 -> LATIN SMALL LETTER N WITH CARON '\u0160' # 0x00e6 -> LATIN CAPITAL LETTER S WITH CARON '\u0161' # 0x00e7 -> LATIN SMALL LETTER S WITH CARON '\u0154' # 0x00e8 -> LATIN CAPITAL LETTER R WITH ACUTE '\xda' # 0x00e9 -> LATIN CAPITAL LETTER U WITH ACUTE '\u0155' # 0x00ea -> LATIN SMALL LETTER R WITH ACUTE '\u0170' # 0x00eb -> LATIN CAPITAL LETTER U WITH DOUBLE ACUTE '\xfd' # 0x00ec -> LATIN SMALL LETTER Y WITH ACUTE '\xdd' # 0x00ed -> LATIN CAPITAL LETTER Y WITH ACUTE '\u0163' # 0x00ee -> LATIN SMALL LETTER T WITH CEDILLA '\xb4' # 0x00ef -> ACUTE ACCENT '\xad' # 0x00f0 -> SOFT HYPHEN '\u02dd' # 0x00f1 -> DOUBLE ACUTE ACCENT '\u02db' # 0x00f2 -> OGONEK '\u02c7' # 0x00f3 -> CARON '\u02d8' # 0x00f4 -> BREVE '\xa7' # 0x00f5 -> SECTION SIGN '\xf7' # 0x00f6 -> DIVISION SIGN '\xb8' # 0x00f7 -> CEDILLA '\xb0' # 0x00f8 -> DEGREE SIGN '\xa8' # 0x00f9 -> DIAERESIS '\u02d9' # 0x00fa -> DOT ABOVE '\u0171' # 0x00fb -> LATIN SMALL LETTER U WITH DOUBLE ACUTE '\u0158' # 0x00fc -> LATIN CAPITAL LETTER R WITH CARON '\u0159' # 0x00fd -> LATIN SMALL LETTER R WITH CARON '\u25a0' # 0x00fe -> BLACK SQUARE '\xa0' # 0x00ff -> NO-BREAK SPACE ) ### Encoding Map encoding_map = { 0x0000: 0x0000, # NULL 0x0001: 0x0001, # START OF HEADING 0x0002: 0x0002, # START OF TEXT 0x0003: 0x0003, # END OF TEXT 0x0004: 0x0004, # END OF TRANSMISSION 0x0005: 0x0005, # ENQUIRY 0x0006: 0x0006, # ACKNOWLEDGE 0x0007: 0x0007, # BELL 0x0008: 0x0008, # BACKSPACE 0x0009: 0x0009, # HORIZONTAL TABULATION 0x000a: 0x000a, # LINE FEED 0x000b: 0x000b, # VERTICAL TABULATION 0x000c: 0x000c, # FORM FEED 0x000d: 0x000d, # CARRIAGE RETURN 0x000e: 0x000e, # SHIFT OUT 0x000f: 0x000f, # SHIFT IN 0x0010: 0x0010, # DATA LINK ESCAPE 0x0011: 0x0011, # DEVICE CONTROL ONE 0x0012: 0x0012, # DEVICE CONTROL TWO 0x0013: 0x0013, # DEVICE CONTROL THREE 0x0014: 0x0014, # DEVICE CONTROL FOUR 0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE 0x0016: 0x0016, # SYNCHRONOUS IDLE 0x0017: 0x0017, # END OF TRANSMISSION BLOCK 0x0018: 0x0018, # CANCEL 0x0019: 0x0019, # END OF MEDIUM 0x001a: 0x001a, # SUBSTITUTE 0x001b: 0x001b, # ESCAPE 0x001c: 0x001c, # FILE SEPARATOR 0x001d: 0x001d, # GROUP SEPARATOR 0x001e: 0x001e, # RECORD SEPARATOR 0x001f: 0x001f, # UNIT SEPARATOR 0x0020: 0x0020, # SPACE 0x0021: 0x0021, # EXCLAMATION MARK 0x0022: 0x0022, # QUOTATION MARK 0x0023: 0x0023, # NUMBER SIGN 0x0024: 0x0024, # DOLLAR SIGN 0x0025: 0x0025, # PERCENT SIGN 0x0026: 0x0026, # AMPERSAND 0x0027: 0x0027, # APOSTROPHE 0x0028: 0x0028, # LEFT PARENTHESIS 0x0029: 0x0029, # RIGHT PARENTHESIS 0x002a: 0x002a, # ASTERISK 0x002b: 0x002b, # PLUS SIGN 0x002c: 0x002c, # COMMA 0x002d: 0x002d, # HYPHEN-MINUS 0x002e: 0x002e, # FULL STOP 0x002f: 0x002f, # SOLIDUS 0x0030: 0x0030, # DIGIT ZERO 0x0031: 0x0031, # DIGIT ONE 0x0032: 0x0032, # DIGIT TWO 0x0033: 0x0033, # DIGIT THREE 0x0034: 0x0034, # DIGIT FOUR 0x0035: 0x0035, # DIGIT FIVE 0x0036: 0x0036, # DIGIT SIX 0x0037: 0x0037, # DIGIT SEVEN 0x0038: 0x0038, # DIGIT EIGHT 0x0039: 0x0039, # DIGIT NINE 0x003a: 0x003a, # COLON 0x003b: 0x003b, # SEMICOLON 0x003c: 0x003c, # LESS-THAN SIGN 0x003d: 0x003d, # EQUALS SIGN 0x003e: 0x003e, # GREATER-THAN SIGN 0x003f: 0x003f, # QUESTION MARK 0x0040: 0x0040, # COMMERCIAL AT 0x0041: 0x0041, # LATIN CAPITAL LETTER A 0x0042: 0x0042, # LATIN CAPITAL LETTER B 0x0043: 0x0043, # LATIN CAPITAL LETTER C 0x0044: 0x0044, # LATIN CAPITAL LETTER D 0x0045: 0x0045, # LATIN CAPITAL LETTER E 0x0046: 0x0046, # LATIN CAPITAL LETTER F 0x0047: 0x0047, # LATIN CAPITAL LETTER G 0x0048: 0x0048, # LATIN CAPITAL LETTER H 0x0049: 0x0049, # LATIN CAPITAL LETTER I 0x004a: 0x004a, # LATIN CAPITAL LETTER J 0x004b: 0x004b, # LATIN CAPITAL LETTER K 0x004c: 0x004c, # LATIN CAPITAL LETTER L 0x004d: 0x004d, # LATIN CAPITAL LETTER M 0x004e: 0x004e, # LATIN CAPITAL LETTER N 0x004f: 0x004f, # LATIN CAPITAL LETTER O 0x0050: 0x0050, # LATIN CAPITAL LETTER P 0x0051: 0x0051, # LATIN CAPITAL LETTER Q 0x0052: 0x0052, # LATIN CAPITAL LETTER R 0x0053: 0x0053, # LATIN CAPITAL LETTER S 0x0054: 0x0054, # LATIN CAPITAL LETTER T 0x0055: 0x0055, # LATIN CAPITAL LETTER U 0x0056: 0x0056, # LATIN CAPITAL LETTER V 0x0057: 0x0057, # LATIN CAPITAL LETTER W 0x0058: 0x0058, # LATIN CAPITAL LETTER X 0x0059: 0x0059, # LATIN CAPITAL LETTER Y 0x005a: 0x005a, # LATIN CAPITAL LETTER Z 0x005b: 0x005b, # LEFT SQUARE BRACKET 0x005c: 0x005c, # REVERSE SOLIDUS 0x005d: 0x005d, # RIGHT SQUARE BRACKET 0x005e: 0x005e, # CIRCUMFLEX ACCENT 0x005f: 0x005f, # LOW LINE 0x0060: 0x0060, # GRAVE ACCENT 0x0061: 0x0061, # LATIN SMALL LETTER A 0x0062: 0x0062, # LATIN SMALL LETTER B 0x0063: 0x0063, # LATIN SMALL LETTER C 0x0064: 0x0064, # LATIN SMALL LETTER D 0x0065: 0x0065, # LATIN SMALL LETTER E 0x0066: 0x0066, # LATIN SMALL LETTER F 0x0067: 0x0067, # LATIN SMALL LETTER G 0x0068: 0x0068, # LATIN SMALL LETTER H 0x0069: 0x0069, # LATIN SMALL LETTER I 0x006a: 0x006a, # LATIN SMALL LETTER J 0x006b: 0x006b, # LATIN SMALL LETTER K 0x006c: 0x006c, # LATIN SMALL LETTER L 0x006d: 0x006d, # LATIN SMALL LETTER M 0x006e: 0x006e, # LATIN SMALL LETTER N 0x006f: 0x006f, # LATIN SMALL LETTER O 0x0070: 0x0070, # LATIN SMALL LETTER P 0x0071: 0x0071, # LATIN SMALL LETTER Q 0x0072: 0x0072, # LATIN SMALL LETTER R 0x0073: 0x0073, # LATIN SMALL LETTER S 0x0074: 0x0074, # LATIN SMALL LETTER T 0x0075: 0x0075, # LATIN SMALL LETTER U 0x0076: 0x0076, # LATIN SMALL LETTER V 0x0077: 0x0077, # LATIN SMALL LETTER W 0x0078: 0x0078, # LATIN SMALL LETTER X 0x0079: 0x0079, # LATIN SMALL LETTER Y 0x007a: 0x007a, # LATIN SMALL LETTER Z 0x007b: 0x007b, # LEFT CURLY BRACKET 0x007c: 0x007c, # VERTICAL LINE 0x007d: 0x007d, # RIGHT CURLY BRACKET 0x007e: 0x007e, # TILDE 0x007f: 0x007f, # DELETE 0x00a0: 0x00ff, # NO-BREAK SPACE 0x00a4: 0x00cf, # CURRENCY SIGN 0x00a7: 0x00f5, # SECTION SIGN 0x00a8: 0x00f9, # DIAERESIS 0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00ac: 0x00aa, # NOT SIGN 0x00ad: 0x00f0, # SOFT HYPHEN 0x00b0: 0x00f8, # DEGREE SIGN 0x00b4: 0x00ef, # ACUTE ACCENT 0x00b8: 0x00f7, # CEDILLA 0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00c1: 0x00b5, # LATIN CAPITAL LETTER A WITH ACUTE 0x00c2: 0x00b6, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00c4: 0x008e, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x00c7: 0x0080, # LATIN CAPITAL LETTER C WITH CEDILLA 0x00c9: 0x0090, # LATIN CAPITAL LETTER E WITH ACUTE 0x00cb: 0x00d3, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00cd: 0x00d6, # LATIN CAPITAL LETTER I WITH ACUTE 0x00ce: 0x00d7, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00d3: 0x00e0, # LATIN CAPITAL LETTER O WITH ACUTE 0x00d4: 0x00e2, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00d6: 0x0099, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x00d7: 0x009e, # MULTIPLICATION SIGN 0x00da: 0x00e9, # LATIN CAPITAL LETTER U WITH ACUTE 0x00dc: 0x009a, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x00dd: 0x00ed, # LATIN CAPITAL LETTER Y WITH ACUTE 0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S 0x00e1: 0x00a0, # LATIN SMALL LETTER A WITH ACUTE 0x00e2: 0x0083, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x00e4: 0x0084, # LATIN SMALL LETTER A WITH DIAERESIS 0x00e7: 0x0087, # LATIN SMALL LETTER C WITH CEDILLA 0x00e9: 0x0082, # LATIN SMALL LETTER E WITH ACUTE 0x00eb: 0x0089, # LATIN SMALL LETTER E WITH DIAERESIS 0x00ed: 0x00a1, # LATIN SMALL LETTER I WITH ACUTE 0x00ee: 0x008c, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE 0x00f4: 0x0093, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x00f6: 0x0094, # LATIN SMALL LETTER O WITH DIAERESIS 0x00f7: 0x00f6, # DIVISION SIGN 0x00fa: 0x00a3, # LATIN SMALL LETTER U WITH ACUTE 0x00fc: 0x0081, # LATIN SMALL LETTER U WITH DIAERESIS 0x00fd: 0x00ec, # LATIN SMALL LETTER Y WITH ACUTE 0x0102: 0x00c6, # LATIN CAPITAL LETTER A WITH BREVE 0x0103: 0x00c7, # LATIN SMALL LETTER A WITH BREVE 0x0104: 0x00a4, # LATIN CAPITAL LETTER A WITH OGONEK 0x0105: 0x00a5, # LATIN SMALL LETTER A WITH OGONEK 0x0106: 0x008f, # LATIN CAPITAL LETTER C WITH ACUTE 0x0107: 0x0086, # LATIN SMALL LETTER C WITH ACUTE 0x010c: 0x00ac, # LATIN CAPITAL LETTER C WITH CARON 0x010d: 0x009f, # LATIN SMALL LETTER C WITH CARON 0x010e: 0x00d2, # LATIN CAPITAL LETTER D WITH CARON 0x010f: 0x00d4, # LATIN SMALL LETTER D WITH CARON 0x0110: 0x00d1, # LATIN CAPITAL LETTER D WITH STROKE 0x0111: 0x00d0, # LATIN SMALL LETTER D WITH STROKE 0x0118: 0x00a8, # LATIN CAPITAL LETTER E WITH OGONEK 0x0119: 0x00a9, # LATIN SMALL LETTER E WITH OGONEK 0x011a: 0x00b7, # LATIN CAPITAL LETTER E WITH CARON 0x011b: 0x00d8, # LATIN SMALL LETTER E WITH CARON 0x0139: 0x0091, # LATIN CAPITAL LETTER L WITH ACUTE 0x013a: 0x0092, # LATIN SMALL LETTER L WITH ACUTE 0x013d: 0x0095, # LATIN CAPITAL LETTER L WITH CARON 0x013e: 0x0096, # LATIN SMALL LETTER L WITH CARON 0x0141: 0x009d, # LATIN CAPITAL LETTER L WITH STROKE 0x0142: 0x0088, # LATIN SMALL LETTER L WITH STROKE 0x0143: 0x00e3, # LATIN CAPITAL LETTER N WITH ACUTE 0x0144: 0x00e4, # LATIN SMALL LETTER N WITH ACUTE 0x0147: 0x00d5, # LATIN CAPITAL LETTER N WITH CARON 0x0148: 0x00e5, # LATIN SMALL LETTER N WITH CARON 0x0150: 0x008a, # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE 0x0151: 0x008b, # LATIN SMALL LETTER O WITH DOUBLE ACUTE 0x0154: 0x00e8, # LATIN CAPITAL LETTER R WITH ACUTE 0x0155: 0x00ea, # LATIN SMALL LETTER R WITH ACUTE 0x0158: 0x00fc, # LATIN CAPITAL LETTER R WITH CARON 0x0159: 0x00fd, # LATIN SMALL LETTER R WITH CARON 0x015a: 0x0097, # LATIN CAPITAL LETTER S WITH ACUTE 0x015b: 0x0098, # LATIN SMALL LETTER S WITH ACUTE 0x015e: 0x00b8, # LATIN CAPITAL LETTER S WITH CEDILLA 0x015f: 0x00ad, # LATIN SMALL LETTER S WITH CEDILLA 0x0160: 0x00e6, # LATIN CAPITAL LETTER S WITH CARON 0x0161: 0x00e7, # LATIN SMALL LETTER S WITH CARON 0x0162: 0x00dd, # LATIN CAPITAL LETTER T WITH CEDILLA 0x0163: 0x00ee, # LATIN SMALL LETTER T WITH CEDILLA 0x0164: 0x009b, # LATIN CAPITAL LETTER T WITH CARON 0x0165: 0x009c, # LATIN SMALL LETTER T WITH CARON 0x016e: 0x00de, # LATIN CAPITAL LETTER U WITH RING ABOVE 0x016f: 0x0085, # LATIN SMALL LETTER U WITH RING ABOVE 0x0170: 0x00eb, # LATIN CAPITAL LETTER U WITH DOUBLE ACUTE 0x0171: 0x00fb, # LATIN SMALL LETTER U WITH DOUBLE ACUTE 0x0179: 0x008d, # LATIN CAPITAL LETTER Z WITH ACUTE 0x017a: 0x00ab, # LATIN SMALL LETTER Z WITH ACUTE 0x017b: 0x00bd, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x017c: 0x00be, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x017d: 0x00a6, # LATIN CAPITAL LETTER Z WITH CARON 0x017e: 0x00a7, # LATIN SMALL LETTER Z WITH CARON 0x02c7: 0x00f3, # CARON 0x02d8: 0x00f4, # BREVE 0x02d9: 0x00fa, # DOT ABOVE 0x02db: 0x00f2, # OGONEK 0x02dd: 0x00f1, # DOUBLE ACUTE ACCENT 0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL 0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL 0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT 0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT 0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL 0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL 0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT 0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x2580: 0x00df, # UPPER HALF BLOCK 0x2584: 0x00dc, # LOWER HALF BLOCK 0x2588: 0x00db, # FULL BLOCK 0x2591: 0x00b0, # LIGHT SHADE 0x2592: 0x00b1, # MEDIUM SHADE 0x2593: 0x00b2, # DARK SHADE 0x25a0: 0x00fe, # BLACK SQUARE } ======= """ Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP852.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_map)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='cp852', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x0085: 0x016f, # LATIN SMALL LETTER U WITH RING ABOVE 0x0086: 0x0107, # LATIN SMALL LETTER C WITH ACUTE 0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x0088: 0x0142, # LATIN SMALL LETTER L WITH STROKE 0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x008a: 0x0150, # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE 0x008b: 0x0151, # LATIN SMALL LETTER O WITH DOUBLE ACUTE 0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x008d: 0x0179, # LATIN CAPITAL LETTER Z WITH ACUTE 0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x008f: 0x0106, # LATIN CAPITAL LETTER C WITH ACUTE 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0091: 0x0139, # LATIN CAPITAL LETTER L WITH ACUTE 0x0092: 0x013a, # LATIN SMALL LETTER L WITH ACUTE 0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x0095: 0x013d, # LATIN CAPITAL LETTER L WITH CARON 0x0096: 0x013e, # LATIN SMALL LETTER L WITH CARON 0x0097: 0x015a, # LATIN CAPITAL LETTER S WITH ACUTE 0x0098: 0x015b, # LATIN SMALL LETTER S WITH ACUTE 0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x0164, # LATIN CAPITAL LETTER T WITH CARON 0x009c: 0x0165, # LATIN SMALL LETTER T WITH CARON 0x009d: 0x0141, # LATIN CAPITAL LETTER L WITH STROKE 0x009e: 0x00d7, # MULTIPLICATION SIGN 0x009f: 0x010d, # LATIN SMALL LETTER C WITH CARON 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00a4: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK 0x00a5: 0x0105, # LATIN SMALL LETTER A WITH OGONEK 0x00a6: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x00a7: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x00a8: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK 0x00a9: 0x0119, # LATIN SMALL LETTER E WITH OGONEK 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x017a, # LATIN SMALL LETTER Z WITH ACUTE 0x00ac: 0x010c, # LATIN CAPITAL LETTER C WITH CARON 0x00ad: 0x015f, # LATIN SMALL LETTER S WITH CEDILLA 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x00b6: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00b7: 0x011a, # LATIN CAPITAL LETTER E WITH CARON 0x00b8: 0x015e, # LATIN CAPITAL LETTER S WITH CEDILLA 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x017b, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x00be: 0x017c, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x0102, # LATIN CAPITAL LETTER A WITH BREVE 0x00c7: 0x0103, # LATIN SMALL LETTER A WITH BREVE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x00a4, # CURRENCY SIGN 0x00d0: 0x0111, # LATIN SMALL LETTER D WITH STROKE 0x00d1: 0x0110, # LATIN CAPITAL LETTER D WITH STROKE 0x00d2: 0x010e, # LATIN CAPITAL LETTER D WITH CARON 0x00d3: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00d4: 0x010f, # LATIN SMALL LETTER D WITH CARON 0x00d5: 0x0147, # LATIN CAPITAL LETTER N WITH CARON 0x00d6: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x00d7: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00d8: 0x011b, # LATIN SMALL LETTER E WITH CARON 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x0162, # LATIN CAPITAL LETTER T WITH CEDILLA 0x00de: 0x016e, # LATIN CAPITAL LETTER U WITH RING ABOVE 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S 0x00e2: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00e3: 0x0143, # LATIN CAPITAL LETTER N WITH ACUTE 0x00e4: 0x0144, # LATIN SMALL LETTER N WITH ACUTE 0x00e5: 0x0148, # LATIN SMALL LETTER N WITH CARON 0x00e6: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x00e7: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x00e8: 0x0154, # LATIN CAPITAL LETTER R WITH ACUTE 0x00e9: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00ea: 0x0155, # LATIN SMALL LETTER R WITH ACUTE 0x00eb: 0x0170, # LATIN CAPITAL LETTER U WITH DOUBLE ACUTE 0x00ec: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE 0x00ed: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE 0x00ee: 0x0163, # LATIN SMALL LETTER T WITH CEDILLA 0x00ef: 0x00b4, # ACUTE ACCENT 0x00f0: 0x00ad, # SOFT HYPHEN 0x00f1: 0x02dd, # DOUBLE ACUTE ACCENT 0x00f2: 0x02db, # OGONEK 0x00f3: 0x02c7, # CARON 0x00f4: 0x02d8, # BREVE 0x00f5: 0x00a7, # SECTION SIGN 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x00b8, # CEDILLA 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x00a8, # DIAERESIS 0x00fa: 0x02d9, # DOT ABOVE 0x00fb: 0x0171, # LATIN SMALL LETTER U WITH DOUBLE ACUTE 0x00fc: 0x0158, # LATIN CAPITAL LETTER R WITH CARON 0x00fd: 0x0159, # LATIN SMALL LETTER R WITH CARON 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Decoding Table decoding_table = ( '\x00' # 0x0000 -> NULL '\x01' # 0x0001 -> START OF HEADING '\x02' # 0x0002 -> START OF TEXT '\x03' # 0x0003 -> END OF TEXT '\x04' # 0x0004 -> END OF TRANSMISSION '\x05' # 0x0005 -> ENQUIRY '\x06' # 0x0006 -> ACKNOWLEDGE '\x07' # 0x0007 -> BELL '\x08' # 0x0008 -> BACKSPACE '\t' # 0x0009 -> HORIZONTAL TABULATION '\n' # 0x000a -> LINE FEED '\x0b' # 0x000b -> VERTICAL TABULATION '\x0c' # 0x000c -> FORM FEED '\r' # 0x000d -> CARRIAGE RETURN '\x0e' # 0x000e -> SHIFT OUT '\x0f' # 0x000f -> SHIFT IN '\x10' # 0x0010 -> DATA LINK ESCAPE '\x11' # 0x0011 -> DEVICE CONTROL ONE '\x12' # 0x0012 -> DEVICE CONTROL TWO '\x13' # 0x0013 -> DEVICE CONTROL THREE '\x14' # 0x0014 -> DEVICE CONTROL FOUR '\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE '\x16' # 0x0016 -> SYNCHRONOUS IDLE '\x17' # 0x0017 -> END OF TRANSMISSION BLOCK '\x18' # 0x0018 -> CANCEL '\x19' # 0x0019 -> END OF MEDIUM '\x1a' # 0x001a -> SUBSTITUTE '\x1b' # 0x001b -> ESCAPE '\x1c' # 0x001c -> FILE SEPARATOR '\x1d' # 0x001d -> GROUP SEPARATOR '\x1e' # 0x001e -> RECORD SEPARATOR '\x1f' # 0x001f -> UNIT SEPARATOR ' ' # 0x0020 -> SPACE '!' # 0x0021 -> EXCLAMATION MARK '"' # 0x0022 -> QUOTATION MARK '#' # 0x0023 -> NUMBER SIGN '$' # 0x0024 -> DOLLAR SIGN '%' # 0x0025 -> PERCENT SIGN '&' # 0x0026 -> AMPERSAND "'" # 0x0027 -> APOSTROPHE '(' # 0x0028 -> LEFT PARENTHESIS ')' # 0x0029 -> RIGHT PARENTHESIS '*' # 0x002a -> ASTERISK '+' # 0x002b -> PLUS SIGN ',' # 0x002c -> COMMA '-' # 0x002d -> HYPHEN-MINUS '.' # 0x002e -> FULL STOP '/' # 0x002f -> SOLIDUS '0' # 0x0030 -> DIGIT ZERO '1' # 0x0031 -> DIGIT ONE '2' # 0x0032 -> DIGIT TWO '3' # 0x0033 -> DIGIT THREE '4' # 0x0034 -> DIGIT FOUR '5' # 0x0035 -> DIGIT FIVE '6' # 0x0036 -> DIGIT SIX '7' # 0x0037 -> DIGIT SEVEN '8' # 0x0038 -> DIGIT EIGHT '9' # 0x0039 -> DIGIT NINE ':' # 0x003a -> COLON ';' # 0x003b -> SEMICOLON '<' # 0x003c -> LESS-THAN SIGN '=' # 0x003d -> EQUALS SIGN '>' # 0x003e -> GREATER-THAN SIGN '?' # 0x003f -> QUESTION MARK '@' # 0x0040 -> COMMERCIAL AT 'A' # 0x0041 -> LATIN CAPITAL LETTER A 'B' # 0x0042 -> LATIN CAPITAL LETTER B 'C' # 0x0043 -> LATIN CAPITAL LETTER C 'D' # 0x0044 -> LATIN CAPITAL LETTER D 'E' # 0x0045 -> LATIN CAPITAL LETTER E 'F' # 0x0046 -> LATIN CAPITAL LETTER F 'G' # 0x0047 -> LATIN CAPITAL LETTER G 'H' # 0x0048 -> LATIN CAPITAL LETTER H 'I' # 0x0049 -> LATIN CAPITAL LETTER I 'J' # 0x004a -> LATIN CAPITAL LETTER J 'K' # 0x004b -> LATIN CAPITAL LETTER K 'L' # 0x004c -> LATIN CAPITAL LETTER L 'M' # 0x004d -> LATIN CAPITAL LETTER M 'N' # 0x004e -> LATIN CAPITAL LETTER N 'O' # 0x004f -> LATIN CAPITAL LETTER O 'P' # 0x0050 -> LATIN CAPITAL LETTER P 'Q' # 0x0051 -> LATIN CAPITAL LETTER Q 'R' # 0x0052 -> LATIN CAPITAL LETTER R 'S' # 0x0053 -> LATIN CAPITAL LETTER S 'T' # 0x0054 -> LATIN CAPITAL LETTER T 'U' # 0x0055 -> LATIN CAPITAL LETTER U 'V' # 0x0056 -> LATIN CAPITAL LETTER V 'W' # 0x0057 -> LATIN CAPITAL LETTER W 'X' # 0x0058 -> LATIN CAPITAL LETTER X 'Y' # 0x0059 -> LATIN CAPITAL LETTER Y 'Z' # 0x005a -> LATIN CAPITAL LETTER Z '[' # 0x005b -> LEFT SQUARE BRACKET '\\' # 0x005c -> REVERSE SOLIDUS ']' # 0x005d -> RIGHT SQUARE BRACKET '^' # 0x005e -> CIRCUMFLEX ACCENT '_' # 0x005f -> LOW LINE '`' # 0x0060 -> GRAVE ACCENT 'a' # 0x0061 -> LATIN SMALL LETTER A 'b' # 0x0062 -> LATIN SMALL LETTER B 'c' # 0x0063 -> LATIN SMALL LETTER C 'd' # 0x0064 -> LATIN SMALL LETTER D 'e' # 0x0065 -> LATIN SMALL LETTER E 'f' # 0x0066 -> LATIN SMALL LETTER F 'g' # 0x0067 -> LATIN SMALL LETTER G 'h' # 0x0068 -> LATIN SMALL LETTER H 'i' # 0x0069 -> LATIN SMALL LETTER I 'j' # 0x006a -> LATIN SMALL LETTER J 'k' # 0x006b -> LATIN SMALL LETTER K 'l' # 0x006c -> LATIN SMALL LETTER L 'm' # 0x006d -> LATIN SMALL LETTER M 'n' # 0x006e -> LATIN SMALL LETTER N 'o' # 0x006f -> LATIN SMALL LETTER O 'p' # 0x0070 -> LATIN SMALL LETTER P 'q' # 0x0071 -> LATIN SMALL LETTER Q 'r' # 0x0072 -> LATIN SMALL LETTER R 's' # 0x0073 -> LATIN SMALL LETTER S 't' # 0x0074 -> LATIN SMALL LETTER T 'u' # 0x0075 -> LATIN SMALL LETTER U 'v' # 0x0076 -> LATIN SMALL LETTER V 'w' # 0x0077 -> LATIN SMALL LETTER W 'x' # 0x0078 -> LATIN SMALL LETTER X 'y' # 0x0079 -> LATIN SMALL LETTER Y 'z' # 0x007a -> LATIN SMALL LETTER Z '{' # 0x007b -> LEFT CURLY BRACKET '|' # 0x007c -> VERTICAL LINE '}' # 0x007d -> RIGHT CURLY BRACKET '~' # 0x007e -> TILDE '\x7f' # 0x007f -> DELETE '\xc7' # 0x0080 -> LATIN CAPITAL LETTER C WITH CEDILLA '\xfc' # 0x0081 -> LATIN SMALL LETTER U WITH DIAERESIS '\xe9' # 0x0082 -> LATIN SMALL LETTER E WITH ACUTE '\xe2' # 0x0083 -> LATIN SMALL LETTER A WITH CIRCUMFLEX '\xe4' # 0x0084 -> LATIN SMALL LETTER A WITH DIAERESIS '\u016f' # 0x0085 -> LATIN SMALL LETTER U WITH RING ABOVE '\u0107' # 0x0086 -> LATIN SMALL LETTER C WITH ACUTE '\xe7' # 0x0087 -> LATIN SMALL LETTER C WITH CEDILLA '\u0142' # 0x0088 -> LATIN SMALL LETTER L WITH STROKE '\xeb' # 0x0089 -> LATIN SMALL LETTER E WITH DIAERESIS '\u0150' # 0x008a -> LATIN CAPITAL LETTER O WITH DOUBLE ACUTE '\u0151' # 0x008b -> LATIN SMALL LETTER O WITH DOUBLE ACUTE '\xee' # 0x008c -> LATIN SMALL LETTER I WITH CIRCUMFLEX '\u0179' # 0x008d -> LATIN CAPITAL LETTER Z WITH ACUTE '\xc4' # 0x008e -> LATIN CAPITAL LETTER A WITH DIAERESIS '\u0106' # 0x008f -> LATIN CAPITAL LETTER C WITH ACUTE '\xc9' # 0x0090 -> LATIN CAPITAL LETTER E WITH ACUTE '\u0139' # 0x0091 -> LATIN CAPITAL LETTER L WITH ACUTE '\u013a' # 0x0092 -> LATIN SMALL LETTER L WITH ACUTE '\xf4' # 0x0093 -> LATIN SMALL LETTER O WITH CIRCUMFLEX '\xf6' # 0x0094 -> LATIN SMALL LETTER O WITH DIAERESIS '\u013d' # 0x0095 -> LATIN CAPITAL LETTER L WITH CARON '\u013e' # 0x0096 -> LATIN SMALL LETTER L WITH CARON '\u015a' # 0x0097 -> LATIN CAPITAL LETTER S WITH ACUTE '\u015b' # 0x0098 -> LATIN SMALL LETTER S WITH ACUTE '\xd6' # 0x0099 -> LATIN CAPITAL LETTER O WITH DIAERESIS '\xdc' # 0x009a -> LATIN CAPITAL LETTER U WITH DIAERESIS '\u0164' # 0x009b -> LATIN CAPITAL LETTER T WITH CARON '\u0165' # 0x009c -> LATIN SMALL LETTER T WITH CARON '\u0141' # 0x009d -> LATIN CAPITAL LETTER L WITH STROKE '\xd7' # 0x009e -> MULTIPLICATION SIGN '\u010d' # 0x009f -> LATIN SMALL LETTER C WITH CARON '\xe1' # 0x00a0 -> LATIN SMALL LETTER A WITH ACUTE '\xed' # 0x00a1 -> LATIN SMALL LETTER I WITH ACUTE '\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE '\xfa' # 0x00a3 -> LATIN SMALL LETTER U WITH ACUTE '\u0104' # 0x00a4 -> LATIN CAPITAL LETTER A WITH OGONEK '\u0105' # 0x00a5 -> LATIN SMALL LETTER A WITH OGONEK '\u017d' # 0x00a6 -> LATIN CAPITAL LETTER Z WITH CARON '\u017e' # 0x00a7 -> LATIN SMALL LETTER Z WITH CARON '\u0118' # 0x00a8 -> LATIN CAPITAL LETTER E WITH OGONEK '\u0119' # 0x00a9 -> LATIN SMALL LETTER E WITH OGONEK '\xac' # 0x00aa -> NOT SIGN '\u017a' # 0x00ab -> LATIN SMALL LETTER Z WITH ACUTE '\u010c' # 0x00ac -> LATIN CAPITAL LETTER C WITH CARON '\u015f' # 0x00ad -> LATIN SMALL LETTER S WITH CEDILLA '\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK '\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK '\u2591' # 0x00b0 -> LIGHT SHADE '\u2592' # 0x00b1 -> MEDIUM SHADE '\u2593' # 0x00b2 -> DARK SHADE '\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL '\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT '\xc1' # 0x00b5 -> LATIN CAPITAL LETTER A WITH ACUTE '\xc2' # 0x00b6 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX '\u011a' # 0x00b7 -> LATIN CAPITAL LETTER E WITH CARON '\u015e' # 0x00b8 -> LATIN CAPITAL LETTER S WITH CEDILLA '\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT '\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL '\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT '\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT '\u017b' # 0x00bd -> LATIN CAPITAL LETTER Z WITH DOT ABOVE '\u017c' # 0x00be -> LATIN SMALL LETTER Z WITH DOT ABOVE '\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT '\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT '\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL '\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL '\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT '\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL '\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL '\u0102' # 0x00c6 -> LATIN CAPITAL LETTER A WITH BREVE '\u0103' # 0x00c7 -> LATIN SMALL LETTER A WITH BREVE '\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT '\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT '\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL '\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL '\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT '\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL '\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL '\xa4' # 0x00cf -> CURRENCY SIGN '\u0111' # 0x00d0 -> LATIN SMALL LETTER D WITH STROKE '\u0110' # 0x00d1 -> LATIN CAPITAL LETTER D WITH STROKE '\u010e' # 0x00d2 -> LATIN CAPITAL LETTER D WITH CARON '\xcb' # 0x00d3 -> LATIN CAPITAL LETTER E WITH DIAERESIS '\u010f' # 0x00d4 -> LATIN SMALL LETTER D WITH CARON '\u0147' # 0x00d5 -> LATIN CAPITAL LETTER N WITH CARON '\xcd' # 0x00d6 -> LATIN CAPITAL LETTER I WITH ACUTE '\xce' # 0x00d7 -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX '\u011b' # 0x00d8 -> LATIN SMALL LETTER E WITH CARON '\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT '\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT '\u2588' # 0x00db -> FULL BLOCK '\u2584' # 0x00dc -> LOWER HALF BLOCK '\u0162' # 0x00dd -> LATIN CAPITAL LETTER T WITH CEDILLA '\u016e' # 0x00de -> LATIN CAPITAL LETTER U WITH RING ABOVE '\u2580' # 0x00df -> UPPER HALF BLOCK '\xd3' # 0x00e0 -> LATIN CAPITAL LETTER O WITH ACUTE '\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S '\xd4' # 0x00e2 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX '\u0143' # 0x00e3 -> LATIN CAPITAL LETTER N WITH ACUTE '\u0144' # 0x00e4 -> LATIN SMALL LETTER N WITH ACUTE '\u0148' # 0x00e5 -> LATIN SMALL LETTER N WITH CARON '\u0160' # 0x00e6 -> LATIN CAPITAL LETTER S WITH CARON '\u0161' # 0x00e7 -> LATIN SMALL LETTER S WITH CARON '\u0154' # 0x00e8 -> LATIN CAPITAL LETTER R WITH ACUTE '\xda' # 0x00e9 -> LATIN CAPITAL LETTER U WITH ACUTE '\u0155' # 0x00ea -> LATIN SMALL LETTER R WITH ACUTE '\u0170' # 0x00eb -> LATIN CAPITAL LETTER U WITH DOUBLE ACUTE '\xfd' # 0x00ec -> LATIN SMALL LETTER Y WITH ACUTE '\xdd' # 0x00ed -> LATIN CAPITAL LETTER Y WITH ACUTE '\u0163' # 0x00ee -> LATIN SMALL LETTER T WITH CEDILLA '\xb4' # 0x00ef -> ACUTE ACCENT '\xad' # 0x00f0 -> SOFT HYPHEN '\u02dd' # 0x00f1 -> DOUBLE ACUTE ACCENT '\u02db' # 0x00f2 -> OGONEK '\u02c7' # 0x00f3 -> CARON '\u02d8' # 0x00f4 -> BREVE '\xa7' # 0x00f5 -> SECTION SIGN '\xf7' # 0x00f6 -> DIVISION SIGN '\xb8' # 0x00f7 -> CEDILLA '\xb0' # 0x00f8 -> DEGREE SIGN '\xa8' # 0x00f9 -> DIAERESIS '\u02d9' # 0x00fa -> DOT ABOVE '\u0171' # 0x00fb -> LATIN SMALL LETTER U WITH DOUBLE ACUTE '\u0158' # 0x00fc -> LATIN CAPITAL LETTER R WITH CARON '\u0159' # 0x00fd -> LATIN SMALL LETTER R WITH CARON '\u25a0' # 0x00fe -> BLACK SQUARE '\xa0' # 0x00ff -> NO-BREAK SPACE ) ### Encoding Map encoding_map = { 0x0000: 0x0000, # NULL 0x0001: 0x0001, # START OF HEADING 0x0002: 0x0002, # START OF TEXT 0x0003: 0x0003, # END OF TEXT 0x0004: 0x0004, # END OF TRANSMISSION 0x0005: 0x0005, # ENQUIRY 0x0006: 0x0006, # ACKNOWLEDGE 0x0007: 0x0007, # BELL 0x0008: 0x0008, # BACKSPACE 0x0009: 0x0009, # HORIZONTAL TABULATION 0x000a: 0x000a, # LINE FEED 0x000b: 0x000b, # VERTICAL TABULATION 0x000c: 0x000c, # FORM FEED 0x000d: 0x000d, # CARRIAGE RETURN 0x000e: 0x000e, # SHIFT OUT 0x000f: 0x000f, # SHIFT IN 0x0010: 0x0010, # DATA LINK ESCAPE 0x0011: 0x0011, # DEVICE CONTROL ONE 0x0012: 0x0012, # DEVICE CONTROL TWO 0x0013: 0x0013, # DEVICE CONTROL THREE 0x0014: 0x0014, # DEVICE CONTROL FOUR 0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE 0x0016: 0x0016, # SYNCHRONOUS IDLE 0x0017: 0x0017, # END OF TRANSMISSION BLOCK 0x0018: 0x0018, # CANCEL 0x0019: 0x0019, # END OF MEDIUM 0x001a: 0x001a, # SUBSTITUTE 0x001b: 0x001b, # ESCAPE 0x001c: 0x001c, # FILE SEPARATOR 0x001d: 0x001d, # GROUP SEPARATOR 0x001e: 0x001e, # RECORD SEPARATOR 0x001f: 0x001f, # UNIT SEPARATOR 0x0020: 0x0020, # SPACE 0x0021: 0x0021, # EXCLAMATION MARK 0x0022: 0x0022, # QUOTATION MARK 0x0023: 0x0023, # NUMBER SIGN 0x0024: 0x0024, # DOLLAR SIGN 0x0025: 0x0025, # PERCENT SIGN 0x0026: 0x0026, # AMPERSAND 0x0027: 0x0027, # APOSTROPHE 0x0028: 0x0028, # LEFT PARENTHESIS 0x0029: 0x0029, # RIGHT PARENTHESIS 0x002a: 0x002a, # ASTERISK 0x002b: 0x002b, # PLUS SIGN 0x002c: 0x002c, # COMMA 0x002d: 0x002d, # HYPHEN-MINUS 0x002e: 0x002e, # FULL STOP 0x002f: 0x002f, # SOLIDUS 0x0030: 0x0030, # DIGIT ZERO 0x0031: 0x0031, # DIGIT ONE 0x0032: 0x0032, # DIGIT TWO 0x0033: 0x0033, # DIGIT THREE 0x0034: 0x0034, # DIGIT FOUR 0x0035: 0x0035, # DIGIT FIVE 0x0036: 0x0036, # DIGIT SIX 0x0037: 0x0037, # DIGIT SEVEN 0x0038: 0x0038, # DIGIT EIGHT 0x0039: 0x0039, # DIGIT NINE 0x003a: 0x003a, # COLON 0x003b: 0x003b, # SEMICOLON 0x003c: 0x003c, # LESS-THAN SIGN 0x003d: 0x003d, # EQUALS SIGN 0x003e: 0x003e, # GREATER-THAN SIGN 0x003f: 0x003f, # QUESTION MARK 0x0040: 0x0040, # COMMERCIAL AT 0x0041: 0x0041, # LATIN CAPITAL LETTER A 0x0042: 0x0042, # LATIN CAPITAL LETTER B 0x0043: 0x0043, # LATIN CAPITAL LETTER C 0x0044: 0x0044, # LATIN CAPITAL LETTER D 0x0045: 0x0045, # LATIN CAPITAL LETTER E 0x0046: 0x0046, # LATIN CAPITAL LETTER F 0x0047: 0x0047, # LATIN CAPITAL LETTER G 0x0048: 0x0048, # LATIN CAPITAL LETTER H 0x0049: 0x0049, # LATIN CAPITAL LETTER I 0x004a: 0x004a, # LATIN CAPITAL LETTER J 0x004b: 0x004b, # LATIN CAPITAL LETTER K 0x004c: 0x004c, # LATIN CAPITAL LETTER L 0x004d: 0x004d, # LATIN CAPITAL LETTER M 0x004e: 0x004e, # LATIN CAPITAL LETTER N 0x004f: 0x004f, # LATIN CAPITAL LETTER O 0x0050: 0x0050, # LATIN CAPITAL LETTER P 0x0051: 0x0051, # LATIN CAPITAL LETTER Q 0x0052: 0x0052, # LATIN CAPITAL LETTER R 0x0053: 0x0053, # LATIN CAPITAL LETTER S 0x0054: 0x0054, # LATIN CAPITAL LETTER T 0x0055: 0x0055, # LATIN CAPITAL LETTER U 0x0056: 0x0056, # LATIN CAPITAL LETTER V 0x0057: 0x0057, # LATIN CAPITAL LETTER W 0x0058: 0x0058, # LATIN CAPITAL LETTER X 0x0059: 0x0059, # LATIN CAPITAL LETTER Y 0x005a: 0x005a, # LATIN CAPITAL LETTER Z 0x005b: 0x005b, # LEFT SQUARE BRACKET 0x005c: 0x005c, # REVERSE SOLIDUS 0x005d: 0x005d, # RIGHT SQUARE BRACKET 0x005e: 0x005e, # CIRCUMFLEX ACCENT 0x005f: 0x005f, # LOW LINE 0x0060: 0x0060, # GRAVE ACCENT 0x0061: 0x0061, # LATIN SMALL LETTER A 0x0062: 0x0062, # LATIN SMALL LETTER B 0x0063: 0x0063, # LATIN SMALL LETTER C 0x0064: 0x0064, # LATIN SMALL LETTER D 0x0065: 0x0065, # LATIN SMALL LETTER E 0x0066: 0x0066, # LATIN SMALL LETTER F 0x0067: 0x0067, # LATIN SMALL LETTER G 0x0068: 0x0068, # LATIN SMALL LETTER H 0x0069: 0x0069, # LATIN SMALL LETTER I 0x006a: 0x006a, # LATIN SMALL LETTER J 0x006b: 0x006b, # LATIN SMALL LETTER K 0x006c: 0x006c, # LATIN SMALL LETTER L 0x006d: 0x006d, # LATIN SMALL LETTER M 0x006e: 0x006e, # LATIN SMALL LETTER N 0x006f: 0x006f, # LATIN SMALL LETTER O 0x0070: 0x0070, # LATIN SMALL LETTER P 0x0071: 0x0071, # LATIN SMALL LETTER Q 0x0072: 0x0072, # LATIN SMALL LETTER R 0x0073: 0x0073, # LATIN SMALL LETTER S 0x0074: 0x0074, # LATIN SMALL LETTER T 0x0075: 0x0075, # LATIN SMALL LETTER U 0x0076: 0x0076, # LATIN SMALL LETTER V 0x0077: 0x0077, # LATIN SMALL LETTER W 0x0078: 0x0078, # LATIN SMALL LETTER X 0x0079: 0x0079, # LATIN SMALL LETTER Y 0x007a: 0x007a, # LATIN SMALL LETTER Z 0x007b: 0x007b, # LEFT CURLY BRACKET 0x007c: 0x007c, # VERTICAL LINE 0x007d: 0x007d, # RIGHT CURLY BRACKET 0x007e: 0x007e, # TILDE 0x007f: 0x007f, # DELETE 0x00a0: 0x00ff, # NO-BREAK SPACE 0x00a4: 0x00cf, # CURRENCY SIGN 0x00a7: 0x00f5, # SECTION SIGN 0x00a8: 0x00f9, # DIAERESIS 0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00ac: 0x00aa, # NOT SIGN 0x00ad: 0x00f0, # SOFT HYPHEN 0x00b0: 0x00f8, # DEGREE SIGN 0x00b4: 0x00ef, # ACUTE ACCENT 0x00b8: 0x00f7, # CEDILLA 0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00c1: 0x00b5, # LATIN CAPITAL LETTER A WITH ACUTE 0x00c2: 0x00b6, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00c4: 0x008e, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x00c7: 0x0080, # LATIN CAPITAL LETTER C WITH CEDILLA 0x00c9: 0x0090, # LATIN CAPITAL LETTER E WITH ACUTE 0x00cb: 0x00d3, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00cd: 0x00d6, # LATIN CAPITAL LETTER I WITH ACUTE 0x00ce: 0x00d7, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00d3: 0x00e0, # LATIN CAPITAL LETTER O WITH ACUTE 0x00d4: 0x00e2, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00d6: 0x0099, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x00d7: 0x009e, # MULTIPLICATION SIGN 0x00da: 0x00e9, # LATIN CAPITAL LETTER U WITH ACUTE 0x00dc: 0x009a, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x00dd: 0x00ed, # LATIN CAPITAL LETTER Y WITH ACUTE 0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S 0x00e1: 0x00a0, # LATIN SMALL LETTER A WITH ACUTE 0x00e2: 0x0083, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x00e4: 0x0084, # LATIN SMALL LETTER A WITH DIAERESIS 0x00e7: 0x0087, # LATIN SMALL LETTER C WITH CEDILLA 0x00e9: 0x0082, # LATIN SMALL LETTER E WITH ACUTE 0x00eb: 0x0089, # LATIN SMALL LETTER E WITH DIAERESIS 0x00ed: 0x00a1, # LATIN SMALL LETTER I WITH ACUTE 0x00ee: 0x008c, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE 0x00f4: 0x0093, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x00f6: 0x0094, # LATIN SMALL LETTER O WITH DIAERESIS 0x00f7: 0x00f6, # DIVISION SIGN 0x00fa: 0x00a3, # LATIN SMALL LETTER U WITH ACUTE 0x00fc: 0x0081, # LATIN SMALL LETTER U WITH DIAERESIS 0x00fd: 0x00ec, # LATIN SMALL LETTER Y WITH ACUTE 0x0102: 0x00c6, # LATIN CAPITAL LETTER A WITH BREVE 0x0103: 0x00c7, # LATIN SMALL LETTER A WITH BREVE 0x0104: 0x00a4, # LATIN CAPITAL LETTER A WITH OGONEK 0x0105: 0x00a5, # LATIN SMALL LETTER A WITH OGONEK 0x0106: 0x008f, # LATIN CAPITAL LETTER C WITH ACUTE 0x0107: 0x0086, # LATIN SMALL LETTER C WITH ACUTE 0x010c: 0x00ac, # LATIN CAPITAL LETTER C WITH CARON 0x010d: 0x009f, # LATIN SMALL LETTER C WITH CARON 0x010e: 0x00d2, # LATIN CAPITAL LETTER D WITH CARON 0x010f: 0x00d4, # LATIN SMALL LETTER D WITH CARON 0x0110: 0x00d1, # LATIN CAPITAL LETTER D WITH STROKE 0x0111: 0x00d0, # LATIN SMALL LETTER D WITH STROKE 0x0118: 0x00a8, # LATIN CAPITAL LETTER E WITH OGONEK 0x0119: 0x00a9, # LATIN SMALL LETTER E WITH OGONEK 0x011a: 0x00b7, # LATIN CAPITAL LETTER E WITH CARON 0x011b: 0x00d8, # LATIN SMALL LETTER E WITH CARON 0x0139: 0x0091, # LATIN CAPITAL LETTER L WITH ACUTE 0x013a: 0x0092, # LATIN SMALL LETTER L WITH ACUTE 0x013d: 0x0095, # LATIN CAPITAL LETTER L WITH CARON 0x013e: 0x0096, # LATIN SMALL LETTER L WITH CARON 0x0141: 0x009d, # LATIN CAPITAL LETTER L WITH STROKE 0x0142: 0x0088, # LATIN SMALL LETTER L WITH STROKE 0x0143: 0x00e3, # LATIN CAPITAL LETTER N WITH ACUTE 0x0144: 0x00e4, # LATIN SMALL LETTER N WITH ACUTE 0x0147: 0x00d5, # LATIN CAPITAL LETTER N WITH CARON 0x0148: 0x00e5, # LATIN SMALL LETTER N WITH CARON 0x0150: 0x008a, # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE 0x0151: 0x008b, # LATIN SMALL LETTER O WITH DOUBLE ACUTE 0x0154: 0x00e8, # LATIN CAPITAL LETTER R WITH ACUTE 0x0155: 0x00ea, # LATIN SMALL LETTER R WITH ACUTE 0x0158: 0x00fc, # LATIN CAPITAL LETTER R WITH CARON 0x0159: 0x00fd, # LATIN SMALL LETTER R WITH CARON 0x015a: 0x0097, # LATIN CAPITAL LETTER S WITH ACUTE 0x015b: 0x0098, # LATIN SMALL LETTER S WITH ACUTE 0x015e: 0x00b8, # LATIN CAPITAL LETTER S WITH CEDILLA 0x015f: 0x00ad, # LATIN SMALL LETTER S WITH CEDILLA 0x0160: 0x00e6, # LATIN CAPITAL LETTER S WITH CARON 0x0161: 0x00e7, # LATIN SMALL LETTER S WITH CARON 0x0162: 0x00dd, # LATIN CAPITAL LETTER T WITH CEDILLA 0x0163: 0x00ee, # LATIN SMALL LETTER T WITH CEDILLA 0x0164: 0x009b, # LATIN CAPITAL LETTER T WITH CARON 0x0165: 0x009c, # LATIN SMALL LETTER T WITH CARON 0x016e: 0x00de, # LATIN CAPITAL LETTER U WITH RING ABOVE 0x016f: 0x0085, # LATIN SMALL LETTER U WITH RING ABOVE 0x0170: 0x00eb, # LATIN CAPITAL LETTER U WITH DOUBLE ACUTE 0x0171: 0x00fb, # LATIN SMALL LETTER U WITH DOUBLE ACUTE 0x0179: 0x008d, # LATIN CAPITAL LETTER Z WITH ACUTE 0x017a: 0x00ab, # LATIN SMALL LETTER Z WITH ACUTE 0x017b: 0x00bd, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x017c: 0x00be, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x017d: 0x00a6, # LATIN CAPITAL LETTER Z WITH CARON 0x017e: 0x00a7, # LATIN SMALL LETTER Z WITH CARON 0x02c7: 0x00f3, # CARON 0x02d8: 0x00f4, # BREVE 0x02d9: 0x00fa, # DOT ABOVE 0x02db: 0x00f2, # OGONEK 0x02dd: 0x00f1, # DOUBLE ACUTE ACCENT 0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL 0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL 0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT<|fim▁hole|> 0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL 0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL 0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT 0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x2580: 0x00df, # UPPER HALF BLOCK 0x2584: 0x00dc, # LOWER HALF BLOCK 0x2588: 0x00db, # FULL BLOCK 0x2591: 0x00b0, # LIGHT SHADE 0x2592: 0x00b1, # MEDIUM SHADE 0x2593: 0x00b2, # DARK SHADE 0x25a0: 0x00fe, # BLACK SQUARE } >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= """ Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP852.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_map)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='cp852', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x0085: 0x016f, # LATIN SMALL LETTER U WITH RING ABOVE 0x0086: 0x0107, # LATIN SMALL LETTER C WITH ACUTE 0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x0088: 0x0142, # LATIN SMALL LETTER L WITH STROKE 0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x008a: 0x0150, # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE 0x008b: 0x0151, # LATIN SMALL LETTER O WITH DOUBLE ACUTE 0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x008d: 0x0179, # LATIN CAPITAL LETTER Z WITH ACUTE 0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x008f: 0x0106, # LATIN CAPITAL LETTER C WITH ACUTE 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0091: 0x0139, # LATIN CAPITAL LETTER L WITH ACUTE 0x0092: 0x013a, # LATIN SMALL LETTER L WITH ACUTE 0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x0095: 0x013d, # LATIN CAPITAL LETTER L WITH CARON 0x0096: 0x013e, # LATIN SMALL LETTER L WITH CARON 0x0097: 0x015a, # LATIN CAPITAL LETTER S WITH ACUTE 0x0098: 0x015b, # LATIN SMALL LETTER S WITH ACUTE 0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x0164, # LATIN CAPITAL LETTER T WITH CARON 0x009c: 0x0165, # LATIN SMALL LETTER T WITH CARON 0x009d: 0x0141, # LATIN CAPITAL LETTER L WITH STROKE 0x009e: 0x00d7, # MULTIPLICATION SIGN 0x009f: 0x010d, # LATIN SMALL LETTER C WITH CARON 0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00a4: 0x0104, # LATIN CAPITAL LETTER A WITH OGONEK 0x00a5: 0x0105, # LATIN SMALL LETTER A WITH OGONEK 0x00a6: 0x017d, # LATIN CAPITAL LETTER Z WITH CARON 0x00a7: 0x017e, # LATIN SMALL LETTER Z WITH CARON 0x00a8: 0x0118, # LATIN CAPITAL LETTER E WITH OGONEK 0x00a9: 0x0119, # LATIN SMALL LETTER E WITH OGONEK 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x017a, # LATIN SMALL LETTER Z WITH ACUTE 0x00ac: 0x010c, # LATIN CAPITAL LETTER C WITH CARON 0x00ad: 0x015f, # LATIN SMALL LETTER S WITH CEDILLA 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE 0x00b6: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00b7: 0x011a, # LATIN CAPITAL LETTER E WITH CARON 0x00b8: 0x015e, # LATIN CAPITAL LETTER S WITH CEDILLA 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x017b, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x00be: 0x017c, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x0102, # LATIN CAPITAL LETTER A WITH BREVE 0x00c7: 0x0103, # LATIN SMALL LETTER A WITH BREVE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x00a4, # CURRENCY SIGN 0x00d0: 0x0111, # LATIN SMALL LETTER D WITH STROKE 0x00d1: 0x0110, # LATIN CAPITAL LETTER D WITH STROKE 0x00d2: 0x010e, # LATIN CAPITAL LETTER D WITH CARON 0x00d3: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00d4: 0x010f, # LATIN SMALL LETTER D WITH CARON 0x00d5: 0x0147, # LATIN CAPITAL LETTER N WITH CARON 0x00d6: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE 0x00d7: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00d8: 0x011b, # LATIN SMALL LETTER E WITH CARON 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x0162, # LATIN CAPITAL LETTER T WITH CEDILLA 0x00de: 0x016e, # LATIN CAPITAL LETTER U WITH RING ABOVE 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S 0x00e2: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00e3: 0x0143, # LATIN CAPITAL LETTER N WITH ACUTE 0x00e4: 0x0144, # LATIN SMALL LETTER N WITH ACUTE 0x00e5: 0x0148, # LATIN SMALL LETTER N WITH CARON 0x00e6: 0x0160, # LATIN CAPITAL LETTER S WITH CARON 0x00e7: 0x0161, # LATIN SMALL LETTER S WITH CARON 0x00e8: 0x0154, # LATIN CAPITAL LETTER R WITH ACUTE 0x00e9: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE 0x00ea: 0x0155, # LATIN SMALL LETTER R WITH ACUTE 0x00eb: 0x0170, # LATIN CAPITAL LETTER U WITH DOUBLE ACUTE 0x00ec: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE 0x00ed: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE 0x00ee: 0x0163, # LATIN SMALL LETTER T WITH CEDILLA 0x00ef: 0x00b4, # ACUTE ACCENT 0x00f0: 0x00ad, # SOFT HYPHEN 0x00f1: 0x02dd, # DOUBLE ACUTE ACCENT 0x00f2: 0x02db, # OGONEK 0x00f3: 0x02c7, # CARON 0x00f4: 0x02d8, # BREVE 0x00f5: 0x00a7, # SECTION SIGN 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x00b8, # CEDILLA 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x00a8, # DIAERESIS 0x00fa: 0x02d9, # DOT ABOVE 0x00fb: 0x0171, # LATIN SMALL LETTER U WITH DOUBLE ACUTE 0x00fc: 0x0158, # LATIN CAPITAL LETTER R WITH CARON 0x00fd: 0x0159, # LATIN SMALL LETTER R WITH CARON 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Decoding Table decoding_table = ( '\x00' # 0x0000 -> NULL '\x01' # 0x0001 -> START OF HEADING '\x02' # 0x0002 -> START OF TEXT '\x03' # 0x0003 -> END OF TEXT '\x04' # 0x0004 -> END OF TRANSMISSION '\x05' # 0x0005 -> ENQUIRY '\x06' # 0x0006 -> ACKNOWLEDGE '\x07' # 0x0007 -> BELL '\x08' # 0x0008 -> BACKSPACE '\t' # 0x0009 -> HORIZONTAL TABULATION '\n' # 0x000a -> LINE FEED '\x0b' # 0x000b -> VERTICAL TABULATION '\x0c' # 0x000c -> FORM FEED '\r' # 0x000d -> CARRIAGE RETURN '\x0e' # 0x000e -> SHIFT OUT '\x0f' # 0x000f -> SHIFT IN '\x10' # 0x0010 -> DATA LINK ESCAPE '\x11' # 0x0011 -> DEVICE CONTROL ONE '\x12' # 0x0012 -> DEVICE CONTROL TWO '\x13' # 0x0013 -> DEVICE CONTROL THREE '\x14' # 0x0014 -> DEVICE CONTROL FOUR '\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE '\x16' # 0x0016 -> SYNCHRONOUS IDLE '\x17' # 0x0017 -> END OF TRANSMISSION BLOCK '\x18' # 0x0018 -> CANCEL '\x19' # 0x0019 -> END OF MEDIUM '\x1a' # 0x001a -> SUBSTITUTE '\x1b' # 0x001b -> ESCAPE '\x1c' # 0x001c -> FILE SEPARATOR '\x1d' # 0x001d -> GROUP SEPARATOR '\x1e' # 0x001e -> RECORD SEPARATOR '\x1f' # 0x001f -> UNIT SEPARATOR ' ' # 0x0020 -> SPACE '!' # 0x0021 -> EXCLAMATION MARK '"' # 0x0022 -> QUOTATION MARK '#' # 0x0023 -> NUMBER SIGN '$' # 0x0024 -> DOLLAR SIGN '%' # 0x0025 -> PERCENT SIGN '&' # 0x0026 -> AMPERSAND "'" # 0x0027 -> APOSTROPHE '(' # 0x0028 -> LEFT PARENTHESIS ')' # 0x0029 -> RIGHT PARENTHESIS '*' # 0x002a -> ASTERISK '+' # 0x002b -> PLUS SIGN ',' # 0x002c -> COMMA '-' # 0x002d -> HYPHEN-MINUS '.' # 0x002e -> FULL STOP '/' # 0x002f -> SOLIDUS '0' # 0x0030 -> DIGIT ZERO '1' # 0x0031 -> DIGIT ONE '2' # 0x0032 -> DIGIT TWO '3' # 0x0033 -> DIGIT THREE '4' # 0x0034 -> DIGIT FOUR '5' # 0x0035 -> DIGIT FIVE '6' # 0x0036 -> DIGIT SIX '7' # 0x0037 -> DIGIT SEVEN '8' # 0x0038 -> DIGIT EIGHT '9' # 0x0039 -> DIGIT NINE ':' # 0x003a -> COLON ';' # 0x003b -> SEMICOLON '<' # 0x003c -> LESS-THAN SIGN '=' # 0x003d -> EQUALS SIGN '>' # 0x003e -> GREATER-THAN SIGN '?' # 0x003f -> QUESTION MARK '@' # 0x0040 -> COMMERCIAL AT 'A' # 0x0041 -> LATIN CAPITAL LETTER A 'B' # 0x0042 -> LATIN CAPITAL LETTER B 'C' # 0x0043 -> LATIN CAPITAL LETTER C 'D' # 0x0044 -> LATIN CAPITAL LETTER D 'E' # 0x0045 -> LATIN CAPITAL LETTER E 'F' # 0x0046 -> LATIN CAPITAL LETTER F 'G' # 0x0047 -> LATIN CAPITAL LETTER G 'H' # 0x0048 -> LATIN CAPITAL LETTER H 'I' # 0x0049 -> LATIN CAPITAL LETTER I 'J' # 0x004a -> LATIN CAPITAL LETTER J 'K' # 0x004b -> LATIN CAPITAL LETTER K 'L' # 0x004c -> LATIN CAPITAL LETTER L 'M' # 0x004d -> LATIN CAPITAL LETTER M 'N' # 0x004e -> LATIN CAPITAL LETTER N 'O' # 0x004f -> LATIN CAPITAL LETTER O 'P' # 0x0050 -> LATIN CAPITAL LETTER P 'Q' # 0x0051 -> LATIN CAPITAL LETTER Q 'R' # 0x0052 -> LATIN CAPITAL LETTER R 'S' # 0x0053 -> LATIN CAPITAL LETTER S 'T' # 0x0054 -> LATIN CAPITAL LETTER T 'U' # 0x0055 -> LATIN CAPITAL LETTER U 'V' # 0x0056 -> LATIN CAPITAL LETTER V 'W' # 0x0057 -> LATIN CAPITAL LETTER W 'X' # 0x0058 -> LATIN CAPITAL LETTER X 'Y' # 0x0059 -> LATIN CAPITAL LETTER Y 'Z' # 0x005a -> LATIN CAPITAL LETTER Z '[' # 0x005b -> LEFT SQUARE BRACKET '\\' # 0x005c -> REVERSE SOLIDUS ']' # 0x005d -> RIGHT SQUARE BRACKET '^' # 0x005e -> CIRCUMFLEX ACCENT '_' # 0x005f -> LOW LINE '`' # 0x0060 -> GRAVE ACCENT 'a' # 0x0061 -> LATIN SMALL LETTER A 'b' # 0x0062 -> LATIN SMALL LETTER B 'c' # 0x0063 -> LATIN SMALL LETTER C 'd' # 0x0064 -> LATIN SMALL LETTER D 'e' # 0x0065 -> LATIN SMALL LETTER E 'f' # 0x0066 -> LATIN SMALL LETTER F 'g' # 0x0067 -> LATIN SMALL LETTER G 'h' # 0x0068 -> LATIN SMALL LETTER H 'i' # 0x0069 -> LATIN SMALL LETTER I 'j' # 0x006a -> LATIN SMALL LETTER J 'k' # 0x006b -> LATIN SMALL LETTER K 'l' # 0x006c -> LATIN SMALL LETTER L 'm' # 0x006d -> LATIN SMALL LETTER M 'n' # 0x006e -> LATIN SMALL LETTER N 'o' # 0x006f -> LATIN SMALL LETTER O 'p' # 0x0070 -> LATIN SMALL LETTER P 'q' # 0x0071 -> LATIN SMALL LETTER Q 'r' # 0x0072 -> LATIN SMALL LETTER R 's' # 0x0073 -> LATIN SMALL LETTER S 't' # 0x0074 -> LATIN SMALL LETTER T 'u' # 0x0075 -> LATIN SMALL LETTER U 'v' # 0x0076 -> LATIN SMALL LETTER V 'w' # 0x0077 -> LATIN SMALL LETTER W 'x' # 0x0078 -> LATIN SMALL LETTER X 'y' # 0x0079 -> LATIN SMALL LETTER Y 'z' # 0x007a -> LATIN SMALL LETTER Z '{' # 0x007b -> LEFT CURLY BRACKET '|' # 0x007c -> VERTICAL LINE '}' # 0x007d -> RIGHT CURLY BRACKET '~' # 0x007e -> TILDE '\x7f' # 0x007f -> DELETE '\xc7' # 0x0080 -> LATIN CAPITAL LETTER C WITH CEDILLA '\xfc' # 0x0081 -> LATIN SMALL LETTER U WITH DIAERESIS '\xe9' # 0x0082 -> LATIN SMALL LETTER E WITH ACUTE '\xe2' # 0x0083 -> LATIN SMALL LETTER A WITH CIRCUMFLEX '\xe4' # 0x0084 -> LATIN SMALL LETTER A WITH DIAERESIS '\u016f' # 0x0085 -> LATIN SMALL LETTER U WITH RING ABOVE '\u0107' # 0x0086 -> LATIN SMALL LETTER C WITH ACUTE '\xe7' # 0x0087 -> LATIN SMALL LETTER C WITH CEDILLA '\u0142' # 0x0088 -> LATIN SMALL LETTER L WITH STROKE '\xeb' # 0x0089 -> LATIN SMALL LETTER E WITH DIAERESIS '\u0150' # 0x008a -> LATIN CAPITAL LETTER O WITH DOUBLE ACUTE '\u0151' # 0x008b -> LATIN SMALL LETTER O WITH DOUBLE ACUTE '\xee' # 0x008c -> LATIN SMALL LETTER I WITH CIRCUMFLEX '\u0179' # 0x008d -> LATIN CAPITAL LETTER Z WITH ACUTE '\xc4' # 0x008e -> LATIN CAPITAL LETTER A WITH DIAERESIS '\u0106' # 0x008f -> LATIN CAPITAL LETTER C WITH ACUTE '\xc9' # 0x0090 -> LATIN CAPITAL LETTER E WITH ACUTE '\u0139' # 0x0091 -> LATIN CAPITAL LETTER L WITH ACUTE '\u013a' # 0x0092 -> LATIN SMALL LETTER L WITH ACUTE '\xf4' # 0x0093 -> LATIN SMALL LETTER O WITH CIRCUMFLEX '\xf6' # 0x0094 -> LATIN SMALL LETTER O WITH DIAERESIS '\u013d' # 0x0095 -> LATIN CAPITAL LETTER L WITH CARON '\u013e' # 0x0096 -> LATIN SMALL LETTER L WITH CARON '\u015a' # 0x0097 -> LATIN CAPITAL LETTER S WITH ACUTE '\u015b' # 0x0098 -> LATIN SMALL LETTER S WITH ACUTE '\xd6' # 0x0099 -> LATIN CAPITAL LETTER O WITH DIAERESIS '\xdc' # 0x009a -> LATIN CAPITAL LETTER U WITH DIAERESIS '\u0164' # 0x009b -> LATIN CAPITAL LETTER T WITH CARON '\u0165' # 0x009c -> LATIN SMALL LETTER T WITH CARON '\u0141' # 0x009d -> LATIN CAPITAL LETTER L WITH STROKE '\xd7' # 0x009e -> MULTIPLICATION SIGN '\u010d' # 0x009f -> LATIN SMALL LETTER C WITH CARON '\xe1' # 0x00a0 -> LATIN SMALL LETTER A WITH ACUTE '\xed' # 0x00a1 -> LATIN SMALL LETTER I WITH ACUTE '\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE '\xfa' # 0x00a3 -> LATIN SMALL LETTER U WITH ACUTE '\u0104' # 0x00a4 -> LATIN CAPITAL LETTER A WITH OGONEK '\u0105' # 0x00a5 -> LATIN SMALL LETTER A WITH OGONEK '\u017d' # 0x00a6 -> LATIN CAPITAL LETTER Z WITH CARON '\u017e' # 0x00a7 -> LATIN SMALL LETTER Z WITH CARON '\u0118' # 0x00a8 -> LATIN CAPITAL LETTER E WITH OGONEK '\u0119' # 0x00a9 -> LATIN SMALL LETTER E WITH OGONEK '\xac' # 0x00aa -> NOT SIGN '\u017a' # 0x00ab -> LATIN SMALL LETTER Z WITH ACUTE '\u010c' # 0x00ac -> LATIN CAPITAL LETTER C WITH CARON '\u015f' # 0x00ad -> LATIN SMALL LETTER S WITH CEDILLA '\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK '\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK '\u2591' # 0x00b0 -> LIGHT SHADE '\u2592' # 0x00b1 -> MEDIUM SHADE '\u2593' # 0x00b2 -> DARK SHADE '\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL '\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT '\xc1' # 0x00b5 -> LATIN CAPITAL LETTER A WITH ACUTE '\xc2' # 0x00b6 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX '\u011a' # 0x00b7 -> LATIN CAPITAL LETTER E WITH CARON '\u015e' # 0x00b8 -> LATIN CAPITAL LETTER S WITH CEDILLA '\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT '\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL '\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT '\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT '\u017b' # 0x00bd -> LATIN CAPITAL LETTER Z WITH DOT ABOVE '\u017c' # 0x00be -> LATIN SMALL LETTER Z WITH DOT ABOVE '\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT '\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT '\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL '\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL '\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT '\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL '\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL '\u0102' # 0x00c6 -> LATIN CAPITAL LETTER A WITH BREVE '\u0103' # 0x00c7 -> LATIN SMALL LETTER A WITH BREVE '\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT '\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT '\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL '\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL '\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT '\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL '\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL '\xa4' # 0x00cf -> CURRENCY SIGN '\u0111' # 0x00d0 -> LATIN SMALL LETTER D WITH STROKE '\u0110' # 0x00d1 -> LATIN CAPITAL LETTER D WITH STROKE '\u010e' # 0x00d2 -> LATIN CAPITAL LETTER D WITH CARON '\xcb' # 0x00d3 -> LATIN CAPITAL LETTER E WITH DIAERESIS '\u010f' # 0x00d4 -> LATIN SMALL LETTER D WITH CARON '\u0147' # 0x00d5 -> LATIN CAPITAL LETTER N WITH CARON '\xcd' # 0x00d6 -> LATIN CAPITAL LETTER I WITH ACUTE '\xce' # 0x00d7 -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX '\u011b' # 0x00d8 -> LATIN SMALL LETTER E WITH CARON '\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT '\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT '\u2588' # 0x00db -> FULL BLOCK '\u2584' # 0x00dc -> LOWER HALF BLOCK '\u0162' # 0x00dd -> LATIN CAPITAL LETTER T WITH CEDILLA '\u016e' # 0x00de -> LATIN CAPITAL LETTER U WITH RING ABOVE '\u2580' # 0x00df -> UPPER HALF BLOCK '\xd3' # 0x00e0 -> LATIN CAPITAL LETTER O WITH ACUTE '\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S '\xd4' # 0x00e2 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX '\u0143' # 0x00e3 -> LATIN CAPITAL LETTER N WITH ACUTE '\u0144' # 0x00e4 -> LATIN SMALL LETTER N WITH ACUTE '\u0148' # 0x00e5 -> LATIN SMALL LETTER N WITH CARON '\u0160' # 0x00e6 -> LATIN CAPITAL LETTER S WITH CARON '\u0161' # 0x00e7 -> LATIN SMALL LETTER S WITH CARON '\u0154' # 0x00e8 -> LATIN CAPITAL LETTER R WITH ACUTE '\xda' # 0x00e9 -> LATIN CAPITAL LETTER U WITH ACUTE '\u0155' # 0x00ea -> LATIN SMALL LETTER R WITH ACUTE '\u0170' # 0x00eb -> LATIN CAPITAL LETTER U WITH DOUBLE ACUTE '\xfd' # 0x00ec -> LATIN SMALL LETTER Y WITH ACUTE '\xdd' # 0x00ed -> LATIN CAPITAL LETTER Y WITH ACUTE '\u0163' # 0x00ee -> LATIN SMALL LETTER T WITH CEDILLA '\xb4' # 0x00ef -> ACUTE ACCENT '\xad' # 0x00f0 -> SOFT HYPHEN '\u02dd' # 0x00f1 -> DOUBLE ACUTE ACCENT '\u02db' # 0x00f2 -> OGONEK '\u02c7' # 0x00f3 -> CARON '\u02d8' # 0x00f4 -> BREVE '\xa7' # 0x00f5 -> SECTION SIGN '\xf7' # 0x00f6 -> DIVISION SIGN '\xb8' # 0x00f7 -> CEDILLA '\xb0' # 0x00f8 -> DEGREE SIGN '\xa8' # 0x00f9 -> DIAERESIS '\u02d9' # 0x00fa -> DOT ABOVE '\u0171' # 0x00fb -> LATIN SMALL LETTER U WITH DOUBLE ACUTE '\u0158' # 0x00fc -> LATIN CAPITAL LETTER R WITH CARON '\u0159' # 0x00fd -> LATIN SMALL LETTER R WITH CARON '\u25a0' # 0x00fe -> BLACK SQUARE '\xa0' # 0x00ff -> NO-BREAK SPACE ) ### Encoding Map encoding_map = { 0x0000: 0x0000, # NULL 0x0001: 0x0001, # START OF HEADING 0x0002: 0x0002, # START OF TEXT 0x0003: 0x0003, # END OF TEXT 0x0004: 0x0004, # END OF TRANSMISSION 0x0005: 0x0005, # ENQUIRY 0x0006: 0x0006, # ACKNOWLEDGE 0x0007: 0x0007, # BELL 0x0008: 0x0008, # BACKSPACE 0x0009: 0x0009, # HORIZONTAL TABULATION 0x000a: 0x000a, # LINE FEED 0x000b: 0x000b, # VERTICAL TABULATION 0x000c: 0x000c, # FORM FEED 0x000d: 0x000d, # CARRIAGE RETURN 0x000e: 0x000e, # SHIFT OUT 0x000f: 0x000f, # SHIFT IN 0x0010: 0x0010, # DATA LINK ESCAPE 0x0011: 0x0011, # DEVICE CONTROL ONE 0x0012: 0x0012, # DEVICE CONTROL TWO 0x0013: 0x0013, # DEVICE CONTROL THREE 0x0014: 0x0014, # DEVICE CONTROL FOUR 0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE 0x0016: 0x0016, # SYNCHRONOUS IDLE 0x0017: 0x0017, # END OF TRANSMISSION BLOCK 0x0018: 0x0018, # CANCEL 0x0019: 0x0019, # END OF MEDIUM 0x001a: 0x001a, # SUBSTITUTE 0x001b: 0x001b, # ESCAPE 0x001c: 0x001c, # FILE SEPARATOR 0x001d: 0x001d, # GROUP SEPARATOR 0x001e: 0x001e, # RECORD SEPARATOR 0x001f: 0x001f, # UNIT SEPARATOR 0x0020: 0x0020, # SPACE 0x0021: 0x0021, # EXCLAMATION MARK 0x0022: 0x0022, # QUOTATION MARK 0x0023: 0x0023, # NUMBER SIGN 0x0024: 0x0024, # DOLLAR SIGN 0x0025: 0x0025, # PERCENT SIGN 0x0026: 0x0026, # AMPERSAND 0x0027: 0x0027, # APOSTROPHE 0x0028: 0x0028, # LEFT PARENTHESIS 0x0029: 0x0029, # RIGHT PARENTHESIS 0x002a: 0x002a, # ASTERISK 0x002b: 0x002b, # PLUS SIGN 0x002c: 0x002c, # COMMA 0x002d: 0x002d, # HYPHEN-MINUS 0x002e: 0x002e, # FULL STOP 0x002f: 0x002f, # SOLIDUS 0x0030: 0x0030, # DIGIT ZERO 0x0031: 0x0031, # DIGIT ONE 0x0032: 0x0032, # DIGIT TWO 0x0033: 0x0033, # DIGIT THREE 0x0034: 0x0034, # DIGIT FOUR 0x0035: 0x0035, # DIGIT FIVE 0x0036: 0x0036, # DIGIT SIX 0x0037: 0x0037, # DIGIT SEVEN 0x0038: 0x0038, # DIGIT EIGHT 0x0039: 0x0039, # DIGIT NINE 0x003a: 0x003a, # COLON 0x003b: 0x003b, # SEMICOLON 0x003c: 0x003c, # LESS-THAN SIGN 0x003d: 0x003d, # EQUALS SIGN 0x003e: 0x003e, # GREATER-THAN SIGN 0x003f: 0x003f, # QUESTION MARK 0x0040: 0x0040, # COMMERCIAL AT 0x0041: 0x0041, # LATIN CAPITAL LETTER A 0x0042: 0x0042, # LATIN CAPITAL LETTER B 0x0043: 0x0043, # LATIN CAPITAL LETTER C 0x0044: 0x0044, # LATIN CAPITAL LETTER D 0x0045: 0x0045, # LATIN CAPITAL LETTER E 0x0046: 0x0046, # LATIN CAPITAL LETTER F 0x0047: 0x0047, # LATIN CAPITAL LETTER G 0x0048: 0x0048, # LATIN CAPITAL LETTER H 0x0049: 0x0049, # LATIN CAPITAL LETTER I 0x004a: 0x004a, # LATIN CAPITAL LETTER J 0x004b: 0x004b, # LATIN CAPITAL LETTER K 0x004c: 0x004c, # LATIN CAPITAL LETTER L 0x004d: 0x004d, # LATIN CAPITAL LETTER M 0x004e: 0x004e, # LATIN CAPITAL LETTER N 0x004f: 0x004f, # LATIN CAPITAL LETTER O 0x0050: 0x0050, # LATIN CAPITAL LETTER P 0x0051: 0x0051, # LATIN CAPITAL LETTER Q 0x0052: 0x0052, # LATIN CAPITAL LETTER R 0x0053: 0x0053, # LATIN CAPITAL LETTER S 0x0054: 0x0054, # LATIN CAPITAL LETTER T 0x0055: 0x0055, # LATIN CAPITAL LETTER U 0x0056: 0x0056, # LATIN CAPITAL LETTER V 0x0057: 0x0057, # LATIN CAPITAL LETTER W 0x0058: 0x0058, # LATIN CAPITAL LETTER X 0x0059: 0x0059, # LATIN CAPITAL LETTER Y 0x005a: 0x005a, # LATIN CAPITAL LETTER Z 0x005b: 0x005b, # LEFT SQUARE BRACKET 0x005c: 0x005c, # REVERSE SOLIDUS 0x005d: 0x005d, # RIGHT SQUARE BRACKET 0x005e: 0x005e, # CIRCUMFLEX ACCENT 0x005f: 0x005f, # LOW LINE 0x0060: 0x0060, # GRAVE ACCENT 0x0061: 0x0061, # LATIN SMALL LETTER A 0x0062: 0x0062, # LATIN SMALL LETTER B 0x0063: 0x0063, # LATIN SMALL LETTER C 0x0064: 0x0064, # LATIN SMALL LETTER D 0x0065: 0x0065, # LATIN SMALL LETTER E 0x0066: 0x0066, # LATIN SMALL LETTER F 0x0067: 0x0067, # LATIN SMALL LETTER G 0x0068: 0x0068, # LATIN SMALL LETTER H 0x0069: 0x0069, # LATIN SMALL LETTER I 0x006a: 0x006a, # LATIN SMALL LETTER J 0x006b: 0x006b, # LATIN SMALL LETTER K 0x006c: 0x006c, # LATIN SMALL LETTER L 0x006d: 0x006d, # LATIN SMALL LETTER M 0x006e: 0x006e, # LATIN SMALL LETTER N 0x006f: 0x006f, # LATIN SMALL LETTER O 0x0070: 0x0070, # LATIN SMALL LETTER P 0x0071: 0x0071, # LATIN SMALL LETTER Q 0x0072: 0x0072, # LATIN SMALL LETTER R 0x0073: 0x0073, # LATIN SMALL LETTER S 0x0074: 0x0074, # LATIN SMALL LETTER T 0x0075: 0x0075, # LATIN SMALL LETTER U 0x0076: 0x0076, # LATIN SMALL LETTER V 0x0077: 0x0077, # LATIN SMALL LETTER W 0x0078: 0x0078, # LATIN SMALL LETTER X 0x0079: 0x0079, # LATIN SMALL LETTER Y 0x007a: 0x007a, # LATIN SMALL LETTER Z 0x007b: 0x007b, # LEFT CURLY BRACKET 0x007c: 0x007c, # VERTICAL LINE 0x007d: 0x007d, # RIGHT CURLY BRACKET 0x007e: 0x007e, # TILDE 0x007f: 0x007f, # DELETE 0x00a0: 0x00ff, # NO-BREAK SPACE 0x00a4: 0x00cf, # CURRENCY SIGN 0x00a7: 0x00f5, # SECTION SIGN 0x00a8: 0x00f9, # DIAERESIS 0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00ac: 0x00aa, # NOT SIGN 0x00ad: 0x00f0, # SOFT HYPHEN 0x00b0: 0x00f8, # DEGREE SIGN 0x00b4: 0x00ef, # ACUTE ACCENT 0x00b8: 0x00f7, # CEDILLA 0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00c1: 0x00b5, # LATIN CAPITAL LETTER A WITH ACUTE 0x00c2: 0x00b6, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00c4: 0x008e, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x00c7: 0x0080, # LATIN CAPITAL LETTER C WITH CEDILLA 0x00c9: 0x0090, # LATIN CAPITAL LETTER E WITH ACUTE 0x00cb: 0x00d3, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00cd: 0x00d6, # LATIN CAPITAL LETTER I WITH ACUTE 0x00ce: 0x00d7, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00d3: 0x00e0, # LATIN CAPITAL LETTER O WITH ACUTE 0x00d4: 0x00e2, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00d6: 0x0099, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x00d7: 0x009e, # MULTIPLICATION SIGN 0x00da: 0x00e9, # LATIN CAPITAL LETTER U WITH ACUTE 0x00dc: 0x009a, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x00dd: 0x00ed, # LATIN CAPITAL LETTER Y WITH ACUTE 0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S 0x00e1: 0x00a0, # LATIN SMALL LETTER A WITH ACUTE 0x00e2: 0x0083, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x00e4: 0x0084, # LATIN SMALL LETTER A WITH DIAERESIS 0x00e7: 0x0087, # LATIN SMALL LETTER C WITH CEDILLA 0x00e9: 0x0082, # LATIN SMALL LETTER E WITH ACUTE 0x00eb: 0x0089, # LATIN SMALL LETTER E WITH DIAERESIS 0x00ed: 0x00a1, # LATIN SMALL LETTER I WITH ACUTE 0x00ee: 0x008c, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE 0x00f4: 0x0093, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x00f6: 0x0094, # LATIN SMALL LETTER O WITH DIAERESIS 0x00f7: 0x00f6, # DIVISION SIGN 0x00fa: 0x00a3, # LATIN SMALL LETTER U WITH ACUTE 0x00fc: 0x0081, # LATIN SMALL LETTER U WITH DIAERESIS 0x00fd: 0x00ec, # LATIN SMALL LETTER Y WITH ACUTE 0x0102: 0x00c6, # LATIN CAPITAL LETTER A WITH BREVE 0x0103: 0x00c7, # LATIN SMALL LETTER A WITH BREVE 0x0104: 0x00a4, # LATIN CAPITAL LETTER A WITH OGONEK 0x0105: 0x00a5, # LATIN SMALL LETTER A WITH OGONEK 0x0106: 0x008f, # LATIN CAPITAL LETTER C WITH ACUTE 0x0107: 0x0086, # LATIN SMALL LETTER C WITH ACUTE 0x010c: 0x00ac, # LATIN CAPITAL LETTER C WITH CARON 0x010d: 0x009f, # LATIN SMALL LETTER C WITH CARON 0x010e: 0x00d2, # LATIN CAPITAL LETTER D WITH CARON 0x010f: 0x00d4, # LATIN SMALL LETTER D WITH CARON 0x0110: 0x00d1, # LATIN CAPITAL LETTER D WITH STROKE 0x0111: 0x00d0, # LATIN SMALL LETTER D WITH STROKE 0x0118: 0x00a8, # LATIN CAPITAL LETTER E WITH OGONEK 0x0119: 0x00a9, # LATIN SMALL LETTER E WITH OGONEK 0x011a: 0x00b7, # LATIN CAPITAL LETTER E WITH CARON 0x011b: 0x00d8, # LATIN SMALL LETTER E WITH CARON 0x0139: 0x0091, # LATIN CAPITAL LETTER L WITH ACUTE 0x013a: 0x0092, # LATIN SMALL LETTER L WITH ACUTE 0x013d: 0x0095, # LATIN CAPITAL LETTER L WITH CARON 0x013e: 0x0096, # LATIN SMALL LETTER L WITH CARON 0x0141: 0x009d, # LATIN CAPITAL LETTER L WITH STROKE 0x0142: 0x0088, # LATIN SMALL LETTER L WITH STROKE 0x0143: 0x00e3, # LATIN CAPITAL LETTER N WITH ACUTE 0x0144: 0x00e4, # LATIN SMALL LETTER N WITH ACUTE 0x0147: 0x00d5, # LATIN CAPITAL LETTER N WITH CARON 0x0148: 0x00e5, # LATIN SMALL LETTER N WITH CARON 0x0150: 0x008a, # LATIN CAPITAL LETTER O WITH DOUBLE ACUTE 0x0151: 0x008b, # LATIN SMALL LETTER O WITH DOUBLE ACUTE 0x0154: 0x00e8, # LATIN CAPITAL LETTER R WITH ACUTE 0x0155: 0x00ea, # LATIN SMALL LETTER R WITH ACUTE 0x0158: 0x00fc, # LATIN CAPITAL LETTER R WITH CARON 0x0159: 0x00fd, # LATIN SMALL LETTER R WITH CARON 0x015a: 0x0097, # LATIN CAPITAL LETTER S WITH ACUTE 0x015b: 0x0098, # LATIN SMALL LETTER S WITH ACUTE 0x015e: 0x00b8, # LATIN CAPITAL LETTER S WITH CEDILLA 0x015f: 0x00ad, # LATIN SMALL LETTER S WITH CEDILLA 0x0160: 0x00e6, # LATIN CAPITAL LETTER S WITH CARON 0x0161: 0x00e7, # LATIN SMALL LETTER S WITH CARON 0x0162: 0x00dd, # LATIN CAPITAL LETTER T WITH CEDILLA 0x0163: 0x00ee, # LATIN SMALL LETTER T WITH CEDILLA 0x0164: 0x009b, # LATIN CAPITAL LETTER T WITH CARON 0x0165: 0x009c, # LATIN SMALL LETTER T WITH CARON 0x016e: 0x00de, # LATIN CAPITAL LETTER U WITH RING ABOVE 0x016f: 0x0085, # LATIN SMALL LETTER U WITH RING ABOVE 0x0170: 0x00eb, # LATIN CAPITAL LETTER U WITH DOUBLE ACUTE 0x0171: 0x00fb, # LATIN SMALL LETTER U WITH DOUBLE ACUTE 0x0179: 0x008d, # LATIN CAPITAL LETTER Z WITH ACUTE 0x017a: 0x00ab, # LATIN SMALL LETTER Z WITH ACUTE 0x017b: 0x00bd, # LATIN CAPITAL LETTER Z WITH DOT ABOVE 0x017c: 0x00be, # LATIN SMALL LETTER Z WITH DOT ABOVE 0x017d: 0x00a6, # LATIN CAPITAL LETTER Z WITH CARON 0x017e: 0x00a7, # LATIN SMALL LETTER Z WITH CARON 0x02c7: 0x00f3, # CARON 0x02d8: 0x00f4, # BREVE 0x02d9: 0x00fa, # DOT ABOVE 0x02db: 0x00f2, # OGONEK 0x02dd: 0x00f1, # DOUBLE ACUTE ACCENT 0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL 0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL 0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT 0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT 0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL 0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL 0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT 0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x2580: 0x00df, # UPPER HALF BLOCK 0x2584: 0x00dc, # LOWER HALF BLOCK 0x2588: 0x00db, # FULL BLOCK 0x2591: 0x00b0, # LIGHT SHADE 0x2592: 0x00b1, # MEDIUM SHADE 0x2593: 0x00b2, # DARK SHADE 0x25a0: 0x00fe, # BLACK SQUARE } >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453<|fim▁end|>
0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT 0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
<|file_name|>kde_po_importer.py<|end_file_name|><|fim▁begin|># Copyright 2009 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). """Import module for legacy KDE .po files. This is an extension of standard gettext PO files. You can read more about this file format from: * http://l10n.kde.org/docs/translation-howto/gui-peculiarities.html * http://docs.kde.org/development/en/kdesdk/kbabel/kbabel-pluralforms.html * http://websvn.kde.org/branches/KDE/3.5/kdelibs/kdecore/klocale.cpp """ __metaclass__ = type __all__ = [ 'KdePOImporter' ] from zope.interface import implements from lp.translations.interfaces.translationfileformat import ( TranslationFileFormat, ) from lp.translations.interfaces.translationimporter import (<|fim▁hole|> ITranslationFormatImporter, ) from lp.translations.utilities.gettext_po_importer import GettextPOImporter class KdePOImporter(GettextPOImporter): """Support class for importing KDE .po files.""" implements(ITranslationFormatImporter) def getFormat(self, file_contents): """See `ITranslationFormatImporter`.""" # XXX DaniloSegan 20070904: I first tried using POParser() # to check if the file is a legacy KDE PO file or not, but # that is too slow in some cases like tarball uploads (processing # of all PO files in a tarball is done in the same transaction, # and with extremely big PO files, this will be too slow). Thus, # a heuristic verified to be correct on all PO files from # Ubuntu language packs. if ('msgid "_n: ' in file_contents or 'msgid ""\n"_n: ' in file_contents or 'msgid "_: ' in file_contents or 'msgid ""\n"_: ' in file_contents): return TranslationFileFormat.KDEPO else: return TranslationFileFormat.PO priority = 10 content_type = 'application/x-po' def parse(self, translation_import_queue_entry): """See `ITranslationFormatImporter`.""" translation_file = GettextPOImporter.parse( self, translation_import_queue_entry) plural_prefix = u'_n: ' context_prefix = u'_: ' for message in translation_file.messages: msgid = message.msgid_singular if msgid.startswith(plural_prefix) and '\n' in msgid: # This is a KDE plural form singular, plural = msgid[len(plural_prefix):].split('\n') message.msgid_singular = singular message.msgid_plural = plural msgstrs = message._translations if len(msgstrs) > 0: message._translations = msgstrs[0].split('\n') self.internal_format = TranslationFileFormat.KDEPO elif msgid.startswith(context_prefix) and '\n' in msgid: # This is a KDE context message message.context, message.msgid_singular = ( msgid[len(context_prefix):].split('\n', 1)) self.internal_format = TranslationFileFormat.KDEPO else: # Other messages are left as they are parsed by # GettextPOImporter pass return translation_file<|fim▁end|>
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>from django.conf import settings <|fim▁hole|><|fim▁end|>
IMAGE_URL = getattr(settings, 'AWARDS_IMAGE_URL', 'icons/awards/{slug}.png')
<|file_name|>TabbedPane.js<|end_file_name|><|fim▁begin|>/** * a tabbed pane based on a definition list */ var openmdao = (typeof openmdao === "undefined" || !openmdao ) ? {} : openmdao ; openmdao.TabbedPane = function(id) { jQuery("#"+id+" dl").css({ 'margin': '0', 'width': '100%', 'position': 'relative' }); jQuery("#"+id+" dt").css({ 'top':'0', 'margin': '0',<|fim▁hole|> 'width': '75px', 'height': '20px', 'text-align': 'center', 'border': '1px solid #222', 'background-color':'#6a6a6a', 'color': 'white', 'font-size': '14px' }); jQuery("#"+id+" dd").css({ 'margin': '0', 'position': 'absolute', 'left': '0', 'top': '25px', 'height': '100%', 'width': '100%', 'min-height': '400px', 'overflow' : 'auto' }); jQuery("#"+id+" dd").hide(); jQuery("#"+id+" dt").click(function() { var tgt = jQuery(this).attr("target"); jQuery("#"+id+" dd:visible").hide(); jQuery("#"+id+" dt.tab_here").removeClass("tab_here"); jQuery("#"+tgt).show(); jQuery(this).addClass("tab_here"); }); };<|fim▁end|>
'position': 'relative', 'float': 'left', 'display': 'block',
<|file_name|>windows.py<|end_file_name|><|fim▁begin|># Copyright 2012 Cloudbase Solutions Srl # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import contextlib import ctypes from ctypes import wintypes import os import re import struct import time from oslo_log import log as oslo_logging import six from six.moves import winreg from tzlocal import windows_tz from win32com import client import win32net import win32netcon import win32process import win32security import wmi from cloudbaseinit import exception from cloudbaseinit.osutils import base from cloudbaseinit.utils.windows import disk from cloudbaseinit.utils.windows import network from cloudbaseinit.utils.windows import privilege from cloudbaseinit.utils.windows import timezone LOG = oslo_logging.getLogger(__name__) AF_INET6 = 23 UNICAST = 1 MANUAL = 1 PREFERRED_ADDR = 4 advapi32 = ctypes.windll.advapi32 kernel32 = ctypes.windll.kernel32 netapi32 = ctypes.windll.netapi32 userenv = ctypes.windll.userenv iphlpapi = ctypes.windll.iphlpapi Ws2_32 = ctypes.windll.Ws2_32 setupapi = ctypes.windll.setupapi msvcrt = ctypes.cdll.msvcrt ntdll = ctypes.windll.ntdll class Win32_PROFILEINFO(ctypes.Structure): _fields_ = [ ('dwSize', wintypes.DWORD), ('dwFlags', wintypes.DWORD), ('lpUserName', wintypes.LPWSTR), ('lpProfilePath', wintypes.LPWSTR), ('lpDefaultPath', wintypes.LPWSTR), ('lpServerName', wintypes.LPWSTR), ('lpPolicyPath', wintypes.LPWSTR), ('hprofile', wintypes.HANDLE) ] class Win32_LOCALGROUP_MEMBERS_INFO_3(ctypes.Structure): _fields_ = [ ('lgrmi3_domainandname', wintypes.LPWSTR) ] class Win32_MIB_IPFORWARDROW(ctypes.Structure): _fields_ = [ ('dwForwardDest', wintypes.DWORD), ('dwForwardMask', wintypes.DWORD), ('dwForwardPolicy', wintypes.DWORD), ('dwForwardNextHop', wintypes.DWORD), ('dwForwardIfIndex', wintypes.DWORD), ('dwForwardType', wintypes.DWORD), ('dwForwardProto', wintypes.DWORD), ('dwForwardAge', wintypes.DWORD), ('dwForwardNextHopAS', wintypes.DWORD), ('dwForwardMetric1', wintypes.DWORD), ('dwForwardMetric2', wintypes.DWORD), ('dwForwardMetric3', wintypes.DWORD), ('dwForwardMetric4', wintypes.DWORD), ('dwForwardMetric5', wintypes.DWORD) ] class Win32_MIB_IPFORWARDTABLE(ctypes.Structure): _fields_ = [ ('dwNumEntries', wintypes.DWORD), ('table', Win32_MIB_IPFORWARDROW * 1) ] class Win32_OSVERSIONINFOEX_W(ctypes.Structure): _fields_ = [ ('dwOSVersionInfoSize', wintypes.DWORD), ('dwMajorVersion', wintypes.DWORD), ('dwMinorVersion', wintypes.DWORD), ('dwBuildNumber', wintypes.DWORD), ('dwPlatformId', wintypes.DWORD), ('szCSDVersion', wintypes.WCHAR * 128), ('wServicePackMajor', wintypes.WORD), ('wServicePackMinor', wintypes.WORD), ('wSuiteMask', wintypes.WORD), ('wProductType', wintypes.BYTE), ('wReserved', wintypes.BYTE) ] class Win32_SP_DEVICE_INTERFACE_DATA(ctypes.Structure): _fields_ = [ ('cbSize', wintypes.DWORD), ('InterfaceClassGuid', disk.GUID), ('Flags', wintypes.DWORD), ('Reserved', ctypes.POINTER(wintypes.ULONG)) ] class Win32_SP_DEVICE_INTERFACE_DETAIL_DATA_W(ctypes.Structure): _fields_ = [ ('cbSize', wintypes.DWORD), ('DevicePath', ctypes.c_byte * 2) ] class Win32_STORAGE_DEVICE_NUMBER(ctypes.Structure): _fields_ = [ ('DeviceType', wintypes.DWORD), ('DeviceNumber', wintypes.DWORD), ('PartitionNumber', wintypes.DWORD) ] msvcrt.malloc.argtypes = [ctypes.c_size_t] msvcrt.malloc.restype = ctypes.c_void_p msvcrt.free.argtypes = [ctypes.c_void_p] msvcrt.free.restype = None ntdll.RtlVerifyVersionInfo.argtypes = [ ctypes.POINTER(Win32_OSVERSIONINFOEX_W), wintypes.DWORD, wintypes.ULARGE_INTEGER] ntdll.RtlVerifyVersionInfo.restype = wintypes.DWORD kernel32.VerSetConditionMask.argtypes = [wintypes.ULARGE_INTEGER, wintypes.DWORD, wintypes.BYTE] kernel32.VerSetConditionMask.restype = wintypes.ULARGE_INTEGER kernel32.SetComputerNameExW.argtypes = [ctypes.c_int, wintypes.LPCWSTR] kernel32.SetComputerNameExW.restype = wintypes.BOOL kernel32.GetLogicalDriveStringsW.argtypes = [wintypes.DWORD, wintypes.LPWSTR] kernel32.GetLogicalDriveStringsW.restype = wintypes.DWORD kernel32.GetDriveTypeW.argtypes = [wintypes.LPCWSTR] kernel32.GetDriveTypeW.restype = wintypes.UINT kernel32.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, wintypes.LPVOID, wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE] kernel32.CreateFileW.restype = wintypes.HANDLE kernel32.DeviceIoControl.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.LPVOID, wintypes.DWORD, wintypes.LPVOID, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), wintypes.LPVOID] kernel32.DeviceIoControl.restype = wintypes.BOOL kernel32.GetProcessHeap.argtypes = [] kernel32.GetProcessHeap.restype = wintypes.HANDLE kernel32.HeapAlloc.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.c_size_t] kernel32.HeapAlloc.restype = wintypes.LPVOID kernel32.HeapFree.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.LPVOID] kernel32.HeapFree.restype = wintypes.BOOL iphlpapi.GetIpForwardTable.argtypes = [ ctypes.POINTER(Win32_MIB_IPFORWARDTABLE), ctypes.POINTER(wintypes.ULONG), wintypes.BOOL] iphlpapi.GetIpForwardTable.restype = wintypes.DWORD Ws2_32.inet_ntoa.restype = ctypes.c_char_p setupapi.SetupDiGetClassDevsW.argtypes = [ctypes.POINTER(disk.GUID), wintypes.LPCWSTR, wintypes.HANDLE, wintypes.DWORD] setupapi.SetupDiGetClassDevsW.restype = wintypes.HANDLE setupapi.SetupDiEnumDeviceInterfaces.argtypes = [ wintypes.HANDLE, wintypes.LPVOID, ctypes.POINTER(disk.GUID), wintypes.DWORD, ctypes.POINTER(Win32_SP_DEVICE_INTERFACE_DATA)] setupapi.SetupDiEnumDeviceInterfaces.restype = wintypes.BOOL setupapi.SetupDiGetDeviceInterfaceDetailW.argtypes = [ wintypes.HANDLE, ctypes.POINTER(Win32_SP_DEVICE_INTERFACE_DATA), ctypes.POINTER(Win32_SP_DEVICE_INTERFACE_DETAIL_DATA_W), wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), wintypes.LPVOID] setupapi.SetupDiGetDeviceInterfaceDetailW.restype = wintypes.BOOL setupapi.SetupDiDestroyDeviceInfoList.argtypes = [wintypes.HANDLE] setupapi.SetupDiDestroyDeviceInfoList.restype = wintypes.BOOL VER_MAJORVERSION = 1 VER_MINORVERSION = 2 VER_BUILDNUMBER = 4 VER_GREATER_EQUAL = 3 GUID_DEVINTERFACE_DISK = disk.GUID(0x53f56307, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b) class WindowsUtils(base.BaseOSUtils): NERR_GroupNotFound = 2220 NERR_UserNotFound = 2221 ERROR_ACCESS_DENIED = 5 ERROR_INSUFFICIENT_BUFFER = 122 ERROR_NO_DATA = 232 ERROR_NO_SUCH_MEMBER = 1387 ERROR_MEMBER_IN_ALIAS = 1378 ERROR_INVALID_MEMBER = 1388 ERROR_NO_MORE_FILES = 18 STATUS_REVISION_MISMATCH = 0xC0000059 ADS_UF_PASSWORD_EXPIRED = 0x800000 PASSWORD_CHANGED_FLAG = 1 INVALID_HANDLE_VALUE = 0xFFFFFFFF FILE_SHARE_READ = 1 FILE_SHARE_WRITE = 2 OPEN_EXISTING = 3 IOCTL_STORAGE_GET_DEVICE_NUMBER = 0x002D1080 MAX_PATH = 260 DIGCF_PRESENT = 2 DIGCF_DEVICEINTERFACE = 0x10 DRIVE_CDROM = 5 SERVICE_STATUS_STOPPED = "Stopped" SERVICE_STATUS_START_PENDING = "Start Pending" SERVICE_STATUS_STOP_PENDING = "Stop Pending" SERVICE_STATUS_RUNNING = "Running" SERVICE_STATUS_CONTINUE_PENDING = "Continue Pending" SERVICE_STATUS_PAUSE_PENDING = "Pause Pending" SERVICE_STATUS_PAUSED = "Paused" SERVICE_STATUS_UNKNOWN = "Unknown" SERVICE_START_MODE_AUTOMATIC = "Automatic" SERVICE_START_MODE_MANUAL = "Manual" SERVICE_START_MODE_DISABLED = "Disabled" ComputerNamePhysicalDnsHostname = 5 _config_key = 'SOFTWARE\\Cloudbase Solutions\\Cloudbase-Init\\' _service_name = 'cloudbase-init' _FW_IP_PROTOCOL_TCP = 6 _FW_IP_PROTOCOL_UDP = 17 _FW_SCOPE_ALL = 0 _FW_SCOPE_LOCAL_SUBNET = 1 def reboot(self): with privilege.acquire_privilege(win32security.SE_SHUTDOWN_NAME): ret_val = advapi32.InitiateSystemShutdownExW( 0, "Cloudbase-Init reboot", 0, True, True, 0) if not ret_val: raise exception.WindowsCloudbaseInitException( "Reboot failed: %r") def user_exists(self, username): try: self._get_user_info(username, 1) return True except exception.ItemNotFoundException: # User not found return False def create_user(self, username, password, password_expires=False): user_info = { "name": username, "password": password, "priv": win32netcon.USER_PRIV_USER, "flags": win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT, } if not password_expires: user_info["flags"] |= win32netcon.UF_DONT_EXPIRE_PASSWD try: win32net.NetUserAdd(None, 1, user_info) except win32net.error as ex: raise exception.CloudbaseInitException( "Create user failed: %s" % ex.args[2]) def _get_user_info(self, username, level): try: return win32net.NetUserGetInfo(None, username, level) except win32net.error as ex: if ex.args[0] == self.NERR_UserNotFound: raise exception.ItemNotFoundException( "User not found: %s" % username) else: raise exception.CloudbaseInitException( "Failed to get user info: %s" % ex.args[2]) def set_user_password(self, username, password, password_expires=False): user_info = self._get_user_info(username, 1) user_info["password"] = password if password_expires: user_info["flags"] &= ~win32netcon.UF_DONT_EXPIRE_PASSWD else: user_info["flags"] |= win32netcon.UF_DONT_EXPIRE_PASSWD try: win32net.NetUserSetInfo(None, username, 1, user_info) except win32net.error as ex: raise exception.CloudbaseInitException( "Set user password failed: %s" % ex.args[2]) def change_password_next_logon(self, username): """Force the given user to change the password at next logon.""" user_info = self._get_user_info(username, 4) user_info["flags"] &= ~win32netcon.UF_DONT_EXPIRE_PASSWD user_info["password_expired"] = 1 try: win32net.NetUserSetInfo(None, username, 4, user_info) except win32net.error as ex: raise exception.CloudbaseInitException( "Setting password expiration failed: %s" % ex.args[2]) @staticmethod def _get_cch_referenced_domain_name(domain_name): return wintypes.DWORD( ctypes.sizeof(domain_name) // ctypes.sizeof(wintypes.WCHAR)) def _get_user_sid_and_domain(self, username): sid = ctypes.create_string_buffer(1024) cbSid = wintypes.DWORD(ctypes.sizeof(sid)) domainName = ctypes.create_unicode_buffer(1024) cchReferencedDomainName = self._get_cch_referenced_domain_name( domainName) sidNameUse = wintypes.DWORD() ret_val = advapi32.LookupAccountNameW( 0, six.text_type(username), sid, ctypes.byref(cbSid), domainName, ctypes.byref(cchReferencedDomainName), ctypes.byref(sidNameUse)) if not ret_val: raise exception.WindowsCloudbaseInitException( "Cannot get user SID: %r") return sid, domainName.value def add_user_to_local_group(self, username, groupname): lmi = Win32_LOCALGROUP_MEMBERS_INFO_3() lmi.lgrmi3_domainandname = six.text_type(username) ret_val = netapi32.NetLocalGroupAddMembers(0, six.text_type(groupname), 3, ctypes.addressof(lmi), 1) if ret_val == self.NERR_GroupNotFound: raise exception.CloudbaseInitException('Group not found') elif ret_val == self.ERROR_ACCESS_DENIED: raise exception.CloudbaseInitException('Access denied') elif ret_val == self.ERROR_NO_SUCH_MEMBER: raise exception.CloudbaseInitException('Username not found') elif ret_val == self.ERROR_MEMBER_IN_ALIAS: # The user is already a member of the group pass elif ret_val == self.ERROR_INVALID_MEMBER: raise exception.CloudbaseInitException('Invalid user') elif ret_val != 0: raise exception.CloudbaseInitException('Unknown error') def get_user_sid(self, username): try: user_info = self._get_user_info(username, 4) return str(user_info["user_sid"])[6:] except exception.ItemNotFoundException: # User not found pass def create_user_logon_session(self, username, password, domain='.', load_profile=True): token = wintypes.HANDLE() ret_val = advapi32.LogonUserW(six.text_type(username), six.text_type(domain), six.text_type(password), 2, 0, ctypes.byref(token)) if not ret_val: raise exception.WindowsCloudbaseInitException( "User logon failed: %r") if load_profile: pi = Win32_PROFILEINFO() pi.dwSize = ctypes.sizeof(Win32_PROFILEINFO) pi.lpUserName = six.text_type(username) ret_val = userenv.LoadUserProfileW(token, ctypes.byref(pi)) if not ret_val: kernel32.CloseHandle(token) raise exception.WindowsCloudbaseInitException( "Cannot load user profile: %r") return token def close_user_logon_session(self, token): kernel32.CloseHandle(token) def get_user_home(self, username): user_sid = self.get_user_sid(username) if user_sid: with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\' 'Microsoft\\Windows NT\\CurrentVersion\\' 'ProfileList\\%s' % user_sid) as key: return winreg.QueryValueEx(key, 'ProfileImagePath')[0] LOG.debug('Home directory not found for user %r', username) return None def sanitize_shell_input(self, value): return value.replace('"', '\\"') def set_host_name(self, new_host_name): ret_val = kernel32.SetComputerNameExW( self.ComputerNamePhysicalDnsHostname, six.text_type(new_host_name)) if not ret_val: raise exception.WindowsCloudbaseInitException( "Cannot set host name: %r") return True def get_network_adapters(self): """Return available adapters as a list of tuples of (name, mac).""" conn = wmi.WMI(moniker='//./root/cimv2') # Get Ethernet adapters only wql = ('SELECT * FROM Win32_NetworkAdapter WHERE ' 'AdapterTypeId = 0 AND MACAddress IS NOT NULL') if self.check_os_version(6, 0): wql += ' AND PhysicalAdapter = True' q = conn.query(wql) return [(r.Name, r.MACAddress) for r in q] def get_dhcp_hosts_in_use(self): dhcp_hosts = [] for net_addr in network.get_adapter_addresses(): if net_addr["dhcp_enabled"] and net_addr["dhcp_server"]: dhcp_hosts.append((net_addr["mac_address"], net_addr["dhcp_server"])) return dhcp_hosts def set_ntp_client_config(self, ntp_hosts): base_dir = self._get_system_dir() w32tm_path = os.path.join(base_dir, "w32tm.exe") # Convert the NTP hosts list to a string, in order to pass # it to w32tm. ntp_hosts = ",".join(ntp_hosts) args = [w32tm_path, '/config', '/manualpeerlist:%s' % ntp_hosts, '/syncfromflags:manual', '/update'] (out, err, ret_val) = self.execute_process(args, shell=False) if ret_val: raise exception.CloudbaseInitException( 'w32tm failed to configure NTP.\nOutput: %(out)s\nError:' ' %(err)s' % {'out': out, 'err': err}) def set_network_adapter_mtu(self, mac_address, mtu): if not self.check_os_version(6, 0): raise exception.CloudbaseInitException( 'Setting the MTU is currently not supported on Windows XP ' 'and Windows Server 2003') iface_index_list = [ net_addr["interface_index"] for net_addr in network.get_adapter_addresses() if net_addr["mac_address"] == mac_address] if not iface_index_list: raise exception.CloudbaseInitException( 'Network interface with MAC address "%s" not found' % mac_address) else: iface_index = iface_index_list[0] LOG.debug('Setting MTU for interface "%(mac_address)s" with ' 'value "%(mtu)s"', {'mac_address': mac_address, 'mtu': mtu}) base_dir = self._get_system_dir() netsh_path = os.path.join(base_dir, 'netsh.exe') args = [netsh_path, "interface", "ipv4", "set", "subinterface", str(iface_index), "mtu=%s" % mtu, "store=persistent"] (out, err, ret_val) = self.execute_process(args, shell=False) if ret_val: raise exception.CloudbaseInitException( 'Setting MTU for interface "%(mac_address)s" with ' 'value "%(mtu)s" failed' % {'mac_address': mac_address, 'mtu': mtu}) def set_static_network_config(self, mac_address, address, netmask, broadcast, gateway, dnsnameservers): conn = wmi.WMI(moniker='//./root/cimv2') query = conn.query("SELECT * FROM Win32_NetworkAdapter WHERE " "MACAddress = '{}'".format(mac_address)) if not len(query): raise exception.CloudbaseInitException( "Network adapter not found") adapter_config = query[0].associators( wmi_result_class='Win32_NetworkAdapterConfiguration')[0] LOG.debug("Setting static IP address") (ret_val,) = adapter_config.EnableStatic([address], [netmask]) if ret_val > 1: raise exception.CloudbaseInitException( "Cannot set static IP address on network adapter (%d)", ret_val) reboot_required = (ret_val == 1) if gateway: LOG.debug("Setting static gateways") (ret_val,) = adapter_config.SetGateways([gateway], [1]) if ret_val > 1: raise exception.CloudbaseInitException( "Cannot set gateway on network adapter (%d)", ret_val) reboot_required = reboot_required or ret_val == 1 if dnsnameservers: LOG.debug("Setting static DNS servers") (ret_val,) = adapter_config.SetDNSServerSearchOrder(dnsnameservers) if ret_val > 1: raise exception.CloudbaseInitException( "Cannot set DNS on network adapter (%d)", ret_val) reboot_required = reboot_required or ret_val == 1 return reboot_required def set_static_network_config_v6(self, mac_address, address6, netmask6, gateway6): """Set IPv6 info for a network card.""" # Get local properties by MAC identification. adapters = network.get_adapter_addresses() for adapter in adapters: if mac_address == adapter["mac_address"]: ifname = adapter["friendly_name"] ifindex = adapter["interface_index"] break else: raise exception.CloudbaseInitException( "Adapter with MAC {!r} not available".format(mac_address)) # TODO(cpoieana): Extend support for other platforms. # Currently windows8 @ ws2012 or above. if not self.check_os_version(6, 2): LOG.warning("Setting IPv6 info not available " "on this system") return conn = wmi.WMI(moniker='//./root/StandardCimv2') query = conn.query("SELECT * FROM MSFT_NetIPAddress " "WHERE InterfaceAlias = '{}'".format(ifname)) netip = query[0] params = { "InterfaceIndex": ifindex, "InterfaceAlias": ifname, "IPAddress": address6, "AddressFamily": AF_INET6, "PrefixLength": netmask6, # Manual set type. "Type": UNICAST, "PrefixOrigin": MANUAL, "SuffixOrigin": MANUAL, "AddressState": PREFERRED_ADDR, # No expiry. "ValidLifetime": None, "PreferredLifetime": None, "SkipAsSource": False, "DefaultGateway": gateway6, "PolicyStore": None, "PassThru": False, } LOG.debug("Setting IPv6 info for %s", ifname) try: netip.Create(**params) except wmi.x_wmi as exc: raise exception.CloudbaseInitException(exc.com_error) def _get_config_key_name(self, section): key_name = self._config_key if section: key_name += section.replace('/', '\\') + '\\' return key_name def set_config_value(self, name, value, section=None): key_name = self._get_config_key_name(section) with winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, key_name) as key: if type(value) == int: regtype = winreg.REG_DWORD else: regtype = winreg.REG_SZ winreg.SetValueEx(key, name, 0, regtype, value) def get_config_value(self, name, section=None): key_name = self._get_config_key_name(section) try: with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_name) as key: (value, regtype) = winreg.QueryValueEx(key, name) return value except WindowsError: return None def wait_for_boot_completion(self): try: with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SYSTEM\\Setup\\Status\\SysprepStatus", 0, winreg.KEY_READ) as key: while True: gen_state = winreg.QueryValueEx(key, "GeneralizationState")[0] if gen_state == 7: break time.sleep(1) LOG.info('Waiting for sysprep completion. ' 'GeneralizationState: %d', gen_state) except WindowsError as ex: if ex.winerror == 2: LOG.debug('Sysprep data not found in the registry, ' 'skipping sysprep completion check.') else: raise ex def _get_service(self, service_name): conn = wmi.WMI(moniker='//./root/cimv2') service_list = conn.Win32_Service(Name=service_name) if len(service_list): return service_list[0] def check_service_exists(self, service_name): return self._get_service(service_name) is not None def get_service_status(self, service_name): service = self._get_service(service_name) return service.State def get_service_start_mode(self, service_name): service = self._get_service(service_name) return service.StartMode def set_service_start_mode(self, service_name, start_mode): # TODO(alexpilotti): Handle the "Delayed Start" case service = self._get_service(service_name) (ret_val,) = service.ChangeStartMode(start_mode) if ret_val != 0: raise exception.CloudbaseInitException( 'Setting service %(service_name)s start mode failed with ' 'return value: %(ret_val)d' % {'service_name': service_name, 'ret_val': ret_val}) def start_service(self, service_name): LOG.debug('Starting service %s', service_name) service = self._get_service(service_name) (ret_val,) = service.StartService() if ret_val != 0: raise exception.CloudbaseInitException( 'Starting service %(service_name)s failed with return value: ' '%(ret_val)d' % {'service_name': service_name, 'ret_val': ret_val}) def stop_service(self, service_name): LOG.debug('Stopping service %s', service_name) service = self._get_service(service_name) (ret_val,) = service.StopService() if ret_val != 0: raise exception.CloudbaseInitException( 'Stopping service %(service_name)s failed with return value:' ' %(ret_val)d' % {'service_name': service_name, 'ret_val': ret_val}) def terminate(self): # Wait for the service to start. Polling the service "Started" property # is not enough time.sleep(3) self.stop_service(self._service_name) def get_default_gateway(self): default_routes = [r for r in self._get_ipv4_routing_table() if r[0] == '0.0.0.0'] if default_routes: return default_routes[0][3], default_routes[0][2] else: return None, None @staticmethod def _heap_alloc(heap, size): table_mem = kernel32.HeapAlloc(heap, 0, ctypes.c_size_t(size.value)) if not table_mem: raise exception.CloudbaseInitException( 'Unable to allocate memory for the IP forward table') return table_mem @contextlib.contextmanager def _get_forward_table(self): heap = kernel32.GetProcessHeap() forward_table_size = ctypes.sizeof(Win32_MIB_IPFORWARDTABLE) size = wintypes.ULONG(forward_table_size) table_mem = self._heap_alloc(heap, size) p_forward_table = ctypes.cast( table_mem, ctypes.POINTER(Win32_MIB_IPFORWARDTABLE)) try: err = iphlpapi.GetIpForwardTable(p_forward_table, ctypes.byref(size), 0) if err == self.ERROR_INSUFFICIENT_BUFFER: kernel32.HeapFree(heap, 0, p_forward_table) table_mem = self._heap_alloc(heap, size) p_forward_table = ctypes.cast( table_mem, ctypes.POINTER(Win32_MIB_IPFORWARDTABLE)) err = iphlpapi.GetIpForwardTable(p_forward_table, ctypes.byref(size), 0) if err and err != kernel32.ERROR_NO_DATA: raise exception.CloudbaseInitException( 'Unable to get IP forward table. Error: %s' % err) yield p_forward_table finally: kernel32.HeapFree(heap, 0, p_forward_table) def _get_ipv4_routing_table(self): routing_table = [] with self._get_forward_table() as p_forward_table: forward_table = p_forward_table.contents table = ctypes.cast( ctypes.addressof(forward_table.table), ctypes.POINTER(Win32_MIB_IPFORWARDROW * forward_table.dwNumEntries)).contents for row in table: destination = Ws2_32.inet_ntoa( row.dwForwardDest).decode() netmask = Ws2_32.inet_ntoa( row.dwForwardMask).decode() gateway = Ws2_32.inet_ntoa( row.dwForwardNextHop).decode() routing_table.append(( destination, netmask, gateway, row.dwForwardIfIndex, row.dwForwardMetric1)) return routing_table def check_static_route_exists(self, destination): return len([r for r in self._get_ipv4_routing_table() if r[0] == destination]) > 0 def add_static_route(self, destination, mask, next_hop, interface_index, metric): args = ['ROUTE', 'ADD', destination, 'MASK', mask, next_hop] (out, err, ret_val) = self.execute_process(args) # Cannot use the return value to determine the outcome if ret_val or err: raise exception.CloudbaseInitException( 'Unable to add route: %s' % err) def check_os_version(self, major, minor, build=0): vi = Win32_OSVERSIONINFOEX_W() vi.dwOSVersionInfoSize = ctypes.sizeof(Win32_OSVERSIONINFOEX_W) vi.dwMajorVersion = major vi.dwMinorVersion = minor vi.dwBuildNumber = build mask = 0 for type_mask in [VER_MAJORVERSION, VER_MINORVERSION, VER_BUILDNUMBER]: mask = kernel32.VerSetConditionMask(mask, type_mask, VER_GREATER_EQUAL) type_mask = VER_MAJORVERSION | VER_MINORVERSION | VER_BUILDNUMBER ret_val = ntdll.RtlVerifyVersionInfo(ctypes.byref(vi), type_mask, mask) if not ret_val: return True elif ret_val == self.STATUS_REVISION_MISMATCH: return False else: raise exception.CloudbaseInitException( "RtlVerifyVersionInfo failed with error: %s" % ret_val) def get_volume_label(self, drive): max_label_size = 261 label = ctypes.create_unicode_buffer(max_label_size) ret_val = kernel32.GetVolumeInformationW(six.text_type(drive), label, max_label_size, 0, 0, 0, 0, 0) if ret_val: return label.value def generate_random_password(self, length): while True: pwd = super(WindowsUtils, self).generate_random_password(length) # Make sure that the Windows complexity requirements are met: # http://technet.microsoft.com/en-us/library/cc786468(v=ws.10).aspx valid = True for r in ["[a-z]", "[A-Z]", "[0-9]"]: if not re.search(r, pwd): valid = False if valid: return pwd def _split_str_buf_list(self, buf, buf_len): i = 0 value = '' values = [] while i < buf_len: c = buf[i] if c != '\x00': value += c else: values.append(value) value = '' i += 1 return values def _get_logical_drives(self): buf_size = self.MAX_PATH buf = ctypes.create_unicode_buffer(buf_size + 1) buf_len = kernel32.GetLogicalDriveStringsW(buf_size, buf) if not buf_len: raise exception.WindowsCloudbaseInitException( "GetLogicalDriveStringsW failed: %r") return self._split_str_buf_list(buf, buf_len) def get_cdrom_drives(self): drives = self._get_logical_drives() return [d for d in drives if kernel32.GetDriveTypeW(d) == self.DRIVE_CDROM] def _is_64bit_arch(self): # interpreter's bits return struct.calcsize("P") == 8 def get_physical_disks(self): physical_disks = [] disk_guid = GUID_DEVINTERFACE_DISK handle_disks = setupapi.SetupDiGetClassDevsW( ctypes.byref(disk_guid), None, None, self.DIGCF_PRESENT | self.DIGCF_DEVICEINTERFACE) if handle_disks == self.INVALID_HANDLE_VALUE: raise exception.CloudbaseInitException( "SetupDiGetClassDevs failed") try: did = Win32_SP_DEVICE_INTERFACE_DATA() did.cbSize = ctypes.sizeof(Win32_SP_DEVICE_INTERFACE_DATA) index = 0 while setupapi.SetupDiEnumDeviceInterfaces( handle_disks, None, ctypes.byref(disk_guid), index, ctypes.byref(did)): index += 1 handle_disk = self.INVALID_HANDLE_VALUE required_size = wintypes.DWORD() if not setupapi.SetupDiGetDeviceInterfaceDetailW( handle_disks, ctypes.byref(did), None, 0, ctypes.byref(required_size), None): if (kernel32.GetLastError() != self.ERROR_INSUFFICIENT_BUFFER): raise exception.WindowsCloudbaseInitException( "SetupDiGetDeviceInterfaceDetailW failed: %r") pdidd = ctypes.cast( msvcrt.malloc(ctypes.c_size_t(required_size.value)), ctypes.POINTER(Win32_SP_DEVICE_INTERFACE_DETAIL_DATA_W)) try: pdidd.contents.cbSize = ctypes.sizeof( Win32_SP_DEVICE_INTERFACE_DETAIL_DATA_W) if not self._is_64bit_arch(): # NOTE(cpoieana): For some reason, on x86 platforms # the alignment or content of the struct # is not taken into consideration. pdidd.contents.cbSize = 6 if not setupapi.SetupDiGetDeviceInterfaceDetailW( handle_disks, ctypes.byref(did), pdidd, required_size, None, None): raise exception.WindowsCloudbaseInitException( "SetupDiGetDeviceInterfaceDetailW failed: %r") device_path = ctypes.cast( pdidd.contents.DevicePath, wintypes.LPWSTR).value handle_disk = kernel32.CreateFileW( device_path, 0, self.FILE_SHARE_READ, None, self.OPEN_EXISTING, 0, 0) if handle_disk == self.INVALID_HANDLE_VALUE: raise exception.CloudbaseInitException( 'CreateFileW failed') sdn = Win32_STORAGE_DEVICE_NUMBER() b = wintypes.DWORD() if not kernel32.DeviceIoControl( handle_disk, self.IOCTL_STORAGE_GET_DEVICE_NUMBER, None, 0, ctypes.byref(sdn), ctypes.sizeof(sdn), ctypes.byref(b), None): raise exception.WindowsCloudbaseInitException( 'DeviceIoControl failed: %r') physical_disks.append( r"\\.\PHYSICALDRIVE%d" % sdn.DeviceNumber) finally: msvcrt.free(pdidd) if handle_disk != self.INVALID_HANDLE_VALUE: kernel32.CloseHandle(handle_disk) finally: setupapi.SetupDiDestroyDeviceInfoList(handle_disks) return physical_disks def get_volumes(self): """Retrieve a list with all the volumes found on all disks.""" volumes = [] volume = ctypes.create_unicode_buffer(chr(0) * self.MAX_PATH) handle_volumes = kernel32.FindFirstVolumeW(volume, self.MAX_PATH) if handle_volumes == self.INVALID_HANDLE_VALUE: raise exception.WindowsCloudbaseInitException( "FindFirstVolumeW failed: %r") try: while True: volumes.append(volume.value) found = kernel32.FindNextVolumeW(handle_volumes, volume, self.MAX_PATH) if not found: errno = ctypes.GetLastError() if errno == self.ERROR_NO_MORE_FILES: break else: raise exception.WindowsCloudbaseInitException( "FindNextVolumeW failed: %r") finally: kernel32.FindVolumeClose(handle_volumes) return volumes def _get_fw_protocol(self, protocol): if protocol == self.PROTOCOL_TCP: fw_protocol = self._FW_IP_PROTOCOL_TCP elif protocol == self.PROTOCOL_UDP: fw_protocol = self._FW_IP_PROTOCOL_UDP else: raise NotImplementedError("Unsupported protocol") return fw_protocol def firewall_create_rule(self, name, port, protocol, allow=True): if not allow: raise NotImplementedError() fw_port = client.Dispatch("HNetCfg.FWOpenPort") fw_port.Name = name fw_port.Protocol = self._get_fw_protocol(protocol) fw_port.Port = port fw_port.Scope = self._FW_SCOPE_ALL fw_port.Enabled = True fw_mgr = client.Dispatch("HNetCfg.FwMgr") fw_profile = fw_mgr.LocalPolicy.CurrentProfile fw_profile = fw_profile.GloballyOpenPorts.Add(fw_port) def firewall_remove_rule(self, name, port, protocol, allow=True): if not allow: raise NotImplementedError() fw_mgr = client.Dispatch("HNetCfg.FwMgr") fw_profile = fw_mgr.LocalPolicy.CurrentProfile <|fim▁hole|> return win32process.IsWow64Process() def get_system32_dir(self): return os.path.expandvars('%windir%\\system32') def get_syswow64_dir(self): return os.path.expandvars('%windir%\\syswow64') def get_sysnative_dir(self): return os.path.expandvars('%windir%\\sysnative') def check_sysnative_dir_exists(self): sysnative_dir_exists = os.path.isdir(self.get_sysnative_dir()) if not sysnative_dir_exists and self.is_wow64(): LOG.warning('Unable to validate sysnative folder presence. ' 'If Target OS is Server 2003 x64, please ensure ' 'you have KB942589 installed') return sysnative_dir_exists def _get_system_dir(self, sysnative=True): """Return Windows system directory with compatibility support. Depending on the interpreter bits and platform architecture, the return value may vary between C:\Windows\(System32|SysWOW64|Sysnative). Note that "Sysnative" is just an alias (doesn't really exist on disk). More info about this can be found in documentation. """ if sysnative and self.check_sysnative_dir_exists(): return self.get_sysnative_dir() if not sysnative and self._is_64bit_arch(): return self.get_syswow64_dir() return self.get_system32_dir() def is_nano_server(self): return self._check_server_level("NanoServer") def _check_server_level(self, server_level): try: with winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows NT\\CurrentVersion\\Server\\" "ServerLevels") as key: return winreg.QueryValueEx(key, server_level)[0] == 1 except WindowsError as ex: if ex.winerror == 2: return False else: raise def execute_powershell_script(self, script_path, sysnative=True): base_dir = self._get_system_dir(sysnative) powershell_path = os.path.join(base_dir, 'WindowsPowerShell\\v1.0\\' 'powershell.exe') args = [powershell_path] if not self.is_nano_server(): args += ['-ExecutionPolicy', 'RemoteSigned', '-NonInteractive', '-File'] args.append(script_path) return self.execute_process(args, shell=False) def execute_system32_process(self, args, shell=True, decode_output=False, sysnative=True): base_dir = self._get_system_dir(sysnative) process_path = os.path.join(base_dir, args[0]) return self.execute_process([process_path] + args[1:], decode_output=decode_output, shell=shell) def get_maximum_password_length(self): return 20 def set_timezone(self, timezone_name): windows_name = windows_tz.tz_win.get(timezone_name) if not windows_name: raise exception.CloudbaseInitException( "The given timezone name is unrecognised: %r" % timezone_name) timezone.Timezone(windows_name).set(self)<|fim▁end|>
fw_protocol = self._get_fw_protocol(protocol) fw_profile = fw_profile.GloballyOpenPorts.Remove(port, fw_protocol) def is_wow64(self):
<|file_name|>data-importer.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import sys, json, psycopg2, argparse parser = argparse.ArgumentParser(description='Imports word data into the taboo database.') parser.add_argument('--verified', dest='verified', action='store_true', help='include if these words are verified as good quality') parser.add_argument('--source', dest='source', help='include to set the source of these imported words') args = parser.parse_args() CONN_STR = 'dbname=prod user=prod' data_str = '\n'.join(sys.stdin.readlines()) data = json.loads(data_str) conn = psycopg2.connect(CONN_STR)<|fim▁hole|> cur = conn.cursor() count = 0 for word in data: try: cur.execute("INSERT INTO words (word, skipped, correct, status, source) VALUES(%s, %s, %s, %s, %s) RETURNING wid", (word, 0, 0, 'approved' if args.verified == True else 'unverified', args.source)) wordid = cur.fetchone()[0] prohibited_count = 0 for prohibited in data[word]: prohibited_count = prohibited_count + 1 cur.execute("INSERT INTO prohibited_words (wid, word, rank) VALUES(%s, %s, %s)", (wordid, prohibited, prohibited_count)) count = count + 1 except Exception as e: print e cur.close() conn.close() print 'Inserted ' + str(count) + ' words'<|fim▁end|>
conn.autocommit = True
<|file_name|>account.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from config.template_middleware import TemplateResponse from gaecookie.decorator import no_csrf from gaepermission.decorator import login_required from pytz import common_timezones import settings from tekton import router from tekton.gae.middleware.redirect import RedirectResponse from gaepermission.decorator import login_not_required @login_not_required @no_csrf def edit(_logged_user, name, user_locale, timezone): if name: _logged_user.name = name _logged_user.locale = user_locale<|fim▁hole|> _logged_user.put() return RedirectResponse('/') @login_not_required @no_csrf def index(_logged_user): _logged_user.locale = _logged_user.locale or settings.DEFAULT_LOCALE _logged_user.timezone = _logged_user.timezone or settings.DEFAULT_TIMEZONE context = {'user': _logged_user, 'timezones': common_timezones, 'save_path': router.to_path(edit)} return TemplateResponse(context, 'permission/account_form.html')<|fim▁end|>
_logged_user.timezone = timezone
<|file_name|>tracked_services.py<|end_file_name|><|fim▁begin|>""" Classes and functions to manage arkOS tracked services. arkOS Core (c) 2016 CitizenWeb Written by Jacob Cook Licensed under GPLv3, see LICENSE.md """ import glob import miniupnpc import random from arkos import config, logger, policies, signals, storage, security from arkos.messages import Notification from arkos.utilities import errors, test_port COMMON_PORTS = [3000, 3306, 5222, 5223, 5232] class SecurityPolicy: """ An object representing an arkOS firewall policy for a service. SecurityPolicies are created for all websites, as well as for all apps that have port-based services registered in their metadata files. They are used to compute the proper values to put into the arkOS firewall (iptables) on regeneration or app update. """ def __init__(self, type="", id="", name="", icon="", ports=[], policy=2, addr=None): """ Initialize the policy object. To create a new policy or to see more info about these parameters, see ``tracked_services.register()`` below. :param str type: Policy type ('website', 'app', etc) :param str id: Website or app ID :param str name: Display name to use in Security settings pane :param str icon: FontAwesome icon class name :param list ports: List of port tuples to allow/restrict :param int policy: Policy identifier :param str addr: Address and port (for websites) """ self.type = type self.id = id self.name = name self.icon = icon self.ports = ports self.policy = policy self.addr = addr def save(self, fw=True): """ Save changes to a security policy to disk. :param bool fw: Regenerate the firewall after save? """ if self.type == "custom": for x in policies.get_all("custom"): if self.id == x["id"]: policies.remove_list("custom", x) break policies.append( "custom", {"id": self.id, "name": self.name, "icon": self.icon, "ports": self.ports, "policy": self.policy} ) else: policies.set(self.type, self.id, self.policy) policies.save() storage.policies[self.id] = self if config.get("general", "firewall") and fw: security.regenerate_firewall(get()) def remove(self, fw=True): """ Remove a security policy from the firewall and config. You should probably use ``tracked_services.deregister()`` for this. :param bool fw: Regenerate the firewall after save? """ if self.type == "custom": for x in policies.get_all("custom"): if self.id == x["id"]: policies.remove_list("custom", x) break else: policies.remove(self.type, self.id) policies.save() if self.id in storage.policies: del storage.policies[self.id] if config.get("general", "firewall") and fw: security.regenerate_firewall(get()) @property def as_dict(self): """Return policy metadata as dict.""" return { "type": self.type, "id": self.id, "name": self.name, "icon": self.icon, "ports": self.ports, "policy": self.policy, "is_ready": True } @property def serialized(self): """Return serializable policy metadata as dict.""" return self.as_dict class PortConflictError(errors.Error): """Raised when an address and port requested are not available.""" def __init__(self, port, domain): self.port = port self.domain = domain def __str__(self): return ("This port is taken by another site or service, " "please choose another") def get(id=None, type=None): """ Get all security policies from cache storage. :param str id: App or website ID :param str type: Filter by type ('website', 'app', etc) """ data = storage.policies if id: return data.get(id) if type: return filter(lambda x: x.type == type, data.values()) return data.values() def register(type, id, name, icon, ports, domain=None, policy=0, default_policy=2, fw=True): """ Register a new security policy with the system. The ``ports`` parameter takes tuples of ports to manage, like so: ports = [('tcp', 8000), ('udp', 21500)] The ``policy`` parameter is an integer with the following meaning: 0 = Restrict access from all outside hosts. (excludes loopback) 1 = Restrict access to local networks only. 2 = Allow access to all networks and ultimately the whole Internet. Addresses should be provided for websites, because multiple websites can be served from the same port (SNI) as long as the address is different. :param str type: Policy type ('website', 'app', etc) :param str id: Website or app ID :param str name: Display name to use in Security settings pane :param str icon: FontAwesome icon class name :param list ports: List of port tuples to allow/restrict :param str domain: Address (for websites) :param int policy: Policy identifier :param int default_policy: Application default policy to use on first init :param bool fw: Regenerate the firewall after save? """ if not policy: policy = policies.get(type, id, default_policy) svc = SecurityPolicy(type, id, name, icon, ports, policy, domain) svc.save(fw) def deregister(type, id="", fw=True): """ Deregister a security policy. :param str type: Policy type ('website', 'app', etc) :param str id: Website or app ID :param bool fw: Regenerate the firewall after save? """ for x in get(type=type): if not id: x.remove(fw=False) elif x.id == id: x.remove(fw=False) break if config.get("general", "firewall") and fw: security.regenerate_firewall(get()) def refresh_policies(): """Recreate security policies based on what is stored in config.""" svcs = get() newpolicies = {} for x in policies.get_all(): if x == "custom": newpolicies["custom"] = policies.get_all("custom") for y in svcs: if x == y.type: if x not in newpolicies: newpolicies[x] = {} for s in policies.get_all(x): if s == y.id: newpolicies[x][s] = policies.get(x, s) policies.config = newpolicies policies.save() def is_open_port(port, domain=None, ignore_common=False): """ Check if the specified port is taken by a tracked service or not. Addresses should be provided for websites, because multiple websites can be served from the same port (SNI) as long as the address is different. :param int port: Port number to check :param str domain: Address to check (for websites) :param bool ignore_common: Don't return False for commonly used ports? :returns: True if port is open :rtype bool: """ data = get() ports = [] for x in data: if domain and x.type == "website" and domain != x.addr: continue for y in x.ports: ports.append(int(y[1])) if not ignore_common: ports = ports + COMMON_PORTS return port not in ports def _upnp_igd_connect(): logger.debug("TrSv", "Attempting to connect to uPnP IGD") upnpc = miniupnpc.UPnP() upnpc.discoverdelay = 3000 devs = upnpc.discover() if devs == 0: msg = "Failed to connect to uPnP IGD: no devices found" logger.warning("TrSv", msg) return try: upnpc.selectigd() except Exception as e: msg = "Failed to connect to uPnP IGD: {0}" logger.warning("TrSv", msg.format(str(e))) return upnpc def open_upnp(port): """ Open and forward a port with the local uPnP IGD. :param tuple port: Port protocol and number """ upnpc = _upnp_igd_connect() if not upnpc: return if upnpc.getspecificportmapping(int(port[1]), port[0].upper()): try: upnpc.deleteportmapping(int(port[1]), port[0].upper()) except: pass try: pf = 'arkOS Port Forwarding: {0}' upnpc.addportmapping( int(port[1]), port[0].upper(), upnpc.lanaddr, int(port[1]), pf.format(port[1]), '' ) except Exception as e: msg = "Failed to register {0} with uPnP IGD: {1}" logger.error("TrSv", msg.format(port, str(e))) def close_upnp(port): """ Remove forwarding of a port with the local uPnP IGD. :param tuple port: Port protocol and number """ upnpc = _upnp_igd_connect() if not upnpc: return if upnpc.getspecificportmapping(port[1], port[0].upper()): try: upnpc.deleteportmapping(port[1], port[0].upper()) except: pass def initialize_upnp(svcs): """ Initialize uPnP port forwarding with the IGD. :param SecurityPolicy svcs: SecurityPolicies to open """ upnpc = _upnp_igd_connect() if not upnpc: return for svc in svcs: if svc.policy != 2: continue for protocol, port in svc.ports: if upnpc.getspecificportmapping(port, protocol.upper()): try: upnpc.deleteportmapping(port, protocol.upper()) except: pass try: pf = 'arkOS Port Forwarding: {0}' upnpc.addportmapping(port, protocol.upper(), upnpc.lanaddr, port, pf.format(port), '') except Exception as e: msg = "Failed to register {0} with uPnP IGD: {1}"\ .format(port, str(e)) logger.warning("TrSv", msg) def open_all_upnp(ports): """ Open and forward multiple ports with the local uPnP IGD. :param list ports: List of port objects to open """ upnpc = _upnp_igd_connect() if not upnpc: return for port in [x for x in ports]: if upnpc.getspecificportmapping(port[1], port[0].upper()): try: upnpc.deleteportmapping(port[1], port[0].upper()) except: pass try: pf = 'arkOS Port Forwarding: {0}' upnpc.addportmapping(port[1], port[0].upper(), upnpc.lanaddr, port[1], pf.format(port[1]), '') except Exception as e: msg = "Failed to register {0} with uPnP IGD: {1}" logger.error("TrSv", msg.format(port, str(e))) def close_all_upnp(ports): """ Remove forwarding of multiple ports with the local uPnP IGD. :param list ports: List of port objects to close """ upnpc = _upnp_igd_connect() if not upnpc: return for port in [x for x in ports]: if upnpc.getspecificportmapping(port[1], port[0].upper()): try: upnpc.deleteportmapping(port[1], port[0].upper()) except: pass def get_open_port(ignore_common=False): """ Get a random TCP port not currently in use by a tracked service. :param bool ignore_common: Don't exclude commonly used ports? :returns: Port number :rtype: int """ data = get() ports = [] for x in data: for y in x.ports: ports.append(int(y[1])) if not ignore_common: ports = ports + COMMON_PORTS r = random.randint(8001, 65534) return r if r not in ports else get_open_port() def initialize(): """Initialize security policy tracking.""" logger.debug("TrSv", "Initializing security policy tracking") # arkOS policy = policies.get("arkos", "arkos", 2) port = [("tcp", int(config.get("genesis", "port")))] pol = SecurityPolicy("arkos", "arkos", "System Management (Genesis/APIs)", "server", port, policy) storage.policies[pol.id] = pol # uPNP policy = policies.get("arkos", "upnp", 1) pol = SecurityPolicy("arkos", "upnp", "uPnP Firewall Comms", "server", [("udp", 1900)], policy) if config.get("general", "enable_upnp"): storage.policies[pol.id] = pol # SSHd policy = policies.get("arkos", "sshd", 1) pol = SecurityPolicy( "arkos", "sshd", "SSH", "server", [("tcp", 22)], policy) # ACME dummies for x in glob.glob("/etc/nginx/sites-enabled/acme-*"): acme_name = x.split("/etc/nginx/sites-enabled/acme-")[1] pol = SecurityPolicy( "acme", acme_name, "{0} (ACME Validation)".format(acme_name), "globe", [('tcp', 80)], 2 ) storage.policies[pol.id] = pol for x in policies.get_all("custom"): pol = SecurityPolicy("custom", x["id"], x["name"], x["icon"], x["ports"], x["policy"]) storage.policies[pol.id] = pol def register_website(site): """Convenience function to register a website as tracked service.""" register("website", site.id, getattr(site, "name", site.id), site.app.icon if site.app else "globe", [("tcp", site.port)], site.domain) def deregister_website(site): """Convenience function to deregister a website as tracked service.""" deregister("website", site.id) <|fim▁hole|> if config.get("general", "enable_upnp"): open_upnp(("tcp", site.port)) domain = site.domain if domain == "localhost" or domain.endswith(".local"): domain = None try: test_port(config.get("general", "repo_server"), site.port, domain) except: msg = ("Port {0} and/or domain {1} could not be tested." " Make sure your ports are properly forwarded and" " that your domain is properly set up.")\ .format(site.port, site.domain) Notification("error", "TrSv", msg).send() def close_upnp_site(site): """Convenience function to deregister a website with uPnP.""" if config.get("general", "enable_upnp"): close_upnp(("tcp", site.port)) signals.add("tracked_services", "websites", "site_loaded", register_website) signals.add("tracked_services", "websites", "site_installed", register_website) signals.add("tracked_services", "websites", "site_installed", open_upnp_site) signals.add("tracked_services", "websites", "site_removed", deregister_website) signals.add("tracked_services", "websites", "site_removed", close_upnp_site)<|fim▁end|>
def open_upnp_site(site): """Convenience function to register a website with uPnP."""
<|file_name|>associated-types-no-suitable-supertrait.rs<|end_file_name|><|fim▁begin|>// Check that we get an error when you use `<Self as Get>::Value` in // the trait definition but `Self` does not, in fact, implement `Get`.<|fim▁hole|>// See also associated-types-no-suitable-supertrait-2.rs, which checks // that we see the same error if we get around to checking the default // method body. // // See also run-pass/associated-types-projection-to-unrelated-trait.rs, // which checks that the trait interface itself is not considered an // error as long as all impls satisfy the constraint. trait Get { type Value; } trait Other { fn uhoh<U:Get>(&self, foo: U, bar: <Self as Get>::Value) {} //~^ ERROR the trait bound `Self: Get` is not satisfied } impl<T:Get> Other for T { fn uhoh<U:Get>(&self, foo: U, bar: <(T, U) as Get>::Value) {} //~^ ERROR the trait bound `(T, U): Get` is not satisfied } fn main() { }<|fim▁end|>
//
<|file_name|>issue-9446.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<|fim▁hole|> struct Wrapper(StrBuf); impl Wrapper { pub fn new(wrapped: StrBuf) -> Wrapper { Wrapper(wrapped) } pub fn say_hi(&self) { let Wrapper(ref s) = *self; println!("hello {}", *s); } } impl Drop for Wrapper { fn drop(&mut self) {} } pub fn main() { { // This runs without complaint. let x = Wrapper::new("Bob".to_strbuf()); x.say_hi(); } { // This fails to compile, circa 0.8-89-gc635fba. // error: internal compiler error: drop_ty_immediate: non-box ty Wrapper::new("Bob".to_strbuf()).say_hi(); } }<|fim▁end|>
// 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.
<|file_name|>portal.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # portal.py # # # # # # # # # # # # # Copyright 2016 Giorgio Ladu <giorgio.ladu >at< gmail.com> # # # # 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<|fim▁hole|># distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # # # # # # import config print 'Status: 302 Found' print 'Location: http://' + config.custom_url print ''<|fim▁end|>
<|file_name|>PyFunctionTypeAnnotationElementTypes.java<|end_file_name|><|fim▁begin|>/* * Copyright 2000-2016 JetBrains s.r.o. * * 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 com.jetbrains.python.codeInsight.functionTypeComments; import com.jetbrains.python.codeInsight.functionTypeComments.psi.PyFunctionTypeAnnotation; import com.jetbrains.python.codeInsight.functionTypeComments.psi.PyParameterTypeList; import com.jetbrains.python.psi.PyElementType;<|fim▁hole|> /** * @author Mikhail Golubev */ public interface PyFunctionTypeAnnotationElementTypes { PyElementType FUNCTION_SIGNATURE = new PyElementType("FUNCTION_SIGNATURE", PyFunctionTypeAnnotation.class); PyElementType PARAMETER_TYPE_LIST = new PyElementType("PARAMETER_TYPE_LIST", PyParameterTypeList.class); }<|fim▁end|>
<|file_name|>ModelRepository.java<|end_file_name|><|fim▁begin|>/******************************************************************************* * Copyright [2016] [Quirino Brizi ([email protected])] * * 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 org.actio.modeler.domain.repository; import java.util.List; import org.actio.commons.message.model.ModelMessage; /**<|fim▁hole|> ModelMessage add(ModelMessage model); List<ModelMessage> getAllModels(); ModelMessage getModel(String modelKey); }<|fim▁end|>
* @author quirino.brizi * */ public interface ModelRepository {
<|file_name|>supported-cast.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::libc; pub fn main() { let f = 1 as *libc::FILE; info!(f as int); info!(f as uint); info!(f as i8); info!(f as i16); info!(f as i32); info!(f as i64); info!(f as u8); info!(f as u16);<|fim▁hole|> info!(1 as int); info!(1 as uint); info!(1 as float); info!(1 as bool); info!(1 as *libc::FILE); info!(1 as i8); info!(1 as i16); info!(1 as i32); info!(1 as i64); info!(1 as u8); info!(1 as u16); info!(1 as u32); info!(1 as u64); info!(1 as f32); info!(1 as f64); info!(1u as int); info!(1u as uint); info!(1u as float); info!(1u as bool); info!(1u as *libc::FILE); info!(1u as i8); info!(1u as i16); info!(1u as i32); info!(1u as i64); info!(1u as u8); info!(1u as u16); info!(1u as u32); info!(1u as u64); info!(1u as f32); info!(1u as f64); info!(1i8 as int); info!(1i8 as uint); info!(1i8 as float); info!(1i8 as bool); info!(1i8 as *libc::FILE); info!(1i8 as i8); info!(1i8 as i16); info!(1i8 as i32); info!(1i8 as i64); info!(1i8 as u8); info!(1i8 as u16); info!(1i8 as u32); info!(1i8 as u64); info!(1i8 as f32); info!(1i8 as f64); info!(1u8 as int); info!(1u8 as uint); info!(1u8 as float); info!(1u8 as bool); info!(1u8 as *libc::FILE); info!(1u8 as i8); info!(1u8 as i16); info!(1u8 as i32); info!(1u8 as i64); info!(1u8 as u8); info!(1u8 as u16); info!(1u8 as u32); info!(1u8 as u64); info!(1u8 as f32); info!(1u8 as f64); info!(1i16 as int); info!(1i16 as uint); info!(1i16 as float); info!(1i16 as bool); info!(1i16 as *libc::FILE); info!(1i16 as i8); info!(1i16 as i16); info!(1i16 as i32); info!(1i16 as i64); info!(1i16 as u8); info!(1i16 as u16); info!(1i16 as u32); info!(1i16 as u64); info!(1i16 as f32); info!(1i16 as f64); info!(1u16 as int); info!(1u16 as uint); info!(1u16 as float); info!(1u16 as bool); info!(1u16 as *libc::FILE); info!(1u16 as i8); info!(1u16 as i16); info!(1u16 as i32); info!(1u16 as i64); info!(1u16 as u8); info!(1u16 as u16); info!(1u16 as u32); info!(1u16 as u64); info!(1u16 as f32); info!(1u16 as f64); info!(1i32 as int); info!(1i32 as uint); info!(1i32 as float); info!(1i32 as bool); info!(1i32 as *libc::FILE); info!(1i32 as i8); info!(1i32 as i16); info!(1i32 as i32); info!(1i32 as i64); info!(1i32 as u8); info!(1i32 as u16); info!(1i32 as u32); info!(1i32 as u64); info!(1i32 as f32); info!(1i32 as f64); info!(1u32 as int); info!(1u32 as uint); info!(1u32 as float); info!(1u32 as bool); info!(1u32 as *libc::FILE); info!(1u32 as i8); info!(1u32 as i16); info!(1u32 as i32); info!(1u32 as i64); info!(1u32 as u8); info!(1u32 as u16); info!(1u32 as u32); info!(1u32 as u64); info!(1u32 as f32); info!(1u32 as f64); info!(1i64 as int); info!(1i64 as uint); info!(1i64 as float); info!(1i64 as bool); info!(1i64 as *libc::FILE); info!(1i64 as i8); info!(1i64 as i16); info!(1i64 as i32); info!(1i64 as i64); info!(1i64 as u8); info!(1i64 as u16); info!(1i64 as u32); info!(1i64 as u64); info!(1i64 as f32); info!(1i64 as f64); info!(1u64 as int); info!(1u64 as uint); info!(1u64 as float); info!(1u64 as bool); info!(1u64 as *libc::FILE); info!(1u64 as i8); info!(1u64 as i16); info!(1u64 as i32); info!(1u64 as i64); info!(1u64 as u8); info!(1u64 as u16); info!(1u64 as u32); info!(1u64 as u64); info!(1u64 as f32); info!(1u64 as f64); info!(1u64 as int); info!(1u64 as uint); info!(1u64 as float); info!(1u64 as bool); info!(1u64 as *libc::FILE); info!(1u64 as i8); info!(1u64 as i16); info!(1u64 as i32); info!(1u64 as i64); info!(1u64 as u8); info!(1u64 as u16); info!(1u64 as u32); info!(1u64 as u64); info!(1u64 as f32); info!(1u64 as f64); info!(true as int); info!(true as uint); info!(true as float); info!(true as bool); info!(true as *libc::FILE); info!(true as i8); info!(true as i16); info!(true as i32); info!(true as i64); info!(true as u8); info!(true as u16); info!(true as u32); info!(true as u64); info!(true as f32); info!(true as f64); info!(1. as int); info!(1. as uint); info!(1. as float); info!(1. as bool); info!(1. as i8); info!(1. as i16); info!(1. as i32); info!(1. as i64); info!(1. as u8); info!(1. as u16); info!(1. as u32); info!(1. as u64); info!(1. as f32); info!(1. as f64); info!(1f32 as int); info!(1f32 as uint); info!(1f32 as float); info!(1f32 as bool); info!(1f32 as i8); info!(1f32 as i16); info!(1f32 as i32); info!(1f32 as i64); info!(1f32 as u8); info!(1f32 as u16); info!(1f32 as u32); info!(1f32 as u64); info!(1f32 as f32); info!(1f32 as f64); info!(1f64 as int); info!(1f64 as uint); info!(1f64 as float); info!(1f64 as bool); info!(1f64 as i8); info!(1f64 as i16); info!(1f64 as i32); info!(1f64 as i64); info!(1f64 as u8); info!(1f64 as u16); info!(1f64 as u32); info!(1f64 as u64); info!(1f64 as f32); info!(1f64 as f64); }<|fim▁end|>
info!(f as u32); info!(f as u64);
<|file_name|>Footer.js<|end_file_name|><|fim▁begin|>/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ import React, {Component} from 'react'; import Link from 'gatsby-link'; import {Icon} from 'antd'; import './Footer.css'; import FacebookOSSLogo from './FacebookOSSLogo'; export default class Footer extends Component<{}> { render() { return ( <div className="Footer"> <a href="https://code.facebook.com/projects/" className="logoOSS"> <FacebookOSSLogo /> Facebook Open Source </a> <div className="SocialNetwork"><|fim▁hole|> </div> </div> ); } }<|fim▁end|>
<a href="https://github.com/facebook/yoga">GitHub</a> <a href="https://twitter.com/yogalayout">Twitter</a>
<|file_name|>bounds.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 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 ast::{MetaItem, MetaWord, Item}; use codemap::Span; use ext::base::ExtCtxt; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use ptr::P; pub fn expand_deriving_bound<F>(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: F) where F: FnOnce(P<Item>), {<|fim▁hole|> match &tname[..] { "Copy" => "Copy", "Send" | "Sync" => { return cx.span_err(span, &format!("{} is an unsafe trait and it \ should be implemented explicitly", *tname)) } ref tname => { cx.span_bug(span, &format!("expected built-in trait name but \ found {}", *tname)) } } }, _ => { return cx.span_err(span, "unexpected value in deriving, expected \ a trait") } }; let path = Path::new(vec![ if cx.use_std { "std" } else { "core" }, "marker", name ]); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: path, additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: Vec::new(), associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) }<|fim▁end|>
let name = match mitem.node { MetaWord(ref tname) => {
<|file_name|>solver.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """Additional helper functions for the optlang solvers. All functions integrate well with the context manager, meaning that all operations defined here are automatically reverted when used in a `with model:` block. The functions defined here together with the existing model functions should allow you to implement custom flux analysis methods with ease. """ from __future__ import absolute_import import re from functools import partial from collections import namedtuple from types import ModuleType from warnings import warn import optlang from optlang.symbolics import Basic, Zero from cobra.exceptions import OptimizationError, OPTLANG_TO_EXCEPTIONS_DICT from cobra.util.context import get_context class SolverNotFound(Exception): """A simple Exception when a solver can not be found.""" pass # Define all the solvers that are found in optlang. solvers = {match.split("_")[0]: getattr(optlang, match) for match in dir(optlang) if "_interface" in match} # Defines all the QP solvers implemented in optlang. qp_solvers = ["cplex"] # QP in gurobi not implemented yet def linear_reaction_coefficients(model, reactions=None): """Coefficient for the reactions in a linear objective. Parameters ---------- model : cobra model the model object that defined the objective reactions : list an optional list for the reactions to get the coefficients for. All reactions if left missing. Returns ------- dict A dictionary where the key is the reaction object and the value is the corresponding coefficient. Empty dictionary if there are no linear terms in the objective. """ linear_coefficients = {} reactions = model.reactions if not reactions else reactions try: objective_expression = model.solver.objective.expression coefficients = objective_expression.as_coefficients_dict() except AttributeError: return linear_coefficients for rxn in reactions: forward_coefficient = coefficients.get(rxn.forward_variable, 0) reverse_coefficient = coefficients.get(rxn.reverse_variable, 0) if forward_coefficient != 0: if forward_coefficient == -reverse_coefficient: linear_coefficients[rxn] = float(forward_coefficient) return linear_coefficients def _valid_atoms(model, expression): """Check whether a sympy expression references the correct variables. Parameters ---------- model : cobra.Model The model in which to check for variables. expression : sympy.Basic A sympy expression. Returns ------- boolean True if all referenced variables are contained in model, False otherwise. """ atoms = expression.atoms(optlang.interface.Variable) return all(a.problem is model.solver for a in atoms) def set_objective(model, value, additive=False): """Set the model objective. Parameters ---------- model : cobra model The model to set the objective for value : model.problem.Objective, e.g. optlang.glpk_interface.Objective, sympy.Basic or dict If the model objective is linear, the value can be a new Objective object or a dictionary with linear coefficients where each key is a reaction and the element the new coefficient (float). If the objective is not linear and `additive` is true, only values of class Objective. additive : bool If true, add the terms to the current objective, otherwise start with an empty objective. """ interface = model.problem reverse_value = model.solver.objective.expression reverse_value = interface.Objective( reverse_value, direction=model.solver.objective.direction, sloppy=True) if isinstance(value, dict): if not model.objective.is_Linear: raise ValueError('can only update non-linear objectives ' 'additively using object of class ' 'model.problem.Objective, not %s' % type(value)) if not additive: model.solver.objective = interface.Objective( Zero, direction=model.solver.objective.direction) for reaction, coef in value.items(): model.solver.objective.set_linear_coefficients( {reaction.forward_variable: coef, reaction.reverse_variable: -coef}) elif isinstance(value, (Basic, optlang.interface.Objective)): if isinstance(value, Basic): value = interface.Objective( value, direction=model.solver.objective.direction, sloppy=False) # Check whether expression only uses variables from current model # clone the objective if not, faster than cloning without checking if not _valid_atoms(model, value.expression): value = interface.Objective.clone(value, model=model.solver) if not additive: model.solver.objective = value else: model.solver.objective += value.expression else: raise TypeError( '%r is not a valid objective for %r.' % (value, model.solver)) context = get_context(model) if context: def reset(): model.solver.objective = reverse_value model.solver.objective.direction = reverse_value.direction context(reset) def interface_to_str(interface): """Give a string representation for an optlang interface. Parameters ---------- interface : string, ModuleType Full name of the interface in optlang or cobra representation. For instance 'optlang.glpk_interface' or 'optlang-glpk'. Returns ------- string The name of the interface as a string """ if isinstance(interface, ModuleType): interface = interface.__name__ return re.sub(r"optlang.|.interface", "", interface) def get_solver_name(mip=False, qp=False): """Select a solver for a given optimization problem. Parameters ---------- mip : bool Does the solver require mixed integer linear programming capabilities? qp : bool Does the solver require quadratic programming capabilities? Returns ------- string The name of feasible solver. Raises ------ SolverNotFound If no suitable solver could be found. """ if len(solvers) == 0: raise SolverNotFound("no solvers installed") # Those lists need to be updated as optlang implements more solvers mip_order = ["gurobi", "cplex", "glpk"] lp_order = ["glpk", "cplex", "gurobi"] qp_order = ["cplex"] if mip is False and qp is False: for solver_name in lp_order: if solver_name in solvers: return solver_name # none of them are in the list order - so return the first one return list(solvers)[0] elif qp: # mip does not yet matter for this determination for solver_name in qp_order: if solver_name in solvers: return solver_name raise SolverNotFound("no qp-capable solver found") else: for solver_name in mip_order: if solver_name in solvers: return solver_name raise SolverNotFound("no mip-capable solver found") def choose_solver(model, solver=None, qp=False): """Choose a solver given a solver name and model. This will choose a solver compatible with the model and required capabilities. Also respects model.solver where it can. Parameters ---------- model : a cobra model The model for which to choose the solver. solver : str, optional The name of the solver to be used. Optlang solvers should be prefixed by "optlang-", for instance "optlang-glpk". qp : boolean, optional Whether the solver needs Quadratic Programming capabilities. Returns ------- legacy : boolean Whether the returned solver is a legacy (old cobra solvers) version or an optlang solver (legacy = False).<|fim▁hole|> Raises ------ SolverNotFound If no suitable solver could be found. """ legacy = False if solver is None: solver = model.problem elif "optlang-" in solver: solver = interface_to_str(solver) solver = solvers[solver] else: legacy = True solver = legacy_solvers.solver_dict[solver] # Check for QP, raise error if no QP solver found # optlang only since old interface interprets None differently if qp and interface_to_str(solver) not in qp_solvers: solver = solvers[get_solver_name(qp=True)] return legacy, solver def add_cons_vars_to_problem(model, what, **kwargs): """Add variables and constraints to a Model's solver object. Useful for variables and constraints that can not be expressed with reactions and lower/upper bounds. Will integrate with the Model's context manager in order to revert changes upon leaving the context. Parameters ---------- model : a cobra model The model to which to add the variables and constraints. what : list or tuple of optlang variables or constraints. The variables or constraints to add to the model. Must be of class `model.problem.Variable` or `model.problem.Constraint`. **kwargs : keyword arguments passed to solver.add() """ context = get_context(model) model.solver.add(what, **kwargs) if context: context(partial(model.solver.remove, what)) def remove_cons_vars_from_problem(model, what): """Remove variables and constraints from a Model's solver object. Useful to temporarily remove variables and constraints from a Models's solver object. Parameters ---------- model : a cobra model The model from which to remove the variables and constraints. what : list or tuple of optlang variables or constraints. The variables or constraints to remove from the model. Must be of class `model.problem.Variable` or `model.problem.Constraint`. """ context = get_context(model) model.solver.remove(what) if context: context(partial(model.solver.add, what)) def add_absolute_expression(model, expression, name="abs_var", ub=None, difference=0, add=True): """Add the absolute value of an expression to the model. Also defines a variable for the absolute value that can be used in other objectives or constraints. Parameters ---------- model : a cobra model The model to which to add the absolute expression. expression : A sympy expression Must be a valid expression within the Model's solver object. The absolute value is applied automatically on the expression. name : string The name of the newly created variable. ub : positive float The upper bound for the variable. difference : positive float The difference between the expression and the variable. add : bool Whether to add the variable to the model at once. Returns ------- namedtuple A named tuple with variable and two constraints (upper_constraint, lower_constraint) describing the new variable and the constraints that assign the absolute value of the expression to it. """ Components = namedtuple('Components', ['variable', 'upper_constraint', 'lower_constraint']) variable = model.problem.Variable(name, lb=0, ub=ub) # The following constraints enforce variable > expression and # variable > -expression upper_constraint = model.problem.Constraint(expression - variable, ub=difference, name="abs_pos_" + name), lower_constraint = model.problem.Constraint(expression + variable, lb=difference, name="abs_neg_" + name) to_add = Components(variable, upper_constraint, lower_constraint) if add: add_cons_vars_to_problem(model, to_add) return to_add def fix_objective_as_constraint(model, fraction=1, bound=None, name='fixed_objective_{}'): """Fix current objective as an additional constraint. When adding constraints to a model, such as done in pFBA which minimizes total flux, these constraints can become too powerful, resulting in solutions that satisfy optimality but sacrifices too much for the original objective function. To avoid that, we can fix the current objective value as a constraint to ignore solutions that give a lower (or higher depending on the optimization direction) objective value than the original model. When done with the model as a context, the modification to the objective will be reverted when exiting that context. Parameters ---------- model : cobra.Model The model to operate on fraction : float The fraction of the optimum the objective is allowed to reach. bound : float, None The bound to use instead of fraction of maximum optimal value. If not None, fraction is ignored. name : str Name of the objective. May contain one `{}` placeholder which is filled with the name of the old objective. """ fix_objective_name = name.format(model.objective.name) if fix_objective_name in model.constraints: model.solver.remove(fix_objective_name) if bound is None: bound = model.slim_optimize(error_value=None) * fraction if model.objective.direction == 'max': ub, lb = None, bound else: ub, lb = bound, None constraint = model.problem.Constraint( model.objective.expression, name=fix_objective_name, ub=ub, lb=lb) add_cons_vars_to_problem(model, constraint, sloppy=True) def check_solver_status(status, raise_error=False): """Perform standard checks on a solver's status.""" if status == optlang.interface.OPTIMAL: return elif status == optlang.interface.INFEASIBLE and not raise_error: warn("solver status is '{}'".format(status), UserWarning) elif status is None: raise RuntimeError( "model was not optimized yet or solver context switched") else: raise OptimizationError("solver status is '{}'".format(status)) def assert_optimal(model, message='optimization failed'): """Assert model solver status is optimal. Do nothing if model solver status is optimal, otherwise throw appropriate exception depending on the status. Parameters ---------- model : cobra.Model The model to check the solver status for. message : str (optional) Message to for the exception if solver status was not optimal. """ if model.solver.status != optlang.interface.OPTIMAL: raise OPTLANG_TO_EXCEPTIONS_DICT[model.solver.status](message) import cobra.solvers as legacy_solvers # noqa<|fim▁end|>
solver : a cobra or optlang solver interface Returns a valid solver for the problem. May be a cobra solver or an optlang interface.
<|file_name|>task-repository.ts<|end_file_name|><|fim▁begin|>import { Task } from '../entities' import { NotFoundError } from '../errors' import { MySql } from '../lib/database' export class TaskRepository { private readonly TABLE: string = 'task' private db: MySql constructor(db: MySql) { this.db = db } public async find(userId: number, id: number): Promise<Task> { const conn = await this.db.getConnection() const row = await conn .select() .from(this.TABLE) .where({ id, user_id: userId }) .first() if (!row) { throw new NotFoundError('Task does not exist') } return this.transform(row) } public async findByUser( userId: number, limit: number, offset: number ): Promise<Task[]> { const conn = await this.db.getConnection() const results = await conn .select() .from(this.TABLE) .where({ user_id: userId }) .orderBy('updated', 'DESC') .offset(offset) .limit(limit) return results.map((r: any) => this.transform(r)) } public async insert(task: Task): Promise<Task> { task.created = new Date() task.updated = new Date() const conn = await this.db.getConnection() const result = await conn.table(this.TABLE).insert({ name: task.name, description: task.description, done: task.done, created: task.created, updated: task.updated, user_id: task.userId }) task.id = result[0] return task }<|fim▁hole|> public async update(task: Task): Promise<Task> { task.updated = new Date() const conn = await this.db.getConnection() await conn .table(this.TABLE) .update({ name: task.name, description: task.description, done: task.done }) .where({ user_id: task.userId, id: task.id }) return task } public async delete(userId: number, taskId: number): Promise<void> { const conn = await this.db.getConnection() const result = await conn .from(this.TABLE) .delete() .where({ id: taskId, user_id: userId }) if (result === 0) { throw new NotFoundError('Task does not exist') } } private transform(row: any): Task { return { id: row.id, name: row.name, description: row.description, userId: row.user_id, done: row.done === 1, created: row.created, updated: row.updated } } }<|fim▁end|>
<|file_name|>negative_binomial.rs<|end_file_name|><|fim▁begin|>use crate::distribution::{self, poisson, Discrete, DiscreteCDF}; use crate::function::{beta, gamma}; use crate::statistics::*; use crate::{Result, StatsError}; use rand::Rng; use std::f64; /// Implements the /// [NegativeBinomial](http://en.wikipedia.org/wiki/Negative_binomial_distribution) /// distribution /// /// # Examples /// /// ``` /// use statrs::distribution::{NegativeBinomial, Discrete}; /// use statrs::statistics::DiscreteDistribution; /// use statrs::prec::almost_eq; /// /// let r = NegativeBinomial::new(4.0, 0.5).unwrap(); /// assert_eq!(r.mean().unwrap(), 4.0); /// assert!(almost_eq(r.pmf(0), 0.0625, 1e-8)); /// assert!(almost_eq(r.pmf(3), 0.15625, 1e-8)); /// ``` #[derive(Debug, Copy, Clone, PartialEq)] pub struct NegativeBinomial { r: f64, p: f64, } impl NegativeBinomial { /// Constructs a new negative binomial distribution /// with a given `p` probability of the number of successes `r` /// /// # Errors /// /// Returns an error if `p` is `NaN`, less than `0.0`, /// greater than `1.0`, or if `r` is `NaN` or less than `0` /// /// # Examples /// /// ``` /// use statrs::distribution::NegativeBinomial; /// /// let mut result = NegativeBinomial::new(4.0, 0.5); /// assert!(result.is_ok()); /// /// result = NegativeBinomial::new(-0.5, 5.0); /// assert!(result.is_err()); /// ``` pub fn new(r: f64, p: f64) -> Result<NegativeBinomial> { if p.is_nan() || p < 0.0 || p > 1.0 || r.is_nan() || r < 0.0 { Err(StatsError::BadParams) } else { Ok(NegativeBinomial { p, r }) } } /// Returns the probability of success `p` of /// the negative binomial distribution. /// /// # Examples /// /// ``` /// use statrs::distribution::NegativeBinomial; /// /// let r = NegativeBinomial::new(5.0, 0.5).unwrap(); /// assert_eq!(r.p(), 0.5); /// ``` pub fn p(&self) -> f64 { self.p } /// Returns the number `r` of success of this negative /// binomial distribution /// /// # Examples /// /// ``` /// use statrs::distribution::NegativeBinomial; /// /// let r = NegativeBinomial::new(5.0, 0.5).unwrap(); /// assert_eq!(r.r(), 5.0); /// ``` pub fn r(&self) -> f64 { self.r } } impl ::rand::distributions::Distribution<u64> for NegativeBinomial { fn sample<R: Rng + ?Sized>(&self, r: &mut R) -> u64 { let lambda = distribution::gamma::sample_unchecked(r, self.r, (1.0 - self.p) / self.p); poisson::sample_unchecked(r, lambda).floor() as u64 } } impl DiscreteCDF<u64, f64> for NegativeBinomial { /// Calculates the cumulative distribution function for the /// negative binomial distribution at `x` /// /// Note that due to extending the distribution to the reals /// (allowing positive real values for `r`), while still technically /// a discrete distribution the CDF behaves more like that of a /// continuous distribution rather than a discrete distribution /// (i.e. a smooth graph rather than a step-ladder) /// /// # Formula /// /// ```ignore /// 1 - I_(1 - p)(x + 1, r) /// ``` /// /// where `I_(x)(a, b)` is the regularized incomplete beta function fn cdf(&self, x: u64) -> f64 { 1.0 - beta::beta_reg(x as f64 + 1.0, self.r, 1.0 - self.p) } } impl Min<u64> for NegativeBinomial { /// Returns the minimum value in the domain of the /// negative binomial distribution representable by a 64-bit /// integer /// /// # Formula /// /// ```ignore /// 0 /// ``` fn min(&self) -> u64 { 0 } } impl Max<u64> for NegativeBinomial { /// Returns the maximum value in the domain of the /// negative binomial distribution representable by a 64-bit /// integer /// /// # Formula /// /// ```ignore /// u64::MAX /// ``` fn max(&self) -> u64 { std::u64::MAX } } impl DiscreteDistribution<f64> for NegativeBinomial { /// Returns the mean of the negative binomial distribution /// /// # Formula /// /// ```ignore /// r * (1-p) / p /// ``` fn mean(&self) -> Option<f64> { Some(self.r * (1.0 - self.p) / self.p) } /// Returns the variance of the negative binomial distribution /// /// # Formula /// /// ```ignore /// r * (1-p) / p^2 /// ``` fn variance(&self) -> Option<f64> { Some(self.r * (1.0 - self.p) / (self.p * self.p)) } /// Returns the skewness of the negative binomial distribution /// /// # Formula /// /// ```ignore /// (2-p) / sqrt(r * (1-p)) /// ``` fn skewness(&self) -> Option<f64> { Some((2.0 - self.p) / f64::sqrt(self.r * (1.0 - self.p))) } } impl Mode<Option<f64>> for NegativeBinomial { /// Returns the mode for the negative binomial distribution /// /// # Formula /// /// ```ignore /// if r > 1 then /// floor((r - 1) * (1-p / p)) /// else /// 0 /// ``` fn mode(&self) -> Option<f64> { let mode = if self.r > 1.0 { f64::floor((self.r - 1.0) * (1.0 - self.p) / self.p) } else { 0.0 }; Some(mode) } } impl Discrete<u64, f64> for NegativeBinomial { /// Calculates the probability mass function for the negative binomial /// distribution at `x` /// /// # Formula /// /// ```ignore /// (x + r - 1 choose k) * (1 - p)^x * p^r /// ``` fn pmf(&self, x: u64) -> f64 { self.ln_pmf(x).exp() } /// Calculates the log probability mass function for the negative binomial /// distribution at `x` /// /// # Formula /// /// ```ignore /// ln(x + r - 1 choose k) * (1 - p)^x * p^r)) /// ``` fn ln_pmf(&self, x: u64) -> f64 { let k = x as f64; gamma::ln_gamma(self.r + k) - gamma::ln_gamma(self.r) - gamma::ln_gamma(k + 1.0) + (self.r * self.p.ln()) + (k * (1.0 - self.p).ln()) } } #[rustfmt::skip] #[cfg(test)] mod tests { use std::fmt::Debug; use crate::statistics::*; use crate::distribution::{DiscreteCDF, Discrete, NegativeBinomial}; use crate::consts::ACC; fn try_create(r: f64, p: f64) -> NegativeBinomial { let r = NegativeBinomial::new(r, p); assert!(r.is_ok()); r.unwrap() } fn create_case(r: f64, p: f64) { let dist = try_create(r, p); assert_eq!(p, dist.p()); assert_eq!(r, dist.r()); } fn bad_create_case(r: f64, p: f64) { let r = NegativeBinomial::new(r, p); assert!(r.is_err()); } fn get_value<T, F>(r: f64, p: f64, eval: F) -> T where T: PartialEq + Debug, F: Fn(NegativeBinomial) -> T { let r = try_create(r, p); eval(r) } fn test_case<T, F>(r: f64, p: f64, expected: T, eval: F) where T: PartialEq + Debug, F: Fn(NegativeBinomial) -> T { let x = get_value(r, p, eval); assert_eq!(expected, x); } fn test_case_or_nan<F>(r: f64, p: f64, expected: f64, eval: F) where F: Fn(NegativeBinomial) -> f64 { let x = get_value(r, p, eval); if expected.is_nan() { assert!(x.is_nan()) } else { assert_eq!(expected, x); } } fn test_almost<F>(r: f64, p: f64, expected: f64, acc: f64, eval: F) where F: Fn(NegativeBinomial) -> f64 { let x = get_value(r, p, eval); assert_almost_eq!(expected, x, acc); } #[test] fn test_create() { create_case(0.0, 0.0); create_case(0.3, 0.4); create_case(1.0, 0.3); } #[test] fn test_bad_create() { bad_create_case(f64::NAN, 1.0); bad_create_case(0.0, f64::NAN); bad_create_case(-1.0, 1.0); bad_create_case(2.0, 2.0); } #[test] fn test_mean() { let mean = |x: NegativeBinomial| x.mean().unwrap(); test_case(4.0, 0.0, f64::INFINITY, mean); test_almost(3.0, 0.3, 7.0, 1e-15 , mean); test_case(2.0, 1.0, 0.0, mean); } #[test] fn test_variance() { let variance = |x: NegativeBinomial| x.variance().unwrap(); test_case(4.0, 0.0, f64::INFINITY, variance); test_almost(3.0, 0.3, 23.333333333333, 1e-12, variance); test_case(2.0, 1.0, 0.0, variance); } #[test] fn test_skewness() { let skewness = |x: NegativeBinomial| x.skewness().unwrap(); test_case(0.0, 0.0, f64::INFINITY, skewness); test_almost(0.1, 0.3, 6.425396041, 1e-09, skewness); test_case(1.0, 1.0, f64::INFINITY, skewness); } #[test] fn test_mode() { let mode = |x: NegativeBinomial| x.mode().unwrap(); test_case(0.0, 0.0, 0.0, mode); test_case(0.3, 0.0, 0.0, mode); test_case(1.0, 1.0, 0.0, mode); test_case(10.0, 0.01, 891.0, mode); } #[test] fn test_min_max() { let min = |x: NegativeBinomial| x.min(); let max = |x: NegativeBinomial| x.max(); test_case(1.0, 0.5, 0, min); test_case(1.0, 0.3, std::u64::MAX, max); } #[test] fn test_pmf() { let pmf = |arg: u64| move |x: NegativeBinomial| x.pmf(arg); test_almost(4.0, 0.5, 0.0625, 1e-8, pmf(0)); test_almost(4.0, 0.5, 0.15625, 1e-8, pmf(3)); test_case(1.0, 0.0, 0.0, pmf(0)); test_case(1.0, 0.0, 0.0, pmf(1)); test_almost(3.0, 0.2, 0.008, 1e-15, pmf(0)); test_almost(3.0, 0.2, 0.0192, 1e-15, pmf(1)); test_almost(3.0, 0.2, 0.04096, 1e-15, pmf(3)); test_almost(10.0, 0.2, 1.024e-07, 1e-07, pmf(0)); test_almost(10.0, 0.2, 8.192e-07, 1e-07, pmf(1)); test_almost(10.0, 0.2, 0.001015706852, 1e-07, pmf(10)); test_almost(1.0, 0.3, 0.3, 1e-15, pmf(0)); test_almost(1.0, 0.3, 0.21, 1e-15, pmf(1)); test_almost(3.0, 0.3, 0.027, 1e-15, pmf(0)); test_case(0.3, 1.0, 0.0, pmf(1)); test_case(0.3, 1.0, 0.0, pmf(3)); test_case_or_nan(0.3, 1.0, f64::NAN, pmf(0)); test_case(0.3, 1.0, 0.0, pmf(1)); test_case(0.3, 1.0, 0.0, pmf(10)); test_case_or_nan(1.0, 1.0, f64::NAN, pmf(0)); test_case(1.0, 1.0, 0.0, pmf(1)); test_case_or_nan(3.0, 1.0, f64::NAN, pmf(0)); test_case(3.0, 1.0, 0.0, pmf(1)); test_case(3.0, 1.0, 0.0, pmf(3)); test_case_or_nan(10.0, 1.0, f64::NAN, pmf(0)); test_case(10.0, 1.0, 0.0, pmf(1)); test_case(10.0, 1.0, 0.0, pmf(10)); } #[test] fn test_ln_pmf() { let ln_pmf = |arg: u64| move |x: NegativeBinomial| x.ln_pmf(arg); test_case(1.0, 0.0, f64::NEG_INFINITY, ln_pmf(0)); test_case(1.0, 0.0, f64::NEG_INFINITY, ln_pmf(1)); test_almost(3.0, 0.2, -4.828313737, 1e-08, ln_pmf(0)); test_almost(3.0, 0.2, -3.952845, 1e-08, ln_pmf(1)); test_almost(3.0, 0.2, -3.195159298, 1e-08, ln_pmf(3)); test_almost(10.0, 0.2, -16.09437912, 1e-08, ln_pmf(0)); test_almost(10.0, 0.2, -14.01493758, 1e-08, ln_pmf(1)); test_almost(10.0, 0.2, -6.892170503, 1e-08, ln_pmf(10)); test_almost(1.0, 0.3, -1.203972804, 1e-08, ln_pmf(0)); test_almost(1.0, 0.3, -1.560647748, 1e-08, ln_pmf(1)); test_almost(3.0, 0.3, -3.611918413, 1e-08, ln_pmf(0)); test_case(0.3, 1.0, f64::NEG_INFINITY, ln_pmf(1)); test_case(0.3, 1.0, f64::NEG_INFINITY, ln_pmf(3)); test_case_or_nan(0.3, 1.0, f64::NAN, ln_pmf(0)); test_case(0.3, 1.0, f64::NEG_INFINITY, ln_pmf(1)); test_case(0.3, 1.0, f64::NEG_INFINITY, ln_pmf(10)); test_case_or_nan(1.0, 1.0, f64::NAN, ln_pmf(0)); test_case(1.0, 1.0, f64::NEG_INFINITY, ln_pmf(1)); test_case_or_nan(3.0, 1.0, f64::NAN, ln_pmf(0)); test_case(3.0, 1.0, f64::NEG_INFINITY, ln_pmf(1)); test_case(3.0, 1.0, f64::NEG_INFINITY, ln_pmf(3)); test_case_or_nan(10.0, 1.0, f64::NAN, ln_pmf(0)); test_case(10.0, 1.0, f64::NEG_INFINITY, ln_pmf(1)); test_case(10.0, 1.0, f64::NEG_INFINITY, ln_pmf(10)); } #[test] fn test_cdf() { let cdf = |arg: u64| move |x: NegativeBinomial| x.cdf(arg);<|fim▁hole|> test_case(1.0, 1.0, 1.0, cdf(0)); test_case(1.0, 1.0, 1.0, cdf(1)); test_almost(10.0, 0.75, 0.05631351471, 1e-08, cdf(0)); test_almost(10.0, 0.75, 0.1970973015, 1e-08, cdf(1)); test_almost(10.0, 0.75, 0.9960578583, 1e-08, cdf(10)); } #[test] fn test_cdf_upper_bound() { let cdf = |arg: u64| move |x: NegativeBinomial| x.cdf(arg); test_case(3.0, 0.5, 1.0, cdf(100)); } // TODO: figure out the best way to re-implement this test. We currently // do not have a good way to characterize a discrete distribution with a // CDF that is continuous // // #[test] // fn test_discrete() { // test::check_discrete_distribution(&try_create(5.0, 0.3), 35); // test::check_discrete_distribution(&try_create(10.0, 0.7), 21); // } }<|fim▁end|>
test_almost(1.0, 0.3, 0.3, 1e-08, cdf(0)); test_almost(1.0, 0.3, 0.51, 1e-08, cdf(1)); test_almost(1.0, 0.3, 0.83193, 1e-08, cdf(4)); test_almost(1.0, 0.3, 0.9802267326, 1e-08, cdf(10));
<|file_name|>debugModel.test.ts<|end_file_name|><|fim▁begin|>/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import assert = require('assert'); import uri from 'vs/base/common/uri'; import severity from 'vs/base/common/severity'; import debugmodel = require('vs/workbench/parts/debug/common/debugModel'); import * as sinon from 'sinon'; import {MockDebugService} from 'vs/workbench/parts/debug/test/common/mockDebugService'; suite('Debug - Model', () => { var model: debugmodel.Model; setup(() => { model = new debugmodel.Model([], true, [], [], []); }); teardown(() => { model = null; }); // Breakpoints test('breakpoints simple', () => { var modelUri = uri.file('/myfolder/myfile.js'); model.addBreakpoints([{ uri: modelUri, lineNumber: 5, enabled: true }, { uri: modelUri, lineNumber: 10, enabled: false }]); assert.equal(model.areBreakpointsActivated(), true); assert.equal(model.getBreakpoints().length, 2); model.removeBreakpoints(model.getBreakpoints()); assert.equal(model.getBreakpoints().length, 0); }); test('breakpoints toggling', () => { var modelUri = uri.file('/myfolder/myfile.js'); model.addBreakpoints([{ uri: modelUri, lineNumber: 5, enabled: true }, { uri: modelUri, lineNumber: 10, enabled: false }]); model.addBreakpoints([{ uri: modelUri, lineNumber: 12, enabled: true, condition: 'fake condition'}]); assert.equal(model.getBreakpoints().length, 3); model.removeBreakpoints([model.getBreakpoints().pop()]); assert.equal(model.getBreakpoints().length, 2); model.setBreakpointsActivated(false); assert.equal(model.areBreakpointsActivated(), false); model.setBreakpointsActivated(true); assert.equal(model.areBreakpointsActivated(), true); }); test('breakpoints two files', () => { var modelUri1 = uri.file('/myfolder/my file first.js'); var modelUri2 = uri.file('/secondfolder/second/second file.js') model.addBreakpoints([{ uri: modelUri1, lineNumber: 5, enabled: true }, { uri: modelUri1, lineNumber: 10, enabled: false }]); model.addBreakpoints([{ uri: modelUri2, lineNumber: 1, enabled: true }, { uri: modelUri2, lineNumber: 2, enabled: true }, { uri: modelUri2, lineNumber: 3, enabled: false }]); assert.equal(model.getBreakpoints().length, 5); var bp = model.getBreakpoints()[0]; var originalLineLumber = bp.lineNumber; const update:any = {}; update[bp.getId()] = { line: 100, verified: false }; model.updateBreakpoints(update); assert.equal(bp.lineNumber, 100); assert.equal(bp.desiredLineNumber, originalLineLumber); model.enableOrDisableAllBreakpoints(false); model.getBreakpoints().forEach(bp => { assert.equal(bp.enabled, false); }); model.setEnablement(bp, true); assert.equal(bp.enabled, true); model.removeBreakpoints(model.getBreakpoints().filter(bp => bp.source.uri.toString() === modelUri1.toString())); assert.equal(model.getBreakpoints().length, 3); }); // Threads test('threads simple', () => { var threadId = 1; var threadName = "firstThread"; model.rawUpdate({ threadId: threadId, thread: { id: threadId, name: threadName } }); var threads = model.getThreads(); assert.equal(threads[threadId].name, threadName); model.clearThreads(true); assert.equal(model.getThreads[threadId], null); }); test('threads multiple wtih allThreadsStopped', () => { const mockDebugService = new MockDebugService(); const sessionStub = sinon.spy(mockDebugService.getActiveSession(), 'stackTrace'); const threadId1 = 1; const threadName1 = "firstThread"; const threadId2 = 2; const threadName2 = "secondThread"; const stoppedReason = "breakpoint"; // Add the threads model.rawUpdate({ threadId: threadId1, thread: { id: threadId1, name: threadName1 } }); model.rawUpdate({ threadId: threadId2, thread: { id: threadId2, name: threadName2 } }); // Stopped event with all threads stopped model.rawUpdate({ threadId: threadId1, stoppedDetails: { reason: stoppedReason, threadId: 1 }, allThreadsStopped: true }); const thread1 = model.getThreads()[threadId1]; const thread2 = model.getThreads()[threadId2]; // at the beginning, callstacks are obtainable but not available assert.equal(thread1.name, threadName1); assert.equal(thread1.stopped, true); assert.equal(thread1.getCachedCallStack(), undefined); assert.equal(thread1.stoppedDetails.reason, stoppedReason); assert.equal(thread2.name, threadName2); assert.equal(thread2.stopped, true); assert.equal(thread2.getCachedCallStack(), undefined); assert.equal(thread2.stoppedDetails.reason, stoppedReason); // after calling getCallStack, the callstack becomes available // and results in a request for the callstack in the debug adapter thread1.getCallStack(mockDebugService).then(() => { assert.notEqual(thread1.getCachedCallStack(), undefined); assert.equal(thread2.getCachedCallStack(), undefined); assert.equal(sessionStub.callCount, 1); }); thread2.getCallStack(mockDebugService).then(() => { assert.notEqual(thread1.getCachedCallStack(), undefined); assert.notEqual(thread2.getCachedCallStack(), undefined); assert.equal(sessionStub.callCount, 2); }); // calling multiple times getCallStack doesn't result in multiple calls // to the debug adapter thread1.getCallStack(mockDebugService).then(() => { return thread2.getCallStack(mockDebugService); }).then(() => { assert.equal(sessionStub.callCount, 2); }); // clearing the callstack results in the callstack not being available thread1.clearCallStack(); assert.equal(thread1.stopped, true); assert.equal(thread1.getCachedCallStack(), undefined); thread2.clearCallStack(); assert.equal(thread2.stopped, true); assert.equal(thread2.getCachedCallStack(), undefined); model.clearThreads(true); assert.equal(model.getThreads[threadId1], null); assert.equal(model.getThreads[threadId2], null); }); test('threads mutltiple without allThreadsStopped', () => { const mockDebugService = new MockDebugService(); const sessionStub = sinon.spy(mockDebugService.getActiveSession(), 'stackTrace'); const stoppedThreadId = 1; const stoppedThreadName = "stoppedThread"; const runningThreadId = 2; const runningThreadName = "runningThread"; const stoppedReason = "breakpoint"; // Add the threads model.rawUpdate({ threadId: stoppedThreadId, thread: { id: stoppedThreadId, name: stoppedThreadName } }); model.rawUpdate({ threadId: runningThreadId, thread: { id: runningThreadId, name: runningThreadName }<|fim▁hole|> threadId: stoppedThreadId, stoppedDetails: { reason: stoppedReason, threadId: 1 }, allThreadsStopped: false }); const stoppedThread = model.getThreads()[stoppedThreadId]; const runningThread = model.getThreads()[runningThreadId]; // the callstack for the stopped thread is obtainable but not available // the callstack for the running thread is not obtainable nor available assert.equal(stoppedThread.name, stoppedThreadName); assert.equal(stoppedThread.stopped, true); assert.equal(stoppedThread.getCachedCallStack(), undefined); assert.equal(stoppedThread.stoppedDetails.reason, stoppedReason); assert.equal(runningThread.name, runningThreadName); assert.equal(runningThread.stopped, false); assert.equal(runningThread.getCachedCallStack(), undefined); assert.equal(runningThread.stoppedDetails, undefined); // after calling getCallStack, the callstack becomes available // and results in a request for the callstack in the debug adapter stoppedThread.getCallStack(mockDebugService).then(() => { assert.notEqual(stoppedThread.getCachedCallStack(), undefined); assert.equal(runningThread.getCachedCallStack(), undefined); assert.equal(sessionStub.callCount, 1); }); // calling getCallStack on the running thread returns empty array // and does not return in a request for the callstack in the debug // adapter runningThread.getCallStack(mockDebugService).then(callStack => { assert.deepEqual(callStack, []); assert.equal(sessionStub.callCount, 1); }); // calling multiple times getCallStack doesn't result in multiple calls // to the debug adapter stoppedThread.getCallStack(mockDebugService).then(() => { assert.equal(sessionStub.callCount, 1); }); // clearing the callstack results in the callstack not being available stoppedThread.clearCallStack(); assert.equal(stoppedThread.stopped, true); assert.equal(stoppedThread.getCachedCallStack(), undefined); model.clearThreads(true); assert.equal(model.getThreads[stoppedThreadId], null); assert.equal(model.getThreads[runningThreadId], null); }); // Expressions function assertWatchExpressions(watchExpressions: debugmodel.Expression[], expectedName: string) { assert.equal(watchExpressions.length, 2); watchExpressions.forEach(we => { assert.equal(we.available, false); assert.equal(we.reference, 0); assert.equal(we.name, expectedName); }); } test('watch expressions', () => { assert.equal(model.getWatchExpressions().length, 0); const stackFrame = new debugmodel.StackFrame(1, 1, null, 'app.js', 1, 1); model.addWatchExpression(null, stackFrame, 'console').done(); model.addWatchExpression(null, stackFrame, 'console').done(); const watchExpressions = model.getWatchExpressions(); assertWatchExpressions(watchExpressions, 'console'); model.renameWatchExpression(null, stackFrame, watchExpressions[0].getId(), 'new_name').done(); model.renameWatchExpression(null, stackFrame, watchExpressions[1].getId(), 'new_name').done(); assertWatchExpressions(model.getWatchExpressions(), 'new_name'); model.clearWatchExpressionValues(); assertWatchExpressions(model.getWatchExpressions(), 'new_name'); model.removeWatchExpressions(); assert.equal(model.getWatchExpressions().length, 0); }); test('repl expressions', () => { assert.equal(model.getReplElements().length, 0); const stackFrame = new debugmodel.StackFrame(1, 1, null, 'app.js', 1, 1); model.addReplExpression(null, stackFrame, 'myVariable').done(); model.addReplExpression(null, stackFrame, 'myVariable').done(); model.addReplExpression(null, stackFrame, 'myVariable').done(); assert.equal(model.getReplElements().length, 3); model.getReplElements().forEach(re => { assert.equal((<debugmodel.Expression> re).available, false); assert.equal((<debugmodel.Expression> re).name, 'myVariable'); assert.equal((<debugmodel.Expression> re).reference, 0); }); model.removeReplExpressions(); assert.equal(model.getReplElements().length, 0); }); // Repl output test('repl output', () => { model.logToRepl('first line', severity.Error); model.logToRepl('second line', severity.Warning); model.logToRepl('second line', severity.Warning); model.logToRepl('second line', severity.Error); let elements = <debugmodel.ValueOutputElement[]> model.getReplElements(); assert.equal(elements.length, 3); assert.equal(elements[0].value, 'first line'); assert.equal(elements[0].counter, 1); assert.equal(elements[0].severity, severity.Error); assert.equal(elements[1].value, 'second line'); assert.equal(elements[1].counter, 2); assert.equal(elements[1].severity, severity.Warning); model.appendReplOutput('1', severity.Error); model.appendReplOutput('2', severity.Error); model.appendReplOutput('3', severity.Error); elements = <debugmodel.ValueOutputElement[]> model.getReplElements(); assert.equal(elements.length, 4); assert.equal(elements[3].value, '123'); assert.equal(elements[3].severity, severity.Error); const keyValueObject = { 'key1' : 2, 'key2': 'value' }; model.logToRepl(keyValueObject); const element = <debugmodel.KeyValueOutputElement> model.getReplElements()[4]; assert.equal(element.value, 'Object'); assert.deepEqual(element.valueObj, keyValueObject); model.removeReplExpressions(); assert.equal(model.getReplElements().length, 0); }); // Utils test('full expression name', () => { const type = 'node'; assert.equal(debugmodel.getFullExpressionName(new debugmodel.Expression(null, false), type), null); assert.equal(debugmodel.getFullExpressionName(new debugmodel.Expression('son', false), type), 'son'); const scope = new debugmodel.Scope(1, 'myscope', 1, false, 1, 0); const son = new debugmodel.Variable(new debugmodel.Variable(new debugmodel.Variable(scope, 0, 'grandfather', '75', 1, 0), 0, 'father', '45', 1, 0), 0, 'son', '20', 1, 0); assert.equal(debugmodel.getFullExpressionName(son, type), 'grandfather.father.son'); const grandson = new debugmodel.Variable(son, 0, '/weird_name', '1', 0, 0); assert.equal(debugmodel.getFullExpressionName(grandson, type), 'grandfather.father.son[\'/weird_name\']'); }); });<|fim▁end|>
}); // Stopped event with only one thread stopped model.rawUpdate({
<|file_name|>run.py<|end_file_name|><|fim▁begin|><|fim▁hole|>import sys,os sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../util') from settings import SettingManager def main(): conf = SettingManager() instance = Scraping4blog(conf) instance.run() if __name__ == "__main__": main()<|fim▁end|>
# -*- coding: utf-8 -*- from Scraping4blog import Scraping4blog
<|file_name|>service_check.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """ 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<|fim▁hole|>from resource_management import * import subprocess class TachyonServiceCheck(Script): # Service check for VSFTPD service def service_check(self, env): import params env.set_params(params) target_host = format("{tachyon_master}") print ('Service check host is: ' + target_host) full_command = [ "ssh", target_host, params.base_dir + "/bin/tachyon", "runTest", "Basic", "STORE", "SYNC_PERSIST" ] proc = subprocess.Popen(full_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = proc.communicate() response = stdout if 'Failed' in response: raise ComponentIsNotRunning() if __name__ == "__main__": TachyonServiceCheck().execute()<|fim▁end|>
limitations under the License. """
<|file_name|>application.js<|end_file_name|><|fim▁begin|>(function(config, models, views, routers, utils, templates) { // This is the top-level piece of UI. views.Application = Backbone.View.extend({ // Events // ------ events: { 'click .toggle-view': 'toggleView' }, toggleView: function (e) { e.preventDefault(); e.stopPropagation(); var link = $(e.currentTarget), route = link.attr('href').replace(/^\//, ''); $('.toggle-view.active').removeClass('active'); link.addClass('active'); router.navigate(route, true); }, // Initialize // ---------- initialize: function () { _.bindAll(this); var that = this; this.header = new views.Header({model: this.model}); // No longer needed // $(window).on('scroll', function() { // if ($(window).scrollTop()>60) { // $('#post').addClass('sticky-menu'); // } else { // $('#post').removeClass('sticky-menu'); // } // }); function calculateLayout() { if (that.mainView && that.mainView.refreshCodeMirror) { that.mainView.refreshCodeMirror(); } } var lazyLayout = _.debounce(calculateLayout, 300); $(window).resize(lazyLayout); }, // Should be rendered just once render: function () { $(this.header.render().el).prependTo(this.el); return this; }, // Helpers // ------- replaceMainView: function (name, view) { $('body').removeClass().addClass('current-view '+name); // Make sure the header gets shown if (name !== "start") $('#header').show(); if (this.mainView) { this.mainView.remove(); } else { $('#main').empty(); } this.mainView = view; $(view.el).appendTo(this.$('#main')); }, // Main Views // ---------- static: function() { this.header.render(); // No-op ;-) }, posts: function (user, repo, branch, path) { this.loading('Loading posts ...'); loadPosts(user, repo, branch, path, _.bind(function (err, data) { this.loaded(); if (err) return this.notify('error', 'The requested resource could not be found.'); this.header.render(); this.replaceMainView("posts", new views.Posts({ model: data, id: 'posts' }).render()); }, this)); }, post: function (user, repo, branch, path, file, mode) { this.loading('Loading post ...'); loadPosts(user, repo, branch, path, _.bind(function (err, data) { if (err) return this.notify('error', 'The requested resource could not be found.'); loadPost(user, repo, branch, path, file, _.bind(function (err, data) { this.loaded(); this.header.render(); if (err) return this.notify('error', 'The requested resource could not be found.'); data.preview = !(mode === "edit") || !window.authenticated; data.lang = _.mode(file); this.replaceMainView(window.authenticated ? "post" : "read-post", new views.Post({ model: data, id: 'post' }).render());<|fim▁hole|> }, this)); this.header.render(); }, this)); }, newPost: function (user, repo, branch, path) { this.loading('Creating file ...'); loadPosts(user, repo, branch, path, _.bind(function (err, data) { emptyPost(user, repo, branch, path, _.bind(function(err, data) { this.loaded(); data.jekyll = _.jekyll(path, data.file); data.preview = false; data.markdown = _.markdown(data.file); this.replaceMainView("post", new views.Post({ model: data, id: 'post' }).render()); this.mainView._makeDirty(); app.state.file = data.file; this.header.render(); }, this)); }, this)); }, profile: function(username) { var that = this; app.state.title = username; this.loading('Loading profile ...'); loadRepos(username, function(err, data) { that.header.render(); that.loaded(); data.authenticated = !!window.authenticated; that.replaceMainView("start", new views.Profile({id: "start", model: data}).render()); }); }, start: function(username) { var that = this; app.state.title = ""; this.header.render(); this.replaceMainView("start", new views.Start({ id: "start", model: _.extend(this.model, { authenticated: !!window.authenticated} ) }).render()); }, notify: function(type, message) { this.header.render(); this.replaceMainView("notification", new views.Notification(type, message).render()); }, loading: function(msg) { $('#main').html('<div class="loading"><span>'+ msg || 'Loading ...' +'</span></div>'); }, loaded: function() { $('#main .loading').remove(); } }); }).apply(this, window.args);<|fim▁end|>
var that = this;
<|file_name|>test_value2D.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import math import random import unittest from measurement_stats import angle from measurement_stats import value from measurement_stats import value2D HALF_SQRT_2 = 0.5 * math.sqrt(2.0) HALF_SQRT_3 = 0.5 * math.sqrt(3.0) <|fim▁hole|> def test_angleBetween(self): p1 = value2D.Point2D( value.ValueUncertainty(2.0, 0.1), value.ValueUncertainty(0.0, 0.1) ) p2 = value2D.Point2D( value.ValueUncertainty(0.0, 0.1), value.ValueUncertainty(2.0, 0.1) ) a = p1.angle_between(p2) self.assertAlmostEquals(a.degrees, 90.0, 1) def test_rotate(self): tests = [ (90.0, 0.0, 1.0), (-90.0, 0.0, -1.0), (180.0, -1.0, 0.0), (-180.0, -1.0, 0.0), (270.0, 0.0, -1.0), (-270.0, 0.0, 1.0), (360.0, 1.0, 0.0), (-360.0, 1.0, 0.0), (45.0, HALF_SQRT_2, HALF_SQRT_2), (-45.0, HALF_SQRT_2, -HALF_SQRT_2), (315.0, HALF_SQRT_2, -HALF_SQRT_2), (-315.0, HALF_SQRT_2, HALF_SQRT_2), (30.0, HALF_SQRT_3, 0.5), (-30.0, HALF_SQRT_3, -0.5), (330.0, HALF_SQRT_3, -0.5), (-330.0, HALF_SQRT_3, 0.5) ] for test in tests: radius = random.uniform(0.001, 1000.0) p = value2D.Point2D( value.ValueUncertainty(radius, 0.25), value.ValueUncertainty(0.0, 0.25) ) p.rotate(angle.Angle(degrees=test[0])) self.assertAlmostEqual(p.x.raw, radius * test[1], 2) self.assertAlmostEqual(p.y.raw, radius * test[2], 2) def test_projection(self): """ :return: """ line_start = value2D.create_point(0, 0) line_end = value2D.create_point(1, 1) point = value2D.create_point(0, 1) result = value2D.closest_point_on_line(point, line_start, line_end) self.assertIsNotNone(result) print('PROJECTION:', result) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestValue2D) unittest.TextTestRunner(verbosity=2).run(suite)<|fim▁end|>
class TestValue2D(unittest.TestCase):
<|file_name|>online.py<|end_file_name|><|fim▁begin|>from typing import ( Dict, Optional, ) import numpy as np from pandas.compat._optional import import_optional_dependency from pandas.core.util.numba_ import ( NUMBA_FUNC_CACHE, get_jit_arguments, ) def generate_online_numba_ewma_func(engine_kwargs: Optional[Dict[str, bool]]): """ Generate a numba jitted groupby ewma function specified by values from engine_kwargs. Parameters ---------- engine_kwargs : dict dictionary of arguments to be passed into numba.jit Returns ------- Numba function """ nopython, nogil, parallel = get_jit_arguments(engine_kwargs) cache_key = (lambda x: x, "online_ewma") if cache_key in NUMBA_FUNC_CACHE: return NUMBA_FUNC_CACHE[cache_key] numba = import_optional_dependency("numba") @numba.jit(nopython=nopython, nogil=nogil, parallel=parallel) def online_ewma( values: np.ndarray, deltas: np.ndarray, minimum_periods: int, old_wt_factor: float, new_wt: float, old_wt: np.ndarray, adjust: bool, ignore_na: bool, ): """ Compute online exponentially weighted mean per column over 2D values. Takes the first observation as is, then computes the subsequent exponentially weighted mean accounting minimum periods. """ result = np.empty(values.shape) weighted_avg = values[0] nobs = (~np.isnan(weighted_avg)).astype(np.int64) result[0] = np.where(nobs >= minimum_periods, weighted_avg, np.nan) for i in range(1, len(values)): cur = values[i] is_observations = ~np.isnan(cur) nobs += is_observations.astype(np.int64) for j in numba.prange(len(cur)): if not np.isnan(weighted_avg[j]): if is_observations[j] or not ignore_na: # note that len(deltas) = len(vals) - 1 and deltas[i] is to be # used in conjunction with vals[i+1] old_wt[j] *= old_wt_factor ** deltas[j - 1] if is_observations[j]: # avoid numerical errors on constant series if weighted_avg[j] != cur[j]: weighted_avg[j] = ( (old_wt[j] * weighted_avg[j]) + (new_wt * cur[j]) ) / (old_wt[j] + new_wt) if adjust: old_wt[j] += new_wt else: old_wt[j] = 1.0 elif is_observations[j]: weighted_avg[j] = cur[j] result[i] = np.where(nobs >= minimum_periods, weighted_avg, np.nan) return result, old_wt return online_ewma class EWMMeanState: def __init__(self, com, adjust, ignore_na, axis, shape): alpha = 1.0 / (1.0 + com) self.axis = axis self.shape = shape self.adjust = adjust self.ignore_na = ignore_na self.new_wt = 1.0 if adjust else alpha self.old_wt_factor = 1.0 - alpha self.old_wt = np.ones(self.shape[self.axis - 1])<|fim▁hole|> def run_ewm(self, weighted_avg, deltas, min_periods, ewm_func): result, old_wt = ewm_func( weighted_avg, deltas, min_periods, self.old_wt_factor, self.new_wt, self.old_wt, self.adjust, self.ignore_na, ) self.old_wt = old_wt self.last_ewm = result[-1] return result def reset(self): self.old_wt = np.ones(self.shape[self.axis - 1]) self.last_ewm = None<|fim▁end|>
self.last_ewm = None
<|file_name|>bootstrap.js<|end_file_name|><|fim▁begin|>/*! * Bootstrap v3.3.6 (http://getbootstrap.com) * Copyright 2011-2015 Twitter, Inc. * Licensed under the MIT license */ if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery') } + function($) { 'use strict'; var version = $.fn.jquery.split(' ')[0].split('.') if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 2)) { throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3') } }(jQuery); /* ======================================================================== * Bootstrap: transition.js v3.3.6 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { WebkitTransition: 'webkitTransitionEnd', MozTransition: 'transitionend', OTransition: 'oTransitionEnd otransitionend', transition: 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } return false // explicit for ie8 ( ._.) } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function(duration) { var called = false var $el = this $(this).one('bsTransitionEnd', function() { called = true }) var callback = function() { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function() { $.support.transition = transitionEnd() if (!$.support.transition) return $.event.special.bsTransitionEnd = { bindType: $.support.transition.end, delegateType: $.support.transition.end, handle: function(e) { if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments) } } }) }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.3.6 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function(el) { $(el).on('click', dismiss, this.close) } Alert.VERSION = '3.3.6' Alert.TRANSITION_DURATION = 150 Alert.prototype.close = function(e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.closest('.alert') } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { // detach from parent, fire event then clean up data $parent.detach().trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one('bsTransitionEnd', removeElement) .emulateTransitionEnd(Alert.TRANSITION_DURATION) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.alert $.fn.alert = Plugin $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function() { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.3.6 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function(element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) this.isLoading = false } Button.VERSION = '3.3.6' Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function(state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state += 'Text' if (data.resetText == null) $el.data('resetText', $el[val]()) // push to event loop to allow forms to submit setTimeout($.proxy(function() { $el[val](data[state] == null ? this.options[state] : data[state]) if (state == 'loadingText') { this.isLoading = true $el.addClass(d).attr(d, d) } else if (this.isLoading) { this.isLoading = false $el.removeClass(d).removeAttr(d) } }, this), 0) } Button.prototype.toggle = function() { var changed = true var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') == 'radio') { if ($input.prop('checked')) changed = false $parent.find('.active').removeClass('active') this.$element.addClass('active') } else if ($input.prop('type') == 'checkbox') { if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false this.$element.toggleClass('active') } $input.prop('checked', this.$element.hasClass('active')) if (changed) $input.trigger('change') } else { this.$element.attr('aria-pressed', !this.$element.hasClass('active')) this.$element.toggleClass('active') } } // BUTTON PLUGIN DEFINITION // ======================== function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } var old = $.fn.button $.fn.button = Plugin $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function() { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document) .on('click.bs.button.data-api', '[data-toggle^="button"]', function(e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') Plugin.call($btn, 'toggle') if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) e.preventDefault() }) .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function(e) { $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type)) }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.3.6 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function(element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = null this.sliding = null this.interval = null this.$active = null this.$items = null this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this)) this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element .on('mouseenter.bs.carousel', $.proxy(this.pause, this)) .on('mouseleave.bs.carousel', $.proxy(this.cycle, this)) } Carousel.VERSION = '3.3.6' Carousel.TRANSITION_DURATION = 600 Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true, keyboard: true } Carousel.prototype.keydown = function(e) { if (/input|textarea/i.test(e.target.tagName)) return switch (e.which) { case 37: this.prev(); break case 39: this.next(); break default: return } e.preventDefault() } Carousel.prototype.cycle = function(e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getItemIndex = function(item) { this.$items = item.parent().children('.item') return this.$items.index(item || this.$active) } Carousel.prototype.getItemForDirection = function(direction, active) { var activeIndex = this.getItemIndex(active) var willWrap = (direction == 'prev' && activeIndex === 0) || (direction == 'next' && activeIndex == (this.$items.length - 1)) if (willWrap && !this.options.wrap) return active var delta = direction == 'prev' ? -1 : 1 var itemIndex = (activeIndex + delta) % this.$items.length return this.$items.eq(itemIndex) } Carousel.prototype.to = function(pos) { var that = this var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active')) if (pos > (this.$items.length - 1) || pos < 0) return <|fim▁hole|> if (this.sliding) return this.$element.one('slid.bs.carousel', function() { that.to(pos) }) // yes, "slid" if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos)) } Carousel.prototype.pause = function(e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function() { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function() { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function(type, next) { var $active = this.$element.find('.item.active') var $next = next || this.getItemForDirection(type, $active) var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var that = this if ($next.hasClass('active')) return (this.sliding = false) var relatedTarget = $next[0] var slideEvent = $.Event('slide.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) this.$element.trigger(slideEvent) if (slideEvent.isDefaultPrevented()) return this.sliding = true isCycling && this.pause() if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)]) $nextIndicator && $nextIndicator.addClass('active') } var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid" if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one('bsTransitionEnd', function() { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function() { that.$element.trigger(slidEvent) }, 0) }) .emulateTransitionEnd(Carousel.TRANSITION_DURATION) } else { $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger(slidEvent) } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } var old = $.fn.carousel $.fn.carousel = Plugin $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function() { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= var clickHandler = function(e) { var href var $this = $(this) var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7 if (!$target.hasClass('carousel')) return var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false Plugin.call($target, options) if (slideIndex) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() } $(document) .on('click.bs.carousel.data-api', '[data-slide]', clickHandler) .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler) $(window).on('load', function() { $('[data-ride="carousel"]').each(function() { var $carousel = $(this) Plugin.call($carousel, $carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.3.6 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function(element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' + '[data-toggle="collapse"][data-target="#' + element.id + '"]') this.transitioning = null if (this.options.parent) { this.$parent = this.getParent() } else { this.addAriaAndCollapsedClass(this.$element, this.$trigger) } if (this.options.toggle) this.toggle() } Collapse.VERSION = '3.3.6' Collapse.TRANSITION_DURATION = 350 Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function() { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function() { if (this.transitioning || this.$element.hasClass('in')) return var activesData var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing') if (actives && actives.length) { activesData = actives.data('bs.collapse') if (activesData && activesData.transitioning) return } var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return if (actives && actives.length) { Plugin.call(actives, 'hide') activesData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing')[dimension](0) .attr('aria-expanded', true) this.$trigger .removeClass('collapsed') .attr('aria-expanded', true) this.transitioning = 1 var complete = function() { this.$element .removeClass('collapsing') .addClass('collapse in')[dimension]('') this.transitioning = 0 this.$element .trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function() { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element[dimension](this.$element[dimension]())[0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse in') .attr('aria-expanded', false) this.$trigger .addClass('collapsed') .attr('aria-expanded', false) this.transitioning = 1 var complete = function() { this.transitioning = 0 this.$element .removeClass('collapsing') .addClass('collapse') .trigger('hidden.bs.collapse') } if (!$.support.transition) return complete.call(this) this.$element[dimension](0) .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION) } Collapse.prototype.toggle = function() { this[this.$element.hasClass('in') ? 'hide' : 'show']() } Collapse.prototype.getParent = function() { return $(this.options.parent) .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]') .each($.proxy(function(i, element) { var $element = $(element) this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element) }, this)) .end() } Collapse.prototype.addAriaAndCollapsedClass = function($element, $trigger) { var isOpen = $element.hasClass('in') $element.attr('aria-expanded', isOpen) $trigger .toggleClass('collapsed', !isOpen) .attr('aria-expanded', isOpen) } function getTargetFromTrigger($trigger) { var href var target = $trigger.attr('data-target') || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7 return $(target) } // COLLAPSE PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.collapse $.fn.collapse = Plugin $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function() { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function(e) { var $this = $(this) if (!$this.attr('data-target')) e.preventDefault() var $target = getTargetFromTrigger($this) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() Plugin.call($target, option) }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.3.6 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle="dropdown"]' var Dropdown = function(element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.VERSION = '3.3.6' function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } function clearMenus(e) { if (e && e.which === 3) return $(backdrop).remove() $(toggle).each(function() { var $this = $(this) var $parent = getParent($this) var relatedTarget = { relatedTarget: this } if (!$parent.hasClass('open')) return if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this.attr('aria-expanded', 'false') $parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget)) }) } Dropdown.prototype.toggle = function(e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $(document.createElement('div')) .addClass('dropdown-backdrop') .insertAfter($(this)) .on('click', clearMenus) } var relatedTarget = { relatedTarget: this } $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this .trigger('focus') .attr('aria-expanded', 'true') $parent .toggleClass('open') .trigger($.Event('shown.bs.dropdown', relatedTarget)) } return false } Dropdown.prototype.keydown = function(e) { if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if (!isActive && e.which != 27 || isActive && e.which == 27) { if (e.which == 27) $parent.find(toggle).trigger('focus') return $this.trigger('click') } var desc = ' li:not(.disabled):visible a' var $items = $parent.find('.dropdown-menu' + desc) if (!$items.length) return var index = $items.index(e.target) if (e.which == 38 && index > 0) index-- // up if (e.which == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items.eq(index).trigger('focus') } // DROPDOWN PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.dropdown') if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.dropdown $.fn.dropdown = Plugin $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function() { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function(e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown) .on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.3.6 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // MODAL CLASS DEFINITION // ====================== var Modal = function(element, options) { this.options = options this.$body = $(document.body) this.$element = $(element) this.$dialog = this.$element.find('.modal-dialog') this.$backdrop = null this.isShown = null this.originalBodyPad = null this.scrollbarWidth = 0 this.ignoreBackdropClick = false if (this.options.remote) { this.$element .find('.modal-content') .load(this.options.remote, $.proxy(function() { this.$element.trigger('loaded.bs.modal') }, this)) } } Modal.VERSION = '3.3.6' Modal.TRANSITION_DURATION = 300 Modal.BACKDROP_TRANSITION_DURATION = 150 Modal.DEFAULTS = { backdrop: true, keyboard: true, show: true } Modal.prototype.toggle = function(_relatedTarget) { return this.isShown ? this.hide() : this.show(_relatedTarget) } Modal.prototype.show = function(_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.checkScrollbar() this.setScrollbar() this.$body.addClass('modal-open') this.escape() this.resize() this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.$dialog.on('mousedown.dismiss.bs.modal', function() { that.$element.one('mouseup.dismiss.bs.modal', function(e) { if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true }) }) this.backdrop(function() { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(that.$body) // don't move modals dom position } that.$element .show() .scrollTop(0) that.adjustDialog() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element.addClass('in') that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$dialog // wait for modal to slide in .one('bsTransitionEnd', function() { that.$element.trigger('focus').trigger(e) }) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : that.$element.trigger('focus').trigger(e) }) } Modal.prototype.hide = function(e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() this.resize() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .off('click.dismiss.bs.modal') .off('mouseup.dismiss.bs.modal') this.$dialog.off('mousedown.dismiss.bs.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one('bsTransitionEnd', $.proxy(this.hideModal, this)) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : this.hideModal() } Modal.prototype.enforceFocus = function() { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function(e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.trigger('focus') } }, this)) } Modal.prototype.escape = function() { if (this.isShown && this.options.keyboard) { this.$element.on('keydown.dismiss.bs.modal', $.proxy(function(e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keydown.dismiss.bs.modal') } } Modal.prototype.resize = function() { if (this.isShown) { $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this)) } else { $(window).off('resize.bs.modal') } } Modal.prototype.hideModal = function() { var that = this this.$element.hide() this.backdrop(function() { that.$body.removeClass('modal-open') that.resetAdjustments() that.resetScrollbar() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function() { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function(callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $(document.createElement('div')) .addClass('modal-backdrop ' + animate) .appendTo(this.$body) this.$element.on('click.dismiss.bs.modal', $.proxy(function(e) { if (this.ignoreBackdropClick) { this.ignoreBackdropClick = false return } if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus() : this.hide() }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one('bsTransitionEnd', callback) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') var callbackRemove = function() { that.removeBackdrop() callback && callback() } $.support.transition && this.$element.hasClass('fade') ? this.$backdrop .one('bsTransitionEnd', callbackRemove) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callbackRemove() } else if (callback) { callback() } } // these following methods are used to handle overflowing modals Modal.prototype.handleUpdate = function() { this.adjustDialog() } Modal.prototype.adjustDialog = function() { var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight this.$element.css({ paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '', paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : '' }) } Modal.prototype.resetAdjustments = function() { this.$element.css({ paddingLeft: '', paddingRight: '' }) } Modal.prototype.checkScrollbar = function() { var fullWindowWidth = window.innerWidth if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8 var documentElementRect = document.documentElement.getBoundingClientRect() fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left) } this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth this.scrollbarWidth = this.measureScrollbar() } Modal.prototype.setScrollbar = function() { var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10) this.originalBodyPad = document.body.style.paddingRight || '' if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth) } Modal.prototype.resetScrollbar = function() { this.$body.css('padding-right', this.originalBodyPad) } Modal.prototype.measureScrollbar = function() { // thx walsh var scrollDiv = document.createElement('div') scrollDiv.className = 'modal-scrollbar-measure' this.$body.append(scrollDiv) var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth this.$body[0].removeChild(scrollDiv) return scrollbarWidth } // MODAL PLUGIN DEFINITION // ======================= function Plugin(option, _relatedTarget) { return this.each(function() { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } var old = $.fn.modal $.fn.modal = Plugin $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function() { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function(e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7 var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) if ($this.is('a')) e.preventDefault() $target.one('show.bs.modal', function(showEvent) { if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown $target.one('hidden.bs.modal', function() { $this.is(':visible') && $this.trigger('focus') }) }) Plugin.call($target, option, this) }) }(jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.3.6 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function(element, options) { this.type = null this.options = null this.enabled = null this.timeout = null this.hoverState = null this.$element = null this.inState = null this.init('tooltip', element, options) } Tooltip.VERSION = '3.3.6' Tooltip.TRANSITION_DURATION = 150 Tooltip.DEFAULTS = { animation: true, placement: 'top', selector: false, template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: 'hover focus', title: '', delay: 0, html: false, container: false, viewport: { selector: 'body', padding: 0 } } Tooltip.prototype.init = function(type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport)) this.inState = { click: false, hover: false, focus: false } if (this.$element[0] instanceof document.constructor && !this.options.selector) { throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!') } var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin' var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function() { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function(options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay, hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function() { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function(key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function(obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } if (obj instanceof $.Event) { self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true } if (self.tip().hasClass('in') || self.hoverState == 'in') { self.hoverState = 'in' return } clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function() { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.isInStateTrue = function() { for (var key in this.inState) { if (this.inState[key]) return true } return false } Tooltip.prototype.leave = function(obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } if (obj instanceof $.Event) { self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false } if (self.isInStateTrue()) return clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function() { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function() { var e = $.Event('show.bs.' + this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0]) if (e.isDefaultPrevented() || !inDom) return var that = this var $tip = this.tip() var tipId = this.getUID(this.type) this.setContent() $tip.attr('id', tipId) this.$element.attr('aria-describedby', tipId) if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) .data('bs.' + this.type, this) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) this.$element.trigger('inserted.bs.' + this.type) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var orgPlacement = placement var viewportDim = this.getPosition(this.$viewport) placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' : placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' : placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' : placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) var complete = function() { var prevHoverState = that.hoverState that.$element.trigger('shown.bs.' + that.type) that.hoverState = null if (prevHoverState == 'out') that.leave(that) } $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() } } Tooltip.prototype.applyPlacement = function(offset, placement) { var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top += marginTop offset.left += marginLeft // $.fn.offset doesn't round pixel values // so we use setOffset directly with our own function B-0 $.offset.setOffset($tip[0], $.extend({ using: function(props) { $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) } }, offset), 0) $tip.addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { offset.top = offset.top + height - actualHeight } var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight) if (delta.left) offset.left += delta.left else offset.top += delta.top var isVertical = /top|bottom/.test(placement) var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight' $tip.offset(offset) this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical) } Tooltip.prototype.replaceArrow = function(delta, dimension, isVertical) { this.arrow() .css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%') .css(isVertical ? 'top' : 'left', '') } Tooltip.prototype.setContent = function() { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function(callback) { var that = this var $tip = $(this.$tip) var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() that.$element .removeAttr('aria-describedby') .trigger('hidden.bs.' + that.type) callback && callback() } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && $tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() this.hoverState = null return this } Tooltip.prototype.fixTitle = function() { var $e = this.$element if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function() { return this.getTitle() } Tooltip.prototype.getPosition = function($element) { $element = $element || this.$element var el = $element[0] var isBody = el.tagName == 'BODY' var elRect = el.getBoundingClientRect() if (elRect.width == null) { // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093 elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top }) } var elOffset = isBody ? { top: 0, left: 0 } : $element.offset() var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() } var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null return $.extend({}, elRect, scroll, outerDims, elOffset) } Tooltip.prototype.getCalculatedOffset = function(placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getViewportAdjustedDelta = function(placement, pos, actualWidth, actualHeight) { var delta = { top: 0, left: 0 } if (!this.$viewport) return delta var viewportPadding = this.options.viewport && this.options.viewport.padding || 0 var viewportDimensions = this.getPosition(this.$viewport) if (/right|left/.test(placement)) { var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight if (topEdgeOffset < viewportDimensions.top) { // top overflow delta.top = viewportDimensions.top - topEdgeOffset } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset } } else { var leftEdgeOffset = pos.left - viewportPadding var rightEdgeOffset = pos.left + viewportPadding + actualWidth if (leftEdgeOffset < viewportDimensions.left) { // left overflow delta.left = viewportDimensions.left - leftEdgeOffset } else if (rightEdgeOffset > viewportDimensions.right) { // right overflow delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset } } return delta } Tooltip.prototype.getTitle = function() { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.getUID = function(prefix) { do prefix += ~~(Math.random() * 1000000) while (document.getElementById(prefix)) return prefix } Tooltip.prototype.tip = function() { if (!this.$tip) { this.$tip = $(this.options.template) if (this.$tip.length != 1) { throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!') } } return this.$tip } Tooltip.prototype.arrow = function() { return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')) } Tooltip.prototype.enable = function() { this.enabled = true } Tooltip.prototype.disable = function() { this.enabled = false } Tooltip.prototype.toggleEnabled = function() { this.enabled = !this.enabled } Tooltip.prototype.toggle = function(e) { var self = this if (e) { self = $(e.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(e.currentTarget, this.getDelegateOptions()) $(e.currentTarget).data('bs.' + this.type, self) } } if (e) { self.inState.click = !self.inState.click if (self.isInStateTrue()) self.enter(self) else self.leave(self) } else { self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } } Tooltip.prototype.destroy = function() { var that = this clearTimeout(this.timeout) this.hide(function() { that.$element.off('.' + that.type).removeData('bs.' + that.type) if (that.$tip) { that.$tip.detach() } that.$tip = null that.$arrow = null that.$viewport = null }) } // TOOLTIP PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data && /destroy|hide/.test(option)) return if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tooltip $.fn.tooltip = Plugin $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function() { $.fn.tooltip = old return this } }(jQuery); /* ======================================================================== * Bootstrap: popover.js v3.3.6 * http://getbootstrap.com/javascript/#popovers * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function(element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.VERSION = '3.3.6' Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right', trigger: 'click', content: '', template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function() { return Popover.DEFAULTS } Popover.prototype.setContent = function() { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text' ](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() } Popover.prototype.hasContent = function() { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function() { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function() { return (this.$arrow = this.$arrow || this.tip().find('.arrow')) } // POPOVER PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data && /destroy|hide/.test(option)) return if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.popover $.fn.popover = Plugin $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function() { $.fn.popover = old return this } }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.3.6 * http://getbootstrap.com/javascript/#scrollspy * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { this.$body = $(document.body) this.$scrollElement = $(element).is(document.body) ? $(window) : $(element) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || '') + ' .nav li > a' this.offsets = [] this.targets = [] this.activeTarget = null this.scrollHeight = 0 this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this)) this.refresh() this.process() } ScrollSpy.VERSION = '3.3.6' ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.getScrollHeight = function() { return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight) } ScrollSpy.prototype.refresh = function() { var that = this var offsetMethod = 'offset' var offsetBase = 0 this.offsets = [] this.targets = [] this.scrollHeight = this.getScrollHeight() if (!$.isWindow(this.$scrollElement[0])) { offsetMethod = 'position' offsetBase = this.$scrollElement.scrollTop() } this.$body .find(this.selector) .map(function() { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#./.test(href) && $(href) return ($href && $href.length && $href.is(':visible') && [ [$href[offsetMethod]().top + offsetBase, href] ]) || null }) .sort(function(a, b) { return a[0] - b[0] }) .each(function() { that.offsets.push(this[0]) that.targets.push(this[1]) }) } ScrollSpy.prototype.process = function() { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.getScrollHeight() var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (this.scrollHeight != scrollHeight) { this.refresh() } if (scrollTop >= maxScroll) { return activeTarget != (i = targets[targets.length - 1]) && this.activate(i) } if (activeTarget && scrollTop < offsets[0]) { this.activeTarget = null return this.clear() } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (offsets[i + 1] === undefined || scrollTop < offsets[i + 1]) && this.activate(targets[i]) } } ScrollSpy.prototype.activate = function(target) { this.activeTarget = target this.clear() var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } ScrollSpy.prototype.clear = function() { $(this.selector) .parentsUntil(this.options.target, '.active') .removeClass('active') } // SCROLLSPY PLUGIN DEFINITION // =========================== function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.scrollspy $.fn.scrollspy = Plugin $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function() { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load.bs.scrollspy.data-api', function() { $('[data-spy="scroll"]').each(function() { var $spy = $(this) Plugin.call($spy, $spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.3.6 * http://getbootstrap.com/javascript/#tabs * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // TAB CLASS DEFINITION // ==================== var Tab = function(element) { // jscs:disable requireDollarBeforejQueryAssignment this.element = $(element) // jscs:enable requireDollarBeforejQueryAssignment } Tab.VERSION = '3.3.6' Tab.TRANSITION_DURATION = 150 Tab.prototype.show = function() { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.data('target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } if ($this.parent('li').hasClass('active')) return var $previous = $ul.find('.active:last a') var hideEvent = $.Event('hide.bs.tab', { relatedTarget: $this[0] }) var showEvent = $.Event('show.bs.tab', { relatedTarget: $previous[0] }) $previous.trigger(hideEvent) $this.trigger(showEvent) if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return var $target = $(selector) this.activate($this.closest('li'), $ul) this.activate($target, $target.parent(), function() { $previous.trigger({ type: 'hidden.bs.tab', relatedTarget: $this[0] }) $this.trigger({ type: 'shown.bs.tab', relatedTarget: $previous[0] }) }) } Tab.prototype.activate = function(element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length) function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', false) element .addClass('active') .find('[data-toggle="tab"]') .attr('aria-expanded', true) if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu').length) { element .closest('li.dropdown') .addClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', true) } callback && callback() } $active.length && transition ? $active .one('bsTransitionEnd', next) .emulateTransitionEnd(Tab.TRANSITION_DURATION) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tab $.fn.tab = Plugin $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function() { $.fn.tab = old return this } // TAB DATA-API // ============ var clickHandler = function(e) { e.preventDefault() Plugin.call($(this), 'show') } $(document) .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler) .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler) }(jQuery); /* ======================================================================== * Bootstrap: affix.js v3.3.6 * http://getbootstrap.com/javascript/#affix * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ + function($) { 'use strict'; // AFFIX CLASS DEFINITION // ====================== var Affix = function(element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$target = $(this.options.target) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = null this.unpin = null this.pinnedOffset = null this.checkPosition() } Affix.VERSION = '3.3.6' Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0, target: window } Affix.prototype.getState = function(scrollHeight, height, offsetTop, offsetBottom) { var scrollTop = this.$target.scrollTop() var position = this.$element.offset() var targetHeight = this.$target.height() if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false if (this.affixed == 'bottom') { if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom' return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom' } var initializing = this.affixed == null var colliderTop = initializing ? scrollTop : position.top var colliderHeight = initializing ? targetHeight : height if (offsetTop != null && scrollTop <= offsetTop) return 'top' if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom' return false } Affix.prototype.getPinnedOffset = function() { if (this.pinnedOffset) return this.pinnedOffset this.$element.removeClass(Affix.RESET).addClass('affix') var scrollTop = this.$target.scrollTop() var position = this.$element.offset() return (this.pinnedOffset = position.top - scrollTop) } Affix.prototype.checkPositionWithEventLoop = function() { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function() { if (!this.$element.is(':visible')) return var height = this.$element.height() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom var scrollHeight = Math.max($(document).height(), $(document.body).height()) if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element) if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element) var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom) if (this.affixed != affix) { if (this.unpin != null) this.$element.css('top', '') var affixType = 'affix' + (affix ? '-' + affix : '') var e = $.Event(affixType + '.bs.affix') this.$element.trigger(e) if (e.isDefaultPrevented()) return this.affixed = affix this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null this.$element .removeClass(Affix.RESET) .addClass(affixType) .trigger(affixType.replace('affix', 'affixed') + '.bs.affix') } if (affix == 'bottom') { this.$element.offset({ top: scrollHeight - height - offsetBottom }) } } // AFFIX PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function() { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.affix $.fn.affix = Plugin $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function() { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function() { $('[data-spy="affix"]').each(function() { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom if (data.offsetTop != null) data.offset.top = data.offsetTop Plugin.call($spy, data) }) }) }(jQuery);<|fim▁end|>
<|file_name|>DirectiveToken.java<|end_file_name|><|fim▁begin|>/** * Copyright (c) 2008-2010 Andrey Somov * * 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 org.yaml.snakeyaml.tokens; import java.util.List; import org.yaml.snakeyaml.error.Mark; import org.yaml.snakeyaml.error.YAMLException; /** * @see <a href="http://pyyaml.org/wiki/PyYAML">PyYAML</a> for more information */ public final class DirectiveToken<T> extends Token { private final String name; private final List<T> value; public DirectiveToken(String name, List<T> value, Mark startMark, Mark endMark) { super(startMark, endMark); this.name = name; if (value != null && value.size() != 2) { throw new YAMLException("Two strings must be provided instead of " + String.valueOf(value.size())); } this.value = value; } public String getName() { return this.name; } public List<T> getValue() { return this.value; } @Override protected String getArguments() { if (value != null) { return "name=" + name + ", value=[" + value.get(0) + ", " + value.get(1) + "]"; } else { return "name=" + name;<|fim▁hole|> } @Override public Token.ID getTokenId() { return ID.Directive; } }<|fim▁end|>
}
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from .views import TriggerCRUDL<|fim▁hole|><|fim▁end|>
urlpatterns = TriggerCRUDL().as_urlpatterns()
<|file_name|>profile_solarcell.py<|end_file_name|><|fim▁begin|>''' Open Source Initiative OSI - The MIT License:Licensing Tue, 2006-10-31 04:56 nelson The MIT License Copyright (c) 2009 BK Precision 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. This script talks to the DC load in two ways: 1. Using a DCLoad object (you'd use this method when you write a python application that talks to the DC load. 2. Using the COM interface. This shows how python code uses the COM interface. Other programming environments (e.g., Visual Basic and Visual C++) would use very similar techniques to talk to the DC load via COM. Note that the DCLoad object and the COM server interface functions always return strings. $RCSfile: client.py $ $Revision: 1.0 $ $Date: 2008/05/16 21:02:50 $ $Author: Don Peterson $ ''' import sys, dcload import time try: from win32com.client import Dispatch except: pass err = sys.stderr.write def TalkToLoad(load, port, baudrate):<|fim▁hole|> same interface, so this code works with either. port is the COM port on your PC that is connected to the DC load. baudrate is a supported baud rate of the DC load. ''' def test(cmd, results): if results: print cmd, "failed:" print " ", results exit(1) else: print cmd load.Initialize(port, baudrate) # Open a serial connection print "Time from DC Load =", load.TimeNow() test("Set to remote control", load.SetRemoteControl()) test("Set max current to 1 A", load.SetMaxCurrent(1)) test("Set CC current to 0.0 A", load.SetCCCurrent(0.0)) print "Settings:" print " Mode =", load.GetMode() print " Max voltage =", load.GetMaxVoltage() print " Max current =", load.GetMaxCurrent() print " Max power =", load.GetMaxPower() print " CC current =", load.GetCCCurrent() print " CV voltage =", load.GetCVVoltage() print " CW power =", load.GetCWPower() print " CR resistance =", load.GetCRResistance() print " Load on timer time =", load.GetLoadOnTimer() print " Load on timer state =", load.GetLoadOnTimerState() print " Trigger source =", load.GetTriggerSource() print " Function =", load.GetFunction() print f = open("output.txt", 'w') f.write("V\tA\tW\n") test("Turn on load", load.TurnLoadOn()) i = 0.0 while i < 0.21: test("Set CC current to %f A" % i, load.SetCCCurrent(i)) i += 0.005 time.sleep(0.2) values = load.GetInputValues() for value in values.split("\t"): print " ", value f.write(value.split(" ")[0]) f.write('\t') f.write("\n") f.close() test("Turn off load", load.TurnLoadOff()) test("Set to local control", load.SetLocalControl()) def Usage(): name = sys.argv[0] msg = '''Usage: %(name)s {com|obj} port baudrate Demonstration python script to talk to a B&K DC load either via the COM (component object model) interface or via a DCLoad object (in dcload.py). port is the COM port number on your PC that the load is connected to. baudrate is the baud rate setting of the DC load. ''' % locals() print msg exit(1) def main(): if len(sys.argv) != 4: Usage() access_type = sys.argv[1] port = int(sys.argv[2]) baudrate = int(sys.argv[3]) if access_type == "com": load = Dispatch('BKServers.DCLoad85xx') elif access_type == "obj": load = dcload.DCLoad() else: Usage() TalkToLoad(load, port, baudrate) return 0 main()<|fim▁end|>
'''load is either a COM object or a DCLoad object. They have the
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#! flask/bin/python from os.path import abspath from flask import current_app from flask.ext.script import Manager from flask.ext.assets import ManageAssets from flask.ext.migrate import Migrate, MigrateCommand from bluespot import create_app from bluespot.extensions import db app = create_app(mode='development') manager = Manager(app) manager.add_command('assets', ManageAssets()) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand)<|fim▁hole|>#app.run(host='0.0.0.0',debug = True)<|fim▁end|>
manager.run()
<|file_name|>0014_auto_20170325_1723.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-25 11:53 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('consent', '0013_auto_20170217_1606'), ] <|fim▁hole|> model_name='educationdetail', name='college_passout_year', field=models.CharField(default=2017, max_length=4), preserve_default=False, ), ]<|fim▁end|>
operations = [ migrations.AlterField(
<|file_name|>url_abuse_async.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # # # Copyright (C) 2014 Sascha Rommelfangen, Raphael Vinot # Copyright (C) 2014 CIRCL Computer Incident Response Center Luxembourg (SMILE gie) # from datetime import date import json import redis try: from urllib.parse import quote except ImportError: from urllib import quote from pyfaup.faup import Faup import socket import dns.resolver import re import sys import logging from pypdns import PyPDNS import bgpranking_web import urlquery from pypssl import PyPSSL from pyeupi import PyEUPI import requests from bs4 import BeautifulSoup try: import sphinxapi sphinx = True except: sphinx = False enable_cache = True r_cache = None def _cache_init(host='localhost', port=6334, db=1): global r_cache if enable_cache and r_cache is None: r_cache = redis.Redis(host, port, db=db) def _cache_set(key, value, field=None): _cache_init() if enable_cache: if field is None: r_cache.setex(key, json.dumps(value), 3600) else: r_cache.hset(key, field, json.dumps(value)) r_cache.expire(key, 3600) def _cache_get(key, field=None): _cache_init() if enable_cache: if field is None: value_json = r_cache.get(key) else: value_json = r_cache.hget(key, field) if value_json is not None: return json.loads(value_json) return None def to_bool(s): """ Converts the given string to a boolean. """ return s.lower() in ('1', 'true', 'yes', 'on') def get_submissions(url, day=None): _cache_init() if enable_cache: if day is None: day = date.today().isoformat() else: day = day.isoformat() key = date.today().isoformat() + '_submissions' return r_cache.zscore(key, url) def get_mail_sent(url, day=None): _cache_init() if enable_cache: if day is None: day = date.today().isoformat() else: day = day.isoformat() key = date.today().isoformat() + '_mails' return r_cache.sismember(key, url) def set_mail_sent(url, day=None): _cache_init() if enable_cache: if day is None: day = date.today().isoformat() else: day = day.isoformat() key = date.today().isoformat() + '_mails' return r_cache.sadd(key, url) def is_valid_url(url): cached = _cache_get(url, 'valid') key = date.today().isoformat() + '_submissions' r_cache.zincrby(key, url) if cached is not None: return cached fex = Faup() if url.startswith('hxxp'): url = 'http' + url[4:] elif not url.startswith('http'): url = 'http://' + url logging.debug("Checking validity of URL: " + url) fex.decode(url) scheme = fex.get_scheme() host = fex.get_host() if scheme is None or host is None: reason = "Not a valid http/https URL/URI" return False, url, reason _cache_set(url, (True, url, None), 'valid') return True, url, None def is_ip(host): if ':' in host: try: socket.inet_pton(socket.AF_INET6, host) return True except: pass else: try: socket.inet_aton(host) return True except: pass return False def try_resolve(fex, url): fex.decode(url) host = fex.get_host().lower() if is_ip(host): return True, None try: ipaddr = dns.resolver.query(host, 'A') except Exception: reason = "DNS server problem. Check resolver settings." return False, reason if not ipaddr: reason = "Host " + host + " does not exist." return False, reason return True, None def get_urls(url, depth=1): if depth > 5: print('Too many redirects.') return fex = Faup() def meta_redirect(content): c = content.lower() soup = BeautifulSoup(c, "html.parser") for result in soup.find_all(attrs={'http-equiv': 'refresh'}): if result: out = result["content"].split(";") if len(out) == 2: wait, text = out a, url = text.split('=', 1) return url.strip() return None resolve, reason = try_resolve(fex, url) if not resolve: # FIXME: inform that the domain does not resolve yield url return logging.debug("Making HTTP connection to " + url) headers = {'User-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0'} try: response = requests.get(url, allow_redirects=True, headers=headers, timeout=15, verify=False) except: # That one can fail (DNS for example) # FIXME: inform that the get failed yield url return if response.history is not None: for h in response.history: # Yeld the urls in the order we find them yield h.url yield response.url meta_redir_url = meta_redirect(response.content) if meta_redir_url is not None: depth += 1 if not meta_redir_url.startswith('http'): fex.decode(url) base = '{}://{}'.format(fex.get_scheme(), fex.get_host()) port = fex.get_port() if port is not None: base += ':{}'.format(port) if not meta_redir_url.startswith('/'): # relative redirect. resource_path has the initial '/' if fex.get_resource_path() is not None: base += fex.get_resource_path() if not base.endswith('/'): base += '/' meta_redir_url = base + meta_redir_url for url in get_urls(meta_redir_url, depth): yield url def url_list(url): cached = _cache_get(url, 'list') if cached is not None: return cached list_urls = [] for u in get_urls(url): if u is None or u in list_urls: continue list_urls.append(u) _cache_set(url, list_urls, 'list') return list_urls def dns_resolve(url): cached = _cache_get(url, 'dns') if cached is not None: return cached fex = Faup() fex.decode(url) host = fex.get_host().lower() ipv4 = None ipv6 = None if is_ip(host): if ':' in host: try: socket.inet_pton(socket.AF_INET6, host) ipv6 = [host] except: pass else: try: socket.inet_aton(host) ipv4 = [host] except: pass else: try: ipv4 = [str(ip) for ip in dns.resolver.query(host, 'A')] except: logging.debug("No IPv4 address assigned to: " + host) try: ipv6 = [str(ip) for ip in dns.resolver.query(host, 'AAAA')] except: logging.debug("No IPv6 address assigned to: " + host) _cache_set(url, (ipv4, ipv6), 'dns') return ipv4, ipv6 def phish_query(url, key, query): cached = _cache_get(query, 'phishtank') if cached is not None: return cached postfields = {'url': quote(query), 'format': 'json', 'app_key': key} response = requests.post(url, data=postfields) res = response.json() if res["meta"]["status"] == "success": if res["results"]["in_database"]: _cache_set(query, res["results"]["phish_detail_page"], 'phishtank') return res["results"]["phish_detail_page"] else: # no information pass elif res["meta"]["status"] == 'error': # Inform the user? # errormsg = res["errortext"] pass return None def sphinxsearch(server, port, url, query): if not sphinx: return None cached = _cache_get(query, 'sphinx') if cached is not None: return cached client = sphinxapi.SphinxClient() client.SetServer(server, port) client.SetMatchMode(2) client.SetConnectTimeout(5.0) result = [] res = client.Query(query) if res.get("matches") is not None: for ticket in res["matches"]:<|fim▁hole|> result.append(ticket_link) _cache_set(query, result, 'sphinx') return result def vt_query_url(url, url_up, key, query, upload=True): cached = _cache_get(query, 'vt') if cached is not None: return cached parameters = {"resource": query, "apikey": key} if upload: parameters['scan'] = 1 response = requests.post(url, data=parameters) if response.text is None or len(response.text) == 0: return None res = response.json() msg = res["verbose_msg"] link = res.get("permalink") positives = res.get("positives") total = res.get("total") if positives is not None: _cache_set(query, (msg, link, positives, total), 'vt') return msg, link, positives, total def gsb_query(url, query): cached = _cache_get(query, 'gsb') if cached is not None: return cached param = '1\n' + query response = requests.post(url, data=param) status = response.status_code if status == 200: _cache_set(query, response.text, 'gsb') return response.text def urlquery_query(url, key, query): cached = _cache_get(query, 'urlquery') if cached is not None: return cached try: urlquery.url = url urlquery.key = key response = urlquery.search(query) except: return None if response['_response_']['status'] == 'ok': if response.get('reports') is not None: total_alert_count = 0 for r in response['reports']: total_alert_count += r['urlquery_alert_count'] total_alert_count += r['ids_alert_count'] total_alert_count += r['blacklist_alert_count'] _cache_set(query, total_alert_count, 'urlquery') return total_alert_count else: return None def process_emails(emails, ignorelist, replacelist): to_return = list(set(emails)) for mail in reversed(to_return): for ignorelist_entry in ignorelist: if re.search(ignorelist_entry, mail, re.I): if mail in to_return: to_return.remove(mail) for k, v in list(replacelist.items()): if re.search(k, mail, re.I): if k in to_return: to_return.remove(k) to_return += v return to_return def whois(server, port, domain, ignorelist, replacelist): cached = _cache_get(domain, 'whois') if cached is not None: return cached s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(15) try: s.connect((server, port)) except Exception: print("Connection problems - check WHOIS server") print(("WHOIS request while problem occurred: ", domain)) print(("WHOIS server: {}:{}".format(server, port))) sys.exit(0) if domain.startswith('http'): fex = Faup() fex.decode(domain) d = fex.get_domain().lower() else: d = domain s.send(d + "\r\n") response = '' while True: d = s.recv(4096) response += d if d == '': break s.close() match = re.findall(r'[\w\.-]+@[\w\.-]+', response) emails = process_emails(match, ignorelist, replacelist) if len(emails) == 0: return None list_mail = list(set(emails)) _cache_set(domain, list_mail, 'whois') return list_mail def pdnscircl(url, user, passwd, q): cached = _cache_get(q, 'pdns') if cached is not None: return cached pdns = PyPDNS(url, basic_auth=(user, passwd)) response = pdns.query(q) all_uniq = [] for e in reversed(response): host = e['rrname'].lower() if host in all_uniq: continue else: all_uniq.append(host) response = (len(all_uniq), all_uniq[:5]) _cache_set(q, response, 'pdns') return response def psslcircl(url, user, passwd, q): cached = _cache_get(q, 'pssl') if cached is not None: return cached pssl = PyPSSL(url, basic_auth=(user, passwd)) response = pssl.query(q) if response.get(q) is not None: certinfo = response.get(q) entries = {} for sha1 in certinfo['certificates']: entries[sha1] = [] if certinfo['subjects'].get(sha1): for value in certinfo['subjects'][sha1]['values']: entries[sha1].append(value) _cache_set(q, entries, 'pssl') return entries return None def eupi(url, key, q): cached = _cache_get(q, 'eupi') if cached is not None: return cached eu = PyEUPI(key, url) response = eu.search_url(q) if response.get('results'): r = response.get('results')[0]['tag_label'] _cache_set(q, r, 'eupi') return r eu.post_submission(q) return None def bgpranking(ip): cached = _cache_get(ip, 'bgp') if cached is not None: return cached details = bgpranking_web.ip_lookup(ip, 7) ptrr = details.get('ptrrecord') if details.get('history') is None or len(details.get('history')) == 0: return ptrr, None, None, None, None, None asn = details['history'][0].get('asn') rank_info = bgpranking_web.cached_daily_rank(asn) position, total = bgpranking_web.cached_position(asn) asn_descr = rank_info[1] rank = rank_info[-1] response = (ptrr, asn_descr, asn, int(position), int(total), float(rank)) _cache_set(ip, response, 'bgp') return response def _deserialize_cached(entry): to_return = {} h = r_cache.hgetall(entry) for key, value in list(h.items()): to_return[key] = json.loads(value) return to_return def get_url_data(url): data = _deserialize_cached(url) if data.get('dns') is not None: ipv4, ipv6 = data['dns'] ip_data = {} if ipv4 is not None: for ip in ipv4: ip_data[ip] = _deserialize_cached(ip) if ipv6 is not None: for ip in ipv6: ip_data[ip] = _deserialize_cached(ip) if len(ip_data) > 0: data.update(ip_data) return {url: data} def cached(url): _cache_init() if not enable_cache: return [url] url_data = get_url_data(url) to_return = [url_data] if url_data[url].get('list') is not None: url_redirs = url_data[url]['list'] for u in url_redirs: if u == url: continue to_return.append(get_url_data(u)) return to_return<|fim▁end|>
ticket_id = ticket["id"] ticket_link = url + str(ticket_id)
<|file_name|>Factorial.java<|end_file_name|><|fim▁begin|>package ua.job4j.loop; /** * Class Класс для вычисления факториала заданного числа. * @author vfrundin * @since 05.11.2017 * @version 1.0 */ public class Factorial { /** * Метод должен вычислять факториал поданного на вход числа. * @param n Число для которого нужно определить факториал. * @return result - найденный факториал числа n. */ public int calc(int n) { int result = 1; <|fim▁hole|> for (int i = 1; i <= n; i++) { result *= i; } } return result; } }<|fim▁end|>
if (n != 0) {
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import include, url from django.views.decorators.cache import cache_page as cp<|fim▁hole|>from django.views.generic import TemplateView from rest_framework.routers import DefaultRouter from .views import ReviewViewSet, ReviewView router = DefaultRouter() router.register(r'reviews', ReviewViewSet) urlpatterns = [ url(r'^$', cp(60 * 5)(ReviewView.as_view(template_name='reviews/index_list.html')), name='reviews-index'), url(r'^api/', include(router.urls), name='reviews-api'), url(r'^manual$', cp(60 * 60)(ReviewView.as_view(template_name='reviews/manual.html')), name='reviews-manual'), url(r'^sample$', cp(60 * 5)(ReviewView.as_view(template_name='reviews/sample_list.html')), name='reviews-sample'), url(r'^edit$', TemplateView.as_view(template_name='reviews/edit.html'), name='reviews-edit'), ]<|fim▁end|>
<|file_name|>model.py<|end_file_name|><|fim▁begin|># Copyright 2021 Google LLC. 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. """Covertype Keras WideDeep Classifier. See additional TFX example pipelines, including the Penguin Pipeline Kubeflow GCP example that this pipeline is based upon: https://github.com/tensorflow/tfx/blob/master/tfx/examples. """ import functools import absl import os from typing import List, Text import tensorflow as tf import tensorflow_model_analysis as tfma import tensorflow_transform as tft from tensorflow_transform.tf_metadata import schema_utils import kerastuner from tensorflow_cloud import CloudTuner from tfx.components.trainer.executor import TrainerFnArgs from tfx.components.trainer.fn_args_utils import DataAccessor from tfx.components.tuner.component import TunerFnResult from tfx_bsl.tfxio import dataset_options from models import features from models.keras.constants import ( EPOCHS, TRAIN_BATCH_SIZE, EVAL_BATCH_SIZE, LOCAL_LOG_DIR, ) def _gzip_reader_fn(filenames): """Small utility returning a record reader that can read gzip'ed files.""" return tf.data.TFRecordDataset(filenames, compression_type='GZIP') def _get_serve_tf_examples_fn(model, tf_transform_output): """Returns a function that parses a serialized tf.Example and applies TFT.""" model.tft_layer = tf_transform_output.transform_features_layer() @tf.function def serve_tf_examples_fn(serialized_tf_examples): """Returns the output to be used in the serving signature.""" feature_spec = tf_transform_output.raw_feature_spec() feature_spec.pop(features.LABEL_KEY) parsed_features = tf.io.parse_example(serialized_tf_examples, feature_spec) transformed_features = model.tft_layer(parsed_features) return model(transformed_features) return serve_tf_examples_fn def _input_fn(file_pattern: List[Text], data_accessor: DataAccessor, tf_transform_output: tft.TFTransformOutput, batch_size: int = 200) -> tf.data.Dataset: """Generates features and label for tuning/training. Args: file_pattern: List of paths or patterns of input tfrecord files. data_accessor: DataAccessor for converting input to RecordBatch. tf_transform_output: A TFTransformOutput. batch_size: representing the number of consecutive elements of returned dataset to combine in a single batch. Returns: A dataset that contains (features, indices) tuple where features is a dictionary of Tensors, and indices is a single Tensor of label indices. """ dataset = data_accessor.tf_dataset_factory( file_pattern, dataset_options.TensorFlowDatasetOptions( batch_size=batch_size, label_key=features.transformed_name(features.LABEL_KEY)), tf_transform_output.transformed_metadata.schema) return dataset def _get_hyperparameters() -> kerastuner.HyperParameters: """Returns hyperparameters for building Keras model. This function defines a conditional hyperparameter space and default values that are used to build the model. Args: None. Returns: A kerastuner HyperParameters object. """ hp = kerastuner.HyperParameters() # Defines hyperparameter search space. hp.Float('learning_rate', min_value=1e-4, max_value=1e-2, sampling='log', default=1e-3) hp.Int('n_layers', 1, 2, default=1) # Based on n_layers, search for the optimal number of hidden units in each layer. with hp.conditional_scope('n_layers', 1): hp.Int('n_units_1', min_value=8, max_value=128, step=8, default=8) with hp.conditional_scope('n_layers', 2): hp.Int('n_units_1', min_value=8, max_value=128, step=8, default=8) hp.Int('n_units_2', min_value=8, max_value=128, step=8, default=8) return hp def _build_keras_model(hparams: kerastuner.HyperParameters, tf_transform_output: tft.TFTransformOutput) -> tf.keras.Model: """Creates a Keras WideDeep Classifier model. Args: hparams: Holds HyperParameters for tuning. tf_transform_output: A TFTransformOutput. Returns: A keras Model. """ # Defines deep feature columns and input layers. deep_columns = [ tf.feature_column.numeric_column( key=features.transformed_name(key), shape=()) for key in features.NUMERIC_FEATURE_KEYS ] input_layers = { column.key: tf.keras.layers.Input(name=column.key, shape=(), dtype=tf.float32) for column in deep_columns } # Defines wide feature columns and input layers. categorical_columns = [ tf.feature_column.categorical_column_with_identity( key=features.transformed_name(key), num_buckets=tf_transform_output.num_buckets_for_transformed_feature(features.transformed_name(key)), default_value=0) for key in features.CATEGORICAL_FEATURE_KEYS ] wide_columns = [ tf.feature_column.indicator_column(categorical_column) for categorical_column in categorical_columns ] input_layers.update({ column.categorical_column.key: tf.keras.layers.Input(name=column.categorical_column.key, shape=(), dtype=tf.int32) for column in wide_columns }) # Build Keras model using hparams. deep = tf.keras.layers.DenseFeatures(deep_columns)(input_layers) for n in range(int(hparams.get('n_layers'))): deep = tf.keras.layers.Dense(units=hparams.get('n_units_' + str(n + 1)))(deep) wide = tf.keras.layers.DenseFeatures(wide_columns)(input_layers) output = tf.keras.layers.Dense(features.NUM_CLASSES, activation='softmax')( tf.keras.layers.concatenate([deep, wide])) model = tf.keras.Model(input_layers, output) model.compile( loss='sparse_categorical_crossentropy', optimizer=tf.keras.optimizers.Adam(lr=hparams.get('learning_rate')), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) model.summary(print_fn=absl.logging.info) return model # TFX Tuner will call this function. def tuner_fn(fn_args: TrainerFnArgs) -> TunerFnResult: """Build the tuner using CloudTuner (KerasTuner instance). Args: fn_args: Holds args used to train and tune the model as name/value pairs. See https://www.tensorflow.org/tfx/api_docs/python/tfx/components/trainer/fn_args_utils/FnArgs. Returns: A namedtuple contains the following: - tuner: A BaseTuner that will be used for tuning. - fit_kwargs: Args to pass to tuner's run_trial function for fitting the model , e.g., the training and validation dataset. Required args depend on the above tuner's implementation. """ transform_graph = tft.TFTransformOutput(fn_args.transform_graph_path) # Construct a build_keras_model_fn that just takes hyperparams from get_hyperparameters as input. build_keras_model_fn = functools.partial( _build_keras_model, tf_transform_output=transform_graph) # CloudTuner is a subclass of kerastuner.Tuner which inherits from BaseTuner. tuner = CloudTuner( build_keras_model_fn, project_id=fn_args.custom_config['ai_platform_training_args']['project'], region=fn_args.custom_config['ai_platform_training_args']['region'], max_trials=50, hyperparameters=_get_hyperparameters(), objective=kerastuner.Objective('val_sparse_categorical_accuracy', 'max'), directory=fn_args.working_dir) train_dataset = _input_fn( fn_args.train_files, fn_args.data_accessor, transform_graph, batch_size=TRAIN_BATCH_SIZE)<|fim▁hole|> fn_args.eval_files, fn_args.data_accessor, transform_graph, batch_size=EVAL_BATCH_SIZE) return TunerFnResult( tuner=tuner, fit_kwargs={ 'x': train_dataset, 'validation_data': eval_dataset, 'steps_per_epoch': fn_args.train_steps, 'validation_steps': fn_args.eval_steps }) def _copy_tensorboard_logs(local_path: str, gcs_path: str): """Copies Tensorboard logs from a local dir to a GCS location. After training, batch copy Tensorboard logs locally to a GCS location. This can result in faster pipeline runtimes over streaming logs per batch to GCS that can get bottlenecked when streaming large volumes. Args: local_path: local filesystem directory uri. gcs_path: cloud filesystem directory uri. Returns: None. """ pattern = '{}/*/events.out.tfevents.*'.format(local_path) local_files = tf.io.gfile.glob(pattern) gcs_log_files = [local_file.replace(local_path, gcs_path) for local_file in local_files] for local_file, gcs_file in zip(local_files, gcs_log_files): tf.io.gfile.copy(local_file, gcs_file) # TFX Trainer will call this function. def run_fn(fn_args: TrainerFnArgs): """Train the model based on given args. Args: fn_args: Holds args used to train and tune the model as name/value pairs. See https://www.tensorflow.org/tfx/api_docs/python/tfx/components/trainer/fn_args_utils/FnArgs. """ tf_transform_output = tft.TFTransformOutput(fn_args.transform_output) train_dataset = _input_fn( fn_args.train_files, fn_args.data_accessor, tf_transform_output, TRAIN_BATCH_SIZE) eval_dataset = _input_fn( fn_args.eval_files, fn_args.data_accessor, tf_transform_output, EVAL_BATCH_SIZE) if fn_args.hyperparameters: hparams = kerastuner.HyperParameters.from_config(fn_args.hyperparameters) else: # This is a shown case when hyperparameters is decided and Tuner is removed # from the pipeline. User can also inline the hyperparameters directly in # _build_keras_model. hparams = _get_hyperparameters() absl.logging.info('HyperParameters for training: %s' % hparams.get_config()) # Distribute training over multiple replicas on the same machine. mirrored_strategy = tf.distribute.MirroredStrategy() with mirrored_strategy.scope(): model = _build_keras_model( hparams=hparams, tf_transform_output=tf_transform_output) tensorboard_callback = tf.keras.callbacks.TensorBoard( log_dir=LOCAL_LOG_DIR, update_freq='batch') model.fit( train_dataset, epochs=EPOCHS, steps_per_epoch=fn_args.train_steps, validation_data=eval_dataset, validation_steps=fn_args.eval_steps, verbose=2, callbacks=[tensorboard_callback]) signatures = { 'serving_default': _get_serve_tf_examples_fn(model, tf_transform_output).get_concrete_function( tf.TensorSpec( shape=[None], dtype=tf.string, name='examples')), } model.save(fn_args.serving_model_dir, save_format='tf', signatures=signatures) _copy_tensorboard_logs(LOCAL_LOG_DIR, fn_args.serving_model_dir + '/logs')<|fim▁end|>
eval_dataset = _input_fn(
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "logger.settings") <|fim▁hole|> execute_from_command_line(sys.argv)<|fim▁end|>
from django.core.management import execute_from_command_line
<|file_name|>cli.py<|end_file_name|><|fim▁begin|>#coding=utf-8 """ Command-line interface utilities for Trigger tools. Intended for re-usable pieces of code like user prompts, that don't fit in other utils modules. """ __author__ = 'Jathan McCollum' __maintainer__ = 'Jathan McCollum' __email__ = '[email protected]' __copyright__ = 'Copyright 2006-2012, AOL Inc.' import datetime from fcntl import ioctl import os import pwd from pytz import timezone import struct import sys import termios import time import tty # Exports __all__ = ('yesno', 'get_terminal_width', 'get_terminal_size', 'Whirlygig', 'NullDevice', 'print_severed_head', 'min_sec', 'pretty_time', 'proceed', 'get_user') # Functions def yesno(prompt, default=False, autoyes=False): """ Present a yes-or-no prompt, get input, and return a boolean. The ``default`` argument is ignored if ``autoyes`` is set. :param prompt: Prompt text :param default: Yes if True; No if False :param autoyes: Automatically return True Default behavior (hitting "enter" returns ``False``):: >>> yesno('Blow up the moon?') Blow up the moon? (y/N) False Reversed behavior (hitting "enter" returns ``True``):: >>> yesno('Blow up the moon?', default=True) Blow up the moon? (Y/n) True Automatically return ``True`` with ``autoyes``; no prompt is displayed:: >>> yesno('Blow up the moon?', autoyes=True) True """ if autoyes: return True sys.stdout.write(prompt) if default: sys.stdout.write(' (Y/n) ') else: sys.stdout.write(' (y/N) ') sys.stdout.flush() fd = sys.stdin.fileno() attr = termios.tcgetattr(fd) try: tty.setraw(fd) yn = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSANOW, attr) print '' if yn in ('y', 'Y'): return True elif yn in ('n', 'N'): return False else: return default def proceed(): """Present a proceed prompt. Return ``True`` if Y, else ``False``""" return raw_input('\nDo you wish to proceed? [y/N] ').lower().startswith('y') def get_terminal_width(): """Find and return stdout's terminal width, if applicable.""" try: width = struct.unpack("hhhh", ioctl(1, termios.TIOCGWINSZ, ' '*8))[1] except IOError: width = sys.maxint return width def get_terminal_size(): """Find and return stdouts terminal size as (height, width)""" rows, cols = os.popen('stty size', 'r').read().split() return rows, cols def get_user(): """Return the name of the current user.""" return pwd.getpwuid(os.getuid())[0] def print_severed_head(): """ Prints a demon holding a severed head. Best used when things go wrong, like production-impacting network outages caused by fat-fingered ACL changes. Thanks to Jeff Sullivan for this best error message ever. """ print r""" _( (~\ _ _ / ( \> > \ -/~/ / ~\ :; \ _ > /(~\/ || | | /\ ;\ |l _____ |; ( \/ > > _\\)\)\)/ ;;; `8o __-~ ~\ d| \ // ///(())(__/~;;\ "88p;. -. _\_;.oP (_._/ / (((__ __ \\ \ `>,% (\ (\./)8" ;:' i )))--`.'-- (( ;,8 \ ,;%%%: ./V^^^V' ;. ;. ((\ | /)) .,88 `: ..,,;;;;,-::::::'_::\ ||\ ;[8: ; )| ~-~ |(|(888; ..``'::::8888oooooo. :\`^^^/,,~--._ |88:: | |\ -===- /| \8;; ``:. oo.8888888888:`((( o.ooo8888Oo;:;:' | |_~-___-~_| `-\. ` `o`88888888b` )) 888b88888P""' ; ; ~~~~;~~ "`--_`. b`888888888;(.,"888b888" ..::;-' ; ; ~"-.... b`8888888:::::.`8888. .:;;;'' ; ; `:::. `:::OOO:::::::.`OO' ;;;''<|fim▁hole|> : ; `. "``::::::'' .' ; `. \_ / ; ; +: ~~-- `:' -'; ACL LOADS FAILED `: : .::/ ; ;;+_ :::. :..;;; YOU LOSE ;;;;;;,;;;;;;;;,; """ def pretty_time(t): """ Print a pretty version of timestamp, including timezone info. Expects the incoming datetime object to have proper tzinfo. :param t: A ``datetime.datetime`` object >>> import datetime >>> from pytz import timezone >>> localzone = timezone('US/Eastern') <DstTzInfo 'US/Eastern' EST-1 day, 19:00:00 STD> >>> t = datetime.datetime.now(localzone) >>> print t 2011-07-19 12:40:30.820920-04:00 >>> print pretty_time(t) 09:40 PDT >>> t = datetime.datetime(2011,07,20,04,13,tzinfo=localzone) >>> print t 2011-07-20 04:13:00-05:00 >>> print pretty_time(t) tomorrow 02:13 PDT """ from trigger.conf import settings localzone = timezone(os.environ.get('TZ', settings.BOUNCE_DEFAULT_TZ)) t = t.astimezone(localzone) midnight = datetime.datetime.combine(datetime.datetime.now(), datetime.time(tzinfo=localzone)) midnight += datetime.timedelta(1) if t < midnight: return t.strftime('%H:%M %Z') elif t < midnight + datetime.timedelta(1): return t.strftime('tomorrow %H:%M %Z') elif t < midnight + datetime.timedelta(6): return t.strftime('%A %H:%M %Z') else: return t.strftime('%Y-%m-%d %H:%M %Z') def min_sec(secs): """ Takes an epoch timestamp and returns string of minutes:seconds. :param secs: Timestamp (in seconds) >>> import time >>> start = time.time() # Wait a few seconds >>> finish = time.time() >>> min_sec(finish - start) '0:11' """ secs = int(secs) return '%d:%02d' % (secs / 60, secs % 60) def setup_tty_for_pty(func): """ Sets up tty for raw mode while retaining original tty settings and then starts the reactor to connect to the pty. Upon exiting pty, restores original tty settings. :param func: The callable to run after the tty is ready, such as ``reactor.run`` """ # Preserve original tty settings stdin_fileno = sys.stdin.fileno() old_ttyattr = tty.tcgetattr(stdin_fileno) try: # Enter raw mode on the local tty. tty.setraw(stdin_fileno) raw_ta = tty.tcgetattr(stdin_fileno) raw_ta[tty.LFLAG] |= tty.ISIG raw_ta[tty.OFLAG] |= tty.OPOST | tty.ONLCR # Pass ^C through so we can abort traceroute, etc. raw_ta[tty.CC][tty.VINTR] = '\x18' # ^X is the new ^C # Ctrl-Z is used by a lot of vendors to exit config mode raw_ta[tty.CC][tty.VSUSP] = 0 # disable ^Z tty.tcsetattr(stdin_fileno, tty.TCSANOW, raw_ta) # Execute our callable here func() finally: # Restore original tty settings tty.tcsetattr(stdin_fileno, tty.TCSANOW, old_ttyattr) def update_password_and_reconnect(hostname): """ Prompts the user to update their password and reconnect to the target device :param hostname: Hostname of the device to connect to. """ if yesno('Authentication failed, would you like to update your password?', default=True): from trigger import tacacsrc tacacsrc.update_credentials(hostname) if yesno('\nReconnect to %s?' % hostname, default=True): # Replaces the current process w/ same pid os.execl(sys.executable, sys.executable, *sys.argv) # Classes class NullDevice(object): """ Used to supress output to ``sys.stdout`` (aka ``print``). Example:: >>> from trigger.utils.cli import NullDevice >>> import sys >>> print "1 - this will print to STDOUT" 1 - this will print to STDOUT >>> original_stdout = sys.stdout # keep a reference to STDOUT >>> sys.stdout = NullDevice() # redirect the real STDOUT >>> print "2 - this won't print" >>> >>> sys.stdout = original_stdout # turn STDOUT back on >>> print "3 - this will print to SDTDOUT" 3 - this will print to SDTDOUT """ def write(self, s): pass class Whirlygig(object): """ Prints a whirlygig for use in displaying pending operation in a command-line tool. Guaranteed to make the user feel warm and fuzzy and be 1000% bug-free. :param start_msg: The status message displayed to the user (e.g. "Doing stuff:") :param done_msg: The completion message displayed upon completion (e.g. "Done.") :param max: Integer of the number of whirlygig repetitions to perform Example:: >>> Whirlygig("Doing stuff:", "Done.", 12).run() """ def __init__(self, start_msg="", done_msg="", max=100): self.unbuff = os.fdopen(sys.stdout.fileno(), 'w', 0) self.start_msg = start_msg self.done_msg = done_msg self.max = max self.whirlygig = ['|', '/', '-', '\\'] self.whirl = self.whirlygig[:] self.first = False def do_whirl(self, whirl): if not self.first: self.unbuff.write(self.start_msg + " ") self.first = True self.unbuff.write('\b%s' % whirl.pop(0)) def run(self): """Executes the whirlygig!""" cnt = 1 while cnt <= self.max: try: self.do_whirl(self.whirl) except IndexError: self.whirl = self.whirlygig[:] time.sleep(.1) cnt += 1 print '\b' + self.done_msg<|fim▁end|>
<|file_name|>button.js<|end_file_name|><|fim▁begin|>// Generated by CoffeeScript 1.12.4 (function() { var BaseButtonTask, ButtonTask, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; BaseButtonTask = require('zooniverse-decision-tree/lib/button-task'); ButtonTask = (function(superClass) { extend(ButtonTask, superClass); function ButtonTask() {<|fim▁hole|> return ButtonTask; })(BaseButtonTask); module.exports = ButtonTask; }).call(this);<|fim▁end|>
return ButtonTask.__super__.constructor.apply(this, arguments); } ButtonTask.prototype.choiceTemplate = require('../templates/choice');
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.shortcuts import render_to_response, get_object_or_404 from django.http import Http404 from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.dates import YearArchiveView, MonthArchiveView,\ DateDetailView from .models import Article, Section class ArticleListView(ListView): template = "news/article_list.html" paginate_by = 5 def get_queryset(self): return Article.objects.published() def get_context_data(self, **kwargs): context = super(ArticleListView, self).get_context_data(**kwargs) context['section_list'] = Section.objects.all() return context class ArticleDateDetailView(DateDetailView): date_field = "published" template = "news/article_detail.html" def get_queryset(self): return Article.objects.published() def get_context_data(self, **kwargs): # import ipdb; ipdb.set_trace() context = super(ArticleDateDetailView, self).get_context_data(**kwargs) context['section_list'] = Section.objects.all() return context class ArticleDetailView(DetailView):<|fim▁hole|> queryset = Article.objects.published() template = "news/post_detail.html" def get_context_data(self, **kwargs): context = super(ArticleDetailView, self).get_context_data(**kwargs) context['section_list'] = Section.objects.all() return context class SectionListView(ListView): queryset = Section.objects.all() template = "news/section_list.html" class SectionDetailView(DetailView): queryset = Section.objects.all() template = "news/section_detail.html" class ArticleYearArchiveView(YearArchiveView): queryset = Article.objects.published() date_field = "published" make_object_list = True template = "news/post_archive_year.html" class ArticleMonthArchiveView(MonthArchiveView): queryset = Article.objects.all() date_field = "published" make_object_list = True template = "news/post_archive_month.html"<|fim▁end|>
<|file_name|>Account.java<|end_file_name|><|fim▁begin|>/* * The MIT License (MIT) * * Copyright (c) 2016 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5 * * 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<|fim▁hole|> * */ package burstcoin.faucet.data; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import java.io.Serializable; import java.util.Date; @Entity public class Account implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue private Long id; @Column(nullable = false, unique = true) private String accountId; @Column(nullable = true) private Date lastClaim; protected Account() { } public Account(String accountId, Date lastClaim) { this.accountId = accountId; this.lastClaim = lastClaim; } public Long getId() { return id; } public void setAccountId(String accountId) { this.accountId = accountId; } public void setLastClaim(Date lastClaim) { this.lastClaim = lastClaim; } public String getAccountId() { return accountId; } public Date getLastClaim() { return lastClaim; } }<|fim▁end|>
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<|file_name|>d3d9types.rs<|end_file_name|><|fim▁begin|>// Copyright © 2015, Corey Richardson // Licensed under the MIT License <LICENSE.md> //! Direct3D capabilities include file pub type D3DCOLOR = ::DWORD; #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DVECTOR { pub x: ::c_float, pub y: ::c_float, pub z: ::c_float, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DCOLORVALUE { pub r: ::c_float, pub g: ::c_float, pub b: ::c_float, pub a: ::c_float, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DRECT { pub x1: ::LONG, pub y1: ::LONG, pub x2: ::LONG, pub y2: ::LONG, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DMATRIX { pub m: [[::c_float; 4]; 4], } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DVIEWPORT9 { pub X: ::DWORD, pub Y: ::DWORD, pub Width: ::DWORD, pub Height: ::DWORD, pub MinZ: ::c_float, pub MaxZ: ::c_float, } pub const D3DMAXUSERCLIPPLANES: ::DWORD = 32; pub const D3DCLIPPLANE0: ::DWORD = (1 << 0); pub const D3DCLIPPLANE1: ::DWORD = (1 << 1); pub const D3DCLIPPLANE2: ::DWORD = (1 << 2); pub const D3DCLIPPLANE3: ::DWORD = (1 << 3); pub const D3DCLIPPLANE4: ::DWORD = (1 << 4); pub const D3DCLIPPLANE5: ::DWORD = (1 << 5); pub const D3DCS_LEFT: ::DWORD = 0x00000001; pub const D3DCS_RIGHT: ::DWORD = 0x00000002; pub const D3DCS_TOP: ::DWORD = 0x00000004; pub const D3DCS_BOTTOM: ::DWORD = 0x00000008; pub const D3DCS_FRONT: ::DWORD = 0x00000010; pub const D3DCS_BACK: ::DWORD = 0x00000020; pub const D3DCS_PLANE0: ::DWORD = 0x00000040; pub const D3DCS_PLANE1: ::DWORD = 0x00000080; pub const D3DCS_PLANE2: ::DWORD = 0x00000100; pub const D3DCS_PLANE3: ::DWORD = 0x00000200; pub const D3DCS_PLANE4: ::DWORD = 0x00000400; pub const D3DCS_PLANE5: ::DWORD = 0x00000800; pub const D3DCS_ALL: ::DWORD = D3DCS_LEFT | D3DCS_RIGHT | D3DCS_TOP | D3DCS_BOTTOM | D3DCS_FRONT | D3DCS_BACK | D3DCS_PLANE0 | D3DCS_PLANE1 | D3DCS_PLANE2 | D3DCS_PLANE3 | D3DCS_PLANE4 | D3DCS_PLANE5; #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DCLIPSTATUS9 { pub ClipUnion: ::DWORD, pub ClipIntersection: ::DWORD, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DMATERIAL9 { pub Diffuse: D3DCOLORVALUE, pub Ambient: D3DCOLORVALUE, pub Specular: D3DCOLORVALUE, pub Emissive: D3DCOLORVALUE, pub Power: ::c_float, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DLIGHTTYPE { POINT = 1, SPOT = 2, DIRECTIONAL = 3, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DLIGHT9 { pub Type: D3DLIGHTTYPE, pub Diffuse: D3DCOLORVALUE, pub Specular: D3DCOLORVALUE, pub Ambient: D3DCOLORVALUE, pub Position: D3DVECTOR, pub Direction: D3DVECTOR, pub Range: ::c_float, pub Falloff: ::c_float, pub Attenuation0: ::c_float, pub Attenuation1: ::c_float, pub Attenuation2: ::c_float, pub Theta: ::c_float, pub Phi: ::c_float, } pub const D3DCLEAR_TARGET: ::DWORD = 0; pub const D3DCLEAR_ZBUFFER: ::DWORD = 0; pub const D3DCLEAR_STENCIL: ::DWORD = 0; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DSHADEMODE { FLAT = 1, GOURAUD = 2, PHONG = 3, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DFILLMODE { POINT = 1, WIREFRAME = 2, SOLID = 3, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DBLEND { ZERO = 1, ONE = 2, SRCCOLOR = 3, INVSRCCOLOR = 4, SRCALPHA = 5, INVSRCALPHA = 6, DESTALPHA = 7, INVDESTALPHA = 8, DESTCOLOR = 9, INVDESTCOLOR = 10, SRCALPHASAT = 11, BOTHSRCALPHA = 12, BOTHINVSRCALPHA = 13, BLENDFACTOR = 14, INVBLENDFACTOR = 15, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DBLENDOP { ADD = 1, SUBTRACT = 2, REVSUBTRACT = 3, MIN = 4, MAX = 5, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DTEXTUREADDRESS { WRAP = 1, MIRROR = 2, CLAMP = 3, BORDER = 4, MIRRORONCE = 5, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DCULL { NONE = 1, CW = 2, CCW = 3, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DCMPFUNC { NEVER = 1, LESS = 2, EQUAL = 3, LESSEQUAL = 4, GREATER = 5, NOTEQUAL = 6, GREATEREQUAL = 7, ALWAYS = 8, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DSTENCILOP { KEEP = 1, ZERO = 2, REPLACE = 3, INCRSAT = 4, DECRSAT = 5, INVERT = 6, INCR = 7, DECR = 8, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DFOGMODE { NONE = 0, EXP = 1, EXP2 = 2, LINEAR = 3, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DZBUFFERTYPE { FALSE = 0, TRUE = 1, USEW = 2, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DPRIMITIVETYPE { POINTLIST = 1, LINELIST = 2, LINESTRIP = 3, TRIANGLELIST = 4, TRIANGLESTRIP = 5, TRIANGLEFAN = 6, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DTRANSFORMSTATETYPE { VIEW = 2, PROJECTION = 3, TEXTURE0 = 16, TEXTURE1 = 17, TEXTURE2 = 18, TEXTURE3 = 19, TEXTURE4 = 20, TEXTURE5 = 21, TEXTURE6 = 22, TEXTURE7 = 23, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DRENDERSTATETYPE { ZENABLE = 7, FILLMODE = 8, SHADEMODE = 9, ZWRITEENABLE = 14, ALPHATESTENABLE = 15, LASTPIXEL = 16, SRCBLEND = 19, DESTBLEND = 20, CULLMODE = 22, ZFUNC = 23, ALPHAREF = 24, ALPHAFUNC = 25, DITHERENABLE = 26, ALPHABLENDENABLE = 27, FOGENABLE = 28, SPECULARENABLE = 29, FOGCOLOR = 34, FOGTABLEMODE = 35, FOGSTART = 36, FOGEND = 37, FOGDENSITY = 38, RANGEFOGENABLE = 48, STENCILENABLE = 52, STENCILFAIL = 53, STENCILZFAIL = 54, STENCILPASS = 55, STENCILFUNC = 56, STENCILREF = 57, STENCILMASK = 58, STENCILWRITEMASK = 59, TEXTUREFACTOR = 60, WRAP0 = 128, WRAP1 = 129, WRAP2 = 130, WRAP3 = 131, WRAP4 = 132, WRAP5 = 133, WRAP6 = 134, WRAP7 = 135, CLIPPING = 136, LIGHTING = 137, AMBIENT = 139, FOGVERTEXMODE = 140, COLORVERTEX = 141, LOCALVIEWER = 142, NORMALIZENORMALS = 143, DIFFUSEMATERIALSOURCE = 145, SPECULARMATERIALSOURCE = 146, AMBIENTMATERIALSOURCE = 147, EMISSIVEMATERIALSOURCE = 148, VERTEXBLEND = 151, CLIPPLANEENABLE = 152, POINTSIZE = 154, POINTSIZE_MIN = 155, POINTSPRITEENABLE = 156, POINTSCALEENABLE = 157, POINTSCALE_A = 158, POINTSCALE_B = 159, POINTSCALE_C = 160, MULTISAMPLEANTIALIAS = 161, MULTISAMPLEMASK = 162, PATCHEDGESTYLE = 163, DEBUGMONITORTOKEN = 165, POINTSIZE_MAX = 166, INDEXEDVERTEXBLENDENABLE = 167, COLORWRITEENABLE = 168, TWEENFACTOR = 170, BLENDOP = 171, POSITIONDEGREE = 172, NORMALDEGREE = 173, SCISSORTESTENABLE = 174, SLOPESCALEDEPTHBIAS = 175, ANTIALIASEDLINEENABLE = 176, MINTESSELLATIONLEVEL = 178, MAXTESSELLATIONLEVEL = 179, ADAPTIVETESS_X = 180, ADAPTIVETESS_Y = 181, ADAPTIVETESS_Z = 182, ADAPTIVETESS_W = 183, ENABLEADAPTIVETESSELLATION = 184, TWOSIDEDSTENCILMODE = 185, CCW_STENCILFAIL = 186, CCW_STENCILZFAIL = 187, CCW_STENCILPASS = 188, CCW_STENCILFUNC = 189, COLORWRITEENABLE1 = 190, COLORWRITEENABLE2 = 191, COLORWRITEENABLE3 = 192, BLENDFACTOR = 193, SRGBWRITEENABLE = 194, DEPTHBIAS = 195, WRAP8 = 198, WRAP9 = 199, WRAP10 = 200, WRAP11 = 201, WRAP12 = 202, WRAP13 = 203, WRAP14 = 204, WRAP15 = 205, SEPARATEALPHABLENDENABLE = 206, SRCBLENDALPHA = 207, DESTBLENDALPHA = 208, BLENDOPALPHA = 209, } pub const D3D_MAX_SIMULTANEOUS_RENDERTARGETS: ::DWORD = 4; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DMATERIALCOLORSOURCE { MATERIAL = 0, COLOR1 = 1, COLOR2 = 2, } pub const D3DRENDERSTATE_WRAPBIAS: ::DWORD = 128; pub const D3DWRAP_U: ::DWORD = 0x00000001; pub const D3DWRAP_V: ::DWORD = 0x00000002; pub const D3DWRAP_W: ::DWORD = 0x00000004; pub const D3DWRAPCOORD_0: ::DWORD = 0x00000001; pub const D3DWRAPCOORD_1: ::DWORD = 0x00000002; pub const D3DWRAPCOORD_2: ::DWORD = 0x00000004; pub const D3DWRAPCOORD_3: ::DWORD = 0x00000008; pub const D3DCOLORWRITEENABLE_RED: ::DWORD = 1 << 0; pub const D3DCOLORWRITEENABLE_GREEN: ::DWORD = 1 << 1; pub const D3DCOLORWRITEENABLE_BLUE: ::DWORD = 1 << 2; pub const D3DCOLORWRITEENABLE_ALPHA: ::DWORD = 1 << 3; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DTEXTURESTAGESTATETYPE { COLOROP = 1, COLORARG1 = 2, COLORARG2 = 3, ALPHAOP = 4, ALPHAARG1 = 5, ALPHAARG2 = 6, BUMPENVMAT00 = 7, BUMPENVMAT01 = 8, BUMPENVMAT10 = 9, BUMPENVMAT11 = 10, TEXCOORDINDEX = 11, BUMPENVLSCALE = 22, BUMPENVLOFFSET = 23, TEXTURETRANSFORMFLAGS = 24, COLORARG0 = 26, ALPHAARG0 = 27, RESULTARG = 28, CONSTANT = 32, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DSAMPLERSTATETYPE { ADDRESSU = 1, ADDRESSV = 2, ADDRESSW = 3, BORDERCOLOR = 4, MAGFILTER = 5, MINFILTER = 6, MIPFILTER = 7, MIPMAPLODBIAS = 8, MAXMIPLEVEL = 9, MAXANISOTROPY = 10, SRGBTEXTURE = 11, ELEMENTINDEX = 12, DMAPOFFSET = 13, } pub const D3DDMAPSAMPLER: ::DWORD = 256; pub const D3DVERTEXTEXTURESAMPLER0: ::DWORD = D3DDMAPSAMPLER + 1; pub const D3DVERTEXTEXTURESAMPLER1: ::DWORD = D3DDMAPSAMPLER + 2; pub const D3DVERTEXTEXTURESAMPLER2: ::DWORD = D3DDMAPSAMPLER + 3; pub const D3DVERTEXTEXTURESAMPLER3: ::DWORD = D3DDMAPSAMPLER + 4; pub const D3DTSS_TCI_PASSTHRU: ::DWORD = 0x00000000; pub const D3DTSS_TCI_CAMERASPACENORMAL: ::DWORD = 0x00010000; pub const D3DTSS_TCI_CAMERASPACEPOSITION: ::DWORD = 0x00020000; pub const D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR: ::DWORD = 0x00030000; pub const D3DTSS_TCI_SPHEREMAP: ::DWORD = 0x00040000; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DTEXTUREOP { DISABLE = 1, SELECTARG1 = 2, SELECTARG2 = 3, MODULATE = 4, MODULATE2X = 5, MODULATE4X = 6, ADD = 7, ADDSIGNED = 8, ADDSIGNED2X = 9, SUBTRACT = 10, ADDSMOOTH = 11, BLENDDIFFUSEALPHA = 12, BLENDTEXTUREALPHA = 13, BLENDFACTORALPHA = 14, BLENDTEXTUREALPHAPM = 15, BLENDCURRENTALPHA = 16, PREMODULATE = 17, MODULATEALPHA_ADDCOLOR = 18, MODULATECOLOR_ADDALPHA = 19, MODULATEINVALPHA_ADDCOLOR = 20, MODULATEINVCOLOR_ADDALPHA = 21, BUMPENVMAP = 22, BUMPENVMAPLUMINANCE = 23, DOTPRODUCT3 = 24, MULTIPLYADD = 25, LERP = 26, } pub const D3DTA_SELECTMASK: ::DWORD = 0x0000000f; pub const D3DTA_DIFFUSE: ::DWORD = 0x00000000; pub const D3DTA_CURRENT: ::DWORD = 0x00000001; pub const D3DTA_TEXTURE: ::DWORD = 0x00000002; pub const D3DTA_TFACTOR: ::DWORD = 0x00000003; pub const D3DTA_SPECULAR: ::DWORD = 0x00000004; pub const D3DTA_TEMP: ::DWORD = 0x00000005; pub const D3DTA_CONSTANT: ::DWORD = 0x00000006; pub const D3DTA_COMPLEMENT: ::DWORD = 0x00000010; pub const D3DTA_ALPHAREPLICATE: ::DWORD = 0x00000020; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DTEXTUREFILTERTYPE { NONE = 0, POINT = 1, LINEAR = 2, ANISOTROPIC = 3, PYRAMIDALQUAD = 6, GAUSSIANQUAD = 7, CONVOLUTIONMONO = 8, } pub const D3DPV_DONOTCOPYDATA: ::DWORD = 1 << 0; pub const D3DFVF_RESERVED0: ::DWORD = 0x001; pub const D3DFVF_POSITION_MASK: ::DWORD = 0x400E; pub const D3DFVF_XYZ: ::DWORD = 0x002; pub const D3DFVF_XYZRHW: ::DWORD = 0x004; pub const D3DFVF_XYZB1: ::DWORD = 0x006; pub const D3DFVF_XYZB2: ::DWORD = 0x008; pub const D3DFVF_XYZB3: ::DWORD = 0x00a; pub const D3DFVF_XYZB4: ::DWORD = 0x00c; pub const D3DFVF_XYZB5: ::DWORD = 0x00e; pub const D3DFVF_XYZW: ::DWORD = 0x4002; pub const D3DFVF_NORMAL: ::DWORD = 0x010; pub const D3DFVF_PSIZE: ::DWORD = 0x020; pub const D3DFVF_DIFFUSE: ::DWORD = 0x040; pub const D3DFVF_SPECULAR: ::DWORD = 0x080; pub const D3DFVF_TEXCOUNT_MASK: ::DWORD = 0xf00; pub const D3DFVF_TEXCOUNT_SHIFT: ::DWORD = 8; pub const D3DFVF_TEX0: ::DWORD = 0x000; pub const D3DFVF_TEX1: ::DWORD = 0x100; pub const D3DFVF_TEX2: ::DWORD = 0x200; pub const D3DFVF_TEX3: ::DWORD = 0x300; pub const D3DFVF_TEX4: ::DWORD = 0x400; pub const D3DFVF_TEX5: ::DWORD = 0x500; pub const D3DFVF_TEX6: ::DWORD = 0x600; pub const D3DFVF_TEX7: ::DWORD = 0x700; pub const D3DFVF_TEX8: ::DWORD = 0x800; pub const D3DFVF_LASTBETA_UBYTE4: ::DWORD = 0x1000; pub const D3DFVF_LASTBETA_D3DCOLOR: ::DWORD = 0x8000; pub const D3DFVF_RESERVED2: ::DWORD = 0x6000; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DDECLUSAGE { POSITION = 0, BLENDWEIGHT, BLENDINDICES, NORMAL, PSIZE, TEXCOORD, TANGENT, BINORMAL, TESSFACTOR, POSITIONT, COLOR, FOG, DEPTH, SAMPLE, } pub const MAXD3DDECLUSAGE: D3DDECLUSAGE = D3DDECLUSAGE::SAMPLE; pub const MAXD3DDECLUSAGEINDEX: ::DWORD = 15; pub const MAXD3DDECLLENGTH: ::DWORD = 64; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DDECLMETHOD { DEFAULT = 0, PARTIALU, PARTIALV, CROSSUV, UV, LOOKUP, LOOKUPPRESAMPLED, } pub const MAXD3DDECLMETHOD: D3DDECLMETHOD = D3DDECLMETHOD::LOOKUPPRESAMPLED; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DDECLTYPE { FLOAT1 = 0, FLOAT2 = 1, FLOAT3 = 2, FLOAT4 = 3, D3DCOLOR = 4, UBYTE4 = 5, SHORT2 = 6, SHORT4 = 7, UBYTE4N = 8, SHORT2N = 9, SHORT4N = 10, USHORT2N = 11, USHORT4N = 12, UDEC3 = 13, DEC3N = 14, FLOAT16_2 = 15, FLOAT16_4 = 16, UNUSED = 17, } pub const MAXD3DDECLTYPE: D3DDECLTYPE = D3DDECLTYPE::UNUSED; #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DVERTEXELEMENT9 { pub Stream: ::WORD, pub Offset: ::WORD, pub Type: ::BYTE, pub Method: ::BYTE, pub Usage: ::BYTE, pub UsageIndex: ::BYTE, } pub type LPD3DVERTEXELEMENT9 = *mut D3DVERTEXELEMENT9; pub const D3DDECL_END: D3DVERTEXELEMENT9 = D3DVERTEXELEMENT9 { Stream: 0xFF, Offset: 0, Type: D3DDECLTYPE::UNUSED as ::BYTE, Method: 0, Usage: 0, UsageIndex: 0, }; pub const D3DDP_MAXTEXCOORD: ::DWORD = 8; pub const D3DSTREAMSOURCE_INDEXEDDATA: ::DWORD = 1 << 30; pub const D3DSTREAMSOURCE_INSTANCEDATA: ::DWORD = 2 << 30; pub const D3DSI_OPCODE_MASK: ::DWORD = 0x0000FFFF; pub const D3DSI_INSTLENGTH_MASK: ::DWORD = 0x0F000000; pub const D3DSI_INSTLENGTH_SHIFT: ::DWORD = 24; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DSHADER_INSTRUCTION_OPCODE_TYPE { NOP = 0, MOV, ADD, SUB, MAD, MUL, RCP, RSQ, DP3, DP4, MIN, MAX, SLT, SGE, EXP, LOG, LIT, DST, LRP, FRC, M4x4, M4x3, M3x4, M3x3, M3x2, CALL, CALLNZ, LOOP, RET, ENDLOOP, LABEL, DCL, POW, CRS, SGN, ABS, NRM, SINCOS, REP, ENDREP, IF, IFC, ELSE, ENDIF, BREAK, BREAKC, MOVA, DEFB, DEFI, TEXCOORD = 64, TEXKILL, TEX, TEXBEM, TEXBEML, TEXREG2AR, TEXREG2GB, TEXM3x2PAD, TEXM3x2TEX, TEXM3x3PAD, TEXM3x3TEX, RESERVED0, TEXM3x3SPEC, TEXM3x3VSPEC, EXPP, LOGP, CND, DEF, TEXREG2RGB, TEXDP3TEX, TEXM3x2DEPTH, TEXDP3, TEXM3x3, TEXDEPTH, CMP, BEM, DP2ADD, DSX, DSY, TEXLDD, SETP, TEXLDL, BREAKP, PHASE = 0xFFFD, COMMENT = 0xFFFE, END = 0xFFFF, } pub const D3DSI_COISSUE: ::DWORD = 0x40000000; pub const D3DSP_OPCODESPECIFICCONTROL_MASK: ::DWORD = 0x00ff0000; pub const D3DSP_OPCODESPECIFICCONTROL_SHIFT: ::DWORD = 16; pub const D3DSI_TEXLD_PROJECT: ::DWORD = 0x01 << D3DSP_OPCODESPECIFICCONTROL_SHIFT; pub const D3DSI_TEXLD_BIAS: ::DWORD = 0x02 << D3DSP_OPCODESPECIFICCONTROL_SHIFT; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DSHADER_COMPARISON { RESERVED0 = 0, GT = 1, EQ = 2, GE = 3, LT = 4, NE = 5, LE = 6, RESERVED1 = 7, } pub const D3DSHADER_COMPARISON_SHIFT: ::DWORD = D3DSP_OPCODESPECIFICCONTROL_SHIFT; pub const D3DSHADER_COMPARISON_MASK: ::DWORD = 0x7 << D3DSHADER_COMPARISON_SHIFT; pub const D3DSHADER_INSTRUCTION_PREDICATED: ::DWORD = 0x1 << 28; pub const D3DSP_DCL_USAGE_SHIFT: ::DWORD = 0; pub const D3DSP_DCL_USAGE_MASK: ::DWORD = 0x0000000f; pub const D3DSP_DCL_USAGEINDEX_SHIFT: ::DWORD = 16; pub const D3DSP_DCL_USAGEINDEX_MASK: ::DWORD = 0x000f0000; pub const D3DSP_TEXTURETYPE_SHIFT: ::DWORD = 27; pub const D3DSP_TEXTURETYPE_MASK: ::DWORD = 0x78000000; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DSAMPLER_TEXTURE_TYPE { UNKNOWN = 0 << D3DSP_TEXTURETYPE_SHIFT, _2D = 2 << D3DSP_TEXTURETYPE_SHIFT, CUBE = 3 << D3DSP_TEXTURETYPE_SHIFT, VOLUME = 4 << D3DSP_TEXTURETYPE_SHIFT, } pub const D3DSP_REGNUM_MASK: ::DWORD = 0x000007FF; pub const D3DSP_WRITEMASK_0: ::DWORD = 0x00010000; pub const D3DSP_WRITEMASK_1: ::DWORD = 0x00020000; pub const D3DSP_WRITEMASK_2: ::DWORD = 0x00040000; pub const D3DSP_WRITEMASK_3: ::DWORD = 0x00080000; pub const D3DSP_WRITEMASK_ALL: ::DWORD = 0x000F0000; pub const D3DSP_DSTMOD_SHIFT: ::DWORD = 20; pub const D3DSP_DSTMOD_MASK: ::DWORD = 0x00F00000; pub const D3DSPDM_NONE: ::DWORD = 0 << D3DSP_DSTMOD_SHIFT; pub const D3DSPDM_SATURATE: ::DWORD = 1 << D3DSP_DSTMOD_SHIFT; pub const D3DSPDM_PARTIALPRECISION: ::DWORD = 2 << D3DSP_DSTMOD_SHIFT; pub const D3DSPDM_MSAMPCENTROID: ::DWORD = 4 << D3DSP_DSTMOD_SHIFT; pub const D3DSP_DSTSHIFT_SHIFT: ::DWORD = 24; pub const D3DSP_DSTSHIFT_MASK: ::DWORD = 0x0F000000; pub const D3DSP_REGTYPE_SHIFT: ::DWORD = 28; pub const D3DSP_REGTYPE_SHIFT2: ::DWORD = 8; pub const D3DSP_REGTYPE_MASK: ::DWORD = 0x70000000; pub const D3DSP_REGTYPE_MASK2: ::DWORD = 0x00001800; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DSHADER_PARAM_REGISTER_TYPE { TEMP = 0, INPUT = 1, CONST = 2, ADDR = 3, // D3DSPR_TEXTURE = 3, // Why Rust? RASTOUT = 4, ATTROUT = 5, TEXCRDOUT = 6, // D3DSPR_OUTPUT = 6, // Why are you doing this to me? CONSTINT = 7, COLOROUT = 8, DEPTHOUT = 9, SAMPLER = 10, CONST2 = 11, CONST3 = 12,<|fim▁hole|> LOOP = 15, TEMPFLOAT16 = 16, MISCTYPE = 17, LABEL = 18, PREDICATE = 19, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DSHADER_MISCTYPE_OFFSETS { POSITION = 0, FACE = 1, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DVS_RASTOUT_OFFSETS { POSITION = 0, FOG, POINT_SIZE, } pub const D3DVS_ADDRESSMODE_SHIFT: ::DWORD = 13; pub const D3DVS_ADDRESSMODE_MASK: ::DWORD = 1 << D3DVS_ADDRESSMODE_SHIFT; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DVS_ADDRESSMODE_TYPE { ADDRMODE_ABSOLUTE = 0 << D3DVS_ADDRESSMODE_SHIFT, ADDRMODE_RELATIVE = 1 << D3DVS_ADDRESSMODE_SHIFT, } pub const D3DSHADER_ADDRESSMODE_SHIFT: ::DWORD = 13; pub const D3DSHADER_ADDRESSMODE_MASK: ::DWORD = 1 << D3DSHADER_ADDRESSMODE_SHIFT; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DSHADER_ADDRESSMODE_TYPE { ABSOLUTE = 0 << D3DSHADER_ADDRESSMODE_SHIFT, RELATIVE = 1 << D3DSHADER_ADDRESSMODE_SHIFT, } pub const D3DVS_SWIZZLE_SHIFT: ::DWORD = 16; pub const D3DVS_SWIZZLE_MASK: ::DWORD = 0x00FF0000; pub const D3DVS_X_X: ::DWORD = 0 << D3DVS_SWIZZLE_SHIFT; pub const D3DVS_X_Y: ::DWORD = 1 << D3DVS_SWIZZLE_SHIFT; pub const D3DVS_X_Z: ::DWORD = 2 << D3DVS_SWIZZLE_SHIFT; pub const D3DVS_X_W: ::DWORD = 3 << D3DVS_SWIZZLE_SHIFT; pub const D3DVS_Y_X: ::DWORD = 0 << (D3DVS_SWIZZLE_SHIFT + 2); pub const D3DVS_Y_Y: ::DWORD = 1 << (D3DVS_SWIZZLE_SHIFT + 2); pub const D3DVS_Y_Z: ::DWORD = 2 << (D3DVS_SWIZZLE_SHIFT + 2); pub const D3DVS_Y_W: ::DWORD = 3 << (D3DVS_SWIZZLE_SHIFT + 2); pub const D3DVS_Z_X: ::DWORD = 0 << (D3DVS_SWIZZLE_SHIFT + 4); pub const D3DVS_Z_Y: ::DWORD = 1 << (D3DVS_SWIZZLE_SHIFT + 4); pub const D3DVS_Z_Z: ::DWORD = 2 << (D3DVS_SWIZZLE_SHIFT + 4); pub const D3DVS_Z_W: ::DWORD = 3 << (D3DVS_SWIZZLE_SHIFT + 4); pub const D3DVS_W_X: ::DWORD = 0 << (D3DVS_SWIZZLE_SHIFT + 6); pub const D3DVS_W_Y: ::DWORD = 1 << (D3DVS_SWIZZLE_SHIFT + 6); pub const D3DVS_W_Z: ::DWORD = 2 << (D3DVS_SWIZZLE_SHIFT + 6); pub const D3DVS_W_W: ::DWORD = 3 << (D3DVS_SWIZZLE_SHIFT + 6); pub const D3DVS_NOSWIZZLE: ::DWORD = D3DVS_X_X | D3DVS_Y_Y | D3DVS_Z_Z | D3DVS_W_W; pub const D3DSP_SWIZZLE_SHIFT: ::DWORD = 16; pub const D3DSP_SWIZZLE_MASK: ::DWORD = 0x00FF0000; pub const D3DSP_NOSWIZZLE: ::DWORD = (0 << (D3DSP_SWIZZLE_SHIFT + 0)) | (1 << (D3DSP_SWIZZLE_SHIFT + 2)) | (2 << (D3DSP_SWIZZLE_SHIFT + 4)) | (3 << (D3DSP_SWIZZLE_SHIFT + 6)); pub const D3DSP_REPLICATERED: ::DWORD = (0 << (D3DSP_SWIZZLE_SHIFT + 0)) | (0 << (D3DSP_SWIZZLE_SHIFT + 2)) | (0 << (D3DSP_SWIZZLE_SHIFT + 4)) | (0 << (D3DSP_SWIZZLE_SHIFT + 6)); pub const D3DSP_REPLICATEGREEN: ::DWORD = (1 << (D3DSP_SWIZZLE_SHIFT + 0)) | (1 << (D3DSP_SWIZZLE_SHIFT + 2)) | (1 << (D3DSP_SWIZZLE_SHIFT + 4)) | (1 << (D3DSP_SWIZZLE_SHIFT + 6)); pub const D3DSP_REPLICATEBLUE: ::DWORD = (2 << (D3DSP_SWIZZLE_SHIFT + 0)) | (2 << (D3DSP_SWIZZLE_SHIFT + 2)) | (2 << (D3DSP_SWIZZLE_SHIFT + 4)) | (2 << (D3DSP_SWIZZLE_SHIFT + 6)); pub const D3DSP_REPLICATEALPHA: ::DWORD = (3 << (D3DSP_SWIZZLE_SHIFT + 0)) | (3 << (D3DSP_SWIZZLE_SHIFT + 2)) | (3 << (D3DSP_SWIZZLE_SHIFT + 4)) | (3 << (D3DSP_SWIZZLE_SHIFT + 6)); pub const D3DSP_SRCMOD_SHIFT: ::DWORD = 24; pub const D3DSP_SRCMOD_MASK: ::DWORD = 0x0F000000; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DSHADER_PARAM_SRCMOD_TYPE { NONE = 0 << D3DSP_SRCMOD_SHIFT, NEG = 1 << D3DSP_SRCMOD_SHIFT, BIAS = 2 << D3DSP_SRCMOD_SHIFT, BIASNEG = 3 << D3DSP_SRCMOD_SHIFT, SIGN = 4 << D3DSP_SRCMOD_SHIFT, SIGNNEG = 5 << D3DSP_SRCMOD_SHIFT, COMP = 6 << D3DSP_SRCMOD_SHIFT, X2 = 7 << D3DSP_SRCMOD_SHIFT, X2NEG = 8 << D3DSP_SRCMOD_SHIFT, DZ = 9 << D3DSP_SRCMOD_SHIFT, DW = 10 << D3DSP_SRCMOD_SHIFT, ABS = 11 << D3DSP_SRCMOD_SHIFT, ABSNEG = 12 << D3DSP_SRCMOD_SHIFT, NOT = 13 << D3DSP_SRCMOD_SHIFT, } pub const D3DSP_MIN_PRECISION_SHIFT: ::DWORD = 14; pub const D3DSP_MIN_PRECISION_MASK: ::DWORD = 0x0000C000; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DSHADER_MIN_PRECISION { DEFAULT = 0, _16 = 1, _2_8 = 2, } pub const D3DSI_COMMENTSIZE_SHIFT: ::DWORD = 16; pub const D3DSI_COMMENTSIZE_MASK: ::DWORD = 0x7FFF0000; pub const D3DPS_END: ::DWORD = 0x0000FFFF; pub const D3DVS_END: ::DWORD = 0x0000FFFF; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DBASISTYPE { BEZIER = 0, BSPLINE = 1, CATMULL_ROM = 2, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DDEGREETYPE { LINEAR = 1, QUADRATIC = 2, CUBIC = 3, QUINTIC = 5, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DPATCHEDGESTYLE { DISCRETE = 0, CONTINUOUS = 1, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DSTATEBLOCKTYPE { ALL = 1, PIXELSTATE = 2, VERTEXSTATE = 3, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DVERTEXBLENDFLAGS { DISABLE = 0, _1WEIGHTS = 1, _2WEIGHTS = 2, _3WEIGHTS = 3, _TWEENING = 255, _0WEIGHTS = 256, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DTEXTURETRANSFORMFLAGS { DISABLE = 0, COUNT1 = 1, COUNT2 = 2, COUNT3 = 3, COUNT4 = 4, PROJECTED = 256, } pub const D3DFVF_TEXTUREFORMAT2: ::DWORD = 0; pub const D3DFVF_TEXTUREFORMAT1: ::DWORD = 3; pub const D3DFVF_TEXTUREFORMAT3: ::DWORD = 1; pub const D3DFVF_TEXTUREFORMAT4: ::DWORD = 2; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DDEVTYPE { HAL = 1, REF = 2, SW = 3, NULLREF = 4, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DMULTISAMPLE_TYPE { NONE = 0, NONMASKABLE = 1, _2_SAMPLES = 2, _3_SAMPLES = 3, _4_SAMPLES = 4, _5_SAMPLES = 5, _6_SAMPLES = 6, _7_SAMPLES = 7, _8_SAMPLES = 8, _9_SAMPLES = 9, _10_SAMPLES = 10, _11_SAMPLES = 11, _12_SAMPLES = 12, _13_SAMPLES = 13, _14_SAMPLES = 14, _15_SAMPLES = 15, _16_SAMPLES = 16, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DFORMAT { UNKNOWN = 0, R8G8B8 = 20, A8R8G8B8 = 21, X8R8G8B8 = 22, R5G6B5 = 23, X1R5G5B5 = 24, A1R5G5B5 = 25, A4R4G4B4 = 26, R3G3B2 = 27, A8 = 28, A8R3G3B2 = 29, X4R4G4B4 = 30, A2B10G10R10 = 31, A8B8G8R8 = 32, X8B8G8R8 = 33, G16R16 = 34, A2R10G10B10 = 35, A16B16G16R16 = 36, A8P8 = 40, P8 = 41, L8 = 50, A8L8 = 51, A4L4 = 52, V8U8 = 60, L6V5U5 = 61, X8L8V8U8 = 62, Q8W8V8U8 = 63, V16U16 = 64, A2W10V10U10 = 67, UYVY = MAKEFOURCC!(b'U', b'Y', b'V', b'Y'), R8G8_B8G8 = MAKEFOURCC!(b'R', b'G', b'B', b'G'), YUY2 = MAKEFOURCC!(b'Y', b'U', b'Y', b'2'), G8R8_G8B8 = MAKEFOURCC!(b'G', b'R', b'G', b'B'), DXT1 = MAKEFOURCC!(b'D', b'X', b'T', b'1'), DXT2 = MAKEFOURCC!(b'D', b'X', b'T', b'2'), DXT3 = MAKEFOURCC!(b'D', b'X', b'T', b'3'), DXT4 = MAKEFOURCC!(b'D', b'X', b'T', b'4'), DXT5 = MAKEFOURCC!(b'D', b'X', b'T', b'5'), D16_LOCKABLE = 70, D32 = 71, D15S1 = 73, D24S8 = 75, D24X8 = 77, D24X4S4 = 79, D16 = 80, D32F_LOCKABLE = 82, D24FS8 = 83, D32_LOCKABLE = 84, S8_LOCKABLE = 85, L16 = 81, VERTEXDATA = 100, INDEX16 = 101, INDEX32 = 102, Q16W16V16U16 = 110, MULTI2_ARGB8 = MAKEFOURCC!(b'M', b'E', b'T', b'1'), R16F = 111, G16R16F = 112, A16B16G16R16F = 113, R32F = 114, G32R32F = 115, A32B32G32R32F = 116, CxV8U8 = 117, A1 = 118, A2B10G10R10_XR_BIAS = 119, BINARYBUFFER = 199, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DDISPLAYMODE { pub Width: ::UINT, pub Height: ::UINT, pub RefreshRate: ::UINT, pub Format: D3DFORMAT, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DDEVICE_CREATION_PARAMETERS { pub AdapterOrdinal: ::UINT, pub DeviceType: D3DDEVTYPE, pub hFocusWindow: ::HWND, pub BehaviorFlags: ::DWORD, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DSWAPEFFECT { DISCARD = 1, FLIP = 2, COPY = 3, OVERLAY = 4, FLIPEX = 5, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DPOOL { DEFAULT = 0, MANAGED = 1, SYSTEMMEM = 2, SCRATCH = 3, } pub const D3DPRESENT_RATE_DEFAULT: ::DWORD = 0x00000000; #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DPRESENT_PARAMETERS { pub BackBufferWidth: ::UINT, pub BackBufferHeight: ::UINT, pub BackBufferFormat: D3DFORMAT, pub BackBufferCount: ::UINT, pub MultiSampleType: D3DMULTISAMPLE_TYPE, pub MultiSampleQuality: ::DWORD, pub SwapEffect: D3DSWAPEFFECT, pub hDeviceWindow: ::HWND, pub Windowed: ::BOOL, pub EnableAutoDepthStencil: ::BOOL, pub AutoDepthStencilFormat: D3DFORMAT, pub Flags: ::DWORD, pub FullScreen_RefreshRateInHz: ::UINT, pub PresentationInterval: ::UINT, } pub const D3DPRESENTFLAG_LOCKABLE_BACKBUFFER: ::DWORD = 0x00000001; pub const D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL: ::DWORD = 0x00000002; pub const D3DPRESENTFLAG_DEVICECLIP: ::DWORD = 0x00000004; pub const D3DPRESENTFLAG_VIDEO: ::DWORD = 0x00000010; pub const D3DPRESENTFLAG_NOAUTOROTATE: ::DWORD = 0x00000020; pub const D3DPRESENTFLAG_UNPRUNEDMODE: ::DWORD = 0x00000040; pub const D3DPRESENTFLAG_OVERLAY_LIMITEDRGB: ::DWORD = 0x00000080; pub const D3DPRESENTFLAG_OVERLAY_YCbCr_BT709: ::DWORD = 0x00000100; pub const D3DPRESENTFLAG_OVERLAY_YCbCr_xvYCC: ::DWORD = 0x00000200; pub const D3DPRESENTFLAG_RESTRICTED_CONTENT: ::DWORD = 0x00000400; pub const D3DPRESENTFLAG_RESTRICT_SHARED_RESOURCE_DRIVER: ::DWORD = 0x00000800; #[repr(C)] #[derive(Copy)] pub struct D3DGAMMARAMP { pub red: [::WORD; 256], pub green: [::WORD; 256], pub blue: [::WORD; 256], } impl Clone for D3DGAMMARAMP { fn clone(&self) -> D3DGAMMARAMP { *self } } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DBACKBUFFER_TYPE { TYPE_MONO = 0, TYPE_LEFT = 1, TYPE_RIGHT = 2, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DRESOURCETYPE { SURFACE = 1, VOLUME = 2, TEXTURE = 3, VOLUMETEXTURE = 4, CUBETEXTURE = 5, VERTEXBUFFER = 6, INDEXBUFFER = 7, } pub const D3DUSAGE_RENDERTARGET: ::DWORD = 0x00000001; pub const D3DUSAGE_DEPTHSTENCIL: ::DWORD = 0x00000002; pub const D3DUSAGE_DYNAMIC: ::DWORD = 0x00000200; pub const D3DUSAGE_NONSECURE: ::DWORD = 0x00800000; pub const D3DUSAGE_AUTOGENMIPMAP: ::DWORD = 0x00000400; pub const D3DUSAGE_DMAP: ::DWORD = 0x00004000; pub const D3DUSAGE_QUERY_LEGACYBUMPMAP: ::DWORD = 0x00008000; pub const D3DUSAGE_QUERY_SRGBREAD: ::DWORD = 0x00010000; pub const D3DUSAGE_QUERY_FILTER: ::DWORD = 0x00020000; pub const D3DUSAGE_QUERY_SRGBWRITE: ::DWORD = 0x00040000; pub const D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING: ::DWORD = 0x00080000; pub const D3DUSAGE_QUERY_VERTEXTEXTURE: ::DWORD = 0x00100000; pub const D3DUSAGE_QUERY_WRAPANDMIP : ::DWORD = 0x00200000; pub const D3DUSAGE_WRITEONLY: ::DWORD = 0x00000008; pub const D3DUSAGE_SOFTWAREPROCESSING: ::DWORD = 0x00000010; pub const D3DUSAGE_DONOTCLIP: ::DWORD = 0x00000020; pub const D3DUSAGE_POINTS: ::DWORD = 0x00000040; pub const D3DUSAGE_RTPATCHES: ::DWORD = 0x00000080; pub const D3DUSAGE_NPATCHES: ::DWORD = 0x00000100; pub const D3DUSAGE_TEXTAPI: ::DWORD = 0x10000000; pub const D3DUSAGE_RESTRICTED_CONTENT: ::DWORD = 0x00000800; pub const D3DUSAGE_RESTRICT_SHARED_RESOURCE: ::DWORD = 0x00002000; pub const D3DUSAGE_RESTRICT_SHARED_RESOURCE_DRIVER: ::DWORD = 0x00001000; #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DCUBEMAP_FACES { POSITIVE_X = 0, NEGATIVE_X = 1, POSITIVE_Y = 2, NEGATIVE_Y = 3, POSITIVE_Z = 4, NEGATIVE_Z = 5, } pub const D3DLOCK_READONLY: ::DWORD = 0x00000010; pub const D3DLOCK_DISCARD: ::DWORD = 0x00002000; pub const D3DLOCK_NOOVERWRITE: ::DWORD = 0x00001000; pub const D3DLOCK_NOSYSLOCK: ::DWORD = 0x00000800; pub const D3DLOCK_DONOTWAIT: ::DWORD = 0x00004000; pub const D3DLOCK_NO_DIRTY_UPDATE: ::DWORD = 0x00008000; #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DVERTEXBUFFER_DESC { pub Format: D3DFORMAT, pub Type: D3DRESOURCETYPE, pub Usage: ::DWORD, pub Pool: D3DPOOL, pub Size: ::UINT, pub FVF: ::DWORD, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DINDEXBUFFER_DESC { pub Format: D3DFORMAT, pub Type: D3DRESOURCETYPE, pub Usage: ::DWORD, pub Pool: D3DPOOL, pub Size: ::UINT, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DSURFACE_DESC { pub Format: D3DFORMAT, pub Type: D3DRESOURCETYPE, pub Usage: ::DWORD, pub Pool: D3DPOOL, pub MultiSampleType: D3DMULTISAMPLE_TYPE, pub MultiSampleQuality: ::DWORD, pub Width: ::UINT, pub Height: ::UINT, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DVOLUME_DESC { pub Format: D3DFORMAT, pub Type: D3DRESOURCETYPE, pub Usage: ::DWORD, pub Pool: D3DPOOL, pub Width: ::UINT, pub Height: ::UINT, pub Depth: ::UINT, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DLOCKED_RECT { pub Pitch: ::INT, pub pBits: *mut ::libc::c_void, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DBOX { pub Left: ::UINT, pub Top: ::UINT, pub Right: ::UINT, pub Bottom: ::UINT, pub Front: ::UINT, pub Back: ::UINT, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DLOCKED_BOX { pub RowPitch: ::INT, pub SlicePitch: ::INT, pub pBits: *mut ::libc::c_void, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DRANGE { pub Offset: ::UINT, pub Size: ::UINT, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DRECTPATCH_INFO { pub StartVertexOffsetWidth: ::UINT, pub StartVertexOffsetHeight: ::UINT, pub Width: ::UINT, pub Height: ::UINT, pub Stride: ::UINT, pub Basis: D3DBASISTYPE, pub Degree: D3DDEGREETYPE, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DTRIPATCH_INFO { pub StartVertexOffset: ::UINT, pub NumVertices: ::UINT, pub Basis: D3DBASISTYPE, pub Degree: D3DDEGREETYPE, } pub const MAX_DEVICE_IDENTIFIER_STRING: usize = 512; #[repr(C)] #[derive(Copy)] pub struct D3DADAPTER_IDENTIFIER9 { pub Driver: [::c_char; MAX_DEVICE_IDENTIFIER_STRING], pub Description: [::c_char; MAX_DEVICE_IDENTIFIER_STRING], pub DeviceName: [::c_char; 32], pub DriverVersion: ::LARGE_INTEGER, pub VendorId: ::DWORD, pub DeviceId: ::DWORD, pub SubSysId: ::DWORD, pub Revision: ::DWORD, pub DeviceIdentifier: ::GUID, pub WHQLLevel: ::DWORD, } impl Clone for D3DADAPTER_IDENTIFIER9 { fn clone(&self) -> D3DADAPTER_IDENTIFIER9 { *self } } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DRASTER_STATUS { pub InVBlank: ::BOOL, pub ScanLine: ::UINT, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DDEBUGMONITORTOKENS { ENABLE = 0, DISABLE = 1, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DQUERYTYPE { VCACHE = 4, RESOURCEMANAGER = 5, VERTEXSTATS = 6, EVENT = 8, OCCLUSION = 9, TIMESTAMP = 10, TIMESTAMPDISJOINT = 11, TIMESTAMPFREQ = 12, PIPELINETIMINGS = 13, INTERFACETIMINGS = 14, VERTEXTIMINGS = 15, PIXELTIMINGS = 16, BANDWIDTHTIMINGS = 17, CACHEUTILIZATION = 18, MEMORYPRESSURE = 19, } pub const D3DISSUE_END: ::DWORD = 1 << 0; pub const D3DISSUE_BEGIN: ::DWORD = 1 << 1; pub const D3DGETDATA_FLUSH: ::DWORD = 1 << 0; #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DRESOURCESTATS { pub bThrashing: ::BOOL, pub ApproxBytesDownloaded: ::DWORD, pub NumEvicts: ::DWORD, pub NumVidCreates: ::DWORD, pub LastPri: ::DWORD, pub NumUsed: ::DWORD, pub NumUsedInVidMem: ::DWORD, pub WorkingSet: ::DWORD, pub WorkingSetBytes: ::DWORD, pub TotalManaged: ::DWORD, pub TotalBytes: ::DWORD, } pub const D3DRTYPECOUNT: usize = 8; #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DDEVINFO_RESOURCEMANAGER { pub stats: [D3DRESOURCESTATS; 8 /*D3DRTYPECOUNT, rust bug?*/], } pub type LPD3DDEVINFO_RESOURCEMANAGER = *mut D3DDEVINFO_RESOURCEMANAGER; #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DDEVINFO_D3DVERTEXSTATS { pub NumRenderedTriangles: ::DWORD, pub NumExtraClippingTriangles: ::DWORD, } pub type LPD3DDEVINFO_D3DVERTEXSTATS = *mut D3DDEVINFO_D3DVERTEXSTATS; #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DDEVINFO_VCACHE { pub Pattern: ::DWORD, pub OptMethod: ::DWORD, pub CacheSize: ::DWORD, pub MagicNumber: ::DWORD, } pub type LPD3DDEVINFO_VCACHE = *mut D3DDEVINFO_VCACHE; #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DDEVINFO_D3D9PIPELINETIMINGS { pub VertexProcessingTimePercent: ::FLOAT, pub PixelProcessingTimePercent: ::FLOAT, pub OtherGPUProcessingTimePercent: ::FLOAT, pub GPUIdleTimePercent: ::FLOAT, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DDEVINFO_D3D9INTERFACETIMINGS { pub WaitingForGPUToUseApplicationResourceTimePercent: ::FLOAT, pub WaitingForGPUToAcceptMoreCommandsTimePercent: ::FLOAT, pub WaitingForGPUToStayWithinLatencyTimePercent: ::FLOAT, pub WaitingForGPUExclusiveResourceTimePercent: ::FLOAT, pub WaitingForGPUOtherTimePercent: ::FLOAT, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DDEVINFO_D3D9STAGETIMINGS { pub MemoryProcessingPercent: ::FLOAT, pub ComputationProcessingPercent: ::FLOAT, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DDEVINFO_D3D9BANDWIDTHTIMINGS { pub MaxBandwidthUtilized: ::FLOAT, pub FrontEndUploadMemoryUtilizedPercent: ::FLOAT, pub VertexRateUtilizedPercent: ::FLOAT, pub TriangleSetupRateUtilizedPercent: ::FLOAT, pub FillRateUtilizedPercent: ::FLOAT, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DDEVINFO_D3D9CACHEUTILIZATION { pub TextureCacheHitRate: ::FLOAT, pub PostTransformVertexCacheHitRate: ::FLOAT, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DMEMORYPRESSURE { pub BytesEvictedFromProcess: ::UINT64, pub SizeOfInefficientAllocation: ::UINT64, pub LevelOfEfficiency: ::DWORD, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DCOMPOSERECTSOP { COPY = 1, OR = 2, AND = 3, NEG = 4, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DCOMPOSERECTDESC { pub X: ::USHORT, pub Y: ::USHORT, pub Width: ::USHORT, pub Height: ::USHORT, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DCOMPOSERECTDESTINATION { pub SrcRectIndex: ::USHORT, pub Reserved: ::USHORT, pub X: ::SHORT, pub Y: ::SHORT, } pub const D3DCOMPOSERECTS_MAXNUMRECTS: ::DWORD = 0xFFFF; pub const D3DCONVOLUTIONMONO_MAXWIDTH: ::DWORD = 7; pub const D3DCONVOLUTIONMONO_MAXHEIGHT: ::DWORD = D3DCONVOLUTIONMONO_MAXWIDTH; pub const D3DFMT_A1_SURFACE_MAXWIDTH: ::DWORD = 8192; pub const D3DFMT_A1_SURFACE_MAXHEIGHT: ::DWORD = 2048; #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DPRESENTSTATS { pub PresentCount: ::UINT, pub PresentRefreshCount: ::UINT, pub SyncRefreshCount: ::UINT, pub SyncQPCTime: ::LARGE_INTEGER, pub SyncGPUTime: ::LARGE_INTEGER, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DSCANLINEORDERING { UNKNOWN = 0, PROGRESSIVE = 1, INTERLACED = 2, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DDISPLAYMODEEX { pub Size: ::UINT, pub Width: ::UINT, pub Height: ::UINT, pub RefreshRate: ::UINT, pub Format: D3DFORMAT, pub ScanLineOrdering: D3DSCANLINEORDERING, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DDISPLAYMODEFILTER { pub Size: ::UINT, pub Format: D3DFORMAT, pub ScanLineOrdering: D3DSCANLINEORDERING, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DDISPLAYROTATION { IDENTITY = 1, _90 = 2, _180 = 3, _270 = 4, } pub const D3D9_RESOURCE_PRIORITY_MINIMUM: ::DWORD = 0x28000000; pub const D3D9_RESOURCE_PRIORITY_LOW: ::DWORD = 0x50000000; pub const D3D9_RESOURCE_PRIORITY_NORMAL: ::DWORD = 0x78000000; pub const D3D9_RESOURCE_PRIORITY_HIGH: ::DWORD = 0xa0000000; pub const D3D9_RESOURCE_PRIORITY_MAXIMUM: ::DWORD = 0xc8000000; pub const D3D_OMAC_SIZE: usize = 16; #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3D_OMAC { pub Omac: [::BYTE; D3D_OMAC_SIZE], } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DAUTHENTICATEDCHANNELTYPE { D3D9 = 1, DRIVER_SOFTWARE = 2, DRIVER_HARDWARE = 3, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERY_INPUT { pub QueryType: ::GUID, pub hChannel: ::HANDLE, pub SequenceNumber: ::UINT, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT { pub omac: D3D_OMAC, pub QueryType: ::GUID, pub hChannel: ::HANDLE, pub SequenceNumber: ::UINT, pub ReturnCode: ::HRESULT, } DEFINE_GUID!(D3DAUTHENTICATEDQUERY_PROTECTION, 0xa84eb584, 0xc495, 0x48aa, 0xb9, 0x4d, 0x8b, 0xd2, 0xd6, 0xfb, 0xce, 0x5); #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_PROTECTION_FLAGS { pub Value: ::UINT, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERYPROTECTION_OUTPUT { pub Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, pub ProtectionFlags: D3DAUTHENTICATEDCHANNEL_PROTECTION_FLAGS, } DEFINE_GUID!(D3DAUTHENTICATEDQUERY_CHANNELTYPE, 0xbc1b18a5, 0xb1fb, 0x42ab, 0xbd, 0x94, 0xb5, 0x82, 0x8b, 0x4b, 0xf7, 0xbe); #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERYCHANNELTYPE_OUTPUT { pub Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, pub ChannelType: D3DAUTHENTICATEDCHANNELTYPE, } DEFINE_GUID!(D3DAUTHENTICATEDQUERY_DEVICEHANDLE, 0xec1c539d, 0x8cff, 0x4e2a, 0xbc, 0xc4, 0xf5, 0x69, 0x2f, 0x99, 0xf4, 0x80); #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERYDEVICEHANDLE_OUTPUT { pub Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, pub DeviceHandle: ::HANDLE, } DEFINE_GUID!(D3DAUTHENTICATEDQUERY_CRYPTOSESSION, 0x2634499e, 0xd018, 0x4d74, 0xac, 0x17, 0x7f, 0x72, 0x40, 0x59, 0x52, 0x8d); #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERYCRYPTOSESSION_INPUT { pub Input: D3DAUTHENTICATEDCHANNEL_QUERY_INPUT, pub DXVA2DecodeHandle: ::HANDLE, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERYCRYPTOSESSION_OUTPUT { pub Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, pub DXVA2DecodeHandle: ::HANDLE, pub CryptoSessionHandle: ::HANDLE, pub DeviceHandle: ::HANDLE, } DEFINE_GUID!(D3DAUTHENTICATEDQUERY_RESTRICTEDSHAREDRESOURCEPROCESSCOUNT, 0xdb207b3, 0x9450, 0x46a6, 0x82, 0xde, 0x1b, 0x96, 0xd4, 0x4f, 0x9c, 0xf2); #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERYRESTRICTEDSHAREDRESOURCEPROCESSCOUNT_OUTPUT { pub Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, pub NumRestrictedSharedResourceProcesses: ::UINT, } DEFINE_GUID!(D3DAUTHENTICATEDQUERY_RESTRICTEDSHAREDRESOURCEPROCESS, 0x649bbadb, 0xf0f4, 0x4639, 0xa1, 0x5b, 0x24, 0x39, 0x3f, 0xc3, 0xab, 0xac); #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERYRESTRICTEDSHAREDRESOURCEPROCESS_INPUT { pub Input: D3DAUTHENTICATEDCHANNEL_QUERY_INPUT, pub ProcessIndex: ::UINT, } #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DAUTHENTICATEDCHANNEL_PROCESSIDENTIFIERTYPE { UNKNOWN = 0, DWM = 1, HANDLE = 2, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERYRESTRICTEDSHAREDRESOURCEPROCESS_OUTPUT { pub Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, pub ProcessIndex: ::UINT, pub ProcessIdentifer: D3DAUTHENTICATEDCHANNEL_PROCESSIDENTIFIERTYPE, pub ProcessHandle: ::HANDLE, } DEFINE_GUID!(D3DAUTHENTICATEDQUERY_UNRESTRICTEDPROTECTEDSHAREDRESOURCECOUNT, 0x12f0bd6, 0xe662, 0x4474, 0xbe, 0xfd, 0xaa, 0x53, 0xe5, 0x14, 0x3c, 0x6d); #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERYUNRESTRICTEDPROTECTEDSHAREDRESOURCECOUNT_OUTPUT { pub Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, pub NumUnrestrictedProtectedSharedResources: ::UINT, } DEFINE_GUID!(D3DAUTHENTICATEDQUERY_OUTPUTIDCOUNT, 0x2c042b5e, 0x8c07, 0x46d5, 0xaa, 0xbe, 0x8f, 0x75, 0xcb, 0xad, 0x4c, 0x31); #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERYOUTPUTIDCOUNT_INPUT { pub Input: D3DAUTHENTICATEDCHANNEL_QUERY_INPUT, pub DeviceHandle: ::HANDLE, pub CryptoSessionHandle: ::HANDLE, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERYOUTPUTIDCOUNT_OUTPUT { pub Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, pub DeviceHandle: ::HANDLE, pub CryptoSessionHandle: ::HANDLE, pub NumOutputIDs: ::UINT, } DEFINE_GUID!(D3DAUTHENTICATEDQUERY_OUTPUTID, 0x839ddca3, 0x9b4e, 0x41e4, 0xb0, 0x53, 0x89, 0x2b, 0xd2, 0xa1, 0x1e, 0xe7); #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERYOUTPUTID_INPUT { pub Input: D3DAUTHENTICATEDCHANNEL_QUERY_INPUT, pub DeviceHandle: ::HANDLE, pub CryptoSessionHandle: ::HANDLE, pub OutputIDIndex: ::UINT, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERYOUTPUTID_OUTPUT { pub Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, pub DeviceHandle: ::HANDLE, pub CryptoSessionHandle: ::HANDLE, pub OutputIDIndex: ::UINT, pub OutputID: ::UINT64, } DEFINE_GUID!(D3DAUTHENTICATEDQUERY_ACCESSIBILITYATTRIBUTES, 0x6214d9d2, 0x432c, 0x4abb, 0x9f, 0xce, 0x21, 0x6e, 0xea, 0x26, 0x9e, 0x3b); #[repr(i32)] #[derive(Clone, Copy, Debug)] pub enum D3DBUSTYPE { OTHER = 0x00000000, PCI = 0x00000001, PCIX = 0x00000002, PCIEXPRESS = 0x00000003, AGP = 0x00000004, MODIFIER_INSIDE_OF_CHIPSET = 0x00010000, MODIFIER_TRACKS_ON_MOTHER_BOARD_TO_CHIP = 0x00020000, MODIFIER_TRACKS_ON_MOTHER_BOARD_TO_SOCKET = 0x00030000, MODIFIER_DAUGHTER_BOARD_CONNECTOR = 0x00040000, MODIFIER_DAUGHTER_BOARD_CONNECTOR_INSIDE_OF_NUAE = 0x00050000, MODIFIER_NON_STANDARD = 0x80000000u32 as i32, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERYINFOBUSTYPE_OUTPUT { pub Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, pub BusType: D3DBUSTYPE, pub bAccessibleInContiguousBlocks: ::BOOL, pub bAccessibleInNonContiguousBlocks: ::BOOL, } DEFINE_GUID!(D3DAUTHENTICATEDQUERY_ENCRYPTIONWHENACCESSIBLEGUIDCOUNT, 0xb30f7066, 0x203c, 0x4b07, 0x93, 0xfc, 0xce, 0xaa, 0xfd, 0x61, 0x24, 0x1e); #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERYEVICTIONENCRYPTIONGUIDCOUNT_OUTPUT { pub Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, pub NumEncryptionGuids: ::UINT, } DEFINE_GUID!(D3DAUTHENTICATEDQUERY_ENCRYPTIONWHENACCESSIBLEGUID, 0xf83a5958, 0xe986, 0x4bda, 0xbe, 0xb0, 0x41, 0x1f, 0x6a, 0x7a, 0x1, 0xb7); #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERYEVICTIONENCRYPTIONGUID_INPUT { pub Input: D3DAUTHENTICATEDCHANNEL_QUERY_INPUT, pub EncryptionGuidIndex: ::UINT, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERYEVICTIONENCRYPTIONGUID_OUTPUT { pub Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, pub EncryptionGuidIndex: ::UINT, pub EncryptionGuid: ::GUID, } DEFINE_GUID!(D3DAUTHENTICATEDQUERY_CURRENTENCRYPTIONWHENACCESSIBLE, 0xec1791c7, 0xdad3, 0x4f15, 0x9e, 0xc3, 0xfa, 0xa9, 0x3d, 0x60, 0xd4, 0xf0); #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_QUERYUNCOMPRESSEDENCRYPTIONLEVEL_OUTPUT { pub Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, pub EncryptionGuid: ::GUID, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_CONFIGURE_INPUT { pub omac: D3D_OMAC, pub ConfigureType: ::GUID, pub hChannel: ::HANDLE, pub SequenceNumber: ::UINT, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_CONFIGURE_OUTPUT { pub omac: D3D_OMAC, pub ConfigureType: ::GUID, pub hChannel: ::HANDLE, pub SequenceNumber: ::UINT, pub ReturnCode: ::HRESULT, } DEFINE_GUID!(D3DAUTHENTICATEDCONFIGURE_INITIALIZE, 0x6114bdb, 0x3523, 0x470a, 0x8d, 0xca, 0xfb, 0xc2, 0x84, 0x51, 0x54, 0xf0); #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_CONFIGUREINITIALIZE { pub Parameters: D3DAUTHENTICATEDCHANNEL_CONFIGURE_INPUT, pub StartSequenceQuery: ::UINT, pub StartSequenceConfigure: ::UINT, } DEFINE_GUID!(D3DAUTHENTICATEDCONFIGURE_PROTECTION, 0x50455658, 0x3f47, 0x4362, 0xbf, 0x99, 0xbf, 0xdf, 0xcd, 0xe9, 0xed, 0x29); #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_CONFIGUREPROTECTION { pub Parameters: D3DAUTHENTICATEDCHANNEL_CONFIGURE_INPUT, pub Protections: D3DAUTHENTICATEDCHANNEL_PROTECTION_FLAGS, } DEFINE_GUID!(D3DAUTHENTICATEDCONFIGURE_CRYPTOSESSION, 0x6346cc54, 0x2cfc, 0x4ad4, 0x82, 0x24, 0xd1, 0x58, 0x37, 0xde, 0x77, 0x0); #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_CONFIGURECRYPTOSESSION { pub Parameters: D3DAUTHENTICATEDCHANNEL_CONFIGURE_INPUT, pub DXVA2DecodeHandle: ::HANDLE, pub CryptoSessionHandle: ::HANDLE, pub DeviceHandle: ::HANDLE, } DEFINE_GUID!(D3DAUTHENTICATEDCONFIGURE_SHAREDRESOURCE, 0x772d047, 0x1b40, 0x48e8, 0x9c, 0xa6, 0xb5, 0xf5, 0x10, 0xde, 0x9f, 0x1); #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_CONFIGURESHAREDRESOURCE { pub Parameters: D3DAUTHENTICATEDCHANNEL_CONFIGURE_INPUT, pub ProcessIdentiferType: D3DAUTHENTICATEDCHANNEL_PROCESSIDENTIFIERTYPE, pub ProcessHandle: ::HANDLE, pub AllowAccess: ::BOOL, } DEFINE_GUID!(D3DAUTHENTICATEDCONFIGURE_ENCRYPTIONWHENACCESSIBLE, 0x41fff286, 0x6ae0, 0x4d43, 0x9d, 0x55, 0xa4, 0x6e, 0x9e, 0xfd, 0x15, 0x8a); #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_CONFIGUREUNCOMPRESSEDENCRYPTION { pub Parameters: D3DAUTHENTICATEDCHANNEL_CONFIGURE_INPUT, pub EncryptionGuid: ::GUID, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DENCRYPTED_BLOCK_INFO { pub NumEncryptedBytesAtBeginning: ::UINT, pub NumBytesInSkipPattern: ::UINT, pub NumBytesInEncryptPattern: ::UINT, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAES_CTR_IV { pub IV: ::UINT64, pub Count: ::UINT64, }<|fim▁end|>
CONST4 = 13, CONSTBOOL = 14,
<|file_name|>once.rs<|end_file_name|><|fim▁begin|>use consumer::*; use stream::*; /// A stream that emits an element exactly once. /// /// This `struct` is created by the [`once()`] function. See its documentation /// for more. /// /// [`once()`]: fn.once.html #[must_use = "stream adaptors are lazy and do nothing unless consumed"] pub struct Once<T> { value: T, } /// Creates a stream that emits an element exactly once. /// /// # Examples /// /// ``` /// use asyncplify::*; ///<|fim▁hole|>/// ``` pub fn once<T>(value: T) -> Once<T> { Once { value: value } } impl<T> Stream for Once<T> { type Item = T; fn consume<C>(self, mut consumer: C) where C: Consumer<Self::Item> { consumer.emit(self.value); } }<|fim▁end|>
/// let vec = once(5).into_vec(); /// assert!(vec == [5], "vec == {:?}", vec);