text
stringlengths
6
947k
repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.map, name='map'), url(r'^mapSim', views.mapSim, name='mapSim'), url(r'^api/getPos', views.getPos, name='getPos'), url(r'^api/getProjAndPos', views.getProjAndPos, name='getProjAndPos'), ]
j-herrera/icarus
icarus_site/ISStrace/urls.py
Python
gpl-2.0
279
0.014337
# -*- coding: utf-8 -*- ## Copyright 2015 Rasmus Scholer Sorensen, rasmusscholer@gmail.com ## ## This file is part of Nascent. ## ## Nascent 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/>. #pylint: disable=C0103,C0111,W0613 from __future__ import absolute_import, print_function, division from pprint import pprint do_print = False def print_debug(*args, **kwargs): """ Change module-level do_print variable to toggle behaviour. """ if 'origin' in kwargs: del kwargs['origin'] if do_print: print(*args, **kwargs) def pprint_debug(*args, **kwargs): if do_print: pprint(*args, **kwargs) def info_print(*args, **kwargs): """ Will print the file and line before printing. Can be used to find spurrious print statements. """ from inspect import currentframe, getframeinfo frameinfo = getframeinfo(currentframe().f_back) print(frameinfo.filename, frameinfo.lineno) pprint(*args, **kwargs) def info_pprint(*args, **kwargs): """ Will print the file and line before printing the variable. """ from inspect import currentframe, getframeinfo frameinfo = getframeinfo(currentframe().f_back) print(frameinfo.filename, frameinfo.lineno) pprint(*args, **kwargs) pprintd = pprint_debug printd = print_debug
scholer/nascent
nascent/graph_sim_nx/debug.py
Python
agpl-3.0
1,923
0.00832
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/spacecat/AutonomousFlight/simulation/simulation_ws/src/rotors_simulator/rotors_joy_interface/include".split(';') if "/home/spacecat/AutonomousFlight/simulation/simulation_ws/src/rotors_simulator/rotors_joy_interface/include" != "" else [] PROJECT_CATKIN_DEPENDS = "roscpp;geometry_msgs;mav_msgs;sensor_msgs".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "rotors_joy_interface" PROJECT_SPACE_DIR = "/home/spacecat/AutonomousFlight/simulation/simulation_ws/devel" PROJECT_VERSION = "1.0.0"
chickonice/AutonomousFlight
simulation/simulation_ws/build/rotors_simulator/rotors_joy_interface/catkin_generated/pkg.develspace.context.pc.py
Python
gpl-3.0
669
0.004484
#!/usr/bin/env python # Copyright (c) 2009, Purdue University # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright notice, this # list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # # Neither the name of the Purdue University nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Setup script for roster config manager.""" __copyright__ = 'Copyright (C) 2009, Purdue University' __license__ = 'BSD' __version__ = '#TRUNK#' try: from setuptools import setup except ImportError: from distutils.core import setup current_version = __version__ if( __version__.startswith('#') ): current_version = '1000' setup(name='RosterConfigManager', version=current_version, description='RosterConfigManager is a Bind9 config importer/exporter for ' 'Roster', long_description='Roster is DNS management software for use with Bind 9. ' 'Roster is written in Python and uses a MySQL database ' 'with an XML-RPC front-end. It contains a set of ' 'command line user tools that connect to the XML-RPC ' 'front-end. The config files for Bind are generated ' 'from the MySQL database so a live MySQL database is ' 'not needed.', maintainer='Roster Development Team', maintainer_email='roster-discussion@googlegroups.com', url='http://code.google.com/p/roster-dns-management/', packages=['roster_config_manager'], license=__license__, classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: BSD License', 'Operating System :: Unix', 'Programming Language :: Python :: 2.5', 'Topic :: Internet :: Name Service (DNS)'], install_requires = ['dnspython>=1.6.0', 'IPy>=0.62', 'iscpy>=1.0.5', 'fabric>=1.4.0', 'RosterCore>=%s' % current_version], scripts = ['scripts/dnsconfigsync', 'scripts/dnszoneimporter', 'scripts/dnstreeexport', 'scripts/dnscheckconfig', 'scripts/dnsexportconfig', 'scripts/dnsrecover', 'scripts/dnszonecompare', 'scripts/dnsquerycheck', 'scripts/dnsservercheck', 'scripts/dnsversioncheck'] )
stephenlienharrell/roster-dns-management
roster-config-manager/setup.py
Python
bsd-3-clause
3,685
0.005156
import logging from future.moves.urllib.parse import quote from future.moves.urllib.error import HTTPError, URLError from future.moves.urllib.request import urlopen, Request logging.getLogger(__name__).addHandler(logging.NullHandler()) class Botan(object): """This class helps to send incoming events to your botan analytics account. See more: https://github.com/botanio/sdk#botan-sdk """ token = '' url_template = 'https://api.botan.io/track?token={token}' \ '&uid={uid}&name={name}&src=python-telegram-bot' def __init__(self, token): self.token = token self.logger = logging.getLogger(__name__) def track(self, message, event_name='event'): try: uid = message.chat_id except AttributeError: self.logger.warn('No chat_id in message') return False data = message.to_json() try: url = self.url_template.format( token=str(self.token), uid=str(uid), name=quote(event_name)) request = Request( url, data=data.encode(), headers={'Content-Type': 'application/json'}) urlopen(request) return True except HTTPError as error: self.logger.warn('Botan track error ' + str(error.code) + ':' + error.read().decode( 'utf-8')) return False except URLError as error: self.logger.warn('Botan track error ' + str(error.reason)) return False
thonkify/thonkify
src/lib/telegram/contrib/botan.py
Python
mit
1,522
0.001971
# -*- coding: utf-8 -*- # __author__ = "Epsirom" class BaseError(Exception): def __init__(self, code, msg): super(BaseError, self).__init__(msg) self.code = code self.msg = msg def __repr__(self): return '[ERRCODE=%d] %s' % (self.code, self.msg) class InputError(BaseError): def __init__(self, msg): super(InputError, self).__init__(1, msg) class LogicError(BaseError): def __init__(self, msg): super(LogicError, self).__init__(2, msg) class ValidateError(BaseError): def __init__(self, msg): super(ValidateError, self).__init__(3, msg)
liuzhenyang14/Meeting
codex/baseerror.py
Python
gpl-3.0
629
0.00159
%bash/bin/python import sys import os import socket host = localhost port = 2275 } s == socket.socket { s.connect('$port' , '$host' ); def curlhttp ('http keepalive == 300 tps '): curlhttp ('http keepalive == 300 tps '): elif curlhttp ('https keepalive == <300 ('https keepalive == <300 print "Not Valid Request " ) ) #require Connection From Socket #require verison control
pesaply/sarafu
smpp.py
Python
mit
447
0.067114
# Bug in 2.7 base64.py _b32alphabet = { 0: 'A', 9: 'J', 18: 'S', 27: '3', 1: 'B', 10: 'K', 19: 'T', 28: '4', 2: 'C', 11: 'L', 20: 'U', 29: '5', 3: 'D', 12: 'M', 21: 'V', 30: '6', 4: 'E', 13: 'N', 22: 'W', 31: '7', 5: 'F', 14: 'O', 23: 'X', 6: 'G', 15: 'P', 24: 'Y', 7: 'H', 16: 'Q', 25: 'Z', 8: 'I', 17: 'R', 26: '2', }
moagstar/python-uncompyle6
test/simple_source/expression/03_map.py
Python
mit
361
0
import time import numpy as np import pandas as pd class DNB: """ Class representing Dynamic Naive Bayes. """ def __init__(self, debug=False): self.states_prior = None self.states_list = None self.features = None self.A = None self.B = None self.debug = debug def _state_index(self, state): return np.searchsorted(self.states_list, state) def mle(self, df, state_col, features=None, avoid_zeros=False, fix_scales=False): t = time.process_time() """ Fitting dynamics in the DNB """ self._dynamic_mle(df[state_col], avoid_zeros) """ Fitting observable variables """ self.B = {} for st in self.states_list: self._features_mle(df[df[state_col] == st].drop([state_col], axis=1), st, features) if fix_scales: self.fix_zero_scale() if self.debug: elapsed_time = time.process_time() - t print("MLE finished in %d seconds." % elapsed_time) return self def _dynamic_mle(self, df, avoid_zeros): states_vec = df.as_matrix() self.states_list = np.unique(states_vec) states_nr = len(self.states_list) self.A = np.zeros((states_nr, states_nr)) if avoid_zeros: self.A += 1 self.states_prior = np.zeros(states_nr) self.states_prior[self._state_index(states_vec[0])] += 1 for i in range(1, len(states_vec)): self.A[self._state_index(states_vec[i - 1]), self._state_index(states_vec[i])] += 1 self.states_prior[self._state_index(states_vec[i])] += 1 self.states_prior = self.states_prior / self.states_prior.sum() for i in range(states_nr): self.A[i] = self.A[i] / self.A[i].sum() def _features_mle(self, df, state, features): import scipy.stats as st if features is None: self.features = dict.fromkeys(list(df.columns.values), st.norm) else: self.features = features for f, dist in self.features.items(): params = dist.fit(df[f]) arg = params[:-2] loc = params[-2] scale = params[-1] if self.debug: print("Distribution: %s, args: %s, loc: %s, scale: %s" % (str(dist), str(arg), str(loc), str(scale))) self.B[(state, f)] = list(params) def fix_zero_scale(self, new_scale=1, tolerance=0.000001): for state in self.states_list: for f, dist in self.features.items(): scale = self.B[(state, f)][-1] if scale < tolerance: if self.debug: print("state: %s,feature: %s" % (str(state), str(f))) self.B[(state, f)][-1] = new_scale def prior_prob(self, state, log=False): if log: return np.log(self.states_prior[self._state_index(state)]) else: return self.states_prior[self._state_index(state)] def emission_prob(self, state, data, log=False): prob = 1 if log: prob = np.log(prob) for f, dist in self.features.items(): arg = self.B[(state, f)][:-2] loc = self.B[(state, f)][-2] scale = self.B[(state, f)][-1] if log: prob += dist.logpdf(data[f], loc=loc, scale=scale, *arg) else: prob *= dist.pdf(data[f], loc=loc, scale=scale, *arg) return prob def transition_prob(self, state1, state2, log=False): if log: return np.log(self.A[self._state_index(state1), self._state_index(state2)]) else: return self.A[self._state_index(state1), self._state_index(state2)] def _forward(self, data, k=None, state=None): alpha = np.zeros((len(self.states_list), len(data))) """ alpha t=0 """ for st in self.states_list: alpha[self._state_index(st)] = self.prior_prob(st, log=True) + self.emission_prob(st, data.iloc[0], log=True) for t in range(1, len(data)): for st in self.states_list: alpha[self._state_index(st)][t] = sum( alpha[self._state_index(_st)][t - 1] + self.transition_prob(_st, st, log=True) for _st in self.states_list) + self.emission_prob(st, data.iloc[t], log=True) if state: alpha = alpha[self._state_index(state), :] if k: alpha = alpha[:, k] return alpha def _backward(self, data, k=None, state=None): beta = np.zeros((len(self.states_list), len(data))) for t in range(len(data) - 1, 0, -1): for st in self.states_list: beta[self._state_index(st)][t] = sum( self.transition_prob(st, _st, log=True) + self.emission_prob(_st, data.iloc[t + 1], log=True) + beta[_st][t + 1] for _st in self.states_list) if state: beta = beta[self._state_index(state), :] if k: beta = beta[:, k] return beta def sample(self, size, n=1): sequences = [] for i in range(n): Y, output = [], {} state = self.states_list[np.random.choice(len(self.states_list), 1, p=self.states_prior)[0]] for _ in range(size): for f, dist in self.features.items(): arr = output.get(f, []) arg = self.B[(state, f)][:-2] loc = self.B[(state, f)][-2] scale = self.B[(state, f)][-1] arr.append(dist(loc=loc, scale=scale, *arg).rvs()) output[f] = arr Y.append(state) state = self.states_list[ np.random.choice(len(self.states_list), 1, p=self.A[self._state_index(state)])[0]] df = pd.DataFrame({**{'state': Y}, **output}) sequences.append(df) return sequences def obs_seq_probability(self, data): return sum(self._forward(data, k=len(data) - 1)) def seq_probability(self, data, path, log=True): prob = 0 path = list(path) prob += self.prior_prob(path[0], log=True) prob += self.emission_prob(path[0], data.iloc[0], log=True) for t in range(1, len(data)): prob += self.transition_prob(path[t - 1], path[t], log=True) prob += self.emission_prob(path[t], data.iloc[t], log=True) if not log: return np.exp(prob) return prob def viterbi(self, data): pass
tsabata/PyDNB
pydnb/dnb.py
Python
mit
6,733
0.001782
from couchpotato.core.event import addEvent from couchpotato.core.logger import CPLog from couchpotato.core.notifications.base import Notification import os import subprocess log = CPLog(__name__) class Synoindex(Notification): index_path = '/usr/syno/bin/synoindex' def __init__(self): super(Synoindex, self).__init__() addEvent('renamer.after', self.addToLibrary) def addToLibrary(self, message = None, group = None): if self.isDisabled(): return if not group: group = {} command = [self.index_path, '-A', group.get('destination_dir')] log.info('Executing synoindex command: %s ', command) try: p = subprocess.Popen(command, stdout = subprocess.PIPE, stderr = subprocess.STDOUT) out = p.communicate() log.info('Result from synoindex: %s', str(out)) return True except OSError, e: log.error('Unable to run synoindex: %s', e) return False def test(self, **kwargs): return { 'success': os.path.isfile(self.index_path) }
lebabouin/CouchPotatoServer-develop
couchpotato/core/notifications/synoindex/main.py
Python
gpl-3.0
1,104
0.009964
# Copyright 2015, Ansible, Inc. # Alan Rominger <arominger@ansible.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 # 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 tower_cli from tower_cli.api import client from tests.compat import unittest, mock from tower_cli.conf import settings import click import json class TemplateTests(unittest.TestCase): """A set of tests for commands operating on the job template """ def setUp(self): self.res = tower_cli.get_resource('job_template') def test_create(self): """Establish that a job template can be created """ with client.test_mode as t: endpoint = '/job_templates/' t.register_json(endpoint, {'count': 0, 'results': [], 'next': None, 'previous': None}, method='GET') t.register_json(endpoint, {'changed': True, 'id': 42}, method='POST') self.res.create(name='bar', job_type='run', inventory=1, project=1, playbook='foobar.yml', credential=1) self.assertEqual(t.requests[0].method, 'GET') self.assertEqual(t.requests[1].method, 'POST') self.assertEqual(len(t.requests), 2) # Check that default job_type will get added when needed with client.test_mode as t: endpoint = '/job_templates/' t.register_json(endpoint, {'count': 0, 'results': [], 'next': None, 'previous': None}, method='GET') t.register_json(endpoint, {'changed': True, 'id': 42}, method='POST') self.res.create(name='bar', inventory=1, project=1, playbook='foobar.yml', credential=1) req_body = json.loads(t.requests[1].body) self.assertIn('job_type', req_body) self.assertEqual(req_body['job_type'], 'run') def test_job_template_create_with_echo(self): """Establish that a job template can be created """ with client.test_mode as t: endpoint = '/job_templates/' t.register_json(endpoint, {'count': 0, 'results': [], 'next': None, 'previous': None}, method='GET') t.register_json(endpoint, {'changed': True, 'id': 42, 'name': 'bar', 'inventory': 1, 'project': 1, 'playbook': 'foobar.yml', 'credential': 1}, method='POST') self.res.create(name='bar', job_type='run', inventory=1, project=1, playbook='foobar.yml', credential=1) f = self.res.as_command()._echo_method(self.res.create) with mock.patch.object(click, 'secho'): with settings.runtime_values(format='human'): f(name='bar', job_type='run', inventory=1, project=1, playbook='foobar.yml', credential=1) def test_create_w_extra_vars(self): """Establish that a job template can be created and extra varas passed to it """ with client.test_mode as t: endpoint = '/job_templates/' t.register_json(endpoint, {'count': 0, 'results': [], 'next': None, 'previous': None}, method='GET') t.register_json(endpoint, {'changed': True, 'id': 42}, method='POST') self.res.create(name='bar', job_type='run', inventory=1, project=1, playbook='foobar.yml', credential=1, extra_vars=['foo: bar']) self.assertEqual(t.requests[0].method, 'GET') self.assertEqual(t.requests[1].method, 'POST') self.assertEqual(len(t.requests), 2) def test_modify(self): """Establish that a job template can be modified """ with client.test_mode as t: endpoint = '/job_templates/' t.register_json(endpoint, {'count': 1, 'results': [{'id': 1, 'name': 'bar'}], 'next': None, 'previous': None}, method='GET') t.register_json('/job_templates/1/', {'name': 'bar', 'id': 1, 'job_type': 'run'}, method='PATCH') self.res.modify(name='bar', playbook='foobared.yml') self.assertEqual(t.requests[0].method, 'GET') self.assertEqual(t.requests[1].method, 'PATCH') self.assertEqual(len(t.requests), 2) def test_modify_extra_vars(self): """Establish that a job template can be modified """ with client.test_mode as t: endpoint = '/job_templates/' t.register_json(endpoint, {'count': 1, 'results': [{'id': 1, 'name': 'bar'}], 'next': None, 'previous': None}, method='GET') t.register_json('/job_templates/1/', {'name': 'bar', 'id': 1, 'job_type': 'run'}, method='PATCH') self.res.modify(name='bar', extra_vars=["a: 5"]) self.assertEqual(t.requests[0].method, 'GET') self.assertEqual(t.requests[1].method, 'PATCH') self.assertEqual(len(t.requests), 2) def test_associate_label(self): """Establish that the associate method makes the HTTP requests that we expect. """ with client.test_mode as t: t.register_json('/job_templates/42/labels/?id=84', {'count': 0, 'results': []}) t.register_json('/job_templates/42/labels/', {}, method='POST') self.res.associate_label(42, 84) self.assertEqual(t.requests[1].body, json.dumps({'associate': True, 'id': 84})) def test_disassociate_label(self): """Establish that the disassociate method makes the HTTP requests that we expect. """ with client.test_mode as t: t.register_json('/job_templates/42/labels/?id=84', {'count': 1, 'results': [{'id': 84}], 'next': None, 'previous': None}) t.register_json('/job_templates/42/labels/', {}, method='POST') self.res.disassociate_label(42, 84) self.assertEqual(t.requests[1].body, json.dumps({'disassociate': True, 'id': 84})) def test_associate_notification_template(self): """Establish that a job template should be able to associate itself with an existing notification template. """ with client.test_mode as t: t.register_json('/job_templates/5/notification_templates_any/' '?id=3', {'count': 0, 'results': []}) t.register_json('/job_templates/5/notification_templates_any/', {}, method='POST') self.res.associate_notification_template(5, 3, 'any') self.assertEqual(t.requests[1].body, json.dumps({'associate': True, 'id': 3})) def test_disassociate_notification_template(self): """Establish that a job template should be able to disassociate itself from an associated notification template. """ with client.test_mode as t: t.register_json('/job_templates/5/notification_templates_any/' '?id=3', {'count': 1, 'results': [{'id': 3}]}) t.register_json('/job_templates/5/notification_templates_any/', {}, method='POST') self.res.disassociate_notification_template(5, 3, 'any') self.assertEqual(t.requests[1].body, json.dumps({'disassociate': True, 'id': 3}))
jangsutsr/tower-cli
tests/test_resources_job_template.py
Python
apache-2.0
8,499
0
# ***** BEGIN GPL LICENSE BLOCK ***** # # 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-1301, USA. # # ***** END GPL LICENSE BLOCK ***** # <pep8 compliant> # Populate a template file (POT format currently) from Blender RNA/py/C data. # XXX: This script is meant to be used from inside Blender! # You should not directly use this script, rather use update_msg.py! import collections import copy import datetime import os import re import sys # XXX Relative import does not work here when used from Blender... from bl_i18n_utils import settings as settings_i18n, utils import bpy ##### Utils ##### # check for strings like "+%f°" ignore_reg = re.compile(r"^(?:[-*.()/\\+%°0-9]|%d|%f|%s|%r|\s)*$") filter_message = ignore_reg.match def init_spell_check(settings, lang="en_US"): try: from bl_i18n_utils import utils_spell_check return utils_spell_check.SpellChecker(settings, lang) except Exception as e: print("Failed to import utils_spell_check ({})".format(str(e))) return None def _gen_check_ctxt(settings): return { "multi_rnatip": set(), "multi_lines": set(), "py_in_rna": set(), "not_capitalized": set(), "end_point": set(), "undoc_ops": set(), "spell_checker": init_spell_check(settings), "spell_errors": {}, } def _diff_check_ctxt(check_ctxt, minus_check_ctxt): """Returns check_ctxt - minus_check_ctxt""" for key in check_ctxt: if isinstance(check_ctxt[key], set): for warning in minus_check_ctxt[key]: if warning in check_ctxt[key]: check_ctxt[key].remove(warning) elif isinstance(check_ctxt[key], dict): for warning in minus_check_ctxt[key]: if warning in check_ctxt[key]: del check_ctxt[key][warning] def _gen_reports(check_ctxt): return { "check_ctxt": check_ctxt, "rna_structs": [], "rna_structs_skipped": [], "rna_props": [], "rna_props_skipped": [], "py_messages": [], "py_messages_skipped": [], "src_messages": [], "src_messages_skipped": [], "messages_skipped": set(), } def check(check_ctxt, msgs, key, msgsrc, settings): """ Performs a set of checks over the given key (context, message)... """ if check_ctxt is None: return multi_rnatip = check_ctxt.get("multi_rnatip") multi_lines = check_ctxt.get("multi_lines") py_in_rna = check_ctxt.get("py_in_rna") not_capitalized = check_ctxt.get("not_capitalized") end_point = check_ctxt.get("end_point") undoc_ops = check_ctxt.get("undoc_ops") spell_checker = check_ctxt.get("spell_checker") spell_errors = check_ctxt.get("spell_errors") if multi_rnatip is not None: if key in msgs and key not in multi_rnatip: multi_rnatip.add(key) if multi_lines is not None: if '\n' in key[1]: multi_lines.add(key) if py_in_rna is not None: if key in py_in_rna[1]: py_in_rna[0].add(key) if not_capitalized is not None: if(key[1] not in settings.WARN_MSGID_NOT_CAPITALIZED_ALLOWED and key[1][0].isalpha() and not key[1][0].isupper()): not_capitalized.add(key) if end_point is not None: if (key[1].strip().endswith('.') and not key[1].strip().endswith('...') and key[1] not in settings.WARN_MSGID_END_POINT_ALLOWED): end_point.add(key) if undoc_ops is not None: if key[1] == settings.UNDOC_OPS_STR: undoc_ops.add(key) if spell_checker is not None and spell_errors is not None: err = spell_checker.check(key[1]) if err: spell_errors[key] = err def print_info(reports, pot): def _print(*args, **kwargs): kwargs["file"] = sys.stderr print(*args, **kwargs) pot.update_info() _print("{} RNA structs were processed (among which {} were skipped), containing {} RNA properties " "(among which {} were skipped).".format(len(reports["rna_structs"]), len(reports["rna_structs_skipped"]), len(reports["rna_props"]), len(reports["rna_props_skipped"]))) _print("{} messages were extracted from Python UI code (among which {} were skipped), and {} from C source code " "(among which {} were skipped).".format(len(reports["py_messages"]), len(reports["py_messages_skipped"]), len(reports["src_messages"]), len(reports["src_messages_skipped"]))) _print("{} messages were rejected.".format(len(reports["messages_skipped"]))) _print("\n") _print("Current POT stats:") pot.print_info(prefix="\t", output=_print) _print("\n") check_ctxt = reports["check_ctxt"] if check_ctxt is None: return multi_rnatip = check_ctxt.get("multi_rnatip") multi_lines = check_ctxt.get("multi_lines") py_in_rna = check_ctxt.get("py_in_rna") not_capitalized = check_ctxt.get("not_capitalized") end_point = check_ctxt.get("end_point") undoc_ops = check_ctxt.get("undoc_ops") spell_errors = check_ctxt.get("spell_errors") # XXX Temp, no multi_rnatip nor py_in_rna, see below. keys = multi_lines | not_capitalized | end_point | undoc_ops | spell_errors.keys() if keys: _print("WARNINGS:") for key in keys: if undoc_ops and key in undoc_ops: _print("\tThe following operators are undocumented!") else: _print("\t“{}”|“{}”:".format(*key)) if multi_lines and key in multi_lines: _print("\t\t-> newline in this message!") if not_capitalized and key in not_capitalized: _print("\t\t-> message not capitalized!") if end_point and key in end_point: _print("\t\t-> message with endpoint!") # XXX Hide this one for now, too much false positives. # if multi_rnatip and key in multi_rnatip: # _print("\t\t-> tip used in several RNA items") # if py_in_rna and key in py_in_rna: # _print("\t\t-> RNA message also used in py UI code!") if spell_errors and spell_errors.get(key): lines = ["\t\t-> {}: misspelled, suggestions are ({})".format(w, "'" + "', '".join(errs) + "'") for w, errs in spell_errors[key]] _print("\n".join(lines)) _print("\t\t{}".format("\n\t\t".join(pot.msgs[key].sources))) def process_msg(msgs, msgctxt, msgid, msgsrc, reports, check_ctxt, settings): if filter_message(msgid): reports["messages_skipped"].add((msgid, msgsrc)) return if not msgctxt: # We do *not* want any "" context! msgctxt = settings.DEFAULT_CONTEXT # Always unescape keys! msgctxt = utils.I18nMessage.do_unescape(msgctxt) msgid = utils.I18nMessage.do_unescape(msgid) key = (msgctxt, msgid) check(check_ctxt, msgs, key, msgsrc, settings) msgsrc = settings.PO_COMMENT_PREFIX_SOURCE_CUSTOM + msgsrc if key not in msgs: msgs[key] = utils.I18nMessage([msgctxt], [msgid], [], [msgsrc], settings=settings) else: msgs[key].comment_lines.append(msgsrc) ##### RNA ##### def dump_rna_messages(msgs, reports, settings, verbose=False): """ Dump into messages dict all RNA-defined UI messages (labels en tooltips). """ def class_blacklist(): blacklist_rna_class = {getattr(bpy.types, cls_id) for cls_id in ( # core classes "Context", "Event", "Function", "UILayout", "UnknownType", "Property", "Struct", # registerable classes "Panel", "Menu", "Header", "RenderEngine", "Operator", "OperatorMacro", "Macro", "KeyingSetInfo", # window classes "Window", ) } # More builtin classes we don't need to parse. blacklist_rna_class |= {cls for cls in bpy.types.Property.__subclasses__()} _rna = {getattr(bpy.types, cls) for cls in dir(bpy.types)} # Classes which are attached to collections can be skipped too, these are api access only. for cls in _rna: for prop in cls.bl_rna.properties: if prop.type == 'COLLECTION': prop_cls = prop.srna if prop_cls is not None: blacklist_rna_class.add(prop_cls.__class__) # Now here is the *ugly* hack! # Unfortunately, all classes we want to access are not available from bpy.types (OperatorProperties subclasses # are not here, as they have the same name as matching Operator ones :( ). So we use __subclasses__() calls # to walk through all rna hierachy. # But unregistered classes remain listed by relevant __subclasses__() calls (be it a Py or BPY/RNA bug), # and obviously the matching RNA struct exists no more, so trying to access their data (even the identifier) # quickly leads to segfault! # To address this, we have to blacklist classes which __name__ does not match any __name__ from bpy.types # (we can't use only RNA identifiers, as some py-defined classes has a different name that rna id, # and we can't use class object themselves, because OperatorProperties subclasses are not in bpy.types!)... _rna_clss_ids = {cls.__name__ for cls in _rna} | {cls.bl_rna.identifier for cls in _rna} # All registrable types. blacklist_rna_class |= {cls for cls in bpy.types.OperatorProperties.__subclasses__() + bpy.types.Operator.__subclasses__() + bpy.types.OperatorMacro.__subclasses__() + bpy.types.Header.__subclasses__() + bpy.types.Panel.__subclasses__() + bpy.types.Menu.__subclasses__() + bpy.types.UIList.__subclasses__() if cls.__name__ not in _rna_clss_ids} # Collect internal operators # extend with all internal operators # note that this uses internal api introspection functions # XXX Do not skip INTERNAL's anymore, some of those ops show up in UI now! # all possible operator names #op_ids = (set(cls.bl_rna.identifier for cls in bpy.types.OperatorProperties.__subclasses__()) | #set(cls.bl_rna.identifier for cls in bpy.types.Operator.__subclasses__()) | #set(cls.bl_rna.identifier for cls in bpy.types.OperatorMacro.__subclasses__())) #get_instance = __import__("_bpy").ops.get_instance #path_resolve = type(bpy.context).__base__.path_resolve #for idname in op_ids: #op = get_instance(idname) #if 'INTERNAL' in path_resolve(op, "bl_options"): #blacklist_rna_class.add(idname) return blacklist_rna_class check_ctxt_rna = check_ctxt_rna_tip = None check_ctxt = reports["check_ctxt"] if check_ctxt: check_ctxt_rna = { "multi_lines": check_ctxt.get("multi_lines"), "not_capitalized": check_ctxt.get("not_capitalized"), "end_point": check_ctxt.get("end_point"), "undoc_ops": check_ctxt.get("undoc_ops"), "spell_checker": check_ctxt.get("spell_checker"), "spell_errors": check_ctxt.get("spell_errors"), } check_ctxt_rna_tip = check_ctxt_rna check_ctxt_rna_tip["multi_rnatip"] = check_ctxt.get("multi_rnatip") default_context = settings.DEFAULT_CONTEXT # Function definitions def walk_properties(cls): bl_rna = cls.bl_rna # Get our parents' properties, to not export them multiple times. bl_rna_base = bl_rna.base if bl_rna_base: bl_rna_base_props = set(bl_rna_base.properties.values()) else: bl_rna_base_props = set() for prop in bl_rna.properties: # Only write this property if our parent hasn't got it. if prop in bl_rna_base_props: continue if prop.identifier == "rna_type": continue reports["rna_props"].append((cls, prop)) msgsrc = "bpy.types.{}.{}".format(bl_rna.identifier, prop.identifier) msgctxt = prop.translation_context or default_context if prop.name and (prop.name != prop.identifier or msgctxt != default_context): process_msg(msgs, msgctxt, prop.name, msgsrc, reports, check_ctxt_rna, settings) if prop.description: process_msg(msgs, default_context, prop.description, msgsrc, reports, check_ctxt_rna_tip, settings) if isinstance(prop, bpy.types.EnumProperty): for item in prop.enum_items: msgsrc = "bpy.types.{}.{}:'{}'".format(bl_rna.identifier, prop.identifier, item.identifier) if item.name and item.name != item.identifier: process_msg(msgs, msgctxt, item.name, msgsrc, reports, check_ctxt_rna, settings) if item.description: process_msg(msgs, default_context, item.description, msgsrc, reports, check_ctxt_rna_tip, settings) blacklist_rna_class = class_blacklist() def walk_class(cls): bl_rna = cls.bl_rna msgsrc = "bpy.types." + bl_rna.identifier msgctxt = bl_rna.translation_context or default_context if bl_rna.name and (bl_rna.name != bl_rna.identifier or msgctxt != default_context): process_msg(msgs, msgctxt, bl_rna.name, msgsrc, reports, check_ctxt_rna, settings) if bl_rna.description: process_msg(msgs, default_context, bl_rna.description, msgsrc, reports, check_ctxt_rna_tip, settings) elif cls.__doc__: # XXX Some classes (like KeyingSetInfo subclasses) have void description... :( process_msg(msgs, default_context, cls.__doc__, msgsrc, reports, check_ctxt_rna_tip, settings) if hasattr(bl_rna, 'bl_label') and bl_rna.bl_label: process_msg(msgs, msgctxt, bl_rna.bl_label, msgsrc, reports, check_ctxt_rna, settings) walk_properties(cls) def walk_keymap_hierarchy(hier, msgsrc_prev): km_i18n_context = bpy.app.translations.contexts.id_windowmanager for lvl in hier: msgsrc = msgsrc_prev + "." + lvl[1] process_msg(msgs, km_i18n_context, lvl[0], msgsrc, reports, None, settings) if lvl[3]: walk_keymap_hierarchy(lvl[3], msgsrc) # Dump Messages def process_cls_list(cls_list): if not cls_list: return def full_class_id(cls): """Gives us 'ID.Lamp.AreaLamp' which is best for sorting.""" # Always the same issue, some classes listed in blacklist should actually no more exist (they have been # unregistered), but are still listed by __subclasses__() calls... :/ if cls in blacklist_rna_class: return cls.__name__ cls_id = "" bl_rna = cls.bl_rna while bl_rna: cls_id = bl_rna.identifier + "." + cls_id bl_rna = bl_rna.base return cls_id if verbose: print(cls_list) cls_list.sort(key=full_class_id) for cls in cls_list: if verbose: print(cls) reports["rna_structs"].append(cls) # Ignore those Operator sub-classes (anyway, will get the same from OperatorProperties sub-classes!)... if (cls in blacklist_rna_class) or issubclass(cls, bpy.types.Operator): reports["rna_structs_skipped"].append(cls) else: walk_class(cls) # Recursively process subclasses. process_cls_list(cls.__subclasses__()) # Parse everything (recursively parsing from bpy_struct "class"...). process_cls_list(bpy.types.ID.__base__.__subclasses__()) # And parse keymaps! from bpy_extras.keyconfig_utils import KM_HIERARCHY walk_keymap_hierarchy(KM_HIERARCHY, "KM_HIERARCHY") ##### Python source code ##### def dump_py_messages_from_files(msgs, reports, files, settings): """ Dump text inlined in the python files given, e.g. 'My Name' in: layout.prop("someprop", text="My Name") """ import ast bpy_struct = bpy.types.ID.__base__ i18n_contexts = bpy.app.translations.contexts root_paths = tuple(bpy.utils.resource_path(t) for t in ('USER', 'LOCAL', 'SYSTEM')) def make_rel(path): for rp in root_paths: if path.startswith(rp): try: # can't always find the relative path (between drive letters on windows) return os.path.relpath(path, rp) except ValueError: return path # Use binary's dir as fallback... try: # can't always find the relative path (between drive letters on windows) return os.path.relpath(path, os.path.dirname(bpy.app.binary_path)) except ValueError: return path # Helper function def extract_strings_ex(node, is_split=False): """ Recursively get strings, needed in case we have "Blah" + "Blah", passed as an argument in that case it won't evaluate to a string. However, break on some kind of stopper nodes, like e.g. Subscript. """ if type(node) == ast.Str: eval_str = ast.literal_eval(node) if eval_str: yield (is_split, eval_str, (node,)) else: is_split = (type(node) in separate_nodes) for nd in ast.iter_child_nodes(node): if type(nd) not in stopper_nodes: yield from extract_strings_ex(nd, is_split=is_split) def _extract_string_merge(estr_ls, nds_ls): return "".join(s for s in estr_ls if s is not None), tuple(n for n in nds_ls if n is not None) def extract_strings(node): estr_ls = [] nds_ls = [] for is_split, estr, nds in extract_strings_ex(node): estr_ls.append(estr) nds_ls.extend(nds) ret = _extract_string_merge(estr_ls, nds_ls) return ret def extract_strings_split(node): """ Returns a list args as returned by 'extract_strings()', But split into groups based on separate_nodes, this way expressions like ("A" if test else "B") wont be merged but "A" + "B" will. """ estr_ls = [] nds_ls = [] bag = [] for is_split, estr, nds in extract_strings_ex(node): if is_split: bag.append((estr_ls, nds_ls)) estr_ls = [] nds_ls = [] estr_ls.append(estr) nds_ls.extend(nds) bag.append((estr_ls, nds_ls)) return [_extract_string_merge(estr_ls, nds_ls) for estr_ls, nds_ls in bag] i18n_ctxt_ids = {v for v in bpy.app.translations.contexts_C_to_py.values()} def _ctxt_to_ctxt(node): # We must try, to some extend, to get contexts from vars instead of only literal strings... ctxt = extract_strings(node)[0] if ctxt: return ctxt # Basically, we search for attributes matching py context names, for now. # So non-literal contexts should be used that way: # i18n_ctxt = bpy.app.translations.contexts # foobar(text="Foo", text_ctxt=i18n_ctxt.id_object) if type(node) == ast.Attribute: if node.attr in i18n_ctxt_ids: #print(node, node.attr, getattr(i18n_contexts, node.attr)) return getattr(i18n_contexts, node.attr) return i18n_contexts.default def _op_to_ctxt(node): opname, _ = extract_strings(node) if not opname: return i18n_contexts.default op = bpy.ops for n in opname.split('.'): op = getattr(op, n) try: return op.get_rna().bl_rna.translation_context except Exception as e: default_op_context = i18n_contexts.operator_default print("ERROR: ", str(e)) print(" Assuming default operator context '{}'".format(default_op_context)) return default_op_context # Gather function names. # In addition of UI func, also parse pgettext ones... # Tuples of (module name, (short names, ...)). pgettext_variants = ( ("pgettext", ("_",)), ("pgettext_iface", ("iface_",)), ("pgettext_tip", ("tip_",)), ("pgettext_data", ("data_",)), ) pgettext_variants_args = {"msgid": (0, {"msgctxt": 1})} # key: msgid keywords. # val: tuples of ((keywords,), context_getter_func) to get a context for that msgid. # Note: order is important, first one wins! translate_kw = { "text": ((("text_ctxt",), _ctxt_to_ctxt), (("operator",), _op_to_ctxt), ), "msgid": ((("msgctxt",), _ctxt_to_ctxt), ), "message": (), } context_kw_set = {} for k, ctxts in translate_kw.items(): s = set() for c, _ in ctxts: s |= set(c) context_kw_set[k] = s # {func_id: {msgid: (arg_pos, # {msgctxt: arg_pos, # ... # } # ), # ... # }, # ... # } func_translate_args = {} # First, functions from UILayout # First loop is for msgid args, second one is for msgctxt args. for func_id, func in bpy.types.UILayout.bl_rna.functions.items(): # check it has one or more arguments as defined in translate_kw for arg_pos, (arg_kw, arg) in enumerate(func.parameters.items()): if ((arg_kw in translate_kw) and (not arg.is_output) and (arg.type == 'STRING')): func_translate_args.setdefault(func_id, {})[arg_kw] = (arg_pos, {}) for func_id, func in bpy.types.UILayout.bl_rna.functions.items(): if func_id not in func_translate_args: continue for arg_pos, (arg_kw, arg) in enumerate(func.parameters.items()): if (not arg.is_output) and (arg.type == 'STRING'): for msgid, msgctxts in context_kw_set.items(): if arg_kw in msgctxts: func_translate_args[func_id][msgid][1][arg_kw] = arg_pos # The report() func of operators. for func_id, func in bpy.types.Operator.bl_rna.functions.items(): # check it has one or more arguments as defined in translate_kw for arg_pos, (arg_kw, arg) in enumerate(func.parameters.items()): if ((arg_kw in translate_kw) and (not arg.is_output) and (arg.type == 'STRING')): func_translate_args.setdefault(func_id, {})[arg_kw] = (arg_pos, {}) # We manually add funcs from bpy.app.translations for func_id, func_ids in pgettext_variants: func_translate_args[func_id] = pgettext_variants_args for func_id in func_ids: func_translate_args[func_id] = pgettext_variants_args #print(func_translate_args) # Break recursive nodes look up on some kind of nodes. # E.g. we don’t want to get strings inside subscripts (blah["foo"])! stopper_nodes = {ast.Subscript} # Consider strings separate: ("a" if test else "b") separate_nodes = {ast.IfExp} check_ctxt_py = None if reports["check_ctxt"]: check_ctxt = reports["check_ctxt"] check_ctxt_py = { "py_in_rna": (check_ctxt.get("py_in_rna"), set(msgs.keys())), "multi_lines": check_ctxt.get("multi_lines"), "not_capitalized": check_ctxt.get("not_capitalized"), "end_point": check_ctxt.get("end_point"), "spell_checker": check_ctxt.get("spell_checker"), "spell_errors": check_ctxt.get("spell_errors"), } for fp in files: with open(fp, 'r', encoding="utf8") as filedata: root_node = ast.parse(filedata.read(), fp, 'exec') fp_rel = make_rel(fp) for node in ast.walk(root_node): if type(node) == ast.Call: # print("found function at") # print("%s:%d" % (fp, node.lineno)) # We can't skip such situations! from blah import foo\nfoo("bar") would also be an ast.Name func! if type(node.func) == ast.Name: func_id = node.func.id elif hasattr(node.func, "attr"): func_id = node.func.attr # Ugly things like getattr(self, con.type)(context, box, con) else: continue func_args = func_translate_args.get(func_id, {}) # First try to get i18n contexts, for every possible msgid id. msgctxts = dict.fromkeys(func_args.keys(), "") for msgid, (_, context_args) in func_args.items(): context_elements = {} for arg_kw, arg_pos in context_args.items(): if arg_pos < len(node.args): context_elements[arg_kw] = node.args[arg_pos] else: for kw in node.keywords: if kw.arg == arg_kw: context_elements[arg_kw] = kw.value break #print(context_elements) for kws, proc in translate_kw[msgid]: if set(kws) <= context_elements.keys(): args = tuple(context_elements[k] for k in kws) #print("running ", proc, " with ", args) ctxt = proc(*args) if ctxt: msgctxts[msgid] = ctxt break #print(translate_args) # do nothing if not found for arg_kw, (arg_pos, _) in func_args.items(): msgctxt = msgctxts[arg_kw] estr_lst = [(None, ())] if arg_pos < len(node.args): estr_lst = extract_strings_split(node.args[arg_pos]) #print(estr, nds) else: for kw in node.keywords: if kw.arg == arg_kw: estr_lst = extract_strings_split(kw.value) break #print(estr, nds) for estr, nds in estr_lst: if estr: if nds: msgsrc = "{}:{}".format(fp_rel, sorted({nd.lineno for nd in nds})[0]) else: msgsrc = "{}:???".format(fp_rel) process_msg(msgs, msgctxt, estr, msgsrc, reports, check_ctxt_py, settings) reports["py_messages"].append((msgctxt, estr, msgsrc)) def dump_py_messages(msgs, reports, addons, settings, addons_only=False): def _get_files(path): if not os.path.exists(path): return [] if os.path.isdir(path): return [os.path.join(dpath, fn) for dpath, _, fnames in os.walk(path) for fn in fnames if not fn.startswith("_") and fn.endswith(".py")] return [path] files = [] if not addons_only: for path in settings.CUSTOM_PY_UI_FILES: for root in (bpy.utils.resource_path(t) for t in ('USER', 'LOCAL', 'SYSTEM')): files += _get_files(os.path.join(root, path)) # Add all given addons. for mod in addons: fn = mod.__file__ if os.path.basename(fn) == "__init__.py": files += _get_files(os.path.dirname(fn)) else: files.append(fn) dump_py_messages_from_files(msgs, reports, sorted(files), settings) ##### C source code ##### def dump_src_messages(msgs, reports, settings): def get_contexts(): """Return a mapping {C_CTXT_NAME: ctxt_value}.""" return {k: getattr(bpy.app.translations.contexts, n) for k, n in bpy.app.translations.contexts_C_to_py.items()} contexts = get_contexts() # Build regexes to extract messages (with optional contexts) from C source. pygettexts = tuple(re.compile(r).search for r in settings.PYGETTEXT_KEYWORDS) _clean_str = re.compile(settings.str_clean_re).finditer clean_str = lambda s: "".join(m.group("clean") for m in _clean_str(s)) def dump_src_file(path, rel_path, msgs, reports, settings): def process_entry(_msgctxt, _msgid): # Context. msgctxt = settings.DEFAULT_CONTEXT if _msgctxt: if _msgctxt in contexts: msgctxt = contexts[_msgctxt] elif '"' in _msgctxt or "'" in _msgctxt: msgctxt = clean_str(_msgctxt) else: print("WARNING: raw context “{}” couldn’t be resolved!".format(_msgctxt)) # Message. msgid = "" if _msgid: if '"' in _msgid or "'" in _msgid: msgid = clean_str(_msgid) else: print("WARNING: raw message “{}” couldn’t be resolved!".format(_msgid)) return msgctxt, msgid check_ctxt_src = None if reports["check_ctxt"]: check_ctxt = reports["check_ctxt"] check_ctxt_src = { "multi_lines": check_ctxt.get("multi_lines"), "not_capitalized": check_ctxt.get("not_capitalized"), "end_point": check_ctxt.get("end_point"), "spell_checker": check_ctxt.get("spell_checker"), "spell_errors": check_ctxt.get("spell_errors"), } data = "" with open(path) as f: data = f.read() for srch in pygettexts: m = srch(data) line = pos = 0 while m: d = m.groupdict() # Line. line += data[pos:m.start()].count('\n') msgsrc = rel_path + ":" + str(line) _msgid = d.get("msg_raw") # First, try the "multi-contexts" stuff! _msgctxts = tuple(d.get("ctxt_raw{}".format(i)) for i in range(settings.PYGETTEXT_MAX_MULTI_CTXT)) if _msgctxts[0]: for _msgctxt in _msgctxts: if not _msgctxt: break msgctxt, msgid = process_entry(_msgctxt, _msgid) process_msg(msgs, msgctxt, msgid, msgsrc, reports, check_ctxt_src, settings) reports["src_messages"].append((msgctxt, msgid, msgsrc)) else: _msgctxt = d.get("ctxt_raw") msgctxt, msgid = process_entry(_msgctxt, _msgid) process_msg(msgs, msgctxt, msgid, msgsrc, reports, check_ctxt_src, settings) reports["src_messages"].append((msgctxt, msgid, msgsrc)) pos = m.end() line += data[m.start():pos].count('\n') m = srch(data, pos) forbidden = set() forced = set() if os.path.isfile(settings.SRC_POTFILES): with open(settings.SRC_POTFILES) as src: for l in src: if l[0] == '-': forbidden.add(l[1:].rstrip('\n')) elif l[0] != '#': forced.add(l.rstrip('\n')) for root, dirs, files in os.walk(settings.POTFILES_SOURCE_DIR): if "/.svn" in root: continue for fname in files: if os.path.splitext(fname)[1] not in settings.PYGETTEXT_ALLOWED_EXTS: continue path = os.path.join(root, fname) try: # can't always find the relative path (between drive letters on windows) rel_path = os.path.relpath(path, settings.SOURCE_DIR) except ValueError: rel_path = path if rel_path in forbidden: continue elif rel_path not in forced: forced.add(rel_path) for rel_path in sorted(forced): path = os.path.join(settings.SOURCE_DIR, rel_path) if os.path.exists(path): dump_src_file(path, rel_path, msgs, reports, settings) ##### Main functions! ##### def dump_messages(do_messages, do_checks, settings): bl_ver = "Blender " + bpy.app.version_string bl_rev = bpy.app.build_revision bl_date = datetime.datetime.strptime(bpy.app.build_date.decode() + "T" + bpy.app.build_time.decode(), "%Y-%m-%dT%H:%M:%S") pot = utils.I18nMessages.gen_empty_messages(settings.PARSER_TEMPLATE_ID, bl_ver, bl_rev, bl_date, bl_date.year, settings=settings) msgs = pot.msgs # Enable all wanted addons. # For now, enable all official addons, before extracting msgids. addons = utils.enable_addons(support={"OFFICIAL"}) # Note this is not needed if we have been started with factory settings, but just in case... utils.enable_addons(support={"COMMUNITY", "TESTING"}, disable=True) reports = _gen_reports(_gen_check_ctxt(settings) if do_checks else None) # Get strings from RNA. dump_rna_messages(msgs, reports, settings) # Get strings from UI layout definitions text="..." args. dump_py_messages(msgs, reports, addons, settings) # Get strings from C source code. dump_src_messages(msgs, reports, settings) # Get strings from addons' categories. for uid, label, tip in bpy.types.WindowManager.addon_filter[1]['items'](bpy.context.window_manager, bpy.context): process_msg(msgs, settings.DEFAULT_CONTEXT, label, "Addons' categories", reports, None, settings) if tip: process_msg(msgs, settings.DEFAULT_CONTEXT, tip, "Addons' categories", reports, None, settings) # Get strings specific to translations' menu. for lng in settings.LANGUAGES: process_msg(msgs, settings.DEFAULT_CONTEXT, lng[1], "Languages’ labels from bl_i18n_utils/settings.py", reports, None, settings) for cat in settings.LANGUAGES_CATEGORIES: process_msg(msgs, settings.DEFAULT_CONTEXT, cat[1], "Language categories’ labels from bl_i18n_utils/settings.py", reports, None, settings) #pot.check() pot.unescape() # Strings gathered in py/C source code may contain escaped chars... print_info(reports, pot) #pot.check() if do_messages: print("Writing messages…") pot.write('PO', settings.FILE_NAME_POT) print("Finished extracting UI messages!") return pot # Not used currently, but may be useful later (and to be consistent with dump_addon_messages!). def dump_addon_messages(module_name, do_checks, settings): import addon_utils # Get current addon state (loaded or not): was_loaded = addon_utils.check(module_name)[1] # Enable our addon. addon = utils.enable_addons(addons={module_name})[0] addon_info = addon_utils.module_bl_info(addon) ver = addon_info["name"] + " " + ".".join(str(v) for v in addon_info["version"]) rev = 0 date = datetime.datetime.now() pot = utils.I18nMessages.gen_empty_messages(settings.PARSER_TEMPLATE_ID, ver, rev, date, date.year, settings=settings) msgs = pot.msgs minus_pot = utils.I18nMessages.gen_empty_messages(settings.PARSER_TEMPLATE_ID, ver, rev, date, date.year, settings=settings) minus_msgs = minus_pot.msgs check_ctxt = _gen_check_ctxt(settings) if do_checks else None minus_check_ctxt = _gen_check_ctxt(settings) if do_checks else None # Get strings from RNA, our addon being enabled. print("A") reports = _gen_reports(check_ctxt) print("B") dump_rna_messages(msgs, reports, settings) print("C") # Now disable our addon, and rescan RNA. utils.enable_addons(addons={module_name}, disable=True) print("D") reports["check_ctxt"] = minus_check_ctxt print("E") dump_rna_messages(minus_msgs, reports, settings) print("F") # Restore previous state if needed! if was_loaded: utils.enable_addons(addons={module_name}) # and make the diff! for key in minus_msgs: if key != settings.PO_HEADER_KEY: del msgs[key] if check_ctxt: check_ctxt = _diff_check_ctxt(check_ctxt, minus_check_ctxt) # and we are done with those! del minus_pot del minus_msgs del minus_check_ctxt # get strings from UI layout definitions text="..." args reports["check_ctxt"] = check_ctxt dump_py_messages(msgs, reports, {addon}, settings, addons_only=True) pot.unescape() # Strings gathered in py/C source code may contain escaped chars... print_info(reports, pot) print("Finished extracting UI messages!") return pot def main(): try: import bpy except ImportError: print("This script must run from inside blender") return import sys back_argv = sys.argv # Get rid of Blender args! sys.argv = sys.argv[sys.argv.index("--") + 1:] import argparse parser = argparse.ArgumentParser(description="Process UI messages from inside Blender.") parser.add_argument('-c', '--no_checks', default=True, action="store_false", help="No checks over UI messages.") parser.add_argument('-m', '--no_messages', default=True, action="store_false", help="No export of UI messages.") parser.add_argument('-o', '--output', default=None, help="Output POT file path.") parser.add_argument('-s', '--settings', default=None, help="Override (some) default settings. Either a JSon file name, or a JSon string.") args = parser.parse_args() settings = settings_i18n.I18nSettings() settings.from_json(args.settings) if args.output: settings.FILE_NAME_POT = args.output dump_messages(do_messages=args.no_messages, do_checks=args.no_checks, settings=settings) sys.argv = back_argv if __name__ == "__main__": print("\n\n *** Running {} *** \n".format(__file__)) main()
cschenck/blender_sim
fluid_sim_deps/blender-2.69/2.69/scripts/modules/bl_i18n_utils/bl_extract_messages.py
Python
gpl-3.0
39,687
0.004009
import logging import httplib from urllib import urlencode import os import sys from lxml import etree # This addresses the issues with relative paths file_dir = os.path.dirname(os.path.realpath(__file__)) goal_dir = os.path.join(file_dir, "../../") proj_root = os.path.abspath(goal_dir)+'/' sys.path.insert(0, proj_root+'rsm') class redcap_transactions: """A class for getting data from redcap instace""" def __init__(self): self.data = [] self.configuration_directory = '' def init_redcap_interface(self,settings,logger): '''This function initializes the variables requrired to get data from redcap interface. This reads the data from the settings.ini and fills the dict with required properties. Mohan''' logger.info('Initializing redcap interface') host = '' path = '' source_data_schema_file = '' source_data_schema_file = self.configuration_directory + '/' + settings.source_data_schema_file if not os.path.exists(source_data_schema_file): raise Exception("Error: source_data_schema.xml file not found at\ "+ source_data_schema_file) else: source = open(source_data_schema_file, 'r') source_data = etree.parse(source_data_schema_file) redcap_uri = source_data.find('redcap_uri').text token = source_data.find('apitoken').text fields = ','.join(field.text for field in source_data.iter('field')) if redcap_uri is None: host = '127.0.0.1:8998' path = '/redcap/api/' if token is None: token = '4CE405878D219CFA5D3ADF7F9AB4E8ED' uri_list = redcap_uri.split('//') http_str = '' if uri_list[0] == 'https:': is_secure = True else: is_secure = False after_httpstr_list = uri_list[1].split('/', 1) host = http_str + '//' + after_httpstr_list[0] host = after_httpstr_list[0] path = '/' + after_httpstr_list[1] properties = {'host' : host, 'path' : path, "is_secure" : is_secure, 'token': token, "fields" : fields} logger.info("redcap interface initialzed") return properties def get_data_from_redcap(self, properties,logger, format_param='xml', type_param='flat', return_format='xml'): '''This function gets data from redcap using POST method for getting person index data formtype='Person_Index' must be passed as argument for getting redcap data formtype='RedCap' must be passed as argument ''' logger.info('getting data from redcap') params = {} params['token'] = properties['token'] params['content'] = 'record' params['format'] = format_param params['type'] = type_param params['returnFormat'] = return_format params['fields'] = properties['fields'] if properties['is_secure'] is True: redcap_connection = httplib.HTTPSConnection(properties['host']) else: redcap_connection = httplib.HTTPConnection(properties['host']) redcap_connection.request('POST', properties['path'], urlencode(params), {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/plain'}) response_buffer = redcap_connection.getresponse() returned = response_buffer.read() logger.info('***********RESPONSE RECEIVED FROM REDCAP***********') redcap_connection.close() return returned
ctsit/research-subject-mapper
rsm/utils/redcap_transactions.py
Python
bsd-3-clause
3,580
0.004469
# # File that determines what each URL points to. This uses _Python_ regular # expressions, not Perl's. # # See: # http://diveintopython.org/regular_expressions/street_addresses.html#re.matching.2.3 # from django.conf import settings from django.conf.urls.defaults import * from django.contrib import admin from django.views.generic import RedirectView # Wiki imports from wiki.urls import get_pattern as get_wiki_pattern from django_notify.urls import get_pattern as get_notify_pattern from djangobb_forum import settings as forum_settings admin.autodiscover() # Setup the root url tree from / # AJAX stuff. from dajaxice.core import dajaxice_autodiscover, dajaxice_config dajaxice_autodiscover() urlpatterns = patterns('', # User Authentication url(r'^login/', 'web.views.login', name="login"), url(r'^logout/', 'django.contrib.auth.views.logout', name="logout"), url(r'^accounts/login', 'views.login_gateway'), # News stuff #url(r'^news/', include('src.web.news.urls')), # Page place-holder for things that aren't implemented yet. url(r'^tbi/', 'game.gamesrc.oasis.web.website.views.to_be_implemented'), # Admin interface url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), # favicon url(r'^favicon\.ico$', RedirectView.as_view(url='/media/images/favicon.ico')), # ajax stuff url(r'^webclient/',include('game.gamesrc.oasis.web.webclient.urls', namespace="webclient")), # Wiki url(r'^notify/', get_notify_pattern()), url(r'^wiki/', get_wiki_pattern()), # Forum (r'^forum/', include('bb_urls', namespace='djangobb')), # Favicon (r'^favicon\.ico$', RedirectView.as_view(url='/media/images/favicon.ico')), # Registration stuff url(r'^roster/', include('roster.urls', namespace='roster')), # Character related stuff. url(r'^character/', include('character.urls', namespace='character')), # Mail stuff url(r'^mail/', include('mail.urls', namespace='mail')), # Search utilities url(r'^search/', include('haystack.urls', namespace='search')), # AJAX stuff url(dajaxice_config.dajaxice_url, include('dajaxice.urls')), url(r'^selectable/', include('selectable.urls')), # Ticket system url(r'^tickets/', include('helpdesk.urls', namespace='helpdesk')), url(r'^$', 'views.page_index', name='index'), ) # 500 Errors: handler500 = 'web.views.custom_500' # This sets up the server if the user want to run the Django # test server (this should normally not be needed). if settings.SERVE_MEDIA: urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), (r'^wiki/([^/]+/)*wiki/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT + '/wiki/'}) ) # PM Extension if (forum_settings.PM_SUPPORT): urlpatterns += patterns('', (r'^mail/', include('mail_urls')), ) if (settings.DEBUG): urlpatterns += patterns('', (r'^%s(?P<path>.*)$' % settings.MEDIA_URL.lstrip('/'), 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )
TaliesinSkye/evennia
wintersoasis-master/web/urls.py
Python
bsd-3-clause
3,320
0.005422
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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. # # @@license_version:1.7@@ import datetime import json import logging import time import cloudstorage from mapreduce import mapreduce_pipeline from pipeline import pipeline from pipeline.common import List from rogerthat.consts import STATS_QUEUE, DEBUG, PIPELINE_BUCKET from rogerthat.dal.service import get_service_identities from rogerthat.settings import get_server_settings from rogerthat.utils import guid, log_offload def start_job(): current_date = datetime.datetime.now() key = 'module_stats_%s_%s' % (current_date.strftime('%Y-%m-%d'), guid()) counter = ModuleStatsPipeline(PIPELINE_BUCKET, key, time.mktime(current_date.timetuple())) task = counter.start(idempotence_key=key, return_task=True) task.add(queue_name=STATS_QUEUE) redirect_url = '%s/status?root=%s' % (counter.base_path, counter.pipeline_id) logging.info('ModuleStats pipeline url: %s', redirect_url) return get_server_settings().baseUrl + redirect_url def mapper(sln_settings): # type: (SolutionSettings) -> GeneratorType for service_identity in get_service_identities(sln_settings.service_user): yield service_identity.app_id, str(sln_settings.modules) def _combine(new_values, previous_combined_values): # type: (list[list[str]], list[dict[str, int]]) -> dict[str, int] combined = {} for stats in previous_combined_values: for module, count in stats.iteritems(): if module not in combined: combined[module] = count else: combined[module] += count for v in new_values: # mapper returns a string modules = eval(v) if isinstance(v, basestring) else v for module in modules: if module not in combined: combined[module] = 1 else: combined[module] += 1 return combined def combiner(key, new_values, previously_combined_values): # type: (str, list[list[str]], list[dict[str, int]]) -> GeneratorType if DEBUG: logging.debug('combiner %s new_values: %s', key, new_values) logging.debug('combiner %s previously_combined_values: %s', key, previously_combined_values) combined = _combine(new_values, previously_combined_values) if DEBUG: logging.debug('combiner %s combined: %s', key, combined) yield combined def reducer(app_id, values): # type: (str, list[dict[str, int]]) -> GeneratorType if DEBUG: logging.info('reducer values: %s', values) combined = _combine([], values) json_line = json.dumps({'app_id': app_id, 'stats': combined}) if DEBUG: logging.debug('reducer %s: %s', app_id, json_line) yield '%s\n' % json_line class ModuleStatsPipeline(pipeline.Pipeline): def run(self, bucket_name, key, current_date): # type: (str, str, long) -> GeneratorType params = { 'mapper_spec': 'solutions.common.job.module_statistics.mapper', 'mapper_params': { 'bucket_name': bucket_name, 'entity_kind': 'solutions.common.models.SolutionSettings', 'filters': [] }, 'combiner_spec': 'solutions.common.job.module_statistics.combiner', 'reducer_spec': 'solutions.common.job.module_statistics.reducer', 'reducer_params': { 'output_writer': { 'bucket_name': bucket_name } }, 'input_reader_spec': 'mapreduce.input_readers.DatastoreInputReader', 'output_writer_spec': 'mapreduce.output_writers.GoogleCloudStorageConsistentOutputWriter', 'shards': 2 if DEBUG else 10 } output = yield mapreduce_pipeline.MapreducePipeline(key, **params) process_output_pipeline = yield ProcessOutputPipeline(output, current_date) with pipeline.After(process_output_pipeline): yield CleanupGoogleCloudStorageFiles(output) def finalized(self): if self.was_aborted: logging.error('%s was aborted', self, _suppress=False) return logging.info('%s was finished', self) class ProcessOutputPipeline(pipeline.Pipeline): def run(self, output, current_date): results = [] for filename in output: results.append((yield ProcessFilePipeline(filename))) yield List(*results) def finalized(self): if DEBUG: logging.debug('ProcessOutputPipeline: self.outputs.default.value = %s', self.outputs.default.value) _, timestamp = self.args # list of dicts with key app_id, value dict of module, amount outputs = self.outputs.default.value # type: list[dict[int, int]] for output in outputs: log_offload.create_log(None, 'oca.active_modules', output, None, timestamp=timestamp) class ProcessFilePipeline(pipeline.Pipeline): def run(self, filename): stats_per_app = {} with cloudstorage.open(filename, "r") as f: for json_line in f: d = json.loads(json_line) stats_per_app[d['app_id']] = d['stats'] if DEBUG: logging.debug('ProcessFilePipeline: %s', stats_per_app) return stats_per_app class CleanupGoogleCloudStorageFiles(pipeline.Pipeline): def run(self, output): for filename in output: cloudstorage.delete(filename)
our-city-app/oca-backend
src/solutions/common/job/module_statistics.py
Python
apache-2.0
6,018
0.001329
""" .. py:attribute:: terminal Exactly like ``bearlibterminal.terminal``, but for any function that takes arguments ``x, y``, ``dx, dy``, or ``x, y, width, height``, you can instead pass a single argument of type :py:class:`Point` (for the first two) or :py:class:`Rect` (for the last). This makes interactions betweeen :py:mod:`geom` and ``bearlibterminal`` much less verbose. Example:: from clubsandwich.blt.nice_terminal import terminal from clubsandwich.geom import Point terminal.open() a = Point(10, 10) b = a + Point(1, 1) terminal.put(a, 'a') terminal.put(b, 'b') terminal.refresh() terminal.read() terminal.close() """ from bearlibterminal import terminal as _terminal from clubsandwich.geom import Point, Rect class NiceTerminal: def __getattr__(self, k): return getattr(_terminal, k) def clear_area(self, *args): if args and isinstance(args[0], Rect): return _terminal.clear_area( args[0].origin.x, args[0].origin.y, args[0].size.width, args[0].size.height) else: return _terminal.clear_area(*args) def crop(self, *args): if args and isinstance(args[0], Rect): return _terminal.crop( args[0].origin.x, args[0].origin.y, args[0].size.width, args[0].size.height) else: return _terminal.crop(*args) def print(self, *args): if isinstance(args[0], Point): return _terminal.print(args[0].x, args[0].y, *args[1:]) else: return _terminal.print(*args) def printf(self, *args): if isinstance(args[0], Point): return _terminal.printf(args[0].x, args[0].y, *args[1:]) else: return _terminal.printf(*args) def put(self, *args): if isinstance(args[0], Point): return _terminal.put(args[0].x, args[0].y, *args[1:]) else: return _terminal.put(*args) def pick(self, *args): if isinstance(args[0], Point): return _terminal.pick(args[0].x, args[0].y, *args[1:]) else: return _terminal.pick(*args) def pick_color(self, *args): if isinstance(args[0], Point): return _terminal.pick_color(args[0].x, args[0].y, *args[1:]) else: return _terminal.pick_color(*args) def pick_bkcolor(self, *args): if isinstance(args[0], Point): return _terminal.pick_bkcolor(args[0].x, args[0].y, *args[1:]) else: return _terminal.pick_bkcolor(*args) def put_ext(self, *args): if isinstance(args[0], Point): return _terminal.put_ext(args[0].x, args[0].y, args[1].x, args[1].y, *args[2:]) else: return _terminal.put_ext(*args) def read_str(self, *args): if isinstance(args[0], Point): return _terminal.read_str(args[0].x, args[0].y, *args[1:]) else: return _terminal.read_str(*args) terminal = NiceTerminal()
irskep/clubsandwich
clubsandwich/blt/nice_terminal.py
Python
mit
3,101
0.000322
"""The test for the threshold sensor platform.""" from homeassistant.const import ATTR_UNIT_OF_MEASUREMENT, STATE_UNKNOWN, TEMP_CELSIUS from homeassistant.setup import async_setup_component async def test_sensor_upper(hass): """Test if source is above threshold.""" config = { "binary_sensor": { "platform": "threshold", "upper": "15", "entity_id": "sensor.test_monitored", } } assert await async_setup_component(hass, "binary_sensor", config) await hass.async_block_till_done() hass.states.async_set( "sensor.test_monitored", 16, {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS} ) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("entity_id") == "sensor.test_monitored" assert state.attributes.get("sensor_value") == 16 assert state.attributes.get("position") == "above" assert state.attributes.get("upper") == float(config["binary_sensor"]["upper"]) assert state.attributes.get("hysteresis") == 0.0 assert state.attributes.get("type") == "upper" assert state.state == "on" hass.states.async_set("sensor.test_monitored", 14) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.state == "off" hass.states.async_set("sensor.test_monitored", 15) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.state == "off" async def test_sensor_lower(hass): """Test if source is below threshold.""" config = { "binary_sensor": { "platform": "threshold", "lower": "15", "entity_id": "sensor.test_monitored", } } assert await async_setup_component(hass, "binary_sensor", config) await hass.async_block_till_done() hass.states.async_set("sensor.test_monitored", 16) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("position") == "above" assert state.attributes.get("lower") == float(config["binary_sensor"]["lower"]) assert state.attributes.get("hysteresis") == 0.0 assert state.attributes.get("type") == "lower" assert state.state == "off" hass.states.async_set("sensor.test_monitored", 14) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.state == "on" async def test_sensor_hysteresis(hass): """Test if source is above threshold using hysteresis.""" config = { "binary_sensor": { "platform": "threshold", "upper": "15", "hysteresis": "2.5", "entity_id": "sensor.test_monitored", } } assert await async_setup_component(hass, "binary_sensor", config) await hass.async_block_till_done() hass.states.async_set("sensor.test_monitored", 20) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("position") == "above" assert state.attributes.get("upper") == float(config["binary_sensor"]["upper"]) assert state.attributes.get("hysteresis") == 2.5 assert state.attributes.get("type") == "upper" assert state.state == "on" hass.states.async_set("sensor.test_monitored", 13) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.state == "on" hass.states.async_set("sensor.test_monitored", 12) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.state == "off" hass.states.async_set("sensor.test_monitored", 17) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.state == "off" hass.states.async_set("sensor.test_monitored", 18) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.state == "on" async def test_sensor_in_range_no_hysteresis(hass): """Test if source is within the range.""" config = { "binary_sensor": { "platform": "threshold", "lower": "10", "upper": "20", "entity_id": "sensor.test_monitored", } } assert await async_setup_component(hass, "binary_sensor", config) await hass.async_block_till_done() hass.states.async_set( "sensor.test_monitored", 16, {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS} ) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("entity_id") == "sensor.test_monitored" assert state.attributes.get("sensor_value") == 16 assert state.attributes.get("position") == "in_range" assert state.attributes.get("lower") == float(config["binary_sensor"]["lower"]) assert state.attributes.get("upper") == float(config["binary_sensor"]["upper"]) assert state.attributes.get("hysteresis") == 0.0 assert state.attributes.get("type") == "range" assert state.state == "on" hass.states.async_set("sensor.test_monitored", 9) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("position") == "below" assert state.state == "off" hass.states.async_set("sensor.test_monitored", 21) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("position") == "above" assert state.state == "off" async def test_sensor_in_range_with_hysteresis(hass): """Test if source is within the range.""" config = { "binary_sensor": { "platform": "threshold", "lower": "10", "upper": "20", "hysteresis": "2", "entity_id": "sensor.test_monitored", } } assert await async_setup_component(hass, "binary_sensor", config) await hass.async_block_till_done() hass.states.async_set( "sensor.test_monitored", 16, {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS} ) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("entity_id") == "sensor.test_monitored" assert state.attributes.get("sensor_value") == 16 assert state.attributes.get("position") == "in_range" assert state.attributes.get("lower") == float(config["binary_sensor"]["lower"]) assert state.attributes.get("upper") == float(config["binary_sensor"]["upper"]) assert state.attributes.get("hysteresis") == float( config["binary_sensor"]["hysteresis"] ) assert state.attributes.get("type") == "range" assert state.state == "on" hass.states.async_set("sensor.test_monitored", 8) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("position") == "in_range" assert state.state == "on" hass.states.async_set("sensor.test_monitored", 7) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("position") == "below" assert state.state == "off" hass.states.async_set("sensor.test_monitored", 12) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("position") == "below" assert state.state == "off" hass.states.async_set("sensor.test_monitored", 13) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("position") == "in_range" assert state.state == "on" hass.states.async_set("sensor.test_monitored", 22) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("position") == "in_range" assert state.state == "on" hass.states.async_set("sensor.test_monitored", 23) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("position") == "above" assert state.state == "off" hass.states.async_set("sensor.test_monitored", 18) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("position") == "above" assert state.state == "off" hass.states.async_set("sensor.test_monitored", 17) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("position") == "in_range" assert state.state == "on" async def test_sensor_in_range_unknown_state(hass): """Test if source is within the range.""" config = { "binary_sensor": { "platform": "threshold", "lower": "10", "upper": "20", "entity_id": "sensor.test_monitored", } } assert await async_setup_component(hass, "binary_sensor", config) await hass.async_block_till_done() hass.states.async_set( "sensor.test_monitored", 16, {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS} ) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("entity_id") == "sensor.test_monitored" assert state.attributes.get("sensor_value") == 16 assert state.attributes.get("position") == "in_range" assert state.attributes.get("lower") == float(config["binary_sensor"]["lower"]) assert state.attributes.get("upper") == float(config["binary_sensor"]["upper"]) assert state.attributes.get("hysteresis") == 0.0 assert state.attributes.get("type") == "range" assert state.state == "on" hass.states.async_set("sensor.test_monitored", STATE_UNKNOWN) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("position") == "unknown" assert state.state == "off" async def test_sensor_lower_zero_threshold(hass): """Test if a lower threshold of zero is set.""" config = { "binary_sensor": { "platform": "threshold", "lower": "0", "entity_id": "sensor.test_monitored", } } assert await async_setup_component(hass, "binary_sensor", config) await hass.async_block_till_done() hass.states.async_set("sensor.test_monitored", 16) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("type") == "lower" assert state.attributes.get("lower") == float(config["binary_sensor"]["lower"]) assert state.state == "off" hass.states.async_set("sensor.test_monitored", -3) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.state == "on" async def test_sensor_upper_zero_threshold(hass): """Test if an upper threshold of zero is set.""" config = { "binary_sensor": { "platform": "threshold", "upper": "0", "entity_id": "sensor.test_monitored", } } assert await async_setup_component(hass, "binary_sensor", config) await hass.async_block_till_done() hass.states.async_set("sensor.test_monitored", -10) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("type") == "upper" assert state.attributes.get("upper") == float(config["binary_sensor"]["upper"]) assert state.state == "off" hass.states.async_set("sensor.test_monitored", 2) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.state == "on"
kennedyshead/home-assistant
tests/components/threshold/test_binary_sensor.py
Python
apache-2.0
11,914
0.001007
import cPickle as pickle import os users = list(pickle.load(file('users.pickle'))) pickle.dump(users, open("users.list.pickle.tmp", "wb")) os.rename("users.list.pickle.tmp", "users.list.pickle")
fgolemo/SocWeb-Reddit-Crawler
usersToFile.py
Python
mit
195
0.005128
# -*- coding: utf-8 -*- """ openload.io urlresolver plugin Copyright (C) 2015 tknorris This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import re import urllib2 from HTMLParser import HTMLParser from urlresolver9 import common from urlresolver9.resolver import ResolverError net = common.Net() def get_media_url(url): try: HTTP_HEADER = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Referer': url} # 'Connection': 'keep-alive' html = net.http_GET(url, headers=HTTP_HEADER).content hiddenurl = HTMLParser().unescape(re.search('hiddenurl">(.+?)<\/span>', html, re.IGNORECASE).group(1)) s = [] for i in hiddenurl: j = ord(i) if (j >= 33 & j <= 126): s.append(chr(33 + ((j + 14) % 94))) else: s.append(chr(j)) res = ''.join(s) videoUrl = 'https://openload.co/stream/{0}?mime=true'.format(res) dtext = videoUrl.replace('https', 'http') headers = {'User-Agent': HTTP_HEADER['User-Agent']} req = urllib2.Request(dtext, None, headers) res = urllib2.urlopen(req) videourl = res.geturl() res.close() return videourl except Exception as e: common.log_utils.log_debug('Exception during openload resolve parse: %s' % e) raise raise ResolverError('Unable to resolve openload.io link. Filelink not found.')
mrknow/filmkodi
script.mrknow.urlresolver/lib/urlresolver9/plugins/ol_gmu.py
Python
apache-2.0
2,291
0.003492
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.utils import timezone from crm.models import Person from geocodable.models import LocationAlias import uuid class Event(models.Model): name = models.CharField(max_length=200) timestamp = models.DateTimeField() end_timestamp = models.DateTimeField() attendees = models.ManyToManyField(Person, related_name='events', blank=True) uid = models.CharField(max_length=200, blank=True) location = models.ForeignKey(LocationAlias, default=None, blank=True, null=True) instance_id = models.CharField(max_length=200, blank=True) @property def geo(self): return {'lat': self.lat, 'lng': self.lng} @property def lat(self): if self.location is not None: return self.location.lat else: return None @property def lng(self): if self.location is not None: return self.location.lng else: return None def __unicode__(self): return "%s (%s)"%(self.name, self.timestamp)
tdfischer/organizer
events/models.py
Python
agpl-3.0
1,124
0.003559
# Double pendulum formula translated from the C code at # http://www.physics.usyd.edu.au/~wheat/dpend_html/solve_dpend.c from numpy import sin, cos import numpy as np import matplotlib.pyplot as plt import scipy.integrate as integrate import matplotlib.animation as animation G = 9.8 # acceleration due to gravity, in m/s^2 L1 = 1.0 # length of pendulum 1 in m L2 = 1.0 # length of pendulum 2 in m M1 = 1.0 # mass of pendulum 1 in kg M2 = 1.0 # mass of pendulum 2 in kg def derivs(state, t): dydx = np.zeros_like(state) dydx[0] = state[1] del_ = state[2] - state[0] den1 = (M1 + M2)*L1 - M2*L1*cos(del_)*cos(del_) dydx[1] = (M2*L1*state[1]*state[1]*sin(del_)*cos(del_) + M2*G*sin(state[2])*cos(del_) + M2*L2*state[3]*state[3]*sin(del_) - (M1 + M2)*G*sin(state[0]))/den1 dydx[2] = state[3] den2 = (L2/L1)*den1 dydx[3] = (-M2*L2*state[3]*state[3]*sin(del_)*cos(del_) + (M1 + M2)*G*sin(state[0])*cos(del_) - (M1 + M2)*L1*state[1]*state[1]*sin(del_) - (M1 + M2)*G*sin(state[2]))/den2 return dydx # create a time array from 0..100 sampled at 0.05 second steps dt = 0.05 t = np.arange(0.0, 20, dt) # th1 and th2 are the initial angles (degrees) # w10 and w20 are the initial angular velocities (degrees per second) th1 = 120.0 w1 = 0.0 th2 = -10.0 w2 = 0.0 # initial state state = np.radians([th1, w1, th2, w2]) # integrate your ODE using scipy.integrate. y = integrate.odeint(derivs, state, t) x1 = L1*sin(y[:, 0]) y1 = -L1*cos(y[:, 0]) x2 = L2*sin(y[:, 2]) + x1 y2 = -L2*cos(y[:, 2]) + y1 fig = plt.figure() ax = fig.add_subplot(111, autoscale_on=False, xlim=(-2, 2), ylim=(-2, 2)) ax.set_aspect('equal') ax.grid() line, = ax.plot([], [], 'o-', lw=2) time_template = 'time = %.1fs' time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes) def init(): line.set_data([], []) time_text.set_text('') return line, time_text def animate(i): thisx = [0, x1[i], x2[i]] thisy = [0, y1[i], y2[i]] line.set_data(thisx, thisy) time_text.set_text(time_template % (i*dt)) return line, time_text ani = animation.FuncAnimation(fig, animate, np.arange(1, len(y)), interval=25, blit=True, init_func=init) #ani.save('double_pendulum.mp4', fps=15) plt.show()
bundgus/python-playground
matplotlib-playground/examples/animation/double_pendulum_animated.py
Python
mit
2,354
0.001274
#!/usr/bin/env python # -*- coding: utf-8 -*- # # || ____ _ __ # +------+ / __ )(_) /_______________ _____ ___ # | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ # # Copyright (C) 2011-2013 Bitcraze AB # # Crazyflie Nano Quadcopter Client # # 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-1301, USA. """ Attitude indicator widget. """ import sys from PyQt4 import QtGui, QtCore __author__ = 'Bitcraze AB' __all__ = ['AttitudeIndicator'] class AttitudeIndicator(QtGui.QWidget): """Widget for showing attitude""" def __init__(self): super(AttitudeIndicator, self).__init__() self.roll = 0 self.pitch = 0 self.hover = False self.hoverASL = 0.0 self.hoverTargetASL = 0.0 self.setMinimumSize(30, 30) # self.setMaximumSize(240,240) def setRoll(self, roll): self.roll = roll self.repaint() def setPitch(self, pitch): self.pitch = pitch self.repaint() def setHover(self, target): self.hoverTargetASL = target self.hover = target > 0 self.repaint() def setBaro(self, asl): self.hoverASL = asl self.repaint() def setRollPitch(self, roll, pitch): self.roll = roll self.pitch = pitch self.repaint() def paintEvent(self, e): qp = QtGui.QPainter() qp.begin(self) self.drawWidget(qp) qp.end() def drawWidget(self, qp): size = self.size() w = size.width() h = size.height() qp.translate(w / 2, h / 2) qp.rotate(self.roll) qp.translate(0, (self.pitch * h) / 50) qp.translate(-w / 2, -h / 2) qp.setRenderHint(qp.Antialiasing) font = QtGui.QFont('Serif', 7, QtGui.QFont.Light) qp.setFont(font) # Draw the blue qp.setPen(QtGui.QColor(0, 61, 144)) qp.setBrush(QtGui.QColor(0, 61, 144)) qp.drawRect(-w, h / 2, 3 * w, -3 * h) # Draw the marron qp.setPen(QtGui.QColor(59, 41, 39)) qp.setBrush(QtGui.QColor(59, 41, 39)) qp.drawRect(-w, h / 2, 3 * w, 3 * h) pen = QtGui.QPen(QtGui.QColor(255, 255, 255), 1.5, QtCore.Qt.SolidLine) qp.setPen(pen) qp.drawLine(-w, h / 2, 3 * w, h / 2) # Drawing pitch lines for ofset in [-180, 0, 180]: for i in range(-900, 900, 25): pos = (((i / 10.0) + 25 + ofset) * h / 50.0) if i % 100 == 0: length = 0.35 * w if i != 0: if ofset == 0: qp.drawText((w / 2) + (length / 2) + (w * 0.06), pos, "{}".format(-i / 10)) qp.drawText((w / 2) - (length / 2) - (w * 0.08), pos, "{}".format(-i / 10)) else: qp.drawText((w / 2) + (length / 2) + (w * 0.06), pos, "{}".format(i / 10)) qp.drawText((w / 2) - (length / 2) - (w * 0.08), pos, "{}".format(i / 10)) elif i % 50 == 0: length = 0.2 * w else: length = 0.1 * w qp.drawLine((w / 2) - (length / 2), pos, (w / 2) + (length / 2), pos) qp.setWorldMatrixEnabled(False) pen = QtGui.QPen(QtGui.QColor(0, 0, 0), 2, QtCore.Qt.SolidLine) qp.setBrush(QtGui.QColor(0, 0, 0)) qp.setPen(pen) qp.drawLine(0, h / 2, w, h / 2) # Draw Hover vs Target qp.setWorldMatrixEnabled(False) pen = QtGui.QPen(QtGui.QColor(255, 255, 255), 2, QtCore.Qt.SolidLine) qp.setBrush(QtGui.QColor(255, 255, 255)) qp.setPen(pen) fh = max(7, h / 50) font = QtGui.QFont('Sans', fh, QtGui.QFont.Light) qp.setFont(font) qp.resetTransform() qp.translate(0, h / 2) if not self.hover: # asl qp.drawText(w - fh * 10, fh / 2, str(round(self.hoverASL, 2))) if self.hover: # target asl (center) qp.drawText( w - fh * 10, fh / 2, str(round(self.hoverTargetASL, 2))) diff = round(self.hoverASL - self.hoverTargetASL, 2) pos_y = -h / 6 * diff # cap to +- 2.8m if diff < -2.8: pos_y = -h / 6 * -2.8 elif diff > 2.8: pos_y = -h / 6 * 2.8 else: pos_y = -h / 6 * diff # difference from target (moves up and down +- 2.8m) qp.drawText(w - fh * 3.8, pos_y + fh / 2, str(diff)) # vertical line qp.drawLine(w - fh * 4.5, 0, w - fh * 4.5, pos_y) # left horizontal line qp.drawLine(w - fh * 4.7, 0, w - fh * 4.5, 0) # right horizontal line qp.drawLine(w - fh * 4.2, pos_y, w - fh * 4.5, pos_y) if __name__ == "__main__": class Example(QtGui.QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def updatePitch(self, pitch): self.wid.setPitch(pitch - 90) def updateRoll(self, roll): self.wid.setRoll((roll / 10.0) - 180.0) def updateTarget(self, target): self.wid.setHover(500 + target / 10.) def updateBaro(self, asl): self.wid.setBaro(500 + asl / 10.) def initUI(self): vbox = QtGui.QVBoxLayout() sld = QtGui.QSlider(QtCore.Qt.Horizontal, self) sld.setFocusPolicy(QtCore.Qt.NoFocus) sld.setRange(0, 3600) sld.setValue(1800) vbox.addWidget(sld) self.wid = AttitudeIndicator() sld.valueChanged[int].connect(self.updateRoll) vbox.addWidget(self.wid) hbox = QtGui.QHBoxLayout() hbox.addLayout(vbox) sldPitch = QtGui.QSlider(QtCore.Qt.Vertical, self) sldPitch.setFocusPolicy(QtCore.Qt.NoFocus) sldPitch.setRange(0, 180) sldPitch.setValue(90) sldPitch.valueChanged[int].connect(self.updatePitch) hbox.addWidget(sldPitch) sldASL = QtGui.QSlider(QtCore.Qt.Vertical, self) sldASL.setFocusPolicy(QtCore.Qt.NoFocus) sldASL.setRange(-200, 200) sldASL.setValue(0) sldASL.valueChanged[int].connect(self.updateBaro) sldT = QtGui.QSlider(QtCore.Qt.Vertical, self) sldT.setFocusPolicy(QtCore.Qt.NoFocus) sldT.setRange(-200, 200) sldT.setValue(0) sldT.valueChanged[int].connect(self.updateTarget) hbox.addWidget(sldT) hbox.addWidget(sldASL) self.setLayout(hbox) self.setGeometry(50, 50, 510, 510) self.setWindowTitle('Attitude Indicator') self.show() def changeValue(self, value): self.c.updateBW.emit(value) self.wid.repaint() def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main()
manojngb/Crazyfly_simple_lift
src/cfclient/ui/widgets/ai.py
Python
gpl-2.0
8,202
0
#!/usr/bin/env python # by teknohog # Python wrapper for Xilinx Serial Miner # Host/user configuration is NOT USED in ltctestmode.py ... # host = "localhost" # Stratum Proxy alternative # user = "username.1" # Your worker goes here # password = "password" # Worker password, NOT your account password # http_port = "8332" # Getwork port (stratum) # CONFIGURATION - CHANGE THIS (eg try COM1, COM2, COM3, COM4 etc) serial_port = "COM4" # serial_port = "/dev/ttyUSB0" # raspberry pi # CONFIGURATION - how often to refresh work - reduced for test askrate = 2 ############################################################################### from jsonrpc import ServiceProxy from time import ctime, sleep, time from serial import Serial from threading import Thread, Event from Queue import Queue import sys dynclock = 0 dynclock_hex = "0000" def stats(count, starttime): # BTC 2**32 hashes per share (difficulty 1) # mhshare = 4294.967296 # LTC 2**32 / 2048 hashes per share (difficulty 32) # khshare = 2097.152 # CHECK THIS !! khshare = 65.536 * writer.diff s = sum(count) tdelta = time() - starttime rate = s * khshare / tdelta # This is only a rough estimate of the true hash rate, # particularly when the number of events is low. However, since # the events follow a Poisson distribution, we can estimate the # standard deviation (sqrt(n) for n events). Thus we get some idea # on how rough an estimate this is. # s should always be positive when this function is called, but # checking for robustness anyway if s > 0: stddev = rate / s**0.5 else: stddev = 0 return "[%i accepted, %i failed, %.2f +/- %.2f khash/s]" % (count[0], count[1], rate, stddev) class Reader(Thread): def __init__(self): Thread.__init__(self) self.daemon = True # flush the input buffer ser.read(1000) def run(self): while True: nonce = ser.read(4) if len(nonce) == 4: # Keep this order, because writer.block will be # updated due to the golden event. submitter = Submitter(writer.block, nonce) submitter.start() golden.set() class Writer(Thread): def __init__(self,dynclock_hex): Thread.__init__(self) # Keep something sensible available while waiting for the # first getwork self.block = "0" * 256 self.target = "f" * 56 + "ff070000" # diff=32 for testmode self.diff = 32 # testmode self.dynclock_hex = dynclock_hex self.daemon = True self.go = True self.infile = open("../../scripts/test_data.txt","r") self.nonce = 0 self.nonce_tested = 0 self.nonce_ok = 0 self.nonce_fail = 0 def run(self): while self.go: try: # work = bitcoin.getwork() # self.block = work['data'] # self.target = work['target'] print "Tested", self.nonce_tested, " passed", self.nonce_ok, " fail", self.nonce_fail, " unmatched", self.nonce_tested - self.nonce_ok - self.nonce_fail self.line = self.infile.readline() if (len(self.line) != 257): print "EOF on test data" # Or its an error, but let's not be worrysome # quit() # Except it doesn't ... self.go = False # Terminating threads is a bit tricksy break self.nonce_tested = self.nonce_tested + 1 self.block = self.line.rstrip() # Hard-code a diff=32 target for test work # Replace MSB 16 bits of target with clock (NB its reversed) self.target = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff07" + self.dynclock_hex self.dynclock_hex = "0000" # Once only # print("block old " + self.block) # We need to subtract a few from the nonces in order to match (why?) nonce_bin = self.block.decode('hex')[79:75:-1] self.nonce = int(nonce_bin.encode('hex'), 16) # print "nonce old =", self.nonce nonce_new = self.nonce - 50 if (nonce_new < 0): nonce_new = 0 # print "nonce new =", nonce_new nonce_hex = "{0:08x}".format(nonce_new) # print "encoded = ", nonce_hex nonce_hex_rev = nonce_hex[6:8]+nonce_hex[4:6]+nonce_hex[2:4]+nonce_hex[0:2] # print "reversed = ", nonce_hex_rev self.block = self.block[0:152]+nonce_hex_rev+self.block[160:] # print("block new " + self.block) except: print("RPC getwork error") # In this case, keep crunching with the old data. It will get # stale at some point, but it's better than doing nothing. # print("block " + self.block + " target " + self.target) # DEBUG sdiff = self.target.decode('hex')[31:27:-1] intTarget = int(sdiff.encode('hex'), 16) if (intTarget < 1): print "WARNING zero target", intTarget print "target", self.target print("sdiff", sdiff) # NB Need brackets here else prints binary self.target = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f0000" else: newdiff = 65536 / intTarget if (self.diff != newdiff): print "New target diff =", newdiff self.diff = newdiff # print("Sending data to FPGA") # DEBUG # for litecoin send 80 bytes of the 128 byte data plus 4 bytes of 32 byte target payload = self.target.decode('hex')[31:27:-1] + self.block.decode('hex')[79::-1] # TEST HASH, this should match on nonce 0000318f # NB The pool will REJECT this share as it did not send the data... # UNCOMMENT the following two lines for testing... # test_payload ="000000014eb4577c82473a069ca0e95703254da62e94d1902ab6f0eae8b1e718565775af20c9ba6ced48fc9915ef01c54da2200090801b2d2afc406264d491c7dfc7b0b251e91f141b44717e00310000ff070000" # payload = test_payload.decode('hex')[::-1] # This is probably best commented out unless debugging ... print("Test " + payload.encode('hex_codec')) # DEBUG ser.write(payload) result = golden.wait(askrate) if result: golden.clear() class Submitter(Thread): def __init__(self, block, nonce): Thread.__init__(self) self.block = block self.nonce = nonce def run(self): # This thread will be created upon every submit, as they may # come in sooner than the submits finish. # print("Block found on " + ctime()) print("Share found on " + ctime() + " nonce " + self.nonce.encode('hex_codec')) if (int(self.nonce.encode('hex_codec'),16) != writer.nonce): print "... ERROR expected nonce", hex(writer.nonce) writer.nonce_fail = writer.nonce_fail + 1 else: print "... CORRECT" writer.nonce_ok = writer.nonce_ok + 1 hrnonce = self.nonce[::-1].encode('hex') data = self.block[:152] + hrnonce + self.block[160:] try: # result = bitcoin.getwork(data) result = False # print("Upstream result: " + str(result)) # Pointless in test mode except: print("RPC send error") # a sensible boolean for stats result = False results_queue.put(result) class Display_stats(Thread): def __init__(self): Thread.__init__(self) self.count = [0, 0] self.starttime = time() self.daemon = True print("Miner started on " + ctime()) def run(self): while True: result = results_queue.get() if result: self.count[0] += 1 else: self.count[1] += 1 # print(stats(self.count, self.starttime)) # Pointless in test mode results_queue.task_done() # ======= main ======= # Process command line if (len(sys.argv) > 2): print "ERROR too many command line arguments" print "usage:", sys.argv[0], "clockfreq" quit() if (len(sys.argv) == 1): print "WARNING no clockfreq supplied, not setting freq" else: # TODO ought to check the value is a valid integer try: dynclock = int(sys.argv[1]) except: print "ERROR parsing clock frequency on command line, needs to be an integer" print "usage:", sys.argv[0], "clockfreq" quit() if (dynclock==0): print "ERROR parsing clock frequency on command line, cannot be zero" print "usage:", sys.argv[0], "clockfreq" quit() if (dynclock>254): # Its 254 since onescomplement(255) is zero, which is not allowed print "ERROR parsing clock frequency on command line, max 254" print "usage:", sys.argv[0], "clockfreq" quit() if (dynclock<25): print "ERROR use at least 25 for clock (the DCM can lock up for low values)" print "usage:", sys.argv[0], "clockfreq" quit() dynclock_hex = "{0:04x}".format((255-dynclock)*256+dynclock) # both value and ones-complement print "INFO will set clock to", dynclock, "MHz hex", dynclock_hex golden = Event() # url = 'http://' + user + ':' + password + '@' + host + ':' + http_port # bitcoin = ServiceProxy(url) results_queue = Queue() # default is 8 bit no parity which is fine ... # http://pyserial.sourceforge.net/shortintro.html#opening-serial-ports ser = Serial(serial_port, 115200, timeout=askrate) reader = Reader() writer = Writer(dynclock_hex) disp = Display_stats() reader.start() writer.start() disp.start() try: while writer.go: # Threads are generally hard to interrupt. So they are left # running as daemons, and we do something simple here that can # be easily terminated to bring down the entire script. sleep(1) except KeyboardInterrupt: print("Terminated")
ychaim/FPGA-Litecoin-Miner
experimental/LX150-EIGHT-B/ltcminer-test-dynclock.py
Python
gpl-3.0
8,949
0.027154
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 30, transform = "RelativeDifference", sigma = 0.0, exog_count = 20, ar_order = 0);
antoinecarme/pyaf
tests/artificial/transf_RelativeDifference/trend_PolyTrend/cycle_30/ar_/test_artificial_32_RelativeDifference_PolyTrend_30__20.py
Python
bsd-3-clause
273
0.084249
import logging import os from autotest.client.shared import error, utils from virttest import data_dir, utils_test def umount_fs(mountpoint): if os.path.ismount(mountpoint): result = utils.run("umount -l %s" % mountpoint, ignore_status=True) if result.exit_status: logging.debug("Umount %s failed", mountpoint) return False logging.debug("Umount %s successfully", mountpoint) return True def run_guestmount(test, params, env): """ Test libguestfs tool guestmount. """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) if vm.is_alive(): vm.destroy() # Create a file to vm with guestmount content = "This is file for guestmount test." path = params.get("gm_tempfile", "/home/gm_tmp") mountpoint = os.path.join(data_dir.get_tmp_dir(), "mountpoint") status_error = "yes" == params.get("status_error", "yes") readonly = "no" == params.get("gm_readonly", "no") special_mount = "yes" == params.get("gm_mount", "no") vt = utils_test.libguestfs.VirtTools(vm, params) if special_mount: # Get root filesystem before test params['libvirt_domain'] = params.get("main_vm") params['gf_inspector'] = True gf = utils_test.libguestfs.GuestfishTools(params) roots, rootfs = gf.get_root() gf.close_session() if roots is False: raise error.TestError("Can not get root filesystem " "in guestfish before test") logging.info("Root filesystem is:%s", rootfs) params['special_mountpoints'] = [rootfs] writes, writeo = vt.write_file_with_guestmount(mountpoint, path, content) if umount_fs(mountpoint) is False: logging.error("Umount vm's filesytem failed.") if status_error: if writes: if readonly: raise error.TestFail("Write file to readonly mounted " "filesystem successfully.Not expected.") else: raise error.TestFail("Write file with guestmount " "successfully.Not expected.") else: if not writes: raise error.TestFail("Write file to mounted filesystem failed.")
kylazhang/virt-test
libguestfs/tests/guestmount.py
Python
gpl-2.0
2,277
0
import json import logging import inspect from .decorators import pipeline_functions, register_pipeline from indra.statements import get_statement_by_name, Statement logger = logging.getLogger(__name__) class AssemblyPipeline(): """An assembly pipeline that runs the specified steps on a given set of statements. Ways to initialize and run the pipeline (examples assume you have a list of INDRA Statements stored in the `stmts` variable.) >>> from indra.statements import * >>> map2k1 = Agent('MAP2K1', db_refs={'HGNC': '6840'}) >>> mapk1 = Agent('MAPK1', db_refs={'HGNC': '6871'}) >>> braf = Agent('BRAF') >>> stmts = [Phosphorylation(map2k1, mapk1, 'T', '185'), ... Phosphorylation(braf, map2k1)] 1) Provide a JSON file containing the steps, then use the classmethod `from_json_file`, and run it with the `run` method on a list of statements. This option allows storing pipeline versions in a separate file and reproducing the same results. All functions referenced in the JSON file have to be registered with the @register_pipeline decorator. >>> import os >>> path_this = os.path.dirname(os.path.abspath(__file__)) >>> filename = os.path.abspath( ... os.path.join(path_this, '..', 'tests', 'pipeline_test.json')) >>> ap = AssemblyPipeline.from_json_file(filename) >>> assembled_stmts = ap.run(stmts) 2) Initialize a pipeline with a list of steps and run it with the `run` method on a list of statements. All functions referenced in steps have to be registered with the @register_pipeline decorator. >>> steps = [ ... {"function": "filter_no_hypothesis"}, ... {"function": "filter_grounded_only", ... "kwargs": {"score_threshold": 0.8}} ... ] >>> ap = AssemblyPipeline(steps) >>> assembled_stmts = ap.run(stmts) 3) Initialize an empty pipeline and append/insert the steps one by one. Provide a function and its args and kwargs. For arguments that require calling a different function, use the RunnableArgument class. All functions referenced here have to be either imported and passed as function objects or registered with the @register_pipeline decorator and passed as function names (strings). The pipeline built this way can be optionally saved into a JSON file. (Note that this example requires indra_world to be installed.) >>> from indra.tools.assemble_corpus import * >>> from indra_world.ontology import load_world_ontology >>> from indra_world.belief import get_eidos_scorer >>> ap = AssemblyPipeline() >>> ap.append(filter_no_hypothesis) >>> ap.append(filter_grounded_only) >>> ap.append(run_preassembly, ... belief_scorer=RunnableArgument(get_eidos_scorer), ... ontology=RunnableArgument(load_world_ontology)) >>> assembled_stmts = ap.run(stmts) >>> ap.to_json_file('filename.json') Parameters ---------- steps : list[dict] A list of dictionaries representing steps in the pipeline. Each step should have a 'function' key and, if appropriate, 'args' and 'kwargs' keys. Arguments can be simple values (strings, integers, booleans, lists, etc.) or can be functions themselves. In case an argument is a function or a result of another function, it should also be represented as a dictionary of a similar structure. If a function itself is an argument (and not its result), the dictionary should contain a key-value pair {'no_run': True}. If an argument is a type of a statement, it should be represented as a dictionary {'stmt_type': <name of a statement type>}. """ def __init__(self, steps=None): # This import is here to avoid circular imports # It is enough to import one function to get all registered functions from indra.tools.assemble_corpus import filter_grounded_only from indra.ontology.bio import bio_ontology from indra.preassembler.grounding_mapper.gilda import ground_statements from indra.preassembler.custom_preassembly import agent_grounding_matches self.steps = steps if steps else [] @classmethod def from_json_file(cls, filename): """Create an instance of AssemblyPipeline from a JSON file with steps.""" with open(filename, 'r') as f: steps = json.load(f) ap = AssemblyPipeline(steps) return ap def to_json_file(self, filename): """Save AssemblyPipeline to a JSON file.""" with open(filename, 'w') as f: json.dump(self.steps, f, indent=1) def run(self, statements, **kwargs): """Run all steps of the pipeline. Parameters ---------- statements : list[indra.statements.Statement] A list of INDRA Statements to run the pipeline on. **kwargs : kwargs It is recommended to define all arguments for the steps functions in the steps definition, but it is also possible to provide some external objects (if it is not possible to provide them as a step argument) as kwargs to the entire pipeline here. One should be cautious to avoid kwargs name clashes between multiple functions (this value will be provided to all functions that expect an argument with the same name). To overwrite this value in other functions, provide it explicitly in the corresponding steps kwargs. Returns ------- list[indra.statements.Statement] The list of INDRA Statements resulting from running the pipeline on the list of input Statements. """ logger.info('Running the pipeline') for step in self.steps: statements = self.run_function(step, statements, **kwargs) return statements def append(self, func, *args, **kwargs): """Append a step to the end of the pipeline. Args and kwargs here can be of any type. All functions referenced here have to be either imported and passed as function objects or registered with @register_pipeline decorator and passed as function names (strings). For arguments that require calling a different function, use RunnableArgument class. Parameters ---------- func : str or function A function or the string name of a function to add to the pipeline. args : args Args that are passed to func when calling it. kwargs : kwargs Kwargs that are passed to func when calling it. """ if inspect.isfunction(func): func_name = func.__name__ if func_name not in pipeline_functions: register_pipeline(func) elif isinstance(func, str): func_name = func else: raise TypeError('Should be a function object or a string') new_step = self.create_new_step(func_name, *args, **kwargs) self.steps.append(new_step) def insert(self, ix, func, *args, **kwargs): """Insert a step to any position in the pipeline. Args and kwargs here can be of any type. All functions referenced here have to be either imported and passed as function objects or registered with @register_pipeline decorator and passed as function names (strings). For arguments that require calling a different function, use RunnableArgument class. Parameters ---------- func : str or function A function or the string name of a function to add to the pipeline. args : args Args that are passed to func when calling it. kwargs : kwargs Kwargs that are passed to func when calling it. """ if inspect.isfunction(func): func_name = func.__name__ if func_name not in pipeline_functions: register_pipeline(func) elif isinstance(func, str): func_name = func else: raise TypeError('Should be a function object or a string') new_step = self.create_new_step(func_name, *args, **kwargs) self.steps.insert(ix, new_step) def create_new_step(self, func_name, *args, **kwargs): """Create a dictionary representing a new step in the pipeline. Parameters ---------- func_name : str The string name of a function to create as a step. args : args Args that are passed to the function when calling it. kwargs : kwargs Kwargs that are passed to the function when calling it. Returns ------- dict A dict structure representing a step in the pipeline. """ assert self.get_function_from_name(func_name) new_step = {'function': func_name} if args: new_step['args'] = [jsonify_arg_input(arg) for arg in args] if kwargs: new_step['kwargs'] = { k: jsonify_arg_input(v) for (k, v) in kwargs.items()} return new_step @staticmethod def get_function_parameters(func_dict): """Retrieve a function name and arguments from function dictionary. Parameters ---------- func_dict : dict A dict structure representing a function and its args and kwargs. Returns ------- tuple of str, list and dict A tuple with the following elements: the name of the function, the args of the function, and the kwargs of the function. """ func_name = func_dict['function'] args = func_dict.get('args', []) kwargs = func_dict.get('kwargs', {}) return func_name, args, kwargs @staticmethod def get_function_from_name(name): """Return a function object by name if available or raise exception. Parameters ---------- name : str The name of the function. Returns ------- function The function that was found based on its name. If not found, a NotRegisteredFunctionError is raised. """ if name in pipeline_functions: return pipeline_functions[name] raise NotRegisteredFunctionError('%s is not registered' % name) @staticmethod def run_simple_function(func, *args, **kwargs): """Run a simple function and return the result. Simple here means a function all arguments of which are simple values (do not require extra function calls). Parameters ---------- func : function The function to call. args : args Args that are passed to the function when calling it. kwargs : kwargs Kwargs that are passed to the function when calling it. Returns ------- object Any value that the given function returns. """ statements = kwargs.pop('statements', None) if statements is not None: return func(statements, *args, **kwargs) return func(*args, **kwargs) def run_function(self, func_dict, statements=None, **kwargs): """Run a given function and return the results. For each of the arguments, if it requires an extra function call, recursively call the functions until we get a simple function. Parameters ---------- func_dict : dict A dict representing the function to call, its args and kwargs. args : args Args that are passed to the function when calling it. kwargs : kwargs Kwargs that are passed to the function when calling it. Returns ------- object Any value that the given function returns. """ func_name, func_args, func_kwargs = self.get_function_parameters( func_dict) func = self.get_function_from_name(func_name) logger.info('Calling %s' % func_name) new_args = [] new_kwargs = {} for arg in func_args: arg_value = self.get_argument_value(arg) new_args.append(arg_value) for k, v in func_kwargs.items(): kwarg_value = self.get_argument_value(v) new_kwargs[k] = kwarg_value if statements is not None: new_kwargs['statements'] = statements if kwargs: for k, v in kwargs.items(): if k not in new_kwargs and k in inspect.getargspec(func).args: new_kwargs[k] = v return self.run_simple_function(func, *new_args, **new_kwargs) @staticmethod def is_function(argument, keyword='function'): """Check if an argument should be converted to a specific object type, e.g. a function or a statement type. Parameters ---------- argument : dict or other object The argument is a dict, its keyword entry is checked, and if it is there, we return True, otherwise we return False. keyword : Optional[str] The keyword to check if it's there if the argument is a dict. Default: function """ if not isinstance(argument, dict): return False if keyword not in argument: return False return True def get_argument_value(self, arg_json): """Get a value of an argument from its json version.""" if self.is_function(arg_json, 'function'): # Argument is a function if arg_json.get('no_run', False): value = self.get_function_from_name(arg_json['function']) # Argument is a result of a function else: value = self.run_function(arg_json) # Argument is a statement type elif self.is_function(arg_json, 'stmt_type'): value = get_statement_by_name(arg_json.get('stmt_type')) # Argument is a simple value (str, int, boolean, etc.) else: value = arg_json return value def __len__(self): return len(self.steps) def __iter__(self): return iter(self.steps) class NotRegisteredFunctionError(Exception): pass class RunnableArgument(): """Class representing arguments generated by calling a function. RunnableArguments should be used as args or kwargs in AssemblyPipeline `append` and `insert` methods. Parameters ---------- func : str or function A function or a name of a function to be called to generate argument value. """ def __init__(self, func, *args, **kwargs): if inspect.isfunction(func): self.func_name = func.__name__ if self.func_name not in pipeline_functions: register_pipeline(func) elif isinstance(func, str): self.func_name = func else: raise TypeError('Should be a function object or a string') self.args = args self.kwargs = kwargs def to_json(self): """Jsonify to standard AssemblyPipeline step format.""" json_dict = {'function': self.func_name} new_args = [] new_kwargs = {} for arg in self.args: new_args.append(jsonify_arg_input(arg)) for k, v in self.kwargs.items(): new_kwargs[k] = jsonify_arg_input(v) if new_args: json_dict['args'] = new_args if new_kwargs: json_dict['kwargs'] = new_kwargs return json_dict def jsonify_arg_input(arg): """Jsonify user input (in AssemblyPipeline `append` and `insert` methods) into a standard step json.""" if isinstance(arg, RunnableArgument): return arg.to_json() # If a function object or name of a function is provided, we assume it # does not have to be run (function itself is argument). if inspect.isfunction(arg): func_name = arg.__name__ if func_name not in pipeline_functions: register_pipeline(arg) return {'function': func_name, 'no_run': True} if isinstance(arg, str) and arg in pipeline_functions: return {'function': arg, 'no_run': True} # For some functions Statement type has to be argument if inspect.isclass(arg) and issubclass(arg, Statement): return {'stmt_type': arg.__name__} # Argument is a simple value and can be stored as provided return arg
johnbachman/indra
indra/pipeline/pipeline.py
Python
bsd-2-clause
16,636
0.00006
"""Mode which allows the player to select another mode to run.""" from mpf.core.utility_functions import Util from mpf.core.mode import Mode class Carousel(Mode): """Mode which allows the player to select another mode to run.""" __slots__ = ["_all_items", "_items", "_select_item_events", "_next_item_events", "_previous_item_events", "_highlighted_item_index", "_done", "_block_events", "_release_events", "_is_blocking"] def __init__(self, *args, **kwargs): """Initialise carousel mode.""" self._all_items = None self._items = None self._select_item_events = None self._next_item_events = None self._previous_item_events = None self._highlighted_item_index = None self._block_events = None self._release_events = None self._is_blocking = None self._done = None super().__init__(*args, **kwargs) def mode_init(self): """Initialise mode and read all settings from config.""" super().mode_init() mode_settings = self.config.get("mode_settings", []) self._all_items = [] for item in Util.string_to_event_list(mode_settings.get("selectable_items", "")): placeholder = self.machine.placeholder_manager.parse_conditional_template(item) # Only add a placeholder if there's a condition, otherwise just the string self._all_items.append(placeholder if placeholder.condition else item) self._select_item_events = Util.string_to_event_list(mode_settings.get("select_item_events", "")) self._next_item_events = Util.string_to_event_list(mode_settings.get("next_item_events", "")) self._previous_item_events = Util.string_to_event_list(mode_settings.get("previous_item_events", "")) self._highlighted_item_index = 0 self._block_events = Util.string_to_event_list(mode_settings.get("block_events", "")) self._release_events = Util.string_to_event_list(mode_settings.get("release_events", "")) if not self._all_items: raise AssertionError("Specify at least one item to select from") def mode_start(self, **kwargs): """Start mode and let the player select.""" self._items = [] for item in self._all_items: # All strings go in, but only conditional templates if they evaluate true if isinstance(item, str): self._items.append(item) elif not item.condition or item.condition.evaluate({}): self._items.append(item.name) if not self._items: self.machine.events.post("{}_items_empty".format(self.name)) '''event (carousel_name)_items_empty desc: A carousel's items are all conditional and all evaluated false. If this event is posted, the carousel mode will not be started. ''' self.stop() return super().mode_start(**kwargs) self._done = False self._is_blocking = False self._register_handlers(self._next_item_events, self._next_item) self._register_handlers(self._previous_item_events, self._previous_item) self._register_handlers(self._select_item_events, self._select_item) self._highlighted_item_index = 0 self._update_highlighted_item(None) # If set to block next/prev on flipper cancel, set those event handlers if self._block_events: # This rudimentary implementation will block on any block_event # and release on any release_event. If future requirements need to # track *which* block_event blocked and *only* release on the # corresponding release_event, additional work will be needed. for event in self._block_events: self.add_mode_event_handler(event, self._block_enable, priority=100) for event in self._release_events: self.add_mode_event_handler(event, self._block_disable, priority=100) def _register_handlers(self, events, handler): for event in events: self.add_mode_event_handler(event, handler) def _get_highlighted_item(self): return self._get_available_items()[self._highlighted_item_index] def _update_highlighted_item(self, direction): self.debug_log("Highlighted item: " + self._get_highlighted_item()) self.machine.events.post("{}_{}_highlighted".format(self.name, self._get_highlighted_item()), direction=direction) '''event (carousel_name)_(item)_highlighted desc: Player highlighted an item in a carousel. Mostly used to play shows or trigger slides. args: direction: The direction the carousel is moving. Either forwards or backwards. None on mode start. ''' def _get_available_items(self): # Return the default items return self._items def _next_item(self, **kwargs): del kwargs if self._done or self._is_blocking: return self._highlighted_item_index += 1 if self._highlighted_item_index >= len(self._get_available_items()): self._highlighted_item_index = 0 self._update_highlighted_item("forwards") def _previous_item(self, **kwargs): del kwargs if self._done or self._is_blocking: return self._highlighted_item_index -= 1 if self._highlighted_item_index < 0: self._highlighted_item_index = len(self._get_available_items()) - 1 self._update_highlighted_item("backwards") def _select_item(self, **kwargs): del kwargs if self._done: return self.debug_log("Selected mode: " + str(self._get_highlighted_item())) self._done = True self.machine.events.post("{}_{}_selected".format(self.name, self._get_highlighted_item())) '''event (carousel_name)_(item)_selected desc: Player selected an item in a carousel. Can be used to trigger modes. ''' self.machine.events.post("{}_item_selected".format(self.name)) '''event (carousel_name)_item_selected desc: Player selected any item in a carousel. Used to stop mode. ''' def _block_enable(self, **kwargs): del kwargs self._is_blocking = True def _block_disable(self, **kwargs): del kwargs self._is_blocking = False
missionpinball/mpf
mpf/modes/carousel/code/carousel.py
Python
mit
6,517
0.003376
# -*- coding: utf-8 -*- # @COPYRIGHT_begin # # Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland # # 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. # # @COPYRIGHT_end """@package src.cm.utils.threads.image """ import subprocess import threading import urllib2 from common.states import image_states from common.hardware import disk_format_commands, disk_filesystems_reversed import os from cm.utils import log import random import hashlib from cm.utils import message class CreateImage(threading.Thread): image = None filesystem = None def __init__(self, image, filesystem): threading.Thread.__init__(self) self.image = image self.filesystem = filesystem def run(self): if os.path.exists(self.image.path): self.image.state = image_states['failed'] self.image.save(update_fields=['state']) log.error(self.image.user.id, "Destination image %d for user %d exists! Aborting creation" % ( self.image.id, self.image.user.id)) return self.image.progress = 0 if self.format() == 'failed': self.image.state = image_states['failed'] self.image.save(update_fields=['state']) else: self.image.progress = 100 self.image.state = image_states['ok'] self.image.save(update_fields=['state', 'progress']) log.debug(self.image.user.id, 'stage [6/6] cleaning..') try: os.remove('%s' % os.path.join('/var/lib/cc1/images-tmp/', os.path.split(self.image.path)[1])) except Exception, e: log.error(self.image.user.id, 'error remove file: %s' % str(e)) def exec_cmd(self, args): p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retr_std = p.stdout.read() ret = p.wait() if ret: retr_err = str(p.stderr.read()) log.error(self.image.user.id, retr_err) log.error(self.image.user.id, retr_std) return retr_err def set_progress(self, prg): self.image.progress = prg self.image.save(update_fields=['progress']) def format(self): if not os.path.exists(os.path.dirname(self.image.path)): os.makedirs(os.path.dirname(self.image.path)) format_cmd = disk_format_commands[disk_filesystems_reversed[self.filesystem]].split() if format_cmd: tmp_dir = '/var/lib/cc1/images-tmp/' tmp_path = os.path.join(tmp_dir, os.path.split(self.image.path)[1]) if not os.path.exists(os.path.dirname(tmp_dir)): os.makedirs(os.path.dirname(tmp_dir)) else: tmp_path = str(self.image.path) log.debug(self.image.user.id, 'stage [1/6] truncate partition file') if self.exec_cmd(['truncate', '-s', '%dM' % self.image.size, '%s' % tmp_path]): return 'failed' self.set_progress(random.randint(0, 15)) if format_cmd: format_cmd.append('%s' % tmp_path) log.debug(self.image.user.id, 'stage [2/6] creating partition filesystem') if self.exec_cmd(format_cmd): return 'failed' self.set_progress(random.randint(15, 50)) log.debug(self.image.user.id, 'stage [3/6] creating disk') if self.exec_cmd(['/usr/bin/ddrescue', '-S', '-o', '1048576', '%s' % tmp_path, str(self.image.path)]): return 'failed' self.set_progress(random.randint(50, 80)) log.debug(self.image.user.id, 'stage [4/6] creating new partition table') if self.exec_cmd(['/sbin/parted', '-s', str(self.image.path), 'mklabel', 'msdos']): return 'failed' self.set_progress(random.randint(80, 90)) log.debug(self.image.user.id, 'stage [5/6] adding partition') if self.exec_cmd(['/sbin/parted', '-s', str(self.image.path), 'mkpart', 'primary', '1048576b', '100%']): return 'failed' self.set_progress(random.randint(90, 100)) log.info(self.image.user.id, 'disk succesfully formatted') class DownloadImage(threading.Thread): image = None url = None size = 0 def __init__(self, image, url, size): threading.Thread.__init__(self) self.image = image self.url = url self.size = size def run(self): try: if self.url.startswith('/'): src_image = open(self.url, 'r') else: src_image = urllib2.urlopen(self.url) except Exception, e: log.exception(self.image.user.id, "Cannot open url %s: %s" % (self.url, str(e))) self.image.state = image_states['failed'] return if os.path.exists(self.image.path): self.image.state = image_states['failed'] self.image.save(update_fields=['state']) log.error(self.image.user.id, "Destination image %d for user %d exists! Aborting download" % ( self.image.id, self.image.user.id)) return try: dirpath = os.path.dirname(self.image.path) if not os.path.exists(dirpath): os.mkdir(dirpath) dest_image = open(self.image.path, 'w') downloaded_size = 0 md5sum = hashlib.md5() while downloaded_size < self.size: buff = src_image.read(1024 * 1024) md5sum.update(buff) downloaded_size += len(buff) dest_image.write(buff) progress = int(downloaded_size * 100 / self.size) if progress != self.image.progress: self.image.progress = progress self.image.save(update_fields=['progress']) dest_image.close() log.info(self.image.user.id, 'md5 hash of image %d is %s' % (self.image.id, md5sum.hexdigest())) self.image.state = image_states['ok'] self.image.size = downloaded_size / (1024 * 1024) self.image.save(update_fields=['progress', 'state', 'size']) message.info(self.image.user.id, 'image_downloaded', {'name': self.image.name, 'md5sum': md5sum.hexdigest()}) except Exception, e: log.exception(self.image.user.id, "Failed to download image: %s" % str(e)) self.image.state = image_states['failed'] self.image.save(update_fields=['state']) class CopyImage(threading.Thread): def __init__(self, src_image, dest_image): threading.Thread.__init__(self) self.src_image = src_image self.dest_image = dest_image def run(self): copied = 0 prev_progress = 0 try: size = os.path.getsize(self.src_image.path) dirpath = os.path.dirname(self.dest_image.path) if not os.path.exists(dirpath): os.mkdir(dirpath) src = open(self.src_image.path, "r") dst = open(self.dest_image.path, "w") while 1: buff = src.read(1024 * 1024) # Should be less than MTU? if len(buff) > 0 and copied <= size: dst.write(buff) copied = copied + len(buff) else: break # Update image information: progress = 100 * copied / size if progress > prev_progress: prev_progress = progress self.dest_image.progress = progress self.dest_image.save(update_fields=['progress']) self.dest_image.state = image_states['ok'] self.dest_image.size = self.src_image.size self.dest_image.save(update_fields=['progress', 'state', 'size']) src.close() dst.close() except Exception, e: log.exception(self.dest_image.user.id, "Failed to copy image: %s" % str(e)) self.dest_image.state = image_states['failed'] self.dest_image.save(update_fields=['state'])
Dev-Cloud-Platform/Dev-Cloud
dev_cloud/cc1/src/cm/utils/threads/image.py
Python
apache-2.0
8,639
0.002084
# # Copyright 2015 chinaskycloud.com.cn # # Author: Chunyang Liu <liucy@chinaskycloud.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 # 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. """ Publish plugins are responsible for publish fetched metrics into different monitoring system. """ plugins = { 'file':'newrelic_plugin_agent.publisher.file.FilePublisher', 'ceilometer':'newrelic_plugin_agent.publisher.ceilometer.CeilometerPublisher' } import base
whiteear/newrelic-plugin-agent
newrelic_plugin_agent/publisher/__init__.py
Python
bsd-3-clause
918
0.005447
""" putJSONdata.py Copyright 2016 OSIsoft, LLC. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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. Call: python putJSONdata.py rest-ufl rest-external Parameters: rest-ufl - The Address specified in the Data Source configuration rest-external - A third party data source which returns JSON data when receving a get request from this URL. Example: python putJSONdata.py https://localhost:5460/connectordata/currency http://api.fixer.io/latest?base=USD """ import argparse import getpass import json import sys from functools import lru_cache import requests import time # Suppress insecure HTTPS warnings, if an untrusted certificate is used by the target endpoint from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) # Process arguments parser = argparse.ArgumentParser() parser.description = 'POST file contents to PI Connector for UFL' parser.add_argument('restufl', help='The UFL rest endpoint address') parser.add_argument('restexternal', help='The external data source rest end point') args = parser.parse_args() @lru_cache(maxsize=1) def password(): return getpass.getpass() @lru_cache(maxsize=1) def username(): return getpass.getpass('Username: ') s = requests.session() # To hardcode the username and password, specify them below # To use anonymous login, use: ("", "") s.auth = ("pi", "pi") def getData(url): # Being very careful when checking for failure when accessing the external site try: response = requests.get(url=url) if response.status_code != requests.codes.ok: print("The url {0} did not return the expected value back.".format(response.url)) print("Response: {0} {1}".format(response.status_code, response.reason)) sys.exit(0) try: return json.dumps(response.json(), indent=4, sort_keys=True) except ValueError as e: print(e) sys.exit(0) except requests.exceptions.Timeout: # Maybe set up for a retry, or continue in a retry loop print("Connection timed out") sys.exit(0) except requests.exceptions.TooManyRedirects: # Tell the user their URL was bad and try a different one print("Too many redirects") sys.exit(0) except requests.exceptions.RequestException as e: print("There was an issue with requesting the data:") print(e) sys.exit(0) data = getData(args.restexternal) # remove verify=False if the certificate used is a trusted one response = s.put(args.restufl, data=data, verify=False) # If instead of using the put request, you need to use the post request # use the function as listed below # response = s.post(args.resturl + '/post', data=data, verify=False) if response.status_code != 200: print("Sending data to the UFL connect failed due to error {0} {1}".format(response.status_code, response.reason)) else: print('The data was sent successfully over https.') print('Check the PI Connectors event logs for any further information.') print("SF Bike Data sent at :") localtime = time.asctime( time.localtime(time.time()) ) print(localtime) time.sleep(45)
danielElopez/PI-Connector-for-UFL-Samples
COMPLETE_SOLUTIONS/North American General Bike Feed/putJSONdata_SF_Bikes_service.py
Python
apache-2.0
3,727
0.003756
# Copyright (C) 2012, Ansgar Burchardt <ansgar@debian.org> # # 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-1301 USA. """Transactions for filesystem actions """ import errno import os import shutil class _FilesystemAction(object): @property def temporary_name(self): raise NotImplementedError() def check_for_temporary(self): try: if os.path.exists(self.temporary_name): raise IOError("Temporary file '{0}' already exists.".format(self.temporary_name)) except NotImplementedError: pass class _FilesystemCopyAction(_FilesystemAction): def __init__(self, source, destination, link=True, symlink=False, mode=None): self.destination = destination self.need_cleanup = False dirmode = 0o2755 if mode is not None: dirmode = 0o2700 | mode # Allow +x for group and others if they have +r. if dirmode & 0o0040: dirmode = dirmode | 0o0010 if dirmode & 0o0004: dirmode = dirmode | 0o0001 self.check_for_temporary() destdir = os.path.dirname(self.destination) if not os.path.exists(destdir): os.makedirs(destdir, dirmode) if symlink: os.symlink(source, self.destination) elif link: try: os.link(source, self.destination) except OSError: shutil.copy2(source, self.destination) else: shutil.copy2(source, self.destination) self.need_cleanup = True if mode is not None: os.chmod(self.destination, mode) @property def temporary_name(self): return self.destination def commit(self): pass def rollback(self): if self.need_cleanup: os.unlink(self.destination) self.need_cleanup = False class _FilesystemUnlinkAction(_FilesystemAction): def __init__(self, path): self.path = path self.need_cleanup = False self.check_for_temporary() os.rename(self.path, self.temporary_name) self.need_cleanup = True @property def temporary_name(self): return "{0}.dak-rm".format(self.path) def commit(self): if self.need_cleanup: os.unlink(self.temporary_name) self.need_cleanup = False def rollback(self): if self.need_cleanup: os.rename(self.temporary_name, self.path) self.need_cleanup = False class _FilesystemCreateAction(_FilesystemAction): def __init__(self, path): self.path = path self.need_cleanup = True @property def temporary_name(self): return self.path def commit(self): pass def rollback(self): if self.need_cleanup: os.unlink(self.path) self.need_cleanup = False class FilesystemTransaction(object): """transactions for filesystem actions""" def __init__(self): self.actions = [] def copy(self, source, destination, link=False, symlink=False, mode=None): """copy C{source} to C{destination} @type source: str @param source: source file @type destination: str @param destination: destination file @type link: bool @param link: try hardlinking, falling back to copying @type symlink: bool @param symlink: create a symlink instead of copying @type mode: int @param mode: permissions to change C{destination} to """ if isinstance(mode, str) or isinstance(mode, unicode): mode = int(mode, 8) self.actions.append(_FilesystemCopyAction(source, destination, link=link, symlink=symlink, mode=mode)) def move(self, source, destination, mode=None): """move C{source} to C{destination} @type source: str @param source: source file @type destination: str @param destination: destination file @type mode: int @param mode: permissions to change C{destination} to """ self.copy(source, destination, link=True, mode=mode) self.unlink(source) def unlink(self, path): """unlink C{path} @type path: str @param path: file to unlink """ self.actions.append(_FilesystemUnlinkAction(path)) def create(self, path, mode=None): """create C{filename} and return file handle @type filename: str @param filename: file to create @type mode: int @param mode: permissions for the new file @return: file handle of the new file """ if isinstance(mode, str) or isinstance(mode, unicode): mode = int(mode, 8) destdir = os.path.dirname(path) if not os.path.exists(destdir): os.makedirs(destdir, 0o2775) if os.path.exists(path): raise IOError("File '{0}' already exists.".format(path)) fh = open(path, 'w') self.actions.append(_FilesystemCreateAction(path)) if mode is not None: os.chmod(path, mode) return fh def commit(self): """Commit all recorded actions.""" try: for action in self.actions: action.commit() except: self.rollback() raise finally: self.actions = [] def rollback(self): """Undo all recorded actions.""" try: for action in self.actions: action.rollback() finally: self.actions = [] def __enter__(self): return self def __exit__(self, type, value, traceback): if type is None: self.commit() else: self.rollback() return None
tanglu-org/tdak
daklib/fstransactions.py
Python
gpl-2.0
6,500
0.001385
"""flex_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^flexselect/', include('flexselect.urls')), ]
twerp/django-admin-flexselect-py3
flex_project/urls.py
Python
cc0-1.0
816
0
# -*- coding: utf-8 -*- """ InformationMachineAPILib.Models.GetNutrientsWrapper """ from InformationMachineAPILib.APIHelper import APIHelper from InformationMachineAPILib.Models.NutrientInfo import NutrientInfo from InformationMachineAPILib.Models.MetaBase import MetaBase class GetNutrientsWrapper(object): """Implementation of the 'GetNutrientsWrapper' model. TODO: type model description here. Attributes: result (list of NutrientInfo): TODO: type description here. meta (MetaBase): TODO: type description here. """ def __init__(self, **kwargs): """Constructor for the GetNutrientsWrapper class Args: **kwargs: Keyword Arguments in order to initialise the object. Any of the attributes in this object are able to be set through the **kwargs of the constructor. The values that can be supplied and their types are as follows:: result -- list of NutrientInfo -- Sets the attribute result meta -- MetaBase -- Sets the attribute meta """ # Set all of the parameters to their default values self.result = None self.meta = None # Create a mapping from API property names to Model property names replace_names = { "result": "result", "meta": "meta", } # Parse all of the Key-Value arguments if kwargs is not None: for key in kwargs: # Only add arguments that are actually part of this object if key in replace_names: setattr(self, replace_names[key], kwargs[key]) # Other objects also need to be initialised properly if "result" in kwargs: # Parameter is an array, so we need to iterate through it self.result = list() for item in kwargs["result"]: self.result.append(NutrientInfo(**item)) # Other objects also need to be initialised properly if "meta" in kwargs: self.meta = MetaBase(**kwargs["meta"]) def resolve_names(self): """Creates a dictionary representation of this object. This method converts an object to a dictionary that represents the format that the model should be in when passed into an API Request. Because of this, the generated dictionary may have different property names to that of the model itself. Returns: dict: The dictionary representing the object. """ # Create a mapping from Model property names to API property names replace_names = { "result": "result", "meta": "meta", } retval = dict() return APIHelper.resolve_names(self, replace_names, retval)
information-machine/information-machine-api-python
InformationMachineAPILib/Models/GetNutrientsWrapper.py
Python
mit
2,942
0.003059
# # 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 datetime import operator import elasticsearch as es from elasticsearch import helpers from oslo_utils import netutils from oslo_utils import timeutils import six from ceilometer.event.storage import base from ceilometer.event.storage import models from ceilometer import utils AVAILABLE_CAPABILITIES = { 'events': {'query': {'simple': True}}, } AVAILABLE_STORAGE_CAPABILITIES = { 'storage': {'production_ready': True}, } class Connection(base.Connection): """Put the event data into an ElasticSearch db. Events in ElasticSearch are indexed by day and stored by event_type. An example document:: {"_index":"events_2014-10-21", "_type":"event_type0", "_id":"dc90e464-65ab-4a5d-bf66-ecb956b5d779", "_score":1.0, "_source":{"timestamp": "2014-10-21T20:02:09.274797" "traits": {"id4_0": "2014-10-21T20:02:09.274797", "id3_0": 0.7510790937279408, "id2_0": 5, "id1_0": "18c97ba1-3b74-441a-b948-a702a30cbce2"} } } """ CAPABILITIES = utils.update_nested(base.Connection.CAPABILITIES, AVAILABLE_CAPABILITIES) STORAGE_CAPABILITIES = utils.update_nested( base.Connection.STORAGE_CAPABILITIES, AVAILABLE_STORAGE_CAPABILITIES, ) index_name = 'events' # NOTE(gordc): mainly for testing, data is not searchable after write, # it is only searchable after periodic refreshes. _refresh_on_write = False def __init__(self, url): url_split = netutils.urlsplit(url) self.conn = es.Elasticsearch(url_split.netloc) def upgrade(self): iclient = es.client.IndicesClient(self.conn) ts_template = { 'template': '*', 'mappings': {'_default_': {'_timestamp': {'enabled': True, 'store': True}, 'properties': {'traits': {'type': 'nested'}}}}} iclient.put_template(name='enable_timestamp', body=ts_template) def record_events(self, events): def _build_bulk_index(event_list): for ev in event_list: traits = {t.name: t.value for t in ev.traits} yield {'_op_type': 'create', '_index': '%s_%s' % (self.index_name, ev.generated.date().isoformat()), '_type': ev.event_type, '_id': ev.message_id, '_source': {'timestamp': ev.generated.isoformat(), 'traits': traits}} problem_events = [] for ok, result in helpers.streaming_bulk( self.conn, _build_bulk_index(events)): if not ok: __, result = result.popitem() if result['status'] == 409: problem_events.append((models.Event.DUPLICATE, result['_id'])) else: problem_events.append((models.Event.UNKNOWN_PROBLEM, result['_id'])) if self._refresh_on_write: self.conn.indices.refresh(index='%s_*' % self.index_name) while self.conn.cluster.pending_tasks(local=True)['tasks']: pass return problem_events def _make_dsl_from_filter(self, indices, ev_filter): q_args = {} filters = [] if ev_filter.start_timestamp: filters.append({'range': {'timestamp': {'ge': ev_filter.start_timestamp.isoformat()}}}) while indices[0] < ( '%s_%s' % (self.index_name, ev_filter.start_timestamp.date().isoformat())): del indices[0] if ev_filter.end_timestamp: filters.append({'range': {'timestamp': {'le': ev_filter.end_timestamp.isoformat()}}}) while indices[-1] > ( '%s_%s' % (self.index_name, ev_filter.end_timestamp.date().isoformat())): del indices[-1] q_args['index'] = indices if ev_filter.event_type: q_args['doc_type'] = ev_filter.event_type if ev_filter.message_id: filters.append({'term': {'_id': ev_filter.message_id}}) if ev_filter.traits_filter: trait_filters = [] for t_filter in ev_filter.traits_filter: value = None for val_type in ['integer', 'string', 'float', 'datetime']: if t_filter.get(val_type): value = t_filter.get(val_type) if isinstance(value, six.string_types): value = value.lower() elif isinstance(value, datetime.datetime): value = value.isoformat() break if t_filter.get('op') in ['gt', 'ge', 'lt', 'le']: op = (t_filter.get('op').replace('ge', 'gte') .replace('le', 'lte')) trait_filters.append( {'range': {t_filter['key']: {op: value}}}) else: tf = {"query": {"query_string": { "query": "%s: \"%s\"" % (t_filter['key'], value)}}} if t_filter.get('op') == 'ne': tf = {"not": tf} trait_filters.append(tf) filters.append( {'nested': {'path': 'traits', 'query': {'filtered': { 'filter': {'bool': {'must': trait_filters}}}}}}) q_args['body'] = {'query': {'filtered': {'filter': {'bool': {'must': filters}}}}} return q_args def get_events(self, event_filter): iclient = es.client.IndicesClient(self.conn) indices = iclient.get_mapping('%s_*' % self.index_name).keys() if indices: filter_args = self._make_dsl_from_filter(indices, event_filter) results = self.conn.search(fields=['_id', 'timestamp', '_type', '_source'], sort='timestamp:asc', **filter_args) trait_mappings = {} for record in results['hits']['hits']: trait_list = [] if not record['_type'] in trait_mappings: trait_mappings[record['_type']] = list( self.get_trait_types(record['_type'])) for key in record['_source']['traits'].keys(): value = record['_source']['traits'][key] for t_map in trait_mappings[record['_type']]: if t_map['name'] == key: dtype = t_map['data_type'] break trait_list.append(models.Trait( name=key, dtype=dtype, value=models.Trait.convert_value(dtype, value))) gen_ts = timeutils.normalize_time(timeutils.parse_isotime( record['_source']['timestamp'])) yield models.Event(message_id=record['_id'], event_type=record['_type'], generated=gen_ts, traits=sorted( trait_list, key=operator.attrgetter('dtype'))) def get_event_types(self): iclient = es.client.IndicesClient(self.conn) es_mappings = iclient.get_mapping('%s_*' % self.index_name) seen_types = set() for index in es_mappings.keys(): for ev_type in es_mappings[index]['mappings'].keys(): seen_types.add(ev_type) # TODO(gordc): tests assume sorted ordering but backends are not # explicitly ordered. # NOTE: _default_ is a type that appears in all mappings but is not # real 'type' seen_types.discard('_default_') return sorted(list(seen_types)) @staticmethod def _remap_es_types(d_type): if d_type == 'string': d_type = 'text' elif d_type == 'long': d_type = 'int' elif d_type == 'double': d_type = 'float' elif d_type == 'date' or d_type == 'date_time': d_type = 'datetime' return d_type def get_trait_types(self, event_type): iclient = es.client.IndicesClient(self.conn) es_mappings = iclient.get_mapping('%s_*' % self.index_name) seen_types = [] for index in es_mappings.keys(): # if event_type exists in index and has traits if (es_mappings[index]['mappings'].get(event_type) and es_mappings[index]['mappings'][event_type]['properties'] ['traits'].get('properties')): for t_type in (es_mappings[index]['mappings'][event_type] ['properties']['traits']['properties'].keys()): d_type = (es_mappings[index]['mappings'][event_type] ['properties']['traits']['properties'] [t_type]['type']) d_type = models.Trait.get_type_by_name( self._remap_es_types(d_type)) if (t_type, d_type) not in seen_types: yield {'name': t_type, 'data_type': d_type} seen_types.append((t_type, d_type)) def get_traits(self, event_type, trait_type=None): t_types = dict((res['name'], res['data_type']) for res in self.get_trait_types(event_type)) if not t_types or (trait_type and trait_type not in t_types.keys()): return result = self.conn.search('%s_*' % self.index_name, event_type) for ev in result['hits']['hits']: if trait_type and ev['_source']['traits'].get(trait_type): yield models.Trait( name=trait_type, dtype=t_types[trait_type], value=models.Trait.convert_value( t_types[trait_type], ev['_source']['traits'][trait_type])) else: for trait in ev['_source']['traits'].keys(): yield models.Trait( name=trait, dtype=t_types[trait], value=models.Trait.convert_value( t_types[trait], ev['_source']['traits'][trait]))
Juniper/ceilometer
ceilometer/event/storage/impl_elasticsearch.py
Python
apache-2.0
11,518
0
########################################################################## # # Copyright (c) 2013-2015, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with # the distribution. # # * Neither the name of John Haddon nor the names of # any other contributors to this software 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. # ########################################################################## import os import unittest import IECore import Gaffer import GafferImage import GafferImageTest class ObjectToImageTest( GafferImageTest.ImageTestCase ) : fileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checker.exr" ) negFileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checkerWithNegativeDataWindow.200x150.exr" ) def test( self ) : i = IECore.Reader.create( self.fileName ).read() n = GafferImage.ObjectToImage() n["object"].setValue( i ) self.assertEqual( n["out"].image(), i ) def testImageWithANegativeDataWindow( self ) : i = IECore.Reader.create( self.negFileName ).read() n = GafferImage.ObjectToImage() n["object"].setValue( i ) self.assertEqual( n["out"].image(), i ) def testHashVariesPerTileAndChannel( self ) : n = GafferImage.ObjectToImage() n["object"].setValue( IECore.Reader.create( self.fileName ).read() ) self.assertNotEqual( n["out"].channelDataHash( "R", IECore.V2i( 0 ) ), n["out"].channelDataHash( "G", IECore.V2i( 0 ) ) ) self.assertNotEqual( n["out"].channelDataHash( "R", IECore.V2i( 0 ) ), n["out"].channelDataHash( "R", IECore.V2i( GafferImage.ImagePlug.tileSize() ) ) ) if __name__ == "__main__": unittest.main()
chippey/gaffer
python/GafferImageTest/ObjectToImageTest.py
Python
bsd-3-clause
3,067
0.025106
"""Generic runner functions.""" # from lutris.util.log import logger __all__ = ( # Native "linux", "steam", "browser", "web", # Microsoft based "wine", "winesteam", "dosbox", # Multi-system "mame", "mess", "mednafen", "scummvm", "residualvm", "libretro", "ags", # Commdore "fsuae", "vice", # Atari "stella", "atari800", "hatari", "virtualjaguar", # Nintendo "snes9x", "mupen64plus", "dolphin", "desmume", "citra", # Sony "pcsxr", "ppsspp", "pcsx2", # Sega "osmose", "dgen", "reicast", # Misc legacy systems "frotz", "jzintv", "o2em", "zdoom" ) class InvalidRunner(Exception): def __init__(self, message): self.message = message class RunnerInstallationError(Exception): def __init__(self, message): self.message = message class NonInstallableRunnerError(Exception): def __init__(self, message): self.message = message def get_runner_module(runner_name): if runner_name not in __all__: raise InvalidRunner("Invalid runner name '%s'" % runner_name) return __import__('lutris.runners.%s' % runner_name, globals(), locals(), [runner_name], 0) def import_runner(runner_name): """Dynamically import a runner class.""" runner_module = get_runner_module(runner_name) if not runner_module: return return getattr(runner_module, runner_name) def import_task(runner, task): """Return a runner task.""" runner_module = get_runner_module(runner) if not runner_module: return return getattr(runner_module, task) def get_installed(sort=True): """Return a list of installed runners (class instances).""" installed = [] for runner_name in __all__: runner = import_runner(runner_name)() if runner.is_installed(): installed.append(runner) return sorted(installed) if sort else installed
RobLoach/lutris
lutris/runners/__init__.py
Python
gpl-3.0
1,920
0
import os def numCPUs(): if not hasattr(os, "sysconf"): raise RuntimeError("No sysconf detected.") return os.sysconf("SC_NPROCESSORS_ONLN") bind = "0.0.0.0:8000" # workers = numCPUs() * 2 + 1 workers = 1 backlog = 2048 worker_class = "sync" # worker_class = "gevent" debug = True # daemon = True # errorlog = 'gunicorn-error.log' # accesslog = 'gunicorn-access.log' # log-file= - loglevel = 'info'
yewsiang/botmother
gunicorn.py
Python
agpl-3.0
417
0.002398
"""Initial schema Revision ID: 2b8459f1e2d6 Revises: None Create Date: 2013-10-22 14:31:32.654367 """ # revision identifiers, used by Alembic. revision = '2b8459f1e2d6' down_revision = None from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('repository', sa.Column('id', sa.GUID(), nullable=False), sa.Column('url', sa.String(length=200), nullable=False), sa.Column('date_created', sa.DateTime(), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('url') ) op.create_table('node', sa.Column('id', sa.GUID(), nullable=False), sa.Column('label', sa.String(length=128), nullable=True), sa.Column('date_created', sa.DateTime(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_table('author', sa.Column('id', sa.GUID(), nullable=False), sa.Column('name', sa.String(length=128), nullable=False), sa.Column('email', sa.String(length=128), nullable=True), sa.Column('date_created', sa.DateTime(), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('email'), sa.UniqueConstraint('name') ) op.create_table('remoteentity', sa.Column('id', sa.GUID(), nullable=False), sa.Column('type', sa.String(), nullable=False), sa.Column('provider', sa.String(length=128), nullable=False), sa.Column('remote_id', sa.String(length=128), nullable=False), sa.Column('internal_id', sa.GUID(), nullable=False), sa.Column('data', sa.JSONEncodedDict(), nullable=True), sa.Column('date_created', sa.DateTime(), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('provider','remote_id','type', name='remote_identifier') ) op.create_table('project', sa.Column('id', sa.GUID(), nullable=False), sa.Column('slug', sa.String(length=64), nullable=False), sa.Column('repository_id', sa.GUID(), nullable=False), sa.Column('name', sa.String(length=64), nullable=True), sa.Column('date_created', sa.DateTime(), nullable=True), sa.Column('avg_build_time', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['repository_id'], ['repository.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('slug') ) op.create_table('revision', sa.Column('repository_id', sa.GUID(), nullable=False), sa.Column('sha', sa.String(length=40), nullable=False), sa.Column('author_id', sa.GUID(), nullable=True), sa.Column('message', sa.Text(), nullable=True), sa.Column('parents', postgresql.ARRAY(sa.String(length=40)), nullable=True), sa.Column('date_created', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['author_id'], ['author.id'], ), sa.ForeignKeyConstraint(['repository_id'], ['repository.id'], ), sa.PrimaryKeyConstraint('repository_id', 'sha') ) op.create_table('change', sa.Column('id', sa.GUID(), nullable=False), sa.Column('hash', sa.String(length=40), nullable=False), sa.Column('repository_id', sa.GUID(), nullable=False), sa.Column('project_id', sa.GUID(), nullable=False), sa.Column('author_id', sa.GUID(), nullable=True), sa.Column('label', sa.String(length=128), nullable=False), sa.Column('message', sa.Text(), nullable=True), sa.Column('date_created', sa.DateTime(), nullable=True), sa.Column('date_modified', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['author_id'], ['author.id'], ), sa.ForeignKeyConstraint(['project_id'], ['project.id'], ), sa.ForeignKeyConstraint(['repository_id'], ['repository.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('hash') ) op.create_table('patch', sa.Column('id', sa.GUID(), nullable=False), sa.Column('change_id', sa.GUID(), nullable=True), sa.Column('repository_id', sa.GUID(), nullable=False), sa.Column('project_id', sa.GUID(), nullable=False), sa.Column('parent_revision_sha', sa.String(length=40), nullable=False), sa.Column('label', sa.String(length=64), nullable=False), sa.Column('url', sa.String(length=200), nullable=True), sa.Column('diff', sa.Text(), nullable=True), sa.Column('message', sa.Text(), nullable=True), sa.Column('date_created', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['change_id'], ['change.id'], ), sa.ForeignKeyConstraint(['project_id'], ['project.id'], ), sa.ForeignKeyConstraint(['repository_id'], ['repository.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('build', sa.Column('id', sa.GUID(), nullable=False), sa.Column('change_id', sa.GUID(), nullable=True), sa.Column('repository_id', sa.GUID(), nullable=False), sa.Column('project_id', sa.GUID(), nullable=False), sa.Column('parent_revision_sha', sa.String(length=40), nullable=True), sa.Column('patch_id', sa.GUID(), nullable=True), sa.Column('author_id', sa.GUID(), nullable=True), sa.Column('label', sa.String(length=128), nullable=False), sa.Column('status', sa.Enum(), nullable=False), sa.Column('result', sa.Enum(), nullable=False), sa.Column('message', sa.Text(), nullable=True), sa.Column('duration', sa.Integer(), nullable=True), sa.Column('date_started', sa.DateTime(), nullable=True), sa.Column('date_finished', sa.DateTime(), nullable=True), sa.Column('date_created', sa.DateTime(), nullable=True), sa.Column('date_modified', sa.DateTime(), nullable=True), sa.Column('data', sa.JSONEncodedDict(), nullable=True), sa.ForeignKeyConstraint(['author_id'], ['author.id'], ), sa.ForeignKeyConstraint(['change_id'], ['change.id'], ), sa.ForeignKeyConstraint(['patch_id'], ['patch.id'], ), sa.ForeignKeyConstraint(['project_id'], ['project.id'], ), sa.ForeignKeyConstraint(['repository_id'], ['repository.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('filecoverage', sa.Column('id', sa.GUID(), nullable=False), sa.Column('build_id', sa.GUID(), nullable=False), sa.Column('filename', sa.String(length=256), nullable=False), sa.Column('project_id', sa.Integer(), nullable=False), sa.Column('data', sa.Text(), nullable=True), sa.Column('date_created', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['build_id'], ['build.id'], ), sa.PrimaryKeyConstraint('id', 'filename') ) op.create_table('test', sa.Column('id', sa.GUID(), nullable=False), sa.Column('build_id', sa.GUID(), nullable=False), sa.Column('project_id', sa.GUID(), nullable=False), sa.Column('group_sha', sa.String(length=40), nullable=False), sa.Column('label_sha', sa.String(length=40), nullable=False), sa.Column('group', sa.Text(), nullable=False), sa.Column('name', sa.Text(), nullable=False), sa.Column('package', sa.Text(), nullable=True), sa.Column('result', sa.Enum(), nullable=True), sa.Column('duration', sa.Integer(), nullable=True), sa.Column('message', sa.Text(), nullable=True), sa.Column('date_created', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['build_id'], ['build.id'], ), sa.ForeignKeyConstraint(['project_id'], ['project.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('build_id','group_sha','label_sha', name='_test_key') ) op.create_table('phase', sa.Column('id', sa.GUID(), nullable=False), sa.Column('build_id', sa.GUID(), nullable=False), sa.Column('repository_id', sa.GUID(), nullable=False), sa.Column('project_id', sa.GUID(), nullable=False), sa.Column('label', sa.String(length=128), nullable=False), sa.Column('status', sa.Enum(), nullable=False), sa.Column('result', sa.Enum(), nullable=False), sa.Column('date_started', sa.DateTime(), nullable=True), sa.Column('date_finished', sa.DateTime(), nullable=True), sa.Column('date_created', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['build_id'], ['build.id'], ), sa.ForeignKeyConstraint(['project_id'], ['project.id'], ), sa.ForeignKeyConstraint(['repository_id'], ['repository.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('step', sa.Column('id', sa.GUID(), nullable=False), sa.Column('build_id', sa.GUID(), nullable=False), sa.Column('phase_id', sa.GUID(), nullable=False), sa.Column('repository_id', sa.GUID(), nullable=False), sa.Column('project_id', sa.GUID(), nullable=False), sa.Column('label', sa.String(length=128), nullable=False), sa.Column('status', sa.Enum(), nullable=False), sa.Column('result', sa.Enum(), nullable=False), sa.Column('node_id', sa.GUID(), nullable=True), sa.Column('date_started', sa.DateTime(), nullable=True), sa.Column('date_finished', sa.DateTime(), nullable=True), sa.Column('date_created', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['build_id'], ['build.id'], ), sa.ForeignKeyConstraint(['node_id'], ['node.id'], ), sa.ForeignKeyConstraint(['phase_id'], ['phase.id'], ), sa.ForeignKeyConstraint(['project_id'], ['project.id'], ), sa.ForeignKeyConstraint(['repository_id'], ['repository.id'], ), sa.PrimaryKeyConstraint('id') ) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_table('step') op.drop_table('phase') op.drop_table('test') op.drop_table('filecoverage') op.drop_table('build') op.drop_table('patch') op.drop_table('change') op.drop_table('revision') op.drop_table('project') op.drop_table('remoteentity') op.drop_table('author') op.drop_table('node') op.drop_table('repository') ### end Alembic commands ###
alex/changes
migrations/versions/2b8459f1e2d6_initial_schema.py
Python
apache-2.0
9,758
0.016807
# -*- coding: utf-8 -*- __author__ = """JanFan""" __email__ = 'guangyizhang.jan@gmail.com' __version__ = '0.1.0'
JanFan/py-aho-corasick
py_aho_corasick/__init__.py
Python
mit
114
0
# -*- coding: utf-8 -*- from sphinx.builders.html import JSONHTMLBuilder from sphinx.util import jsonimpl class DeconstJSONImpl: """ Enhance the default JSON encoder by adding additional keys. """ def dump(self, obj, fp, *args, **kwargs): self._enhance(obj) return jsonimpl.dump(obj, fp, *args, **kwargs) def dumps(self, obj, *args, **kwargs): self._enhance(obj) return jsonimpl.dumps(obj, *args, **kwargs) def load(self, *args, **kwargs): return jsonimpl.load(*args, **kwargs) def loads(self, *args, **kwargs): return jsonimpl.loads(*args, **kwargs) def _enhance(self, obj): """ Add additional properties to "obj" to get them into the JSON. """ obj["hello"] = "Sup" class DeconstJSONBuilder(JSONHTMLBuilder): """ Custom Sphinx builder that generates Deconst-compatible JSON documents. """ implementation = DeconstJSONImpl() name = 'deconst' out_suffix = '.json' def init(self): JSONHTMLBuilder.init(self)
smashwilson/deconst-preparer-sphinx
deconstrst/builder.py
Python
apache-2.0
1,067
0
# -*- coding: utf-8 -*- import os,tcxparser cd = os.path.dirname(os.path.abspath(__file__)) #use to browse tcx files at the correct location file_list=os.listdir(os.getcwd()) f=open("result.txt","a") f.write("date (ISO UTC Format)"+'\t'+"Distance [m]"+'\t'+"Duration [s]"+'\n') for a in file_list: if a == "result.txt": print() #Quick and dirty... elif a== "readTCXFiles.py": print() #Quick and dirty... else: tcx=tcxparser.TCXParser(cd+'/'+a) #see https://github.com/vkurup/python-tcxparser/ for details if tcx.activity_type == 'biking' : #To select only my biking session (could be change to 'hiking', 'running' etc.) f.write(str(tcx.completed_at)+'\t'+str(tcx.distance)+'\t'+str(tcx.duration)+'\n') f.close
tdargent/TCXfilestodata
readTCXFiles.py
Python
mit
784
0.026786
#!/usr/bin/python3 # -*- Coding : UTF-8 -*- from os import path import github_update_checker from setuptools import setup, find_packages file_path = path.abspath(path.dirname(__file__)) with open(path.join(file_path, "README.md"), encoding="UTF-8") as f: long_description = f.read() setup( name="github_update_checker", version=github_update_checker.__version__, description="A simple update checker for github in python", long_description=long_description, url="https://github.com/Tellendil/py_github_update_checker", author="Benjamin Schubert", author_email="ben.c.schubert@gmail.com", license="MIT", classifiers=[ 'Development Status :: 5 - Stable', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 3' ], keywords="update", packages=find_packages() )
BenjaminSchubert/py_github_update_checker
setup.py
Python
mit
995
0
# Copyright (c) 2013 Yubico AB # 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import os import sys import re from jinja2 import Environment, FileSystemLoader from webob import exc, Response from webob.dec import wsgify __all__ = [ 'App', 'CollectionApp', 'render', 'populate_forms', ] cwd = os.path.dirname(__file__) base_dir = os.path.abspath(os.path.join(cwd, os.pardir)) template_dir = os.path.join(base_dir, 'templates') env = Environment(loader=FileSystemLoader(template_dir)) class TemplateBinding(object): def __init__(self, template, **kwargs): self.template = env.get_template('%s.html' % template) self.data = kwargs for (key, val) in kwargs.items(): if isinstance(val, TemplateBinding): self.data.update(val.data) def extend(self, sub_variable, sub_binding): if hasattr(sub_binding, 'data'): self.data.update(sub_binding.data) sub_binding.data = self.data self.data[sub_variable] = sub_binding @property def prerendered(self): self._rendered = str(self) return self def __str__(self): if hasattr(self, '_rendered'): return self._rendered return self.template.render(self.data) @wsgify def __call__(self, request): return str(self) def render(tmpl, **kwargs): return TemplateBinding(tmpl, **kwargs) def populate_forms(forms, data): if not data: for form in filter(lambda x: hasattr(x, 'load'), forms): form.load() else: errors = False for form in forms: form.process(data) errors = not form.validate() or errors if not errors: for form in filter(lambda x: hasattr(x, 'save'), forms): form.save() class App(object): sections = [] priority = 50 @property def name(self): self.__class__.name = sys.modules[self.__module__].__file__ \ .split('/')[-1].rsplit('.', 1)[0] return self.name def __call__(self, request): section_name = request.path_info_pop() if not section_name: return self.redirect('/%s/%s' % (self.name, self.sections[0])) if not hasattr(self, section_name): raise exc.HTTPNotFound sections = [{ 'name': section, 'title': (getattr(self, section).__doc__ or section.capitalize() ).strip(), 'active': section == section_name, 'advanced': bool(getattr(getattr(self, section), 'advanced', False)) } for section in self.sections] request.environ['yubiadmin.response'].extend('content', render( 'app_base', name=self.name, sections=sections, title='YubiAdmin - %s - %s' % (self.name, section_name) )) resp = getattr(self, section_name)(request) if isinstance(resp, Response): return resp request.environ['yubiadmin.response'].extend('page', resp) def redirect(self, url): raise exc.HTTPSeeOther(location=url) def render_forms(self, request, forms, template='form', success_msg='Settings updated!', **kwargs): alerts = [] if not request.params: for form in filter(lambda x: hasattr(x, 'load'), forms): form.load() else: errors = False for form in forms: form.process(request.params) errors = not form.validate() or errors if not errors: try: if success_msg: alerts = [{'type': 'success', 'title': success_msg}] for form in filter(lambda x: hasattr(x, 'save'), forms): form.save() except Exception as e: alerts = [{'type': 'error', 'title': 'Error:', 'message': str(e)}] else: alerts = [{'type': 'error', 'title': 'Invalid data!'}] return render(template, target=request.path, fieldsets=forms, alerts=alerts, **kwargs) ITEM_RANGE = re.compile('(\d+)-(\d+)') class CollectionApp(App): base_url = '' caption = 'Items' item_name = 'Items' columns = [] template = 'table' scripts = ['table'] selectable = True max_limit = 100 def _size(self): return len(self._get()) def _get(self, offset=0, limit=None): return [{}] def _labels(self, ids): return [x['label'] for x in self._get() if x['id'] in ids] def _delete(self, ids): raise Exception('Not implemented!') def __call__(self, request): sub_cmd = request.path_info_pop() if sub_cmd and not sub_cmd.startswith('_') and hasattr(self, sub_cmd): return getattr(self, sub_cmd)(request) else: match = ITEM_RANGE.match(sub_cmd) if sub_cmd else None if match: offset = int(match.group(1)) - 1 limit = int(match.group(2)) - offset return self.list(offset, limit) else: return self.list() def list(self, offset=0, limit=10): limit = min(self.max_limit, limit) items = self._get(offset, limit) total = self._size() shown = (min(offset + 1, total), min(offset + limit, total)) if offset > 0: st = max(0, offset - limit) ed = st + limit prev = '%s/%d-%d' % (self.base_url, st + 1, ed) else: prev = None if total > shown[1]: next = '%s/%d-%d' % (self.base_url, offset + limit + 1, shown[1] + limit) else: next = None return render( self.template, scripts=self.scripts, items=items, offset=offset, limit=limit, total=total, shown='%d-%d' % shown, prev=prev, next=next, base_url=self.base_url, caption=self.caption, cols=self.columns, item_name=self.item_name, selectable=self.selectable) def delete(self, request): ids = [x[5:] for x in request.params if request.params[x] == 'on'] labels = self._labels(ids) return render('table_delete', ids=','.join(ids), labels=labels, item_name=self.item_name, base_url=self.base_url) def delete_confirm(self, request): self._delete(request.params['delete'].split(',')) return self.redirect(self.base_url)
Yubico/yubiadmin
yubiadmin/util/app.py
Python
bsd-2-clause
7,953
0.000251
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding index on 'Tweet', fields ['analyzed_by'] db.create_index(u'twitter_stream_tweet', ['analyzed_by']) # Adding index on 'Tweet', fields ['created_at'] db.create_index(u'twitter_stream_tweet', ['created_at']) def backwards(self, orm): # Removing index on 'Tweet', fields ['created_at'] db.delete_index(u'twitter_stream_tweet', ['created_at']) # Removing index on 'Tweet', fields ['analyzed_by'] db.delete_index(u'twitter_stream_tweet', ['analyzed_by']) models = { u'twitter_stream.apikey': { 'Meta': {'object_name': 'ApiKey'}, 'access_token': ('django.db.models.fields.CharField', [], {'max_length': '250'}), 'access_token_secret': ('django.db.models.fields.CharField', [], {'max_length': '250'}), 'api_key': ('django.db.models.fields.CharField', [], {'max_length': '250'}), 'api_secret': ('django.db.models.fields.CharField', [], {'max_length': '250'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'default': 'None', 'max_length': '75', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '250'}) }, u'twitter_stream.filterterm': { 'Meta': {'object_name': 'FilterTerm'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'term': ('django.db.models.fields.CharField', [], {'max_length': '250'}) }, u'twitter_stream.streamprocess': { 'Meta': {'object_name': 'StreamProcess'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'error_count': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}), 'expires_at': ('django.db.models.fields.DateTimeField', [], {}), 'hostname': ('django.db.models.fields.CharField', [], {'max_length': '250'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'keys': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['twitter_stream.ApiKey']", 'null': 'True'}), 'last_heartbeat': ('django.db.models.fields.DateTimeField', [], {}), 'process_id': ('django.db.models.fields.PositiveIntegerField', [], {}), 'status': ('django.db.models.fields.CharField', [], {'default': "'WAITING'", 'max_length': '10'}), 'timeout_seconds': ('django.db.models.fields.PositiveIntegerField', [], {}), 'tweet_rate': ('django.db.models.fields.FloatField', [], {'default': '0'}) }, u'twitter_stream.tweet': { 'Meta': {'object_name': 'Tweet'}, 'analyzed_by': ('django.db.models.fields.SmallIntegerField', [], {'default': '0', 'db_index': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True'}), 'favorite_count': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'filter_level': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '6', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'in_reply_to_status_id': ('django.db.models.fields.BigIntegerField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'lang': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '9', 'null': 'True', 'blank': 'True'}), 'latitude': ('django.db.models.fields.FloatField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'longitude': ('django.db.models.fields.FloatField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'retweet_count': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'retweeted_status_id': ('django.db.models.fields.BigIntegerField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'text': ('django.db.models.fields.CharField', [], {'max_length': '250'}), 'truncated': ('django.db.models.fields.BooleanField', [], {}), 'tweet_id': ('django.db.models.fields.BigIntegerField', [], {}), 'user_followers_count': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'user_friends_count': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'user_geo_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'user_id': ('django.db.models.fields.BigIntegerField', [], {}), 'user_location': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '150', 'null': 'True', 'blank': 'True'}), 'user_name': ('django.db.models.fields.CharField', [], {'max_length': '150'}), 'user_screen_name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'user_time_zone': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '150', 'null': 'True', 'blank': 'True'}), 'user_utc_offset': ('django.db.models.fields.IntegerField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'user_verified': ('django.db.models.fields.BooleanField', [], {}) } } complete_apps = ['twitter_stream']
michaelbrooks/django-twitter-stream
twitter_stream/migrations/0002_auto__add_index_tweet_analyzed_by__add_index_tweet_created_at.py
Python
mit
6,130
0.007341
#!/usr/bin/env python """Implementation of client-side file-finder subactions.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import abc from future.utils import with_metaclass from grr_response_client import client_utils from grr_response_client import client_utils_common from grr_response_client.client_actions.file_finder_utils import uploading class Action(with_metaclass(abc.ABCMeta, object)): """An abstract class for subactions of the client-side file-finder. Attributes: flow: A parent flow action that spawned the subaction. """ def __init__(self, flow): self.flow = flow @abc.abstractmethod def Execute(self, filepath, result): """Executes the action on a given path. Concrete action implementations should return results by filling-in appropriate fields of the result instance. Args: filepath: A path to the file on which the action is going to be performed. result: An `FileFinderResult` instance to fill-in. """ pass class StatAction(Action): """Implementation of the stat subaction. This subaction just gathers basic metadata information about the specified file (such as size, modification time, extended attributes and flags. Attributes: flow: A parent flow action that spawned the subaction. opts: A `FileFinderStatActionOptions` instance. """ def __init__(self, flow, opts): super(StatAction, self).__init__(flow) self.opts = opts def Execute(self, filepath, result): stat_cache = self.flow.stat_cache stat = stat_cache.Get(filepath, follow_symlink=self.opts.resolve_links) result.stat_entry = client_utils.StatEntryFromStatPathSpec( stat, ext_attrs=self.opts.collect_ext_attrs) class HashAction(Action): """Implementation of the hash subaction. This subaction returns results of various hashing algorithms applied to the specified file. Additionally it also gathers basic information about the hashed file. Attributes: flow: A parent flow action that spawned the subaction. opts: A `FileFinderHashActionOptions` instance. """ def __init__(self, flow, opts): super(HashAction, self).__init__(flow) self.opts = opts def Execute(self, filepath, result): stat = self.flow.stat_cache.Get(filepath, follow_symlink=True) result.stat_entry = client_utils.StatEntryFromStatPathSpec( stat, ext_attrs=self.opts.collect_ext_attrs) if stat.IsDirectory(): return policy = self.opts.oversized_file_policy max_size = self.opts.max_size if stat.GetSize() <= self.opts.max_size: result.hash_entry = _HashEntry(stat, self.flow) elif policy == self.opts.OversizedFilePolicy.HASH_TRUNCATED: result.hash_entry = _HashEntry(stat, self.flow, max_size=max_size) elif policy == self.opts.OversizedFilePolicy.SKIP: return else: raise ValueError("Unknown oversized file policy: %s" % policy) class DownloadAction(Action): """Implementation of the download subaction. This subaction sends a specified file to the server and returns a handle to its stored version. Additionally it also gathers basic metadata about the file. Attributes: flow: A parent flow action that spawned the subaction. opts: A `FileFinderDownloadActionOptions` instance. """ def __init__(self, flow, opts): super(DownloadAction, self).__init__(flow) self.opts = opts def Execute(self, filepath, result): stat = self.flow.stat_cache.Get(filepath, follow_symlink=True) result.stat_entry = client_utils.StatEntryFromStatPathSpec( stat, ext_attrs=self.opts.collect_ext_attrs) if stat.IsDirectory(): return policy = self.opts.oversized_file_policy max_size = self.opts.max_size if stat.GetSize() <= max_size: result.transferred_file = self._UploadFilePath(filepath) elif policy == self.opts.OversizedFilePolicy.DOWNLOAD_TRUNCATED: result.transferred_file = self._UploadFilePath(filepath, truncate=True) elif policy == self.opts.OversizedFilePolicy.HASH_TRUNCATED: result.hash_entry = _HashEntry(stat, self.flow, max_size=max_size) elif policy == self.opts.OversizedFilePolicy.SKIP: return else: raise ValueError("Unknown oversized file policy: %s" % policy) def _UploadFilePath(self, filepath, truncate=False): max_size = self.opts.max_size chunk_size = self.opts.chunk_size uploader = uploading.TransferStoreUploader(self.flow, chunk_size=chunk_size) return uploader.UploadFilePath(filepath, amount=max_size) def _HashEntry(stat, flow, max_size=None): hasher = client_utils_common.MultiHasher(progress=flow.Progress) try: hasher.HashFilePath(stat.GetPath(), max_size or stat.GetSize()) return hasher.GetHashObject() except IOError: return None
dunkhong/grr
grr/client/grr_response_client/client_actions/file_finder_utils/subactions.py
Python
apache-2.0
4,871
0.006159
# Copyright (c) 2014 VMware, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Classes and utility methods for datastore selection. """ import random from oslo_log import log as logging from oslo_vmware import pbm from oslo_vmware import vim_util from cinder.i18n import _LE from cinder.volume.drivers.vmware import exceptions as vmdk_exceptions LOG = logging.getLogger(__name__) class DatastoreType(object): """Supported datastore types.""" NFS = "nfs" VMFS = "vmfs" VSAN = "vsan" VVOL = "vvol" _ALL_TYPES = {NFS, VMFS, VSAN, VVOL} @staticmethod def get_all_types(): return DatastoreType._ALL_TYPES class DatastoreSelector(object): """Class for selecting datastores which satisfy input requirements.""" HARD_AFFINITY_DS_TYPE = "hardAffinityDatastoreTypes" HARD_ANTI_AFFINITY_DS = "hardAntiAffinityDatastores" SIZE_BYTES = "sizeBytes" PROFILE_NAME = "storageProfileName" # TODO(vbala) Remove dependency on volumeops. def __init__(self, vops, session, max_objects): self._vops = vops self._session = session self._max_objects = max_objects def get_profile_id(self, profile_name): """Get vCenter profile ID for the given profile name. :param profile_name: profile name :return: vCenter profile ID :raises: ProfileNotFoundException """ profile_id = pbm.get_profile_id_by_name(self._session, profile_name) if profile_id is None: LOG.error(_LE("Storage profile: %s cannot be found in vCenter."), profile_name) raise vmdk_exceptions.ProfileNotFoundException( storage_profile=profile_name) LOG.debug("Storage profile: %(name)s resolved to vCenter profile ID: " "%(id)s.", {'name': profile_name, 'id': profile_id}) return profile_id def _filter_by_profile(self, datastores, profile_id): """Filter out input datastores that do not match the given profile.""" cf = self._session.pbm.client.factory hubs = pbm.convert_datastores_to_hubs(cf, datastores) hubs = pbm.filter_hubs_by_profile(self._session, hubs, profile_id) hub_ids = [hub.hubId for hub in hubs] return {k: v for k, v in datastores.items() if k.value in hub_ids} def _filter_datastores(self, datastores, size_bytes, profile_id, hard_anti_affinity_ds, hard_affinity_ds_types, valid_host_refs=None): if not datastores: return def _is_valid_ds_type(summary): ds_type = summary.type.lower() return (ds_type in DatastoreType.get_all_types() and (hard_affinity_ds_types is None or ds_type in hard_affinity_ds_types)) def _is_ds_usable(summary): return summary.accessible and not self._vops._in_maintenance( summary) valid_host_refs = valid_host_refs or [] valid_hosts = [host_ref.value for host_ref in valid_host_refs] def _is_ds_accessible_to_valid_host(host_mounts): for host_mount in host_mounts: if host_mount.key.value in valid_hosts: return True def _is_ds_valid(ds_ref, ds_props): summary = ds_props.get('summary') host_mounts = ds_props.get('host') if (summary is None or host_mounts is None): return False if (hard_anti_affinity_ds and ds_ref.value in hard_anti_affinity_ds): return False if summary.freeSpace < size_bytes: return False if (valid_hosts and not _is_ds_accessible_to_valid_host(host_mounts)): return False return _is_valid_ds_type(summary) and _is_ds_usable(summary) datastores = {k: v for k, v in datastores.items() if _is_ds_valid(k, v)} if datastores and profile_id: datastores = self._filter_by_profile(datastores, profile_id) return datastores def _get_object_properties(self, obj_content): props = {} if hasattr(obj_content, 'propSet'): prop_set = obj_content.propSet if prop_set: props = {prop.name: prop.val for prop in prop_set} return props def _get_datastores(self): datastores = {} retrieve_result = self._session.invoke_api( vim_util, 'get_objects', self._session.vim, 'Datastore', self._max_objects, properties_to_collect=['host', 'summary']) while retrieve_result: if retrieve_result.objects: for obj_content in retrieve_result.objects: props = self._get_object_properties(obj_content) if ('host' in props and hasattr(props['host'], 'DatastoreHostMount')): props['host'] = props['host'].DatastoreHostMount datastores[obj_content.obj] = props retrieve_result = self._session.invoke_api(vim_util, 'continue_retrieval', self._session.vim, retrieve_result) return datastores def _get_host_properties(self, host_ref): retrieve_result = self._session.invoke_api(vim_util, 'get_object_properties', self._session.vim, host_ref, ['runtime', 'parent']) if retrieve_result: return self._get_object_properties(retrieve_result[0]) def _get_resource_pool(self, cluster_ref): return self._session.invoke_api(vim_util, 'get_object_property', self._session.vim, cluster_ref, 'resourcePool') def _select_best_datastore(self, datastores, valid_host_refs=None): if not datastores: return def _sort_key(ds_props): host = ds_props.get('host') summary = ds_props.get('summary') space_utilization = (1.0 - (summary.freeSpace / float(summary.capacity))) return (-len(host), space_utilization) host_prop_map = {} def _is_host_usable(host_ref): props = host_prop_map.get(host_ref.value) if props is None: props = self._get_host_properties(host_ref) host_prop_map[host_ref.value] = props runtime = props.get('runtime') parent = props.get('parent') if runtime and parent: return (runtime.connectionState == 'connected' and not runtime.inMaintenanceMode) else: return False valid_host_refs = valid_host_refs or [] valid_hosts = [host_ref.value for host_ref in valid_host_refs] def _select_host(host_mounts): random.shuffle(host_mounts) for host_mount in host_mounts: if valid_hosts and host_mount.key.value not in valid_hosts: continue if (self._vops._is_usable(host_mount.mountInfo) and _is_host_usable(host_mount.key)): return host_mount.key sorted_ds_props = sorted(datastores.values(), key=_sort_key) for ds_props in sorted_ds_props: host_ref = _select_host(ds_props['host']) if host_ref: rp = self._get_resource_pool( host_prop_map[host_ref.value]['parent']) return (host_ref, rp, ds_props['summary']) def select_datastore(self, req, hosts=None): """Selects a datastore satisfying the given requirements. A datastore which is connected to maximum number of hosts is selected. Ties if any are broken based on space utilization-- datastore with least space utilization is preferred. It returns the selected datastore's summary along with a host and resource pool where the volume can be created. :param req: selection requirements :param hosts: list of hosts to consider :return: (host, resourcePool, summary) """ LOG.debug("Using requirements: %s for datastore selection.", req) hard_affinity_ds_types = req.get( DatastoreSelector.HARD_AFFINITY_DS_TYPE) hard_anti_affinity_datastores = req.get( DatastoreSelector.HARD_ANTI_AFFINITY_DS) size_bytes = req[DatastoreSelector.SIZE_BYTES] profile_name = req.get(DatastoreSelector.PROFILE_NAME) profile_id = None if profile_name is not None: profile_id = self.get_profile_id(profile_name) datastores = self._get_datastores() datastores = self._filter_datastores(datastores, size_bytes, profile_id, hard_anti_affinity_datastores, hard_affinity_ds_types, valid_host_refs=hosts) res = self._select_best_datastore(datastores, valid_host_refs=hosts) LOG.debug("Selected (host, resourcepool, datastore): %s", res) return res def is_datastore_compliant(self, datastore, profile_name): """Check if the datastore is compliant with given profile. :param datastore: datastore to check the compliance :param profile_name: profile to check the compliance against :return: True if the datastore is compliant; False otherwise :raises: ProfileNotFoundException """ LOG.debug("Checking datastore: %(datastore)s compliance against " "profile: %(profile)s.", {'datastore': datastore, 'profile': profile_name}) if profile_name is None: # Any datastore is trivially compliant with a None profile. return True profile_id = self.get_profile_id(profile_name) # _filter_by_profile expects a map of datastore references to its # properties. It only uses the properties to construct a map of # filtered datastores to its properties. Here we don't care about # the datastore property, so pass it as None. is_compliant = bool(self._filter_by_profile({datastore: None}, profile_id)) LOG.debug("Compliance is %(is_compliant)s for datastore: " "%(datastore)s against profile: %(profile)s.", {'is_compliant': is_compliant, 'datastore': datastore, 'profile': profile_name}) return is_compliant
NetApp/cinder
cinder/volume/drivers/vmware/datastore.py
Python
apache-2.0
12,036
0
### Generating picture frames to a "pic" folder #from pylab import * import numpy as np from time import sleep import matplotlib matplotlib.use("Agg") from matplotlib import rc matplotlib.rcParams['text.usetex'] = True matplotlib.rcParams['text.latex.unicode'] = True import matplotlib.pyplot as plt #matplotlib.use("Agg") #import matplotlib.animation as animation from boutdata import collect from boututils import DataFile pathname = "data3" T = np.squeeze(collect("T", path=pathname, xguards=False)) time = np.squeeze(collect("t_array", path=pathname, xguards=False)) #dx = collect(("dx", path="data") #dz = collect("dz", path="data") print T.shape #dx = dx.squeeze() #print dx #time = collect("t", path="data") #create 5000 Random points distributed within the circle radius 100 max_r = 1.8 min_r = 0.05 max_theta = 2.0 * np.pi #number_points = 5000 #points = np.random.rand(number_points,2)*[max_r,max_theta] #Some function to generate values for these points, #this could be values = np.random.rand(number_points) #values = points[:,0] * np.sin(points[:,1])* np.cos(points[:,1]) #now we create a grid of values, interpolated from our random sample above theta = np.linspace(0.0, max_theta, 128) r = np.linspace(min_r, max_r, 64) #grid_r, grid_theta = np.meshgrid(r, theta) #data = griddata(points, values, (grid_r, grid_theta), method='cubic',fill_value=0) #Create a polar projection fig = plt.figure() ax = fig.add_subplot(111, projection='polar') ax.set_axis_bgcolor('black') ax.set_xticklabels(['']) ax.set_yticklabels(['']) #plt.show() cax = ax.pcolormesh(theta,r, T[0,:,:]) fig.patch.set_facecolor('black') color_bar = plt.colorbar(cax, orientation='horizontal') cbytick_obj = plt.getp(color_bar.ax.axes, 'xticklabels') plt.setp(cbytick_obj, color = 'white') #cax = ax.pcolormesh(theta,r, T[i,:,0,:]) for i in range(len(time)): #Color bar txt = ax.text(0.9*np.pi,3., r'$t = ' + str(time[i]) + r'$', color='white', fontsize=16) #Plottingi cax.set_array(T[i,:-1,:-1].ravel()) fig.savefig("pic/tempBR%0.5i.png" %i, facecolor=fig.get_facecolor(), edgecolor='none') txt.remove() #fig.clear()
AlxMar/conduction-cylinder
genpics.py
Python
gpl-3.0
2,141
0.01915
#-*- coding: utf-8 -*- from django.contrib.gis.db.models import DateTimeField, Model class Base(Model): created = DateTimeField(auto_now_add=True, null=True) modified = DateTimeField(auto_now=True, null=True) class Meta: abstract = True def __str__(self): try: for propname in ["name", "key", "token", "text"]: if hasattr(self, propname): text = getattr(self, propname).encode("utf-8") if len(text) > 20: return text[:20] + "..." else: return text else: return str(self.id) except: return str(self.id) def update(self, d): save = False for k,v in d.items(): if getattr(self, k) != v: save = True setattr(self,k,v) if save: self.save()
FirstDraftGIS/firstdraft
projfd/appfd/models/base.py
Python
apache-2.0
940
0.006383
#!/usr/bin/python # # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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 .metrics_processor import MetricsProcessor from .monitoring_facade import MonitoringFacade __all__ = ('MonitoringFacade', 'MetricsProcessor')
GoogleCloudPlatform/datacatalog-connectors
google-datacatalog-connectors-commons/src/google/datacatalog_connectors/commons/monitoring/__init__.py
Python
apache-2.0
744
0
import process_operations as po import module_map_icons def process_entry(processor, txt_file, entry, index): entry_len = len(entry) output_list = ["%s %d %s %f %d " % (entry[0], entry[1], entry[2], entry[3], processor.process_id(entry[4], "snd"))] triggers = [] if entry_len >= 8: output_list.append("%f %f %f " % entry[5:8]) if entry_len > 8: triggers = entry[8] else: output_list.append("0 0 0 ") if entry_len > 5: triggers = entry[5] output_list.extend(processor.process_triggers(triggers, entry[0])) output_list.append("\r\n\r\n") txt_file.write("".join(output_list)) export = po.make_export(data=module_map_icons.map_icons, data_name="map_icons", tag="icon", header_format="map_icons_file version 1\r\n%d\r\n", process_entry=process_entry)
RaJiska/Warband-PW-Punishments-Manager
scripts/process_map_icons.py
Python
gpl-3.0
796
0.020101
""" Monkey patch and defuse all stdlib xml packages and lxml. """ import sys patched_modules = ( 'lxml', 'ElementTree', 'minidom', 'pulldom', 'sax', 'expatbuilder', 'expatreader', 'xmlrpc', ) if any(module in sys.modules for module in patched_modules): existing_modules = [(module, module in sys.modules) for module in patched_modules] raise ImportError( 'this monkey patch was not applied early enough. {0}'.format(existing_modules) ) from defusedxml import defuse_stdlib # noqa defuse_stdlib() import lxml # noqa import lxml.etree # noqa from xml.sax.handler import ( # noqa feature_external_ges, feature_external_pes, ) from olympia.lib import safe_lxml_etree # noqa lxml.etree = safe_lxml_etree
bqbn/addons-server
src/olympia/lib/safe_xml.py
Python
bsd-3-clause
774
0.002584
from collections import namedtuple from corehq.apps.change_feed.consumer.feed import KafkaChangeFeed from corehq.apps.change_feed.document_types import GROUP from corehq.apps.groups.models import Group from corehq.elastic import stream_es_query, get_es_new, ES_META from corehq.pillows.mappings.user_mapping import USER_INDEX, USER_INDEX_INFO from pillowtop.checkpoints.manager import PillowCheckpointEventHandler, get_checkpoint_for_elasticsearch_pillow from pillowtop.pillow.interface import ConstructedPillow from pillowtop.processors import PillowProcessor from pillowtop.reindexer.change_providers.couch import CouchViewChangeProvider from pillowtop.reindexer.reindexer import PillowChangeProviderReindexer class GroupsToUsersProcessor(PillowProcessor): def __init__(self): self._es = get_es_new() def process_change(self, pillow_instance, change): if change.deleted: remove_group_from_users(change.get_document(), self._es) else: update_es_user_with_groups(change.get_document(), self._es) def get_group_to_user_pillow(pillow_id='GroupToUserPillow'): assert pillow_id == 'GroupToUserPillow', 'Pillow ID is not allowed to change' checkpoint = get_checkpoint_for_elasticsearch_pillow(pillow_id, USER_INDEX_INFO) processor = GroupsToUsersProcessor() return ConstructedPillow( name=pillow_id, checkpoint=checkpoint, change_feed=KafkaChangeFeed(topics=[GROUP], group_id='groups-to-users'), processor=processor, change_processed_event_handler=PillowCheckpointEventHandler( checkpoint=checkpoint, checkpoint_frequency=100, ), ) def remove_group_from_users(group_doc, es_client): if group_doc is None: return for user_source in stream_user_sources(group_doc.get("users", [])): made_changes = False if group_doc["name"] in user_source.group_names: user_source.group_names.remove(group_doc["name"]) made_changes = True if group_doc["_id"] in user_source.group_ids: user_source.group_ids.remove(group_doc["_id"]) made_changes = True if made_changes: doc = {"__group_ids": list(user_source.group_ids), "__group_names": list(user_source.group_names)} es_client.update(USER_INDEX, ES_META['users'].type, user_source.user_id, body={"doc": doc}) def update_es_user_with_groups(group_doc, es_client=None): if not es_client: es_client = get_es_new() for user_source in stream_user_sources(group_doc.get("users", [])): if group_doc["name"] not in user_source.group_names or group_doc["_id"] not in user_source.group_ids: user_source.group_ids.add(group_doc["_id"]) user_source.group_names.add(group_doc["name"]) doc = {"__group_ids": list(user_source.group_ids), "__group_names": list(user_source.group_names)} es_client.update(USER_INDEX, ES_META['users'].type, user_source.user_id, body={"doc": doc}) UserSource = namedtuple('UserSource', ['user_id', 'group_ids', 'group_names']) def stream_user_sources(user_ids): q = {"filter": {"and": [{"terms": {"_id": user_ids}}]}} for result in stream_es_query(es_index='users', q=q, fields=["__group_ids", "__group_names"]): group_ids = result.get('fields', {}).get("__group_ids", []) group_ids = set(group_ids) if isinstance(group_ids, list) else {group_ids} group_names = result.get('fields', {}).get("__group_names", []) group_names = set(group_names) if isinstance(group_names, list) else {group_names} yield UserSource(result['_id'], group_ids, group_names) def get_groups_to_user_reindexer(): return PillowChangeProviderReindexer( pillow=get_group_to_user_pillow(), change_provider=CouchViewChangeProvider( couch_db=Group.get_db(), view_name='all_docs/by_doc_type', view_kwargs={ 'startkey': ['Group'], 'endkey': ['Group', {}], 'include_docs': True, } ), )
qedsoftware/commcare-hq
corehq/pillows/groups_to_user.py
Python
bsd-3-clause
4,115
0.002916
#!/usr/bin/env python from setuptools import setup, find_packages tests_requires = [ 'ddt>=1.0.0' ] dev_requires = [ 'Sphinx==1.2.2', ] install_requires = [ 'pbr!=2.1.0', 'Babel!=2.4.0,>=2.3.4', 'cmd2<0.9.0', # TODO: Drop restriction after Waldur is migrated to Python 3. 'iptools>=0.6.1', 'waldur-core>=0.161.1', 'python-ceilometerclient>=2.9.0', 'python-cinderclient>=3.1.0', 'python-glanceclient>=2.8.0', 'python-keystoneclient>=3.13.0', 'python-neutronclient>=6.5.0', 'python-novaclient>=9.1.0', ] setup( name='waldur-openstack', version='0.43.4', author='OpenNode Team', author_email='info@opennodecloud.com', url='http://waldur.com', description='Waldur plugin for managing OpenStack resources.', long_description=open('README.rst').read(), license='MIT', package_dir={'': 'src'}, packages=find_packages('src'), install_requires=install_requires, zip_safe=False, extras_require={ 'dev': dev_requires, 'tests': tests_requires, }, entry_points={ 'waldur_extensions': ( 'openstack = waldur_openstack.openstack.extension:OpenStackExtension', 'openstack_tenant = waldur_openstack.openstack_tenant.extension:OpenStackTenantExtension', ), }, include_package_data=True, classifiers=[ 'Framework :: Django', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', ], )
opennode/nodeconductor-openstack
setup.py
Python
mit
1,602
0.001873
# # Copyright (C) 2014 Dell, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import shutil import tempfile import unittest import uuid import mock import dcm.agent.exceptions as exceptions import dcm.agent.tests.utils.general as test_utils import dcm.agent.cloudmetadata as cm class TestCloudMetaDataBase(unittest.TestCase): @classmethod def setUpClass(cls): test_utils.connect_to_debugger() def setUp(self): self.conf = mock.Mock() self.cm_obj = cm.CloudMetaData(self.conf) def test_base_instance_id(self): instance_id = self.cm_obj.get_instance_id() self.assertIsNone(instance_id) def test_base_is_effective(self): v = self.cm_obj.is_effective_cloud() self.assertFalse(v) def test_base_startup(self): self.assertRaises(exceptions.AgentNotImplementedException, self.cm_obj.get_startup_script) def test_base_get_cloud_type(self): self.assertRaises(exceptions.AgentNotImplementedException, self.cm_obj.get_cloud_type) def test_env_injected_id_no_env(self): tmp_dir = tempfile.mkdtemp() try: self.conf.get_secure_dir.return_value = tmp_dir injected_id = self.cm_obj.get_injected_id() self.assertIsNone(injected_id) finally: shutil.rmtree(tmp_dir) def test_env_injected_id_env(self): tmp_dir = tempfile.mkdtemp() fake_id = str(uuid.uuid4()) id_file = os.path.join(tmp_dir, "injected_id") try: self.conf.get_secure_dir.return_value = tmp_dir with mock.patch.dict('os.environ', {cm.ENV_INJECTED_ID_KEY: fake_id}): injected_id = self.cm_obj.get_injected_id() self.assertEqual(injected_id, fake_id) self.assertTrue(os.path.exists(id_file)) with open(id_file, "r") as fptr: v = fptr.read().strip() self.assertEqual(v, injected_id) finally: shutil.rmtree(tmp_dir) def test_env_injected_id_env_file_exists(self): tmp_dir = tempfile.mkdtemp() fake_id = str(uuid.uuid4()) id_file = os.path.join(tmp_dir, "injected_id") try: with open(id_file, "w") as fptr: fptr.write(fake_id) self.conf.get_secure_dir.return_value = tmp_dir injected_id = self.cm_obj.get_injected_id() self.assertEqual(injected_id, fake_id) with open(id_file, "r") as fptr: v = fptr.read().strip() self.assertEqual(v, injected_id) finally: shutil.rmtree(tmp_dir) def test_ipv4_address(self): addr = self.cm_obj.get_ipv4_addresses() self.assertEqual(type(addr), list) self.assertGreaterEqual(len(addr), 1) def test_handshake_address(self): addr = self.cm_obj.get_handshake_ip_address() self.assertEqual(type(addr), list) self.assertGreaterEqual(len(addr), 1) class TestUnknownMetaDataBase(unittest.TestCase): @classmethod def setUpClass(cls): test_utils.connect_to_debugger() def setUp(self): conf = mock.Mock() self.cm_obj = cm.UnknownMetaData(conf) def test_effective_cloud(self): self.assertTrue(self.cm_obj.is_effective_cloud()) def test_cloud_type(self): self.assertEqual(self.cm_obj.get_cloud_type(), cm.CLOUD_TYPES.UNKNOWN) class TestAWSMetaDataBase(unittest.TestCase): @classmethod def setUpClass(cls): test_utils.connect_to_debugger() def setUp(self): self.conf = mock.Mock() self.cm_obj = cm.AWSMetaData(self.conf) def test_cloud_type(self): self.assertEqual(self.cm_obj.get_cloud_type(), cm.CLOUD_TYPES.Amazon) @mock.patch('dcm.agent.cloudmetadata._get_metadata_server_url_data') def test_base_startup(self, md_server_data): startup_data = "some date" md_server_data.return_value = startup_data sd = self.cm_obj.get_startup_script() self.assertEqual(startup_data, sd) @mock.patch('dcm.agent.cloudmetadata._get_metadata_server_url_data') def test_base_injected_id(self, md_server_data): fake_id = "somedata" md_server_data.return_value = fake_id sd = self.cm_obj.get_injected_id() self.assertEqual(fake_id, sd) @mock.patch('dcm.agent.cloudmetadata._get_metadata_server_url_data') def test_base_injected_id_none(self, md_server_data): tmp_dir = tempfile.mkdtemp() try: self.conf.get_secure_dir.return_value = tmp_dir fake_id = None md_server_data.return_value = fake_id sd = self.cm_obj.get_injected_id() self.assertIsNone(sd) finally: shutil.rmtree(tmp_dir) class TestCloudStackMetaDataBase(unittest.TestCase): @classmethod def setUpClass(cls): test_utils.connect_to_debugger() def setUp(self): conf = mock.Mock() self.cm_obj = cm.CloudStackMetaData(conf) def test_cloud_type(self): self.assertEqual(self.cm_obj.get_cloud_type(), cm.CLOUD_TYPES.CloudStack) class TestJoyentMetaDataBase(unittest.TestCase): @classmethod def setUpClass(cls): test_utils.connect_to_debugger() def setUp(self): self.conf = mock.Mock() self.cm_obj = cm.JoyentMetaData(self.conf) def test_cloud_type(self): self.assertEqual(self.cm_obj.get_cloud_type(), cm.CLOUD_TYPES.Joyent) @mock.patch('dcm.agent.utils.run_command') def test_base_injected_id(self, runcmd): fakeid = "someid" runcmd.return_value = (fakeid, "", 0) x = self.cm_obj.get_injected_id() self.assertEqual(fakeid, x) @mock.patch('dcm.agent.utils.run_command') def test_base_cached_injected_id(self, runcmd): fakeid = "someid" runcmd.return_value = (fakeid, "", 0) x = self.cm_obj.get_injected_id() self.assertEqual(fakeid, x) x = self.cm_obj.get_injected_id() self.assertEqual(fakeid, x) @mock.patch('dcm.agent.utils.run_command') def test_base_injected_try_both_locations(self, runcmd): runcmd.return_value = ("", "error", 1) tmp_dir = tempfile.mkdtemp() try: self.conf.get_secure_dir.return_value = tmp_dir self.conf.system_sudo = "sudo" x = self.cm_obj.get_injected_id() call1 = mock.call( self.conf, ["sudo", "/usr/sbin/mdata-get", "es:dmcm-launch-id"]) call2 = mock.call( self.conf, ["sudo", "/lib/smartdc/mdata-get", "es:dmcm-launch-id"]) self.assertEqual(runcmd.call_args_list, [call1, call2]) self.assertEqual(runcmd.call_count, 2) self.assertIsNone(x) finally: shutil.rmtree(tmp_dir) class TestGCEMetaDataBase(unittest.TestCase): @classmethod def setUpClass(cls): test_utils.connect_to_debugger() def setUp(self): conf = mock.Mock() self.cm_obj = cm.GCEMetaData(conf) def test_cloud_type(self): self.assertEqual(self.cm_obj.get_cloud_type(), cm.CLOUD_TYPES.Google) class TestAzureMetaDataBase(unittest.TestCase): @classmethod def setUpClass(cls): test_utils.connect_to_debugger() def setUp(self): conf = mock.Mock() self.cm_obj = cm.AzureMetaData(conf) def test_cloud_type(self): self.assertEqual(self.cm_obj.get_cloud_type(), cm.CLOUD_TYPES.Azure) class TestOpenStackMetaDataBase(unittest.TestCase): @classmethod def setUpClass(cls): test_utils.connect_to_debugger() def setUp(self): conf = mock.Mock() self.cm_obj = cm.OpenStackMetaData(conf) def test_cloud_type(self): self.assertEqual(self.cm_obj.get_cloud_type(), cm.CLOUD_TYPES.OpenStack) class TestKonamiMetaDataBase(unittest.TestCase): @classmethod def setUpClass(cls): test_utils.connect_to_debugger() def setUp(self): conf = mock.Mock() self.cm_obj = cm.KonamiMetaData(conf) def test_cloud_type(self): self.assertEqual(self.cm_obj.get_cloud_type(), cm.CLOUD_TYPES._Konami) class TestDigitalOceanMetaDataBase(unittest.TestCase): @classmethod def setUpClass(cls): test_utils.connect_to_debugger() def setUp(self): conf = mock.Mock() self.cm_obj = cm.DigitalOceanMetaData(conf) def test_cloud_type(self): self.assertEqual(self.cm_obj.get_cloud_type(), cm.CLOUD_TYPES.DigitalOcean) @mock.patch('dcm.agent.cloudmetadata._get_metadata_server_url_data') def test_base_startup(self, md_server_data): startup_data = "some date" md_server_data.return_value = startup_data sd = self.cm_obj.get_startup_script() self.assertEqual(startup_data, sd)
JPWKU/unix-agent
src/dcm/agent/tests/unit/test_cloudmetadata.py
Python
apache-2.0
9,676
0
from __future__ import absolute_import from contextlib import contextmanager from copy import copy from flask import g, request from flask.globals import _app_ctx_stack, _request_ctx_stack from .base import VersioningManager as BaseVersioningManager class VersioningManager(BaseVersioningManager): _actor_cls = 'User' def get_transaction_values(self): values = copy(self.values) if context_available() and hasattr(g, 'activity_values'): values.update(g.activity_values) if ( 'client_addr' not in values and self.default_client_addr is not None ): values['client_addr'] = self.default_client_addr if ( 'actor_id' not in values and self.default_actor_id is not None ): values['actor_id'] = self.default_actor_id return values @property def default_actor_id(self): from flask_login import current_user # Return None if we are outside of request context. if not context_available(): return try: return current_user.id except AttributeError: return @property def default_client_addr(self): # Return None if we are outside of request context. if not context_available(): return return request.remote_addr or None def context_available(): return ( _app_ctx_stack.top is not None and _request_ctx_stack.top is not None ) def merge_dicts(a, b): c = copy(a) c.update(b) return c @contextmanager def activity_values(**values): if not context_available(): return if hasattr(g, 'activity_values'): previous_value = g.activity_values values = merge_dicts(previous_value, values) else: previous_value = None g.activity_values = values yield if previous_value is None: del g.activity_values else: g.activity_values = previous_value versioning_manager = VersioningManager()
kvesteri/postgresql-audit
postgresql_audit/flask.py
Python
bsd-2-clause
2,063
0
from pylab import * def stem_user(user, channel_list, start_index, stop_index): data = user.windowData for channel in channel_list: stem_pandas_column(data, channel, start_index, stop_index) def stem_pandas_column(dataframe, columname, start_index, stop_index): column = dataframe[columname] stem_channel(column.values, start_index, stop_index) def stem_channel(channel, start_index, stop_index): values = channel[start_index:stop_index] markerline, stemlines, baseline = stem(range(start_index,stop_index), values, '-.') setp(markerline, 'markerfacecolor', 'b') setp(baseline, 'color','r', 'linewidth', 2) show()
joergsimon/gesture-analysis
visualise/Stem.py
Python
apache-2.0
664
0.004518
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 """Generate SystemVerilog designs from IpBlock object""" import logging as log import os from typing import Dict, Optional, Tuple from mako import exceptions # type: ignore from mako.template import Template # type: ignore from pkg_resources import resource_filename from .ip_block import IpBlock from .lib import check_int from .multi_register import MultiRegister from .reg_base import RegBase from .register import Register def escape_name(name: str) -> str: return name.lower().replace(' ', '_') def make_box_quote(msg: str, indent: str = ' ') -> str: hr = indent + ('/' * (len(msg) + 6)) middle = indent + '// ' + msg + ' //' return '\n'.join([hr, middle, hr]) def _get_awparam_name(iface_name: Optional[str]) -> str: return (iface_name or 'Iface').capitalize() + 'Aw' def get_addr_widths(block: IpBlock) -> Dict[Optional[str], Tuple[str, int]]: '''Return the address widths for the device interfaces Returns a dictionary keyed by interface name whose values are pairs: (paramname, width) where paramname is IfaceAw for an unnamed interface and FooAw for an interface called foo. This is constructed in the same order as block.reg_blocks. If there is a single device interface and that interface is unnamed, use the more general parameter name "BlockAw". ''' assert block.reg_blocks if len(block.reg_blocks) == 1 and None in block.reg_blocks: return {None: ('BlockAw', block.reg_blocks[None].get_addr_width())} return {name: (_get_awparam_name(name), rb.get_addr_width()) for name, rb in block.reg_blocks.items()} def get_type_name_pfx(block: IpBlock, iface_name: Optional[str]) -> str: return block.name.lower() + ('' if iface_name is None else '_{}'.format(iface_name.lower())) def get_r0(reg: RegBase) -> Register: '''Get a Register representing an entry in the RegBase''' if isinstance(reg, Register): return reg else: assert isinstance(reg, MultiRegister) return reg.reg def get_iface_tx_type(block: IpBlock, iface_name: Optional[str], hw2reg: bool) -> str: x2x = 'hw2reg' if hw2reg else 'reg2hw' pfx = get_type_name_pfx(block, iface_name) return '_'.join([pfx, x2x, 't']) def get_reg_tx_type(block: IpBlock, reg: RegBase, hw2reg: bool) -> str: '''Get the name of the hw2reg or reg2hw type for reg''' if isinstance(reg, Register): r0 = reg type_suff = 'reg_t' else: assert isinstance(reg, MultiRegister) r0 = reg.reg type_suff = 'mreg_t' x2x = 'hw2reg' if hw2reg else 'reg2hw' return '_'.join([block.name.lower(), x2x, r0.name.lower(), type_suff]) def gen_rtl(block: IpBlock, outdir: str) -> int: # Read Register templates reg_top_tpl = Template( filename=resource_filename('reggen', 'reg_top.sv.tpl')) reg_pkg_tpl = Template( filename=resource_filename('reggen', 'reg_pkg.sv.tpl')) # Generate <block>_reg_pkg.sv # # This defines the various types used to interface between the *_reg_top # module(s) and the block itself. reg_pkg_path = os.path.join(outdir, block.name.lower() + "_reg_pkg.sv") with open(reg_pkg_path, 'w', encoding='UTF-8') as fout: try: fout.write(reg_pkg_tpl.render(block=block)) except: # noqa F722 for template Exception handling log.error(exceptions.text_error_template().render()) return 1 # Generate the register block implementation(s). For a device interface # with no name we generate the register module "<block>_reg_top" (writing # to <block>_reg_top.sv). In any other case, we also need the interface # name, giving <block>_<ifname>_reg_top. lblock = block.name.lower() for if_name, rb in block.reg_blocks.items(): if if_name is None: mod_base = lblock else: mod_base = lblock + '_' + if_name.lower() mod_name = mod_base + '_reg_top' reg_top_path = os.path.join(outdir, mod_name + '.sv') with open(reg_top_path, 'w', encoding='UTF-8') as fout: try: fout.write(reg_top_tpl.render(block=block, mod_base=mod_base, mod_name=mod_name, if_name=if_name, rb=rb)) except: # noqa F722 for template Exception handling log.error(exceptions.text_error_template().render()) return 1 return 0 def render_param(dst_type: str, value: str) -> str: '''Render a parameter value as used for the destination type The value is itself a string but we have already checked that if dst_type happens to be "int" or "int unsigned" then it can be parsed as an integer. If dst_type is "int unsigned" and the value is larger than 2^31 then explicitly generate a 32-bit hex value. This allows 32-bit literals whose top bits are set (which can't be written as bare integers in SystemVerilog without warnings, because those are interpreted as ints). ''' if dst_type == 'int unsigned': # This shouldn't fail because we've already checked it in # _parse_parameter in params.py int_val = check_int(value, "integer parameter") if int_val >= (1 << 31): return "32'h{:08x}".format(int_val) return value
lowRISC/opentitan
util/reggen/gen_rtl.py
Python
apache-2.0
5,763
0
#Stage 2 Update (Python 3) from __future__ import print_function from __future__ import unicode_literals from builtins import str import datetime from optparse import make_option from django.conf import settings from django.core.mail import mail_admins from django.core.management import CommandError from django.core.management.base import BaseCommand from dynamic_scraper.models import Scraper class Command(BaseCommand): help = 'Checks last checker deletes of a scraper being older than <last_checker_delete_alert_period> period provided in admin form' def add_arguments(self, parser): parser.add_argument('--only-active', type=bool, default=False, help="Run checker delete checks only for active scrapers, default=False") parser.add_argument('--send-admin-mail', type=bool, default=False, help="Send report mail to Django admins if last deletes are too old, default=False") parser.add_argument('--with-next-alert', type=bool, default=False, help="Only run for scrapers with past next alert timestamp/update timestamp afterwards, default=False") def handle(self, *args, **options): mail_to_admins = False msg = '' only_active = options['only_active'] send_admin_mail = options['send_admin_mail'] with_next_alert = options['with_next_alert'] if with_next_alert: scrapers = Scraper.objects.filter(next_last_checker_delete_alert__lte=datetime.datetime.now()) print("{num} scraper(s) with future next alert timestamp found in DB...\n".format(num=len(scrapers))) else: scrapers = Scraper.objects.all() print("{num} scraper(s) found in DB...\n".format(num=len(scrapers))) for s in scrapers: if not (only_active and s.status != 'A'): td = s.get_last_checker_delete_alert_period_timedelta() if td: period = s.last_checker_delete_alert_period s_str = "SCRAPER: {scraper}\nID:{id}, Status:{status}, Alert Period:{period}".format( scraper=str(s), id=s.pk, status=s.get_status_display(), period=period) print(s_str) if with_next_alert: s.next_last_checker_delete_alert = datetime.datetime.now() + td s.save() if not s.last_checker_delete or \ (s.last_checker_delete < (datetime.datetime.now() - td)): if s.last_checker_delete: error_str = "Last checker delete older than alert period ({date_str})!".format( date_str=s.last_checker_delete.strftime('%Y-%m-%d %H:%m'),) else: error_str = "Last checker delete not available!" print(error_str) msg += s_str + '\n' + error_str + '\n\n' mail_to_admins = True else: print("OK") print() else: print("Ommitting scraper {scraper}, no (valid) time period set.\n".format(scraper=str(s))) else: print("Ommitting scraper {scraper}, not active.\n".format(scraper=str(s))) if send_admin_mail and mail_to_admins: print("Send mail to admins...") if 'django.contrib.sites' in settings.INSTALLED_APPS: from django.contrib.sites.models import Site subject = Site.objects.get_current().name else: subject = 'DDS Scraper Site' subject += " - Last checker delete check for scraper(s) failed" mail_admins(subject, msg)
DeanSherwin/django-dynamic-scraper
dynamic_scraper/management/commands/check_last_checker_deletes.py
Python
bsd-3-clause
3,890
0.007969
from __future__ import division, print_function import json from collections import Iterable, OrderedDict, namedtuple import numpy as np from six import string_types def isnamedtuple(obj): """Heuristic check if an object is a namedtuple.""" return isinstance(obj, tuple) \ and hasattr(obj, "_fields") \ and hasattr(obj, "_asdict") \ and callable(obj._asdict) def serialize(data): if data is None or isinstance(data, (bool, int, float, str, string_types)): return data if isinstance(data, list): return [serialize(val) for val in data] if isinstance(data, OrderedDict): return {"py/collections.OrderedDict": [[serialize(k), serialize(v)] for k, v in data.items()]} if isnamedtuple(data): return {"py/collections.namedtuple": { "type": type(data).__name__, "fields": list(data._fields), "values": [serialize(getattr(data, f)) for f in data._fields]}} if isinstance(data, dict): if all(isinstance(k, str) for k in data): return {k: serialize(v) for k, v in data.items()} return {"py/dict": [[serialize(k), serialize(v)] for k, v in data.items()]} if isinstance(data, tuple): return {"py/tuple": [serialize(val) for val in data]} if isinstance(data, set): return {"py/set": [serialize(val) for val in data]} if isinstance(data, np.ndarray): return {"py/numpy.ndarray": { "values": data.tolist(), "dtype": str(data.dtype)}} raise TypeError("Type %s not data-serializable" % type(data)) def restore(dct): if "py/dict" in dct: return dict(dct["py/dict"]) if "py/tuple" in dct: return tuple(dct["py/tuple"]) if "py/set" in dct: return set(dct["py/set"]) if "py/collections.namedtuple" in dct: data = dct["py/collections.namedtuple"] return namedtuple(data["type"], data["fields"])(*data["values"]) if "py/numpy.ndarray" in dct: data = dct["py/numpy.ndarray"] return np.array(data["values"], dtype=data["dtype"]) if "py/collections.OrderedDict" in dct: return OrderedDict(dct["py/collections.OrderedDict"]) return dct def data_to_json(data): return json.dumps(serialize(data)) def json_to_data(s): return json.loads(s, object_hook=restore)
chemlab/chemlab
chemlab/core/serialization.py
Python
gpl-3.0
2,379
0.003363
import pyparsing """ The query language that won't die. Syntax: Typical search engine query language, terms with boolean operators and parenthesized grouping: (term AND (term OR term OR ...) AND NOT term ...) In it's simplest case, xaql searches for a list of terms: term term term ... This expands to '(term AND term AND term AND ...)' Terms can be prefixed. The prefix and the value are separated by colons. Values that contain spaces must be double quoted. term color:blue name:"My Lagoon" Functions: Functions provide features that take query input from the user and do some transformation on the query itself. Functions begin with a star, then a name, then a pair of parenthesis that contain the query input. The syntax of the input is up to the function: $xp(...) -- Pass the input string directly into the Xapian query parser. $rel(...) $now Prefix Modifiers: This are pre-prefixes that transform the following term. published-before:now """
michelp/xodb
xodb/xaql.py
Python
mit
1,060
0.001887
# coding: utf-8 import time, datetime # 接收的参数可以为:1. 时间戳字符串 2. datetime, 3. None def unixtime_fromtimestamp(dt = None): if dt and isinstance(dt, datetime.datetime) : return int(time.mktime(dt.timetuple())) elif dt and isinstance(dt, basestring) : return int(time.mktime(time.strptime(dt, '%Y-%m-%d %H:%M:%S'))) else: return int(time.mktime(datetime.datetime.now().timetuple())) # value为传入的值为时间戳(整形),如:1332888820 def timestamp_fromunixtime(value=None, format=None): return time.strftime(format if format else '%Y-%m-%d %H:%M:%S' , time.localtime(value if value else unixtime_fromtimestamp())) def timestamp_fromunixtime2(value=None, format=None): return time.strftime(format if format else '%Y%m%d_%H%M%S' , time.localtime(value if value else unixtime_fromtimestamp())) if __name__ == "__main__": # print unixtime_fromtimestamp() print unixtime_fromtimestamp(datetime.datetime.today())
cychenyin/sfproxy
py/timeutils.py
Python
apache-2.0
1,010
0.02521
import math class Neptune: """ NEPTUNE - VSOP87 Series Version C HELIOCENTRIC DYNAMICAL ECLIPTIC AND EQUINOX OF THE DATE Rectangular (X,Y,Z) Coordinates in AU (Astronomical Units) Series Validity Span: 4000 BC < Date < 8000 AD Theoretical accuracy over span: +-1 arc sec R*R = X*X + Y*Y + Z*Z t = (JD - 2451545) / 365250 C++ Programming Language VSOP87 Functions Source Code Generated By The VSOP87 Source Code Generator Tool (c) Jay Tanner 2015 Ref: Planetary Theories in Rectangular and Spherical Variables VSOP87 Solutions Pierre Bretagnon, Gerard Francou Journal of Astronomy & Astrophysics vol. 202, p309-p315 1988 Source code provided under the provisions of the GNU General Public License (GPL), version 3. http://www.gnu.org/licenses/gpl.html """ def __init__(self, t): self.t = t def calculate(self): # Neptune_X0 (t) // 821 terms of order 0 X0 = 0 X0 += 30.05973100580 * math.cos(5.31188633083 + 38.3768531213 * self.t) X0 += 0.40567587218 * math.cos(3.98149970131 + 0.2438174835 * self.t) X0 += 0.13506026414 * math.cos(3.50055820972 + 76.50988875911 * self.t) X0 += 0.15716341901 * math.cos(0.11310077968 + 36.892380413 * self.t) X0 += 0.14935642614 * math.cos(1.08477702063 + 39.86132582961 * self.t) X0 += 0.02590782232 * math.cos(1.99609768221 + 1.7282901918 * self.t) X0 += 0.01073890204 * math.cos(5.38477153556 + 75.0254160508 * self.t) X0 += 0.00816388197 * math.cos(0.78185518038 + 3.21276290011 * self.t) X0 += 0.00702768075 * math.cos(1.45363642119 + 35.40790770471 * self.t) X0 += 0.00687594822 * math.cos(0.72075739344 + 37.88921815429 * self.t) X0 += 0.00565555652 * math.cos(5.98943773879 + 41.3457985379 * self.t) X0 += 0.00495650075 * math.cos(0.59957534348 + 529.9347825781 * self.t) X0 += 0.00306025380 * math.cos(0.39916788140 + 73.5409433425 * self.t) X0 += 0.00272446904 * math.cos(0.87404115637 + 213.5429129215 * self.t) X0 += 0.00135892298 * math.cos(5.54654979922 + 77.9943614674 * self.t) X0 += 0.00122117697 * math.cos(1.30863876781 + 34.9202727377 * self.t) X0 += 0.00090968285 * math.cos(1.68886748674 + 114.6429243969 * self.t) X0 += 0.00068915400 * math.cos(5.83470374400 + 4.6972356084 * self.t) X0 += 0.00040370680 * math.cos(2.66129691063 + 33.9234349964 * self.t) X0 += 0.00028891307 * math.cos(4.78947715515 + 42.83027124621 * self.t) X0 += 0.00029247752 * math.cos(1.62319522731 + 72.05647063421 * self.t) X0 += 0.00025576289 * math.cos(1.48342967006 + 71.5688356672 * self.t) X0 += 0.00020517968 * math.cos(2.55621077117 + 33.43580002939 * self.t) X0 += 0.00012614154 * math.cos(3.56929744338 + 113.15845168861 * self.t) X0 += 0.00012788929 * math.cos(2.73769634046 + 111.67397898031 * self.t) X0 += 0.00012013477 * math.cos(0.94915799508 + 1059.6257476727 * self.t) X0 += 0.00009854638 * math.cos(0.25713641240 + 36.404745446 * self.t) X0 += 0.00008385825 * math.cos(1.65242210861 + 108.2173985967 * self.t) X0 += 0.00007577585 * math.cos(0.09970777629 + 426.8420083595 * self.t) X0 += 0.00006452053 * math.cos(4.62556526073 + 6.1817083167 * self.t) X0 += 0.00006551074 * math.cos(1.91884050790 + 1.24065522479 * self.t) X0 += 0.00004652534 * math.cos(0.10344003066 + 37.8555882595 * self.t) X0 += 0.00004732958 * math.cos(4.09711900918 + 79.47883417571 * self.t) X0 += 0.00004557247 * math.cos(1.09712661798 + 38.89811798311 * self.t) X0 += 0.00004322550 * math.cos(2.37744779374 + 38.32866901151 * self.t) X0 += 0.00004315539 * math.cos(5.10473140788 + 38.4250372311 * self.t) X0 += 0.00004089036 * math.cos(1.99429063701 + 37.4136452748 * self.t) X0 += 0.00004248658 * math.cos(5.63379709294 + 28.81562556571 * self.t) X0 += 0.00004622142 * math.cos(2.73995451568 + 70.08436295889 * self.t) X0 += 0.00003926447 * math.cos(5.48975060892 + 39.34006096781 * self.t) X0 += 0.00003148422 * math.cos(5.18755364576 + 76.0222537921 * self.t) X0 += 0.00003940981 * math.cos(2.29766376691 + 98.6561710411 * self.t) X0 += 0.00003323363 * math.cos(4.68776245279 + 4.4366031775 * self.t) X0 += 0.00003282964 * math.cos(2.81551282614 + 39.3736908626 * self.t) X0 += 0.00003110464 * math.cos(1.84416897204 + 47.9380806769 * self.t) X0 += 0.00002927062 * math.cos(2.83767313961 + 70.5719979259 * self.t) X0 += 0.00002748919 * math.cos(3.86990252936 + 32.4389622881 * self.t) X0 += 0.00003316668 * math.cos(1.82194084200 + 144.8659615262 * self.t) X0 += 0.00002822405 * math.cos(3.78131048254 + 31.9513273211 * self.t) X0 += 0.00002695972 * math.cos(3.85276301548 + 110.189506272 * self.t) X0 += 0.00002522990 * math.cos(4.66308619966 + 311.9552664791 * self.t) X0 += 0.00001888129 * math.cos(3.20464683230 + 35.9291725665 * self.t) X0 += 0.00001648229 * math.cos(4.07040254381 + 30.300098274 * self.t) X0 += 0.00001826545 * math.cos(3.58021128918 + 44.31474395451 * self.t) X0 += 0.00001956241 * math.cos(4.14516146871 + 206.42936592071 * self.t) X0 += 0.00001681257 * math.cos(4.27560127770 + 40.8245336761 * self.t) X0 += 0.00001533383 * math.cos(1.17732213608 + 38.26497853671 * self.t) X0 += 0.00001893076 * math.cos(0.75017402977 + 220.6564599223 * self.t) X0 += 0.00001527526 * math.cos(0.02173638301 + 38.4887277059 * self.t) X0 += 0.00002085691 * math.cos(1.56948272604 + 149.8070146181 * self.t) X0 += 0.00002070612 * math.cos(2.82581806721 + 136.78920667889 * self.t) X0 += 0.00001535699 * math.cos(0.61413315675 + 73.0533083755 * self.t) X0 += 0.00001667976 * math.cos(2.91712458990 + 106.73292588839 * self.t) X0 += 0.00001289620 * math.cos(3.39708861100 + 46.4536079686 * self.t) X0 += 0.00001559811 * math.cos(0.55870841967 + 38.11622069041 * self.t) X0 += 0.00001545705 * math.cos(0.64028776037 + 38.6374855522 * self.t) X0 += 0.00001435033 * math.cos(0.72855949679 + 522.8212355773 * self.t) X0 += 0.00001406206 * math.cos(3.61717027558 + 537.0483295789 * self.t) X0 += 0.00001256446 * math.cos(2.70907758736 + 34.1840674273 * self.t) X0 += 0.00001387973 * math.cos(3.71843398082 + 116.12739710521 * self.t) X0 += 0.00001457739 * math.cos(1.98981635014 + 181.5145244557 * self.t) X0 += 0.00001228429 * math.cos(2.78646343835 + 72.31710306511 * self.t) X0 += 0.00001140665 * math.cos(3.96643713353 + 7.83293736379 * self.t) X0 += 0.00001080801 * math.cos(4.75483465055 + 42.5696388153 * self.t) X0 += 0.00001201409 * math.cos(0.74547986507 + 2.7251279331 * self.t) X0 += 0.00001228671 * math.cos(2.65249731727 + 148.32254190981 * self.t) X0 += 0.00000722014 * math.cos(6.16806714444 + 152.77596003471 * self.t) X0 += 0.00000608545 * math.cos(4.49536985567 + 35.4560918145 * self.t) X0 += 0.00000722865 * math.cos(3.09340262825 + 143.38148881789 * self.t) X0 += 0.00000632820 * math.cos(3.41702130042 + 7.66618102501 * self.t) X0 += 0.00000642369 * math.cos(3.97490787694 + 68.5998902506 * self.t) X0 += 0.00000553789 * math.cos(2.98606728111 + 41.2976144281 * self.t) X0 += 0.00000682276 * math.cos(2.15806346682 + 218.1630873852 * self.t) X0 += 0.00000463186 * math.cos(2.74420554348 + 31.7845709823 * self.t) X0 += 0.00000521560 * math.cos(0.34813640632 + 0.719390363 * self.t) X0 += 0.00000437892 * math.cos(1.29807722623 + 1589.3167127673 * self.t) X0 += 0.00000398091 * math.cos(5.50783691510 + 6.3484646555 * self.t) X0 += 0.00000384065 * math.cos(4.72632236146 + 44.96913526031 * self.t) X0 += 0.00000395583 * math.cos(5.05527677390 + 108.70503356371 * self.t) X0 += 0.00000327446 * math.cos(2.69199709491 + 60.52313540329 * self.t) X0 += 0.00000358824 * math.cos(4.99912098256 + 30.4668546128 * self.t) X0 += 0.00000315179 * math.cos(0.17468500209 + 74.53778108379 * self.t) X0 += 0.00000343384 * math.cos(1.74645896957 + 0.7650823453 * self.t) X0 += 0.00000399611 * math.cos(5.33540800911 + 31.2633061205 * self.t) X0 += 0.00000314611 * math.cos(2.98803024638 + 419.72846135871 * self.t) X0 += 0.00000347596 * math.cos(3.26643963659 + 180.03005174739 * self.t) X0 += 0.00000382279 * math.cos(0.21764578681 + 487.1213262793 * self.t) X0 += 0.00000300918 * math.cos(4.04922612099 + 69.0875252176 * self.t) X0 += 0.00000340448 * math.cos(3.90546849629 + 146.8380692015 * self.t) X0 += 0.00000298710 * math.cos(5.18013539651 + 84.5866436064 * self.t) X0 += 0.00000290629 * math.cos(1.74873675275 + 110.45013870291 * self.t) X0 += 0.00000336211 * math.cos(2.14815098729 + 45.49040012211 * self.t) X0 += 0.00000305606 * math.cos(5.63265481978 + 640.1411037975 * self.t) X0 += 0.00000333702 * math.cos(2.32938316969 + 254.8116503147 * self.t) X0 += 0.00000268060 * math.cos(3.30852201658 + 37.0042549976 * self.t) X0 += 0.00000264760 * math.cos(4.12724058864 + 39.749451245 * self.t) X0 += 0.00000315240 * math.cos(2.72241788492 + 388.70897272171 * self.t) X0 += 0.00000227098 * math.cos(4.59157281152 + 273.8222308413 * self.t) X0 += 0.00000306112 * math.cos(1.75345186469 + 6283.3196674749 * self.t) X0 += 0.00000284373 * math.cos(3.36139825385 + 12.77399045571 * self.t) X0 += 0.00000221105 * math.cos(3.50940363876 + 213.0552779545 * self.t) X0 += 0.00000242568 * math.cos(2.06437650010 + 14.258463164 * self.t) X0 += 0.00000241087 * math.cos(4.16115355874 + 105.2484531801 * self.t) X0 += 0.00000226136 * math.cos(2.83815938853 + 80.963306884 * self.t) X0 += 0.00000245904 * math.cos(0.54462524204 + 27.3311528574 * self.t) X0 += 0.00000265825 * math.cos(4.10952660358 + 944.7390057923 * self.t) X0 += 0.00000207893 * math.cos(5.07812851336 + 30.95448957981 * self.t) X0 += 0.00000214661 * math.cos(2.65402494691 + 316.6356871401 * self.t) X0 += 0.00000190638 * math.cos(2.32667703756 + 69.3963417583 * self.t) X0 += 0.00000246295 * math.cos(1.98638488517 + 102.84895673509 * self.t) X0 += 0.00000202915 * math.cos(0.60029260077 + 415.04804069769 * self.t) X0 += 0.00000176465 * math.cos(0.14731292877 + 36.7805058284 * self.t) X0 += 0.00000193886 * math.cos(3.35476299352 + 174.9222423167 * self.t) X0 += 0.00000175209 * math.cos(1.12575693515 + 39.97320041421 * self.t) X0 += 0.00000177868 * math.cos(3.43923391414 + 216.67861467689 * self.t) X0 += 0.00000138494 * math.cos(5.45265920432 + 75.98862389731 * self.t) X0 += 0.00000152234 * math.cos(4.81662104772 + 11.2895177474 * self.t) X0 += 0.00000147648 * math.cos(1.68543706672 + 151.2914873264 * self.t) X0 += 0.00000156202 * math.cos(3.65252575052 + 146.3504342345 * self.t) X0 += 0.00000152289 * math.cos(0.07345728764 + 23.87457247379 * self.t) X0 += 0.00000177911 * math.cos(3.17643554721 + 10213.5293636945 * self.t) X0 += 0.00000162474 * math.cos(4.13351391379 + 63.9797157869 * self.t) X0 += 0.00000121226 * math.cos(5.10584286197 + 38.16440480021 * self.t) X0 += 0.00000129049 * math.cos(3.80684906955 + 37.1048287341 * self.t) X0 += 0.00000120334 * math.cos(2.37637214462 + 38.5893014424 * self.t) X0 += 0.00000168977 * math.cos(2.49551838497 + 291.4602132442 * self.t) X0 += 0.00000121138 * math.cos(1.49657109299 + 33.26904369061 * self.t) X0 += 0.00000129366 * math.cos(2.36903010922 + 45.7992166628 * self.t) X0 += 0.00000144682 * math.cos(0.63023431786 + 49.42255338521 * self.t) X0 += 0.00000122915 * math.cos(3.67433526761 + 39.6488775085 * self.t) X0 += 0.00000113400 * math.cos(0.42160185021 + 83.1021708981 * self.t) X0 += 0.00000154892 * math.cos(1.74989069653 + 77.4730966056 * self.t) X0 += 0.00000106737 * math.cos(0.57437068095 + 4.8639919472 * self.t) X0 += 0.00000104756 * math.cos(5.96272070512 + 43.484662552 * self.t) X0 += 0.00000125142 * math.cos(5.82780261996 + 4.2096006414 * self.t) X0 += 0.00000103541 * math.cos(5.25634741505 + 41.08516610701 * self.t) X0 += 0.00000133573 * math.cos(3.92147215781 + 182.998997164 * self.t) X0 += 0.00000103627 * math.cos(2.29256111601 + 35.6685401356 * self.t) X0 += 0.00000116874 * math.cos(5.41378396536 + 62.4952430786 * self.t) X0 += 0.00000098063 * math.cos(3.25654027665 + 9.8050450391 * self.t) X0 += 0.00000111411 * math.cos(4.34345309647 + 141.8970161096 * self.t) X0 += 0.00000114294 * math.cos(5.56228935636 + 633.0275567967 * self.t) X0 += 0.00000104705 * math.cos(6.26072139356 + 433.9555553603 * self.t) X0 += 0.00000121306 * math.cos(1.44892345337 + 40.8581635709 * self.t) X0 += 0.00000096954 * math.cos(6.17373469303 + 1052.51220067191 * self.t) X0 += 0.00000085104 * math.cos(4.79018222360 + 36.6799320919 * self.t) X0 += 0.00000085209 * math.cos(5.94497188324 + 105.76971804189 * self.t) X0 += 0.00000085291 * math.cos(2.59495207397 + 109.701871305 * self.t) X0 += 0.00000083260 * math.cos(0.00625676877 + 529.44714761109 * self.t) X0 += 0.00000080200 * math.cos(2.69199769694 + 40.07377415071 * self.t) X0 += 0.00000107927 * math.cos(0.01570870082 + 1162.7185218913 * self.t) X0 += 0.00000095241 * math.cos(3.61102256601 + 253.32717760639 * self.t) X0 += 0.00000089535 * math.cos(3.25178384851 + 32.9602271499 * self.t) X0 += 0.00000089793 * math.cos(2.76430560225 + 65.46418849521 * self.t) X0 += 0.00000072027 * math.cos(0.11366576076 + 36.9405645228 * self.t) X0 += 0.00000080381 * math.cos(5.21057317852 + 67.1154175423 * self.t) X0 += 0.00000099502 * math.cos(2.53010647936 + 453.1810763355 * self.t) X0 += 0.00000088685 * math.cos(1.33848394125 + 251.6759485593 * self.t) X0 += 0.00000094971 * math.cos(4.11602347578 + 219.6475600935 * self.t) X0 += 0.00000077015 * math.cos(5.30660266172 + 5.6604434549 * self.t) X0 += 0.00000069098 * math.cos(1.84984192453 + 22.3900997655 * self.t) X0 += 0.00000079079 * math.cos(4.12824954018 + 44.48150029329 * self.t) X0 += 0.00000069159 * math.cos(3.95901333551 + 1066.7392946735 * self.t) X0 += 0.00000064446 * math.cos(4.03076164648 + 66.9486612035 * self.t) X0 += 0.00000088518 * math.cos(2.66179796694 + 328.1087761737 * self.t) X0 += 0.00000065817 * math.cos(1.42821476263 + 36.3711155512 * self.t) X0 += 0.00000071422 * math.cos(4.23104971231 + 43.79347909271 * self.t) X0 += 0.00000063298 * math.cos(2.21146718451 + 9.1506537333 * self.t) X0 += 0.00000077320 * math.cos(0.26842720811 + 97.17169833279 * self.t) X0 += 0.00000073912 * math.cos(1.72397638430 + 2.6769438233 * self.t) X0 += 0.00000073965 * math.cos(5.55809543248 + 2.9521304692 * self.t) X0 += 0.00000056194 * math.cos(4.45857439361 + 949.4194264533 * self.t) X0 += 0.00000059173 * math.cos(1.41372632607 + 100.14064374939 * self.t) X0 += 0.00000067507 * math.cos(3.94700376513 + 7.14491616321 * self.t) X0 += 0.00000071718 * math.cos(0.93392607299 + 2.20386307129 * self.t) X0 += 0.00000063606 * math.cos(5.17175542607 + 25.8466801491 * self.t) X0 += 0.00000071523 * math.cos(2.05830478088 + 662.28738607949 * self.t) X0 += 0.00000057219 * math.cos(0.88485013288 + 15.7429358723 * self.t) X0 += 0.00000050322 * math.cos(1.08310288762 + 37.15301284391 * self.t) X0 += 0.00000066615 * math.cos(3.42462264660 + 846.3266522347 * self.t) X0 += 0.00000056220 * math.cos(4.52386924168 + 178.5455790391 * self.t) X0 += 0.00000067883 * math.cos(3.88546727303 + 224.5886131854 * self.t) X0 += 0.00000057761 * math.cos(5.16493680948 + 145.35359649321 * self.t) X0 += 0.00000053973 * math.cos(6.25404762289 + 107.2205608554 * self.t) X0 += 0.00000057588 * math.cos(4.84839311245 + 25.3590451821 * self.t) X0 += 0.00000049026 * math.cos(1.27836371915 + 19.2543980101 * self.t) X0 += 0.00000063036 * math.cos(4.29760573349 + 256.296123023 * self.t) X0 += 0.00000045304 * math.cos(0.86492921312 + 4.1759707466 * self.t) X0 += 0.00000045669 * math.cos(2.17547535945 + 117.6118698135 * self.t) X0 += 0.00000052821 * math.cos(3.77933473571 + 289.97574053589 * self.t) X0 += 0.00000044016 * math.cos(2.25498623278 + 32.7477788288 * self.t) X0 += 0.00000042933 * math.cos(6.21504221321 + 28.98238190449 * self.t) X0 += 0.00000038369 * math.cos(0.36602717013 + 39.6006933987 * self.t) X0 += 0.00000038805 * math.cos(4.12403932769 + 103.3365917021 * self.t) X0 += 0.00000037679 * math.cos(3.40097359574 + 9.3174100721 * self.t) X0 += 0.00000040292 * math.cos(6.03933270535 + 111.18634401329 * self.t) X0 += 0.00000050011 * math.cos(6.19966711969 + 221.61966776881 * self.t) X0 += 0.00000037056 * math.cos(4.63008749202 + 8.32057233081 * self.t) X0 += 0.00000036562 * math.cos(0.18548635975 + 448.98829064149 * self.t) X0 += 0.00000044628 * math.cos(3.82762130859 + 525.2543619171 * self.t) X0 += 0.00000038213 * math.cos(0.28030378709 + 75.54668091261 * self.t) X0 += 0.00000045963 * math.cos(4.06403723861 + 183.486632131 * self.t) X0 += 0.00000048222 * math.cos(2.81328685847 + 364.7573391032 * self.t) X0 += 0.00000038164 * math.cos(5.23367149002 + 44.00592741381 * self.t) X0 += 0.00000047779 * math.cos(6.19272750750 + 3340.8562441833 * self.t) X0 += 0.00000042228 * math.cos(5.64690940917 + 77.0311536209 * self.t) X0 += 0.00000035247 * math.cos(0.20766845689 + 34.7535163989 * self.t) X0 += 0.00000046804 * math.cos(3.96902162832 + 33.6964324603 * self.t) X0 += 0.00000034352 * math.cos(1.08289070011 + 33.71098667531 * self.t) X0 += 0.00000034949 * math.cos(2.01384094499 + 3.37951923889 * self.t) X0 += 0.00000036030 * math.cos(2.17275904548 + 71.09326278771 * self.t) X0 += 0.00000038112 * math.cos(5.65470955047 + 45.9659730016 * self.t) X0 += 0.00000033119 * math.cos(5.27794057043 + 7.3573644843 * self.t) X0 += 0.00000032049 * math.cos(4.61840704188 + 34.44469985821 * self.t) X0 += 0.00000031910 * math.cos(1.77890975693 + 81.61769818981 * self.t) X0 += 0.00000038697 * math.cos(2.66910057126 + 184.97110483931 * self.t) X0 += 0.00000041486 * math.cos(2.58550378076 + 310.4707937708 * self.t) X0 += 0.00000038631 * math.cos(2.31715796823 + 50.9070260935 * self.t) X0 += 0.00000042711 * math.cos(2.19232104972 + 1021.49271203491 * self.t) X0 += 0.00000032006 * math.cos(0.97590559431 + 42.00018984371 * self.t) X0 += 0.00000038436 * math.cos(0.31352578874 + 5.92107588581 * self.t) X0 += 0.00000038880 * math.cos(3.29381198979 + 76.55807286891 * self.t) X0 += 0.00000041190 * math.cos(4.58002024645 + 563.87503252191 * self.t) X0 += 0.00000029786 * math.cos(1.00565266044 + 77.5067265004 * self.t) X0 += 0.00000040604 * math.cos(4.47511985144 + 292.9446859525 * self.t) X0 += 0.00000035275 * math.cos(1.67517293934 + 304.84171947829 * self.t) X0 += 0.00000038242 * math.cos(2.80091349300 + 17.76992530181 * self.t) X0 += 0.00000034445 * math.cos(4.48124108827 + 319.06881347989 * self.t) X0 += 0.00000028725 * math.cos(5.51593817617 + 67.6366824041 * self.t) X0 += 0.00000032809 * math.cos(5.57900930431 + 91.54262404029 * self.t) X0 += 0.00000038880 * math.cos(0.56654650956 + 76.4617046493 * self.t) X0 += 0.00000030731 * math.cos(5.22467991145 + 67.60305250931 * self.t) X0 += 0.00000028459 * math.cos(0.11298908847 + 43.0427195673 * self.t) X0 += 0.00000035368 * math.cos(3.56936550095 + 313.43973918739 * self.t) X0 += 0.00000035703 * math.cos(0.06787236157 + 258.26823069831 * self.t) X0 += 0.00000032317 * math.cos(2.30071476395 + 78.9575693139 * self.t) X0 += 0.00000029243 * math.cos(0.30724049567 + 61.01077037031 * self.t) X0 += 0.00000026235 * math.cos(3.88058959053 + 137.2768416459 * self.t) X0 += 0.00000026519 * math.cos(6.20266742881 + 57.4993082325 * self.t) X0 += 0.00000024931 * math.cos(5.73688334159 + 42.997027585 * self.t) X0 += 0.00000027608 * math.cos(5.39681935370 + 103.7639804718 * self.t) X0 += 0.00000028680 * math.cos(4.65490114562 + 215.1941419686 * self.t) X0 += 0.00000025052 * math.cos(5.70195779765 + 350.08830211689 * self.t) X0 += 0.00000031386 * math.cos(4.10756442698 + 22.22334342671 * self.t) X0 += 0.00000027545 * math.cos(1.30787829275 + 100.6282787164 * self.t) X0 += 0.00000022617 * math.cos(3.46251776435 + 36.8441963032 * self.t) X0 += 0.00000024909 * math.cos(0.20851017271 + 24.36220744081 * self.t) X0 += 0.00000026216 * math.cos(4.94808817995 + 491.8017469403 * self.t) X0 += 0.00000028040 * math.cos(2.83295165264 + 11.55015017831 * self.t) X0 += 0.00000023047 * math.cos(4.24570423583 + 35.51978228931 * self.t) X0 += 0.00000027067 * math.cos(3.95547247738 + 326.62430346539 * self.t) X0 += 0.00000026192 * math.cos(2.35959813381 + 20.7388707184 * self.t) X0 += 0.00000023134 * math.cos(2.59485537406 + 68.4331339118 * self.t) X0 += 0.00000021423 * math.cos(0.87822750255 + 39.90950993941 * self.t) X0 += 0.00000025696 * math.cos(0.32414101638 + 186.4555775476 * self.t) X0 += 0.00000026985 * math.cos(3.53264939991 + 69.6087900794 * self.t) X0 += 0.00000023284 * math.cos(2.71588030137 + 79.43065006591 * self.t) X0 += 0.00000022894 * math.cos(0.61847067768 + 227.77000692311 * self.t) X0 += 0.00000022482 * math.cos(0.72349596890 + 39.8131417198 * self.t) X0 += 0.00000023480 * math.cos(4.39643703557 + 30.9881194746 * self.t) X0 += 0.00000020858 * math.cos(3.23577429095 + 41.2339239533 * self.t) X0 += 0.00000020327 * math.cos(1.15567976096 + 39.0312444271 * self.t) X0 += 0.00000020327 * math.cos(0.04331485179 + 37.72246181551 * self.t) X0 += 0.00000022639 * math.cos(0.21515321589 + 0.9800227939 * self.t) X0 += 0.00000022639 * math.cos(0.21515321589 + 1.46765776091 * self.t) X0 += 0.00000019139 * math.cos(0.03506366059 + 205.9417309537 * self.t) X0 += 0.00000019118 * math.cos(1.62564867989 + 2119.00767786191 * self.t) X0 += 0.00000025698 * math.cos(2.97643019475 + 401.4059020327 * self.t) X0 += 0.00000021582 * math.cos(4.29532713983 + 81.13006322279 * self.t) X0 += 0.00000025509 * math.cos(4.64829559110 + 329.593248882 * self.t) X0 += 0.00000024296 * math.cos(2.11682013072 + 62.0076081116 * self.t) X0 += 0.00000023969 * math.cos(0.88887585882 + 135.3047339706 * self.t) X0 += 0.00000020599 * math.cos(4.51946091131 + 491.3141119733 * self.t) X0 += 0.00000016829 * math.cos(5.63589438225 + 3.1645787903 * self.t) X0 += 0.00000020030 * math.cos(4.02146628228 + 217.4750661846 * self.t) X0 += 0.00000020377 * math.cos(0.89378346451 + 209.6107596584 * self.t) X0 += 0.00000017251 * math.cos(2.57319624936 + 350.5759370839 * self.t) X0 += 0.00000019625 * math.cos(6.12382765898 + 129.6756596781 * self.t) X0 += 0.00000022707 * math.cos(5.69106089810 + 1436.2969352491 * self.t) X0 += 0.00000017142 * math.cos(0.00501932570 + 29.4700168715 * self.t) X0 += 0.00000016188 * math.cos(4.90861200887 + 39.00999256771 * self.t) X0 += 0.00000016188 * math.cos(2.57356791106 + 37.7437136749 * self.t) X0 += 0.00000020858 * math.cos(4.67505024087 + 58.9837809408 * self.t) X0 += 0.00000015747 * math.cos(1.88900821622 + 154.260432743 * self.t) X0 += 0.00000019714 * math.cos(0.33238117487 + 294.91679362781 * self.t) X0 += 0.00000019078 * math.cos(2.73754913300 + 202.4972126576 * self.t) X0 += 0.00000021530 * math.cos(3.37996249680 + 114.1552894299 * self.t) X0 += 0.00000019068 * math.cos(1.82733694293 + 138.2736793872 * self.t) X0 += 0.00000018723 * math.cos(6.21404671018 + 323.74923414091 * self.t) X0 += 0.00000018916 * math.cos(5.47002080885 + 40.3825906914 * self.t) X0 += 0.00000015843 * math.cos(0.27660393480 + 72.577735496 * self.t) X0 += 0.00000020695 * math.cos(5.32080415125 + 86.07111631471 * self.t) X0 += 0.00000015895 * math.cos(5.73200518668 + 736.1203310153 * self.t) X0 += 0.00000014983 * math.cos(2.13549071268 + 743.23387801611 * self.t) X0 += 0.00000014928 * math.cos(0.78464963633 + 34.23225153711 * self.t) X0 += 0.00000015461 * math.cos(6.04598420333 + 20.850745303 * self.t) X0 += 0.00000016206 * math.cos(6.05974800797 + 138.76131435421 * self.t) X0 += 0.00000015978 * math.cos(0.85734083354 + 515.70768857651 * self.t) X0 += 0.00000014173 * math.cos(2.99587831656 + 99.1438060081 * self.t) X0 += 0.00000018749 * math.cos(3.37545937432 + 54.5303628159 * self.t) X0 += 0.00000013971 * math.cos(5.11256155147 + 76.77052119001 * self.t) X0 += 0.00000013971 * math.cos(5.03098185419 + 76.2492563282 * self.t) X0 += 0.00000014035 * math.cos(4.45768361334 + 235.68919520349 * self.t) X0 += 0.00000018894 * math.cos(4.59865824553 + 31.4757544416 * self.t) X0 += 0.00000014967 * math.cos(0.97104009185 + 52.3914988018 * self.t) X0 += 0.00000017392 * math.cos(1.69348450373 + 74.0622082043 * self.t) X0 += 0.00000014788 * math.cos(5.00944229014 + 56.01483552421 * self.t) X0 += 0.00000015758 * math.cos(5.97423795440 + 208.8624922605 * self.t) X0 += 0.00000012911 * math.cos(0.41434497695 + 42.5214547055 * self.t) X0 += 0.00000014356 * math.cos(4.89778066710 + 251.8427048981 * self.t) X0 += 0.00000016266 * math.cos(4.96350311575 + 853.4401992355 * self.t) X0 += 0.00000015513 * math.cos(1.02523907534 + 59.038662695 * self.t) X0 += 0.00000012783 * math.cos(2.34267333656 + 107.52937739611 * self.t) X0 += 0.00000016075 * math.cos(4.73335524561 + 366.24181181149 * self.t) X0 += 0.00000014277 * math.cos(4.88488299527 + 19.36627259471 * self.t) X0 += 0.00000014742 * math.cos(1.55115458505 + 82.4477795923 * self.t) X0 += 0.00000015111 * math.cos(4.13629021798 + 363.27286639489 * self.t) X0 += 0.00000014981 * math.cos(5.88358063018 + 82.6145359311 * self.t) X0 += 0.00000014840 * math.cos(0.62836299110 + 44.0541115236 * self.t) X0 += 0.00000015592 * math.cos(1.03195525294 + 8.6293888715 * self.t) X0 += 0.00000014568 * math.cos(2.02105422692 + 73.80157577341 * self.t) X0 += 0.00000012251 * math.cos(1.18824225128 + 47.28368937111 * self.t) X0 += 0.00000011447 * math.cos(0.91374266731 + 175.40987728371 * self.t) X0 += 0.00000013900 * math.cos(5.64591952885 + 700.4204217173 * self.t) X0 += 0.00000015583 * math.cos(3.88966860773 + 837.4534458797 * self.t) X0 += 0.00000012109 * math.cos(2.10142517621 + 33.0084112597 * self.t) X0 += 0.00000012379 * math.cos(5.59016916358 + 140.4125434013 * self.t) X0 += 0.00000011481 * math.cos(5.22670638349 + 39.2069345238 * self.t) X0 += 0.00000011481 * math.cos(2.25547353643 + 37.54677171881 * self.t) X0 += 0.00000011452 * math.cos(1.21111994028 + 529.4135177163 * self.t) X0 += 0.00000010981 * math.cos(0.01852111423 + 63.49208081989 * self.t) X0 += 0.00000012137 * math.cos(2.33017731448 + 42.3090063844 * self.t) X0 += 0.00000013771 * math.cos(4.49397894473 + 76.62176334371 * self.t) X0 += 0.00000011036 * math.cos(3.16457889057 + 530.45604743991 * self.t) X0 += 0.00000011537 * math.cos(4.29449656032 + 199.3158189199 * self.t) X0 += 0.00000011189 * math.cos(3.24467764115 + 80.1332254815 * self.t) X0 += 0.00000012835 * math.cos(1.26831311464 + 38.85242600079 * self.t) X0 += 0.00000012879 * math.cos(4.74400685998 + 5.69407334969 * self.t) X0 += 0.00000013663 * math.cos(3.12818073078 + 438.0544649622 * self.t) X0 += 0.00000010132 * math.cos(4.37559264666 + 187.9400502559 * self.t) X0 += 0.00000012619 * math.cos(4.66177013386 + 65.2035560643 * self.t) X0 += 0.00000010088 * math.cos(6.12382762451 + 26.58288545949 * self.t) X0 += 0.00000011959 * math.cos(5.90953104234 + 64.7159210973 * self.t) X0 += 0.00000011578 * math.cos(4.24710384177 + 275.3067035496 * self.t) X0 += 0.00000012795 * math.cos(3.23836197733 + 17.8817998864 * self.t) X0 += 0.00000013771 * math.cos(5.64956481971 + 76.3980141745 * self.t) X0 += 0.00000010044 * math.cos(0.10145082472 + 147.83490694279 * self.t) X0 += 0.00000013632 * math.cos(2.86683446064 + 45.277951801 * self.t) X0 += 0.00000011660 * math.cos(2.65801239040 + 143.9027536797 * self.t) X0 += 0.00000009938 * math.cos(4.21970476320 + 6.86972951729 * self.t) X0 += 0.00000009719 * math.cos(6.05786462616 + 956.53297345411 * self.t) X0 += 0.00000011441 * math.cos(0.61314587598 + 533.8669358412 * self.t) X0 += 0.00000010240 * math.cos(2.91846731922 + 80.7026744531 * self.t) X0 += 0.00000010031 * math.cos(5.38075474506 + 43.74529498291 * self.t) X0 += 0.00000010063 * math.cos(5.77064020369 + 0.27744737829 * self.t) X0 += 0.00000011428 * math.cos(3.77013145660 + 526.00262931501 * self.t) X0 += 0.00000009279 * math.cos(6.16721103485 + 79.6455905145 * self.t) X0 += 0.00000010172 * math.cos(2.46540726742 + 568.0678182159 * self.t) X0 += 0.00000009198 * math.cos(5.07759437389 + 112.6708167216 * self.t) X0 += 0.00000009831 * math.cos(2.49002547943 + 20.9056270572 * self.t) X0 += 0.00000009830 * math.cos(3.51040521049 + 544.1618765797 * self.t) X0 += 0.00000008646 * math.cos(4.49185896918 + 30.7756711535 * self.t) X0 += 0.00000009315 * math.cos(0.15689765715 + 65.63094483399 * self.t) X0 += 0.00000009201 * math.cos(0.09219461091 + 184.48346987229 * self.t) X0 += 0.00000008674 * math.cos(2.01170720350 + 624.1543504417 * self.t) X0 += 0.00000010739 * math.cos(0.49719235939 + 331.56535655731 * self.t) X0 += 0.00000009612 * math.cos(5.38629260665 + 182.00215942271 * self.t) X0 += 0.00000008664 * math.cos(5.62437013922 + 1479.11039154791 * self.t) X0 += 0.00000008092 * math.cos(5.65922856578 + 6.8360996225 * self.t) X0 += 0.00000010092 * math.cos(4.71596617075 + 419.2408263917 * self.t) X0 += 0.00000010233 * math.cos(4.88231209018 + 402.89037474099 * self.t) X0 += 0.00000008502 * math.cos(2.03567120581 + 17.39416491939 * self.t) X0 += 0.00000010189 * math.cos(2.58985636739 + 21.7020785649 * self.t) X0 += 0.00000009829 * math.cos(5.23644081358 + 121.2352065359 * self.t) X0 += 0.00000008406 * math.cos(2.47191018350 + 376.9150050599 * self.t) X0 += 0.00000008060 * math.cos(5.62304271115 + 415.7963080956 * self.t) X0 += 0.00000009455 * math.cos(0.06796991442 + 167.80869531589 * self.t) X0 += 0.00000007941 * math.cos(1.43287391293 + 526.7533888404 * self.t) X0 += 0.00000007870 * math.cos(2.90339733997 + 533.1161763158 * self.t) X0 += 0.00000007695 * math.cos(0.92731028198 + 906.60597015449 * self.t) X0 += 0.00000007862 * math.cos(0.91484097138 + 1265.81129610991 * self.t) X0 += 0.00000008062 * math.cos(1.12885573257 + 105.7360881471 * self.t) X0 += 0.00000008904 * math.cos(4.30824949636 + 399.9214293244 * self.t) X0 += 0.00000008050 * math.cos(0.14722556593 + 143.8691237849 * self.t) X0 += 0.00000009102 * math.cos(4.77518241515 + 348.17644063891 * self.t) X0 += 0.00000007137 * math.cos(1.26110622464 + 117.5636857037 * self.t) X0 += 0.00000007076 * math.cos(3.19957487812 + 26.84351789039 * self.t) X0 += 0.00000008418 * math.cos(1.48515415206 + 77.73372903651 * self.t) X0 += 0.00000008257 * math.cos(4.44435970504 + 117.77862615229 * self.t) X0 += 0.00000007868 * math.cos(5.07706724776 + 288.4912678276 * self.t) X0 += 0.00000008093 * math.cos(0.41458983168 + 1692.40948698591 * self.t) X0 += 0.00000006910 * math.cos(0.44789832682 + 216.72430665921 * self.t) X0 += 0.00000007092 * math.cos(0.01337002281 + 452.65981147369 * self.t) X0 += 0.00000007060 * math.cos(1.93108090539 + 453.7023411973 * self.t) X0 += 0.00000008233 * math.cos(3.50880140177 + 480.00777927849 * self.t) X0 += 0.00000006772 * math.cos(4.46250089888 + 210.36151918381 * self.t) X0 += 0.00000007025 * math.cos(1.42668370417 + 55.9029609396 * self.t) X0 += 0.00000008356 * math.cos(2.10000097648 + 95.7354097343 * self.t) X0 += 0.00000007404 * math.cos(1.00293545057 + 75.2860484817 * self.t) X0 += 0.00000006839 * math.cos(0.99943444853 + 41.5125548767 * self.t) X0 += 0.00000007909 * math.cos(1.64368221183 + 36.63174798211 * self.t) X0 += 0.00000007909 * math.cos(2.69690505451 + 40.12195826051 * self.t) X0 += 0.00000006362 * math.cos(0.26347531595 + 29.99128173331 * self.t) X0 += 0.00000006712 * math.cos(0.84138813413 + 133.82026126229 * self.t) X0 += 0.00000007571 * math.cos(2.81738238064 + 23.707816135 * self.t) X0 += 0.00000006677 * math.cos(0.10164158344 + 1.20702533 * self.t) X0 += 0.00000007600 * math.cos(0.07294781428 + 494.2348732801 * self.t) X0 += 0.00000008009 * math.cos(0.39086308190 + 170.72945662269 * self.t) X0 += 0.00000007584 * math.cos(6.04989436828 + 119.2630988606 * self.t) X0 += 0.00000006599 * math.cos(2.25520576507 + 32.226513967 * self.t) X0 += 0.00000006085 * math.cos(4.97064703625 + 322.00412900171 * self.t) X0 += 0.00000005953 * math.cos(2.49854544351 + 52214.1831362697 * self.t) X0 += 0.00000007827 * math.cos(3.28593277837 + 474.7030278917 * self.t) X0 += 0.00000007907 * math.cos(4.46293464979 + 485.63685357099 * self.t) X0 += 0.00000007372 * math.cos(4.88712847504 + 55.05162767771 * self.t) X0 += 0.00000006966 * math.cos(5.60552242454 + 647.25465079831 * self.t) X0 += 0.00000006266 * math.cos(5.78133779594 + 177.0611063308 * self.t) X0 += 0.00000005900 * math.cos(4.92602771915 + 52061.16335875149 * self.t) X0 += 0.00000006221 * math.cos(2.35523958706 + 602.00806815971 * self.t) X0 += 0.00000005552 * math.cos(5.87735995607 + 223.1041404771 * self.t) X0 += 0.00000005976 * math.cos(1.83099110545 + 10.8018827804 * self.t) X0 += 0.00000007600 * math.cos(5.33804556108 + 488.6057989876 * self.t) X0 += 0.00000006831 * math.cos(0.04615498459 + 1582.2031657665 * self.t) X0 += 0.00000005654 * math.cos(3.04032114806 + 12604.5285531041 * self.t) X0 += 0.00000005798 * math.cos(1.13675043219 + 27.4979091962 * self.t) X0 += 0.00000007216 * math.cos(0.18192294134 + 739.0410923221 * self.t) X0 += 0.00000006579 * math.cos(3.94809746775 + 2.69149803831 * self.t) X0 += 0.00000005758 * math.cos(2.82344188087 + 30.0394658431 * self.t) X0 += 0.00000005270 * math.cos(3.46743079634 + 6166.94845288619 * self.t) X0 += 0.00000007398 * math.cos(0.58333334375 + 709.721016842 * self.t) X0 += 0.00000005679 * math.cos(5.91776083103 + 17.22740858061 * self.t) X0 += 0.00000005205 * math.cos(2.61017638124 + 426.3543733925 * self.t) X0 += 0.00000005146 * math.cos(0.81172664742 + 46.7624245093 * self.t) X0 += 0.00000005694 * math.cos(2.94913098744 + 168.98435148349 * self.t) X0 += 0.00000006627 * math.cos(6.07668723879 + 221.13203280179 * self.t) X0 += 0.00000005443 * math.cos(4.34867602386 + 525.7419968841 * self.t) X0 += 0.00000006475 * math.cos(2.52364293984 + 591.07424248041 * self.t) X0 += 0.00000004984 * math.cos(4.89088409053 + 10097.15814910579 * self.t) X0 += 0.00000005318 * math.cos(5.22697316848 + 44.52719227561 * self.t) X0 += 0.00000006699 * math.cos(2.95047965393 + 2157.1407134997 * self.t) X0 += 0.00000006443 * math.cos(5.65068156930 + 675.0445615878 * self.t) X0 += 0.00000005078 * math.cos(0.96513123174 + 101.62511645769 * self.t) X0 += 0.00000005394 * math.cos(0.88948762211 + 368.21391948681 * self.t) X0 += 0.00000005072 * math.cos(2.52597530610 + 272.33775813299 * self.t) X0 += 0.00000005208 * math.cos(4.53150187093 + 277.2788112249 * self.t) X0 += 0.00000005332 * math.cos(1.28621962216 + 280.9357778421 * self.t) X0 += 0.00000005989 * math.cos(5.89271411050 + 93.0270967486 * self.t) X0 += 0.00000006329 * math.cos(0.49570607842 + 18.87863762769 * self.t) X0 += 0.00000005551 * math.cos(2.57045763275 + 57.3874336479 * self.t) X0 += 0.00000006471 * math.cos(0.04463535540 + 68.1243173711 * self.t) X0 += 0.00000004708 * math.cos(2.23921095477 + 95.68722562449 * self.t) X0 += 0.00000005891 * math.cos(5.96441381591 + 381.5954257209 * self.t) X0 += 0.00000004717 * math.cos(4.31682479516 + 104.2852453336 * self.t) X0 += 0.00000005675 * math.cos(1.71229301179 + 1165.6392831981 * self.t) X0 += 0.00000005888 * math.cos(0.43219504278 + 42.34263627919 * self.t) X0 += 0.00000005587 * math.cos(4.09170092519 + 459.6066021357 * self.t) X0 += 0.00000005456 * math.cos(1.50864831442 + 75.50098893029 * self.t) X0 += 0.00000005940 * math.cos(6.28075673596 + 6318.4837576961 * self.t) X0 += 0.00000005207 * math.cos(4.55134069280 + 436.5699922539 * self.t) X0 += 0.00000006160 * math.cos(4.76046448210 + 749.82616015511 * self.t) X0 += 0.00000006137 * math.cos(4.59348226478 + 713.17759722561 * self.t) X0 += 0.00000004547 * math.cos(2.39218547281 + 32.47259218289 * self.t) X0 += 0.00000005246 * math.cos(4.97888240032 + 109.9625037359 * self.t) X0 += 0.00000005244 * math.cos(2.33674770879 + 73.5891274523 * self.t) X0 += 0.00000005572 * math.cos(6.12038028190 + 102.11275142471 * self.t) X0 += 0.00000005638 * math.cos(1.42053892188 + 10248.6934539157 * self.t) X0 += 0.00000004513 * math.cos(1.62848698862 + 1272.9248431107 * self.t) X0 += 0.00000004340 * math.cos(2.36449866810 + 384.02855206069 * self.t) X0 += 0.00000004263 * math.cos(4.24631269159 + 1577.52274510549 * self.t) X0 += 0.00000005964 * math.cos(4.92643136579 + 786.47472308461 * self.t) X0 += 0.00000004962 * math.cos(6.09839378254 + 257.78059573129 * self.t) X0 += 0.00000005327 * math.cos(5.70215230442 + 107.74182571721 * self.t) X0 += 0.00000005572 * math.cos(0.87438107795 + 291.2934569054 * self.t) X0 += 0.00000004336 * math.cos(5.80113193852 + 53.40958840249 * self.t) X0 += 0.00000004427 * math.cos(3.00157250839 + 189.42452296421 * self.t) X0 += 0.00000004157 * math.cos(3.46647899628 + 29.5036467663 * self.t) X0 += 0.00000004646 * math.cos(2.87774169214 + 13285.93981804009 * self.t) X0 += 0.00000005507 * math.cos(4.27464738844 + 178.11819026941 * self.t) X0 += 0.00000005348 * math.cos(1.42468292991 + 24.88347230261 * self.t) X0 += 0.00000005339 * math.cos(3.91840662285 + 314.6635794648 * self.t) X0 += 0.00000004678 * math.cos(4.43608792406 + 1474.4299708869 * self.t) X0 += 0.00000004090 * math.cos(3.35633664186 + 765.3801602981 * self.t) X0 += 0.00000005008 * math.cos(5.85701520659 + 352.06040979221 * self.t) X0 += 0.00000005562 * math.cos(0.40887335705 + 6248.1555772537 * self.t) X0 += 0.00000004983 * math.cos(3.16236150253 + 1055.43296197871 * self.t) X0 += 0.00000004566 * math.cos(5.25700629292 + 325.1398307571 * self.t) X0 += 0.00000005327 * math.cos(5.25347269162 + 439.53893767049 * self.t) X0 += 0.00000005121 * math.cos(5.84825704577 + 711.6931245173 * self.t) X0 += 0.00000004181 * math.cos(1.11749590962 + 6606.1994373488 * self.t) X0 += 0.00000004293 * math.cos(4.65873798886 + 46.71424039951 * self.t) X0 += 0.00000005532 * math.cos(0.53479774781 + 320.03202132639 * self.t) X0 += 0.00000004492 * math.cos(0.09912827297 + 52177.53457334019 * self.t) X0 += 0.00000004312 * math.cos(1.38883413817 + 22.8777347325 * self.t) X0 += 0.00000005332 * math.cos(1.83070192574 + 10178.3652734733 * self.t) X0 += 0.00000004593 * math.cos(0.14820750962 + 1025.6854977289 * self.t) X0 += 0.00000005439 * math.cos(5.09447580219 + 823.12328601411 * self.t) X0 += 0.00000003870 * math.cos(4.27995377915 + 1596.43025976811 * self.t) X0 += 0.00000003892 * math.cos(2.11564791977 + 226.07308589371 * self.t) X0 += 0.00000004891 * math.cos(2.80814026706 + 8.1417539045 * self.t) X0 += 0.00000004689 * math.cos(3.52062924653 + 276.79117625789 * self.t) X0 += 0.00000004268 * math.cos(2.59269427473 + 374.15181032 * self.t) X0 += 0.00000003828 * math.cos(2.28076604659 + 2138.2331988371 * self.t) X0 += 0.00000004592 * math.cos(3.87527577295 + 1376.0176173293 * self.t) X0 += 0.00000004629 * math.cos(0.97709160917 + 122.71967924421 * self.t) X0 += 0.00000003871 * math.cos(3.17548325596 + 531.4192552864 * self.t) X0 += 0.00000004995 * math.cos(0.32063762943 + 32.69959471901 * self.t) X0 += 0.00000004711 * math.cos(0.43748317622 + 52252.31617190749 * self.t) X0 += 0.00000003893 * math.cos(0.12475334110 + 116.294153444 * self.t) X0 += 0.00000004481 * math.cos(4.66479841820 + 53.0458901076 * self.t) X0 += 0.00000004136 * math.cos(2.59386926777 + 503.1080796351 * self.t) X0 += 0.00000004508 * math.cos(4.38574998818 + 562.12992738271 * self.t) X0 += 0.00000005025 * math.cos(0.39865233659 + 283.38345839689 * self.t) X0 += 0.00000004789 * math.cos(2.68692249791 + 627.7228054099 * self.t) X0 += 0.00000004021 * math.cos(0.14454426922 + 6603.23049193219 * self.t) X0 += 0.00000005163 * math.cos(4.77460676620 + 25519.83532335829 * self.t) X0 += 0.00000004150 * math.cos(3.86319541901 + 27.443027442 * self.t) X0 += 0.00000003623 * math.cos(2.29457319711 + 1665.5827840429 * self.t) X0 += 0.00000004634 * math.cos(1.79141170909 + 3227.45397501119 * self.t) X0 += 0.00000004060 * math.cos(6.21658618282 + 304.4780211834 * self.t) X0 += 0.00000003862 * math.cos(0.50812728673 + 74.504151189 * self.t) X0 += 0.00000003561 * math.cos(4.92971224760 + 358.6526919312 * self.t) X0 += 0.00000004557 * math.cos(6.27521064672 + 25974.74468988559 * self.t) X0 += 0.00000004264 * math.cos(1.56884112199 + 634.93941827469 * self.t) X0 += 0.00000004482 * math.cos(1.70550805319 + 342.61105682121 * self.t) X0 += 0.00000003539 * math.cos(0.56907944763 + 119.7507338276 * self.t) X0 += 0.00000004304 * math.cos(0.63784646457 + 12567.8799901746 * self.t) X0 += 0.00000004138 * math.cos(4.03567139847 + 107.2541907502 * self.t) X0 += 0.00000004284 * math.cos(0.05420881503 + 294.42915866079 * self.t) X0 += 0.00000003723 * math.cos(5.58644401851 + 987.325459555 * self.t) X0 += 0.00000003723 * math.cos(5.58644401851 + 987.813094522 * self.t) X0 += 0.00000004606 * math.cos(5.49553530451 + 14.42521950279 * self.t) X0 += 0.00000004236 * math.cos(6.22240593144 + 155.9116617901 * self.t) X0 += 0.00000004458 * math.cos(2.64590572483 + 395.8225197225 * self.t) X0 += 0.00000004798 * math.cos(5.23929868658 + 530.195415009 * self.t) X0 += 0.00000003640 * math.cos(2.22734915897 + 2564.8313897131 * self.t) X0 += 0.00000003563 * math.cos(5.37459598926 + 12451.50877558589 * self.t) X0 += 0.00000003443 * math.cos(2.13809774331 + 245.2504227591 * self.t) X0 += 0.00000003429 * math.cos(4.73423412994 + 530.0466571627 * self.t) X0 += 0.00000003872 * math.cos(4.09217464449 + 308.98632106249 * self.t) X0 += 0.00000003406 * math.cos(5.88979864779 + 529.82290799351 * self.t) X0 += 0.00000004348 * math.cos(1.52419659995 + 20311.92816802509 * self.t) X0 += 0.00000004589 * math.cos(5.24153025487 + 181.08713568601 * self.t) X0 += 0.00000003854 * math.cos(5.92510183178 + 12564.91104475801 * self.t) X0 += 0.00000003789 * math.cos(4.29351893525 + 3101.6359018085 * self.t) X0 += 0.00000003783 * math.cos(0.26936683978 + 1614.17130803499 * self.t) X0 += 0.00000003904 * math.cos(0.00421090422 + 369.8014580591 * self.t) X0 += 0.00000003765 * math.cos(4.70889835066 + 1025.94613015981 * self.t) X0 += 0.00000004231 * math.cos(5.35914297519 + 31.52393855141 * self.t) X0 += 0.00000004303 * math.cos(4.97345150272 + 396.785727569 * self.t) X0 += 0.00000004085 * math.cos(1.80921070558 + 14.47091148511 * self.t) X0 += 0.00000004085 * math.cos(1.80921070558 + 13.9832765181 * self.t) X0 += 0.00000003346 * math.cos(4.91522066963 + 20351.54567637119 * self.t) X0 += 0.00000004021 * math.cos(6.08537487228 + 748.3416874468 * self.t) X0 += 0.00000003753 * math.cos(1.17204243376 + 524.99372948619 * self.t) X0 += 0.00000003935 * math.cos(1.24122122244 + 1617.14025345159 * self.t) X0 += 0.00000004432 * math.cos(3.45778366813 + 511.3515908212 * self.t) X0 += 0.00000004170 * math.cos(4.42864444413 + 274.87931477991 * self.t) X0 += 0.00000003317 * math.cos(1.79347554880 + 266.70868384049 * self.t) X0 += 0.00000004545 * math.cos(4.56531161641 + 244.5624015585 * self.t) X0 += 0.00000003589 * math.cos(1.55384880430 + 59.526297662 * self.t) X0 += 0.00000003464 * math.cos(0.37736158688 + 102.27950776349 * self.t) X0 += 0.00000004526 * math.cos(4.55402483522 + 525.7901809939 * self.t) X0 += 0.00000004603 * math.cos(4.40260765490 + 26088.1469590577 * self.t) X0 += 0.00000004021 * math.cos(5.38581853850 + 52174.56562792359 * self.t) X0 += 0.00000003276 * math.cos(1.95663025139 + 1306.3774580875 * self.t) X0 += 0.00000003214 * math.cos(3.94235488355 + 20348.57673095459 * self.t) X0 += 0.00000003706 * math.cos(5.25360971143 + 27.07052042651 * self.t) X0 += 0.00000003759 * math.cos(4.32245166720 + 164.83974989929 * self.t) X0 += 0.00000003184 * math.cos(2.01654309849 + 538.0115374254 * self.t) X0 += 0.00000004430 * math.cos(5.37917502758 + 529.6741501472 * self.t) X0 += 0.00000004064 * math.cos(1.03322736236 + 6130.2998899567 * self.t) X0 += 0.00000003918 * math.cos(4.20575585414 + 375.43053235159 * self.t) X0 += 0.00000004058 * math.cos(5.13313296042 + 433.4342904985 * self.t) X0 += 0.00000003919 * math.cos(0.36694469487 + 1092.8177302186 * self.t) X0 += 0.00000003919 * math.cos(0.36694469487 + 1093.3053651856 * self.t) X0 += 0.00000003175 * math.cos(1.14568678321 + 241.3664536058 * self.t) X0 += 0.00000003135 * math.cos(5.81037649777 + 127.22797912329 * self.t) X0 += 0.00000003834 * math.cos(1.84941829775 + 14.3133449182 * self.t) X0 += 0.00000004022 * math.cos(1.72079825603 + 1477.8383671607 * self.t) X0 += 0.00000003221 * math.cos(1.09261076661 + 78.1611178062 * self.t) X0 += 0.00000003426 * math.cos(0.06166201047 + 519.8522901607 * self.t) X0 += 0.00000004369 * math.cos(0.74973637733 + 746.3695797715 * self.t) X0 += 0.00000003160 * math.cos(2.01821245093 + 664.99569906519 * self.t) X0 += 0.00000004060 * math.cos(6.06087716530 + 51.87023394 * self.t) X0 += 0.00000003107 * math.cos(5.38240469077 + 28.9275001503 * self.t) X0 += 0.00000003259 * math.cos(5.62260974194 + 657.8821520644 * self.t) X0 += 0.00000003428 * math.cos(1.24133782529 + 2351.5322942751 * self.t) X0 += 0.00000003235 * math.cos(1.64692472660 + 406.3469551246 * self.t) X0 += 0.00000003161 * math.cos(5.69758725685 + 982.8720414301 * self.t) X0 += 0.00000004351 * math.cos(1.04662835997 + 20388.19423930069 * self.t) X0 += 0.00000003384 * math.cos(0.30649784029 + 660.851097481 * self.t) X0 += 0.00000003452 * math.cos(4.39659352485 + 326.1823604807 * self.t) X0 += 0.00000003298 * math.cos(0.15489069807 + 1403.84115801359 * self.t) X0 += 0.00000003278 * math.cos(3.68945780931 + 941.7700603757 * self.t) X0 += 0.00000003723 * math.cos(5.00962048402 + 451.9572360581 * self.t) X0 += 0.00000003173 * math.cos(5.46640783518 + 1400.87221259699 * self.t) X0 += 0.00000004113 * math.cos(1.87439213951 + 1049.31625271919 * self.t) X0 += 0.00000004012 * math.cos(2.15082049909 + 52.6039471229 * self.t) X0 += 0.00000004142 * math.cos(4.89782789900 + 978.6792557361 * self.t) X0 += 0.00000004295 * math.cos(1.37302733197 + 875.58648151749 * self.t) X0 += 0.00000003224 * math.cos(3.81995287471 + 459.1189671687 * self.t) X0 += 0.00000003151 * math.cos(3.69005421605 + 381.8560581518 * self.t) X0 += 0.00000003633 * math.cos(1.38559724652 + 256.78375799 * self.t) X0 += 0.00000004250 * math.cos(0.10595516218 + 528.71094230071 * self.t) X0 += 0.00000004186 * math.cos(2.09187651842 + 943.25453308399 * self.t) X0 += 0.00000003406 * math.cos(0.25126866750 + 170.46882419179 * self.t) X0 += 0.00000003231 * math.cos(4.61367643853 + 400.8209466961 * self.t) X0 += 0.00000003726 * math.cos(0.55318715397 + 1096.48675892331 * self.t) X0 += 0.00000003792 * math.cos(0.75464081409 + 111.9346114112 * self.t) X0 += 0.00000003651 * math.cos(4.56933341620 + 154.42718908179 * self.t) X0 += 0.00000003839 * math.cos(2.45649426115 + 10060.50958617629 * self.t) X0 += 0.00000003356 * math.cos(0.62546125542 + 1586.34776735071 * self.t) X0 += 0.00000003219 * math.cos(5.97786590701 + 213.7096692603 * self.t) X0 += 0.00000003671 * math.cos(1.51743688101 + 57.6023740965 * self.t) X0 += 0.00000004187 * math.cos(0.29242250575 + 2772.54460848389 * self.t) X0 += 0.00000002960 * math.cos(2.20142019667 + 2461.7386154945 * self.t) X0 += 0.00000003331 * math.cos(0.81281655951 + 10133.80671203529 * self.t) X0 += 0.00000003341 * math.cos(1.17831577639 + 243.7659500508 * self.t) X0 += 0.00000003466 * math.cos(4.73891819304 + 1150.92455422949 * self.t) X0 += 0.00000003296 * math.cos(3.49817757911 + 1653.78881638109 * self.t) X0 += 0.00000003014 * math.cos(1.90092216670 + 1477.3989163035 * self.t) X0 += 0.00000004118 * math.cos(2.83150543771 + 25596.5890296009 * self.t) X0 += 0.00000002951 * math.cos(5.04298380276 + 42.78208713641 * self.t) X0 += 0.00000002951 * math.cos(5.58078877076 + 33.9716191062 * self.t) X0 += 0.00000003830 * math.cos(4.59720174528 + 323.48860171 * self.t) X0 += 0.00000003313 * math.cos(1.64840054600 + 939.1099314998 * self.t) X0 += 0.00000003031 * math.cos(2.75126158832 + 156450.90896068608 * self.t) X0 += 0.00000003606 * math.cos(3.92819651217 + 1082.2596649217 * self.t) X0 += 0.00000002967 * math.cos(0.01380556143 + 6.3941566378 * self.t) X0 += 0.00000002995 * math.cos(3.55729257964 + 139.7099679857 * self.t) X0 += 0.00000003251 * math.cos(3.50186784018 + 709.29362807231 * self.t) X0 += 0.00000003480 * math.cos(0.61716473120 + 518.1408149163 * self.t) X0 += 0.00000003906 * math.cos(2.84871380483 + 1119.90506559249 * self.t) X0 += 0.00000003406 * math.cos(1.85522558472 + 148.79811478929 * self.t) X0 += 0.00000003359 * math.cos(1.74239209634 + 642.8494167832 * self.t) X0 += 0.00000003027 * math.cos(0.29741383095 + 184.0078969928 * self.t) X0 += 0.00000002918 * math.cos(2.25866029656 + 83.6234357599 * self.t) X0 += 0.00000003347 * math.cos(6.10666820526 + 217.68751450571 * self.t) X0 += 0.00000003277 * math.cos(0.27333269638 + 912.5438609877 * self.t) X0 += 0.00000003277 * math.cos(0.27333269638 + 913.03149595471 * self.t) X0 += 0.00000003196 * math.cos(5.84286985933 + 363.1061100561 * self.t) X0 += 0.00000002869 * math.cos(4.50334436600 + 285.35556607221 * self.t) X0 += 0.00000003158 * math.cos(1.18152957041 + 540.01727499551 * self.t) X0 += 0.00000002810 * math.cos(5.14802919795 + 1592.2856581839 * self.t) X0 += 0.00000003471 * math.cos(6.13160952457 + 144.39038864671 * self.t) X0 += 0.00000003159 * math.cos(4.14451339136 + 197.5561595657 * self.t) X0 += 0.00000003227 * math.cos(5.73841253304 + 6203.5970158157 * self.t) X0 += 0.00000003750 * math.cos(5.81139240481 + 303.35724676999 * self.t) X0 += 0.00000003848 * math.cos(3.38110828764 + 26048.04181574459 * self.t) X0 += 0.00000002741 * math.cos(1.70084306406 + 70.8326303568 * self.t) X0 += 0.00000002826 * math.cos(2.07742210458 + 460.2946233363 * self.t) X0 += 0.00000002748 * math.cos(0.98378370701 + 600.52359545141 * self.t) X0 += 0.00000003057 * math.cos(6.13629771077 + 23.81969071961 * self.t) X0 += 0.00000003057 * math.cos(1.34588220916 + 52.934015523 * self.t) X0 += 0.00000003446 * math.cos(3.54046646150 + 500.1391342185 * self.t) X0 += 0.00000002703 * math.cos(4.69192633180 + 908.0904428628 * self.t) X0 += 0.00000002817 * math.cos(3.26718539283 + 210.6221516147 * self.t) X0 += 0.00000002848 * math.cos(5.88127781412 + 450.4727633498 * self.t) X0 += 0.00000002724 * math.cos(0.93671586048 + 23.18655127321 * self.t) X0 += 0.00000002905 * math.cos(5.85039527890 + 149.3193796511 * self.t) X0 += 0.00000002848 * math.cos(6.20081143930 + 622.66987773339 * self.t) X0 += 0.00000002733 * math.cos(3.50715759295 + 262.72164882321 * self.t) X0 += 0.00000002863 * math.cos(0.69834580836 + 175.57663362249 * self.t) X0 += 0.00000002681 * math.cos(1.11809511751 + 25.1922888433 * self.t) X0 += 0.00000002822 * math.cos(1.57963221264 + 259.7527034066 * self.t) X0 += 0.00000003174 * math.cos(6.18541771069 + 347.1193567003 * self.t) X0 += 0.00000003271 * math.cos(1.40248413653 + 458.5977023069 * self.t) X0 += 0.00000002894 * math.cos(4.18128306427 + 71.82946809809 * self.t) X0 += 0.00000003490 * math.cos(2.85083291634 + 664.3713683394 * self.t) X0 += 0.00000003506 * math.cos(5.48691285949 + 771.3481117113 * self.t) X0 += 0.00000003326 * math.cos(2.12303698267 + 45.2297676912 * self.t) X0 += 0.00000002988 * math.cos(0.23324807191 + 299.37021175271 * self.t) X0 += 0.00000002916 * math.cos(3.60780287924 + 6642.8480002783 * self.t) X0 += 0.00000002916 * math.cos(0.46621022565 + 6643.3356352453 * self.t) X0 += 0.00000002630 * math.cos(1.12694509764 + 2751.79141717511 * self.t) X0 += 0.00000002903 * math.cos(4.31055308658 + 477.08701797169 * self.t) X0 += 0.00000002804 * math.cos(0.26456593020 + 6681.46867088311 * self.t) X0 += 0.00000002622 * math.cos(2.30179163581 + 521.8580277308 * self.t) X0 += 0.00000002606 * math.cos(6.15707729666 + 410.8552550037 * self.t) X0 += 0.00000003046 * math.cos(2.36386768037 + 959.45373476091 * self.t) X0 += 0.00000003127 * math.cos(3.04512463308 + 225.5518210319 * self.t) X0 += 0.00000002700 * math.cos(4.45467896965 + 963.6465204549 * self.t) X0 += 0.00000002778 * math.cos(1.65860124839 + 238.39750818919 * self.t) X0 += 0.00000003029 * math.cos(4.72630934575 + 473.2185551834 * self.t) X0 += 0.00000002671 * math.cos(4.60029996028 + 531.9405201482 * self.t) X0 += 0.00000002914 * math.cos(3.86169076602 + 554.31380496631 * self.t) X0 += 0.00000003087 * math.cos(6.08851917121 + 340.2664421304 * self.t) X0 += 0.00000003438 * math.cos(2.32466413132 + 6171.40187101109 * self.t) X0 += 0.00000002879 * math.cos(5.61809470376 + 218.6507223522 * self.t) X0 += 0.00000003140 * math.cos(5.02001385281 + 609.1216151605 * self.t) X0 += 0.00000003003 * math.cos(0.53592571188 + 464.97504399731 * self.t) X0 += 0.00000003257 * math.cos(1.52476284257 + 305.96249389171 * self.t) X0 += 0.00000003211 * math.cos(5.64833047248 + 416.532513406 * self.t) X0 += 0.00000003265 * math.cos(1.54950325507 + 24.7347144563 * self.t) X0 += 0.00000002644 * math.cos(1.01963899758 + 508.5941415757 * self.t) X0 += 0.00000002764 * math.cos(4.98225869197 + 410.59462257279 * self.t) X0 += 0.00000003428 * math.cos(5.71088563789 + 1012.6195056799 * self.t) X0 += 0.00000002614 * math.cos(4.07639961382 + 213.5910970313 * self.t) X0 += 0.00000003469 * math.cos(5.28643352424 + 24.14975911971 * self.t) X0 += 0.00000002606 * math.cos(0.81160096517 + 213.4947288117 * self.t) X0 += 0.00000003444 * math.cos(2.56432157215 + 891.57323487331 * self.t) X0 += 0.00000002540 * math.cos(4.32167771768 + 564.8718702632 * self.t) X0 += 0.00000002540 * math.cos(4.32167771768 + 565.35950523021 * self.t) X0 += 0.00000002754 * math.cos(2.69535555411 + 57.5541899867 * self.t) X0 += 0.00000002531 * math.cos(0.59020723407 + 800.5924346291 * self.t) X0 += 0.00000002557 * math.cos(0.66999256840 + 341.49028240779 * self.t) X0 += 0.00000002601 * math.cos(4.54885591305 + 261.2371761149 * self.t) X0 += 0.00000003027 * math.cos(0.20183300410 + 331.07772159029 * self.t) X0 += 0.00000002494 * math.cos(0.58142193078 + 203.9816853659 * self.t) X0 += 0.00000002590 * math.cos(1.76325981719 + 1190.5420625756 * self.t) X0 += 0.00000003494 * math.cos(2.90876238684 + 534.0793841623 * self.t) X0 += 0.00000003144 * math.cos(0.01981710217 + 1503.9649868156 * self.t) X0 += 0.00000002818 * math.cos(3.61898449244 + 49.31067880061 * self.t) X0 += 0.00000002791 * math.cos(4.48606671949 + 288.32451148881 * self.t) X0 += 0.00000002471 * math.cos(1.23009614301 + 411.11588743459 * self.t) X0 += 0.00000003059 * math.cos(3.30977686438 + 172.48911597691 * self.t) X0 += 0.00000002972 * math.cos(0.30229231666 + 569.29165849331 * self.t) X0 += 0.00000003418 * math.cos(5.40293550246 + 638.3959986583 * self.t) X0 += 0.00000002541 * math.cos(4.99016167757 + 1448.09090291091 * self.t) X0 += 0.00000002663 * math.cos(0.43151826022 + 573.6968925084 * self.t) X0 += 0.00000002439 * math.cos(4.39632185677 + 1625.9652756968 * self.t) X0 += 0.00000002739 * math.cos(5.72535305895 + 112.8832650427 * self.t) X0 += 0.00000002821 * math.cos(5.66863744979 + 402.93606672331 * self.t) X0 += 0.00000003412 * math.cos(1.27007980380 + 772.8325844196 * self.t) X0 += 0.00000002624 * math.cos(5.85528852490 + 1624.4808029885 * self.t) X0 += 0.00000003170 * math.cos(0.53682796950 + 1011.13503297159 * self.t) X0 += 0.00000002908 * math.cos(4.60949958082 + 635.94831810351 * self.t) X0 += 0.00000002664 * math.cos(2.68003479349 + 409.41896640519 * self.t) X0 += 0.00000003091 * math.cos(1.88245278611 + 379.25961975071 * self.t) X0 += 0.00000003301 * math.cos(1.91350932819 + 19.7936613644 * self.t) X0 += 0.00000003176 * math.cos(3.29730129609 + 300.9095662152 * self.t) X0 += 0.00000003022 * math.cos(5.94822554077 + 52.0189917863 * self.t) X0 += 0.00000002890 * math.cos(1.53549747897 + 293.4323209195 * self.t) X0 += 0.00000002698 * math.cos(1.69370735844 + 78149.06650032569 * self.t) X0 += 0.00000002558 * math.cos(0.74578099458 + 1371.3371966683 * self.t) X0 += 0.00000002619 * math.cos(3.80578981072 + 202.0095776906 * self.t) X0 += 0.00000003176 * math.cos(3.75055063339 + 10101.61156723069 * self.t) X0 += 0.00000003341 * math.cos(2.34080319182 + 345.8955164229 * self.t) X0 += 0.00000002373 * math.cos(4.96475711609 + 130.8513158457 * self.t) X0 += 0.00000002644 * math.cos(2.68099240015 + 305.10235190919 * self.t) X0 += 0.00000003339 * math.cos(4.63303989765 + 2849.2983147265 * self.t) X0 += 0.00000002410 * math.cos(1.58163612779 + 951.8525527931 * self.t) X0 += 0.00000003303 * math.cos(2.25771292490 + 769.5729459921 * self.t) X0 += 0.00000003302 * math.cos(4.85894681967 + 90.1520274241 * self.t) X0 += 0.00000002416 * math.cos(6.00635580174 + 527.929045008 * self.t) X0 += 0.00000002361 * math.cos(5.34789183737 + 905.1214974462 * self.t) X0 += 0.00000002737 * math.cos(4.77190944455 + 1206.2199993907 * self.t) X0 += 0.00000002441 * math.cos(3.82975575752 + 246.73489546739 * self.t) X0 += 0.00000002441 * math.cos(0.68816310393 + 247.2225304344 * self.t) X0 += 0.00000002957 * math.cos(4.25832811500 + 238.23075185041 * self.t) X0 += 0.00000003263 * math.cos(0.98630889937 + 1506.93393223219 * self.t) X0 += 0.00000003293 * math.cos(5.93270574395 + 66.1522096958 * self.t) X0 += 0.00000003241 * math.cos(3.43806050184 + 978.4186233052 * self.t) X0 += 0.00000003149 * math.cos(3.64971867049 + 271.9103693633 * self.t) X0 += 0.00000003149 * math.cos(3.64971867050 + 271.4227343963 * self.t) X0 += 0.00000002328 * math.cos(5.07609916236 + 31.73887900 * self.t) X0 += 0.00000002372 * math.cos(0.68652074740 + 309.0345051723 * self.t) X0 += 0.00000002372 * math.cos(3.82811340099 + 309.5221401393 * self.t) X0 += 0.00000002369 * math.cos(4.33012817739 + 418.9801939608 * self.t) X0 += 0.00000003007 * math.cos(4.64009260533 + 1437.7814079574 * self.t) X0 += 0.00000003034 * math.cos(5.98346126252 + 330.8627811417 * self.t) X0 += 0.00000002345 * math.cos(2.80677153952 + 453.9318358609 * self.t) X0 += 0.00000003118 * math.cos(3.73398781358 + 1434.81246254079 * self.t) X0 += 0.00000002324 * math.cos(3.85931736808 + 495.2462652364 * self.t) X0 += 0.00000002340 * math.cos(5.41992470939 + 452.43031681009 * self.t) X0 += 0.00000002336 * math.cos(0.04655833240 + 189.591279303 * self.t) X0 += 0.00000002920 * math.cos(3.78758562864 + 1549.69920442121 * self.t) X0 += 0.00000002494 * math.cos(0.79353025531 + 1187.57311715899 * self.t) X0 += 0.00000002692 * math.cos(4.17807622816 + 425.13053311509 * self.t) X0 += 0.00000002874 * math.cos(4.63267401857 + 1654.2764513481 * self.t) X0 += 0.00000002809 * math.cos(5.67077170621 + 317.5843407716 * self.t) X0 += 0.00000002735 * math.cos(3.93990204220 + 1513.05064149171 * self.t) X0 += 0.00000002949 * math.cos(6.26993364897 + 186.71620997851 * self.t) X0 += 0.00000002320 * math.cos(0.74326897219 + 487.38195871019 * self.t) X0 += 0.00000003113 * math.cos(6.20902109610 + 353.28425006961 * self.t) X0 += 0.00000003086 * math.cos(4.87476303199 + 1230.5990217789 * self.t) X0 += 0.00000002722 * math.cos(2.16494792915 + 49.6831858161 * self.t) X0 += 0.00000003064 * math.cos(3.68765217385 + 133.13224006171 * self.t) X0 += 0.00000003064 * math.cos(3.68765217385 + 132.64460509469 * self.t) X0 += 0.00000002470 * math.cos(2.78243316001 + 532.3824631329 * self.t) X0 += 0.00000002640 * math.cos(0.51790972890 + 394.33804701421 * self.t) X0 += 0.00000002252 * math.cos(1.84613004390 + 22.6507321964 * self.t) X0 += 0.00000003151 * math.cos(5.26039361613 + 859.77184894361 * self.t) X0 += 0.00000002671 * math.cos(0.92145640556 + 37.3679532925 * self.t) X0 += 0.00000002380 * math.cos(0.86687455354 + 429.2751346993 * self.t) X0 += 0.00000002655 * math.cos(2.72088152594 + 484.1523808627 * self.t) X0 += 0.00000003005 * math.cos(3.02367934874 + 1929.33933741419 * self.t) X0 += 0.00000002550 * math.cos(5.60497907633 + 496.9431862658 * self.t) X0 += 0.00000002290 * math.cos(3.41120190653 + 455.18681390559 * self.t) X0 += 0.00000002608 * math.cos(3.85525903926 + 422.9580392062 * self.t) X0 += 0.00000002226 * math.cos(2.09977531258 + 47.82620609231 * self.t) X0 += 0.00000002233 * math.cos(4.94028872789 + 877.3461408717 * self.t) X0 += 0.00000002764 * math.cos(0.83501700112 + 356.68058425589 * self.t) X0 += 0.00000002719 * math.cos(1.98953734068 + 177.5823711926 * self.t) X0 += 0.00000002999 * math.cos(2.06885612973 + 1926.37039199759 * self.t) X0 += 0.00000002693 * math.cos(3.57972778548 + 6284.8041401832 * self.t) X0 += 0.00000002369 * math.cos(1.19578023344 + 70.88081446661 * self.t) X0 += 0.00000002498 * math.cos(3.71851216671 + 315.1512144318 * self.t) X0 += 0.00000002204 * math.cos(3.20466206592 + 442.886135597 * self.t) X0 += 0.00000002261 * math.cos(3.32534753019 + 621.2335891349 * self.t) X0 += 0.00000002213 * math.cos(6.16263836668 + 1189.0575898673 * self.t) X0 += 0.00000002492 * math.cos(2.67366070604 + 406.9712858504 * self.t) X0 += 0.00000002976 * math.cos(1.45402284302 + 1014.1039783882 * self.t) X0 += 0.00000002840 * math.cos(5.35710509350 + 522.3336006103 * self.t) X0 += 0.00000002340 * math.cos(1.72448626630 + 440.43845504219 * self.t) X0 += 0.00000003012 * math.cos(1.13512104183 + 15.9096922111 * self.t) X0 += 0.00000003012 * math.cos(4.27671369542 + 16.3973271781 * self.t) X0 += 0.00000002372 * math.cos(0.24227395275 + 132.5964209849 * self.t) X0 += 0.00000002232 * math.cos(2.42168492591 + 158.12984768129 * self.t) X0 += 0.00000002961 * math.cos(4.37134416172 + 286.3524038135 * self.t) X0 += 0.00000002961 * math.cos(4.37134416172 + 286.8400387805 * self.t) # Neptune_X1 (t) // 342 terms of order 1 X1 = 0 X1 += 0.00357822049 * math.cos(4.60537437341 + 0.2438174835 * self.t) X1 += 0.00256200629 * math.cos(2.01693264233 + 36.892380413 * self.t) X1 += 0.00242677799 * math.cos(5.46293481092 + 39.86132582961 * self.t) X1 += 0.00106073143 * math.cos(3.07856435709 + 37.88921815429 * self.t) X1 += 0.00103735195 * math.cos(6.08270773807 + 38.3768531213 * self.t) X1 += 0.00118508231 * math.cos(2.88623136735 + 76.50988875911 * self.t) X1 += 0.00021930692 * math.cos(3.20019569049 + 35.40790770471 * self.t) X1 += 0.00017445772 * math.cos(4.26396070854 + 41.3457985379 * self.t) X1 += 0.00013038843 * math.cos(5.36684741537 + 3.21276290011 * self.t) X1 += 0.00004928885 * math.cos(2.08893204170 + 73.5409433425 * self.t) X1 += 0.00002742686 * math.cos(4.06389633495 + 77.9943614674 * self.t) X1 += 0.00002155134 * math.cos(4.11881068429 + 4.6972356084 * self.t) X1 += 0.00001882800 * math.cos(4.42038284259 + 33.9234349964 * self.t) X1 += 0.00001572888 * math.cos(1.07810551784 + 114.6429243969 * self.t) X1 += 0.00001326507 * math.cos(6.02985868883 + 75.0254160508 * self.t) X1 += 0.00001343094 * math.cos(3.03838214796 + 42.83027124621 * self.t) X1 += 0.00000897979 * math.cos(4.26993024752 + 426.8420083595 * self.t) X1 += 0.00000865617 * math.cos(1.66618456177 + 37.8555882595 * self.t) X1 += 0.00000849963 * math.cos(5.81599535394 + 38.89811798311 * self.t) X1 += 0.00000922754 * math.cos(3.34516686314 + 72.05647063421 * self.t) X1 += 0.00000726258 * math.cos(4.24833812431 + 36.404745446 * self.t) X1 += 0.00000778220 * math.cos(5.84479856092 + 206.42936592071 * self.t) X1 += 0.00000754025 * math.cos(5.33205816073 + 220.6564599223 * self.t) X1 += 0.00000607406 * math.cos(0.10576615596 + 1059.6257476727 * self.t) X1 += 0.00000571831 * math.cos(2.42930874906 + 522.8212355773 * self.t) X1 += 0.00000560995 * math.cos(1.91555986158 + 537.0483295789 * self.t) X1 += 0.00000501078 * math.cos(1.71335109406 + 28.81562556571 * self.t) X1 += 0.00000493238 * math.cos(5.24702261334 + 39.3736908626 * self.t) X1 += 0.00000474802 * math.cos(4.40715596351 + 98.6561710411 * self.t) X1 += 0.00000453975 * math.cos(1.71443209341 + 35.9291725665 * self.t) X1 += 0.00000471731 * math.cos(4.84217171915 + 1.7282901918 * self.t) X1 += 0.00000410057 * math.cos(5.76579953705 + 40.8245336761 * self.t) X1 += 0.00000366899 * math.cos(5.76755572930 + 47.9380806769 * self.t) X1 += 0.00000450109 * math.cos(1.25670451550 + 76.0222537921 * self.t) X1 += 0.00000354347 * math.cos(6.27109348494 + 1.24065522479 * self.t) X1 += 0.00000300159 * math.cos(2.88687992256 + 6.1817083167 * self.t) X1 += 0.00000327501 * math.cos(4.20479564636 + 33.43580002939 * self.t) X1 += 0.00000174973 * math.cos(5.64027558321 + 32.4389622881 * self.t) X1 += 0.00000171503 * math.cos(4.43985554308 + 34.1840674273 * self.t) X1 += 0.00000156749 * math.cos(2.59545084410 + 79.47883417571 * self.t) X1 += 0.00000152549 * math.cos(0.58219894744 + 30.300098274 * self.t) X1 += 0.00000150775 * math.cos(3.03954929901 + 42.5696388153 * self.t) X1 += 0.00000162280 * math.cos(0.79977049351 + 31.2633061205 * self.t) X1 += 0.00000131609 * math.cos(1.62895622934 + 7.83293736379 * self.t) X1 += 0.00000136159 * math.cos(4.57878446789 + 70.5719979259 * self.t) X1 += 0.00000134616 * math.cos(0.39184091634 + 45.49040012211 * self.t) X1 += 0.00000116304 * math.cos(0.61710594601 + 46.4536079686 * self.t) X1 += 0.00000115918 * math.cos(1.81843338530 + 44.31474395451 * self.t) X1 += 0.00000110293 * math.cos(6.26561089969 + 35.4560918145 * self.t) X1 += 0.00000099282 * math.cos(5.06218386285 + 2.7251279331 * self.t) X1 += 0.00000099914 * math.cos(1.21626942611 + 41.2976144281 * self.t) X1 += 0.00000108706 * math.cos(3.09142093314 + 113.15845168861 * self.t) X1 += 0.00000088965 * math.cos(4.26680850699 + 60.52313540329 * self.t) X1 += 0.00000086886 * math.cos(5.46872067794 + 31.9513273211 * self.t) X1 += 0.00000072232 * math.cos(3.50587405737 + 640.1411037975 * self.t) X1 += 0.00000086985 * math.cos(4.80098575405 + 419.72846135871 * self.t) X1 += 0.00000073430 * math.cos(4.36511226727 + 70.08436295889 * self.t) X1 += 0.00000053395 * math.cos(4.46520807878 + 433.9555553603 * self.t) X1 += 0.00000057451 * math.cos(1.08003733120 + 213.5429129215 * self.t) X1 += 0.00000051458 * math.cos(4.01726374522 + 69.3963417583 * self.t) X1 += 0.00000048797 * math.cos(6.01365170443 + 111.67397898031 * self.t) X1 += 0.00000048557 * math.cos(6.24808481100 + 2.6769438233 * self.t) X1 += 0.00000042206 * math.cos(3.23823062186 + 74.53778108379 * self.t) X1 += 0.00000042550 * math.cos(1.67247318349 + 7.66618102501 * self.t) X1 += 0.00000039462 * math.cos(5.84051041865 + 31.7845709823 * self.t) X1 += 0.00000039445 * math.cos(0.94630986910 + 12.77399045571 * self.t) X1 += 0.00000042389 * math.cos(5.59019905902 + 110.189506272 * self.t) X1 += 0.00000044118 * math.cos(0.44615133445 + 1589.3167127673 * self.t) X1 += 0.00000037988 * math.cos(2.73850879415 + 6.3484646555 * self.t) X1 += 0.00000037802 * math.cos(5.98781130211 + 14.258463164 * self.t) X1 += 0.00000036280 * math.cos(6.27894536142 + 273.8222308413 * self.t) X1 += 0.00000037247 * math.cos(4.62968774107 + 73.0533083755 * self.t) X1 += 0.00000036282 * math.cos(2.85336450932 + 84.5866436064 * self.t) X1 += 0.00000040018 * math.cos(4.27418471085 + 4.4366031775 * self.t) X1 += 0.00000032400 * math.cos(1.64328879813 + 44.96913526031 * self.t) X1 += 0.00000031842 * math.cos(5.16652228087 + 34.9202727377 * self.t) X1 += 0.00000032037 * math.cos(2.94551844856 + 27.3311528574 * self.t) X1 += 0.00000034456 * math.cos(3.37152599360 + 529.9347825781 * self.t) X1 += 0.00000031208 * math.cos(1.73420111381 + 1052.51220067191 * self.t) X1 += 0.00000030002 * math.cos(2.33639558082 + 1066.7392946735 * self.t) X1 += 0.00000033805 * math.cos(6.04114496470 + 149.8070146181 * self.t) X1 += 0.00000033096 * math.cos(2.45794089359 + 116.12739710521 * self.t) X1 += 0.00000030571 * math.cos(4.02151161164 + 22.3900997655 * self.t) X1 += 0.00000024020 * math.cos(0.23821463973 + 63.9797157869 * self.t) X1 += 0.00000023780 * math.cos(4.34619784366 + 105.76971804189 * self.t) X1 += 0.00000023110 * math.cos(2.51348904373 + 23.87457247379 * self.t) X1 += 0.00000022233 * math.cos(1.21582777350 + 174.9222423167 * self.t) X1 += 0.00000021377 * math.cos(3.74139728076 + 316.6356871401 * self.t) X1 += 0.00000025400 * math.cos(4.52702077197 + 106.73292588839 * self.t) X1 += 0.00000020754 * math.cos(0.94473828111 + 5.6604434549 * self.t) X1 += 0.00000025572 * math.cos(5.46068636869 + 529.44714761109 * self.t) X1 += 0.00000019878 * math.cos(1.01805940417 + 32.9602271499 * self.t) X1 += 0.00000019754 * math.cos(4.49000124955 + 49.42255338521 * self.t) X1 += 0.00000019241 * math.cos(6.01413524726 + 7.14491616321 * self.t) X1 += 0.00000017979 * math.cos(1.48478132886 + 62.4952430786 * self.t) X1 += 0.00000019513 * math.cos(5.64767624982 + 68.5998902506 * self.t) X1 += 0.00000018273 * math.cos(5.20130356006 + 227.77000692311 * self.t) X1 += 0.00000017552 * math.cos(5.80350239388 + 69.0875252176 * self.t) X1 += 0.00000016704 * math.cos(3.94483252805 + 40.8581635709 * self.t) X1 += 0.00000016996 * math.cos(1.10449263633 + 91.54262404029 * self.t) X1 += 0.00000016800 * math.cos(0.51632981099 + 30.4668546128 * self.t) X1 += 0.00000016800 * math.cos(0.51632981099 + 30.95448957981 * self.t) X1 += 0.00000016400 * math.cos(5.02426208775 + 33.26904369061 * self.t) X1 += 0.00000017242 * math.cos(0.18352088447 + 11.55015017831 * self.t) X1 += 0.00000015590 * math.cos(1.99260946960 + 37.1048287341 * self.t) X1 += 0.00000015590 * math.cos(5.48957045033 + 39.6488775085 * self.t) X1 += 0.00000015469 * math.cos(0.19931591320 + 43.79347909271 * self.t) X1 += 0.00000016590 * math.cos(2.76837508684 + 33.71098667531 * self.t) X1 += 0.00000019347 * math.cos(5.63498287914 + 152.77596003471 * self.t) X1 += 0.00000014994 * math.cos(2.71995630411 + 319.06881347989 * self.t) X1 += 0.00000014395 * math.cos(0.95950619453 + 110.45013870291 * self.t) X1 += 0.00000015528 * math.cos(1.16348592635 + 79.43065006591 * self.t) X1 += 0.00000013727 * math.cos(2.45811249773 + 43.484662552 * self.t) X1 += 0.00000013988 * math.cos(3.96979676090 + 4.2096006414 * self.t) X1 += 0.00000014467 * math.cos(0.42164709009 + 108.70503356371 * self.t) X1 += 0.00000016652 * math.cos(3.17617180933 + 304.84171947829 * self.t) X1 += 0.00000015153 * math.cos(3.21783791411 + 72.31710306511 * self.t) X1 += 0.00000012810 * math.cos(2.37864271463 + 11.2895177474 * self.t) X1 += 0.00000012751 * math.cos(0.61424962834 + 45.7992166628 * self.t) X1 += 0.00000013293 * math.cos(4.71511827202 + 43.0427195673 * self.t) X1 += 0.00000012751 * math.cos(2.55685741962 + 515.70768857651 * self.t) X1 += 0.00000011616 * math.cos(2.50185569269 + 97.17169833279 * self.t) X1 += 0.00000011538 * math.cos(6.20327139591 + 633.0275567967 * self.t) X1 += 0.00000011046 * math.cos(1.26188662646 + 25.8466801491 * self.t) X1 += 0.00000011032 * math.cos(3.82567311622 + 4.8639919472 * self.t) X1 += 0.00000011189 * math.cos(3.94939417077 + 83.1021708981 * self.t) X1 += 0.00000010860 * math.cos(0.38739756984 + 9.8050450391 * self.t) X1 += 0.00000010958 * math.cos(1.48375898962 + 415.04804069769 * self.t) X1 += 0.00000010244 * math.cos(0.26615444717 + 71.09326278771 * self.t) X1 += 0.00000011427 * math.cos(1.50679043329 + 129.6756596781 * self.t) X1 += 0.00000009895 * math.cos(5.62468142972 + 251.6759485593 * self.t) X1 += 0.00000009802 * math.cos(1.83814841533 + 44.48150029329 * self.t) X1 += 0.00000011029 * math.cos(4.69741395112 + 143.38148881789 * self.t) X1 += 0.00000009235 * math.cos(5.99370019321 + 199.3158189199 * self.t) X1 += 0.00000008899 * math.cos(3.54958918415 + 7.3573644843 * self.t) X1 += 0.00000007746 * math.cos(5.89688581764 + 103.3365917021 * self.t) X1 += 0.00000008691 * math.cos(3.86130807292 + 32.7477788288 * self.t) X1 += 0.00000007714 * math.cos(5.08136079606 + 65.46418849521 * self.t) X1 += 0.00000008007 * math.cos(1.80952555463 + 544.1618765797 * self.t) X1 += 0.00000007513 * math.cos(1.47497152514 + 69.6087900794 * self.t) X1 += 0.00000007336 * math.cos(5.00489054996 + 15.7429358723 * self.t) X1 += 0.00000007195 * math.cos(6.14029832936 + 949.4194264533 * self.t) X1 += 0.00000009601 * math.cos(0.96952505042 + 80.963306884 * self.t) X1 += 0.00000008094 * math.cos(3.27383873772 + 526.7533888404 * self.t) X1 += 0.00000008109 * math.cos(1.06293290956 + 533.1161763158 * self.t) X1 += 0.00000006906 * math.cos(5.27751864757 + 137.2768416459 * self.t) X1 += 0.00000007455 * math.cos(5.82601593331 + 105.2484531801 * self.t) X1 += 0.00000007826 * math.cos(4.02401038086 + 77.0311536209 * self.t) X1 += 0.00000006529 * math.cos(0.86598314454 + 65.2035560643 * self.t) X1 += 0.00000007134 * math.cos(3.62090018772 + 44.00592741381 * self.t) X1 += 0.00000006186 * math.cos(2.42103444520 + 31.4757544416 * self.t) X1 += 0.00000006186 * math.cos(2.42103444520 + 30.9881194746 * self.t) X1 += 0.00000007698 * math.cos(0.17876132177 + 14.47091148511 * self.t) X1 += 0.00000007434 * math.cos(5.53413189412 + 146.8380692015 * self.t) X1 += 0.00000006317 * math.cos(0.53538901275 + 66.9486612035 * self.t) X1 += 0.00000006903 * math.cos(6.20818943193 + 75.98862389731 * self.t) X1 += 0.00000005591 * math.cos(1.90701487438 + 448.98829064149 * self.t) X1 += 0.00000006425 * math.cos(5.04706195455 + 678.27413943531 * self.t) X1 += 0.00000005483 * math.cos(3.18327336885 + 34.44469985821 * self.t) X1 += 0.00000005483 * math.cos(4.29890655108 + 42.3090063844 * self.t) X1 += 0.00000005519 * math.cos(2.84195707915 + 853.4401992355 * self.t) X1 += 0.00000005483 * math.cos(3.53790147295 + 100.14064374939 * self.t) X1 += 0.00000005483 * math.cos(3.53790147295 + 100.6282787164 * self.t) X1 += 0.00000006288 * math.cos(1.03240051727 + 143.9027536797 * self.t) X1 += 0.00000006239 * math.cos(5.78066710550 + 17.76992530181 * self.t) X1 += 0.00000005246 * math.cos(5.09114965169 + 209.6107596584 * self.t) X1 += 0.00000005331 * math.cos(3.26471064810 + 45.9659730016 * self.t) X1 += 0.00000005131 * math.cos(6.10583196953 + 217.4750661846 * self.t) X1 += 0.00000005325 * math.cos(4.39759756568 + 19.2543980101 * self.t) X1 += 0.00000005172 * math.cos(0.86928942503 + 25.3590451821 * self.t) X1 += 0.00000005139 * math.cos(2.60427452606 + 6.86972951729 * self.t) X1 += 0.00000005992 * math.cos(1.19287924990 + 9.3174100721 * self.t) X1 += 0.00000005011 * math.cos(3.34804654196 + 38.85242600079 * self.t) X1 += 0.00000004975 * math.cos(1.43964900757 + 525.2543619171 * self.t) X1 += 0.00000004910 * math.cos(5.04787040559 + 45.277951801 * self.t) X1 += 0.00000005250 * math.cos(4.87798510402 + 0.719390363 * self.t) X1 += 0.00000004731 * math.cos(1.56230403811 + 40.3825906914 * self.t) X1 += 0.00000004731 * math.cos(2.77828322823 + 36.3711155512 * self.t) X1 += 0.00000005910 * math.cos(6.11804979728 + 6168.43292559449 * self.t) X1 += 0.00000004700 * math.cos(6.23394030506 + 50.9070260935 * self.t) X1 += 0.00000005127 * math.cos(0.06949696047 + 140.9338082631 * self.t) X1 += 0.00000005321 * math.cos(3.67018745291 + 1104.87233031131 * self.t) X1 += 0.00000006339 * math.cos(2.59865692618 + 10175.3963280567 * self.t) X1 += 0.00000004983 * math.cos(3.03193615352 + 1090.6452363097 * self.t) X1 += 0.00000005487 * math.cos(4.85218420019 + 180.03005174739 * self.t) X1 += 0.00000004560 * math.cos(3.95095239655 + 323.74923414091 * self.t) X1 += 0.00000004689 * math.cos(1.24271255508 + 1068.22376738181 * self.t) X1 += 0.00000005562 * math.cos(1.26401999292 + 10098.64262181409 * self.t) X1 += 0.00000004432 * math.cos(2.40638908148 + 415.7963080956 * self.t) X1 += 0.00000004456 * math.cos(6.17485306628 + 235.68919520349 * self.t) X1 += 0.00000004289 * math.cos(5.97528879519 + 1051.0277279636 * self.t) X1 += 0.00000004145 * math.cos(3.13378236518 + 33.6964324603 * self.t) X1 += 0.00000004167 * math.cos(1.72807331665 + 416.532513406 * self.t) X1 += 0.00000004107 * math.cos(2.49036069416 + 61.01077037031 * self.t) X1 += 0.00000004088 * math.cos(5.45739808026 + 423.66061462181 * self.t) X1 += 0.00000005027 * math.cos(4.43953537205 + 21.7020785649 * self.t) X1 += 0.00000004030 * math.cos(5.01269280095 + 216.72430665921 * self.t) X1 += 0.00000004278 * math.cos(4.65333719777 + 310.4707937708 * self.t) X1 += 0.00000004013 * math.cos(1.39689438468 + 104275.10267753768 * self.t) X1 += 0.00000004505 * math.cos(1.22507263591 + 291.9478482112 * self.t) X1 += 0.00000003959 * math.cos(6.18034607330 + 210.36151918381 * self.t) X1 += 0.00000003962 * math.cos(4.02082978591 + 978.93988816699 * self.t) X1 += 0.00000005561 * math.cos(1.74843583918 + 1409.47023230609 * self.t) X1 += 0.00000005073 * math.cos(3.58205424554 + 1498.3359125231 * self.t) X1 += 0.00000004227 * math.cos(1.48715312131 + 534.38820070301 * self.t) X1 += 0.00000004054 * math.cos(4.02884108627 + 430.02340209721 * self.t) X1 += 0.00000003863 * math.cos(2.24264031920 + 1127.50624756031 * self.t) X1 += 0.00000004367 * math.cos(1.71153359581 + 58.9837809408 * self.t) X1 += 0.00000004694 * math.cos(3.33961949377 + 77.5067265004 * self.t) X1 += 0.00000004144 * math.cos(3.59057653937 + 518.1408149163 * self.t) X1 += 0.00000004289 * math.cos(3.29776439152 + 921.3206991231 * self.t) X1 += 0.00000004039 * math.cos(3.79987840474 + 1622.76932774409 * self.t) X1 += 0.00000005180 * math.cos(5.37115331697 + 99.1438060081 * self.t) X1 += 0.00000004845 * math.cos(6.04321981604 + 136.78920667889 * self.t) X1 += 0.00000004827 * math.cos(2.78459346340 + 418.2439886504 * self.t) X1 += 0.00000003722 * math.cos(0.22932453326 + 1065.2548219652 * self.t) X1 += 0.00000004729 * math.cos(3.76762324044 + 421.212934067 * self.t) X1 += 0.00000003490 * math.cos(5.25995346649 + 986.8041946932 * self.t) X1 += 0.00000003715 * math.cos(6.02151166051 + 254.10907489909 * self.t) X1 += 0.00000003488 * math.cos(1.23861297869 + 187.9400502559 * self.t) X1 += 0.00000003989 * math.cos(3.79961685835 + 95.7354097343 * self.t) X1 += 0.00000003603 * math.cos(0.65230587403 + 67.1154175423 * self.t) X1 += 0.00000003530 * math.cos(2.51065807549 + 24.36220744081 * self.t) X1 += 0.00000003538 * math.cos(3.09031960755 + 57.4993082325 * self.t) X1 += 0.00000003838 * math.cos(1.99815683749 + 979.90309601349 * self.t) X1 += 0.00000003615 * math.cos(3.17553643085 + 493.2862196486 * self.t) X1 += 0.00000003457 * math.cos(0.22865254260 + 807.70598162989 * self.t) X1 += 0.00000003648 * math.cos(3.01000228275 + 647.25465079831 * self.t) X1 += 0.00000004048 * math.cos(4.68171378592 + 979.69064769239 * self.t) X1 += 0.00000004414 * math.cos(3.57495606042 + 1062.59469308931 * self.t) X1 += 0.00000003631 * math.cos(2.31921127570 + 486.1726726478 * self.t) X1 += 0.00000003347 * math.cos(5.70639780704 + 151.2914873264 * self.t) X1 += 0.00000003305 * math.cos(0.52158954660 + 1544.07013012871 * self.t) X1 += 0.00000003428 * math.cos(1.68792809396 + 107.2205608554 * self.t) X1 += 0.00000003286 * math.cos(5.12949558917 + 1131.6990332543 * self.t) X1 += 0.00000003389 * math.cos(1.65565102713 + 28.98238190449 * self.t) X1 += 0.00000003353 * math.cos(3.87388681549 + 10289.7954349701 * self.t) X1 += 0.00000003214 * math.cos(2.40799794941 + 569.5522909242 * self.t) X1 += 0.00000003210 * math.cos(5.76688710335 + 114.1552894299 * self.t) X1 += 0.00000003353 * math.cos(3.19692974184 + 157.8837694654 * self.t) X1 += 0.00000003339 * math.cos(3.69632773816 + 443.0985839181 * self.t) X1 += 0.00000003188 * math.cos(1.05807532391 + 361.13400238079 * self.t) X1 += 0.00000003390 * math.cos(0.82325646834 + 1558.2972241303 * self.t) X1 += 0.00000003933 * math.cos(0.51543027693 + 313.43973918739 * self.t) X1 += 0.00000003131 * math.cos(5.23811887945 + 275.3067035496 * self.t) X1 += 0.00000003156 * math.cos(4.66486358528 + 431.8404353331 * self.t) X1 += 0.00000003993 * math.cos(3.33001170426 + 67.6366824041 * self.t) X1 += 0.00000003708 * math.cos(1.81916567333 + 500.39976664941 * self.t) X1 += 0.00000004051 * math.cos(2.84746860357 + 59.038662695 * self.t) X1 += 0.00000003757 * math.cos(3.59917867608 + 296.4012663361 * self.t) X1 += 0.00000003138 * math.cos(5.35145867078 + 347.1193567003 * self.t) X1 += 0.00000003086 * math.cos(3.24315098824 + 392.9017584157 * self.t) X1 += 0.00000003466 * math.cos(0.02941146445 + 215.1941419686 * self.t) X1 += 0.00000003139 * math.cos(4.67079139650 + 159.36824217371 * self.t) X1 += 0.00000003466 * math.cos(1.90282193275 + 2145.34674583789 * self.t) X1 += 0.00000003737 * math.cos(1.95939265626 + 449.0364747513 * self.t) X1 += 0.00000003286 * math.cos(3.39700619187 + 435.44002806861 * self.t) X1 += 0.00000003043 * math.cos(3.45909355839 + 2.20386307129 * self.t) X1 += 0.00000003999 * math.cos(1.21766663097 + 6245.1866318371 * self.t) X1 += 0.00000003999 * math.cos(4.35925928456 + 6244.69899687009 * self.t) X1 += 0.00000002999 * math.cos(1.64598289911 + 526.00262931501 * self.t) X1 += 0.00000003014 * math.cos(3.95092279768 + 1054.94532701169 * self.t) X1 += 0.00000003091 * math.cos(2.95397758261 + 42.997027585 * self.t) X1 += 0.00000003274 * math.cos(1.10162661548 + 736.1203310153 * self.t) X1 += 0.00000002965 * math.cos(2.69144881941 + 533.8669358412 * self.t) X1 += 0.00000003149 * math.cos(0.77764778909 + 103.7639804718 * self.t) X1 += 0.00000003610 * math.cos(3.04477019722 + 55.05162767771 * self.t) X1 += 0.00000002937 * math.cos(4.36852075939 + 385.2523923381 * self.t) X1 += 0.00000002903 * math.cos(5.92315544183 + 117.5636857037 * self.t) X1 += 0.00000002968 * math.cos(2.85171539624 + 613.31440085451 * self.t) X1 += 0.00000003097 * math.cos(2.85040396879 + 1395.24313830449 * self.t) X1 += 0.00000002931 * math.cos(5.17875295945 + 202.4972126576 * self.t) X1 += 0.00000003013 * math.cos(3.06605929280 + 121.2352065359 * self.t) X1 += 0.00000003206 * math.cos(1.29027400076 + 53.40958840249 * self.t) X1 += 0.00000003269 * math.cos(5.16847517364 + 480.00777927849 * self.t) X1 += 0.00000003948 * math.cos(3.85972628729 + 112.8832650427 * self.t) X1 += 0.00000002824 * math.cos(1.57846497121 + 176.406715025 * self.t) X1 += 0.00000002827 * math.cos(1.93940329091 + 429.81095377611 * self.t) X1 += 0.00000003348 * math.cos(5.12243609352 + 6284.8041401832 * self.t) X1 += 0.00000002862 * math.cos(0.86276885894 + 384.02855206069 * self.t) X1 += 0.00000003228 * math.cos(0.42457598020 + 52.6039471229 * self.t) X1 += 0.00000003446 * math.cos(3.75606585057 + 62.0076081116 * self.t) X1 += 0.00000003096 * math.cos(3.26760360935 + 71.82946809809 * self.t) X1 += 0.00000003031 * math.cos(4.66996407487 + 494.2348732801 * self.t) X1 += 0.00000003021 * math.cos(1.39292760491 + 328.5964111407 * self.t) X1 += 0.00000002731 * math.cos(2.36952809744 + 432.471082652 * self.t) X1 += 0.00000003171 * math.cos(0.25949036332 + 10215.0138364028 * self.t) X1 += 0.00000002674 * math.cos(0.72177739894 + 158.12984768129 * self.t) X1 += 0.00000002901 * math.cos(5.80027365050 + 559.4697985068 * self.t) X1 += 0.00000002631 * math.cos(5.78146252380 + 2008.8013566425 * self.t) X1 += 0.00000002695 * math.cos(5.11715867535 + 81.61769818981 * self.t) X1 += 0.00000002695 * math.cos(1.97556602176 + 81.13006322279 * self.t) X1 += 0.00000002721 * math.cos(2.68965946829 + 326.1823604807 * self.t) X1 += 0.00000002775 * math.cos(5.84695952836 + 457.8614969965 * self.t) X1 += 0.00000003054 * math.cos(1.52217085552 + 6281.8351947666 * self.t) X1 += 0.00000002852 * math.cos(4.47706032032 + 186.71620997851 * self.t) X1 += 0.00000002538 * math.cos(0.16145086268 + 111.18634401329 * self.t) X1 += 0.00000002835 * math.cos(4.50055998275 + 419.50145882259 * self.t) X1 += 0.00000002868 * math.cos(2.09813621145 + 844.56699288049 * self.t) X1 += 0.00000002530 * math.cos(1.04013419881 + 1050.7525413177 * self.t) X1 += 0.00000002843 * math.cos(2.58892628620 + 830.3398988789 * self.t) X1 += 0.00000002848 * math.cos(3.12250765680 + 659.36662477269 * self.t) X1 += 0.00000003031 * math.cos(4.13022602708 + 406.3469551246 * self.t) X1 += 0.00000002907 * math.cos(5.28583383732 + 573.6968925084 * self.t) X1 += 0.00000002536 * math.cos(3.44172011173 + 82.6145359311 * self.t) X1 += 0.00000002957 * math.cos(0.45041658093 + 947.70795120889 * self.t) X1 += 0.00000003321 * math.cos(2.30536254604 + 449.9996825978 * self.t) X1 += 0.00000003117 * math.cos(3.17172140219 + 457.32567791969 * self.t) X1 += 0.00000002902 * math.cos(2.94761781535 + 10212.0448909862 * self.t) X1 += 0.00000002459 * math.cos(2.17142711813 + 450.73339578069 * self.t) X1 += 0.00000002557 * math.cos(2.89791026532 + 525.4813644532 * self.t) X1 += 0.00000002624 * math.cos(1.78027142371 + 946.2234785006 * self.t) X1 += 0.00000002417 * math.cos(4.80936350850 + 351.5727748252 * self.t) X1 += 0.00000002454 * math.cos(4.84992044892 + 196.01680510321 * self.t) X1 += 0.00000002585 * math.cos(0.99587951695 + 248.70700314271 * self.t) X1 += 0.00000002549 * math.cos(1.80324449988 + 1062.80714141041 * self.t) X1 += 0.00000002615 * math.cos(2.49010683388 + 425.13053311509 * self.t) X1 += 0.00000002387 * math.cos(3.61270640757 + 654.3681977991 * self.t) X1 += 0.00000002439 * math.cos(6.16957116292 + 462.74230389109 * self.t) X1 += 0.00000002367 * math.cos(4.32238656757 + 107.52937739611 * self.t) X1 += 0.00000002538 * math.cos(2.61932649618 + 481.2316195559 * self.t) X1 += 0.00000002479 * math.cos(1.99143603619 + 205.9417309537 * self.t) X1 += 0.00000002791 * math.cos(0.73480816467 + 24.14975911971 * self.t) X1 += 0.00000002626 * math.cos(1.16663444616 + 213.0552779545 * self.t) X1 += 0.00000002445 * math.cos(4.84988920933 + 146.87169909629 * self.t) X1 += 0.00000002575 * math.cos(1.89431453798 + 86.07111631471 * self.t) X1 += 0.00000003120 * math.cos(5.91742201237 + 456.36247007319 * self.t) X1 += 0.00000002587 * math.cos(0.02224873460 + 400.8209466961 * self.t) X1 += 0.00000002261 * math.cos(4.82066845150 + 644.33388949151 * self.t) X1 += 0.00000002796 * math.cos(5.01395178381 + 216.67861467689 * self.t) X1 += 0.00000002896 * math.cos(2.29072801127 + 1685.2959399851 * self.t) X1 += 0.00000002453 * math.cos(3.24288673382 + 109.9625037359 * self.t) X1 += 0.00000002325 * math.cos(4.96633817815 + 442.886135597 * self.t) X1 += 0.00000002387 * math.cos(5.32424727918 + 599.0873068529 * self.t) X1 += 0.00000002873 * math.cos(3.56351208170 + 834.5326845729 * self.t) X1 += 0.00000002963 * math.cos(0.77021714990 + 2119.00767786191 * self.t) X1 += 0.00000002233 * math.cos(5.94426610995 + 709.29362807231 * self.t) X1 += 0.00000002337 * math.cos(4.30558394222 + 210.5739675049 * self.t) X1 += 0.00000002259 * math.cos(3.67528651606 + 29.5036467663 * self.t) X1 += 0.00000002300 * math.cos(0.62755545112 + 986.0534351678 * self.t) X1 += 0.00000002199 * math.cos(2.78438991669 + 606.2008538537 * self.t) X1 += 0.00000002325 * math.cos(3.26991047297 + 109.701871305 * self.t) # Neptune_X2 (t) // 113 terms of order 2 X2 = 0 X2 += 0.01620002167 * math.cos(0.60038473142 + 38.3768531213 * self.t) X2 += 0.00028138323 * math.cos(5.58440767451 + 0.2438174835 * self.t) X2 += 0.00012318619 * math.cos(2.58513114618 + 39.86132582961 * self.t) X2 += 0.00008346956 * math.cos(5.13440715484 + 37.88921815429 * self.t) X2 += 0.00005131003 * math.cos(5.12974075920 + 76.50988875911 * self.t) X2 += 0.00004109792 * math.cos(1.46495026130 + 36.892380413 * self.t) X2 += 0.00001369663 * math.cos(3.55762715050 + 1.7282901918 * self.t) X2 += 0.00000633706 * math.cos(2.38135108376 + 3.21276290011 * self.t) X2 += 0.00000583006 * math.cos(1.54592369321 + 41.3457985379 * self.t) X2 += 0.00000546517 * math.cos(0.70972594452 + 75.0254160508 * self.t) X2 += 0.00000246224 * math.cos(2.44618778574 + 213.5429129215 * self.t) X2 += 0.00000159773 * math.cos(1.26414365966 + 206.42936592071 * self.t) X2 += 0.00000156619 * math.cos(3.61656709171 + 220.6564599223 * self.t) X2 += 0.00000191674 * math.cos(2.17166123081 + 529.9347825781 * self.t) X2 += 0.00000188212 * math.cos(4.43184732741 + 35.40790770471 * self.t) X2 += 0.00000117788 * math.cos(4.12530218101 + 522.8212355773 * self.t) X2 += 0.00000114488 * math.cos(0.05081176794 + 35.9291725665 * self.t) X2 += 0.00000112666 * math.cos(0.21220394551 + 537.0483295789 * self.t) X2 += 0.00000105949 * math.cos(1.13080468733 + 40.8245336761 * self.t) X2 += 0.00000077696 * math.cos(0.84633184914 + 77.9943614674 * self.t) X2 += 0.00000090798 * math.cos(2.05479887039 + 73.5409433425 * self.t) X2 += 0.00000067696 * math.cos(2.44679430551 + 426.8420083595 * self.t) X2 += 0.00000074860 * math.cos(1.44346648461 + 4.6972356084 * self.t) X2 += 0.00000064717 * math.cos(6.06001471150 + 34.9202727377 * self.t) X2 += 0.00000051378 * math.cos(6.13002795973 + 36.404745446 * self.t) X2 += 0.00000050205 * math.cos(0.67007332287 + 42.83027124621 * self.t) X2 += 0.00000040929 * math.cos(6.22049348014 + 33.9234349964 * self.t) X2 += 0.00000036136 * math.cos(6.15460243008 + 98.6561710411 * self.t) X2 += 0.00000033953 * math.cos(5.02568302050 + 1059.6257476727 * self.t) X2 += 0.00000034603 * math.cos(3.26702076082 + 76.0222537921 * self.t) X2 += 0.00000035441 * math.cos(2.49518827466 + 31.2633061205 * self.t) X2 += 0.00000029614 * math.cos(3.34814694529 + 28.81562556571 * self.t) X2 += 0.00000031027 * math.cos(4.97087448592 + 45.49040012211 * self.t) X2 += 0.00000035521 * math.cos(1.13028002523 + 39.3736908626 * self.t) X2 += 0.00000025488 * math.cos(4.04320892614 + 47.9380806769 * self.t) X2 += 0.00000020115 * math.cos(3.93227849656 + 1.24065522479 * self.t) X2 += 0.00000014328 * math.cos(2.73754899228 + 433.9555553603 * self.t) X2 += 0.00000015503 * math.cos(3.13160557995 + 114.6429243969 * self.t) X2 += 0.00000016998 * math.cos(0.93393874821 + 33.43580002939 * self.t) X2 += 0.00000013166 * math.cos(0.39556817176 + 419.72846135871 * self.t) X2 += 0.00000013053 * math.cos(6.11304367644 + 60.52313540329 * self.t) X2 += 0.00000010637 * math.cos(5.94332175983 + 34.1840674273 * self.t) X2 += 0.00000009610 * math.cos(1.65699013342 + 640.1411037975 * self.t) X2 += 0.00000009354 * math.cos(1.41415954295 + 42.5696388153 * self.t) X2 += 0.00000011447 * math.cos(6.19793150566 + 71.5688356672 * self.t) X2 += 0.00000008454 * math.cos(2.75562169800 + 2.7251279331 * self.t) X2 += 0.00000009012 * math.cos(4.44112001347 + 72.05647063421 * self.t) X2 += 0.00000009594 * math.cos(5.79483289118 + 69.3963417583 * self.t) X2 += 0.00000007419 * math.cos(3.49645345230 + 227.77000692311 * self.t) X2 += 0.00000006800 * math.cos(5.14250085135 + 113.15845168861 * self.t) X2 += 0.00000006267 * math.cos(0.79586518424 + 1066.7392946735 * self.t) X2 += 0.00000006895 * math.cos(4.31090775556 + 111.67397898031 * self.t) X2 += 0.00000005770 * math.cos(1.23253284004 + 32.4389622881 * self.t) X2 += 0.00000005686 * math.cos(2.23805923850 + 30.300098274 * self.t) X2 += 0.00000006679 * math.cos(4.85529332414 + 258.78949556011 * self.t) X2 += 0.00000007799 * math.cos(1.58396135295 + 7.3573644843 * self.t) X2 += 0.00000005906 * math.cos(5.92485931723 + 44.31474395451 * self.t) X2 += 0.00000005606 * math.cos(5.17941805418 + 46.4536079686 * self.t) X2 += 0.00000005525 * math.cos(3.61911776351 + 1052.51220067191 * self.t) X2 += 0.00000007257 * math.cos(0.17315189128 + 1097.7587833105 * self.t) X2 += 0.00000005427 * math.cos(1.80586256737 + 105.76971804189 * self.t) X2 += 0.00000005179 * math.cos(4.25986194250 + 515.70768857651 * self.t) X2 += 0.00000005163 * math.cos(6.27919257182 + 7.83293736379 * self.t) X2 += 0.00000004688 * math.cos(2.52139212878 + 222.14093263061 * self.t) X2 += 0.00000005379 * math.cos(5.86341629561 + 22.3900997655 * self.t) X2 += 0.00000004607 * math.cos(4.89100806572 + 549.1603035533 * self.t) X2 += 0.00000004101 * math.cos(0.29016053329 + 213.0552779545 * self.t) X2 += 0.00000004262 * math.cos(5.51395238453 + 204.9448932124 * self.t) X2 += 0.00000003916 * math.cos(0.21419544093 + 207.913838629 * self.t) X2 += 0.00000004089 * math.cos(4.97684127402 + 304.84171947829 * self.t) X2 += 0.00000003729 * math.cos(1.40848954224 + 199.3158189199 * self.t) X2 += 0.00000003680 * math.cos(5.54809318630 + 1589.3167127673 * self.t) X2 += 0.00000003702 * math.cos(1.01863119774 + 319.06881347989 * self.t) X2 += 0.00000004832 * math.cos(1.26423594188 + 215.0273856298 * self.t) X2 += 0.00000003474 * math.cos(1.17401543445 + 103.3365917021 * self.t) X2 += 0.00000003298 * math.cos(0.10619126376 + 544.1618765797 * self.t) X2 += 0.00000004521 * math.cos(0.07911565781 + 108.2173985967 * self.t) X2 += 0.00000003967 * math.cos(2.67776762695 + 944.7390057923 * self.t) X2 += 0.00000004059 * math.cos(3.01104350847 + 149.8070146181 * self.t) X2 += 0.00000004009 * math.cos(5.61852534309 + 533.1161763158 * self.t) X2 += 0.00000003288 * math.cos(1.44957894842 + 407.9344936969 * self.t) X2 += 0.00000003976 * math.cos(5.00221858099 + 526.7533888404 * self.t) X2 += 0.00000003343 * math.cos(0.65785646071 + 531.4192552864 * self.t) X2 += 0.00000003932 * math.cos(3.66244745467 + 91.54262404029 * self.t) X2 += 0.00000003478 * math.cos(6.19876429652 + 6.1817083167 * self.t) X2 += 0.00000002967 * math.cos(1.04478648324 + 860.55374623631 * self.t) X2 += 0.00000003058 * math.cos(0.02482940557 + 342.9747551161 * self.t) X2 += 0.00000003974 * math.cos(2.04910269520 + 335.8612081153 * self.t) X2 += 0.00000002849 * math.cos(0.86611245106 + 666.4801717735 * self.t) X2 += 0.00000002999 * math.cos(1.27874757189 + 937.62545879149 * self.t) X2 += 0.00000003008 * math.cos(5.16783990611 + 74.53778108379 * self.t) X2 += 0.00000003080 * math.cos(3.04902400148 + 129.6756596781 * self.t) X2 += 0.00000003346 * math.cos(4.64303639862 + 1162.7185218913 * self.t) X2 += 0.00000002625 * math.cos(1.69459459452 + 273.8222308413 * self.t) X2 += 0.00000002931 * math.cos(1.57809055514 + 235.68919520349 * self.t) X2 += 0.00000002579 * math.cos(0.48473918174 + 1073.85284167431 * self.t) X2 += 0.00000002550 * math.cos(6.14366282644 + 26.58288545949 * self.t) X2 += 0.00000002542 * math.cos(4.22297682017 + 1265.81129610991 * self.t) X2 += 0.00000002483 * math.cos(1.73279038376 + 453.1810763355 * self.t) X2 += 0.00000002732 * math.cos(1.76626805419 + 563.38739755489 * self.t) X2 += 0.00000002508 * math.cos(1.67664275102 + 37.8555882595 * self.t) X2 += 0.00000002508 * math.cos(0.34076894500 + 425.35753565121 * self.t) X2 += 0.00000002680 * math.cos(5.74609617365 + 454.6655490438 * self.t) X2 += 0.00000002511 * math.cos(3.15018930028 + 209.6107596584 * self.t) X2 += 0.00000002512 * math.cos(1.74477024139 + 217.4750661846 * self.t) X2 += 0.00000002552 * math.cos(5.67032305105 + 79.47883417571 * self.t) X2 += 0.00000002457 * math.cos(2.67033044982 + 38.89811798311 * self.t) X2 += 0.00000002343 * math.cos(1.93599816349 + 981.3875687218 * self.t) X2 += 0.00000002501 * math.cos(1.67412173715 + 669.4009330803 * self.t) X2 += 0.00000002330 * math.cos(3.95065162563 + 38.32866901151 * self.t) X2 += 0.00000002327 * math.cos(0.39474993260 + 38.4250372311 * self.t) X2 += 0.00000002481 * math.cos(5.56752927904 + 655.1738390787 * self.t) X2 += 0.00000002569 * math.cos(4.22623902188 + 464.97504399731 * self.t) # Neptune_X3 (t) // 37 terms of order 3 X3 = 0 X3 += 0.00000985355 * math.cos(0.69240373955 + 38.3768531213 * self.t) X3 += 0.00000482798 * math.cos(0.83271959724 + 37.88921815429 * self.t) X3 += 0.00000416447 * math.cos(0.37037561694 + 0.2438174835 * self.t) X3 += 0.00000303825 * math.cos(0.53797420117 + 39.86132582961 * self.t) X3 += 0.00000089203 * math.cos(1.52338099991 + 36.892380413 * self.t) X3 += 0.00000070862 * math.cos(5.83899744010 + 76.50988875911 * self.t) X3 += 0.00000028900 * math.cos(5.65001946959 + 41.3457985379 * self.t) X3 += 0.00000022279 * math.cos(2.95886685234 + 206.42936592071 * self.t) X3 += 0.00000021480 * math.cos(1.87359273442 + 220.6564599223 * self.t) X3 += 0.00000016157 * math.cos(5.83581915834 + 522.8212355773 * self.t) X3 += 0.00000015714 * math.cos(4.76719570238 + 537.0483295789 * self.t) X3 += 0.00000011404 * math.cos(2.25961154910 + 35.40790770471 * self.t) X3 += 0.00000013199 * math.cos(0.06057423298 + 7.3573644843 * self.t) X3 += 0.00000007024 * math.cos(0.69890179308 + 3.21276290011 * self.t) X3 += 0.00000006772 * math.cos(1.19679143435 + 69.3963417583 * self.t) X3 += 0.00000004517 * math.cos(3.28893027439 + 45.49040012211 * self.t) X3 += 0.00000004523 * math.cos(4.18705629066 + 31.2633061205 * self.t) X3 += 0.00000003682 * math.cos(1.47261975259 + 98.6561710411 * self.t) X3 += 0.00000003656 * math.cos(0.60146659814 + 968.64494742849 * self.t) X3 += 0.00000003927 * math.cos(0.54740561653 + 426.8420083595 * self.t) X3 += 0.00000003199 * math.cos(1.67327016260 + 1519.6765535255 * self.t) X3 += 0.00000003498 * math.cos(3.27476696786 + 407.9344936969 * self.t) X3 += 0.00000003304 * math.cos(2.24745680549 + 422.1615876985 * self.t) X3 += 0.00000003331 * math.cos(1.97045240379 + 36.404745446 * self.t) X3 += 0.00000003244 * math.cos(2.85168281358 + 484.2005649725 * self.t) X3 += 0.00000002689 * math.cos(0.89932845788 + 441.06910236111 * self.t) X3 += 0.00000003247 * math.cos(1.76512860403 + 498.42765897409 * self.t) X3 += 0.00000002651 * math.cos(0.45669916115 + 304.84171947829 * self.t) X3 += 0.00000002645 * math.cos(5.61672793904 + 461.77909604459 * self.t) X3 += 0.00000002542 * math.cos(5.76347018476 + 444.5830566264 * self.t) X3 += 0.00000002524 * math.cos(0.75739625090 + 433.9555553603 * self.t) X3 += 0.00000002472 * math.cos(5.63416184223 + 319.06881347989 * self.t) X3 += 0.00000002355 * math.cos(0.46192754883 + 447.552002043 * self.t) X3 += 0.00000002876 * math.cos(5.22513442854 + 853.4401992355 * self.t) X3 += 0.00000002279 * math.cos(4.63709500769 + 458.810150628 * self.t) X3 += 0.00000002147 * math.cos(2.63611189369 + 175.40987728371 * self.t) X3 += 0.00000002637 * math.cos(3.63693499332 + 73.5409433425 * self.t) # Neptune_X4 (t) // 14 terms of order 4 X4 = 0 X4 += 0.00003455306 * math.cos(3.61464892215 + 38.3768531213 * self.t) X4 += 0.00000047405 * math.cos(2.21390996774 + 0.2438174835 * self.t) X4 += 0.00000021936 * math.cos(2.72972488197 + 37.88921815429 * self.t) X4 += 0.00000015596 * math.cos(1.87854121560 + 76.50988875911 * self.t) X4 += 0.00000017186 * math.cos(5.53785371687 + 39.86132582961 * self.t) X4 += 0.00000017459 * math.cos(4.82899740364 + 36.892380413 * self.t) X4 += 0.00000004229 * math.cos(1.43245860878 + 515.70768857651 * self.t) X4 += 0.00000004334 * math.cos(5.41648117577 + 433.9555553603 * self.t) X4 += 0.00000003547 * math.cos(5.75561157107 + 989.98558843089 * self.t) X4 += 0.00000003155 * math.cos(4.85322840051 + 467.40817033709 * self.t) X4 += 0.00000003017 * math.cos(0.06479449145 + 227.77000692311 * self.t) X4 += 0.00000002981 * math.cos(0.29920864811 + 1.7282901918 * self.t) X4 += 0.00000002295 * math.cos(0.13749342692 + 220.6564599223 * self.t) X4 += 0.00000002296 * math.cos(4.70646260044 + 206.42936592071 * self.t) # Neptune_X5 (t) // 1 term of order 5 X5 = 0 X5 += 0.00000026291 * math.cos(3.71724730200 + 38.3768531213 * self.t) X = (X0+ X1*self.t+ X2*self.t*self.t+ X3*self.t*self.t*self.t+ X4*self.t*self.t*self.t*self.t+ X5*self.t*self.t*self.t*self.t*self.t) # Neptune_Y0 (t) // 821 terms of order 0 Y0 = 0 Y0 += 30.05973100580 * math.cos(3.74109000403 + 38.3768531213 * self.t) Y0 += 0.40567587218 * math.cos(2.41070337452 + 0.2438174835 * self.t) Y0 += 0.13506026414 * math.cos(1.92976188293 + 76.50988875911 * self.t) Y0 += 0.15716341901 * math.cos(4.82548976006 + 36.892380413 * self.t) Y0 += 0.14935642614 * math.cos(5.79716600101 + 39.86132582961 * self.t) Y0 += 0.02590782232 * math.cos(0.42530135542 + 1.7282901918 * self.t) Y0 += 0.01073890204 * math.cos(3.81397520876 + 75.0254160508 * self.t) Y0 += 0.00816388197 * math.cos(5.49424416077 + 3.21276290011 * self.t) Y0 += 0.00702768075 * math.cos(6.16602540157 + 35.40790770471 * self.t) Y0 += 0.00687594822 * math.cos(2.29155372023 + 37.88921815429 * self.t) Y0 += 0.00565555652 * math.cos(4.41864141199 + 41.3457985379 * self.t) Y0 += 0.00495650075 * math.cos(5.31196432386 + 529.9347825781 * self.t) Y0 += 0.00306025380 * math.cos(5.11155686178 + 73.5409433425 * self.t) Y0 += 0.00272446904 * math.cos(5.58643013675 + 213.5429129215 * self.t) Y0 += 0.00135892298 * math.cos(3.97575347243 + 77.9943614674 * self.t) Y0 += 0.00122117697 * math.cos(2.87943509460 + 34.9202727377 * self.t) Y0 += 0.00090968285 * math.cos(0.11807115994 + 114.6429243969 * self.t) Y0 += 0.00068915400 * math.cos(4.26390741720 + 4.6972356084 * self.t) Y0 += 0.00040370680 * math.cos(1.09050058383 + 33.9234349964 * self.t) Y0 += 0.00028891307 * math.cos(3.21868082836 + 42.83027124621 * self.t) Y0 += 0.00029247752 * math.cos(0.05239890051 + 72.05647063421 * self.t) Y0 += 0.00025576289 * math.cos(3.05422599686 + 71.5688356672 * self.t) Y0 += 0.00020517968 * math.cos(4.12700709797 + 33.43580002939 * self.t) Y0 += 0.00012614154 * math.cos(1.99850111659 + 113.15845168861 * self.t) Y0 += 0.00012788929 * math.cos(1.16690001367 + 111.67397898031 * self.t) Y0 += 0.00012013477 * math.cos(5.66154697546 + 1059.6257476727 * self.t) Y0 += 0.00009854638 * math.cos(1.82793273920 + 36.404745446 * self.t) Y0 += 0.00008385825 * math.cos(3.22321843541 + 108.2173985967 * self.t) Y0 += 0.00007577585 * math.cos(4.81209675667 + 426.8420083595 * self.t) Y0 += 0.00006452053 * math.cos(3.05476893393 + 6.1817083167 * self.t) Y0 += 0.00006551074 * math.cos(3.48963683470 + 1.24065522479 * self.t) Y0 += 0.00004652534 * math.cos(4.81582901104 + 37.8555882595 * self.t) Y0 += 0.00004732958 * math.cos(2.52632268239 + 79.47883417571 * self.t) Y0 += 0.00004557247 * math.cos(5.80951559837 + 38.89811798311 * self.t) Y0 += 0.00004322550 * math.cos(0.80665146695 + 38.32866901151 * self.t) Y0 += 0.00004315539 * math.cos(3.53393508109 + 38.4250372311 * self.t) Y0 += 0.00004089036 * math.cos(0.42349431022 + 37.4136452748 * self.t) Y0 += 0.00004248658 * math.cos(4.06300076615 + 28.81562556571 * self.t) Y0 += 0.00004622142 * math.cos(4.31075084247 + 70.08436295889 * self.t) Y0 += 0.00003926447 * math.cos(3.91895428213 + 39.34006096781 * self.t) Y0 += 0.00003148422 * math.cos(0.47516466537 + 76.0222537921 * self.t) Y0 += 0.00003940981 * math.cos(3.86846009370 + 98.6561710411 * self.t) Y0 += 0.00003323363 * math.cos(3.11696612599 + 4.4366031775 * self.t) Y0 += 0.00003282964 * math.cos(4.38630915294 + 39.3736908626 * self.t) Y0 += 0.00003110464 * math.cos(0.27337264525 + 47.9380806769 * self.t) Y0 += 0.00002927062 * math.cos(1.26687681282 + 70.5719979259 * self.t) Y0 += 0.00002748919 * math.cos(2.29910620256 + 32.4389622881 * self.t) Y0 += 0.00003316668 * math.cos(3.39273716880 + 144.8659615262 * self.t) Y0 += 0.00002822405 * math.cos(5.35210680933 + 31.9513273211 * self.t) Y0 += 0.00002695972 * math.cos(2.28196668869 + 110.189506272 * self.t) Y0 += 0.00002522990 * math.cos(6.23388252645 + 311.9552664791 * self.t) Y0 += 0.00001888129 * math.cos(1.63385050550 + 35.9291725665 * self.t) Y0 += 0.00001648229 * math.cos(2.49960621702 + 30.300098274 * self.t) Y0 += 0.00001826545 * math.cos(2.00941496239 + 44.31474395451 * self.t) Y0 += 0.00001956241 * math.cos(2.57436514192 + 206.42936592071 * self.t) Y0 += 0.00001681257 * math.cos(2.70480495091 + 40.8245336761 * self.t) Y0 += 0.00001533383 * math.cos(5.88971111646 + 38.26497853671 * self.t) Y0 += 0.00001893076 * math.cos(5.46256301015 + 220.6564599223 * self.t) Y0 += 0.00001527526 * math.cos(4.73412536340 + 38.4887277059 * self.t) Y0 += 0.00002085691 * math.cos(6.28187170642 + 149.8070146181 * self.t) Y0 += 0.00002070612 * math.cos(4.39661439400 + 136.78920667889 * self.t) Y0 += 0.00001535699 * math.cos(2.18492948354 + 73.0533083755 * self.t) Y0 += 0.00001667976 * math.cos(4.48792091670 + 106.73292588839 * self.t) Y0 += 0.00001289620 * math.cos(1.82629228420 + 46.4536079686 * self.t) Y0 += 0.00001559811 * math.cos(5.27109740006 + 38.11622069041 * self.t) Y0 += 0.00001545705 * math.cos(5.35267674075 + 38.6374855522 * self.t) Y0 += 0.00001435033 * math.cos(5.44094847718 + 522.8212355773 * self.t) Y0 += 0.00001406206 * math.cos(2.04637394879 + 537.0483295789 * self.t) Y0 += 0.00001256446 * math.cos(1.13828126057 + 34.1840674273 * self.t) Y0 += 0.00001387973 * math.cos(2.14763765402 + 116.12739710521 * self.t) Y0 += 0.00001457739 * math.cos(3.56061267693 + 181.5145244557 * self.t) Y0 += 0.00001228429 * math.cos(1.21566711155 + 72.31710306511 * self.t) Y0 += 0.00001140665 * math.cos(5.53723346032 + 7.83293736379 * self.t) Y0 += 0.00001080801 * math.cos(3.18403832376 + 42.5696388153 * self.t) Y0 += 0.00001201409 * math.cos(2.31627619186 + 2.7251279331 * self.t) Y0 += 0.00001228671 * math.cos(1.08170099047 + 148.32254190981 * self.t) Y0 += 0.00000722014 * math.cos(4.59727081765 + 152.77596003471 * self.t) Y0 += 0.00000608545 * math.cos(2.92457352888 + 35.4560918145 * self.t) Y0 += 0.00000722865 * math.cos(4.66419895504 + 143.38148881789 * self.t) Y0 += 0.00000632820 * math.cos(1.84622497362 + 7.66618102501 * self.t) Y0 += 0.00000642369 * math.cos(5.54570420373 + 68.5998902506 * self.t) Y0 += 0.00000553789 * math.cos(1.41527095431 + 41.2976144281 * self.t) Y0 += 0.00000682276 * math.cos(3.72885979362 + 218.1630873852 * self.t) Y0 += 0.00000463186 * math.cos(1.17340921668 + 31.7845709823 * self.t) Y0 += 0.00000521560 * math.cos(1.91893273311 + 0.719390363 * self.t) Y0 += 0.00000437892 * math.cos(6.01046620661 + 1589.3167127673 * self.t) Y0 += 0.00000398091 * math.cos(0.79544793472 + 6.3484646555 * self.t) Y0 += 0.00000384065 * math.cos(3.15552603467 + 44.96913526031 * self.t) Y0 += 0.00000395583 * math.cos(3.48448044710 + 108.70503356371 * self.t) Y0 += 0.00000327446 * math.cos(4.26279342171 + 60.52313540329 * self.t) Y0 += 0.00000358824 * math.cos(0.28673200218 + 30.4668546128 * self.t) Y0 += 0.00000315179 * math.cos(1.74548132888 + 74.53778108379 * self.t) Y0 += 0.00000343384 * math.cos(0.17566264278 + 0.7650823453 * self.t) Y0 += 0.00000399611 * math.cos(3.76461168231 + 31.2633061205 * self.t) Y0 += 0.00000314611 * math.cos(1.41723391958 + 419.72846135871 * self.t) Y0 += 0.00000347596 * math.cos(4.83723596339 + 180.03005174739 * self.t) Y0 += 0.00000382279 * math.cos(1.78844211361 + 487.1213262793 * self.t) Y0 += 0.00000300918 * math.cos(2.47842979419 + 69.0875252176 * self.t) Y0 += 0.00000340448 * math.cos(2.33467216950 + 146.8380692015 * self.t) Y0 += 0.00000298710 * math.cos(3.60933906971 + 84.5866436064 * self.t) Y0 += 0.00000290629 * math.cos(0.17794042595 + 110.45013870291 * self.t) Y0 += 0.00000336211 * math.cos(0.57735466050 + 45.49040012211 * self.t) Y0 += 0.00000305606 * math.cos(4.06185849299 + 640.1411037975 * self.t) Y0 += 0.00000333702 * math.cos(3.90017949649 + 254.8116503147 * self.t) Y0 += 0.00000268060 * math.cos(1.73772568979 + 37.0042549976 * self.t) Y0 += 0.00000264760 * math.cos(2.55644426185 + 39.749451245 * self.t) Y0 += 0.00000315240 * math.cos(1.15162155813 + 388.70897272171 * self.t) Y0 += 0.00000227098 * math.cos(6.16236913832 + 273.8222308413 * self.t) Y0 += 0.00000306112 * math.cos(0.18265553789 + 6283.3196674749 * self.t) Y0 += 0.00000284373 * math.cos(1.79060192705 + 12.77399045571 * self.t) Y0 += 0.00000221105 * math.cos(5.08019996555 + 213.0552779545 * self.t) Y0 += 0.00000242568 * math.cos(0.49358017330 + 14.258463164 * self.t) Y0 += 0.00000241087 * math.cos(5.73194988554 + 105.2484531801 * self.t) Y0 += 0.00000226136 * math.cos(1.26736306174 + 80.963306884 * self.t) Y0 += 0.00000245904 * math.cos(5.25701422242 + 27.3311528574 * self.t) Y0 += 0.00000265825 * math.cos(5.68032293038 + 944.7390057923 * self.t) Y0 += 0.00000207893 * math.cos(3.50733218656 + 30.95448957981 * self.t) Y0 += 0.00000214661 * math.cos(1.08322862012 + 316.6356871401 * self.t) Y0 += 0.00000190638 * math.cos(0.75588071076 + 69.3963417583 * self.t) Y0 += 0.00000246295 * math.cos(3.55718121196 + 102.84895673509 * self.t) Y0 += 0.00000202915 * math.cos(2.17108892757 + 415.04804069769 * self.t) Y0 += 0.00000176465 * math.cos(4.85970190916 + 36.7805058284 * self.t) Y0 += 0.00000193886 * math.cos(4.92555932032 + 174.9222423167 * self.t) Y0 += 0.00000175209 * math.cos(5.83814591553 + 39.97320041421 * self.t) Y0 += 0.00000177868 * math.cos(5.01003024093 + 216.67861467689 * self.t) Y0 += 0.00000138494 * math.cos(3.88186287753 + 75.98862389731 * self.t) Y0 += 0.00000152234 * math.cos(3.24582472092 + 11.2895177474 * self.t) Y0 += 0.00000147648 * math.cos(0.11464073993 + 151.2914873264 * self.t) Y0 += 0.00000156202 * math.cos(5.22332207731 + 146.3504342345 * self.t) Y0 += 0.00000152289 * math.cos(1.64425361444 + 23.87457247379 * self.t) Y0 += 0.00000177911 * math.cos(1.60563922042 + 10213.5293636945 * self.t) Y0 += 0.00000162474 * math.cos(2.56271758700 + 63.9797157869 * self.t) Y0 += 0.00000121226 * math.cos(3.53504653517 + 38.16440480021 * self.t) Y0 += 0.00000129049 * math.cos(2.23605274276 + 37.1048287341 * self.t) Y0 += 0.00000120334 * math.cos(0.80557581782 + 38.5893014424 * self.t) Y0 += 0.00000168977 * math.cos(4.06631471177 + 291.4602132442 * self.t) Y0 += 0.00000121138 * math.cos(6.20896007337 + 33.26904369061 * self.t) Y0 += 0.00000129366 * math.cos(0.79823378243 + 45.7992166628 * self.t) Y0 += 0.00000144682 * math.cos(5.34262329825 + 49.42255338521 * self.t) Y0 += 0.00000122915 * math.cos(2.10353894081 + 39.6488775085 * self.t) Y0 += 0.00000113400 * math.cos(5.13399083059 + 83.1021708981 * self.t) Y0 += 0.00000154892 * math.cos(0.17909436973 + 77.4730966056 * self.t) Y0 += 0.00000106737 * math.cos(2.14516700774 + 4.8639919472 * self.t) Y0 += 0.00000104756 * math.cos(4.39192437833 + 43.484662552 * self.t) Y0 += 0.00000125142 * math.cos(1.11541363958 + 4.2096006414 * self.t) Y0 += 0.00000103541 * math.cos(3.68555108825 + 41.08516610701 * self.t) Y0 += 0.00000133573 * math.cos(5.49226848460 + 182.998997164 * self.t) Y0 += 0.00000103627 * math.cos(0.72176478921 + 35.6685401356 * self.t) Y0 += 0.00000116874 * math.cos(3.84298763857 + 62.4952430786 * self.t) Y0 += 0.00000098063 * math.cos(1.68574394986 + 9.8050450391 * self.t) Y0 += 0.00000111411 * math.cos(5.91424942326 + 141.8970161096 * self.t) Y0 += 0.00000114294 * math.cos(3.99149302956 + 633.0275567967 * self.t) Y0 += 0.00000104705 * math.cos(4.68992506677 + 433.9555553603 * self.t) Y0 += 0.00000121306 * math.cos(3.01971978017 + 40.8581635709 * self.t) Y0 += 0.00000096954 * math.cos(4.60293836623 + 1052.51220067191 * self.t) Y0 += 0.00000085104 * math.cos(3.21938589681 + 36.6799320919 * self.t) Y0 += 0.00000085209 * math.cos(1.23258290286 + 105.76971804189 * self.t) Y0 += 0.00000085291 * math.cos(4.16574840077 + 109.701871305 * self.t) Y0 += 0.00000083260 * math.cos(1.57705309557 + 529.44714761109 * self.t) Y0 += 0.00000080200 * math.cos(1.12120137014 + 40.07377415071 * self.t) Y0 += 0.00000107927 * math.cos(4.72809768120 + 1162.7185218913 * self.t) Y0 += 0.00000095241 * math.cos(5.18181889280 + 253.32717760639 * self.t) Y0 += 0.00000089535 * math.cos(1.68098752171 + 32.9602271499 * self.t) Y0 += 0.00000089793 * math.cos(1.19350927545 + 65.46418849521 * self.t) Y0 += 0.00000072027 * math.cos(4.82605474115 + 36.9405645228 * self.t) Y0 += 0.00000080381 * math.cos(0.49818419813 + 67.1154175423 * self.t) Y0 += 0.00000099502 * math.cos(4.10090280616 + 453.1810763355 * self.t) Y0 += 0.00000088685 * math.cos(6.05087292163 + 251.6759485593 * self.t) Y0 += 0.00000094971 * math.cos(5.68681980258 + 219.6475600935 * self.t) Y0 += 0.00000077015 * math.cos(3.73580633492 + 5.6604434549 * self.t) Y0 += 0.00000069098 * math.cos(3.42063825132 + 22.3900997655 * self.t) Y0 += 0.00000079079 * math.cos(5.69904586697 + 44.48150029329 * self.t) Y0 += 0.00000069159 * math.cos(2.38821700872 + 1066.7392946735 * self.t) Y0 += 0.00000064446 * math.cos(2.45996531968 + 66.9486612035 * self.t) Y0 += 0.00000088518 * math.cos(4.23259429373 + 328.1087761737 * self.t) Y0 += 0.00000065817 * math.cos(6.14060374302 + 36.3711155512 * self.t) Y0 += 0.00000071422 * math.cos(2.66025338551 + 43.79347909271 * self.t) Y0 += 0.00000063298 * math.cos(0.64067085772 + 9.1506537333 * self.t) Y0 += 0.00000077320 * math.cos(1.83922353490 + 97.17169833279 * self.t) Y0 += 0.00000073912 * math.cos(3.29477271110 + 2.6769438233 * self.t) Y0 += 0.00000073965 * math.cos(3.98729910569 + 2.9521304692 * self.t) Y0 += 0.00000056194 * math.cos(2.88777806681 + 949.4194264533 * self.t) Y0 += 0.00000059173 * math.cos(2.98452265287 + 100.14064374939 * self.t) Y0 += 0.00000067507 * math.cos(2.37620743833 + 7.14491616321 * self.t) Y0 += 0.00000071718 * math.cos(2.50472239979 + 2.20386307129 * self.t) Y0 += 0.00000063606 * math.cos(3.60095909928 + 25.8466801491 * self.t) Y0 += 0.00000071523 * math.cos(3.62910110768 + 662.28738607949 * self.t) Y0 += 0.00000057219 * math.cos(5.59723911326 + 15.7429358723 * self.t) Y0 += 0.00000050322 * math.cos(5.79549186801 + 37.15301284391 * self.t) Y0 += 0.00000066615 * math.cos(1.85382631980 + 846.3266522347 * self.t) Y0 += 0.00000056220 * math.cos(6.09466556848 + 178.5455790391 * self.t) Y0 += 0.00000067883 * math.cos(2.31467094623 + 224.5886131854 * self.t) Y0 += 0.00000057761 * math.cos(3.59414048269 + 145.35359649321 * self.t) Y0 += 0.00000053973 * math.cos(4.68325129609 + 107.2205608554 * self.t) Y0 += 0.00000057588 * math.cos(0.13600413206 + 25.3590451821 * self.t) Y0 += 0.00000049026 * math.cos(5.99075269953 + 19.2543980101 * self.t) Y0 += 0.00000063036 * math.cos(5.86840206029 + 256.296123023 * self.t) Y0 += 0.00000045304 * math.cos(5.57731819351 + 4.1759707466 * self.t) Y0 += 0.00000045669 * math.cos(0.60467903265 + 117.6118698135 * self.t) Y0 += 0.00000052821 * math.cos(5.35013106251 + 289.97574053589 * self.t) Y0 += 0.00000044016 * math.cos(0.68418990599 + 32.7477788288 * self.t) Y0 += 0.00000042933 * math.cos(1.50265323283 + 28.98238190449 * self.t) Y0 += 0.00000038369 * math.cos(5.07841615051 + 39.6006933987 * self.t) Y0 += 0.00000038805 * math.cos(2.55324300089 + 103.3365917021 * self.t) Y0 += 0.00000037679 * math.cos(4.97176992254 + 9.3174100721 * self.t) Y0 += 0.00000040292 * math.cos(1.32694372497 + 111.18634401329 * self.t) Y0 += 0.00000050011 * math.cos(4.62887079290 + 221.61966776881 * self.t) Y0 += 0.00000037056 * math.cos(3.05929116522 + 8.32057233081 * self.t) Y0 += 0.00000036562 * math.cos(1.75628268654 + 448.98829064149 * self.t) Y0 += 0.00000044628 * math.cos(5.39841763538 + 525.2543619171 * self.t) Y0 += 0.00000038213 * math.cos(4.99269276748 + 75.54668091261 * self.t) Y0 += 0.00000045963 * math.cos(2.49324091181 + 183.486632131 * self.t) Y0 += 0.00000048222 * math.cos(4.38408318526 + 364.7573391032 * self.t) Y0 += 0.00000038164 * math.cos(3.66287516322 + 44.00592741381 * self.t) Y0 += 0.00000047779 * math.cos(4.62193118070 + 3340.8562441833 * self.t) Y0 += 0.00000042228 * math.cos(4.07611308238 + 77.0311536209 * self.t) Y0 += 0.00000035247 * math.cos(4.92005743728 + 34.7535163989 * self.t) Y0 += 0.00000046804 * math.cos(5.53981795511 + 33.6964324603 * self.t) Y0 += 0.00000034352 * math.cos(5.79527968049 + 33.71098667531 * self.t) Y0 += 0.00000034949 * math.cos(3.58463727178 + 3.37951923889 * self.t) Y0 += 0.00000036030 * math.cos(0.60196271868 + 71.09326278771 * self.t) Y0 += 0.00000038112 * math.cos(0.94232057009 + 45.9659730016 * self.t) Y0 += 0.00000033119 * math.cos(3.70714424363 + 7.3573644843 * self.t) Y0 += 0.00000032049 * math.cos(3.04761071508 + 34.44469985821 * self.t) Y0 += 0.00000031910 * math.cos(0.20811343013 + 81.61769818981 * self.t) Y0 += 0.00000038697 * math.cos(1.09830424446 + 184.97110483931 * self.t) Y0 += 0.00000041486 * math.cos(4.15630010756 + 310.4707937708 * self.t) Y0 += 0.00000038631 * math.cos(0.74636164144 + 50.9070260935 * self.t) Y0 += 0.00000042711 * math.cos(0.62152472293 + 1021.49271203491 * self.t) Y0 += 0.00000032006 * math.cos(5.68829457469 + 42.00018984371 * self.t) Y0 += 0.00000038436 * math.cos(5.02591476913 + 5.92107588581 * self.t) Y0 += 0.00000038880 * math.cos(1.72301566300 + 76.55807286891 * self.t) Y0 += 0.00000041190 * math.cos(3.00922391966 + 563.87503252191 * self.t) Y0 += 0.00000029786 * math.cos(2.57644898724 + 77.5067265004 * self.t) Y0 += 0.00000040604 * math.cos(6.04591617823 + 292.9446859525 * self.t) Y0 += 0.00000035275 * math.cos(3.24596926614 + 304.84171947829 * self.t) Y0 += 0.00000038242 * math.cos(1.23011716621 + 17.76992530181 * self.t) Y0 += 0.00000034445 * math.cos(6.05203741506 + 319.06881347989 * self.t) Y0 += 0.00000028725 * math.cos(0.80354919578 + 67.6366824041 * self.t) Y0 += 0.00000032809 * math.cos(0.86662032393 + 91.54262404029 * self.t) Y0 += 0.00000038880 * math.cos(5.27893548994 + 76.4617046493 * self.t) Y0 += 0.00000030731 * math.cos(3.65388358465 + 67.60305250931 * self.t) Y0 += 0.00000028459 * math.cos(4.82537806886 + 43.0427195673 * self.t) Y0 += 0.00000035368 * math.cos(5.14016182775 + 313.43973918739 * self.t) Y0 += 0.00000035703 * math.cos(4.78026134196 + 258.26823069831 * self.t) Y0 += 0.00000032317 * math.cos(0.72991843715 + 78.9575693139 * self.t) Y0 += 0.00000029243 * math.cos(5.01962947605 + 61.01077037031 * self.t) Y0 += 0.00000026235 * math.cos(2.30979326374 + 137.2768416459 * self.t) Y0 += 0.00000026519 * math.cos(4.63187110201 + 57.4993082325 * self.t) Y0 += 0.00000024931 * math.cos(1.02449436120 + 42.997027585 * self.t) Y0 += 0.00000027608 * math.cos(0.68443037331 + 103.7639804718 * self.t) Y0 += 0.00000028680 * math.cos(6.22569747241 + 215.1941419686 * self.t) Y0 += 0.00000025052 * math.cos(0.98956881727 + 350.08830211689 * self.t) Y0 += 0.00000031386 * math.cos(2.53676810018 + 22.22334342671 * self.t) Y0 += 0.00000027545 * math.cos(6.02026727313 + 100.6282787164 * self.t) Y0 += 0.00000022617 * math.cos(1.89172143755 + 36.8441963032 * self.t) Y0 += 0.00000024909 * math.cos(4.92089915310 + 24.36220744081 * self.t) Y0 += 0.00000026216 * math.cos(3.37729185316 + 491.8017469403 * self.t) Y0 += 0.00000028040 * math.cos(1.26215532584 + 11.55015017831 * self.t) Y0 += 0.00000023047 * math.cos(2.67490790904 + 35.51978228931 * self.t) Y0 += 0.00000027067 * math.cos(5.52626880418 + 326.62430346539 * self.t) Y0 += 0.00000026192 * math.cos(0.78880180701 + 20.7388707184 * self.t) Y0 += 0.00000023134 * math.cos(1.02405904726 + 68.4331339118 * self.t) Y0 += 0.00000021423 * math.cos(5.59061648293 + 39.90950993941 * self.t) Y0 += 0.00000025696 * math.cos(5.03652999676 + 186.4555775476 * self.t) Y0 += 0.00000026985 * math.cos(1.96185307311 + 69.6087900794 * self.t) Y0 += 0.00000023284 * math.cos(1.14508397457 + 79.43065006591 * self.t) Y0 += 0.00000022894 * math.cos(5.33085965806 + 227.77000692311 * self.t) Y0 += 0.00000022482 * math.cos(5.43588494929 + 39.8131417198 * self.t) Y0 += 0.00000023480 * math.cos(5.96723336237 + 30.9881194746 * self.t) Y0 += 0.00000020858 * math.cos(1.66497796416 + 41.2339239533 * self.t) Y0 += 0.00000020327 * math.cos(5.86806874135 + 39.0312444271 * self.t) Y0 += 0.00000020327 * math.cos(4.75570383217 + 37.72246181551 * self.t) Y0 += 0.00000022639 * math.cos(1.78594954268 + 0.9800227939 * self.t) Y0 += 0.00000022639 * math.cos(4.92754219627 + 1.46765776091 * self.t) Y0 += 0.00000019139 * math.cos(1.60585998738 + 205.9417309537 * self.t) Y0 += 0.00000019118 * math.cos(0.05485235310 + 2119.00767786191 * self.t) Y0 += 0.00000025698 * math.cos(4.54722652155 + 401.4059020327 * self.t) Y0 += 0.00000021582 * math.cos(5.86612346662 + 81.13006322279 * self.t) Y0 += 0.00000025509 * math.cos(6.21909191790 + 329.593248882 * self.t) Y0 += 0.00000024296 * math.cos(3.68761645751 + 62.0076081116 * self.t) Y0 += 0.00000023969 * math.cos(2.45967218561 + 135.3047339706 * self.t) Y0 += 0.00000020599 * math.cos(6.09025723810 + 491.3141119733 * self.t) Y0 += 0.00000016829 * math.cos(4.06509805545 + 3.1645787903 * self.t) Y0 += 0.00000020030 * math.cos(2.45066995549 + 217.4750661846 * self.t) Y0 += 0.00000020377 * math.cos(5.60617244490 + 209.6107596584 * self.t) Y0 += 0.00000017251 * math.cos(1.00239992257 + 350.5759370839 * self.t) Y0 += 0.00000019625 * math.cos(1.41143867859 + 129.6756596781 * self.t) Y0 += 0.00000022707 * math.cos(0.97867191772 + 1436.2969352491 * self.t) Y0 += 0.00000017142 * math.cos(4.71740830608 + 29.4700168715 * self.t) Y0 += 0.00000016188 * math.cos(3.33781568208 + 39.00999256771 * self.t) Y0 += 0.00000016188 * math.cos(1.00277158426 + 37.7437136749 * self.t) Y0 += 0.00000020858 * math.cos(3.10425391408 + 58.9837809408 * self.t) Y0 += 0.00000015747 * math.cos(0.31821188942 + 154.260432743 * self.t) Y0 += 0.00000019714 * math.cos(5.04477015525 + 294.91679362781 * self.t) Y0 += 0.00000019078 * math.cos(1.16675280621 + 202.4972126576 * self.t) Y0 += 0.00000021530 * math.cos(4.95075882360 + 114.1552894299 * self.t) Y0 += 0.00000019068 * math.cos(3.39813326972 + 138.2736793872 * self.t) Y0 += 0.00000018723 * math.cos(4.64325038338 + 323.74923414091 * self.t) Y0 += 0.00000018916 * math.cos(3.89922448206 + 40.3825906914 * self.t) Y0 += 0.00000015843 * math.cos(4.98899291519 + 72.577735496 * self.t) Y0 += 0.00000020695 * math.cos(3.75000782446 + 86.07111631471 * self.t) Y0 += 0.00000015895 * math.cos(4.16120885988 + 736.1203310153 * self.t) Y0 += 0.00000014983 * math.cos(0.56469438588 + 743.23387801611 * self.t) Y0 += 0.00000014928 * math.cos(5.49703861671 + 34.23225153711 * self.t) Y0 += 0.00000015461 * math.cos(4.47518787654 + 20.850745303 * self.t) Y0 += 0.00000016206 * math.cos(4.48895168117 + 138.76131435421 * self.t) Y0 += 0.00000015978 * math.cos(5.56972981392 + 515.70768857651 * self.t) Y0 += 0.00000014173 * math.cos(1.42508198977 + 99.1438060081 * self.t) Y0 += 0.00000018749 * math.cos(1.80466304752 + 54.5303628159 * self.t) Y0 += 0.00000013971 * math.cos(3.54176522468 + 76.77052119001 * self.t) Y0 += 0.00000013971 * math.cos(3.46018552739 + 76.2492563282 * self.t) Y0 += 0.00000014035 * math.cos(6.02847994013 + 235.68919520349 * self.t) Y0 += 0.00000018894 * math.cos(3.02786191873 + 31.4757544416 * self.t) Y0 += 0.00000014967 * math.cos(5.68342907224 + 52.3914988018 * self.t) Y0 += 0.00000017392 * math.cos(0.12268817693 + 74.0622082043 * self.t) Y0 += 0.00000014788 * math.cos(3.43864596335 + 56.01483552421 * self.t) Y0 += 0.00000015758 * math.cos(1.26184897401 + 208.8624922605 * self.t) Y0 += 0.00000012911 * math.cos(5.12673395733 + 42.5214547055 * self.t) Y0 += 0.00000014356 * math.cos(0.18539168671 + 251.8427048981 * self.t) Y0 += 0.00000016266 * math.cos(3.39270678896 + 853.4401992355 * self.t) Y0 += 0.00000015513 * math.cos(2.59603540214 + 59.038662695 * self.t) Y0 += 0.00000012783 * math.cos(0.77187700977 + 107.52937739611 * self.t) Y0 += 0.00000016075 * math.cos(0.02096626523 + 366.24181181149 * self.t) Y0 += 0.00000014277 * math.cos(3.31408666848 + 19.36627259471 * self.t) Y0 += 0.00000014742 * math.cos(6.26354356543 + 82.4477795923 * self.t) Y0 += 0.00000015111 * math.cos(5.70708654477 + 363.27286639489 * self.t) Y0 += 0.00000014981 * math.cos(1.17119164980 + 82.6145359311 * self.t) Y0 += 0.00000014840 * math.cos(5.34075197148 + 44.0541115236 * self.t) Y0 += 0.00000015592 * math.cos(5.74434423333 + 8.6293888715 * self.t) Y0 += 0.00000014568 * math.cos(0.45025790013 + 73.80157577341 * self.t) Y0 += 0.00000012251 * math.cos(5.90063123167 + 47.28368937111 * self.t) Y0 += 0.00000011447 * math.cos(5.62613164770 + 175.40987728371 * self.t) Y0 += 0.00000013900 * math.cos(0.93353054847 + 700.4204217173 * self.t) Y0 += 0.00000015583 * math.cos(5.46046493452 + 837.4534458797 * self.t) Y0 += 0.00000012109 * math.cos(0.53062884942 + 33.0084112597 * self.t) Y0 += 0.00000012379 * math.cos(0.87778018320 + 140.4125434013 * self.t) Y0 += 0.00000011481 * math.cos(3.65591005670 + 39.2069345238 * self.t) Y0 += 0.00000011481 * math.cos(0.68467720964 + 37.54677171881 * self.t) Y0 += 0.00000011452 * math.cos(5.92350892067 + 529.4135177163 * self.t) Y0 += 0.00000010981 * math.cos(1.58931744102 + 63.49208081989 * self.t) Y0 += 0.00000012137 * math.cos(0.75938098769 + 42.3090063844 * self.t) Y0 += 0.00000013771 * math.cos(2.92318261793 + 76.62176334371 * self.t) Y0 += 0.00000011036 * math.cos(1.59378256377 + 530.45604743991 * self.t) Y0 += 0.00000011537 * math.cos(2.72370023352 + 199.3158189199 * self.t) Y0 += 0.00000011189 * math.cos(1.67388131435 + 80.1332254815 * self.t) Y0 += 0.00000012835 * math.cos(2.83910944143 + 38.85242600079 * self.t) Y0 += 0.00000012879 * math.cos(0.03161787960 + 5.69407334969 * self.t) Y0 += 0.00000013663 * math.cos(4.69897705757 + 438.0544649622 * self.t) Y0 += 0.00000010132 * math.cos(2.80479631986 + 187.9400502559 * self.t) Y0 += 0.00000012619 * math.cos(3.09097380707 + 65.2035560643 * self.t) Y0 += 0.00000010088 * math.cos(1.41143864412 + 26.58288545949 * self.t) Y0 += 0.00000011959 * math.cos(1.19714206196 + 64.7159210973 * self.t) Y0 += 0.00000011578 * math.cos(5.81790016857 + 275.3067035496 * self.t) Y0 += 0.00000012795 * math.cos(1.66756565053 + 17.8817998864 * self.t) Y0 += 0.00000013771 * math.cos(4.07876849292 + 76.3980141745 * self.t) Y0 += 0.00000010044 * math.cos(1.67224715151 + 147.83490694279 * self.t) Y0 += 0.00000013632 * math.cos(1.29603813384 + 45.277951801 * self.t) Y0 += 0.00000011660 * math.cos(4.22880871720 + 143.9027536797 * self.t) Y0 += 0.00000009938 * math.cos(5.79050109000 + 6.86972951729 * self.t) Y0 += 0.00000009719 * math.cos(4.48706829937 + 956.53297345411 * self.t) Y0 += 0.00000011441 * math.cos(5.32553485636 + 533.8669358412 * self.t) Y0 += 0.00000010240 * math.cos(1.34767099242 + 80.7026744531 * self.t) Y0 += 0.00000010031 * math.cos(3.80995841826 + 43.74529498291 * self.t) Y0 += 0.00000010063 * math.cos(1.05825122331 + 0.27744737829 * self.t) Y0 += 0.00000011428 * math.cos(2.19933512981 + 526.00262931501 * self.t) Y0 += 0.00000009279 * math.cos(1.45482205447 + 79.6455905145 * self.t) Y0 += 0.00000010172 * math.cos(0.89461094062 + 568.0678182159 * self.t) Y0 += 0.00000009198 * math.cos(0.36520539350 + 112.6708167216 * self.t) Y0 += 0.00000009831 * math.cos(4.06082180622 + 20.9056270572 * self.t) Y0 += 0.00000009830 * math.cos(1.93960888370 + 544.1618765797 * self.t) Y0 += 0.00000008646 * math.cos(6.06265529598 + 30.7756711535 * self.t) Y0 += 0.00000009315 * math.cos(1.72769398395 + 65.63094483399 * self.t) Y0 += 0.00000009201 * math.cos(1.66299093770 + 184.48346987229 * self.t) Y0 += 0.00000008674 * math.cos(3.58250353029 + 624.1543504417 * self.t) Y0 += 0.00000010739 * math.cos(5.20958133978 + 331.56535655731 * self.t) Y0 += 0.00000009612 * math.cos(3.81549627985 + 182.00215942271 * self.t) Y0 += 0.00000008664 * math.cos(4.05357381243 + 1479.11039154791 * self.t) Y0 += 0.00000008092 * math.cos(4.08843223898 + 6.8360996225 * self.t) Y0 += 0.00000010092 * math.cos(0.00357719036 + 419.2408263917 * self.t) Y0 += 0.00000010233 * math.cos(0.16992310980 + 402.89037474099 * self.t) Y0 += 0.00000008502 * math.cos(3.60646753260 + 17.39416491939 * self.t) Y0 += 0.00000010189 * math.cos(1.01906004060 + 21.7020785649 * self.t) Y0 += 0.00000009829 * math.cos(3.66564448678 + 121.2352065359 * self.t) Y0 += 0.00000008406 * math.cos(4.04270651029 + 376.9150050599 * self.t) Y0 += 0.00000008060 * math.cos(4.05224638436 + 415.7963080956 * self.t) Y0 += 0.00000009455 * math.cos(1.63876624122 + 167.80869531589 * self.t) Y0 += 0.00000007941 * math.cos(6.14526289331 + 526.7533888404 * self.t) Y0 += 0.00000007870 * math.cos(1.33260101318 + 533.1161763158 * self.t) Y0 += 0.00000007695 * math.cos(2.49810660877 + 906.60597015449 * self.t) Y0 += 0.00000007862 * math.cos(5.62722995177 + 1265.81129610991 * self.t) Y0 += 0.00000008062 * math.cos(5.84124471296 + 105.7360881471 * self.t) Y0 += 0.00000008904 * math.cos(5.87904582316 + 399.9214293244 * self.t) Y0 += 0.00000008050 * math.cos(4.85961454632 + 143.8691237849 * self.t) Y0 += 0.00000009102 * math.cos(3.20438608836 + 348.17644063891 * self.t) Y0 += 0.00000007137 * math.cos(5.97349520503 + 117.5636857037 * self.t) Y0 += 0.00000007076 * math.cos(4.77037120491 + 26.84351789039 * self.t) Y0 += 0.00000008418 * math.cos(6.19754313245 + 77.73372903651 * self.t) Y0 += 0.00000008257 * math.cos(6.01515603184 + 117.77862615229 * self.t) Y0 += 0.00000007868 * math.cos(0.36467826737 + 288.4912678276 * self.t) Y0 += 0.00000008093 * math.cos(5.12697881207 + 1692.40948698591 * self.t) Y0 += 0.00000006910 * math.cos(5.16028730720 + 216.72430665921 * self.t) Y0 += 0.00000007092 * math.cos(1.58416634960 + 452.65981147369 * self.t) Y0 += 0.00000007060 * math.cos(3.50187723218 + 453.7023411973 * self.t) Y0 += 0.00000008233 * math.cos(5.07959772857 + 480.00777927849 * self.t) Y0 += 0.00000006772 * math.cos(2.89170457209 + 210.36151918381 * self.t) Y0 += 0.00000007025 * math.cos(6.13907268455 + 55.9029609396 * self.t) Y0 += 0.00000008356 * math.cos(3.67079730328 + 95.7354097343 * self.t) Y0 += 0.00000007404 * math.cos(5.71532443096 + 75.2860484817 * self.t) Y0 += 0.00000006839 * math.cos(2.57023077532 + 41.5125548767 * self.t) Y0 += 0.00000007909 * math.cos(0.07288588503 + 36.63174798211 * self.t) Y0 += 0.00000007909 * math.cos(1.12610872772 + 40.12195826051 * self.t) Y0 += 0.00000006362 * math.cos(4.97586429633 + 29.99128173331 * self.t) Y0 += 0.00000006712 * math.cos(2.41218446093 + 133.82026126229 * self.t) Y0 += 0.00000007571 * math.cos(1.24658605384 + 23.707816135 * self.t) Y0 += 0.00000006677 * math.cos(4.81403056382 + 1.20702533 * self.t) Y0 += 0.00000007600 * math.cos(1.64374414108 + 494.2348732801 * self.t) Y0 += 0.00000008009 * math.cos(1.96165940869 + 170.72945662269 * self.t) Y0 += 0.00000007584 * math.cos(1.33750538789 + 119.2630988606 * self.t) Y0 += 0.00000006599 * math.cos(0.68440943828 + 32.226513967 * self.t) Y0 += 0.00000006085 * math.cos(3.39985070945 + 322.00412900171 * self.t) Y0 += 0.00000005953 * math.cos(0.92774911672 + 52214.1831362697 * self.t) Y0 += 0.00000007827 * math.cos(4.85672910517 + 474.7030278917 * self.t) Y0 += 0.00000007907 * math.cos(6.03373097658 + 485.63685357099 * self.t) Y0 += 0.00000007372 * math.cos(3.31633214824 + 55.05162767771 * self.t) Y0 += 0.00000006966 * math.cos(4.03472609774 + 647.25465079831 * self.t) Y0 += 0.00000006266 * math.cos(1.06894881555 + 177.0611063308 * self.t) Y0 += 0.00000005900 * math.cos(0.21363873876 + 52061.16335875149 * self.t) Y0 += 0.00000006221 * math.cos(0.78444326027 + 602.00806815971 * self.t) Y0 += 0.00000005552 * math.cos(4.30656362928 + 223.1041404771 * self.t) Y0 += 0.00000005976 * math.cos(3.40178743225 + 10.8018827804 * self.t) Y0 += 0.00000007600 * math.cos(0.62565658069 + 488.6057989876 * self.t) Y0 += 0.00000006831 * math.cos(4.75854396498 + 1582.2031657665 * self.t) Y0 += 0.00000005654 * math.cos(1.46952482126 + 12604.5285531041 * self.t) Y0 += 0.00000005798 * math.cos(2.70754675899 + 27.4979091962 * self.t) Y0 += 0.00000007216 * math.cos(4.89431192173 + 739.0410923221 * self.t) Y0 += 0.00000006579 * math.cos(2.37730114095 + 2.69149803831 * self.t) Y0 += 0.00000005758 * math.cos(1.25264555408 + 30.0394658431 * self.t) Y0 += 0.00000005270 * math.cos(5.03822712313 + 6166.94845288619 * self.t) Y0 += 0.00000007398 * math.cos(2.15412967054 + 709.721016842 * self.t) Y0 += 0.00000005679 * math.cos(4.34696450423 + 17.22740858061 * self.t) Y0 += 0.00000005205 * math.cos(4.18097270804 + 426.3543733925 * self.t) Y0 += 0.00000005146 * math.cos(5.52411562781 + 46.7624245093 * self.t) Y0 += 0.00000005694 * math.cos(4.51992731423 + 168.98435148349 * self.t) Y0 += 0.00000006627 * math.cos(1.36429825841 + 221.13203280179 * self.t) Y0 += 0.00000005443 * math.cos(2.77787969707 + 525.7419968841 * self.t) Y0 += 0.00000006475 * math.cos(0.95284661304 + 591.07424248041 * self.t) Y0 += 0.00000004984 * math.cos(0.17849511014 + 10097.15814910579 * self.t) Y0 += 0.00000005318 * math.cos(3.65617684169 + 44.52719227561 * self.t) Y0 += 0.00000006699 * math.cos(1.37968332714 + 2157.1407134997 * self.t) Y0 += 0.00000006443 * math.cos(4.07988524250 + 675.0445615878 * self.t) Y0 += 0.00000005078 * math.cos(2.53592755854 + 101.62511645769 * self.t) Y0 += 0.00000005394 * math.cos(5.60187660250 + 368.21391948681 * self.t) Y0 += 0.00000005072 * math.cos(4.09677163290 + 272.33775813299 * self.t) Y0 += 0.00000005208 * math.cos(2.96070554414 + 277.2788112249 * self.t) Y0 += 0.00000005332 * math.cos(2.85701594895 + 280.9357778421 * self.t) Y0 += 0.00000005989 * math.cos(1.18032513011 + 93.0270967486 * self.t) Y0 += 0.00000006329 * math.cos(2.06650240521 + 18.87863762769 * self.t) Y0 += 0.00000005551 * math.cos(0.99966130596 + 57.3874336479 * self.t) Y0 += 0.00000006471 * math.cos(4.75702433578 + 68.1243173711 * self.t) Y0 += 0.00000004708 * math.cos(3.81000728156 + 95.68722562449 * self.t) Y0 += 0.00000005891 * math.cos(4.39361748912 + 381.5954257209 * self.t) Y0 += 0.00000004717 * math.cos(5.88762112195 + 104.2852453336 * self.t) Y0 += 0.00000005675 * math.cos(0.14149668499 + 1165.6392831981 * self.t) Y0 += 0.00000005888 * math.cos(2.00299136957 + 42.34263627919 * self.t) Y0 += 0.00000005587 * math.cos(2.52090459839 + 459.6066021357 * self.t) Y0 += 0.00000005456 * math.cos(3.07944464122 + 75.50098893029 * self.t) Y0 += 0.00000005940 * math.cos(4.70996040917 + 6318.4837576961 * self.t) Y0 += 0.00000005207 * math.cos(6.12213701959 + 436.5699922539 * self.t) Y0 += 0.00000006160 * math.cos(3.18966815531 + 749.82616015511 * self.t) Y0 += 0.00000006137 * math.cos(3.02268593798 + 713.17759722561 * self.t) Y0 += 0.00000004547 * math.cos(3.96298179960 + 32.47259218289 * self.t) Y0 += 0.00000005246 * math.cos(0.26649341993 + 109.9625037359 * self.t) Y0 += 0.00000005244 * math.cos(0.76595138199 + 73.5891274523 * self.t) Y0 += 0.00000005572 * math.cos(4.54958395511 + 102.11275142471 * self.t) Y0 += 0.00000005638 * math.cos(6.13292790226 + 10248.6934539157 * self.t) Y0 += 0.00000004513 * math.cos(0.05769066183 + 1272.9248431107 * self.t) Y0 += 0.00000004340 * math.cos(3.93529499489 + 384.02855206069 * self.t) Y0 += 0.00000004263 * math.cos(5.81710901839 + 1577.52274510549 * self.t) Y0 += 0.00000005964 * math.cos(3.35563503899 + 786.47472308461 * self.t) Y0 += 0.00000004962 * math.cos(1.38600480216 + 257.78059573129 * self.t) Y0 += 0.00000005327 * math.cos(4.13135597763 + 107.74182571721 * self.t) Y0 += 0.00000005572 * math.cos(5.58677005833 + 291.2934569054 * self.t) Y0 += 0.00000004336 * math.cos(1.08874295813 + 53.40958840249 * self.t) Y0 += 0.00000004427 * math.cos(1.43077618159 + 189.42452296421 * self.t) Y0 += 0.00000004157 * math.cos(5.03727532307 + 29.5036467663 * self.t) Y0 += 0.00000004646 * math.cos(4.44853801893 + 13285.93981804009 * self.t) Y0 += 0.00000005507 * math.cos(2.70385106164 + 178.11819026941 * self.t) Y0 += 0.00000005348 * math.cos(6.13707191030 + 24.88347230261 * self.t) Y0 += 0.00000005339 * math.cos(5.48920294964 + 314.6635794648 * self.t) Y0 += 0.00000004678 * math.cos(6.00688425085 + 1474.4299708869 * self.t) Y0 += 0.00000004090 * math.cos(4.92713296866 + 765.3801602981 * self.t) Y0 += 0.00000005008 * math.cos(4.28621887979 + 352.06040979221 * self.t) Y0 += 0.00000005562 * math.cos(5.12126233744 + 6248.1555772537 * self.t) Y0 += 0.00000004983 * math.cos(1.59156517574 + 1055.43296197871 * self.t) Y0 += 0.00000004566 * math.cos(0.54461731254 + 325.1398307571 * self.t) Y0 += 0.00000005327 * math.cos(0.54108371123 + 439.53893767049 * self.t) Y0 += 0.00000005121 * math.cos(4.27746071897 + 711.6931245173 * self.t) Y0 += 0.00000004181 * math.cos(2.68829223641 + 6606.1994373488 * self.t) Y0 += 0.00000004293 * math.cos(3.08794166207 + 46.71424039951 * self.t) Y0 += 0.00000005532 * math.cos(2.10559407460 + 320.03202132639 * self.t) Y0 += 0.00000004492 * math.cos(4.81151725335 + 52177.53457334019 * self.t) Y0 += 0.00000004312 * math.cos(6.10122311855 + 22.8777347325 * self.t) Y0 += 0.00000005332 * math.cos(0.25990559894 + 10178.3652734733 * self.t) Y0 += 0.00000004593 * math.cos(4.86059649000 + 1025.6854977289 * self.t) Y0 += 0.00000005439 * math.cos(3.52367947540 + 823.12328601411 * self.t) Y0 += 0.00000003870 * math.cos(2.70915745235 + 1596.43025976811 * self.t) Y0 += 0.00000003892 * math.cos(0.54485159298 + 226.07308589371 * self.t) Y0 += 0.00000004891 * math.cos(4.37893659385 + 8.1417539045 * self.t) Y0 += 0.00000004689 * math.cos(5.09142557332 + 276.79117625789 * self.t) Y0 += 0.00000004268 * math.cos(1.02189794794 + 374.15181032 * self.t) Y0 += 0.00000003828 * math.cos(3.85156237339 + 2138.2331988371 * self.t) Y0 += 0.00000004592 * math.cos(2.30447944615 + 1376.0176173293 * self.t) Y0 += 0.00000004629 * math.cos(5.68948058955 + 122.71967924421 * self.t) Y0 += 0.00000003871 * math.cos(1.60468692916 + 531.4192552864 * self.t) Y0 += 0.00000004995 * math.cos(5.03302660981 + 32.69959471901 * self.t) Y0 += 0.00000004711 * math.cos(5.14987215661 + 52252.31617190749 * self.t) Y0 += 0.00000003893 * math.cos(1.69554966790 + 116.294153444 * self.t) Y0 += 0.00000004481 * math.cos(3.09400209140 + 53.0458901076 * self.t) Y0 += 0.00000004136 * math.cos(1.02307294098 + 503.1080796351 * self.t) Y0 += 0.00000004508 * math.cos(2.81495366139 + 562.12992738271 * self.t) Y0 += 0.00000005025 * math.cos(1.96944866339 + 283.38345839689 * self.t) Y0 += 0.00000004789 * math.cos(1.11612617111 + 627.7228054099 * self.t) Y0 += 0.00000004021 * math.cos(1.71534059601 + 6603.23049193219 * self.t) Y0 += 0.00000005163 * math.cos(0.06221778581 + 25519.83532335829 * self.t) Y0 += 0.00000004150 * math.cos(2.29239909221 + 27.443027442 * self.t) Y0 += 0.00000003623 * math.cos(0.72377687032 + 1665.5827840429 * self.t) Y0 += 0.00000004634 * math.cos(3.36220803589 + 3227.45397501119 * self.t) Y0 += 0.00000004060 * math.cos(4.64578985602 + 304.4780211834 * self.t) Y0 += 0.00000003862 * math.cos(5.22051626712 + 74.504151189 * self.t) Y0 += 0.00000003561 * math.cos(3.35891592080 + 358.6526919312 * self.t) Y0 += 0.00000004557 * math.cos(1.56282166634 + 25974.74468988559 * self.t) Y0 += 0.00000004264 * math.cos(3.13963744879 + 634.93941827469 * self.t) Y0 += 0.00000004482 * math.cos(0.13471172639 + 342.61105682121 * self.t) Y0 += 0.00000003539 * math.cos(5.28146842802 + 119.7507338276 * self.t) Y0 += 0.00000004304 * math.cos(5.35023544496 + 12567.8799901746 * self.t) Y0 += 0.00000004138 * math.cos(5.60646772527 + 107.2541907502 * self.t) Y0 += 0.00000004284 * math.cos(1.62500514182 + 294.42915866079 * self.t) Y0 += 0.00000003723 * math.cos(0.87405503812 + 987.325459555 * self.t) Y0 += 0.00000003723 * math.cos(4.01564769171 + 987.813094522 * self.t) Y0 += 0.00000004606 * math.cos(0.78314632413 + 14.42521950279 * self.t) Y0 += 0.00000004236 * math.cos(1.51001695106 + 155.9116617901 * self.t) Y0 += 0.00000004458 * math.cos(1.07510939804 + 395.8225197225 * self.t) Y0 += 0.00000004798 * math.cos(3.66850235979 + 530.195415009 * self.t) Y0 += 0.00000003640 * math.cos(3.79814548576 + 2564.8313897131 * self.t) Y0 += 0.00000003563 * math.cos(0.66220700888 + 12451.50877558589 * self.t) Y0 += 0.00000003443 * math.cos(3.70889407011 + 245.2504227591 * self.t) Y0 += 0.00000003429 * math.cos(3.16343780315 + 530.0466571627 * self.t) Y0 += 0.00000003872 * math.cos(5.66297097129 + 308.98632106249 * self.t) Y0 += 0.00000003406 * math.cos(4.31900232100 + 529.82290799351 * self.t) Y0 += 0.00000004348 * math.cos(3.09499292675 + 20311.92816802509 * self.t) Y0 += 0.00000004589 * math.cos(3.67073392808 + 181.08713568601 * self.t) Y0 += 0.00000003854 * math.cos(4.35430550499 + 12564.91104475801 * self.t) Y0 += 0.00000003789 * math.cos(5.86431526205 + 3101.6359018085 * self.t) Y0 += 0.00000003783 * math.cos(1.84016316657 + 1614.17130803499 * self.t) Y0 += 0.00000003904 * math.cos(1.57500723101 + 369.8014580591 * self.t) Y0 += 0.00000003765 * math.cos(3.13810202386 + 1025.94613015981 * self.t) Y0 += 0.00000004231 * math.cos(3.78834664840 + 31.52393855141 * self.t) Y0 += 0.00000004303 * math.cos(3.40265517593 + 396.785727569 * self.t) Y0 += 0.00000004085 * math.cos(0.23841437878 + 14.47091148511 * self.t) Y0 += 0.00000004085 * math.cos(3.38000703237 + 13.9832765181 * self.t) Y0 += 0.00000003346 * math.cos(0.20283168925 + 20351.54567637119 * self.t) Y0 += 0.00000004021 * math.cos(4.51457854549 + 748.3416874468 * self.t) Y0 += 0.00000003753 * math.cos(2.74283876055 + 524.99372948619 * self.t) Y0 += 0.00000003935 * math.cos(2.81201754924 + 1617.14025345159 * self.t) Y0 += 0.00000004432 * math.cos(5.02857999493 + 511.3515908212 * self.t) Y0 += 0.00000004170 * math.cos(2.85784811733 + 274.87931477991 * self.t) Y0 += 0.00000003317 * math.cos(3.36427187559 + 266.70868384049 * self.t) Y0 += 0.00000004545 * math.cos(2.99451528962 + 244.5624015585 * self.t) Y0 += 0.00000003589 * math.cos(6.26623778468 + 59.526297662 * self.t) Y0 += 0.00000003464 * math.cos(1.94815791367 + 102.27950776349 * self.t) Y0 += 0.00000004526 * math.cos(2.98322850842 + 525.7901809939 * self.t) Y0 += 0.00000004603 * math.cos(2.83181132811 + 26088.1469590577 * self.t) Y0 += 0.00000004021 * math.cos(3.81502221170 + 52174.56562792359 * self.t) Y0 += 0.00000003276 * math.cos(3.52742657818 + 1306.3774580875 * self.t) Y0 += 0.00000003214 * math.cos(5.51315121035 + 20348.57673095459 * self.t) Y0 += 0.00000003706 * math.cos(3.68281338464 + 27.07052042651 * self.t) Y0 += 0.00000003759 * math.cos(5.89324799399 + 164.83974989929 * self.t) Y0 += 0.00000003184 * math.cos(0.44574677170 + 538.0115374254 * self.t) Y0 += 0.00000004430 * math.cos(3.80837870078 + 529.6741501472 * self.t) Y0 += 0.00000004064 * math.cos(2.60402368915 + 6130.2998899567 * self.t) Y0 += 0.00000003918 * math.cos(5.77655218093 + 375.43053235159 * self.t) Y0 += 0.00000004058 * math.cos(3.56233663362 + 433.4342904985 * self.t) Y0 += 0.00000003919 * math.cos(1.93774102166 + 1092.8177302186 * self.t) Y0 += 0.00000003919 * math.cos(5.07933367525 + 1093.3053651856 * self.t) Y0 += 0.00000003175 * math.cos(2.71648311000 + 241.3664536058 * self.t) Y0 += 0.00000003135 * math.cos(1.09798751738 + 127.22797912329 * self.t) Y0 += 0.00000003834 * math.cos(3.42021462454 + 14.3133449182 * self.t) Y0 += 0.00000004022 * math.cos(0.15000192924 + 1477.8383671607 * self.t) Y0 += 0.00000003221 * math.cos(2.66340709341 + 78.1611178062 * self.t) Y0 += 0.00000003426 * math.cos(4.77405099085 + 519.8522901607 * self.t) Y0 += 0.00000004369 * math.cos(2.32053270413 + 746.3695797715 * self.t) Y0 += 0.00000003160 * math.cos(3.58900877772 + 664.99569906519 * self.t) Y0 += 0.00000004060 * math.cos(4.49008083850 + 51.87023394 * self.t) Y0 += 0.00000003107 * math.cos(3.81160836398 + 28.9275001503 * self.t) Y0 += 0.00000003259 * math.cos(0.91022076156 + 657.8821520644 * self.t) Y0 += 0.00000003428 * math.cos(2.81213415208 + 2351.5322942751 * self.t) Y0 += 0.00000003235 * math.cos(0.07612839981 + 406.3469551246 * self.t) Y0 += 0.00000003161 * math.cos(0.98519827646 + 982.8720414301 * self.t) Y0 += 0.00000004351 * math.cos(2.61742468676 + 20388.19423930069 * self.t) Y0 += 0.00000003384 * math.cos(1.87729416709 + 660.851097481 * self.t) Y0 += 0.00000003452 * math.cos(5.96738985165 + 326.1823604807 * self.t) Y0 += 0.00000003298 * math.cos(1.72568702486 + 1403.84115801359 * self.t) Y0 += 0.00000003278 * math.cos(5.26025413610 + 941.7700603757 * self.t) Y0 += 0.00000003723 * math.cos(0.29723150363 + 451.9572360581 * self.t) Y0 += 0.00000003173 * math.cos(0.75401885480 + 1400.87221259699 * self.t) Y0 += 0.00000004113 * math.cos(3.44518846630 + 1049.31625271919 * self.t) Y0 += 0.00000004012 * math.cos(0.58002417229 + 52.6039471229 * self.t) Y0 += 0.00000004142 * math.cos(0.18543891861 + 978.6792557361 * self.t) Y0 += 0.00000004295 * math.cos(2.94382365877 + 875.58648151749 * self.t) Y0 += 0.00000003224 * math.cos(5.39074920150 + 459.1189671687 * self.t) Y0 += 0.00000003151 * math.cos(2.11925788926 + 381.8560581518 * self.t) Y0 += 0.00000003633 * math.cos(6.09798622690 + 256.78375799 * self.t) Y0 += 0.00000004250 * math.cos(4.81834414256 + 528.71094230071 * self.t) Y0 += 0.00000004186 * math.cos(3.66267284521 + 943.25453308399 * self.t) Y0 += 0.00000003406 * math.cos(1.82206499429 + 170.46882419179 * self.t) Y0 += 0.00000003231 * math.cos(6.18447276533 + 400.8209466961 * self.t) Y0 += 0.00000003726 * math.cos(5.26557613435 + 1096.48675892331 * self.t) Y0 += 0.00000003792 * math.cos(5.46702979448 + 111.9346114112 * self.t) Y0 += 0.00000003651 * math.cos(6.14012974300 + 154.42718908179 * self.t) Y0 += 0.00000003839 * math.cos(4.02729058795 + 10060.50958617629 * self.t) Y0 += 0.00000003356 * math.cos(5.33785023580 + 1586.34776735071 * self.t) Y0 += 0.00000003219 * math.cos(1.26547692662 + 213.7096692603 * self.t) Y0 += 0.00000003671 * math.cos(3.08823320781 + 57.6023740965 * self.t) Y0 += 0.00000004187 * math.cos(1.86321883254 + 2772.54460848389 * self.t) Y0 += 0.00000002960 * math.cos(3.77221652347 + 2461.7386154945 * self.t) Y0 += 0.00000003331 * math.cos(2.38361288630 + 10133.80671203529 * self.t) Y0 += 0.00000003341 * math.cos(2.74911210318 + 243.7659500508 * self.t) Y0 += 0.00000003466 * math.cos(0.02652921265 + 1150.92455422949 * self.t) Y0 += 0.00000003296 * math.cos(5.06897390591 + 1653.78881638109 * self.t) Y0 += 0.00000003014 * math.cos(3.47171849350 + 1477.3989163035 * self.t) Y0 += 0.00000004118 * math.cos(1.26070911091 + 25596.5890296009 * self.t) Y0 += 0.00000002951 * math.cos(3.47218747597 + 42.78208713641 * self.t) Y0 += 0.00000002951 * math.cos(4.00999244396 + 33.9716191062 * self.t) Y0 += 0.00000003830 * math.cos(3.02640541849 + 323.48860171 * self.t) Y0 += 0.00000003313 * math.cos(3.21919687279 + 939.1099314998 * self.t) Y0 += 0.00000003031 * math.cos(4.32205791511 + 156450.90896068608 * self.t) Y0 += 0.00000003606 * math.cos(2.35740018537 + 1082.2596649217 * self.t) Y0 += 0.00000002967 * math.cos(4.72619454182 + 6.3941566378 * self.t) Y0 += 0.00000002995 * math.cos(5.12808890644 + 139.7099679857 * self.t) Y0 += 0.00000003251 * math.cos(1.93107151339 + 709.29362807231 * self.t) Y0 += 0.00000003480 * math.cos(2.18796105799 + 518.1408149163 * self.t) Y0 += 0.00000003906 * math.cos(4.41951013162 + 1119.90506559249 * self.t) Y0 += 0.00000003406 * math.cos(3.42602191152 + 148.79811478929 * self.t) Y0 += 0.00000003359 * math.cos(0.17159576955 + 642.8494167832 * self.t) Y0 += 0.00000003027 * math.cos(5.00980281133 + 184.0078969928 * self.t) Y0 += 0.00000002918 * math.cos(0.68786396977 + 83.6234357599 * self.t) Y0 += 0.00000003347 * math.cos(4.53587187847 + 217.68751450571 * self.t) Y0 += 0.00000003277 * math.cos(1.84412902317 + 912.5438609877 * self.t) Y0 += 0.00000003277 * math.cos(4.98572167676 + 913.03149595471 * self.t) Y0 += 0.00000003196 * math.cos(4.27207353253 + 363.1061100561 * self.t) Y0 += 0.00000002869 * math.cos(2.93254803921 + 285.35556607221 * self.t) Y0 += 0.00000003158 * math.cos(5.89391855080 + 540.01727499551 * self.t) Y0 += 0.00000002810 * math.cos(3.57723287116 + 1592.2856581839 * self.t) Y0 += 0.00000003471 * math.cos(4.56081319778 + 144.39038864671 * self.t) Y0 += 0.00000003159 * math.cos(5.71530971815 + 197.5561595657 * self.t) Y0 += 0.00000003227 * math.cos(1.02602355265 + 6203.5970158157 * self.t) Y0 += 0.00000003750 * math.cos(1.09900342443 + 303.35724676999 * self.t) Y0 += 0.00000003848 * math.cos(4.95190461444 + 26048.04181574459 * self.t) Y0 += 0.00000002741 * math.cos(0.13004673727 + 70.8326303568 * self.t) Y0 += 0.00000002826 * math.cos(3.64821843137 + 460.2946233363 * self.t) Y0 += 0.00000002748 * math.cos(5.69617268740 + 600.52359545141 * self.t) Y0 += 0.00000003057 * math.cos(4.56550138397 + 23.81969071961 * self.t) Y0 += 0.00000003057 * math.cos(6.05827118955 + 52.934015523 * self.t) Y0 += 0.00000003446 * math.cos(1.96967013470 + 500.1391342185 * self.t) Y0 += 0.00000002703 * math.cos(6.26272265860 + 908.0904428628 * self.t) Y0 += 0.00000002817 * math.cos(1.69638906604 + 210.6221516147 * self.t) Y0 += 0.00000002848 * math.cos(1.16888883373 + 450.4727633498 * self.t) Y0 += 0.00000002724 * math.cos(5.64910484087 + 23.18655127321 * self.t) Y0 += 0.00000002905 * math.cos(1.13800629851 + 149.3193796511 * self.t) Y0 += 0.00000002848 * math.cos(1.48842245891 + 622.66987773339 * self.t) Y0 += 0.00000002733 * math.cos(1.93636126616 + 262.72164882321 * self.t) Y0 += 0.00000002863 * math.cos(2.26914213515 + 175.57663362249 * self.t) Y0 += 0.00000002681 * math.cos(5.83048409789 + 25.1922888433 * self.t) Y0 += 0.00000002822 * math.cos(0.00883588585 + 259.7527034066 * self.t) Y0 += 0.00000003174 * math.cos(1.47302873031 + 347.1193567003 * self.t) Y0 += 0.00000003271 * math.cos(2.97328046332 + 458.5977023069 * self.t) Y0 += 0.00000002894 * math.cos(5.75207939107 + 71.82946809809 * self.t) Y0 += 0.00000003490 * math.cos(1.28003658954 + 664.3713683394 * self.t) Y0 += 0.00000003506 * math.cos(3.91611653269 + 771.3481117113 * self.t) Y0 += 0.00000003326 * math.cos(0.55224065588 + 45.2297676912 * self.t) Y0 += 0.00000002988 * math.cos(4.94563705230 + 299.37021175271 * self.t) Y0 += 0.00000002916 * math.cos(5.17859920603 + 6642.8480002783 * self.t) Y0 += 0.00000002916 * math.cos(5.17859920603 + 6643.3356352453 * self.t) Y0 += 0.00000002630 * math.cos(5.83933407803 + 2751.79141717511 * self.t) Y0 += 0.00000002903 * math.cos(5.88134941337 + 477.08701797169 * self.t) Y0 += 0.00000002804 * math.cos(4.97695491059 + 6681.46867088311 * self.t) Y0 += 0.00000002622 * math.cos(0.73099530901 + 521.8580277308 * self.t) Y0 += 0.00000002606 * math.cos(1.44468831628 + 410.8552550037 * self.t) Y0 += 0.00000003046 * math.cos(0.79307135358 + 959.45373476091 * self.t) Y0 += 0.00000003127 * math.cos(1.47432830628 + 225.5518210319 * self.t) Y0 += 0.00000002700 * math.cos(2.88388264285 + 963.6465204549 * self.t) Y0 += 0.00000002778 * math.cos(3.22939757518 + 238.39750818919 * self.t) Y0 += 0.00000003029 * math.cos(0.01392036536 + 473.2185551834 * self.t) Y0 += 0.00000002671 * math.cos(3.02950363348 + 531.9405201482 * self.t) Y0 += 0.00000002914 * math.cos(2.29089443923 + 554.31380496631 * self.t) Y0 += 0.00000003087 * math.cos(1.37613019083 + 340.2664421304 * self.t) Y0 += 0.00000003438 * math.cos(3.89546045811 + 6171.40187101109 * self.t) Y0 += 0.00000002879 * math.cos(4.04729837696 + 218.6507223522 * self.t) Y0 += 0.00000003140 * math.cos(3.44921752602 + 609.1216151605 * self.t) Y0 += 0.00000003003 * math.cos(5.24831469226 + 464.97504399731 * self.t) Y0 += 0.00000003257 * math.cos(6.23715182295 + 305.96249389171 * self.t) Y0 += 0.00000003211 * math.cos(0.93594149210 + 416.532513406 * self.t) Y0 += 0.00000003265 * math.cos(6.26189223545 + 24.7347144563 * self.t) Y0 += 0.00000002644 * math.cos(5.73202797797 + 508.5941415757 * self.t) Y0 += 0.00000002764 * math.cos(0.26986971158 + 410.59462257279 * self.t) Y0 += 0.00000003428 * math.cos(0.99849665750 + 1012.6195056799 * self.t) Y0 += 0.00000002614 * math.cos(2.50560328703 + 213.5910970313 * self.t) Y0 += 0.00000003469 * math.cos(3.71563719744 + 24.14975911971 * self.t) Y0 += 0.00000002606 * math.cos(5.52398994555 + 213.4947288117 * self.t) Y0 += 0.00000003444 * math.cos(0.99352524535 + 891.57323487331 * self.t) Y0 += 0.00000002540 * math.cos(5.89247404448 + 564.8718702632 * self.t) Y0 += 0.00000002540 * math.cos(2.75088139089 + 565.35950523021 * self.t) Y0 += 0.00000002754 * math.cos(4.26615188091 + 57.5541899867 * self.t) Y0 += 0.00000002531 * math.cos(2.16100356086 + 800.5924346291 * self.t) Y0 += 0.00000002557 * math.cos(2.24078889519 + 341.49028240779 * self.t) Y0 += 0.00000002601 * math.cos(2.97805958626 + 261.2371761149 * self.t) Y0 += 0.00000003027 * math.cos(1.77262933089 + 331.07772159029 * self.t) Y0 += 0.00000002494 * math.cos(5.29381091116 + 203.9816853659 * self.t) Y0 += 0.00000002590 * math.cos(3.33405614398 + 1190.5420625756 * self.t) Y0 += 0.00000003494 * math.cos(1.33796606005 + 534.0793841623 * self.t) Y0 += 0.00000003144 * math.cos(1.59061342897 + 1503.9649868156 * self.t) Y0 += 0.00000002818 * math.cos(2.04818816564 + 49.31067880061 * self.t) Y0 += 0.00000002791 * math.cos(2.91527039269 + 288.32451148881 * self.t) Y0 += 0.00000002471 * math.cos(2.80089246981 + 411.11588743459 * self.t) Y0 += 0.00000003059 * math.cos(1.73898053758 + 172.48911597691 * self.t) Y0 += 0.00000002972 * math.cos(5.01468129705 + 569.29165849331 * self.t) Y0 += 0.00000003418 * math.cos(3.83213917567 + 638.3959986583 * self.t) Y0 += 0.00000002541 * math.cos(3.41936535077 + 1448.09090291091 * self.t) Y0 += 0.00000002663 * math.cos(5.14390724060 + 573.6968925084 * self.t) Y0 += 0.00000002439 * math.cos(2.82552552997 + 1625.9652756968 * self.t) Y0 += 0.00000002739 * math.cos(1.01296407856 + 112.8832650427 * self.t) Y0 += 0.00000002821 * math.cos(4.09784112299 + 402.93606672331 * self.t) Y0 += 0.00000003412 * math.cos(5.98246878418 + 772.8325844196 * self.t) Y0 += 0.00000002624 * math.cos(4.28449219810 + 1624.4808029885 * self.t) Y0 += 0.00000003170 * math.cos(2.10762429629 + 1011.13503297159 * self.t) Y0 += 0.00000002908 * math.cos(3.03870325402 + 635.94831810351 * self.t) Y0 += 0.00000002664 * math.cos(4.25083112029 + 409.41896640519 * self.t) Y0 += 0.00000003091 * math.cos(0.31165645931 + 379.25961975071 * self.t) Y0 += 0.00000003301 * math.cos(3.48430565498 + 19.7936613644 * self.t) Y0 += 0.00000003176 * math.cos(4.86809762289 + 300.9095662152 * self.t) Y0 += 0.00000003022 * math.cos(4.37742921398 + 52.0189917863 * self.t) Y0 += 0.00000002890 * math.cos(6.24788645936 + 293.4323209195 * self.t) Y0 += 0.00000002698 * math.cos(3.26450368524 + 78149.06650032569 * self.t) Y0 += 0.00000002558 * math.cos(2.31657732137 + 1371.3371966683 * self.t) Y0 += 0.00000002619 * math.cos(5.37658613752 + 202.0095776906 * self.t) Y0 += 0.00000003176 * math.cos(5.32134696018 + 10101.61156723069 * self.t) Y0 += 0.00000003341 * math.cos(3.91159951862 + 345.8955164229 * self.t) Y0 += 0.00000002373 * math.cos(0.25236813570 + 130.8513158457 * self.t) Y0 += 0.00000002644 * math.cos(4.25178872695 + 305.10235190919 * self.t) Y0 += 0.00000003339 * math.cos(3.06224357085 + 2849.2983147265 * self.t) Y0 += 0.00000002410 * math.cos(3.15243245459 + 951.8525527931 * self.t) Y0 += 0.00000003303 * math.cos(3.82850925169 + 769.5729459921 * self.t) Y0 += 0.00000003302 * math.cos(3.28815049288 + 90.1520274241 * self.t) Y0 += 0.00000002416 * math.cos(4.43555947495 + 527.929045008 * self.t) Y0 += 0.00000002361 * math.cos(0.63550285699 + 905.1214974462 * self.t) Y0 += 0.00000002737 * math.cos(3.20111311776 + 1206.2199993907 * self.t) Y0 += 0.00000002441 * math.cos(5.40055208431 + 246.73489546739 * self.t) Y0 += 0.00000002441 * math.cos(5.40055208431 + 247.2225304344 * self.t) Y0 += 0.00000002957 * math.cos(2.68753178821 + 238.23075185041 * self.t) Y0 += 0.00000003263 * math.cos(2.55710522617 + 1506.93393223219 * self.t) Y0 += 0.00000003293 * math.cos(1.22031676357 + 66.1522096958 * self.t) Y0 += 0.00000003241 * math.cos(5.00885682863 + 978.4186233052 * self.t) Y0 += 0.00000003149 * math.cos(2.07892234370 + 271.9103693633 * self.t) Y0 += 0.00000003149 * math.cos(5.22051499729 + 271.4227343963 * self.t) Y0 += 0.00000002328 * math.cos(0.36371018198 + 31.73887900 * self.t) Y0 += 0.00000002372 * math.cos(2.25731707420 + 309.0345051723 * self.t) Y0 += 0.00000002372 * math.cos(2.25731707420 + 309.5221401393 * self.t) Y0 += 0.00000002369 * math.cos(5.90092450419 + 418.9801939608 * self.t) Y0 += 0.00000003007 * math.cos(6.21088893213 + 1437.7814079574 * self.t) Y0 += 0.00000003034 * math.cos(4.41266493573 + 330.8627811417 * self.t) Y0 += 0.00000002345 * math.cos(4.37756786631 + 453.9318358609 * self.t) Y0 += 0.00000003118 * math.cos(5.30478414038 + 1434.81246254079 * self.t) Y0 += 0.00000002324 * math.cos(5.43011369487 + 495.2462652364 * self.t) Y0 += 0.00000002340 * math.cos(0.70753572900 + 452.43031681009 * self.t) Y0 += 0.00000002336 * math.cos(1.61735465920 + 189.591279303 * self.t) Y0 += 0.00000002920 * math.cos(2.21678930184 + 1549.69920442121 * self.t) Y0 += 0.00000002494 * math.cos(2.36432658211 + 1187.57311715899 * self.t) Y0 += 0.00000002692 * math.cos(5.74887255496 + 425.13053311509 * self.t) Y0 += 0.00000002874 * math.cos(3.06187769177 + 1654.2764513481 * self.t) Y0 += 0.00000002809 * math.cos(0.95838272583 + 317.5843407716 * self.t) Y0 += 0.00000002735 * math.cos(2.36910571540 + 1513.05064149171 * self.t) Y0 += 0.00000002949 * math.cos(4.69913732218 + 186.71620997851 * self.t) Y0 += 0.00000002320 * math.cos(2.31406529898 + 487.38195871019 * self.t) Y0 += 0.00000003113 * math.cos(4.63822476931 + 353.28425006961 * self.t) Y0 += 0.00000003086 * math.cos(3.30396670519 + 1230.5990217789 * self.t) Y0 += 0.00000002722 * math.cos(0.59415160235 + 49.6831858161 * self.t) Y0 += 0.00000003064 * math.cos(2.11685584705 + 133.13224006171 * self.t) Y0 += 0.00000003064 * math.cos(5.25844850064 + 132.64460509469 * self.t) Y0 += 0.00000002470 * math.cos(1.21163683322 + 532.3824631329 * self.t) Y0 += 0.00000002640 * math.cos(5.23029870928 + 394.33804701421 * self.t) Y0 += 0.00000002252 * math.cos(3.41692637069 + 22.6507321964 * self.t) Y0 += 0.00000003151 * math.cos(3.68959728933 + 859.77184894361 * self.t) Y0 += 0.00000002671 * math.cos(2.49225273236 + 37.3679532925 * self.t) Y0 += 0.00000002380 * math.cos(2.43767088034 + 429.2751346993 * self.t) Y0 += 0.00000002655 * math.cos(4.29167785274 + 484.1523808627 * self.t) Y0 += 0.00000003005 * math.cos(4.59447567553 + 1929.33933741419 * self.t) Y0 += 0.00000002550 * math.cos(0.89259009595 + 496.9431862658 * self.t) Y0 += 0.00000002290 * math.cos(4.98199823333 + 455.18681390559 * self.t) Y0 += 0.00000002608 * math.cos(2.28446271246 + 422.9580392062 * self.t) Y0 += 0.00000002226 * math.cos(0.52897898579 + 47.82620609231 * self.t) Y0 += 0.00000002233 * math.cos(3.36949240110 + 877.3461408717 * self.t) Y0 += 0.00000002764 * math.cos(2.40581332791 + 356.68058425589 * self.t) Y0 += 0.00000002719 * math.cos(3.56033366747 + 177.5823711926 * self.t) Y0 += 0.00000002999 * math.cos(3.63965245652 + 1926.37039199759 * self.t) Y0 += 0.00000002693 * math.cos(2.00893145868 + 6284.8041401832 * self.t) Y0 += 0.00000002369 * math.cos(5.90816921383 + 70.88081446661 * self.t) Y0 += 0.00000002498 * math.cos(2.14771583991 + 315.1512144318 * self.t) Y0 += 0.00000002204 * math.cos(4.77545839271 + 442.886135597 * self.t) Y0 += 0.00000002261 * math.cos(4.89614385698 + 621.2335891349 * self.t) Y0 += 0.00000002213 * math.cos(1.45024938630 + 1189.0575898673 * self.t) Y0 += 0.00000002492 * math.cos(4.24445703283 + 406.9712858504 * self.t) Y0 += 0.00000002976 * math.cos(3.02481916981 + 1014.1039783882 * self.t) Y0 += 0.00000002840 * math.cos(0.64471611311 + 522.3336006103 * self.t) Y0 += 0.00000002340 * math.cos(3.29528259310 + 440.43845504219 * self.t) Y0 += 0.00000003012 * math.cos(2.70591736862 + 15.9096922111 * self.t) Y0 += 0.00000003012 * math.cos(2.70591736862 + 16.3973271781 * self.t) Y0 += 0.00000002372 * math.cos(1.81307027955 + 132.5964209849 * self.t) Y0 += 0.00000002232 * math.cos(3.99248125271 + 158.12984768129 * self.t) Y0 += 0.00000002961 * math.cos(5.94214048852 + 286.3524038135 * self.t) Y0 += 0.00000002961 * math.cos(2.80054783493 + 286.8400387805 * self.t) # Neptune_Y1 (t) // 342 terms of order 1 Y1 = 0 Y1 += 0.00357822049 * math.cos(3.03457804662 + 0.2438174835 * self.t) Y1 += 0.00256200629 * math.cos(0.44613631554 + 36.892380413 * self.t) Y1 += 0.00242677799 * math.cos(3.89213848413 + 39.86132582961 * self.t) Y1 += 0.00106073143 * math.cos(4.64936068389 + 37.88921815429 * self.t) Y1 += 0.00103735195 * math.cos(4.51191141127 + 38.3768531213 * self.t) Y1 += 0.00118508231 * math.cos(1.31543504055 + 76.50988875911 * self.t) Y1 += 0.00021930692 * math.cos(1.62939936370 + 35.40790770471 * self.t) Y1 += 0.00017445772 * math.cos(2.69316438174 + 41.3457985379 * self.t) Y1 += 0.00013038843 * math.cos(3.79605108858 + 3.21276290011 * self.t) Y1 += 0.00004928885 * math.cos(0.51813571490 + 73.5409433425 * self.t) Y1 += 0.00002742686 * math.cos(2.49310000815 + 77.9943614674 * self.t) Y1 += 0.00002155134 * math.cos(2.54801435750 + 4.6972356084 * self.t) Y1 += 0.00001882800 * math.cos(2.84958651579 + 33.9234349964 * self.t) Y1 += 0.00001572888 * math.cos(5.79049449823 + 114.6429243969 * self.t) Y1 += 0.00001326507 * math.cos(4.45906236203 + 75.0254160508 * self.t) Y1 += 0.00001343094 * math.cos(1.46758582116 + 42.83027124621 * self.t) Y1 += 0.00000897979 * math.cos(2.69913392072 + 426.8420083595 * self.t) Y1 += 0.00000865617 * math.cos(0.09538823497 + 37.8555882595 * self.t) Y1 += 0.00000849963 * math.cos(4.24519902715 + 38.89811798311 * self.t) Y1 += 0.00000922754 * math.cos(1.77437053635 + 72.05647063421 * self.t) Y1 += 0.00000726258 * math.cos(5.81913445111 + 36.404745446 * self.t) Y1 += 0.00000778220 * math.cos(4.27400223412 + 206.42936592071 * self.t) Y1 += 0.00000754025 * math.cos(3.76126183394 + 220.6564599223 * self.t) Y1 += 0.00000607406 * math.cos(4.81815513635 + 1059.6257476727 * self.t) Y1 += 0.00000571831 * math.cos(0.85851242227 + 522.8212355773 * self.t) Y1 += 0.00000560995 * math.cos(0.34476353479 + 537.0483295789 * self.t) Y1 += 0.00000501078 * math.cos(0.14255476727 + 28.81562556571 * self.t) Y1 += 0.00000493238 * math.cos(0.53463363296 + 39.3736908626 * self.t) Y1 += 0.00000474802 * math.cos(5.97795229031 + 98.6561710411 * self.t) Y1 += 0.00000453975 * math.cos(0.14363576661 + 35.9291725665 * self.t) Y1 += 0.00000471731 * math.cos(3.27137539235 + 1.7282901918 * self.t) Y1 += 0.00000410057 * math.cos(4.19500321025 + 40.8245336761 * self.t) Y1 += 0.00000366899 * math.cos(4.19675940250 + 47.9380806769 * self.t) Y1 += 0.00000450109 * math.cos(2.82750084230 + 76.0222537921 * self.t) Y1 += 0.00000354347 * math.cos(1.55870450456 + 1.24065522479 * self.t) Y1 += 0.00000300159 * math.cos(1.31608359577 + 6.1817083167 * self.t) Y1 += 0.00000327501 * math.cos(5.77559197316 + 33.43580002939 * self.t) Y1 += 0.00000174973 * math.cos(4.06947925642 + 32.4389622881 * self.t) Y1 += 0.00000171503 * math.cos(2.86905921629 + 34.1840674273 * self.t) Y1 += 0.00000156749 * math.cos(1.02465451730 + 79.47883417571 * self.t) Y1 += 0.00000152549 * math.cos(5.29458792782 + 30.300098274 * self.t) Y1 += 0.00000150775 * math.cos(1.46875297221 + 42.5696388153 * self.t) Y1 += 0.00000162280 * math.cos(5.51215947389 + 31.2633061205 * self.t) Y1 += 0.00000131609 * math.cos(3.19975255613 + 7.83293736379 * self.t) Y1 += 0.00000136159 * math.cos(3.00798814109 + 70.5719979259 * self.t) Y1 += 0.00000134616 * math.cos(5.10422989672 + 45.49040012211 * self.t) Y1 += 0.00000116304 * math.cos(5.32949492640 + 46.4536079686 * self.t) Y1 += 0.00000115918 * math.cos(0.24763705851 + 44.31474395451 * self.t) Y1 += 0.00000110293 * math.cos(4.69481457289 + 35.4560918145 * self.t) Y1 += 0.00000099282 * math.cos(0.34979488247 + 2.7251279331 * self.t) Y1 += 0.00000099914 * math.cos(5.92865840649 + 41.2976144281 * self.t) Y1 += 0.00000108706 * math.cos(1.52062460635 + 113.15845168861 * self.t) Y1 += 0.00000088965 * math.cos(5.83760483379 + 60.52313540329 * self.t) Y1 += 0.00000086886 * math.cos(0.75633169755 + 31.9513273211 * self.t) Y1 += 0.00000072232 * math.cos(1.93507773057 + 640.1411037975 * self.t) Y1 += 0.00000086985 * math.cos(3.23018942725 + 419.72846135871 * self.t) Y1 += 0.00000073430 * math.cos(5.93590859407 + 70.08436295889 * self.t) Y1 += 0.00000053395 * math.cos(2.89441175199 + 433.9555553603 * self.t) Y1 += 0.00000057451 * math.cos(5.79242631159 + 213.5429129215 * self.t) Y1 += 0.00000051458 * math.cos(2.44646741842 + 69.3963417583 * self.t) Y1 += 0.00000048797 * math.cos(4.44285537763 + 111.67397898031 * self.t) Y1 += 0.00000048557 * math.cos(1.53569583062 + 2.6769438233 * self.t) Y1 += 0.00000042206 * math.cos(4.80902694866 + 74.53778108379 * self.t) Y1 += 0.00000042550 * math.cos(0.10167685669 + 7.66618102501 * self.t) Y1 += 0.00000039462 * math.cos(4.26971409186 + 31.7845709823 * self.t) Y1 += 0.00000039445 * math.cos(5.65869884949 + 12.77399045571 * self.t) Y1 += 0.00000042389 * math.cos(4.01940273222 + 110.189506272 * self.t) Y1 += 0.00000044118 * math.cos(5.15854031484 + 1589.3167127673 * self.t) Y1 += 0.00000037988 * math.cos(4.30930512095 + 6.3484646555 * self.t) Y1 += 0.00000037802 * math.cos(4.41701497532 + 14.258463164 * self.t) Y1 += 0.00000036280 * math.cos(1.56655638104 + 273.8222308413 * self.t) Y1 += 0.00000037247 * math.cos(6.20048406786 + 73.0533083755 * self.t) Y1 += 0.00000036282 * math.cos(1.28256818253 + 84.5866436064 * self.t) Y1 += 0.00000040018 * math.cos(2.70338838405 + 4.4366031775 * self.t) Y1 += 0.00000032400 * math.cos(0.07249247133 + 44.96913526031 * self.t) Y1 += 0.00000031842 * math.cos(0.45413330049 + 34.9202727377 * self.t) Y1 += 0.00000032037 * math.cos(1.37472212177 + 27.3311528574 * self.t) Y1 += 0.00000034456 * math.cos(1.80072966680 + 529.9347825781 * self.t) Y1 += 0.00000031208 * math.cos(0.16340478702 + 1052.51220067191 * self.t) Y1 += 0.00000030002 * math.cos(0.76559925402 + 1066.7392946735 * self.t) Y1 += 0.00000033805 * math.cos(4.47034863791 + 149.8070146181 * self.t) Y1 += 0.00000033096 * math.cos(0.88714456679 + 116.12739710521 * self.t) Y1 += 0.00000030571 * math.cos(5.59230793843 + 22.3900997655 * self.t) Y1 += 0.00000024020 * math.cos(4.95060362012 + 63.9797157869 * self.t) Y1 += 0.00000023780 * math.cos(5.91699417045 + 105.76971804189 * self.t) Y1 += 0.00000023110 * math.cos(4.08428537053 + 23.87457247379 * self.t) Y1 += 0.00000022233 * math.cos(2.78662410030 + 174.9222423167 * self.t) Y1 += 0.00000021377 * math.cos(2.17060095397 + 316.6356871401 * self.t) Y1 += 0.00000025400 * math.cos(6.09781709877 + 106.73292588839 * self.t) Y1 += 0.00000020754 * math.cos(5.65712726150 + 5.6604434549 * self.t) Y1 += 0.00000025572 * math.cos(0.74829738831 + 529.44714761109 * self.t) Y1 += 0.00000019878 * math.cos(5.73044838456 + 32.9602271499 * self.t) Y1 += 0.00000019754 * math.cos(2.91920492275 + 49.42255338521 * self.t) Y1 += 0.00000019241 * math.cos(4.44333892046 + 7.14491616321 * self.t) Y1 += 0.00000017979 * math.cos(6.19717030924 + 62.4952430786 * self.t) Y1 += 0.00000019513 * math.cos(0.93528726944 + 68.5998902506 * self.t) Y1 += 0.00000018273 * math.cos(3.63050723326 + 227.77000692311 * self.t) Y1 += 0.00000017552 * math.cos(4.23270606709 + 69.0875252176 * self.t) Y1 += 0.00000016704 * math.cos(5.51562885485 + 40.8581635709 * self.t) Y1 += 0.00000016996 * math.cos(2.67528896312 + 91.54262404029 * self.t) Y1 += 0.00000016800 * math.cos(2.08712613778 + 30.4668546128 * self.t) Y1 += 0.00000016800 * math.cos(5.22871879137 + 30.95448957981 * self.t) Y1 += 0.00000016400 * math.cos(3.45346576095 + 33.26904369061 * self.t) Y1 += 0.00000017242 * math.cos(4.89590986485 + 11.55015017831 * self.t) Y1 += 0.00000015590 * math.cos(0.42181314281 + 37.1048287341 * self.t) Y1 += 0.00000015590 * math.cos(3.91877412353 + 39.6488775085 * self.t) Y1 += 0.00000015469 * math.cos(4.91170489358 + 43.79347909271 * self.t) Y1 += 0.00000016590 * math.cos(1.19757876004 + 33.71098667531 * self.t) Y1 += 0.00000019347 * math.cos(4.06418655235 + 152.77596003471 * self.t) Y1 += 0.00000014994 * math.cos(4.29075263091 + 319.06881347989 * self.t) Y1 += 0.00000014395 * math.cos(5.67189517492 + 110.45013870291 * self.t) Y1 += 0.00000015528 * math.cos(5.87587490674 + 79.43065006591 * self.t) Y1 += 0.00000013727 * math.cos(0.88731617093 + 43.484662552 * self.t) Y1 += 0.00000013988 * math.cos(5.54059308769 + 4.2096006414 * self.t) Y1 += 0.00000014467 * math.cos(5.13403607047 + 108.70503356371 * self.t) Y1 += 0.00000016652 * math.cos(4.74696813612 + 304.84171947829 * self.t) Y1 += 0.00000015153 * math.cos(1.64704158732 + 72.31710306511 * self.t) Y1 += 0.00000012810 * math.cos(0.80784638784 + 11.2895177474 * self.t) Y1 += 0.00000012751 * math.cos(5.32663860873 + 45.7992166628 * self.t) Y1 += 0.00000013293 * math.cos(3.14432194523 + 43.0427195673 * self.t) Y1 += 0.00000012751 * math.cos(0.98606109283 + 515.70768857651 * self.t) Y1 += 0.00000011616 * math.cos(4.07265201948 + 97.17169833279 * self.t) Y1 += 0.00000011538 * math.cos(4.63247506911 + 633.0275567967 * self.t) Y1 += 0.00000011046 * math.cos(5.97427560684 + 25.8466801491 * self.t) Y1 += 0.00000011032 * math.cos(5.39646944302 + 4.8639919472 * self.t) Y1 += 0.00000011189 * math.cos(2.37859784397 + 83.1021708981 * self.t) Y1 += 0.00000010860 * math.cos(5.09978655023 + 9.8050450391 * self.t) Y1 += 0.00000010958 * math.cos(3.05455531642 + 415.04804069769 * self.t) Y1 += 0.00000010244 * math.cos(4.97854342755 + 71.09326278771 * self.t) Y1 += 0.00000011427 * math.cos(3.07758676009 + 129.6756596781 * self.t) Y1 += 0.00000009895 * math.cos(4.05388510292 + 251.6759485593 * self.t) Y1 += 0.00000009802 * math.cos(3.40894474212 + 44.48150029329 * self.t) Y1 += 0.00000011029 * math.cos(6.26821027792 + 143.38148881789 * self.t) Y1 += 0.00000009235 * math.cos(4.42290386641 + 199.3158189199 * self.t) Y1 += 0.00000008899 * math.cos(1.97879285736 + 7.3573644843 * self.t) Y1 += 0.00000007746 * math.cos(4.32608949084 + 103.3365917021 * self.t) Y1 += 0.00000008691 * math.cos(2.29051174612 + 32.7477788288 * self.t) Y1 += 0.00000007714 * math.cos(3.51056446926 + 65.46418849521 * self.t) Y1 += 0.00000008007 * math.cos(0.23872922784 + 544.1618765797 * self.t) Y1 += 0.00000007513 * math.cos(6.18736050552 + 69.6087900794 * self.t) Y1 += 0.00000007336 * math.cos(3.43409422317 + 15.7429358723 * self.t) Y1 += 0.00000007195 * math.cos(4.56950200257 + 949.4194264533 * self.t) Y1 += 0.00000009601 * math.cos(5.68191403081 + 80.963306884 * self.t) Y1 += 0.00000008094 * math.cos(1.70304241092 + 526.7533888404 * self.t) Y1 += 0.00000008109 * math.cos(5.77532188995 + 533.1161763158 * self.t) Y1 += 0.00000006906 * math.cos(3.70672232078 + 137.2768416459 * self.t) Y1 += 0.00000007455 * math.cos(1.11362695292 + 105.2484531801 * self.t) Y1 += 0.00000007826 * math.cos(2.45321405406 + 77.0311536209 * self.t) Y1 += 0.00000006529 * math.cos(5.57837212493 + 65.2035560643 * self.t) Y1 += 0.00000007134 * math.cos(2.05010386093 + 44.00592741381 * self.t) Y1 += 0.00000006186 * math.cos(0.85023811841 + 31.4757544416 * self.t) Y1 += 0.00000006186 * math.cos(3.99183077200 + 30.9881194746 * self.t) Y1 += 0.00000007698 * math.cos(4.89115030216 + 14.47091148511 * self.t) Y1 += 0.00000007434 * math.cos(3.96333556733 + 146.8380692015 * self.t) Y1 += 0.00000006317 * math.cos(5.24777799313 + 66.9486612035 * self.t) Y1 += 0.00000006903 * math.cos(4.63739310514 + 75.98862389731 * self.t) Y1 += 0.00000005591 * math.cos(3.47781120117 + 448.98829064149 * self.t) Y1 += 0.00000006425 * math.cos(3.47626562775 + 678.27413943531 * self.t) Y1 += 0.00000005483 * math.cos(1.61247704205 + 34.44469985821 * self.t) Y1 += 0.00000005483 * math.cos(2.72811022429 + 42.3090063844 * self.t) Y1 += 0.00000005519 * math.cos(1.27116075236 + 853.4401992355 * self.t) Y1 += 0.00000005483 * math.cos(5.10869779974 + 100.14064374939 * self.t) Y1 += 0.00000005483 * math.cos(1.96710514615 + 100.6282787164 * self.t) Y1 += 0.00000006288 * math.cos(2.60319684406 + 143.9027536797 * self.t) Y1 += 0.00000006239 * math.cos(4.20987077870 + 17.76992530181 * self.t) Y1 += 0.00000005246 * math.cos(3.52035332490 + 209.6107596584 * self.t) Y1 += 0.00000005331 * math.cos(4.83550697489 + 45.9659730016 * self.t) Y1 += 0.00000005131 * math.cos(4.53503564274 + 217.4750661846 * self.t) Y1 += 0.00000005325 * math.cos(2.82680123889 + 19.2543980101 * self.t) Y1 += 0.00000005172 * math.cos(2.44008575183 + 25.3590451821 * self.t) Y1 += 0.00000005139 * math.cos(4.17507085285 + 6.86972951729 * self.t) Y1 += 0.00000005992 * math.cos(2.76367557670 + 9.3174100721 * self.t) Y1 += 0.00000005011 * math.cos(4.91884286875 + 38.85242600079 * self.t) Y1 += 0.00000004975 * math.cos(3.01044533436 + 525.2543619171 * self.t) Y1 += 0.00000004910 * math.cos(3.47707407879 + 45.277951801 * self.t) Y1 += 0.00000005250 * math.cos(0.16559612363 + 0.719390363 * self.t) Y1 += 0.00000004731 * math.cos(6.27469301850 + 40.3825906914 * self.t) Y1 += 0.00000004731 * math.cos(1.20748690143 + 36.3711155512 * self.t) Y1 += 0.00000005910 * math.cos(1.40566081690 + 6168.43292559449 * self.t) Y1 += 0.00000004700 * math.cos(4.66314397827 + 50.9070260935 * self.t) Y1 += 0.00000005127 * math.cos(1.64029328726 + 140.9338082631 * self.t) Y1 += 0.00000005321 * math.cos(2.09939112611 + 1104.87233031131 * self.t) Y1 += 0.00000006339 * math.cos(1.02786059939 + 10175.3963280567 * self.t) Y1 += 0.00000004983 * math.cos(1.46113982673 + 1090.6452363097 * self.t) Y1 += 0.00000005487 * math.cos(0.13979521980 + 180.03005174739 * self.t) Y1 += 0.00000004560 * math.cos(2.38015606975 + 323.74923414091 * self.t) Y1 += 0.00000004689 * math.cos(5.95510153546 + 1068.22376738181 * self.t) Y1 += 0.00000005562 * math.cos(2.83481631972 + 10098.64262181409 * self.t) Y1 += 0.00000004432 * math.cos(0.83559275468 + 415.7963080956 * self.t) Y1 += 0.00000004456 * math.cos(1.46246408589 + 235.68919520349 * self.t) Y1 += 0.00000004289 * math.cos(4.40449246840 + 1051.0277279636 * self.t) Y1 += 0.00000004145 * math.cos(4.70457869197 + 33.6964324603 * self.t) Y1 += 0.00000004167 * math.cos(3.29886964345 + 416.532513406 * self.t) Y1 += 0.00000004107 * math.cos(0.91956436736 + 61.01077037031 * self.t) Y1 += 0.00000004088 * math.cos(3.88660175347 + 423.66061462181 * self.t) Y1 += 0.00000005027 * math.cos(2.86873904525 + 21.7020785649 * self.t) Y1 += 0.00000004030 * math.cos(3.44189647415 + 216.72430665921 * self.t) Y1 += 0.00000004278 * math.cos(6.22413352457 + 310.4707937708 * self.t) Y1 += 0.00000004013 * math.cos(2.96769071148 + 104275.10267753768 * self.t) Y1 += 0.00000004505 * math.cos(5.93746161630 + 291.9478482112 * self.t) Y1 += 0.00000003959 * math.cos(4.60954974650 + 210.36151918381 * self.t) Y1 += 0.00000003962 * math.cos(5.59162611271 + 978.93988816699 * self.t) Y1 += 0.00000005561 * math.cos(3.31923216598 + 1409.47023230609 * self.t) Y1 += 0.00000005073 * math.cos(5.15285057233 + 1498.3359125231 * self.t) Y1 += 0.00000004227 * math.cos(6.19954210169 + 534.38820070301 * self.t) Y1 += 0.00000004054 * math.cos(2.45804475947 + 430.02340209721 * self.t) Y1 += 0.00000003863 * math.cos(0.67184399240 + 1127.50624756031 * self.t) Y1 += 0.00000004367 * math.cos(0.14073726901 + 58.9837809408 * self.t) Y1 += 0.00000004694 * math.cos(4.91041582057 + 77.5067265004 * self.t) Y1 += 0.00000004144 * math.cos(5.16137286617 + 518.1408149163 * self.t) Y1 += 0.00000004289 * math.cos(1.72696806473 + 921.3206991231 * self.t) Y1 += 0.00000004039 * math.cos(5.37067473153 + 1622.76932774409 * self.t) Y1 += 0.00000005180 * math.cos(3.80035699018 + 99.1438060081 * self.t) Y1 += 0.00000004845 * math.cos(1.33083083566 + 136.78920667889 * self.t) Y1 += 0.00000004827 * math.cos(1.21379713661 + 418.2439886504 * self.t) Y1 += 0.00000003722 * math.cos(4.94171351364 + 1065.2548219652 * self.t) Y1 += 0.00000004729 * math.cos(2.19682691364 + 421.212934067 * self.t) Y1 += 0.00000003490 * math.cos(0.54756448610 + 986.8041946932 * self.t) Y1 += 0.00000003715 * math.cos(1.30912268012 + 254.10907489909 * self.t) Y1 += 0.00000003488 * math.cos(5.95100195908 + 187.9400502559 * self.t) Y1 += 0.00000003989 * math.cos(5.37041318514 + 95.7354097343 * self.t) Y1 += 0.00000003603 * math.cos(2.22310220083 + 67.1154175423 * self.t) Y1 += 0.00000003530 * math.cos(0.93986174870 + 24.36220744081 * self.t) Y1 += 0.00000003538 * math.cos(1.51952328076 + 57.4993082325 * self.t) Y1 += 0.00000003838 * math.cos(3.56895316428 + 979.90309601349 * self.t) Y1 += 0.00000003615 * math.cos(1.60474010406 + 493.2862196486 * self.t) Y1 += 0.00000003457 * math.cos(1.79944886939 + 807.70598162989 * self.t) Y1 += 0.00000003648 * math.cos(1.43920595596 + 647.25465079831 * self.t) Y1 += 0.00000004048 * math.cos(6.25251011272 + 979.69064769239 * self.t) Y1 += 0.00000004414 * math.cos(2.00415973362 + 1062.59469308931 * self.t) Y1 += 0.00000003631 * math.cos(0.74841494891 + 486.1726726478 * self.t) Y1 += 0.00000003347 * math.cos(4.13560148025 + 151.2914873264 * self.t) Y1 += 0.00000003305 * math.cos(5.23397852699 + 1544.07013012871 * self.t) Y1 += 0.00000003428 * math.cos(0.11713176717 + 107.2205608554 * self.t) Y1 += 0.00000003286 * math.cos(3.55869926238 + 1131.6990332543 * self.t) Y1 += 0.00000003389 * math.cos(3.22644735392 + 28.98238190449 * self.t) Y1 += 0.00000003353 * math.cos(2.30309048870 + 10289.7954349701 * self.t) Y1 += 0.00000003214 * math.cos(0.83720162261 + 569.5522909242 * self.t) Y1 += 0.00000003210 * math.cos(1.05449812296 + 114.1552894299 * self.t) Y1 += 0.00000003353 * math.cos(1.62613341505 + 157.8837694654 * self.t) Y1 += 0.00000003339 * math.cos(5.26712406495 + 443.0985839181 * self.t) Y1 += 0.00000003188 * math.cos(2.62887165071 + 361.13400238079 * self.t) Y1 += 0.00000003390 * math.cos(5.53564544873 + 1558.2972241303 * self.t) Y1 += 0.00000003933 * math.cos(2.08622660372 + 313.43973918739 * self.t) Y1 += 0.00000003131 * math.cos(0.52572989907 + 275.3067035496 * self.t) Y1 += 0.00000003156 * math.cos(6.23565991208 + 431.8404353331 * self.t) Y1 += 0.00000003993 * math.cos(4.90080803105 + 67.6366824041 * self.t) Y1 += 0.00000003708 * math.cos(0.24836934654 + 500.39976664941 * self.t) Y1 += 0.00000004051 * math.cos(4.41826493037 + 59.038662695 * self.t) Y1 += 0.00000003757 * math.cos(2.02838234929 + 296.4012663361 * self.t) Y1 += 0.00000003138 * math.cos(0.63906969040 + 347.1193567003 * self.t) Y1 += 0.00000003086 * math.cos(1.67235466145 + 392.9017584157 * self.t) Y1 += 0.00000003466 * math.cos(1.60020779124 + 215.1941419686 * self.t) Y1 += 0.00000003139 * math.cos(3.09999506971 + 159.36824217371 * self.t) Y1 += 0.00000003466 * math.cos(3.47361825954 + 2145.34674583789 * self.t) Y1 += 0.00000003737 * math.cos(3.53018898305 + 449.0364747513 * self.t) Y1 += 0.00000003286 * math.cos(1.82620986507 + 435.44002806861 * self.t) Y1 += 0.00000003043 * math.cos(5.02988988519 + 2.20386307129 * self.t) Y1 += 0.00000003999 * math.cos(5.93005561135 + 6245.1866318371 * self.t) Y1 += 0.00000003999 * math.cos(5.93005561135 + 6244.69899687009 * self.t) Y1 += 0.00000002999 * math.cos(0.07518657231 + 526.00262931501 * self.t) Y1 += 0.00000003014 * math.cos(5.52171912448 + 1054.94532701169 * self.t) Y1 += 0.00000003091 * math.cos(4.52477390940 + 42.997027585 * self.t) Y1 += 0.00000003274 * math.cos(5.81401559586 + 736.1203310153 * self.t) Y1 += 0.00000002965 * math.cos(1.12065249261 + 533.8669358412 * self.t) Y1 += 0.00000003149 * math.cos(2.34844411589 + 103.7639804718 * self.t) Y1 += 0.00000003610 * math.cos(1.47397387042 + 55.05162767771 * self.t) Y1 += 0.00000002937 * math.cos(5.93931708618 + 385.2523923381 * self.t) Y1 += 0.00000002903 * math.cos(4.35235911504 + 117.5636857037 * self.t) Y1 += 0.00000002968 * math.cos(1.28091906944 + 613.31440085451 * self.t) Y1 += 0.00000003097 * math.cos(4.42120029558 + 1395.24313830449 * self.t) Y1 += 0.00000002931 * math.cos(3.60795663266 + 202.4972126576 * self.t) Y1 += 0.00000003013 * math.cos(1.49526296600 + 121.2352065359 * self.t) Y1 += 0.00000003206 * math.cos(2.86107032756 + 53.40958840249 * self.t) Y1 += 0.00000003269 * math.cos(0.45608619325 + 480.00777927849 * self.t) Y1 += 0.00000003948 * math.cos(5.43052261409 + 112.8832650427 * self.t) Y1 += 0.00000002824 * math.cos(3.14926129801 + 176.406715025 * self.t) Y1 += 0.00000002827 * math.cos(0.36860696411 + 429.81095377611 * self.t) Y1 += 0.00000003348 * math.cos(3.55163976673 + 6284.8041401832 * self.t) Y1 += 0.00000002862 * math.cos(2.43356518574 + 384.02855206069 * self.t) Y1 += 0.00000003228 * math.cos(5.13696496058 + 52.6039471229 * self.t) Y1 += 0.00000003446 * math.cos(5.32686217736 + 62.0076081116 * self.t) Y1 += 0.00000003096 * math.cos(4.83839993614 + 71.82946809809 * self.t) Y1 += 0.00000003031 * math.cos(6.24076040166 + 494.2348732801 * self.t) Y1 += 0.00000003021 * math.cos(6.10531658530 + 328.5964111407 * self.t) Y1 += 0.00000002731 * math.cos(0.79873177065 + 432.471082652 * self.t) Y1 += 0.00000003171 * math.cos(4.97187934370 + 10215.0138364028 * self.t) Y1 += 0.00000002674 * math.cos(2.29257372574 + 158.12984768129 * self.t) Y1 += 0.00000002901 * math.cos(4.22947732371 + 559.4697985068 * self.t) Y1 += 0.00000002631 * math.cos(4.21066619701 + 2008.8013566425 * self.t) Y1 += 0.00000002695 * math.cos(3.54636234855 + 81.61769818981 * self.t) Y1 += 0.00000002695 * math.cos(3.54636234855 + 81.13006322279 * self.t) Y1 += 0.00000002721 * math.cos(4.26045579509 + 326.1823604807 * self.t) Y1 += 0.00000002775 * math.cos(4.27616320157 + 457.8614969965 * self.t) Y1 += 0.00000003054 * math.cos(6.23455983590 + 6281.8351947666 * self.t) Y1 += 0.00000002852 * math.cos(2.90626399353 + 186.71620997851 * self.t) Y1 += 0.00000002538 * math.cos(1.73224718947 + 111.18634401329 * self.t) Y1 += 0.00000002835 * math.cos(6.07135630955 + 419.50145882259 * self.t) Y1 += 0.00000002868 * math.cos(3.66893253825 + 844.56699288049 * self.t) Y1 += 0.00000002530 * math.cos(2.61093052560 + 1050.7525413177 * self.t) Y1 += 0.00000002843 * math.cos(4.15972261299 + 830.3398988789 * self.t) Y1 += 0.00000002848 * math.cos(4.69330398359 + 659.36662477269 * self.t) Y1 += 0.00000003031 * math.cos(2.55942970028 + 406.3469551246 * self.t) Y1 += 0.00000002907 * math.cos(3.71503751053 + 573.6968925084 * self.t) Y1 += 0.00000002536 * math.cos(5.01251643852 + 82.6145359311 * self.t) Y1 += 0.00000002957 * math.cos(2.02121290773 + 947.70795120889 * self.t) Y1 += 0.00000003321 * math.cos(3.87615887284 + 449.9996825978 * self.t) Y1 += 0.00000003117 * math.cos(4.74251772899 + 457.32567791969 * self.t) Y1 += 0.00000002902 * math.cos(1.37682148855 + 10212.0448909862 * self.t) Y1 += 0.00000002459 * math.cos(3.74222344492 + 450.73339578069 * self.t) Y1 += 0.00000002557 * math.cos(1.32711393852 + 525.4813644532 * self.t) Y1 += 0.00000002624 * math.cos(3.35106775051 + 946.2234785006 * self.t) Y1 += 0.00000002417 * math.cos(0.09697452811 + 351.5727748252 * self.t) Y1 += 0.00000002454 * math.cos(3.27912412212 + 196.01680510321 * self.t) Y1 += 0.00000002585 * math.cos(5.70826849733 + 248.70700314271 * self.t) Y1 += 0.00000002549 * math.cos(0.23244817308 + 1062.80714141041 * self.t) Y1 += 0.00000002615 * math.cos(4.06090316067 + 425.13053311509 * self.t) Y1 += 0.00000002387 * math.cos(2.04191008078 + 654.3681977991 * self.t) Y1 += 0.00000002439 * math.cos(1.45718218253 + 462.74230389109 * self.t) Y1 += 0.00000002367 * math.cos(2.75159024078 + 107.52937739611 * self.t) Y1 += 0.00000002538 * math.cos(4.19012282298 + 481.2316195559 * self.t) Y1 += 0.00000002479 * math.cos(3.56223236298 + 205.9417309537 * self.t) Y1 += 0.00000002791 * math.cos(5.44719714506 + 24.14975911971 * self.t) Y1 += 0.00000002626 * math.cos(2.73743077295 + 213.0552779545 * self.t) Y1 += 0.00000002445 * math.cos(0.13750022894 + 146.87169909629 * self.t) Y1 += 0.00000002575 * math.cos(0.32351821119 + 86.07111631471 * self.t) Y1 += 0.00000003120 * math.cos(1.20503303199 + 456.36247007319 * self.t) Y1 += 0.00000002587 * math.cos(1.59304506140 + 400.8209466961 * self.t) Y1 += 0.00000002261 * math.cos(3.24987212470 + 644.33388949151 * self.t) Y1 += 0.00000002796 * math.cos(0.30156280343 + 216.67861467689 * self.t) Y1 += 0.00000002896 * math.cos(0.71993168447 + 1685.2959399851 * self.t) Y1 += 0.00000002453 * math.cos(4.81368306062 + 109.9625037359 * self.t) Y1 += 0.00000002325 * math.cos(0.25394919776 + 442.886135597 * self.t) Y1 += 0.00000002387 * math.cos(3.75345095238 + 599.0873068529 * self.t) Y1 += 0.00000002873 * math.cos(5.13430840850 + 834.5326845729 * self.t) Y1 += 0.00000002963 * math.cos(5.48260613029 + 2119.00767786191 * self.t) Y1 += 0.00000002233 * math.cos(4.37346978315 + 709.29362807231 * self.t) Y1 += 0.00000002337 * math.cos(2.73478761543 + 210.5739675049 * self.t) Y1 += 0.00000002259 * math.cos(5.24608284286 + 29.5036467663 * self.t) Y1 += 0.00000002300 * math.cos(2.19835177792 + 986.0534351678 * self.t) Y1 += 0.00000002199 * math.cos(1.21359358990 + 606.2008538537 * self.t) Y1 += 0.00000002325 * math.cos(4.84070679976 + 109.701871305 * self.t) # Neptune_Y2 (t) // 113 terms of order 2 Y2 = 0 Y2 += 0.01620002167 * math.cos(5.31277371181 + 38.3768531213 * self.t) Y2 += 0.00028138323 * math.cos(4.01361134771 + 0.2438174835 * self.t) Y2 += 0.00012318619 * math.cos(1.01433481938 + 39.86132582961 * self.t) Y2 += 0.00008346956 * math.cos(0.42201817445 + 37.88921815429 * self.t) Y2 += 0.00005131003 * math.cos(3.55894443240 + 76.50988875911 * self.t) Y2 += 0.00004109792 * math.cos(6.17733924169 + 36.892380413 * self.t) Y2 += 0.00001369663 * math.cos(1.98683082370 + 1.7282901918 * self.t) Y2 += 0.00000633706 * math.cos(0.81055475696 + 3.21276290011 * self.t) Y2 += 0.00000583006 * math.cos(6.25831267359 + 41.3457985379 * self.t) Y2 += 0.00000546517 * math.cos(5.42211492491 + 75.0254160508 * self.t) Y2 += 0.00000246224 * math.cos(0.87539145895 + 213.5429129215 * self.t) Y2 += 0.00000159773 * math.cos(5.97653264005 + 206.42936592071 * self.t) Y2 += 0.00000156619 * math.cos(2.04577076492 + 220.6564599223 * self.t) Y2 += 0.00000191674 * math.cos(0.60086490402 + 529.9347825781 * self.t) Y2 += 0.00000188212 * math.cos(2.86105100061 + 35.40790770471 * self.t) Y2 += 0.00000117788 * math.cos(2.55450585422 + 522.8212355773 * self.t) Y2 += 0.00000114488 * math.cos(4.76320074833 + 35.9291725665 * self.t) Y2 += 0.00000112666 * math.cos(4.92459292590 + 537.0483295789 * self.t) Y2 += 0.00000105949 * math.cos(5.84319366771 + 40.8245336761 * self.t) Y2 += 0.00000077696 * math.cos(5.55872082952 + 77.9943614674 * self.t) Y2 += 0.00000090798 * math.cos(0.48400254359 + 73.5409433425 * self.t) Y2 += 0.00000067696 * math.cos(0.87599797871 + 426.8420083595 * self.t) Y2 += 0.00000074860 * math.cos(6.15585546499 + 4.6972356084 * self.t) Y2 += 0.00000064717 * math.cos(1.34762573111 + 34.9202727377 * self.t) Y2 += 0.00000051378 * math.cos(1.41763897935 + 36.404745446 * self.t) Y2 += 0.00000050205 * math.cos(5.38246230326 + 42.83027124621 * self.t) Y2 += 0.00000040929 * math.cos(4.64969715335 + 33.9234349964 * self.t) Y2 += 0.00000036136 * math.cos(1.44221344970 + 98.6561710411 * self.t) Y2 += 0.00000033953 * math.cos(3.45488669371 + 1059.6257476727 * self.t) Y2 += 0.00000034603 * math.cos(4.83781708761 + 76.0222537921 * self.t) Y2 += 0.00000035441 * math.cos(0.92439194787 + 31.2633061205 * self.t) Y2 += 0.00000029614 * math.cos(1.77735061850 + 28.81562556571 * self.t) Y2 += 0.00000031027 * math.cos(3.40007815913 + 45.49040012211 * self.t) Y2 += 0.00000035521 * math.cos(2.70107635202 + 39.3736908626 * self.t) Y2 += 0.00000025488 * math.cos(2.47241259934 + 47.9380806769 * self.t) Y2 += 0.00000020115 * math.cos(5.50307482336 + 1.24065522479 * self.t) Y2 += 0.00000014328 * math.cos(1.16675266548 + 433.9555553603 * self.t) Y2 += 0.00000015503 * math.cos(1.56080925316 + 114.6429243969 * self.t) Y2 += 0.00000016998 * math.cos(2.50473507501 + 33.43580002939 * self.t) Y2 += 0.00000013166 * math.cos(5.10795715214 + 419.72846135871 * self.t) Y2 += 0.00000013053 * math.cos(1.40065469605 + 60.52313540329 * self.t) Y2 += 0.00000010637 * math.cos(4.37252543304 + 34.1840674273 * self.t) Y2 += 0.00000009610 * math.cos(0.08619380662 + 640.1411037975 * self.t) Y2 += 0.00000009354 * math.cos(6.12654852334 + 42.5696388153 * self.t) Y2 += 0.00000011447 * math.cos(1.48554252527 + 71.5688356672 * self.t) Y2 += 0.00000008454 * math.cos(4.32641802480 + 2.7251279331 * self.t) Y2 += 0.00000009012 * math.cos(2.87032368668 + 72.05647063421 * self.t) Y2 += 0.00000009594 * math.cos(4.22403656438 + 69.3963417583 * self.t) Y2 += 0.00000007419 * math.cos(1.92565712551 + 227.77000692311 * self.t) Y2 += 0.00000006800 * math.cos(3.57170452455 + 113.15845168861 * self.t) Y2 += 0.00000006267 * math.cos(5.50825416463 + 1066.7392946735 * self.t) Y2 += 0.00000006895 * math.cos(2.74011142877 + 111.67397898031 * self.t) Y2 += 0.00000005770 * math.cos(5.94492182042 + 32.4389622881 * self.t) Y2 += 0.00000005686 * math.cos(0.66726291170 + 30.300098274 * self.t) Y2 += 0.00000006679 * math.cos(3.28449699734 + 258.78949556011 * self.t) Y2 += 0.00000007799 * math.cos(0.01316502615 + 7.3573644843 * self.t) Y2 += 0.00000005906 * math.cos(4.35406299044 + 44.31474395451 * self.t) Y2 += 0.00000005606 * math.cos(3.60862172739 + 46.4536079686 * self.t) Y2 += 0.00000005525 * math.cos(2.04832143671 + 1052.51220067191 * self.t) Y2 += 0.00000007257 * math.cos(4.88554087166 + 1097.7587833105 * self.t) Y2 += 0.00000005427 * math.cos(3.37665889417 + 105.76971804189 * self.t) Y2 += 0.00000005179 * math.cos(2.68906561571 + 515.70768857651 * self.t) Y2 += 0.00000005163 * math.cos(1.56680359144 + 7.83293736379 * self.t) Y2 += 0.00000004688 * math.cos(0.95059580199 + 222.14093263061 * self.t) Y2 += 0.00000005379 * math.cos(1.15102731522 + 22.3900997655 * self.t) Y2 += 0.00000004607 * math.cos(0.17861908533 + 549.1603035533 * self.t) Y2 += 0.00000004101 * math.cos(1.86095686008 + 213.0552779545 * self.t) Y2 += 0.00000004262 * math.cos(3.94315605774 + 204.9448932124 * self.t) Y2 += 0.00000003916 * math.cos(4.92658442131 + 207.913838629 * self.t) Y2 += 0.00000004089 * math.cos(0.26445229364 + 304.84171947829 * self.t) Y2 += 0.00000003729 * math.cos(6.12087852262 + 199.3158189199 * self.t) Y2 += 0.00000003680 * math.cos(3.97729685951 + 1589.3167127673 * self.t) Y2 += 0.00000003702 * math.cos(2.58942752453 + 319.06881347989 * self.t) Y2 += 0.00000004832 * math.cos(5.97662492227 + 215.0273856298 * self.t) Y2 += 0.00000003474 * math.cos(5.88640441483 + 103.3365917021 * self.t) Y2 += 0.00000003298 * math.cos(4.81858024415 + 544.1618765797 * self.t) Y2 += 0.00000004521 * math.cos(1.64991198460 + 108.2173985967 * self.t) Y2 += 0.00000003967 * math.cos(4.24856395374 + 944.7390057923 * self.t) Y2 += 0.00000004059 * math.cos(1.44024718167 + 149.8070146181 * self.t) Y2 += 0.00000004009 * math.cos(4.04772901629 + 533.1161763158 * self.t) Y2 += 0.00000003288 * math.cos(3.02037527521 + 407.9344936969 * self.t) Y2 += 0.00000003976 * math.cos(3.43142225420 + 526.7533888404 * self.t) Y2 += 0.00000003343 * math.cos(5.37024544109 + 531.4192552864 * self.t) Y2 += 0.00000003932 * math.cos(5.23324378146 + 91.54262404029 * self.t) Y2 += 0.00000003478 * math.cos(4.62796796973 + 6.1817083167 * self.t) Y2 += 0.00000002967 * math.cos(5.75717546362 + 860.55374623631 * self.t) Y2 += 0.00000003058 * math.cos(1.59562573237 + 342.9747551161 * self.t) Y2 += 0.00000003974 * math.cos(3.61989902199 + 335.8612081153 * self.t) Y2 += 0.00000002849 * math.cos(2.43690877786 + 666.4801717735 * self.t) Y2 += 0.00000002999 * math.cos(2.84954389869 + 937.62545879149 * self.t) Y2 += 0.00000003008 * math.cos(0.45545092573 + 74.53778108379 * self.t) Y2 += 0.00000003080 * math.cos(4.61982032828 + 129.6756596781 * self.t) Y2 += 0.00000003346 * math.cos(3.07224007183 + 1162.7185218913 * self.t) Y2 += 0.00000002625 * math.cos(3.26539092131 + 273.8222308413 * self.t) Y2 += 0.00000002931 * math.cos(3.14888688193 + 235.68919520349 * self.t) Y2 += 0.00000002579 * math.cos(5.19712816213 + 1073.85284167431 * self.t) Y2 += 0.00000002550 * math.cos(1.43127384605 + 26.58288545949 * self.t) Y2 += 0.00000002542 * math.cos(2.65218049337 + 1265.81129610991 * self.t) Y2 += 0.00000002483 * math.cos(3.30358671055 + 453.1810763355 * self.t) Y2 += 0.00000002732 * math.cos(3.33706438099 + 563.38739755489 * self.t) Y2 += 0.00000002508 * math.cos(0.10584642422 + 37.8555882595 * self.t) Y2 += 0.00000002508 * math.cos(5.05315792539 + 425.35753565121 * self.t) Y2 += 0.00000002680 * math.cos(1.03370719327 + 454.6655490438 * self.t) Y2 += 0.00000002511 * math.cos(1.57939297348 + 209.6107596584 * self.t) Y2 += 0.00000002512 * math.cos(0.17397391459 + 217.4750661846 * self.t) Y2 += 0.00000002552 * math.cos(4.09952672426 + 79.47883417571 * self.t) Y2 += 0.00000002457 * math.cos(1.09953412303 + 38.89811798311 * self.t) Y2 += 0.00000002343 * math.cos(3.50679449028 + 981.3875687218 * self.t) Y2 += 0.00000002501 * math.cos(3.24491806395 + 669.4009330803 * self.t) Y2 += 0.00000002330 * math.cos(2.37985529884 + 38.32866901151 * self.t) Y2 += 0.00000002327 * math.cos(5.10713891298 + 38.4250372311 * self.t) Y2 += 0.00000002481 * math.cos(0.85514029866 + 655.1738390787 * self.t) Y2 += 0.00000002569 * math.cos(2.65544269508 + 464.97504399731 * self.t) # Neptune_Y3 (t) // 37 terms of order 3 Y3 = 0 Y3 += 0.00000985355 * math.cos(5.40479271994 + 38.3768531213 * self.t) Y3 += 0.00000482798 * math.cos(2.40351592403 + 37.88921815429 * self.t) Y3 += 0.00000416447 * math.cos(5.08276459732 + 0.2438174835 * self.t) Y3 += 0.00000303825 * math.cos(5.25036318156 + 39.86132582961 * self.t) Y3 += 0.00000089203 * math.cos(6.23576998030 + 36.892380413 * self.t) Y3 += 0.00000070862 * math.cos(4.26820111330 + 76.50988875911 * self.t) Y3 += 0.00000028900 * math.cos(4.07922314280 + 41.3457985379 * self.t) Y3 += 0.00000022279 * math.cos(1.38807052555 + 206.42936592071 * self.t) Y3 += 0.00000021480 * math.cos(0.30279640762 + 220.6564599223 * self.t) Y3 += 0.00000016157 * math.cos(4.26502283154 + 522.8212355773 * self.t) Y3 += 0.00000015714 * math.cos(3.19639937559 + 537.0483295789 * self.t) Y3 += 0.00000011404 * math.cos(0.68881522230 + 35.40790770471 * self.t) Y3 += 0.00000013199 * math.cos(4.77296321336 + 7.3573644843 * self.t) Y3 += 0.00000007024 * math.cos(5.41129077346 + 3.21276290011 * self.t) Y3 += 0.00000006772 * math.cos(5.90918041474 + 69.3963417583 * self.t) Y3 += 0.00000004517 * math.cos(1.71813394760 + 45.49040012211 * self.t) Y3 += 0.00000004523 * math.cos(2.61625996387 + 31.2633061205 * self.t) Y3 += 0.00000003682 * math.cos(3.04341607939 + 98.6561710411 * self.t) Y3 += 0.00000003656 * math.cos(2.17226292493 + 968.64494742849 * self.t) Y3 += 0.00000003927 * math.cos(5.25979459691 + 426.8420083595 * self.t) Y3 += 0.00000003199 * math.cos(3.24406648940 + 1519.6765535255 * self.t) Y3 += 0.00000003498 * math.cos(4.84556329465 + 407.9344936969 * self.t) Y3 += 0.00000003304 * math.cos(3.81825313228 + 422.1615876985 * self.t) Y3 += 0.00000003331 * math.cos(3.54124873059 + 36.404745446 * self.t) Y3 += 0.00000003244 * math.cos(4.42247914038 + 484.2005649725 * self.t) Y3 += 0.00000002689 * math.cos(5.61171743826 + 441.06910236111 * self.t) Y3 += 0.00000003247 * math.cos(3.33592493083 + 498.42765897409 * self.t) Y3 += 0.00000002651 * math.cos(2.02749548795 + 304.84171947829 * self.t) Y3 += 0.00000002645 * math.cos(0.90433895865 + 461.77909604459 * self.t) Y3 += 0.00000002542 * math.cos(1.05108120438 + 444.5830566264 * self.t) Y3 += 0.00000002524 * math.cos(5.46978523129 + 433.9555553603 * self.t) Y3 += 0.00000002472 * math.cos(0.92177286185 + 319.06881347989 * self.t) Y3 += 0.00000002355 * math.cos(2.03272387563 + 447.552002043 * self.t) Y3 += 0.00000002876 * math.cos(3.65433810175 + 853.4401992355 * self.t) Y3 += 0.00000002279 * math.cos(6.20789133449 + 458.810150628 * self.t) Y3 += 0.00000002147 * math.cos(1.06531556689 + 175.40987728371 * self.t) Y3 += 0.00000002637 * math.cos(2.06613866653 + 73.5409433425 * self.t) # Neptune_Y4 (t) // 14 terms of order 4 Y4 = 0 Y4 += 0.00003455306 * math.cos(2.04385259535 + 38.3768531213 * self.t) Y4 += 0.00000047405 * math.cos(0.64311364094 + 0.2438174835 * self.t) Y4 += 0.00000021936 * math.cos(4.30052120876 + 37.88921815429 * self.t) Y4 += 0.00000015596 * math.cos(0.30774488881 + 76.50988875911 * self.t) Y4 += 0.00000017186 * math.cos(3.96705739007 + 39.86132582961 * self.t) Y4 += 0.00000017459 * math.cos(3.25820107685 + 36.892380413 * self.t) Y4 += 0.00000004229 * math.cos(6.14484758916 + 515.70768857651 * self.t) Y4 += 0.00000004334 * math.cos(3.84568484898 + 433.9555553603 * self.t) Y4 += 0.00000003547 * math.cos(1.04322259069 + 989.98558843089 * self.t) Y4 += 0.00000003155 * math.cos(0.14083942013 + 467.40817033709 * self.t) Y4 += 0.00000003017 * math.cos(4.77718347184 + 227.77000692311 * self.t) Y4 += 0.00000002981 * math.cos(5.01159762849 + 1.7282901918 * self.t) Y4 += 0.00000002295 * math.cos(4.84988240730 + 220.6564599223 * self.t) Y4 += 0.00000002296 * math.cos(3.13566627364 + 206.42936592071 * self.t) # Neptune_Y5 (t) // 1 term of order 5 Y5 = 0 Y5 += 0.00000026291 * math.cos(2.14645097520 + 38.3768531213 * self.t) Y = ( Y0+ Y1*self.t+ Y2*self.t*self.t+ Y3*self.t*self.t*self.t+ Y4*self.t*self.t*self.t*self.t+ Y5*self.t*self.t*self.t*self.t*self.t) # Neptune_Z0 (t) // 133 terms of order 0 Z0 = 0 Z0 += 0.92866054405 * math.cos(1.44103930278 + 38.1330356378 * self.t) Z0 += 0.01245978462 Z0 += 0.00474333567 * math.cos(2.52218774238 + 36.6485629295 * self.t) Z0 += 0.00451987936 * math.cos(3.50949720541 + 39.6175083461 * self.t) Z0 += 0.00417558068 * math.cos(5.91310695421 + 76.2660712756 * self.t) Z0 += 0.00084104329 * math.cos(4.38928900096 + 1.4844727083 * self.t) Z0 += 0.00032704958 * math.cos(1.52048692001 + 74.7815985673 * self.t) Z0 += 0.00030873335 * math.cos(3.29017611456 + 35.1640902212 * self.t) Z0 += 0.00025812584 * math.cos(3.19303128782 + 2.9689454166 * self.t) Z0 += 0.00016865319 * math.cos(2.13251104425 + 41.1019810544 * self.t) Z0 += 0.00011789909 * math.cos(3.60001877675 + 213.299095438 * self.t) Z0 += 0.00009770125 * math.cos(2.80133971586 + 73.297125859 * self.t) Z0 += 0.00011279680 * math.cos(3.55816676334 + 529.6909650946 * self.t) Z0 += 0.00004119873 * math.cos(1.67934316836 + 77.7505439839 * self.t) Z0 += 0.00002818034 * math.cos(4.10661077794 + 114.3991069134 * self.t) Z0 += 0.00002868677 * math.cos(4.27011526203 + 33.6796175129 * self.t) Z0 += 0.00002213464 * math.cos(1.96045135168 + 4.4534181249 * self.t) Z0 += 0.00001865650 * math.cos(5.05540709577 + 71.8126531507 * self.t) Z0 += 0.00000840177 * math.cos(0.94268885160 + 42.5864537627 * self.t) Z0 += 0.00000457516 * math.cos(5.71650412080 + 108.4612160802 * self.t) Z0 += 0.00000530252 * math.cos(0.85800267793 + 111.4301614968 * self.t) Z0 += 0.00000490859 * math.cos(6.07827301209 + 112.9146342051 * self.t) Z0 += 0.00000331254 * math.cos(0.29304964526 + 70.3281804424 * self.t) Z0 += 0.00000330045 * math.cos(2.83839676215 + 426.598190876 * self.t) Z0 += 0.00000273589 * math.cos(3.91013681794 + 1059.3819301892 * self.t) Z0 += 0.00000277586 * math.cos(1.45092010545 + 148.0787244263 * self.t) Z0 += 0.00000274474 * math.cos(5.42657022437 + 32.1951448046 * self.t) Z0 += 0.00000205306 * math.cos(0.75818737085 + 5.9378908332 * self.t) Z0 += 0.00000173516 * math.cos(5.85498030099 + 145.1097790097 * self.t) Z0 += 0.00000141275 * math.cos(1.73147597657 + 28.5718080822 * self.t) Z0 += 0.00000139093 * math.cos(1.67466701191 + 184.7272873558 * self.t) Z0 += 0.00000143647 * math.cos(2.51620047812 + 37.611770776 * self.t) Z0 += 0.00000136955 * math.cos(0.20339778664 + 79.2350166922 * self.t) Z0 += 0.00000126296 * math.cos(4.40661385040 + 37.1698277913 * self.t) Z0 += 0.00000120906 * math.cos(1.61767636602 + 39.0962434843 * self.t) Z0 += 0.00000111761 * math.cos(6.20948230785 + 98.8999885246 * self.t) Z0 += 0.00000140758 * math.cos(3.50944989694 + 38.6543004996 * self.t) Z0 += 0.00000111589 * math.cos(4.18561395578 + 47.6942631934 * self.t) Z0 += 0.00000133509 * math.cos(4.78977105547 + 38.084851528 * self.t) Z0 += 0.00000102622 * math.cos(0.81673762159 + 4.192785694 * self.t) Z0 += 0.00000133292 * math.cos(1.23386935925 + 38.1812197476 * self.t) Z0 += 0.00000098771 * math.cos(0.72335005782 + 106.9767433719 * self.t) Z0 += 0.00000093919 * math.cos(0.56607810948 + 206.1855484372 * self.t) Z0 += 0.00000081727 * math.cos(3.47861315258 + 220.4126424388 * self.t) Z0 += 0.00000074559 * math.cos(2.31518880439 + 312.1990839626 * self.t) Z0 += 0.00000074401 * math.cos(5.99935727164 + 181.7583419392 * self.t) Z0 += 0.00000073141 * math.cos(1.80069951634 + 137.0330241624 * self.t) Z0 += 0.00000066838 * math.cos(1.87185330904 + 221.3758502853 * self.t) Z0 += 0.00000058303 * math.cos(5.61662561548 + 35.685355083 * self.t) Z0 += 0.00000051685 * math.cos(6.02831347649 + 44.070926471 * self.t) Z0 += 0.00000051928 * math.cos(0.40473854286 + 40.5807161926 * self.t) Z0 += 0.00000048182 * math.cos(2.97141991737 + 37.8724032069 * self.t) Z0 += 0.00000049439 * math.cos(1.66178905717 + 68.8437077341 * self.t) Z0 += 0.00000047742 * math.cos(3.05261105371 + 38.3936680687 * self.t) Z0 += 0.00000046428 * math.cos(2.66596739242 + 146.594251718 * self.t) Z0 += 0.00000050936 * math.cos(0.19994012329 + 30.0562807905 * self.t) Z0 += 0.00000041127 * math.cos(6.05239303825 + 115.8835796217 * self.t) Z0 += 0.00000055537 * math.cos(2.11977296055 + 109.9456887885 * self.t) Z0 += 0.00000041357 * math.cos(0.86667380713 + 143.6253063014 * self.t) Z0 += 0.00000044492 * math.cos(6.00613878606 + 149.5631971346 * self.t) Z0 += 0.00000037856 * math.cos(5.19945796177 + 72.0732855816 * self.t) Z0 += 0.00000047361 * math.cos(3.58964541604 + 38.0211610532 * self.t) Z0 += 0.00000034690 * math.cos(1.47398766326 + 8.0767548473 * self.t) Z0 += 0.00000037349 * math.cos(5.15067903040 + 33.9402499438 * self.t) Z0 += 0.00000034386 * math.cos(6.15246630929 + 218.4069048687 * self.t) Z0 += 0.00000047180 * math.cos(2.43405967107 + 38.2449102224 * self.t) Z0 += 0.00000033382 * math.cos(0.88396990078 + 42.3258213318 * self.t) Z0 += 0.00000040753 * math.cos(3.59668759304 + 522.5774180938 * self.t) Z0 += 0.00000033071 * math.cos(2.02572550598 + 258.0244132148 * self.t) Z0 += 0.00000038849 * math.cos(5.79294381756 + 46.2097904851 * self.t) Z0 += 0.00000031716 * math.cos(0.30412624027 + 536.8045120954 * self.t) Z0 += 0.00000027605 * math.cos(2.81540405940 + 183.2428146475 * self.t) Z0 += 0.00000024616 * math.cos(0.40597272412 + 30.7106720963 * self.t) Z0 += 0.00000021716 * math.cos(0.90792314747 + 175.1660598002 * self.t) Z0 += 0.00000021634 * math.cos(3.25469228647 + 388.4651552382 * self.t) Z0 += 0.00000020384 * math.cos(5.80954414865 + 7.4223635415 * self.t) Z0 += 0.00000018640 * math.cos(1.06424642993 + 180.2738692309 * self.t) Z0 += 0.00000016716 * math.cos(0.02332590259 + 255.0554677982 * self.t) Z0 += 0.00000018790 * math.cos(0.62408059806 + 35.212274331 * self.t) Z0 += 0.00000016990 * math.cos(2.19726523790 + 294.6729761443 * self.t) Z0 += 0.00000016083 * math.cos(4.20629091415 + 0.9632078465 * self.t) Z0 += 0.00000021571 * math.cos(2.39337706760 + 152.5321425512 * self.t) Z0 += 0.00000017102 * math.cos(5.39964889794 + 41.0537969446 * self.t) Z0 += 0.00000014503 * math.cos(4.66614523797 + 110.2063212194 * self.t) Z0 += 0.00000015218 * math.cos(2.93182248771 + 219.891377577 * self.t) Z0 += 0.00000014757 * math.cos(2.02029526083 + 105.4922706636 * self.t) Z0 += 0.00000013303 * math.cos(2.09362099250 + 639.897286314 * self.t) Z0 += 0.00000013582 * math.cos(0.99222619680 + 44.7253177768 * self.t) Z0 += 0.00000011309 * math.cos(4.15253392707 + 487.3651437628 * self.t) Z0 += 0.00000012521 * math.cos(0.41449986025 + 186.2117600641 * self.t) Z0 += 0.00000012363 * math.cos(3.07599476497 + 6.592282139 * self.t) Z0 += 0.00000010825 * math.cos(4.13817476053 + 0.5212648618 * self.t) Z0 += 0.00000014304 * math.cos(5.15644933777 + 31.5407534988 * self.t) Z0 += 0.00000010056 * math.cos(4.27077049743 + 1589.0728952838 * self.t) Z0 += 0.00000009355 * math.cos(1.23360360711 + 216.9224321604 * self.t) Z0 += 0.00000008774 * math.cos(5.77195684843 + 12.5301729722 * self.t) Z0 += 0.00000008445 * math.cos(0.17584724644 + 291.7040307277 * self.t) Z0 += 0.00000008927 * math.cos(2.36869187243 + 331.3215390738 * self.t) Z0 += 0.00000009613 * math.cos(0.28151591238 + 60.7669528868 * self.t) Z0 += 0.00000008279 * math.cos(5.72084525545 + 36.7604375141 * self.t) Z0 += 0.00000009111 * math.cos(3.49027191661 + 45.2465826386 * self.t) Z0 += 0.00000008178 * math.cos(0.25637861075 + 39.5056337615 * self.t) Z0 += 0.00000008598 * math.cos(3.10287346009 + 256.5399405065 * self.t) Z0 += 0.00000009489 * math.cos(4.94205919676 + 151.0476698429 * self.t) Z0 += 0.00000008564 * math.cos(2.15904622462 + 274.0660483248 * self.t) Z0 += 0.00000007474 * math.cos(2.93279436008 + 27.0873353739 * self.t) Z0 += 0.00000007944 * math.cos(0.38277699900 + 10213.285546211 * self.t) Z0 += 0.00000007132 * math.cos(1.50971234331 + 944.9828232758 * self.t) Z0 += 0.00000009005 * math.cos(0.07284074730 + 419.4846438752 * self.t) Z0 += 0.00000007642 * math.cos(5.56097006597 + 187.6962327724 * self.t) Z0 += 0.00000007705 * math.cos(1.54152595157 + 84.3428261229 * self.t) Z0 += 0.00000006896 * math.cos(4.71453324740 + 406.1031376411 * self.t) Z0 += 0.00000007282 * math.cos(5.81348163927 + 316.3918696566 * self.t) Z0 += 0.00000006215 * math.cos(5.27967153537 + 7.1135470008 * self.t) Z0 += 0.00000006090 * math.cos(4.48506819561 + 415.2918581812 * self.t) Z0 += 0.00000006316 * math.cos(0.59502514374 + 453.424893819 * self.t) Z0 += 0.00000006177 * math.cos(5.20115334051 + 80.7194894005 * self.t) Z0 += 0.00000006324 * math.cos(2.18406254461 + 142.1408335931 * self.t) Z0 += 0.00000005646 * math.cos(0.76840537906 + 11.0457002639 * self.t) Z0 += 0.00000006102 * math.cos(5.58764378724 + 662.531203563 * self.t) Z0 += 0.00000005334 * math.cos(4.52703538458 + 103.0927742186 * self.t) Z0 += 0.00000006269 * math.cos(1.95162790177 + 605.9570363702 * self.t) Z0 += 0.00000005591 * math.cos(5.20631788297 + 14.0146456805 * self.t) Z0 += 0.00000004914 * math.cos(1.39906038110 + 253.5709950899 * self.t) Z0 += 0.00000004519 * math.cos(2.07610590431 + 2042.4977891028 * self.t) Z0 += 0.00000005681 * math.cos(4.80791039970 + 641.1211265914 * self.t) Z0 += 0.00000006294 * math.cos(0.56936923702 + 31.019488637 * self.t) Z0 += 0.00000004758 * math.cos(2.54312258712 + 367.9701020033 * self.t) Z0 += 0.00000004406 * math.cos(0.33696669222 + 328.3525936572 * self.t) Z0 += 0.00000004390 * math.cos(5.08949604858 + 286.596221297 * self.t) Z0 += 0.00000004678 * math.cos(4.87546696295 + 442.7517005706 * self.t) Z0 += 0.00000004407 * math.cos(5.58110402011 + 252.0865223816 * self.t) Z0 += 0.00000004305 * math.cos(1.31724140028 + 493.0424021651 * self.t) # Neptune_Z1 (t) // 61 terms of order 1 Z1 = 0 Z1 += 0.06832633707 * math.cos(3.80782656293 + 38.1330356378 * self.t) Z1 -= 0.00064598028 Z1 += 0.00042738331 * math.cos(4.82540335637 + 36.6485629295 * self.t) Z1 += 0.00031421638 * math.cos(6.08083255385 + 39.6175083461 * self.t) Z1 += 0.00027088623 * math.cos(1.97557659098 + 76.2660712756 * self.t) Z1 += 0.00005924197 * math.cos(0.48500737803 + 1.4844727083 * self.t) Z1 += 0.00002429056 * math.cos(3.86784381378 + 74.7815985673 * self.t) Z1 += 0.00002107258 * math.cos(6.19720726581 + 35.1640902212 * self.t) Z1 += 0.00001644542 * math.cos(5.76041185818 + 2.9689454166 * self.t) Z1 += 0.00001059588 * math.cos(4.89687990866 + 41.1019810544 * self.t) Z1 += 0.00001084464 * math.cos(5.33722455731 + 213.299095438 * self.t) Z1 += 0.00000880611 * math.cos(5.70150456912 + 529.6909650946 * self.t) Z1 += 0.00000824125 * math.cos(5.04137560987 + 73.297125859 * self.t) Z1 += 0.00000250821 * math.cos(4.25953295692 + 77.7505439839 * self.t) Z1 += 0.00000158517 * math.cos(0.13500997625 + 114.3991069134 * self.t) Z1 += 0.00000129390 * math.cos(4.76999039957 + 4.4534181249 * self.t) Z1 += 0.00000105033 * math.cos(0.99234583035 + 33.6796175129 * self.t) Z1 += 0.00000054734 * math.cos(3.96812588022 + 42.5864537627 * self.t) Z1 += 0.00000034799 * math.cos(4.30403521625 + 37.611770776 * self.t) Z1 += 0.00000041340 * math.cos(2.29314729799 + 206.1855484372 * self.t) Z1 += 0.00000028374 * math.cos(1.67853213747 + 111.4301614968 * self.t) Z1 += 0.00000025340 * math.cos(1.70015942799 + 220.4126424388 * self.t) Z1 += 0.00000026021 * math.cos(6.09040669128 + 426.598190876 * self.t) Z1 += 0.00000027198 * math.cos(5.95188476775 + 71.8126531507 * self.t) Z1 += 0.00000021598 * math.cos(2.17619854748 + 112.9146342051 * self.t) Z1 += 0.00000025154 * math.cos(4.13631230281 + 28.5718080822 * self.t) Z1 += 0.00000020543 * math.cos(1.56946393801 + 38.6543004996 * self.t) Z1 += 0.00000017216 * math.cos(2.81703507859 + 98.8999885246 * self.t) Z1 += 0.00000019926 * math.cos(3.15301554161 + 108.4612160802 * self.t) Z1 += 0.00000015544 * math.cos(2.07364839388 + 40.5807161926 * self.t) Z1 += 0.00000015357 * math.cos(5.45891321516 + 522.5774180938 * self.t) Z1 += 0.00000012266 * math.cos(3.82427247378 + 5.9378908332 * self.t) Z1 += 0.00000013587 * math.cos(1.34795861192 + 47.6942631934 * self.t) Z1 += 0.00000010839 * math.cos(4.75461825384 + 536.8045120954 * self.t) Z1 += 0.00000010785 * math.cos(2.61566414257 + 79.2350166922 * self.t) Z1 += 0.00000010916 * math.cos(3.88744647444 + 35.685355083 * self.t) Z1 += 0.00000009833 * math.cos(3.62341506247 + 38.1812197476 * self.t) Z1 += 0.00000009849 * math.cos(0.89613145346 + 38.084851528 * self.t) Z1 += 0.00000009317 * math.cos(0.51297445145 + 37.1698277913 * self.t) Z1 += 0.00000008955 * math.cos(4.00532631258 + 39.0962434843 * self.t) Z1 += 0.00000007089 * math.cos(2.29610703652 + 137.0330241624 * self.t) Z1 += 0.00000007573 * math.cos(3.20619266484 + 4.192785694 * self.t) Z1 += 0.00000008063 * math.cos(5.86511590361 + 1059.3819301892 * self.t) Z1 += 0.00000007655 * math.cos(3.39616255650 + 145.1097790097 * self.t) Z1 += 0.00000006061 * math.cos(2.31235275416 + 109.9456887885 * self.t) Z1 += 0.00000005726 * math.cos(6.23400745185 + 312.1990839626 * self.t) Z1 += 0.00000003739 * math.cos(2.50010254963 + 30.0562807905 * self.t) Z1 += 0.00000004145 * math.cos(2.00938305966 + 44.070926471 * self.t) Z1 += 0.00000003480 * math.cos(5.88971113590 + 38.0211610532 * self.t) Z1 += 0.00000003467 * math.cos(4.73412534395 + 38.2449102224 * self.t) Z1 += 0.00000004736 * math.cos(6.28313624461 + 149.5631971346 * self.t) Z1 += 0.00000003905 * math.cos(4.49400805134 + 106.9767433719 * self.t) Z1 += 0.00000002982 * math.cos(1.80386443362 + 46.2097904851 * self.t) Z1 += 0.00000003538 * math.cos(5.27114846878 + 37.8724032069 * self.t) Z1 += 0.00000003508 * math.cos(5.35267669439 + 38.3936680687 * self.t) Z1 += 0.00000002821 * math.cos(1.10242173566 + 33.9402499438 * self.t) Z1 += 0.00000003150 * math.cos(2.14792830412 + 115.8835796217 * self.t) Z1 += 0.00000003329 * math.cos(3.56226463770 + 181.7583419392 * self.t) Z1 += 0.00000002787 * math.cos(1.21334651843 + 72.0732855816 * self.t) Z1 += 0.00000002453 * math.cos(3.18401661435 + 42.3258213318 * self.t) Z1 += 0.00000002523 * math.cos(5.51669920239 + 8.0767548473 * self.t) # Neptune_Z2 (t) // 20 terms of order 2 Z2 = 0 Z2 += 0.00291361164 * math.cos(5.57085222635 + 38.1330356378 * self.t) Z2 += 0.00002207820 * math.cos(0.45423510946 + 36.6485629295 * self.t) Z2 -= 0.00002644401 Z2 += 0.00001184984 * math.cos(3.62696666572 + 76.2660712756 * self.t) Z2 += 0.00000875873 * math.cos(1.60783110298 + 39.6175083461 * self.t) Z2 += 0.00000253280 * math.cos(2.25499665308 + 1.4844727083 * self.t) Z2 += 0.00000139875 * math.cos(1.66224942942 + 35.1640902212 * self.t) Z2 += 0.00000105837 * math.cos(5.61746558118 + 74.7815985673 * self.t) Z2 += 0.00000055479 * math.cos(0.51417309302 + 213.299095438 * self.t) Z2 += 0.00000051858 * math.cos(1.20450519900 + 2.9689454166 * self.t) Z2 += 0.00000040183 * math.cos(1.45604293605 + 529.6909650946 * self.t) Z2 += 0.00000041153 * math.cos(0.64158589676 + 73.297125859 * self.t) Z2 += 0.00000013931 * math.cos(0.27428875486 + 41.1019810544 * self.t) Z2 += 0.00000009181 * math.cos(2.83312722213 + 33.6796175129 * self.t) Z2 += 0.00000007421 * math.cos(4.32019600438 + 206.1855484372 * self.t) Z2 += 0.00000006998 * math.cos(5.87666052849 + 77.7505439839 * self.t) Z2 += 0.00000007085 * math.cos(1.66037085233 + 71.8126531507 * self.t) Z2 += 0.00000006818 * math.cos(1.56386946094 + 114.3991069134 * self.t) Z2 += 0.00000004838 * math.cos(0.83470875824 + 220.4126424388 * self.t) Z2 += 0.00000002545 * math.cos(0.43712705655 + 4.4534181249 * self.t) # Neptune_Z3 (t) // 8 terms of order 3 Z3 = 0 Z3 += 0.00008221290 * math.cos(1.01632472042 + 38.1330356378 * self.t) Z3 += 0.00000103933 Z3 += 0.00000070154 * math.cos(2.36502685986 + 36.6485629295 * self.t) Z3 += 0.00000031617 * math.cos(5.35266161292 + 76.2660712756 * self.t) Z3 += 0.00000015470 * math.cos(3.21170859085 + 39.6175083461 * self.t) Z3 += 0.00000007111 * math.cos(3.99067059016 + 1.4844727083 * self.t) Z3 += 0.00000004656 * math.cos(3.62376309338 + 35.1640902212 * self.t) Z3 += 0.00000002988 * math.cos(1.03727330540 + 74.7815985673 * self.t) # Neptune_Z4 (t) // 1 term of order 4 Z4 = 0 Z4 += 0.00000172227 * math.cos(2.66872693322 + 38.1330356378 * self.t) # Neptune_Z5 (t) // 1 term of order 5 Z5 = 0 Z5 += 0.00000003394 * math.cos(4.70646877989 + 38.1330356378 * self.t) Z = ( Z0+ Z1*self.t+ Z2*self.t*self.t+ Z3*self.t*self.t*self.t+ Z4*self.t*self.t*self.t*self.t+ Z5*self.t*self.t*self.t*self.t*self.t) return (X, Y, Z)
zdomjus60/astrometry
vsop87c/neptune.py
Python
cc0-1.0
232,946
0.003778
''' Generate a pdf knittinf pattern + chart from a bitmap image ''' __author__ = 'Thomas Payne' __email__ = 'tomkentpayne@hotmail.com' __copyright__ = 'Copyright © 2015 Thomas Payne' __licence__ = 'GPL v2' from argparse import ArgumentParser from pattern import Pattern def parse_sys_args(): ''' Parse arguments for bitmap path ''' parser = ArgumentParser(description='Generate knitting pattern from a bitmap image') parser.add_argument('bitmap' ,action='store') return parser.parse_args() if __name__ == '__main__': args = parse_sys_args() bitmap_path = args.bitmap pattern = Pattern() #Print arg for debug purposes print(bitmap_path)
tomkentpayne/knitify
source/knitify.py
Python
gpl-2.0
676
0.008889
# Commands submodule definition. # # Import all python files in the directory to simplify adding commands. # Just drop a new command .py file in the directory and it will be picked up # automatically. # # Author: Tony DiCola # # The MIT License (MIT) # # Copyright (c) 2015 Adafruit Industries # # 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 os # Import all python files in the commands directory by setting them to the __all__ # global which tells python the modules to load. Grabs a list of all files in # the directory and filters down to just the names (without .py extensions) of # python files that don't start with '__' (which are module metadata that should # be ignored. __all__ = map(lambda x: x[:-3], filter(lambda x: not x.startswith('__') and x.lower().endswith('.py'), os.listdir(__path__[0])))
adafruit/Adafruit_Legolas
Adafruit_Legolas/commands/__init__.py
Python
mit
1,864
0.002682
""" Various bayesian regression """ # Authors: V. Michel, F. Pedregosa, A. Gramfort # License: BSD 3 clause from math import log import numpy as np from scipy import linalg from ._base import LinearModel, _rescale_data from ..base import RegressorMixin from ._base import _deprecate_normalize from ..utils.extmath import fast_logdet from scipy.linalg import pinvh from ..utils.validation import _check_sample_weight ############################################################################### # BayesianRidge regression class BayesianRidge(RegressorMixin, LinearModel): """Bayesian ridge regression. Fit a Bayesian ridge model. See the Notes section for details on this implementation and the optimization of the regularization parameters lambda (precision of the weights) and alpha (precision of the noise). Read more in the :ref:`User Guide <bayesian_regression>`. Parameters ---------- n_iter : int, default=300 Maximum number of iterations. Should be greater than or equal to 1. tol : float, default=1e-3 Stop the algorithm if w has converged. alpha_1 : float, default=1e-6 Hyper-parameter : shape parameter for the Gamma distribution prior over the alpha parameter. alpha_2 : float, default=1e-6 Hyper-parameter : inverse scale parameter (rate parameter) for the Gamma distribution prior over the alpha parameter. lambda_1 : float, default=1e-6 Hyper-parameter : shape parameter for the Gamma distribution prior over the lambda parameter. lambda_2 : float, default=1e-6 Hyper-parameter : inverse scale parameter (rate parameter) for the Gamma distribution prior over the lambda parameter. alpha_init : float, default=None Initial value for alpha (precision of the noise). If not set, alpha_init is 1/Var(y). .. versionadded:: 0.22 lambda_init : float, default=None Initial value for lambda (precision of the weights). If not set, lambda_init is 1. .. versionadded:: 0.22 compute_score : bool, default=False If True, compute the log marginal likelihood at each iteration of the optimization. fit_intercept : bool, default=True Whether to calculate the intercept for this model. The intercept is not treated as a probabilistic parameter and thus has no associated variance. If set to False, no intercept will be used in calculations (i.e. data is expected to be centered). normalize : bool, default=False This parameter is ignored when ``fit_intercept`` is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use :class:`~sklearn.preprocessing.StandardScaler` before calling ``fit`` on an estimator with ``normalize=False``. .. deprecated:: 1.0 ``normalize`` was deprecated in version 1.0 and will be removed in 1.2. copy_X : bool, default=True If True, X will be copied; else, it may be overwritten. verbose : bool, default=False Verbose mode when fitting the model. Attributes ---------- coef_ : array-like of shape (n_features,) Coefficients of the regression model (mean of distribution) intercept_ : float Independent term in decision function. Set to 0.0 if ``fit_intercept = False``. alpha_ : float Estimated precision of the noise. lambda_ : float Estimated precision of the weights. sigma_ : array-like of shape (n_features, n_features) Estimated variance-covariance matrix of the weights scores_ : array-like of shape (n_iter_+1,) If computed_score is True, value of the log marginal likelihood (to be maximized) at each iteration of the optimization. The array starts with the value of the log marginal likelihood obtained for the initial values of alpha and lambda and ends with the value obtained for the estimated alpha and lambda. n_iter_ : int The actual number of iterations to reach the stopping criterion. X_offset_ : float If `normalize=True`, offset subtracted for centering data to a zero mean. X_scale_ : float If `normalize=True`, parameter used to scale data to a unit standard deviation. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 See Also -------- ARDRegression : Bayesian ARD regression. Notes ----- There exist several strategies to perform Bayesian ridge regression. This implementation is based on the algorithm described in Appendix A of (Tipping, 2001) where updates of the regularization parameters are done as suggested in (MacKay, 1992). Note that according to A New View of Automatic Relevance Determination (Wipf and Nagarajan, 2008) these update rules do not guarantee that the marginal likelihood is increasing between two consecutive iterations of the optimization. References ---------- D. J. C. MacKay, Bayesian Interpolation, Computation and Neural Systems, Vol. 4, No. 3, 1992. M. E. Tipping, Sparse Bayesian Learning and the Relevance Vector Machine, Journal of Machine Learning Research, Vol. 1, 2001. Examples -------- >>> from sklearn import linear_model >>> clf = linear_model.BayesianRidge() >>> clf.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2]) BayesianRidge() >>> clf.predict([[1, 1]]) array([1.]) """ def __init__( self, *, n_iter=300, tol=1.0e-3, alpha_1=1.0e-6, alpha_2=1.0e-6, lambda_1=1.0e-6, lambda_2=1.0e-6, alpha_init=None, lambda_init=None, compute_score=False, fit_intercept=True, normalize="deprecated", copy_X=True, verbose=False, ): self.n_iter = n_iter self.tol = tol self.alpha_1 = alpha_1 self.alpha_2 = alpha_2 self.lambda_1 = lambda_1 self.lambda_2 = lambda_2 self.alpha_init = alpha_init self.lambda_init = lambda_init self.compute_score = compute_score self.fit_intercept = fit_intercept self.normalize = normalize self.copy_X = copy_X self.verbose = verbose def fit(self, X, y, sample_weight=None): """Fit the model. Parameters ---------- X : ndarray of shape (n_samples, n_features) Training data. y : ndarray of shape (n_samples,) Target values. Will be cast to X's dtype if necessary. sample_weight : ndarray of shape (n_samples,), default=None Individual weights for each sample. .. versionadded:: 0.20 parameter *sample_weight* support to BayesianRidge. Returns ------- self : object Returns the instance itself. """ self._normalize = _deprecate_normalize( self.normalize, default=False, estimator_name=self.__class__.__name__ ) if self.n_iter < 1: raise ValueError( "n_iter should be greater than or equal to 1. Got {!r}.".format( self.n_iter ) ) X, y = self._validate_data(X, y, dtype=np.float64, y_numeric=True) if sample_weight is not None: sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) X, y, X_offset_, y_offset_, X_scale_ = self._preprocess_data( X, y, self.fit_intercept, self._normalize, self.copy_X, sample_weight=sample_weight, ) if sample_weight is not None: # Sample weight can be implemented via a simple rescaling. X, y = _rescale_data(X, y, sample_weight) self.X_offset_ = X_offset_ self.X_scale_ = X_scale_ n_samples, n_features = X.shape # Initialization of the values of the parameters eps = np.finfo(np.float64).eps # Add `eps` in the denominator to omit division by zero if `np.var(y)` # is zero alpha_ = self.alpha_init lambda_ = self.lambda_init if alpha_ is None: alpha_ = 1.0 / (np.var(y) + eps) if lambda_ is None: lambda_ = 1.0 verbose = self.verbose lambda_1 = self.lambda_1 lambda_2 = self.lambda_2 alpha_1 = self.alpha_1 alpha_2 = self.alpha_2 self.scores_ = list() coef_old_ = None XT_y = np.dot(X.T, y) U, S, Vh = linalg.svd(X, full_matrices=False) eigen_vals_ = S ** 2 # Convergence loop of the bayesian ridge regression for iter_ in range(self.n_iter): # update posterior mean coef_ based on alpha_ and lambda_ and # compute corresponding rmse coef_, rmse_ = self._update_coef_( X, y, n_samples, n_features, XT_y, U, Vh, eigen_vals_, alpha_, lambda_ ) if self.compute_score: # compute the log marginal likelihood s = self._log_marginal_likelihood( n_samples, n_features, eigen_vals_, alpha_, lambda_, coef_, rmse_ ) self.scores_.append(s) # Update alpha and lambda according to (MacKay, 1992) gamma_ = np.sum((alpha_ * eigen_vals_) / (lambda_ + alpha_ * eigen_vals_)) lambda_ = (gamma_ + 2 * lambda_1) / (np.sum(coef_ ** 2) + 2 * lambda_2) alpha_ = (n_samples - gamma_ + 2 * alpha_1) / (rmse_ + 2 * alpha_2) # Check for convergence if iter_ != 0 and np.sum(np.abs(coef_old_ - coef_)) < self.tol: if verbose: print("Convergence after ", str(iter_), " iterations") break coef_old_ = np.copy(coef_) self.n_iter_ = iter_ + 1 # return regularization parameters and corresponding posterior mean, # log marginal likelihood and posterior covariance self.alpha_ = alpha_ self.lambda_ = lambda_ self.coef_, rmse_ = self._update_coef_( X, y, n_samples, n_features, XT_y, U, Vh, eigen_vals_, alpha_, lambda_ ) if self.compute_score: # compute the log marginal likelihood s = self._log_marginal_likelihood( n_samples, n_features, eigen_vals_, alpha_, lambda_, coef_, rmse_ ) self.scores_.append(s) self.scores_ = np.array(self.scores_) # posterior covariance is given by 1/alpha_ * scaled_sigma_ scaled_sigma_ = np.dot( Vh.T, Vh / (eigen_vals_ + lambda_ / alpha_)[:, np.newaxis] ) self.sigma_ = (1.0 / alpha_) * scaled_sigma_ self._set_intercept(X_offset_, y_offset_, X_scale_) return self def predict(self, X, return_std=False): """Predict using the linear model. In addition to the mean of the predictive distribution, also its standard deviation can be returned. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Samples. return_std : bool, default=False Whether to return the standard deviation of posterior prediction. Returns ------- y_mean : array-like of shape (n_samples,) Mean of predictive distribution of query points. y_std : array-like of shape (n_samples,) Standard deviation of predictive distribution of query points. """ y_mean = self._decision_function(X) if return_std is False: return y_mean else: if self._normalize: X = (X - self.X_offset_) / self.X_scale_ sigmas_squared_data = (np.dot(X, self.sigma_) * X).sum(axis=1) y_std = np.sqrt(sigmas_squared_data + (1.0 / self.alpha_)) return y_mean, y_std def _update_coef_( self, X, y, n_samples, n_features, XT_y, U, Vh, eigen_vals_, alpha_, lambda_ ): """Update posterior mean and compute corresponding rmse. Posterior mean is given by coef_ = scaled_sigma_ * X.T * y where scaled_sigma_ = (lambda_/alpha_ * np.eye(n_features) + np.dot(X.T, X))^-1 """ if n_samples > n_features: coef_ = np.linalg.multi_dot( [Vh.T, Vh / (eigen_vals_ + lambda_ / alpha_)[:, np.newaxis], XT_y] ) else: coef_ = np.linalg.multi_dot( [X.T, U / (eigen_vals_ + lambda_ / alpha_)[None, :], U.T, y] ) rmse_ = np.sum((y - np.dot(X, coef_)) ** 2) return coef_, rmse_ def _log_marginal_likelihood( self, n_samples, n_features, eigen_vals, alpha_, lambda_, coef, rmse ): """Log marginal likelihood.""" alpha_1 = self.alpha_1 alpha_2 = self.alpha_2 lambda_1 = self.lambda_1 lambda_2 = self.lambda_2 # compute the log of the determinant of the posterior covariance. # posterior covariance is given by # sigma = (lambda_ * np.eye(n_features) + alpha_ * np.dot(X.T, X))^-1 if n_samples > n_features: logdet_sigma = -np.sum(np.log(lambda_ + alpha_ * eigen_vals)) else: logdet_sigma = np.full(n_features, lambda_, dtype=np.array(lambda_).dtype) logdet_sigma[:n_samples] += alpha_ * eigen_vals logdet_sigma = -np.sum(np.log(logdet_sigma)) score = lambda_1 * log(lambda_) - lambda_2 * lambda_ score += alpha_1 * log(alpha_) - alpha_2 * alpha_ score += 0.5 * ( n_features * log(lambda_) + n_samples * log(alpha_) - alpha_ * rmse - lambda_ * np.sum(coef ** 2) + logdet_sigma - n_samples * log(2 * np.pi) ) return score ############################################################################### # ARD (Automatic Relevance Determination) regression class ARDRegression(RegressorMixin, LinearModel): """Bayesian ARD regression. Fit the weights of a regression model, using an ARD prior. The weights of the regression model are assumed to be in Gaussian distributions. Also estimate the parameters lambda (precisions of the distributions of the weights) and alpha (precision of the distribution of the noise). The estimation is done by an iterative procedures (Evidence Maximization) Read more in the :ref:`User Guide <bayesian_regression>`. Parameters ---------- n_iter : int, default=300 Maximum number of iterations. tol : float, default=1e-3 Stop the algorithm if w has converged. alpha_1 : float, default=1e-6 Hyper-parameter : shape parameter for the Gamma distribution prior over the alpha parameter. alpha_2 : float, default=1e-6 Hyper-parameter : inverse scale parameter (rate parameter) for the Gamma distribution prior over the alpha parameter. lambda_1 : float, default=1e-6 Hyper-parameter : shape parameter for the Gamma distribution prior over the lambda parameter. lambda_2 : float, default=1e-6 Hyper-parameter : inverse scale parameter (rate parameter) for the Gamma distribution prior over the lambda parameter. compute_score : bool, default=False If True, compute the objective function at each step of the model. threshold_lambda : float, default=10 000 Threshold for removing (pruning) weights with high precision from the computation. fit_intercept : bool, default=True Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (i.e. data is expected to be centered). normalize : bool, default=False This parameter is ignored when ``fit_intercept`` is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use :class:`~sklearn.preprocessing.StandardScaler` before calling ``fit`` on an estimator with ``normalize=False``. .. deprecated:: 1.0 ``normalize`` was deprecated in version 1.0 and will be removed in 1.2. copy_X : bool, default=True If True, X will be copied; else, it may be overwritten. verbose : bool, default=False Verbose mode when fitting the model. Attributes ---------- coef_ : array-like of shape (n_features,) Coefficients of the regression model (mean of distribution) alpha_ : float estimated precision of the noise. lambda_ : array-like of shape (n_features,) estimated precisions of the weights. sigma_ : array-like of shape (n_features, n_features) estimated variance-covariance matrix of the weights scores_ : float if computed, value of the objective function (to be maximized) intercept_ : float Independent term in decision function. Set to 0.0 if ``fit_intercept = False``. X_offset_ : float If `normalize=True`, offset subtracted for centering data to a zero mean. X_scale_ : float If `normalize=True`, parameter used to scale data to a unit standard deviation. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 See Also -------- BayesianRidge : Bayesian ridge regression. Notes ----- For an example, see :ref:`examples/linear_model/plot_ard.py <sphx_glr_auto_examples_linear_model_plot_ard.py>`. References ---------- D. J. C. MacKay, Bayesian nonlinear modeling for the prediction competition, ASHRAE Transactions, 1994. R. Salakhutdinov, Lecture notes on Statistical Machine Learning, http://www.utstat.toronto.edu/~rsalakhu/sta4273/notes/Lecture2.pdf#page=15 Their beta is our ``self.alpha_`` Their alpha is our ``self.lambda_`` ARD is a little different than the slide: only dimensions/features for which ``self.lambda_ < self.threshold_lambda`` are kept and the rest are discarded. Examples -------- >>> from sklearn import linear_model >>> clf = linear_model.ARDRegression() >>> clf.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2]) ARDRegression() >>> clf.predict([[1, 1]]) array([1.]) """ def __init__( self, *, n_iter=300, tol=1.0e-3, alpha_1=1.0e-6, alpha_2=1.0e-6, lambda_1=1.0e-6, lambda_2=1.0e-6, compute_score=False, threshold_lambda=1.0e4, fit_intercept=True, normalize="deprecated", copy_X=True, verbose=False, ): self.n_iter = n_iter self.tol = tol self.fit_intercept = fit_intercept self.normalize = normalize self.alpha_1 = alpha_1 self.alpha_2 = alpha_2 self.lambda_1 = lambda_1 self.lambda_2 = lambda_2 self.compute_score = compute_score self.threshold_lambda = threshold_lambda self.copy_X = copy_X self.verbose = verbose def fit(self, X, y): """Fit the model according to the given training data and parameters. Iterative procedure to maximize the evidence Parameters ---------- X : array-like of shape (n_samples, n_features) Training vector, where n_samples in the number of samples and n_features is the number of features. y : array-like of shape (n_samples,) Target values (integers). Will be cast to X's dtype if necessary. Returns ------- self : object Fitted estimator. """ self._normalize = _deprecate_normalize( self.normalize, default=False, estimator_name=self.__class__.__name__ ) X, y = self._validate_data( X, y, dtype=np.float64, y_numeric=True, ensure_min_samples=2 ) n_samples, n_features = X.shape coef_ = np.zeros(n_features) X, y, X_offset_, y_offset_, X_scale_ = self._preprocess_data( X, y, self.fit_intercept, self._normalize, self.copy_X ) self.X_offset_ = X_offset_ self.X_scale_ = X_scale_ # Launch the convergence loop keep_lambda = np.ones(n_features, dtype=bool) lambda_1 = self.lambda_1 lambda_2 = self.lambda_2 alpha_1 = self.alpha_1 alpha_2 = self.alpha_2 verbose = self.verbose # Initialization of the values of the parameters eps = np.finfo(np.float64).eps # Add `eps` in the denominator to omit division by zero if `np.var(y)` # is zero alpha_ = 1.0 / (np.var(y) + eps) lambda_ = np.ones(n_features) self.scores_ = list() coef_old_ = None def update_coeff(X, y, coef_, alpha_, keep_lambda, sigma_): coef_[keep_lambda] = alpha_ * np.linalg.multi_dot( [sigma_, X[:, keep_lambda].T, y] ) return coef_ update_sigma = ( self._update_sigma if n_samples >= n_features else self._update_sigma_woodbury ) # Iterative procedure of ARDRegression for iter_ in range(self.n_iter): sigma_ = update_sigma(X, alpha_, lambda_, keep_lambda) coef_ = update_coeff(X, y, coef_, alpha_, keep_lambda, sigma_) # Update alpha and lambda rmse_ = np.sum((y - np.dot(X, coef_)) ** 2) gamma_ = 1.0 - lambda_[keep_lambda] * np.diag(sigma_) lambda_[keep_lambda] = (gamma_ + 2.0 * lambda_1) / ( (coef_[keep_lambda]) ** 2 + 2.0 * lambda_2 ) alpha_ = (n_samples - gamma_.sum() + 2.0 * alpha_1) / ( rmse_ + 2.0 * alpha_2 ) # Prune the weights with a precision over a threshold keep_lambda = lambda_ < self.threshold_lambda coef_[~keep_lambda] = 0 # Compute the objective function if self.compute_score: s = (lambda_1 * np.log(lambda_) - lambda_2 * lambda_).sum() s += alpha_1 * log(alpha_) - alpha_2 * alpha_ s += 0.5 * ( fast_logdet(sigma_) + n_samples * log(alpha_) + np.sum(np.log(lambda_)) ) s -= 0.5 * (alpha_ * rmse_ + (lambda_ * coef_ ** 2).sum()) self.scores_.append(s) # Check for convergence if iter_ > 0 and np.sum(np.abs(coef_old_ - coef_)) < self.tol: if verbose: print("Converged after %s iterations" % iter_) break coef_old_ = np.copy(coef_) if not keep_lambda.any(): break if keep_lambda.any(): # update sigma and mu using updated params from the last iteration sigma_ = update_sigma(X, alpha_, lambda_, keep_lambda) coef_ = update_coeff(X, y, coef_, alpha_, keep_lambda, sigma_) else: sigma_ = np.array([]).reshape(0, 0) self.coef_ = coef_ self.alpha_ = alpha_ self.sigma_ = sigma_ self.lambda_ = lambda_ self._set_intercept(X_offset_, y_offset_, X_scale_) return self def _update_sigma_woodbury(self, X, alpha_, lambda_, keep_lambda): # See slides as referenced in the docstring note # this function is used when n_samples < n_features and will invert # a matrix of shape (n_samples, n_samples) making use of the # woodbury formula: # https://en.wikipedia.org/wiki/Woodbury_matrix_identity n_samples = X.shape[0] X_keep = X[:, keep_lambda] inv_lambda = 1 / lambda_[keep_lambda].reshape(1, -1) sigma_ = pinvh( np.eye(n_samples) / alpha_ + np.dot(X_keep * inv_lambda, X_keep.T) ) sigma_ = np.dot(sigma_, X_keep * inv_lambda) sigma_ = -np.dot(inv_lambda.reshape(-1, 1) * X_keep.T, sigma_) sigma_[np.diag_indices(sigma_.shape[1])] += 1.0 / lambda_[keep_lambda] return sigma_ def _update_sigma(self, X, alpha_, lambda_, keep_lambda): # See slides as referenced in the docstring note # this function is used when n_samples >= n_features and will # invert a matrix of shape (n_features, n_features) X_keep = X[:, keep_lambda] gram = np.dot(X_keep.T, X_keep) eye = np.eye(gram.shape[0]) sigma_inv = lambda_[keep_lambda] * eye + alpha_ * gram sigma_ = pinvh(sigma_inv) return sigma_ def predict(self, X, return_std=False): """Predict using the linear model. In addition to the mean of the predictive distribution, also its standard deviation can be returned. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Samples. return_std : bool, default=False Whether to return the standard deviation of posterior prediction. Returns ------- y_mean : array-like of shape (n_samples,) Mean of predictive distribution of query points. y_std : array-like of shape (n_samples,) Standard deviation of predictive distribution of query points. """ y_mean = self._decision_function(X) if return_std is False: return y_mean else: if self._normalize: X = (X - self.X_offset_) / self.X_scale_ X = X[:, self.lambda_ < self.threshold_lambda] sigmas_squared_data = (np.dot(X, self.sigma_) * X).sum(axis=1) y_std = np.sqrt(sigmas_squared_data + (1.0 / self.alpha_)) return y_mean, y_std
shyamalschandra/scikit-learn
sklearn/linear_model/_bayes.py
Python
bsd-3-clause
26,416
0.000492
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' Provide the standard 147 CSS (X11) named colors. ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function, unicode_literals import logging log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Standard library imports # External imports # Bokeh imports from .util import NamedColor #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- aliceblue = NamedColor("aliceblue", 240, 248, 255) antiquewhite = NamedColor("antiquewhite", 250, 235, 215) aqua = NamedColor("aqua", 0, 255, 255) aquamarine = NamedColor("aquamarine", 127, 255, 212) azure = NamedColor("azure", 240, 255, 255) beige = NamedColor("beige", 245, 245, 220) bisque = NamedColor("bisque", 255, 228, 196) black = NamedColor("black", 0, 0, 0 ) blanchedalmond = NamedColor("blanchedalmond", 255, 235, 205) blue = NamedColor("blue", 0, 0, 255) blueviolet = NamedColor("blueviolet", 138, 43, 226) brown = NamedColor("brown", 165, 42, 42 ) burlywood = NamedColor("burlywood", 222, 184, 135) cadetblue = NamedColor("cadetblue", 95, 158, 160) chartreuse = NamedColor("chartreuse", 127, 255, 0 ) chocolate = NamedColor("chocolate", 210, 105, 30 ) coral = NamedColor("coral", 255, 127, 80 ) cornflowerblue = NamedColor("cornflowerblue", 100, 149, 237) cornsilk = NamedColor("cornsilk", 255, 248, 220) crimson = NamedColor("crimson", 220, 20, 60 ) cyan = NamedColor("cyan", 0, 255, 255) darkblue = NamedColor("darkblue", 0, 0, 139) darkcyan = NamedColor("darkcyan", 0, 139, 139) darkgoldenrod = NamedColor("darkgoldenrod", 184, 134, 11 ) darkgray = NamedColor("darkgray", 169, 169, 169) darkgreen = NamedColor("darkgreen", 0, 100, 0 ) darkgrey = NamedColor("darkgrey", 169, 169, 169) darkkhaki = NamedColor("darkkhaki", 189, 183, 107) darkmagenta = NamedColor("darkmagenta", 139, 0, 139) darkolivegreen = NamedColor("darkolivegreen", 85, 107, 47 ) darkorange = NamedColor("darkorange", 255, 140, 0 ) darkorchid = NamedColor("darkorchid", 153, 50, 204) darkred = NamedColor("darkred", 139, 0, 0 ) darksalmon = NamedColor("darksalmon", 233, 150, 122) darkseagreen = NamedColor("darkseagreen", 143, 188, 143) darkslateblue = NamedColor("darkslateblue", 72, 61, 139) darkslategray = NamedColor("darkslategray", 47, 79, 79 ) darkslategrey = NamedColor("darkslategrey", 47, 79, 79 ) darkturquoise = NamedColor("darkturquoise", 0, 206, 209) darkviolet = NamedColor("darkviolet", 148, 0, 211) deeppink = NamedColor("deeppink", 255, 20, 147) deepskyblue = NamedColor("deepskyblue", 0, 191, 255) dimgray = NamedColor("dimgray", 105, 105, 105) dimgrey = NamedColor("dimgrey", 105, 105, 105) dodgerblue = NamedColor("dodgerblue", 30, 144, 255) firebrick = NamedColor("firebrick", 178, 34, 34 ) floralwhite = NamedColor("floralwhite", 255, 250, 240) forestgreen = NamedColor("forestgreen", 34, 139, 34 ) fuchsia = NamedColor("fuchsia", 255, 0, 255) gainsboro = NamedColor("gainsboro", 220, 220, 220) ghostwhite = NamedColor("ghostwhite", 248, 248, 255) gold = NamedColor("gold", 255, 215, 0 ) goldenrod = NamedColor("goldenrod", 218, 165, 32 ) gray = NamedColor("gray", 128, 128, 128) green = NamedColor("green", 0, 128, 0 ) greenyellow = NamedColor("greenyellow", 173, 255, 47 ) grey = NamedColor("grey", 128, 128, 128) honeydew = NamedColor("honeydew", 240, 255, 240) hotpink = NamedColor("hotpink", 255, 105, 180) indianred = NamedColor("indianred", 205, 92, 92 ) indigo = NamedColor("indigo", 75, 0, 130) ivory = NamedColor("ivory", 255, 255, 240) khaki = NamedColor("khaki", 240, 230, 140) lavender = NamedColor("lavender", 230, 230, 250) lavenderblush = NamedColor("lavenderblush", 255, 240, 245) lawngreen = NamedColor("lawngreen", 124, 252, 0 ) lemonchiffon = NamedColor("lemonchiffon", 255, 250, 205) lightblue = NamedColor("lightblue", 173, 216, 230) lightcoral = NamedColor("lightcoral", 240, 128, 128) lightcyan = NamedColor("lightcyan", 224, 255, 255) lightgoldenrodyellow = NamedColor("lightgoldenrodyellow", 250, 250, 210) lightgray = NamedColor("lightgray", 211, 211, 211) lightgreen = NamedColor("lightgreen", 144, 238, 144) lightgrey = NamedColor("lightgrey", 211, 211, 211) lightpink = NamedColor("lightpink", 255, 182, 193) lightsalmon = NamedColor("lightsalmon", 255, 160, 122) lightseagreen = NamedColor("lightseagreen", 32, 178, 170) lightskyblue = NamedColor("lightskyblue", 135, 206, 250) lightslategray = NamedColor("lightslategray", 119, 136, 153) lightslategrey = NamedColor("lightslategrey", 119, 136, 153) lightsteelblue = NamedColor("lightsteelblue", 176, 196, 222) lightyellow = NamedColor("lightyellow", 255, 255, 224) lime = NamedColor("lime", 0, 255, 0 ) limegreen = NamedColor("limegreen", 50, 205, 50 ) linen = NamedColor("linen", 250, 240, 230) magenta = NamedColor("magenta", 255, 0, 255) maroon = NamedColor("maroon", 128, 0, 0 ) mediumaquamarine = NamedColor("mediumaquamarine", 102, 205, 170) mediumblue = NamedColor("mediumblue", 0, 0, 205) mediumorchid = NamedColor("mediumorchid", 186, 85, 211) mediumpurple = NamedColor("mediumpurple", 147, 112, 219) mediumseagreen = NamedColor("mediumseagreen", 60, 179, 113) mediumslateblue = NamedColor("mediumslateblue", 123, 104, 238) mediumspringgreen = NamedColor("mediumspringgreen", 0, 250, 154) mediumturquoise = NamedColor("mediumturquoise", 72, 209, 204) mediumvioletred = NamedColor("mediumvioletred", 199, 21, 133) midnightblue = NamedColor("midnightblue", 25, 25, 112) mintcream = NamedColor("mintcream", 245, 255, 250) mistyrose = NamedColor("mistyrose", 255, 228, 225) moccasin = NamedColor("moccasin", 255, 228, 181) navajowhite = NamedColor("navajowhite", 255, 222, 173) navy = NamedColor("navy", 0, 0, 128) oldlace = NamedColor("oldlace", 253, 245, 230) olive = NamedColor("olive", 128, 128, 0 ) olivedrab = NamedColor("olivedrab", 107, 142, 35 ) orange = NamedColor("orange", 255, 165, 0 ) orangered = NamedColor("orangered", 255, 69, 0 ) orchid = NamedColor("orchid", 218, 112, 214) palegoldenrod = NamedColor("palegoldenrod", 238, 232, 170) palegreen = NamedColor("palegreen", 152, 251, 152) paleturquoise = NamedColor("paleturquoise", 175, 238, 238) palevioletred = NamedColor("palevioletred", 219, 112, 147) papayawhip = NamedColor("papayawhip", 255, 239, 213) peachpuff = NamedColor("peachpuff", 255, 218, 185) peru = NamedColor("peru", 205, 133, 63 ) pink = NamedColor("pink", 255, 192, 203) plum = NamedColor("plum", 221, 160, 221) powderblue = NamedColor("powderblue", 176, 224, 230) purple = NamedColor("purple", 128, 0, 128) red = NamedColor("red", 255, 0, 0 ) rosybrown = NamedColor("rosybrown", 188, 143, 143) royalblue = NamedColor("royalblue", 65, 105, 225) saddlebrown = NamedColor("saddlebrown", 139, 69, 19 ) salmon = NamedColor("salmon", 250, 128, 114) sandybrown = NamedColor("sandybrown", 244, 164, 96 ) seagreen = NamedColor("seagreen", 46, 139, 87 ) seashell = NamedColor("seashell", 255, 245, 238) sienna = NamedColor("sienna", 160, 82, 45 ) silver = NamedColor("silver", 192, 192, 192) skyblue = NamedColor("skyblue", 135, 206, 235) slateblue = NamedColor("slateblue", 106, 90, 205) slategray = NamedColor("slategray", 112, 128, 144) slategrey = NamedColor("slategrey", 112, 128, 144) snow = NamedColor("snow", 255, 250, 250) springgreen = NamedColor("springgreen", 0, 255, 127) steelblue = NamedColor("steelblue", 70, 130, 180) tan = NamedColor("tan", 210, 180, 140) teal = NamedColor("teal", 0, 128, 128) thistle = NamedColor("thistle", 216, 191, 216) tomato = NamedColor("tomato", 255, 99, 71 ) turquoise = NamedColor("turquoise", 64, 224, 208) violet = NamedColor("violet", 238, 130, 238) wheat = NamedColor("wheat", 245, 222, 179) white = NamedColor("white", 255, 255, 255) whitesmoke = NamedColor("whitesmoke", 245, 245, 245) yellow = NamedColor("yellow", 255, 255, 0 ) yellowgreen = NamedColor("yellowgreen", 154, 205, 50 ) __all__ = NamedColor.__all__ #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
stonebig/bokeh
bokeh/colors/named.py
Python
bsd-3-clause
13,025
0.015432
import codecs import json import os import random import asyncio import re from cloudbot import hook from cloudbot.util import textgen @hook.on_start() def load_attacks(bot): """ :type bot: cloudbot.bot.CloudBot """ global larts, insults, flirts, kills, slaps, moms with codecs.open(os.path.join(bot.data_dir, "larts.json"), encoding="utf-8") as f: larts = json.load(f) with codecs.open(os.path.join(bot.data_dir, "flirts.json"), encoding="utf-8") as f: flirts = json.load(f) with codecs.open(os.path.join(bot.data_dir, "moms.json"), encoding="utf-8") as f: moms = json.load(f) with codecs.open(os.path.join(bot.data_dir, "kills.json"), encoding="utf-8") as f: kills = json.load(f) with codecs.open(os.path.join(bot.data_dir, "slaps.json"), encoding="utf-8") as f: slaps = json.load(f) def is_self(conn, target): """ :type conn: cloudbot.client.Client :type target: str """ if re.search("(^..?.?.?self|{})".format(re.escape(conn.nick.lower())), target.lower()): return True else: return False def get_attack_string(text, conn, nick, notice, attack_json, message): """ :type text: str :type conn: cloudbot.client.Client :type nick: str """ target = text.strip() if " " in target: notice("Invalid username!") return None # if the user is trying to make the bot target itself, target them if is_self(conn, target): target = nick permission_manager = conn.permissions if permission_manager.has_perm_nick(target, "unattackable"): generator = textgen.TextGenerator(flirts["templates"], flirts["parts"], variables={"user": target}) message(generator.generate_string()) return None else: generator = textgen.TextGenerator(attack_json["templates"], attack_json["parts"], variables={"user": target}) return generator.generate_string() @asyncio.coroutine @hook.command() def lart(text, conn, nick, notice, action, message): """<user> - LARTs <user> :type text: str :type conn: cloudbot.client.Client :type nick: str """ phrase = get_attack_string(text, conn, nick, notice, larts, message) if phrase is not None: action(phrase) @asyncio.coroutine @hook.command() def flirt(text, conn, nick, notice, action, message): """<user> - flirts with <user> :type text: str :type conn: cloudbot.client.Client :type nick: str """ phrase = get_attack_string(text, conn, nick, notice, flirts, message) if phrase is not None: message(phrase) @asyncio.coroutine @hook.command() def kill(text, conn, nick, notice, action, message): """<user> - kills <user> :type text: str :type conn: cloudbot.client.Client :type nick: str """ phrase = get_attack_string(text, conn, nick, notice, kills, message) if phrase is not None: action(phrase) @hook.command def slap(text, nick, conn, notice, action, message): """slap <user> -- Makes the bot slap <user>.""" phrase = get_attack_string(text, conn, nick, notice, slaps, message) if phrase is not None: action(phrase) @asyncio.coroutine @hook.command() def insult(text, conn, nick, notice, action, message): """<user> - insults <user> :type text: str :type conn: cloudbot.client.Client :type nick: str """ phrase = get_attack_string(text, conn, nick, notice, moms, message) if phrase is not None: message(phrase)
nidhididi/CloudBot
plugins/attacks.py
Python
gpl-3.0
3,577
0.00643
#!/usr/bin/python ########################################################### # # Copyright (c) 2008, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permission. # # # import unittest, sys # import the client lib sys.path.insert( 0, ".." ) from tactic_client_lib.interpreter import * class PipelineTest(unittest.TestCase): def test_all(my): my.test_handler = 'tactic_client_lib.test.TestHandler' my.pipeline_xml = ''' <pipeline> <process name='model'> <action class='%s'> <test>pig</test> <test2>cow</test2> </action> </process> <process name='texture'> <action class='%s'/> </process> <process name='rig'> <action class='tactic_client_lib.test.TestNextProcessHandler'/> </process> <process name='extra'/> <process name='extra2'/> <connect from='model' to='texture'/> <connect from='model' to='rig'/> <connect from='rig' to='publish'/> </pipeline> ''' % (my.test_handler, my.test_handler) my.pipeline = Pipeline(my.pipeline_xml) my._test_pipeline() my._test_interpreter() def _test_pipeline(my): # get the output names output_names = my.pipeline.get_output_process_names('model') my.assertEquals( ['texture', 'rig'], output_names ) # get the input names input_names = my.pipeline.get_input_process_names('texture') my.assertEquals( ['model'], input_names) # get the handler class of model handler_class = my.pipeline.get_handler_class('model') my.assertEquals( my.test_handler, handler_class) # small test running through pipeline process = my.pipeline.get_first_process_name() my.assertEquals( 'model', process) def _test_interpreter(my): # create a package to be delivered to each handler package = { 'company': 'Acme', 'city': 'Toronto', 'context': 'whatever' } # use client api from tactic_client_lib import TacticServerStub server = TacticServerStub() interpreter = PipelineInterpreter(my.pipeline_xml) interpreter.set_server(server) interpreter.set_package(package) interpreter.execute() # introspect the interpreter to see if everything ran well handlers = interpreter.get_handlers() process_names = [x.get_process_name() for x in handlers] expected = ['model', 'texture', 'rig', 'extra1', 'extra2'] my.assertEquals( expected, process_names ) # make sure all the handlers completed my.assertEquals( 5, len(handlers) ) for handler in handlers: my.assertEquals( "complete", handler.get_status() ) # check that the package is delivered to the input my.assertEquals("Acme", handler.get_input_value('company') ) my.assertEquals("Toronto", handler.get_input_value('city') ) process_name = handler.get_process_name() if process_name == 'model': my.assertEquals("Acme", handler.company) my.assertEquals("pig", handler.get_option_value('test') ) my.assertEquals("cow", handler.get_option_value('test2') ) # ensure input settings propogate if process_name == 'extra1': my.assertEquals("test.txt", handler.get_output_value('file')) my.assertEquals("Acme", handler.get_package_value('company')) if __name__ == "__main__": unittest.main()
rvanlaar/tactic-client
test/pipeline_test.py
Python
epl-1.0
3,879
0.006961
from werkzeug.security import generate_password_hash, check_password_hash def hash_pwd(password): return generate_password_hash(password) def check_password(hashed, password): return check_password_hash(hashed, password)
OVERLOADROBOTICA/OVERLOADROBOTICA.github.io
mail/formspree-master/formspree/users/helpers.py
Python
mit
231
0.008658
import webuntis import mock from webuntis.utils.third_party import json from .. import WebUntisTestCase, BytesIO class BasicUsage(WebUntisTestCase): def test_parse_result(self): x = webuntis.utils.remote._parse_result a = {'id': 2} b = {'id': 3} self.assertRaisesRegex(webuntis.errors.RemoteError, 'Request ID', x, a, b) a = b = {'id': 2} self.assertRaisesRegex(webuntis.errors.RemoteError, 'no information', x, a, b) a = {'id': 2} b = {'id': 2, 'result': 'YESSIR'} assert x(a, b) == 'YESSIR' def test_parse_error_code(self): x = webuntis.utils.remote._parse_error_code a = b = {} self.assertRaisesRegex(webuntis.errors.RemoteError, 'no information', x, a, b) b = {'error': {'code': 0, 'message': 'hello world'}} self.assertRaisesRegex(webuntis.errors.RemoteError, 'hello world', x, a, b) for code, exc in webuntis.utils.remote._errorcodes.items(): self.assertRaises(exc, x, a, { 'error': {'code': code, 'message': 'hello'} })
maphy-psd/python-webuntis
tests/utils/test_remote.py
Python
bsd-3-clause
1,228
0
# Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import copy import hashlib import multiprocessing import os.path import re import signal import subprocess import sys import gyp import gyp.common import gyp.msvs_emulation import gyp.MSVSVersion import gyp.xcode_emulation from gyp.common import GetEnvironFallback import gyp.ninja_syntax as ninja_syntax generator_default_variables = { 'EXECUTABLE_PREFIX': '', 'EXECUTABLE_SUFFIX': '', 'STATIC_LIB_PREFIX': 'lib', 'STATIC_LIB_SUFFIX': '.a', 'SHARED_LIB_PREFIX': 'lib', # Gyp expects the following variables to be expandable by the build # system to the appropriate locations. Ninja prefers paths to be # known at gyp time. To resolve this, introduce special # variables starting with $! and $| (which begin with a $ so gyp knows it # should be treated specially, but is otherwise an invalid # ninja/shell variable) that are passed to gyp here but expanded # before writing out into the target .ninja files; see # ExpandSpecial. # $! is used for variables that represent a path and that can only appear at # the start of a string, while $| is used for variables that can appear # anywhere in a string. 'INTERMEDIATE_DIR': '$!INTERMEDIATE_DIR', 'SHARED_INTERMEDIATE_DIR': '$!PRODUCT_DIR/gen', 'PRODUCT_DIR': '$!PRODUCT_DIR', 'CONFIGURATION_NAME': '$|CONFIGURATION_NAME', # Special variables that may be used by gyp 'rule' targets. # We generate definitions for these variables on the fly when processing a # rule. 'RULE_INPUT_ROOT': '${root}', 'RULE_INPUT_DIRNAME': '${dirname}', 'RULE_INPUT_PATH': '${source}', 'RULE_INPUT_EXT': '${ext}', 'RULE_INPUT_NAME': '${name}', } # Placates pylint. generator_additional_non_configuration_keys = [] generator_additional_path_sections = [] generator_extra_sources_for_rules = [] # TODO: figure out how to not build extra host objects in the non-cross-compile # case when this is enabled, and enable unconditionally. generator_supports_multiple_toolsets = ( os.environ.get('GYP_CROSSCOMPILE') or os.environ.get('AR_host') or os.environ.get('CC_host') or os.environ.get('CXX_host') or os.environ.get('AR_target') or os.environ.get('CC_target') or os.environ.get('CXX_target')) def StripPrefix(arg, prefix): if arg.startswith(prefix): return arg[len(prefix):] return arg def QuoteShellArgument(arg, flavor): """Quote a string such that it will be interpreted as a single argument by the shell.""" # Rather than attempting to enumerate the bad shell characters, just # whitelist common OK ones and quote anything else. if re.match(r'^[a-zA-Z0-9_=.\\/-]+$', arg): return arg # No quoting necessary. if flavor == 'win': return gyp.msvs_emulation.QuoteForRspFile(arg) return "'" + arg.replace("'", "'" + '"\'"' + "'") + "'" def Define(d, flavor): """Takes a preprocessor define and returns a -D parameter that's ninja- and shell-escaped.""" if flavor == 'win': # cl.exe replaces literal # characters with = in preprocesor definitions for # some reason. Octal-encode to work around that. d = d.replace('#', '\\%03o' % ord('#')) return QuoteShellArgument(ninja_syntax.escape('-D' + d), flavor) class Target: """Target represents the paths used within a single gyp target. Conceptually, building a single target A is a series of steps: 1) actions/rules/copies generates source/resources/etc. 2) compiles generates .o files 3) link generates a binary (library/executable) 4) bundle merges the above in a mac bundle (Any of these steps can be optional.) From a build ordering perspective, a dependent target B could just depend on the last output of this series of steps. But some dependent commands sometimes need to reach inside the box. For example, when linking B it needs to get the path to the static library generated by A. This object stores those paths. To keep things simple, member variables only store concrete paths to single files, while methods compute derived values like "the last output of the target". """ def __init__(self, type): # Gyp type ("static_library", etc.) of this target. self.type = type # File representing whether any input dependencies necessary for # dependent actions have completed. self.preaction_stamp = None # File representing whether any input dependencies necessary for # dependent compiles have completed. self.precompile_stamp = None # File representing the completion of actions/rules/copies, if any. self.actions_stamp = None # Path to the output of the link step, if any. self.binary = None # Path to the file representing the completion of building the bundle, # if any. self.bundle = None # On Windows, incremental linking requires linking against all the .objs # that compose a .lib (rather than the .lib itself). That list is stored # here. self.component_objs = None # Windows only. The import .lib is the output of a build step, but # because dependents only link against the lib (not both the lib and the # dll) we keep track of the import library here. self.import_lib = None def Linkable(self): """Return true if this is a target that can be linked against.""" return self.type in ('static_library', 'shared_library') def UsesToc(self, flavor): """Return true if the target should produce a restat rule based on a TOC file.""" # For bundles, the .TOC should be produced for the binary, not for # FinalOutput(). But the naive approach would put the TOC file into the # bundle, so don't do this for bundles for now. if flavor == 'win' or self.bundle: return False return self.type in ('shared_library', 'loadable_module') def PreActionInput(self, flavor): """Return the path, if any, that should be used as a dependency of any dependent action step.""" if self.UsesToc(flavor): return self.FinalOutput() + '.TOC' return self.FinalOutput() or self.preaction_stamp def PreCompileInput(self): """Return the path, if any, that should be used as a dependency of any dependent compile step.""" return self.actions_stamp or self.precompile_stamp def FinalOutput(self): """Return the last output of the target, which depends on all prior steps.""" return self.bundle or self.binary or self.actions_stamp # A small discourse on paths as used within the Ninja build: # All files we produce (both at gyp and at build time) appear in the # build directory (e.g. out/Debug). # # Paths within a given .gyp file are always relative to the directory # containing the .gyp file. Call these "gyp paths". This includes # sources as well as the starting directory a given gyp rule/action # expects to be run from. We call the path from the source root to # the gyp file the "base directory" within the per-.gyp-file # NinjaWriter code. # # All paths as written into the .ninja files are relative to the build # directory. Call these paths "ninja paths". # # We translate between these two notions of paths with two helper # functions: # # - GypPathToNinja translates a gyp path (i.e. relative to the .gyp file) # into the equivalent ninja path. # # - GypPathToUniqueOutput translates a gyp path into a ninja path to write # an output file; the result can be namespaced such that it is unique # to the input file name as well as the output target name. class NinjaWriter: def __init__(self, qualified_target, target_outputs, base_dir, build_dir, output_file, flavor, toplevel_dir=None): """ base_dir: path from source root to directory containing this gyp file, by gyp semantics, all input paths are relative to this build_dir: path from source root to build output toplevel_dir: path to the toplevel directory """ self.qualified_target = qualified_target self.target_outputs = target_outputs self.base_dir = base_dir self.build_dir = build_dir self.ninja = ninja_syntax.Writer(output_file) self.flavor = flavor self.abs_build_dir = None if toplevel_dir is not None: self.abs_build_dir = os.path.abspath(os.path.join(toplevel_dir, build_dir)) self.obj_ext = '.obj' if flavor == 'win' else '.o' if flavor == 'win': # See docstring of msvs_emulation.GenerateEnvironmentFiles(). self.win_env = {} for arch in ('x86', 'x64'): self.win_env[arch] = 'environment.' + arch # Relative path from build output dir to base dir. build_to_top = gyp.common.InvertRelativePath(build_dir, toplevel_dir) self.build_to_base = os.path.join(build_to_top, base_dir) # Relative path from base dir to build dir. base_to_top = gyp.common.InvertRelativePath(base_dir, toplevel_dir) self.base_to_build = os.path.join(base_to_top, build_dir) def ExpandSpecial(self, path, product_dir=None): """Expand specials like $!PRODUCT_DIR in |path|. If |product_dir| is None, assumes the cwd is already the product dir. Otherwise, |product_dir| is the relative path to the product dir. """ PRODUCT_DIR = '$!PRODUCT_DIR' if PRODUCT_DIR in path: if product_dir: path = path.replace(PRODUCT_DIR, product_dir) else: path = path.replace(PRODUCT_DIR + '/', '') path = path.replace(PRODUCT_DIR + '\\', '') path = path.replace(PRODUCT_DIR, '.') INTERMEDIATE_DIR = '$!INTERMEDIATE_DIR' if INTERMEDIATE_DIR in path: int_dir = self.GypPathToUniqueOutput('gen') # GypPathToUniqueOutput generates a path relative to the product dir, # so insert product_dir in front if it is provided. path = path.replace(INTERMEDIATE_DIR, os.path.join(product_dir or '', int_dir)) CONFIGURATION_NAME = '$|CONFIGURATION_NAME' path = path.replace(CONFIGURATION_NAME, self.config_name) return path def ExpandRuleVariables(self, path, root, dirname, source, ext, name): if self.flavor == 'win': path = self.msvs_settings.ConvertVSMacros( path, config=self.config_name) path = path.replace(generator_default_variables['RULE_INPUT_ROOT'], root) path = path.replace(generator_default_variables['RULE_INPUT_DIRNAME'], dirname) path = path.replace(generator_default_variables['RULE_INPUT_PATH'], source) path = path.replace(generator_default_variables['RULE_INPUT_EXT'], ext) path = path.replace(generator_default_variables['RULE_INPUT_NAME'], name) return path def GypPathToNinja(self, path, env=None): """Translate a gyp path to a ninja path, optionally expanding environment variable references in |path| with |env|. See the above discourse on path conversions.""" if env: if self.flavor == 'mac': path = gyp.xcode_emulation.ExpandEnvVars(path, env) elif self.flavor == 'win': path = gyp.msvs_emulation.ExpandMacros(path, env) if path.startswith('$!'): expanded = self.ExpandSpecial(path) if self.flavor == 'win': expanded = os.path.normpath(expanded) return expanded if '$|' in path: path = self.ExpandSpecial(path) assert '$' not in path, path return os.path.normpath(os.path.join(self.build_to_base, path)) def GypPathToUniqueOutput(self, path, qualified=True): """Translate a gyp path to a ninja path for writing output. If qualified is True, qualify the resulting filename with the name of the target. This is necessary when e.g. compiling the same path twice for two separate output targets. See the above discourse on path conversions.""" path = self.ExpandSpecial(path) assert not path.startswith('$'), path # Translate the path following this scheme: # Input: foo/bar.gyp, target targ, references baz/out.o # Output: obj/foo/baz/targ.out.o (if qualified) # obj/foo/baz/out.o (otherwise) # (and obj.host instead of obj for cross-compiles) # # Why this scheme and not some other one? # 1) for a given input, you can compute all derived outputs by matching # its path, even if the input is brought via a gyp file with '..'. # 2) simple files like libraries and stamps have a simple filename. obj = 'obj' if self.toolset != 'target': obj += '.' + self.toolset path_dir, path_basename = os.path.split(path) if qualified: path_basename = self.name + '.' + path_basename return os.path.normpath(os.path.join(obj, self.base_dir, path_dir, path_basename)) def WriteCollapsedDependencies(self, name, targets): """Given a list of targets, return a path for a single file representing the result of building all the targets or None. Uses a stamp file if necessary.""" assert targets == filter(None, targets), targets if len(targets) == 0: return None if len(targets) > 1: stamp = self.GypPathToUniqueOutput(name + '.stamp') targets = self.ninja.build(stamp, 'stamp', targets) self.ninja.newline() return targets[0] def WriteSpec(self, spec, config_name, generator_flags, case_sensitive_filesystem): """The main entry point for NinjaWriter: write the build rules for a spec. Returns a Target object, which represents the output paths for this spec. Returns None if there are no outputs (e.g. a settings-only 'none' type target).""" self.config_name = config_name self.name = spec['target_name'] self.toolset = spec['toolset'] config = spec['configurations'][config_name] self.target = Target(spec['type']) self.is_standalone_static_library = bool( spec.get('standalone_static_library', 0)) self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec) self.xcode_settings = self.msvs_settings = None if self.flavor == 'mac': self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec) if self.flavor == 'win': self.msvs_settings = gyp.msvs_emulation.MsvsSettings(spec, generator_flags) arch = self.msvs_settings.GetArch(config_name) self.ninja.variable('arch', self.win_env[arch]) # Compute predepends for all rules. # actions_depends is the dependencies this target depends on before running # any of its action/rule/copy steps. # compile_depends is the dependencies this target depends on before running # any of its compile steps. actions_depends = [] compile_depends = [] # TODO(evan): it is rather confusing which things are lists and which # are strings. Fix these. if 'dependencies' in spec: for dep in spec['dependencies']: if dep in self.target_outputs: target = self.target_outputs[dep] actions_depends.append(target.PreActionInput(self.flavor)) compile_depends.append(target.PreCompileInput()) actions_depends = filter(None, actions_depends) compile_depends = filter(None, compile_depends) actions_depends = self.WriteCollapsedDependencies('actions_depends', actions_depends) compile_depends = self.WriteCollapsedDependencies('compile_depends', compile_depends) self.target.preaction_stamp = actions_depends self.target.precompile_stamp = compile_depends # Write out actions, rules, and copies. These must happen before we # compile any sources, so compute a list of predependencies for sources # while we do it. extra_sources = [] mac_bundle_depends = [] self.target.actions_stamp = self.WriteActionsRulesCopies( spec, extra_sources, actions_depends, mac_bundle_depends) # If we have actions/rules/copies, we depend directly on those, but # otherwise we depend on dependent target's actions/rules/copies etc. # We never need to explicitly depend on previous target's link steps, # because no compile ever depends on them. compile_depends_stamp = (self.target.actions_stamp or compile_depends) # Write out the compilation steps, if any. link_deps = [] sources = spec.get('sources', []) + extra_sources if sources: pch = None if self.flavor == 'win': gyp.msvs_emulation.VerifyMissingSources( sources, self.abs_build_dir, generator_flags, self.GypPathToNinja) pch = gyp.msvs_emulation.PrecompiledHeader( self.msvs_settings, config_name, self.GypPathToNinja) else: pch = gyp.xcode_emulation.MacPrefixHeader( self.xcode_settings, self.GypPathToNinja, lambda path, lang: self.GypPathToUniqueOutput(path + '-' + lang)) link_deps = self.WriteSources( config_name, config, sources, compile_depends_stamp, pch, case_sensitive_filesystem, spec) # Some actions/rules output 'sources' that are already object files. link_deps += [self.GypPathToNinja(f) for f in sources if f.endswith(self.obj_ext)] if self.flavor == 'win' and self.target.type == 'static_library': self.target.component_objs = link_deps # Write out a link step, if needed. output = None if link_deps or self.target.actions_stamp or actions_depends: output = self.WriteTarget(spec, config_name, config, link_deps, self.target.actions_stamp or actions_depends) if self.is_mac_bundle: mac_bundle_depends.append(output) # Bundle all of the above together, if needed. if self.is_mac_bundle: output = self.WriteMacBundle(spec, mac_bundle_depends) if not output: return None assert self.target.FinalOutput(), output return self.target def _WinIdlRule(self, source, prebuild, outputs): """Handle the implicit VS .idl rule for one source file. Fills |outputs| with files that are generated.""" outdir, output, vars, flags = self.msvs_settings.GetIdlBuildData( source, self.config_name) outdir = self.GypPathToNinja(outdir) def fix_path(path, rel=None): path = os.path.join(outdir, path) dirname, basename = os.path.split(source) root, ext = os.path.splitext(basename) path = self.ExpandRuleVariables( path, root, dirname, source, ext, basename) if rel: path = os.path.relpath(path, rel) return path vars = [(name, fix_path(value, outdir)) for name, value in vars] output = [fix_path(p) for p in output] vars.append(('outdir', outdir)) vars.append(('idlflags', flags)) input = self.GypPathToNinja(source) self.ninja.build(output, 'idl', input, variables=vars, order_only=prebuild) outputs.extend(output) def WriteWinIdlFiles(self, spec, prebuild): """Writes rules to match MSVS's implicit idl handling.""" assert self.flavor == 'win' if self.msvs_settings.HasExplicitIdlRules(spec): return [] outputs = [] for source in filter(lambda x: x.endswith('.idl'), spec['sources']): self._WinIdlRule(source, prebuild, outputs) return outputs def WriteActionsRulesCopies(self, spec, extra_sources, prebuild, mac_bundle_depends): """Write out the Actions, Rules, and Copies steps. Return a path representing the outputs of these steps.""" outputs = [] extra_mac_bundle_resources = [] if 'actions' in spec: outputs += self.WriteActions(spec['actions'], extra_sources, prebuild, extra_mac_bundle_resources) if 'rules' in spec: outputs += self.WriteRules(spec['rules'], extra_sources, prebuild, extra_mac_bundle_resources) if 'copies' in spec: outputs += self.WriteCopies(spec['copies'], prebuild, mac_bundle_depends) if 'sources' in spec and self.flavor == 'win': outputs += self.WriteWinIdlFiles(spec, prebuild) stamp = self.WriteCollapsedDependencies('actions_rules_copies', outputs) if self.is_mac_bundle: mac_bundle_resources = spec.get('mac_bundle_resources', []) + \ extra_mac_bundle_resources self.WriteMacBundleResources(mac_bundle_resources, mac_bundle_depends) self.WriteMacInfoPlist(mac_bundle_depends) return stamp def GenerateDescription(self, verb, message, fallback): """Generate and return a description of a build step. |verb| is the short summary, e.g. ACTION or RULE. |message| is a hand-written description, or None if not available. |fallback| is the gyp-level name of the step, usable as a fallback. """ if self.toolset != 'target': verb += '(%s)' % self.toolset if message: return '%s %s' % (verb, self.ExpandSpecial(message)) else: return '%s %s: %s' % (verb, self.name, fallback) def WriteActions(self, actions, extra_sources, prebuild, extra_mac_bundle_resources): # Actions cd into the base directory. env = self.GetSortedXcodeEnv() if self.flavor == 'win': env = self.msvs_settings.GetVSMacroEnv( '$!PRODUCT_DIR', config=self.config_name) all_outputs = [] for action in actions: # First write out a rule for the action. name = '%s_%s' % (action['action_name'], hashlib.md5(self.qualified_target).hexdigest()) description = self.GenerateDescription('ACTION', action.get('message', None), name) is_cygwin = (self.msvs_settings.IsRuleRunUnderCygwin(action) if self.flavor == 'win' else False) args = action['action'] rule_name, _ = self.WriteNewNinjaRule(name, args, description, is_cygwin, env=env) inputs = [self.GypPathToNinja(i, env) for i in action['inputs']] if int(action.get('process_outputs_as_sources', False)): extra_sources += action['outputs'] if int(action.get('process_outputs_as_mac_bundle_resources', False)): extra_mac_bundle_resources += action['outputs'] outputs = [self.GypPathToNinja(o, env) for o in action['outputs']] # Then write out an edge using the rule. self.ninja.build(outputs, rule_name, inputs, order_only=prebuild) all_outputs += outputs self.ninja.newline() return all_outputs def WriteRules(self, rules, extra_sources, prebuild, extra_mac_bundle_resources): env = self.GetSortedXcodeEnv() all_outputs = [] for rule in rules: # First write out a rule for the rule action. name = '%s_%s' % (rule['rule_name'], hashlib.md5(self.qualified_target).hexdigest()) # Skip a rule with no action and no inputs. if 'action' not in rule and not rule.get('rule_sources', []): continue args = rule['action'] description = self.GenerateDescription( 'RULE', rule.get('message', None), ('%s ' + generator_default_variables['RULE_INPUT_PATH']) % name) is_cygwin = (self.msvs_settings.IsRuleRunUnderCygwin(rule) if self.flavor == 'win' else False) rule_name, args = self.WriteNewNinjaRule( name, args, description, is_cygwin, env=env) # TODO: if the command references the outputs directly, we should # simplify it to just use $out. # Rules can potentially make use of some special variables which # must vary per source file. # Compute the list of variables we'll need to provide. special_locals = ('source', 'root', 'dirname', 'ext', 'name') needed_variables = set(['source']) for argument in args: for var in special_locals: if ('${%s}' % var) in argument: needed_variables.add(var) def cygwin_munge(path): if is_cygwin: return path.replace('\\', '/') return path # For each source file, write an edge that generates all the outputs. for source in rule.get('rule_sources', []): dirname, basename = os.path.split(source) root, ext = os.path.splitext(basename) # Gather the list of inputs and outputs, expanding $vars if possible. outputs = [self.ExpandRuleVariables(o, root, dirname, source, ext, basename) for o in rule['outputs']] inputs = [self.ExpandRuleVariables(i, root, dirname, source, ext, basename) for i in rule.get('inputs', [])] if int(rule.get('process_outputs_as_sources', False)): extra_sources += outputs if int(rule.get('process_outputs_as_mac_bundle_resources', False)): extra_mac_bundle_resources += outputs extra_bindings = [] for var in needed_variables: if var == 'root': extra_bindings.append(('root', cygwin_munge(root))) elif var == 'dirname': extra_bindings.append(('dirname', cygwin_munge(dirname))) elif var == 'source': # '$source' is a parameter to the rule action, which means # it shouldn't be converted to a Ninja path. But we don't # want $!PRODUCT_DIR in there either. source_expanded = self.ExpandSpecial(source, self.base_to_build) extra_bindings.append(('source', cygwin_munge(source_expanded))) elif var == 'ext': extra_bindings.append(('ext', ext)) elif var == 'name': extra_bindings.append(('name', cygwin_munge(basename))) else: assert var == None, repr(var) inputs = [self.GypPathToNinja(i, env) for i in inputs] outputs = [self.GypPathToNinja(o, env) for o in outputs] extra_bindings.append(('unique_name', hashlib.md5(outputs[0]).hexdigest())) self.ninja.build(outputs, rule_name, self.GypPathToNinja(source), implicit=inputs, order_only=prebuild, variables=extra_bindings) all_outputs.extend(outputs) return all_outputs def WriteCopies(self, copies, prebuild, mac_bundle_depends): outputs = [] env = self.GetSortedXcodeEnv() for copy in copies: for path in copy['files']: # Normalize the path so trailing slashes don't confuse us. path = os.path.normpath(path) basename = os.path.split(path)[1] src = self.GypPathToNinja(path, env) dst = self.GypPathToNinja(os.path.join(copy['destination'], basename), env) outputs += self.ninja.build(dst, 'copy', src, order_only=prebuild) if self.is_mac_bundle: # gyp has mac_bundle_resources to copy things into a bundle's # Resources folder, but there's no built-in way to copy files to other # places in the bundle. Hence, some targets use copies for this. Check # if this file is copied into the current bundle, and if so add it to # the bundle depends so that dependent targets get rebuilt if the copy # input changes. if dst.startswith(self.xcode_settings.GetBundleContentsFolderPath()): mac_bundle_depends.append(dst) return outputs def WriteMacBundleResources(self, resources, bundle_depends): """Writes ninja edges for 'mac_bundle_resources'.""" for output, res in gyp.xcode_emulation.GetMacBundleResources( self.ExpandSpecial(generator_default_variables['PRODUCT_DIR']), self.xcode_settings, map(self.GypPathToNinja, resources)): self.ninja.build(output, 'mac_tool', res, variables=[('mactool_cmd', 'copy-bundle-resource')]) bundle_depends.append(output) def WriteMacInfoPlist(self, bundle_depends): """Write build rules for bundle Info.plist files.""" info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist( self.ExpandSpecial(generator_default_variables['PRODUCT_DIR']), self.xcode_settings, self.GypPathToNinja) if not info_plist: return if defines: # Create an intermediate file to store preprocessed results. intermediate_plist = self.GypPathToUniqueOutput( os.path.basename(info_plist)) defines = ' '.join([Define(d, self.flavor) for d in defines]) info_plist = self.ninja.build(intermediate_plist, 'infoplist', info_plist, variables=[('defines',defines)]) env = self.GetSortedXcodeEnv(additional_settings=extra_env) env = self.ComputeExportEnvString(env) self.ninja.build(out, 'mac_tool', info_plist, variables=[('mactool_cmd', 'copy-info-plist'), ('env', env)]) bundle_depends.append(out) def WriteSources(self, config_name, config, sources, predepends, precompiled_header, case_sensitive_filesystem, spec): """Write build rules to compile all of |sources|.""" if self.toolset == 'host': self.ninja.variable('ar', '$ar_host') self.ninja.variable('cc', '$cc_host') self.ninja.variable('cxx', '$cxx_host') self.ninja.variable('ld', '$ld_host') extra_defines = [] if self.flavor == 'mac': cflags = self.xcode_settings.GetCflags(config_name) cflags_c = self.xcode_settings.GetCflagsC(config_name) cflags_cc = self.xcode_settings.GetCflagsCC(config_name) cflags_objc = ['$cflags_c'] + \ self.xcode_settings.GetCflagsObjC(config_name) cflags_objcc = ['$cflags_cc'] + \ self.xcode_settings.GetCflagsObjCC(config_name) elif self.flavor == 'win': cflags = self.msvs_settings.GetCflags(config_name) cflags_c = self.msvs_settings.GetCflagsC(config_name) cflags_cc = self.msvs_settings.GetCflagsCC(config_name) extra_defines = self.msvs_settings.GetComputedDefines(config_name) pdbpath = self.msvs_settings.GetCompilerPdbName( config_name, self.ExpandSpecial) if not pdbpath: obj = 'obj' if self.toolset != 'target': obj += '.' + self.toolset pdbpath = os.path.normpath(os.path.join(obj, self.base_dir, self.name + '.pdb')) self.WriteVariableList('pdbname', [pdbpath]) self.WriteVariableList('pchprefix', [self.name]) else: cflags = config.get('cflags', []) cflags_c = config.get('cflags_c', []) cflags_cc = config.get('cflags_cc', []) defines = config.get('defines', []) + extra_defines self.WriteVariableList('defines', [Define(d, self.flavor) for d in defines]) if self.flavor == 'win': self.WriteVariableList('rcflags', [QuoteShellArgument(self.ExpandSpecial(f), self.flavor) for f in self.msvs_settings.GetRcflags(config_name, self.GypPathToNinja)]) include_dirs = config.get('include_dirs', []) if self.flavor == 'win': include_dirs = self.msvs_settings.AdjustIncludeDirs(include_dirs, config_name) self.WriteVariableList('includes', [QuoteShellArgument('-I' + self.GypPathToNinja(i), self.flavor) for i in include_dirs]) pch_commands = precompiled_header.GetPchBuildCommands() if self.flavor == 'mac': self.WriteVariableList('cflags_pch_c', [precompiled_header.GetInclude('c')]) self.WriteVariableList('cflags_pch_cc', [precompiled_header.GetInclude('cc')]) self.WriteVariableList('cflags_pch_objc', [precompiled_header.GetInclude('m')]) self.WriteVariableList('cflags_pch_objcc', [precompiled_header.GetInclude('mm')]) self.WriteVariableList('cflags', map(self.ExpandSpecial, cflags)) self.WriteVariableList('cflags_c', map(self.ExpandSpecial, cflags_c)) self.WriteVariableList('cflags_cc', map(self.ExpandSpecial, cflags_cc)) if self.flavor == 'mac': self.WriteVariableList('cflags_objc', map(self.ExpandSpecial, cflags_objc)) self.WriteVariableList('cflags_objcc', map(self.ExpandSpecial, cflags_objcc)) self.ninja.newline() outputs = [] for source in sources: filename, ext = os.path.splitext(source) ext = ext[1:] obj_ext = self.obj_ext if ext in ('cc', 'cpp', 'cxx'): command = 'cxx' elif ext == 'c' or (ext == 'S' and self.flavor != 'win'): command = 'cc' elif ext == 's' and self.flavor != 'win': # Doesn't generate .o.d files. command = 'cc_s' elif (self.flavor == 'win' and ext == 'asm' and self.msvs_settings.GetArch(config_name) == 'x86' and not self.msvs_settings.HasExplicitAsmRules(spec)): # Asm files only get auto assembled for x86 (not x64). command = 'asm' # Add the _asm suffix as msvs is capable of handling .cc and # .asm files of the same name without collision. obj_ext = '_asm.obj' elif self.flavor == 'mac' and ext == 'm': command = 'objc' elif self.flavor == 'mac' and ext == 'mm': command = 'objcxx' elif self.flavor == 'win' and ext == 'rc': command = 'rc' obj_ext = '.res' else: # Ignore unhandled extensions. continue input = self.GypPathToNinja(source) output = self.GypPathToUniqueOutput(filename + obj_ext) # Ninja's depfile handling gets confused when the case of a filename # changes on a case-insensitive file system. To work around that, always # convert .o filenames to lowercase on such file systems. See # https://github.com/martine/ninja/issues/402 for details. if not case_sensitive_filesystem: output = output.lower() implicit = precompiled_header.GetObjDependencies([input], [output]) self.ninja.build(output, command, input, implicit=[gch for _, _, gch in implicit], order_only=predepends) outputs.append(output) self.WritePchTargets(pch_commands) self.ninja.newline() return outputs def WritePchTargets(self, pch_commands): """Writes ninja rules to compile prefix headers.""" if not pch_commands: return for gch, lang_flag, lang, input in pch_commands: var_name = { 'c': 'cflags_pch_c', 'cc': 'cflags_pch_cc', 'm': 'cflags_pch_objc', 'mm': 'cflags_pch_objcc', }[lang] map = { 'c': 'cc', 'cc': 'cxx', 'm': 'objc', 'mm': 'objcxx', } if self.flavor == 'win': map.update({'c': 'cc_pch', 'cc': 'cxx_pch'}) cmd = map.get(lang) self.ninja.build(gch, cmd, input, variables=[(var_name, lang_flag)]) def WriteLink(self, spec, config_name, config, link_deps): """Write out a link step. Fills out target.binary. """ command = { 'executable': 'link', 'loadable_module': 'solink_module', 'shared_library': 'solink', }[spec['type']] implicit_deps = set() solibs = set() if 'dependencies' in spec: # Two kinds of dependencies: # - Linkable dependencies (like a .a or a .so): add them to the link line. # - Non-linkable dependencies (like a rule that generates a file # and writes a stamp file): add them to implicit_deps extra_link_deps = set() for dep in spec['dependencies']: target = self.target_outputs.get(dep) if not target: continue linkable = target.Linkable() if linkable: if (self.flavor == 'win' and target.component_objs and self.msvs_settings.IsUseLibraryDependencyInputs(config_name)): extra_link_deps |= set(target.component_objs) elif self.flavor == 'win' and target.import_lib: extra_link_deps.add(target.import_lib) elif target.UsesToc(self.flavor): solibs.add(target.binary) implicit_deps.add(target.binary + '.TOC') else: extra_link_deps.add(target.binary) final_output = target.FinalOutput() if not linkable or final_output != target.binary: implicit_deps.add(final_output) link_deps.extend(list(extra_link_deps)) extra_bindings = [] if self.is_mac_bundle: output = self.ComputeMacBundleBinaryOutput() else: output = self.ComputeOutput(spec) extra_bindings.append(('postbuilds', self.GetPostbuildCommand(spec, output, output))) is_executable = spec['type'] == 'executable' if self.flavor == 'mac': ldflags = self.xcode_settings.GetLdflags(config_name, self.ExpandSpecial(generator_default_variables['PRODUCT_DIR']), self.GypPathToNinja) elif self.flavor == 'win': manifest_name = self.GypPathToUniqueOutput( self.ComputeOutputFileName(spec)) ldflags, manifest_files = self.msvs_settings.GetLdflags(config_name, self.GypPathToNinja, self.ExpandSpecial, manifest_name, is_executable) self.WriteVariableList('manifests', manifest_files) else: ldflags = config.get('ldflags', []) if is_executable and len(solibs): ldflags.append('-Wl,-rpath=\$$ORIGIN/lib/') self.WriteVariableList('ldflags', gyp.common.uniquer(map(self.ExpandSpecial, ldflags))) libraries = gyp.common.uniquer(map(self.ExpandSpecial, spec.get('libraries', []))) if self.flavor == 'mac': libraries = self.xcode_settings.AdjustLibraries(libraries) elif self.flavor == 'win': libraries = self.msvs_settings.AdjustLibraries(libraries) self.WriteVariableList('libs', libraries) self.target.binary = output if command in ('solink', 'solink_module'): extra_bindings.append(('soname', os.path.split(output)[1])) extra_bindings.append(('lib', gyp.common.EncodePOSIXShellArgument(output))) if self.flavor == 'win': extra_bindings.append(('dll', output)) if '/NOENTRY' not in ldflags: self.target.import_lib = output + '.lib' extra_bindings.append(('implibflag', '/IMPLIB:%s' % self.target.import_lib)) output = [output, self.target.import_lib] else: output = [output, output + '.TOC'] if len(solibs): extra_bindings.append(('solibs', gyp.common.EncodePOSIXShellList(solibs))) self.ninja.build(output, command, link_deps, implicit=list(implicit_deps), variables=extra_bindings) def WriteTarget(self, spec, config_name, config, link_deps, compile_deps): if spec['type'] == 'none': # TODO(evan): don't call this function for 'none' target types, as # it doesn't do anything, and we fake out a 'binary' with a stamp file. self.target.binary = compile_deps elif spec['type'] == 'static_library': self.target.binary = self.ComputeOutput(spec) variables = [] postbuild = self.GetPostbuildCommand( spec, self.target.binary, self.target.binary) if postbuild: variables.append(('postbuilds', postbuild)) if self.xcode_settings: variables.append(('libtool_flags', self.xcode_settings.GetLibtoolflags(config_name))) if (self.flavor not in ('mac', 'win') and not self.is_standalone_static_library): self.ninja.build(self.target.binary, 'alink_thin', link_deps, order_only=compile_deps, variables=variables) else: if self.msvs_settings: libflags = self.msvs_settings.GetLibFlags(config_name, self.GypPathToNinja) variables.append(('libflags', libflags)) self.ninja.build(self.target.binary, 'alink', link_deps, order_only=compile_deps, variables=variables) else: self.WriteLink(spec, config_name, config, link_deps) return self.target.binary def WriteMacBundle(self, spec, mac_bundle_depends): assert self.is_mac_bundle package_framework = spec['type'] in ('shared_library', 'loadable_module') output = self.ComputeMacBundleOutput() postbuild = self.GetPostbuildCommand(spec, output, self.target.binary, is_command_start=not package_framework) variables = [] if postbuild: variables.append(('postbuilds', postbuild)) if package_framework: variables.append(('version', self.xcode_settings.GetFrameworkVersion())) self.ninja.build(output, 'package_framework', mac_bundle_depends, variables=variables) else: self.ninja.build(output, 'stamp', mac_bundle_depends, variables=variables) self.target.bundle = output return output def GetSortedXcodeEnv(self, additional_settings=None): """Returns the variables Xcode would set for build steps.""" assert self.abs_build_dir abs_build_dir = self.abs_build_dir return gyp.xcode_emulation.GetSortedXcodeEnv( self.xcode_settings, abs_build_dir, os.path.join(abs_build_dir, self.build_to_base), self.config_name, additional_settings) def GetSortedXcodePostbuildEnv(self): """Returns the variables Xcode would set for postbuild steps.""" postbuild_settings = {} # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack. # TODO(thakis): It would be nice to have some general mechanism instead. strip_save_file = self.xcode_settings.GetPerTargetSetting( 'CHROMIUM_STRIP_SAVE_FILE') if strip_save_file: postbuild_settings['CHROMIUM_STRIP_SAVE_FILE'] = strip_save_file return self.GetSortedXcodeEnv(additional_settings=postbuild_settings) def GetPostbuildCommand(self, spec, output, output_binary, is_command_start=False): """Returns a shell command that runs all the postbuilds, and removes |output| if any of them fails. If |is_command_start| is False, then the returned string will start with ' && '.""" if not self.xcode_settings or spec['type'] == 'none' or not output: return '' output = QuoteShellArgument(output, self.flavor) target_postbuilds = self.xcode_settings.GetTargetPostbuilds( self.config_name, os.path.normpath(os.path.join(self.base_to_build, output)), QuoteShellArgument( os.path.normpath(os.path.join(self.base_to_build, output_binary)), self.flavor), quiet=True) postbuilds = gyp.xcode_emulation.GetSpecPostbuildCommands(spec, quiet=True) postbuilds = target_postbuilds + postbuilds if not postbuilds: return '' # Postbuilds expect to be run in the gyp file's directory, so insert an # implicit postbuild to cd to there. postbuilds.insert(0, gyp.common.EncodePOSIXShellList( ['cd', self.build_to_base])) env = self.ComputeExportEnvString(self.GetSortedXcodePostbuildEnv()) # G will be non-null if any postbuild fails. Run all postbuilds in a # subshell. commands = env + ' (F=0; ' + \ ' '.join([ninja_syntax.escape(command) + ' || F=$$?;' for command in postbuilds]) command_string = (commands + ' exit $$F); G=$$?; ' # Remove the final output if any postbuild failed. '((exit $$G) || rm -rf %s) ' % output + '&& exit $$G)') if is_command_start: return '(' + command_string + ' && ' else: return '$ && (' + command_string def ComputeExportEnvString(self, env): """Given an environment, returns a string looking like 'export FOO=foo; export BAR="${FOO} bar;' that exports |env| to the shell.""" export_str = [] for k, v in env: export_str.append('export %s=%s;' % (k, ninja_syntax.escape(gyp.common.EncodePOSIXShellArgument(v)))) return ' '.join(export_str) def ComputeMacBundleOutput(self): """Return the 'output' (full output path) to a bundle output directory.""" assert self.is_mac_bundle path = self.ExpandSpecial(generator_default_variables['PRODUCT_DIR']) return os.path.join(path, self.xcode_settings.GetWrapperName()) def ComputeMacBundleBinaryOutput(self): """Return the 'output' (full output path) to the binary in a bundle.""" assert self.is_mac_bundle path = self.ExpandSpecial(generator_default_variables['PRODUCT_DIR']) return os.path.join(path, self.xcode_settings.GetExecutablePath()) def ComputeOutputFileName(self, spec, type=None): """Compute the filename of the final output for the current target.""" if not type: type = spec['type'] default_variables = copy.copy(generator_default_variables) CalculateVariables(default_variables, {'flavor': self.flavor}) # Compute filename prefix: the product prefix, or a default for # the product type. DEFAULT_PREFIX = { 'loadable_module': default_variables['SHARED_LIB_PREFIX'], 'shared_library': default_variables['SHARED_LIB_PREFIX'], 'static_library': default_variables['STATIC_LIB_PREFIX'], 'executable': default_variables['EXECUTABLE_PREFIX'], } prefix = spec.get('product_prefix', DEFAULT_PREFIX.get(type, '')) # Compute filename extension: the product extension, or a default # for the product type. DEFAULT_EXTENSION = { 'loadable_module': default_variables['SHARED_LIB_SUFFIX'], 'shared_library': default_variables['SHARED_LIB_SUFFIX'], 'static_library': default_variables['STATIC_LIB_SUFFIX'], 'executable': default_variables['EXECUTABLE_SUFFIX'], } extension = spec.get('product_extension') if extension: extension = '.' + extension else: extension = DEFAULT_EXTENSION.get(type, '') if 'product_name' in spec: # If we were given an explicit name, use that. target = spec['product_name'] else: # Otherwise, derive a name from the target name. target = spec['target_name'] if prefix == 'lib': # Snip out an extra 'lib' from libs if appropriate. target = StripPrefix(target, 'lib') if type in ('static_library', 'loadable_module', 'shared_library', 'executable'): return '%s%s%s' % (prefix, target, extension) elif type == 'none': return '%s.stamp' % target else: raise Exception('Unhandled output type %s' % type) def ComputeOutput(self, spec, type=None): """Compute the path for the final output of the spec.""" assert not self.is_mac_bundle or type if not type: type = spec['type'] if self.flavor == 'win': override = self.msvs_settings.GetOutputName(self.config_name, self.ExpandSpecial) if override: return override if self.flavor == 'mac' and type in ( 'static_library', 'executable', 'shared_library', 'loadable_module'): filename = self.xcode_settings.GetExecutablePath() else: filename = self.ComputeOutputFileName(spec, type) if 'product_dir' in spec: path = os.path.join(spec['product_dir'], filename) return self.ExpandSpecial(path) # Some products go into the output root, libraries go into shared library # dir, and everything else goes into the normal place. type_in_output_root = ['executable', 'loadable_module'] if self.flavor == 'mac' and self.toolset == 'target': type_in_output_root += ['shared_library', 'static_library'] elif self.flavor == 'win' and self.toolset == 'target': type_in_output_root += ['shared_library'] if type in type_in_output_root or self.is_standalone_static_library: return filename elif type == 'shared_library': libdir = 'lib' if self.toolset != 'target': libdir = os.path.join('lib', '%s' % self.toolset) return os.path.join(libdir, filename) else: return self.GypPathToUniqueOutput(filename, qualified=False) def WriteVariableList(self, var, values): assert not isinstance(values, str) if values is None: values = [] self.ninja.variable(var, ' '.join(values)) def WriteNewNinjaRule(self, name, args, description, is_cygwin, env): """Write out a new ninja "rule" statement for a given command. Returns the name of the new rule, and a copy of |args| with variables expanded.""" if self.flavor == 'win': args = [self.msvs_settings.ConvertVSMacros( arg, self.base_to_build, config=self.config_name) for arg in args] description = self.msvs_settings.ConvertVSMacros( description, config=self.config_name) elif self.flavor == 'mac': # |env| is an empty list on non-mac. args = [gyp.xcode_emulation.ExpandEnvVars(arg, env) for arg in args] description = gyp.xcode_emulation.ExpandEnvVars(description, env) # TODO: we shouldn't need to qualify names; we do it because # currently the ninja rule namespace is global, but it really # should be scoped to the subninja. rule_name = self.name if self.toolset == 'target': rule_name += '.' + self.toolset rule_name += '.' + name rule_name = re.sub('[^a-zA-Z0-9_]', '_', rule_name) # Remove variable references, but not if they refer to the magic rule # variables. This is not quite right, as it also protects these for # actions, not just for rules where they are valid. Good enough. protect = [ '${root}', '${dirname}', '${source}', '${ext}', '${name}' ] protect = '(?!' + '|'.join(map(re.escape, protect)) + ')' description = re.sub(protect + r'\$', '_', description) # gyp dictates that commands are run from the base directory. # cd into the directory before running, and adjust paths in # the arguments to point to the proper locations. rspfile = None rspfile_content = None args = [self.ExpandSpecial(arg, self.base_to_build) for arg in args] if self.flavor == 'win': rspfile = rule_name + '.$unique_name.rsp' # The cygwin case handles this inside the bash sub-shell. run_in = '' if is_cygwin else ' ' + self.build_to_base if is_cygwin: rspfile_content = self.msvs_settings.BuildCygwinBashCommandLine( args, self.build_to_base) else: rspfile_content = gyp.msvs_emulation.EncodeRspFileList(args) command = ('%s gyp-win-tool action-wrapper $arch ' % sys.executable + rspfile + run_in) else: env = self.ComputeExportEnvString(env) command = gyp.common.EncodePOSIXShellList(args) command = 'cd %s; ' % self.build_to_base + env + command # GYP rules/actions express being no-ops by not touching their outputs. # Avoid executing downstream dependencies in this case by specifying # restat=1 to ninja. self.ninja.rule(rule_name, command, description, restat=True, rspfile=rspfile, rspfile_content=rspfile_content) self.ninja.newline() return rule_name, args def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" global generator_additional_non_configuration_keys global generator_additional_path_sections flavor = gyp.common.GetFlavor(params) if flavor == 'mac': default_variables.setdefault('OS', 'mac') default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib') default_variables.setdefault('SHARED_LIB_DIR', generator_default_variables['PRODUCT_DIR']) default_variables.setdefault('LIB_DIR', generator_default_variables['PRODUCT_DIR']) # Copy additional generator configuration data from Xcode, which is shared # by the Mac Ninja generator. import gyp.generator.xcode as xcode_generator generator_additional_non_configuration_keys = getattr(xcode_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(xcode_generator, 'generator_additional_path_sections', []) global generator_extra_sources_for_rules generator_extra_sources_for_rules = getattr(xcode_generator, 'generator_extra_sources_for_rules', []) elif flavor == 'win': default_variables.setdefault('OS', 'win') default_variables['EXECUTABLE_SUFFIX'] = '.exe' default_variables['STATIC_LIB_PREFIX'] = '' default_variables['STATIC_LIB_SUFFIX'] = '.lib' default_variables['SHARED_LIB_PREFIX'] = '' default_variables['SHARED_LIB_SUFFIX'] = '.dll' generator_flags = params.get('generator_flags', {}) # Copy additional generator configuration data from VS, which is shared # by the Windows Ninja generator. import gyp.generator.msvs as msvs_generator generator_additional_non_configuration_keys = getattr(msvs_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(msvs_generator, 'generator_additional_path_sections', []) # Set a variable so conditions can be based on msvs_version. msvs_version = gyp.msvs_emulation.GetVSVersion(generator_flags) default_variables['MSVS_VERSION'] = msvs_version.ShortName() # To determine processor word size on Windows, in addition to checking # PROCESSOR_ARCHITECTURE (which reflects the word size of the current # process), it is also necessary to check PROCESSOR_ARCHITEW6432 (which # contains the actual word size of the system when running thru WOW64). if ('64' in os.environ.get('PROCESSOR_ARCHITECTURE', '') or '64' in os.environ.get('PROCESSOR_ARCHITEW6432', '')): default_variables['MSVS_OS_BITS'] = 64 else: default_variables['MSVS_OS_BITS'] = 32 else: operating_system = flavor if flavor == 'android': operating_system = 'linux' # Keep this legacy behavior for now. default_variables.setdefault('OS', operating_system) default_variables.setdefault('SHARED_LIB_SUFFIX', '.so') default_variables.setdefault('SHARED_LIB_DIR', os.path.join('$!PRODUCT_DIR', 'lib')) default_variables.setdefault('LIB_DIR', os.path.join('$!PRODUCT_DIR', 'obj')) def OpenOutput(path, mode='w'): """Open |path| for writing, creating directories if necessary.""" try: os.makedirs(os.path.dirname(path)) except OSError: pass return open(path, mode) def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name): options = params['options'] flavor = gyp.common.GetFlavor(params) generator_flags = params.get('generator_flags', {}) # generator_dir: relative path from pwd to where make puts build files. # Makes migrating from make to ninja easier, ninja doesn't put anything here. generator_dir = os.path.relpath(params['options'].generator_output or '.') # output_dir: relative path from generator_dir to the build directory. output_dir = generator_flags.get('output_dir', 'out') # build_dir: relative path from source root to our output files. # e.g. "out/Debug" build_dir = os.path.normpath(os.path.join(generator_dir, output_dir, config_name)) toplevel_build = os.path.join(options.toplevel_dir, build_dir) master_ninja = ninja_syntax.Writer( OpenOutput(os.path.join(toplevel_build, 'build.ninja')), width=120) case_sensitive_filesystem = not os.path.exists( os.path.join(toplevel_build, 'BUILD.NINJA')) # Put build-time support tools in out/{config_name}. gyp.common.CopyTool(flavor, toplevel_build) # Grab make settings for CC/CXX. # The rules are # - The priority from low to high is gcc/g++, the 'make_global_settings' in # gyp, the environment variable. # - If there is no 'make_global_settings' for CC.host/CXX.host or # 'CC_host'/'CXX_host' enviroment variable, cc_host/cxx_host should be set # to cc/cxx. if flavor == 'win': cc = 'cl.exe' cxx = 'cl.exe' ld = 'link.exe' gyp.msvs_emulation.GenerateEnvironmentFiles( toplevel_build, generator_flags, OpenOutput) ld_host = '$ld' else: cc = 'gcc' cxx = 'g++' ld = '$cxx' ld_host = '$cxx_host' cc_host = None cxx_host = None cc_host_global_setting = None cxx_host_global_setting = None build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0]) make_global_settings = data[build_file].get('make_global_settings', []) build_to_root = gyp.common.InvertRelativePath(build_dir, options.toplevel_dir) for key, value in make_global_settings: if key == 'CC': cc = os.path.join(build_to_root, value) if key == 'CXX': cxx = os.path.join(build_to_root, value) if key == 'LD': ld = os.path.join(build_to_root, value) if key == 'CC.host': cc_host = os.path.join(build_to_root, value) cc_host_global_setting = value if key == 'CXX.host': cxx_host = os.path.join(build_to_root, value) cxx_host_global_setting = value if key == 'LD.host': ld_host = os.path.join(build_to_root, value) flock = 'flock' if flavor == 'mac': flock = './gyp-mac-tool flock' cc = GetEnvironFallback(['CC_target', 'CC'], cc) master_ninja.variable('cc', cc) cxx = GetEnvironFallback(['CXX_target', 'CXX'], cxx) master_ninja.variable('cxx', cxx) ld = GetEnvironFallback(['LD_target', 'LD'], ld) if not cc_host: cc_host = cc if not cxx_host: cxx_host = cxx if flavor == 'win': master_ninja.variable('ld', ld) master_ninja.variable('idl', 'midl.exe') master_ninja.variable('ar', 'lib.exe') master_ninja.variable('rc', 'rc.exe') master_ninja.variable('asm', 'ml.exe') master_ninja.variable('mt', 'mt.exe') master_ninja.variable('use_dep_database', '1') else: master_ninja.variable('ld', flock + ' linker.lock ' + ld) master_ninja.variable('ar', GetEnvironFallback(['AR_target', 'AR'], 'ar')) master_ninja.variable('ar_host', GetEnvironFallback(['AR_host'], 'ar')) cc_host = GetEnvironFallback(['CC_host'], cc_host) cxx_host = GetEnvironFallback(['CXX_host'], cxx_host) ld_host = GetEnvironFallback(['LD_host'], ld_host) # The environment variable could be used in 'make_global_settings', like # ['CC.host', '$(CC)'] or ['CXX.host', '$(CXX)'], transform them here. if '$(CC)' in cc_host and cc_host_global_setting: cc_host = cc_host_global_setting.replace('$(CC)', cc) if '$(CXX)' in cxx_host and cxx_host_global_setting: cxx_host = cxx_host_global_setting.replace('$(CXX)', cxx) master_ninja.variable('cc_host', cc_host) master_ninja.variable('cxx_host', cxx_host) if flavor == 'win': master_ninja.variable('ld_host', ld_host) else: master_ninja.variable('ld_host', flock + ' linker.lock ' + ld_host) master_ninja.newline() if flavor != 'win': master_ninja.rule( 'cc', description='CC $out', command=('$cc -MMD -MF $out.d $defines $includes $cflags $cflags_c ' '$cflags_pch_c -c $in -o $out'), depfile='$out.d') master_ninja.rule( 'cc_s', description='CC $out', command=('$cc $defines $includes $cflags $cflags_c ' '$cflags_pch_c -c $in -o $out')) master_ninja.rule( 'cxx', description='CXX $out', command=('$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_cc ' '$cflags_pch_cc -c $in -o $out'), depfile='$out.d') else: # Template for compile commands mostly shared between compiling files # and generating PCH. In the case of PCH, the "output" is specified by /Fp # rather than /Fo (for object files), but we still need to specify an /Fo # when compiling PCH. cc_template = ('ninja -t msvc -o $out -e $arch ' '-- ' '$cc /nologo /showIncludes /FC ' '@$out.rsp ' '$cflags_pch_c /c $in %(outspec)s /Fd$pdbname ') cxx_template = ('ninja -t msvc -o $out -e $arch ' '-- ' '$cxx /nologo /showIncludes /FC ' '@$out.rsp ' '$cflags_pch_cc /c $in %(outspec)s $pchobj /Fd$pdbname ') master_ninja.rule( 'cc', description='CC $out', command=cc_template % {'outspec': '/Fo$out'}, depfile='$out.d', rspfile='$out.rsp', rspfile_content='$defines $includes $cflags $cflags_c') master_ninja.rule( 'cc_pch', description='CC PCH $out', command=cc_template % {'outspec': '/Fp$out /Fo$out.obj'}, depfile='$out.d', rspfile='$out.rsp', rspfile_content='$defines $includes $cflags $cflags_c') master_ninja.rule( 'cxx', description='CXX $out', command=cxx_template % {'outspec': '/Fo$out'}, depfile='$out.d', rspfile='$out.rsp', rspfile_content='$defines $includes $cflags $cflags_cc') master_ninja.rule( 'cxx_pch', description='CXX PCH $out', command=cxx_template % {'outspec': '/Fp$out /Fo$out.obj'}, depfile='$out.d', rspfile='$out.rsp', rspfile_content='$defines $includes $cflags $cflags_cc') master_ninja.rule( 'idl', description='IDL $in', command=('%s gyp-win-tool midl-wrapper $arch $outdir ' '$tlb $h $dlldata $iid $proxy $in ' '$idlflags' % sys.executable)) master_ninja.rule( 'rc', description='RC $in', # Note: $in must be last otherwise rc.exe complains. command=('%s gyp-win-tool rc-wrapper ' '$arch $rc $defines $includes $rcflags /fo$out $in' % sys.executable)) master_ninja.rule( 'asm', description='ASM $in', command=('%s gyp-win-tool asm-wrapper ' '$arch $asm $defines $includes /c /Fo $out $in' % sys.executable)) if flavor != 'mac' and flavor != 'win': master_ninja.rule( 'alink', description='AR $out', command='rm -f $out && $ar rcs $out $in') master_ninja.rule( 'alink_thin', description='AR $out', command='rm -f $out && $ar rcsT $out $in') # This allows targets that only need to depend on $lib's API to declare an # order-only dependency on $lib.TOC and avoid relinking such downstream # dependencies when $lib changes only in non-public ways. # The resulting string leaves an uninterpolated %{suffix} which # is used in the final substitution below. mtime_preserving_solink_base = ( 'if [ ! -e $lib -o ! -e ${lib}.TOC ]; then ' '%(solink)s && %(extract_toc)s > ${lib}.TOC; else ' '%(solink)s && %(extract_toc)s > ${lib}.tmp && ' 'if ! cmp -s ${lib}.tmp ${lib}.TOC; then mv ${lib}.tmp ${lib}.TOC ; ' 'fi; fi' % { 'solink': '$ld -shared $ldflags -o $lib -Wl,-soname=$soname %(suffix)s', 'extract_toc': ('{ readelf -d ${lib} | grep SONAME ; ' 'nm -gD -f p ${lib} | cut -f1-2 -d\' \'; }')}) master_ninja.rule( 'solink', description='SOLINK $lib', restat=True, command=(mtime_preserving_solink_base % { 'suffix': '-Wl,--whole-archive $in $solibs -Wl,--no-whole-archive ' '$libs'})) master_ninja.rule( 'solink_module', description='SOLINK(module) $lib', restat=True, command=(mtime_preserving_solink_base % { 'suffix': '-Wl,--start-group $in $solibs -Wl,--end-group $libs'})) master_ninja.rule( 'link', description='LINK $out', command=('$ld $ldflags -o $out ' '-Wl,--start-group $in $solibs -Wl,--end-group $libs')) elif flavor == 'win': master_ninja.rule( 'alink', description='LIB $out', command=('%s gyp-win-tool link-wrapper $arch ' '$ar /nologo /ignore:4221 /OUT:$out @$out.rsp' % sys.executable), rspfile='$out.rsp', rspfile_content='$in_newline $libflags') dlldesc = 'LINK(DLL) $dll' dllcmd = ('%s gyp-win-tool link-wrapper $arch ' '$ld /nologo $implibflag /DLL /OUT:$dll ' '/PDB:$dll.pdb @$dll.rsp' % sys.executable) dllcmd += (' && %s gyp-win-tool manifest-wrapper $arch ' '$mt -nologo -manifest $manifests -out:$dll.manifest' % sys.executable) master_ninja.rule('solink', description=dlldesc, command=dllcmd, rspfile='$dll.rsp', rspfile_content='$libs $in_newline $ldflags', restat=True) master_ninja.rule('solink_module', description=dlldesc, command=dllcmd, rspfile='$dll.rsp', rspfile_content='$libs $in_newline $ldflags', restat=True) # Note that ldflags goes at the end so that it has the option of # overriding default settings earlier in the command line. master_ninja.rule( 'link', description='LINK $out', command=('%s gyp-win-tool link-wrapper $arch ' '$ld /nologo /OUT:$out /PDB:$out.pdb @$out.rsp && ' '%s gyp-win-tool manifest-wrapper $arch ' '$mt -nologo -manifest $manifests -out:$out.manifest' % (sys.executable, sys.executable)), rspfile='$out.rsp', rspfile_content='$in_newline $libs $ldflags') else: master_ninja.rule( 'objc', description='OBJC $out', command=('$cc -MMD -MF $out.d $defines $includes $cflags $cflags_objc ' '$cflags_pch_objc -c $in -o $out'), depfile='$out.d') master_ninja.rule( 'objcxx', description='OBJCXX $out', command=('$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_objcc ' '$cflags_pch_objcc -c $in -o $out'), depfile='$out.d') master_ninja.rule( 'alink', description='LIBTOOL-STATIC $out, POSTBUILDS', command='rm -f $out && ' './gyp-mac-tool filter-libtool libtool $libtool_flags ' '-static -o $out $in' '$postbuilds') # Record the public interface of $lib in $lib.TOC. See the corresponding # comment in the posix section above for details. mtime_preserving_solink_base = ( 'if [ ! -e $lib -o ! -e ${lib}.TOC ] || ' # Always force dependent targets to relink if this library # reexports something. Handling this correctly would require # recursive TOC dumping but this is rare in practice, so punt. 'otool -l $lib | grep -q LC_REEXPORT_DYLIB ; then ' '%(solink)s && %(extract_toc)s > ${lib}.TOC; ' 'else ' '%(solink)s && %(extract_toc)s > ${lib}.tmp && ' 'if ! cmp -s ${lib}.tmp ${lib}.TOC; then ' 'mv ${lib}.tmp ${lib}.TOC ; ' 'fi; ' 'fi' % { 'solink': '$ld -shared $ldflags -o $lib %(suffix)s', 'extract_toc': '{ otool -l $lib | grep LC_ID_DYLIB -A 5; ' 'nm -gP $lib | cut -f1-2 -d\' \' | grep -v U$$; true; }'}) # TODO(thakis): The solink_module rule is likely wrong. Xcode seems to pass # -bundle -single_module here (for osmesa.so). master_ninja.rule( 'solink', description='SOLINK $lib, POSTBUILDS', restat=True, command=(mtime_preserving_solink_base % { 'suffix': '$in $solibs $libs$postbuilds'})) master_ninja.rule( 'solink_module', description='SOLINK(module) $lib, POSTBUILDS', restat=True, command=(mtime_preserving_solink_base % { 'suffix': '$in $solibs $libs$postbuilds'})) master_ninja.rule( 'link', description='LINK $out, POSTBUILDS', command=('$ld $ldflags -o $out ' '$in $solibs $libs$postbuilds')) master_ninja.rule( 'infoplist', description='INFOPLIST $out', command=('$cc -E -P -Wno-trigraphs -x c $defines $in -o $out && ' 'plutil -convert xml1 $out $out')) master_ninja.rule( 'mac_tool', description='MACTOOL $mactool_cmd $in', command='$env ./gyp-mac-tool $mactool_cmd $in $out') master_ninja.rule( 'package_framework', description='PACKAGE FRAMEWORK $out, POSTBUILDS', command='./gyp-mac-tool package-framework $out $version$postbuilds ' '&& touch $out') if flavor == 'win': master_ninja.rule( 'stamp', description='STAMP $out', command='%s gyp-win-tool stamp $out' % sys.executable) master_ninja.rule( 'copy', description='COPY $in $out', command='%s gyp-win-tool recursive-mirror $in $out' % sys.executable) else: master_ninja.rule( 'stamp', description='STAMP $out', command='${postbuilds}touch $out') master_ninja.rule( 'copy', description='COPY $in $out', command='ln -f $in $out 2>/dev/null || (rm -rf $out && cp -af $in $out)') master_ninja.newline() all_targets = set() for build_file in params['build_files']: for target in gyp.common.AllTargets(target_list, target_dicts, os.path.normpath(build_file)): all_targets.add(target) all_outputs = set() # target_outputs is a map from qualified target name to a Target object. target_outputs = {} # target_short_names is a map from target short name to a list of Target # objects. target_short_names = {} for qualified_target in target_list: # qualified_target is like: third_party/icu/icu.gyp:icui18n#target build_file, name, toolset = \ gyp.common.ParseQualifiedTarget(qualified_target) this_make_global_settings = data[build_file].get('make_global_settings', []) assert make_global_settings == this_make_global_settings, ( "make_global_settings needs to be the same for all targets.") spec = target_dicts[qualified_target] if flavor == 'mac': gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec) build_file = gyp.common.RelativePath(build_file, options.toplevel_dir) base_path = os.path.dirname(build_file) obj = 'obj' if toolset != 'target': obj += '.' + toolset output_file = os.path.join(obj, base_path, name + '.ninja') abs_build_dir = os.path.abspath(toplevel_build) writer = NinjaWriter(qualified_target, target_outputs, base_path, build_dir, OpenOutput(os.path.join(toplevel_build, output_file)), flavor, toplevel_dir=options.toplevel_dir) master_ninja.subninja(output_file) target = writer.WriteSpec( spec, config_name, generator_flags, case_sensitive_filesystem) if target: if name != target.FinalOutput() and spec['toolset'] == 'target': target_short_names.setdefault(name, []).append(target) target_outputs[qualified_target] = target if qualified_target in all_targets: all_outputs.add(target.FinalOutput()) if target_short_names: # Write a short name to build this target. This benefits both the # "build chrome" case as well as the gyp tests, which expect to be # able to run actions and build libraries by their short name. master_ninja.newline() master_ninja.comment('Short names for targets.') for short_name in target_short_names: master_ninja.build(short_name, 'phony', [x.FinalOutput() for x in target_short_names[short_name]]) if all_outputs: master_ninja.newline() master_ninja.build('all', 'phony', list(all_outputs)) master_ninja.default(generator_flags.get('default_target', 'all')) def PerformBuild(data, configurations, params): options = params['options'] for config in configurations: builddir = os.path.join(options.toplevel_dir, 'out', config) arguments = ['ninja', '-C', builddir] print 'Building [%s]: %s' % (config, arguments) subprocess.check_call(arguments) def CallGenerateOutputForConfig(arglist): # Ignore the interrupt signal so that the parent process catches it and # kills all multiprocessing children. signal.signal(signal.SIGINT, signal.SIG_IGN) (target_list, target_dicts, data, params, config_name) = arglist GenerateOutputForConfig(target_list, target_dicts, data, params, config_name) def GenerateOutput(target_list, target_dicts, data, params): user_config = params.get('generator_flags', {}).get('config', None) if user_config: GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: config_names = target_dicts[target_list[0]]['configurations'].keys() if params['parallel']: try: pool = multiprocessing.Pool(len(config_names)) arglists = [] for config_name in config_names: arglists.append( (target_list, target_dicts, data, params, config_name)) pool.map(CallGenerateOutputForConfig, arglists) except KeyboardInterrupt, e: pool.terminate() raise e else: for config_name in config_names: GenerateOutputForConfig(target_list, target_dicts, data, params, config_name)
DanialLiu/SkiaWin32Port
third_party/externals/gyp/pylib/gyp/generator/ninja.py
Python
bsd-3-clause
74,180
0.006794
# 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., 675 Mass Ave, Cambridge, MA 02139, USA. from sos.plugins import Plugin, UbuntuPlugin, DebianPlugin class Zfs(Plugin, UbuntuPlugin, DebianPlugin): """ZFS filesystem """ plugin_name = 'zfs' profiles = ('storage',) packages = ('zfsutils-linux',) def setup(self): self.add_cmd_output([ "zfs get all", "zfs list -t all -o space", "zpool list", "zpool status -x" ]) # vim: set et ts=4 sw=4 :
cnewcome/sos
sos/plugins/zfs.py
Python
gpl-2.0
1,124
0
import os from PIL import Image import numpy from utils import ensure_dir DRAWABLE = 'drawable' class ImageTypeException(Exception): pass class Density(object): LDPI = 'ldpi' MDPI = 'mdpi' HDPI = 'hdpi' XHDPI = 'xhdpi' XXHDPI = 'xxhdpi' XXXHDPI = 'xxxhdpi' RATIOS = { LDPI: 3, MDPI: 4, HDPI: 6, XHDPI: 8, XXHDPI: 12, XXXHDPI: 16, } ORDER = [LDPI, MDPI, HDPI, XHDPI, XXHDPI, XXXHDPI] class ImageType(object): PNG = 'png' PNG_9_BIT = '9.png' SVG = 'svg' # haven't flushed out SVG support yet, or scaling 9-bits SUPPORTED_TYPES = [PNG] @classmethod def is_supported_type(cls, image_type): return image_type in cls.SUPPORTED_TYPES class ImageSpec(object): def __init__(self, src): self.filename = src['filename'] self.source_dpi = src['source_dpi'] self.other_scaling = src.get('other_scaling', {}) self.excluded_dpis = src.get('excluded_dpis', []) # Determine Image Type by filename extension = self.filename.split('.', 1)[1] if not ImageType.is_supported_type(extension): raise ImageTypeException( 'The image type %(ext)s is not yet supported.' % { 'ext': extension, }) class DPIManager(object): def __init__(self, spec_src, source_folder, target_folder): """The DPIManager handles all the scaling of an image according to its spec and ImageType. :param spec_src: :param source_folder: :return: """ self.source_folder = source_folder self.target_folder = target_folder self.spec = ImageSpec(spec_src) src_dpi_index = Density.ORDER.index(self.spec.source_dpi) + 1 target_dpis = set(Density.ORDER[:src_dpi_index]) self.target_dpis = list(target_dpis.difference(self.spec.excluded_dpis)) self.scaling_ratios = self.get_scaling_ratios() def get_scaling_ratios(self): src_scale = Density.RATIOS[self.spec.source_dpi] scaling = {} for dpi in self.target_dpis: scaling[dpi] = Density.RATIOS[dpi] / float(src_scale) return scaling def update_resources(self): src_path = os.path.join(self.source_folder, self.spec.filename) src_img = Image.open(src_path) # Premult alpha resizing, to avoid halo effect # http://stackoverflow.com/questions/9142825/transparent-png-resizing-with-python-image-library-and-the-halo-effect premult = numpy.fromstring(src_img.tobytes(), dtype=numpy.uint8) alphaLayer = premult[3::4] / 255.0 premult[::4] *= alphaLayer premult[1::4] *= alphaLayer premult[2::4] *= alphaLayer src_img = Image.frombytes("RGBA", src_img.size, premult.tobytes()) # save original image to drawables default_dir = os.path.join(self.target_folder, DRAWABLE) ensure_dir(default_dir) default_path = os.path.join(default_dir, self.spec.filename) src_img.save(default_path) print "save to", default_path src_width, src_height = src_img.size for dpi in self.target_dpis: ratio = self.scaling_ratios[dpi] dpi_width = int(round(src_width * ratio, 0)) dpi_height = int(round(src_height * ratio, 0)) print "scale image %(from_dims)s --> %(to_dims)s" % { 'from_dims': "%d x %d" % (src_width, src_height), 'to_dims': "%d x %d" % (dpi_width, dpi_height), } dpi_dir = os.path.join( self.target_folder, '%s-%s' % (DRAWABLE, dpi) ) ensure_dir(dpi_dir) dpi_path = os.path.join(dpi_dir, self.spec.filename) src_img.resize((dpi_width, dpi_height), Image.ANTIALIAS).save( dpi_path ) print "save to", dpi_path for label, size in self.spec.other_scaling.items(): scale_dir = os.path.join( self.target_folder, '%s-%s' % (DRAWABLE, label) ) ensure_dir(scale_dir) scale_path = os.path.join(scale_dir, self.spec.filename) src_img.resize((size[0], size[1]), Image.ANTIALIAS).save( scale_path ) print "save to", scale_path
dimagi/commcare-android
images/dpi_manager.py
Python
apache-2.0
4,399
0.000227
# coding=utf-8 """HCTSA test time series.""" import os.path as op import numpy as np from pyopy.hctsa.hctsa_config import HCTSA_TESTTS_DIR def hctsa_sine(): return np.loadtxt(op.join(HCTSA_TESTTS_DIR, 'SY_sine.dat')) def hctsa_noise(): return np.loadtxt(op.join(HCTSA_TESTTS_DIR, 'SY_noise.dat')) def hctsa_noisysinusoid(): return np.loadtxt(op.join(HCTSA_TESTTS_DIR, 'SY_noisysinusoid.dat')) HCTSA_TEST_TIME_SERIES = ( ('sine', hctsa_sine), ('noise', hctsa_noise), ('noisysinusoid', hctsa_noisysinusoid), )
strawlab/pyopy
pyopy/hctsa/hctsa_data.py
Python
bsd-3-clause
540
0
#!/usr/bin/env python3 # Copyright 2017 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys os.chdir(os.path.join(os.path.dirname(sys.argv[0]), '../../..')) def check_port_platform_inclusion(directory_root): bad_files = [] for root, dirs, files in os.walk(directory_root): for filename in files: path = os.path.join(root, filename) if os.path.splitext(path)[1] not in ['.c', '.cc', '.h']: continue if path in [ os.path.join('include', 'grpc', 'support', 'port_platform.h'), os.path.join('include', 'grpc', 'impl', 'codegen', 'port_platform.h'), ]: continue if filename.endswith('.pb.h') or filename.endswith('.pb.c'): continue # Skip check for upb generated code. if (filename.endswith('.upb.h') or filename.endswith('.upb.c') or filename.endswith('.upbdefs.h') or filename.endswith('.upbdefs.c')): continue with open(path) as f: all_lines_in_file = f.readlines() for index, l in enumerate(all_lines_in_file): if '#include' in l: if l not in [ '#include <grpc/support/port_platform.h>\n', '#include <grpc/impl/codegen/port_platform.h>\n' ]: bad_files.append(path) elif all_lines_in_file[index + 1] != '\n': # Require a blank line after including port_platform.h in # order to prevent the formatter from reording it's # inclusion order upon future changes. bad_files.append(path) break return bad_files all_bad_files = [] all_bad_files += check_port_platform_inclusion(os.path.join('src', 'core')) all_bad_files += check_port_platform_inclusion(os.path.join('include', 'grpc')) if len(all_bad_files) > 0: for f in all_bad_files: print((('port_platform.h is not the first included header or there ' 'is not a blank line following its inclusion in %s') % f)) sys.exit(1)
vjpai/grpc
tools/run_tests/sanity/check_port_platform.py
Python
apache-2.0
2,915
0.000686
# -*- coding: utf-8 -*- """ lets.alarm ~~~~~~~~~~ An event which is awoken up based on time. :copyright: (c) 2013-2018 by Heungsub Lee :license: BSD, see LICENSE for more details. """ import operator import time as time_ from gevent import get_hub, Timeout from gevent.event import Event __all__ = ['Alarm', 'Earliest', 'Latest'] class _Alarm(object): """A :class:`gevent.event.AsyncResult`-like class to wait until the final set time. """ __slots__ = ('time', 'value', 'timer', 'event') #: Implement it to decide to reschedule the awaking time. It's a function #: which takes 2 time arguments. The first argument is new time to set, #: and the second argument is the previously accepted time. Both arguments #: are never ``None``. accept = NotImplemented def __init__(self): self.time = self.value = self.timer = None self.event = Event() def set(self, time, value=None): """Sets the time to awake up. If the time is not accepted, will be ignored and it returns ``False``. Otherwise, returns ``True``. """ if time is None: raise TypeError('use clear() instead of setting none time') elif self.time is not None and not self.accept(time, self.time): # Not accepted. return False self._reset(time, value) delay = time - time_.time() if delay > 0: # Set timer to wake up. self.timer = get_hub().loop.timer(delay) self.timer.start(self.event.set) else: # Wake up immediately. self.event.set() return True def when(self): """When it will be awoken or ``None``.""" return self.time def ready(self): """Whether it has been awoken.""" return self.event.ready() def wait(self, timeout=None): """Waits until the awaking time. It returns the time.""" if self.event.wait(timeout): return self.time def get(self, block=True, timeout=None): """Waits until and gets the awaking time and the value.""" if not block and not self.ready(): raise Timeout if self.event.wait(timeout): return self.time, self.value raise Timeout(timeout) def clear(self): """Discards the schedule for awaking.""" self.event.clear() self._reset(None, None) def _reset(self, time, value): self.time = time self.value = value if self.timer is not None: self.timer.stop() def __nonzero__(self): return self.time is not None class Alarm(_Alarm): """An alarm which accepts any time. Its awaking time will always be reset. """ accept = lambda x, y: True class Earliest(_Alarm): """An alarm which accepts only the earliest time among many times that've been set. Earlier time means that smaller timestamp. """ accept = operator.lt class Latest(_Alarm): """An alarm which accepts only the latest time among many times that've been set. Later time means that bigger timestamp. """ accept = operator.gt
sublee/lets
lets/alarm.py
Python
bsd-3-clause
3,197
0.000313
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsDefaultValue. .. note:: 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. """ __author__ = 'Matthias Kuhn' __date__ = '26.9.2017' __copyright__ = 'Copyright 2017, The QGIS Project' import qgis # NOQA from qgis.core import (QgsDefaultValue) from qgis.testing import unittest class TestQgsRasterColorRampShader(unittest.TestCase): def testValid(self): self.assertFalse(QgsDefaultValue()) self.assertTrue(QgsDefaultValue('test')) self.assertTrue(QgsDefaultValue('abc', True)) self.assertTrue(QgsDefaultValue('abc', False)) def setGetExpression(self): value = QgsDefaultValue('abc', False) self.assertEqual(value.expression(), 'abc') value.setExpression('def') self.assertEqual(value.expression(), 'def') def setGetApplyOnUpdate(self): value = QgsDefaultValue('abc', False) self.assertEqual(value.applyOnUpdate(), False) value.setApplyOnUpdate(True) self.assertEqual(value.applyOnUpdate(), True) if __name__ == '__main__': unittest.main()
pblottiere/QGIS
tests/src/python/test_qgsdefaultvalue.py
Python
gpl-2.0
1,300
0
#!/usr/bin/python # -*- coding: utf-8 -*- """ This script adds a missing references section to pages. It goes over multiple pages, searches for pages where <references /> is missing although a <ref> tag is present, and in that case adds a new references section. These command line parameters can be used to specify which pages to work on: &params; -xml Retrieve information from a local XML dump (pages-articles or pages-meta-current, see https://download.wikimedia.org). Argument can also be given as "-xml:filename". -namespace:n Number or name of namespace to process. The parameter can be used multiple times. It works in combination with all other parameters, except for the -start parameter. If you e.g. want to iterate over all categories starting at M, use -start:Category:M. -always Don't prompt you for each replacement. -quiet Use this option to get less output If neither a page title nor a page generator is given, it takes all pages from the default maintenance category. It is strongly recommended not to run this script over the entire article namespace (using the -start) parameter, as that would consume too much bandwidth. Instead, use the -xml parameter, or use another way to generate a list of affected articles """ # # (C) Pywikibot team, 2007-2015 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __version__ = '$Id$' # import re import pywikibot from pywikibot import i18n, pagegenerators, textlib, Bot # This is required for the text that is shown when you run this script # with the parameter -help. docuReplacements = { '&params;': pagegenerators.parameterHelp, } # References sections are usually placed before further reading / external # link sections. This dictionary defines these sections, sorted by priority. # For example, on an English wiki, the script would place the "References" # section in front of the "Further reading" section, if that existed. # Otherwise, it would try to put it in front of the "External links" section, # or if that fails, the "See also" section, etc. placeBeforeSections = { 'ar': [ # no explicit policy on where to put the references u'وصلات خارجية', u'انظر أيضا', u'ملاحظات' ], 'ca': [ u'Bibliografia', u'Bibliografia complementària', u'Vegeu també', u'Enllaços externs', u'Enllaços', ], 'cs': [ u'Externí odkazy', u'Poznámky', ], 'da': [ # no explicit policy on where to put the references u'Eksterne links' ], 'de': [ # no explicit policy on where to put the references u'Literatur', u'Weblinks', u'Siehe auch', u'Weblink', # bad, but common singular form of Weblinks ], 'dsb': [ u'Nožki', ], 'en': [ # no explicit policy on where to put the references u'Further reading', u'External links', u'See also', u'Notes' ], 'ru': [ u'Ссылки', u'Литература', ], 'eo': [ u'Eksteraj ligiloj', u'Ekstera ligilo', u'Eksteraj ligoj', u'Ekstera ligo', u'Rete' ], 'es': [ u'Enlaces externos', u'Véase también', u'Notas', ], 'fa': [ u'پیوند به بیرون', u'پانویس', u'جستارهای وابسته' ], 'fi': [ u'Kirjallisuutta', u'Aiheesta muualla', u'Ulkoiset linkit', u'Linkkejä', ], 'fr': [ u'Liens externes', u'Voir aussi', u'Notes' ], 'he': [ u'ראו גם', u'לקריאה נוספת', u'קישורים חיצוניים', u'הערות שוליים', ], 'hsb': [ u'Nóžki', ], 'hu': [ u'Külső hivatkozások', u'Lásd még', ], 'it': [ u'Bibliografia', u'Voci correlate', u'Altri progetti', u'Collegamenti esterni', u'Vedi anche', ], 'ja': [ u'関連項目', u'参考文献', u'外部リンク', ], 'ko': [ # no explicit policy on where to put the references u'외부 링크', u'외부링크', u'바깥 고리', u'바깥고리', u'바깥 링크', u'바깥링크' u'외부 고리', u'외부고리' ], 'lt': [ # no explicit policy on where to put the references u'Nuorodos' ], 'nl': [ # no explicit policy on where to put the references u'Literatuur', u'Zie ook', u'Externe verwijzingen', u'Externe verwijzing', ], 'pdc': [ u'Beweisunge', u'Quelle unn Literatur', u'Gwelle', u'Gwuelle', u'Auswenniche Gleecher', u'Gewebbgleecher', u'Guckt mol aa', u'Seh aa', ], 'pl': [ u'Źródła', u'Bibliografia', u'Zobacz też', u'Linki zewnętrzne', ], 'pt': [ u'Ligações externas', u'Veja também', u'Ver também', u'Notas', ], 'sk': [ u'Pozri aj', ], 'szl': [ u'Przipisy', u'Připisy', ], 'th': [ u'อ่านเพิ่มเติม', u'แหล่งข้อมูลอื่น', u'ดูเพิ่ม', u'หมายเหตุ', ], 'zh': [ u'外部链接', u'外部連结', u'外部連結', u'外部连接', ], } # Titles of sections where a reference tag would fit into. # The first title should be the preferred one: It's the one that # will be used when a new section has to be created. referencesSections = { 'ar': [ # not sure about which ones are preferred. u'مراجع', u'المراجع', u'مصادر', u'المصادر', u'مراجع ومصادر', u'مصادر ومراجع', u'المراجع والمصادر', u'المصادر والمراجع', ], 'ca': [ u'Referències', ], 'cs': [ u'Reference', u'Poznámky', ], 'da': [ u'Noter', ], 'de': [ # see [[de:WP:REF]] u'Einzelnachweise', u'Anmerkungen', u'Belege', u'Endnoten', u'Fußnoten', u'Fuß-/Endnoten', u'Quellen', u'Quellenangaben', ], 'dsb': [ u'Nožki', ], 'en': [ # not sure about which ones are preferred. u'References', u'Footnotes', u'Notes', ], 'ru': [ u'Примечания', u'Сноски', u'Источники', ], 'eo': [ u'Referencoj', ], 'es': [ u'Referencias', u'Notas', ], 'fa': [ u'منابع', u'منبع' ], 'fi': [ u'Lähteet', u'Viitteet', ], 'fr': [ # [[fr:Aide:Note]] u'Notes et références', u'Références', u'References', u'Notes' ], 'he': [ u'הערות שוליים', ], 'hsb': [ u'Nóžki', ], 'hu': [ u'Források és jegyzetek', u'Források', u'Jegyzetek', u'Hivatkozások', u'Megjegyzések', ], 'is': [ u'Heimildir', u'Tilvísanir', ], 'it': [ u'Note', u'Riferimenti', ], 'ja': [ u'脚注', u'脚注欄', u'脚注・出典', u'出典', u'注釈', u'註', ], 'ko': [ u'주석', u'각주' u'주석 및 참고 자료' u'주석 및 참고자료', u'주석 및 참고 출처' ], 'lt': [ # not sure about which ones are preferred. u'Šaltiniai', u'Literatūra', ], 'nl': [ # not sure about which ones are preferred. u'Voetnoten', u'Voetnoot', u'Referenties', u'Noten', u'Bronvermelding', ], 'pdc': [ u'Aamarrickunge', ], 'pl': [ u'Przypisy', u'Uwagi', ], 'pt': [ u'Referências', ], 'sk': [ u'Referencie', ], 'szl': [ u'Przipisy', u'Připisy', ], 'th': [ u'อ้างอิง', u'เชิงอรรถ', u'หมายเหตุ', ], 'zh': [ u'參考資料', u'参考资料', u'參考文獻', u'参考文献', u'資料來源', u'资料来源', ], } # Templates which include a <references /> tag. If there is no such template # on your wiki, you don't have to enter anything here. referencesTemplates = { 'wikipedia': { 'ar': ['Reflist', 'مراجع', 'ثبت المراجع', 'ثبت_المراجع', 'بداية المراجع', 'نهاية المراجع'], 'be': [u'Зноскі', u'Примечания', u'Reflist', u'Спіс заўваг', u'Заўвагі'], 'be-tarask': [u'Зноскі'], 'ca': [u'Referències', u'Reflist', u'Listaref', u'Referència', u'Referencies', u'Referències2', u'Amaga', u'Amaga ref', u'Amaga Ref', u'Amaga Ref2', u'Apèndix'], 'da': [u'Reflist'], 'dsb': [u'Referency'], 'en': [u'Reflist', u'Refs', u'FootnotesSmall', u'Reference', u'Ref-list', u'Reference list', u'References-small', u'Reflink', u'Footnotes', u'FootnotesSmall'], 'eo': [u'Referencoj'], 'es': ['Listaref', 'Reflist', 'muchasref'], 'fa': [u'Reflist', u'Refs', u'FootnotesSmall', u'Reference', u'پانویس', u'پانویس‌ها ', u'پانویس ۲', u'پانویس۲', u'فهرست منابع'], 'fi': [u'Viitteet', u'Reflist'], 'fr': [u'Références', u'Notes', u'References', u'Reflist'], 'he': [u'הערות שוליים', u'הערה'], 'hsb': [u'Referency'], 'hu': [u'reflist', u'források', u'references', u'megjegyzések'], 'is': [u'reflist'], 'it': [u'References'], 'ja': [u'Reflist', u'脚注リスト'], 'ko': [u'주석', u'Reflist'], 'lt': [u'Reflist', u'Ref', u'Litref'], 'nl': [u'Reflist', u'Refs', u'FootnotesSmall', u'Reference', u'Ref-list', u'Reference list', u'References-small', u'Reflink', u'Referenties', u'Bron', u'Bronnen/noten/referenties', u'Bron2', u'Bron3', u'ref', u'references', u'appendix', u'Noot', u'FootnotesSmall'], 'pl': [u'Przypisy', u'Przypisy-lista', u'Uwagi'], 'pt': [u'Notas', u'ref-section', u'Referências', u'Reflist'], 'ru': [u'Reflist', u'Ref-list', u'Refs', u'Sources', u'Примечания', u'Список примечаний', u'Сноска', u'Сноски'], 'szl': [u'Przipisy', u'Připisy'], 'th': [u'รายการอ้างอิง'], 'zh': [u'Reflist', u'RefFoot', u'NoteFoot'], }, } # Text to be added instead of the <references /> tag. # Define this only if required by your wiki. referencesSubstitute = { 'wikipedia': { 'ar': u'{{مراجع}}', 'be': u'{{зноскі}}', 'da': u'{{reflist}}', 'dsb': u'{{referency}}', 'fa': u'{{پانویس}}', 'fi': u'{{viitteet}}', 'he': u'{{הערות שוליים}}', 'hsb': u'{{referency}}', 'hu': u'{{Források}}', 'pl': u'{{Przypisy}}', 'ru': u'{{примечания}}', 'szl': u'{{Przipisy}}', 'th': u'{{รายการอ้างอิง}}', 'zh': u'{{reflist}}', }, } # Sites where no title is required for references template # as it is already included there # like pl.wiki where {{Przypisy}} generates # == Przypisy == # <references /> noTitleRequired = [u'pl', u'be', u'szl'] maintenance_category = 'cite_error_refs_without_references_category' class XmlDumpNoReferencesPageGenerator: """ Generator which will yield Pages that might lack a references tag. These pages will be retrieved from a local XML dump file (pages-articles or pages-meta-current). """ def __init__(self, xmlFilename): """ Constructor. Arguments: * xmlFilename - The dump's path, either absolute or relative """ self.xmlFilename = xmlFilename self.refR = re.compile('</ref>', re.IGNORECASE) # The references tab can contain additional spaces and a group # attribute. self.referencesR = re.compile('<references.*?/>', re.IGNORECASE) def __iter__(self): """XML iterator.""" from pywikibot import xmlreader dump = xmlreader.XmlDump(self.xmlFilename) for entry in dump.parse(): text = textlib.removeDisabledParts(entry.text) if self.refR.search(text) and not self.referencesR.search(text): yield pywikibot.Page(pywikibot.Site(), entry.title) class NoReferencesBot(Bot): """References section bot.""" def __init__(self, generator, **kwargs): """Constructor.""" self.availableOptions.update({ 'verbose': True, }) super(NoReferencesBot, self).__init__(**kwargs) self.generator = pagegenerators.PreloadingGenerator(generator) self.site = pywikibot.Site() self.comment = i18n.twtranslate(self.site, 'noreferences-add-tag') self.refR = re.compile('</ref>', re.IGNORECASE) self.referencesR = re.compile('<references.*?/>', re.IGNORECASE) self.referencesTagR = re.compile('<references>.*?</references>', re.IGNORECASE | re.DOTALL) try: self.referencesTemplates = referencesTemplates[ self.site.family.name][self.site.code] except KeyError: self.referencesTemplates = [] try: self.referencesText = referencesSubstitute[ self.site.family.name][self.site.code] except KeyError: self.referencesText = u'<references />' def lacksReferences(self, text): """Check whether or not the page is lacking a references tag.""" oldTextCleaned = textlib.removeDisabledParts(text) if self.referencesR.search(oldTextCleaned) or \ self.referencesTagR.search(oldTextCleaned): if self.getOption('verbose'): pywikibot.output(u'No changes necessary: references tag found.') return False elif self.referencesTemplates: templateR = u'{{(' + u'|'.join(self.referencesTemplates) + ')' if re.search(templateR, oldTextCleaned, re.IGNORECASE | re.UNICODE): if self.getOption('verbose'): pywikibot.output( u'No changes necessary: references template found.') return False if not self.refR.search(oldTextCleaned): if self.getOption('verbose'): pywikibot.output(u'No changes necessary: no ref tags found.') return False else: if self.getOption('verbose'): pywikibot.output(u'Found ref without references.') return True def addReferences(self, oldText): """ Add a references tag into an existing section where it fits into. If there is no such section, creates a new section containing the references tag. * Returns : The modified pagetext """ # Do we have a malformed <reference> tag which could be repaired? # Repair two opening tags or a opening and an empty tag pattern = re.compile(r'< *references *>(.*?)' r'< */?\s*references */? *>', re.DOTALL) if pattern.search(oldText): pywikibot.output('Repairing references tag') return re.sub(pattern, '<references>\1</references>', oldText) # Repair single unclosed references tag pattern = re.compile(r'< *references *>') if pattern.search(oldText): pywikibot.output('Repairing references tag') return re.sub(pattern, '<references />', oldText) # Is there an existing section where we can add the references tag? for section in i18n.translate(self.site, referencesSections): sectionR = re.compile(r'\r?\n=+ *%s *=+ *\r?\n' % section) index = 0 while index < len(oldText): match = sectionR.search(oldText, index) if match: if textlib.isDisabled(oldText, match.start()): pywikibot.output( 'Existing %s section is commented out, skipping.' % section) index = match.end() else: pywikibot.output( 'Adding references tag to existing %s section...\n' % section) newText = ( oldText[:match.end()] + u'\n' + self.referencesText + u'\n' + oldText[match.end():] ) return newText else: break # Create a new section for the references tag for section in i18n.translate(self.site, placeBeforeSections): # Find out where to place the new section sectionR = re.compile(r'\r?\n(?P<ident>=+) *%s *(?P=ident) *\r?\n' % section) index = 0 while index < len(oldText): match = sectionR.search(oldText, index) if match: if textlib.isDisabled(oldText, match.start()): pywikibot.output( 'Existing %s section is commented out, won\'t add ' 'the references in front of it.' % section) index = match.end() else: pywikibot.output( u'Adding references section before %s section...\n' % section) index = match.start() ident = match.group('ident') return self.createReferenceSection(oldText, index, ident) else: break # This gets complicated: we want to place the new references # section over the interwiki links and categories, but also # over all navigation bars, persondata, and other templates # that are at the bottom of the page. So we need some advanced # regex magic. # The strategy is: create a temporary copy of the text. From that, # keep removing interwiki links, templates etc. from the bottom. # At the end, look at the length of the temp text. That's the position # where we'll insert the references section. catNamespaces = '|'.join(self.site.namespaces.CATEGORY) categoryPattern = r'\[\[\s*(%s)\s*:[^\n]*\]\]\s*' % catNamespaces interwikiPattern = r'\[\[([a-zA-Z\-]+)\s?:([^\[\]\n]*)\]\]\s*' # won't work with nested templates # the negative lookahead assures that we'll match the last template # occurrence in the temp text. # FIXME: # {{commons}} or {{commonscat}} are part of Weblinks section # * {{template}} is mostly part of a section # so templatePattern must be fixed templatePattern = r'\r?\n{{((?!}}).)+?}}\s*' commentPattern = r'<!--((?!-->).)*?-->\s*' metadataR = re.compile(r'(\r?\n)?(%s|%s|%s|%s)$' % (categoryPattern, interwikiPattern, templatePattern, commentPattern), re.DOTALL) tmpText = oldText while True: match = metadataR.search(tmpText) if match: tmpText = tmpText[:match.start()] else: break pywikibot.output( u'Found no section that can be preceeded by a new references ' u'section.\nPlacing it before interwiki links, categories, and ' u'bottom templates.') index = len(tmpText) return self.createReferenceSection(oldText, index) def createReferenceSection(self, oldText, index, ident='=='): """Create a reference section and insert it into the given text.""" if self.site.code in noTitleRequired: newSection = u'\n%s\n' % (self.referencesText) else: newSection = u'\n%s %s %s\n%s\n' % (ident, i18n.translate( self.site, referencesSections)[0], ident, self.referencesText) return oldText[:index] + newSection + oldText[index:] def run(self): """Run the bot.""" for page in self.generator: self.current_page = page try: text = page.text except pywikibot.NoPage: pywikibot.output(u"Page %s does not exist?!" % page.title(asLink=True)) continue except pywikibot.IsRedirectPage: pywikibot.output(u"Page %s is a redirect; skipping." % page.title(asLink=True)) continue except pywikibot.LockedPage: pywikibot.output(u"Page %s is locked?!" % page.title(asLink=True)) continue if page.isDisambig(): pywikibot.output(u"Page %s is a disambig; skipping." % page.title(asLink=True)) continue if self.site.sitename == 'wikipedia:en' and page.isIpEdit(): pywikibot.output( u"Page %s is edited by IP. Possible vandalized" % page.title(asLink=True)) continue if self.lacksReferences(text): newText = self.addReferences(text) try: self.userPut(page, page.text, newText, summary=self.comment) except pywikibot.EditConflict: pywikibot.output(u'Skipping %s because of edit conflict' % page.title()) except pywikibot.SpamfilterError as e: pywikibot.output( u'Cannot change %s because of blacklist entry %s' % (page.title(), e.url)) except pywikibot.LockedPage: pywikibot.output(u'Skipping %s (locked page)' % page.title()) def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ options = {} # Process global args and prepare generator args parser local_args = pywikibot.handle_args(args) genFactory = pagegenerators.GeneratorFactory() for arg in local_args: if arg.startswith('-xml'): if len(arg) == 4: xmlFilename = i18n.input('pywikibot-enter-xml-filename') else: xmlFilename = arg[5:] genFactory.gens.append(XmlDumpNoReferencesPageGenerator(xmlFilename)) elif arg == '-always': options['always'] = True elif arg == '-quiet': options['verbose'] = False else: genFactory.handleArg(arg) gen = genFactory.getCombinedGenerator() if not gen: site = pywikibot.Site() try: cat = site.expand_text( site.mediawiki_message(maintenance_category)) except: pass else: cat = pywikibot.Category(site, "%s:%s" % ( site.namespaces.CATEGORY, cat)) gen = cat.articles(namespaces=genFactory.namespaces or [0]) if gen: bot = NoReferencesBot(gen, **options) bot.run() return True else: pywikibot.bot.suggest_help(missing_generator=True) return False if __name__ == "__main__": main()
icyflame/batman
scripts/noreferences.py
Python
mit
25,133
0.000331
import subprocess import os import sys import commands import numpy as np import pyroms import pyroms_toolbox from remap_bio_woa import remap_bio_woa from remap_bio_glodap import remap_bio_glodap data_dir_woa = '/archive/u1/uaf/kate/COBALT/' data_dir_glodap = '/archive/u1/uaf/kate/COBALT/' dst_dir='./' src_grd = pyroms_toolbox.BGrid_GFDL.get_nc_BGrid_GFDL('/archive/u1/uaf/kate/COBALT/GFDL_CM2.1_grid.nc', name='ESM2M_NWGOA3') dst_grd = pyroms.grid.get_ROMS_grid('NWGOA3') # define all tracer stuff list_tracer = ['alk', 'cadet_arag', 'cadet_calc', 'dic', 'fed', 'fedet', 'fedi', 'felg', 'fesm', 'ldon', 'ldop', 'lith', 'lithdet', 'nbact', 'ndet', 'ndi', 'nlg', 'nsm', 'nh4', 'no3', 'o2', 'pdet', 'po4', 'srdon', 'srdop', 'sldon', 'sldop', 'sidet', 'silg', 'sio4', 'nsmz', 'nmdz', 'nlgz'] tracer_longname = ['Alkalinity', 'Detrital CaCO3', 'Detrital CaCO3', 'Dissolved Inorganic Carbon', 'Dissolved Iron', 'Detrital Iron', 'Diazotroph Iron', 'Large Phytoplankton Iron', 'Small Phytoplankton Iron', 'labile DON', 'labile DOP', 'Lithogenic Aluminosilicate', 'lithdet', 'bacterial', 'ndet', 'Diazotroph Nitrogen', 'Large Phytoplankton Nitrogen', 'Small Phytoplankton Nitrogen', 'Ammonia', 'Nitrate', 'Oxygen', 'Detrital Phosphorus', 'Phosphate', 'Semi-Refractory DON', 'Semi-Refractory DOP', 'Semilabile DON', 'Semilabile DOP', 'Detrital Silicon', 'Large Phytoplankton Silicon', 'Silicate', 'Small Zooplankton Nitrogen', 'Medium-sized zooplankton Nitrogen', 'large Zooplankton Nitrogen'] tracer_units = ['mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'g/kg', 'g/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg', 'mol/kg'] #------- WOA13 --------------------------------- id_tracer_update_woa = [19,20,22,29] list_tracer_update_woa = [] tracer_longname_update_woa = [] tracer_units_update_woa = [] for idtra in id_tracer_update_woa: print list_tracer[idtra] for idtra in id_tracer_update_woa: # add to tracer update list_tracer_update_woa.append(list_tracer[idtra]) tracer_longname_update_woa.append(tracer_longname[idtra]) tracer_units_update_woa.append(tracer_units[idtra]) for mm in np.arange(12): clim_file = dst_dir + dst_grd.name + '_clim_bio_GFDL+WOA+GLODAP_m' + str(mm+1).zfill(2) + '.nc' print '\nBuild CLIM file for month', mm for ktr in np.arange(len(list_tracer_update_woa)): ctra = list_tracer_update_woa[ktr] if ctra == 'sio4': ctra = 'si' mydict = {'tracer':list_tracer_update_woa[ktr],'longname':tracer_longname_update_woa[ktr],'units':tracer_units_update_woa[ktr],'file':data_dir_woa + ctra + '_WOA13-CM2.1_monthly.nc', \ 'frame':mm} remap_bio_woa(mydict, src_grd, dst_grd, dst_dir=dst_dir) out_file = dst_dir + dst_grd.name + '_clim_bio_' + list_tracer_update_woa[ktr] + '.nc' command = ('ncks', '-a', '-A', out_file, clim_file) subprocess.check_call(command) os.remove(out_file) #--------- GLODAP ------------------------------- id_tracer_update_glodap = [0,3] list_tracer_update_glodap = [] tracer_longname_update_glodap = [] tracer_units_update_glodap = [] for idtra in id_tracer_update_glodap: print list_tracer[idtra] for idtra in id_tracer_update_glodap: # add to tracer update list_tracer_update_glodap.append(list_tracer[idtra]) tracer_longname_update_glodap.append(tracer_longname[idtra]) tracer_units_update_glodap.append(tracer_units[idtra]) for mm in np.arange(12): clim_file = dst_dir + dst_grd.name + '_clim_bio_GFDL+WOA+GLODAP_m' + str(mm+1).zfill(2) + '.nc' print '\nBuild CLIM file for month', mm for ktr in np.arange(len(list_tracer_update_glodap)): ctra = list_tracer_update_glodap[ktr] mydict = {'tracer':list_tracer_update_glodap[ktr],'longname':tracer_longname_update_glodap[ktr],'units':tracer_units_update_glodap[ktr],'file':data_dir_glodap + ctra + '_GLODAP-ESM2M_annual.nc', \ 'frame':mm} remap_bio_glodap(mydict, src_grd, dst_grd, dst_dir=dst_dir) out_file = dst_dir + dst_grd.name + '_clim_bio_' + list_tracer_update_glodap[ktr] + '.nc' command = ('ncks', '-a', '-A', out_file, clim_file) subprocess.check_call(command) os.remove(out_file)
kshedstrom/pyroms
examples/cobalt-preproc/Clim_bio/make_clim_file_bio_addons.py
Python
bsd-3-clause
4,460
0.01009
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel 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 urllib import time import random import urlparse import hmac import binascii import httplib2 try: from urlparse import parse_qs except ImportError: from cgi import parse_qs VERSION = '1.0' # Hi Blaine! HTTP_METHOD = 'GET' SIGNATURE_METHOD = 'PLAINTEXT' class Error(RuntimeError): """Generic exception class.""" def __init__(self, message='OAuth error occurred.'): self._message = message @property def message(self): """A hack to get around the deprecation errors in 2.6.""" return self._message def __str__(self): return self._message class MissingSignature(Error): pass def build_authenticate_header(realm=''): """Optional WWW-Authenticate header (401 error)""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} def build_xoauth_string(url, consumer, token=None): """Build an XOAUTH string for use in SMTP/IMPA authentication.""" request = Request.from_consumer_and_token(consumer, token, "GET", url) signing_method = SignatureMethod_HMAC_SHA1() request.sign_request(signing_method, consumer, token) params = [] for k, v in sorted(request.iteritems()): if v is not None: params.append('%s="%s"' % (k, escape(v))) return "%s %s %s" % ("GET", url, ','.join(params)) def escape(s): """Escape a URL including any /.""" return urllib.quote(s, safe='~') def generate_timestamp(): """Get seconds since epoch (UTC).""" return int(time.time()) def generate_nonce(length=8): """Generate pseudorandom number.""" return ''.join([str(random.randint(0, 9)) for i in range(length)]) def generate_verifier(length=8): """Generate pseudorandom number.""" return ''.join([str(random.randint(0, 9)) for i in range(length)]) class Consumer(object): """A consumer of OAuth-protected services. The OAuth consumer is a "third-party" service that wants to access protected resources from an OAuth service provider on behalf of an end user. It's kind of the OAuth client. Usually a consumer must be registered with the service provider by the developer of the consumer software. As part of that process, the service provider gives the consumer a *key* and a *secret* with which the consumer software can identify itself to the service. The consumer will include its key in each request to identify itself, but will use its secret only when signing requests, to prove that the request is from that particular registered consumer. Once registered, the consumer can then use its consumer credentials to ask the service provider for a request token, kicking off the OAuth authorization process. """ key = None secret = None def __init__(self, key, secret): self.key = key self.secret = secret if self.key is None or self.secret is None: raise ValueError("Key and secret must be set.") def __str__(self): data = {'oauth_consumer_key': self.key, 'oauth_consumer_secret': self.secret} return urllib.urlencode(data) class Token(object): """An OAuth credential used to request authorization or a protected resource. Tokens in OAuth comprise a *key* and a *secret*. The key is included in requests to identify the token being used, but the secret is used only in the signature, to prove that the requester is who the server gave the token to. When first negotiating the authorization, the consumer asks for a *request token* that the live user authorizes with the service provider. The consumer then exchanges the request token for an *access token* that can be used to access protected resources. """ key = None secret = None callback = None callback_confirmed = None verifier = None def __init__(self, key, secret): self.key = key self.secret = secret if self.key is None or self.secret is None: raise ValueError("Key and secret must be set.") def set_callback(self, callback): self.callback = callback self.callback_confirmed = 'true' def set_verifier(self, verifier=None): if verifier is not None: self.verifier = verifier else: self.verifier = generate_verifier() def get_callback_url(self): if self.callback and self.verifier: # Append the oauth_verifier. parts = urlparse.urlparse(self.callback) scheme, netloc, path, params, query, fragment = parts[:6] if query: query = '%s&oauth_verifier=%s' % (query, self.verifier) else: query = 'oauth_verifier=%s' % self.verifier return urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) return self.callback def to_string(self): """Returns this token as a plain string, suitable for storage. The resulting string includes the token's secret, so you should never send or store this string where a third party can read it. """ data = { 'oauth_token': self.key, 'oauth_token_secret': self.secret, } if self.callback_confirmed is not None: data['oauth_callback_confirmed'] = self.callback_confirmed return urllib.urlencode(data) @staticmethod def from_string(s): """Deserializes a token from a string like one returned by `to_string()`.""" if not len(s): raise ValueError("Invalid parameter string.") params = parse_qs(s, keep_blank_values=False) if not len(params): raise ValueError("Invalid parameter string.") try: key = params['oauth_token'][0] except Exception: raise ValueError("'oauth_token' not found in OAuth request.") try: secret = params['oauth_token_secret'][0] except Exception: raise ValueError("'oauth_token_secret' not found in " "OAuth request.") token = Token(key, secret) try: token.callback_confirmed = params['oauth_callback_confirmed'][0] except KeyError: pass # 1.0, no callback confirmed. return token def __str__(self): return self.to_string() def setter(attr): name = attr.__name__ def getter(self): try: return self.__dict__[name] except KeyError: raise AttributeError(name) def deleter(self): del self.__dict__[name] return property(getter, attr, deleter) class Request(dict): """The parameters and information for an HTTP request, suitable for authorizing with OAuth credentials. When a consumer wants to access a service's protected resources, it does so using a signed HTTP request identifying itself (the consumer) with its key, and providing an access token authorized by the end user to access those resources. """ version = VERSION def __init__(self, method=HTTP_METHOD, url=None, parameters=None): self.method = method self.url = url if parameters is not None: self.update(parameters) @setter def url(self, value): self.__dict__['url'] = value if value is not None: scheme, netloc, path, params, query, fragment = urlparse.urlparse(value) # Exclude default port numbers. if scheme == 'http' and netloc[-3:] == ':80': netloc = netloc[:-3] elif scheme == 'https' and netloc[-4:] == ':443': netloc = netloc[:-4] if scheme not in ('http', 'https'): raise ValueError("Unsupported URL %s (%s)." % (value, scheme)) # Normalized URL excludes params, query, and fragment. self.normalized_url = urlparse.urlunparse((scheme, netloc, path, None, None, None)) else: self.normalized_url = None self.__dict__['url'] = None @setter def method(self, value): self.__dict__['method'] = value.upper() def _get_timestamp_nonce(self): return self['oauth_timestamp'], self['oauth_nonce'] def get_nonoauth_parameters(self): """Get any non-OAuth parameters.""" return dict([(k, v) for k, v in self.iteritems() if not k.startswith('oauth_')]) def to_header(self, realm=''): """Serialize as a header for an HTTPAuth request.""" oauth_params = ((k, v) for k, v in self.items() if k.startswith('oauth_')) stringy_params = ((k, escape(str(v))) for k, v in oauth_params) header_params = ('%s="%s"' % (k, v) for k, v in stringy_params) params_header = ', '.join(header_params) auth_header = 'OAuth realm="%s"' % realm if params_header: auth_header = "%s, %s" % (auth_header, params_header) return {'Authorization': auth_header} def to_postdata(self): """Serialize as post data for a POST request.""" # tell urlencode to deal with sequence values and map them correctly # to resulting querystring. for example self["k"] = ["v1", "v2"] will # result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D return urllib.urlencode(self, True).replace('+', '%20') def to_url(self): """Serialize as a URL for a GET request.""" base_url = urlparse.urlparse(self.url) try: query = base_url.query except AttributeError: # must be python <2.5 query = base_url[4] query = parse_qs(query) for k, v in self.items(): query.setdefault(k, []).append(v) try: scheme = base_url.scheme netloc = base_url.netloc path = base_url.path params = base_url.params fragment = base_url.fragment except AttributeError: # must be python <2.5 scheme = base_url[0] netloc = base_url[1] path = base_url[2] params = base_url[3] fragment = base_url[5] url = (scheme, netloc, path, params, urllib.urlencode(query, True), fragment) return urlparse.urlunparse(url) def get_parameter(self, parameter): ret = self.get(parameter) if ret is None: raise Error('Parameter not found: %s' % parameter) return ret def get_normalized_parameters(self): """Return a string that contains the parameters that must be signed.""" items = [] for key, value in self.iteritems(): if key == 'oauth_signature': continue # 1.0a/9.1.1 states that kvp must be sorted by key, then by value, # so we unpack sequence values into multiple items for sorting. if hasattr(value, '__iter__'): items.extend((key, item) for item in value) else: items.append((key, value)) # Include any query string parameters from the provided URL query = urlparse.urlparse(self.url)[4] url_items = self._split_url_string(query).items() non_oauth_url_items = list([(k, v) for k, v in url_items if not k.startswith('oauth_')]) items.extend(non_oauth_url_items) encoded_str = urllib.urlencode(sorted(items)) # Encode signature parameters per Oauth Core 1.0 protocol # spec draft 7, section 3.6 # (http://tools.ietf.org/html/draft-hammer-oauth-07#section-3.6) # Spaces must be encoded with "%20" instead of "+" return encoded_str.replace('+', '%20').replace('%7E', '~') def sign_request(self, signature_method, consumer, token): """Set the signature parameter to the result of sign.""" if 'oauth_consumer_key' not in self: self['oauth_consumer_key'] = consumer.key if token and 'oauth_token' not in self: self['oauth_token'] = token.key self['oauth_signature_method'] = signature_method.name self['oauth_signature'] = signature_method.sign(self, consumer, token) @classmethod def make_timestamp(cls): """Get seconds since epoch (UTC).""" return str(int(time.time())) @classmethod def make_nonce(cls): """Generate pseudorandom number.""" return str(random.randint(0, 100000000)) @classmethod def from_request(cls, http_method, http_url, headers=None, parameters=None, query_string=None): """Combines multiple parameter sources.""" if parameters is None: parameters = {} # Headers if headers and 'Authorization' in headers: auth_header = headers['Authorization'] # Check that the authorization header is OAuth. if auth_header[:6] == 'OAuth ': auth_header = auth_header[6:] try: # Get the parameters from the header. header_params = cls._split_header(auth_header) parameters.update(header_params) except: raise Error('Unable to parse OAuth parameters from ' 'Authorization header.') # GET or POST query string. if query_string: query_params = cls._split_url_string(query_string) parameters.update(query_params) # URL parameters. param_str = urlparse.urlparse(http_url)[4] # query url_params = cls._split_url_string(param_str) parameters.update(url_params) if parameters: return cls(http_method, http_url, parameters) return None @classmethod def from_consumer_and_token(cls, consumer, token=None, http_method=HTTP_METHOD, http_url=None, parameters=None): if not parameters: parameters = {} defaults = { 'oauth_consumer_key': consumer.key, 'oauth_timestamp': cls.make_timestamp(), 'oauth_nonce': cls.make_nonce(), 'oauth_version': cls.version, } defaults.update(parameters) parameters = defaults if token: parameters['oauth_token'] = token.key if token.verifier: parameters['oauth_verifier'] = token.verifier return Request(http_method, http_url, parameters) @classmethod def from_token_and_callback(cls, token, callback=None, http_method=HTTP_METHOD, http_url=None, parameters=None): if not parameters: parameters = {} parameters['oauth_token'] = token.key if callback: parameters['oauth_callback'] = callback return cls(http_method, http_url, parameters) @staticmethod def _split_header(header): """Turn Authorization: header into parameters.""" params = {} parts = header.split(',') for param in parts: # Ignore realm parameter. if param.find('realm') > -1: continue # Remove whitespace. param = param.strip() # Split key-value. param_parts = param.split('=', 1) # Remove quotes and unescape the value. params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"')) return params @staticmethod def _split_url_string(param_str): """Turn URL string into parameters.""" parameters = parse_qs(param_str, keep_blank_values=False) for k, v in parameters.iteritems(): parameters[k] = urllib.unquote(v[0]) return parameters class Client(httplib2.Http): """OAuthClient is a worker to attempt to execute a request.""" def __init__(self, consumer, token=None, cache=None, timeout=None, proxy_info=None): if consumer is not None and not isinstance(consumer, Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, Token): raise ValueError("Invalid token.") self.consumer = consumer self.token = token self.method = SignatureMethod_HMAC_SHA1() httplib2.Http.__init__(self, cache=cache, timeout=timeout, proxy_info=proxy_info) def set_signature_method(self, method): if not isinstance(method, SignatureMethod): raise ValueError("Invalid signature method.") self.method = method def request(self, uri, method="GET", body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): DEFAULT_CONTENT_TYPE = 'application/x-www-form-urlencoded' if not isinstance(headers, dict): headers = {} is_multipart = method == 'POST' and headers.get('Content-Type', DEFAULT_CONTENT_TYPE) != DEFAULT_CONTENT_TYPE if body and method == "POST" and not is_multipart: parameters = parse_qs(body) else: parameters = None req = Request.from_consumer_and_token(self.consumer, token=self.token, http_method=method, http_url=uri, parameters=parameters) req.sign_request(self.method, self.consumer, self.token) if method == "POST": headers['Content-Type'] = headers.get('Content-Type', DEFAULT_CONTENT_TYPE) if is_multipart: headers.update(req.to_header()) else: body = req.to_postdata() elif method == "GET": uri = req.to_url() else: headers.update(req.to_header()) return httplib2.Http.request(self, uri, method=method, body=body, headers=headers, redirections=redirections, connection_type=connection_type) class Server(object): """A skeletal implementation of a service provider, providing protected resources to requests from authorized consumers. This class implements the logic to check requests for authorization. You can use it with your web server or web framework to protect certain resources with OAuth. """ timestamp_threshold = 300 # In seconds, five minutes. version = VERSION signature_methods = None def __init__(self, signature_methods=None): self.signature_methods = signature_methods or {} def add_signature_method(self, signature_method): self.signature_methods[signature_method.name] = signature_method return self.signature_methods def verify_request(self, request, consumer, token): """Verifies an api call and checks all the parameters.""" version = self._get_version(request) self._check_signature(request, consumer, token) parameters = request.get_nonoauth_parameters() return parameters def build_authenticate_header(self, realm=''): """Optional support for the authenticate header.""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} def _get_version(self, request): """Verify the correct version request for this server.""" try: version = request.get_parameter('oauth_version') except: version = VERSION if version and version != self.version: raise Error('OAuth version %s not supported.' % str(version)) return version def _get_signature_method(self, request): """Figure out the signature with some defaults.""" try: signature_method = request.get_parameter('oauth_signature_method') except: signature_method = SIGNATURE_METHOD try: # Get the signature method object. signature_method = self.signature_methods[signature_method] except: signature_method_names = ', '.join(self.signature_methods.keys()) raise Error('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names)) return signature_method def _get_verifier(self, request): return request.get_parameter('oauth_verifier') def _check_signature(self, request, consumer, token): timestamp, nonce = request._get_timestamp_nonce() self._check_timestamp(timestamp) signature_method = self._get_signature_method(request) try: signature = request.get_parameter('oauth_signature') except: raise MissingSignature('Missing oauth_signature.') # Validate the signature. valid = signature_method.check(request, consumer, token, signature) if not valid: key, base = signature_method.signing_base(request, consumer, token) raise Error('Invalid signature. Expected signature base ' 'string: %s' % base) built = signature_method.sign(request, consumer, token) def _check_timestamp(self, timestamp): """Verify that timestamp is recentish.""" timestamp = int(timestamp) now = int(time.time()) lapsed = now - timestamp if lapsed > self.timestamp_threshold: raise Error('Expired timestamp: given %d and now %s has a ' 'greater difference than threshold %d' % (timestamp, now, self.timestamp_threshold)) class SignatureMethod(object): """A way of signing requests. The OAuth protocol lets consumers and service providers pick a way to sign requests. This interface shows the methods expected by the other `oauth` modules for signing requests. Subclass it and implement its methods to provide a new way to sign requests. """ def signing_base(self, request, consumer, token): """Calculates the string that needs to be signed. This method returns a 2-tuple containing the starting key for the signing and the message to be signed. The latter may be used in error messages to help clients debug their software. """ raise NotImplementedError def sign(self, request, consumer, token): """Returns the signature for the given request, based on the consumer and token also provided. You should use your implementation of `signing_base()` to build the message to sign. Otherwise it may be less useful for debugging. """ raise NotImplementedError def check(self, request, consumer, token, signature): """Returns whether the given signature is the correct signature for the given consumer and token signing the given request.""" built = self.sign(request, consumer, token) return built == signature class SignatureMethod_HMAC_SHA1(SignatureMethod): name = 'HMAC-SHA1' def signing_base(self, request, consumer, token): if request.normalized_url is None: raise ValueError("Base URL for request is not set.") sig = ( escape(request.method), escape(request.normalized_url), escape(request.get_normalized_parameters()), ) key = '%s&' % escape(consumer.secret) if token: key += escape(token.secret) raw = '&'.join(sig) return key, raw def sign(self, request, consumer, token): """Builds the base signature string.""" key, raw = self.signing_base(request, consumer, token) # HMAC object. try: from hashlib import sha1 as sha except ImportError: import sha # Deprecated hashed = hmac.new(key, raw, sha) # Calculate the digest base 64. return binascii.b2a_base64(hashed.digest())[:-1] class SignatureMethod_PLAINTEXT(SignatureMethod): name = 'PLAINTEXT' def signing_base(self, request, consumer, token): """Concatenates the consumer key and secret with the token's secret.""" sig = '%s&' % escape(consumer.secret) if token: sig = sig + escape(token.secret) return sig, sig def sign(self, request, consumer, token): key, raw = self.signing_base(request, consumer, token) return raw
jiivan/python-oauth2
oauth2/__init__.py
Python
mit
25,600
0.003984
# -*- coding: utf-8 -*- # # Copyright (C) 2007-2009 Edgewall Software # Copyright (C) 2007 Alec Thomas <alec@swapoff.org> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://trac.edgewall.org/log/. # # Author: Alec Thomas <alec@swapoff.org> from fnmatch import fnmatch from itertools import groupby import os from trac.core import * from trac.config import Option from trac.perm import PermissionSystem, IPermissionPolicy ConfigObj = None try: from configobj import ConfigObj except ImportError: pass class AuthzPolicy(Component): """Permission policy using an authz-like configuration file. Refer to SVN documentation for syntax of the authz file. Groups are supported. As the fine-grained permissions brought by this permission policy are often used in complement of the other pemission policies (like the `DefaultPermissionPolicy`), there's no need to redefine all the permissions here. Only additional rights or restrictions should be added. === Installation === Note that this plugin requires the `configobj` package: http://www.voidspace.org.uk/python/configobj.html You should be able to install it by doing a simple `easy_install configobj` Enabling this policy requires listing it in `trac.ini: {{{ [trac] permission_policies = AuthzPolicy, DefaultPermissionPolicy [authz_policy] authz_file = conf/authzpolicy.conf }}} This means that the `AuthzPolicy` permissions will be checked first, and only if no rule is found will the `DefaultPermissionPolicy` be used. === Configuration === The `authzpolicy.conf` file is a `.ini` style configuration file. - Each section of the config is a glob pattern used to match against a Trac resource descriptor. These descriptors are in the form: {{{ <realm>:<id>@<version>[/<realm>:<id>@<version> ...] }}} Resources are ordered left to right, from parent to child. If any component is inapplicable, `*` is substituted. If the version pattern is not specified explicitely, all versions (`@*`) is added implicitly Example: Match the WikiStart page {{{ [wiki:*] [wiki:WikiStart*] [wiki:WikiStart@*] [wiki:WikiStart] }}} Example: Match the attachment `wiki:WikiStart@117/attachment/FOO.JPG@*` on WikiStart {{{ [wiki:*] [wiki:WikiStart*] [wiki:WikiStart@*] [wiki:WikiStart@*/attachment/*] [wiki:WikiStart@117/attachment/FOO.JPG] }}} - Sections are checked against the current Trac resource '''IN ORDER''' of appearance in the configuration file. '''ORDER IS CRITICAL'''. - Once a section matches, the current username is matched, '''IN ORDER''', against the keys of the section. If a key is prefixed with a `@`, it is treated as a group. If a key is prefixed with a `!`, the permission is denied rather than granted. The username will match any of 'anonymous', 'authenticated', <username> or '*', using normal Trac permission rules. Example configuration: {{{ [groups] administrators = athomas [*/attachment:*] * = WIKI_VIEW, TICKET_VIEW [wiki:WikiStart@*] @administrators = WIKI_ADMIN anonymous = WIKI_VIEW * = WIKI_VIEW # Deny access to page templates [wiki:PageTemplates/*] * = # Match everything else [*] @administrators = TRAC_ADMIN anonymous = BROWSER_VIEW, CHANGESET_VIEW, FILE_VIEW, LOG_VIEW, MILESTONE_VIEW, POLL_VIEW, REPORT_SQL_VIEW, REPORT_VIEW, ROADMAP_VIEW, SEARCH_VIEW, TICKET_CREATE, TICKET_MODIFY, TICKET_VIEW, TIMELINE_VIEW, WIKI_CREATE, WIKI_MODIFY, WIKI_VIEW # Give authenticated users some extra permissions authenticated = REPO_SEARCH, XML_RPC }}} """ implements(IPermissionPolicy) authz_file = Option('authz_policy', 'authz_file', None, 'Location of authz policy configuration file.') authz = None authz_mtime = None # IPermissionPolicy methods def check_permission(self, action, username, resource, perm): if ConfigObj is None: self.log.error('configobj package not found') return None if self.authz_file and not self.authz_mtime or \ os.path.getmtime(self.get_authz_file()) > self.authz_mtime: self.parse_authz() resource_key = self.normalise_resource(resource) self.log.debug('Checking %s on %s', action, resource_key) permissions = self.authz_permissions(resource_key, username) if permissions is None: return None # no match, can't decide elif permissions == ['']: return False # all actions are denied # FIXME: expand all permissions once for all ps = PermissionSystem(self.env) for deny, perms in groupby(permissions, key=lambda p: p.startswith('!')): if deny and action in ps.expand_actions([p[1:] for p in perms]): return False # action is explicitly denied elif action in ps.expand_actions(perms): return True # action is explicitly granted return None # no match for action, can't decide # Internal methods def get_authz_file(self): f = self.authz_file return os.path.isabs(f) and f or os.path.join(self.env.path, f) def parse_authz(self): self.env.log.debug('Parsing authz security policy %s' % self.get_authz_file()) self.authz = ConfigObj(self.get_authz_file()) self.groups_by_user = {} for group, users in self.authz.get('groups', {}).iteritems(): if isinstance(users, basestring): users = [users] for user in users: self.groups_by_user.setdefault(user, set()).add('@' + group) self.authz_mtime = os.path.getmtime(self.get_authz_file()) def normalise_resource(self, resource): def flatten(resource): if not resource or not (resource.realm or resource.id): return [] # XXX Due to the mixed functionality in resource we can end up with # ticket, ticket:1, ticket:1@10. This code naively collapses all # subsets of the parent resource into one. eg. ticket:1@10 parent = resource.parent while parent and (resource.realm == parent.realm or \ (resource.realm == parent.realm and resource.id == parent.id)): parent = parent.parent if parent: parent = flatten(parent) else: parent = [] return parent + ['%s:%s@%s' % (resource.realm or '*', resource.id or '*', resource.version or '*')] return '/'.join(flatten(resource)) def authz_permissions(self, resource_key, username): # TODO: Handle permission negation in sections. eg. "if in this # ticket, remove TICKET_MODIFY" valid_users = ['*', 'anonymous'] if username and username != 'anonymous': valid_users = ['*', 'authenticated', username] for resource_section in [a for a in self.authz.sections if a != 'groups']: resource_glob = resource_section if '@' not in resource_glob: resource_glob += '@*' if fnmatch(resource_key, resource_glob): section = self.authz[resource_section] for who, permissions in section.iteritems(): if who in valid_users or \ who in self.groups_by_user.get(username, []): self.env.log.debug('%s matched section %s for user %s' % (resource_key, resource_glob, username)) if isinstance(permissions, basestring): return [permissions] else: return permissions return None
dokipen/trac
tracopt/perm/authz_policy.py
Python
bsd-3-clause
8,731
0.002978
# Copyright (c) 2013 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 containing the different outputs. Each output type is defined inside a module. """
v-legoff/croissant
croissant/output/__init__.py
Python
bsd-3-clause
1,636
0
from django import forms from event.models import Event class EventForm(forms.ModelForm): class Meta: model = Event fields = [ 'date', 'starttime', 'endtime', 'event', 'location', 'organization', 'speakers', 'rating', 'feedback' ]
kwailamchan/programming-languages
python/django/elf/elf/src/event/forms.py
Python
mit
332
0.006024
ucodes = { "U0001" : "High Speed CAN Communication Bus" , "U0002" : "High Speed CAN Communication Bus (Performance)" , "U0003" : "High Speed CAN Communication Bus (Open)" , "U0004" : "High Speed CAN Communication Bus (Low)" , "U0005" : "High Speed CAN Communication Bus (High)" , "U0006" : "High Speed CAN Communication Bus (Open)" , "U0007" : "High Speed CAN Communication Bus (Low)" , "U0008" : "High Speed CAN Communication Bus (High)" , "U0009" : "High Speed CAN Communication Bus (shorted to Bus)" , "U0010" : "Medium Speed CAN Communication Bus" , "U0011" : "Medium Speed CAN Communication Bus (Performance)" , "U0012" : "Medium Speed CAN Communication Bus (Open)" , "U0013" : "Medium Speed CAN Communication Bus (Low)" , "U0014" : "Medium Speed CAN Communication Bus (High)" , "U0015" : "Medium Speed CAN Communication Bus (Open)" , "U0016" : "Medium Speed CAN Communication Bus (Low)" , "U0017" : "Medium Speed CAN Communication Bus (High)" , "U0018" : "Medium Speed CAN Communication Bus (shorted to Bus)" , "U0019" : "Low Speed CAN Communication Bus" , "U0020" : "Low Speed CAN Communication Bus (Performance)" , "U0021" : "Low Speed CAN Communication Bus (Open)" , "U0022" : "Low Speed CAN Communication Bus (Low)" , "U0023" : "Low Speed CAN Communication Bus (High)" , "U0024" : "Low Speed CAN Communication Bus (Open)" , "U0025" : "Low Speed CAN Communication Bus (Low)" , "U0026" : "Low Speed CAN Communication Bus (High)" , "U0027" : "Low Speed CAN Communication Bus (shorted to Bus)" , "U0028" : "Vehicle Communication Bus A" , "U0029" : "Vehicle Communication Bus A (Performance)" , "U0030" : "Vehicle Communication Bus A (Open)" , "U0031" : "Vehicle Communication Bus A (Low)" , "U0032" : "Vehicle Communication Bus A (High)" , "U0033" : "Vehicle Communication Bus A (Open)" , "U0034" : "Vehicle Communication Bus A (Low)" , "U0035" : "Vehicle Communication Bus A (High)" , "U0036" : "Vehicle Communication Bus A (shorted to Bus A)" , "U0037" : "Vehicle Communication Bus B" , "U0038" : "Vehicle Communication Bus B (Performance)" , "U0039" : "Vehicle Communication Bus B (Open)" , "U0040" : "Vehicle Communication Bus B (Low)" , "U0041" : "Vehicle Communication Bus B (High)" , "U0042" : "Vehicle Communication Bus B (Open)" , "U0043" : "Vehicle Communication Bus B (Low)" , "U0044" : "Vehicle Communication Bus B (High)" , "U0045" : "Vehicle Communication Bus B (shorted to Bus B)" , "U0046" : "Vehicle Communication Bus C" , "U0047" : "Vehicle Communication Bus C (Performance)" , "U0048" : "Vehicle Communication Bus C (Open)" , "U0049" : "Vehicle Communication Bus C (Low)" , "U0050" : "Vehicle Communication Bus C (High)" , "U0051" : "Vehicle Communication Bus C (Open)" , "U0052" : "Vehicle Communication Bus C (Low)" , "U0053" : "Vehicle Communication Bus C (High)" , "U0054" : "Vehicle Communication Bus C (shorted to Bus C)" , "U0055" : "Vehicle Communication Bus D" , "U0056" : "Vehicle Communication Bus D (Performance)" , "U0057" : "Vehicle Communication Bus D (Open)" , "U0058" : "Vehicle Communication Bus D (Low)" , "U0059" : "Vehicle Communication Bus D (High)" , "U0060" : "Vehicle Communication Bus D (Open)" , "U0061" : "Vehicle Communication Bus D (Low)" , "U0062" : "Vehicle Communication Bus D (High)" , "U0063" : "Vehicle Communication Bus D (shorted to Bus D)" , "U0064" : "Vehicle Communication Bus E" , "U0065" : "Vehicle Communication Bus E (Performance)" , "U0066" : "Vehicle Communication Bus E (Open)" , "U0067" : "Vehicle Communication Bus E (Low)" , "U0068" : "Vehicle Communication Bus E (High)" , "U0069" : "Vehicle Communication Bus E (Open)" , "U0070" : "Vehicle Communication Bus E (Low)" , "U0071" : "Vehicle Communication Bus E (High)" , "U0072" : "Vehicle Communication Bus E (shorted to Bus E)" , "U0073" : "Control Module Communication Bus Off" , "U0074" : "Reserved by J2012" , "U0075" : "Reserved by J2012" , "U0076" : "Reserved by J2012" , "U0077" : "Reserved by J2012" , "U0078" : "Reserved by J2012" , "U0079" : "Reserved by J2012" , "U0080" : "Reserved by J2012" , "U0081" : "Reserved by J2012" , "U0082" : "Reserved by J2012" , "U0083" : "Reserved by J2012" , "U0084" : "Reserved by J2012" , "U0085" : "Reserved by J2012" , "U0086" : "Reserved by J2012" , "U0087" : "Reserved by J2012" , "U0088" : "Reserved by J2012" , "U0089" : "Reserved by J2012" , "U0090" : "Reserved by J2012" , "U0091" : "Reserved by J2012" , "U0092" : "Reserved by J2012" , "U0093" : "Reserved by J2012" , "U0094" : "Reserved by J2012" , "U0095" : "Reserved by J2012" , "U0096" : "Reserved by J2012" , "U0097" : "Reserved by J2012" , "U0098" : "Reserved by J2012" , "U0099" : "Reserved by J2012" , "U0100" : "Lost Communication With ECM/PCM A" , "U0101" : "Lost Communication with TCM" , "U0102" : "Lost Communication with Transfer Case Control Module" , "U0103" : "Lost Communication With Gear Shift Module" , "U0104" : "Lost Communication With Cruise Control Module" , "U0105" : "Lost Communication With Fuel Injector Control Module" , "U0106" : "Lost Communication With Glow Plug Control Module" , "U0107" : "Lost Communication With Throttle Actuator Control Module" , "U0108" : "Lost Communication With Alternative Fuel Control Module" , "U0109" : "Lost Communication With Fuel Pump Control Module" , "U0110" : "Lost Communication With Drive Motor Control Module" , "U0111" : "Lost Communication With Battery Energy Control Module 'A'" , "U0112" : "Lost Communication With Battery Energy Control Module 'B'" , "U0113" : "Lost Communication With Emissions Critical Control Information" , "U0114" : "Lost Communication With Four-Wheel Drive Clutch Control Module" , "U0115" : "Lost Communication With ECM/PCM B" , "U0116" : "Reserved by J2012" , "U0117" : "Reserved by J2012" , "U0118" : "Reserved by J2012" , "U0119" : "Reserved by J2012" , "U0120" : "Reserved by J2012" , "U0121" : "Lost Communication With Anti-Lock Brake System (ABS) Control Module" , "U0122" : "Lost Communication With Vehicle Dynamics Control Module" , "U0123" : "Lost Communication With Yaw Rate Sensor Module" , "U0124" : "Lost Communication With Lateral Acceleration Sensor Module" , "U0125" : "Lost Communication With Multi-axis Acceleration Sensor Module" , "U0126" : "Lost Communication With Steering Angle Sensor Module" , "U0127" : "Lost Communication With Tire Pressure Monitor Module" , "U0128" : "Lost Communication With Park Brake Control Module" , "U0129" : "Lost Communication With Brake System Control Module" , "U0130" : "Lost Communication With Steering Effort Control Module" , "U0131" : "Lost Communication With Power Steering Control Module" , "U0132" : "Lost Communication With Ride Level Control Module" , "U0133" : "Reserved by J2012" , "U0134" : "Reserved by J2012" , "U0135" : "Reserved by J2012" , "U0136" : "Reserved by J2012" , "U0137" : "Reserved by J2012" , "U0138" : "Reserved by J2012" , "U0139" : "Reserved by J2012" , "U0140" : "Lost Communication With Body Control Module" , "U0141" : "Lost Communication With Body Control Module 'A'" , "U0142" : "Lost Communication With Body Control Module 'B'" , "U0143" : "Lost Communication With Body Control Module 'C'" , "U0144" : "Lost Communication With Body Control Module 'D'" , "U0145" : "Lost Communication With Body Control Module 'E'" , "U0146" : "Lost Communication With Gateway 'A'" , "U0147" : "Lost Communication With Gateway 'B'" , "U0148" : "Lost Communication With Gateway 'C'" , "U0149" : "Lost Communication With Gateway 'D'" , "U0150" : "Lost Communication With Gateway 'E'" , "U0151" : "Lost Communication With Restraints Control Module" , "U0152" : "Lost Communication With Side Restraints Control Module Left" , "U0153" : "Lost Communication With Side Restraints Control Module Right" , "U0154" : "Lost Communication With Restraints Occupant Sensing Control Module" , "U0155" : "Lost Communication With Instrument Panel Cluster (IPC) Control Module" , "U0156" : "Lost Communication With Information Center 'A'" , "U0157" : "Lost Communication With Information Center 'B'" , "U0158" : "Lost Communication With Head Up Display" , "U0159" : "Lost Communication With Parking Assist Control Module" , "U0160" : "Lost Communication With Audible Alert Control Module" , "U0161" : "Lost Communication With Compass Module" , "U0162" : "Lost Communication With Navigation Display Module" , "U0163" : "Lost Communication With Navigation Control Module" , "U0164" : "Lost Communication With HVAC Control Module" , "U0165" : "Lost Communication With HVAC Control Module Rear" , "U0166" : "Lost Communication With Auxiliary Heater Control Module" , "U0167" : "Lost Communication With Vehicle Immobilizer Control Module" , "U0168" : "Lost Communication With Vehicle Security Control Module" , "U0169" : "Lost Communication With Sunroof Control Module" , "U0170" : "Lost Communication With 'Restraints System Sensor A'" , "U0171" : "Lost Communication With 'Restraints System Sensor B'" , "U0172" : "Lost Communication With 'Restraints System Sensor C'" , "U0173" : "Lost Communication With 'Restraints System Sensor D'" , "U0174" : "Lost Communication With 'Restraints System Sensor E'" , "U0175" : "Lost Communication With 'Restraints System Sensor F'" , "U0176" : "Lost Communication With 'Restraints System Sensor G'" , "U0177" : "Lost Communication With 'Restraints System Sensor H'" , "U0178" : "Lost Communication With 'Restraints System Sensor I'" , "U0179" : "Lost Communication With 'Restraints System Sensor J'" , "U0180" : "Lost Communication With Automatic Lighting Control Module" , "U0181" : "Lost Communication With Headlamp Leveling Control Module" , "U0182" : "Lost Communication With Lighting Control Module Front" , "U0183" : "Lost Communication With Lighting Control Module Rear" , "U0184" : "Lost Communication With Radio" , "U0185" : "Lost Communication With Antenna Control Module" , "U0186" : "Lost Communication With Audio Amplifier" , "U0187" : "Lost Communication With Digital Disc Player/Changer Module 'A'" , "U0188" : "Lost Communication With Digital Disc Player/Changer Module 'B'" , "U0189" : "Lost Communication With Digital Disc Player/Changer Module 'C'" , "U0190" : "Lost Communication With Digital Disc Player/Changer Module 'D'" , "U0191" : "Lost Communication With Television" , "U0192" : "Lost Communication With Personal Computer" , "U0193" : "Lost Communication With 'Digital Audio Control Module A'" , "U0194" : "Lost Communication With 'Digital Audio Control Module B'" , "U0195" : "Lost Communication With Subscription Entertainment Receiver Module" , "U0196" : "Lost Communication With Rear Seat Entertainment Control Module" , "U0197" : "Lost Communication With Telephone Control Module" , "U0198" : "Lost Communication With Telematic Control Module" , "U0199" : "Lost Communication With 'Door Control Module A'" , "U0200" : "Lost Communication With 'Door Control Module B'" , "U0201" : "Lost Communication With 'Door Control Module C'" , "U0202" : "Lost Communication With 'Door Control Module D'" , "U0203" : "Lost Communication With 'Door Control Module E'" , "U0204" : "Lost Communication With 'Door Control Module F'" , "U0205" : "Lost Communication With 'Door Control Module G'" , "U0206" : "Lost Communication With Folding Top Control Module" , "U0207" : "Lost Communication With Moveable Roof Control Module" , "U0208" : "Lost Communication With 'Seat Control Module A'" , "U0209" : "Lost Communication With 'Seat Control Module B'" , "U0210" : "Lost Communication With 'Seat Control Module C'" , "U0211" : "Lost Communication With 'Seat Control Module D'" , "U0212" : "Lost Communication With Steering Column Control Module" , "U0213" : "Lost Communication With Mirror Control Module" , "U0214" : "Lost Communication With Remote Function Actuation" , "U0215" : "Lost Communication With 'Door Switch A'" , "U0216" : "Lost Communication With 'Door Switch B'" , "U0217" : "Lost Communication With 'Door Switch C'" , "U0218" : "Lost Communication With 'Door Switch D'" , "U0219" : "Lost Communication With 'Door Switch E'" , "U0220" : "Lost Communication With 'Door Switch F'" , "U0221" : "Lost Communication With 'Door Switch G'" , "U0222" : "Lost Communication With 'Door Window Motor A'" , "U0223" : "Lost Communication With 'Door Window Motor B'" , "U0224" : "Lost Communication With 'Door Window Motor C'" , "U0225" : "Lost Communication With 'Door Window Motor D'" , "U0226" : "Lost Communication With 'Door Window Motor E'" , "U0227" : "Lost Communication With 'Door Window Motor F'" , "U0228" : "Lost Communication With 'Door Window Motor G'" , "U0229" : "Lost Communication With Heated Steering Wheel Module" , "U0230" : "Lost Communication With Rear Gate Module" , "U0231" : "Lost Communication With Rain Sensing Module" , "U0232" : "Lost Communication With Side Obstacle Detection Control Module Left" , "U0233" : "Lost Communication With Side Obstacle Detection Control Module Right" , "U0234" : "Lost Communication With Convenience Recall Module" , "U0235" : "Lost Communication With Cruise Control Front Distance Range Sensor" , "U0300" : "Internal Control Module Software Incompatibility" , "U0301" : "Software Incompatibility with ECM/PCM" , "U0302" : "Software Incompatibility with Transmission Control Module" , "U0303" : "Software Incompatibility with Transfer Case Control Module" , "U0304" : "Software Incompatibility with Gear Shift Control Module" , "U0305" : "Software Incompatibility with Cruise Control Module" , "U0306" : "Software Incompatibility with Fuel Injector Control Module" , "U0307" : "Software Incompatibility with Glow Plug Control Module" , "U0308" : "Software Incompatibility with Throttle Actuator Control Module" , "U0309" : "Software Incompatibility with Alternative Fuel Control Module" , "U0310" : "Software Incompatibility with Fuel Pump Control Module" , "U0311" : "Software Incompatibility with Drive Motor Control Module" , "U0312" : "Software Incompatibility with Battery Energy Control Module A" , "U0313" : "Software Incompatibility with Battery Energy Control Module B" , "U0314" : "Software Incompatibility with Four-Wheel Drive Clutch Control Module" , "U0315" : "Software Incompatibility with Anti-Lock Brake System Control Module" , "U0316" : "Software Incompatibility with Vehicle Dynamics Control Module" , "U0317" : "Software Incompatibility with Park Brake Control Module" , "U0318" : "Software Incompatibility with Brake System Control Module" , "U0319" : "Software Incompatibility with Steering Effort Control Module" , "U0320" : "Software Incompatibility with Power Steering Control Module" , "U0321" : "Software Incompatibility with Ride Level Control Module" , "U0322" : "Software Incompatibility with Body Control Module" , "U0323" : "Software Incompatibility with Instrument Panel Control Module" , "U0324" : "Software Incompatibility with HVAC Control Module" , "U0325" : "Software Incompatibility with Auxiliary Heater Control Module" , "U0326" : "Software Incompatibility with Vehicle Immobilizer Control Module" , "U0327" : "Software Incompatibility with Vehicle Security Control Module" , "U0328" : "Software Incompatibility with Steering Angle Sensor Module" , "U0329" : "Software Incompatibility with Steering Column Control Module" , "U0330" : "Software Incompatibility with Tire Pressure Monitor Module" , "U0331" : "Software Incompatibility with Body Control Module 'A'" , "U0400" : "Invalid Data Received" , "U0401" : "Invalid Data Received From ECM/PCM" , "U0402" : "Invalid Data Received From Transmission Control Module" , "U0403" : "Invalid Data Received From Transfer Case Control Module" , "U0404" : "Invalid Data Received From Gear Shift Control Module" , "U0405" : "Invalid Data Received From Cruise Control Module" , "U0406" : "Invalid Data Received From Fuel Injector Control Module" , "U0407" : "Invalid Data Received From Glow Plug Control Module" , "U0408" : "Invalid Data Received From Throttle Actuator Control Module" , "U0409" : "Invalid Data Received From Alternative Fuel Control Module" , "U0410" : "Invalid Data Received From Fuel Pump Control Module" , "U0411" : "Invalid Data Received From Drive Motor Control Module" , "U0412" : "Invalid Data Received From Battery Energy Control Module A" , "U0413" : "Invalid Data Received From Battery Energy Control Module B" , "U0414" : "Invalid Data Received From Four-Wheel Drive Clutch Control Module" , "U0415" : "Invalid Data Received From Anti-Lock Brake System Control Module" , "U0416" : "Invalid Data Received From Vehicle Dynamics Control Module" , "U0417" : "Invalid Data Received From Park Brake Control Module" , "U0418" : "Invalid Data Received From Brake System Control Module" , "U0419" : "Invalid Data Received From Steering Effort Control Module" , "U0420" : "Invalid Data Received From Power Steering Control Module" , "U0421" : "Invalid Data Received From Ride Level Control Module" , "U0422" : "Invalid Data Received From Body Control Module" , "U0423" : "Invalid Data Received From Instrument Panel Control Module" , "U0424" : "Invalid Data Received From HVAC Control Module" , "U0425" : "Invalid Data Received From Auxiliary Heater Control Module" , "U0426" : "Invalid Data Received From Vehicle Immobilizer Control Module" , "U0427" : "Invalid Data Received From Vehicle Security Control Module" , "U0428" : "Invalid Data Received From Steering Angle Sensor Module" , "U0429" : "Invalid Data Received From Steering Column Control Module" , "U0430" : "Invalid Data Received From Tire Pressure Monitor Module" , "U0431" : "Invalid Data Received From Body Control Module 'A'" }
lkarsten/pyobd
network_codes.py
Python
gpl-2.0
18,096
0.066589
from ._fs import Vlermv from ._s3 import S3Vlermv from . import serializers, transformers # For backwards compatibility cache = Vlermv.memoize
tlevine/vlermv
vlermv/__init__.py
Python
agpl-3.0
144
0
"""The base Controller API Provides the BaseController class for subclassing. """ from pylons.controllers import WSGIController from pylons.templating import render_mako as render from quanthistling.model.meta import Session #from quanthistling.lib.helpers import History from pylons import request, response, session, tmpl_context as c, url class BaseController(WSGIController): def __call__(self, environ, start_response): """Invoke the Controller""" # WSGIController.__call__ dispatches to the Controller method # the request is routed to. This routing information is # available in environ['pylons.routes_dict'] try: return WSGIController.__call__(self, environ, start_response) finally: Session.remove() # def __after__(self, action): # if 'history' in session: # c.history = session['history'] # print "History in session" # else: # c.history = History(20) # # # if hasattr(c, 'heading'): # c.history.add(c.heading, url) # # session['history'] = c.history # session.save() #
FrankNagel/qlc
src/webapp/quanthistling/quanthistling/lib/base.py
Python
gpl-3.0
1,177
0.004248
from gain import Css, Item, Parser, Xpath def test_parse(): html = '<title class="username">tom</title><div class="karma">15</div>' class User(Item): username = Xpath('//title') karma = Css('.karma') parser = Parser(html, User) user = parser.parse_item(html) assert user.results == { 'username': 'tom', 'karma': '15' } def test_parse_urls(): html = ('<a href="item?id=14447885">64comments</a>' '<a href="item?id=14447886">64comments</a>') class User(Item): username = Xpath('//title') karma = Css('.karma') parser = Parser('item\?id=\d+', User) parser.parse_urls(html, 'https://blog.scrapinghub.com') assert parser.pre_parse_urls.qsize() == 2
babykick/gain
tests/test_parser.py
Python
gpl-3.0
757
0.002642
import os import sys from Bio import SeqIO with open(sys.argv[1], "rU") as handle, open(sys.argv[2], "r") as segments, open(sys.argv[3],"w") as out_handle: """ This function takes fasta file as first argument. As second argument it takes tab delimited file containing queryid and start and end postion of segment of interest. Then trims unaligned parts of the sequence and outputs in out in new fasta file """ #first create dictionarry of QI and start postioions QI_pos_dict = dict() for lines in segments: line = lines.strip().split() QI_pos_dict[line[0]] = (line[1],line[2]) #loop through the fasta file and extarct segments for record in SeqIO.parse(handle , "fasta"): for QI in QI_pos_dict: if record.id == QI: out_handle.write(">%s\n%s\n" % (record.id,record.seq[ int(QI_pos_dict[QI][0]) : int(QI_pos_dict[QI][1])] ))
NIASC/VirusMeta
seq_corret_module/seg_trim.py
Python
gpl-3.0
963
0.030114
from functools import wraps from aiohttp.abc import AbstractView from aiohttp.web import HTTPForbidden, json_response, StreamResponse try: import ujson as json except ImportError: import json from .cfg import cfg from .utils import url_for, redirect, get_cur_user def _get_request(args): # Supports class based views see web.View if isinstance(args[0], AbstractView): return args[0].request return args[-1] def user_to_request(handler): '''Add user to request if user logged in''' @wraps(handler) async def decorator(*args): request = _get_request(args) request[cfg.REQUEST_USER_KEY] = await get_cur_user(request) return await handler(*args) return decorator def login_required(handler): @user_to_request @wraps(handler) async def decorator(*args): request = _get_request(args) if not request[cfg.REQUEST_USER_KEY]: return redirect(get_login_url(request)) return await handler(*args) return decorator def restricted_api(handler): @user_to_request @wraps(handler) async def decorator(*args): request = _get_request(args) if not request[cfg.REQUEST_USER_KEY]: return json_response({'error': 'Access denied'}, status=403) response = await handler(*args) if not isinstance(response, StreamResponse): response = json_response(response, dumps=json.dumps) return response return decorator def admin_required(handler): @wraps(handler) async def decorator(*args): request = _get_request(args) response = await login_required(handler)(request) if request['user']['email'] not in cfg.ADMIN_EMAILS: raise HTTPForbidden(reason='You are not admin') return response return decorator def get_login_url(request): return url_for('auth_login').with_query({ cfg.BACK_URL_QS_KEY: request.path_qs})
imbolc/aiohttp-login
aiohttp_login/decorators.py
Python
isc
1,959
0
from datetime import datetime from json import load, dump import logging from logging import INFO from os import listdir, makedirs, remove from os.path import join, exists import requests import shelve from static_aid import config from static_aid.DataExtractor import DataExtractor, bytesLabel def makeDir(dirPath): try: makedirs(dirPath) except OSError: # exists pass def adlibKeyFromUnicode(u): return u.encode('ascii', errors='backslashreplace').lower() def prirefString(u): if type(u) == int: return str(u) return u.encode('ascii', errors='backslashreplace').lower() def uriRef(category, priref): linkDestination = config.destinations[category].strip('/ ') return '/%s/%s' % (linkDestination, priref) class DataExtractor_Adlib(DataExtractor): def __init__(self, *args, **kwargs): super(DataExtractor_Adlib, self).__init__(*args, **kwargs) self.objectCaches = {} # contains 'shelve' instances keyed by collection name self.objectCacheInsertionCount = 0 # set to True to cache the raw JSON result from Adlib (before it is converted to StaticAid-friendly JSON) DUMP_RAW_DATA = True # set to True to read raw JSON results from the cache instead of from Adlib endpoints (offline/debug mode) READ_FROM_RAW_DUMP = False # set to False for testing purposes (quicker processing when using RAW_DUMP mechanism) READ_FROM_ADLIB_API = True # number of records to save to JSON cache before syncing to disk CACHE_SYNC_INTERVAL = 100 ### Top-level stuff ### def _run(self): # create a collection > key > object cache so that we can generate links between them self.cacheAllCollections() # link each cached object by priref wherever there is a reference to agent name, part_of, parts, etc. self.linkRecordsById() # analyze the extent records by item > ... > collection self.propagateDefaultExtentsToChildren() # save the results to build/data/**.json self.saveAllRecords() def cacheAllCollections(self): logging.debug('Extracting data from Adlib into object cache...') self.clearCache() self.extractPeople() self.extractOrganizations() self.extractCollections() self.extractSubCollections() self.extractSeries() self.extractSubSeries() self.extractFileLevelObjects() self.extractItemLevelObjects() def linkRecordsById(self): tree = shelve.open(self.cacheFilename('trees')) for category in self.objectCaches: cache = self.objectCaches[category] for adlibKey in cache: data = cache[adlibKey] # link records together by type if category == 'objects': self.addRefToLinkedAgents(data, category) self.createTreeNode(tree, data, 'archival_object', category) elif category == 'collections': # NOTE: in ArchivesSpace, collection.tree.ref is something like "/repositories/2/resources/91/tree" # but in collections.html, it's only used as an indicator of whether a tree node exists. data['tree'] = {'ref': True} self.addRefToLinkedAgents(data, category) self.createTreeNode(tree, data, 'resource', category) # this is necessary because the 'shelve' objects don't behave *exactly* like a dict self.objectCaches[category][adlibKey] = data # sync after each category so the in-memory map doesn't get too heavy cache.sync() tree.sync() # combine the tree with the other data so that it gets saved to *.json self.objectCaches['trees'] = tree # now we have all records joined by ID, and we have un-linked tree nodes. # Go through each tree node and recursively link them using the format: # node.children = [node, node, ...] self.createParentChildStructure() def addRefToLinkedAgents(self, data, category): # linked_agents[]: (objects OR collections) => (people OR organizations) for linkedAgent in data.get('linked_agents', []): if 'ref' not in linkedAgent: linkKey = adlibKeyFromUnicode(linkedAgent['title']) if linkKey in self.objectCaches.get('people', []): linkCategory = 'people' elif linkKey in self.objectCaches.get('organizations', []): linkCategory = 'organizations' else: msg = ''' While processing '%s/%s', linked_agent '%s' could not be found in 'people' or 'organizations' caches. '''.strip() % (category, data['adlib_key'], linkKey) logging.error(msg) continue priref = self.objectCaches[linkCategory][linkKey]['id'] linkedAgent['ref'] = uriRef(linkCategory, priref) def createTreeNode(self, tree, data, nodeType, category): node = { 'id': data['id'], 'title': data['title'], 'level': data['level'], # item/file/collection/etc 'adlib_key': data['adlib_key'], # for traversing node > data 'category': category, # for traversing node > data 'node_type': nodeType, 'jsonmodel_type': 'resource_tree', 'publish': True, 'children': [], } tree[str(data['id'])] = node def createParentChildStructure(self): '''start at the top-level collections and recurse downward by 'parts_reference' links''' collections = self.objectCaches['collections'] trees = self.objectCaches['trees'] for adlibKey in collections: data = collections[adlibKey] node = trees[data['id']] self.createNodeChildren(node, data, 'collections') # this is necessary for updates because the 'shelve' objects don't behave *exactly* like a dict trees[data['id']] = node trees.sync() # TODO necessary? self.objectCaches['trees'] = trees def createNodeChildren(self, node, data, category): selfRef = {'ref': uriRef(category, data['id'])} for childKey in data['parts_reference']: # connect the objects by 'parent.ref' field if category == 'collections' and childKey in self.objectCaches['collections']: # parts_reference links which point TO collections are only valid FROM collections. # if this is wrong, it will mess up link creation. childCategory = 'collections' elif childKey in self.objectCaches['objects']: childCategory = 'objects' else: msg = ''' While processing '%s/%s', parts_reference '%s' could not be found in 'objects' or 'collections' caches. '''.strip() % (category, data['adlib_key'], childKey) logging.error(msg) continue child = self.objectCaches[childCategory][childKey] child['parent'] = selfRef child['parent_node_object'] = node child['resource'] = {'ref': selfRef} # connect the tree-node objects by children[] list childNode = self.objectCaches['trees'][child['id']] node['children'].append(childNode) node['has_children'] = True node['tree'] = {'ref': True} self.createNodeChildren(childNode, child, childCategory) def propagateDefaultExtentsToChildren(self): '''start at the top-level collections and recurse downward by 'parts_reference' links''' collections = self.objectCaches['collections'] for adlibKey in collections: data = collections[adlibKey] if data['level'] == 'collection': # start the recursion process at the toplevel ('collection') nodes only self._propagateDefaultExtentsToChildren(data) def _propagateDefaultExtentsToChildren(self, data, default=[]): ''' recursively propagate extent information, going from parent to child levels, such that parent info is the default for its children ''' # MERGE the default extents from parent record(s) with any other extents present # NOTE: this will have no effect at the top (collection) level because default == [] data['extents'] = data.get('extents', []) + default # recurse to children # child = data > node > node.child > childData node = self.objectCaches['trees'][data['id']] for childNode in node['children']: childData = self.objectCaches[childNode['category']][childNode['adlib_key']] self._propagateDefaultExtentsToChildren(childData, data['extents']) # this is necessary because the 'shelve' objects don't behave *exactly* like a dict self.objectCaches[childNode['category']][childNode['adlib_key']] = childData def saveAllRecords(self): logging.debug('Saving data from object cache into folder: %s...' % (config.DATA_DIR)) for category in self.objectCaches: destination = config.destinations[category] makeDir(self.getDestinationDirname(destination)) for adlibKey in self.objectCaches[category]: data = self.objectCaches[category][adlibKey] if category == 'trees' and data['level'] != 'collection': # trees are cached as a recursive node graph, so we only want to save the top-level nodes continue self.saveFile(data['id'], data, destination) ### Object-Extraction stuff ### def extractPeople(self): searchTerm = 'name.type=person %s' % config.adlib.get('peoplefilter', '') for data in self.getApiData(config.adlib['peopledb'], searchTerm=searchTerm.strip()): result = self.getAgentData(data, 'person') self.cacheJson('people', result) def extractOrganizations(self): searchTerm = 'name.type=inst %s' % config.adlib.get('institutionsfilter', '') for data in self.getApiData(config.adlib['institutionsdb'], searchTerm=searchTerm.strip()): result = self.getAgentData(data, 'inst') result['uri'] = uriRef('organizations', result['id']) self.cacheJson('organizations', result) def getAgentData(self, data, level): priref = prirefString(data['priref'][0]) # written this way because we want an exception if 'name' is not present for people/orgs title = None for name in data['name']: # first non-empty name wins if type(name) == str or type(name) == unicode: title = name break if type(name) == dict: title = name['value'][0] break if title is None: pass adlibKey = adlibKeyFromUnicode(title) names = [{'authorized': True, 'sort_name': name, 'use_dates': False, } for name in data.get('equivalent_name', [])] relatedAgents = self.getRelatedAgents(data, 'part_of') relatedAgents += self.getRelatedAgents(data, 'parts') relatedAgents += self.getRelatedAgents(data, 'relationship') notes = [{'type': 'note', 'jsonmodel_type': 'note_singlepart', 'content': n, } for n in data.get('documentation', [])] notes += [{'type': 'bioghist', 'jsonmodel_type': 'note_singlepart', 'content': n, } for n in data.get('biography', [])] dates = [{'expression': '%s - %s' % (data.get('birth.date.start', [''])[0], data.get('death.date.start', [''])[0], ) }] preferred = False if 'name.status' in data: preferred = str(data['name.status'][0]['value'][0]) == '1' return { 'id': priref, 'adlib_key': adlibKey, 'level': level, 'title': title, 'preferred': preferred, 'names': names, 'related_agents': relatedAgents, 'notes': notes, 'dates_of_existence': dates, } def getRelatedAgents(self, person, k): return [{'_resolved':{'title': name}, 'relator': k.replace('_', ' '), # TODO # 'dates':[{'expression':''}], # 'description': '', } for name in person.get(k, []) ] def extractCollections(self): searchTerm = 'description_level=collection %s' % config.adlib.get('collectionfilter', '') for data in self.getApiData(config.adlib['collectiondb'], searchTerm=searchTerm.strip()): result = self.getCollectionOrSeries(data) self.cacheJson('collections', result) def extractSubCollections(self): searchTerm = 'description_level="sub-collection" %s' % config.adlib.get('collectionfilter', '') for data in self.getApiData(config.adlib['collectiondb'], searchTerm=searchTerm.strip()): result = self.getCollectionOrSeries(data) self.cacheJson('collections', result) def extractSeries(self): searchTerm = 'description_level=series %s' % config.adlib.get('collectionfilter', '') for data in self.getApiData(config.adlib['collectiondb'], searchTerm=searchTerm.strip()): result = self.getCollectionOrSeries(data) self.cacheJson('collections', result) def extractSubSeries(self): searchTerm = 'description_level="sub-series" %s' % config.adlib.get('collectionfilter', '') for data in self.getApiData(config.adlib['collectiondb'], searchTerm=searchTerm.strip()): result = self.getCollectionOrSeries(data) self.cacheJson('collections', result) def getCollectionOrSeries(self, data): priref = prirefString(data['priref'][0]) adlibKey = adlibKeyFromUnicode(data['object_number'][0]) level = data['description_level'][0]['value'][0].lower() # collection/series/etc. hide = level != 'collection' # only show top-level collections on the main page # NOTE: 'ref' is added later, in addRefToLinkedAgents() linkedAgents = [{'title':creator, 'role':'creator'} for creator in data.get('creator', []) if creator ] linkedAgents += [{'title':name, 'role':'subject'} for name in data.get('content.person.name', []) if name ] subjects = [{'title': subject} for subject in data.get('content.subject', []) if subject ] notes = [{'type': 'scopecontent', 'jsonmodel_type': 'note_singlepart', # 2 note representations for each record: 'subnotes':[{'content': n}], # list format is compatible with 'scopecontent' type 'content': n, # single format is compatible with 'note_singlepart' (technically this isn't 'scopecontent' format) } for n in data.get('content.description', [])] def extentObject(text, extentType, level): return {'number': text, 'extent_type': extentType, 'container_summary': '%s level' % level, } extents = [extentObject(bytesLabel(d), 'digital_extent', level) for d in data.get('digital_extent', [])] extents += [extentObject(d, 'dimension-free', level) # TODO syntax? for d in data.get('dimension.free', [])] result = { 'id': priref, 'id_0': adlibKey, 'adlib_key': adlibKey, 'uri': uriRef('collections', priref), 'level': level, 'linked_agents': linkedAgents, 'parts_reference': [adlibKeyFromUnicode(r) for r in data.get('parts_reference', [])], 'hide_on_main_page': hide, 'title': data['title'][0], 'dates': [{'expression': data.get('production.date.start', [''])[0]}], 'extents': [], 'notes': notes, 'subjects': subjects, 'extents': extents, } return result def extractFileLevelObjects(self): searchTerm = 'description_level=file %s' % config.adlib.get('objectfilter', '') for data in self.getApiData(config.adlib['collectiondb'], searchTerm=searchTerm.strip()): result = self.getArchivalObject(data) self.cacheJson('objects', result) def extractItemLevelObjects(self): searchTerm = 'description_level=item %s' % config.adlib.get('objectfilter', '') for data in self.getApiData(config.adlib['collectiondb'], searchTerm=searchTerm.strip()): result = self.getArchivalObject(data) self.cacheJson('objects', result) def getArchivalObject(self, data): priref = prirefString(data['priref'][0]) try: adlibKey = adlibKeyFromUnicode(data['object_number'][0]) except: adlibKey = None try: instances = [{ 'container.type_1': data['current_location.name'], 'container.indicator_1':data.get('current_location', ''), 'container.type_2':data.get('current_location.package.location', ''), 'container.indicator_2':data.get('current_location.package.context', ''), } ] except: instances = [] subjects = [{'title': subject} for subject in data.get('content.subject', [])] notes = [{'type': 'note', 'jsonmodel_type': 'note_singlepart', 'content': n, } for n in data.get('content.description', [])] # NOTE: 'ref' is added later, in addRefToLinkedAgents() linkedAgents = [{'title':name, 'role':'subject'} for name in data.get('content.person.name', []) if name ] linkedAgents += [{'title':creator, 'role':'creator'} for creator in data.get('creator', []) if creator ] level = data['description_level'][0]['value'][0].lower() # file/item if 'title' in data and 'object_name' in data: title = '%s (%s)' % (data['title'][0], data['object_name'][0]) elif 'title' in data: title = data['title'][0] elif 'object_name' in data: title = data['object_name'][0] else: logging.error('No title or object_name found for %s with ID %s' % (level, priref)) title = '' result = { 'id': priref, 'adlib_key': adlibKey, 'level': level, 'linked_agents': linkedAgents, 'parts_reference': [adlibKeyFromUnicode(r) for r in data.get('parts_reference', [])], 'title': title, 'display_string': title, 'instances': instances, 'subjects': subjects, 'notes': notes, 'dates': [{'expression':data.get('production.date.start', '')}], } return result def getApiData(self, database, searchTerm=''): if self.update: lastExport = datetime.fromtimestamp(self.lastExportTime()) searchTerm += ' modification greater "%4d-%02d-%02d"' % (lastExport.year, lastExport.month, lastExport.day) elif not searchTerm or searchTerm.strip() == '': searchTerm = 'all' return self._getApiData(database, searchTerm) def _getApiData(self, database, searchTerm): startFrom = 1 numResults = config.ROW_FETCH_LIMIT + 1 # fake to force while() == True while numResults >= config.ROW_FETCH_LIMIT: targetDir = join(config.RAW_DATA_DIR, database) filename = join(targetDir, '%s.%s-%s.json' % ((searchTerm, startFrom, startFrom + config.ROW_FETCH_LIMIT, ) ) ) rawJson = None if self.READ_FROM_RAW_DUMP: try: logging.info('Loading from %s...' % filename) with open(filename, 'r') as fp: rawJson = load(fp) except: logging.info('Loading from %s failed.' % filename) if rawJson is None and not self.READ_FROM_ADLIB_API: rawJson = {'adlibJSON':{'recordList':{'record':[]}}} if rawJson is None: logging.info('Fetching %s:%s records %d-%d...' % (database, searchTerm, startFrom, startFrom + config.ROW_FETCH_LIMIT)) url = '%s?database=%s&search=%s&xmltype=structured&limit=%d&startfrom=%d&output=json' % (config.adlib['baseurl'], database, searchTerm.strip(), config.ROW_FETCH_LIMIT, startFrom) try: logging.info("GET " + url) response = requests.get(url) rawJson = response.json() except Exception, e: logging.error("Exception while retrieving URL %s: %s" % (url, e)) return if self.DUMP_RAW_DATA: logging.info('Dumping raw data to %s...' % filename) makeDir(targetDir) with open(filename, 'w') as fp: dump(rawJson, fp, indent=4, sort_keys=True) records = rawJson['adlibJSON']['recordList']['record'] numResults = len(records) startFrom += config.ROW_FETCH_LIMIT for record in records: yield record def cacheFilename(self, category): return join(config.OBJECT_CACHE_DIR, category) def clearCache(self): for category in self.objectCaches: self.objectCaches[category].close() if exists(config.OBJECT_CACHE_DIR): for category in listdir(config.OBJECT_CACHE_DIR): remove(self.cacheFilename(category)) self.objectCaches = {} def cacheJson(self, category, data): if category not in self.objectCaches: makeDir(config.OBJECT_CACHE_DIR) self.objectCaches[category] = shelve.open(self.cacheFilename(category)) collection = self.objectCaches[category] adlibKey = data['adlib_key'] if adlibKey in collection: # 'preferred' names can supersede non-preferred ones. if data.get('preferred'): msg = '''Duplicate object '%s/%s' is superseding an existing one in the JSON cache because it is marked as 'preferred'.''' % (category, adlibKey) collection[adlibKey] = data logging.warn(msg) else: msg = '''Refusing to insert duplicate object '%s/%s' into JSON cache.''' % (category, adlibKey) logging.error(msg) else: collection[adlibKey] = data # flush at regular intervals self.objectCacheInsertionCount += 1 if self.objectCacheInsertionCount > self.CACHE_SYNC_INTERVAL: collection.sync() self.objectCacheInsertionCount = 0 class DataExtractor_Adlib_Fake(DataExtractor_Adlib): def _getApiData(self, database, searchTerm): def jsonFileContents(sampleDataType): filename = join(config.SAMPLE_DATA_DIR, 'adlib-sampledata', '%s.json' % sampleDataType) data = load(open(filename)) return data if database == config.adlib['peopledb'] and searchTerm == 'name.type=person': result = jsonFileContents('person') elif database == config.adlib['peopledb'] and searchTerm == 'name.type=inst': result = jsonFileContents('organization') elif database == config.adlib['collectiondb'] and searchTerm == 'description_level=collection': result = jsonFileContents('collection') elif database == config.adlib['collectiondb'] and searchTerm == 'description_level="sub-collection"': result = jsonFileContents('sub-collection') elif database == config.adlib['collectiondb'] and searchTerm == 'description_level=series': # TODO if you care # result = jsonFileContents('series') result = [] elif database == config.adlib['collectiondb'] and searchTerm == 'description_level="sub-series"': # TODO if you care # result = jsonFileContents('sub-series') result = [] elif database == config.adlib['collectiondb'] and searchTerm == 'description_level=file': result = jsonFileContents('file') elif database == config.adlib['collectiondb'] and searchTerm == 'description_level=item': result = jsonFileContents('item') else: raise Exception('''Please create a mock JSON config for getApiData('%s', '%s')!''' % (database, searchTerm)) # we actually return the contents of adlibJSON > recordList > record # return {'adlibJSON': {'recordList': {'record': data}}} return result if __name__ == '__main__': # NOTE: this is useful for launching in a debugger or for isolated testing; # it will not run when StaticAid is launched via 'grunt rebuild', so it is safe to leave in place. logging.basicConfig(level=INFO) e = DataExtractor_Adlib() e.READ_FROM_RAW_DUMP = True e.READ_FROM_ADLIB_API = False e.run()
GALabs/StaticAid
static_aid/DataExtractor_Adlib.py
Python
mit
27,394
0.00522
from iRODSLibrary import iRODSLibrary __version__ = "0.0.4" class iRODSLibrary(iRODSLibrary): """ iRODSLibrary is a client keyword library that uses the python-irodsclient module from iRODS https://github.com/irods/python-irodsclient Examples: | Connect To Grid | iPlant | data.iplantcollaborative.org | ${1247} | jdoe | jdoePassword | tempZone """ ROBOT_LIBRARY_SCOPE = 'GLOBAL'
jerry57/Robotframework-iRODS-Library
src/iRODSLibrary/__init__.py
Python
bsd-3-clause
422
0.004739
#! /usr/bin/env python # coding=utf-8 # Copyright (c) 2019 Uber Technologies, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import argparse import logging import os import sys from typing import List, Union import numpy as np from ludwig.api import LudwigModel from ludwig.backend import ALL_BACKENDS, LOCAL, Backend from ludwig.constants import FULL, TEST, TRAINING, VALIDATION from ludwig.contrib import contrib_command from ludwig.globals import LUDWIG_VERSION from ludwig.utils.print_utils import (logging_level_registry, print_boxed, print_ludwig) from ludwig.utils.strings_utils import make_safe_filename logger = logging.getLogger(__name__) def collect_activations( model_path: str, layers: List[str], dataset: str, data_format: str = None, split: str = FULL, batch_size: int = 128, output_directory: str = 'results', gpus: List[str] = None, gpu_memory_limit: int =None, allow_parallel_threads: bool = True, backend: Union[Backend, str] = None, debug: bool = False, **kwargs ) -> List[str]: """ Uses the pretrained model to collect the tensors corresponding to a datapoint in the dataset. Saves the tensors to the experiment directory # Inputs :param model_path: (str) filepath to pre-trained model. :param layers: (List[str]) list of strings for layer names in the model to collect activations. :param dataset: (str) source containing the data to make predictions. :param data_format: (str, default: `None`) format to interpret data sources. Will be inferred automatically if not specified. Valid formats are `'auto'`, `'csv'`, `'excel'`, `'feather'`, `'fwf'`, `'hdf5'` (cache file produced during previous training), `'html'` (file containing a single HTML `<table>`), `'json'`, `'jsonl'`, `'parquet'`, `'pickle'` (pickled Pandas DataFrame), `'sas'`, `'spss'`, `'stata'`, `'tsv'`. :param split: (str, default: `full`) split on which to perform predictions. Valid values are `'training'`, `'validation'`, `'test'` and `'full'`. :param batch_size: (int, default `128`) size of batches for processing. :param output_directory: (str, default: `'results'`) the directory that will contain the training statistics, TensorBoard logs, the saved model and the training progress files. :param gpus: (list, default: `None`) list of GPUs that are available for training. :param gpu_memory_limit: (int, default: `None`) maximum memory in MB to allocate per GPU device. :param allow_parallel_threads: (bool, default: `True`) allow TensorFlow to use multithreading parallelism to improve performance at the cost of determinism. :param backend: (Union[Backend, str]) `Backend` or string name of backend to use to execute preprocessing / training steps. :param debug: (bool, default: `False) if `True` turns on `tfdbg` with `inf_or_nan` checks. # Return :return: (List[str]) list of filepath to `*.npy` files containing the activations. """ logger.info('Dataset path: {}'.format(dataset) ) logger.info('Model path: {}'.format(model_path)) logger.info('Output path: {}'.format(output_directory)) logger.info('\n') model = LudwigModel.load( model_path, gpus=gpus, gpu_memory_limit=gpu_memory_limit, allow_parallel_threads=allow_parallel_threads, backend=backend ) # collect activations print_boxed('COLLECT ACTIVATIONS') collected_tensors = model.collect_activations( layers, dataset, data_format=data_format, split=split, batch_size=batch_size, debug=debug ) # saving os.makedirs(output_directory, exist_ok=True) saved_filenames = save_tensors(collected_tensors, output_directory) logger.info('Saved to: {0}'.format(output_directory)) return saved_filenames def collect_weights( model_path: str, tensors: List[str], output_directory: str = 'results', debug: bool = False, **kwargs ) -> List[str]: """ Loads a pretrained model and collects weights. # Inputs :param model_path: (str) filepath to pre-trained model. :param tensors: (list, default: `None`) List of tensor names to collect weights :param output_directory: (str, default: `'results'`) the directory where collected weights will be stored. :param debug: (bool, default: `False) if `True` turns on `tfdbg` with `inf_or_nan` checks. # Return :return: (List[str]) list of filepath to `*.npy` files containing the weights. """ logger.info('Model path: {}'.format(model_path)) logger.info('Output path: {}'.format(output_directory)) logger.info('\n') model = LudwigModel.load(model_path) # collect weights print_boxed('COLLECT WEIGHTS') collected_tensors = model.collect_weights(tensors) # saving os.makedirs(output_directory, exist_ok=True) saved_filenames = save_tensors(collected_tensors, output_directory) logger.info('Saved to: {0}'.format(output_directory)) return saved_filenames def save_tensors(collected_tensors, output_directory): filenames = [] for tensor_name, tensor_value in collected_tensors: np_filename = os.path.join( output_directory, make_safe_filename(tensor_name) + '.npy' ) np.save(np_filename, tensor_value.numpy()) filenames.append(np_filename) return filenames def print_model_summary( model_path: str, **kwargs ) -> None: """ Loads a pretrained model and prints names of weights and layers activations. # Inputs :param model_path: (str) filepath to pre-trained model. # Return :return: (`None`) """ model = LudwigModel.load(model_path) collected_tensors = model.collect_weights() names = [name for name, w in collected_tensors] keras_model = model.model.get_connected_model(training=False) keras_model.summary() print('\nLayers:\n') for layer in keras_model.layers: print(layer.name) print('\nWeights:\n') for name in names: print(name) def cli_collect_activations(sys_argv): """Command Line Interface to communicate with the collection of tensors and there are several options that can specified when calling this function: --data_csv: Filepath for the input csv --data_hdf5: Filepath for the input hdf5 file, if there is a csv file, this is not read --d: Refers to the dataset type of the file being read, by default is *generic* --s: Refers to the split of the data, can be one of: train, test, validation, full --m: Input model that is necessary to collect to the tensors, this is a required *option* --t: Tensors to collect --od: Output directory of the model, defaults to results --bs: Batch size --g: Number of gpus that are to be used --gf: Fraction of each GPUs memory to use. --dbg: Debug if the model is to be started with python debugger --v: Verbose: Defines the logging level that the user will be exposed to """ parser = argparse.ArgumentParser( description='This script loads a pretrained model and uses it collect ' 'tensors for each datapoint in the dataset.', prog='ludwig collect_activations', usage='%(prog)s [options]') # --------------- # Data parameters # --------------- parser.add_argument( '--dataset', help='input data file path', required=True ) parser.add_argument( '--data_format', help='format of the input data', default='auto', choices=['auto', 'csv', 'excel', 'feather', 'fwf', 'hdf5', 'html' 'tables', 'json', 'jsonl', 'parquet', 'pickle', 'sas', 'spss', 'stata', 'tsv'] ) parser.add_argument( '-s', '--split', default=FULL, choices=[TRAINING, VALIDATION, TEST, FULL], help='the split to obtain the model activations from' ) # ---------------- # Model parameters # ---------------- parser.add_argument( '-m', '--model_path', help='model to load', required=True ) parser.add_argument( '-lyr', '--layers', help='tensors to collect', nargs='+', required=True ) # ------------------------- # Output results parameters # ------------------------- parser.add_argument( '-od', '--output_directory', type=str, default='results', help='directory that contains the results' ) # ------------------ # Generic parameters # ------------------ parser.add_argument( '-bs', '--batch_size', type=int, default=128, help='size of batches' ) # ------------------ # Runtime parameters # ------------------ parser.add_argument( '-g', '--gpus', type=int, default=0, help='list of gpu to use' ) parser.add_argument( '-gml', '--gpu_memory_limit', type=int, default=None, help='maximum memory in MB to allocate per GPU device' ) parser.add_argument( '-dpt', '--disable_parallel_threads', action='store_false', dest='allow_parallel_threads', help='disable TensorFlow from using multithreading for reproducibility' ) parser.add_argument( "-b", "--backend", help='specifies backend to use for parallel / distributed execution, ' 'defaults to local execution or Horovod if called using horovodrun', choices=ALL_BACKENDS, ) parser.add_argument( '-dbg', '--debug', action='store_true', default=False, help='enables debugging mode' ) parser.add_argument( '-l', '--logging_level', default='info', help='the level of logging to use', choices=['critical', 'error', 'warning', 'info', 'debug', 'notset'] ) args = parser.parse_args(sys_argv) args.logging_level = logging_level_registry[args.logging_level] logging.getLogger('ludwig').setLevel( args.logging_level ) global logger logger = logging.getLogger('ludwig.collect') print_ludwig('Collect Activations', LUDWIG_VERSION) collect_activations(**vars(args)) def cli_collect_weights(sys_argv): """Command Line Interface to collecting the weights for the model --m: Input model that is necessary to collect to the tensors, this is a required *option* --t: Tensors to collect --od: Output directory of the model, defaults to results --dbg: Debug if the model is to be started with python debugger --v: Verbose: Defines the logging level that the user will be exposed to """ parser = argparse.ArgumentParser( description='This script loads a pretrained model ' 'and uses it collect weights.', prog='ludwig collect_weights', usage='%(prog)s [options]' ) # ---------------- # Model parameters # ---------------- parser.add_argument( '-m', '--model_path', help='model to load', required=True ) parser.add_argument( '-t', '--tensors', help='tensors to collect', nargs='+', required=True ) # ------------------------- # Output results parameters # ------------------------- parser.add_argument( '-od', '--output_directory', type=str, default='results', help='directory that contains the results' ) # ------------------ # Runtime parameters # ------------------ parser.add_argument( '-dbg', '--debug', action='store_true', default=False, help='enables debugging mode' ) parser.add_argument( '-l', '--logging_level', default='info', help='the level of logging to use', choices=['critical', 'error', 'warning', 'info', 'debug', 'notset'] ) args = parser.parse_args(sys_argv) args.logging_level = logging_level_registry[args.logging_level] logging.getLogger('ludwig').setLevel( args.logging_level ) global logger logger = logging.getLogger('ludwig.collect') print_ludwig('Collect Weights', LUDWIG_VERSION) collect_weights(**vars(args)) def cli_collect_summary(sys_argv): """Command Line Interface to collecting a summary of the model layers and weights. --m: Input model that is necessary to collect to the tensors, this is a required *option* --v: Verbose: Defines the logging level that the user will be exposed to """ parser = argparse.ArgumentParser( description='This script loads a pretrained model ' 'and prints names of weights and layers activations ' 'to use with other collect commands', prog='ludwig collect_summary', usage='%(prog)s [options]' ) # ---------------- # Model parameters # ---------------- parser.add_argument( '-m', '--model_path', help='model to load', required=True ) # ------------------ # Runtime parameters # ------------------ parser.add_argument( '-l', '--logging_level', default='info', help='the level of logging to use', choices=['critical', 'error', 'warning', 'info', 'debug', 'notset'] ) args = parser.parse_args(sys_argv) args.logging_level = logging_level_registry[args.logging_level] logging.getLogger('ludwig').setLevel( args.logging_level ) global logger logger = logging.getLogger('ludwig.collect') print_ludwig('Collect Summary', LUDWIG_VERSION) print_model_summary(**vars(args)) if __name__ == '__main__': if len(sys.argv) > 1: if sys.argv[1] == 'activations': contrib_command("collect_activations", *sys.argv) cli_collect_activations(sys.argv[2:]) elif sys.argv[1] == 'weights': contrib_command("collect_weights", *sys.argv) cli_collect_weights(sys.argv[2:]) elif sys.argv[1] == 'names': contrib_command("collect_summary", *sys.argv) cli_collect_summary(sys.argv[2:]) else: print('Unrecognized command') else: print('Unrecognized command')
uber/ludwig
ludwig/collect.py
Python
apache-2.0
15,469
0.000388
#======================================================================= # # Python Lexical Analyser # # Exception classes # #======================================================================= import exceptions class PlexError(exceptions.Exception): message = "" class PlexTypeError(PlexError, TypeError): pass class PlexValueError(PlexError, ValueError): pass class InvalidRegex(PlexError): pass class InvalidToken(PlexError): def __init__(self, token_number, message): PlexError.__init__(self, "Token number %d: %s" % (token_number, message)) class InvalidScanner(PlexError): pass class AmbiguousAction(PlexError): message = "Two tokens with different actions can match the same string" def __init__(self): pass class UnrecognizedInput(PlexError): scanner = None position = None state_name = None def __init__(self, scanner, state_name): self.scanner = scanner self.position = scanner.position() self.state_name = state_name def __str__(self): return ("'%s', line %d, char %d: Token not recognised in state %s" % (self.position + (repr(self.state_name),)))
onoga/wm
src/gnue/common/external/plex/Errors.py
Python
gpl-2.0
1,109
0.027953
from ..route_handler import BaseModelRouter, SUCCESS from ..serializers.model_serializer import ModelSerializer from .dragon_test_case import DragonTestCase from swampdragon.tests.models import TwoFieldModel class Serializer(ModelSerializer): class Meta: update_fields = ('text', 'number') model = TwoFieldModel class Router(BaseModelRouter): model = TwoFieldModel serializer_class = Serializer class TestBaseModelRouter(DragonTestCase): def setUp(self): self.router = Router(self.connection) def test_subscribe(self): data = {'channel': 'client-channel'} self.router.subscribe(**data) self.assertEqual(self.connection.last_message['context']['state'], SUCCESS) self.assertIn('channel_data', self.connection.last_message) self.assertEqual(self.connection.last_message['channel_data']['local_channel'], 'client-channel')
h-hirokawa/swampdragon
swampdragon/tests/test_base_model_router_subscribe.py
Python
bsd-3-clause
911
0.002195
## ## This file is part of the sigrok-meter project. ## ## Copyright (C) 2015 Jens Steinhauser <jens.steinhauser@gmail.com> ## ## 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, see <http://www.gnu.org/licenses/>. ## import qtcompat QtCore = qtcompat.QtCore QtGui = qtcompat.QtGui pyqtgraph = qtcompat.pyqtgraph # Black foreground on white background. pyqtgraph.setConfigOption('background', 'w') pyqtgraph.setConfigOption('foreground', 'k') class Plot(object): '''Helper class to keep all graphics items of a plot together.''' def __init__(self, view, xaxis, yaxis): self.view = view self.xaxis = xaxis self.yaxis = yaxis self.visible = False class MultiPlotItem(pyqtgraph.GraphicsWidget): # Emitted when a plot is shown. plotShown = QtCore.Signal() # Emitted when a plot is hidden by the user via the context menu. plotHidden = QtCore.Signal(Plot) def __init__(self, parent=None): pyqtgraph.GraphicsWidget.__init__(self, parent) self.setLayout(QtGui.QGraphicsGridLayout()) self.layout().setContentsMargins(10, 10, 10, 1) self.layout().setHorizontalSpacing(0) self.layout().setVerticalSpacing(0) for i in range(2): self.layout().setColumnPreferredWidth(i, 0) self.layout().setColumnMinimumWidth(i, 0) self.layout().setColumnSpacing(i, 0) self.layout().setColumnStretchFactor(0, 0) self.layout().setColumnStretchFactor(1, 100) # List of 'Plot' objects that are shown. self._plots = [] self._hideActions = {} def addPlot(self): '''Adds and returns a new plot.''' row = self.layout().rowCount() view = pyqtgraph.ViewBox(parent=self) # If this is not the first plot, link to the axis of the previous one. if self._plots: view.setXLink(self._plots[-1].view) yaxis = pyqtgraph.AxisItem(parent=self, orientation='left') yaxis.linkToView(view) yaxis.setGrid(255) xaxis = pyqtgraph.AxisItem(parent=self, orientation='bottom') xaxis.linkToView(view) xaxis.setGrid(255) plot = Plot(view, xaxis, yaxis) self._plots.append(plot) self.showPlot(plot) # Create a separate action object for each plots context menu, so that # we can later find out which plot should be hidden by looking at # 'self._hideActions'. hideAction = QtGui.QAction('Hide', self) hideAction.triggered.connect(self._onHideActionTriggered) self._hideActions[id(hideAction)] = plot view.menu.insertAction(view.menu.actions()[0], hideAction) return plot def _rowNumber(self, plot): '''Returns the number of the first row a plot occupies.''' # Every plot takes up two rows. return 2 * self._plots.index(plot) @QtCore.Slot() def _onHideActionTriggered(self, checked=False): # The plot that we want to hide. plot = self._hideActions[id(self.sender())] self.hidePlot(plot) def hidePlot(self, plot): '''Hides 'plot'.''' # Only hiding wouldn't give up the space occupied by the items, # we have to remove them from the layout. self.layout().removeItem(plot.view) self.layout().removeItem(plot.xaxis) self.layout().removeItem(plot.yaxis) plot.view.hide() plot.xaxis.hide() plot.yaxis.hide() row = self._rowNumber(plot) self.layout().setRowStretchFactor(row, 0) self.layout().setRowStretchFactor(row + 1, 0) plot.visible = False self.plotHidden.emit(plot) def showPlot(self, plot): '''Adds the items of the plot to the scene's layout and makes them visible.''' if plot.visible: return row = self._rowNumber(plot) self.layout().addItem(plot.yaxis, row, 0, QtCore.Qt.AlignRight) self.layout().addItem(plot.view, row, 1) self.layout().addItem(plot.xaxis, row + 1, 1) plot.view.show() plot.xaxis.show() plot.yaxis.show() for i in range(row, row + 2): self.layout().setRowPreferredHeight(i, 0) self.layout().setRowMinimumHeight(i, 0) self.layout().setRowSpacing(i, 0) self.layout().setRowStretchFactor(row, 100) self.layout().setRowStretchFactor(row + 1, 0) plot.visible = True self.plotShown.emit() class MultiPlotWidget(pyqtgraph.GraphicsView): '''Widget that aligns multiple plots on top of each other. (The built in classes fail at doing this correctly when the axis grow, just try zooming in the "GraphicsLayout" or the "Linked View" examples.)''' def __init__(self, parent=None): pyqtgraph.GraphicsView.__init__(self, parent) self.multiPlotItem = MultiPlotItem() self.setCentralItem(self.multiPlotItem) for m in [ 'addPlot', 'hidePlot', 'showPlot' ]: setattr(self, m, getattr(self.multiPlotItem, m)) self.multiPlotItem.plotShown.connect(self._on_plotShown) # Expose the signal of the plot item. self.plotHidden = self.multiPlotItem.plotHidden def _on_plotShown(self): # This call is needed if only one plot exists and it was hidden, # without it the layout would start acting weird and not make the # MultiPlotItem fill the view widget after showing the plot again. self.resizeEvent(None)
swegener/sigrok-meter
multiplotwidget.py
Python
gpl-3.0
6,148
0.00244
from scrapy.commands.crawl import Command from scrapy.exceptions import UsageError class CustomCrawlCommand(Command): def run(self, args, opts): if len(args) < 1: raise UsageError() elif len(args) > 1: raise UsageError("running 'scrapy crawl' with more than one spider is no longer supported") spname = args[0] # added new code spider_settings_path = self.settings.getdict('SPIDER_SETTINGS', {}).get(spname, None) if spider_settings_path is not None: self.settings.setmodule(spider_settings_path, priority='cmdline') # end crawler = self.crawler_process.create_crawler() spider = crawler.spiders.create(spname, **opts.spargs) crawler.crawl(spider) self.crawler_process.start()
lnxpgn/scrapy_multiple_spiders
commands/crawl.py
Python
mit
809
0.002472
#!/usr/bin/env python #-*- coding: utf-8 -*- import paramiko def traffic(ip,username,passwd): try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,22,username,passwd,timeout=5) stdin, stdout, stderr = ssh.exec_command('cat /proc/net/dev') out = stdout.readlines() conn = out[2].split() ReceiveBytes = round(float(conn[1])/(10**9),1) TransmitBytes = round(float(conn[9])/(10**9),1) print '%s\t%s\t%s'%(ip,ReceiveBytes,TransmitBytes) ssh.close() except : print '%s\tError'%(ip) if __name__=='__main__': ip_list=['192.168.1.55','192.168.1.100','192.168.1.101','192.168.1.200','192.168.1.201'] username = "root" #用户名 passwd = "" #密码 print '\nIP\t\tRX(G)\tTX(G)' for ip in ip_list: traffic(ip,username,passwd) print '\n'
wwgc/trafficstats
trafficstats.py
Python
gpl-2.0
912
0.032151
# -*- coding:utf-8 -*- def cipher(string): encoding = "" for character in string: #range 97 -> 123 = a-z if 97 <= ord(character) <= 123: #encode 219 - character number encoding +=chr(219-ord(character)) else: encoding += character return encoding input_value = "Hello World" print cipher(input_value) print cipher(cipher(input_value))
yasutaka/nlp_100
johnny/第1章/08.py
Python
mit
425
0.009412
""" Microformats2 is a general way to mark up any HTML document with classes and propeties. This library parses structured data from a microformatted HTML document and returns a well-formed JSON dictionary. """ from .version import __version__ from .parser import Parser, parse from .mf_helpers import get_url __all__ = ['Parser', 'parse', 'get_url', '__version__']
tommorris/mf2py
mf2py/__init__.py
Python
mit
369
0
"""Event loop implementation that uses the `asyncio` standard module. The `asyncio` module was added to python standard library on 3.4, and it provides a pure python implementation of an event loop library. It is used as a fallback in case pyuv is not available(on python implementations other than CPython). Earlier python versions are supported through the `trollius` package, which is a backport of `asyncio` that works on Python 2.6+. """ from __future__ import absolute_import import os import sys from collections import deque try: # For python 3.4+, use the standard library module import asyncio except (ImportError, SyntaxError): # Fallback to trollius import trollius as asyncio from .base import BaseEventLoop loop_cls = asyncio.SelectorEventLoop if os.name == 'nt': # On windows use ProactorEventLoop which support pipes and is backed by the # more powerful IOCP facility loop_cls = asyncio.ProactorEventLoop class AsyncioEventLoop(BaseEventLoop, asyncio.Protocol, asyncio.SubprocessProtocol): """`BaseEventLoop` subclass that uses `asyncio` as a backend.""" def connection_made(self, transport): """Used to signal `asyncio.Protocol` of a successful connection.""" self._transport = transport self._raw_transport = transport if isinstance(transport, asyncio.SubprocessTransport): self._transport = transport.get_pipe_transport(0) def connection_lost(self, exc): """Used to signal `asyncio.Protocol` of a lost connection.""" self._on_error(exc.args[0] if exc else 'EOF') def data_received(self, data): """Used to signal `asyncio.Protocol` of incoming data.""" if self._on_data: self._on_data(data) return self._queued_data.append(data) def pipe_connection_lost(self, fd, exc): """Used to signal `asyncio.SubprocessProtocol` of a lost connection.""" self._on_error(exc.args[0] if exc else 'EOF') def pipe_data_received(self, fd, data): """Used to signal `asyncio.SubprocessProtocol` of incoming data.""" if fd == 2: # stderr fd number self._on_stderr(data) elif self._on_data: self._on_data(data) else: self._queued_data.append(data) def process_exited(self): """Used to signal `asyncio.SubprocessProtocol` when the child exits.""" self._on_error('EOF') def _init(self): self._loop = loop_cls() self._queued_data = deque() self._fact = lambda: self self._raw_transport = None def _connect_tcp(self, address, port): coroutine = self._loop.create_connection(self._fact, address, port) self._loop.run_until_complete(coroutine) def _connect_socket(self, path): if os.name == 'nt': coroutine = self._loop.create_pipe_connection(self._fact, path) else: coroutine = self._loop.create_unix_connection(self._fact, path) self._loop.run_until_complete(coroutine) def _connect_stdio(self): coroutine = self._loop.connect_read_pipe(self._fact, sys.stdin) self._loop.run_until_complete(coroutine) coroutine = self._loop.connect_write_pipe(self._fact, sys.stdout) self._loop.run_until_complete(coroutine) def _connect_child(self, argv): self._child_watcher = asyncio.get_child_watcher() self._child_watcher.attach_loop(self._loop) coroutine = self._loop.subprocess_exec(self._fact, *argv) self._loop.run_until_complete(coroutine) def _start_reading(self): pass def _send(self, data): self._transport.write(data) def _run(self): while self._queued_data: self._on_data(self._queued_data.popleft()) self._loop.run_forever() def _stop(self): self._loop.stop() def _close(self): if self._raw_transport is not None: self._raw_transport.close() self._loop.close() def _threadsafe_call(self, fn): self._loop.call_soon_threadsafe(fn) def _setup_signals(self, signals): if os.name == 'nt': # add_signal_handler is not supported in win32 self._signals = [] return self._signals = list(signals) for signum in self._signals: self._loop.add_signal_handler(signum, self._on_signal, signum) def _teardown_signals(self): for signum in self._signals: self._loop.remove_signal_handler(signum)
meitham/python-client
neovim/msgpack_rpc/event_loop/asyncio.py
Python
apache-2.0
4,579
0