def _config_check(): from message import Messager from sys import path from copy import deepcopy from os.path import dirname # Reset the path to force config.py to be in the root (could be hacked # using __init__.py, but we can be monkey-patched anyway) orig_path = deepcopy(path) # Can't you empty in O(1) instead of O(N)? while path: path.pop() path.append(path_join(abspath(dirname(__file__)), '../..')) # Check if we have a config, otherwise whine try: import config del config except ImportError, e: path.extend(orig_path) # "Prettiest" way to check specific failure if e.message == 'No module named config': Messager.error(_miss_config_msg(), duration=-1) else: Messager.error(_get_stack_trace(), duration=-1) raise ConfigurationError
def _build_mod_list( mod_path: list[str], suffix: str, blacklist: list[str]) -> Generator[tuple[str, str], None, None]: """Build a list of modules. Add all the paths in mod_path to sys.path and return a list of all modules in sys.path ending in suffix. """ from sys import path as sys_path mod_path = [mod_path] if type(mod_path) is str else mod_path blacklist = [blacklist] if type(blacklist) is str else blacklist # Add suffix to all names in blacklist. blacklist.extend( [f"{name}{suffix}" for name in blacklist if not name.endswith(suffix)]) # Add the path of this file to the search path. mod_path.append(abspath(dirname(__file__))) # Add the path(s) in mod_path to sys.path so we can import from # them. for path in mod_path: if path not in sys_path: sys_path.extend((path, dirname(path.rstrip('/')))) def isdir_list(path: str) -> list[str]: """Return a list of files from path if path is a directory.""" return listdir(path) if isdir(path) else [] # Return a genorator list of modules ending in suffix in the mod_path(s). return ((path, name) for path in sys_path for name in isdir_list(path) if name not in blacklist and name.endswith(suffix))
def CT_Init(): """creat a new calltips windows""" global helpBuffer vim.command('silent botright new Python_CallTips_Windows') vim.command('set buftype=nofile') vim.command('set nonumber') vim.command('resize 5') vim.command('set noswapfile') helpBuffer = vim.current.buffer vim.command('wincmd p') #switch back window from sys import path path.extend(['.','..']) #add current path and parent path
def CT_Init(): """creat a new calltips windows""" global helpBuffer vim.command('silent botright new Python_CallTips') vim.command('set buftype=nofile') vim.command('set nonumber') vim.command('resize 5') vim.command('set noswapfile') helpBuffer = vim.current.buffer vim.command('wincmd p') #switch back window vim.command('autocmd CursorHold *.py python CT_ImportObject()') vim.command('set updatetime=5000') from sys import path path.extend(['.','..']) #add current path and parent path
def _build_mod_list(mod_path: list, suffix: str, blacklist: list) -> list: """ _build_mod_list(mod_path, suffix) -> Add all the paths in mod_path to sys.path and return a list of all modules in sys.path ending in suffix. """ from sys import path as sys_path mod_path = [mod_path] if type(mod_path) is str else mod_path blacklist = [blacklist] if type(blacklist) is str else blacklist # Add suffix to all names in blacklist. blacklist.extend(["%s%s" % (name, suffix) for name in blacklist if not name.endswith(suffix)]) # Add the path of this file to the search path. mod_path.append(os_abspath(os_dirname(__file__))) # Add the path(s) in mod_path to sys.path so we can import from # them. [sys_path.extend((path, os_dirname(path.rstrip("/")))) for path in mod_path if path not in sys_path] # Build the list of modules ending in suffix in the mod_path(s). mod_list = ( (path, name) for path in sys_path if os_isdir(path) for name in os_listdir(path) if name.endswith(suffix) and name not in blacklist ) return mod_list
def _build_mod_list(mod_path, suffix, blacklist): """ _build_mod_list(mod_path, suffix) -> Add all the paths in mod_path to sys.path and return a list of all modules in sys.path ending in suffix. """ from sys import path as sys_path mod_path = [mod_path] if type(mod_path) is str else mod_path blacklist = [blacklist] if type(blacklist) is str else blacklist # Add suffix to all names in blacklist. blacklist.extend([ '%s%s' % (name, suffix) for name in blacklist if not name.endswith(suffix) ]) # Add the path of this file to the search path. mod_path.append(os_abspath(os_dirname(__file__))) # Add the path(s) in mod_path to sys.path so we can import from # them. [ sys_path.extend((path, os_dirname(path.rstrip('/')))) for path in mod_path if path not in sys_path ] # Build the list of modules ending in suffix in the mod_path(s). mod_list = ((path, name) for path in sys_path if os_isdir(path) for name in os_listdir(path) if name.endswith(suffix) and name not in blacklist) return mod_list
def _config_check(): from message import Messager from sys import path from copy import deepcopy from os.path import dirname # Reset the path to force config.py to be in the root (could be hacked # using __init__.py, but we can be monkey-patched anyway) orig_path = deepcopy(path) try: # Can't you empty in O(1) instead of O(N)? while path: path.pop() path.append(path_join(abspath(dirname(__file__)), '../..')) # Check if we have a config, otherwise whine try: import config del config except ImportError as e: path.extend(orig_path) # "Prettiest" way to check specific failure if e.message == 'No module named config': Messager.error(_miss_config_msg(), duration=-1) else: Messager.error(_get_stack_trace(), duration=-1) raise ConfigurationError # Try importing the config entries we need try: from config import DEBUG except ImportError: path.extend(orig_path) Messager.error(_miss_var_msg('DEBUG'), duration=-1) raise ConfigurationError try: from config import ADMIN_CONTACT_EMAIL except ImportError: path.extend(orig_path) Messager.error(_miss_var_msg('ADMIN_CONTACT_EMAIL'), duration=-1) raise ConfigurationError finally: # Remove our entry to the path while path: path.pop() # Then restore it path.extend(orig_path)
''' Example solution for batch processing LVIS ''' # set up path to packages from sys import path from os import getenv homeDir = getenv("HOME") path.extend(["%s/src/pprs_lvis/lvis" % homeDir]) # import functions from lvisHandler import * # get a list of all LVIS data using the os package import os direc = '/geos/netdata/avtrain/data/3d/pprs_waveform/lvis/' fileList = os.listdir(direc) # read first file to set up arrays filename = direc + fileList[0] waves, lon, lat, nWaves, nBins, z, lfid, lShot = readLVIS(filename) # loop over all files and use the appendLVIS function. for namen in fileList[1:]: filename = direc + namen waves, lon, lat, nWaves, nBins, z, lfid, lShot = appendLVIS( filename, waves, lon, lat, nWaves, nBins, z, lfid, lShot) # the waves array now contains all the data from all files
assert abs(a.ediff - 2e-5) < 1e-8 assert abs(a.ediffg - 2e-4) < 1e-8 assert a.lorbit == 0 assert abs(a.nupdown + 1.0) < 1e-8 assert a.lmaxmix == 4 assert abs(a.valence - 8.0) < 1e-8 assert a.nonscf == False assert a.lwave == False assert a.lcharg assert a.lvtot == False assert a.nelm == 60 assert a.nelmin == 2 assert a.nelmdl == -5 assert all(abs(a.kpoints - array([[0.25, 0.25, 0.25], [0.75, -0.25, -0.25]])) < 1e-8) assert all(abs(a.multiplicity - [96.0, 288.0]) < 1e-8) pylada.verbose_representation = True # assert repr(a.functional) == "from pylada.vasp.functional import Vasp\nfrom pylada.vasp.specie import Specie\nfunctional = Vasp()\nfunctional.addgrid = None\nfunctional.algo = 'Fast'\nfunctional.ediff = 1e-05\nfunctional.ediffg = None\nfunctional.encut = 1\nfunctional.encutgw = None\nfunctional.extraelectron = 0\nfunctional.fftgrid = None\nfunctional.ispin = 1\nfunctional.istart = None\nfunctional.isym = None\nfunctional.kpoints = 'Automatic generation\\n0\\nMonkhorst\\n2 2 2\\n0 0 0'\nfunctional.lcharg = True\nfunctional.lmaxfockae = None\nfunctional.lmaxmix = 4\nfunctional.loptics = False\nfunctional.lorbit = None\nfunctional.lpead = False\nfunctional.lrpa = False\nfunctional.lvtot = False\nfunctional.lwave = False\nfunctional.magmom = True\nfunctional.nbands = None\nfunctional.nelm = None\nfunctional.nelmdl = None\nfunctional.nelmin = None\nfunctional.nomega = None\nfunctional.nonscf = False\nfunctional.npar = None\nfunctional.nupdown = None\nfunctional.precfock = None\nfunctional.precision = 'Accurate'\nfunctional.relaxation = 'volume'\nfunctional.restart = None\nfunctional.restart_from_contcar = True\nfunctional.smearing = None\nfunctional.symprec = None\nfunctional.system = True\nfunctional.U_verbosity = 1\nfunctional.species['Si'] = Specie('~/usr/src/Pylada/revamped/vasp/tests/pseudos/Si')\n" # pylada.verbose_representation = False # assert repr(a.functional) == "from pylada.vasp.functional import Vasp\nfrom pylada.vasp.specie import Specie\nfunctional = Vasp()\nfunctional.ediff = 1e-05\nfunctional.encut = 1\nfunctional.kpoints = 'Automatic generation\\n0\\nMonkhorst\\n2 2 2\\n0 0 0'\nfunctional.relaxation = 'volume'\nfunctional.species['Si'] = Specie('~/usr/src/Pylada/revamped/vasp/tests/pseudos/Si')\n" if __name__ == "__main__": from sys import argv, path from os.path import join if len(argv) > 2: path.extend(argv[2:]) test(join(argv[1], "COMMON"))
from copy import copy from sys import path import matplotlib.cm as cm import matplotlib.pyplot as plt import numpy as np path.extend([path[0][:path[0].rindex("src") - 1]]) from bin.Coordinators.gym_coordinator import Coordinator from bin.Environment.simple_env import Env with open('E:/ETSI/Proyecto/data/Databases/numpy_files/nans.npy', 'rb') as g: nans = np.load(g) def get_clean(_file): for nnan in nans: _file[nnan[0], nnan[1]] = -1 return np.ma.array(_file, mask=(_file == -1)) # _bo_xs = np.array([[563, 375], # [559, 410], # [604, 368], # [647, 327], # [704, 362], # [690, 430], # [671, 504], # [676, 581], # [649, 650], # [611, 716],
except ImportError: path.extend(orig_path) Messager.error(_miss_var_msg('DEBUG'), duration=-1) raise ConfigurationError try: from config import ADMIN_CONTACT_EMAIL except ImportError: path.extend(orig_path) Messager.error(_miss_var_msg('ADMIN_CONTACT_EMAIL'), duration=-1) raise ConfigurationError finally: # Remove our entry to the path while path: path.pop() # Then restore it path.extend(orig_path) # Convert internal log level to `logging` log level def _convert_log_level(log_level): import config import logging if log_level == config.LL_DEBUG: return logging.DEBUG elif log_level == config.LL_INFO: return logging.INFO elif log_level == config.LL_WARNING: return logging.WARNING elif log_level == config.LL_ERROR: return logging.ERROR elif log_level == config.LL_CRITICAL: return logging.CRITICAL
# 1. Add the assembly reference to the clr system # 2. Import the assembly # 3. Expose the assembly via the RFmxService (rpyc) import clr import colorama import os import rpyc import importlib from sys import path # Add search paths for .NET assemblies to system path path.extend([ os.environ["ProgramFiles(x86)"] + r"\National Instruments\MeasurementStudioVS2010\DotNET\Assemblies\Current", # RFmx personalities os.environ["ProgramFiles"] + r"\National Instruments\RFmxWC\DotNET", # waveform creator personalities os.path.abspath(__file__ + "\\..\\..\\bin") # wrappers for wlan and rfsa/rfsg ]) # Add in all of the IVI .NET paths for finding additional assemblies ivi_dotnet_path = os.environ[ "ProgramFiles"] + r"\IVI Foundation\IVI\Microsoft.NET\Framework64" for x in os.walk(ivi_dotnet_path): path.append(x[0]) # Prepare terminal for colored printing colorama.init() # This function allows for dynamic importation of modules since some modules may not be installed
# Script Description: Retrieve the score card ids from the Garmin website. # Script Version: 0.1 # Script Author: Michael Krakovsky from sys import path path.extend('../../../') # Import the entire project. from My_Golf_Journey.config import garmin_info, exe_paths, mongo_config from pathlib import Path from selenium import webdriver from selenium.webdriver.common.keys import Keys from re import findall from time import sleep from pymongo import MongoClient from json import loads username_field = '//input[@name="username"]' password_field = '//input[@name="password"]' submit_button = '//button[@id]' frame = '//iframe' gen_url = "https://connect.garmin.com/signin/" score_url = 'https://connect.garmin.com/modern/profile/433ae1d7-ba04-4209-bfa4-4814c426397d/scorecards' source_data_location = Path(__file__).absolute( ).parent.parent.parent / 'data' / 'score_card_source.txt' log_file = Path(__file__).absolute( ).parent.parent.parent.parent / 'logs' / 'score_card_source_logs.txt' def connect_to_scorecards_collection(): """ Function Description: Connecto the scorecards collections. Function Parameters: Nothing
TODO: SteeringBehavious.flocking is not automatically updated by pause, stop, and resume methods. FIX THIS! TODO: Future versions might provide a mechanism for importing only a subset of the available behaviours, but this isn't really needed at this time. """ # for python3 compat from __future__ import unicode_literals from __future__ import absolute_import from __future__ import print_function from __future__ import division from sys import path path.extend(['../vpoints']) from point2d import Point2d # Constants for steering behaviours from steering_constants import * # Math Constants (for readability) INF = float('inf') from math import sqrt SQRT_HALF = sqrt(0.5) # Random number generator from random import Random rand_gen = Random() rand_gen.seed() rand_uni = lambda x: rand_gen.uniform(-x, x)
from os import getcwd from sys import path, platform path.extend(['/'.join(getcwd().split('/')[0:-4])]) from model.DAO.RegistroDAO import RegistroDAO from model.DMO.RegistroDMO import RegistroDMO class RegistroCTR(): def CadastrarRegistro(self, Laboratorio, NumeroPatri, NumeroSerie, Padrao, Modelo, Fabricante, DataCali, DataChec, DataVenc, DataProxCali, DataSaida): DAO = RegistroDAO() DAO.Laboratorio = Laboratorio DAO.NumeroPatri = NumeroPatri DAO.NumeroSerie = NumeroSerie DAO.Padrao = Padrao DAO.Modelo = Modelo DAO.Fabricante = Fabricante DAO.DataCali = DataCali DAO.DataChec = DataChec DAO.DataVenc = DataVenc DAO.DataProxCali = DataProxCali DAO.DataSaida = DataSaida DMO = RegistroDMO() DMO.CadastrarRegistro(DAO)
assert a.electropot.units == eV and all(abs(a.electropot - [-83.4534, -83.4534]*eV) < 1e-8) assert a.forces.units == eV/angstrom and all(abs(a.forces) < 1e-8) assert a.stresses.units == kB \ and all(abs(a.stresses - [[[ 21.96, 0. , 0. ], [ 0. , 21.96, 0. ], [ 0. , 0. , 21.96]], [[-14.05, 0. , 0. ], [ 0. , -14.05, 0. ], [ 0. , 0. , -14.05]], [[ 0.1 , 0. , 0. ], [ 0. , 0.1 , 0. ], [ 0. , 0. , 0.1 ]]] * kB) < 1e-3) assert a.stress.units == kB \ and all(abs(a.stress - [[ 0.1 , 0. , 0. ], [ 0. , 0.1 , 0. ], [ 0. , 0. , 0.1 ]] * kB) < 1e-3) assert hasattr(a.structure, 'stress')\ and a.structure.stress.units == a.stress.units \ and all(abs(a.structure.stress - a.stress) < 1e-8) assert all([hasattr(b, 'force') for b in a.structure])\ and all([b.force.units == a.forces.units for b in a.structure])\ and all(abs(a.forces.magnitude - array([b.force for b in a.structure])) < 1e-8) if __name__ == "__main__": from sys import argv, path from os.path import join if len(argv) > 2: path.extend(argv[2:]) test(join(argv[1], 'COMMON'))
import time from sys import path import numpy as np path.extend([path[0][:path[0].rindex("bin") - 1]]) from bin.Agents.gym_agent_trimmed import SimpleAgent from bin.Simulators.gym_environment import GymEnvironment seeds = np.linspace(163343, 3647565, 100) ss = [ ["s1", "s2"], ["s5", "s6"], ["s1", "s2", "s3"], ["s5", "s6", "s7"], ["s1", "s2", "s3", "s4"], ["s5", "s6", "s7", "s8"], # ["s1", "s2", "s3", "s4", "s5"], # ["s5", "s6", "s7", "s8", "s1"], ] for sensores in ss: nro_drones = [4, 3, 2] for cant_drones in nro_drones: print(cant_drones, sensores, "gaussian_ei", 0.375) i = 0 for seed in seeds: i += 1 np.random.seed(np.round(seed).astype(int)) drones = [SimpleAgent(sensores, _id=k) for k in range(cant_drones)] sim = GymEnvironment(path[-1] + "/data/Map/Ypacarai/map.yaml", agents=drones,
"""File config.""" # !/usr/bin/python # library from os import path from sys import path as syspath # path ROOT_PATH = path.dirname(path.abspath(__file__)) SCRIPT_PATH = path.join(ROOT_PATH, 'scripts') HANDLE_PATH = path.join(ROOT_PATH, 'handle') TEMPLATE_PATH = path.join(ROOT_PATH, 'templates') syspath.extend([SCRIPT_PATH, HANDLE_PATH]) # form input FORM_DATA = { 'name': '', 'err': '', 'library': set(), 'all_var': set(), 'get_snmp_var': [], 'walk_snmp_var': [], 'list_option': [], 'regex_var': [], 'type_is_list': [], 'list_last': [], 'oid': {}, 'option': [], 'snmp': {}, 'vars': [], 'UNKNOWN': [], 'CRITICAL': [],
# -*- coding: utf-8 -*- """Tests for collision""" from sys import path path.extend(['.', '..','../..']) import unittest from mosp import collide from math import sqrt __author__ = "F. Ludwig, P. Tute" __maintainer__ = "B. Henne" __contact__ = "*****@*****.**" __copyright__ = "(c) 2010-2011, DCSec, Leibniz Universitaet Hannover, Germany" __license__ = "GPLv3" class CollideTest(unittest.TestCase): """Tests mosp.collide basic functions.""" def test_Line_closest_to_point(self): """Test Line.closest_to_point with four Lines w/different angles.""" h = collide.Line(2.0, 5.0, 8.0, 5.0) self.assertEqual(h.closest_to_point( 0.0, 0.0), (2,5)) self.assertEqual(h.closest_to_point( 5.0, 0.0), (5,5)) self.assertEqual(h.closest_to_point(10.0, 0.0), (8,5)) self.assertEqual(h.closest_to_point(10.0, 5.0), (8,5)) self.assertEqual(h.closest_to_point(10.0,10.0), (8,5)) self.assertEqual(h.closest_to_point( 5.0,10.0), (5,5)) self.assertEqual(h.closest_to_point( 0.0,10.0), (2,5))
vim.command("wincmd p") #switch back window #mapping "a-zA-Z." keys for letter in letters+'.': vim.command("inoremap <buffer> %s %s<Esc>:python CallTips()<CR>" \ % (letter, letter)) #mapping "Back Space" keys vim.command("inoremap <buffer> <BS> <BS><Esc>:python CallTips()<CR>") #mapping "F4" keys vim.command("inoremap <buffer> <F4> <Esc>:python ImportObject()<CR>") #mapping "Alt 1" key vim.command("inoremap <buffer> <M-1> <Esc>:python AutoComplete(1)<CR>") #mapping "Alt 2" key vim.command("inoremap <buffer> <M-2> <Esc>:python AutoComplete(2)<CR>") #mapping "Alt 3" key vim.command("inoremap <buffer> <M-3> <Esc>:python AutoComplete(3)<CR>") #mapping "Alt 4" key vim.command("inoremap <buffer> <M-4> <Esc>:python AutoComplete(4)<CR>") #mapping "Alt 5" key vim.command("inoremap <buffer> <M-5> <Esc>:python AutoComplete(5)<CR>") path.extend(['.','..']) #add current path and parent path del path, letter ImportObject()
from sys import path import os from itertools import combinations_with_replacement, permutations import numpy as np from matplotlib import pyplot as plt from scipy.optimize import leastsq from toy import HamiltonianToy as H_ex from toy import HamiltonianToyEffective as H_eff from toy import get_a_exact as exact from toy import custom_a_prescription as custom from toy import get_n_i_fn as get_ni_fn path.extend([b'../../tr-a_dependence_plots/src']) # noinspection PyPep8,PyUnresolvedReferences from plotting import save_plot_figure # noinspection PyPep8,PyUnresolvedReferences from plotting import save_plot_data_file # noinspection PyPep8,PyUnresolvedReferences from constants import LEGEND_SIZE A_PRESCRIPTIONS = [ exact, # custom(16, 17, 18), # custom(18, 18, 18), # custom(19.25066421, 19.11085927, 17.88211487), # T2 = -1 custom(4, 5, 6), custom(6, 6, 6), # custom(6.81052543, 7.16905406, 7.56813846), # T2 = [-5,0]
from sys import path path.extend(['./', './alphabt']) import warnings warnings.filterwarnings('ignore') import numpy as np import plotly.graph_objects as go import statistic import pandas as pd from plotly.subplots import make_subplots def add_trace(fig, tech_df, row): ''' 畫技術指標 ''' for col in tech_df.columns: fig.add_trace(go.Scatter(x=tech_df.index, y=tech_df[col], mode='lines', name=col, line=dict(width=1)), row=row, col=1) def _main_fig(data, fig, callback): fig.add_trace(go.Candlestick(x=data.index, open=data['open'],
Structure(0.0, 0.5, 0.5, 0.5, 0.0, 0.5, 0.5, 0.5, 0.0, scale=2.0, m=True) .add_atom(0, 0, 0, "As") .add_atom(0.25, 0.25, 0.25, ["In", "Ga"], m=True) ) assert is_primitive(lattice) for cell in itercells(10): structure = supercell(lattice, dot(lattice.cell, cell)) assert not is_primitive(structure) # structure = primitive(structure, 1e-8) # assert is_primitive(structure) # assert abs(structure.volume - lattice.volume) < 1e-8 # assert len(structure) == len(lattice) # assert is_integer(dot(structure.cell, inv(lattice.cell))) # assert is_integer(dot(lattice.cell, inv(structure.cell))) # invcell = inv(lattice.cell) # for atom in structure: # assert api(lattice[atom.site].pos, atom.pos, invcell) and \ # atom.type == lattice[atom.site].type and \ # getattr(lattice[atom.site], 'm', False) == getattr(atom, 'm', False) and \ # (getattr(atom, 'm', False) or atom.site == 0) if __name__ == "__main__": from sys import argv, path if len(argv) > 0: path.extend(argv[1:]) test_primitive()
from sys import path from pathlib import Path, PureWindowsPath path.extend(['SNIPPET_SEARCH']) from os import path import numpy as np from PIL import Image from wordcloud import WordCloud, STOPWORDS from SNIPPET_SEARCH.snippet_search import SNIPPET_SEARCH from SNIPPET_SEARCH.LDA import lda_modeling from SNIPPET_SEARCH.tfIdf import tf_idf filename = Path("C:/Users/spark/PycharmProjects/webapp/snippet_twitter.txt") class SnippetInstance(object): def __init__(self): self.snippets_ob = SNIPPET_SEARCH() self.lda_ob = lda_modeling() self.tf_idf_ob = tf_idf() def snippets(self, str_input, number): result = self.snippets_ob.snippets(str_input, number) return result def generate_topic(self, result): lda_topics = self.lda_ob.generate_topic(result) return lda_topics def generate_tfidf_topic(self, result):
raise Exception() assert len(program.errors) == 1 # compute second set of updated jobs program.update(supp) try: program.wait() except Fail: pass else: raise Exception() assert len(program.errors) == 2 program.errors.clear() finally: try: rmtree(dir) except: pass if __name__ == "__main__": from sys import argv, path from os.path import abspath if len(argv) < 1: raise ValueError("test need to be passed location of pifunc.") if len(argv) > 2: path.extend(argv[2:]) test(abspath(argv[1])) test_update(abspath(argv[1])) test_update_with_fail(abspath(argv[1]))
assert comms[0]['n'] == sum(comms[0].machines.values()) for key in machines: assert machines[key] == comms[0].machines[key] for key in comms[0].machines: assert machines[key] == comms[0].machines[key] for comm in comms: comm.cleanup() assert root['n'] == 32 assert all(u == 8 for u in root.machines.values()) try: comm.lend(33) except MPISizeError: pass else: raise Exception() try: comm.split(33) except MPISizeError: pass else: raise Exception() if __name__ == "__main__": from sys import argv, path from os.path import abspath if len(argv) > 1: path.extend(argv[1:]) test()
break points3d(x,y,z,s, scale_factor=0.004, colormap="autumn") x, y, z, s = [], [], [], [] for i, box in enumerate(boxes): if i < N: continue x.extend([(atom.pos[0] + trans[0]) for atom, trans, inbox in box if not inbox]) y.extend([(atom.pos[1] + trans[1]) for atom, trans, inbox in box if not inbox]) z.extend([(atom.pos[2] + trans[2]) for atom, trans, inbox in box if not inbox]) s.extend([float(i+2) + (0. if inbox else 0.4) for atom, trans, inbox in box if not inbox]) break points3d(x,y,z,s, scale_factor=0.01, opacity=0.3) if __name__ == "__main__": from sys import argv, path if len(argv) > 0: path.extend(argv[1:]) from random import randint from numpy import zeros from numpy.linalg import det from pylada.crystal.cppwrappers import supercell lattice = b5() check(lattice) for i in xrange(10): cell = zeros((3,3)) while det(cell) == 0: cell[:] = [[randint(-10, 11) for j in xrange(3)] for k in xrange(3)] if det(cell) < 0: cell[:, 0], cell[:, 1] = cell[:, 1].copy(), cell[:, 0].copy() structure = supercell(lattice, cell)
# Script Description: The script will prepare all the features related to offensive. The data will queried and then stored in the database # to prevent work being re-executed. The intent will be that all players will have there features calculated starting with the first record. # Script Notes: To date there are three features that will be used related specific to offensive: # 1. Batting Average # 2. On Base Percentage # 3. Slugging Percentage # Related to Pitchers, there are three features that have been choosen to begin. # 1. Strikeouts # 2. WHIP # 3. Approx. Runs Allowed # Script Creator: Michael Krakovsky # Script Version: 0.1 from sys import path path.extend('../../../') # Import the entire project to be found. from timeit import default_timer as timer from BaseballAnalytics.bin.app_utils.common_help import Log_Helper from BaseballAnalytics.bin.app_utils.queries import Queries from pymysql import connect from generic_creator import Generic_Features class Offensive_Features(Generic_Features): def __init__(self, db_connection): # Class Description: The class will direct the queries in creating the stats and inputting them into the database. To be exact, # I will create the tables prior to executing the queries. The tables can be found in the schema diagram. # Class Instantiators: db_connection (pymysql.connections.Connection: The connection to the database.) Generic_Features.__init__(self, db_connection)
# Automatically update module system path to locate local modules from glob import glob from os.path import dirname, isdir, join as joinpath, normpath, pardir from sys import path as syspath, version_info PY_REQ_VERSION = (3, 5) if version_info[:2] < PY_REQ_VERSION: raise RuntimeError("Python %s+ is required" % '.'.join(['%d' % ver for ver in PY_REQ_VERSION])) curdir = dirname(__file__) topdir = normpath(joinpath(curdir, pardir, pardir)) extradirs = [path for path in glob(joinpath(topdir, '*', 'py')) if isdir(path)] syspath.extend(extradirs)
sc[3].type = "Ge" decoration(sc, sc, zb) def test2(): from random import random from pylada.crystal.cppwrappers import Structure, supercell zb = Structure( 0,0.5,0.5, 0.5,0,0.5, 0.5,0.5,0 )\ .add_atom(0,0,0, "Si")\ .add_atom(0.25,0.25,0.25, "Si") sc = supercell(zb, [[2, 0, 0], [0, 2, 0], [0, 0, 2]]) del sc.lattice for i in xrange(1): x = random() * 0.5 for atom in sc: atom.type = "Si" if x > random() else "Ge" decoration(sc, sc, zb) if __name__ == "__main__": from sys import argv, path from numpy import array if len(argv) > 0: path.extend(argv[1:]) # test0() # no decoration. # test1() test2()
'/usr/lib/python3.5' , '/usr/lib/python3.5/lib-dynload' , '/usr/lib/python3.5/plat-i386-linux-gnu' , '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3/dist-packages' , '/usr/lib/python35.zip' , ] ########################################################################################## log_format = '`%(asctime)s:%(msecs)03d [%(levelname)s]` `%(message)s`' log_manager = logspike.Logspike(fmt=']+> {} <+[ {}'.format(log_room, log_format)) log_manager.set_verbosity(verbosity) logger = log_manager.logger path.extend(local_path) room = argv[1] username = argv[2] message = argv[3] bot_name = argv[4] direct = message.strip().lower().replace('@', '', 1).startswith(bot_name.lower()) arguments = message.strip().split(' ') if bot_name.lower() in arguments[0].lower(): arguments.pop(0) command = arguments.pop(0).strip() debug_args = '''`` room:\t{} user:\t{}