content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
import turtle import math import speech_recognition as sr import re r = sr.Recognizer() with sr.Microphone() as source: print('Say Something') audio=r.listen(source) try: print('Google thinks you said:\n' + r.recognize_google(audio)) except: pass n=r.recognize_google(audio) patterns= [r'\d+'] radd=findmatches(patterns, n) if len(radd)==0: int22=int('1') else: str1 = ''.join(radd) int22 = int(str1) wordList = re.sub("[^\w]", " ", n).split() if 'circle' in wordList: circle(20*int22) print('finished') turtle.done() elif 'square' in wordList: square1(20*int22) print('finished') turtle.done() elif 'rectangle' in wordList: rectangle1(20*int22) print('finished') turtle.done()
[ 11748, 28699, 198, 11748, 10688, 198, 11748, 4046, 62, 26243, 653, 355, 19677, 198, 11748, 302, 628, 628, 628, 198, 198, 81, 796, 19677, 13, 6690, 2360, 7509, 3419, 198, 4480, 19677, 13, 13031, 4862, 3419, 355, 2723, 25, 198, 220, 220...
2.264535
344
import ply.lex as lex keywords = { 'BREAK', 'CONST', 'CONTINUE', 'ELIF', 'ELSE', 'FOR', 'FUNC', 'GOTO', 'IF', 'RETURN', 'STRUCT', 'TYPE', 'VAR' } operators = { 'ADD', # + 'SUB', # - 'MUL', # * 'QUO', # / 'REM', # % 'AND', # & 'OR', # | 'SHL', # << 'SHR', # >> 'AGN', # = 'NOT', # ! 'LAND', # && 'LOR', # || 'EQL', # == 'LSS', # < 'GTR', # > 'NEQ', # != 'LEQ', # <= 'GEQ', # >= 'DEFN', # := 'LPRN', # ( 'LSQR', # [ 'LCURL', # { # 'LPRN_OR', # (| 'COMMA', # , 'DOT', # . 'RPRN', # ) 'RSQR', # ] 'RCURL', # } # 'RPRN_OR', # |) 'SEMCLN', # ; 'COLON' # : } reserved = {} for r in keywords: reserved[r.lower()] = r types = {'INTEGER_LIT', 'FLOAT_LIT', 'STRING_LIT', 'IDENT'} tokens = list(operators) \ + list(types) + list(reserved.values()) t_ignore_COMMENT = r'(/\*([^*]|\n|(\*+([^*/]|\n])))*\*+/)|(//.*)' t_ignore = ' \t' t_ADD = r'\+' t_SUB = r'-' t_MUL = r'\*' t_QUO = r'/' t_REM = r'%' t_AND = r'&' t_OR = r'\|' t_SHL = r'<<' t_SHR = r'>>' t_LAND = r'&&' t_LOR = r'\|\|' t_EQL = r'==' t_LSS = r'<' t_GTR = r'>' t_AGN = r'=' t_NOT = r'!' t_NEQ = r'!=' t_LEQ = r'<=' t_GEQ = r'>=' t_DEFN = r':=' t_LPRN = r'\(' t_LSQR = r'\[' t_LCURL = r'\{' # t_LPRN_OR = r'\(\|' t_COMMA = r',' t_DOT = r'\.' t_RPRN = r'\)' t_RSQR = r'\]' t_RCURL = r'\}' # t_RPRN_OR = r'\|\)' t_SEMCLN = r';' t_COLON = r':' decimal_lit = r"(0|([1-9][0-9]*))" float_lit = r"[0-9]*\.[0-9]+([eE][-+]?[0-9]+)?" string_lit = r"""("[^"]*")|('[^']*')""" identifier_lit = r"[_a-zA-Z]+[a-zA-Z0-9_]*" @lex.TOKEN(identifier_lit) @lex.TOKEN(string_lit) @lex.TOKEN(float_lit) @lex.TOKEN(decimal_lit) def t_newline(t): r'\n+' t.lexer.lineno += len(t.value) lexer = lex.lex()
[ 11748, 35960, 13, 2588, 355, 31191, 198, 198, 2539, 10879, 796, 1391, 198, 220, 220, 220, 705, 40438, 10206, 3256, 705, 10943, 2257, 3256, 705, 37815, 1268, 8924, 3256, 705, 3698, 5064, 3256, 198, 220, 220, 220, 705, 3698, 5188, 3256, ...
1.629401
1,136
from distutils.core import setup, Extension from distutils import sysconfig cfg_vars = sysconfig.get_config_vars() for key, value in cfg_vars.items(): if type(value) == str: cfg_vars[key] = value.replace('-Wstrict-prototypes', '') cpp_args = ['-std=c++11'] ext_modules = [ Extension( 'HEAAN', ['src/base64.cpp', 'src/wrapper.cpp'], include_dirs=['/usr/include/python3.6', 'pybind11/include', '/usr/local/include', 'HEAAN/src'], language='c++', extra_compile_args=cpp_args, extra_objects=['/usr/local/lib/libntl.so', 'HEAAN/lib/libHEAAN.a'], # both lib need compiled with -fPIC ), ] setup( name='HEAAN', version='2.1.0', author='Huelse', author_email='huelse@oini.top', description='Python wrapper for HEAAN', url='https://github.com/Huelse/HEAAN-Python', license='MIT', ext_modules=ext_modules, )
[ 6738, 1233, 26791, 13, 7295, 1330, 9058, 11, 27995, 198, 6738, 1233, 26791, 1330, 25064, 11250, 198, 198, 37581, 62, 85, 945, 796, 25064, 11250, 13, 1136, 62, 11250, 62, 85, 945, 3419, 198, 1640, 1994, 11, 1988, 287, 30218, 70, 62, ...
2.243781
402
#!/usr/bin/env python # -*- encoding: utf-8 -*- """Tests for checks.""" import os from absl import app from grr_response_core import config from grr_response_core.lib.parsers import config_file as config_file_parsers from grr_response_core.lib.parsers import linux_cmd_parser from grr_response_core.lib.parsers import wmi_parser from grr_response_core.lib.rdfvalues import anomaly as rdf_anomaly from grr_response_core.lib.rdfvalues import client as rdf_client from grr_response_core.lib.util.compat import yaml from grr_response_server.check_lib import checks from grr_response_server.check_lib import checks_test_lib from grr_response_server.check_lib import filters from grr.test_lib import test_lib CHECKS_DIR = os.path.join(config.CONFIG["Test.data_dir"], "checks") TRIGGER_1 = ("DebianPackagesStatus", "Linux", None, None) TRIGGER_2 = ("WMIInstalledSoftware", "Windows", None, None) TRIGGER_3 = ("DebianPackagesStatus", None, None, "foo") DPKG_SW = [] WMI_SW = [] SSHD_CFG = [] class MatchMethodTests(test_lib.GRRBaseTest): """Test match method selection and comparisons.""" def testCheckNone(self): """NONE returns an anomaly if there are no results.""" matcher = checks.Matcher(["NONE"], self.hint) for baseline in self.baselines: self.assertIsInstance( matcher.Detect(baseline, self.none), checks.CheckResult) for result in [self.one, self.some]: self.assertFalse(matcher.Detect(baseline, result)) def testCheckOne(self): """ONE operations should return anomalies if there is not one result.""" matcher = checks.Matcher(["ONE"], self.hint) for baseline in self.baselines: self.assertIsInstance( matcher.Detect(baseline, self.one), checks.CheckResult) for result in [self.none, self.some]: self.assertFalse(matcher.Detect(baseline, result)) def testCheckSome(self): """SOME operations should return anomalies if there is >1 result.""" matcher = checks.Matcher(["SOME"], self.hint) for baseline in self.baselines: self.assertIsInstance( matcher.Detect(baseline, self.some), checks.CheckResult) for result in [self.none, self.one]: self.assertFalse(matcher.Detect(baseline, result)) def testCheckAny(self): """ANY operations should not return anomalies if there are results.""" matcher = checks.Matcher(["ANY"], self.hint) for baseline in self.baselines: for result in [self.one, self.some]: self.assertIsInstance( matcher.Detect(baseline, result), checks.CheckResult) self.assertFalse(matcher.Detect(baseline, self.none)) def testCheckAll(self): """ALL operations return anomalies if input and result counts differ.""" matcher = checks.Matcher(["ALL"], self.hint) will_detect = [(self.one, self.one), (self.some, self.some)] not_detect = [(self.none, self.none), (self.some, self.one), (self.some, self.none)] will_raise = [(self.none, self.one), (self.one, self.some), (self.none, self.some)] for base, result in will_detect: self.assertIsInstance(matcher.Detect(base, result), checks.CheckResult) for base, result in not_detect: self.assertFalse(matcher.Detect(base, result)) for base, result in will_raise: self.assertRaises(checks.ProcessingError, matcher.Detect, base, result) def testMultipleMatch(self): """Checks with multiple match methods emit results if any methods fire.""" matcher = checks.Matcher(["NONE", "ONE"], self.hint) for baseline in self.baselines: for result in [self.none, self.one]: self.assertIsInstance( matcher.Detect(baseline, result), checks.CheckResult) self.assertFalse(matcher.Detect(baseline, self.some)) class CheckLoaderTests(test_lib.GRRBaseTest): """Check definitions can be loaded.""" class FilterTests(ChecksTestBase): """Test 'Filter' setup and operations.""" class ProbeTest(ChecksTestBase): """Test 'Probe' operations.""" configs = {} def Init(self, name, artifact, handler_class, result_context): """Helper method to verify that the Probe sets up the right handler.""" cfg = self.configs.get(name) probe = checks.Probe(**cfg) self.assertEqual(artifact, probe.artifact) self.assertIsInstance(probe.handler, handler_class) self.assertIsInstance(probe.matcher, checks.Matcher) self.assertCountEqual(result_context, str(probe.result_context)) def testInitialize(self): """Tests the input/output sequence validation.""" self.Init("NO-FILTER", "DpkgDb", filters.NoOpHandler, "PARSER") self.Init("ANOM-CONTEXT", "DpkgDb", filters.NoOpHandler, "ANOMALY") self.Init("SERIAL", "DpkgDb", filters.SerialHandler, "PARSER") self.Init("PARALLEL", "DpkgDb", filters.ParallelHandler, "PARSER") self.Init("BASELINE", "DpkgDb", filters.SerialHandler, "PARSER") def testParse(self): """Host data should be passed to filters, results should be returned.""" pass class MethodTest(ChecksTestBase): """Test 'Method' operations.""" configs = {} class CheckTest(ChecksTestBase): """Test 'Check' operations.""" cfg = {} class CheckResultsTest(ChecksTestBase): """Test 'CheckResult' operations.""" class HintDefinitionTests(ChecksTestBase): """Test 'Hint' operations.""" configs = {} if __name__ == "__main__": app.run(main)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 21004, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 51, 3558, 329, 8794, 526, 15931, 198, 198, 11748, 28686, 198, 198, 6738, 2352, 75, 1330, 598, 198, 198, 6738, ...
2.786674
1,936
# Strategy known as "Grim Trigger" or "Grudger". # We will cooperate repeatedly until our opponent betrays us once. # Then, we will get angry and defect for the rest of time. # # In this implementation, I used the memory variable to store Grim Trigger's state of mind. # memory is true if Grim Trigger has been wronged, and false if it hasn't. #
[ 2, 20561, 1900, 355, 366, 38, 3036, 24593, 1, 393, 366, 8642, 463, 1362, 1911, 198, 2, 775, 481, 21270, 7830, 1566, 674, 6125, 731, 20477, 514, 1752, 13, 198, 2, 3244, 11, 356, 481, 651, 7954, 290, 11855, 329, 262, 1334, 286, 640,...
3.723404
94
import os import requests import json from base64 import b64encode, b64decode # NOTE: For 'requests' to work with 'https' addrs, must use 'verify=False' # to ignore invalid SSL certificates. TEST_URL = 'https://10.210.39.16/jsonrpc' # NOTE: List is used to control the order in which RPC requests are sent (order # matters). TEST_LIST = [ 'get_status', 'get_dev_settings', 'get_option_settings', 'get_scan_stats', 'get_backup_file', 'get_file_verdict', 'get_file_rating', 'file_upload', 'file_upload_url', 'get_url_rating', 'get_job_verdict', 'cancel-submssion', 'get-jobs-of-submission', 'get-job-behavior' ] # 'set_dev_settings' # 'set_option_settings' # NOTE: 'session' values will be set after login in test function below. TEST_INPUTS = { 'login': { "method": "exec", "params": [ { "url": "/sys/login/user", "data": [{"user": "admin", "passwd": ""}] } ], "id": 1, "ver": "2.1" }, 'logout': { "method": "exec", "params": [{"url": "/sys/logout", }], "session": '', "id": 2, "ver": "2.1" }, 'get_status': { "method": "get", "params": [{"url": "/sys/status", }], "session": '', "id": 3, "ver": "2.1" }, 'get_dev_settings': { "method": "get", "params": [{"url": "/config/scan/devsniffer", }], "session": '', "id": 4, "ver": "2.1" }, 'get_option_settings': { "method": "get", "params": [{ "url": "/config/scan/options", "data": [ { "cloud_upload": 0, "vm_network_access": 1, "log_device_submission": 1, "rej_dup_device_submission": 1, "del_clean_file": 20160, "del_job_info": 20160 } ] } ], "session": '', "id": 7, "ver": "2.1" }, 'get_scan_stats': { "method": "get", "params": [ { "url": "/scan/stat/last_7day", } ], "session": '', "id": 8, "ver": "2.1" }, 'get_backup_file': { "method": "exec", "params": [{"url": "/backup/config", }], "session": '', "id": 9, "ver": "2.1" }, 'get_file_verdict_old': { "method": "get", "params": [ { "url": "/scan/result/file", "md5": "90877c1f6e7c97fb11249dc28dd16a3a3ddfac935d4f38c69307a71d96c8ef45" } ], "session": '', "id": 10, "ver": "2.1" }, 'get_file_verdict': { "method": "get", "params": [ { "url": "/scan/result/file", "checksum": None, "ctype": "md5" } ], "session": '', "id": 10, "ver": "2.1" }, 'get_job_verdict': { "method": "get", "params": [ { "url": "/scan/result/job", "jid": 1986798562984719030 } ], "session": '', "id": 10, "ver": "2.1" }, 'get_file_rating': { "method": "get", "params": [ { "url": "/scan/result/filerating", "sha256": "90877c1f6e7c97fb11249dc28dd16a3a3ddfac935d4f38c69307a71d96c8ef45" } ], "session": '', "id": 13, "ver": "2.1" }, 'file_upload': { "method": "set", "params": [ { "file": "", "filename": "", "url": "/alert/ondemand/submit-file", "type": "file" } ], "session": '', "id": 11, "ver": "2.1" }, 'file_upload_url': { "method": "set", "params": [ { "file": "dGhpcyBpcyBhIHRlc3QhCg==", "filename": b64encode("test.txt"), "url": "/alert/ondemand/submit-file", "timeout": "60", "depth": "1", "type": "url" } ], "session": '', "id": 12, "ver": "2.1" }, 'get_url_rating': { "method": "get", "params": [ { "url": "/scan/result/urlrating", "address": "1385967878564516.172.16.92.92.0" } ], "session": '', "id": 14, "ver": "2.1" }, 'cancel-submssion': { "method": "exec", "params": [ { "url": "/alert/ondemand/cancel-submssion", "sid": 2030159349466600881, "reason": 'want to cancel' } ], "session": "", "id": 16, "ver": "2.1" }, 'get-jobs-of-submission': { "method": "get", "params": [ { "url": "/scan/result/get-jobs-of-submission", "sid": 2050809724026386707, } ], "session": "", "id": 17, "ver": "2.1" }, 'get-job-behavior': { "method": "get", "params": [ { "url": "/scan/result/get-job-behavior", "sha256": "4e811adc363f4f52b9b4268d789aae5094056c8f5771fbf3f049185737ea51a5" } ], "session": "gzKj2PsMZ+4Hhs8Q9Ra+br+YStvpqWz\/8e291G1j1GI=", "id": 18, "ver": "2.1" } } def _handle_post(post_url, data): """ POST JSON RPC request.. @type post_url: basestring @param post_url: URL to server running RPC code. @type data: dict @param data: JSON RPC request data. @rtype: HttpResponse @return: JSON RPC response data. """ response = requests.post(post_url, data=json.dumps(data), verify=False) return response def _handle_post_with_session(session, post_url, data): """ POST JSON RPC request.. @type post_url: basestring @param post_url: URL to server running RPC code. @type data: dict @param data: JSON RPC request data. @rtype: HttpResponse @return: JSON RPC response data. """ response = session.post(post_url, data=json.dumps(data), verify=False) return response def _load_file_for_upload(path_to_file, test_input, filename=''): """ Load file contents into input mapping. @type path_to_file: basestring @param path_to_file: files absolute path. @type test_input: dict @param test_input: JSON RPC request data. @type filename: basestring @param filename: filename override optional param. @rtype: dict @return: updated JSON RPC request dict. """ f = open(path_to_file, 'rb') data = f.read() f.close() filename = os.path.basename(path_to_file) if not filename else filename test_input['params'][0]['file'] = b64encode(data) test_input['params'][0]['filename'] = b64encode(filename) return test_input def main(): """:wq! Test RPC supported requests. @rtype: None @return: None """ # NOTE: login, create session ID (sid). login_input = TEST_INPUTS.get('login') login_response = _handle_post(TEST_URL, login_input) result = json.loads(login_response.text)['result'] sid = json.loads(login_response.text)['session'] print login_response.text # NOTE: 'OVERRIDE_FILE' should be the absolute path to the file. # When submitting a file via RPC the noted file ('OVERRIDE_FILE') # will be used as an OVERRIDE. This can be used to send files # from your local PC to an FSA device. OVERRIDE_FILE = '' for test_key in TEST_LIST: print 'test key = %s' % test_key test_input = TEST_INPUTS.get(test_key) print 'test_input = %s' % test_input test_input['session'] = sid # NOTE: Skip url file upload IF path to file is not defined. if test_key == 'file_upload_url' and not OVERRIDE_FILE: continue test_input = _load_file_for_upload(OVERRIDE_FILE, test_input) \ if OVERRIDE_FILE and test_key in ['file_upload', 'file_upload_url'] \ else test_input response = _handle_post(TEST_URL, test_input) print response if test_key == 'get_backup_file': #print json.loads(response.text)['result']['data']['file'] print b64decode(json.loads(response.text)['result']['data']['file']) elif test_key == 'get-job-behavior': result = json.loads(response.text)['result'] if 'data' in result and 'behavior_files' in result['data']: with open("/tmp/json_behavior.tgz", 'wb') as output: output.write(b64decode(result['data']['behavior_files'])) else: print "No behavior data was found" else: print response.text # NOTE: Logout of session logout_input = TEST_INPUTS.get('logout') logout_input['session'] = sid logout_response = _handle_post(TEST_URL, logout_input) print logout_response.text if __name__ == "__main__": main()
[ 11748, 28686, 198, 11748, 7007, 198, 11748, 33918, 198, 6738, 2779, 2414, 1330, 275, 2414, 268, 8189, 11, 275, 2414, 12501, 1098, 198, 2, 24550, 25, 1114, 705, 8897, 3558, 6, 284, 670, 351, 705, 5450, 6, 751, 3808, 11, 1276, 779, 70...
1.891815
4,899
# -*- coding: utf-8 -*- # Copyright (c) 2015 Ericsson AB # # 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 calvin.runtime.south.plugins.media import mediaplayer class MediaPlayer(object): """ Play media file """ def play(self, media_file): """ Play media file """ self.player.play(media_file) def close(self): """ Close player """ self.player.close() def register(node=None, actor=None): """ Called when the system object is first created. """ return MediaPlayer()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 15069, 357, 66, 8, 1853, 7651, 16528, 9564, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345,...
2.940054
367
#!/usr/bin/env python # -*- coding: utf-8 -*- import uuid try: from setuptools import setup except ImportError: from distutils.core import setup from pip.req import parse_requirements with open('README.rst') as readme_file: readme = readme_file.read() install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1()) requirements = [str(ir.req) for ir in install_reqs] test_requirements = requirements setup( name='vulyk_pythondigest_moderator', version='0.1.0', description="Vulyk Pythondigest.ru moderator", long_description=readme, author="Alexander Sapronov", author_email='sapronov.alexander92@gmail.com', url='https://github.com/WarmongeR1/vulyk-pythondigest-moderator', packages=[ 'vulyk_pythondigest_moderator', 'vulyk_pythondigest_moderator.models', 'vulyk_pythondigest_moderator.static', 'vulyk_pythondigest_moderator.views' ], package_dir={'vulyk_pythondigest_moderator': 'vulyk_pythondigest_moderator'}, include_package_data=True, install_requires=requirements, license="MIT", zip_safe=False, keywords='vulyk_pythondigest_moderator', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 334, 27112, 198, 198, 28311, 25, 198, 220, 220, 220, 422, 900, 37623, 10141, 1330, 9058, 198, 16341, 17267, 1233...
2.408309
698
from .typereduction import *
[ 6738, 764, 4906, 445, 8110, 1330, 1635, 201, 198 ]
3.333333
9
import discord import datetime from discord.ext import commands from all import food_list # adding cog to bot setup
[ 11748, 36446, 198, 11748, 4818, 8079, 198, 198, 6738, 36446, 13, 2302, 1330, 9729, 198, 6738, 477, 1330, 2057, 62, 4868, 628, 198, 198, 2, 4375, 43072, 284, 10214, 9058 ]
3.966667
30
# # @lc app=leetcode.cn id=198 lang=python3 # # [198] house-robber # None # @lc code=end
[ 2, 198, 2, 2488, 44601, 598, 28, 293, 316, 8189, 13, 31522, 4686, 28, 22337, 42392, 28, 29412, 18, 198, 2, 198, 2, 685, 22337, 60, 2156, 12, 22609, 527, 198, 2, 198, 14202, 198, 2, 2488, 44601, 2438, 28, 437 ]
2.146341
41
""" Given a m * n matrix grid which is sorted in non-increasing order both row-wise and column-wise. Return the number of negative numbers in grid. Example: Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] Output: 8 Explanation: There are 8 negatives number in the matrix. Constraints: - m == grid.length - n == grid[i].length - 1 <= m, n <= 100 - -100 <= grid[i][j] <= 100 """ #Difficulty: Easy #44 / 44 test cases passed. #Runtime: 136 ms #Memory Usage: 14.5 MB #Runtime: 136 ms, faster than 28.51% of Python3 online submissions for Count Negative Numbers in a Sorted Matrix. #Memory Usage: 14.5 MB, less than 95.00% of Python3 online submissions for Count Negative Numbers in a Sorted Matrix.
[ 37811, 198, 220, 220, 220, 11259, 257, 285, 1635, 299, 17593, 10706, 543, 318, 23243, 287, 1729, 12, 42647, 1502, 1111, 220, 198, 220, 220, 220, 5752, 12, 3083, 290, 5721, 12, 3083, 13, 220, 198, 220, 220, 220, 8229, 262, 1271, 286,...
2.618421
304
import pandas as pd import numpy as np from statsmodels.formula.api import ols import plotly_express import plotly.graph_objs as go from plotly.subplots import make_subplots # Read in data batter_data = pd.read_csv("~/Desktop/MLB_FA/Data/fg_bat_data.csv") del batter_data['Age'] print(len(batter_data)) print(batter_data.head()) pitcher_data = pd.read_csv("~/Desktop/MLB_FA/Data/fg_pitch_data.csv") del pitcher_data['Age'] print(len(pitcher_data)) print(pitcher_data.head()) salary_data = pd.read_csv("~/Desktop/MLB_FA/Data/salary_data.csv") print(len(salary_data)) injury_data = pd.read_csv("~/Desktop/MLB_FA/Data/injury_data_use.csv") # Check for whether there is overlap between injury data and the salary data players # injury_data_players = injury_data['Player'].unique() # mutual = salary_data[salary_data['Player'].isin(injury_data_players)] # 945 out of 1135 players included # excl = salary_data[~salary_data['Player'].isin(injury_data_players)] # print(len(excl['Player'].unique())) # 129 unique players injury data omitted; use mlb.com trans for these # Define inflation salary_data = npv(salary_data, 0.05) # Lagged metrics to see if there is carryover value / value in continuity # Attach the injury data to the players, merge on player and year # MA print(len(salary_data)) salary_data = merge_injuries(salary_data, injury_data) print(len(salary_data)) salary_data['injury_duration'] = salary_data['injury_duration'].fillna(0) salary_data = Metrics.injury_engineering(salary_data) # Lag batter_data = Metrics.short_season_fix_batter(batter_data) batter_data = Metrics.rate_stats_batter(batter_data) batter_data = Metrics.lagged_batter(batter_data) pitcher_data = Metrics.short_season_fix_pitcher(pitcher_data) pitcher_data = Metrics.rate_stats_pitcher(pitcher_data) pitcher_data = Metrics.lagged_pitcher(pitcher_data) # Position fix salary_data = Metrics.fix_position(salary_data) # Non Linears batter_data = NonLinearVars.fg_batter_vars(batter_data) pitcher_data = NonLinearVars.fg_pitcher_vars(pitcher_data) salary_data = NonLinearVars.salary_vars(salary_data) # Merge data sets (one pitcher, one batter) batter_merged = pd.merge(batter_data, salary_data, left_on=['Name', 'Year'], right_on=['Player', 'Season']) batter_merged = batter_merged[(batter_merged['Position'] != "SP") & (batter_merged['Position'] != "RP")] # remove P's print(len(batter_merged)) pitcher_merged = pd.merge(pitcher_data, salary_data, left_on=['Name', 'Year'], right_on=['Player', 'Season']) pitcher_merged = pitcher_merged[(pitcher_merged['Position'] == "SP") | (pitcher_merged['Position'] == "RP")] # keep P's print(len(pitcher_merged)) # Begin modeling # train_data_batter = batter_merged[(batter_merged['Year'] != max(batter_merged['Year']))] # train_data_pitcher = pitcher_merged[(pitcher_merged['Year'] != max(pitcher_merged['Year']))] train_data_batter = batter_merged.loc[~batter_merged['NPV'].isnull()] train_data_pitcher = pitcher_merged.loc[~pitcher_merged['NPV'].isnull()] test_data_batter = batter_merged[ # (batter_merged['Year'] == max(batter_merged['Year'])) # & (np.isnan(batter_merged['NPV']))] test_data_pitcher = pitcher_merged[ # (pitcher_merged['Year'] == max(pitcher_merged['Year'])) # & (np.isnan(pitcher_merged['NPV']))] train_data_batter.to_csv('~/Desktop/MLB_FA/Data/train_data_batter.csv', index=False) train_data_pitcher.to_csv('~/Desktop/MLB_FA/Data/train_data_pitcher.csv', index=False) test_data_batter.to_csv('~/Desktop/MLB_FA/Data/test_data_batter.csv', index=False) test_data_pitcher.to_csv('~/Desktop/MLB_FA/Data/test_data_pitcher.csv', index=False) fit = ols('NPV ~ C(Position) + WAR_sq + WAR + Age', data=train_data_batter).fit() fit.summary() # 0.597 r-sq, 0.587 adj r-sq # Plot NPV / WAR to see nonlinear relationship plot_data = train_data_batter[(train_data_batter['Year'] > 2010)] fig = plotly_express.scatter(plot_data, x="dWAR", y="NPV", color='Position', hover_data=['Player', 'Position', 'Year', 'Prev Team'], title="dWAR, NPV Colored By Position (since {})".format(min(plot_data['Year']))) fig.show() # Plot WAR / Rate WAR plot_data = batter_data[(batter_data['Year'] == 2021) & (batter_data['PA'] > 100)] fig = plotly_express.scatter(plot_data, x="PA", y="dWAR", color='Name') fig.update_layout( hoverlabel=dict( bgcolor="white", font_size=10, font_family="Arial" ) ) fig.show() # remove linear WAR # Let's add a season factor and qualifying offer fit = ols('NPV ~ C(Position) + C(Season) + WAR_sq + Age + Qual + WAR_PA', data=train_data_batter).fit() fit.summary() # Getting better, but there's more unexplained variance. Let's try log of Age and prior season's WAR # Log Age fit = ols('NPV ~ C(Position) + C(Season) + y_n1_war_sq + WAR_sq + Age_log + Qual + WAR_PA + y_n1_war_pa', data=train_data_batter).fit() fit.summary() # Still marginally improving. Up to around 50% of the variance explained. # WAR is a counting stat, let's add in base-running UBR, non-log Age # UBR fit = ols('NPV ~ C(Position) + y_n1_war_sq + WAR_sq + Age + UBR + Qual', data=train_data_batter).fit() fit.summary() # Try some new variables (e.g. OPS, ISO, wRC+, wOBA, y_n2_war_sq, etc) fit = ols('NPV ~ C(Position) + y_n2_war_sq + y_n1_war_sq + WAR_sq + Age + UBR + Qual + wOBA + ISO', data=train_data_batter).fit() fit.summary() # Now let's consider only deals signed for multiple-years train_data_batter_multiyear = train_data_batter[(train_data_batter['Years'] > 1)] fit = ols('NPV ~ C(Position) + y_n1_war_sq + WAR_sq + Age + UBR + Qual', data=train_data_batter_multiyear).fit() fit.summary() # Single year only train_data_batter_single = train_data_batter[(train_data_batter['Years'] == 1)] fit = ols('NPV ~ C(Position) + y_n1_war_sq + WAR_sq + Age + Qual', data=train_data_batter_single).fit() fit.summary() # So what are team's using to assess these single year contracts? fit = ols('NPV ~ ISO + WAR_sq + y_n1_war_sq + y_n2_war_sq + wGDP + BABIP + Qual', data=train_data_batter_single).fit() fit.summary() # Now add injury duration fit = ols('NPV ~ ISO + WAR_sq + y_n1_war_sq + y_n2_war_sq + injury_duration + Qual', data=train_data_batter).fit() fit.summary() # Kitchen sink fit_rate = ols('NPV ~ BBpct + Kpct + AVG + OBP + SLG + OPS + ISO + Spd + BABIP + UBR + wGDP + wSB + wRC + ' 'wRAA + wOBA + WAR + dWAR + oWAR + Year + WAR_PA + oWAR_PA + y_n1_war + y_n2_war + y_n3_war + ' 'y_n4_war + y_n5_war + y_n6_war + y_n1_wOBA + y_n2_wOBA + y_n3_wOBA + y_n4_wOBA + ' 'y_n1_war_pa + y_n2_war_pa + y_n3_war_pa + y_n4_war_pa + y_n5_war_pa + y_n6_war_pa +' 'WAR_sq + y_n1_war_sq + y_n2_war_sq + y_n3_war_sq + y_n4_war_sq + y_n5_war_sq + y_n6_war_sq + ' 'y_n1_wOBA_sq + y_n2_wOBA_sq + Position + Age + Qual + injury_duration', data=train_data_batter).fit() fit_rate.summary() # Remove unwanted vars fit_rate = ols('NPV ~ Kpct + Year + y_n1_war +' 'y_n1_wOBA + y_n2_war_pa + WAR_sq + y_n1_war_sq +' 'Age + Qual', data=train_data_batter).fit() fit_rate.summary() # PITCHERS train_data_pitcher['pos_dummy'] = np.where(train_data_pitcher['Position'] == "SP", 1, 0) fit = ols('NPV ~ WAR_sq + Age + Qual + pos_dummy + FBv + Kpct + y_n1_war_sq', data=train_data_pitcher).fit() fit.summary() # Predict WAR fit = ols('WAR ~ FBv + Kpct + BBpct + FIP + IP + wFB + pos_dummy', data=train_data_pitcher).fit() fit.summary() # Let's add in injury duration train_data_pitcher['injury_duration_log'] = np.log(train_data_pitcher['injury_duration']) fit = ols('NPV ~ WAR_sq + Age + Qual + injury_duration + pos_dummy', data=train_data_pitcher).fit() fit.summary() # Add FBv fit = ols('NPV ~ WAR_sq + Age + Qual + injury_duration + FBv + pos_dummy', data=train_data_pitcher).fit() fit.summary() # Kpct fit = ols('NPV ~ WAR_sq + Age + Qual + injury_duration + FBv + Kpct + pos_dummy + BBpct', data=train_data_pitcher).fit() fit.summary() # CBv fit = ols('NPV ~ Age + Qual + injury_duration + FBv + Kpct + CBv + pos_dummy', data=train_data_pitcher).fit() fit.summary() # Rate stats fit_rate = ols( 'NPV ~ Age + WAR_TBF + y_n1_war_tbf + y_n2_war_tbf + FBv + xFIP_sq + pos_dummy + injury_duration + Qual', data=train_data_pitcher).fit() fit_rate.summary() multi_year_pitcher = train_data_pitcher[(train_data_pitcher['Years'] > 1)] fit_rate_multi = ols( 'NPV ~ Age + WAR_TBF + y_n1_war_tbf + y_n2_war_tbf + FBv + xFIP_sq + pos_dummy + injury_duration', data=multi_year_pitcher).fit() fit_rate_multi.summary() # Change position and Season to random effect batter_grp = batter_merged.groupby(['Season']).agg({ 'NPV': sum, 'WAR': sum, 'Name': 'nunique' }).reset_index() batter_grp['NPV'] = batter_grp['NPV'] / 1000000 fig = plotly_express.bar(batter_grp, x="Season", y="NPV", color_continuous_scale=plotly_express.colors.qualitative.D3, title="Yearly total NPV and total WAR") fig.add_trace(go.Scatter(x=batter_grp['Season'], y=batter_grp['WAR'], line=dict(color='red'), name='WAR'), row=1, col=1) fig.show() # Create figure with secondary y-axis fig = make_subplots(specs=[[{"secondary_y": True}]]) # Add traces fig.add_trace( go.Bar(x=batter_grp['Season'], y=batter_grp['NPV'], name="NPV total"), secondary_y=False, ) fig.add_trace( go.Scatter(x=batter_grp['Season'], y=batter_grp['WAR'], name="WAR total"), secondary_y=True, ) # Add figure title fig.update_layout( title_text="Yearly total NPV and total WAR" ) # Set x-axis title fig.update_xaxes(title_text="Off-Season Year") # Set y-axes titles fig.update_yaxes(title_text="<b>NPV</b> total ($ Millions)", secondary_y=False) fig.update_yaxes(title_text="<b>WAR</b> total", secondary_y=True) fig.show()
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 9756, 27530, 13, 687, 4712, 13, 15042, 1330, 267, 7278, 198, 11748, 7110, 306, 62, 42712, 198, 11748, 7110, 306, 13, 34960, 62, 672, 8457, 355, 467, 198, ...
2.377922
4,149
import json import re import tensorflow as tf import tensorflow_text as text import tensorflow_hub as hub from official.nlp.modeling import networks from official.nlp.tools import export_tfhub_lib from absl import app, flags from tqdm import tqdm from save_as_weight_from_saved_model import create_model FLAGS = flags.FLAGS flags.DEFINE_string("langs", "en,fr,es,de,zh,ar,zh_classical,it,ja,ko,nl,pl,pt,th,tr,ru", help='language to use') flags.DEFINE_integer("seq_len", 128, "default seq len") if __name__ == '__main__': app.run(main)
[ 11748, 33918, 198, 11748, 302, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 11192, 273, 11125, 62, 5239, 355, 2420, 198, 11748, 11192, 273, 11125, 62, 40140, 355, 12575, 198, 6738, 1743, 13, 21283, 79, 13, 4666, 10809, 1330, 7...
2.779487
195
""" Automount utility. """ from __future__ import absolute_import from __future__ import unicode_literals __all__ = ['AutoMounter'] class AutoMounter(object): """ Automount utility. Being connected to the udiskie daemon, this component automatically mounts newly discovered external devices. Instances are constructed with a Mounter object, like so: >>> AutoMounter(Mounter(udisks=Daemon())) """ def __init__(self, mounter): """ Store mounter as member variable and connect to the underlying udisks. :param Mounter mounter: mounter object """ self._mounter = mounter mounter.udisks.connect('device_changed', self.device_changed) mounter.udisks.connect('device_added', mounter.auto_add) mounter.udisks.connect('media_added', mounter.auto_add) def device_changed(self, old_state, new_state): """ Mount newly mountable devices. :param Device old_state: before change :param Device new_state: after change """ # udisks2 sometimes adds empty devices and later updates them which # makes is_external become true not at device_added time: if (self._mounter.is_addable(new_state) and not self._mounter.is_addable(old_state) and not self._mounter.is_removable(old_state)): self._mounter.auto_add(new_state)
[ 37811, 198, 38062, 608, 10361, 13, 198, 37811, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 628, 198, 834, 439, 834, 796, 37250, 27722, 44, 6828, 20520, 628, ...
2.621072
541
"""Beacon Python Application Configuration.""" import json import os from configparser import ConfigParser from collections import namedtuple from distutils.util import strtobool def parse_drspaths(paths): """Parse handover configuration.""" return [p.strip().split(',', 2) for p in paths.split('\n') if p.split()] def parse_config_file(path): """Parse configuration file.""" config = ConfigParser() config.read(path) config_vars = { 'title': config.get('beacon_general_info', 'title'), 'version': config.get('beacon_general_info', 'version'), 'author': config.get('beacon_general_info', 'author'), 'license': config.get('beacon_general_info', 'license'), 'copyright': config.get('beacon_general_info', 'copyright'), 'docs_url': config.get('beacon_general_info', 'docs_url'), 'handover_drs': config.get('handover_info', 'drs', fallback=''), 'handover_datasets': parse_drspaths(config.get('handover_info', 'dataset_paths', fallback='')), 'handover_beacon': parse_drspaths(config.get('handover_info', 'beacon_paths', fallback='')), 'handover_base': int(config.get('handover_info', 'handover_base', fallback=0)), 'apiVersion': config.get('beacon_api_info', 'apiVersion'), 'beaconId': config.get('beacon_api_info', 'beaconId'), 'description': config.get('beacon_api_info', 'description'), 'url': config.get('beacon_api_info', 'url'), 'alturl': config.get('beacon_api_info', 'alturl'), 'createtime': config.get('beacon_api_info', 'createtime'), 'service_type': config.get('beacon_api_info', 'service_type'), 'environment': config.get('beacon_api_info', 'environment'), 'org_id': config.get('organisation_info', 'org_id'), 'org_name': config.get('organisation_info', 'org_name'), 'org_description': config.get('organisation_info', 'org_description'), 'org_address': config.get('organisation_info', 'org_address'), 'org_welcomeUrl': config.get('organisation_info', 'org_welcomeUrl'), 'org_contactUrl': config.get('organisation_info', 'org_contactUrl'), 'org_logoUrl': config.get('organisation_info', 'org_logoUrl'), 'org_info': config.get('organisation_info', 'org_info') } return namedtuple("Config", config_vars.keys())(*config_vars.values()) CONFIG_INFO = parse_config_file(os.environ.get('CONFIG_FILE', os.path.join(os.path.dirname(__file__), 'config.ini'))) def parse_oauth2_config_file(path): """Parse configuration file.""" config = ConfigParser() config.read(path) config_vars = { 'server': config.get('oauth2', 'server'), 'issuers': config.get('oauth2', 'issuers'), 'userinfo': config.get('oauth2', 'userinfo'), 'audience': config.get('oauth2', 'audience') or None, 'verify_aud': bool(strtobool(config.get('oauth2', 'verify_aud'))), 'bona_fide_value': config.get('oauth2', 'bona_fide_value') } return namedtuple("Config", config_vars.keys())(*config_vars.values()) OAUTH2_CONFIG = parse_oauth2_config_file(os.environ.get('CONFIG_FILE', os.path.join(os.path.dirname(__file__), 'config.ini'))) # Sample query file should be of format [{BeaconAlleleRequest}] https://github.com/ga4gh-beacon/specification/ sampleq_file = os.environ.get('SAMPLEQUERY_FILE', os.path.join(os.path.dirname(__file__), 'sample_queries.json')) SAMPLE_QUERIES = json.load(open(sampleq_file)) if os.path.isfile(sampleq_file) else []
[ 37811, 3856, 7807, 11361, 15678, 28373, 526, 15931, 198, 198, 11748, 33918, 198, 11748, 28686, 198, 6738, 4566, 48610, 1330, 17056, 46677, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, 6738, 1233, 26791, 13, 22602, 1330, 965, 83, 672, 970...
2.515324
1,403
""" A collection of EOTasks for feature manipulation """ from .temporal_features import ( AddSpatioTemporalFeaturesTask, AddMaxMinTemporalIndicesTask, AddMaxMinNDVISlopeIndicesTask, ) from .interpolation import ( InterpolationTask, ResamplingTask, LinearInterpolationTask, CubicInterpolationTask, SplineInterpolationTask, BSplineInterpolationTask, AkimaInterpolationTask, NearestResamplingTask, LinearResamplingTask, CubicResamplingTask, KrigingInterpolationTask, ) from .feature_manipulation import ( SimpleFilterTask, FilterTimeSeriesTask, ValueFilloutTask, LinearFunctionTask, ) from .haralick import HaralickTask from .radiometric_normalization import ( ReferenceScenesTask, HistogramMatchingTask, BlueCompositingTask, HOTCompositingTask, MaxNDVICompositingTask, MaxNDWICompositingTask, MaxRatioCompositingTask, ) from .blob import BlobTask, DoGBlobTask, DoHBlobTask, LoGBlobTask from .hog import HOGTask from .local_binary_pattern import LocalBinaryPatternTask from .bands_extraction import EuclideanNormTask, NormalizedDifferenceIndexTask from .clustering import ClusteringTask from .doubly_logistic_approximation import DoublyLogisticApproximationTask __version__ = "1.0.0"
[ 37811, 198, 32, 4947, 286, 412, 2394, 6791, 329, 3895, 17512, 198, 37811, 198, 198, 6738, 764, 11498, 35738, 62, 40890, 1330, 357, 198, 220, 220, 220, 3060, 4561, 39485, 12966, 35738, 23595, 25714, 11, 198, 220, 220, 220, 3060, 11518, ...
2.821978
455
# -*- coding: utf-8 -*- # Copyright 2016 Open Permissions Platform Coalition # 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. """Unit tests for the main application code""" from mock import patch import identity.app @patch('identity.app.options') @patch('tornado.ioloop.IOLoop.instance') @patch('identity.app.koi.make_server') @patch('identity.app.koi.load_config')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 1584, 4946, 2448, 8481, 19193, 15135, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779...
3.683983
231
import argparse import os from subprocess import check_call import sys import utils PYTHON = sys.executable parser = argparse.ArgumentParser() parser.add_argument('--parent_dir', default='experiments/learning_rate', help='Directory containing params.json') parser.add_argument('--data_dir', default='data/small', help="Directory containing the dataset") if __name__ == "__main__": args = parser.parse_args() json_path = os.path.join(args.parent_dir, 'params.json') assert os.path.isfile(json_path), "No json configuration file found at {}".format(json_path) params = utils.Params(json_path) learning_rates = [1e-4, 1e-3, 1e-2] for learning_rate in learning_rates: params.learning_rate = learning_rate job_name = "learning_rate_{}".format(learning_rate) launch_training_job(args.parent_dir, args.data_dir, job_name, params)
[ 198, 11748, 1822, 29572, 198, 11748, 28686, 198, 6738, 850, 14681, 1330, 2198, 62, 13345, 198, 11748, 25064, 198, 198, 11748, 3384, 4487, 628, 198, 47, 56, 4221, 1340, 796, 25064, 13, 18558, 18187, 198, 48610, 796, 1822, 29572, 13, 2810...
2.75841
327
""" Module for enums and constants. """ from enum import Enum class TileType(str, Enum): """Enum for types of tiles in the world. These types represent types of planetary surfaces. """ SPACE = " " LUSH = "L" ARID = "D" AQUATIC = "W" SOLAR = "*" class Resource(str, Enum): """Enumeration of all resource types in the game. These item types are the kinds of items players can gather or collect from the world and account for resources that cities require and loot from defeating mobs. """ FOOD = "food" WATER = "water" FUEL = "fuel" ORE = "ore" class ShipSystemAttributeType(str, Enum): """ Enumeration of all possible ship system attributes. """ HARD_POINT_COST = "hard_point_cost" MODULE_COST = "module_cost" COMPONENT_COST = "component_cost" BASE_COST = "base_cost" MOVEMENT_SPEED = "movement_speed" ATTACK_POWER = "attack_power" GATHER_POWER = "gather_power" CARRY_CAPACITY = "carry_capacity" class UnitType(str, Enum): """ Enumeration of all unit types in the game. """ TRANSPORT = "transport" RAIDER = "raider" ALIEN = "alien" class StructureType(str, Enum): """ Enumeration of all structure types in the game. """ RESOURCE_YARD = "resource yard" FACTORY = "factory" TURRET = "turret" class Action(str, Enum): """ Enumeration of available game actions. """ ATTACK = "attack" GATHER = "gather" BUY = "buy" SELL = "sell" MOVE = "move" WAIT = "wait"
[ 37811, 19937, 329, 551, 5700, 290, 38491, 13, 37227, 198, 198, 6738, 33829, 1330, 2039, 388, 628, 198, 4871, 47870, 6030, 7, 2536, 11, 2039, 388, 2599, 198, 220, 220, 220, 37227, 4834, 388, 329, 3858, 286, 19867, 287, 262, 995, 13, ...
2.607143
588
#!/usr/bin/env python3 """ Generate a summary of last week's issues tagged with "topic: feature". The summary will include a list of new and changed issues and is sent each Monday at 0200 CE(S)T to the typing-sig mailing list. Due to limitation with GitHub Actions, the mail is sent from a private server, currently maintained by @srittau. """ from __future__ import annotations import datetime from dataclasses import dataclass from typing import Any, Iterable, Sequence import requests ISSUES_API_URL = "https://api.github.com/repos/python/typing/issues" ISSUES_URL = "https://github.com/python/typing/issues?q=label%3A%22topic%3A+feature%22" ISSUES_LABEL = "topic: feature" SENDER_EMAIL = "Typing Bot <noreply@python.org>" RECEIVER_EMAIL = "typing-sig@python.org" @dataclass def fetch_issues(since: datetime.date) -> list[Issue]: """Return (new, updated) issues.""" j = requests.get( ISSUES_API_URL, params={ "labels": ISSUES_LABEL, "since": f"{since:%Y-%m-%d}T00:00:00Z", "per_page": "100", "state": "open", }, headers={"Accept": "application/vnd.github.v3+json"}, ).json() assert isinstance(j, list) return [parse_issue(j_i) for j_i in j] if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 37811, 198, 8645, 378, 257, 10638, 286, 938, 1285, 338, 2428, 30509, 351, 366, 26652, 25, 3895, 1911, 198, 198, 464, 10638, 481, 2291, 257, 1351, 286, 649, 290, 3421, 2428, ...
2.492337
522
#Datosdeentrada print("Ingrese el Sexo (H/M):") sexo = input() print("Ingrese la EdadSLLB:") #proceso edad = int(input()) if edad>=70: print("la vacuna es de tipo C") if sexo=="H": edad>=16 and edad<=69 print("la vacuna es de tipo A") if sexo=="M": edad>=16 and edad<=69 print("la vacuna es de tipo B") if edad<=16: print("la vacuna es de tipo a")
[ 2, 27354, 418, 2934, 298, 81, 4763, 198, 4798, 7203, 27682, 260, 325, 1288, 14419, 78, 357, 39, 14, 44, 2599, 4943, 198, 8044, 78, 796, 5128, 3419, 198, 4798, 7203, 27682, 260, 325, 8591, 1717, 324, 50, 3069, 33, 25, 4943, 198, 2,...
2.168675
166
__author__ = 'Aaron Yang' __email__ = 'byang971@usc.edu' __date__ = '12/24/2020 10:01 PM' func1()
[ 834, 9800, 834, 796, 705, 34451, 10998, 6, 198, 834, 12888, 834, 796, 705, 1525, 648, 24, 4869, 31, 16241, 13, 15532, 6, 198, 834, 4475, 834, 796, 705, 1065, 14, 1731, 14, 42334, 838, 25, 486, 3122, 6, 628, 198, 198, 20786, 16, ...
2.222222
45
# class Array(Instruction): # def __init__(self, dest, src): # self.dest = dest # self.src = src
[ 628, 628, 628, 198, 198, 2, 1398, 15690, 7, 6310, 2762, 2599, 198, 2, 220, 220, 220, 220, 825, 11593, 15003, 834, 7, 944, 11, 2244, 11, 12351, 2599, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 2116, 13, 16520, 796, 2244, 198...
2.083333
60
import csv from oscar.core.loading import import_module report_classes = import_module('reports.reports', ['ReportGenerator']) analytics_models = import_module('analytics.models', ['ProductRecord', 'UserRecord'])
[ 11748, 269, 21370, 198, 198, 6738, 267, 13034, 13, 7295, 13, 25138, 1330, 1330, 62, 21412, 198, 13116, 62, 37724, 796, 1330, 62, 21412, 10786, 48922, 13, 48922, 3256, 37250, 19100, 8645, 1352, 6, 12962, 198, 38200, 14094, 62, 27530, 796...
3.421875
64
from . import * class strip_to_slot(pya.PCellDeclarationHelper): """ The PCell declaration for the strip_to_slot. draft by Lukas Chrostowski july 24, 2017 based on https://www.osapublishing.org/oe/fulltext.cfm?uri=oe-21-16-19029&id=259920 """
[ 6738, 764, 1330, 1635, 198, 198, 4871, 10283, 62, 1462, 62, 43384, 7, 79, 3972, 13, 5662, 695, 37835, 10186, 47429, 2599, 198, 220, 37227, 198, 220, 383, 4217, 695, 14305, 329, 262, 10283, 62, 1462, 62, 43384, 13, 198, 220, 4538, 41...
2.645833
96
URL_is_Null = "The URL is null"
[ 21886, 62, 271, 62, 35067, 796, 366, 464, 10289, 318, 9242, 1 ]
2.583333
12
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # check and return missing values in each features in the dataframe def missing_statistics(df): """ This function check and return missing values in each features for a dataframe Parameters ---------- df: dataframe Returns ------- statitics (dataframe) contains missing inforamtion for each features """ statitics = pd.DataFrame(df.isnull().sum()).reset_index() statitics.columns = ['COLUMN NAME', "MISSING VALUES"] statitics['TOTAL ROWS'] = df.shape[0] statitics['% MISSING'] = round((statitics['MISSING VALUES'] / statitics['TOTAL ROWS']) * 100, 2) return statitics
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 384, 397, 1211, 355, 3013, 82, 628, 198, 2, 2198, 290, 1441, 4814, 3815, 287, 1123, 3033, ...
2.814672
259
#!/usr/bin/env python # coding: utf-8 # In[1]: import cv2 import numpy as np from PIL import Image import matplotlib.pyplot as plt import YoloHelper # In[2]: yolo_net, yolo_output_layers, yolo_classes = YoloHelper.load_yolo('yolov3.weights','yolov3.cfg', 'coco.names') # In[3]: img = cv2.imread('test-image.jpg') # In[4]: img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) plt.imshow(img_rgb) plt.show() #img_rgb = Image.open('test_img.jpg') #plt.imshow(img_rgb) #plt.show() # In[5]: outputs, img_box = YoloHelper.detect_obj(yolo_net, yolo_output_layers, yolo_classes, img) #label,(x,y,w,h),confidences for output in outputs: print(output) # In[6]: #plt.figure(figsize=(16,10)) img_rgb = cv2.cvtColor(img_box, cv2.COLOR_BGR2RGB) plt.imshow(img_rgb) plt.show() # In[7]: img_crop = YoloHelper.crop_output(img, outputs[0], 10) img_crop_rgb = cv2.cvtColor(img_crop, cv2.COLOR_BGR2RGB) plt.imshow(img_crop_rgb) plt.show() # In[8]: img_crop = YoloHelper.crop_output(img, outputs[1], 10) img_crop_rgb = cv2.cvtColor(img_crop, cv2.COLOR_BGR2RGB) plt.imshow(img_crop_rgb) plt.show() # In[9]: outputs, img_box = YoloHelper.detect_obj(yolo_net, yolo_output_layers, yolo_classes, img, only=['person']) #label,(x,y,w,h),confidences for output in outputs: print(output) #plt.figure(figsize=(16,10)) img_rgb = cv2.cvtColor(img_box, cv2.COLOR_BGR2RGB) plt.imshow(img_rgb) plt.show() # In[10]: plt.imshow(img_crop_rgb) plt.show() # In[11]: img_crop_rgb_fill = YoloHelper.make_image_square(img_crop) img_crop_rgb_fill_rgb = cv2.cvtColor(img_crop_rgb_fill, cv2.COLOR_BGR2RGB) plt.imshow(img_crop_rgb_fill_rgb) plt.show() # In[ ]: # In[ ]: # In[ ]: # In[ ]:
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 554, 58, 16, 5974, 628, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 350, 4146, 1330, 7412, 198, 11748,...
2.029516
847
from PIL import Image, ImageDraw from skimage.measure import compare_ssim as ssim from numpy import array from pickle import loads from flask import Flask, request from os import path import genetic.individual import json from base64 import b64decode image_path = '/home/ubuntu/image.jpg' individual_path = '/home/ubuntu/individual' app = Flask(__name__) @app.route('/calculate-fitness', methods=['POST']) if __name__ == '__main__': import sys app.run(host='0.0.0.0', port=sys.argv[1], debug=True)
[ 6738, 350, 4146, 1330, 7412, 11, 7412, 25302, 198, 6738, 1341, 9060, 13, 1326, 5015, 1330, 8996, 62, 824, 320, 355, 264, 14323, 198, 6738, 299, 32152, 1330, 7177, 198, 6738, 2298, 293, 1330, 15989, 198, 6738, 42903, 1330, 46947, 11, 2...
3.011905
168
"""Views for deposit of records.""" from __future__ import absolute_import, print_function from flask import Blueprint, redirect, render_template, url_for from flask_login import login_required from flask_security import current_user from .forms import RecordForm from .api import create_record # define a new Flask Blueprint that is register under the url path /deposit blueprint = Blueprint( 'deposit', __name__, url_prefix='/deposit', template_folder='templates', static_folder='static', ) @blueprint.route('/create', methods=('GET', 'POST')) @login_required def create(): """The create view.""" form = RecordForm() # if the form is submitted and valid if form.validate_on_submit(): # we creare one contributor object with the submitted name contributors = [dict(name=form.contributor_name.data)] # set the owner as the current logged in user owner = int(current_user.get_id()) # create the record create_record( dict( title=form.title.data, contributors=contributors, owner=owner, ) ) # redirect to the success page return redirect(url_for('deposit.success')) return render_template('deposit/create.html', form=form) @blueprint.route("/success") @login_required def success(): """The success view.""" return render_template('deposit/success.html')
[ 37811, 7680, 82, 329, 14667, 286, 4406, 526, 15931, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 3601, 62, 8818, 198, 198, 6738, 42903, 1330, 39932, 11, 18941, 11, 8543, 62, 28243, 11, 19016, 62, 1640, 198, 6738, 4290...
2.782946
516
from skills_taxonomy import PROJECT_DIR from pprint import pprint from skills_taxonomy.utils.json_management import load_json, save_json def input_name(class_id, informative_words): """Print most informative words, and then ask for user input to assign a suitable name. Args: class_id(str): id for class assigned after clustiner informative_words (list of str): most informative words Returns: str: user input name for class """ pprint(informative_words) print(f"Using the most informative words for class {class_id} above,") return input(f"enter name for class {class_id}:") def name_clusters(informative_words_path): """Iterate through json file of class_ids and most informative words, printing info to user and asking for user input to name the classes. Return a dictionary of the user given names. Args: informative_words_path (str): path to json file of most informative words Returns: dict: dict with keys of class ids and values of user assigned class name """ informative_words = load_json(informative_words_path) named_clusters = {} for k, v in informative_words.items(): named_clusters[k] = input_name(k, v) return named_clusters def save_named_clusters(save_dir=f"{PROJECT_DIR}/outputs/named_classes/"): """Run name_clusters on most_informative_words/class.json and most_informative_words/subclass.json and save json file. Args: save_dir (str): save directory, defaults to f"{PROJECT_DIR}/outputs/named_classes/" """ save_json( save_dir, file_name="named_classes.json", json_to_save=name_clusters( f"{PROJECT_DIR}/outputs/most_informative_words/class.json" ), ) save_json( save_dir, file_name="named_subclasses.json", json_to_save=name_clusters( f"{PROJECT_DIR}/outputs/most_informative_words/subclass.json" ), )
[ 6738, 4678, 62, 19290, 30565, 1330, 21965, 23680, 62, 34720, 198, 6738, 279, 4798, 1330, 279, 4798, 198, 6738, 4678, 62, 19290, 30565, 13, 26791, 13, 17752, 62, 27604, 1330, 3440, 62, 17752, 11, 3613, 62, 17752, 628, 198, 4299, 5128, ...
2.522924
807
# -*- coding: utf-8 -*- import numpy as np from .base import DataFlow __all__ = [] class _EmptyDataFlow(DataFlow): """Empty data flow. This class is useful when constructing a data flow by merging sources from other data flows. """ @property @property @property @property @property @property # use a global shared empty data flow. empty_flow = _EmptyDataFlow()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 764, 8692, 1330, 6060, 37535, 198, 198, 834, 439, 834, 796, 17635, 628, 198, 4871, 4808, 40613, 6601, 37535, 7, 6601, 3753...
2.908451
142
from os import getenv import json from flask import Flask, render_template, request, jsonify from flask_mongoengine import MongoEngine from flask_pymongo import PyMongo from pymongo import MongoClient
[ 6738, 28686, 1330, 651, 24330, 198, 11748, 33918, 198, 6738, 42903, 1330, 46947, 11, 8543, 62, 28243, 11, 2581, 11, 33918, 1958, 198, 6738, 42903, 62, 76, 25162, 18392, 1330, 42591, 13798, 198, 6738, 42903, 62, 79, 4948, 25162, 1330, 94...
3.865385
52
# -------------------------------------------------------- # MTCNN # Licensed under The MIT License [see LICENSE for details] # Copyright 2019 smarsu. All Rights Reserved. # -------------------------------------------------------- import os.path as osp import cv2 import numpy as np from mtcnn import PNet, RNet, ONet from square import square_boxes from broad import broad_boxes from crop import crop pnet = PNet(scale_factor=0.89, conf_thrs=0.8, nms_thrs=0.5, min_face=60, nms_topk=32) pnet.sess.restore(osp.join(pnet.model_root, '3.2153504_cycle_7_0.01_pnet_v2.npz')) rnet = RNet(conf_thrs=0.5) rnet.sess.restore(osp.join(rnet.model_root, '0.022445953_53_0.001_rnet.npz')) onet = ONet(conf_thrs=0.5) onet.sess.restore(osp.join(onet.model_root, '0.012311436_69_0.01_onet.npz')) def detect(img, top_k=-1): """Do face detection with the input img. Args: img: ndarray, shape with [h, w, 3] top_k: output with the top k detected faces. default for -1, which means return all detected bboxes. Returns: bboxes: ndarray, [n, 4] """ h, w, c = img.shape if c != 3: print('WARNING: wrong input shape {}, we need the c to be 3.'.format(c)) return np.array([]) confs, bboxes = pnet.test(img) bboxes = np.round(bboxes).astype(np.int32) confs, bboxes = rnet.test(img, bboxes) bboxes = np.round(bboxes).astype(np.int32) confs, bboxes = onet.test(img, bboxes) bboxes = np.round(bboxes).astype(np.int32) if len(confs) != 1: print('WARNING: Unexpected face num ', len(confs)) sorted_id = np.argsort(-confs.flatten())[:top_k] keeped_bboxes = bboxes[sorted_id] return keeped_bboxes def crop_face(img, bboxes, dst_face_path): """Crop face with the raw image and face boxes. Args: img: ndarray, shape with [h, w, 3] bboxes: ndarray, [n, 4] dst_face_path: str, the path to write the face. """ h, w, c = img.shape n, axis = bboxes.shape if c != 3: print('ERROR: wrong input shape {}, we need the c to be 3.'.format(c)) exit() if axis != 4: print('ERROR: wrong input shape {}, we need the axis to be 4.'.format(axis)) exit() bboxes = np.round(bboxes).astype(np.int32) bboxes = square_boxes(bboxes) bboxes = broad_boxes(bboxes, 0.4) for idx, bbox in enumerate(bboxes): crop(img, bbox, dst_face_path) if __name__ == '__main__': main()
[ 2, 20368, 22369, 198, 2, 337, 4825, 6144, 198, 2, 49962, 739, 383, 17168, 13789, 685, 3826, 38559, 24290, 329, 3307, 60, 198, 2, 15069, 13130, 895, 945, 84, 13, 1439, 6923, 33876, 13, 198, 2, 20368, 22369, 198, 198, 11748, 28686, 13...
2.315248
1,069
from typing import Dict, List from jina.executors.crafters import BaseSegmenter class JiebaSegmenter(BaseSegmenter): """ :class:`JiebaSegmenter` split the chinese text on the doc-level into words on the chunk-level with `jieba`. """ def __init__(self, mode: str = 'accurate', *args, **kwargs): """ :param mode: the jieba cut mode, accurate, all, search. default accurate """ super().__init__(*args, **kwargs) if mode not in ('accurate', 'all', 'search'): raise ValueError('you must choose one of modes to cut the text: accurate, all, search.') self.mode = mode def craft(self, text: str, *args, **kwargs) -> List[Dict]: """ Split the chinese text into words :param text: the raw text :return: a list of chunk dicts """ import jieba if self.mode == 'search': words = jieba.cut_for_search(text) elif self.mode == 'all': words = jieba.cut(text, cut_all=True) else: words = jieba.cut(text) chunks = [] for idx, word in enumerate(words): chunks.append( dict(text=word, offset=idx, weight=1.0)) return chunks
[ 6738, 19720, 1330, 360, 713, 11, 7343, 198, 198, 6738, 474, 1437, 13, 18558, 315, 669, 13, 66, 430, 47131, 1330, 7308, 41030, 434, 263, 628, 198, 4871, 449, 494, 7012, 41030, 434, 263, 7, 14881, 41030, 434, 263, 2599, 198, 220, 220,...
2.229947
561
# ----------------------------------------------------------------------- # Use Case 2 # ----------------------------------------------------------------------- import sys import csv import scriptutils import traceback if __name__ == "__main__": try: assert (len(sys.argv) == 2), \ "Script requires one and only one parameter: full filename of the node_args.json file" UC2.perform(sys.argv[1]) except AssertionError as assertionError: print ('uc2: Script failure on assert: ') print (assertionError) except Exception as exception: print ('uc2: Script failure with exception: ') print (traceback.format_exc()) else: print ('uc2: Done with the script business.')
[ 2, 16529, 26866, 198, 2, 220, 5765, 8913, 362, 198, 2, 16529, 26866, 198, 11748, 25064, 198, 11748, 269, 21370, 198, 11748, 4226, 26791, 198, 11748, 12854, 1891, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, ...
3.125
240
# Wrapper module for _ssl, providing some additional facilities # implemented in Python. Written by Bill Janssen. """\ This module provides some more Pythonic support for SSL. Object types: SSLSocket -- subtype of socket.socket which does SSL over the socket Exceptions: SSLError -- exception raised for I/O errors Functions: cert_time_to_seconds -- convert time string used for certificate notBefore and notAfter functions to integer seconds past the Epoch (the time values returned from time.time()) fetch_server_certificate (HOST, PORT) -- fetch the certificate provided by the server running on HOST at port PORT. No validation of the certificate is performed. Integer constants: SSL_ERROR_ZERO_RETURN SSL_ERROR_WANT_READ SSL_ERROR_WANT_WRITE SSL_ERROR_WANT_X509_LOOKUP SSL_ERROR_SYSCALL SSL_ERROR_SSL SSL_ERROR_WANT_CONNECT SSL_ERROR_EOF SSL_ERROR_INVALID_ERROR_CODE The following group define certificate requirements that one side is allowing/requiring from the other side: CERT_NONE - no certificates from the other side are required (or will be looked at if provided) CERT_OPTIONAL - certificates are not required, but if provided will be validated, and if validation fails, the connection will also fail CERT_REQUIRED - certificates are required, and will be validated, and if validation fails, the connection will also fail The following constants identify various SSL protocol variants: PROTOCOL_SSLv2 PROTOCOL_SSLv3 PROTOCOL_SSLv23 PROTOCOL_TLSv1 """ import textwrap import _ssl # if we can't import it, let the error propagate from _ssl import SSLError from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED from _ssl import PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1 from _ssl import RAND_status, RAND_egd, RAND_add from _ssl import \ SSL_ERROR_ZERO_RETURN, \ SSL_ERROR_WANT_READ, \ SSL_ERROR_WANT_WRITE, \ SSL_ERROR_WANT_X509_LOOKUP, \ SSL_ERROR_SYSCALL, \ SSL_ERROR_SSL, \ SSL_ERROR_WANT_CONNECT, \ SSL_ERROR_EOF, \ SSL_ERROR_INVALID_ERROR_CODE from socket import socket, _fileobject from socket import getnameinfo as _getnameinfo import base64 # for DER-to-PEM translation class SSLSocket (socket): """This class implements a subtype of socket.socket that wraps the underlying OS socket in an SSL context when necessary, and provides read and write methods over that channel.""" def read(self, len=1024): """Read up to LEN bytes and return them. Return zero-length string on EOF.""" try: return self._sslobj.read(len) except SSLError, x: if x.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs: return '' else: raise def write(self, data): """Write DATA to the underlying SSL channel. Returns number of bytes of DATA actually transmitted.""" return self._sslobj.write(data) def getpeercert(self, binary_form=False): """Returns a formatted version of the data in the certificate provided by the other end of the SSL channel. Return None if no certificate was provided, {} if a certificate was provided, but not validated.""" return self._sslobj.peer_certificate(binary_form) def do_handshake (self): """Perform a TLS/SSL handshake.""" self._sslobj.do_handshake() def connect(self, addr): """Connects to remote ADDR, and then wraps the connection in an SSL channel.""" # Here we assume that the socket is client-side, and not # connected at the time of the call. We connect it, then wrap it. if self._sslobj: raise ValueError("attempt to connect already-connected SSLSocket!") socket.connect(self, addr) self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile, self.cert_reqs, self.ssl_version, self.ca_certs) if self.do_handshake_on_connect: self.do_handshake() def accept(self): """Accepts a new connection from a remote client, and returns a tuple containing that new connection wrapped with a server-side SSL channel, and the address of the remote client.""" newsock, addr = socket.accept(self) return (SSLSocket(newsock, keyfile=self.keyfile, certfile=self.certfile, server_side=True, cert_reqs=self.cert_reqs, ssl_version=self.ssl_version, ca_certs=self.ca_certs, do_handshake_on_connect=self.do_handshake_on_connect, suppress_ragged_eofs=self.suppress_ragged_eofs), addr) def makefile(self, mode='r', bufsize=-1): """Make and return a file-like object that works with the SSL connection. Just use the code from the socket module.""" self._makefile_refs += 1 return _fileobject(self, mode, bufsize) # some utility functions def cert_time_to_seconds(cert_time): """Takes a date-time string in standard ASN1_print form ("MON DAY 24HOUR:MINUTE:SEC YEAR TIMEZONE") and return a Python time value in seconds past the epoch.""" import time return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT")) PEM_HEADER = "-----BEGIN CERTIFICATE-----" PEM_FOOTER = "-----END CERTIFICATE-----" def DER_cert_to_PEM_cert(der_cert_bytes): """Takes a certificate in binary DER format and returns the PEM version of it as a string.""" if hasattr(base64, 'standard_b64encode'): # preferred because older API gets line-length wrong f = base64.standard_b64encode(der_cert_bytes) return (PEM_HEADER + '\n' + textwrap.fill(f, 64) + PEM_FOOTER + '\n') else: return (PEM_HEADER + '\n' + base64.encodestring(der_cert_bytes) + PEM_FOOTER + '\n') def PEM_cert_to_DER_cert(pem_cert_string): """Takes a certificate in ASCII PEM format and returns the DER-encoded version of it as a byte sequence""" if not pem_cert_string.startswith(PEM_HEADER): raise ValueError("Invalid PEM encoding; must start with %s" % PEM_HEADER) if not pem_cert_string.strip().endswith(PEM_FOOTER): raise ValueError("Invalid PEM encoding; must end with %s" % PEM_FOOTER) d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)] return base64.decodestring(d) def get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None): """Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version' is specified, use it in the connection attempt.""" host, port = addr if (ca_certs is not None): cert_reqs = CERT_REQUIRED else: cert_reqs = CERT_NONE s = wrap_socket(socket(), ssl_version=ssl_version, cert_reqs=cert_reqs, ca_certs=ca_certs) s.connect(addr) dercert = s.getpeercert(True) s.close() return DER_cert_to_PEM_cert(dercert) # a replacement for the old socket.ssl function def sslwrap_simple (sock, keyfile=None, certfile=None): """A replacement for the old socket.ssl function. Designed for compability with Python 2.5 and earlier. Will disappear in Python 3.0.""" ssl_sock = _ssl.sslwrap(sock._sock, 0, keyfile, certfile, CERT_NONE, PROTOCOL_SSLv23, None) ssl_sock.do_handshake() return ssl_sock
[ 2, 27323, 2848, 8265, 329, 4808, 45163, 11, 4955, 617, 3224, 7291, 198, 2, 9177, 287, 11361, 13, 220, 22503, 416, 3941, 449, 504, 6248, 13, 198, 198, 37811, 59, 198, 1212, 8265, 3769, 617, 517, 11361, 291, 1104, 329, 25952, 13, 198,...
2.35641
3,409
import random import torch import collections from myrl.agents.agent import Agent from myrl.utils.memory import ReplayMemory from myrl.models import FullyConnectedNet, get_optimizer from myrl.utils.save import net_directory, get_filename
[ 11748, 4738, 198, 11748, 28034, 198, 11748, 17268, 198, 198, 6738, 616, 45895, 13, 49638, 13, 25781, 1330, 15906, 198, 6738, 616, 45895, 13, 26791, 13, 31673, 1330, 23635, 30871, 198, 6738, 616, 45895, 13, 27530, 1330, 40234, 13313, 276, ...
3.809524
63
import numpy as np from tfsnippet.dataflow import DataMapper __all__ = ['BaseSampler', 'BernoulliSampler', 'UniformNoiseSampler'] class BaseSampler(DataMapper): """Base class for samplers.""" def sample(self, x): """ Sample array according to `x`. Args: x (np.ndarray): The input `x` array. Returns: np.ndarray: The sampled array. """ raise NotImplementedError() class BernoulliSampler(BaseSampler): """ A :class:`DataMapper` which can sample 0/1 integers according to the input probability. The input is assumed to be float numbers range within [0, 1) or [0, 1]. """ def __init__(self, dtype=np.int32, random_state=None): """ Construct a new :class:`BernoulliSampler`. Args: dtype: The data type of the sampled array. Default `np.int32`. random_state (RandomState): Optional numpy RandomState for sampling. (default :obj:`None`, use the global :class:`RandomState`). """ self._dtype = dtype self._random_state = random_state @property def dtype(self): """Get the data type of the sampled array.""" return self._dtype class UniformNoiseSampler(BaseSampler): """ A :class:`DataMapper` which can add uniform noise onto the input array. The data type of the returned array will be the same as the input array, unless `dtype` is specified at construction. """ def __init__(self, minval=0., maxval=1., dtype=None, random_state=None): """ Construct a new :class:`UniformNoiseSampler`. Args: minval: The lower bound of the uniform noise (included). maxval: The upper bound of the uniform noise (excluded). dtype: The data type of the sampled array. Default `np.int32`. random_state (RandomState): Optional numpy RandomState for sampling. (default :obj:`None`, use the global :class:`RandomState`). """ self._minval = minval self._maxval = maxval self._dtype = np.dtype(dtype) if dtype is not None else None self._random_state = random_state @property def minval(self): """Get the lower bound of the uniform noise (included).""" return self._minval @property def maxval(self): """Get the upper bound of the uniform noise (excluded).""" return self._maxval @property def dtype(self): """Get the data type of the sampled array.""" return self._dtype
[ 11748, 299, 32152, 355, 45941, 198, 198, 6738, 256, 9501, 77, 3974, 316, 13, 7890, 11125, 1330, 6060, 44, 11463, 198, 198, 834, 439, 834, 796, 37250, 14881, 16305, 20053, 3256, 705, 23927, 280, 15516, 16305, 20053, 3256, 705, 3118, 6933...
2.457035
1,059
from checkov.terraform.checks.resource.base_resource_value_check import BaseResourceValueCheck from checkov.common.models.enums import CheckResult, CheckCategories check = GKENetworkPolicyEnabled()
[ 6738, 2198, 709, 13, 353, 430, 687, 13, 42116, 13, 31092, 13, 8692, 62, 31092, 62, 8367, 62, 9122, 1330, 7308, 26198, 11395, 9787, 198, 6738, 2198, 709, 13, 11321, 13, 27530, 13, 268, 5700, 1330, 6822, 23004, 11, 6822, 34, 26129, 62...
3.654545
55
from django.contrib.auth import get_user_model from rest_framework import filters from rest_framework.viewsets import ModelViewSet from pastebin.users.permissions import IsAuthenticatedOrCreate from pastebin.users.serializers import UserSerializer User = get_user_model()
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, 19849, 198, 6738, 1334, 62, 30604, 1330, 16628, 198, 6738, 1334, 62, 30604, 13, 1177, 28709, 1330, 9104, 7680, 7248, 198, 198, 6738, 1613, 23497, 13, 18417, 13, 52...
3.767123
73
"""empty message Revision ID: fbfec56d097e Revises: 3b1f45ed96c7 Create Date: 2018-06-27 10:04:50.000959 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "fbfec56d097e" down_revision = "3b1f45ed96c7" branch_labels = None depends_on = None
[ 37811, 28920, 3275, 198, 198, 18009, 1166, 4522, 25, 277, 19881, 721, 3980, 67, 2931, 22, 68, 198, 18009, 2696, 25, 513, 65, 16, 69, 2231, 276, 4846, 66, 22, 198, 16447, 7536, 25, 2864, 12, 3312, 12, 1983, 838, 25, 3023, 25, 1120,...
2.392
125
# Copyright (C) 2010-2011 Richard Lincoln # # 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. from CIM16.CDPSM.Balanced.IEC61970.Wires.PhaseTapChangerNonLinear import PhaseTapChangerNonLinear class PhaseTapChangerSymetrical(PhaseTapChangerNonLinear): """In a PhaseTapChangerSymetrical tranformer the secondary side voltage magnitude is the same as at the primary side. The difference voltage magnitude, &Delta;U, is the base in an equal-sided triangle where the sides corresponds to the primary and secondary voltages. The phase angle difference correpsonds the top angle and can be expressed as follows &alpha; = 2arctan(&Delta;U/2) """ def __init__(self, *args, **kw_args): """Initialises a new 'PhaseTapChangerSymetrical' instance. """ super(PhaseTapChangerSymetrical, self).__init__(*args, **kw_args) _attrs = [] _attr_types = {} _defaults = {} _enums = {} _refs = [] _many_refs = []
[ 2, 15069, 357, 34, 8, 3050, 12, 9804, 6219, 12406, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 2, 286, 428, 3788, 290, 3917, 10314, 3696, 357, 1169, 366, 25423, 123...
3.389273
578
import numpy, scipy from matplotlib.ticker import FuncFormatter import matplotlib.colors as colors from echem_plate_math import * import time, pickle from echem_plate_fcns import * p='C:/Users/Public/Documents/EchemDropAnalyzedData/FCVdata/20130523 NiFeCoCe_3V_FCV_4835/Sample4825_x60_y65_A33B23C3D40_FCVS7.txt' p2='C:/Users/Public/Documents/EchemDropAnalyzedData/FCVdata/20130523 NiFeCoCe_3V_FCV_4835/Sample4825_x60_y65_A33B23C3D40_FCVS8.txt' #p2='' vrange=(-.19, -.14) d=readechemtxt(p) if p2!='': d2=readechemtxt(p2) for k, v in d2.iteritems(): d[k]=numpy.append(d[k], v) vraw=d['Ewe(V)'] iraw=d['I(A)'] pylab.plot(d['Ewe(V)'], d['I(A)']) #pylab.show() vrbool=(vraw>=vrange[0])&(vraw<=vrange[1]) testlen=4 vrboolmean=numpy.array([vrbool[i:i+testlen].mean(dtype='float32')>.5 for i in range(len(vrbool)-testlen//2)]) vrboolapproxinds=numpy.where(numpy.logical_not(vrboolmean[:-1])&(vrboolmean[1:]))[0]+testlen//2 vrboolnoisyinds=numpy.where(numpy.logical_not(vrbool[:-1])&(vrbool[1:]))[0] vstartinds_seg=vrboolnoisyinds[numpy.array([numpy.argmin((vrboolnoisyinds-i)**2) for i in vrboolapproxinds])] vlen_seg=[] for i, j in zip(vstartinds_seg, numpy.concatenate([vstartinds_seg[1:], [-1]])): print len(vrboolmean), i, j, j-testlen vlen_seg+=[numpy.where(vrboolmean[i:j-testlen])[0][-1]+testlen//2] pylab.figure() segdl=[] for vsi, vlen in zip(vstartinds_seg, vlen_seg): segd={} for k in ['Ewe(V)','I(A)', 't(s)']: segd[k]=d[k][vsi:vsi+vlen] v=segd['Ewe(V)'] i=segd['I(A)'] t=segd['t(s)'] ans=scipy.polyfit(v, i, 1) segd['I_Efit']=scipy.polyval(ans, v) segd['I_Efitfitpars']=ans ans=scipy.polyfit(t, v, 1) segd['E_tfit']=scipy.polyval(ans, t) segd['E_tfitfitpars']=ans segdl+=[segd] pylab.plot(segd['Ewe(V)'], segd['I(A)']) pylab.plot(segd['Ewe(V)'], segd['I_Efit']) dEdt=numpy.array([sd['E_tfitfitpars'][0] for sd in segdl]) dIdE=numpy.array([sd['I_Efitfitpars'][0] for sd in segdl]) C=numpy.array([numpy.trapz(sd['I_Efitfitpars'], x=sd['t(s)']) for sd in segdl]) inds=numpy.arange(0, len(segdl), 2) dEdtmean=(numpy.abs(dEdt[inds])+numpy.abs(dEdt[inds+1]))/2. dC=C[inds]-C[inds+1] vtest=numpy.array(vrange).mean() itestarr=numpy.array([scipy.polyval(sd['I_Efitfitpars'], vtest) for sd in segdl]) delI=itestarr[inds]-itestarr[inds+1] #pylab.figure() #pylab.plot(dEdtmean, dC*1.e6, 'o') #pylab.ylabel('differentialcharge (microC)') #pylab.xlabel('ave scan rate (V/s)') pylab.figure() dIdtplot=dIdE*dEdt*1.e6 pylab.plot(dIdtplot[inds], 'bo', label='fwd') pylab.plot(numpy.abs(dIdtplot[inds+1]), 'go', label='rev') pylab.ylabel('dI/dt (microA/s)') pylab.xlabel('CV number') pylab.legend(loc=2) pylab.figure() pylab.plot(dEdtmean, delI*1.e6, 'o') pylab.ylabel('capacitive current ($\mu$A)') pylab.xlabel('ave scan rate (V/s)') CC_dEdtfitpars=scipy.polyfit(dEdtmean, delI, 1) lims=numpy.array([0, dEdtmean.max()]) fitvals=scipy.polyval(CC_dEdtfitpars, lims) pylab.plot(lims, fitvals*1.e6, 'r-') pylab.title('%.2e $\mu$C/V +%.2e $\mu$A' %(CC_dEdtfitpars[0]*1.e6, CC_dEdtfitpars[1]*1.e6)) pylab.show()
[ 11748, 299, 32152, 11, 629, 541, 88, 198, 6738, 2603, 29487, 8019, 13, 83, 15799, 1330, 11138, 66, 8479, 1436, 198, 11748, 2603, 29487, 8019, 13, 4033, 669, 355, 7577, 198, 6738, 304, 15245, 62, 6816, 62, 11018, 1330, 1635, 198, 11748...
1.864397
1,674
l = lambda *x: print("%s %s %s" % x) l(1,2,3)
[ 75, 796, 37456, 1635, 87, 25, 3601, 7203, 4, 82, 4064, 82, 4064, 82, 1, 4064, 2124, 8, 198, 75, 7, 16, 11, 17, 11, 18, 8, 198 ]
1.642857
28
from django.db import models from django.urls import reverse # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 198, 2, 13610, 534, 4981, 994, 13, 628 ]
3.708333
24
begin_unit comment|'# Copyright 2013 IBM Corp.' nl|'\n' comment|'# Copyright 2011 OpenStack Foundation' nl|'\n' comment|'# All Rights Reserved.' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in compliance with the License. You may obtain' nl|'\n' comment|'# a copy of the License at' nl|'\n' comment|'#' nl|'\n' comment|'# http://www.apache.org/licenses/LICENSE-2.0' nl|'\n' comment|'#' nl|'\n' comment|'# Unless required by applicable law or agreed to in writing, software' nl|'\n' comment|'# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT' nl|'\n' comment|'# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the' nl|'\n' comment|'# License for the specific language governing permissions and limitations' nl|'\n' comment|'# under the License.' nl|'\n' nl|'\n' name|'import' name|'functools' newline|'\n' name|'import' name|'inspect' newline|'\n' name|'import' name|'math' newline|'\n' name|'import' name|'time' newline|'\n' nl|'\n' name|'import' name|'microversion_parse' newline|'\n' name|'from' name|'oslo_log' name|'import' name|'log' name|'as' name|'logging' newline|'\n' name|'from' name|'oslo_serialization' name|'import' name|'jsonutils' newline|'\n' name|'from' name|'oslo_utils' name|'import' name|'strutils' newline|'\n' name|'import' name|'six' newline|'\n' name|'import' name|'webob' newline|'\n' nl|'\n' name|'from' name|'nova' op|'.' name|'api' op|'.' name|'openstack' name|'import' name|'api_version_request' name|'as' name|'api_version' newline|'\n' name|'from' name|'nova' op|'.' name|'api' op|'.' name|'openstack' name|'import' name|'versioned_method' newline|'\n' name|'from' name|'nova' name|'import' name|'exception' newline|'\n' name|'from' name|'nova' name|'import' name|'i18n' newline|'\n' name|'from' name|'nova' op|'.' name|'i18n' name|'import' name|'_' newline|'\n' name|'from' name|'nova' op|'.' name|'i18n' name|'import' name|'_LE' newline|'\n' name|'from' name|'nova' op|'.' name|'i18n' name|'import' name|'_LI' newline|'\n' name|'from' name|'nova' name|'import' name|'utils' newline|'\n' name|'from' name|'nova' name|'import' name|'wsgi' newline|'\n' nl|'\n' nl|'\n' DECL|variable|LOG name|'LOG' op|'=' name|'logging' op|'.' name|'getLogger' op|'(' name|'__name__' op|')' newline|'\n' nl|'\n' DECL|variable|_SUPPORTED_CONTENT_TYPES name|'_SUPPORTED_CONTENT_TYPES' op|'=' op|'(' nl|'\n' string|"'application/json'" op|',' nl|'\n' string|"'application/vnd.openstack.compute+json'" op|',' nl|'\n' op|')' newline|'\n' nl|'\n' DECL|variable|_MEDIA_TYPE_MAP name|'_MEDIA_TYPE_MAP' op|'=' op|'{' nl|'\n' string|"'application/vnd.openstack.compute+json'" op|':' string|"'json'" op|',' nl|'\n' string|"'application/json'" op|':' string|"'json'" op|',' nl|'\n' op|'}' newline|'\n' nl|'\n' comment|'# These are typically automatically created by routes as either defaults' nl|'\n' comment|'# collection or member methods.' nl|'\n' DECL|variable|_ROUTES_METHODS name|'_ROUTES_METHODS' op|'=' op|'[' nl|'\n' string|"'create'" op|',' nl|'\n' string|"'delete'" op|',' nl|'\n' string|"'show'" op|',' nl|'\n' string|"'update'" op|',' nl|'\n' op|']' newline|'\n' nl|'\n' DECL|variable|_METHODS_WITH_BODY name|'_METHODS_WITH_BODY' op|'=' op|'[' nl|'\n' string|"'POST'" op|',' nl|'\n' string|"'PUT'" op|',' nl|'\n' op|']' newline|'\n' nl|'\n' comment|'# The default api version request if none is requested in the headers' nl|'\n' comment|'# Note(cyeoh): This only applies for the v2.1 API once microversions' nl|'\n' comment|'# support is fully merged. It does not affect the V2 API.' nl|'\n' DECL|variable|DEFAULT_API_VERSION name|'DEFAULT_API_VERSION' op|'=' string|'"2.1"' newline|'\n' nl|'\n' comment|'# name of attribute to keep version method information' nl|'\n' DECL|variable|VER_METHOD_ATTR name|'VER_METHOD_ATTR' op|'=' string|"'versioned_methods'" newline|'\n' nl|'\n' comment|'# Name of header used by clients to request a specific version' nl|'\n' comment|'# of the REST API' nl|'\n' DECL|variable|API_VERSION_REQUEST_HEADER name|'API_VERSION_REQUEST_HEADER' op|'=' string|"'X-OpenStack-Nova-API-Version'" newline|'\n' nl|'\n' nl|'\n' DECL|variable|ENV_LEGACY_V2 name|'ENV_LEGACY_V2' op|'=' string|"'openstack.legacy_v2'" newline|'\n' nl|'\n' nl|'\n' DECL|function|get_supported_content_types name|'def' name|'get_supported_content_types' op|'(' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'_SUPPORTED_CONTENT_TYPES' newline|'\n' nl|'\n' nl|'\n' DECL|function|get_media_map dedent|'' name|'def' name|'get_media_map' op|'(' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'dict' op|'(' name|'_MEDIA_TYPE_MAP' op|'.' name|'items' op|'(' op|')' op|')' newline|'\n' nl|'\n' nl|'\n' comment|'# NOTE(rlrossit): This function allows a get on both a dict-like and an' nl|'\n' comment|'# object-like object. cache_db_items() is used on both versioned objects and' nl|'\n' comment|"# dicts, so the function can't be totally changed over to [] syntax, nor" nl|'\n' comment|'# can it be changed over to use getattr().' nl|'\n' DECL|function|item_get dedent|'' name|'def' name|'item_get' op|'(' name|'item' op|',' name|'item_key' op|')' op|':' newline|'\n' indent|' ' name|'if' name|'hasattr' op|'(' name|'item' op|',' string|"'__getitem__'" op|')' op|':' newline|'\n' indent|' ' name|'return' name|'item' op|'[' name|'item_key' op|']' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'return' name|'getattr' op|'(' name|'item' op|',' name|'item_key' op|')' newline|'\n' nl|'\n' nl|'\n' DECL|class|Request dedent|'' dedent|'' name|'class' name|'Request' op|'(' name|'wsgi' op|'.' name|'Request' op|')' op|':' newline|'\n' indent|' ' string|'"""Add some OpenStack API-specific logic to the base webob.Request."""' newline|'\n' nl|'\n' DECL|member|__init__ name|'def' name|'__init__' op|'(' name|'self' op|',' op|'*' name|'args' op|',' op|'**' name|'kwargs' op|')' op|':' newline|'\n' indent|' ' name|'super' op|'(' name|'Request' op|',' name|'self' op|')' op|'.' name|'__init__' op|'(' op|'*' name|'args' op|',' op|'**' name|'kwargs' op|')' newline|'\n' name|'self' op|'.' name|'_extension_data' op|'=' op|'{' string|"'db_items'" op|':' op|'{' op|'}' op|'}' newline|'\n' name|'if' name|'not' name|'hasattr' op|'(' name|'self' op|',' string|"'api_version_request'" op|')' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'api_version_request' op|'=' name|'api_version' op|'.' name|'APIVersionRequest' op|'(' op|')' newline|'\n' nl|'\n' DECL|member|cache_db_items dedent|'' dedent|'' name|'def' name|'cache_db_items' op|'(' name|'self' op|',' name|'key' op|',' name|'items' op|',' name|'item_key' op|'=' string|"'id'" op|')' op|':' newline|'\n' indent|' ' string|'"""Allow API methods to store objects from a DB query to be\n used by API extensions within the same API request.\n\n An instance of this class only lives for the lifetime of a\n single API request, so there\'s no need to implement full\n cache management.\n """' newline|'\n' name|'db_items' op|'=' name|'self' op|'.' name|'_extension_data' op|'[' string|"'db_items'" op|']' op|'.' name|'setdefault' op|'(' name|'key' op|',' op|'{' op|'}' op|')' newline|'\n' name|'for' name|'item' name|'in' name|'items' op|':' newline|'\n' indent|' ' name|'db_items' op|'[' name|'item_get' op|'(' name|'item' op|',' name|'item_key' op|')' op|']' op|'=' name|'item' newline|'\n' nl|'\n' DECL|member|get_db_items dedent|'' dedent|'' name|'def' name|'get_db_items' op|'(' name|'self' op|',' name|'key' op|')' op|':' newline|'\n' indent|' ' string|'"""Allow an API extension to get previously stored objects within\n the same API request.\n\n Note that the object data will be slightly stale.\n """' newline|'\n' name|'return' name|'self' op|'.' name|'_extension_data' op|'[' string|"'db_items'" op|']' op|'[' name|'key' op|']' newline|'\n' nl|'\n' DECL|member|get_db_item dedent|'' name|'def' name|'get_db_item' op|'(' name|'self' op|',' name|'key' op|',' name|'item_key' op|')' op|':' newline|'\n' indent|' ' string|'"""Allow an API extension to get a previously stored object\n within the same API request.\n\n Note that the object data will be slightly stale.\n """' newline|'\n' name|'return' name|'self' op|'.' name|'get_db_items' op|'(' name|'key' op|')' op|'.' name|'get' op|'(' name|'item_key' op|')' newline|'\n' nl|'\n' DECL|member|cache_db_instances dedent|'' name|'def' name|'cache_db_instances' op|'(' name|'self' op|',' name|'instances' op|')' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'cache_db_items' op|'(' string|"'instances'" op|',' name|'instances' op|',' string|"'uuid'" op|')' newline|'\n' nl|'\n' DECL|member|cache_db_instance dedent|'' name|'def' name|'cache_db_instance' op|'(' name|'self' op|',' name|'instance' op|')' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'cache_db_items' op|'(' string|"'instances'" op|',' op|'[' name|'instance' op|']' op|',' string|"'uuid'" op|')' newline|'\n' nl|'\n' DECL|member|get_db_instances dedent|'' name|'def' name|'get_db_instances' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'self' op|'.' name|'get_db_items' op|'(' string|"'instances'" op|')' newline|'\n' nl|'\n' DECL|member|get_db_instance dedent|'' name|'def' name|'get_db_instance' op|'(' name|'self' op|',' name|'instance_uuid' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'self' op|'.' name|'get_db_item' op|'(' string|"'instances'" op|',' name|'instance_uuid' op|')' newline|'\n' nl|'\n' DECL|member|cache_db_flavors dedent|'' name|'def' name|'cache_db_flavors' op|'(' name|'self' op|',' name|'flavors' op|')' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'cache_db_items' op|'(' string|"'flavors'" op|',' name|'flavors' op|',' string|"'flavorid'" op|')' newline|'\n' nl|'\n' DECL|member|cache_db_flavor dedent|'' name|'def' name|'cache_db_flavor' op|'(' name|'self' op|',' name|'flavor' op|')' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'cache_db_items' op|'(' string|"'flavors'" op|',' op|'[' name|'flavor' op|']' op|',' string|"'flavorid'" op|')' newline|'\n' nl|'\n' DECL|member|get_db_flavors dedent|'' name|'def' name|'get_db_flavors' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'self' op|'.' name|'get_db_items' op|'(' string|"'flavors'" op|')' newline|'\n' nl|'\n' DECL|member|get_db_flavor dedent|'' name|'def' name|'get_db_flavor' op|'(' name|'self' op|',' name|'flavorid' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'self' op|'.' name|'get_db_item' op|'(' string|"'flavors'" op|',' name|'flavorid' op|')' newline|'\n' nl|'\n' DECL|member|cache_db_compute_nodes dedent|'' name|'def' name|'cache_db_compute_nodes' op|'(' name|'self' op|',' name|'compute_nodes' op|')' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'cache_db_items' op|'(' string|"'compute_nodes'" op|',' name|'compute_nodes' op|',' string|"'id'" op|')' newline|'\n' nl|'\n' DECL|member|cache_db_compute_node dedent|'' name|'def' name|'cache_db_compute_node' op|'(' name|'self' op|',' name|'compute_node' op|')' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'cache_db_items' op|'(' string|"'compute_nodes'" op|',' op|'[' name|'compute_node' op|']' op|',' string|"'id'" op|')' newline|'\n' nl|'\n' DECL|member|get_db_compute_nodes dedent|'' name|'def' name|'get_db_compute_nodes' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'self' op|'.' name|'get_db_items' op|'(' string|"'compute_nodes'" op|')' newline|'\n' nl|'\n' DECL|member|get_db_compute_node dedent|'' name|'def' name|'get_db_compute_node' op|'(' name|'self' op|',' name|'id' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'self' op|'.' name|'get_db_item' op|'(' string|"'compute_nodes'" op|',' name|'id' op|')' newline|'\n' nl|'\n' DECL|member|best_match_content_type dedent|'' name|'def' name|'best_match_content_type' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' string|'"""Determine the requested response content-type."""' newline|'\n' name|'if' string|"'nova.best_content_type'" name|'not' name|'in' name|'self' op|'.' name|'environ' op|':' newline|'\n' comment|'# Calculate the best MIME type' nl|'\n' indent|' ' name|'content_type' op|'=' name|'None' newline|'\n' nl|'\n' comment|'# Check URL path suffix' nl|'\n' name|'parts' op|'=' name|'self' op|'.' name|'path' op|'.' name|'rsplit' op|'(' string|"'.'" op|',' number|'1' op|')' newline|'\n' name|'if' name|'len' op|'(' name|'parts' op|')' op|'>' number|'1' op|':' newline|'\n' indent|' ' name|'possible_type' op|'=' string|"'application/'" op|'+' name|'parts' op|'[' number|'1' op|']' newline|'\n' name|'if' name|'possible_type' name|'in' name|'get_supported_content_types' op|'(' op|')' op|':' newline|'\n' indent|' ' name|'content_type' op|'=' name|'possible_type' newline|'\n' nl|'\n' dedent|'' dedent|'' name|'if' name|'not' name|'content_type' op|':' newline|'\n' indent|' ' name|'content_type' op|'=' name|'self' op|'.' name|'accept' op|'.' name|'best_match' op|'(' nl|'\n' name|'get_supported_content_types' op|'(' op|')' op|')' newline|'\n' nl|'\n' dedent|'' name|'self' op|'.' name|'environ' op|'[' string|"'nova.best_content_type'" op|']' op|'=' op|'(' name|'content_type' name|'or' nl|'\n' string|"'application/json'" op|')' newline|'\n' nl|'\n' dedent|'' name|'return' name|'self' op|'.' name|'environ' op|'[' string|"'nova.best_content_type'" op|']' newline|'\n' nl|'\n' DECL|member|get_content_type dedent|'' name|'def' name|'get_content_type' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' string|'"""Determine content type of the request body.\n\n Does not do any body introspection, only checks header\n\n """' newline|'\n' name|'if' string|'"Content-Type"' name|'not' name|'in' name|'self' op|'.' name|'headers' op|':' newline|'\n' indent|' ' name|'return' name|'None' newline|'\n' nl|'\n' dedent|'' name|'content_type' op|'=' name|'self' op|'.' name|'content_type' newline|'\n' nl|'\n' comment|'# NOTE(markmc): text/plain is the default for eventlet and' nl|'\n' comment|'# other webservers which use mimetools.Message.gettype()' nl|'\n' comment|"# whereas twisted defaults to ''." nl|'\n' name|'if' name|'not' name|'content_type' name|'or' name|'content_type' op|'==' string|"'text/plain'" op|':' newline|'\n' indent|' ' name|'return' name|'None' newline|'\n' nl|'\n' dedent|'' name|'if' name|'content_type' name|'not' name|'in' name|'get_supported_content_types' op|'(' op|')' op|':' newline|'\n' indent|' ' name|'raise' name|'exception' op|'.' name|'InvalidContentType' op|'(' name|'content_type' op|'=' name|'content_type' op|')' newline|'\n' nl|'\n' dedent|'' name|'return' name|'content_type' newline|'\n' nl|'\n' DECL|member|best_match_language dedent|'' name|'def' name|'best_match_language' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' string|'"""Determine the best available language for the request.\n\n :returns: the best language match or None if the \'Accept-Language\'\n header was not available in the request.\n """' newline|'\n' name|'if' name|'not' name|'self' op|'.' name|'accept_language' op|':' newline|'\n' indent|' ' name|'return' name|'None' newline|'\n' dedent|'' name|'return' name|'self' op|'.' name|'accept_language' op|'.' name|'best_match' op|'(' nl|'\n' name|'i18n' op|'.' name|'get_available_languages' op|'(' op|')' op|')' newline|'\n' nl|'\n' DECL|member|set_api_version_request dedent|'' name|'def' name|'set_api_version_request' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' string|'"""Set API version request based on the request header information."""' newline|'\n' name|'hdr_string' op|'=' name|'microversion_parse' op|'.' name|'get_version' op|'(' nl|'\n' name|'self' op|'.' name|'headers' op|',' name|'service_type' op|'=' string|"'compute'" op|',' nl|'\n' name|'legacy_headers' op|'=' op|'[' name|'API_VERSION_REQUEST_HEADER' op|']' op|')' newline|'\n' nl|'\n' name|'if' name|'hdr_string' name|'is' name|'None' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'api_version_request' op|'=' name|'api_version' op|'.' name|'APIVersionRequest' op|'(' nl|'\n' name|'api_version' op|'.' name|'DEFAULT_API_VERSION' op|')' newline|'\n' dedent|'' name|'elif' name|'hdr_string' op|'==' string|"'latest'" op|':' newline|'\n' comment|"# 'latest' is a special keyword which is equivalent to" nl|'\n' comment|'# requesting the maximum version of the API supported' nl|'\n' indent|' ' name|'self' op|'.' name|'api_version_request' op|'=' name|'api_version' op|'.' name|'max_api_version' op|'(' op|')' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'api_version_request' op|'=' name|'api_version' op|'.' name|'APIVersionRequest' op|'(' nl|'\n' name|'hdr_string' op|')' newline|'\n' nl|'\n' comment|'# Check that the version requested is within the global' nl|'\n' comment|'# minimum/maximum of supported API versions' nl|'\n' name|'if' name|'not' name|'self' op|'.' name|'api_version_request' op|'.' name|'matches' op|'(' nl|'\n' name|'api_version' op|'.' name|'min_api_version' op|'(' op|')' op|',' nl|'\n' name|'api_version' op|'.' name|'max_api_version' op|'(' op|')' op|')' op|':' newline|'\n' indent|' ' name|'raise' name|'exception' op|'.' name|'InvalidGlobalAPIVersion' op|'(' nl|'\n' name|'req_ver' op|'=' name|'self' op|'.' name|'api_version_request' op|'.' name|'get_string' op|'(' op|')' op|',' nl|'\n' name|'min_ver' op|'=' name|'api_version' op|'.' name|'min_api_version' op|'(' op|')' op|'.' name|'get_string' op|'(' op|')' op|',' nl|'\n' name|'max_ver' op|'=' name|'api_version' op|'.' name|'max_api_version' op|'(' op|')' op|'.' name|'get_string' op|'(' op|')' op|')' newline|'\n' nl|'\n' DECL|member|set_legacy_v2 dedent|'' dedent|'' dedent|'' name|'def' name|'set_legacy_v2' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'environ' op|'[' name|'ENV_LEGACY_V2' op|']' op|'=' name|'True' newline|'\n' nl|'\n' DECL|member|is_legacy_v2 dedent|'' name|'def' name|'is_legacy_v2' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'self' op|'.' name|'environ' op|'.' name|'get' op|'(' name|'ENV_LEGACY_V2' op|',' name|'False' op|')' newline|'\n' nl|'\n' nl|'\n' DECL|class|ActionDispatcher dedent|'' dedent|'' name|'class' name|'ActionDispatcher' op|'(' name|'object' op|')' op|':' newline|'\n' indent|' ' string|'"""Maps method name to local methods through action name."""' newline|'\n' nl|'\n' DECL|member|dispatch name|'def' name|'dispatch' op|'(' name|'self' op|',' op|'*' name|'args' op|',' op|'**' name|'kwargs' op|')' op|':' newline|'\n' indent|' ' string|'"""Find and call local method."""' newline|'\n' name|'action' op|'=' name|'kwargs' op|'.' name|'pop' op|'(' string|"'action'" op|',' string|"'default'" op|')' newline|'\n' name|'action_method' op|'=' name|'getattr' op|'(' name|'self' op|',' name|'str' op|'(' name|'action' op|')' op|',' name|'self' op|'.' name|'default' op|')' newline|'\n' name|'return' name|'action_method' op|'(' op|'*' name|'args' op|',' op|'**' name|'kwargs' op|')' newline|'\n' nl|'\n' DECL|member|default dedent|'' name|'def' name|'default' op|'(' name|'self' op|',' name|'data' op|')' op|':' newline|'\n' indent|' ' name|'raise' name|'NotImplementedError' op|'(' op|')' newline|'\n' nl|'\n' nl|'\n' DECL|class|JSONDeserializer dedent|'' dedent|'' name|'class' name|'JSONDeserializer' op|'(' name|'ActionDispatcher' op|')' op|':' newline|'\n' nl|'\n' DECL|member|_from_json indent|' ' name|'def' name|'_from_json' op|'(' name|'self' op|',' name|'datastring' op|')' op|':' newline|'\n' indent|' ' name|'try' op|':' newline|'\n' indent|' ' name|'return' name|'jsonutils' op|'.' name|'loads' op|'(' name|'datastring' op|')' newline|'\n' dedent|'' name|'except' name|'ValueError' op|':' newline|'\n' indent|' ' name|'msg' op|'=' name|'_' op|'(' string|'"cannot understand JSON"' op|')' newline|'\n' name|'raise' name|'exception' op|'.' name|'MalformedRequestBody' op|'(' name|'reason' op|'=' name|'msg' op|')' newline|'\n' nl|'\n' DECL|member|deserialize dedent|'' dedent|'' name|'def' name|'deserialize' op|'(' name|'self' op|',' name|'datastring' op|',' name|'action' op|'=' string|"'default'" op|')' op|':' newline|'\n' indent|' ' name|'return' name|'self' op|'.' name|'dispatch' op|'(' name|'datastring' op|',' name|'action' op|'=' name|'action' op|')' newline|'\n' nl|'\n' DECL|member|default dedent|'' name|'def' name|'default' op|'(' name|'self' op|',' name|'datastring' op|')' op|':' newline|'\n' indent|' ' name|'return' op|'{' string|"'body'" op|':' name|'self' op|'.' name|'_from_json' op|'(' name|'datastring' op|')' op|'}' newline|'\n' nl|'\n' nl|'\n' DECL|class|JSONDictSerializer dedent|'' dedent|'' name|'class' name|'JSONDictSerializer' op|'(' name|'ActionDispatcher' op|')' op|':' newline|'\n' indent|' ' string|'"""Default JSON request body serialization."""' newline|'\n' nl|'\n' DECL|member|serialize name|'def' name|'serialize' op|'(' name|'self' op|',' name|'data' op|',' name|'action' op|'=' string|"'default'" op|')' op|':' newline|'\n' indent|' ' name|'return' name|'self' op|'.' name|'dispatch' op|'(' name|'data' op|',' name|'action' op|'=' name|'action' op|')' newline|'\n' nl|'\n' DECL|member|default dedent|'' name|'def' name|'default' op|'(' name|'self' op|',' name|'data' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'six' op|'.' name|'text_type' op|'(' name|'jsonutils' op|'.' name|'dumps' op|'(' name|'data' op|')' op|')' newline|'\n' nl|'\n' nl|'\n' DECL|function|response dedent|'' dedent|'' name|'def' name|'response' op|'(' name|'code' op|')' op|':' newline|'\n' indent|' ' string|'"""Attaches response code to a method.\n\n This decorator associates a response code with a method. Note\n that the function attributes are directly manipulated; the method\n is not wrapped.\n """' newline|'\n' nl|'\n' DECL|function|decorator name|'def' name|'decorator' op|'(' name|'func' op|')' op|':' newline|'\n' indent|' ' name|'func' op|'.' name|'wsgi_code' op|'=' name|'code' newline|'\n' name|'return' name|'func' newline|'\n' dedent|'' name|'return' name|'decorator' newline|'\n' nl|'\n' nl|'\n' DECL|class|ResponseObject dedent|'' name|'class' name|'ResponseObject' op|'(' name|'object' op|')' op|':' newline|'\n' indent|' ' string|'"""Bundles a response object\n\n Object that app methods may return in order to allow its response\n to be modified by extensions in the code. Its use is optional (and\n should only be used if you really know what you are doing).\n """' newline|'\n' nl|'\n' DECL|member|__init__ name|'def' name|'__init__' op|'(' name|'self' op|',' name|'obj' op|',' name|'code' op|'=' name|'None' op|',' name|'headers' op|'=' name|'None' op|')' op|':' newline|'\n' indent|' ' string|'"""Builds a response object."""' newline|'\n' nl|'\n' name|'self' op|'.' name|'obj' op|'=' name|'obj' newline|'\n' name|'self' op|'.' name|'_default_code' op|'=' number|'200' newline|'\n' name|'self' op|'.' name|'_code' op|'=' name|'code' newline|'\n' name|'self' op|'.' name|'_headers' op|'=' name|'headers' name|'or' op|'{' op|'}' newline|'\n' name|'self' op|'.' name|'serializer' op|'=' name|'JSONDictSerializer' op|'(' op|')' newline|'\n' nl|'\n' DECL|member|__getitem__ dedent|'' name|'def' name|'__getitem__' op|'(' name|'self' op|',' name|'key' op|')' op|':' newline|'\n' indent|' ' string|'"""Retrieves a header with the given name."""' newline|'\n' nl|'\n' name|'return' name|'self' op|'.' name|'_headers' op|'[' name|'key' op|'.' name|'lower' op|'(' op|')' op|']' newline|'\n' nl|'\n' DECL|member|__setitem__ dedent|'' name|'def' name|'__setitem__' op|'(' name|'self' op|',' name|'key' op|',' name|'value' op|')' op|':' newline|'\n' indent|' ' string|'"""Sets a header with the given name to the given value."""' newline|'\n' nl|'\n' name|'self' op|'.' name|'_headers' op|'[' name|'key' op|'.' name|'lower' op|'(' op|')' op|']' op|'=' name|'value' newline|'\n' nl|'\n' DECL|member|__delitem__ dedent|'' name|'def' name|'__delitem__' op|'(' name|'self' op|',' name|'key' op|')' op|':' newline|'\n' indent|' ' string|'"""Deletes the header with the given name."""' newline|'\n' nl|'\n' name|'del' name|'self' op|'.' name|'_headers' op|'[' name|'key' op|'.' name|'lower' op|'(' op|')' op|']' newline|'\n' nl|'\n' DECL|member|serialize dedent|'' name|'def' name|'serialize' op|'(' name|'self' op|',' name|'request' op|',' name|'content_type' op|')' op|':' newline|'\n' indent|' ' string|'"""Serializes the wrapped object.\n\n Utility method for serializing the wrapped object. Returns a\n webob.Response object.\n """' newline|'\n' nl|'\n' name|'serializer' op|'=' name|'self' op|'.' name|'serializer' newline|'\n' nl|'\n' name|'body' op|'=' name|'None' newline|'\n' name|'if' name|'self' op|'.' name|'obj' name|'is' name|'not' name|'None' op|':' newline|'\n' indent|' ' name|'body' op|'=' name|'serializer' op|'.' name|'serialize' op|'(' name|'self' op|'.' name|'obj' op|')' newline|'\n' dedent|'' name|'response' op|'=' name|'webob' op|'.' name|'Response' op|'(' name|'body' op|'=' name|'body' op|')' newline|'\n' name|'if' name|'response' op|'.' name|'headers' op|'.' name|'get' op|'(' string|"'Content-Length'" op|')' op|':' newline|'\n' comment|"# NOTE(andreykurilin): we need to encode 'Content-Length' header," nl|'\n' comment|'# since webob.Response auto sets it if "body" attr is presented.' nl|'\n' comment|'# https://github.com/Pylons/webob/blob/1.5.0b0/webob/response.py#L147' nl|'\n' indent|' ' name|'response' op|'.' name|'headers' op|'[' string|"'Content-Length'" op|']' op|'=' name|'utils' op|'.' name|'utf8' op|'(' nl|'\n' name|'response' op|'.' name|'headers' op|'[' string|"'Content-Length'" op|']' op|')' newline|'\n' dedent|'' name|'response' op|'.' name|'status_int' op|'=' name|'self' op|'.' name|'code' newline|'\n' name|'for' name|'hdr' op|',' name|'value' name|'in' name|'self' op|'.' name|'_headers' op|'.' name|'items' op|'(' op|')' op|':' newline|'\n' indent|' ' name|'response' op|'.' name|'headers' op|'[' name|'hdr' op|']' op|'=' name|'utils' op|'.' name|'utf8' op|'(' name|'value' op|')' newline|'\n' dedent|'' name|'response' op|'.' name|'headers' op|'[' string|"'Content-Type'" op|']' op|'=' name|'utils' op|'.' name|'utf8' op|'(' name|'content_type' op|')' newline|'\n' name|'return' name|'response' newline|'\n' nl|'\n' dedent|'' op|'@' name|'property' newline|'\n' DECL|member|code name|'def' name|'code' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' string|'"""Retrieve the response status."""' newline|'\n' nl|'\n' name|'return' name|'self' op|'.' name|'_code' name|'or' name|'self' op|'.' name|'_default_code' newline|'\n' nl|'\n' dedent|'' op|'@' name|'property' newline|'\n' DECL|member|headers name|'def' name|'headers' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' string|'"""Retrieve the headers."""' newline|'\n' nl|'\n' name|'return' name|'self' op|'.' name|'_headers' op|'.' name|'copy' op|'(' op|')' newline|'\n' nl|'\n' nl|'\n' DECL|function|action_peek dedent|'' dedent|'' name|'def' name|'action_peek' op|'(' name|'body' op|')' op|':' newline|'\n' indent|' ' string|'"""Determine action to invoke.\n\n This looks inside the json body and fetches out the action method\n name.\n """' newline|'\n' nl|'\n' name|'try' op|':' newline|'\n' indent|' ' name|'decoded' op|'=' name|'jsonutils' op|'.' name|'loads' op|'(' name|'body' op|')' newline|'\n' dedent|'' name|'except' name|'ValueError' op|':' newline|'\n' indent|' ' name|'msg' op|'=' name|'_' op|'(' string|'"cannot understand JSON"' op|')' newline|'\n' name|'raise' name|'exception' op|'.' name|'MalformedRequestBody' op|'(' name|'reason' op|'=' name|'msg' op|')' newline|'\n' nl|'\n' comment|"# Make sure there's exactly one key..." nl|'\n' dedent|'' name|'if' name|'len' op|'(' name|'decoded' op|')' op|'!=' number|'1' op|':' newline|'\n' indent|' ' name|'msg' op|'=' name|'_' op|'(' string|'"too many body keys"' op|')' newline|'\n' name|'raise' name|'exception' op|'.' name|'MalformedRequestBody' op|'(' name|'reason' op|'=' name|'msg' op|')' newline|'\n' nl|'\n' comment|'# Return the action name' nl|'\n' dedent|'' name|'return' name|'list' op|'(' name|'decoded' op|'.' name|'keys' op|'(' op|')' op|')' op|'[' number|'0' op|']' newline|'\n' nl|'\n' nl|'\n' DECL|class|ResourceExceptionHandler dedent|'' name|'class' name|'ResourceExceptionHandler' op|'(' name|'object' op|')' op|':' newline|'\n' indent|' ' string|'"""Context manager to handle Resource exceptions.\n\n Used when processing exceptions generated by API implementation\n methods (or their extensions). Converts most exceptions to Fault\n exceptions, with the appropriate logging.\n """' newline|'\n' nl|'\n' DECL|member|__enter__ name|'def' name|'__enter__' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'None' newline|'\n' nl|'\n' DECL|member|__exit__ dedent|'' name|'def' name|'__exit__' op|'(' name|'self' op|',' name|'ex_type' op|',' name|'ex_value' op|',' name|'ex_traceback' op|')' op|':' newline|'\n' indent|' ' name|'if' name|'not' name|'ex_value' op|':' newline|'\n' indent|' ' name|'return' name|'True' newline|'\n' nl|'\n' dedent|'' name|'if' name|'isinstance' op|'(' name|'ex_value' op|',' name|'exception' op|'.' name|'Forbidden' op|')' op|':' newline|'\n' indent|' ' name|'raise' name|'Fault' op|'(' name|'webob' op|'.' name|'exc' op|'.' name|'HTTPForbidden' op|'(' nl|'\n' name|'explanation' op|'=' name|'ex_value' op|'.' name|'format_message' op|'(' op|')' op|')' op|')' newline|'\n' dedent|'' name|'elif' name|'isinstance' op|'(' name|'ex_value' op|',' name|'exception' op|'.' name|'VersionNotFoundForAPIMethod' op|')' op|':' newline|'\n' indent|' ' name|'raise' newline|'\n' dedent|'' name|'elif' name|'isinstance' op|'(' name|'ex_value' op|',' name|'exception' op|'.' name|'Invalid' op|')' op|':' newline|'\n' indent|' ' name|'raise' name|'Fault' op|'(' name|'exception' op|'.' name|'ConvertedException' op|'(' nl|'\n' name|'code' op|'=' name|'ex_value' op|'.' name|'code' op|',' nl|'\n' name|'explanation' op|'=' name|'ex_value' op|'.' name|'format_message' op|'(' op|')' op|')' op|')' newline|'\n' dedent|'' name|'elif' name|'isinstance' op|'(' name|'ex_value' op|',' name|'TypeError' op|')' op|':' newline|'\n' indent|' ' name|'exc_info' op|'=' op|'(' name|'ex_type' op|',' name|'ex_value' op|',' name|'ex_traceback' op|')' newline|'\n' name|'LOG' op|'.' name|'error' op|'(' name|'_LE' op|'(' string|"'Exception handling resource: %s'" op|')' op|',' name|'ex_value' op|',' nl|'\n' name|'exc_info' op|'=' name|'exc_info' op|')' newline|'\n' name|'raise' name|'Fault' op|'(' name|'webob' op|'.' name|'exc' op|'.' name|'HTTPBadRequest' op|'(' op|')' op|')' newline|'\n' dedent|'' name|'elif' name|'isinstance' op|'(' name|'ex_value' op|',' name|'Fault' op|')' op|':' newline|'\n' indent|' ' name|'LOG' op|'.' name|'info' op|'(' name|'_LI' op|'(' string|'"Fault thrown: %s"' op|')' op|',' name|'ex_value' op|')' newline|'\n' name|'raise' name|'ex_value' newline|'\n' dedent|'' name|'elif' name|'isinstance' op|'(' name|'ex_value' op|',' name|'webob' op|'.' name|'exc' op|'.' name|'HTTPException' op|')' op|':' newline|'\n' indent|' ' name|'LOG' op|'.' name|'info' op|'(' name|'_LI' op|'(' string|'"HTTP exception thrown: %s"' op|')' op|',' name|'ex_value' op|')' newline|'\n' name|'raise' name|'Fault' op|'(' name|'ex_value' op|')' newline|'\n' nl|'\n' comment|"# We didn't handle the exception" nl|'\n' dedent|'' name|'return' name|'False' newline|'\n' nl|'\n' nl|'\n' DECL|class|Resource dedent|'' dedent|'' name|'class' name|'Resource' op|'(' name|'wsgi' op|'.' name|'Application' op|')' op|':' newline|'\n' indent|' ' string|'"""WSGI app that handles (de)serialization and controller dispatch.\n\n WSGI app that reads routing information supplied by RoutesMiddleware\n and calls the requested action method upon its controller. All\n controller action methods must accept a \'req\' argument, which is the\n incoming wsgi.Request. If the operation is a PUT or POST, the controller\n method must also accept a \'body\' argument (the deserialized request body).\n They may raise a webob.exc exception or return a dict, which will be\n serialized by requested content type.\n\n Exceptions derived from webob.exc.HTTPException will be automatically\n wrapped in Fault() to provide API friendly error responses.\n\n """' newline|'\n' DECL|variable|support_api_request_version name|'support_api_request_version' op|'=' name|'False' newline|'\n' nl|'\n' DECL|member|__init__ name|'def' name|'__init__' op|'(' name|'self' op|',' name|'controller' op|',' name|'inherits' op|'=' name|'None' op|')' op|':' newline|'\n' indent|' ' string|'""":param controller: object that implement methods created by routes\n lib\n :param inherits: another resource object that this resource should\n inherit extensions from. Any action extensions that\n are applied to the parent resource will also apply\n to this resource.\n """' newline|'\n' nl|'\n' name|'self' op|'.' name|'controller' op|'=' name|'controller' newline|'\n' nl|'\n' name|'self' op|'.' name|'default_serializers' op|'=' name|'dict' op|'(' name|'json' op|'=' name|'JSONDictSerializer' op|')' newline|'\n' nl|'\n' comment|'# Copy over the actions dictionary' nl|'\n' name|'self' op|'.' name|'wsgi_actions' op|'=' op|'{' op|'}' newline|'\n' name|'if' name|'controller' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'register_actions' op|'(' name|'controller' op|')' newline|'\n' nl|'\n' comment|'# Save a mapping of extensions' nl|'\n' dedent|'' name|'self' op|'.' name|'wsgi_extensions' op|'=' op|'{' op|'}' newline|'\n' name|'self' op|'.' name|'wsgi_action_extensions' op|'=' op|'{' op|'}' newline|'\n' name|'self' op|'.' name|'inherits' op|'=' name|'inherits' newline|'\n' nl|'\n' DECL|member|register_actions dedent|'' name|'def' name|'register_actions' op|'(' name|'self' op|',' name|'controller' op|')' op|':' newline|'\n' indent|' ' string|'"""Registers controller actions with this resource."""' newline|'\n' nl|'\n' name|'actions' op|'=' name|'getattr' op|'(' name|'controller' op|',' string|"'wsgi_actions'" op|',' op|'{' op|'}' op|')' newline|'\n' name|'for' name|'key' op|',' name|'method_name' name|'in' name|'actions' op|'.' name|'items' op|'(' op|')' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'wsgi_actions' op|'[' name|'key' op|']' op|'=' name|'getattr' op|'(' name|'controller' op|',' name|'method_name' op|')' newline|'\n' nl|'\n' DECL|member|register_extensions dedent|'' dedent|'' name|'def' name|'register_extensions' op|'(' name|'self' op|',' name|'controller' op|')' op|':' newline|'\n' indent|' ' string|'"""Registers controller extensions with this resource."""' newline|'\n' nl|'\n' name|'extensions' op|'=' name|'getattr' op|'(' name|'controller' op|',' string|"'wsgi_extensions'" op|',' op|'[' op|']' op|')' newline|'\n' name|'for' name|'method_name' op|',' name|'action_name' name|'in' name|'extensions' op|':' newline|'\n' comment|'# Look up the extending method' nl|'\n' indent|' ' name|'extension' op|'=' name|'getattr' op|'(' name|'controller' op|',' name|'method_name' op|')' newline|'\n' nl|'\n' name|'if' name|'action_name' op|':' newline|'\n' comment|'# Extending an action...' nl|'\n' indent|' ' name|'if' name|'action_name' name|'not' name|'in' name|'self' op|'.' name|'wsgi_action_extensions' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'wsgi_action_extensions' op|'[' name|'action_name' op|']' op|'=' op|'[' op|']' newline|'\n' dedent|'' name|'self' op|'.' name|'wsgi_action_extensions' op|'[' name|'action_name' op|']' op|'.' name|'append' op|'(' name|'extension' op|')' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' comment|'# Extending a regular method' nl|'\n' indent|' ' name|'if' name|'method_name' name|'not' name|'in' name|'self' op|'.' name|'wsgi_extensions' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'wsgi_extensions' op|'[' name|'method_name' op|']' op|'=' op|'[' op|']' newline|'\n' dedent|'' name|'self' op|'.' name|'wsgi_extensions' op|'[' name|'method_name' op|']' op|'.' name|'append' op|'(' name|'extension' op|')' newline|'\n' nl|'\n' DECL|member|get_action_args dedent|'' dedent|'' dedent|'' name|'def' name|'get_action_args' op|'(' name|'self' op|',' name|'request_environment' op|')' op|':' newline|'\n' indent|' ' string|'"""Parse dictionary created by routes library."""' newline|'\n' nl|'\n' comment|'# NOTE(Vek): Check for get_action_args() override in the' nl|'\n' comment|'# controller' nl|'\n' name|'if' name|'hasattr' op|'(' name|'self' op|'.' name|'controller' op|',' string|"'get_action_args'" op|')' op|':' newline|'\n' indent|' ' name|'return' name|'self' op|'.' name|'controller' op|'.' name|'get_action_args' op|'(' name|'request_environment' op|')' newline|'\n' nl|'\n' dedent|'' name|'try' op|':' newline|'\n' indent|' ' name|'args' op|'=' name|'request_environment' op|'[' string|"'wsgiorg.routing_args'" op|']' op|'[' number|'1' op|']' op|'.' name|'copy' op|'(' op|')' newline|'\n' dedent|'' name|'except' op|'(' name|'KeyError' op|',' name|'IndexError' op|',' name|'AttributeError' op|')' op|':' newline|'\n' indent|' ' name|'return' op|'{' op|'}' newline|'\n' nl|'\n' dedent|'' name|'try' op|':' newline|'\n' indent|' ' name|'del' name|'args' op|'[' string|"'controller'" op|']' newline|'\n' dedent|'' name|'except' name|'KeyError' op|':' newline|'\n' indent|' ' name|'pass' newline|'\n' nl|'\n' dedent|'' name|'try' op|':' newline|'\n' indent|' ' name|'del' name|'args' op|'[' string|"'format'" op|']' newline|'\n' dedent|'' name|'except' name|'KeyError' op|':' newline|'\n' indent|' ' name|'pass' newline|'\n' nl|'\n' dedent|'' name|'return' name|'args' newline|'\n' nl|'\n' DECL|member|get_body dedent|'' name|'def' name|'get_body' op|'(' name|'self' op|',' name|'request' op|')' op|':' newline|'\n' indent|' ' name|'content_type' op|'=' name|'request' op|'.' name|'get_content_type' op|'(' op|')' newline|'\n' nl|'\n' name|'return' name|'content_type' op|',' name|'request' op|'.' name|'body' newline|'\n' nl|'\n' DECL|member|deserialize dedent|'' name|'def' name|'deserialize' op|'(' name|'self' op|',' name|'body' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'JSONDeserializer' op|'(' op|')' op|'.' name|'deserialize' op|'(' name|'body' op|')' newline|'\n' nl|'\n' comment|"# NOTE(sdague): I didn't start the fire, however here is what all" nl|'\n' comment|'# of this is about.' nl|'\n' comment|'#' nl|'\n' comment|'# In the legacy v2 code stack, extensions could extend actions' nl|'\n' comment|'# with a generator that let 1 method be split into a top and' nl|'\n' comment|'# bottom half. The top half gets executed before the main' nl|'\n' comment|'# processing of the request (so effectively gets to modify the' nl|'\n' comment|'# request before it gets to the main method).' nl|'\n' comment|'#' nl|'\n' comment|'# Returning a response triggers a shortcut to fail out. The' nl|'\n' comment|'# response will nearly always be a failure condition, as it ends' nl|'\n' comment|'# up skipping further processing one level up from here.' nl|'\n' comment|'#' nl|'\n' comment|'# This then passes on the list of extensions, in reverse order,' nl|'\n' comment|'# on. post_process will run through all those, again with same' nl|'\n' comment|'# basic logic.' nl|'\n' comment|'#' nl|'\n' comment|'# In tree this is only used in the legacy v2 stack, and only in' nl|'\n' comment|'# the DiskConfig and SchedulerHints from what I can see.' nl|'\n' comment|'#' nl|'\n' comment|'# pre_process_extensions can be removed when the legacyv2 code' nl|'\n' comment|'# goes away. post_process_extensions can be massively simplified' nl|'\n' comment|'# at that point.' nl|'\n' DECL|member|pre_process_extensions dedent|'' name|'def' name|'pre_process_extensions' op|'(' name|'self' op|',' name|'extensions' op|',' name|'request' op|',' name|'action_args' op|')' op|':' newline|'\n' comment|'# List of callables for post-processing extensions' nl|'\n' indent|' ' name|'post' op|'=' op|'[' op|']' newline|'\n' nl|'\n' name|'for' name|'ext' name|'in' name|'extensions' op|':' newline|'\n' indent|' ' name|'if' name|'inspect' op|'.' name|'isgeneratorfunction' op|'(' name|'ext' op|')' op|':' newline|'\n' indent|' ' name|'response' op|'=' name|'None' newline|'\n' nl|'\n' comment|"# If it's a generator function, the part before the" nl|'\n' comment|'# yield is the preprocessing stage' nl|'\n' name|'try' op|':' newline|'\n' indent|' ' name|'with' name|'ResourceExceptionHandler' op|'(' op|')' op|':' newline|'\n' indent|' ' name|'gen' op|'=' name|'ext' op|'(' name|'req' op|'=' name|'request' op|',' op|'**' name|'action_args' op|')' newline|'\n' name|'response' op|'=' name|'next' op|'(' name|'gen' op|')' newline|'\n' dedent|'' dedent|'' name|'except' name|'Fault' name|'as' name|'ex' op|':' newline|'\n' indent|' ' name|'response' op|'=' name|'ex' newline|'\n' nl|'\n' comment|'# We had a response...' nl|'\n' dedent|'' name|'if' name|'response' op|':' newline|'\n' indent|' ' name|'return' name|'response' op|',' op|'[' op|']' newline|'\n' nl|'\n' comment|'# No response, queue up generator for post-processing' nl|'\n' dedent|'' name|'post' op|'.' name|'append' op|'(' name|'gen' op|')' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' comment|'# Regular functions only perform post-processing' nl|'\n' indent|' ' name|'post' op|'.' name|'append' op|'(' name|'ext' op|')' newline|'\n' nl|'\n' comment|'# None is response, it means we keep going. We reverse the' nl|'\n' comment|'# extension list for post-processing.' nl|'\n' dedent|'' dedent|'' name|'return' name|'None' op|',' name|'reversed' op|'(' name|'post' op|')' newline|'\n' nl|'\n' DECL|member|post_process_extensions dedent|'' name|'def' name|'post_process_extensions' op|'(' name|'self' op|',' name|'extensions' op|',' name|'resp_obj' op|',' name|'request' op|',' nl|'\n' name|'action_args' op|')' op|':' newline|'\n' indent|' ' name|'for' name|'ext' name|'in' name|'extensions' op|':' newline|'\n' indent|' ' name|'response' op|'=' name|'None' newline|'\n' name|'if' name|'inspect' op|'.' name|'isgenerator' op|'(' name|'ext' op|')' op|':' newline|'\n' comment|"# If it's a generator, run the second half of" nl|'\n' comment|'# processing' nl|'\n' indent|' ' name|'try' op|':' newline|'\n' indent|' ' name|'with' name|'ResourceExceptionHandler' op|'(' op|')' op|':' newline|'\n' indent|' ' name|'response' op|'=' name|'ext' op|'.' name|'send' op|'(' name|'resp_obj' op|')' newline|'\n' dedent|'' dedent|'' name|'except' name|'StopIteration' op|':' newline|'\n' comment|'# Normal exit of generator' nl|'\n' indent|' ' name|'continue' newline|'\n' dedent|'' name|'except' name|'Fault' name|'as' name|'ex' op|':' newline|'\n' indent|' ' name|'response' op|'=' name|'ex' newline|'\n' dedent|'' dedent|'' name|'else' op|':' newline|'\n' comment|'# Regular functions get post-processing...' nl|'\n' indent|' ' name|'try' op|':' newline|'\n' indent|' ' name|'with' name|'ResourceExceptionHandler' op|'(' op|')' op|':' newline|'\n' indent|' ' name|'response' op|'=' name|'ext' op|'(' name|'req' op|'=' name|'request' op|',' name|'resp_obj' op|'=' name|'resp_obj' op|',' nl|'\n' op|'**' name|'action_args' op|')' newline|'\n' dedent|'' dedent|'' name|'except' name|'exception' op|'.' name|'VersionNotFoundForAPIMethod' op|':' newline|'\n' comment|'# If an attached extension (@wsgi.extends) for the' nl|'\n' comment|'# method has no version match its not an error. We' nl|'\n' comment|"# just don't run the extends code" nl|'\n' indent|' ' name|'continue' newline|'\n' dedent|'' name|'except' name|'Fault' name|'as' name|'ex' op|':' newline|'\n' indent|' ' name|'response' op|'=' name|'ex' newline|'\n' nl|'\n' comment|'# We had a response...' nl|'\n' dedent|'' dedent|'' name|'if' name|'response' op|':' newline|'\n' indent|' ' name|'return' name|'response' newline|'\n' nl|'\n' dedent|'' dedent|'' name|'return' name|'None' newline|'\n' nl|'\n' DECL|member|_should_have_body dedent|'' name|'def' name|'_should_have_body' op|'(' name|'self' op|',' name|'request' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'request' op|'.' name|'method' name|'in' name|'_METHODS_WITH_BODY' newline|'\n' nl|'\n' dedent|'' op|'@' name|'webob' op|'.' name|'dec' op|'.' name|'wsgify' op|'(' name|'RequestClass' op|'=' name|'Request' op|')' newline|'\n' DECL|member|__call__ name|'def' name|'__call__' op|'(' name|'self' op|',' name|'request' op|')' op|':' newline|'\n' indent|' ' string|'"""WSGI method that controls (de)serialization and method dispatch."""' newline|'\n' nl|'\n' name|'if' name|'self' op|'.' name|'support_api_request_version' op|':' newline|'\n' comment|'# Set the version of the API requested based on the header' nl|'\n' indent|' ' name|'try' op|':' newline|'\n' indent|' ' name|'request' op|'.' name|'set_api_version_request' op|'(' op|')' newline|'\n' dedent|'' name|'except' name|'exception' op|'.' name|'InvalidAPIVersionString' name|'as' name|'e' op|':' newline|'\n' indent|' ' name|'return' name|'Fault' op|'(' name|'webob' op|'.' name|'exc' op|'.' name|'HTTPBadRequest' op|'(' nl|'\n' name|'explanation' op|'=' name|'e' op|'.' name|'format_message' op|'(' op|')' op|')' op|')' newline|'\n' dedent|'' name|'except' name|'exception' op|'.' name|'InvalidGlobalAPIVersion' name|'as' name|'e' op|':' newline|'\n' indent|' ' name|'return' name|'Fault' op|'(' name|'webob' op|'.' name|'exc' op|'.' name|'HTTPNotAcceptable' op|'(' nl|'\n' name|'explanation' op|'=' name|'e' op|'.' name|'format_message' op|'(' op|')' op|')' op|')' newline|'\n' nl|'\n' comment|'# Identify the action, its arguments, and the requested' nl|'\n' comment|'# content type' nl|'\n' dedent|'' dedent|'' name|'action_args' op|'=' name|'self' op|'.' name|'get_action_args' op|'(' name|'request' op|'.' name|'environ' op|')' newline|'\n' name|'action' op|'=' name|'action_args' op|'.' name|'pop' op|'(' string|"'action'" op|',' name|'None' op|')' newline|'\n' nl|'\n' comment|'# NOTE(sdague): we filter out InvalidContentTypes early so we' nl|'\n' comment|'# know everything is good from here on out.' nl|'\n' name|'try' op|':' newline|'\n' indent|' ' name|'content_type' op|',' name|'body' op|'=' name|'self' op|'.' name|'get_body' op|'(' name|'request' op|')' newline|'\n' name|'accept' op|'=' name|'request' op|'.' name|'best_match_content_type' op|'(' op|')' newline|'\n' dedent|'' name|'except' name|'exception' op|'.' name|'InvalidContentType' op|':' newline|'\n' indent|' ' name|'msg' op|'=' name|'_' op|'(' string|'"Unsupported Content-Type"' op|')' newline|'\n' name|'return' name|'Fault' op|'(' name|'webob' op|'.' name|'exc' op|'.' name|'HTTPUnsupportedMediaType' op|'(' name|'explanation' op|'=' name|'msg' op|')' op|')' newline|'\n' nl|'\n' comment|'# NOTE(Vek): Splitting the function up this way allows for' nl|'\n' comment|'# auditing by external tools that wrap the existing' nl|'\n' comment|'# function. If we try to audit __call__(), we can' nl|'\n' comment|'# run into troubles due to the @webob.dec.wsgify()' nl|'\n' comment|'# decorator.' nl|'\n' dedent|'' name|'return' name|'self' op|'.' name|'_process_stack' op|'(' name|'request' op|',' name|'action' op|',' name|'action_args' op|',' nl|'\n' name|'content_type' op|',' name|'body' op|',' name|'accept' op|')' newline|'\n' nl|'\n' DECL|member|_process_stack dedent|'' name|'def' name|'_process_stack' op|'(' name|'self' op|',' name|'request' op|',' name|'action' op|',' name|'action_args' op|',' nl|'\n' name|'content_type' op|',' name|'body' op|',' name|'accept' op|')' op|':' newline|'\n' indent|' ' string|'"""Implement the processing stack."""' newline|'\n' nl|'\n' comment|'# Get the implementing method' nl|'\n' name|'try' op|':' newline|'\n' indent|' ' name|'meth' op|',' name|'extensions' op|'=' name|'self' op|'.' name|'get_method' op|'(' name|'request' op|',' name|'action' op|',' nl|'\n' name|'content_type' op|',' name|'body' op|')' newline|'\n' dedent|'' name|'except' op|'(' name|'AttributeError' op|',' name|'TypeError' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'Fault' op|'(' name|'webob' op|'.' name|'exc' op|'.' name|'HTTPNotFound' op|'(' op|')' op|')' newline|'\n' dedent|'' name|'except' name|'KeyError' name|'as' name|'ex' op|':' newline|'\n' indent|' ' name|'msg' op|'=' name|'_' op|'(' string|'"There is no such action: %s"' op|')' op|'%' name|'ex' op|'.' name|'args' op|'[' number|'0' op|']' newline|'\n' name|'return' name|'Fault' op|'(' name|'webob' op|'.' name|'exc' op|'.' name|'HTTPBadRequest' op|'(' name|'explanation' op|'=' name|'msg' op|')' op|')' newline|'\n' dedent|'' name|'except' name|'exception' op|'.' name|'MalformedRequestBody' op|':' newline|'\n' indent|' ' name|'msg' op|'=' name|'_' op|'(' string|'"Malformed request body"' op|')' newline|'\n' name|'return' name|'Fault' op|'(' name|'webob' op|'.' name|'exc' op|'.' name|'HTTPBadRequest' op|'(' name|'explanation' op|'=' name|'msg' op|')' op|')' newline|'\n' nl|'\n' dedent|'' name|'if' name|'body' op|':' newline|'\n' indent|' ' name|'msg' op|'=' name|'_' op|'(' string|'"Action: \'%(action)s\', calling method: %(meth)s, body: "' nl|'\n' string|'"%(body)s"' op|')' op|'%' op|'{' string|"'action'" op|':' name|'action' op|',' nl|'\n' string|"'body'" op|':' name|'six' op|'.' name|'text_type' op|'(' name|'body' op|',' string|"'utf-8'" op|')' op|',' nl|'\n' string|"'meth'" op|':' name|'str' op|'(' name|'meth' op|')' op|'}' newline|'\n' name|'LOG' op|'.' name|'debug' op|'(' name|'strutils' op|'.' name|'mask_password' op|'(' name|'msg' op|')' op|')' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'LOG' op|'.' name|'debug' op|'(' string|'"Calling method \'%(meth)s\'"' op|',' nl|'\n' op|'{' string|"'meth'" op|':' name|'str' op|'(' name|'meth' op|')' op|'}' op|')' newline|'\n' nl|'\n' comment|'# Now, deserialize the request body...' nl|'\n' dedent|'' name|'try' op|':' newline|'\n' indent|' ' name|'contents' op|'=' op|'{' op|'}' newline|'\n' name|'if' name|'self' op|'.' name|'_should_have_body' op|'(' name|'request' op|')' op|':' newline|'\n' comment|'# allow empty body with PUT and POST' nl|'\n' indent|' ' name|'if' name|'request' op|'.' name|'content_length' op|'==' number|'0' op|':' newline|'\n' indent|' ' name|'contents' op|'=' op|'{' string|"'body'" op|':' name|'None' op|'}' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'contents' op|'=' name|'self' op|'.' name|'deserialize' op|'(' name|'body' op|')' newline|'\n' dedent|'' dedent|'' dedent|'' name|'except' name|'exception' op|'.' name|'MalformedRequestBody' op|':' newline|'\n' indent|' ' name|'msg' op|'=' name|'_' op|'(' string|'"Malformed request body"' op|')' newline|'\n' name|'return' name|'Fault' op|'(' name|'webob' op|'.' name|'exc' op|'.' name|'HTTPBadRequest' op|'(' name|'explanation' op|'=' name|'msg' op|')' op|')' newline|'\n' nl|'\n' comment|'# Update the action args' nl|'\n' dedent|'' name|'action_args' op|'.' name|'update' op|'(' name|'contents' op|')' newline|'\n' nl|'\n' name|'project_id' op|'=' name|'action_args' op|'.' name|'pop' op|'(' string|'"project_id"' op|',' name|'None' op|')' newline|'\n' name|'context' op|'=' name|'request' op|'.' name|'environ' op|'.' name|'get' op|'(' string|"'nova.context'" op|')' newline|'\n' name|'if' op|'(' name|'context' name|'and' name|'project_id' name|'and' op|'(' name|'project_id' op|'!=' name|'context' op|'.' name|'project_id' op|')' op|')' op|':' newline|'\n' indent|' ' name|'msg' op|'=' name|'_' op|'(' string|'"Malformed request URL: URL\'s project_id \'%(project_id)s\'"' nl|'\n' string|'" doesn\'t match Context\'s project_id"' nl|'\n' string|'" \'%(context_project_id)s\'"' op|')' op|'%' op|'{' string|"'project_id'" op|':' name|'project_id' op|',' nl|'\n' string|"'context_project_id'" op|':' name|'context' op|'.' name|'project_id' op|'}' newline|'\n' name|'return' name|'Fault' op|'(' name|'webob' op|'.' name|'exc' op|'.' name|'HTTPBadRequest' op|'(' name|'explanation' op|'=' name|'msg' op|')' op|')' newline|'\n' nl|'\n' comment|'# Run pre-processing extensions' nl|'\n' dedent|'' name|'response' op|',' name|'post' op|'=' name|'self' op|'.' name|'pre_process_extensions' op|'(' name|'extensions' op|',' nl|'\n' name|'request' op|',' name|'action_args' op|')' newline|'\n' nl|'\n' name|'if' name|'not' name|'response' op|':' newline|'\n' indent|' ' name|'try' op|':' newline|'\n' indent|' ' name|'with' name|'ResourceExceptionHandler' op|'(' op|')' op|':' newline|'\n' indent|' ' name|'action_result' op|'=' name|'self' op|'.' name|'dispatch' op|'(' name|'meth' op|',' name|'request' op|',' name|'action_args' op|')' newline|'\n' dedent|'' dedent|'' name|'except' name|'Fault' name|'as' name|'ex' op|':' newline|'\n' indent|' ' name|'response' op|'=' name|'ex' newline|'\n' nl|'\n' dedent|'' dedent|'' name|'if' name|'not' name|'response' op|':' newline|'\n' comment|'# No exceptions; convert action_result into a' nl|'\n' comment|'# ResponseObject' nl|'\n' indent|' ' name|'resp_obj' op|'=' name|'None' newline|'\n' name|'if' name|'type' op|'(' name|'action_result' op|')' name|'is' name|'dict' name|'or' name|'action_result' name|'is' name|'None' op|':' newline|'\n' indent|' ' name|'resp_obj' op|'=' name|'ResponseObject' op|'(' name|'action_result' op|')' newline|'\n' dedent|'' name|'elif' name|'isinstance' op|'(' name|'action_result' op|',' name|'ResponseObject' op|')' op|':' newline|'\n' indent|' ' name|'resp_obj' op|'=' name|'action_result' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'response' op|'=' name|'action_result' newline|'\n' nl|'\n' comment|'# Run post-processing extensions' nl|'\n' dedent|'' name|'if' name|'resp_obj' op|':' newline|'\n' comment|'# Do a preserialize to set up the response object' nl|'\n' indent|' ' name|'if' name|'hasattr' op|'(' name|'meth' op|',' string|"'wsgi_code'" op|')' op|':' newline|'\n' indent|' ' name|'resp_obj' op|'.' name|'_default_code' op|'=' name|'meth' op|'.' name|'wsgi_code' newline|'\n' comment|'# Process post-processing extensions' nl|'\n' dedent|'' name|'response' op|'=' name|'self' op|'.' name|'post_process_extensions' op|'(' name|'post' op|',' name|'resp_obj' op|',' nl|'\n' name|'request' op|',' name|'action_args' op|')' newline|'\n' nl|'\n' dedent|'' name|'if' name|'resp_obj' name|'and' name|'not' name|'response' op|':' newline|'\n' indent|' ' name|'response' op|'=' name|'resp_obj' op|'.' name|'serialize' op|'(' name|'request' op|',' name|'accept' op|')' newline|'\n' nl|'\n' dedent|'' dedent|'' name|'if' name|'hasattr' op|'(' name|'response' op|',' string|"'headers'" op|')' op|':' newline|'\n' indent|' ' name|'for' name|'hdr' op|',' name|'val' name|'in' name|'list' op|'(' name|'response' op|'.' name|'headers' op|'.' name|'items' op|'(' op|')' op|')' op|':' newline|'\n' comment|'# Headers must be utf-8 strings' nl|'\n' indent|' ' name|'response' op|'.' name|'headers' op|'[' name|'hdr' op|']' op|'=' name|'utils' op|'.' name|'utf8' op|'(' name|'val' op|')' newline|'\n' nl|'\n' dedent|'' name|'if' name|'not' name|'request' op|'.' name|'api_version_request' op|'.' name|'is_null' op|'(' op|')' op|':' newline|'\n' indent|' ' name|'response' op|'.' name|'headers' op|'[' name|'API_VERSION_REQUEST_HEADER' op|']' op|'=' name|'request' op|'.' name|'api_version_request' op|'.' name|'get_string' op|'(' op|')' newline|'\n' name|'response' op|'.' name|'headers' op|'[' string|"'Vary'" op|']' op|'=' name|'API_VERSION_REQUEST_HEADER' newline|'\n' nl|'\n' dedent|'' dedent|'' name|'return' name|'response' newline|'\n' nl|'\n' DECL|member|get_method dedent|'' name|'def' name|'get_method' op|'(' name|'self' op|',' name|'request' op|',' name|'action' op|',' name|'content_type' op|',' name|'body' op|')' op|':' newline|'\n' indent|' ' name|'meth' op|',' name|'extensions' op|'=' name|'self' op|'.' name|'_get_method' op|'(' name|'request' op|',' nl|'\n' name|'action' op|',' nl|'\n' name|'content_type' op|',' nl|'\n' name|'body' op|')' newline|'\n' name|'if' name|'self' op|'.' name|'inherits' op|':' newline|'\n' indent|' ' name|'_meth' op|',' name|'parent_ext' op|'=' name|'self' op|'.' name|'inherits' op|'.' name|'get_method' op|'(' name|'request' op|',' nl|'\n' name|'action' op|',' nl|'\n' name|'content_type' op|',' nl|'\n' name|'body' op|')' newline|'\n' name|'extensions' op|'.' name|'extend' op|'(' name|'parent_ext' op|')' newline|'\n' dedent|'' name|'return' name|'meth' op|',' name|'extensions' newline|'\n' nl|'\n' DECL|member|_get_method dedent|'' name|'def' name|'_get_method' op|'(' name|'self' op|',' name|'request' op|',' name|'action' op|',' name|'content_type' op|',' name|'body' op|')' op|':' newline|'\n' indent|' ' string|'"""Look up the action-specific method and its extensions."""' newline|'\n' comment|'# Look up the method' nl|'\n' name|'try' op|':' newline|'\n' indent|' ' name|'if' name|'not' name|'self' op|'.' name|'controller' op|':' newline|'\n' indent|' ' name|'meth' op|'=' name|'getattr' op|'(' name|'self' op|',' name|'action' op|')' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'meth' op|'=' name|'getattr' op|'(' name|'self' op|'.' name|'controller' op|',' name|'action' op|')' newline|'\n' dedent|'' dedent|'' name|'except' name|'AttributeError' op|':' newline|'\n' indent|' ' name|'if' op|'(' name|'not' name|'self' op|'.' name|'wsgi_actions' name|'or' nl|'\n' name|'action' name|'not' name|'in' name|'_ROUTES_METHODS' op|'+' op|'[' string|"'action'" op|']' op|')' op|':' newline|'\n' comment|'# Propagate the error' nl|'\n' indent|' ' name|'raise' newline|'\n' dedent|'' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'return' name|'meth' op|',' name|'self' op|'.' name|'wsgi_extensions' op|'.' name|'get' op|'(' name|'action' op|',' op|'[' op|']' op|')' newline|'\n' nl|'\n' dedent|'' name|'if' name|'action' op|'==' string|"'action'" op|':' newline|'\n' indent|' ' name|'action_name' op|'=' name|'action_peek' op|'(' name|'body' op|')' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'action_name' op|'=' name|'action' newline|'\n' nl|'\n' comment|'# Look up the action method' nl|'\n' dedent|'' name|'return' op|'(' name|'self' op|'.' name|'wsgi_actions' op|'[' name|'action_name' op|']' op|',' nl|'\n' name|'self' op|'.' name|'wsgi_action_extensions' op|'.' name|'get' op|'(' name|'action_name' op|',' op|'[' op|']' op|')' op|')' newline|'\n' nl|'\n' DECL|member|dispatch dedent|'' name|'def' name|'dispatch' op|'(' name|'self' op|',' name|'method' op|',' name|'request' op|',' name|'action_args' op|')' op|':' newline|'\n' indent|' ' string|'"""Dispatch a call to the action-specific method."""' newline|'\n' nl|'\n' name|'try' op|':' newline|'\n' indent|' ' name|'return' name|'method' op|'(' name|'req' op|'=' name|'request' op|',' op|'**' name|'action_args' op|')' newline|'\n' dedent|'' name|'except' name|'exception' op|'.' name|'VersionNotFoundForAPIMethod' op|':' newline|'\n' comment|"# We deliberately don't return any message information" nl|'\n' comment|'# about the exception to the user so it looks as if' nl|'\n' comment|'# the method is simply not implemented.' nl|'\n' indent|' ' name|'return' name|'Fault' op|'(' name|'webob' op|'.' name|'exc' op|'.' name|'HTTPNotFound' op|'(' op|')' op|')' newline|'\n' nl|'\n' nl|'\n' DECL|class|ResourceV21 dedent|'' dedent|'' dedent|'' name|'class' name|'ResourceV21' op|'(' name|'Resource' op|')' op|':' newline|'\n' DECL|variable|support_api_request_version indent|' ' name|'support_api_request_version' op|'=' name|'True' newline|'\n' nl|'\n' nl|'\n' DECL|function|action dedent|'' name|'def' name|'action' op|'(' name|'name' op|')' op|':' newline|'\n' indent|' ' string|'"""Mark a function as an action.\n\n The given name will be taken as the action key in the body.\n\n This is also overloaded to allow extensions to provide\n non-extending definitions of create and delete operations.\n """' newline|'\n' nl|'\n' DECL|function|decorator name|'def' name|'decorator' op|'(' name|'func' op|')' op|':' newline|'\n' indent|' ' name|'func' op|'.' name|'wsgi_action' op|'=' name|'name' newline|'\n' name|'return' name|'func' newline|'\n' dedent|'' name|'return' name|'decorator' newline|'\n' nl|'\n' nl|'\n' DECL|function|extends dedent|'' name|'def' name|'extends' op|'(' op|'*' name|'args' op|',' op|'**' name|'kwargs' op|')' op|':' newline|'\n' indent|' ' string|'"""Indicate a function extends an operation.\n\n Can be used as either::\n\n @extends\n def index(...):\n pass\n\n or as::\n\n @extends(action=\'resize\')\n def _action_resize(...):\n pass\n """' newline|'\n' nl|'\n' DECL|function|decorator name|'def' name|'decorator' op|'(' name|'func' op|')' op|':' newline|'\n' comment|"# Store enough information to find what we're extending" nl|'\n' indent|' ' name|'func' op|'.' name|'wsgi_extends' op|'=' op|'(' name|'func' op|'.' name|'__name__' op|',' name|'kwargs' op|'.' name|'get' op|'(' string|"'action'" op|')' op|')' newline|'\n' name|'return' name|'func' newline|'\n' nl|'\n' comment|'# If we have positional arguments, call the decorator' nl|'\n' dedent|'' name|'if' name|'args' op|':' newline|'\n' indent|' ' name|'return' name|'decorator' op|'(' op|'*' name|'args' op|')' newline|'\n' nl|'\n' comment|'# OK, return the decorator instead' nl|'\n' dedent|'' name|'return' name|'decorator' newline|'\n' nl|'\n' nl|'\n' DECL|class|ControllerMetaclass dedent|'' name|'class' name|'ControllerMetaclass' op|'(' name|'type' op|')' op|':' newline|'\n' indent|' ' string|'"""Controller metaclass.\n\n This metaclass automates the task of assembling a dictionary\n mapping action keys to method names.\n """' newline|'\n' nl|'\n' DECL|member|__new__ name|'def' name|'__new__' op|'(' name|'mcs' op|',' name|'name' op|',' name|'bases' op|',' name|'cls_dict' op|')' op|':' newline|'\n' indent|' ' string|'"""Adds the wsgi_actions dictionary to the class."""' newline|'\n' nl|'\n' comment|'# Find all actions' nl|'\n' name|'actions' op|'=' op|'{' op|'}' newline|'\n' name|'extensions' op|'=' op|'[' op|']' newline|'\n' name|'versioned_methods' op|'=' name|'None' newline|'\n' comment|'# start with wsgi actions from base classes' nl|'\n' name|'for' name|'base' name|'in' name|'bases' op|':' newline|'\n' indent|' ' name|'actions' op|'.' name|'update' op|'(' name|'getattr' op|'(' name|'base' op|',' string|"'wsgi_actions'" op|',' op|'{' op|'}' op|')' op|')' newline|'\n' nl|'\n' name|'if' name|'base' op|'.' name|'__name__' op|'==' string|'"Controller"' op|':' newline|'\n' comment|'# NOTE(cyeoh): This resets the VER_METHOD_ATTR attribute' nl|'\n' comment|'# between API controller class creations. This allows us' nl|'\n' comment|"# to use a class decorator on the API methods that doesn't" nl|'\n' comment|'# require naming explicitly what method is being versioned as' nl|'\n' comment|'# it can be implicit based on the method decorated. It is a bit' nl|'\n' comment|'# ugly.' nl|'\n' indent|' ' name|'if' name|'VER_METHOD_ATTR' name|'in' name|'base' op|'.' name|'__dict__' op|':' newline|'\n' indent|' ' name|'versioned_methods' op|'=' name|'getattr' op|'(' name|'base' op|',' name|'VER_METHOD_ATTR' op|')' newline|'\n' name|'delattr' op|'(' name|'base' op|',' name|'VER_METHOD_ATTR' op|')' newline|'\n' nl|'\n' dedent|'' dedent|'' dedent|'' name|'for' name|'key' op|',' name|'value' name|'in' name|'cls_dict' op|'.' name|'items' op|'(' op|')' op|':' newline|'\n' indent|' ' name|'if' name|'not' name|'callable' op|'(' name|'value' op|')' op|':' newline|'\n' indent|' ' name|'continue' newline|'\n' dedent|'' name|'if' name|'getattr' op|'(' name|'value' op|',' string|"'wsgi_action'" op|',' name|'None' op|')' op|':' newline|'\n' indent|' ' name|'actions' op|'[' name|'value' op|'.' name|'wsgi_action' op|']' op|'=' name|'key' newline|'\n' dedent|'' name|'elif' name|'getattr' op|'(' name|'value' op|',' string|"'wsgi_extends'" op|',' name|'None' op|')' op|':' newline|'\n' indent|' ' name|'extensions' op|'.' name|'append' op|'(' name|'value' op|'.' name|'wsgi_extends' op|')' newline|'\n' nl|'\n' comment|'# Add the actions and extensions to the class dict' nl|'\n' dedent|'' dedent|'' name|'cls_dict' op|'[' string|"'wsgi_actions'" op|']' op|'=' name|'actions' newline|'\n' name|'cls_dict' op|'[' string|"'wsgi_extensions'" op|']' op|'=' name|'extensions' newline|'\n' name|'if' name|'versioned_methods' op|':' newline|'\n' indent|' ' name|'cls_dict' op|'[' name|'VER_METHOD_ATTR' op|']' op|'=' name|'versioned_methods' newline|'\n' nl|'\n' dedent|'' name|'return' name|'super' op|'(' name|'ControllerMetaclass' op|',' name|'mcs' op|')' op|'.' name|'__new__' op|'(' name|'mcs' op|',' name|'name' op|',' name|'bases' op|',' nl|'\n' name|'cls_dict' op|')' newline|'\n' nl|'\n' nl|'\n' dedent|'' dedent|'' op|'@' name|'six' op|'.' name|'add_metaclass' op|'(' name|'ControllerMetaclass' op|')' newline|'\n' DECL|class|Controller name|'class' name|'Controller' op|'(' name|'object' op|')' op|':' newline|'\n' indent|' ' string|'"""Default controller."""' newline|'\n' nl|'\n' DECL|variable|_view_builder_class name|'_view_builder_class' op|'=' name|'None' newline|'\n' nl|'\n' DECL|member|__init__ name|'def' name|'__init__' op|'(' name|'self' op|',' name|'view_builder' op|'=' name|'None' op|')' op|':' newline|'\n' indent|' ' string|'"""Initialize controller with a view builder instance."""' newline|'\n' name|'if' name|'view_builder' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'_view_builder' op|'=' name|'view_builder' newline|'\n' dedent|'' name|'elif' name|'self' op|'.' name|'_view_builder_class' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'_view_builder' op|'=' name|'self' op|'.' name|'_view_builder_class' op|'(' op|')' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'_view_builder' op|'=' name|'None' newline|'\n' nl|'\n' DECL|member|__getattribute__ dedent|'' dedent|'' name|'def' name|'__getattribute__' op|'(' name|'self' op|',' name|'key' op|')' op|':' newline|'\n' nl|'\n' DECL|function|version_select indent|' ' name|'def' name|'version_select' op|'(' op|'*' name|'args' op|',' op|'**' name|'kwargs' op|')' op|':' newline|'\n' indent|' ' string|'"""Look for the method which matches the name supplied and version\n constraints and calls it with the supplied arguments.\n\n @return: Returns the result of the method called\n @raises: VersionNotFoundForAPIMethod if there is no method which\n matches the name and version constraints\n """' newline|'\n' nl|'\n' comment|'# The first arg to all versioned methods is always the request' nl|'\n' comment|'# object. The version for the request is attached to the' nl|'\n' comment|'# request object' nl|'\n' name|'if' name|'len' op|'(' name|'args' op|')' op|'==' number|'0' op|':' newline|'\n' indent|' ' name|'ver' op|'=' name|'kwargs' op|'[' string|"'req'" op|']' op|'.' name|'api_version_request' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'ver' op|'=' name|'args' op|'[' number|'0' op|']' op|'.' name|'api_version_request' newline|'\n' nl|'\n' dedent|'' name|'func_list' op|'=' name|'self' op|'.' name|'versioned_methods' op|'[' name|'key' op|']' newline|'\n' name|'for' name|'func' name|'in' name|'func_list' op|':' newline|'\n' indent|' ' name|'if' name|'ver' op|'.' name|'matches' op|'(' name|'func' op|'.' name|'start_version' op|',' name|'func' op|'.' name|'end_version' op|')' op|':' newline|'\n' comment|'# Update the version_select wrapper function so' nl|'\n' comment|'# other decorator attributes like wsgi.response' nl|'\n' comment|'# are still respected.' nl|'\n' indent|' ' name|'functools' op|'.' name|'update_wrapper' op|'(' name|'version_select' op|',' name|'func' op|'.' name|'func' op|')' newline|'\n' name|'return' name|'func' op|'.' name|'func' op|'(' name|'self' op|',' op|'*' name|'args' op|',' op|'**' name|'kwargs' op|')' newline|'\n' nl|'\n' comment|'# No version match' nl|'\n' dedent|'' dedent|'' name|'raise' name|'exception' op|'.' name|'VersionNotFoundForAPIMethod' op|'(' name|'version' op|'=' name|'ver' op|')' newline|'\n' nl|'\n' dedent|'' name|'try' op|':' newline|'\n' indent|' ' name|'version_meth_dict' op|'=' name|'object' op|'.' name|'__getattribute__' op|'(' name|'self' op|',' name|'VER_METHOD_ATTR' op|')' newline|'\n' dedent|'' name|'except' name|'AttributeError' op|':' newline|'\n' comment|'# No versioning on this class' nl|'\n' indent|' ' name|'return' name|'object' op|'.' name|'__getattribute__' op|'(' name|'self' op|',' name|'key' op|')' newline|'\n' nl|'\n' dedent|'' name|'if' name|'version_meth_dict' name|'and' name|'key' name|'in' name|'object' op|'.' name|'__getattribute__' op|'(' name|'self' op|',' name|'VER_METHOD_ATTR' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'version_select' newline|'\n' nl|'\n' dedent|'' name|'return' name|'object' op|'.' name|'__getattribute__' op|'(' name|'self' op|',' name|'key' op|')' newline|'\n' nl|'\n' comment|'# NOTE(cyeoh): This decorator MUST appear first (the outermost' nl|'\n' comment|'# decorator) on an API method for it to work correctly' nl|'\n' dedent|'' op|'@' name|'classmethod' newline|'\n' DECL|member|api_version name|'def' name|'api_version' op|'(' name|'cls' op|',' name|'min_ver' op|',' name|'max_ver' op|'=' name|'None' op|')' op|':' newline|'\n' indent|' ' string|'"""Decorator for versioning api methods.\n\n Add the decorator to any method which takes a request object\n as the first parameter and belongs to a class which inherits from\n wsgi.Controller.\n\n @min_ver: string representing minimum version\n @max_ver: optional string representing maximum version\n """' newline|'\n' nl|'\n' DECL|function|decorator name|'def' name|'decorator' op|'(' name|'f' op|')' op|':' newline|'\n' indent|' ' name|'obj_min_ver' op|'=' name|'api_version' op|'.' name|'APIVersionRequest' op|'(' name|'min_ver' op|')' newline|'\n' name|'if' name|'max_ver' op|':' newline|'\n' indent|' ' name|'obj_max_ver' op|'=' name|'api_version' op|'.' name|'APIVersionRequest' op|'(' name|'max_ver' op|')' newline|'\n' dedent|'' name|'else' op|':' newline|'\n' indent|' ' name|'obj_max_ver' op|'=' name|'api_version' op|'.' name|'APIVersionRequest' op|'(' op|')' newline|'\n' nl|'\n' comment|'# Add to list of versioned methods registered' nl|'\n' dedent|'' name|'func_name' op|'=' name|'f' op|'.' name|'__name__' newline|'\n' name|'new_func' op|'=' name|'versioned_method' op|'.' name|'VersionedMethod' op|'(' nl|'\n' name|'func_name' op|',' name|'obj_min_ver' op|',' name|'obj_max_ver' op|',' name|'f' op|')' newline|'\n' nl|'\n' name|'func_dict' op|'=' name|'getattr' op|'(' name|'cls' op|',' name|'VER_METHOD_ATTR' op|',' op|'{' op|'}' op|')' newline|'\n' name|'if' name|'not' name|'func_dict' op|':' newline|'\n' indent|' ' name|'setattr' op|'(' name|'cls' op|',' name|'VER_METHOD_ATTR' op|',' name|'func_dict' op|')' newline|'\n' nl|'\n' dedent|'' name|'func_list' op|'=' name|'func_dict' op|'.' name|'get' op|'(' name|'func_name' op|',' op|'[' op|']' op|')' newline|'\n' name|'if' name|'not' name|'func_list' op|':' newline|'\n' indent|' ' name|'func_dict' op|'[' name|'func_name' op|']' op|'=' name|'func_list' newline|'\n' dedent|'' name|'func_list' op|'.' name|'append' op|'(' name|'new_func' op|')' newline|'\n' comment|'# Ensure the list is sorted by minimum version (reversed)' nl|'\n' comment|'# so later when we work through the list in order we find' nl|'\n' comment|'# the method which has the latest version which supports' nl|'\n' comment|'# the version requested.' nl|'\n' name|'is_intersect' op|'=' name|'Controller' op|'.' name|'check_for_versions_intersection' op|'(' nl|'\n' name|'func_list' op|')' newline|'\n' nl|'\n' name|'if' name|'is_intersect' op|':' newline|'\n' indent|' ' name|'raise' name|'exception' op|'.' name|'ApiVersionsIntersect' op|'(' nl|'\n' name|'name' op|'=' name|'new_func' op|'.' name|'name' op|',' nl|'\n' name|'min_ver' op|'=' name|'new_func' op|'.' name|'start_version' op|',' nl|'\n' name|'max_ver' op|'=' name|'new_func' op|'.' name|'end_version' op|',' nl|'\n' op|')' newline|'\n' nl|'\n' dedent|'' name|'func_list' op|'.' name|'sort' op|'(' name|'key' op|'=' name|'lambda' name|'f' op|':' name|'f' op|'.' name|'start_version' op|',' name|'reverse' op|'=' name|'True' op|')' newline|'\n' nl|'\n' name|'return' name|'f' newline|'\n' nl|'\n' dedent|'' name|'return' name|'decorator' newline|'\n' nl|'\n' dedent|'' op|'@' name|'staticmethod' newline|'\n' DECL|member|is_valid_body name|'def' name|'is_valid_body' op|'(' name|'body' op|',' name|'entity_name' op|')' op|':' newline|'\n' indent|' ' name|'if' name|'not' op|'(' name|'body' name|'and' name|'entity_name' name|'in' name|'body' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'False' newline|'\n' nl|'\n' DECL|function|is_dict dedent|'' name|'def' name|'is_dict' op|'(' name|'d' op|')' op|':' newline|'\n' indent|' ' name|'try' op|':' newline|'\n' indent|' ' name|'d' op|'.' name|'get' op|'(' name|'None' op|')' newline|'\n' name|'return' name|'True' newline|'\n' dedent|'' name|'except' name|'AttributeError' op|':' newline|'\n' indent|' ' name|'return' name|'False' newline|'\n' nl|'\n' dedent|'' dedent|'' name|'return' name|'is_dict' op|'(' name|'body' op|'[' name|'entity_name' op|']' op|')' newline|'\n' nl|'\n' dedent|'' op|'@' name|'staticmethod' newline|'\n' DECL|member|check_for_versions_intersection name|'def' name|'check_for_versions_intersection' op|'(' name|'func_list' op|')' op|':' newline|'\n' indent|' ' string|'"""Determines whether function list contains version intervals\n intersections or not. General algorithm:\n\n https://en.wikipedia.org/wiki/Intersection_algorithm\n\n :param func_list: list of VersionedMethod objects\n :return: boolean\n """' newline|'\n' name|'pairs' op|'=' op|'[' op|']' newline|'\n' name|'counter' op|'=' number|'0' newline|'\n' nl|'\n' name|'for' name|'f' name|'in' name|'func_list' op|':' newline|'\n' indent|' ' name|'pairs' op|'.' name|'append' op|'(' op|'(' name|'f' op|'.' name|'start_version' op|',' number|'1' op|',' name|'f' op|')' op|')' newline|'\n' name|'pairs' op|'.' name|'append' op|'(' op|'(' name|'f' op|'.' name|'end_version' op|',' op|'-' number|'1' op|',' name|'f' op|')' op|')' newline|'\n' nl|'\n' DECL|function|compare dedent|'' name|'def' name|'compare' op|'(' name|'x' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'x' op|'[' number|'0' op|']' newline|'\n' nl|'\n' dedent|'' name|'pairs' op|'.' name|'sort' op|'(' name|'key' op|'=' name|'compare' op|')' newline|'\n' nl|'\n' name|'for' name|'p' name|'in' name|'pairs' op|':' newline|'\n' indent|' ' name|'counter' op|'+=' name|'p' op|'[' number|'1' op|']' newline|'\n' nl|'\n' name|'if' name|'counter' op|'>' number|'1' op|':' newline|'\n' indent|' ' name|'return' name|'True' newline|'\n' nl|'\n' dedent|'' dedent|'' name|'return' name|'False' newline|'\n' nl|'\n' nl|'\n' DECL|class|Fault dedent|'' dedent|'' name|'class' name|'Fault' op|'(' name|'webob' op|'.' name|'exc' op|'.' name|'HTTPException' op|')' op|':' newline|'\n' indent|' ' string|'"""Wrap webob.exc.HTTPException to provide API friendly response."""' newline|'\n' nl|'\n' DECL|variable|_fault_names name|'_fault_names' op|'=' op|'{' nl|'\n' number|'400' op|':' string|'"badRequest"' op|',' nl|'\n' number|'401' op|':' string|'"unauthorized"' op|',' nl|'\n' number|'403' op|':' string|'"forbidden"' op|',' nl|'\n' number|'404' op|':' string|'"itemNotFound"' op|',' nl|'\n' number|'405' op|':' string|'"badMethod"' op|',' nl|'\n' number|'409' op|':' string|'"conflictingRequest"' op|',' nl|'\n' number|'413' op|':' string|'"overLimit"' op|',' nl|'\n' number|'415' op|':' string|'"badMediaType"' op|',' nl|'\n' number|'429' op|':' string|'"overLimit"' op|',' nl|'\n' number|'501' op|':' string|'"notImplemented"' op|',' nl|'\n' number|'503' op|':' string|'"serviceUnavailable"' op|'}' newline|'\n' nl|'\n' DECL|member|__init__ name|'def' name|'__init__' op|'(' name|'self' op|',' name|'exception' op|')' op|':' newline|'\n' indent|' ' string|'"""Create a Fault for the given webob.exc.exception."""' newline|'\n' name|'self' op|'.' name|'wrapped_exc' op|'=' name|'exception' newline|'\n' name|'for' name|'key' op|',' name|'value' name|'in' name|'list' op|'(' name|'self' op|'.' name|'wrapped_exc' op|'.' name|'headers' op|'.' name|'items' op|'(' op|')' op|')' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'wrapped_exc' op|'.' name|'headers' op|'[' name|'key' op|']' op|'=' name|'str' op|'(' name|'value' op|')' newline|'\n' dedent|'' name|'self' op|'.' name|'status_int' op|'=' name|'exception' op|'.' name|'status_int' newline|'\n' nl|'\n' dedent|'' op|'@' name|'webob' op|'.' name|'dec' op|'.' name|'wsgify' op|'(' name|'RequestClass' op|'=' name|'Request' op|')' newline|'\n' DECL|member|__call__ name|'def' name|'__call__' op|'(' name|'self' op|',' name|'req' op|')' op|':' newline|'\n' indent|' ' string|'"""Generate a WSGI response based on the exception passed to ctor."""' newline|'\n' nl|'\n' name|'user_locale' op|'=' name|'req' op|'.' name|'best_match_language' op|'(' op|')' newline|'\n' comment|'# Replace the body with fault details.' nl|'\n' name|'code' op|'=' name|'self' op|'.' name|'wrapped_exc' op|'.' name|'status_int' newline|'\n' name|'fault_name' op|'=' name|'self' op|'.' name|'_fault_names' op|'.' name|'get' op|'(' name|'code' op|',' string|'"computeFault"' op|')' newline|'\n' name|'explanation' op|'=' name|'self' op|'.' name|'wrapped_exc' op|'.' name|'explanation' newline|'\n' name|'LOG' op|'.' name|'debug' op|'(' string|'"Returning %(code)s to user: %(explanation)s"' op|',' nl|'\n' op|'{' string|"'code'" op|':' name|'code' op|',' string|"'explanation'" op|':' name|'explanation' op|'}' op|')' newline|'\n' nl|'\n' name|'explanation' op|'=' name|'i18n' op|'.' name|'translate' op|'(' name|'explanation' op|',' name|'user_locale' op|')' newline|'\n' name|'fault_data' op|'=' op|'{' nl|'\n' name|'fault_name' op|':' op|'{' nl|'\n' string|"'code'" op|':' name|'code' op|',' nl|'\n' string|"'message'" op|':' name|'explanation' op|'}' op|'}' newline|'\n' name|'if' name|'code' op|'==' number|'413' name|'or' name|'code' op|'==' number|'429' op|':' newline|'\n' indent|' ' name|'retry' op|'=' name|'self' op|'.' name|'wrapped_exc' op|'.' name|'headers' op|'.' name|'get' op|'(' string|"'Retry-After'" op|',' name|'None' op|')' newline|'\n' name|'if' name|'retry' op|':' newline|'\n' indent|' ' name|'fault_data' op|'[' name|'fault_name' op|']' op|'[' string|"'retryAfter'" op|']' op|'=' name|'retry' newline|'\n' nl|'\n' dedent|'' dedent|'' name|'if' name|'not' name|'req' op|'.' name|'api_version_request' op|'.' name|'is_null' op|'(' op|')' op|':' newline|'\n' indent|' ' name|'self' op|'.' name|'wrapped_exc' op|'.' name|'headers' op|'[' name|'API_VERSION_REQUEST_HEADER' op|']' op|'=' name|'req' op|'.' name|'api_version_request' op|'.' name|'get_string' op|'(' op|')' newline|'\n' name|'self' op|'.' name|'wrapped_exc' op|'.' name|'headers' op|'[' string|"'Vary'" op|']' op|'=' name|'API_VERSION_REQUEST_HEADER' newline|'\n' nl|'\n' dedent|'' name|'self' op|'.' name|'wrapped_exc' op|'.' name|'content_type' op|'=' string|"'application/json'" newline|'\n' name|'self' op|'.' name|'wrapped_exc' op|'.' name|'charset' op|'=' string|"'UTF-8'" newline|'\n' name|'self' op|'.' name|'wrapped_exc' op|'.' name|'text' op|'=' name|'JSONDictSerializer' op|'(' op|')' op|'.' name|'serialize' op|'(' name|'fault_data' op|')' newline|'\n' nl|'\n' name|'return' name|'self' op|'.' name|'wrapped_exc' newline|'\n' nl|'\n' DECL|member|__str__ dedent|'' name|'def' name|'__str__' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'self' op|'.' name|'wrapped_exc' op|'.' name|'__str__' op|'(' op|')' newline|'\n' nl|'\n' nl|'\n' DECL|class|RateLimitFault dedent|'' dedent|'' name|'class' name|'RateLimitFault' op|'(' name|'webob' op|'.' name|'exc' op|'.' name|'HTTPException' op|')' op|':' newline|'\n' indent|' ' string|'"""Rate-limited request response."""' newline|'\n' nl|'\n' DECL|member|__init__ name|'def' name|'__init__' op|'(' name|'self' op|',' name|'message' op|',' name|'details' op|',' name|'retry_time' op|')' op|':' newline|'\n' indent|' ' string|'"""Initialize new `RateLimitFault` with relevant information."""' newline|'\n' name|'hdrs' op|'=' name|'RateLimitFault' op|'.' name|'_retry_after' op|'(' name|'retry_time' op|')' newline|'\n' name|'self' op|'.' name|'wrapped_exc' op|'=' name|'webob' op|'.' name|'exc' op|'.' name|'HTTPTooManyRequests' op|'(' name|'headers' op|'=' name|'hdrs' op|')' newline|'\n' name|'self' op|'.' name|'content' op|'=' op|'{' nl|'\n' string|'"overLimit"' op|':' op|'{' nl|'\n' string|'"code"' op|':' name|'self' op|'.' name|'wrapped_exc' op|'.' name|'status_int' op|',' nl|'\n' string|'"message"' op|':' name|'message' op|',' nl|'\n' string|'"details"' op|':' name|'details' op|',' nl|'\n' string|'"retryAfter"' op|':' name|'hdrs' op|'[' string|"'Retry-After'" op|']' op|',' nl|'\n' op|'}' op|',' nl|'\n' op|'}' newline|'\n' nl|'\n' dedent|'' op|'@' name|'staticmethod' newline|'\n' DECL|member|_retry_after name|'def' name|'_retry_after' op|'(' name|'retry_time' op|')' op|':' newline|'\n' indent|' ' name|'delay' op|'=' name|'int' op|'(' name|'math' op|'.' name|'ceil' op|'(' name|'retry_time' op|'-' name|'time' op|'.' name|'time' op|'(' op|')' op|')' op|')' newline|'\n' name|'retry_after' op|'=' name|'delay' name|'if' name|'delay' op|'>' number|'0' name|'else' number|'0' newline|'\n' name|'headers' op|'=' op|'{' string|"'Retry-After'" op|':' string|"'%d'" op|'%' name|'retry_after' op|'}' newline|'\n' name|'return' name|'headers' newline|'\n' nl|'\n' dedent|'' op|'@' name|'webob' op|'.' name|'dec' op|'.' name|'wsgify' op|'(' name|'RequestClass' op|'=' name|'Request' op|')' newline|'\n' DECL|member|__call__ name|'def' name|'__call__' op|'(' name|'self' op|',' name|'request' op|')' op|':' newline|'\n' indent|' ' string|'"""Return the wrapped exception with a serialized body conforming\n to our error format.\n """' newline|'\n' name|'user_locale' op|'=' name|'request' op|'.' name|'best_match_language' op|'(' op|')' newline|'\n' nl|'\n' name|'self' op|'.' name|'content' op|'[' string|"'overLimit'" op|']' op|'[' string|"'message'" op|']' op|'=' name|'i18n' op|'.' name|'translate' op|'(' name|'self' op|'.' name|'content' op|'[' string|"'overLimit'" op|']' op|'[' string|"'message'" op|']' op|',' name|'user_locale' op|')' newline|'\n' name|'self' op|'.' name|'content' op|'[' string|"'overLimit'" op|']' op|'[' string|"'details'" op|']' op|'=' name|'i18n' op|'.' name|'translate' op|'(' name|'self' op|'.' name|'content' op|'[' string|"'overLimit'" op|']' op|'[' string|"'details'" op|']' op|',' name|'user_locale' op|')' newline|'\n' nl|'\n' name|'content' op|'=' name|'JSONDictSerializer' op|'(' op|')' op|'.' name|'serialize' op|'(' name|'self' op|'.' name|'content' op|')' newline|'\n' name|'self' op|'.' name|'wrapped_exc' op|'.' name|'charset' op|'=' string|"'UTF-8'" newline|'\n' name|'self' op|'.' name|'wrapped_exc' op|'.' name|'content_type' op|'=' string|'"application/json"' newline|'\n' name|'self' op|'.' name|'wrapped_exc' op|'.' name|'text' op|'=' name|'content' newline|'\n' nl|'\n' name|'return' name|'self' op|'.' name|'wrapped_exc' newline|'\n' dedent|'' dedent|'' endmarker|'' end_unit
[ 27471, 62, 20850, 198, 23893, 91, 6, 2, 15069, 2211, 19764, 11421, 2637, 198, 21283, 91, 6, 59, 77, 6, 198, 23893, 91, 6, 2, 15069, 2813, 4946, 25896, 5693, 6, 198, 21283, 91, 6, 59, 77, 6, 198, 23893, 91, 6, 2, 1439, 6923, 33...
1.9223
44,852
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.2' # jupytext_version: 1.2.3 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% [markdown] # # # Examples illustrating the use of the Qmod class. # # This notebook shows how to construct and use objects of the Qmod class, which is defined in Q_investment.py. # %% {"code_folding": []} # Preamble import numpy as np import matplotlib.pyplot as plt # Since the Qmod class is in other folder we need to # change the path. import sys sys.path.append('../') from Qmod.Q_investment import Qmod # %% [markdown] # # Examples # %% [markdown] # ## 1. Model solution and policy rule. # # We first create and solve a model. To solve the model is to find its policy rule: a function specifying what is the optimal value for capital at $t+1$ given capital at $t$ (implicitly defining optimal investment). # %% # Create model object Qexample = Qmod() # Solve to find the policy rule (k[t+1] in terms of k[t]) Qexample.solve() # Plot policy rule k = np.linspace(1,3*Qexample.kss,20) plt.figure() plt.plot(k,[Qexample.k1Func(x) for x in k], label = "Optimal capital") plt.plot(k,k, linestyle = '--', color = 'k', label = "45掳 line") plt.plot(Qexample.kss,Qexample.kss,'*r', label = "Steady state") plt.title('Policy Rule') plt.xlabel('$k(t)$') plt.ylabel('$k(t+1)$') plt.legend() plt.show() # %% [markdown] # ## 2. Simulation of capital dynamics. # # The class can also compute the dynamic adjustment of capital from a given starting level. # # We can use this to see how adjustment costs affect the speed of adjustment. # %% # Create and solve two instances, one with high and one with low adjustment costs omega Qlow = Qmod(omega = 0.1) Qhigh = Qmod(omega = 0.9) Qlow.solve() Qhigh.solve() # Simulate adjustment from an initial capital level k0 = 2*Qhigh.kss t = 50 k_low = Qlow.simulate(k0,t) k_high = Qhigh.simulate(k0,t) # Plot plt.figure() plt.plot(k_low, label = 'Low $\\omega$') plt.plot(k_high, label = 'High $\\omega$') plt.axhline(y = Qhigh.kss,linestyle = '--',color = 'k', label = 'Steady state ${k}$') plt.title('Capital') plt.xlabel('$t$') plt.ylabel('$k(t)$') plt.legend() plt.show() # %% [markdown] # ## 3. Phase diagram. # # The class can plot a model's phase diagram. The model has to be solved if the stable arm is to be displayed. # %% # Create and solve model object Qexample = Qmod() Qexample.solve() # Generate its phase diagram Qexample.phase_diagram(stableArm = True) # %% [markdown] # Why is the $\dot{\lambda}=0$ locus truncated? # # With constant prices, there may be instances where $\lambda_t$ can not be equal to $\lambda_{t+1}$. Notice first that $\lambda_t$ is a function of $\lambda_{t+1}$ (current marginal value of capital is a function of its expected marginal value tomorrow). # # If, for instance, $k_t$ is low, the marginal productivity of capital will be high, and this can push $\lambda_t$ above $\lambda_{t+1}$, as is the case in the following diagram, which plots $\lambda_t$ computed from the envelope condition at a fixed $k$ and varying $\lambda_{t+1}$. # %% Qexample.plotEnvelopeCond(k=2) # %% [markdown] # Note that the envelope condition never crosses the $\lambda_t = \lambda_{t+1}$ line. Thus, there is no $\dot{\lambda}=0$ locus at $k=2$. # # However, zooming in we can see that the locus is well defined around the steady state level of capital. # %% Qexample.phase_diagram( k_min = 0.99,k_max = 1.01 , stableArm = True)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 11420, 198, 2, 474, 929, 88, 353, 25, 198, 2, 220, 220, 474, 929, 88, 5239, 25, 198, 2, 220, 220, 220, 220, 17519, 25, 20966, 2047, 65, 11, 9078, 25, 25067, 1...
2.772936
1,308
""" hellostats sample API author: Alex G.S. Utils for use by the hello app such as html formatting getting loadavg of the server and ipaddress """ import os, socket, re import requests import json # server tools and stats def get_ip(): """get the ip address for the server""" aws_url="http://169.254.169.254/latest/meta-data/public-ipv4" pub_ip = requests.get(aws_url).text return pub_ip def get_stats(): """return ip and loadavg as a tuple""" loada, loadb, loadc = os.getloadavg() stats = [get_ip(), loada, loadb, loadc] return stats def json_stats(): """return stats as JSON list with ip as key""" stats = get_stats() return json.dumps(stats) def node_list(): """get the list of nodes from the host list excluding localhost""" host_file = "/var/www/hello/hosts.list" if os.path.exists(host_file): try: with open(host_file, 'r') as hostfile: host_list = [h.strip() for h in hostfile.readlines() if h.strip() != get_ip()] except: return "ERROR: could not access host list!" else: return host_list else: return "ERROR: host list is missing!" def node_stats(): """get the loadavg stats from the entire cluster""" node_stats = list() node_stats.append(get_stats()) if len(node_list()) > 0: for node in node_list(): url = "http://{}/loadavg".format(node) try: resp = requests.get(url) except: return "ERROR: problem talking to node!" else: raw = re.sub(r'<h1>|</h1>|\s', '', resp.text) stats = re.split(r':|,', raw) node_stats.append(stats) else: return "ERROR: no nodes in the host list!" return node_stats def node_avg(): """get the avg of the node stats""" node_raw = ["average", 0, 0, 0] for node in node_stats(): node_raw[1] += float(node[1]) node_raw[2] += float(node[2]) node_raw[3] += float(node[3]) num = len(node_stats()) node_avg = ["average", "{:.2f}".format(node_raw[1]/num), "{:.2f}".format(node_raw[2]/num), "{:.2f}".format(node_raw[3]/num)] return node_avg # html formatters def wrap_h(msg): """wraps text in a header tag for good desploy""" return "<h1>{}</h1>".format(msg) def wrap_p(msg): """wraps text in a paragraph tag for good desploy""" return "<p>{}</p>".format(msg)
[ 37811, 198, 12758, 455, 1381, 6291, 7824, 198, 9800, 25, 4422, 402, 13, 50, 13, 198, 198, 18274, 4487, 329, 779, 416, 262, 23748, 598, 884, 355, 27711, 33313, 198, 37210, 3440, 615, 70, 286, 262, 4382, 290, 20966, 21975, 198, 198, 3...
2.222812
1,131
""" Unit Tests for preprocess module. """ import sys import math import unittest import argparse import numpy import pysam from mixemt import phylotree from mixemt import preprocess # TODO: Stuff to test: # def process_reads(samfile, var_pos, min_mq, min_bq): # def build_em_input(samfile, refseq, phylo, args): if __name__ == '__main__': unittest.main()
[ 37811, 198, 26453, 30307, 329, 662, 14681, 8265, 13, 198, 37811, 198, 198, 11748, 25064, 198, 11748, 10688, 198, 11748, 555, 715, 395, 198, 11748, 1822, 29572, 198, 11748, 299, 32152, 198, 11748, 279, 893, 321, 198, 198, 6738, 5022, 368...
2.753731
134
# # Copyright 2021 Red Hat Inc. # SPDX-License-Identifier: Apache-2.0 # """Tests for Settings Access Permissions.""" from unittest.mock import Mock from django.test import TestCase from api.common.permissions.settings_access import SettingsAccessPermission from api.iam.models import User class SettingsAccessPermissionTest(TestCase): """Test the settings access permission.""" def test_has_perm_admin(self): """Test that an admin user can execute.""" user = Mock(spec=User, admin=True) req = Mock(user=user) accessPerm = SettingsAccessPermission() result = accessPerm.has_permission(request=req, view=None) self.assertTrue(result) def test_has_perm_with_access_on_get(self): """Test that a user read.""" user = Mock(spec=User, admin=False) req = Mock(user=user, method="GET") accessPerm = SettingsAccessPermission() result = accessPerm.has_permission(request=req, view=None) self.assertTrue(result) def test_has_perm_with_no_access_on_post(self): """Test that a user cannot execute POST.""" user = Mock(spec=User, admin=False) req = Mock(user=user, method="POST", META={"PATH_INFO": "http://localhost/api/v1/settings/"}) accessPerm = SettingsAccessPermission() result = accessPerm.has_permission(request=req, view=None) self.assertFalse(result)
[ 2, 198, 2, 15069, 33448, 2297, 10983, 3457, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 2, 198, 37811, 51, 3558, 329, 16163, 8798, 2448, 8481, 526, 15931, 198, 6738, 555, 715, 395, 13, 76, ...
2.641121
535
import uuid import asyncio import httpx from hannah.http.mappings import HTTPTrafficMapper REQUEST_RATE_LIMIT = 50
[ 11748, 334, 27112, 198, 11748, 30351, 952, 198, 198, 11748, 2638, 87, 198, 198, 6738, 289, 25761, 13, 4023, 13, 76, 39242, 1330, 14626, 15721, 2108, 44, 11463, 628, 198, 2200, 35780, 62, 49, 6158, 62, 43, 3955, 2043, 796, 2026, 628, ...
2.837209
43
#!/usr/bin/env python3 import sdfield_generator import sys if __name__ == "__main__": if(len(sys.argv) == 5): sdf = sdfield_generator.SDF_Generator(str(sys.argv[1]), resolution = int(sys.argv[2]), padding = float(sys.argv[3])) distance_array, sdf_origin, sdf_spacing, sdf_resolution = sdf.calculate_sdf_array() sdf.create_sdf_file(sys.argv[4]) #new_sdf = sdfield_generator.SDF_Generator("obj_mesh/Measuring_Block.obj", file_name = "test_file.pickle") sdf.visualize_sdf() else: print("INCORRECT ARGUMENTS") print("Please format command line arguments as 'Path to obj mesh' Resolution Padding 'Pickle file name with .pickle extension'") print("EX: ./demo_sdf.py 'obj_mesh/Measuring_Block.obj' 32 .02 'test.pickle' ") print("I dont recommend going much higher on the resolution or much lower on the padding\n\n\n")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 45647, 3245, 62, 8612, 1352, 198, 11748, 25064, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 220, 628, 220, 220, 220, 611, 7, 11925, 7, 17597, 1...
2.408
375
# -*- coding: utf-8 -*- # Generated by Django 1.11.25 on 2019-11-13 02:31 from __future__ import unicode_literals from django.db import migrations, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 1495, 319, 13130, 12, 1157, 12, 1485, 7816, 25, 3132, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198...
2.754386
57
import argparse import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np from astropy.io import fits from astropy.modeling.models import Linear1D from astropy.modeling.fitting import LinearLSQFitter from miri_ramp_utils import get_ramp, get_good_ramp, fit_diffs, calc_lincor if __name__ == "__main__": # commandline parser parser = argparse.ArgumentParser() parser.add_argument( "--pixel", help="x y pixel values", metavar=("x", "y"), type=int, nargs=2, default=[512, 512], ) parser.add_argument( "--nrej", help="number of groups to ignore in linear fit", type=int, default=24 ) parser.add_argument( "--primeonly", help="plot the primary exposure", action="store_true" ) parser.add_argument("--png", help="save figure as an png file", action="store_true") parser.add_argument("--pdf", help="save figure as a pdf file", action="store_true") args = parser.parse_args() all_filenames = [ "Data/MIRI_5692_18_S_20191017-193412_SCE1.fits", "Data/MIRI_5692_17_S_20191017-184107_SCE1.fits", "Data/MIRI_5692_19_S_20191017-202738_SCE1.fits", "Data/MIRI_5692_20_S_20191017-212044_SCE1.fits", "Data/MIRI_5692_21_S_20191017-221350_SCE1.fits", "Data/MIRI_5694_21_S_20191018-170349_SCE1.fits", "Data/MIRI_5694_22_S_20191018-172524_SCE1.fits", "Data/MIRI_5694_23_S_20191018-174658_SCE1.fits", "Data/MIRI_5694_24_S_20191018-180833_SCE1.fits", "Data/MIRI_5694_25_S_20191018-183008_SCE1.fits", ] all_filenames = ['Data/MIRI_5700_18_S_20191022-225042_SCE1.fits'] all_filenames = ['Data/MIRI_5701_238_S_20191023-215644_SCE1.fits'] all_filenames = [ # "Data/MIRI_5708_80_S_20191027-053806_SCE1.fits", "Data/MIRI_5708_137_S_20191027-201705_SCE1.fits", "Data/MIRI_5708_153_S_20191027-223137_SCE1.fits", "Data/MIRI_5709_34_S_20191029-011921_SCE1.fits", "Data/MIRI_5709_32_S_20191029-010437_SCE1.fits", "Data/MIRI_5709_30_S_20191029-004923_SCE1.fits", "Data/MIRI_5709_28_S_20191029-003349_SCE1.fits", "Data/MIRI_5709_24_S_20191029-000141_SCE1.fits", "Data/MIRI_5709_18_S_20191028-231009_SCE1.fits"] rampoffvals = [0.0, 0.0, -4900., -4900., -4900., -4900., -4900., -4900.] rampoffvals = np.zeros((len(all_filenames))) # all_filenames = ["Data/MIRI_5709_18_S_20191028-231009_SCE1.fits"] # all_filenames = all_filenames[::-1] hdu = fits.open(all_filenames[0], memmap=False) fig, sax = plt.subplots(ncols=4, nrows=2, figsize=(18, 9)) # fig, sax = plt.subplots(ncols=4, nrows=2, figsize=(8, 6)) ax = [ sax[0, 0], sax[1, 0], sax[1, 1], sax[0, 1], sax[0, 2], sax[1, 2], sax[1, 3], sax[0, 3], ] # plotting setup for easier to read plots # fontsize = 18 fontsize = 8 font = {"size": fontsize} mpl.rc("font", **font) mpl.rc("lines", linewidth=1) mpl.rc("axes", linewidth=2) mpl.rc("xtick.major", width=2) mpl.rc("xtick.minor", width=2) mpl.rc("ytick.major", width=2) mpl.rc("ytick.minor", width=2) pix_x, pix_y = args.pixel ngrps = hdu[0].header["NGROUPS"] nints = hdu[0].header["NINT"] nrej = args.nrej # for fitting x = [] y = [] # for plotting pcol = ["b", "g", "r", "c", "y", "b", "g", "r", "c", "y"] # plot all integrations folded mm_delta = 0.0 max_ramp_k = -1 rampoffval = rampoffvals[0] # print("# ints = ", nints) for k in range(nints): gnum, ydata = get_ramp(hdu[0], pix_x, pix_y, k, rampoffval=rampoffvals[0]) ggnum, gdata, aveDN, diffDN = get_good_ramp(gnum, ydata) ax[0].plot(gnum, ydata, label=f"Int #{k+1}", color=pcol[k]) # plot the 2pt diffs ax[1].plot(ggnum[:-1], diffDN, label=f"Int #{k+1}", color=pcol[k]) # plot the 2pt diffs versus average DN ax[2].plot(aveDN, diffDN, label=f"Int #{k+1}", color=pcol[k]) if k == 0: ax[1].set_ylim(0.9 * min(diffDN), 1.1 * max(diffDN)) ax[2].set_ylim(0.9 * min(diffDN), 1.1 * max(diffDN)) # accumulate data for later plotting x.append(aveDN) y.append(diffDN) # find the ramp that spans the largest range of DN # and save some info -> needed for creating the correction # if (gdata.max() - gdata.min()) > mm_delta: # mm_delta = gdata.max() - gdata.min() if k == 3: max_ramp_k = k max_ramp_gdata = gdata max_ramp_aveDN = aveDN # fit the aveDN versus diffDN combined data from all integrations x = np.concatenate(x) y = np.concatenate(y) mod = fit_diffs(x, y) polymod = mod[2] # plot the model mod_x = np.linspace(0.0, 65000.0, num=100) # for k in range(nints): # gnum, ydata = get_ramp(hdu[0], pix_x, pix_y, k) # ggnum, gdata, aveDN, diffDN = get_good_ramp(gnum, ydata) # (DN_exp, cor, cor_mod) = calc_lincor(mod[1], gdata, args.startDN) # ax[3].plot(DN_exp, cor, "--", label=f"Int #{k+1}") startDNvals = np.arange(0.0, 20000.0, 200.0) chival = np.zeros((nints, len(startDNvals))) ints = range(nints) for i, startDN in enumerate(startDNvals): (DN_exp, cor, cor_mod) = calc_lincor(polymod, max_ramp_aveDN, startDN) for k in ints: gnum, ydata = get_ramp(hdu[0], pix_x, pix_y, k, rampoffval=rampoffvals[0]) ggnum, gdata, aveDN, diffDN = get_good_ramp(gnum, ydata) # correct the ramps ycor = cor_mod(gdata) gdata_cor = gdata * ycor # calculate the chisqr for each integration set of differences # from the expected flat line diffDN = np.diff(gdata_cor) aveDN = 0.5 * (gdata[:-1] + gdata[1:]) cindxs, = np.where(aveDN > 10000.0) chival[k, i] = np.sum((diffDN[aveDN > 15000.0] - polymod.c0) ** 2) minindx = np.zeros((nints), dtype=int) for k in ints[1:]: # ax[6].plot(startDNvals, chival[k, :], label=f"Int #{k+1}", color=pcol[k]) minindx[k] = np.argmin(chival[k, :]) startDN = startDNvals[minindx[max_ramp_k]] # get the correction (DN_exp, cor, cor_mod) = calc_lincor(polymod, max_ramp_aveDN, startDN) ax[3].plot(DN_exp, cor, "ko", label=f"Int #{max_ramp_k+1} StartDN={startDN:.1f}") ax[3].plot(mod_x, cor_mod(mod_x), "k--", label="Cor Poly1D") # apply the correction line_init = Linear1D() fit_line = LinearLSQFitter() intslopes = np.zeros((nints)) linfit_metric = np.zeros((nints)) for k in range(nints): gnum, ydata = get_ramp(hdu[0], pix_x, pix_y, k, rampoffval=rampoffvals[0]) ggnum, gdata, aveDN, diffDN = get_good_ramp(gnum, ydata) # correct the ramps and plot ycor = cor_mod(gdata) gdata_cor = gdata * ycor ax[0].plot(ggnum, gdata_cor, "--", label=f"Cor Int #{k+1}", color=pcol[k]) # plot the corrected ramp divided by a linear fit line_mod = fit_line(line_init, ggnum[nrej:], gdata_cor[nrej:]) intslopes[k] = line_mod.slope.value linfit_ratio = gdata_cor / line_mod(ggnum) ax[4].plot(ggnum, linfit_ratio, "--", label=f"Int #{k+1}", color=pcol[k]) ax[4].plot(ggnum, np.full((len(ggnum)), 1.0), "k--") # compute metric on deviations from the linear fit linfit_metric[k] = np.sum(np.power(linfit_ratio[nrej:] - 1.0, 2.0)) / len( linfit_ratio[nrej:] ) # plot the 2pt diffs versus average DN diffDN = np.diff(gdata_cor) aveDN = 0.5 * (gdata[:-1] + gdata[1:]) ax[5].plot(aveDN, diffDN, label=f"Int #{k+1}", color=pcol[k]) # diffDN_orig = np.diff(gdata) # ax[2].plot(aveDN, diffDN_orig - mod[0](aveDN), '--') if k == 0: ax[5].set_ylim(0.9 * min(diffDN), 1.1 * max(diffDN)) aveslope = np.average(intslopes) ax[7].plot( np.array(ints) + 1, intslopes / aveslope, "ko", label=f"Exp 1: Ave = {aveslope:.2f}", ) ax[6].plot( np.array(ints) + 1, np.sqrt(linfit_metric), "ko", label=f"Exp 1: Ave = {aveslope:.2f}", ) # *** if args.primeonly: filenames = [] else: filenames = all_filenames[1:] lin_off_val = 0.01 prev_ints = nints for z, cfile in enumerate(filenames): hdu = fits.open(cfile) nints = hdu[0].header["NINT"] ints = range(nints) # off_int = (z + 1) * nints off_int = prev_ints prev_ints += nints # plot all integrations folded for k in range(nints): gnum, ydata = get_ramp(hdu[0], pix_x, pix_y, k, rampoffval=rampoffvals[z + 1]) ggnum, gdata, aveDN, diffDN = get_good_ramp(gnum, ydata) ax[0].plot(gnum, ydata, color=pcol[k]) # plot the 2pt diffs ax[1].plot(ggnum[:-1], diffDN, color=pcol[k]) # plot the 2pt diffs versus average DN ax[2].plot(aveDN, diffDN, color=pcol[k]) # apply the correction line_init = Linear1D() fit_line = LinearLSQFitter() intslopes = np.zeros((nints)) linfit_metric = np.zeros((nints)) for k in range(nints): gnum, ydata = get_ramp(hdu[0], pix_x, pix_y, k, rampoffval=rampoffvals[z + 1]) ggnum, gdata, aveDN, diffDN = get_good_ramp(gnum, ydata) # correct the ramps and plot ycor = cor_mod(gdata) gdata_cor = gdata * ycor ax[0].plot(ggnum, gdata_cor, "--", color=pcol[k]) # plot the corrected ramp divided by a linear fit line_mod = fit_line(line_init, ggnum[nrej:], gdata_cor[nrej:]) intslopes[k] = line_mod.slope.value linfit_ratio = gdata_cor / line_mod(ggnum) ax[4].plot(ggnum, linfit_ratio + (z + 1) * lin_off_val, "--", color=pcol[k]) ax[4].plot(ggnum, (z + 1) * lin_off_val + np.full((len(ggnum)), 1.0), "k--") # compute metric on deviations from the linear fit linfit_metric[k] = np.sum(np.power(linfit_ratio[nrej:] - 1.0, 2.0)) / len( linfit_ratio[nrej:] ) # plot the 2pt diffs versus average DN diffDN = np.diff(gdata_cor) aveDN = 0.5 * (gdata[:-1] + gdata[1:]) ax[5].plot(aveDN, diffDN) aveslope = np.average(intslopes) ax[7].plot( np.array(ints) + 1 + off_int, intslopes / aveslope, "o", label=f"Exp {z+2}: Ave = {aveslope:.2f}", ) ax[6].plot( np.array(ints) + 1 + off_int, np.sqrt(linfit_metric), "o", label=f"Exp {z+2}: Ave = {aveslope:.2f}", ) # *** ax[2].plot(mod_x, mod(mod_x), "k--", label="Exp1D+Poly1D") ax[2].plot(mod_x, polymod(mod_x), "k-.", label="Poly1D only") ax[5].plot(ax[5].get_xlim(), [polymod.c0, polymod.c0], "k--", label="c_0") ax[7].set_xlabel("integration #") ax[7].set_ylabel("slope / ave") ax[7].set_ylim(0.99, 1.05) # finish the plots ax[0].set_xlabel("group #") ax[0].set_ylabel("DN") ax[4].set_xlabel("group #") ax[4].set_ylabel("DN_cor/line_fit") ax[4].set_ylim(0.99, 1.01 + lin_off_val * len(filenames)) ax[4].plot(nrej * np.full((2), 1.0), ax[4].get_ylim(), "k--", label="nrej") ax[1].set_xlabel("group #") ax[1].set_ylabel("DN/group") ax[5].set_xlabel("DN") ax[5].set_ylabel("DN_cor/group") ax[2].set_xlabel("DN") ax[2].set_ylabel("DN/group") ax[3].set_xlabel("DN") ax[3].set_ylabel("Mult Correction") ax[6].set_xlabel("integration #") ax[6].set_ylabel(r"$\sigma$ dev from linfit per group") for k in range(len(ax)): ax[k].legend() ax[7].legend(ncol=2) ax[6].legend().set_visible(False) fig.suptitle(f"{all_filenames[0]}; Pixel ({pix_x}, {pix_y})") fig.tight_layout(rect=[0, 0.03, 1, 0.95]) out_basename = f"plot_miri_ramp_{pix_x}_{pix_y}_nreg{args.nrej+1}" if args.primeonly: out_basename += "_primeonly" if args.png: fig.savefig(out_basename) elif args.pdf: fig.savefig(out_basename) else: plt.show()
[ 11748, 1822, 29572, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2603, 29487, 8019, 355, 285, 489, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 6468, 28338, 13, 952, 1330, 11414, 198, 6738, 6468, 2833...
1.882379
6,657
import FWCore.ParameterSet.Config as cms source = cms.Source("EmptySource") # name of DQM Source program from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer hlxdqmsource = DQMEDAnalyzer('HLXMonitor', NBINS = cms.untracked.uint32(335), ## 10 bunch crossings per bin Style = cms.untracked.string('BX'), ## BX for bunch crossing vs. Num events outputFile = cms.untracked.string('DQM'), # 2 random data HLXDAQIP = cms.untracked.string('lxplus247'), subSystemName = cms.untracked.string('HLX'), XMIN = cms.untracked.double(100.0), XMAX = cms.untracked.double(3450.0), SourcePort = cms.untracked.uint32(51001), AquireMode = cms.untracked.uint32(1), ## 0 TCP data, 1 constant fake data # History for time vs. Num events # Dist for Distribution of Num events Accumulate = cms.untracked.bool(True), outputDir = cms.untracked.string('/tmp/neadam/dqmdata'), SavePeriod = cms.untracked.uint32(64) )
[ 11748, 48849, 14055, 13, 36301, 7248, 13, 16934, 355, 269, 907, 198, 198, 10459, 796, 269, 907, 13, 7416, 7203, 40613, 7416, 4943, 198, 198, 2, 1438, 286, 360, 48, 44, 8090, 1430, 198, 6738, 360, 48, 5653, 712, 1063, 13, 14055, 13, ...
2.539683
378
from queue import Queue from generateAST import TreeNode # tranverse the tree to find the defect node # usually use the pattern call.value
[ 6738, 16834, 1330, 4670, 518, 198, 6738, 7716, 11262, 1330, 12200, 19667, 198, 198, 2, 491, 272, 4399, 262, 5509, 284, 1064, 262, 11855, 10139, 198, 198, 2, 3221, 779, 262, 3912, 869, 13, 8367 ]
4
35
#Copyright (c) 2021, Rutwik and contributors # For license information, please see license.txt import frappe, json, datetime from frappe.utils import getdate from frappe.model.document import Document from accounting.accounting.doctype.gl_entry.gl_entry import make_gl_entries @frappe.whitelist(allow_guest=True)
[ 2, 15269, 357, 66, 8, 33448, 11, 21214, 20763, 290, 20420, 198, 2, 1114, 5964, 1321, 11, 3387, 766, 5964, 13, 14116, 198, 198, 11748, 5306, 27768, 11, 33918, 11, 4818, 8079, 198, 6738, 5306, 27768, 13, 26791, 1330, 651, 4475, 198, 6...
3.315789
95
from abc import ABC, abstractmethod from typing import Union, Tuple, Iterable, TypeVar from .. import ex T = TypeVar('T', bound=IRow)
[ 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 6738, 19720, 1330, 4479, 11, 309, 29291, 11, 40806, 540, 11, 5994, 19852, 198, 198, 6738, 11485, 1330, 409, 628, 198, 198, 51, 796, 5994, 19852, 10786, 51, 3256, 5421, 28, 4663, 322, ...
3.159091
44
#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" import io from setuptools import find_packages, setup with io.open("README.rst", encoding="UTF-8") as readme_file: readme = readme_file.read() with io.open("CHANGELOG.rst", encoding="UTF-8") as changelog_file: history = changelog_file.read() requirements = ["attrs>=18.1.0", "numpy>=1.11.0", "oop-ext>=0.2.4"] extras_require = { "docs": ["sphinx >= 1.4", "sphinx_rtd_theme", "sphinx-autodoc-typehints"], "testing": ["codecov", "pytest", "pytest-cov", "pytest-mock", "pre-commit", "tox"], } setup( author="ESSS", author_email="foss@esss.co", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", ], description="Python package to manage units for physical quantities", extras_require=extras_require, install_requires=requirements, license="MIT license", long_description=readme + "\n\n" + history, include_package_data=True, python_requires=">=3.6", keywords="barril", name="barril", packages=find_packages(where="src"), package_dir={"": "src"}, url="https://github.com/ESSS/barril", use_scm_version=True, setup_requires=["setuptools_scm"], zip_safe=False, )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 464, 9058, 4226, 526, 15931, 198, 198, 11748, 33245, 198, 6738, 900, 37623, 10141, 1330, 1064, 62, 43789, 1...
2.443686
586
import numpy as np import sympy as sp HyperbolicTangentFluidFractionSolution().DerivativeCalculator()
[ 11748, 299, 32152, 355, 45941, 201, 198, 11748, 10558, 88, 355, 599, 201, 198, 201, 198, 38197, 65, 4160, 43909, 298, 37, 2290, 312, 37, 7861, 46344, 22446, 28532, 452, 876, 9771, 3129, 1352, 3419 ]
3
35
from jason.ctrnn import CTRNN import matplotlib.pyplot as plt import matplotlib.patches as mpatches import numpy as np import random import sys import json import os import math from util.fitness_functions import fitness_maximize_output_change, fitness_frequency_match def simulate_ctrnn(ctrnn, stepsize=0.01, init_duration=0, test_duration=10): """This function simply provides an average change in output per neuron per time. Optionally can include initial duration to prevent transient changes at start of simulation.""" init_time = np.arange(0.0, init_duration, stepsize) test_time = np.arange(0.0, test_duration, stepsize) output_history=np.zeros((len(test_time),ctrnn.size)) #allow transients to clear ctrnn.initializeState( np.zeros( ctrnn.size )) #ctrnn.initializeState( np.asarray( [-5.0, 10.0] )) for i in range(len(init_time)): ctrnn.step(stepsize) #evaluate after transient period change_in_output=0 for i in range(len(test_time)): output_history[i] = ctrnn.outputs pastOutputs = ctrnn.outputs ctrnn.step(stepsize) currentOutputs = ctrnn.outputs change_in_output += np.sum(abs(currentOutputs - pastOutputs) ) #average over time and per neuron return change_in_output / ctrnn.size / test_duration, output_history main()
[ 198, 6738, 474, 888, 13, 24087, 20471, 1330, 34577, 6144, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2603, 29487, 8019, 13, 8071, 2052, 355, 285, 8071, 2052, 198, 11748, 299, 32152, 355, 45941, 198, 11748,...
2.689723
506
#!/usr/bin/env python3 import codecs, json from PokeFacts import DataPulls
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 40481, 82, 11, 33918, 198, 6738, 41163, 37, 8656, 1330, 6060, 42940, 82 ]
3
25
#!python3 try: from .Settings import * except Exception: # ImportError from Settings import * import time from classes import Variable_Holder as VH import math import websocket import json import threading global vars vars = VH() if __name__ == "__main__": print("Main function started:\n") if not ((Headlights_Pin == False) or (ESC_Pin == False) or (Steering_Pin == False)): import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) vars.status_initial = True if Using_Blinkstick: print("Blinkstick plugged in, starting...") blinkstick_lights_thread = threading.Thread(target=set_blinkstick, args=(vars,)) blinkstick_lights_thread.start() if not (Headlights_Pin == False): print("Headlights plugged in, start...") headlights_thread = threading.Thread(target=set_headlights, args=(vars,)) headlights_thread.start() print("Init servo function:\n") if not ((ESC_Pin == False) or (Steering_Pin == False)): import pigpio pi = pigpio.pi() init_servo(pi) servo_thread = threading.Thread(target=do_servos, args=(vars,pi)) servo_thread.start() ws_thread = threading.Thread(target=ws_loop, args=(vars,)) print("Starting tasks...\n") ws_thread.start() vars.status_initial = False
[ 2, 0, 29412, 18, 198, 198, 28311, 25, 198, 220, 220, 220, 422, 764, 26232, 1330, 1635, 198, 16341, 35528, 25, 220, 1303, 17267, 12331, 198, 220, 220, 220, 422, 16163, 1330, 1635, 198, 11748, 640, 198, 6738, 6097, 1330, 35748, 62, 39...
2.521154
520
import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import sensor, spi from esphome.const import CONF_ID, CONF_MAINS_FILTER, CONF_REFERENCE_RESISTANCE, \ CONF_RTD_NOMINAL_RESISTANCE, CONF_RTD_WIRES, ICON_THERMOMETER, UNIT_CELSIUS max31865_ns = cg.esphome_ns.namespace('max31865') MAX31865Sensor = max31865_ns.class_('MAX31865Sensor', sensor.Sensor, cg.PollingComponent, spi.SPIDevice) MAX31865ConfigFilter = max31865_ns.enum('MAX31865ConfigFilter') FILTER = { '50HZ': MAX31865ConfigFilter.FILTER_50HZ, '60HZ': MAX31865ConfigFilter.FILTER_60HZ, } CONFIG_SCHEMA = sensor.sensor_schema(UNIT_CELSIUS, ICON_THERMOMETER, 2).extend({ cv.GenerateID(): cv.declare_id(MAX31865Sensor), cv.Required(CONF_REFERENCE_RESISTANCE): cv.All(cv.resistance, cv.Range(min=100, max=10000)), cv.Required(CONF_RTD_NOMINAL_RESISTANCE): cv.All(cv.resistance, cv.Range(min=100, max=1000)), cv.Optional(CONF_MAINS_FILTER, default='60HZ'): cv.enum(FILTER, upper=True, space=''), cv.Optional(CONF_RTD_WIRES, default=4): cv.int_range(min=2, max=4), }).extend(cv.polling_component_schema('60s')).extend(spi.SPI_DEVICE_SCHEMA)
[ 11748, 1658, 746, 462, 13, 8189, 5235, 355, 269, 70, 198, 11748, 1658, 746, 462, 13, 11250, 62, 12102, 341, 355, 269, 85, 198, 6738, 1658, 746, 462, 13, 5589, 3906, 1330, 12694, 11, 599, 72, 198, 6738, 1658, 746, 462, 13, 9979, 13...
2.17509
554
# This file exists only so that I can do `os.path.dirname(dummy.__file__)`
[ 2, 770, 2393, 7160, 691, 523, 326, 314, 460, 466, 4600, 418, 13, 6978, 13, 15908, 3672, 7, 67, 13513, 13, 834, 7753, 834, 8, 63, 198 ]
2.777778
27
""" `miniwdl <https://github.com/chanzuckerberg/miniwdl/>`_ is a developer toolkit and local runner for the bioinformatics-focused `Workflow Description Language (WDL) <http://openwdl.org/>`_. This documentation covers the Python3 ``WDL`` package facilitating parsing & static analysis of WDL documents. * `GitHub repo <https://github.com/chanzuckerberg/miniwdl/>`_ for installation and further background * `Codelabs <https://miniwdl.readthedocs.io/en/latest/WDL.html#python-codelabs>`_ on using this package """ import os import errno import inspect from typing import List, Optional, Callable, Dict, Any, Awaitable, Union from . import _util, _parser, Error, Type, Value, Env, Expr, Tree, Walker, Lint, StdLib from .Tree import ( Decl, StructTypeDef, Task, Call, Scatter, Conditional, Gather, Workflow, Document, WorkflowNode, WorkflowSection, SourceComment, ) from . import runtime SourcePosition = Error.SourcePosition SourceNode = Error.SourceNode def load( uri: str, path: Optional[List[str]] = None, check_quant: bool = True, read_source: Optional[ Callable[[str, List[str], Optional[Document]], Awaitable["ReadSourceResult"]] ] = None, import_max_depth: int = 10, ) -> Document: """ Parse a WDL document given filename/URI, recursively descend into imported documents, then typecheck the tasks and workflow. :param path: local filesystem directories to search for imports, in addition to the current working directory :param check_quant: set to ``False`` to relax static typechecking of the optional (?) and nonempty (+) type quantifiers. This is discouraged, but may be useful for older WDL workflows which assume less-rigorous static validation of these annotations. :param read_source: async routine to read the WDL source code from filename/URI; see :func:`read_source_default` below for details :param import_max_depth: to prevent recursive import infinite loops, fail when there are too many import nesting levels (default 10) :raises WDL.Error.SyntaxError: when the document is syntactically invalid under the WDL grammar :raises WDL.Error.ValidationError: when the document is syntactically OK, but fails typechecking or other static validity checks :raises WDL.Error.MultipleValidationErrors: when multiple validation errors are detected in one pass, listed in the ``exceptions`` attribute :raises WDL.Error.ImportError: when an imported sub-document can't be loaded; the ``__cause__`` attribute has the specific error """ return Tree.load( uri, path=path, check_quant=check_quant, read_source=read_source, import_max_depth=import_max_depth, ) async def load_async( uri: str, path: Optional[List[str]] = None, check_quant: bool = True, read_source: Optional[ Callable[[str, List[str], Optional[Document]], Awaitable["ReadSourceResult"]] ] = None, import_max_depth: int = 10, ) -> Document: """ Async version of :func:`load`, with all the same arguments """ return await Tree.load_async( uri, path=path, check_quant=check_quant, read_source=read_source, import_max_depth=import_max_depth, ) async def read_source_default( uri: str, path: List[str], importer: Optional[Document] ) -> "ReadSourceResult": """ Default async routine for the ``read_source`` parameter to :func:`load` and :func:`load_async`, which they use to read the desired WDL document and its imports. This default routine handles local files only, supplying the search path logic to resolve relative filenames; it fails with network URIs. :param uri: Filename/URI to read, as provided to :func:`load` or the WDL import statement; may be relative :param path: Local directories to search for relative imports :param importer: The document importing the one here requested, if any; the ``importer.pos.uri`` and ``importer.pos.abspath`` fields may be relevant to resolve relative imports. :returns: ``ReadSourceResult(source_text="...", abspath="...")`` Callers may wish to override ``read_source`` with logic to download source code from network URIs, and for local filenames fall back to ``return await WDL.read_source_default(...)``. Note: the synchronous :func:`load` merely calls :func:`load_async` on the current ``asyncio.get_event_loop()`` and awaits the result. """ return await Tree.read_source_default(uri, path, importer) class ReadSourceResult(Tree.ReadSourceResult): """ The ``NamedTuple`` to be returned by the ``read_source`` routine. Its ``source_text: str`` field provides the WDL source code, and the ``abspath: str`` field is the absolute filename/URI from which the source was read (e.g. after resolving a relative path). """ async def resolve_file_import(uri: str, path: List[str], importer: Optional[Document]) -> str: """ Exposes the logic by which :func:`read_source_default` resolves ``uri`` to the absolute path of an extant file. If ``uri`` is already an absolute path, it's normalized and returned. A relative ``uri`` is resolved by first joining it to either, the directory of the importer document (if any), or the process current working directory (otherwise). Failing that, it's searched in the ``path`` directories (in reverse order). """ return await Tree.resolve_file_import(uri, path, importer) def copy_source(doc: Document, dir: str) -> str: "" """ Copy the original WDL document source, and any imports, into the specified directory. Ignores any imports using absolute file paths or URIs. Returns the path to the copy of the given document, which possibly could be nested in a subdirectory if it uses .. relative imports. """ # make list of all docs to save docs = [] queue = [doc] while queue: a_doc = queue.pop() docs.append(a_doc) for imp in a_doc.imports: if ( not imp.uri.startswith("http:") and not imp.uri.startswith("https:") and not os.path.isabs(imp.uri) ): queue.append(imp.doc) # find longest common prefix (up to a '/') among docs' pos.abspath (note these could be URIs!) lcp = os.path.dirname(os.path.commonprefix([a_doc.pos.abspath for a_doc in docs])) # write each doc text out under dir, its abspath without lcp ans = None for a_doc in docs: assert a_doc.pos.abspath.startswith(lcp) rp = a_doc.pos.abspath[len(lcp) :].lstrip("/") fn = os.path.join(dir, rp) os.makedirs(os.path.dirname(fn), exist_ok=True) _util.write_atomic(a_doc.source_text, fn, end="") if a_doc is doc: assert not ans ans = fn assert ans return ans def parse_document(txt: str, version: Optional[str] = None, uri: str = "") -> Document: "" """ Parse WDL document text into an abstract syntax tree. Doesn't descend into imported documents nor typecheck the AST. :param version: Override the WDL language version, such as "1.0" or "draft-2". (By default, detects from the "version" string at the beginning of the document, per the WDL spec.) :param uri: filename/URI for error reporting (not otherwise used) """ return _parser.parse_document(txt, version, uri) def parse_expr(txt: str, version: Optional[str] = None) -> Expr.Base: "" """ Parse an isolated WDL expression text into an abstract syntax tree """ return _parser.parse_expr(txt, version) def values_from_json( values_json: Dict[str, Any], available: Env.Bindings[Union[Tree.Decl, Type.Base]], required: Optional[Env.Bindings[Union[Tree.Decl, Type.Base]]] = None, namespace: str = "", ) -> Env.Bindings[Value.Base]: """ Given a dict parsed from Cromwell-style JSON and the available input (or output) declarations of a task or workflow, create a ``WDL.Env.Bindings[Value.Base]``. :param required: raise an error if any of these required inputs aren't present :param namespace: expect each key to start with this namespace prefixed to the input/output names (e.g. the workflow name) """ if namespace and not namespace.endswith("."): namespace += "." ans = Env.Bindings() for key in values_json: if not key.startswith("#"): # ignore "comments" key2 = key if namespace and key.startswith(namespace): key2 = key[len(namespace) :] if key2 not in available: # attempt to simplify <call>.<subworkflow>.<input> key2parts = key2.split(".") if len(key2parts) == 3 and key2parts[0] and key2parts[1] and key2parts[2]: key2 = ".".join([key2parts[0], key2parts[2]]) try: ty = available[key2] except KeyError: raise Error.InputError("unknown input/output: " + key) from None if isinstance(ty, Tree.Decl): ty = ty.type assert isinstance(ty, Type.Base) ans = ans.bind(key2, Value.from_json(ty, values_json[key])) if required: missing = required.subtract(ans) if missing: raise Error.InputError( "missing required inputs/outputs: " + ", ".join(values_to_json(missing)) ) return ans def values_to_json(values_env: Env.Bindings[Value.Base], namespace: str = "") -> Dict[str, Any]: """ Convert a ``WDL.Env.Bindings[WDL.Value.Base]`` to a dict which ``json.dumps`` to Cromwell-style JSON. :param namespace: prefix this namespace to each key (e.g. workflow name) """ # also can be used on Env.Bindings[Tree.Decl] or Env.Types, then the right-hand side of # each entry will be the type string. if namespace and not namespace.endswith("."): namespace += "." ans = {} for item in values_env: v = item.value if isinstance(v, Value.Base): j = v.json elif isinstance(item.value, Tree.Decl): j = str(item.value.type) else: assert isinstance(item.value, Type.Base) j = str(item.value) ans[namespace + item.name] = j return ans
[ 37811, 198, 63, 1084, 14246, 25404, 1279, 5450, 1378, 12567, 13, 785, 14, 3147, 89, 12603, 3900, 14, 1084, 14246, 25404, 15913, 63, 62, 318, 257, 8517, 2891, 15813, 290, 1957, 17490, 329, 198, 1169, 13401, 259, 18982, 873, 12, 18143, ...
2.66269
3,940
# Generated by Django 3.1.1 on 2020-10-11 20:24 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 16, 319, 12131, 12, 940, 12, 1157, 1160, 25, 1731, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
# test_model.py import numpy as np from grabscreen import grab_screen import cv2 import time from alexnet import alexnet from getkeys import key_check import serial arduinoSerial = serial.Serial('com4',9600) time.sleep(1) import random WIDTH = 160 HEIGHT = 120 LR = 1e-3 EPOCHS = 20 MODEL_NAME = 'self-driving-car-fast-final-{}-{}-{}-epochs-930-data.model'.format(LR, 'alexnetv2',EPOCHS) t_time = 0.09 ## ReleaseKey(A) # ReleaseKey(D) model = alexnet(WIDTH, HEIGHT, LR) model.load(MODEL_NAME) main()
[ 2, 1332, 62, 19849, 13, 9078, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 5552, 9612, 1330, 5552, 62, 9612, 198, 11748, 269, 85, 17, 198, 11748, 640, 198, 6738, 257, 2588, 3262, 1330, 257, 2588, 3262, 198, 6738, 651, 13083, ...
2.314159
226
# # (c) Copyright 2015 Hewlett-Packard Development Company, L.P. # # 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. """API over the neutron service. """ from django.views import generic from openstack_dashboard import api from openstack_dashboard.api.rest import utils as rest_utils from openstack_dashboard.api.rest import urls @urls.register class Networks(generic.View): """API for Neutron Networks http://developer.openstack.org/api-ref-networking-v2.html """ url_regex = r'neutron/networks/$' @rest_utils.ajax() def get(self, request): """Get a list of networks for a project The listing result is an object with property "items". Each item is a network. """ tenant_id = request.user.tenant_id result = api.neutron.network_list_for_tenant(request, tenant_id) return{'items': [n.to_dict() for n in result]} @rest_utils.ajax(data_required=True) def post(self, request): """Create a network :param admin_state_up (optional): The administrative state of the network, which is up (true) or down (false). :param name (optional): The network name. A request body is optional: If you include it, it can specify this optional attribute. :param net_profile_id (optional): network profile id :param shared (optional): Indicates whether this network is shared across all tenants. By default, only administrative users can change this value. :param tenant_id (optional): Admin-only. The UUID of the tenant that will own the network. This tenant can be different from the tenant that makes the create network request. However, only administrative users can specify a tenant ID other than their own. You cannot change this value through authorization policies. :return: JSON representation of a Network """ if not api.neutron.is_port_profiles_supported(): request.DATA.pop("net_profile_id", None) new_network = api.neutron.network_create(request, **request.DATA) return rest_utils.CreatedResponse( '/api/neutron/networks/%s' % new_network.id, new_network.to_dict() ) @urls.register class Subnets(generic.View): """API for Neutron SubNets http://developer.openstack.org/api-ref-networking-v2.html#subnets """ url_regex = r'neutron/subnets/$' @rest_utils.ajax() def get(self, request): """Get a list of subnets for a project The listing result is an object with property "items". Each item is a subnet. """ result = api.neutron.subnet_list(request, **request.GET) return{'items': [n.to_dict() for n in result]} @rest_utils.ajax(data_required=True) def post(self, request): """Create a Subnet for a given Network :param name (optional): The subnet name. :param network_id: The ID of the attached network. :param tenant_id (optional): The ID of the tenant who owns the network. Only administrative users can specify a tenant ID other than their own. :param allocation_pools (optional): The start and end addresses for the allocation pools. :param gateway_ip (optional): The gateway IP address. :param ip_version: The IP version, which is 4 or 6. :param cidr: The CIDR. :param id (optional): The ID of the subnet. :param enable_dhcp (optional): Set to true if DHCP is enabled and false if DHCP is disabled. :return: JSON representation of a Subnet """ new_subnet = api.neutron.subnet_create(request, **request.DATA) return rest_utils.CreatedResponse( '/api/neutron/subnets/%s' % new_subnet.id, new_subnet.to_dict() ) @urls.register class Ports(generic.View): """API for Neutron Ports http://developer.openstack.org/api-ref-networking-v2.html#ports """ url_regex = r'neutron/ports/$' @rest_utils.ajax() def get(self, request): """Get a list of ports for a network The listing result is an object with property "items". Each item is a subnet. """ # see # https://github.com/openstack/neutron/blob/master/neutron/api/v2/attributes.py result = api.neutron.port_list(request, **request.GET) return{'items': [n.to_dict() for n in result]}
[ 2, 198, 2, 220, 220, 220, 357, 66, 8, 15069, 1853, 30446, 15503, 12, 11869, 446, 7712, 5834, 11, 406, 13, 47, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, ...
2.566381
1,981
#!/usr/bin/env python # $Id$ #------------------------------------------------------------------------ # NAME: grid_sizer_dialog.py - # HISTORY: - # 2017-07-21 leerw@ornl.gov - # Fixing _OnCharHook for Linux. # 2017-03-31 leerw@ornl.gov - # Added EVT_CHAR_HOOK # 2015-02-14 leerw@ornl.gov - #------------------------------------------------------------------------ import math, os, sys, time, traceback import numpy as np import pdb #pdb.set_trace() try: import wx, wx.lib.newevent except ImportException: raise ImportError, 'The wxPython module is required for this component' from .grid_sizer_bean import * #------------------------------------------------------------------------ # CLASS: GridSizerDialog - #------------------------------------------------------------------------ class GridSizerDialog( wx.Dialog ): """ Properties: bean component reference """ # -- Properties # -- #---------------------------------------------------------------------- # PROPERTY: GridSizerDialog.bean - #---------------------------------------------------------------------- @property def bean( self ): """reference to component instance, read-only""" return self.fBean #end bean.getter #---------------------------------------------------------------------- # PROPERTY: GridSizerDialog.result - #---------------------------------------------------------------------- @property def result( self ): """( rows, cols ) or None, read-only""" return self.fResult #end result.getter #---------------------------------------------------------------------- # PROPERTY: GridSizerDialog.value - #---------------------------------------------------------------------- # @property # def value( self ): # """( rows, cols ), read-only""" # return self.fBean.value if self.fBean is not None else ( 1, 1 ) # #end value.getter # -- Builtin Object Methods # -- #---------------------------------------------------------------------- # METHOD: __init__() - #---------------------------------------------------------------------- #def __init__( self, container, id = -1 ): def __init__( self, *args, **kwargs ): """ """ super( GridSizerDialog, self ).__init__( *args, **kwargs ) self.fBean = None self.fResult = None self._InitUI() #end __init__ # -- Object Methods # -- #---------------------------------------------------------------------- # METHOD: GridSizerDialog.GetResult() - #---------------------------------------------------------------------- #end GetResult #---------------------------------------------------------------------- # METHOD: GridSizerDialog._InitUI() - #---------------------------------------------------------------------- def _InitUI( self ): """Builds this UI component. Obviously, must be called in the UI thread. """ # -- Bean # -- self.fBean = GridSizerBean( self, -1 ) # -- Button Panel # -- #button_panel = wx.Panel( self, -1 ) button_sizer = wx.BoxSizer( wx.HORIZONTAL ) ok_button = wx.Button( self, label = '&OK' ) ok_button.Bind( wx.EVT_BUTTON, self._OnClick ) cancel_button = wx.Button( self, label = 'Cancel' ) cancel_button.Bind( wx.EVT_BUTTON, self._OnClick ) button_sizer.AddStretchSpacer() button_sizer.Add( ok_button, 0, wx.ALL | wx.EXPAND, 6 ) button_sizer.AddSpacer( 10 ) button_sizer.Add( cancel_button, 0, wx.ALL | wx.EXPAND, 6 ) button_sizer.AddStretchSpacer() # -- Lay Out # -- sizer = wx.BoxSizer( wx.VERTICAL ) sizer.Add( self.fBean, 1, wx.ALL | wx.EXPAND | wx.ALIGN_LEFT | wx.ALIGN_TOP, 6 ) sizer.Add( button_sizer, 0, wx.ALL | wx.EXPAND, 6 ) sizer.Layout() self.Bind( wx.EVT_CHAR_HOOK, self._OnCharHook ) self.SetTitle( 'Set Grid Size' ) self.SetSizer( sizer ) self.Fit() self.Center() #end _InitUI #---------------------------------------------------------------------- # METHOD: GridSizerDialog._OnCharHook() - #---------------------------------------------------------------------- #end _OnCharHook #---------------------------------------------------------------------- # METHOD: GridSizerDialog._OnClick() - #---------------------------------------------------------------------- #end _OnClick #---------------------------------------------------------------------- # METHOD: GridSizerDialog.ShowModal() - #---------------------------------------------------------------------- #end ShowModal #end GridSizerDialog
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 720, 7390, 3, 198, 2, 10097, 982, 198, 2, 197, 20608, 25, 197, 197, 25928, 62, 82, 7509, 62, 38969, 519, 13, 9078, 197, 197, 197, 197, 12, 198, 2, 197, 39, 42480, 25, 197, 1...
3.211592
1,432
""" Module to handle attributes related to the pbs jobmanager configuration """ import os import logging from osg_configure.modules import utilities from osg_configure.modules import configfile from osg_configure.modules import validation from osg_configure.modules.jobmanagerconfiguration import JobManagerConfiguration __all__ = ['PBSConfiguration'] class PBSConfiguration(JobManagerConfiguration): """Class to handle attributes related to pbs job manager configuration""" def parse_configuration(self, configuration): """Try to get configuration information from ConfigParser or SafeConfigParser object given by configuration and write recognized settings to attributes dict """ super(PBSConfiguration, self).parse_configuration(configuration) self.log('PBSConfiguration.parse_configuration started') self.check_config(configuration) if not configuration.has_section(self.config_section): self.log('PBS section not found in config file') self.log('PBSConfiguration.parse_configuration completed') return if not self.set_status(configuration): self.log('PBSConfiguration.parse_configuration completed') return True self.get_options(configuration, ignore_options=['enabled', 'job_contact', 'util_contact', 'accept_limited', 'seg_enabled', 'log_directory']) # set OSG_JOB_MANAGER and OSG_JOB_MANAGER_HOME self.options['job_manager'] = configfile.Option(name='job_manager', value='PBS', mapping='OSG_JOB_MANAGER') self.options['home'] = configfile.Option(name='job_manager_home', value=self.options['pbs_location'].value, mapping='OSG_JOB_MANAGER_HOME') self.pbs_bin_location = os.path.join(self.options['pbs_location'].value, 'bin') self.log('PBSConfiguration.parse_configuration completed') # pylint: disable-msg=W0613 def check_attributes(self, attributes): """Check attributes currently stored and make sure that they are consistent""" self.log('PBSConfiguration.check_attributes started') attributes_ok = True if not self.enabled: self.log('PBS not enabled, returning True') self.log('PBSConfiguration.check_attributes completed') return attributes_ok if self.ignored: self.log('Ignored, returning True') self.log('PBSConfiguration.check_attributes completed') return attributes_ok # make sure locations exist if not validation.valid_location(self.options['pbs_location'].value): attributes_ok = False self.log("Non-existent location given: %s" % (self.options['pbs_location'].value), option='pbs_location', section=self.config_section, level=logging.ERROR) if not validation.valid_directory(self.pbs_bin_location): attributes_ok = False self.log("Given pbs_location %r has no bin/ directory" % self.options['pbs_location'].value, option='pbs_location', section=self.config_section, level=logging.ERROR) self.log('PBSConfiguration.check_attributes completed') return attributes_ok def configure(self, attributes): """Configure installation using attributes""" self.log('PBSConfiguration.configure started') if not self.enabled: self.log('PBS not enabled, returning True') self.log('PBSConfiguration.configure completed') return True if self.ignored: self.log("%s configuration ignored" % self.config_section, level=logging.WARNING) self.log('PBSConfiguration.configure completed') return True if self.htcondor_gateway_enabled: self.write_binpaths_to_blah_config('pbs', self.pbs_bin_location) self.write_blah_disable_wn_proxy_renewal_to_blah_config() self.write_htcondor_ce_sentinel() self.log('PBSConfiguration.configure completed') return True def module_name(self): """Return a string with the name of the module""" return "PBS" def separately_configurable(self): """Return a boolean that indicates whether this module can be configured separately""" return True def enabled_services(self): """Return a list of system services needed for module to work """ if not self.enabled or self.ignored: return set() services = set(['globus-gridftp-server']) services.update(self.gateway_services()) return services
[ 37811, 19937, 284, 5412, 12608, 3519, 284, 262, 279, 1443, 1693, 37153, 220, 198, 11250, 3924, 37227, 198, 198, 11748, 28686, 198, 11748, 18931, 198, 198, 6738, 28686, 70, 62, 11250, 495, 13, 18170, 1330, 20081, 198, 6738, 28686, 70, 62...
2.353573
2,141
import FWCore.ParameterSet.Config as cms from DQMOffline.Trigger.HTMonitor_cfi import hltHTmonitoring from DQMOffline.Trigger.JetMonitor_cfi import hltJetMETmonitoring from DQMOffline.Trigger.TrackingMonitoring_cff import * DisplacedJetIter2TracksMonitoringHLT = trackingMonHLT.clone() DisplacedJetIter2TracksMonitoringHLT.FolderName = 'HLT/EXO/DisplacedJet/Tracking/iter2MergedForBTag' DisplacedJetIter2TracksMonitoringHLT.TrackProducer = 'hltIter2MergedForBTag' DisplacedJetIter2TracksMonitoringHLT.allTrackProducer = 'hltIter2MergedForBTag' DisplacedJetIter4TracksMonitoringHLT = trackingMonHLT.clone() DisplacedJetIter4TracksMonitoringHLT.FolderName = 'HLT/EXO/DisplacedJet/Tracking/iter4ForDisplaced' DisplacedJetIter4TracksMonitoringHLT.TrackProducer = 'hltDisplacedhltIter4PFlowTrackSelectionHighPurity' DisplacedJetIter4TracksMonitoringHLT.allTrackProducer = 'hltDisplacedhltIter4PFlowTrackSelectionHighPurity' trackingMonitorHLTDisplacedJet = cms.Sequence( DisplacedJetIter2TracksMonitoringHLT +DisplacedJetIter4TracksMonitoringHLT ) hltHT_HT425_Prommonitoring = hltHTmonitoring.clone() hltHT_HT425_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/HT/HT_425/') hltHT_HT425_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT425_v*") hltHT_HT425_Prommonitoring.jetSelection_HT = cms.string("pt > 40 && eta < 3.0") hltHT_HT400_DisplacedDijet40_DisplacedTrack_Prommonitoring = hltHTmonitoring.clone() hltHT_HT400_DisplacedDijet40_DisplacedTrack_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/HT/HLT_CaloJet_HT400_DisplacedDijet40_DisplacedTrack') hltHT_HT400_DisplacedDijet40_DisplacedTrack_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT400_DisplacedDijet40_DisplacedTrack_v*") hltHT_HT400_DisplacedDijet40_DisplacedTrack_Prommonitoring.jetSelection = cms.string("pt>40 && eta<2.0") hltHT_HT400_DisplacedDijet40_DisplacedTrack_Prommonitoring.jetSelection_HT = cms.string("pt > 40 && eta < 3.0") hltHT_HT430_DisplacedDijet40_DisplacedTrack_Prommonitoring = hltHTmonitoring.clone() hltHT_HT430_DisplacedDijet40_DisplacedTrack_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/HT/HLT_CaloJet_HT430_DisplacedDijet40_DisplacedTrack') hltHT_HT430_DisplacedDijet40_DisplacedTrack_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT430_DisplacedDijet40_DisplacedTrack_v*") hltHT_HT430_DisplacedDijet40_DisplacedTrack_Prommonitoring.jetSelection = cms.string("pt>40 && eta<2.0") hltHT_HT430_DisplacedDijet40_DisplacedTrack_Prommonitoring.jetSelection_HT = cms.string("pt > 40 && eta < 3.0") hltHT_HT430_DisplacedDijet60_DisplacedTrack_Prommonitoring = hltHTmonitoring.clone() hltHT_HT430_DisplacedDijet60_DisplacedTrack_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/HT/HLT_CaloJet_HT430_DisplacedDijet60_DisplacedTrack') hltHT_HT430_DisplacedDijet60_DisplacedTrack_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT430_DisplacedDijet60_DisplacedTrack_v*") hltHT_HT430_DisplacedDijet60_DisplacedTrack_Prommonitoring.jetSelection = cms.string("pt>60 && eta<2.0") hltHT_HT430_DisplacedDijet60_DisplacedTrack_Prommonitoring.jetSelection_HT = cms.string("pt > 40 && eta < 3.0") hltHT_HT430_DisplacedDijet80_DisplacedTrack_Prommonitoring = hltHTmonitoring.clone() hltHT_HT430_DisplacedDijet80_DisplacedTrack_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/HT/HLT_CaloJet_HT430_DisplacedDijet80_DisplacedTrack') hltHT_HT430_DisplacedDijet80_DisplacedTrack_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT430_DisplacedDijet80_DisplacedTrack_v*") hltHT_HT430_DisplacedDijet80_DisplacedTrack_Prommonitoring.jetSelection = cms.string("pt>80 && eta<2.0") hltHT_HT430_DisplacedDijet80_DisplacedTrack_Prommonitoring.jetSelection_HT = cms.string("pt > 40 && eta < 3.0") hltHT_HT550_DisplacedDijet60_Inclusive_Prommonitoring = hltHTmonitoring.clone() hltHT_HT550_DisplacedDijet60_Inclusive_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/HT/HT_CaloJet_HLT_HT550_DisplacedDijet60_Inclusive') hltHT_HT550_DisplacedDijet60_Inclusive_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT550_DisplacedDijet60_Inclusive_v*") hltHT_HT550_DisplacedDijet60_Inclusive_Prommonitoring.jetSelection = cms.string("pt>60 && eta<2.0") hltHT_HT550_DisplacedDijet60_Inclusive_Prommonitoring.jetSelection_HT = cms.string("pt > 40 && eta < 3.0") hltHT_HT550_DisplacedDijet80_Inclusive_Prommonitoring = hltHTmonitoring.clone() hltHT_HT550_DisplacedDijet80_Inclusive_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/HT/HT_CaloJet_HLT_HT550_DisplacedDijet80_Inclusive') hltHT_HT550_DisplacedDijet80_Inclusive_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT550_DisplacedDijet80_Inclusive_v*") hltHT_HT550_DisplacedDijet80_Inclusive_Prommonitoring.jetSelection = cms.string("pt>80 && eta<2.0") hltHT_HT550_DisplacedDijet80_Inclusive_Prommonitoring.jetSelection_HT = cms.string("pt > 40 && eta < 3.0") hltHT_HT650_DisplacedDijet60_Inclusive_Prommonitoring = hltHTmonitoring.clone() hltHT_HT650_DisplacedDijet60_Inclusive_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/HT/HT_CaloJet_HLT_HT650_DisplacedDijet60_Inclusive') hltHT_HT650_DisplacedDijet60_Inclusive_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT650_DisplacedDijet60_Inclusive_v*") hltHT_HT650_DisplacedDijet60_Inclusive_Prommonitoring.jetSelection = cms.string("pt>60 && eta<2.0") hltHT_HT650_DisplacedDijet60_Inclusive_Prommonitoring.jetSelection_HT = cms.string("pt > 40 && eta < 3.0") hltHT_HT650_DisplacedDijet80_Inclusive_Prommonitoring = hltHTmonitoring.clone() hltHT_HT650_DisplacedDijet80_Inclusive_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/HT/HT_CaloJet_HLT_HT650_DisplacedDijet80_Inclusive') hltHT_HT650_DisplacedDijet80_Inclusive_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT650_DisplacedDijet80_Inclusive_v*") hltHT_HT650_DisplacedDijet80_Inclusive_Prommonitoring.jetSelection = cms.string("pt>80 && eta<2.0") hltHT_HT650_DisplacedDijet80_Inclusive_Prommonitoring.jetSelection_HT = cms.string("pt > 40 && eta < 3.0") hltHT_HT750_DisplacedDijet80_Inclusive_Prommonitoring = hltHTmonitoring.clone() hltHT_HT750_DisplacedDijet80_Inclusive_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/HT/HT_CaloJet_HLT_HT750_DisplacedDijet80_Inclusive') hltHT_HT750_DisplacedDijet80_Inclusive_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT750_DisplacedDijet80_Inclusive_v*") hltHT_HT750_DisplacedDijet80_Inclusive_Prommonitoring.jetSelection = cms.string("pt>80 && eta<2.0") hltHT_HT750_DisplacedDijet80_Inclusive_Prommonitoring.jetSelection_HT = cms.string("pt > 40 && eta < 3.0") hltJet_HT400_DisplacedDijet40_DisplacedTrack_Prommonitoring = hltJetMETmonitoring.clone() hltJet_HT400_DisplacedDijet40_DisplacedTrack_Prommonitoring.jetSrc = cms.InputTag("ak4CaloJets") hltJet_HT400_DisplacedDijet40_DisplacedTrack_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/Jet/HLT_CaloJet_HT400_DisplacedDijet40_DisplacedTrack') hltJet_HT400_DisplacedDijet40_DisplacedTrack_Prommonitoring.ptcut = cms.double(20) hltJet_HT400_DisplacedDijet40_DisplacedTrack_Prommonitoring.histoPSet.jetptBinning = cms.vdouble(20.,26.,28.,30.,32.,34.,36.,38.,40.,42.,44.,46.,48.,50.,55.,60.,70.,80.,100.,120.,170.,220.,300.,400.) hltJet_HT400_DisplacedDijet40_DisplacedTrack_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT400_DisplacedDijet40_DisplacedTrack_v*") hltJet_HT400_DisplacedDijet40_DisplacedTrack_Prommonitoring.ispfjettrg = cms.bool(False) hltJet_HT400_DisplacedDijet40_DisplacedTrack_Prommonitoring.iscalojettrg = cms.bool(True) hltJet_HT430_DisplacedDijet40_DisplacedTrack_Prommonitoring = hltJetMETmonitoring.clone() hltJet_HT430_DisplacedDijet40_DisplacedTrack_Prommonitoring.jetSrc = cms.InputTag("ak4CaloJets") hltJet_HT430_DisplacedDijet40_DisplacedTrack_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/Jet/HLT_CaloJet_HT430_DisplacedDijet40_DisplacedTrack') hltJet_HT430_DisplacedDijet40_DisplacedTrack_Prommonitoring.ptcut = cms.double(20) hltJet_HT430_DisplacedDijet40_DisplacedTrack_Prommonitoring.histoPSet.jetptBinning = cms.vdouble(20.,26.,28.,30.,32.,34.,36.,38.,40.,42.,44.,46.,48.,50.,55.,60.,70.,80.,100.,120.,170.,220.,300.,400.) hltJet_HT430_DisplacedDijet40_DisplacedTrack_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT430_DisplacedDijet40_DisplacedTrack_v*") hltJet_HT430_DisplacedDijet40_DisplacedTrack_Prommonitoring.ispfjettrg = cms.bool(False) hltJet_HT430_DisplacedDijet40_DisplacedTrack_Prommonitoring.iscalojettrg = cms.bool(True) hltJet_HT430_DisplacedDijet60_DisplacedTrack_Prommonitoring = hltJetMETmonitoring.clone() hltJet_HT430_DisplacedDijet60_DisplacedTrack_Prommonitoring.jetSrc = cms.InputTag("ak4CaloJets") hltJet_HT430_DisplacedDijet60_DisplacedTrack_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/Jet/HLT_CaloJet_HT430_DisplacedDijet60_DisplacedTrack') hltJet_HT430_DisplacedDijet60_DisplacedTrack_Prommonitoring.ptcut = cms.double(20) hltJet_HT430_DisplacedDijet60_DisplacedTrack_Prommonitoring.histoPSet.jetptBinning = cms.vdouble(20.,26.,30.,35.,40.,45.,50.,52.,53.,54.,56.,58.,60.,62.,64.,66.,68.,70.,72.,75.,80.,100.,120.,170.,220.,300.,400.) hltJet_HT430_DisplacedDijet60_DisplacedTrack_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT430_DisplacedDijet60_DisplacedTrack_v*") hltJet_HT430_DisplacedDijet60_DisplacedTrack_Prommonitoring.ispfjettrg = cms.bool(False) hltJet_HT430_DisplacedDijet60_DisplacedTrack_Prommonitoring.iscalojettrg = cms.bool(True) hltJet_HT430_DisplacedDijet80_DisplacedTrack_Prommonitoring = hltJetMETmonitoring.clone() hltJet_HT430_DisplacedDijet80_DisplacedTrack_Prommonitoring.jetSrc = cms.InputTag("ak4CaloJets") hltJet_HT430_DisplacedDijet80_DisplacedTrack_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/Jet/HLT_CaloJet_HT430_DisplacedDijet80_DisplacedTrack') hltJet_HT430_DisplacedDijet80_DisplacedTrack_Prommonitoring.ptcut = cms.double(20) hltJet_HT430_DisplacedDijet80_DisplacedTrack_Prommonitoring.histoPSet.jetptBinning = cms.vdouble(20.,30.,40.,50.,60.,65.,68.,70.,72.,74.,76.,78.,80.,82.,84.,86.,88.,90.,92.,94.,100.,120.,170.,220.,300.,400.) hltJet_HT430_DisplacedDijet80_DisplacedTrack_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT430_DisplacedDijet80_DisplacedTrack_v*") hltJet_HT430_DisplacedDijet80_DisplacedTrack_Prommonitoring.ispfjettrg = cms.bool(False) hltJet_HT430_DisplacedDijet60_DisplacedTrack_Prommonitoring.iscalojettrg = cms.bool(True) hltJet_HT550_DisplacedDijet60_Inclusive_Prommonitoring = hltJetMETmonitoring.clone() hltJet_HT550_DisplacedDijet60_Inclusive_Prommonitoring.jetSrc = cms.InputTag("ak4CaloJets") hltJet_HT550_DisplacedDijet60_Inclusive_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/Jet/HLT_CaloJet_HT550_DisplacedDijet60_Inclusive') hltJet_HT550_DisplacedDijet60_Inclusive_Prommonitoring.ptcut = cms.double(20) hltJet_HT550_DisplacedDijet60_Inclusive_Prommonitoring.histoPSet.jetptBinning = cms.vdouble(20.,26.,30.,35.,40.,45.,50.,52.,53.,54.,56.,58.,60.,62.,64.,66.,68.,70.,72.,75.,80.,100.,120.,170.,220.,300.,400.) hltJet_HT550_DisplacedDijet60_Inclusive_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT550_DisplacedDijet60_Inclusive_v*") hltJet_HT550_DisplacedDijet60_Inclusive_Prommonitoring.ispfjettrg = cms.bool(False) hltJet_HT550_DisplacedDijet60_Inclusive_Prommonitoring.iscalojettrg = cms.bool(True) hltJet_HT550_DisplacedDijet80_Inclusive_Prommonitoring = hltJetMETmonitoring.clone() hltJet_HT550_DisplacedDijet80_Inclusive_Prommonitoring.jetSrc = cms.InputTag("ak4CaloJets") hltJet_HT550_DisplacedDijet80_Inclusive_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/Jet/HLT_CaloJet_HT550_DisplacedDijet80_Inclusive') hltJet_HT550_DisplacedDijet80_Inclusive_Prommonitoring.ptcut = cms.double(20) hltJet_HT550_DisplacedDijet80_Inclusive_Prommonitoring.histoPSet.jetptBinning = cms.vdouble(20.,30.,40.,50.,60,65,68,70,72,74,76,78,80,82,84,86,88,90,92,94,100,120,170,220,300,400) hltJet_HT550_DisplacedDijet80_Inclusive_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT550_DisplacedDijet80_Inclusive_v*") hltJet_HT550_DisplacedDijet80_Inclusive_Prommonitoring.ispfjettrg = cms.bool(False) hltJet_HT550_DisplacedDijet80_Inclusive_Prommonitoring.iscalojettrg = cms.bool(True) hltJet_HT650_DisplacedDijet60_Inclusive_Prommonitoring = hltJetMETmonitoring.clone() hltJet_HT650_DisplacedDijet60_Inclusive_Prommonitoring.jetSrc = cms.InputTag("ak4CaloJets") hltJet_HT650_DisplacedDijet60_Inclusive_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/Jet/HLT_CaloJet_HT650_DisplacedDijet60_Inclusive') hltJet_HT650_DisplacedDijet60_Inclusive_Prommonitoring.ptcut = cms.double(20) hltJet_HT650_DisplacedDijet60_Inclusive_Prommonitoring.histoPSet.jetptBinning = cms.vdouble(20,26,30,35,40,45,50,52,53,54,56,58,60,62,64,66,68,70,72,75,80,100,120,170,220,300,400) hltJet_HT650_DisplacedDijet60_Inclusive_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT650_DisplacedDijet60_Inclusive_v*") hltJet_HT650_DisplacedDijet60_Inclusive_Prommonitoring.ispfjettrg = cms.bool(False) hltJet_HT650_DisplacedDijet60_Inclusive_Prommonitoring.iscalojettrg = cms.bool(True) hltJet_HT650_DisplacedDijet80_Inclusive_Prommonitoring = hltJetMETmonitoring.clone() hltJet_HT650_DisplacedDijet80_Inclusive_Prommonitoring.jetSrc = cms.InputTag("ak4CaloJets") hltJet_HT650_DisplacedDijet80_Inclusive_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/Jet/HLT_CaloJet_HT650_DisplacedDijet80_Inclusive') hltJet_HT650_DisplacedDijet80_Inclusive_Prommonitoring.ptcut = cms.double(20) hltJet_HT650_DisplacedDijet80_Inclusive_Prommonitoring.histoPSet.jetptBinning = cms.vdouble(20,30,40,50,60,65,68,70,72,74,76,78,80,82,84,86,88,90,92,94,100,120,170,220,300,400) hltJet_HT650_DisplacedDijet80_Inclusive_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT650_DisplacedDijet80_Inclusive_v*") hltJet_HT650_DisplacedDijet80_Inclusive_Prommonitoring.ispfjettrg = cms.bool(False) hltJet_HT650_DisplacedDijet80_Inclusive_Prommonitoring.iscalojettrg = cms.bool(True) hltJet_HT750_DisplacedDijet80_Inclusive_Prommonitoring = hltJetMETmonitoring.clone() hltJet_HT750_DisplacedDijet80_Inclusive_Prommonitoring.jetSrc = cms.InputTag("ak4CaloJets") hltJet_HT750_DisplacedDijet80_Inclusive_Prommonitoring.FolderName = cms.string('HLT/EXO/DisplacedJet/Jet/HLT_CaloJet_HT750_DisplacedDijet80_Inclusive') hltJet_HT750_DisplacedDijet80_Inclusive_Prommonitoring.ptcut = cms.double(20) hltJet_HT750_DisplacedDijet80_Inclusive_Prommonitoring.histoPSet.jetptBinning = cms.vdouble(20,30,40,50,60,65,68,70,72,74,76,78,80,82,84,86,88,90,92,94,100,120,170,220,300,400) hltJet_HT750_DisplacedDijet80_Inclusive_Prommonitoring.numGenericTriggerEventPSet.hltPaths = cms.vstring("HLT_HT750_DisplacedDijet80_Inclusive_v*") hltJet_HT750_DisplacedDijet80_Inclusive_Prommonitoring.ispfjettrg = cms.bool(False) hltJet_HT750_DisplacedDijet80_Inclusive_Prommonitoring.iscalojettrg = cms.bool(True) exoHLTDisplacedJetmonitoring = cms.Sequence( hltHT_HT425_Prommonitoring +hltHT_HT400_DisplacedDijet40_DisplacedTrack_Prommonitoring +hltHT_HT430_DisplacedDijet40_DisplacedTrack_Prommonitoring +hltHT_HT430_DisplacedDijet60_DisplacedTrack_Prommonitoring +hltHT_HT430_DisplacedDijet80_DisplacedTrack_Prommonitoring +hltHT_HT550_DisplacedDijet60_Inclusive_Prommonitoring +hltHT_HT550_DisplacedDijet80_Inclusive_Prommonitoring +hltHT_HT650_DisplacedDijet60_Inclusive_Prommonitoring +hltHT_HT650_DisplacedDijet80_Inclusive_Prommonitoring +hltHT_HT750_DisplacedDijet80_Inclusive_Prommonitoring +hltJet_HT400_DisplacedDijet40_DisplacedTrack_Prommonitoring +hltJet_HT430_DisplacedDijet40_DisplacedTrack_Prommonitoring +hltJet_HT430_DisplacedDijet60_DisplacedTrack_Prommonitoring +hltJet_HT430_DisplacedDijet80_DisplacedTrack_Prommonitoring +hltJet_HT550_DisplacedDijet60_Inclusive_Prommonitoring +hltJet_HT550_DisplacedDijet80_Inclusive_Prommonitoring +hltJet_HT650_DisplacedDijet60_Inclusive_Prommonitoring +hltJet_HT650_DisplacedDijet80_Inclusive_Prommonitoring +hltJet_HT750_DisplacedDijet80_Inclusive_Prommonitoring )
[ 11748, 48849, 14055, 13, 36301, 7248, 13, 16934, 355, 269, 907, 198, 198, 6738, 360, 48, 44, 28657, 13, 48344, 13, 6535, 35479, 62, 66, 12463, 1330, 289, 2528, 6535, 41143, 278, 198, 6738, 360, 48, 44, 28657, 13, 48344, 13, 42273, 3...
2.470633
6,640
import numpy as np from scipy import special from numpy import linalg as LA # noisy max '''some LDP primitives''' # stochastic rounding (Duchi et al.) # piecewise mechanism (Wang et al.) # square wave (Li et al.)
[ 11748, 299, 32152, 355, 45941, 198, 198, 6738, 629, 541, 88, 1330, 2041, 198, 6738, 299, 32152, 1330, 300, 1292, 70, 355, 9131, 628, 628, 198, 2, 31210, 3509, 628, 198, 7061, 6, 11246, 406, 6322, 2684, 20288, 7061, 6, 628, 198, 2, ...
2.935897
78
import pytest from db.models.job_type import JobType @pytest.fixture @pytest.fixture
[ 11748, 12972, 9288, 198, 198, 6738, 20613, 13, 27530, 13, 21858, 62, 4906, 1330, 15768, 6030, 628, 198, 31, 9078, 9288, 13, 69, 9602, 628, 198, 31, 9078, 9288, 13, 69, 9602, 198 ]
2.727273
33
import pickle ###############################################################################
[ 11748, 2298, 293, 198, 198, 29113, 29113, 7804, 4242, 21017 ]
9.4
10
# -*- coding: utf-8 -*- from setuptools import setup, Extension packages = [ "swig_ex2", ] ext_modules = [ Extension( name="_swig_ex2", sources=["ex2.c", "ex2_wrap.c"], ), ] setup( name="swig_ex2", version="1.0.0", description="SWIG Example2", ext_modules=ext_modules, packages=packages, package_dir={"swig_ex2": ""}, )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 27995, 198, 198, 43789, 796, 685, 198, 197, 1, 2032, 328, 62, 1069, 17, 1600, 198, 60, 198, 198, 2302, 62, 18170, 796, 685, ...
2.181818
154
import hashlib import logging import os import threading import time from tkinter import * import cv2 import numpy as np from PIL import Image, ImageTk from src.ImageProcessing.contouring import cnt_from_img, save_contour, save_image class ResizingImageCanvas(Canvas): """ Customized Canvas that can handle dynamic image resizing and displays for slice contours. """ def __init__(self, parent=None, image=None, dicom_manager=None, **kwargs): """ Initializer :param parent: The parent to this tk Element :param image: The image to load :param dicom_manager: The DicomManager instance to assign to this class :param kwargs: Keyword arguments to pass to parent """ Canvas.__init__(self, **kwargs) self.parent = parent self.dm = dicom_manager self.logger = logging.getLogger(__name__) # Configure key and mouse bindings self.bind("<Key>", self.keydispatch) self.bind("<Configure>", self.on_resize) self.bind("<Button-1>", self.create_point) self.bind("<Button-3>", self.plot_points) self.bind("<Button-2>", self.toggle_smoothing) self.configure(cursor="crosshair red") self.configure() # Configure window size self.height = self.winfo_reqheight() self.width = self.winfo_reqwidth() # Configure contour parameters self.user_points = [] self.spline = 0 self.new_point = False self.user_line_tag = "usr_line" self.user_point_tag = "usr_point" self.contour_line_tag = "cnt_line" self.contour_point_tag = "cnt_point" self.contours = None self.curr_contour = 0 self.cnt_points = [] self.contour_image = None self.contour_photo = None # Configure image parameters self.image_path = "" self.image_folder = "" self.image_names = [] self.image_idx = 0 self.image = None self.photo = None # Configure ROI parameters self.roi = None self.roi_set = False self.cnt_img = None self.thresh_val = 70 self.ready = False self.set_image(image) def keydispatch(self, event): """ Receives key events and chooses the appropriate action. :param event: The key event to process """ self.logger.debug("User pressed: '{}'".format(event.keysym)) if event.keysym == "Right": self.update_contour_idx(1) if event.keysym == "Left": self.update_contour_idx(-1) if event.keysym == "Down": self.export_contour(self.curr_contour) if event.keysym == "a": self.logger.info("Current image: {}".format(self.image_idx)) self.update_image_idx(-1) if event.keysym == "d": self.logger.info("Current image: {}".format(self.image_idx)) self.update_image_idx(1) if event.keysym == "x": self.clear_points() if event.keysym == "c": self.apply_corrections() if event.keysym == "equal" or event.keysym == "plus": self.update_thresh(1) if event.keysym == "minus": self.update_thresh(-1) if event.keysym == "r": self.activate_roi() def activate_roi(self): """ Activates the region of interest that the user selected. """ img_arr = self.dm.get_image_array(self.image_idx) self.roi = cv2.selectROI( cv2.cvtColor(np.asarray(img_arr, np.uint8), cv2.COLOR_GRAY2BGR), False ) self.extract_roi(img_arr) def extract_roi(self, img_arr): """ Extracts the ROI from the provided image array and sets it as this canvas's image. :param img_arr: An OpenCV image array """ r = self.roi (x, y, w, h) = r if not x == y == w == h == 0: self.roi_set = True im_crop = img_arr[ int(r[1]) : int(r[1] + r[3]), int(r[0]) : int(r[0] + r[2]) ] img = Image.fromarray(im_crop) self.image_idx %= self.dm.get_num_images() self.set_image(img) def update_image_idx(self, direction): """ Updates the image index when a user switches image. :param direction: An integer representing whether or not we're moving forward or backward """ self.clear_points() self.curr_contour = -1 self.image_idx += direction # Use images if we don't have DicomManager if self.dm is None: path = os.path.join(self.image_folder, self.image_names[self.image_idx]) self.image_idx %= len(self.image_names) self.open_image(path) else: img_arr = self.dm.get_image_array(self.image_idx) if self.roi_set: self.extract_roi(img_arr) else: img = Image.fromarray(img_arr) self.image_idx %= self.dm.get_num_images() self.set_image(img) self.parent.update_slice_label(self.image_idx) def update_contour_idx(self, direction): """ Updates the visible contour on user input. :param direction: An integer representing whether or not we're incrementing or decrementing """ self.logger.debug("Current contour: {}".format(self.curr_contour)) valid_contour = 0 <= self.curr_contour + direction < len(self.contours) - 1 if valid_contour: self.curr_contour += direction self.draw_contour(self.curr_contour) def open_image(self, path): """ Opens the image at the provided path for display. :param path: The path to the image. """ self.focus() self.image_path = path new_image = Image.open(self.image_path) self.set_image(new_image) def set_image(self, image): """ Sets up a PhotoImage from the provided PIL image so the Canvas can display. :param image: An Image """ if image is not None: self.image = image self.photo = ImageTk.PhotoImage(self.image) self.width = self.photo.width() self.height = self.photo.height() thread = threading.Thread(target=self.update_contours, args=()) thread.start() self.create_image(0, 0, anchor=NW, image=self.photo) else: self.create_image(0, 0, anchor=NW) self.config(width=self.width, height=self.height) self.parent.config(width=self.width, height=self.height) def update_thresh(self, delta_thresh): """ Update the current contouring threshold. :param delta_thresh: Amount and direction to change the contour by. """ self.thresh_val += delta_thresh self.parent.update_thresh_label(self.thresh_val) self.update_contours() def set_folder(self, folder): """ Updates the folder the the Canvas reads Images from. :param folder: A path to the folder """ self.image_folder = folder self.image_names = os.listdir(folder) for name in self.image_names: if os.path.isdir(os.path.join(folder, name)): self.image_names.remove(name) self.image_names.sort() self.open_image( os.path.join(self.image_folder, self.image_names[self.image_idx]) ) def update_contours(self): """ Updates the computed contours for the current Image. """ self.ready = False self.configure(cursor="clock") self.contours = [] self.curr_contour = 0 self.contours = cnt_from_img(self.image, self.thresh_val) self.logger.debug("Got {} contours".format(len(self.contours))) self.ready = True self.configure(cursor="crosshair red") def apply_corrections(self): """ Updates the image given the user's inputted corrections and updates the contours. """ point_list = self.get_point_list(self.user_points) point_list_len = len(point_list) im = None for i in range(point_list_len): j = i + 1 self.logger.debug( "i: {}, j: {}, point_list_len: {}".format(i, j, point_list_len) ) if j <= point_list_len - 1: self.logger.debug( "Drawing points {} and {}".format(point_list[i], point_list[j]) ) im = np.array(self.image.convert("RGB")) im = cv2.line( im, point_list[i], point_list[j], thickness=2, color=(255, 255, 255), lineType=cv2.LINE_AA, ) self.image = Image.fromarray(im) self.update_contours() def draw_contour(self, cnt_idx): """ Overlays the contour at cnt_idx over the currently displayed Image. :param cnt_idx: The contour to draw """ if self.ready: self.delete(self.contour_point_tag) self.delete(self.contour_line_tag) self.cnt_points.clear() for point in self.contours[cnt_idx]: point_x = point[0][0] point_y = point[0][1] self.cnt_points.append(point_x) self.cnt_points.append(point_y) kwargs = { "tags": self.contour_line_tag, "width": 2, "fill": "red", "joinstyle": "round", "capstyle": "round", } self.itemconfigure(self.contour_line_tag, smooth=1) self.create_line(self.cnt_points, kwargs) else: self.contours_not_ready() def export_contour(self, cnt_idx): """ Exports the current contour profile to file. :param cnt_idx: The contour to write """ if self.dm: new_path = self.dm.get_output_path() else: # Save the contour to an image by itself path_segs = self.image_path.split("/") new_path = "/".join(path_segs[:-1]) new_path += "/saved_contours/" time_hash = hashlib.sha1() time_hash.update(str(time.time()).encode("utf-8")) file_name_hash = "{}".format(time_hash.hexdigest()[:10]) scaling_factor = self.dm.get_scaling_factor() contour_img_path = os.path.join( new_path, "{}-{}-{}-{}-{}".format( file_name_hash, scaling_factor, self.image_idx, self.curr_contour, self.thresh_val, ), ) contour_string_path = os.path.join( new_path, "{}-{}-{}-{}-{}.txt".format( file_name_hash, scaling_factor, self.image_idx, self.curr_contour, self.thresh_val, ), ) try: os.mkdir(new_path) except OSError: # directory already exists pass thread = threading.Thread( target=save_contour, args=(self.contours[cnt_idx], self.width, self.height, contour_img_path), ) thread.start() # Save a background image for more processing bkg_save_path = contour_img_path + "-bkg" thread = threading.Thread(target=save_image, args=(self.image, bkg_save_path)) thread.start() file = open(contour_string_path, "w") np.set_printoptions(threshold=np.nan) file.write(np.array2string(self.contours[cnt_idx], separator=",")) file.close() @staticmethod def contours_not_ready(): """ Indicator to show the user that the contours aren't computed yet. """ filewin = Toplevel() label = Label(filewin, text="Contours not ready") label.pack() def create_point(self, event): """ Displays and stores the point from the user's mouse click event. :param event: The click event for the user's action """ self.focus_set() self.new_point = True self.create_oval( event.x, event.y, event.x + 1, event.y + 1, outline="red", fill="red", tag=self.user_point_tag, ) self.user_points.append(event.x) self.user_points.append(event.y) def plot_points(self): """ Plots the connections between the points that the user selected. """ if self.new_point and len(self.user_points) > 2: self.delete(self.user_line_tag) self.spline = 0 self.create_line( self.user_points, tags=self.user_line_tag, width=2, fill="red", joinstyle="round", capstyle="round", ) self.new_point = False def toggle_smoothing(self): """ Toggles between smooth and connect the dot plots for the connections between points. :return: """ if self.spline == 0: self.itemconfigure(self.user_line_tag, smooth=1) self.spline = 1 elif self.spline == 1: self.itemconfigure(self.user_line_tag, smooth=0) self.spline = 0 def clear_points(self): """ Clears the points that the user selected. """ self.user_points.clear() self.delete(self.user_point_tag) self.delete(self.user_line_tag) @staticmethod def get_point_list(point_list): """ Zips the lists of x and y coordinates. :param point_list: The list of points that the user input :return: A list of tuples representing x/y pairs """ x_list = point_list[0::2] y_list = point_list[1::2] point_list = list(zip(x_list, y_list)) return point_list
[ 11748, 12234, 8019, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 4704, 278, 198, 11748, 640, 198, 6738, 256, 74, 3849, 1330, 1635, 198, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 350, 4146, 1330, 7412, ...
2.005046
7,134
# -*- coding:utf-8 -*- from __future__ import absolute_import, unicode_literals, print_function from setuptools import setup, find_packages # todo: add install_requires and test_requires setup(name='hookman', version='0.1.2', packages=find_packages(), test_requires = ['py.test>=2.92', 'mock'], install_requires = ['flask>=0.6.0'], entry_points={ 'console_scripts': ['hookman = hookman.manage:main'] }, author='zhanglun', author_email='zhanglun.me@gmail.com', description='this is a easy webhook manage tool for github webhook, developed by TDD', license='Apache', keywords='webhook github tool', url='https://github.com/mrzhangboss/hookman')
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 28000, 1098, 62, 17201, 874, 11, 3601, 62, 8818, 198, 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198...
2.583333
276
from app import app """ If Twisted's WSGI server is not desired in favor for solutions like uwsgi or gunicorn or anything similar, the `crochet` library can execute Twisted code in an isolated thread. Be EXTREMELY careful with this solution! Python's WSGI servers generally use threads, as does `crochet`, and/or processes which means there might be situations where one thread may spawn multiple threads. It's up to the developers to account for intricacies hen dealing with multi threaded/process applications. Local usage: python flask_crochet.py Gunicorn usage: gunicorn -b 0.0.0.0:9000 flask_crochet:app """ # @app.route('/greeting') # @app.route('/greeting/<name>') # def greeting(name='World'): # return 'Hello %s!' % (name) if __name__ == "__main__": # app = factory.create_app(celery=app.celery) print("inside myproject file") app.run(host='0.0.0.0')
[ 6738, 598, 1330, 598, 198, 37811, 198, 1532, 40006, 338, 25290, 18878, 4382, 318, 407, 10348, 287, 2661, 329, 8136, 588, 334, 18504, 12397, 393, 2485, 291, 1211, 393, 1997, 2092, 11, 198, 1169, 4600, 19915, 20043, 63, 5888, 460, 12260, ...
3.14539
282
# -*- coding: utf-8 -*- # Copyright (c) 2010-2017 Tuukka Turto # # 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. # flake8: noqa """ Package for events that are used to communicate between creatures and UI """ from .combat import (new_attack_hit_event, new_attack_miss_event, new_attack_nothing_event) from .damage import (damage_triggered, damage_added, damage_ended) from .dig import new_dig_event from .death import new_death_event from .effect import new_effect_added_event, new_effect_removed_event from .error import new_error_event from .event import (e_event_type, e_level, e_location, e_character, e_old_spirit, e_new_spirit, e_target, e_damage, e_deceased, e_new_items, e_new_characters, e_item, e_new_character, e_destroyed_characters, e_old_location, e_direction, e_attacker, e_old_hit_points, e_new_hit_points, e_trap, empty_event, e_healing) from .healing import (new_heal_triggered_event, new_heal_added_event, new_heal_ended_event) from .hitpoints import new_hit_points_changed_event from .inventory import (new_pick_up_event, new_drop_event, new_equip_event, new_unequip_event) from .metamorphosis import new_metamorphosis_event from .mitosis import new_mitosis_event from .move import new_move_event from .new_level import new_level_event from .perception import new_notice_event, new_lose_focus_event from .poison import (poison_triggered, poison_added, poison_ended) from .spirit import new_spirit_points_changed_event from .trap import new_trap_placed_event, damage_trap_triggered
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 15069, 357, 66, 8, 3050, 12, 5539, 16749, 2724, 4914, 3831, 1462, 198, 2, 220, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048,...
2.907205
916
# TCP Server from socket import socket, AF_INET, SOCK_STREAM from Crypto.PublicKey import RSA from Crypto.Cipher import AES, PKCS1_OAEP from Crypto.Util import Counter import os class Server: ''' Shell Server ''' def str_xor(self, s1, s2): ''' Encrypt/Decrypt function ''' return "".join([chr(ord(c1) ^ ord(c2)) for (c1,c2) in zip(s1,s2)]) def encrypt_AES_KEY(self, KEY): ''' Encrypt using RSA public key ''' # read pem file or embed key to script publickey = open('src/public.pem', 'r').read() encryptor = RSA.importKey(publickey) cipher = PKCS1_OAEP.new(encryptor) encriptedData = cipher.encrypt(KEY) return encriptedData def encrypt(self, message): ''' AES encrypt algorithm using CTR mode, takes bytes variable ''' iv = os.urandom(16) ctr = Counter.new(128, initial_value=int.from_bytes(iv, byteorder='big')) encrypto = AES.new(self.key, AES.MODE_CTR, counter=ctr) return iv + encrypto.encrypt(message) def decrypt(self, message): ''' AES decrypt algorithm using CTR mode, takes bytes variable ''' iv = message[:16] ctr = Counter.new(128, initial_value=int.from_bytes(iv, byteorder='big')) decrypto = AES.new(self.key, AES.MODE_CTR, counter=ctr) return decrypto.decrypt(message[16:]) def transfer(self, conn, command): ''' receive transfer file ''' conn.send(self.encrypt(command.encode())) filename = command.split()[-1] if filename == command: filename = 'screen.jpg' f = open(filename, 'wb') while True: bits = conn.recv(1024) if b'Unable to find out the file' in bits: print('[!] Unable to find out the file') break if bits == b'DONE': print('[*] Transfer completed ') f.close() break f.write(bits) def connect(self): ''' listen for client connection ''' s = socket(AF_INET, SOCK_STREAM) # define the server IP and the listening port s.bind((self.IP, self.PORT)) # define the backlog size, since we are expecting a single connection from a single # target we will listen to one connection s.listen(1) print(f'[*] Listening for incoming TCP connection on port {self.PORT}') # accept() function will return the connection object ID (conn) and will return the client(target) IP address and source # port in a tuple format (IP,port) conn, addr = s.accept() print('[+] Connection Received: ', addr) # send encrypted key conn.send(self.encrypt_AES_KEY(self.key)) self.USERNAME = self.decrypt(conn.recv(1024)).decode() while True: # Get user input and store it in command variable command = input(f"{self.USERNAME}> ") if 'terminate' in command: # If we got terminate command, inform the client and close the connect and break the loop conn.send(self.encrypt('terminate'.encode())) conn.close() break elif 'grab' in command or 'screenshoot' in command: # if we received grab keyword from the user input, then this is an indicator for # file transfer operation, hence we will call transfer function self.transfer(conn, command) else: # Otherwise we will send the command to the target conn.send(self.encrypt(command.encode())) # and print the result that we got back print(self.decrypt(conn.recv(1024)).decode()) if __name__ == "__main__": main()
[ 2, 23633, 9652, 201, 198, 6738, 17802, 1330, 17802, 11, 12341, 62, 1268, 2767, 11, 311, 11290, 62, 2257, 32235, 201, 198, 6738, 36579, 13, 15202, 9218, 1330, 42319, 201, 198, 6738, 36579, 13, 34, 10803, 1330, 34329, 11, 29673, 7902, 1...
2.195177
1,783
# File: infrastructure_service.py # # Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) # from .ds_base_service import DSBaseService from .ds_find_service import DSFindService from ..model.infrastructure import Infrastructure
[ 2, 9220, 25, 6884, 62, 15271, 13, 9078, 198, 2, 198, 2, 49962, 739, 24843, 362, 13, 15, 357, 5450, 1378, 2503, 13, 43073, 13, 2398, 14, 677, 4541, 14, 43, 2149, 24290, 12, 17, 13, 15, 13, 14116, 8, 198, 2, 198, 198, 6738, 764,...
3.269231
78
# this Python file uses the following encoding: utf-8 import os # to execute shall cmds import time # to sleep() import redis # to interface with the queue of requests. installed with => python3 -m pip install redis import requests # because if's simpler to use for an http query than the default python . installed with python3 -m pip install requests #RSSI=$(grep wlan0 /proc/net/wireless | awk '{print $4}' | tr -d '.') #root@mtbr00622:~# cat /proc/net/wireless #Inter-| sta-| Quality | Discarded packets | Missed | WE # face | tus | link level noise | nwid crypt frag retry misc | beacon | 22 # wlan0: 0000 49. -61. -256 0 0 0 0 0 0 #CHAN=$(iwlist wlan0 channel | grep Current | rev | tr -d ')' | awk '{print $1}' | rev) #root@mtbr00622:~# iwlist wlan0 channel | grep Current # Current Frequency:5.18 GHz (Channel 36) if __name__ == "__main__": run()
[ 2, 428, 11361, 2393, 3544, 262, 1708, 21004, 25, 3384, 69, 12, 23, 198, 198, 11748, 28686, 1303, 284, 12260, 2236, 23991, 82, 198, 11748, 640, 1303, 284, 3993, 3419, 198, 11748, 2266, 271, 1303, 284, 7071, 351, 262, 16834, 286, 7007, ...
2.534574
376
from django.core.urlresolvers import reverse from utilities.utils import CleanTestCase class ViewsTest(CleanTestCase): '''Tests for all the views in the events app''' fixtures = [ 'events.json' ] def test_event_page_view(self): '''Tests the context for the page that shows all the details about a certain event ''' resp = self.client.get(reverse('events:event', args=('event1',))) self.assertEqual(resp.status_code, 200) self.assertTrue(resp.context['event_page']) def test_no_event_view_return_404(self): '''Tests that if you request an event that doesn't exist a HTTP 404 error is returned ''' resp = self.client.get(reverse('events:event', args=('nope',))) self.assertEqual(resp.status_code, 404)
[ 6738, 42625, 14208, 13, 7295, 13, 6371, 411, 349, 690, 1330, 9575, 198, 198, 6738, 20081, 13, 26791, 1330, 5985, 14402, 20448, 198, 198, 4871, 29978, 14402, 7, 32657, 14402, 20448, 2599, 198, 197, 7061, 6, 51, 3558, 329, 477, 262, 500...
2.83908
261
""" Functions to transform firework model files to netCDF files """ import logging import os import sys import numpy as np import datetime import xarray as xr import click import smoke.utils.utilities as utilities from pathlib import Path from smoke.load.parsers import * logging.getLogger(__name__).addHandler(logging.NullHandler()) def firework_to_xr(firework_file): """ Loading and returning data from firework geotiff files as of file format including and previous to 2020/06/29 :param firework_file: path to raw firework data file, file name must have date as first 10 digits in form %Y%m%d%H :type firework_file: str :returns: xarray dataset with specs for GeographicalDataset :rtype: xr.Dataset """ parser = FireworkParser() return parser.parse_file(firework_file) @click.command(help=convert_firework.__doc__) @click.argument("firework_file", type=click.Path(exists=True)) @click.argument("output_directory", type=click.Path(writable=True)) @click.option( "-v", "--verbosity", default="WARNING", show_default=True, type=click.Choice(("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL")), help=""" Choose the logging level. Defaults to WARNING. WARNING, ERROR, and CRITICAL will only report when Murphy's law kicks in """, )
[ 37811, 198, 24629, 2733, 284, 6121, 2046, 1818, 2746, 3696, 284, 2010, 34, 8068, 3696, 198, 37811, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 4818, 8079, 198, 11748, 2124, 1874...
2.847134
471
from django.test import TestCase from django.core.urlresolvers import reverse from contact_updater import views api_data = { 'offices': [], 'public_liaison_email': None, 'foia_libraries': [{'url': 'http://www.amtrak.com/library'}], 'simple_processing_time': 1.0, 'name': 'AMTRAK', 'common_requests': [], 'phone': '202-906-3741', 'abbreviation': 'NRPC', 'request_form_url': None, 'agency_slug': 'amtrak', 'state': 'DC', 'slug': 'amtrak', 'description': 'Test Description', 'toll_free_phone': None, 'complex_processing_time': 13.5, 'no_records_about': ['test 1', 'test 2'], 'street': '60 Massachusetts Avenue, NE', 'agency_name': 'AMTRAK', 'zip_code': '20002', 'person_name': None, 'office_url': 'http://www.amtrak.com/test', 'keywords': None, 'emails': ['foiarequests@amtrak.com', 'foiarequests@amtrak.com'], 'address_lines': ['Sharron H. Hawkins', 'FOIA Officer'], 'is_a': 'agency', 'public_liaison_name': 'Sharron H. Hawkins', 'public_liaison_phone': '202-906-3740', 'city': 'Washington', 'fax': '202-906-3285' }
[ 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 198, 6738, 42625, 14208, 13, 7295, 13, 6371, 411, 349, 690, 1330, 9575, 198, 198, 6738, 2800, 62, 929, 67, 729, 1330, 5009, 628, 198, 15042, 62, 7890, 796, 1391, 198, 220, 220, 220, 7...
2.319672
488
""" Module for creating mask features Credits: Copyright (c) 2017-2022 Matej Aleksandrov, Matej Bati膷, Grega Mil膷inski, Domagoj Korais, Matic Lubej (Sinergise) Copyright (c) 2017-2022 沤iga Luk拧i膷, Devis Peressutti, Nejc Vesel, Jovan Vi拧nji膰, An啪e Zupanc (Sinergise) Copyright (c) 2019-2020 Jernej Puc, Lojze 沤ust (Sinergise) Copyright (c) 2017-2019 Bla啪 Sovdat, Andrej Burja (Sinergise) Copyright (c) 2018-2019 Johannes Schmid (GeoVille) This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from typing import Union, Callable import numpy as np from eolearn.core import EOTask, ZipFeatureTask class JoinMasksTask(ZipFeatureTask): """Joins together masks with the provided logical operation.""" def __init__(self, input_features, output_feature, join_operation: Union[str, Callable] = "and"): """ :param input_features: Mask features to be joined together. :param output_feature: Feature to which to save the joined mask. :param join_operation: How to join masks. Supports `'and'`, `'or'`, `'xor'`, or a `Callable` object. """ input_features = self.parse_features(input_features) output_feature = self.parse_feature(output_feature) if isinstance(join_operation, str): methods = {"and": np.logical_and, "or": np.logical_or, "xor": np.logical_xor} if join_operation not in methods: raise ValueError( f"Join operation {join_operation} is not a viable choice. For operations other than {list(methods)}" "the user must provide a `Callable` object." ) self.join_method = methods[join_operation] else: self.join_method = join_operation super().__init__(input_features, output_feature) def zip_method(self, *masks: np.ndarray) -> np.ndarray: """Joins masks using the provided operation""" final_mask, *masks = masks for mask in masks: final_mask = self.join_method(final_mask, mask) return final_mask class MaskFeatureTask(EOTask): """Masks out values of a feature using defined values of a given mask feature. As an example, it can be used to mask the data feature using values from the Sen2cor Scene Classification Layer (SCL). Contributor: Johannes Schmid, GeoVille Information Systems GmbH, 2018 """ def __init__(self, feature, mask_feature, mask_values, no_data_value=np.nan): """ :param feature: A feature to be masked with optional new feature name :type feature: (FeatureType, str) or (FeatureType, str, str) :param mask_feature: Masking feature. Values of this mask will be used to mask values of `feature` :type mask_feature: (FeatureType, str) :param mask_values: List of values of `mask_feature` to be used for masking `feature` :type mask_values: list of int :param no_data_value: Value that replaces masked values in `feature`. Default is `NaN` :type no_data_value: float :return: The same `eopatch` instance with a masked array """ self.renamed_feature = self.parse_renamed_feature(feature) self.mask_feature = self.parse_feature(mask_feature) self.mask_values = mask_values self.no_data_value = no_data_value if not isinstance(self.mask_values, list): raise ValueError("Incorrect format or values of argument 'mask_values'") def execute(self, eopatch): """Mask values of `feature` according to the `mask_values` in `mask_feature` :param eopatch: `eopatch` to be processed :return: Same `eopatch` instance with masked `feature` """ feature_type, feature_name, new_feature_name = self.renamed_feature mask_feature_type, mask_feature_name = self.mask_feature data = np.copy(eopatch[feature_type][feature_name]) mask = eopatch[mask_feature_type][mask_feature_name] for value in self.mask_values: data = apply_mask(data, mask, value, self.no_data_value, feature_type, mask_feature_type) eopatch[feature_type][new_feature_name] = data return eopatch def apply_mask(data, mask, old_value, new_value, data_type, mask_type): """A general masking function :param data: A data feature :type data: numpy.ndarray :param mask: A mask feature :type mask: numpy.ndarray :param old_value: An old value in data that will be replaced :type old_value: float :param new_value: A new value that will replace the old value in data :type new_value: float :param data_type: A data feature type :type data_type: FeatureType :param mask_type: A mask feature type :type mask_type: FeatureType """ if not (data_type.is_spatial() and mask_type.is_spatial()): raise ValueError("Masking with non-spatial data types is not yet supported") if data_type.is_timeless() and mask_type.is_temporal(): raise ValueError("Cannot mask timeless data feature with time dependent mask feature") if data.shape[-3:-1] != mask.shape[-3:-1]: raise ValueError("Data feature and mask feature have different spatial dimensions") if mask_type.is_temporal() and data.shape[0] != mask.shape[0]: raise ValueError("Data feature and mask feature have different temporal dimensions") if mask.shape[-1] == data.shape[-1]: data[..., mask == old_value] = new_value elif mask.shape[-1] == 1: data[..., mask[..., 0] == old_value, :] = new_value else: raise ValueError( f"Mask feature has {mask.shape[-1]} number of bands while data feature has {data.shape[-1]} number of bands" ) return data
[ 37811, 198, 26796, 329, 4441, 9335, 3033, 198, 198, 42855, 25, 198, 15269, 357, 66, 8, 2177, 12, 1238, 1828, 24787, 73, 9300, 591, 392, 18657, 11, 24787, 73, 6577, 72, 46195, 11, 8547, 64, 4460, 46195, 21141, 11, 9666, 3839, 73, 509...
2.651481
2,195
# -*- coding: utf-8 -*- import locale ############## Manejo de archivos ############## with open("5_with.py", "r", encoding='utf-8') as file: #With permite cerrar el archivo automaticamente cuando se ejecute el bloque print(locale.getpreferredencoding()) # LANG environment variable print(locale.setlocale(locale.LC_ALL, ''))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 36693, 198, 198, 7804, 4242, 2235, 42736, 7639, 390, 3934, 452, 418, 1303, 7804, 4242, 2, 198, 198, 4480, 1280, 7203, 20, 62, 4480, 13, 9078, 1600, 366, 81, 160...
2.75
124
import sys from PyQt5.QtWidgets import * if __name__=='__main__': main()
[ 11748, 25064, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 54, 312, 11407, 1330, 1635, 628, 198, 361, 11593, 3672, 834, 855, 6, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 628 ]
2.285714
35
"""Import handler tests.""" from pathlib import Path from marshpy.core.constants import UNDEFINED from marshpy.core.errors import ErrorCode from marshpy.tag_handlers.import_handler import ImportHandler from tests.tag_handlers.path_handler_helpers import check_path_tag from tests.tag_handlers.path_handler_helpers import check_path_tag_error def test_import_tag_handler(datadir: Path) -> None: """Import tag should load file if set correctly.""" check_path_tag( ImportHandler, '!import file_1.yaml', ['file_1'], roots=[datadir] ) check_path_tag( ImportHandler, '!try-import file_1.yaml', ['file_1'], roots=[datadir] ) root_1 = datadir / 'test_ignore_dir' / 'root_1' root_2 = datadir / 'test_ignore_dir' / 'root_2' check_path_tag( ImportHandler, '!import file_2.yaml', ['file_2'], roots=[root_1, root_2] ) # Shouldn't emit an error check_path_tag(ImportHandler, '!try-import doesnt_exists', UNDEFINED) check_path_tag( ImportHandler, '!import file_1.yaml', ['file_1'], allow_relative=True, location=datadir / 'parent_file.yaml' ) check_path_tag_error( ImportHandler, '!import file_1.yaml', ErrorCode.IMPORT_NOT_FOUND, allow_relative=False, location=str(datadir / 'parent_file.yaml') ) check_path_tag( ImportHandler, '!import {}'.format(datadir / 'file_1.yaml'), ['file_1'] ) def test_import_tag_handler_error_handling(datadir: Path) -> None: """Import tag handler shoud correctly handle errors.""" check_path_tag_error( ImportHandler, '!import []', ErrorCode.UNEXPECTED_NODE_TYPE ) check_path_tag_error( ImportHandler, '!import {}', ErrorCode.UNEXPECTED_NODE_TYPE ) check_path_tag_error( ImportHandler, '!import doest_exists', ErrorCode.IMPORT_NOT_FOUND, roots=[datadir] ) check_path_tag_error( ImportHandler, '!import yaml_error.yaml', ErrorCode.VALUE_ERROR, roots=[datadir] )
[ 37811, 20939, 21360, 5254, 526, 15931, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 6738, 22397, 9078, 13, 7295, 13, 9979, 1187, 1330, 4725, 7206, 20032, 1961, 198, 6738, 22397, 9078, 13, 7295, 13, 48277, 1330, 13047, 10669, 198, 6738, ...
2.153171
1,025
import abc import sys import typing from yadi import listeners SINGLETON = 'singleton' PROTOTYPE = 'prototype'
[ 11748, 450, 66, 198, 11748, 25064, 198, 11748, 19720, 198, 198, 6738, 331, 9189, 1330, 22054, 628, 628, 198, 50, 2751, 2538, 11357, 796, 705, 12215, 10565, 6, 198, 4805, 2394, 2394, 56, 11401, 796, 705, 38124, 6, 198 ]
2.974359
39
#!/usr/bin/env python """ Copyright (c) 2012 The Ohio State University. 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 subprocess import sys CURRENT_DIR = os.getcwd() FRONTEND_DIR = 'SQL2XML' BACKEND_DIR = 'XML2MapReduce' EXEC_DIR = 'bin' if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 198, 220, 220, 15069, 357, 66, 8, 2321, 383, 6835, 1812, 2059, 13, 628, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198...
3.152091
263
import numpy as np from collections import Counter from scipy import stats from util import *
[ 11748, 299, 32152, 355, 45941, 198, 6738, 17268, 1330, 15034, 198, 6738, 629, 541, 88, 1330, 9756, 198, 6738, 7736, 1330, 1635 ]
4.227273
22
#!/usr/bin/python3 -S # -*- coding: utf-8 -*- """ `Unit tests for cargo.clients.create_pool` --路--路--路--路--路--路--路--路--路--路--路--路--路--路--路--路--路--路--路--路--路--路--路--路--路--路-- 2016 Jared Lunde 漏 The MIT License (MIT) http://github.com/jaredlunde """ import unittest from multiprocessing import cpu_count from cargo.clients import db, create_pool, local_client, PostgresPool if __name__ == '__main__': # Unit test unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 18, 532, 50, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 220, 220, 220, 4600, 26453, 5254, 329, 15892, 13, 565, 2334, 13, 17953, 62, 7742, 63, 198, 438, 9...
2.326425
193
import polygon2cog as p2c import unittest import numpy as np if __name__ == '__main__': unittest.main()
[ 11748, 7514, 14520, 17, 66, 519, 355, 279, 17, 66, 198, 11748, 555, 715, 395, 198, 11748, 299, 32152, 355, 45941, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 220, 220, 220, 220, 555, 715, ...
2.375
48
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import tensorflow as tf from tensorflow.contrib.seq2seq.python.ops import basic_decoder from tensorflow.python.framework import ops from tensorflow.python.ops import nn_ops from tensorflow.python.util import nest class BasicDecoder(basic_decoder.BasicDecoder): """Basic sampling decoder (for MMI).""" #''' @property @property def step(self, time, inputs, state, name=None): """Perform a decoding step. Args: time: scalar `int32` tensor. inputs: A (structure of) input tensors. state: A (structure of) state tensors and TensorArrays. name: Name scope for any created operations. Returns: `(outputs, next_state, next_inputs, finished)`. """ with ops.name_scope(name, "BasicCustomDecoderStep", (time, inputs, state)): cell_outputs, cell_state = self._cell(inputs, state) if self._output_layer is not None: cell_outputs = self._output_layer(cell_outputs) # Calculate probabilities at each step step_log_probs = nn_ops.log_softmax(cell_outputs) sample_ids = self._helper.sample( time=time, outputs=cell_outputs, state=cell_state) (finished, next_inputs, next_state) = self._helper.next_inputs( time=time, outputs=cell_outputs, state=cell_state, sample_ids=sample_ids) outputs = BasicDecoderOutput(step_log_probs, cell_outputs, sample_ids) return (outputs, next_state, next_inputs, finished) ''' @property def output_size(self): # Return the cell output and the id return BasicDecoderOutput( rnn_output=self._rnn_output_size(), sample_id=self._helper.sample_ids_shape) @property def output_dtype(self): # Assume the dtype of the cell is the output_size structure # containing the input_state's first component's dtype. # Return that structure and the sample_ids_dtype from the helper. dtype = nest.flatten(self._initial_state)[0].dtype return BasicDecoderOutput( nest.map_structure(lambda _: dtype, self._rnn_output_size()), self._helper.sample_ids_dtype) def step(self, time, inputs, state, name=None): """Perform a decoding step. Args: time: scalar `int32` tensor. inputs: A (structure of) input tensors. state: A (structure of) state tensors and TensorArrays. name: Name scope for any created operations. Returns: `(outputs, next_state, next_inputs, finished)`. """ with ops.name_scope(name, "BasicDecoderStep", (time, inputs, state)): cell_outputs, cell_state = self._cell(inputs, state) if self._output_layer is not None: cell_outputs = self._output_layer(cell_outputs) sample_ids = self._helper.sample( time=time, outputs=cell_outputs, state=cell_state) (finished, next_inputs, next_state) = self._helper.next_inputs( time=time, outputs=cell_outputs, state=cell_state, sample_ids=sample_ids) outputs = BasicDecoderOutput(tf.zeros(tf.shape(sample_ids)[0]), cell_outputs, sample_ids) return (outputs, next_state, next_inputs, finished) '''
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 17268, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11192, 273, 11125,...
2.324271
1,508
import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.utils.spectral_norm as SpectralNorm
[ 11748, 10688, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 11748, 28034, 13, 20471, 13, 26791, 13, 4443, 1373, 62, 27237, 355,...
3.333333
45
""" Afterglow Core: AJAX API endpoints """ url_prefix = '/ajax/' from .app_authorizations import * from .tokens import * from .sessions import * from .initialize import * from .oauth2_providers import * from .oauth2_clients import * from .server_status import *
[ 37811, 198, 3260, 4743, 322, 7231, 25, 25347, 25922, 7824, 886, 13033, 198, 37811, 198, 198, 6371, 62, 40290, 796, 31051, 1228, 897, 14, 6, 198, 198, 6738, 764, 1324, 62, 9800, 4582, 1330, 1635, 198, 6738, 764, 83, 482, 641, 1330, 1...
2.988889
90