text stringlengths 4 1.02M | meta dict |
|---|---|
import os
import sys
import string
import utils
from SCons.Script import *
from utils import _make_path_relative
from mkdist import do_copy_file
BuildOptions = {}
Projects = []
Rtt_Root = ''
Env = None
# SCons PreProcessor patch
def start_handling_includes(self, t=None):
"""
Causes the PreProcessor object to start processing #import,
#include and #include_next lines.
This method will be called when a #if, #ifdef, #ifndef or #elif
evaluates True, or when we reach the #else in a #if, #ifdef,
#ifndef or #elif block where a condition already evaluated
False.
"""
d = self.dispatch_table
p = self.stack[-1] if self.stack else self.default_table
for k in ('import', 'include', 'include_next', 'define'):
d[k] = p[k]
def stop_handling_includes(self, t=None):
"""
Causes the PreProcessor object to stop processing #import,
#include and #include_next lines.
This method will be called when a #if, #ifdef, #ifndef or #elif
evaluates False, or when we reach the #else in a #if, #ifdef,
#ifndef or #elif block where a condition already evaluated True.
"""
d = self.dispatch_table
d['import'] = self.do_nothing
d['include'] = self.do_nothing
d['include_next'] = self.do_nothing
d['define'] = self.do_nothing
PatchedPreProcessor = SCons.cpp.PreProcessor
PatchedPreProcessor.start_handling_includes = start_handling_includes
PatchedPreProcessor.stop_handling_includes = stop_handling_includes
class Win32Spawn:
def spawn(self, sh, escape, cmd, args, env):
# deal with the cmd build-in commands which cannot be used in
# subprocess.Popen
if cmd == 'del':
for f in args[1:]:
try:
os.remove(f)
except Exception as e:
print ('Error removing file: ' + e)
return -1
return 0
import subprocess
newargs = ' '.join(args[1:])
cmdline = cmd + " " + newargs
# Make sure the env is constructed by strings
_e = dict([(k, str(v)) for k, v in env.items()])
# Windows(tm) CreateProcess does not use the env passed to it to find
# the executables. So we have to modify our own PATH to make Popen
# work.
old_path = os.environ['PATH']
os.environ['PATH'] = _e['PATH']
try:
proc = subprocess.Popen(cmdline, env=_e, shell=False)
except Exception as e:
print ('Error in calling command:' + cmdline.split(' ')[0])
print ('Exception: ' + os.strerror(e.errno))
if (os.strerror(e.errno) == "No such file or directory"):
print ("\nPlease check Toolchains PATH setting.\n")
return e.errno
finally:
os.environ['PATH'] = old_path
return proc.wait()
# generate cconfig.h file
def GenCconfigFile(env, BuildOptions):
import rtconfig
if rtconfig.PLATFORM == 'gcc':
contents = ''
if not os.path.isfile('cconfig.h'):
import gcc
gcc.GenerateGCCConfig(rtconfig)
# try again
if os.path.isfile('cconfig.h'):
f = open('cconfig.h', 'r')
if f:
contents = f.read()
f.close()
prep = PatchedPreProcessor()
prep.process_contents(contents)
options = prep.cpp_namespace
BuildOptions.update(options)
# add HAVE_CCONFIG_H definition
env.AppendUnique(CPPDEFINES = ['HAVE_CCONFIG_H'])
def PrepareBuilding(env, root_directory, has_libcpu=False, remove_components = []):
import rtconfig
global BuildOptions
global Projects
global Env
global Rtt_Root
# ===== Add option to SCons =====
AddOption('--dist',
dest = 'make-dist',
action = 'store_true',
default = False,
help = 'make distribution')
AddOption('--dist-strip',
dest = 'make-dist-strip',
action = 'store_true',
default = False,
help = 'make distribution and strip useless files')
AddOption('--dist-ide',
dest = 'make-dist-ide',
action = 'store_true',
default = False,
help = 'make distribution for RT-Thread Studio IDE')
AddOption('--project-path',
dest = 'project-path',
type = 'string',
default = False,
help = 'set dist-ide project output path')
AddOption('--project-name',
dest = 'project-name',
type = 'string',
default = False,
help = 'set project name')
AddOption('--reset-project-config',
dest = 'reset-project-config',
action = 'store_true',
default = False,
help = 'reset the project configurations to default')
AddOption('--cscope',
dest = 'cscope',
action = 'store_true',
default = False,
help = 'Build Cscope cross reference database. Requires cscope installed.')
AddOption('--clang-analyzer',
dest = 'clang-analyzer',
action = 'store_true',
default = False,
help = 'Perform static analyze with Clang-analyzer. ' + \
'Requires Clang installed.\n' + \
'It is recommended to use with scan-build like this:\n' + \
'`scan-build scons --clang-analyzer`\n' + \
'If things goes well, scan-build will instruct you to invoke scan-view.')
AddOption('--buildlib',
dest = 'buildlib',
type = 'string',
help = 'building library of a component')
AddOption('--cleanlib',
dest = 'cleanlib',
action = 'store_true',
default = False,
help = 'clean up the library by --buildlib')
AddOption('--target',
dest = 'target',
type = 'string',
help = 'set target project: mdk/mdk4/mdk5/iar/vs/vsc/ua/cdk/ses/makefile/eclipse')
AddOption('--genconfig',
dest = 'genconfig',
action = 'store_true',
default = False,
help = 'Generate .config from rtconfig.h')
AddOption('--useconfig',
dest = 'useconfig',
type = 'string',
help = 'make rtconfig.h from config file.')
AddOption('--verbose',
dest = 'verbose',
action = 'store_true',
default = False,
help = 'print verbose information during build')
Env = env
Rtt_Root = os.path.abspath(root_directory)
# make an absolute root directory
RTT_ROOT = Rtt_Root
Export('RTT_ROOT')
# set RTT_ROOT in ENV
Env['RTT_ROOT'] = Rtt_Root
# set BSP_ROOT in ENV
Env['BSP_ROOT'] = Dir('#').abspath
sys.path = sys.path + [os.path.join(Rtt_Root, 'tools')]
# {target_name:(CROSS_TOOL, PLATFORM)}
tgt_dict = {'mdk':('keil', 'armcc'),
'mdk4':('keil', 'armcc'),
'mdk5':('keil', 'armcc'),
'iar':('iar', 'iar'),
'vs':('msvc', 'cl'),
'vs2012':('msvc', 'cl'),
'vsc' : ('gcc', 'gcc'),
'cb':('keil', 'armcc'),
'ua':('gcc', 'gcc'),
'cdk':('gcc', 'gcc'),
'makefile':('gcc', 'gcc'),
'eclipse':('gcc', 'gcc'),
'ses' : ('gcc', 'gcc')}
tgt_name = GetOption('target')
if tgt_name:
# --target will change the toolchain settings which clang-analyzer is
# depend on
if GetOption('clang-analyzer'):
print ('--clang-analyzer cannot be used with --target')
sys.exit(1)
SetOption('no_exec', 1)
try:
rtconfig.CROSS_TOOL, rtconfig.PLATFORM = tgt_dict[tgt_name]
# replace the 'RTT_CC' to 'CROSS_TOOL'
os.environ['RTT_CC'] = rtconfig.CROSS_TOOL
utils.ReloadModule(rtconfig)
except KeyError:
print ('Unknow target: '+ tgt_name+'. Avaible targets: ' +', '.join(tgt_dict.keys()))
sys.exit(1)
elif (GetDepend('RT_USING_NEWLIB') == False and GetDepend('RT_USING_NOLIBC') == False) \
and rtconfig.PLATFORM == 'gcc':
AddDepend('RT_USING_MINILIBC')
# auto change the 'RTT_EXEC_PATH' when 'rtconfig.EXEC_PATH' get failed
if not os.path.exists(rtconfig.EXEC_PATH):
if 'RTT_EXEC_PATH' in os.environ:
# del the 'RTT_EXEC_PATH' and using the 'EXEC_PATH' setting on rtconfig.py
del os.environ['RTT_EXEC_PATH']
utils.ReloadModule(rtconfig)
# add compability with Keil MDK 4.6 which changes the directory of armcc.exe
if rtconfig.PLATFORM == 'armcc' or rtconfig.PLATFORM == 'armclang':
if rtconfig.PLATFORM == 'armcc' and not os.path.isfile(os.path.join(rtconfig.EXEC_PATH, 'armcc.exe')):
if rtconfig.EXEC_PATH.find('bin40') > 0:
rtconfig.EXEC_PATH = rtconfig.EXEC_PATH.replace('bin40', 'armcc/bin')
Env['LINKFLAGS'] = Env['LINKFLAGS'].replace('RV31', 'armcc')
# reset AR command flags
env['ARCOM'] = '$AR --create $TARGET $SOURCES'
env['LIBPREFIX'] = ''
env['LIBSUFFIX'] = '.lib'
env['LIBLINKPREFIX'] = ''
env['LIBLINKSUFFIX'] = '.lib'
env['LIBDIRPREFIX'] = '--userlibpath '
elif rtconfig.PLATFORM == 'iar':
env['LIBPREFIX'] = ''
env['LIBSUFFIX'] = '.a'
env['LIBLINKPREFIX'] = ''
env['LIBLINKSUFFIX'] = '.a'
env['LIBDIRPREFIX'] = '--search '
# patch for win32 spawn
if env['PLATFORM'] == 'win32':
win32_spawn = Win32Spawn()
win32_spawn.env = env
env['SPAWN'] = win32_spawn.spawn
if env['PLATFORM'] == 'win32':
os.environ['PATH'] = rtconfig.EXEC_PATH + ";" + os.environ['PATH']
else:
os.environ['PATH'] = rtconfig.EXEC_PATH + ":" + os.environ['PATH']
# add program path
env.PrependENVPath('PATH', os.environ['PATH'])
# add rtconfig.h/BSP path into Kernel group
DefineGroup("Kernel", [], [], CPPPATH=[str(Dir('#').abspath)])
# add library build action
act = SCons.Action.Action(BuildLibInstallAction, 'Install compiled library... $TARGET')
bld = Builder(action = act)
Env.Append(BUILDERS = {'BuildLib': bld})
# parse rtconfig.h to get used component
PreProcessor = PatchedPreProcessor()
f = open('rtconfig.h', 'r')
contents = f.read()
f.close()
PreProcessor.process_contents(contents)
BuildOptions = PreProcessor.cpp_namespace
if GetOption('clang-analyzer'):
# perform what scan-build does
env.Replace(
CC = 'ccc-analyzer',
CXX = 'c++-analyzer',
# skip as and link
LINK = 'true',
AS = 'true',)
env["ENV"].update(x for x in os.environ.items() if x[0].startswith("CCC_"))
# only check, don't compile. ccc-analyzer use CCC_CC as the CC.
# fsyntax-only will give us some additional warning messages
env['ENV']['CCC_CC'] = 'clang'
env.Append(CFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
env['ENV']['CCC_CXX'] = 'clang++'
env.Append(CXXFLAGS=['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding'])
# remove the POST_ACTION as it will cause meaningless errors(file not
# found or something like that).
rtconfig.POST_ACTION = ''
# generate cconfig.h file
GenCconfigFile(env, BuildOptions)
# auto append '_REENT_SMALL' when using newlib 'nano.specs' option
if rtconfig.PLATFORM == 'gcc' and str(env['LINKFLAGS']).find('nano.specs') != -1:
env.AppendUnique(CPPDEFINES = ['_REENT_SMALL'])
if GetOption('genconfig'):
from genconf import genconfig
genconfig()
exit(0)
if env['PLATFORM'] != 'win32':
AddOption('--menuconfig',
dest = 'menuconfig',
action = 'store_true',
default = False,
help = 'make menuconfig for RT-Thread BSP')
if GetOption('menuconfig'):
from menuconfig import menuconfig
menuconfig(Rtt_Root)
exit(0)
AddOption('--pyconfig',
dest = 'pyconfig',
action = 'store_true',
default = False,
help = 'Python GUI menuconfig for RT-Thread BSP')
AddOption('--pyconfig-silent',
dest = 'pyconfig_silent',
action = 'store_true',
default = False,
help = 'Don`t show pyconfig window')
if GetOption('pyconfig_silent'):
from menuconfig import guiconfig_silent
guiconfig_silent(Rtt_Root)
exit(0)
elif GetOption('pyconfig'):
from menuconfig import guiconfig
guiconfig(Rtt_Root)
exit(0)
configfn = GetOption('useconfig')
if configfn:
from menuconfig import mk_rtconfig
mk_rtconfig(configfn)
exit(0)
if not GetOption('verbose'):
# override the default verbose command string
env.Replace(
ARCOMSTR = 'AR $TARGET',
ASCOMSTR = 'AS $TARGET',
ASPPCOMSTR = 'AS $TARGET',
CCCOMSTR = 'CC $TARGET',
CXXCOMSTR = 'CXX $TARGET',
LINKCOMSTR = 'LINK $TARGET'
)
# fix the linker for C++
if GetDepend('RT_USING_CPLUSPLUS'):
if env['LINK'].find('gcc') != -1:
env['LINK'] = env['LINK'].replace('gcc', 'g++')
# we need to seperate the variant_dir for BSPs and the kernels. BSPs could
# have their own components etc. If they point to the same folder, SCons
# would find the wrong source code to compile.
bsp_vdir = 'build'
kernel_vdir = 'build/kernel'
# board build script
objs = SConscript('SConscript', variant_dir=bsp_vdir, duplicate=0)
# include kernel
objs.extend(SConscript(Rtt_Root + '/src/SConscript', variant_dir=kernel_vdir + '/src', duplicate=0))
# include libcpu
if not has_libcpu:
objs.extend(SConscript(Rtt_Root + '/libcpu/SConscript',
variant_dir=kernel_vdir + '/libcpu', duplicate=0))
# include components
objs.extend(SConscript(Rtt_Root + '/components/SConscript',
variant_dir=kernel_vdir + '/components',
duplicate=0,
exports='remove_components'))
return objs
def PrepareModuleBuilding(env, root_directory, bsp_directory):
import rtconfig
global BuildOptions
global Env
global Rtt_Root
# patch for win32 spawn
if env['PLATFORM'] == 'win32':
win32_spawn = Win32Spawn()
win32_spawn.env = env
env['SPAWN'] = win32_spawn.spawn
Env = env
Rtt_Root = root_directory
# parse bsp rtconfig.h to get used component
PreProcessor = PatchedPreProcessor()
f = open(bsp_directory + '/rtconfig.h', 'r')
contents = f.read()
f.close()
PreProcessor.process_contents(contents)
BuildOptions = PreProcessor.cpp_namespace
# add build/clean library option for library checking
AddOption('--buildlib',
dest='buildlib',
type='string',
help='building library of a component')
AddOption('--cleanlib',
dest='cleanlib',
action='store_true',
default=False,
help='clean up the library by --buildlib')
# add program path
env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
def GetConfigValue(name):
assert type(name) == str, 'GetConfigValue: only string parameter is valid'
try:
return BuildOptions[name]
except:
return ''
def GetDepend(depend):
building = True
if type(depend) == type('str'):
if not depend in BuildOptions or BuildOptions[depend] == 0:
building = False
elif BuildOptions[depend] != '':
return BuildOptions[depend]
return building
# for list type depend
for item in depend:
if item != '':
if not item in BuildOptions or BuildOptions[item] == 0:
building = False
return building
def LocalOptions(config_filename):
from SCons.Script import SCons
# parse wiced_config.h to get used component
PreProcessor = SCons.cpp.PreProcessor()
f = open(config_filename, 'r')
contents = f.read()
f.close()
PreProcessor.process_contents(contents)
local_options = PreProcessor.cpp_namespace
return local_options
def GetLocalDepend(options, depend):
building = True
if type(depend) == type('str'):
if not depend in options or options[depend] == 0:
building = False
elif options[depend] != '':
return options[depend]
return building
# for list type depend
for item in depend:
if item != '':
if not item in options or options[item] == 0:
building = False
return building
def AddDepend(option):
BuildOptions[option] = 1
def MergeGroup(src_group, group):
src_group['src'] = src_group['src'] + group['src']
if 'CCFLAGS' in group:
if 'CCFLAGS' in src_group:
src_group['CCFLAGS'] = src_group['CCFLAGS'] + group['CCFLAGS']
else:
src_group['CCFLAGS'] = group['CCFLAGS']
if 'CPPPATH' in group:
if 'CPPPATH' in src_group:
src_group['CPPPATH'] = src_group['CPPPATH'] + group['CPPPATH']
else:
src_group['CPPPATH'] = group['CPPPATH']
if 'CPPDEFINES' in group:
if 'CPPDEFINES' in src_group:
src_group['CPPDEFINES'] = src_group['CPPDEFINES'] + group['CPPDEFINES']
else:
src_group['CPPDEFINES'] = group['CPPDEFINES']
if 'ASFLAGS' in group:
if 'ASFLAGS' in src_group:
src_group['ASFLAGS'] = src_group['ASFLAGS'] + group['ASFLAGS']
else:
src_group['ASFLAGS'] = group['ASFLAGS']
# for local CCFLAGS/CPPPATH/CPPDEFINES
if 'LOCAL_CCFLAGS' in group:
if 'LOCAL_CCFLAGS' in src_group:
src_group['LOCAL_CCFLAGS'] = src_group['LOCAL_CCFLAGS'] + group['LOCAL_CCFLAGS']
else:
src_group['LOCAL_CCFLAGS'] = group['LOCAL_CCFLAGS']
if 'LOCAL_CPPPATH' in group:
if 'LOCAL_CPPPATH' in src_group:
src_group['LOCAL_CPPPATH'] = src_group['LOCAL_CPPPATH'] + group['LOCAL_CPPPATH']
else:
src_group['LOCAL_CPPPATH'] = group['LOCAL_CPPPATH']
if 'LOCAL_CPPDEFINES' in group:
if 'LOCAL_CPPDEFINES' in src_group:
src_group['LOCAL_CPPDEFINES'] = src_group['LOCAL_CPPDEFINES'] + group['LOCAL_CPPDEFINES']
else:
src_group['LOCAL_CPPDEFINES'] = group['LOCAL_CPPDEFINES']
if 'LINKFLAGS' in group:
if 'LINKFLAGS' in src_group:
src_group['LINKFLAGS'] = src_group['LINKFLAGS'] + group['LINKFLAGS']
else:
src_group['LINKFLAGS'] = group['LINKFLAGS']
if 'LIBS' in group:
if 'LIBS' in src_group:
src_group['LIBS'] = src_group['LIBS'] + group['LIBS']
else:
src_group['LIBS'] = group['LIBS']
if 'LIBPATH' in group:
if 'LIBPATH' in src_group:
src_group['LIBPATH'] = src_group['LIBPATH'] + group['LIBPATH']
else:
src_group['LIBPATH'] = group['LIBPATH']
if 'LOCAL_ASFLAGS' in group:
if 'LOCAL_ASFLAGS' in src_group:
src_group['LOCAL_ASFLAGS'] = src_group['LOCAL_ASFLAGS'] + group['LOCAL_ASFLAGS']
else:
src_group['LOCAL_ASFLAGS'] = group['LOCAL_ASFLAGS']
def DefineGroup(name, src, depend, **parameters):
global Env
if not GetDepend(depend):
return []
# find exist group and get path of group
group_path = ''
for g in Projects:
if g['name'] == name:
group_path = g['path']
if group_path == '':
group_path = GetCurrentDir()
group = parameters
group['name'] = name
group['path'] = group_path
if type(src) == type([]):
group['src'] = File(src)
else:
group['src'] = src
if 'CCFLAGS' in group:
Env.AppendUnique(CCFLAGS = group['CCFLAGS'])
if 'CPPPATH' in group:
paths = []
for item in group['CPPPATH']:
paths.append(os.path.abspath(item))
group['CPPPATH'] = paths
Env.AppendUnique(CPPPATH = group['CPPPATH'])
if 'CPPDEFINES' in group:
Env.AppendUnique(CPPDEFINES = group['CPPDEFINES'])
if 'LINKFLAGS' in group:
Env.AppendUnique(LINKFLAGS = group['LINKFLAGS'])
if 'ASFLAGS' in group:
Env.AppendUnique(ASFLAGS = group['ASFLAGS'])
if 'LOCAL_CPPPATH' in group:
paths = []
for item in group['LOCAL_CPPPATH']:
paths.append(os.path.abspath(item))
group['LOCAL_CPPPATH'] = paths
import rtconfig
if rtconfig.PLATFORM == 'gcc':
if 'CCFLAGS' in group:
group['CCFLAGS'] = utils.GCCC99Patch(group['CCFLAGS'])
if 'LOCAL_CCFLAGS' in group:
group['LOCAL_CCFLAGS'] = utils.GCCC99Patch(group['LOCAL_CCFLAGS'])
# check whether to clean up library
if GetOption('cleanlib') and os.path.exists(os.path.join(group['path'], GroupLibFullName(name, Env))):
if group['src'] != []:
print ('Remove library:'+ GroupLibFullName(name, Env))
fn = os.path.join(group['path'], GroupLibFullName(name, Env))
if os.path.exists(fn):
os.unlink(fn)
if 'LIBS' in group:
Env.AppendUnique(LIBS = group['LIBS'])
if 'LIBPATH' in group:
Env.AppendUnique(LIBPATH = group['LIBPATH'])
# check whether to build group library
if 'LIBRARY' in group:
objs = Env.Library(name, group['src'])
else:
# only add source
objs = group['src']
# merge group
for g in Projects:
if g['name'] == name:
# merge to this group
MergeGroup(g, group)
return objs
# add a new group
Projects.append(group)
return objs
def GetCurrentDir():
conscript = File('SConscript')
fn = conscript.rfile()
name = fn.name
path = os.path.dirname(fn.abspath)
return path
PREBUILDING = []
def RegisterPreBuildingAction(act):
global PREBUILDING
assert callable(act), 'Could only register callable objects. %s received' % repr(act)
PREBUILDING.append(act)
def PreBuilding():
global PREBUILDING
for a in PREBUILDING:
a()
def GroupLibName(name, env):
import rtconfig
if rtconfig.PLATFORM == 'armcc':
return name + '_rvds'
elif rtconfig.PLATFORM == 'gcc':
return name + '_gcc'
return name
def GroupLibFullName(name, env):
return env['LIBPREFIX'] + GroupLibName(name, env) + env['LIBSUFFIX']
def BuildLibInstallAction(target, source, env):
lib_name = GetOption('buildlib')
for Group in Projects:
if Group['name'] == lib_name:
lib_name = GroupLibFullName(Group['name'], env)
dst_name = os.path.join(Group['path'], lib_name)
print ('Copy '+lib_name+' => ' +dst_name)
do_copy_file(lib_name, dst_name)
break
def DoBuilding(target, objects):
# merge all objects into one list
def one_list(l):
lst = []
for item in l:
if type(item) == type([]):
lst += one_list(item)
else:
lst.append(item)
return lst
# handle local group
def local_group(group, objects):
if 'LOCAL_CCFLAGS' in group or 'LOCAL_CPPPATH' in group or 'LOCAL_CPPDEFINES' in group or 'LOCAL_ASFLAGS' in group:
CCFLAGS = Env.get('CCFLAGS', '') + group.get('LOCAL_CCFLAGS', '')
CPPPATH = Env.get('CPPPATH', ['']) + group.get('LOCAL_CPPPATH', [''])
CPPDEFINES = Env.get('CPPDEFINES', ['']) + group.get('LOCAL_CPPDEFINES', [''])
ASFLAGS = Env.get('ASFLAGS', '') + group.get('LOCAL_ASFLAGS', '')
for source in group['src']:
objects.append(Env.Object(source, CCFLAGS = CCFLAGS, ASFLAGS = ASFLAGS,
CPPPATH = CPPPATH, CPPDEFINES = CPPDEFINES))
return True
return False
objects = one_list(objects)
program = None
# check whether special buildlib option
lib_name = GetOption('buildlib')
if lib_name:
objects = [] # remove all of objects
# build library with special component
for Group in Projects:
if Group['name'] == lib_name:
lib_name = GroupLibName(Group['name'], Env)
if not local_group(Group, objects):
objects = Env.Object(Group['src'])
program = Env.Library(lib_name, objects)
# add library copy action
Env.BuildLib(lib_name, program)
break
else:
# remove source files with local flags setting
for group in Projects:
if 'LOCAL_CCFLAGS' in group or 'LOCAL_CPPPATH' in group or 'LOCAL_CPPDEFINES' in group:
for source in group['src']:
for obj in objects:
if source.abspath == obj.abspath or (len(obj.sources) > 0 and source.abspath == obj.sources[0].abspath):
objects.remove(obj)
# re-add the source files to the objects
for group in Projects:
local_group(group, objects)
program = Env.Program(target, objects)
EndBuilding(target, program)
def GenTargetProject(program = None):
if GetOption('target') == 'mdk':
from keil import MDKProject
from keil import MDK4Project
from keil import MDK5Project
template = os.path.isfile('template.Uv2')
if template:
MDKProject('project.Uv2', Projects)
else:
template = os.path.isfile('template.uvproj')
if template:
MDK4Project('project.uvproj', Projects)
else:
template = os.path.isfile('template.uvprojx')
if template:
MDK5Project('project.uvprojx', Projects)
else:
print ('No template project file found.')
if GetOption('target') == 'mdk4':
from keil import MDK4Project
MDK4Project('project.uvproj', Projects)
if GetOption('target') == 'mdk5':
from keil import MDK5Project
MDK5Project('project.uvprojx', Projects)
if GetOption('target') == 'iar':
from iar import IARProject
IARProject('project.ewp', Projects)
if GetOption('target') == 'vs':
from vs import VSProject
VSProject('project.vcproj', Projects, program)
if GetOption('target') == 'vs2012':
from vs2012 import VS2012Project
VS2012Project('project.vcxproj', Projects, program)
if GetOption('target') == 'cb':
from codeblocks import CBProject
CBProject('project.cbp', Projects, program)
if GetOption('target') == 'ua':
from ua import PrepareUA
PrepareUA(Projects, Rtt_Root, str(Dir('#')))
if GetOption('target') == 'vsc':
from vsc import GenerateVSCode
GenerateVSCode(Env)
if GetOption('target') == 'cdk':
from cdk import CDKProject
CDKProject('project.cdkproj', Projects)
if GetOption('target') == 'ses':
from ses import SESProject
SESProject(Env)
if GetOption('target') == 'makefile':
from makefile import TargetMakefile
TargetMakefile(Env)
if GetOption('target') == 'eclipse':
from eclipse import TargetEclipse
TargetEclipse(Env, GetOption('reset-project-config'), GetOption('project-name'))
def EndBuilding(target, program = None):
import rtconfig
need_exit = False
Env['target'] = program
Env['project'] = Projects
if hasattr(rtconfig, 'BSP_LIBRARY_TYPE'):
Env['bsp_lib_type'] = rtconfig.BSP_LIBRARY_TYPE
if hasattr(rtconfig, 'dist_handle'):
Env['dist_handle'] = rtconfig.dist_handle
Env.AddPostAction(target, rtconfig.POST_ACTION)
# Add addition clean files
Clean(target, 'cconfig.h')
Clean(target, 'rtua.py')
Clean(target, 'rtua.pyc')
if GetOption('target'):
GenTargetProject(program)
BSP_ROOT = Dir('#').abspath
if GetOption('make-dist') and program != None:
from mkdist import MkDist
MkDist(program, BSP_ROOT, Rtt_Root, Env)
if GetOption('make-dist-strip') and program != None:
from mkdist import MkDist_Strip
MkDist_Strip(program, BSP_ROOT, Rtt_Root, Env)
need_exit = True
if GetOption('make-dist-ide') and program != None:
from mkdist import MkDist
project_path = GetOption('project-path')
project_name = GetOption('project-name')
if not isinstance(project_path, str) or len(project_path) == 0 :
print("\nwarning : --project-path=your_project_path parameter is required.")
print("\nstop!")
exit(0)
if not isinstance(project_name, str) or len(project_name) == 0:
print("\nwarning : --project-name=your_project_name parameter is required.")
print("\nstop!")
exit(0)
rtt_ide = {'project_path' : project_path, 'project_name' : project_name}
MkDist(program, BSP_ROOT, Rtt_Root, Env, rtt_ide)
need_exit = True
if GetOption('cscope'):
from cscope import CscopeDatabase
CscopeDatabase(Projects)
if not GetOption('help') and not GetOption('target'):
if not os.path.exists(rtconfig.EXEC_PATH):
print ("Error: the toolchain path (" + rtconfig.EXEC_PATH + ") is not exist, please check 'EXEC_PATH' in path or rtconfig.py.")
need_exit = True
if need_exit:
exit(0)
def SrcRemove(src, remove):
if not src:
return
src_bak = src[:]
if type(remove) == type('str'):
if os.path.isabs(remove):
remove = os.path.relpath(remove, GetCurrentDir())
remove = os.path.normpath(remove)
for item in src_bak:
if type(item) == type('str'):
item_str = item
else:
item_str = item.rstr()
if os.path.isabs(item_str):
item_str = os.path.relpath(item_str, GetCurrentDir())
item_str = os.path.normpath(item_str)
if item_str == remove:
src.remove(item)
else:
for remove_item in remove:
remove_str = str(remove_item)
if os.path.isabs(remove_str):
remove_str = os.path.relpath(remove_str, GetCurrentDir())
remove_str = os.path.normpath(remove_str)
for item in src_bak:
if type(item) == type('str'):
item_str = item
else:
item_str = item.rstr()
if os.path.isabs(item_str):
item_str = os.path.relpath(item_str, GetCurrentDir())
item_str = os.path.normpath(item_str)
if item_str == remove_str:
src.remove(item)
def GetVersion():
import SCons.cpp
import string
rtdef = os.path.join(Rtt_Root, 'include', 'rtdef.h')
# parse rtdef.h to get RT-Thread version
prepcessor = PatchedPreProcessor()
f = open(rtdef, 'r')
contents = f.read()
f.close()
prepcessor.process_contents(contents)
def_ns = prepcessor.cpp_namespace
version = int(filter(lambda ch: ch in '0123456789.', def_ns['RT_VERSION']))
subversion = int(filter(lambda ch: ch in '0123456789.', def_ns['RT_SUBVERSION']))
if 'RT_REVISION' in def_ns:
revision = int(filter(lambda ch: ch in '0123456789.', def_ns['RT_REVISION']))
return '%d.%d.%d' % (version, subversion, revision)
return '0.%d.%d' % (version, subversion)
def GlobSubDir(sub_dir, ext_name):
import os
import glob
def glob_source(sub_dir, ext_name):
list = os.listdir(sub_dir)
src = glob.glob(os.path.join(sub_dir, ext_name))
for item in list:
full_subdir = os.path.join(sub_dir, item)
if os.path.isdir(full_subdir):
src += glob_source(full_subdir, ext_name)
return src
dst = []
src = glob_source(sub_dir, ext_name)
for item in src:
dst.append(os.path.relpath(item, sub_dir))
return dst
def PackageSConscript(package):
from package import BuildPackage
return BuildPackage(package)
| {
"content_hash": "977d8a7b8632661ba61f061245a8b0de",
"timestamp": "",
"source": "github",
"line_count": 982,
"max_line_length": 139,
"avg_line_length": 33.95926680244399,
"alnum_prop": 0.5618627803766343,
"repo_name": "gbcwbz/rt-thread",
"id": "8d461102bc1d6b6f515feef54af757d9b148f1dd",
"size": "34430",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/building.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "10728289"
},
{
"name": "Batchfile",
"bytes": "187896"
},
{
"name": "C",
"bytes": "582512328"
},
{
"name": "C++",
"bytes": "7742180"
},
{
"name": "CMake",
"bytes": "148026"
},
{
"name": "CSS",
"bytes": "9978"
},
{
"name": "DIGITAL Command Language",
"bytes": "13234"
},
{
"name": "GDB",
"bytes": "11796"
},
{
"name": "HTML",
"bytes": "2274919"
},
{
"name": "Lex",
"bytes": "7026"
},
{
"name": "Logos",
"bytes": "7078"
},
{
"name": "M4",
"bytes": "17515"
},
{
"name": "Makefile",
"bytes": "271627"
},
{
"name": "Module Management System",
"bytes": "1548"
},
{
"name": "Objective-C",
"bytes": "4110192"
},
{
"name": "Pawn",
"bytes": "1427"
},
{
"name": "Perl",
"bytes": "9520"
},
{
"name": "PowerShell",
"bytes": "1628"
},
{
"name": "Python",
"bytes": "1486699"
},
{
"name": "RPC",
"bytes": "14162"
},
{
"name": "Rich Text Format",
"bytes": "355402"
},
{
"name": "Roff",
"bytes": "4486"
},
{
"name": "Ruby",
"bytes": "869"
},
{
"name": "Shell",
"bytes": "407900"
},
{
"name": "TeX",
"bytes": "3113"
},
{
"name": "Yacc",
"bytes": "16084"
}
],
"symlink_target": ""
} |
from __future__ import division, print_function
import math
import warnings
from operator import itemgetter
import itertools
import numpy as np
from numpy import ma
import matplotlib
rcParams = matplotlib.rcParams
import matplotlib.artist as martist
from matplotlib.artist import allow_rasterization
import matplotlib.axis as maxis
import matplotlib.cbook as cbook
import matplotlib.collections as mcoll
import matplotlib.colors as mcolors
import matplotlib.contour as mcontour
import matplotlib.dates as _ # <-registers a date unit converter
from matplotlib import docstring
import matplotlib.font_manager as font_manager
import matplotlib.image as mimage
import matplotlib.legend as mlegend
import matplotlib.lines as mlines
import matplotlib.markers as mmarkers
import matplotlib.mlab as mlab
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.spines as mspines
import matplotlib.quiver as mquiver
import matplotlib.scale as mscale
import matplotlib.stackplot as mstack
import matplotlib.streamplot as mstream
import matplotlib.table as mtable
import matplotlib.text as mtext
import matplotlib.ticker as mticker
import matplotlib.transforms as mtransforms
import matplotlib.tri as mtri
from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer
iterable = cbook.iterable
is_string_like = cbook.is_string_like
is_sequence_of_strings = cbook.is_sequence_of_strings
def _string_to_bool(s):
if not is_string_like(s):
return s
if s == 'on':
return True
if s == 'off':
return False
raise ValueError("string argument must be either 'on' or 'off'")
def _process_plot_format(fmt):
"""
Process a MATLAB style color/line style format string. Return a
(*linestyle*, *color*) tuple as a result of the processing. Default
values are ('-', 'b'). Example format strings include:
* 'ko': black circles
* '.b': blue dots
* 'r--': red dashed lines
.. seealso::
:func:`~matplotlib.Line2D.lineStyles` and
:func:`~matplotlib.pyplot.colors`
for all possible styles and color format string.
"""
linestyle = None
marker = None
color = None
# Is fmt just a colorspec?
try:
color = mcolors.colorConverter.to_rgb(fmt)
# We need to differentiate grayscale '1.0' from tri_down marker '1'
try:
fmtint = str(int(fmt))
except ValueError:
return linestyle, marker, color # Yes
else:
if fmt != fmtint:
# user definitely doesn't want tri_down marker
return linestyle, marker, color # Yes
else:
# ignore converted color
color = None
except ValueError:
pass # No, not just a color.
# handle the multi char special cases and strip them from the
# string
if fmt.find('--') >= 0:
linestyle = '--'
fmt = fmt.replace('--', '')
if fmt.find('-.') >= 0:
linestyle = '-.'
fmt = fmt.replace('-.', '')
if fmt.find(' ') >= 0:
linestyle = 'None'
fmt = fmt.replace(' ', '')
chars = [c for c in fmt]
for c in chars:
if c in mlines.lineStyles:
if linestyle is not None:
raise ValueError(
'Illegal format string "%s"; two linestyle symbols' % fmt)
linestyle = c
elif c in mlines.lineMarkers:
if marker is not None:
raise ValueError(
'Illegal format string "%s"; two marker symbols' % fmt)
marker = c
elif c in mcolors.colorConverter.colors:
if color is not None:
raise ValueError(
'Illegal format string "%s"; two color symbols' % fmt)
color = c
else:
raise ValueError(
'Unrecognized character %c in format string' % c)
if linestyle is None and marker is None:
linestyle = rcParams['lines.linestyle']
if linestyle is None:
linestyle = 'None'
if marker is None:
marker = 'None'
return linestyle, marker, color
class _process_plot_var_args(object):
"""
Process variable length arguments to the plot command, so that
plot commands like the following are supported::
plot(t, s)
plot(t1, s1, t2, s2)
plot(t1, s1, 'ko', t2, s2)
plot(t1, s1, 'ko', t2, s2, 'r--', t3, e3)
an arbitrary number of *x*, *y*, *fmt* are allowed
"""
def __init__(self, axes, command='plot'):
self.axes = axes
self.command = command
self.set_color_cycle()
def __getstate__(self):
# note: it is not possible to pickle a itertools.cycle instance
return {'axes': self.axes, 'command': self.command}
def __setstate__(self, state):
self.__dict__ = state.copy()
self.set_color_cycle()
def set_color_cycle(self, clist=None):
if clist is None:
clist = rcParams['axes.color_cycle']
self.color_cycle = itertools.cycle(clist)
def __call__(self, *args, **kwargs):
if self.axes.xaxis is not None and self.axes.yaxis is not None:
xunits = kwargs.pop('xunits', self.axes.xaxis.units)
if self.axes.name == 'polar':
xunits = kwargs.pop('thetaunits', xunits)
yunits = kwargs.pop('yunits', self.axes.yaxis.units)
if self.axes.name == 'polar':
yunits = kwargs.pop('runits', yunits)
if xunits != self.axes.xaxis.units:
self.axes.xaxis.set_units(xunits)
if yunits != self.axes.yaxis.units:
self.axes.yaxis.set_units(yunits)
ret = self._grab_next_args(*args, **kwargs)
return ret
def set_lineprops(self, line, **kwargs):
assert self.command == 'plot', 'set_lineprops only works with "plot"'
for key, val in kwargs.items():
funcName = "set_%s" % key
if not hasattr(line, funcName):
raise TypeError('There is no line property "%s"' % key)
func = getattr(line, funcName)
func(val)
def set_patchprops(self, fill_poly, **kwargs):
assert self.command == 'fill', 'set_patchprops only works with "fill"'
for key, val in kwargs.items():
funcName = "set_%s" % key
if not hasattr(fill_poly, funcName):
raise TypeError('There is no patch property "%s"' % key)
func = getattr(fill_poly, funcName)
func(val)
def _xy_from_xy(self, x, y):
if self.axes.xaxis is not None and self.axes.yaxis is not None:
bx = self.axes.xaxis.update_units(x)
by = self.axes.yaxis.update_units(y)
if self.command != 'plot':
# the Line2D class can handle unitized data, with
# support for post hoc unit changes etc. Other mpl
# artists, eg Polygon which _process_plot_var_args
# also serves on calls to fill, cannot. So this is a
# hack to say: if you are not "plot", which is
# creating Line2D, then convert the data now to
# floats. If you are plot, pass the raw data through
# to Line2D which will handle the conversion. So
# polygons will not support post hoc conversions of
# the unit type since they are not storing the orig
# data. Hopefully we can rationalize this at a later
# date - JDH
if bx:
x = self.axes.convert_xunits(x)
if by:
y = self.axes.convert_yunits(y)
x = np.atleast_1d(x) # like asanyarray, but converts scalar to array
y = np.atleast_1d(y)
if x.shape[0] != y.shape[0]:
raise ValueError("x and y must have same first dimension")
if x.ndim > 2 or y.ndim > 2:
raise ValueError("x and y can be no greater than 2-D")
if x.ndim == 1:
x = x[:, np.newaxis]
if y.ndim == 1:
y = y[:, np.newaxis]
return x, y
def _makeline(self, x, y, kw, kwargs):
kw = kw.copy() # Don't modify the original kw.
if not 'color' in kw and not 'color' in kwargs.keys():
kw['color'] = self.color_cycle.next()
# (can't use setdefault because it always evaluates
# its second argument)
seg = mlines.Line2D(x, y,
axes=self.axes,
**kw
)
self.set_lineprops(seg, **kwargs)
return seg
def _makefill(self, x, y, kw, kwargs):
try:
facecolor = kw['color']
except KeyError:
facecolor = self.color_cycle.next()
seg = mpatches.Polygon(np.hstack((x[:, np.newaxis],
y[:, np.newaxis])),
facecolor=facecolor,
fill=True,
closed=kw['closed'])
self.set_patchprops(seg, **kwargs)
return seg
def _plot_args(self, tup, kwargs):
ret = []
if len(tup) > 1 and is_string_like(tup[-1]):
linestyle, marker, color = _process_plot_format(tup[-1])
tup = tup[:-1]
elif len(tup) == 3:
raise ValueError('third arg must be a format string')
else:
linestyle, marker, color = None, None, None
kw = {}
for k, v in zip(('linestyle', 'marker', 'color'),
(linestyle, marker, color)):
if v is not None:
kw[k] = v
y = np.atleast_1d(tup[-1])
if len(tup) == 2:
x = np.atleast_1d(tup[0])
else:
x = np.arange(y.shape[0], dtype=float)
x, y = self._xy_from_xy(x, y)
if self.command == 'plot':
func = self._makeline
else:
kw['closed'] = kwargs.get('closed', True)
func = self._makefill
ncx, ncy = x.shape[1], y.shape[1]
for j in xrange(max(ncx, ncy)):
seg = func(x[:, j % ncx], y[:, j % ncy], kw, kwargs)
ret.append(seg)
return ret
def _grab_next_args(self, *args, **kwargs):
remaining = args
while 1:
if len(remaining) == 0:
return
if len(remaining) <= 3:
for seg in self._plot_args(remaining, kwargs):
yield seg
return
if is_string_like(remaining[2]):
isplit = 3
else:
isplit = 2
for seg in self._plot_args(remaining[:isplit], kwargs):
yield seg
remaining = remaining[isplit:]
class Axes(martist.Artist):
"""
The :class:`Axes` contains most of the figure elements:
:class:`~matplotlib.axis.Axis`, :class:`~matplotlib.axis.Tick`,
:class:`~matplotlib.lines.Line2D`, :class:`~matplotlib.text.Text`,
:class:`~matplotlib.patches.Polygon`, etc., and sets the
coordinate system.
The :class:`Axes` instance supports callbacks through a callbacks
attribute which is a :class:`~matplotlib.cbook.CallbackRegistry`
instance. The events you can connect to are 'xlim_changed' and
'ylim_changed' and the callback will be called with func(*ax*)
where *ax* is the :class:`Axes` instance.
"""
name = "rectilinear"
_shared_x_axes = cbook.Grouper()
_shared_y_axes = cbook.Grouper()
def __str__(self):
return "Axes(%g,%g;%gx%g)" % tuple(self._position.bounds)
def __init__(self, fig, rect,
axisbg=None, # defaults to rc axes.facecolor
frameon=True,
sharex=None, # use Axes instance's xaxis info
sharey=None, # use Axes instance's yaxis info
label='',
xscale=None,
yscale=None,
**kwargs
):
"""
Build an :class:`Axes` instance in
:class:`~matplotlib.figure.Figure` *fig* with
*rect=[left, bottom, width, height]* in
:class:`~matplotlib.figure.Figure` coordinates
Optional keyword arguments:
================ =========================================
Keyword Description
================ =========================================
*adjustable* [ 'box' | 'datalim' | 'box-forced']
*alpha* float: the alpha transparency (can be None)
*anchor* [ 'C', 'SW', 'S', 'SE', 'E', 'NE', 'N',
'NW', 'W' ]
*aspect* [ 'auto' | 'equal' | aspect_ratio ]
*autoscale_on* [ *True* | *False* ] whether or not to
autoscale the *viewlim*
*axis_bgcolor* any matplotlib color, see
:func:`~matplotlib.pyplot.colors`
*axisbelow* draw the grids and ticks below the other
artists
*cursor_props* a (*float*, *color*) tuple
*figure* a :class:`~matplotlib.figure.Figure`
instance
*frame_on* a boolean - draw the axes frame
*label* the axes label
*navigate* [ *True* | *False* ]
*navigate_mode* [ 'PAN' | 'ZOOM' | None ] the navigation
toolbar button status
*position* [left, bottom, width, height] in
class:`~matplotlib.figure.Figure` coords
*sharex* an class:`~matplotlib.axes.Axes` instance
to share the x-axis with
*sharey* an class:`~matplotlib.axes.Axes` instance
to share the y-axis with
*title* the title string
*visible* [ *True* | *False* ] whether the axes is
visible
*xlabel* the xlabel
*xlim* (*xmin*, *xmax*) view limits
*xscale* [%(scale)s]
*xticklabels* sequence of strings
*xticks* sequence of floats
*ylabel* the ylabel strings
*ylim* (*ymin*, *ymax*) view limits
*yscale* [%(scale)s]
*yticklabels* sequence of strings
*yticks* sequence of floats
================ =========================================
""" % {'scale': ' | '.join(
[repr(x) for x in mscale.get_scale_names()])}
martist.Artist.__init__(self)
if isinstance(rect, mtransforms.Bbox):
self._position = rect
else:
self._position = mtransforms.Bbox.from_bounds(*rect)
self._originalPosition = self._position.frozen()
self.set_axes(self)
self.set_aspect('auto')
self._adjustable = 'box'
self.set_anchor('C')
self._sharex = sharex
self._sharey = sharey
if sharex is not None:
self._shared_x_axes.join(self, sharex)
if sharex._adjustable == 'box':
sharex._adjustable = 'datalim'
#warnings.warn(
# 'shared axes: "adjustable" is being changed to "datalim"')
self._adjustable = 'datalim'
if sharey is not None:
self._shared_y_axes.join(self, sharey)
if sharey._adjustable == 'box':
sharey._adjustable = 'datalim'
#warnings.warn(
# 'shared axes: "adjustable" is being changed to "datalim"')
self._adjustable = 'datalim'
self.set_label(label)
self.set_figure(fig)
self.set_axes_locator(kwargs.get("axes_locator", None))
self.spines = self._gen_axes_spines()
# this call may differ for non-sep axes, eg polar
self._init_axis()
if axisbg is None:
axisbg = rcParams['axes.facecolor']
self._axisbg = axisbg
self._frameon = frameon
self._axisbelow = rcParams['axes.axisbelow']
self._rasterization_zorder = None
self._hold = rcParams['axes.hold']
self._connected = {} # a dict from events to (id, func)
self.cla()
# funcs used to format x and y - fall back on major formatters
self.fmt_xdata = None
self.fmt_ydata = None
self.set_cursor_props((1, 'k')) # set the cursor properties for axes
self._cachedRenderer = None
self.set_navigate(True)
self.set_navigate_mode(None)
if xscale:
self.set_xscale(xscale)
if yscale:
self.set_yscale(yscale)
if len(kwargs):
martist.setp(self, **kwargs)
if self.xaxis is not None:
self._xcid = self.xaxis.callbacks.connect('units finalize',
self.relim)
if self.yaxis is not None:
self._ycid = self.yaxis.callbacks.connect('units finalize',
self.relim)
def __setstate__(self, state):
self.__dict__ = state
# put the _remove_method back on all artists contained within the axes
for container_name in ['lines', 'collections', 'tables', 'patches',
'texts', 'images']:
container = getattr(self, container_name)
for artist in container:
artist._remove_method = container.remove
def get_window_extent(self, *args, **kwargs):
"""
get the axes bounding box in display space; *args* and
*kwargs* are empty
"""
return self.bbox
def _init_axis(self):
"move this out of __init__ because non-separable axes don't use it"
self.xaxis = maxis.XAxis(self)
self.spines['bottom'].register_axis(self.xaxis)
self.spines['top'].register_axis(self.xaxis)
self.yaxis = maxis.YAxis(self)
self.spines['left'].register_axis(self.yaxis)
self.spines['right'].register_axis(self.yaxis)
self._update_transScale()
def set_figure(self, fig):
"""
Set the class:`~matplotlib.axes.Axes` figure
accepts a class:`~matplotlib.figure.Figure` instance
"""
martist.Artist.set_figure(self, fig)
self.bbox = mtransforms.TransformedBbox(self._position,
fig.transFigure)
# these will be updated later as data is added
self.dataLim = mtransforms.Bbox.null()
self.viewLim = mtransforms.Bbox.unit()
self.transScale = mtransforms.TransformWrapper(
mtransforms.IdentityTransform())
self._set_lim_and_transforms()
def _set_lim_and_transforms(self):
"""
set the *dataLim* and *viewLim*
:class:`~matplotlib.transforms.Bbox` attributes and the
*transScale*, *transData*, *transLimits* and *transAxes*
transformations.
.. note::
This method is primarily used by rectilinear projections
of the :class:`~matplotlib.axes.Axes` class, and is meant
to be overridden by new kinds of projection axes that need
different transformations and limits. (See
:class:`~matplotlib.projections.polar.PolarAxes` for an
example.
"""
self.transAxes = mtransforms.BboxTransformTo(self.bbox)
# Transforms the x and y axis separately by a scale factor.
# It is assumed that this part will have non-linear components
# (e.g., for a log scale).
self.transScale = mtransforms.TransformWrapper(
mtransforms.IdentityTransform())
# An affine transformation on the data, generally to limit the
# range of the axes
self.transLimits = mtransforms.BboxTransformFrom(
mtransforms.TransformedBbox(self.viewLim, self.transScale))
# The parentheses are important for efficiency here -- they
# group the last two (which are usually affines) separately
# from the first (which, with log-scaling can be non-affine).
self.transData = self.transScale + (self.transLimits + self.transAxes)
self._xaxis_transform = mtransforms.blended_transform_factory(
self.transData, self.transAxes)
self._yaxis_transform = mtransforms.blended_transform_factory(
self.transAxes, self.transData)
def get_xaxis_transform(self, which='grid'):
"""
Get the transformation used for drawing x-axis labels, ticks
and gridlines. The x-direction is in data coordinates and the
y-direction is in axis coordinates.
.. note::
This transformation is primarily used by the
:class:`~matplotlib.axis.Axis` class, and is meant to be
overridden by new kinds of projections that may need to
place axis elements in different locations.
"""
if which == 'grid':
return self._xaxis_transform
elif which == 'tick1':
# for cartesian projection, this is bottom spine
return self.spines['bottom'].get_spine_transform()
elif which == 'tick2':
# for cartesian projection, this is top spine
return self.spines['top'].get_spine_transform()
else:
raise ValueError('unknown value for which')
def get_xaxis_text1_transform(self, pad_points):
"""
Get the transformation used for drawing x-axis labels, which
will add the given amount of padding (in points) between the
axes and the label. The x-direction is in data coordinates
and the y-direction is in axis coordinates. Returns a
3-tuple of the form::
(transform, valign, halign)
where *valign* and *halign* are requested alignments for the
text.
.. note::
This transformation is primarily used by the
:class:`~matplotlib.axis.Axis` class, and is meant to be
overridden by new kinds of projections that may need to
place axis elements in different locations.
"""
return (self.get_xaxis_transform(which='tick1') +
mtransforms.ScaledTranslation(0, -1 * pad_points / 72.0,
self.figure.dpi_scale_trans),
"top", "center")
def get_xaxis_text2_transform(self, pad_points):
"""
Get the transformation used for drawing the secondary x-axis
labels, which will add the given amount of padding (in points)
between the axes and the label. The x-direction is in data
coordinates and the y-direction is in axis coordinates.
Returns a 3-tuple of the form::
(transform, valign, halign)
where *valign* and *halign* are requested alignments for the
text.
.. note::
This transformation is primarily used by the
:class:`~matplotlib.axis.Axis` class, and is meant to be
overridden by new kinds of projections that may need to
place axis elements in different locations.
"""
return (self.get_xaxis_transform(which='tick2') +
mtransforms.ScaledTranslation(0, pad_points / 72.0,
self.figure.dpi_scale_trans),
"bottom", "center")
def get_yaxis_transform(self, which='grid'):
"""
Get the transformation used for drawing y-axis labels, ticks
and gridlines. The x-direction is in axis coordinates and the
y-direction is in data coordinates.
.. note::
This transformation is primarily used by the
:class:`~matplotlib.axis.Axis` class, and is meant to be
overridden by new kinds of projections that may need to
place axis elements in different locations.
"""
if which == 'grid':
return self._yaxis_transform
elif which == 'tick1':
# for cartesian projection, this is bottom spine
return self.spines['left'].get_spine_transform()
elif which == 'tick2':
# for cartesian projection, this is top spine
return self.spines['right'].get_spine_transform()
else:
raise ValueError('unknown value for which')
def get_yaxis_text1_transform(self, pad_points):
"""
Get the transformation used for drawing y-axis labels, which
will add the given amount of padding (in points) between the
axes and the label. The x-direction is in axis coordinates
and the y-direction is in data coordinates. Returns a 3-tuple
of the form::
(transform, valign, halign)
where *valign* and *halign* are requested alignments for the
text.
.. note::
This transformation is primarily used by the
:class:`~matplotlib.axis.Axis` class, and is meant to be
overridden by new kinds of projections that may need to
place axis elements in different locations.
"""
return (self.get_yaxis_transform(which='tick1') +
mtransforms.ScaledTranslation(-1 * pad_points / 72.0, 0,
self.figure.dpi_scale_trans),
"center", "right")
def get_yaxis_text2_transform(self, pad_points):
"""
Get the transformation used for drawing the secondary y-axis
labels, which will add the given amount of padding (in points)
between the axes and the label. The x-direction is in axis
coordinates and the y-direction is in data coordinates.
Returns a 3-tuple of the form::
(transform, valign, halign)
where *valign* and *halign* are requested alignments for the
text.
.. note::
This transformation is primarily used by the
:class:`~matplotlib.axis.Axis` class, and is meant to be
overridden by new kinds of projections that may need to
place axis elements in different locations.
"""
return (self.get_yaxis_transform(which='tick2') +
mtransforms.ScaledTranslation(pad_points / 72.0, 0,
self.figure.dpi_scale_trans),
"center", "left")
def _update_transScale(self):
self.transScale.set(
mtransforms.blended_transform_factory(
self.xaxis.get_transform(), self.yaxis.get_transform()))
if hasattr(self, "lines"):
for line in self.lines:
try:
line._transformed_path.invalidate()
except AttributeError:
pass
def get_position(self, original=False):
'Return the a copy of the axes rectangle as a Bbox'
if original:
return self._originalPosition.frozen()
else:
return self._position.frozen()
def set_position(self, pos, which='both'):
"""
Set the axes position with::
pos = [left, bottom, width, height]
in relative 0,1 coords, or *pos* can be a
:class:`~matplotlib.transforms.Bbox`
There are two position variables: one which is ultimately
used, but which may be modified by :meth:`apply_aspect`, and a
second which is the starting point for :meth:`apply_aspect`.
Optional keyword arguments:
*which*
========== ====================
value description
========== ====================
'active' to change the first
'original' to change the second
'both' to change both
========== ====================
"""
if not isinstance(pos, mtransforms.BboxBase):
pos = mtransforms.Bbox.from_bounds(*pos)
if which in ('both', 'active'):
self._position.set(pos)
if which in ('both', 'original'):
self._originalPosition.set(pos)
def reset_position(self):
"""Make the original position the active position"""
pos = self.get_position(original=True)
self.set_position(pos, which='active')
def set_axes_locator(self, locator):
"""
set axes_locator
ACCEPT: a callable object which takes an axes instance and renderer and
returns a bbox.
"""
self._axes_locator = locator
def get_axes_locator(self):
"""
return axes_locator
"""
return self._axes_locator
def _set_artist_props(self, a):
"""set the boilerplate props for artists added to axes"""
a.set_figure(self.figure)
if not a.is_transform_set():
a.set_transform(self.transData)
a.set_axes(self)
def _gen_axes_patch(self):
"""
Returns the patch used to draw the background of the axes. It
is also used as the clipping path for any data elements on the
axes.
In the standard axes, this is a rectangle, but in other
projections it may not be.
.. note::
Intended to be overridden by new projection types.
"""
return mpatches.Rectangle((0.0, 0.0), 1.0, 1.0)
def _gen_axes_spines(self, locations=None, offset=0.0, units='inches'):
"""
Returns a dict whose keys are spine names and values are
Line2D or Patch instances. Each element is used to draw a
spine of the axes.
In the standard axes, this is a single line segment, but in
other projections it may not be.
.. note::
Intended to be overridden by new projection types.
"""
return {
'left': mspines.Spine.linear_spine(self, 'left'),
'right': mspines.Spine.linear_spine(self, 'right'),
'bottom': mspines.Spine.linear_spine(self, 'bottom'),
'top': mspines.Spine.linear_spine(self, 'top'), }
def cla(self):
"""Clear the current axes."""
# Note: this is called by Axes.__init__()
self.xaxis.cla()
self.yaxis.cla()
for name, spine in self.spines.iteritems():
spine.cla()
self.ignore_existing_data_limits = True
self.callbacks = cbook.CallbackRegistry()
if self._sharex is not None:
# major and minor are class instances with
# locator and formatter attributes
self.xaxis.major = self._sharex.xaxis.major
self.xaxis.minor = self._sharex.xaxis.minor
x0, x1 = self._sharex.get_xlim()
self.set_xlim(x0, x1, emit=False, auto=None)
# Save the current formatter/locator so we don't lose it
majf = self._sharex.xaxis.get_major_formatter()
minf = self._sharex.xaxis.get_minor_formatter()
majl = self._sharex.xaxis.get_major_locator()
minl = self._sharex.xaxis.get_minor_locator()
# This overwrites the current formatter/locator
self.xaxis._set_scale(self._sharex.xaxis.get_scale())
# Reset the formatter/locator
self.xaxis.set_major_formatter(majf)
self.xaxis.set_minor_formatter(minf)
self.xaxis.set_major_locator(majl)
self.xaxis.set_minor_locator(minl)
else:
self.xaxis._set_scale('linear')
if self._sharey is not None:
self.yaxis.major = self._sharey.yaxis.major
self.yaxis.minor = self._sharey.yaxis.minor
y0, y1 = self._sharey.get_ylim()
self.set_ylim(y0, y1, emit=False, auto=None)
# Save the current formatter/locator so we don't lose it
majf = self._sharey.yaxis.get_major_formatter()
minf = self._sharey.yaxis.get_minor_formatter()
majl = self._sharey.yaxis.get_major_locator()
minl = self._sharey.yaxis.get_minor_locator()
# This overwrites the current formatter/locator
self.yaxis._set_scale(self._sharey.yaxis.get_scale())
# Reset the formatter/locator
self.yaxis.set_major_formatter(majf)
self.yaxis.set_minor_formatter(minf)
self.yaxis.set_major_locator(majl)
self.yaxis.set_minor_locator(minl)
else:
self.yaxis._set_scale('linear')
self._autoscaleXon = True
self._autoscaleYon = True
self._xmargin = rcParams['axes.xmargin']
self._ymargin = rcParams['axes.ymargin']
self._tight = False
self._update_transScale() # needed?
self._get_lines = _process_plot_var_args(self)
self._get_patches_for_fill = _process_plot_var_args(self, 'fill')
self._gridOn = rcParams['axes.grid']
self.lines = []
self.patches = []
self.texts = []
self.tables = []
self.artists = []
self.images = []
self._current_image = None # strictly for pyplot via _sci, _gci
self.legend_ = None
self.collections = [] # collection.Collection instances
self.containers = []
self.grid(self._gridOn)
props = font_manager.FontProperties(size=rcParams['axes.titlesize'])
self.titleOffsetTrans = mtransforms.ScaledTranslation(
0.0, 5.0 / 72.0, self.figure.dpi_scale_trans)
self.title = mtext.Text(
x=0.5, y=1.0, text='',
fontproperties=props,
verticalalignment='baseline',
horizontalalignment='center',
)
self._left_title = mtext.Text(
x=0.0, y=1.0, text='',
fontproperties=props,
verticalalignment='baseline',
horizontalalignment='left', )
self._right_title = mtext.Text(
x=1.0, y=1.0, text='',
fontproperties=props,
verticalalignment='baseline',
horizontalalignment='right',
)
for _title in (self.title, self._left_title, self._right_title):
_title.set_transform(self.transAxes + self.titleOffsetTrans)
_title.set_clip_box(None)
self._set_artist_props(_title)
# the patch draws the background of the axes. we want this to
# be below the other artists; the axesPatch name is
# deprecated. We use the frame to draw the edges so we are
# setting the edgecolor to None
self.patch = self.axesPatch = self._gen_axes_patch()
self.patch.set_figure(self.figure)
self.patch.set_facecolor(self._axisbg)
self.patch.set_edgecolor('None')
self.patch.set_linewidth(0)
self.patch.set_transform(self.transAxes)
self.axison = True
self.xaxis.set_clip_path(self.patch)
self.yaxis.set_clip_path(self.patch)
self._shared_x_axes.clean()
self._shared_y_axes.clean()
def clear(self):
"""clear the axes"""
self.cla()
def set_color_cycle(self, clist):
"""
Set the color cycle for any future plot commands on this Axes.
*clist* is a list of mpl color specifiers.
"""
self._get_lines.set_color_cycle(clist)
self._get_patches_for_fill.set_color_cycle(clist)
def ishold(self):
"""return the HOLD status of the axes"""
return self._hold
def hold(self, b=None):
"""
Call signature::
hold(b=None)
Set the hold state. If *hold* is *None* (default), toggle the
*hold* state. Else set the *hold* state to boolean value *b*.
Examples::
# toggle hold
hold()
# turn hold on
hold(True)
# turn hold off
hold(False)
When hold is *True*, subsequent plot commands will be added to
the current axes. When hold is *False*, the current axes and
figure will be cleared on the next plot command
"""
if b is None:
self._hold = not self._hold
else:
self._hold = b
def get_aspect(self):
return self._aspect
def set_aspect(self, aspect, adjustable=None, anchor=None):
"""
*aspect*
======== ================================================
value description
======== ================================================
'auto' automatic; fill position rectangle with data
'normal' same as 'auto'; deprecated
'equal' same scaling from data to plot units for x and y
num a circle will be stretched such that the height
is num times the width. aspect=1 is the same as
aspect='equal'.
======== ================================================
*adjustable*
============ =====================================
value description
============ =====================================
'box' change physical size of axes
'datalim' change xlim or ylim
'box-forced' same as 'box', but axes can be shared
============ =====================================
'box' does not allow axes sharing, as this can cause
unintended side effect. For cases when sharing axes is
fine, use 'box-forced'.
*anchor*
===== =====================
value description
===== =====================
'C' centered
'SW' lower left corner
'S' middle of bottom edge
'SE' lower right corner
etc.
===== =====================
.. deprecated:: 1.2
the option 'normal' for aspect is deprecated. Use 'auto' instead.
"""
if aspect == 'normal':
cbook.warn_deprecated(
'1.2', name='normal', alternative='auto', obj_type='aspect')
self._aspect = 'auto'
elif aspect in ('equal', 'auto'):
self._aspect = aspect
else:
self._aspect = float(aspect) # raise ValueError if necessary
if adjustable is not None:
self.set_adjustable(adjustable)
if anchor is not None:
self.set_anchor(anchor)
def get_adjustable(self):
return self._adjustable
def set_adjustable(self, adjustable):
"""
ACCEPTS: [ 'box' | 'datalim' | 'box-forced']
"""
if adjustable in ('box', 'datalim', 'box-forced'):
if self in self._shared_x_axes or self in self._shared_y_axes:
if adjustable == 'box':
raise ValueError(
'adjustable must be "datalim" for shared axes')
self._adjustable = adjustable
else:
raise ValueError('argument must be "box", or "datalim"')
def get_anchor(self):
return self._anchor
def set_anchor(self, anchor):
"""
*anchor*
===== ============
value description
===== ============
'C' Center
'SW' bottom left
'S' bottom
'SE' bottom right
'E' right
'NE' top right
'N' top
'NW' top left
'W' left
===== ============
"""
if anchor in mtransforms.Bbox.coefs.keys() or len(anchor) == 2:
self._anchor = anchor
else:
raise ValueError('argument must be among %s' %
', '.join(mtransforms.Bbox.coefs.keys()))
def get_data_ratio(self):
"""
Returns the aspect ratio of the raw data.
This method is intended to be overridden by new projection
types.
"""
xmin, xmax = self.get_xbound()
ymin, ymax = self.get_ybound()
xsize = max(math.fabs(xmax - xmin), 1e-30)
ysize = max(math.fabs(ymax - ymin), 1e-30)
return ysize / xsize
def get_data_ratio_log(self):
"""
Returns the aspect ratio of the raw data in log scale.
Will be used when both axis scales are in log.
"""
xmin, xmax = self.get_xbound()
ymin, ymax = self.get_ybound()
xsize = max(math.fabs(math.log10(xmax) - math.log10(xmin)), 1e-30)
ysize = max(math.fabs(math.log10(ymax) - math.log10(ymin)), 1e-30)
return ysize / xsize
def apply_aspect(self, position=None):
"""
Use :meth:`_aspect` and :meth:`_adjustable` to modify the
axes box or the view limits.
"""
if position is None:
position = self.get_position(original=True)
aspect = self.get_aspect()
if self.name != 'polar':
xscale, yscale = self.get_xscale(), self.get_yscale()
if xscale == "linear" and yscale == "linear":
aspect_scale_mode = "linear"
elif xscale == "log" and yscale == "log":
aspect_scale_mode = "log"
elif ((xscale == "linear" and yscale == "log") or
(xscale == "log" and yscale == "linear")):
if aspect is not "auto":
warnings.warn(
'aspect is not supported for Axes with xscale=%s, '
'yscale=%s' % (xscale, yscale))
aspect = "auto"
else: # some custom projections have their own scales.
pass
else:
aspect_scale_mode = "linear"
if aspect == 'auto':
self.set_position(position, which='active')
return
if aspect == 'equal':
A = 1
else:
A = aspect
#Ensure at drawing time that any Axes involved in axis-sharing
# does not have its position changed.
if self in self._shared_x_axes or self in self._shared_y_axes:
if self._adjustable == 'box':
self._adjustable = 'datalim'
warnings.warn(
'shared axes: "adjustable" is being changed to "datalim"')
figW, figH = self.get_figure().get_size_inches()
fig_aspect = figH / figW
if self._adjustable in ['box', 'box-forced']:
if aspect_scale_mode == "log":
box_aspect = A * self.get_data_ratio_log()
else:
box_aspect = A * self.get_data_ratio()
pb = position.frozen()
pb1 = pb.shrunk_to_aspect(box_aspect, pb, fig_aspect)
self.set_position(pb1.anchored(self.get_anchor(), pb), 'active')
return
# reset active to original in case it had been changed
# by prior use of 'box'
self.set_position(position, which='active')
xmin, xmax = self.get_xbound()
ymin, ymax = self.get_ybound()
if aspect_scale_mode == "log":
xmin, xmax = math.log10(xmin), math.log10(xmax)
ymin, ymax = math.log10(ymin), math.log10(ymax)
xsize = max(math.fabs(xmax - xmin), 1e-30)
ysize = max(math.fabs(ymax - ymin), 1e-30)
l, b, w, h = position.bounds
box_aspect = fig_aspect * (h / w)
data_ratio = box_aspect / A
y_expander = (data_ratio * xsize / ysize - 1.0)
#print 'y_expander', y_expander
# If y_expander > 0, the dy/dx viewLim ratio needs to increase
if abs(y_expander) < 0.005:
#print 'good enough already'
return
if aspect_scale_mode == "log":
dL = self.dataLim
dL_width = math.log10(dL.x1) - math.log10(dL.x0)
dL_height = math.log10(dL.y1) - math.log10(dL.y0)
xr = 1.05 * dL_width
yr = 1.05 * dL_height
else:
dL = self.dataLim
xr = 1.05 * dL.width
yr = 1.05 * dL.height
xmarg = xsize - xr
ymarg = ysize - yr
Ysize = data_ratio * xsize
Xsize = ysize / data_ratio
Xmarg = Xsize - xr
Ymarg = Ysize - yr
xm = 0 # Setting these targets to, e.g., 0.05*xr does not seem to
# help.
ym = 0
#print 'xmin, xmax, ymin, ymax', xmin, xmax, ymin, ymax
#print 'xsize, Xsize, ysize, Ysize', xsize, Xsize, ysize, Ysize
changex = (self in self._shared_y_axes
and self not in self._shared_x_axes)
changey = (self in self._shared_x_axes
and self not in self._shared_y_axes)
if changex and changey:
warnings.warn("adjustable='datalim' cannot work with shared "
"x and y axes")
return
if changex:
adjust_y = False
else:
#print 'xmarg, ymarg, Xmarg, Ymarg', xmarg, ymarg, Xmarg, Ymarg
if xmarg > xm and ymarg > ym:
adjy = ((Ymarg > 0 and y_expander < 0)
or (Xmarg < 0 and y_expander > 0))
else:
adjy = y_expander > 0
#print 'y_expander, adjy', y_expander, adjy
adjust_y = changey or adjy # (Ymarg > xmarg)
if adjust_y:
yc = 0.5 * (ymin + ymax)
y0 = yc - Ysize / 2.0
y1 = yc + Ysize / 2.0
if aspect_scale_mode == "log":
self.set_ybound((10. ** y0, 10. ** y1))
else:
self.set_ybound((y0, y1))
#print 'New y0, y1:', y0, y1
#print 'New ysize, ysize/xsize', y1-y0, (y1-y0)/xsize
else:
xc = 0.5 * (xmin + xmax)
x0 = xc - Xsize / 2.0
x1 = xc + Xsize / 2.0
if aspect_scale_mode == "log":
self.set_xbound((10. ** x0, 10. ** x1))
else:
self.set_xbound((x0, x1))
#print 'New x0, x1:', x0, x1
#print 'New xsize, ysize/xsize', x1-x0, ysize/(x1-x0)
def axis(self, *v, **kwargs):
"""
Convenience method for manipulating the x and y view limits
and the aspect ratio of the plot. For details, see
:func:`~matplotlib.pyplot.axis`.
*kwargs* are passed on to :meth:`set_xlim` and
:meth:`set_ylim`
"""
if len(v) == 0 and len(kwargs) == 0:
xmin, xmax = self.get_xlim()
ymin, ymax = self.get_ylim()
return xmin, xmax, ymin, ymax
if len(v) == 1 and is_string_like(v[0]):
s = v[0].lower()
if s == 'on':
self.set_axis_on()
elif s == 'off':
self.set_axis_off()
elif s in ('equal', 'tight', 'scaled', 'normal', 'auto', 'image'):
self.set_autoscale_on(True)
self.set_aspect('auto')
self.autoscale_view(tight=False)
# self.apply_aspect()
if s == 'equal':
self.set_aspect('equal', adjustable='datalim')
elif s == 'scaled':
self.set_aspect('equal', adjustable='box', anchor='C')
self.set_autoscale_on(False) # Req. by Mark Bakker
elif s == 'tight':
self.autoscale_view(tight=True)
self.set_autoscale_on(False)
elif s == 'image':
self.autoscale_view(tight=True)
self.set_autoscale_on(False)
self.set_aspect('equal', adjustable='box', anchor='C')
else:
raise ValueError('Unrecognized string %s to axis; '
'try on or off' % s)
xmin, xmax = self.get_xlim()
ymin, ymax = self.get_ylim()
return xmin, xmax, ymin, ymax
emit = kwargs.get('emit', True)
try:
v[0]
except IndexError:
xmin = kwargs.get('xmin', None)
xmax = kwargs.get('xmax', None)
auto = False # turn off autoscaling, unless...
if xmin is None and xmax is None:
auto = None # leave autoscaling state alone
xmin, xmax = self.set_xlim(xmin, xmax, emit=emit, auto=auto)
ymin = kwargs.get('ymin', None)
ymax = kwargs.get('ymax', None)
auto = False # turn off autoscaling, unless...
if ymin is None and ymax is None:
auto = None # leave autoscaling state alone
ymin, ymax = self.set_ylim(ymin, ymax, emit=emit, auto=auto)
return xmin, xmax, ymin, ymax
v = v[0]
if len(v) != 4:
raise ValueError('v must contain [xmin xmax ymin ymax]')
self.set_xlim([v[0], v[1]], emit=emit, auto=False)
self.set_ylim([v[2], v[3]], emit=emit, auto=False)
return v
def get_legend(self):
"""
Return the legend.Legend instance, or None if no legend is defined
"""
return self.legend_
def get_images(self):
"""return a list of Axes images contained by the Axes"""
return cbook.silent_list('AxesImage', self.images)
def get_lines(self):
"""Return a list of lines contained by the Axes"""
return cbook.silent_list('Line2D', self.lines)
def get_xaxis(self):
"""Return the XAxis instance"""
return self.xaxis
def get_xgridlines(self):
"""Get the x grid lines as a list of Line2D instances"""
return cbook.silent_list('Line2D xgridline',
self.xaxis.get_gridlines())
def get_xticklines(self):
"""Get the xtick lines as a list of Line2D instances"""
return cbook.silent_list('Text xtickline',
self.xaxis.get_ticklines())
def get_yaxis(self):
"""Return the YAxis instance"""
return self.yaxis
def get_ygridlines(self):
"""Get the y grid lines as a list of Line2D instances"""
return cbook.silent_list('Line2D ygridline',
self.yaxis.get_gridlines())
def get_yticklines(self):
"""Get the ytick lines as a list of Line2D instances"""
return cbook.silent_list('Line2D ytickline',
self.yaxis.get_ticklines())
#### Adding and tracking artists
def _sci(self, im):
"""
helper for :func:`~matplotlib.pyplot.sci`;
do not use elsewhere.
"""
if isinstance(im, matplotlib.contour.ContourSet):
if im.collections[0] not in self.collections:
raise ValueError(
"ContourSet must be in current Axes")
elif im not in self.images and im not in self.collections:
raise ValueError(
"Argument must be an image, collection, or ContourSet in "
"this Axes")
self._current_image = im
def _gci(self):
"""
Helper for :func:`~matplotlib.pyplot.gci`;
do not use elsewhere.
"""
return self._current_image
def has_data(self):
"""
Return *True* if any artists have been added to axes.
This should not be used to determine whether the *dataLim*
need to be updated, and may not actually be useful for
anything.
"""
return (
len(self.collections) +
len(self.images) +
len(self.lines) +
len(self.patches)) > 0
def add_artist(self, a):
"""
Add any :class:`~matplotlib.artist.Artist` to the axes.
Returns the artist.
"""
a.set_axes(self)
self.artists.append(a)
self._set_artist_props(a)
a.set_clip_path(self.patch)
a._remove_method = lambda h: self.artists.remove(h)
return a
def add_collection(self, collection, autolim=True):
"""
Add a :class:`~matplotlib.collections.Collection` instance
to the axes.
Returns the collection.
"""
label = collection.get_label()
if not label:
collection.set_label('_collection%d' % len(self.collections))
self.collections.append(collection)
self._set_artist_props(collection)
if collection.get_clip_path() is None:
collection.set_clip_path(self.patch)
if (autolim and
collection._paths is not None and
len(collection._paths) and
len(collection._offsets)):
self.update_datalim(collection.get_datalim(self.transData))
collection._remove_method = lambda h: self.collections.remove(h)
return collection
def add_line(self, line):
"""
Add a :class:`~matplotlib.lines.Line2D` to the list of plot
lines
Returns the line.
"""
self._set_artist_props(line)
if line.get_clip_path() is None:
line.set_clip_path(self.patch)
self._update_line_limits(line)
if not line.get_label():
line.set_label('_line%d' % len(self.lines))
self.lines.append(line)
line._remove_method = lambda h: self.lines.remove(h)
return line
def _update_line_limits(self, line):
"""
Figures out the data limit of the given line, updating self.dataLim.
"""
path = line.get_path()
if path.vertices.size == 0:
return
line_trans = line.get_transform()
if line_trans == self.transData:
data_path = path
elif any(line_trans.contains_branch_seperately(self.transData)):
# identify the transform to go from line's coordinates
# to data coordinates
trans_to_data = line_trans - self.transData
# if transData is affine we can use the cached non-affine component
# of line's path. (since the non-affine part of line_trans is
# entirely encapsulated in trans_to_data).
if self.transData.is_affine:
line_trans_path = line._get_transformed_path()
na_path, _ = line_trans_path.get_transformed_path_and_affine()
data_path = trans_to_data.transform_path_affine(na_path)
else:
data_path = trans_to_data.transform_path(path)
else:
# for backwards compatibility we update the dataLim with the
# coordinate range of the given path, even though the coordinate
# systems are completely different. This may occur in situations
# such as when ax.transAxes is passed through for absolute
# positioning.
data_path = path
if data_path.vertices.size > 0:
updatex, updatey = line_trans.contains_branch_seperately(
self.transData
)
self.dataLim.update_from_path(data_path,
self.ignore_existing_data_limits,
updatex=updatex,
updatey=updatey)
self.ignore_existing_data_limits = False
def add_patch(self, p):
"""
Add a :class:`~matplotlib.patches.Patch` *p* to the list of
axes patches; the clipbox will be set to the Axes clipping
box. If the transform is not set, it will be set to
:attr:`transData`.
Returns the patch.
"""
self._set_artist_props(p)
if p.get_clip_path() is None:
p.set_clip_path(self.patch)
self._update_patch_limits(p)
self.patches.append(p)
p._remove_method = lambda h: self.patches.remove(h)
return p
def _update_patch_limits(self, patch):
"""update the data limits for patch *p*"""
# hist can add zero height Rectangles, which is useful to keep
# the bins, counts and patches lined up, but it throws off log
# scaling. We'll ignore rects with zero height or width in
# the auto-scaling
# cannot check for '==0' since unitized data may not compare to zero
if (isinstance(patch, mpatches.Rectangle) and
((not patch.get_width()) or (not patch.get_height()))):
return
vertices = patch.get_path().vertices
if vertices.size > 0:
xys = patch.get_patch_transform().transform(vertices)
if patch.get_data_transform() != self.transData:
patch_to_data = (patch.get_data_transform() -
self.transData)
xys = patch_to_data.transform(xys)
updatex, updatey = patch.get_transform().\
contains_branch_seperately(self.transData)
self.update_datalim(xys, updatex=updatex,
updatey=updatey)
def add_table(self, tab):
"""
Add a :class:`~matplotlib.tables.Table` instance to the
list of axes tables
Returns the table.
"""
self._set_artist_props(tab)
self.tables.append(tab)
tab.set_clip_path(self.patch)
tab._remove_method = lambda h: self.tables.remove(h)
return tab
def add_container(self, container):
"""
Add a :class:`~matplotlib.container.Container` instance
to the axes.
Returns the collection.
"""
label = container.get_label()
if not label:
container.set_label('_container%d' % len(self.containers))
self.containers.append(container)
container.set_remove_method(lambda h: self.containers.remove(h))
return container
def relim(self):
"""
Recompute the data limits based on current artists.
At present, :class:`~matplotlib.collections.Collection`
instances are not supported.
"""
# Collections are deliberately not supported (yet); see
# the TODO note in artists.py.
self.dataLim.ignore(True)
self.dataLim.set_points(mtransforms.Bbox.null().get_points())
self.ignore_existing_data_limits = True
for line in self.lines:
self._update_line_limits(line)
for p in self.patches:
self._update_patch_limits(p)
def update_datalim(self, xys, updatex=True, updatey=True):
"""
Update the data lim bbox with seq of xy tups or equiv. 2-D array
"""
# if no data is set currently, the bbox will ignore its
# limits and set the bound to be the bounds of the xydata.
# Otherwise, it will compute the bounds of it's current data
# and the data in xydata
if iterable(xys) and not len(xys):
return
if not ma.isMaskedArray(xys):
xys = np.asarray(xys)
self.dataLim.update_from_data_xy(xys, self.ignore_existing_data_limits,
updatex=updatex, updatey=updatey)
self.ignore_existing_data_limits = False
def update_datalim_numerix(self, x, y):
"""
Update the data lim bbox with seq of xy tups
"""
# if no data is set currently, the bbox will ignore it's
# limits and set the bound to be the bounds of the xydata.
# Otherwise, it will compute the bounds of it's current data
# and the data in xydata
if iterable(x) and not len(x):
return
self.dataLim.update_from_data(x, y, self.ignore_existing_data_limits)
self.ignore_existing_data_limits = False
def update_datalim_bounds(self, bounds):
"""
Update the datalim to include the given
:class:`~matplotlib.transforms.Bbox` *bounds*
"""
self.dataLim.set(mtransforms.Bbox.union([self.dataLim, bounds]))
def _process_unit_info(self, xdata=None, ydata=None, kwargs=None):
"""Look for unit *kwargs* and update the axis instances as necessary"""
if self.xaxis is None or self.yaxis is None:
return
#print 'processing', self.get_geometry()
if xdata is not None:
# we only need to update if there is nothing set yet.
if not self.xaxis.have_units():
self.xaxis.update_units(xdata)
#print '\tset from xdata', self.xaxis.units
if ydata is not None:
# we only need to update if there is nothing set yet.
if not self.yaxis.have_units():
self.yaxis.update_units(ydata)
#print '\tset from ydata', self.yaxis.units
# process kwargs 2nd since these will override default units
if kwargs is not None:
xunits = kwargs.pop('xunits', self.xaxis.units)
if self.name == 'polar':
xunits = kwargs.pop('thetaunits', xunits)
if xunits != self.xaxis.units:
#print '\tkw setting xunits', xunits
self.xaxis.set_units(xunits)
# If the units being set imply a different converter,
# we need to update.
if xdata is not None:
self.xaxis.update_units(xdata)
yunits = kwargs.pop('yunits', self.yaxis.units)
if self.name == 'polar':
yunits = kwargs.pop('runits', yunits)
if yunits != self.yaxis.units:
#print '\tkw setting yunits', yunits
self.yaxis.set_units(yunits)
# If the units being set imply a different converter,
# we need to update.
if ydata is not None:
self.yaxis.update_units(ydata)
def in_axes(self, mouseevent):
"""
Return *True* if the given *mouseevent* (in display coords)
is in the Axes
"""
return self.patch.contains(mouseevent)[0]
def get_autoscale_on(self):
"""
Get whether autoscaling is applied for both axes on plot commands
"""
return self._autoscaleXon and self._autoscaleYon
def get_autoscalex_on(self):
"""
Get whether autoscaling for the x-axis is applied on plot commands
"""
return self._autoscaleXon
def get_autoscaley_on(self):
"""
Get whether autoscaling for the y-axis is applied on plot commands
"""
return self._autoscaleYon
def set_autoscale_on(self, b):
"""
Set whether autoscaling is applied on plot commands
accepts: [ *True* | *False* ]
"""
self._autoscaleXon = b
self._autoscaleYon = b
def set_autoscalex_on(self, b):
"""
Set whether autoscaling for the x-axis is applied on plot commands
accepts: [ *True* | *False* ]
"""
self._autoscaleXon = b
def set_autoscaley_on(self, b):
"""
Set whether autoscaling for the y-axis is applied on plot commands
accepts: [ *True* | *False* ]
"""
self._autoscaleYon = b
def set_xmargin(self, m):
"""
Set padding of X data limits prior to autoscaling.
*m* times the data interval will be added to each
end of that interval before it is used in autoscaling.
accepts: float in range 0 to 1
"""
if m < 0 or m > 1:
raise ValueError("margin must be in range 0 to 1")
self._xmargin = m
def set_ymargin(self, m):
"""
Set padding of Y data limits prior to autoscaling.
*m* times the data interval will be added to each
end of that interval before it is used in autoscaling.
accepts: float in range 0 to 1
"""
if m < 0 or m > 1:
raise ValueError("margin must be in range 0 to 1")
self._ymargin = m
def margins(self, *args, **kw):
"""
Set or retrieve autoscaling margins.
signatures::
margins()
returns xmargin, ymargin
::
margins(margin)
margins(xmargin, ymargin)
margins(x=xmargin, y=ymargin)
margins(..., tight=False)
All three forms above set the xmargin and ymargin parameters.
All keyword parameters are optional. A single argument
specifies both xmargin and ymargin. The *tight* parameter
is passed to :meth:`autoscale_view`, which is executed after
a margin is changed; the default here is *True*, on the
assumption that when margins are specified, no additional
padding to match tick marks is usually desired. Setting
*tight* to *None* will preserve the previous setting.
Specifying any margin changes only the autoscaling; for example,
if *xmargin* is not None, then *xmargin* times the X data
interval will be added to each end of that interval before
it is used in autoscaling.
"""
if not args and not kw:
return self._xmargin, self._ymargin
tight = kw.pop('tight', True)
mx = kw.pop('x', None)
my = kw.pop('y', None)
if len(args) == 1:
mx = my = args[0]
elif len(args) == 2:
mx, my = args
else:
raise ValueError("more than two arguments were supplied")
if mx is not None:
self.set_xmargin(mx)
if my is not None:
self.set_ymargin(my)
scalex = (mx is not None)
scaley = (my is not None)
self.autoscale_view(tight=tight, scalex=scalex, scaley=scaley)
def set_rasterization_zorder(self, z):
"""
Set zorder value below which artists will be rasterized. Set
to `None` to disable rasterizing of artists below a particular
zorder.
"""
self._rasterization_zorder = z
def get_rasterization_zorder(self):
"""
Get zorder value below which artists will be rasterized
"""
return self._rasterization_zorder
def autoscale(self, enable=True, axis='both', tight=None):
"""
Autoscale the axis view to the data (toggle).
Convenience method for simple axis view autoscaling.
It turns autoscaling on or off, and then,
if autoscaling for either axis is on, it performs
the autoscaling on the specified axis or axes.
*enable*: [True | False | None]
True (default) turns autoscaling on, False turns it off.
None leaves the autoscaling state unchanged.
*axis*: ['x' | 'y' | 'both']
which axis to operate on; default is 'both'
*tight*: [True | False | None]
If True, set view limits to data limits;
if False, let the locator and margins expand the view limits;
if None, use tight scaling if the only artist is an image,
otherwise treat *tight* as False.
The *tight* setting is retained for future autoscaling
until it is explicitly changed.
Returns None.
"""
if enable is None:
scalex = True
scaley = True
else:
scalex = False
scaley = False
if axis in ['x', 'both']:
self._autoscaleXon = bool(enable)
scalex = self._autoscaleXon
if axis in ['y', 'both']:
self._autoscaleYon = bool(enable)
scaley = self._autoscaleYon
self.autoscale_view(tight=tight, scalex=scalex, scaley=scaley)
def autoscale_view(self, tight=None, scalex=True, scaley=True):
"""
Autoscale the view limits using the data limits. You can
selectively autoscale only a single axis, eg, the xaxis by
setting *scaley* to *False*. The autoscaling preserves any
axis direction reversal that has already been done.
The data limits are not updated automatically when artist data are
changed after the artist has been added to an Axes instance. In that
case, use :meth:`matplotlib.axes.Axes.relim` prior to calling
autoscale_view.
"""
if tight is None:
# if image data only just use the datalim
_tight = self._tight or (len(self.images) > 0 and
len(self.lines) == 0 and
len(self.patches) == 0)
else:
_tight = self._tight = bool(tight)
if scalex and self._autoscaleXon:
xshared = self._shared_x_axes.get_siblings(self)
dl = [ax.dataLim for ax in xshared]
bb = mtransforms.BboxBase.union(dl)
x0, x1 = bb.intervalx
xlocator = self.xaxis.get_major_locator()
try:
# e.g., DateLocator has its own nonsingular()
x0, x1 = xlocator.nonsingular(x0, x1)
except AttributeError:
# Default nonsingular for, e.g., MaxNLocator
x0, x1 = mtransforms.nonsingular(x0, x1, increasing=False,
expander=0.05)
if self._xmargin > 0:
delta = (x1 - x0) * self._xmargin
x0 -= delta
x1 += delta
if not _tight:
x0, x1 = xlocator.view_limits(x0, x1)
self.set_xbound(x0, x1)
if scaley and self._autoscaleYon:
yshared = self._shared_y_axes.get_siblings(self)
dl = [ax.dataLim for ax in yshared]
bb = mtransforms.BboxBase.union(dl)
y0, y1 = bb.intervaly
ylocator = self.yaxis.get_major_locator()
try:
y0, y1 = ylocator.nonsingular(y0, y1)
except AttributeError:
y0, y1 = mtransforms.nonsingular(y0, y1, increasing=False,
expander=0.05)
if self._ymargin > 0:
delta = (y1 - y0) * self._ymargin
y0 -= delta
y1 += delta
if not _tight:
y0, y1 = ylocator.view_limits(y0, y1)
self.set_ybound(y0, y1)
#### Drawing
@allow_rasterization
def draw(self, renderer=None, inframe=False):
"""Draw everything (plot lines, axes, labels)"""
if renderer is None:
renderer = self._cachedRenderer
if renderer is None:
raise RuntimeError('No renderer defined')
if not self.get_visible():
return
renderer.open_group('axes')
locator = self.get_axes_locator()
if locator:
pos = locator(self, renderer)
self.apply_aspect(pos)
else:
self.apply_aspect()
artists = []
artists.extend(self.collections)
artists.extend(self.patches)
artists.extend(self.lines)
artists.extend(self.texts)
artists.extend(self.artists)
if self.axison and not inframe:
if self._axisbelow:
self.xaxis.set_zorder(0.5)
self.yaxis.set_zorder(0.5)
else:
self.xaxis.set_zorder(2.5)
self.yaxis.set_zorder(2.5)
artists.extend([self.xaxis, self.yaxis])
if not inframe:
artists.append(self.title)
artists.append(self._left_title)
artists.append(self._right_title)
artists.extend(self.tables)
if self.legend_ is not None:
artists.append(self.legend_)
# the frame draws the edges around the axes patch -- we
# decouple these so the patch can be in the background and the
# frame in the foreground.
if self.axison and self._frameon:
artists.extend(self.spines.itervalues())
if self.figure.canvas.is_saving():
dsu = [(a.zorder, a) for a in artists]
else:
dsu = [(a.zorder, a) for a in artists
if not a.get_animated()]
# add images to dsu if the backend support compositing.
# otherwise, does the manaul compositing without adding images to dsu.
if len(self.images) <= 1 or renderer.option_image_nocomposite():
dsu.extend([(im.zorder, im) for im in self.images])
_do_composite = False
else:
_do_composite = True
dsu.sort(key=itemgetter(0))
# rasterize artists with negative zorder
# if the minimum zorder is negative, start rasterization
rasterization_zorder = self._rasterization_zorder
if (rasterization_zorder is not None and
len(dsu) > 0 and dsu[0][0] < rasterization_zorder):
renderer.start_rasterizing()
dsu_rasterized = [l for l in dsu if l[0] < rasterization_zorder]
dsu = [l for l in dsu if l[0] >= rasterization_zorder]
else:
dsu_rasterized = []
# the patch draws the background rectangle -- the frame below
# will draw the edges
if self.axison and self._frameon:
self.patch.draw(renderer)
if _do_composite:
# make a composite image blending alpha
# list of (mimage.Image, ox, oy)
zorder_images = [(im.zorder, im) for im in self.images
if im.get_visible()]
zorder_images.sort(key=lambda x: x[0])
mag = renderer.get_image_magnification()
ims = [(im.make_image(mag), 0, 0, im.get_alpha()) for z, im in zorder_images]
l, b, r, t = self.bbox.extents
width = mag * ((round(r) + 0.5) - (round(l) - 0.5))
height = mag * ((round(t) + 0.5) - (round(b) - 0.5))
im = mimage.from_images(height,
width,
ims)
im.is_grayscale = False
l, b, w, h = self.bbox.bounds
# composite images need special args so they will not
# respect z-order for now
gc = renderer.new_gc()
gc.set_clip_rectangle(self.bbox)
gc.set_clip_path(mtransforms.TransformedPath(
self.patch.get_path(),
self.patch.get_transform()))
renderer.draw_image(gc, round(l), round(b), im)
gc.restore()
if dsu_rasterized:
for zorder, a in dsu_rasterized:
a.draw(renderer)
renderer.stop_rasterizing()
for zorder, a in dsu:
a.draw(renderer)
renderer.close_group('axes')
self._cachedRenderer = renderer
def draw_artist(self, a):
"""
This method can only be used after an initial draw which
caches the renderer. It is used to efficiently update Axes
data (axis ticks, labels, etc are not updated)
"""
assert self._cachedRenderer is not None
a.draw(self._cachedRenderer)
def redraw_in_frame(self):
"""
This method can only be used after an initial draw which
caches the renderer. It is used to efficiently update Axes
data (axis ticks, labels, etc are not updated)
"""
assert self._cachedRenderer is not None
self.draw(self._cachedRenderer, inframe=True)
def get_renderer_cache(self):
return self._cachedRenderer
#### Axes rectangle characteristics
def get_frame_on(self):
"""
Get whether the axes rectangle patch is drawn
"""
return self._frameon
def set_frame_on(self, b):
"""
Set whether the axes rectangle patch is drawn
ACCEPTS: [ *True* | *False* ]
"""
self._frameon = b
def get_axisbelow(self):
"""
Get whether axis below is true or not
"""
return self._axisbelow
def set_axisbelow(self, b):
"""
Set whether the axis ticks and gridlines are above or below most
artists
ACCEPTS: [ *True* | *False* ]
"""
self._axisbelow = b
@docstring.dedent_interpd
def grid(self, b=None, which='major', axis='both', **kwargs):
"""
Turn the axes grids on or off.
Call signature::
grid(self, b=None, which='major', axis='both', **kwargs)
Set the axes grids on or off; *b* is a boolean. (For MATLAB
compatibility, *b* may also be a string, 'on' or 'off'.)
If *b* is *None* and ``len(kwargs)==0``, toggle the grid state. If
*kwargs* are supplied, it is assumed that you want a grid and *b*
is thus set to *True*.
*which* can be 'major' (default), 'minor', or 'both' to control
whether major tick grids, minor tick grids, or both are affected.
*axis* can be 'both' (default), 'x', or 'y' to control which
set of gridlines are drawn.
*kwargs* are used to set the grid line properties, eg::
ax.grid(color='r', linestyle='-', linewidth=2)
Valid :class:`~matplotlib.lines.Line2D` kwargs are
%(Line2D)s
"""
if len(kwargs):
b = True
b = _string_to_bool(b)
if axis == 'x' or axis == 'both':
self.xaxis.grid(b, which=which, **kwargs)
if axis == 'y' or axis == 'both':
self.yaxis.grid(b, which=which, **kwargs)
def ticklabel_format(self, **kwargs):
"""
Change the `~matplotlib.ticker.ScalarFormatter` used by
default for linear axes.
Optional keyword arguments:
============ =========================================
Keyword Description
============ =========================================
*style* [ 'sci' (or 'scientific') | 'plain' ]
plain turns off scientific notation
*scilimits* (m, n), pair of integers; if *style*
is 'sci', scientific notation will
be used for numbers outside the range
10`m`:sup: to 10`n`:sup:.
Use (0,0) to include all numbers.
*useOffset* [True | False | offset]; if True,
the offset will be calculated as needed;
if False, no offset will be used; if a
numeric offset is specified, it will be
used.
*axis* [ 'x' | 'y' | 'both' ]
*useLocale* If True, format the number according to
the current locale. This affects things
such as the character used for the
decimal separator. If False, use
C-style (English) formatting. The
default setting is controlled by the
axes.formatter.use_locale rcparam.
============ =========================================
Only the major ticks are affected.
If the method is called when the
:class:`~matplotlib.ticker.ScalarFormatter` is not the
:class:`~matplotlib.ticker.Formatter` being used, an
:exc:`AttributeError` will be raised.
"""
style = kwargs.pop('style', '').lower()
scilimits = kwargs.pop('scilimits', None)
useOffset = kwargs.pop('useOffset', None)
useLocale = kwargs.pop('useLocale', None)
axis = kwargs.pop('axis', 'both').lower()
if scilimits is not None:
try:
m, n = scilimits
m + n + 1 # check that both are numbers
except (ValueError, TypeError):
raise ValueError("scilimits must be a sequence of 2 integers")
if style[:3] == 'sci':
sb = True
elif style in ['plain', 'comma']:
sb = False
if style == 'plain':
cb = False
else:
cb = True
raise NotImplementedError("comma style remains to be added")
elif style == '':
sb = None
else:
raise ValueError("%s is not a valid style value")
try:
if sb is not None:
if axis == 'both' or axis == 'x':
self.xaxis.major.formatter.set_scientific(sb)
if axis == 'both' or axis == 'y':
self.yaxis.major.formatter.set_scientific(sb)
if scilimits is not None:
if axis == 'both' or axis == 'x':
self.xaxis.major.formatter.set_powerlimits(scilimits)
if axis == 'both' or axis == 'y':
self.yaxis.major.formatter.set_powerlimits(scilimits)
if useOffset is not None:
if axis == 'both' or axis == 'x':
self.xaxis.major.formatter.set_useOffset(useOffset)
if axis == 'both' or axis == 'y':
self.yaxis.major.formatter.set_useOffset(useOffset)
if useLocale is not None:
if axis == 'both' or axis == 'x':
self.xaxis.major.formatter.set_useLocale(useLocale)
if axis == 'both' or axis == 'y':
self.yaxis.major.formatter.set_useLocale(useLocale)
except AttributeError:
raise AttributeError(
"This method only works with the ScalarFormatter.")
def locator_params(self, axis='both', tight=None, **kwargs):
"""
Control behavior of tick locators.
Keyword arguments:
*axis*
['x' | 'y' | 'both'] Axis on which to operate;
default is 'both'.
*tight*
[True | False | None] Parameter passed to :meth:`autoscale_view`.
Default is None, for no change.
Remaining keyword arguments are passed to directly to the
:meth:`~matplotlib.ticker.MaxNLocator.set_params` method.
Typically one might want to reduce the maximum number
of ticks and use tight bounds when plotting small
subplots, for example::
ax.locator_params(tight=True, nbins=4)
Because the locator is involved in autoscaling,
:meth:`autoscale_view` is called automatically after
the parameters are changed.
This presently works only for the
:class:`~matplotlib.ticker.MaxNLocator` used
by default on linear axes, but it may be generalized.
"""
_x = axis in ['x', 'both']
_y = axis in ['y', 'both']
if _x:
self.xaxis.get_major_locator().set_params(**kwargs)
if _y:
self.yaxis.get_major_locator().set_params(**kwargs)
self.autoscale_view(tight=tight, scalex=_x, scaley=_y)
def tick_params(self, axis='both', **kwargs):
"""
Change the appearance of ticks and tick labels.
Keyword arguments:
*axis* : ['x' | 'y' | 'both']
Axis on which to operate; default is 'both'.
*reset* : [True | False]
If *True*, set all parameters to defaults
before processing other keyword arguments. Default is
*False*.
*which* : ['major' | 'minor' | 'both']
Default is 'major'; apply arguments to *which* ticks.
*direction* : ['in' | 'out' | 'inout']
Puts ticks inside the axes, outside the axes, or both.
*length*
Tick length in points.
*width*
Tick width in points.
*color*
Tick color; accepts any mpl color spec.
*pad*
Distance in points between tick and label.
*labelsize*
Tick label font size in points or as a string (e.g., 'large').
*labelcolor*
Tick label color; mpl color spec.
*colors*
Changes the tick color and the label color to the same value:
mpl color spec.
*zorder*
Tick and label zorder.
*bottom*, *top*, *left*, *right* : [bool | 'on' | 'off']
controls whether to draw the respective ticks.
*labelbottom*, *labeltop*, *labelleft*, *labelright*
Boolean or ['on' | 'off'], controls whether to draw the
respective tick labels.
Example::
ax.tick_params(direction='out', length=6, width=2, colors='r')
This will make all major ticks be red, pointing out of the box,
and with dimensions 6 points by 2 points. Tick labels will
also be red.
"""
if axis in ['x', 'both']:
xkw = dict(kwargs)
xkw.pop('left', None)
xkw.pop('right', None)
xkw.pop('labelleft', None)
xkw.pop('labelright', None)
self.xaxis.set_tick_params(**xkw)
if axis in ['y', 'both']:
ykw = dict(kwargs)
ykw.pop('top', None)
ykw.pop('bottom', None)
ykw.pop('labeltop', None)
ykw.pop('labelbottom', None)
self.yaxis.set_tick_params(**ykw)
def set_axis_off(self):
"""turn off the axis"""
self.axison = False
def set_axis_on(self):
"""turn on the axis"""
self.axison = True
def get_axis_bgcolor(self):
"""Return the axis background color"""
return self._axisbg
def set_axis_bgcolor(self, color):
"""
set the axes background color
ACCEPTS: any matplotlib color - see
:func:`~matplotlib.pyplot.colors`
"""
self._axisbg = color
self.patch.set_facecolor(color)
### data limits, ticks, tick labels, and formatting
def invert_xaxis(self):
"Invert the x-axis."
left, right = self.get_xlim()
self.set_xlim(right, left, auto=None)
def xaxis_inverted(self):
"""Returns *True* if the x-axis is inverted."""
left, right = self.get_xlim()
return right < left
def get_xbound(self):
"""
Returns the x-axis numerical bounds where::
lowerBound < upperBound
"""
left, right = self.get_xlim()
if left < right:
return left, right
else:
return right, left
def set_xbound(self, lower=None, upper=None):
"""
Set the lower and upper numerical bounds of the x-axis.
This method will honor axes inversion regardless of parameter order.
It will not change the _autoscaleXon attribute.
"""
if upper is None and iterable(lower):
lower, upper = lower
old_lower, old_upper = self.get_xbound()
if lower is None:
lower = old_lower
if upper is None:
upper = old_upper
if self.xaxis_inverted():
if lower < upper:
self.set_xlim(upper, lower, auto=None)
else:
self.set_xlim(lower, upper, auto=None)
else:
if lower < upper:
self.set_xlim(lower, upper, auto=None)
else:
self.set_xlim(upper, lower, auto=None)
def get_xlim(self):
"""
Get the x-axis range [*left*, *right*]
"""
return tuple(self.viewLim.intervalx)
def set_xlim(self, left=None, right=None, emit=True, auto=False, **kw):
"""
Call signature::
set_xlim(self, *args, **kwargs):
Set the data limits for the xaxis
Examples::
set_xlim((left, right))
set_xlim(left, right)
set_xlim(left=1) # right unchanged
set_xlim(right=1) # left unchanged
Keyword arguments:
*left*: scalar
The left xlim; *xmin*, the previous name, may still be used
*right*: scalar
The right xlim; *xmax*, the previous name, may still be used
*emit*: [ *True* | *False* ]
Notify observers of limit change
*auto*: [ *True* | *False* | *None* ]
Turn *x* autoscaling on (*True*), off (*False*; default),
or leave unchanged (*None*)
Note, the *left* (formerly *xmin*) value may be greater than
the *right* (formerly *xmax*).
For example, suppose *x* is years before present.
Then one might use::
set_ylim(5000, 0)
so 5000 years ago is on the left of the plot and the
present is on the right.
Returns the current xlimits as a length 2 tuple
ACCEPTS: length 2 sequence of floats
"""
if 'xmin' in kw:
left = kw.pop('xmin')
if 'xmax' in kw:
right = kw.pop('xmax')
if kw:
raise ValueError("unrecognized kwargs: %s" % kw.keys())
if right is None and iterable(left):
left, right = left
self._process_unit_info(xdata=(left, right))
if left is not None:
left = self.convert_xunits(left)
if right is not None:
right = self.convert_xunits(right)
old_left, old_right = self.get_xlim()
if left is None:
left = old_left
if right is None:
right = old_right
if left == right:
warnings.warn(('Attempting to set identical left==right results\n'
+ 'in singular transformations; automatically expanding.\n'
+ 'left=%s, right=%s') % (left, right))
left, right = mtransforms.nonsingular(left, right, increasing=False)
left, right = self.xaxis.limit_range_for_scale(left, right)
self.viewLim.intervalx = (left, right)
if auto is not None:
self._autoscaleXon = bool(auto)
if emit:
self.callbacks.process('xlim_changed', self)
# Call all of the other x-axes that are shared with this one
for other in self._shared_x_axes.get_siblings(self):
if other is not self:
other.set_xlim(self.viewLim.intervalx,
emit=False, auto=auto)
if (other.figure != self.figure and
other.figure.canvas is not None):
other.figure.canvas.draw_idle()
return left, right
def get_xscale(self):
return self.xaxis.get_scale()
get_xscale.__doc__ = "Return the xaxis scale string: %s""" % (
", ".join(mscale.get_scale_names()))
@docstring.dedent_interpd
def set_xscale(self, value, **kwargs):
"""
Call signature::
set_xscale(value)
Set the scaling of the x-axis: %(scale)s
ACCEPTS: [%(scale)s]
Different kwargs are accepted, depending on the scale:
%(scale_docs)s
"""
self.xaxis._set_scale(value, **kwargs)
self.autoscale_view(scaley=False)
self._update_transScale()
def get_xticks(self, minor=False):
"""Return the x ticks as a list of locations"""
return self.xaxis.get_ticklocs(minor=minor)
def set_xticks(self, ticks, minor=False):
"""
Set the x ticks with list of *ticks*
ACCEPTS: sequence of floats
"""
return self.xaxis.set_ticks(ticks, minor=minor)
def get_xmajorticklabels(self):
"""
Get the xtick labels as a list of :class:`~matplotlib.text.Text`
instances.
"""
return cbook.silent_list('Text xticklabel',
self.xaxis.get_majorticklabels())
def get_xminorticklabels(self):
"""
Get the x minor tick labels as a list of
:class:`matplotlib.text.Text` instances.
"""
return cbook.silent_list('Text xticklabel',
self.xaxis.get_minorticklabels())
def get_xticklabels(self, minor=False):
"""
Get the x tick labels as a list of :class:`~matplotlib.text.Text`
instances.
"""
return cbook.silent_list('Text xticklabel',
self.xaxis.get_ticklabels(minor=minor))
@docstring.dedent_interpd
def set_xticklabels(self, labels, fontdict=None, minor=False, **kwargs):
"""
Call signature::
set_xticklabels(labels, fontdict=None, minor=False, **kwargs)
Set the xtick labels with list of strings *labels*. Return a
list of axis text instances.
*kwargs* set the :class:`~matplotlib.text.Text` properties.
Valid properties are
%(Text)s
ACCEPTS: sequence of strings
"""
return self.xaxis.set_ticklabels(labels, fontdict,
minor=minor, **kwargs)
def invert_yaxis(self):
"""
Invert the y-axis.
"""
bottom, top = self.get_ylim()
self.set_ylim(top, bottom, auto=None)
def yaxis_inverted(self):
"""Returns *True* if the y-axis is inverted."""
bottom, top = self.get_ylim()
return top < bottom
def get_ybound(self):
"""
Return y-axis numerical bounds in the form of
``lowerBound < upperBound``
"""
bottom, top = self.get_ylim()
if bottom < top:
return bottom, top
else:
return top, bottom
def set_ybound(self, lower=None, upper=None):
"""
Set the lower and upper numerical bounds of the y-axis.
This method will honor axes inversion regardless of parameter order.
It will not change the _autoscaleYon attribute.
"""
if upper is None and iterable(lower):
lower, upper = lower
old_lower, old_upper = self.get_ybound()
if lower is None:
lower = old_lower
if upper is None:
upper = old_upper
if self.yaxis_inverted():
if lower < upper:
self.set_ylim(upper, lower, auto=None)
else:
self.set_ylim(lower, upper, auto=None)
else:
if lower < upper:
self.set_ylim(lower, upper, auto=None)
else:
self.set_ylim(upper, lower, auto=None)
def get_ylim(self):
"""
Get the y-axis range [*bottom*, *top*]
"""
return tuple(self.viewLim.intervaly)
def set_ylim(self, bottom=None, top=None, emit=True, auto=False, **kw):
"""
Call signature::
set_ylim(self, *args, **kwargs):
Set the data limits for the yaxis
Examples::
set_ylim((bottom, top))
set_ylim(bottom, top)
set_ylim(bottom=1) # top unchanged
set_ylim(top=1) # bottom unchanged
Keyword arguments:
*bottom*: scalar
The bottom ylim; the previous name, *ymin*, may still be used
*top*: scalar
The top ylim; the previous name, *ymax*, may still be used
*emit*: [ *True* | *False* ]
Notify observers of limit change
*auto*: [ *True* | *False* | *None* ]
Turn *y* autoscaling on (*True*), off (*False*; default),
or leave unchanged (*None*)
Note, the *bottom* (formerly *ymin*) value may be greater than
the *top* (formerly *ymax*).
For example, suppose *y* is depth in the ocean.
Then one might use::
set_ylim(5000, 0)
so 5000 m depth is at the bottom of the plot and the
surface, 0 m, is at the top.
Returns the current ylimits as a length 2 tuple
ACCEPTS: length 2 sequence of floats
"""
if 'ymin' in kw:
bottom = kw.pop('ymin')
if 'ymax' in kw:
top = kw.pop('ymax')
if kw:
raise ValueError("unrecognized kwargs: %s" % kw.keys())
if top is None and iterable(bottom):
bottom, top = bottom
if bottom is not None:
bottom = self.convert_yunits(bottom)
if top is not None:
top = self.convert_yunits(top)
old_bottom, old_top = self.get_ylim()
if bottom is None:
bottom = old_bottom
if top is None:
top = old_top
if bottom == top:
warnings.warn(('Attempting to set identical bottom==top results\n'
+ 'in singular transformations; automatically expanding.\n'
+ 'bottom=%s, top=%s') % (bottom, top))
bottom, top = mtransforms.nonsingular(bottom, top, increasing=False)
bottom, top = self.yaxis.limit_range_for_scale(bottom, top)
self.viewLim.intervaly = (bottom, top)
if auto is not None:
self._autoscaleYon = bool(auto)
if emit:
self.callbacks.process('ylim_changed', self)
# Call all of the other y-axes that are shared with this one
for other in self._shared_y_axes.get_siblings(self):
if other is not self:
other.set_ylim(self.viewLim.intervaly,
emit=False, auto=auto)
if (other.figure != self.figure and
other.figure.canvas is not None):
other.figure.canvas.draw_idle()
return bottom, top
def get_yscale(self):
return self.yaxis.get_scale()
get_yscale.__doc__ = "Return the yaxis scale string: %s""" % (
", ".join(mscale.get_scale_names()))
@docstring.dedent_interpd
def set_yscale(self, value, **kwargs):
"""
Call signature::
set_yscale(value)
Set the scaling of the y-axis: %(scale)s
ACCEPTS: [%(scale)s]
Different kwargs are accepted, depending on the scale:
%(scale_docs)s
"""
self.yaxis._set_scale(value, **kwargs)
self.autoscale_view(scalex=False)
self._update_transScale()
def get_yticks(self, minor=False):
"""Return the y ticks as a list of locations"""
return self.yaxis.get_ticklocs(minor=minor)
def set_yticks(self, ticks, minor=False):
"""
Set the y ticks with list of *ticks*
ACCEPTS: sequence of floats
Keyword arguments:
*minor*: [ *False* | *True* ]
Sets the minor ticks if *True*
"""
return self.yaxis.set_ticks(ticks, minor=minor)
def get_ymajorticklabels(self):
"""
Get the major y tick labels as a list of
:class:`~matplotlib.text.Text` instances.
"""
return cbook.silent_list('Text yticklabel',
self.yaxis.get_majorticklabels())
def get_yminorticklabels(self):
"""
Get the minor y tick labels as a list of
:class:`~matplotlib.text.Text` instances.
"""
return cbook.silent_list('Text yticklabel',
self.yaxis.get_minorticklabels())
def get_yticklabels(self, minor=False):
"""
Get the y tick labels as a list of :class:`~matplotlib.text.Text`
instances
"""
return cbook.silent_list('Text yticklabel',
self.yaxis.get_ticklabels(minor=minor))
@docstring.dedent_interpd
def set_yticklabels(self, labels, fontdict=None, minor=False, **kwargs):
"""
Call signature::
set_yticklabels(labels, fontdict=None, minor=False, **kwargs)
Set the y tick labels with list of strings *labels*. Return a list of
:class:`~matplotlib.text.Text` instances.
*kwargs* set :class:`~matplotlib.text.Text` properties for the labels.
Valid properties are
%(Text)s
ACCEPTS: sequence of strings
"""
return self.yaxis.set_ticklabels(labels, fontdict,
minor=minor, **kwargs)
def xaxis_date(self, tz=None):
"""
Sets up x-axis ticks and labels that treat the x data as dates.
*tz* is a timezone string or :class:`tzinfo` instance.
Defaults to rc value.
"""
# should be enough to inform the unit conversion interface
# dates are coming in
self.xaxis.axis_date(tz)
def yaxis_date(self, tz=None):
"""
Sets up y-axis ticks and labels that treat the y data as dates.
*tz* is a timezone string or :class:`tzinfo` instance.
Defaults to rc value.
"""
self.yaxis.axis_date(tz)
def format_xdata(self, x):
"""
Return *x* string formatted. This function will use the attribute
self.fmt_xdata if it is callable, else will fall back on the xaxis
major formatter
"""
try:
return self.fmt_xdata(x)
except TypeError:
func = self.xaxis.get_major_formatter().format_data_short
val = func(x)
return val
def format_ydata(self, y):
"""
Return y string formatted. This function will use the
:attr:`fmt_ydata` attribute if it is callable, else will fall
back on the yaxis major formatter
"""
try:
return self.fmt_ydata(y)
except TypeError:
func = self.yaxis.get_major_formatter().format_data_short
val = func(y)
return val
def format_coord(self, x, y):
"""Return a format string formatting the *x*, *y* coord"""
if x is None:
xs = '???'
else:
xs = self.format_xdata(x)
if y is None:
ys = '???'
else:
ys = self.format_ydata(y)
return 'x=%s y=%s' % (xs, ys)
#### Interactive manipulation
def can_zoom(self):
"""
Return *True* if this axes supports the zoom box button functionality.
"""
return True
def can_pan(self):
"""
Return *True* if this axes supports any pan/zoom button functionality.
"""
return True
def get_navigate(self):
"""
Get whether the axes responds to navigation commands
"""
return self._navigate
def set_navigate(self, b):
"""
Set whether the axes responds to navigation toolbar commands
ACCEPTS: [ *True* | *False* ]
"""
self._navigate = b
def get_navigate_mode(self):
"""
Get the navigation toolbar button status: 'PAN', 'ZOOM', or None
"""
return self._navigate_mode
def set_navigate_mode(self, b):
"""
Set the navigation toolbar button status;
.. warning::
this is not a user-API function.
"""
self._navigate_mode = b
def start_pan(self, x, y, button):
"""
Called when a pan operation has started.
*x*, *y* are the mouse coordinates in display coords.
button is the mouse button number:
* 1: LEFT
* 2: MIDDLE
* 3: RIGHT
.. note::
Intended to be overridden by new projection types.
"""
self._pan_start = cbook.Bunch(
lim=self.viewLim.frozen(),
trans=self.transData.frozen(),
trans_inverse=self.transData.inverted().frozen(),
bbox=self.bbox.frozen(),
x=x,
y=y
)
def end_pan(self):
"""
Called when a pan operation completes (when the mouse button
is up.)
.. note::
Intended to be overridden by new projection types.
"""
del self._pan_start
def drag_pan(self, button, key, x, y):
"""
Called when the mouse moves during a pan operation.
*button* is the mouse button number:
* 1: LEFT
* 2: MIDDLE
* 3: RIGHT
*key* is a "shift" key
*x*, *y* are the mouse coordinates in display coords.
.. note::
Intended to be overridden by new projection types.
"""
def format_deltas(key, dx, dy):
if key == 'control':
if abs(dx) > abs(dy):
dy = dx
else:
dx = dy
elif key == 'x':
dy = 0
elif key == 'y':
dx = 0
elif key == 'shift':
if 2 * abs(dx) < abs(dy):
dx = 0
elif 2 * abs(dy) < abs(dx):
dy = 0
elif abs(dx) > abs(dy):
dy = dy / abs(dy) * abs(dx)
else:
dx = dx / abs(dx) * abs(dy)
return (dx, dy)
p = self._pan_start
dx = x - p.x
dy = y - p.y
if dx == 0 and dy == 0:
return
if button == 1:
dx, dy = format_deltas(key, dx, dy)
result = p.bbox.translated(-dx, -dy) \
.transformed(p.trans_inverse)
elif button == 3:
try:
dx = -dx / float(self.bbox.width)
dy = -dy / float(self.bbox.height)
dx, dy = format_deltas(key, dx, dy)
if self.get_aspect() != 'auto':
dx = 0.5 * (dx + dy)
dy = dx
alpha = np.power(10.0, (dx, dy))
start = np.array([p.x, p.y])
oldpoints = p.lim.transformed(p.trans)
newpoints = start + alpha * (oldpoints - start)
result = mtransforms.Bbox(newpoints) \
.transformed(p.trans_inverse)
except OverflowError:
warnings.warn('Overflow while panning')
return
self.set_xlim(*result.intervalx)
self.set_ylim(*result.intervaly)
def get_cursor_props(self):
"""
Return the cursor propertiess as a (*linewidth*, *color*)
tuple, where *linewidth* is a float and *color* is an RGBA
tuple
"""
return self._cursorProps
def set_cursor_props(self, *args):
"""
Set the cursor property as::
ax.set_cursor_props(linewidth, color)
or::
ax.set_cursor_props((linewidth, color))
ACCEPTS: a (*float*, *color*) tuple
"""
if len(args) == 1:
lw, c = args[0]
elif len(args) == 2:
lw, c = args
else:
raise ValueError('args must be a (linewidth, color) tuple')
c = mcolors.colorConverter.to_rgba(c)
self._cursorProps = lw, c
def get_children(self):
"""return a list of child artists"""
children = []
children.append(self.xaxis)
children.append(self.yaxis)
children.extend(self.lines)
children.extend(self.patches)
children.extend(self.texts)
children.extend(self.tables)
children.extend(self.artists)
children.extend(self.images)
if self.legend_ is not None:
children.append(self.legend_)
children.extend(self.collections)
children.append(self.title)
children.append(self._left_title)
children.append(self._right_title)
children.append(self.patch)
children.extend(self.spines.itervalues())
return children
def contains(self, mouseevent):
"""
Test whether the mouse event occured in the axes.
Returns *True* / *False*, {}
"""
if callable(self._contains):
return self._contains(self, mouseevent)
return self.patch.contains(mouseevent)
def contains_point(self, point):
"""
Returns *True* if the point (tuple of x,y) is inside the axes
(the area defined by the its patch). A pixel coordinate is
required.
"""
return self.patch.contains_point(point, radius=1.0)
def pick(self, *args):
"""
Call signature::
pick(mouseevent)
each child artist will fire a pick event if mouseevent is over
the artist and the artist has picker set
"""
martist.Artist.pick(self, args[0])
### Labelling
def get_title(self, loc="center"):
"""Get an axes title.
Get one of the three available axes titles. The available titles
are positioned above the axes in the center, flush with the left
edge, and flush with the right edge.
Parameters
----------
loc : {'center', 'left', 'right'}, str, optional
Which title to get, defaults to 'center'
Returns
-------
title: str
The title text string.
"""
try:
title = {'left': self._left_title,
'center': self.title,
'right': self._right_title}[loc.lower()]
except KeyError:
raise ValueError("'%s' is not a valid location" % loc)
return title.get_text()
@docstring.dedent_interpd
def set_title(self, label, fontdict=None, loc="center", **kwargs):
"""
Set a title for the axes.
Set one of the three available axes titles. The available titles
are positioned above the axes in the center, flush with the left
edge, and flush with the right edge.
Parameters
----------
label : str
Text to use for the title
fontdict : dict
A dictionary controlling the appearance of the title text,
the default `fontdict` is::
{'fontsize': rcParams['axes.titlesize'],
'verticalalignment': 'baseline',
'horizontalalignment': loc}
loc : {'center', 'left', 'right'}, str, optional
Which title to set, defaults to 'center'
Returns
-------
text : :class:`~matplotlib.text.Text`
The matplotlib text instance representing the title
Other parameters
----------------
Other keyword arguments are text properties, see
:class:`~matplotlib.text.Text` for a list of valid text
properties.
"""
try:
title = {'left': self._left_title,
'center': self.title,
'right': self._right_title}[loc.lower()]
except KeyError:
raise ValueError("'%s' is not a valid location" % loc)
default = {
'fontsize': rcParams['axes.titlesize'],
'verticalalignment': 'baseline',
'horizontalalignment': loc.lower()
}
title.set_text(label)
title.update(default)
if fontdict is not None:
title.update(fontdict)
title.update(kwargs)
return title
def get_xlabel(self):
"""
Get the xlabel text string.
"""
label = self.xaxis.get_label()
return label.get_text()
@docstring.dedent_interpd
def set_xlabel(self, xlabel, fontdict=None, labelpad=None, **kwargs):
"""
Set the label for the xaxis.
Parameters
----------
xlabel : string
x label
labelpad : scalar, optional, default: None
spacing in points between the label and the x-axis
Other parameters
----------------
kwargs : `~matplotlib.text.Text` properties
See also
--------
text : for information on how override and the optional args work
"""
if labelpad is not None:
self.xaxis.labelpad = labelpad
return self.xaxis.set_label_text(xlabel, fontdict, **kwargs)
def get_ylabel(self):
"""
Get the ylabel text string.
"""
label = self.yaxis.get_label()
return label.get_text()
@docstring.dedent_interpd
def set_ylabel(self, ylabel, fontdict=None, labelpad=None, **kwargs):
"""
Set the label for the yaxis
Parameters
----------
ylabel : string
y label
labelpad : scalar, optional, default: None
spacing in points between the label and the x-axis
Other parameters
----------------
kwargs : `~matplotlib.text.Text` properties
See also
--------
text : for information on how override and the optional args work
"""
if labelpad is not None:
self.yaxis.labelpad = labelpad
return self.yaxis.set_label_text(ylabel, fontdict, **kwargs)
@docstring.dedent_interpd
def text(self, x, y, s, fontdict=None,
withdash=False, **kwargs):
"""
Add text to the axes.
Add text in string *s* to axis at location *x*, *y*, data
coordinates.
Parameters
----------
s : string
text
x, y : scalars
data coordinates
fontdict : dictionary, optional, default: None
A dictionary to override the default text properties. If fontdict
is None, the defaults are determined by your rc parameters.
withdash : boolean, optional, default: False
Creates a `~matplotlib.text.TextWithDash` instance instead of a
`~matplotlib.text.Text` instance.
Other parameters
----------------
kwargs : `~matplotlib.text.Text` properties.
Other miscellaneous text parameters.
Examples
--------
Individual keyword arguments can be used to override any given
parameter::
>>> text(x, y, s, fontsize=12)
The default transform specifies that text is in data coords,
alternatively, you can specify text in axis coords (0,0 is
lower-left and 1,1 is upper-right). The example below places
text in the center of the axes::
>>> text(0.5, 0.5,'matplotlib', horizontalalignment='center',
... verticalalignment='center',
... transform=ax.transAxes)
You can put a rectangular box around the text instance (e.g., to
set a background color) by using the keyword *bbox*. *bbox* is
a dictionary of `~matplotlib.patches.Rectangle`
properties. For example::
>>> text(x, y, s, bbox=dict(facecolor='red', alpha=0.5))
"""
default = {
'verticalalignment': 'baseline',
'horizontalalignment': 'left',
'transform': self.transData,
'clip_on': False
}
# At some point if we feel confident that TextWithDash
# is robust as a drop-in replacement for Text and that
# the performance impact of the heavier-weight class
# isn't too significant, it may make sense to eliminate
# the withdash kwarg and simply delegate whether there's
# a dash to TextWithDash and dashlength.
if withdash:
t = mtext.TextWithDash(
x=x, y=y, text=s)
else:
t = mtext.Text(
x=x, y=y, text=s)
self._set_artist_props(t)
t.update(default)
if fontdict is not None:
t.update(fontdict)
t.update(kwargs)
self.texts.append(t)
t._remove_method = lambda h: self.texts.remove(h)
t.set_clip_path(self.patch)
return t
@docstring.dedent_interpd
def annotate(self, *args, **kwargs):
"""
Create an annotation: a piece of text referring to a data
point.
Call signature::
annotate(s, xy, xytext=None, xycoords='data',
textcoords='data', arrowprops=None, **kwargs)
Keyword arguments:
%(Annotation)s
.. plot:: mpl_examples/pylab_examples/annotation_demo2.py
"""
a = mtext.Annotation(*args, **kwargs)
a.set_transform(mtransforms.IdentityTransform())
self._set_artist_props(a)
if kwargs.has_key('clip_on'):
a.set_clip_path(self.patch)
self.texts.append(a)
a._remove_method = lambda h: self.texts.remove(h)
return a
#### Lines and spans
@docstring.dedent_interpd
def axhline(self, y=0, xmin=0, xmax=1, **kwargs):
"""
Add a horizontal line across the axis.
Call signature::
axhline(y=0, xmin=0, xmax=1, **kwargs)
Draw a horizontal line at *y* from *xmin* to *xmax*. With the
default values of *xmin* = 0 and *xmax* = 1, this line will
always span the horizontal extent of the axes, regardless of
the xlim settings, even if you change them, e.g., with the
:meth:`set_xlim` command. That is, the horizontal extent is
in axes coords: 0=left, 0.5=middle, 1.0=right but the *y*
location is in data coordinates.
Return value is the :class:`~matplotlib.lines.Line2D`
instance. kwargs are the same as kwargs to plot, and can be
used to control the line properties. e.g.,
* draw a thick red hline at *y* = 0 that spans the xrange::
>>> axhline(linewidth=4, color='r')
* draw a default hline at *y* = 1 that spans the xrange::
>>> axhline(y=1)
* draw a default hline at *y* = .5 that spans the the middle half of
the xrange::
>>> axhline(y=.5, xmin=0.25, xmax=0.75)
Valid kwargs are :class:`~matplotlib.lines.Line2D` properties,
with the exception of 'transform':
%(Line2D)s
.. seealso::
:meth:`axhspan`
for example plot and source code
"""
if "transform" in kwargs:
raise ValueError(
"'transform' is not allowed as a kwarg;"
+ "axhline generates its own transform.")
ymin, ymax = self.get_ybound()
# We need to strip away the units for comparison with
# non-unitized bounds
self._process_unit_info(ydata=y, kwargs=kwargs)
yy = self.convert_yunits(y)
scaley = (yy < ymin) or (yy > ymax)
trans = mtransforms.blended_transform_factory(
self.transAxes, self.transData)
l = mlines.Line2D([xmin, xmax], [y, y], transform=trans, **kwargs)
self.add_line(l)
self.autoscale_view(scalex=False, scaley=scaley)
return l
@docstring.dedent_interpd
def axvline(self, x=0, ymin=0, ymax=1, **kwargs):
"""
Add a vertical line across the axes.
Call signature::
axvline(x=0, ymin=0, ymax=1, **kwargs)
Draw a vertical line at *x* from *ymin* to *ymax*. With the
default values of *ymin* = 0 and *ymax* = 1, this line will
always span the vertical extent of the axes, regardless of the
ylim settings, even if you change them, e.g., with the
:meth:`set_ylim` command. That is, the vertical extent is in
axes coords: 0=bottom, 0.5=middle, 1.0=top but the *x* location
is in data coordinates.
Return value is the :class:`~matplotlib.lines.Line2D`
instance. kwargs are the same as kwargs to plot, and can be
used to control the line properties. e.g.,
* draw a thick red vline at *x* = 0 that spans the yrange::
>>> axvline(linewidth=4, color='r')
* draw a default vline at *x* = 1 that spans the yrange::
>>> axvline(x=1)
* draw a default vline at *x* = .5 that spans the the middle half of
the yrange::
>>> axvline(x=.5, ymin=0.25, ymax=0.75)
Valid kwargs are :class:`~matplotlib.lines.Line2D` properties,
with the exception of 'transform':
%(Line2D)s
.. seealso::
:meth:`axhspan`
for example plot and source code
"""
if "transform" in kwargs:
raise ValueError(
"'transform' is not allowed as a kwarg;"
+ "axvline generates its own transform.")
xmin, xmax = self.get_xbound()
# We need to strip away the units for comparison with
# non-unitized bounds
self._process_unit_info(xdata=x, kwargs=kwargs)
xx = self.convert_xunits(x)
scalex = (xx < xmin) or (xx > xmax)
trans = mtransforms.blended_transform_factory(
self.transData, self.transAxes)
l = mlines.Line2D([x, x], [ymin, ymax], transform=trans, **kwargs)
self.add_line(l)
self.autoscale_view(scalex=scalex, scaley=False)
return l
@docstring.dedent_interpd
def axhspan(self, ymin, ymax, xmin=0, xmax=1, **kwargs):
"""
Add a horizontal span (rectangle) across the axis.
Call signature::
axhspan(ymin, ymax, xmin=0, xmax=1, **kwargs)
*y* coords are in data units and *x* coords are in axes (relative
0-1) units.
Draw a horizontal span (rectangle) from *ymin* to *ymax*.
With the default values of *xmin* = 0 and *xmax* = 1, this
always spans the xrange, regardless of the xlim settings, even
if you change them, e.g., with the :meth:`set_xlim` command.
That is, the horizontal extent is in axes coords: 0=left,
0.5=middle, 1.0=right but the *y* location is in data
coordinates.
Return value is a :class:`matplotlib.patches.Polygon`
instance.
Examples:
* draw a gray rectangle from *y* = 0.25-0.75 that spans the
horizontal extent of the axes::
>>> axhspan(0.25, 0.75, facecolor='0.5', alpha=0.5)
Valid kwargs are :class:`~matplotlib.patches.Polygon` properties:
%(Polygon)s
**Example:**
.. plot:: mpl_examples/pylab_examples/axhspan_demo.py
"""
trans = mtransforms.blended_transform_factory(
self.transAxes, self.transData)
# process the unit information
self._process_unit_info([xmin, xmax], [ymin, ymax], kwargs=kwargs)
# first we need to strip away the units
xmin, xmax = self.convert_xunits([xmin, xmax])
ymin, ymax = self.convert_yunits([ymin, ymax])
verts = (xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)
p = mpatches.Polygon(verts, **kwargs)
p.set_transform(trans)
self.add_patch(p)
self.autoscale_view(scalex=False)
return p
@docstring.dedent_interpd
def axvspan(self, xmin, xmax, ymin=0, ymax=1, **kwargs):
"""
Add a vertical span (rectangle) across the axes.
Call signature::
axvspan(xmin, xmax, ymin=0, ymax=1, **kwargs)
*x* coords are in data units and *y* coords are in axes (relative
0-1) units.
Draw a vertical span (rectangle) from *xmin* to *xmax*. With
the default values of *ymin* = 0 and *ymax* = 1, this always
spans the yrange, regardless of the ylim settings, even if you
change them, e.g., with the :meth:`set_ylim` command. That is,
the vertical extent is in axes coords: 0=bottom, 0.5=middle,
1.0=top but the *y* location is in data coordinates.
Return value is the :class:`matplotlib.patches.Polygon`
instance.
Examples:
* draw a vertical green translucent rectangle from x=1.25 to 1.55 that
spans the yrange of the axes::
>>> axvspan(1.25, 1.55, facecolor='g', alpha=0.5)
Valid kwargs are :class:`~matplotlib.patches.Polygon`
properties:
%(Polygon)s
.. seealso::
:meth:`axhspan`
for example plot and source code
"""
trans = mtransforms.blended_transform_factory(
self.transData, self.transAxes)
# process the unit information
self._process_unit_info([xmin, xmax], [ymin, ymax], kwargs=kwargs)
# first we need to strip away the units
xmin, xmax = self.convert_xunits([xmin, xmax])
ymin, ymax = self.convert_yunits([ymin, ymax])
verts = [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)]
p = mpatches.Polygon(verts, **kwargs)
p.set_transform(trans)
self.add_patch(p)
self.autoscale_view(scaley=False)
return p
@docstring.dedent
def hlines(self, y, xmin, xmax, colors='k', linestyles='solid',
label='', **kwargs):
"""
Plot horizontal lines.
Plot horizontal lines at each `y` from `xmin` to `xmax`.
Parameters
----------
y : scalar or 1D array_like
y-indexes where to plot the lines.
xmin, xmax : scalar or 1D array_like
Respective beginning and end of each line. If scalars are
provided, all lines will have same length.
colors : array_like of colors, optional, default: 'k'
linestyles : ['solid' | 'dashed' | 'dashdot' | 'dotted'], optional
label : string, optional, default: ''
Returns
-------
lines : `~matplotlib.collections.LineCollection`
Other parameters
----------------
kwargs : `~matplotlib.collections.LineCollection` properties.
See also
--------
vlines : vertical lines
Examples
--------
.. plot:: mpl_examples/pylab_examples/vline_hline_demo.py
"""
# We do the conversion first since not all unitized data is uniform
# process the unit information
self._process_unit_info([xmin, xmax], y, kwargs=kwargs)
y = self.convert_yunits(y)
xmin = self.convert_xunits(xmin)
xmax = self.convert_xunits(xmax)
if not iterable(y):
y = [y]
if not iterable(xmin):
xmin = [xmin]
if not iterable(xmax):
xmax = [xmax]
y = np.asarray(y)
xmin = np.asarray(xmin)
xmax = np.asarray(xmax)
if len(xmin) == 1:
xmin = np.resize(xmin, y.shape)
if len(xmax) == 1:
xmax = np.resize(xmax, y.shape)
if len(xmin) != len(y):
raise ValueError('xmin and y are unequal sized sequences')
if len(xmax) != len(y):
raise ValueError('xmax and y are unequal sized sequences')
verts = [((thisxmin, thisy), (thisxmax, thisy))
for thisxmin, thisxmax, thisy in zip(xmin, xmax, y)]
coll = mcoll.LineCollection(verts, colors=colors,
linestyles=linestyles, label=label)
self.add_collection(coll)
coll.update(kwargs)
if len(y) > 0:
minx = min(xmin.min(), xmax.min())
maxx = max(xmin.max(), xmax.max())
miny = y.min()
maxy = y.max()
corners = (minx, miny), (maxx, maxy)
self.update_datalim(corners)
self.autoscale_view()
return coll
@docstring.dedent_interpd
def vlines(self, x, ymin, ymax, colors='k', linestyles='solid',
label='', **kwargs):
"""
Plot vertical lines.
Plot vertical lines at each `x` from `ymin` to `ymax`.
Parameters
----------
x : scalar or 1D array_like
x-indexes where to plot the lines.
xmin, xmax : scalar or 1D array_like
Respective beginning and end of each line. If scalars are
provided, all lines will have same length.
colors : array_like of colors, optional, default: 'k'
linestyles : ['solid' | 'dashed' | 'dashdot' | 'dotted'], optional
label : string, optional, default: ''
Returns
-------
lines : `~matplotlib.collections.LineCollection`
Other parameters
----------------
kwargs : `~matplotlib.collections.LineCollection` properties.
See also
--------
hlines : horizontal lines
Examples
---------
.. plot:: mpl_examples/pylab_examples/vline_hline_demo.py
"""
self._process_unit_info(xdata=x, ydata=[ymin, ymax], kwargs=kwargs)
# We do the conversion first since not all unitized data is uniform
x = self.convert_xunits(x)
ymin = self.convert_yunits(ymin)
ymax = self.convert_yunits(ymax)
if not iterable(x):
x = [x]
if not iterable(ymin):
ymin = [ymin]
if not iterable(ymax):
ymax = [ymax]
x = np.asarray(x)
ymin = np.asarray(ymin)
ymax = np.asarray(ymax)
if len(ymin) == 1:
ymin = np.resize(ymin, x.shape)
if len(ymax) == 1:
ymax = np.resize(ymax, x.shape)
if len(ymin) != len(x):
raise ValueError('ymin and x are unequal sized sequences')
if len(ymax) != len(x):
raise ValueError('ymax and x are unequal sized sequences')
Y = np.array([ymin, ymax]).T
verts = [((thisx, thisymin), (thisx, thisymax))
for thisx, (thisymin, thisymax) in zip(x, Y)]
#print 'creating line collection'
coll = mcoll.LineCollection(verts, colors=colors,
linestyles=linestyles, label=label)
self.add_collection(coll)
coll.update(kwargs)
if len(x) > 0:
minx = min(x)
maxx = max(x)
miny = min(min(ymin), min(ymax))
maxy = max(max(ymin), max(ymax))
corners = (minx, miny), (maxx, maxy)
self.update_datalim(corners)
self.autoscale_view()
return coll
@docstring.dedent_interpd
def eventplot(self, positions, orientation='horizontal', lineoffsets=1,
linelengths=1, linewidths=None, colors=None,
linestyles='solid', **kwargs):
"""
Plot identical parallel lines at specific positions.
Call signature::
eventplot(positions, orientation='horizontal', lineoffsets=0,
linelengths=1, linewidths=None, color =None,
linestyles='solid'
Plot parallel lines at the given positions. positions should be a 1D
or 2D array-like object, with each row corresponding to a row or column
of lines.
This type of plot is commonly used in neuroscience for representing
neural events, where it is commonly called a spike raster, dot raster,
or raster plot.
However, it is useful in any situation where you wish to show the
timing or position of multiple sets of discrete events, such as the
arrival times of people to a business on each day of the month or the
date of hurricanes each year of the last century.
*orientation* : [ 'horizonal' | 'vertical' ]
'horizonal' : the lines will be vertical and arranged in rows
"vertical' : lines will be horizontal and arranged in columns
*lineoffsets* :
A float or array-like containing floats.
*linelengths* :
A float or array-like containing floats.
*linewidths* :
A float or array-like containing floats.
*colors*
must be a sequence of RGBA tuples (eg arbitrary color
strings, etc, not allowed) or a list of such sequences
*linestyles* :
[ 'solid' | 'dashed' | 'dashdot' | 'dotted' ] or an array of these
values
For linelengths, linewidths, colors, and linestyles, if only a single
value is given, that value is applied to all lines. If an array-like
is given, it must have the same length as positions, and each value
will be applied to the corresponding row or column in positions.
Returns a list of :class:`matplotlib.collections.EventCollection`
objects that were added.
kwargs are :class:`~matplotlib.collections.LineCollection` properties:
%(LineCollection)s
**Example:**
.. plot:: mpl_examples/pylab_examples/eventplot_demo.py
"""
self._process_unit_info(xdata=positions,
ydata=[lineoffsets, linelengths],
kwargs=kwargs)
# We do the conversion first since not all unitized data is uniform
positions = self.convert_xunits(positions)
lineoffsets = self.convert_yunits(lineoffsets)
linelengths = self.convert_yunits(linelengths)
if not iterable(positions):
positions = [positions]
elif any(iterable(position) for position in positions):
positions = [np.asanyarray(position) for position in positions]
else:
positions = [np.asanyarray(positions)]
if len(positions) == 0:
return []
if not iterable(lineoffsets):
lineoffsets = [lineoffsets]
if not iterable(linelengths):
linelengths = [linelengths]
if not iterable(linewidths):
linewidths = [linewidths]
if not iterable(colors):
colors = [colors]
if hasattr(linestyles, 'lower') or not iterable(linestyles):
linestyles = [linestyles]
lineoffsets = np.asarray(lineoffsets)
linelengths = np.asarray(linelengths)
linewidths = np.asarray(linewidths)
if len(lineoffsets) == 0:
lineoffsets = [None]
if len(linelengths) == 0:
linelengths = [None]
if len(linewidths) == 0:
lineoffsets = [None]
if len(linewidths) == 0:
lineoffsets = [None]
if len(colors) == 0:
colors = [None]
if len(lineoffsets) == 1 and len(positions) != 1:
lineoffsets = np.tile(lineoffsets, len(positions))
lineoffsets[0] = 0
lineoffsets = np.cumsum(lineoffsets)
if len(linelengths) == 1:
linelengths = np.tile(linelengths, len(positions))
if len(linewidths) == 1:
linewidths = np.tile(linewidths, len(positions))
if len(colors) == 1:
colors = np.asanyarray(colors)
colors = np.tile(colors, [len(positions), 1])
if len(linestyles) == 1:
linestyles = [linestyles] * len(positions)
if len(lineoffsets) != len(positions):
raise ValueError('lineoffsets and positions are unequal sized '
'sequences')
if len(linelengths) != len(positions):
raise ValueError('linelengths and positions are unequal sized '
'sequences')
if len(linewidths) != len(positions):
raise ValueError('linewidths and positions are unequal sized '
'sequences')
if len(colors) != len(positions):
raise ValueError('colors and positions are unequal sized '
'sequences')
if len(linestyles) != len(positions):
raise ValueError('linestyles and positions are unequal sized '
'sequences')
colls = []
for position, lineoffset, linelength, linewidth, color, linestyle in \
itertools.izip(positions, lineoffsets, linelengths, linewidths,
colors, linestyles):
coll = mcoll.EventCollection(position,
orientation=orientation,
lineoffset=lineoffset,
linelength=linelength,
linewidth=linewidth,
color=color,
linestyle=linestyle)
self.add_collection(coll)
coll.update(kwargs)
colls.append(coll)
if len(positions) > 0:
minpos = min(position.min() for position in positions)
maxpos = max(position.max() for position in positions)
minline = (lineoffsets - linelengths).min()
maxline = (lineoffsets + linelengths).max()
if colls[0].is_horizontal():
corners = (minpos, minline), (maxpos, maxline)
else:
corners = (minline, minpos), (maxline, maxpos)
self.update_datalim(corners)
self.autoscale_view()
return colls
#### Basic plotting
@docstring.dedent_interpd
def plot(self, *args, **kwargs):
"""
Plot lines and/or markers to the
:class:`~matplotlib.axes.Axes`. *args* is a variable length
argument, allowing for multiple *x*, *y* pairs with an
optional format string. For example, each of the following is
legal::
plot(x, y) # plot x and y using default line style and color
plot(x, y, 'bo') # plot x and y using blue circle markers
plot(y) # plot y using x as index array 0..N-1
plot(y, 'r+') # ditto, but with red plusses
If *x* and/or *y* is 2-dimensional, then the corresponding columns
will be plotted.
An arbitrary number of *x*, *y*, *fmt* groups can be
specified, as in::
a.plot(x1, y1, 'g^', x2, y2, 'g-')
Return value is a list of lines that were added.
By default, each line is assigned a different color specified by a
'color cycle'. To change this behavior, you can edit the
axes.color_cycle rcParam. Alternatively, you can use
:meth:`~matplotlib.axes.Axes.set_default_color_cycle`.
The following format string characters are accepted to control
the line style or marker:
================ ===============================
character description
================ ===============================
``'-'`` solid line style
``'--'`` dashed line style
``'-.'`` dash-dot line style
``':'`` dotted line style
``'.'`` point marker
``','`` pixel marker
``'o'`` circle marker
``'v'`` triangle_down marker
``'^'`` triangle_up marker
``'<'`` triangle_left marker
``'>'`` triangle_right marker
``'1'`` tri_down marker
``'2'`` tri_up marker
``'3'`` tri_left marker
``'4'`` tri_right marker
``'s'`` square marker
``'p'`` pentagon marker
``'*'`` star marker
``'h'`` hexagon1 marker
``'H'`` hexagon2 marker
``'+'`` plus marker
``'x'`` x marker
``'D'`` diamond marker
``'d'`` thin_diamond marker
``'|'`` vline marker
``'_'`` hline marker
================ ===============================
The following color abbreviations are supported:
========== ========
character color
========== ========
'b' blue
'g' green
'r' red
'c' cyan
'm' magenta
'y' yellow
'k' black
'w' white
========== ========
In addition, you can specify colors in many weird and
wonderful ways, including full names (``'green'``), hex
strings (``'#008000'``), RGB or RGBA tuples (``(0,1,0,1)``) or
grayscale intensities as a string (``'0.8'``). Of these, the
string specifications can be used in place of a ``fmt`` group,
but the tuple forms can be used only as ``kwargs``.
Line styles and colors are combined in a single format string, as in
``'bo'`` for blue circles.
The *kwargs* can be used to set line properties (any property that has
a ``set_*`` method). You can use this to set a line label (for auto
legends), linewidth, anitialising, marker face color, etc. Here is an
example::
plot([1,2,3], [1,2,3], 'go-', label='line 1', linewidth=2)
plot([1,2,3], [1,4,9], 'rs', label='line 2')
axis([0, 4, 0, 10])
legend()
If you make multiple lines with one plot command, the kwargs
apply to all those lines, e.g.::
plot(x1, y1, x2, y2, antialised=False)
Neither line will be antialiased.
You do not need to use format strings, which are just
abbreviations. All of the line properties can be controlled
by keyword arguments. For example, you can set the color,
marker, linestyle, and markercolor with::
plot(x, y, color='green', linestyle='dashed', marker='o',
markerfacecolor='blue', markersize=12).
See :class:`~matplotlib.lines.Line2D` for details.
The kwargs are :class:`~matplotlib.lines.Line2D` properties:
%(Line2D)s
kwargs *scalex* and *scaley*, if defined, are passed on to
:meth:`~matplotlib.axes.Axes.autoscale_view` to determine
whether the *x* and *y* axes are autoscaled; the default is
*True*.
"""
scalex = kwargs.pop('scalex', True)
scaley = kwargs.pop('scaley', True)
if not self._hold:
self.cla()
lines = []
for line in self._get_lines(*args, **kwargs):
self.add_line(line)
lines.append(line)
self.autoscale_view(scalex=scalex, scaley=scaley)
return lines
@docstring.dedent_interpd
def plot_date(self, x, y, fmt='bo', tz=None, xdate=True, ydate=False,
**kwargs):
"""
Plot with data with dates.
Call signature::
plot_date(x, y, fmt='bo', tz=None, xdate=True,
ydate=False, **kwargs)
Similar to the :func:`~matplotlib.pyplot.plot` command, except
the *x* or *y* (or both) data is considered to be dates, and the
axis is labeled accordingly.
*x* and/or *y* can be a sequence of dates represented as float
days since 0001-01-01 UTC.
Keyword arguments:
*fmt*: string
The plot format string.
*tz*: [ *None* | timezone string | :class:`tzinfo` instance]
The time zone to use in labeling dates. If *None*, defaults to rc
value.
*xdate*: [ *True* | *False* ]
If *True*, the *x*-axis will be labeled with dates.
*ydate*: [ *False* | *True* ]
If *True*, the *y*-axis will be labeled with dates.
Note if you are using custom date tickers and formatters, it
may be necessary to set the formatters/locators after the call
to :meth:`plot_date` since :meth:`plot_date` will set the
default tick locator to
:class:`matplotlib.dates.AutoDateLocator` (if the tick
locator is not already set to a
:class:`matplotlib.dates.DateLocator` instance) and the
default tick formatter to
:class:`matplotlib.dates.AutoDateFormatter` (if the tick
formatter is not already set to a
:class:`matplotlib.dates.DateFormatter` instance).
Valid kwargs are :class:`~matplotlib.lines.Line2D` properties:
%(Line2D)s
.. seealso::
:mod:`~matplotlib.dates` for helper functions
:func:`~matplotlib.dates.date2num`,
:func:`~matplotlib.dates.num2date` and
:func:`~matplotlib.dates.drange` for help on creating the required
floating point dates.
"""
if not self._hold:
self.cla()
ret = self.plot(x, y, fmt, **kwargs)
if xdate:
self.xaxis_date(tz)
if ydate:
self.yaxis_date(tz)
self.autoscale_view()
return ret
@docstring.dedent_interpd
def loglog(self, *args, **kwargs):
"""
Make a plot with log scaling on both the *x* and *y* axis.
Call signature::
loglog(*args, **kwargs)
:func:`~matplotlib.pyplot.loglog` supports all the keyword
arguments of :func:`~matplotlib.pyplot.plot` and
:meth:`matplotlib.axes.Axes.set_xscale` /
:meth:`matplotlib.axes.Axes.set_yscale`.
Notable keyword arguments:
*basex*/*basey*: scalar > 1
Base of the *x*/*y* logarithm
*subsx*/*subsy*: [ *None* | sequence ]
The location of the minor *x*/*y* ticks; *None* defaults
to autosubs, which depend on the number of decades in the
plot; see :meth:`matplotlib.axes.Axes.set_xscale` /
:meth:`matplotlib.axes.Axes.set_yscale` for details
*nonposx*/*nonposy*: ['mask' | 'clip' ]
Non-positive values in *x* or *y* can be masked as
invalid, or clipped to a very small positive number
The remaining valid kwargs are
:class:`~matplotlib.lines.Line2D` properties:
%(Line2D)s
**Example:**
.. plot:: mpl_examples/pylab_examples/log_demo.py
"""
if not self._hold:
self.cla()
dx = {'basex': kwargs.pop('basex', 10),
'subsx': kwargs.pop('subsx', None),
'nonposx': kwargs.pop('nonposx', 'mask'),
}
dy = {'basey': kwargs.pop('basey', 10),
'subsy': kwargs.pop('subsy', None),
'nonposy': kwargs.pop('nonposy', 'mask'),
}
self.set_xscale('log', **dx)
self.set_yscale('log', **dy)
b = self._hold
self._hold = True # we've already processed the hold
l = self.plot(*args, **kwargs)
self._hold = b # restore the hold
return l
@docstring.dedent_interpd
def semilogx(self, *args, **kwargs):
"""
Make a plot with log scaling on the *x* axis.
Call signature::
semilogx(*args, **kwargs)
:func:`semilogx` supports all the keyword arguments of
:func:`~matplotlib.pyplot.plot` and
:meth:`matplotlib.axes.Axes.set_xscale`.
Notable keyword arguments:
*basex*: scalar > 1
Base of the *x* logarithm
*subsx*: [ *None* | sequence ]
The location of the minor xticks; *None* defaults to
autosubs, which depend on the number of decades in the
plot; see :meth:`~matplotlib.axes.Axes.set_xscale` for
details.
*nonposx*: [ 'mask' | 'clip' ]
Non-positive values in *x* can be masked as
invalid, or clipped to a very small positive number
The remaining valid kwargs are
:class:`~matplotlib.lines.Line2D` properties:
%(Line2D)s
.. seealso::
:meth:`loglog`
For example code and figure
"""
if not self._hold:
self.cla()
d = {'basex': kwargs.pop('basex', 10),
'subsx': kwargs.pop('subsx', None),
'nonposx': kwargs.pop('nonposx', 'mask'),
}
self.set_xscale('log', **d)
b = self._hold
self._hold = True # we've already processed the hold
l = self.plot(*args, **kwargs)
self._hold = b # restore the hold
return l
@docstring.dedent_interpd
def semilogy(self, *args, **kwargs):
"""
Make a plot with log scaling on the *y* axis.
call signature::
semilogy(*args, **kwargs)
:func:`semilogy` supports all the keyword arguments of
:func:`~matplotlib.pylab.plot` and
:meth:`matplotlib.axes.Axes.set_yscale`.
Notable keyword arguments:
*basey*: scalar > 1
Base of the *y* logarithm
*subsy*: [ *None* | sequence ]
The location of the minor yticks; *None* defaults to
autosubs, which depend on the number of decades in the
plot; see :meth:`~matplotlib.axes.Axes.set_yscale` for
details.
*nonposy*: [ 'mask' | 'clip' ]
Non-positive values in *y* can be masked as
invalid, or clipped to a very small positive number
The remaining valid kwargs are
:class:`~matplotlib.lines.Line2D` properties:
%(Line2D)s
.. seealso::
:meth:`loglog`
For example code and figure
"""
if not self._hold:
self.cla()
d = {'basey': kwargs.pop('basey', 10),
'subsy': kwargs.pop('subsy', None),
'nonposy': kwargs.pop('nonposy', 'mask'),
}
self.set_yscale('log', **d)
b = self._hold
self._hold = True # we've already processed the hold
l = self.plot(*args, **kwargs)
self._hold = b # restore the hold
return l
@docstring.dedent_interpd
def acorr(self, x, **kwargs):
"""
Plot the autocorrelation of *x*.
Call signature::
acorr(x, normed=True, detrend=mlab.detrend_none, usevlines=True,
maxlags=10, **kwargs)
If *normed* = *True*, normalize the data by the autocorrelation at
0-th lag. *x* is detrended by the *detrend* callable (default no
normalization).
Data are plotted as ``plot(lags, c, **kwargs)``
Return value is a tuple (*lags*, *c*, *line*) where:
- *lags* are a length 2*maxlags+1 lag vector
- *c* is the 2*maxlags+1 auto correlation vector
- *line* is a :class:`~matplotlib.lines.Line2D` instance
returned by :meth:`plot`
The default *linestyle* is None and the default *marker* is
``'o'``, though these can be overridden with keyword args.
The cross correlation is performed with
:func:`numpy.correlate` with *mode* = 2.
If *usevlines* is *True*, :meth:`~matplotlib.axes.Axes.vlines`
rather than :meth:`~matplotlib.axes.Axes.plot` is used to draw
vertical lines from the origin to the acorr. Otherwise, the
plot style is determined by the kwargs, which are
:class:`~matplotlib.lines.Line2D` properties.
*maxlags* is a positive integer detailing the number of lags
to show. The default value of *None* will return all
``(2*len(x)-1)`` lags.
The return value is a tuple (*lags*, *c*, *linecol*, *b*)
where
- *linecol* is the
:class:`~matplotlib.collections.LineCollection`
- *b* is the *x*-axis.
.. seealso::
:meth:`~matplotlib.axes.Axes.plot` or
:meth:`~matplotlib.axes.Axes.vlines`
For documentation on valid kwargs.
**Example:**
:func:`~matplotlib.pyplot.xcorr` is top graph, and
:func:`~matplotlib.pyplot.acorr` is bottom graph.
.. plot:: mpl_examples/pylab_examples/xcorr_demo.py
"""
return self.xcorr(x, x, **kwargs)
@docstring.dedent_interpd
def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none,
usevlines=True, maxlags=10, **kwargs):
"""
Plot the cross correlation between *x* and *y*.
Call signature::
xcorr(self, x, y, normed=True, detrend=mlab.detrend_none,
usevlines=True, maxlags=10, **kwargs)
If *normed* = *True*, normalize the data by the cross
correlation at 0-th lag. *x* and y are detrended by the
*detrend* callable (default no normalization). *x* and *y*
must be equal length.
Data are plotted as ``plot(lags, c, **kwargs)``
Return value is a tuple (*lags*, *c*, *line*) where:
- *lags* are a length ``2*maxlags+1`` lag vector
- *c* is the ``2*maxlags+1`` auto correlation vector
- *line* is a :class:`~matplotlib.lines.Line2D` instance
returned by :func:`~matplotlib.pyplot.plot`.
The default *linestyle* is *None* and the default *marker* is
'o', though these can be overridden with keyword args. The
cross correlation is performed with :func:`numpy.correlate`
with *mode* = 2.
If *usevlines* is *True*:
:func:`~matplotlib.pyplot.vlines`
rather than :func:`~matplotlib.pyplot.plot` is used to draw
vertical lines from the origin to the xcorr. Otherwise the
plotstyle is determined by the kwargs, which are
:class:`~matplotlib.lines.Line2D` properties.
The return value is a tuple (*lags*, *c*, *linecol*, *b*)
where *linecol* is the
:class:`matplotlib.collections.LineCollection` instance and
*b* is the *x*-axis.
*maxlags* is a positive integer detailing the number of lags to show.
The default value of *None* will return all ``(2*len(x)-1)`` lags.
**Example:**
:func:`~matplotlib.pyplot.xcorr` is top graph, and
:func:`~matplotlib.pyplot.acorr` is bottom graph.
.. plot:: mpl_examples/pylab_examples/xcorr_demo.py
"""
Nx = len(x)
if Nx != len(y):
raise ValueError('x and y must be equal length')
x = detrend(np.asarray(x))
y = detrend(np.asarray(y))
c = np.correlate(x, y, mode=2)
if normed:
c /= np.sqrt(np.dot(x, x) * np.dot(y, y))
if maxlags is None:
maxlags = Nx - 1
if maxlags >= Nx or maxlags < 1:
raise ValueError('maglags must be None or strictly '
'positive < %d' % Nx)
lags = np.arange(-maxlags, maxlags + 1)
c = c[Nx - 1 - maxlags:Nx + maxlags]
if usevlines:
a = self.vlines(lags, [0], c, **kwargs)
b = self.axhline(**kwargs)
else:
kwargs.setdefault('marker', 'o')
kwargs.setdefault('linestyle', 'None')
a, = self.plot(lags, c, **kwargs)
b = None
return lags, c, a, b
def _get_legend_handles(self, legend_handler_map=None):
"return artists that will be used as handles for legend"
handles_original = self.lines + self.patches + \
self.collections + self.containers
# collections
handler_map = mlegend.Legend.get_default_handler_map()
if legend_handler_map is not None:
handler_map = handler_map.copy()
handler_map.update(legend_handler_map)
handles = []
for h in handles_original:
if h.get_label() == "_nolegend_": # .startswith('_'):
continue
if mlegend.Legend.get_legend_handler(handler_map, h):
handles.append(h)
return handles
def get_legend_handles_labels(self, legend_handler_map=None):
"""
Return handles and labels for legend
``ax.legend()`` is equivalent to ::
h, l = ax.get_legend_handles_labels()
ax.legend(h, l)
"""
handles = []
labels = []
for handle in self._get_legend_handles(legend_handler_map):
label = handle.get_label()
if label and not label.startswith('_'):
handles.append(handle)
labels.append(label)
return handles, labels
def legend(self, *args, **kwargs):
"""
Place a legend on the current axes.
Call signature::
legend(*args, **kwargs)
Places legend at location *loc*. Labels are a sequence of
strings and *loc* can be a string or an integer specifying the
legend location.
To make a legend with existing lines::
legend()
:meth:`legend` by itself will try and build a legend using the label
property of the lines/patches/collections. You can set the label of
a line by doing::
plot(x, y, label='my data')
or::
line.set_label('my data').
If label is set to '_nolegend_', the item will not be shown in
legend.
To automatically generate the legend from labels::
legend( ('label1', 'label2', 'label3') )
To make a legend for a list of lines and labels::
legend( (line1, line2, line3), ('label1', 'label2', 'label3') )
To make a legend at a given location, using a location argument::
legend( ('label1', 'label2', 'label3'), loc='upper left')
or::
legend((line1, line2, line3), ('label1', 'label2', 'label3'), loc=2)
The location codes are
=============== =============
Location String Location Code
=============== =============
'best' 0
'upper right' 1
'upper left' 2
'lower left' 3
'lower right' 4
'right' 5
'center left' 6
'center right' 7
'lower center' 8
'upper center' 9
'center' 10
=============== =============
Users can specify any arbitrary location for the legend using the
*bbox_to_anchor* keyword argument. bbox_to_anchor can be an instance
of BboxBase(or its derivatives) or a tuple of 2 or 4 floats.
For example::
loc = 'upper right', bbox_to_anchor = (0.5, 0.5)
will place the legend so that the upper right corner of the legend at
the center of the axes.
The legend location can be specified in other coordinate, by using the
*bbox_transform* keyword.
The loc itslef can be a 2-tuple giving x,y of the lower-left corner of
the legend in axes coords (*bbox_to_anchor* is ignored).
Keyword arguments:
*prop*: [ *None* | FontProperties | dict ]
A :class:`matplotlib.font_manager.FontProperties`
instance. If *prop* is a dictionary, a new instance will be
created with *prop*. If *None*, use rc settings.
*fontsize*: [size in points | 'xx-small' | 'x-small' | 'small' |
'medium' | 'large' | 'x-large' | 'xx-large']
Set the font size. May be either a size string, relative to
the default font size, or an absolute font size in points. This
argument is only used if prop is not specified.
*numpoints*: integer
The number of points in the legend for line
*scatterpoints*: integer
The number of points in the legend for scatter plot
*scatteryoffsets*: list of floats
a list of yoffsets for scatter symbols in legend
*markerscale*: [ *None* | scalar ]
The relative size of legend markers vs. original. If *None*,
use rc settings.
*frameon*: [ *True* | *False* ]
if *True*, draw a frame around the legend.
The default is set by the rcParam 'legend.frameon'
*fancybox*: [ *None* | *False* | *True* ]
if *True*, draw a frame with a round fancybox. If *None*,
use rc settings
*shadow*: [ *None* | *False* | *True* ]
If *True*, draw a shadow behind legend. If *None*,
use rc settings.
*framealpha*: [*None* | float]
If not None, alpha channel for legend frame. Default *None*.
*ncol* : integer
number of columns. default is 1
*mode* : [ "expand" | *None* ]
if mode is "expand", the legend will be horizontally expanded
to fill the axes area (or *bbox_to_anchor*)
*bbox_to_anchor*: an instance of BboxBase or a tuple of 2 or 4 floats
the bbox that the legend will be anchored.
*bbox_transform* : [ an instance of Transform | *None* ]
the transform for the bbox. transAxes if *None*.
*title* : string
the legend title
Padding and spacing between various elements use following
keywords parameters. These values are measure in font-size
units. e.g., a fontsize of 10 points and a handlelength=5
implies a handlelength of 50 points. Values from rcParams
will be used if None.
================ ====================================================
Keyword Description
================ ====================================================
borderpad the fractional whitespace inside the legend border
labelspacing the vertical space between the legend entries
handlelength the length of the legend handles
handletextpad the pad between the legend handle and text
borderaxespad the pad between the axes and legend border
columnspacing the spacing between columns
================ ====================================================
.. note::
Not all kinds of artist are supported by the legend command.
See :ref:`plotting-guide-legend` for details.
**Example:**
.. plot:: mpl_examples/api/legend_demo.py
.. seealso::
:ref:`plotting-guide-legend`.
"""
if len(args) == 0:
handles, labels = self.get_legend_handles_labels()
if len(handles) == 0:
warnings.warn("No labeled objects found. "
"Use label='...' kwarg on individual plots.")
return None
elif len(args) == 1:
# LABELS
labels = args[0]
handles = [h for h, label in zip(self._get_legend_handles(),
labels)]
elif len(args) == 2:
if is_string_like(args[1]) or isinstance(args[1], int):
# LABELS, LOC
labels, loc = args
handles = [h for h, label in zip(self._get_legend_handles(),
labels)]
kwargs['loc'] = loc
else:
# LINES, LABELS
handles, labels = args
elif len(args) == 3:
# LINES, LABELS, LOC
handles, labels, loc = args
kwargs['loc'] = loc
else:
raise TypeError('Invalid arguments to legend')
# Why do we need to call "flatten" here? -JJL
# handles = cbook.flatten(handles)
self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
return self.legend_
#### Specialized plotting
def step(self, x, y, *args, **kwargs):
"""
Make a step plot.
Call signature::
step(x, y, *args, **kwargs)
Additional keyword args to :func:`step` are the same as those
for :func:`~matplotlib.pyplot.plot`.
*x* and *y* must be 1-D sequences, and it is assumed, but not checked,
that *x* is uniformly increasing.
Keyword arguments:
*where*: [ 'pre' | 'post' | 'mid' ]
If 'pre', the interval from x[i] to x[i+1] has level y[i+1]
If 'post', that interval has level y[i]
If 'mid', the jumps in *y* occur half-way between the
*x*-values.
"""
where = kwargs.pop('where', 'pre')
if where not in ('pre', 'post', 'mid'):
raise ValueError("'where' argument to step must be "
"'pre', 'post' or 'mid'")
usr_linestyle = kwargs.pop('linestyle', '')
kwargs['linestyle'] = 'steps-' + where + usr_linestyle
return self.plot(x, y, *args, **kwargs)
@docstring.dedent_interpd
def bar(self, left, height, width=0.8, bottom=None, **kwargs):
"""
Make a bar plot.
Make a bar plot with rectangles bounded by:
`left`, `left` + `width`, `bottom`, `bottom` + `height`
(left, right, bottom and top edges)
Parameters
----------
left : sequence of scalars
the x coordinates of the left sides of the bars
height : sequence of scalars
the heights of the bars
width : scalar or array-like, optional, default: 0.8
the width(s) of the bars
bottom : scalar or array-like, optional, default: None
the y coordinate(s) of the bars
color : scalar or array-like, optional
the colors of the bar faces
edgecolor : scalar or array-like, optional
the colors of the bar edges
linewidth : scalar or array-like, optional, default: None
width of bar edge(s). If None, use default
linewidth; If 0, don't draw edges.
xerr : scalar or array-like, optional, default: None
if not None, will be used to generate errorbar(s) on the bar chart
yerr :scalar or array-like, optional, default: None
if not None, will be used to generate errorbar(s) on the bar chart
ecolor : scalar or array-like, optional, default: None
specifies the color of errorbar(s)
capsize : integer, optional, default: 3
determines the length in points of the error bar caps
error_kw :
dictionary of kwargs to be passed to errorbar method. *ecolor* and
*capsize* may be specified here rather than as independent kwargs.
align : ['edge' | 'center'], optional, default: 'edge'
If `edge`, aligns bars by their left edges (for vertical bars) and
by their bottom edges (for horizontal bars). If `center`, interpret
the `left` argument as the coordinates of the centers of the bars.
orientation : 'vertical' | 'horizontal', optional, default: 'vertical'
The orientation of the bars.
log : boolean, optional, default: False
If true, sets the axis to be log scale
Returns
-------
:class:`matplotlib.patches.Rectangle` instances.
Notes
-----
The optional arguments `color`, `edgecolor`, `linewidth`,
`xerr`, and `yerr` can be either scalars or sequences of
length equal to the number of bars. This enables you to use
bar as the basis for stacked bar charts, or candlestick plots.
Detail: `xerr` and `yerr` are passed directly to
:meth:`errorbar`, so they can also have shape 2xN for
independent specification of lower and upper errors.
Other optional kwargs:
%(Rectangle)s
**Example:** A stacked bar chart.
.. plot:: mpl_examples/pylab_examples/bar_stacked.py
"""
if not self._hold:
self.cla()
color = kwargs.pop('color', None)
edgecolor = kwargs.pop('edgecolor', None)
linewidth = kwargs.pop('linewidth', None)
# Because xerr and yerr will be passed to errorbar,
# most dimension checking and processing will be left
# to the errorbar method.
xerr = kwargs.pop('xerr', None)
yerr = kwargs.pop('yerr', None)
error_kw = kwargs.pop('error_kw', dict())
ecolor = kwargs.pop('ecolor', None)
capsize = kwargs.pop('capsize', 3)
error_kw.setdefault('ecolor', ecolor)
error_kw.setdefault('capsize', capsize)
align = kwargs.pop('align', 'edge')
orientation = kwargs.pop('orientation', 'vertical')
log = kwargs.pop('log', False)
label = kwargs.pop('label', '')
def make_iterable(x):
if not iterable(x):
return [x]
else:
return x
# make them safe to take len() of
_left = left
left = make_iterable(left)
height = make_iterable(height)
width = make_iterable(width)
_bottom = bottom
bottom = make_iterable(bottom)
linewidth = make_iterable(linewidth)
adjust_ylim = False
adjust_xlim = False
if orientation == 'vertical':
self._process_unit_info(xdata=left, ydata=height, kwargs=kwargs)
if log:
self.set_yscale('log', nonposy='clip')
# size width and bottom according to length of left
if _bottom is None:
if self.get_yscale() == 'log':
adjust_ylim = True
bottom = [0]
nbars = len(left)
if len(width) == 1:
width *= nbars
if len(bottom) == 1:
bottom *= nbars
elif orientation == 'horizontal':
self._process_unit_info(xdata=width, ydata=bottom, kwargs=kwargs)
if log:
self.set_xscale('log', nonposx='clip')
# size left and height according to length of bottom
if _left is None:
if self.get_xscale() == 'log':
adjust_xlim = True
left = [0]
nbars = len(bottom)
if len(left) == 1:
left *= nbars
if len(height) == 1:
height *= nbars
else:
raise ValueError('invalid orientation: %s' % orientation)
if len(linewidth) < nbars:
linewidth *= nbars
if color is None:
color = [None] * nbars
else:
color = list(mcolors.colorConverter.to_rgba_array(color))
if len(color) == 0: # until to_rgba_array is changed
color = [[0, 0, 0, 0]]
if len(color) < nbars:
color *= nbars
if edgecolor is None:
edgecolor = [None] * nbars
else:
edgecolor = list(mcolors.colorConverter.to_rgba_array(edgecolor))
if len(edgecolor) == 0: # until to_rgba_array is changed
edgecolor = [[0, 0, 0, 0]]
if len(edgecolor) < nbars:
edgecolor *= nbars
# FIXME: convert the following to proper input validation
# raising ValueError; don't use assert for this.
assert len(left) == nbars, ("incompatible sizes: argument 'left' must "
"be length %d or scalar" % nbars)
assert len(height) == nbars, ("incompatible sizes: argument 'height' "
"must be length %d or scalar" %
nbars)
assert len(width) == nbars, ("incompatible sizes: argument 'width' "
"must be length %d or scalar" %
nbars)
assert len(bottom) == nbars, ("incompatible sizes: argument 'bottom' "
"must be length %d or scalar" %
nbars)
patches = []
# lets do some conversions now since some types cannot be
# subtracted uniformly
if self.xaxis is not None:
left = self.convert_xunits(left)
width = self.convert_xunits(width)
if xerr is not None:
xerr = self.convert_xunits(xerr)
if self.yaxis is not None:
bottom = self.convert_yunits(bottom)
height = self.convert_yunits(height)
if yerr is not None:
yerr = self.convert_yunits(yerr)
if align == 'edge':
pass
elif align == 'center':
if orientation == 'vertical':
left = [left[i] - width[i] / 2. for i in xrange(len(left))]
elif orientation == 'horizontal':
bottom = [bottom[i] - height[i] / 2.
for i in xrange(len(bottom))]
else:
raise ValueError('invalid alignment: %s' % align)
args = zip(left, bottom, width, height, color, edgecolor, linewidth)
for l, b, w, h, c, e, lw in args:
if h < 0:
b += h
h = abs(h)
if w < 0:
l += w
w = abs(w)
r = mpatches.Rectangle(
xy=(l, b), width=w, height=h,
facecolor=c,
edgecolor=e,
linewidth=lw,
label='_nolegend_'
)
r.update(kwargs)
r.get_path()._interpolation_steps = 100
#print r.get_label(), label, 'label' in kwargs
self.add_patch(r)
patches.append(r)
holdstate = self._hold
self.hold(True) # ensure hold is on before plotting errorbars
if xerr is not None or yerr is not None:
if orientation == 'vertical':
# using list comps rather than arrays to preserve unit info
x = [l + 0.5 * w for l, w in zip(left, width)]
y = [b + h for b, h in zip(bottom, height)]
elif orientation == 'horizontal':
# using list comps rather than arrays to preserve unit info
x = [l + w for l, w in zip(left, width)]
y = [b + 0.5 * h for b, h in zip(bottom, height)]
if "label" not in error_kw:
error_kw["label"] = '_nolegend_'
errorbar = self.errorbar(x, y,
yerr=yerr, xerr=xerr,
fmt=None, **error_kw)
else:
errorbar = None
self.hold(holdstate) # restore previous hold state
if adjust_xlim:
xmin, xmax = self.dataLim.intervalx
xmin = np.amin([w for w in width if w > 0])
if xerr is not None:
xmin = xmin - np.amax(xerr)
xmin = max(xmin * 0.9, 1e-100)
self.dataLim.intervalx = (xmin, xmax)
if adjust_ylim:
ymin, ymax = self.dataLim.intervaly
ymin = np.amin([h for h in height if h > 0])
if yerr is not None:
ymin = ymin - np.amax(yerr)
ymin = max(ymin * 0.9, 1e-100)
self.dataLim.intervaly = (ymin, ymax)
self.autoscale_view()
bar_container = BarContainer(patches, errorbar, label=label)
self.add_container(bar_container)
return bar_container
@docstring.dedent_interpd
def barh(self, bottom, width, height=0.8, left=None, **kwargs):
"""
Make a horizontal bar plot.
Call signature::
barh(bottom, width, height=0.8, left=0, **kwargs)
Make a horizontal bar plot with rectangles bounded by:
*left*, *left* + *width*, *bottom*, *bottom* + *height*
(left, right, bottom and top edges)
*bottom*, *width*, *height*, and *left* can be either scalars
or sequences
Return value is a list of
:class:`matplotlib.patches.Rectangle` instances.
Required arguments:
======== ======================================================
Argument Description
======== ======================================================
*bottom* the vertical positions of the bottom edges of the bars
*width* the lengths of the bars
======== ======================================================
Optional keyword arguments:
=============== ==========================================
Keyword Description
=============== ==========================================
*height* the heights (thicknesses) of the bars
*left* the x coordinates of the left edges of the
bars
*color* the colors of the bars
*edgecolor* the colors of the bar edges
*linewidth* width of bar edges; None means use default
linewidth; 0 means don't draw edges.
*xerr* if not None, will be used to generate
errorbars on the bar chart
*yerr* if not None, will be used to generate
errorbars on the bar chart
*ecolor* specifies the color of any errorbar
*capsize* (default 3) determines the length in
points of the error bar caps
*align* 'edge' (default) | 'center'
*log* [False|True] False (default) leaves the
horizontal axis as-is; True sets it to log
scale
=============== ==========================================
Setting *align* = 'edge' aligns bars by their bottom edges in
bottom, while *align* = 'center' interprets these values as
the *y* coordinates of the bar centers.
The optional arguments *color*, *edgecolor*, *linewidth*,
*xerr*, and *yerr* can be either scalars or sequences of
length equal to the number of bars. This enables you to use
barh as the basis for stacked bar charts, or candlestick
plots.
other optional kwargs:
%(Rectangle)s
"""
patches = self.bar(left=left, height=height, width=width,
bottom=bottom, orientation='horizontal', **kwargs)
return patches
@docstring.dedent_interpd
def broken_barh(self, xranges, yrange, **kwargs):
"""
Plot horizontal bars.
Call signature::
broken_barh(self, xranges, yrange, **kwargs)
A collection of horizontal bars spanning *yrange* with a sequence of
*xranges*.
Required arguments:
========= ==============================
Argument Description
========= ==============================
*xranges* sequence of (*xmin*, *xwidth*)
*yrange* sequence of (*ymin*, *ywidth*)
========= ==============================
kwargs are
:class:`matplotlib.collections.BrokenBarHCollection`
properties:
%(BrokenBarHCollection)s
these can either be a single argument, ie::
facecolors = 'black'
or a sequence of arguments for the various bars, ie::
facecolors = ('black', 'red', 'green')
**Example:**
.. plot:: mpl_examples/pylab_examples/broken_barh.py
"""
col = mcoll.BrokenBarHCollection(xranges, yrange, **kwargs)
self.add_collection(col, autolim=True)
self.autoscale_view()
return col
def stem(self, *args, **kwargs):
"""
Create a stem plot.
Call signatures::
stem(y, linefmt='b-', markerfmt='bo', basefmt='r-')
stem(x, y, linefmt='b-', markerfmt='bo', basefmt='r-')
A stem plot plots vertical lines (using *linefmt*) at each *x*
location from the baseline to *y*, and places a marker there
using *markerfmt*. A horizontal line at 0 is is plotted using
*basefmt*.
If no *x* values are provided, the default is (0, 1, ..., len(y) - 1)
Return value is a tuple (*markerline*, *stemlines*,
*baseline*).
.. seealso::
This
`document <http://www.mathworks.com/help/techdoc/ref/stem.html>`_
for details.
**Example:**
.. plot:: mpl_examples/pylab_examples/stem_plot.py
"""
remember_hold = self._hold
if not self._hold:
self.cla()
self.hold(True)
# Assume there's at least one data array
y = np.asarray(args[0], dtype=np.float)
args = args[1:]
# Try a second one
try:
second = np.asarray(args[0], dtype=np.float)
x, y = y, second
args = args[1:]
except (IndexError, ValueError):
# The second array doesn't make sense, or it doesn't exist
second = np.arange(len(y))
x = second
# Popping some defaults
try:
linefmt = kwargs.pop('linefmt', args[0])
except IndexError:
linefmt = kwargs.pop('linefmt', 'b-')
try:
markerfmt = kwargs.pop('markerfmt', args[1])
except IndexError:
markerfmt = kwargs.pop('markerfmt', 'bo')
try:
basefmt = kwargs.pop('basefmt', args[2])
except IndexError:
basefmt = kwargs.pop('basefmt', 'r-')
bottom = kwargs.pop('bottom', None)
label = kwargs.pop('label', None)
markerline, = self.plot(x, y, markerfmt, label="_nolegend_")
if bottom is None:
bottom = 0
stemlines = []
for thisx, thisy in zip(x, y):
l, = self.plot([thisx, thisx], [bottom, thisy], linefmt,
label="_nolegend_")
stemlines.append(l)
baseline, = self.plot([np.amin(x), np.amax(x)], [bottom, bottom],
basefmt, label="_nolegend_")
self.hold(remember_hold)
stem_container = StemContainer((markerline, stemlines, baseline),
label=label)
self.add_container(stem_container)
return stem_container
def pie(self, x, explode=None, labels=None, colors=None,
autopct=None, pctdistance=0.6, shadow=False,
labeldistance=1.1, startangle=None, radius=None):
r"""
Plot a pie chart.
Call signature::
pie(x, explode=None, labels=None,
colors=('b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'),
autopct=None, pctdistance=0.6, shadow=False,
labeldistance=1.1, startangle=None, radius=None)
Make a pie chart of array *x*. The fractional area of each
wedge is given by x/sum(x). If sum(x) <= 1, then the values
of x give the fractional area directly and the array will not
be normalized. The wedges are plotted counterclockwise,
by default starting from the x-axis.
Keyword arguments:
*explode*: [ *None* | len(x) sequence ]
If not *None*, is a ``len(x)`` array which specifies the
fraction of the radius with which to offset each wedge.
*colors*: [ *None* | color sequence ]
A sequence of matplotlib color args through which the pie chart
will cycle.
*labels*: [ *None* | len(x) sequence of strings ]
A sequence of strings providing the labels for each wedge
*autopct*: [ *None* | format string | format function ]
If not *None*, is a string or function used to label the wedges
with their numeric value. The label will be placed inside the
wedge. If it is a format string, the label will be ``fmt%pct``.
If it is a function, it will be called.
*pctdistance*: scalar
The ratio between the center of each pie slice and the
start of the text generated by *autopct*. Ignored if
*autopct* is *None*; default is 0.6.
*labeldistance*: scalar
The radial distance at which the pie labels are drawn
*shadow*: [ *False* | *True* ]
Draw a shadow beneath the pie.
*startangle*: [ *None* | Offset angle ]
If not *None*, rotates the start of the pie chart by *angle*
degrees counterclockwise from the x-axis.
*radius*: [ *None* | scalar ]
The radius of the pie, if *radius* is *None* it will be set to 1.
The pie chart will probably look best if the figure and axes are
square, or the Axes aspect is equal. e.g.::
figure(figsize=(8,8))
ax = axes([0.1, 0.1, 0.8, 0.8])
or::
axes(aspect=1)
Return value:
If *autopct* is *None*, return the tuple (*patches*, *texts*):
- *patches* is a sequence of
:class:`matplotlib.patches.Wedge` instances
- *texts* is a list of the label
:class:`matplotlib.text.Text` instances.
If *autopct* is not *None*, return the tuple (*patches*,
*texts*, *autotexts*), where *patches* and *texts* are as
above, and *autotexts* is a list of
:class:`~matplotlib.text.Text` instances for the numeric
labels.
"""
self.set_frame_on(False)
x = np.asarray(x).astype(np.float32)
sx = float(x.sum())
if sx > 1:
x = np.divide(x, sx)
if labels is None:
labels = [''] * len(x)
if explode is None:
explode = [0] * len(x)
assert(len(x) == len(labels))
assert(len(x) == len(explode))
if colors is None:
colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k', 'w')
center = 0, 0
if radius is None:
radius = 1
# Starting theta1 is the start fraction of the circle
if startangle is None:
theta1 = 0
else:
theta1 = startangle / 360.0
texts = []
slices = []
autotexts = []
i = 0
for frac, label, expl in cbook.safezip(x, labels, explode):
x, y = center
theta2 = theta1 + frac
thetam = 2 * math.pi * 0.5 * (theta1 + theta2)
x += expl * math.cos(thetam)
y += expl * math.sin(thetam)
w = mpatches.Wedge((x, y), radius, 360. * theta1, 360. * theta2,
facecolor=colors[i % len(colors)])
slices.append(w)
self.add_patch(w)
w.set_label(label)
if shadow:
# make sure to add a shadow after the call to
# add_patch so the figure and transform props will be
# set
shad = mpatches.Shadow(w, -0.02, -0.02,
#props={'facecolor':w.get_facecolor()}
)
shad.set_zorder(0.9 * w.get_zorder())
shad.set_label('_nolegend_')
self.add_patch(shad)
xt = x + labeldistance * radius * math.cos(thetam)
yt = y + labeldistance * radius * math.sin(thetam)
label_alignment = xt > 0 and 'left' or 'right'
t = self.text(xt, yt, label,
size=rcParams['xtick.labelsize'],
horizontalalignment=label_alignment,
verticalalignment='center')
texts.append(t)
if autopct is not None:
xt = x + pctdistance * radius * math.cos(thetam)
yt = y + pctdistance * radius * math.sin(thetam)
if is_string_like(autopct):
s = autopct % (100. * frac)
elif callable(autopct):
s = autopct(100. * frac)
else:
raise TypeError(
'autopct must be callable or a format string')
t = self.text(xt, yt, s,
horizontalalignment='center',
verticalalignment='center')
autotexts.append(t)
theta1 = theta2
i += 1
self.set_xlim((-1.25, 1.25))
self.set_ylim((-1.25, 1.25))
self.set_xticks([])
self.set_yticks([])
if autopct is None:
return slices, texts
else:
return slices, texts, autotexts
@docstring.dedent_interpd
def errorbar(self, x, y, yerr=None, xerr=None,
fmt='-', ecolor=None, elinewidth=None, capsize=3,
barsabove=False, lolims=False, uplims=False,
xlolims=False, xuplims=False, errorevery=1, capthick=None,
**kwargs):
"""
Plot an errorbar graph.
Call signature::
errorbar(x, y, yerr=None, xerr=None,
fmt='-', ecolor=None, elinewidth=None, capsize=3,
barsabove=False, lolims=False, uplims=False,
xlolims=False, xuplims=False, errorevery=1,
capthick=None)
Plot *x* versus *y* with error deltas in *yerr* and *xerr*.
Vertical errorbars are plotted if *yerr* is not *None*.
Horizontal errorbars are plotted if *xerr* is not *None*.
*x*, *y*, *xerr*, and *yerr* can all be scalars, which plots a
single error bar at *x*, *y*.
Optional keyword arguments:
*xerr*/*yerr*: [ scalar | N, Nx1, or 2xN array-like ]
If a scalar number, len(N) array-like object, or an Nx1
array-like object, errorbars are drawn at +/-value relative
to the data.
If a sequence of shape 2xN, errorbars are drawn at -row1
and +row2 relative to the data.
*fmt*: '-'
The plot format symbol. If *fmt* is *None*, only the
errorbars are plotted. This is used for adding
errorbars to a bar plot, for example.
*ecolor*: [ *None* | mpl color ]
A matplotlib color arg which gives the color the errorbar lines;
if *None*, use the marker color.
*elinewidth*: scalar
The linewidth of the errorbar lines. If *None*, use the linewidth.
*capsize*: scalar
The length of the error bar caps in points
*capthick*: scalar
An alias kwarg to *markeredgewidth* (a.k.a. - *mew*). This
setting is a more sensible name for the property that
controls the thickness of the error bar cap in points. For
backwards compatibility, if *mew* or *markeredgewidth* are given,
then they will over-ride *capthick*. This may change in future
releases.
*barsabove*: [ *True* | *False* ]
if *True*, will plot the errorbars above the plot
symbols. Default is below.
*lolims* / *uplims* / *xlolims* / *xuplims*: [ *False* | *True* ]
These arguments can be used to indicate that a value gives
only upper/lower limits. In that case a caret symbol is
used to indicate this. lims-arguments may be of the same
type as *xerr* and *yerr*.
*errorevery*: positive integer
subsamples the errorbars. e.g., if everyerror=5, errorbars for
every 5-th datapoint will be plotted. The data plot itself still
shows all data points.
All other keyword arguments are passed on to the plot command for the
markers. For example, this code makes big red squares with
thick green edges::
x,y,yerr = rand(3,10)
errorbar(x, y, yerr, marker='s',
mfc='red', mec='green', ms=20, mew=4)
where *mfc*, *mec*, *ms* and *mew* are aliases for the longer
property names, *markerfacecolor*, *markeredgecolor*, *markersize*
and *markeredgewith*.
valid kwargs for the marker properties are
%(Line2D)s
Returns (*plotline*, *caplines*, *barlinecols*):
*plotline*: :class:`~matplotlib.lines.Line2D` instance
*x*, *y* plot markers and/or line
*caplines*: list of error bar cap
:class:`~matplotlib.lines.Line2D` instances
*barlinecols*: list of
:class:`~matplotlib.collections.LineCollection` instances for
the horizontal and vertical error ranges.
**Example:**
.. plot:: mpl_examples/statistics/errorbar_demo.py
"""
if errorevery < 1:
raise ValueError(
'errorevery has to be a strictly positive integer')
self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)
if not self._hold:
self.cla()
holdstate = self._hold
self._hold = True
label = kwargs.pop("label", None)
# make sure all the args are iterable; use lists not arrays to
# preserve units
if not iterable(x):
x = [x]
if not iterable(y):
y = [y]
if xerr is not None:
if not iterable(xerr):
xerr = [xerr] * len(x)
if yerr is not None:
if not iterable(yerr):
yerr = [yerr] * len(y)
l0 = None
if barsabove and fmt is not None:
l0, = self.plot(x, y, fmt, label="_nolegend_", **kwargs)
barcols = []
caplines = []
lines_kw = {'label': '_nolegend_'}
if elinewidth:
lines_kw['linewidth'] = elinewidth
else:
if 'linewidth' in kwargs:
lines_kw['linewidth'] = kwargs['linewidth']
if 'lw' in kwargs:
lines_kw['lw'] = kwargs['lw']
if 'transform' in kwargs:
lines_kw['transform'] = kwargs['transform']
if 'alpha' in kwargs:
lines_kw['alpha'] = kwargs['alpha']
if 'zorder' in kwargs:
lines_kw['zorder'] = kwargs['zorder']
# arrays fine here, they are booleans and hence not units
if not iterable(lolims):
lolims = np.asarray([lolims] * len(x), bool)
else:
lolims = np.asarray(lolims, bool)
if not iterable(uplims):
uplims = np.array([uplims] * len(x), bool)
else:
uplims = np.asarray(uplims, bool)
if not iterable(xlolims):
xlolims = np.array([xlolims] * len(x), bool)
else:
xlolims = np.asarray(xlolims, bool)
if not iterable(xuplims):
xuplims = np.array([xuplims] * len(x), bool)
else:
xuplims = np.asarray(xuplims, bool)
everymask = np.arange(len(x)) % errorevery == 0
def xywhere(xs, ys, mask):
"""
return xs[mask], ys[mask] where mask is True but xs and
ys are not arrays
"""
assert len(xs) == len(ys)
assert len(xs) == len(mask)
xs = [thisx for thisx, b in zip(xs, mask) if b]
ys = [thisy for thisy, b in zip(ys, mask) if b]
return xs, ys
if capsize > 0:
plot_kw = {
'ms': 2 * capsize,
'label': '_nolegend_'}
if capthick is not None:
# 'mew' has higher priority, I believe,
# if both 'mew' and 'markeredgewidth' exists.
# So, save capthick to markeredgewidth so that
# explicitly setting mew or markeredgewidth will
# over-write capthick.
plot_kw['markeredgewidth'] = capthick
# For backwards-compat, allow explicit setting of
# 'mew' or 'markeredgewidth' to over-ride capthick.
if 'markeredgewidth' in kwargs:
plot_kw['markeredgewidth'] = kwargs['markeredgewidth']
if 'mew' in kwargs:
plot_kw['mew'] = kwargs['mew']
if 'transform' in kwargs:
plot_kw['transform'] = kwargs['transform']
if 'alpha' in kwargs:
plot_kw['alpha'] = kwargs['alpha']
if 'zorder' in kwargs:
plot_kw['zorder'] = kwargs['zorder']
if xerr is not None:
if (iterable(xerr) and len(xerr) == 2 and
iterable(xerr[0]) and iterable(xerr[1])):
# using list comps rather than arrays to preserve units
left = [thisx - thiserr for (thisx, thiserr)
in cbook.safezip(x, xerr[0])]
right = [thisx + thiserr for (thisx, thiserr)
in cbook.safezip(x, xerr[1])]
else:
# using list comps rather than arrays to preserve units
left = [thisx - thiserr for (thisx, thiserr)
in cbook.safezip(x, xerr)]
right = [thisx + thiserr for (thisx, thiserr)
in cbook.safezip(x, xerr)]
yo, _ = xywhere(y, right, everymask)
lo, ro = xywhere(left, right, everymask)
barcols.append(self.hlines(yo, lo, ro, **lines_kw))
if capsize > 0:
if xlolims.any():
# can't use numpy logical indexing since left and
# y are lists
leftlo, ylo = xywhere(left, y, xlolims & everymask)
caplines.extend(
self.plot(leftlo, ylo, ls='None',
marker=mlines.CARETLEFT, **plot_kw))
xlolims = ~xlolims
leftlo, ylo = xywhere(left, y, xlolims & everymask)
caplines.extend(self.plot(leftlo, ylo, 'k|', **plot_kw))
else:
leftlo, ylo = xywhere(left, y, everymask)
caplines.extend(self.plot(leftlo, ylo, 'k|', **plot_kw))
if xuplims.any():
rightup, yup = xywhere(right, y, xuplims & everymask)
caplines.extend(
self.plot(rightup, yup, ls='None',
marker=mlines.CARETRIGHT, **plot_kw))
xuplims = ~xuplims
rightup, yup = xywhere(right, y, xuplims & everymask)
caplines.extend(self.plot(rightup, yup, 'k|', **plot_kw))
else:
rightup, yup = xywhere(right, y, everymask)
caplines.extend(self.plot(rightup, yup, 'k|', **plot_kw))
if yerr is not None:
if (iterable(yerr) and len(yerr) == 2 and
iterable(yerr[0]) and iterable(yerr[1])):
# using list comps rather than arrays to preserve units
lower = [thisy - thiserr for (thisy, thiserr)
in cbook.safezip(y, yerr[0])]
upper = [thisy + thiserr for (thisy, thiserr)
in cbook.safezip(y, yerr[1])]
else:
# using list comps rather than arrays to preserve units
lower = [thisy - thiserr for (thisy, thiserr)
in cbook.safezip(y, yerr)]
upper = [thisy + thiserr for (thisy, thiserr)
in cbook.safezip(y, yerr)]
xo, _ = xywhere(x, lower, everymask)
lo, uo = xywhere(lower, upper, everymask)
barcols.append(self.vlines(xo, lo, uo, **lines_kw))
if capsize > 0:
if lolims.any():
xlo, lowerlo = xywhere(x, lower, lolims & everymask)
caplines.extend(
self.plot(xlo, lowerlo, ls='None',
marker=mlines.CARETDOWN, **plot_kw))
lolims = ~lolims
xlo, lowerlo = xywhere(x, lower, lolims & everymask)
caplines.extend(self.plot(xlo, lowerlo, 'k_', **plot_kw))
else:
xlo, lowerlo = xywhere(x, lower, everymask)
caplines.extend(self.plot(xlo, lowerlo, 'k_', **plot_kw))
if uplims.any():
xup, upperup = xywhere(x, upper, uplims & everymask)
caplines.extend(
self.plot(xup, upperup, ls='None',
marker=mlines.CARETUP, **plot_kw))
uplims = ~uplims
xup, upperup = xywhere(x, upper, uplims & everymask)
caplines.extend(self.plot(xup, upperup, 'k_', **plot_kw))
else:
xup, upperup = xywhere(x, upper, everymask)
caplines.extend(self.plot(xup, upperup, 'k_', **plot_kw))
if not barsabove and fmt is not None:
l0, = self.plot(x, y, fmt, **kwargs)
if ecolor is None:
if l0 is None:
ecolor = self._get_lines.color_cycle.next()
else:
ecolor = l0.get_color()
for l in barcols:
l.set_color(ecolor)
for l in caplines:
l.set_color(ecolor)
self.autoscale_view()
self._hold = holdstate
errorbar_container = ErrorbarContainer((l0, tuple(caplines),
tuple(barcols)),
has_xerr=(xerr is not None),
has_yerr=(yerr is not None),
label=label)
self.containers.append(errorbar_container)
return errorbar_container # (l0, caplines, barcols)
def boxplot(self, x, notch=False, sym='b+', vert=True, whis=1.5,
positions=None, widths=None, patch_artist=False,
bootstrap=None, usermedians=None, conf_intervals=None):
"""
Make a box and whisker plot.
Call signature::
boxplot(x, notch=False, sym='+', vert=True, whis=1.5,
positions=None, widths=None, patch_artist=False,
bootstrap=None, usermedians=None, conf_intervals=None)
Make a box and whisker plot for each column of *x* or each
vector in sequence *x*. The box extends from the lower to
upper quartile values of the data, with a line at the median.
The whiskers extend from the box to show the range of the
data. Flier points are those past the end of the whiskers.
Function Arguments:
*x* :
Array or a sequence of vectors.
*notch* : [ False (default) | True ]
If False (default), produces a rectangular box plot.
If True, will produce a notched box plot
*sym* : [ default 'b+' ]
The default symbol for flier points.
Enter an empty string ('') if you don't want to show fliers.
*vert* : [ False | True (default) ]
If True (default), makes the boxes vertical.
If False, makes horizontal boxes.
*whis* : [ default 1.5 ]
Defines the length of the whiskers as a function of the inner
quartile range. They extend to the most extreme data point
within ( ``whis*(75%-25%)`` ) data range.
*bootstrap* : [ *None* (default) | integer ]
Specifies whether to bootstrap the confidence intervals
around the median for notched boxplots. If bootstrap==None,
no bootstrapping is performed, and notches are calculated
using a Gaussian-based asymptotic approximation (see McGill, R.,
Tukey, J.W., and Larsen, W.A., 1978, and Kendall and Stuart,
1967). Otherwise, bootstrap specifies the number of times to
bootstrap the median to determine it's 95% confidence intervals.
Values between 1000 and 10000 are recommended.
*usermedians* : [ default None ]
An array or sequence whose first dimension (or length) is
compatible with *x*. This overrides the medians computed by
matplotlib for each element of *usermedians* that is not None.
When an element of *usermedians* == None, the median will be
computed directly as normal.
*conf_intervals* : [ default None ]
Array or sequence whose first dimension (or length) is compatible
with *x* and whose second dimension is 2. When the current element
of *conf_intervals* is not None, the notch locations computed by
matplotlib are overridden (assuming notch is True). When an
element of *conf_intervals* is None, boxplot compute notches the
method specified by the other kwargs (e.g., *bootstrap*).
*positions* : [ default 1,2,...,n ]
Sets the horizontal positions of the boxes. The ticks and limits
are automatically set to match the positions.
*widths* : [ default 0.5 ]
Either a scalar or a vector and sets the width of each box. The
default is 0.5, or ``0.15*(distance between extreme positions)``
if that is smaller.
*patch_artist* : [ False (default) | True ]
If False produces boxes with the Line2D artist
If True produces boxes with the Patch artist
Returns a dictionary mapping each component of the boxplot
to a list of the :class:`matplotlib.lines.Line2D`
instances created. That dictionary has the following keys
(assuming vertical boxplots):
- boxes: the main body of the boxplot showing the quartiles
and the median's confidence intervals if enabled.
- medians: horizonal lines at the median of each box.
- whiskers: the vertical lines extending to the most extreme,
n-outlier data points.
- caps: the horizontal lines at the ends of the whiskers.
- fliers: points representing data that extend beyone the
whiskers (outliers).
**Example:**
.. plot:: pyplots/boxplot_demo.py
"""
def bootstrapMedian(data, N=5000):
# determine 95% confidence intervals of the median
M = len(data)
percentile = [2.5, 97.5]
estimate = np.zeros(N)
for n in range(N):
bsIndex = np.random.random_integers(0, M - 1, M)
bsData = data[bsIndex]
estimate[n] = mlab.prctile(bsData, 50)
CI = mlab.prctile(estimate, percentile)
return CI
def computeConfInterval(data, med, iq, bootstrap):
if bootstrap is not None:
# Do a bootstrap estimate of notch locations.
# get conf. intervals around median
CI = bootstrapMedian(data, N=bootstrap)
notch_min = CI[0]
notch_max = CI[1]
else:
# Estimate notch locations using Gaussian-based
# asymptotic approximation.
#
# For discussion: McGill, R., Tukey, J.W.,
# and Larsen, W.A. (1978) "Variations of
# Boxplots", The American Statistician, 32:12-16.
N = len(data)
notch_min = med - 1.57 * iq / np.sqrt(N)
notch_max = med + 1.57 * iq / np.sqrt(N)
return notch_min, notch_max
if not self._hold:
self.cla()
holdStatus = self._hold
whiskers, caps, boxes, medians, fliers = [], [], [], [], []
# convert x to a list of vectors
if hasattr(x, 'shape'):
if len(x.shape) == 1:
if hasattr(x[0], 'shape'):
x = list(x)
else:
x = [x, ]
elif len(x.shape) == 2:
nr, nc = x.shape
if nr == 1:
x = [x]
elif nc == 1:
x = [x.ravel()]
else:
x = [x[:, i] for i in xrange(nc)]
else:
raise ValueError("input x can have no more than 2 dimensions")
if not hasattr(x[0], '__len__'):
x = [x]
col = len(x)
# sanitize user-input medians
msg1 = "usermedians must either be a list/tuple or a 1d array"
msg2 = "usermedians' length must be compatible with x"
if usermedians is not None:
if hasattr(usermedians, 'shape'):
if len(usermedians.shape) != 1:
raise ValueError(msg1)
elif usermedians.shape[0] != col:
raise ValueError(msg2)
elif len(usermedians) != col:
raise ValueError(msg2)
#sanitize user-input confidence intervals
msg1 = "conf_intervals must either be a list of tuples or a 2d array"
msg2 = "conf_intervals' length must be compatible with x"
msg3 = "each conf_interval, if specificied, must have two values"
if conf_intervals is not None:
if hasattr(conf_intervals, 'shape'):
if len(conf_intervals.shape) != 2:
raise ValueError(msg1)
elif conf_intervals.shape[0] != col:
raise ValueError(msg2)
elif conf_intervals.shape[1] == 2:
raise ValueError(msg3)
else:
if len(conf_intervals) != col:
raise ValueError(msg2)
for ci in conf_intervals:
if ci is not None and len(ci) != 2:
raise ValueError(msg3)
# get some plot info
if positions is None:
positions = range(1, col + 1)
if widths is None:
distance = max(positions) - min(positions)
widths = min(0.15 * max(distance, 1.0), 0.5)
if isinstance(widths, float) or isinstance(widths, int):
widths = np.ones((col,), float) * widths
# loop through columns, adding each to plot
self.hold(True)
for i, pos in enumerate(positions):
d = np.ravel(x[i])
row = len(d)
if row == 0:
# no data, skip this position
continue
# get median and quartiles
q1, med, q3 = mlab.prctile(d, [25, 50, 75])
# replace with input medians if available
if usermedians is not None:
if usermedians[i] is not None:
med = usermedians[i]
# get high extreme
iq = q3 - q1
hi_val = q3 + whis * iq
wisk_hi = np.compress(d <= hi_val, d)
if len(wisk_hi) == 0 or np.max(wisk_hi) < q3:
wisk_hi = q3
else:
wisk_hi = max(wisk_hi)
# get low extreme
lo_val = q1 - whis * iq
wisk_lo = np.compress(d >= lo_val, d)
if len(wisk_lo) == 0 or np.min(wisk_lo) > q1:
wisk_lo = q1
else:
wisk_lo = min(wisk_lo)
# get fliers - if we are showing them
flier_hi = []
flier_lo = []
flier_hi_x = []
flier_lo_x = []
if len(sym) != 0:
flier_hi = np.compress(d > wisk_hi, d)
flier_lo = np.compress(d < wisk_lo, d)
flier_hi_x = np.ones(flier_hi.shape[0]) * pos
flier_lo_x = np.ones(flier_lo.shape[0]) * pos
# get x locations for fliers, whisker, whisker cap and box sides
box_x_min = pos - widths[i] * 0.5
box_x_max = pos + widths[i] * 0.5
wisk_x = np.ones(2) * pos
cap_x_min = pos - widths[i] * 0.25
cap_x_max = pos + widths[i] * 0.25
cap_x = [cap_x_min, cap_x_max]
# get y location for median
med_y = [med, med]
# calculate 'notch' plot
if notch:
# conf. intervals from user, if available
if (conf_intervals is not None and
conf_intervals[i] is not None):
notch_max = np.max(conf_intervals[i])
notch_min = np.min(conf_intervals[i])
else:
notch_min, notch_max = computeConfInterval(d, med, iq,
bootstrap)
# make our notched box vectors
box_x = [box_x_min, box_x_max, box_x_max, cap_x_max, box_x_max,
box_x_max, box_x_min, box_x_min, cap_x_min, box_x_min,
box_x_min]
box_y = [q1, q1, notch_min, med, notch_max, q3, q3, notch_max,
med, notch_min, q1]
# make our median line vectors
med_x = [cap_x_min, cap_x_max]
med_y = [med, med]
# calculate 'regular' plot
else:
# make our box vectors
box_x = [box_x_min, box_x_max, box_x_max, box_x_min, box_x_min]
box_y = [q1, q1, q3, q3, q1]
# make our median line vectors
med_x = [box_x_min, box_x_max]
def to_vc(xs, ys):
# convert arguments to verts and codes
verts = []
#codes = []
for xi, yi in zip(xs, ys):
verts.append((xi, yi))
verts.append((0, 0)) # ignored
codes = [mpath.Path.MOVETO] + \
[mpath.Path.LINETO] * (len(verts) - 2) + \
[mpath.Path.CLOSEPOLY]
return verts, codes
def patch_list(xs, ys):
verts, codes = to_vc(xs, ys)
path = mpath.Path(verts, codes)
patch = mpatches.PathPatch(path)
self.add_artist(patch)
return [patch]
# vertical or horizontal plot?
if vert:
def doplot(*args):
return self.plot(*args)
def dopatch(xs, ys):
return patch_list(xs, ys)
else:
def doplot(*args):
shuffled = []
for i in xrange(0, len(args), 3):
shuffled.extend([args[i + 1], args[i], args[i + 2]])
return self.plot(*shuffled)
def dopatch(xs, ys):
xs, ys = ys, xs # flip X, Y
return patch_list(xs, ys)
if patch_artist:
median_color = 'k'
else:
median_color = 'r'
whiskers.extend(doplot(wisk_x, [q1, wisk_lo], 'b--',
wisk_x, [q3, wisk_hi], 'b--'))
caps.extend(doplot(cap_x, [wisk_hi, wisk_hi], 'k-',
cap_x, [wisk_lo, wisk_lo], 'k-'))
if patch_artist:
boxes.extend(dopatch(box_x, box_y))
else:
boxes.extend(doplot(box_x, box_y, 'b-'))
medians.extend(doplot(med_x, med_y, median_color + '-'))
fliers.extend(doplot(flier_hi_x, flier_hi, sym,
flier_lo_x, flier_lo, sym))
# fix our axes/ticks up a little
if vert:
setticks, setlim = self.set_xticks, self.set_xlim
else:
setticks, setlim = self.set_yticks, self.set_ylim
newlimits = min(positions) - 0.5, max(positions) + 0.5
setlim(newlimits)
setticks(positions)
# reset hold status
self.hold(holdStatus)
return dict(whiskers=whiskers, caps=caps, boxes=boxes,
medians=medians, fliers=fliers)
@docstring.dedent_interpd
def scatter(self, x, y, s=20, c='b', marker='o', cmap=None, norm=None,
vmin=None, vmax=None, alpha=None, linewidths=None,
verts=None, **kwargs):
"""
Make a scatter plot of x vs y, where x and y are sequence like objects
of the same lengths.
Parameters
----------
x, y : array_like, shape (n, )
Input data
s : scalar or array_like, shape (n, ), optional, default: 20
size in points^2.
c : color or sequence of color, optional, default : 'b'
`c` can be a single color format string, or a sequence of color
specifications of length `N`, or a sequence of `N` numbers to be
mapped to colors using the `cmap` and `norm` specified via kwargs
(see below). Note that `c` should not be a single numeric RGB or
RGBA sequence because that is indistinguishable from an array of
values to be colormapped. `c` can be a 2-D array in which the
rows are RGB or RGBA, however.
marker : `~matplotlib.markers.MarkerStyle`, optional, default: 'o'
See `~matplotlib.markers` for more information on the different
styles of markers scatter supports.
cmap : `~matplotlib.colors.Colormap`, optional, default: None
A `~matplotlib.colors.Colormap` instance or registered name.
`cmap` is only used if `c` is an array of floats. If None,
defaults to rc `image.cmap`.
norm : `~matplotlib.colors.Normalize`, optional, default: None
A `~matplotlib.colors.Normalize` instance is used to scale
luminance data to 0, 1. `norm` is only used if `c` is an array of
floats. If `None`, use the default :func:`normalize`.
vmin, vmax : scalar, optional, default: None
`vmin` and `vmax` are used in conjunction with `norm` to normalize
luminance data. If either are `None`, the min and max of the
color array is used. Note if you pass a `norm` instance, your
settings for `vmin` and `vmax` will be ignored.
alpha : scalar, optional, default: None
The alpha blending value, between 0 (transparent) and 1 (opaque)
linewidths : scalar or array_like, optional, default: None
If None, defaults to (lines.linewidth,). Note that this is a
tuple, and if you set the linewidths argument you must set it as a
sequence of floats, as required by
`~matplotlib.collections.RegularPolyCollection`.
Returns
-------
paths : `~matplotlib.collections.PathCollection`
Other parameters
----------------
kwargs : `~matplotlib.collections.Collection` properties
Notes
------
Any or all of `x`, `y`, `s`, and `c` may be masked arrays, in
which case all masks will be combined and only unmasked points
will be plotted.
Examples
--------
.. plot:: mpl_examples/shapes_and_collections/scatter_demo.py
"""
if not self._hold:
self.cla()
self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)
x = self.convert_xunits(x)
y = self.convert_yunits(y)
# np.ma.ravel yields an ndarray, not a masked array,
# unless its argument is a masked array.
x = np.ma.ravel(x)
y = np.ma.ravel(y)
if x.size != y.size:
raise ValueError("x and y must be the same size")
s = np.ma.ravel(s) # This doesn't have to match x, y in size.
c_is_stringy = is_string_like(c) or is_sequence_of_strings(c)
if not c_is_stringy:
c = np.asanyarray(c)
if c.size == x.size:
c = np.ma.ravel(c)
x, y, s, c = cbook.delete_masked_points(x, y, s, c)
scales = s # Renamed for readability below.
if c_is_stringy:
colors = mcolors.colorConverter.to_rgba_array(c, alpha)
else:
# The inherent ambiguity is resolved in favor of color
# mapping, not interpretation as rgb or rgba:
if c.size == x.size:
colors = None # use cmap, norm after collection is created
else:
colors = mcolors.colorConverter.to_rgba_array(c, alpha)
faceted = kwargs.pop('faceted', None)
edgecolors = kwargs.get('edgecolors', None)
if faceted is not None:
cbook.warn_deprecated(
'1.2', name='faceted', alternative='edgecolor',
obj_type='option')
if faceted:
edgecolors = None
else:
edgecolors = 'none'
# to be API compatible
if marker is None and not (verts is None):
marker = (verts, 0)
verts = None
marker_obj = mmarkers.MarkerStyle(marker)
path = marker_obj.get_path().transformed(
marker_obj.get_transform())
if not marker_obj.is_filled():
edgecolors = 'face'
collection = mcoll.PathCollection(
(path,), scales,
facecolors=colors,
edgecolors=edgecolors,
linewidths=linewidths,
offsets=zip(x, y),
transOffset=kwargs.pop('transform', self.transData),
)
collection.set_transform(mtransforms.IdentityTransform())
collection.set_alpha(alpha)
collection.update(kwargs)
if colors is None:
if norm is not None:
assert(isinstance(norm, mcolors.Normalize))
collection.set_array(np.asarray(c))
collection.set_cmap(cmap)
collection.set_norm(norm)
if vmin is not None or vmax is not None:
collection.set_clim(vmin, vmax)
else:
collection.autoscale_None()
# The margin adjustment is a hack to deal with the fact that we don't
# want to transform all the symbols whose scales are in points
# to data coords to get the exact bounding box for efficiency
# reasons. It can be done right if this is deemed important.
# Also, only bother with this padding if there is anything to draw.
if self._xmargin < 0.05 and x.size > 0:
self.set_xmargin(0.05)
if self._ymargin < 0.05 and x.size > 0:
self.set_ymargin(0.05)
self.add_collection(collection)
self.autoscale_view()
return collection
@docstring.dedent_interpd
def hexbin(self, x, y, C=None, gridsize=100, bins=None,
xscale='linear', yscale='linear', extent=None,
cmap=None, norm=None, vmin=None, vmax=None,
alpha=None, linewidths=None, edgecolors='none',
reduce_C_function=np.mean, mincnt=None, marginals=False,
**kwargs):
"""
Make a hexagonal binning plot.
Call signature::
hexbin(x, y, C = None, gridsize = 100, bins = None,
xscale = 'linear', yscale = 'linear',
cmap=None, norm=None, vmin=None, vmax=None,
alpha=None, linewidths=None, edgecolors='none'
reduce_C_function = np.mean, mincnt=None, marginals=True
**kwargs)
Make a hexagonal binning plot of *x* versus *y*, where *x*,
*y* are 1-D sequences of the same length, *N*. If *C* is *None*
(the default), this is a histogram of the number of occurences
of the observations at (x[i],y[i]).
If *C* is specified, it specifies values at the coordinate
(x[i],y[i]). These values are accumulated for each hexagonal
bin and then reduced according to *reduce_C_function*, which
defaults to numpy's mean function (np.mean). (If *C* is
specified, it must also be a 1-D sequence of the same length
as *x* and *y*.)
*x*, *y* and/or *C* may be masked arrays, in which case only
unmasked points will be plotted.
Optional keyword arguments:
*gridsize*: [ 100 | integer ]
The number of hexagons in the *x*-direction, default is
100. The corresponding number of hexagons in the
*y*-direction is chosen such that the hexagons are
approximately regular. Alternatively, gridsize can be a
tuple with two elements specifying the number of hexagons
in the *x*-direction and the *y*-direction.
*bins*: [ *None* | 'log' | integer | sequence ]
If *None*, no binning is applied; the color of each hexagon
directly corresponds to its count value.
If 'log', use a logarithmic scale for the color
map. Internally, :math:`log_{10}(i+1)` is used to
determine the hexagon color.
If an integer, divide the counts in the specified number
of bins, and color the hexagons accordingly.
If a sequence of values, the values of the lower bound of
the bins to be used.
*xscale*: [ 'linear' | 'log' ]
Use a linear or log10 scale on the horizontal axis.
*scale*: [ 'linear' | 'log' ]
Use a linear or log10 scale on the vertical axis.
*mincnt*: [ *None* | a positive integer ]
If not *None*, only display cells with more than *mincnt*
number of points in the cell
*marginals*: [ *True* | *False* ]
if marginals is *True*, plot the marginal density as
colormapped rectagles along the bottom of the x-axis and
left of the y-axis
*extent*: [ *None* | scalars (left, right, bottom, top) ]
The limits of the bins. The default assigns the limits
based on gridsize, x, y, xscale and yscale.
Other keyword arguments controlling color mapping and normalization
arguments:
*cmap*: [ *None* | Colormap ]
a :class:`matplotlib.colors.Colormap` instance. If *None*,
defaults to rc ``image.cmap``.
*norm*: [ *None* | Normalize ]
:class:`matplotlib.colors.Normalize` instance is used to
scale luminance data to 0,1.
*vmin* / *vmax*: scalar
*vmin* and *vmax* are used in conjunction with *norm* to normalize
luminance data. If either are *None*, the min and max of the color
array *C* is used. Note if you pass a norm instance, your settings
for *vmin* and *vmax* will be ignored.
*alpha*: scalar between 0 and 1, or *None*
the alpha value for the patches
*linewidths*: [ *None* | scalar ]
If *None*, defaults to rc lines.linewidth. Note that this
is a tuple, and if you set the linewidths argument you
must set it as a sequence of floats, as required by
:class:`~matplotlib.collections.RegularPolyCollection`.
Other keyword arguments controlling the Collection properties:
*edgecolors*: [ *None* | ``'none'`` | mpl color | color sequence ]
If ``'none'``, draws the edges in the same color as the fill color.
This is the default, as it avoids unsightly unpainted pixels
between the hexagons.
If *None*, draws the outlines in the default color.
If a matplotlib color arg or sequence of rgba tuples, draws the
outlines in the specified color.
Here are the standard descriptions of all the
:class:`~matplotlib.collections.Collection` kwargs:
%(Collection)s
The return value is a
:class:`~matplotlib.collections.PolyCollection` instance; use
:meth:`~matplotlib.collections.PolyCollection.get_array` on
this :class:`~matplotlib.collections.PolyCollection` to get
the counts in each hexagon. If *marginals* is *True*, horizontal
bar and vertical bar (both PolyCollections) will be attached
to the return collection as attributes *hbar* and *vbar*.
**Example:**
.. plot:: mpl_examples/pylab_examples/hexbin_demo.py
"""
if not self._hold:
self.cla()
self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)
x, y, C = cbook.delete_masked_points(x, y, C)
# Set the size of the hexagon grid
if iterable(gridsize):
nx, ny = gridsize
else:
nx = gridsize
ny = int(nx / math.sqrt(3))
# Count the number of data in each hexagon
x = np.array(x, float)
y = np.array(y, float)
if xscale == 'log':
if np.any(x <= 0.0):
raise ValueError("x contains non-positive values, so can not"
" be log-scaled")
x = np.log10(x)
if yscale == 'log':
if np.any(y <= 0.0):
raise ValueError("y contains non-positive values, so can not"
" be log-scaled")
y = np.log10(y)
if extent is not None:
xmin, xmax, ymin, ymax = extent
else:
xmin = np.amin(x)
xmax = np.amax(x)
ymin = np.amin(y)
ymax = np.amax(y)
# In the x-direction, the hexagons exactly cover the region from
# xmin to xmax. Need some padding to avoid roundoff errors.
padding = 1.e-9 * (xmax - xmin)
xmin -= padding
xmax += padding
sx = (xmax - xmin) / nx
sy = (ymax - ymin) / ny
if marginals:
xorig = x.copy()
yorig = y.copy()
x = (x - xmin) / sx
y = (y - ymin) / sy
ix1 = np.round(x).astype(int)
iy1 = np.round(y).astype(int)
ix2 = np.floor(x).astype(int)
iy2 = np.floor(y).astype(int)
nx1 = nx + 1
ny1 = ny + 1
nx2 = nx
ny2 = ny
n = nx1 * ny1 + nx2 * ny2
d1 = (x - ix1) ** 2 + 3.0 * (y - iy1) ** 2
d2 = (x - ix2 - 0.5) ** 2 + 3.0 * (y - iy2 - 0.5) ** 2
bdist = (d1 < d2)
if C is None:
accum = np.zeros(n)
# Create appropriate views into "accum" array.
lattice1 = accum[:nx1 * ny1]
lattice2 = accum[nx1 * ny1:]
lattice1.shape = (nx1, ny1)
lattice2.shape = (nx2, ny2)
for i in xrange(len(x)):
if bdist[i]:
if ((ix1[i] >= 0) and (ix1[i] < nx1) and
(iy1[i] >= 0) and (iy1[i] < ny1)):
lattice1[ix1[i], iy1[i]] += 1
else:
if ((ix2[i] >= 0) and (ix2[i] < nx2) and
(iy2[i] >= 0) and (iy2[i] < ny2)):
lattice2[ix2[i], iy2[i]] += 1
# threshold
if mincnt is not None:
for i in xrange(nx1):
for j in xrange(ny1):
if lattice1[i, j] < mincnt:
lattice1[i, j] = np.nan
for i in xrange(nx2):
for j in xrange(ny2):
if lattice2[i, j] < mincnt:
lattice2[i, j] = np.nan
accum = np.hstack((lattice1.astype(float).ravel(),
lattice2.astype(float).ravel()))
good_idxs = ~np.isnan(accum)
else:
if mincnt is None:
mincnt = 0
# create accumulation arrays
lattice1 = np.empty((nx1, ny1), dtype=object)
for i in xrange(nx1):
for j in xrange(ny1):
lattice1[i, j] = []
lattice2 = np.empty((nx2, ny2), dtype=object)
for i in xrange(nx2):
for j in xrange(ny2):
lattice2[i, j] = []
for i in xrange(len(x)):
if bdist[i]:
if ((ix1[i] >= 0) and (ix1[i] < nx1) and
(iy1[i] >= 0) and (iy1[i] < ny1)):
lattice1[ix1[i], iy1[i]].append(C[i])
else:
if ((ix2[i] >= 0) and (ix2[i] < nx2) and
(iy2[i] >= 0) and (iy2[i] < ny2)):
lattice2[ix2[i], iy2[i]].append(C[i])
for i in xrange(nx1):
for j in xrange(ny1):
vals = lattice1[i, j]
if len(vals) > mincnt:
lattice1[i, j] = reduce_C_function(vals)
else:
lattice1[i, j] = np.nan
for i in xrange(nx2):
for j in xrange(ny2):
vals = lattice2[i, j]
if len(vals) > mincnt:
lattice2[i, j] = reduce_C_function(vals)
else:
lattice2[i, j] = np.nan
accum = np.hstack((lattice1.astype(float).ravel(),
lattice2.astype(float).ravel()))
good_idxs = ~np.isnan(accum)
offsets = np.zeros((n, 2), float)
offsets[:nx1 * ny1, 0] = np.repeat(np.arange(nx1), ny1)
offsets[:nx1 * ny1, 1] = np.tile(np.arange(ny1), nx1)
offsets[nx1 * ny1:, 0] = np.repeat(np.arange(nx2) + 0.5, ny2)
offsets[nx1 * ny1:, 1] = np.tile(np.arange(ny2), nx2) + 0.5
offsets[:, 0] *= sx
offsets[:, 1] *= sy
offsets[:, 0] += xmin
offsets[:, 1] += ymin
# remove accumulation bins with no data
offsets = offsets[good_idxs, :]
accum = accum[good_idxs]
polygon = np.zeros((6, 2), float)
polygon[:, 0] = sx * np.array([0.5, 0.5, 0.0, -0.5, -0.5, 0.0])
polygon[:, 1] = sy * np.array([-0.5, 0.5, 1.0, 0.5, -0.5, -1.0]) / 3.0
if edgecolors == 'none':
edgecolors = 'face'
if xscale == 'log' or yscale == 'log':
polygons = np.expand_dims(polygon, 0) + np.expand_dims(offsets, 1)
if xscale == 'log':
polygons[:, :, 0] = 10.0 ** polygons[:, :, 0]
xmin = 10.0 ** xmin
xmax = 10.0 ** xmax
self.set_xscale(xscale)
if yscale == 'log':
polygons[:, :, 1] = 10.0 ** polygons[:, :, 1]
ymin = 10.0 ** ymin
ymax = 10.0 ** ymax
self.set_yscale(yscale)
collection = mcoll.PolyCollection(
polygons,
edgecolors=edgecolors,
linewidths=linewidths,
)
else:
collection = mcoll.PolyCollection(
[polygon],
edgecolors=edgecolors,
linewidths=linewidths,
offsets=offsets,
transOffset=mtransforms.IdentityTransform(),
offset_position="data"
)
if isinstance(norm, mcolors.LogNorm):
if (accum == 0).any():
# make sure we have not zeros
accum += 1
# autoscale the norm with curren accum values if it hasn't
# been set
if norm is not None:
if norm.vmin is None and norm.vmax is None:
norm.autoscale(accum)
# Transform accum if needed
if bins == 'log':
accum = np.log10(accum + 1)
elif bins != None:
if not iterable(bins):
minimum, maximum = min(accum), max(accum)
bins -= 1 # one less edge than bins
bins = minimum + (maximum - minimum) * np.arange(bins) / bins
bins = np.sort(bins)
accum = bins.searchsorted(accum)
if norm is not None:
assert(isinstance(norm, mcolors.Normalize))
collection.set_array(accum)
collection.set_cmap(cmap)
collection.set_norm(norm)
collection.set_alpha(alpha)
collection.update(kwargs)
if vmin is not None or vmax is not None:
collection.set_clim(vmin, vmax)
else:
collection.autoscale_None()
corners = ((xmin, ymin), (xmax, ymax))
self.update_datalim(corners)
self.autoscale_view(tight=True)
# add the collection last
self.add_collection(collection)
if not marginals:
return collection
if C is None:
C = np.ones(len(x))
def coarse_bin(x, y, coarse):
ind = coarse.searchsorted(x).clip(0, len(coarse) - 1)
mus = np.zeros(len(coarse))
for i in range(len(coarse)):
mu = reduce_C_function(y[ind == i])
mus[i] = mu
return mus
coarse = np.linspace(xmin, xmax, gridsize)
xcoarse = coarse_bin(xorig, C, coarse)
valid = ~np.isnan(xcoarse)
verts, values = [], []
for i, val in enumerate(xcoarse):
thismin = coarse[i]
if i < len(coarse) - 1:
thismax = coarse[i + 1]
else:
thismax = thismin + np.diff(coarse)[-1]
if not valid[i]:
continue
verts.append([(thismin, 0),
(thismin, 0.05),
(thismax, 0.05),
(thismax, 0)])
values.append(val)
values = np.array(values)
trans = mtransforms.blended_transform_factory(
self.transData, self.transAxes)
hbar = mcoll.PolyCollection(verts, transform=trans, edgecolors='face')
hbar.set_array(values)
hbar.set_cmap(cmap)
hbar.set_norm(norm)
hbar.set_alpha(alpha)
hbar.update(kwargs)
self.add_collection(hbar)
coarse = np.linspace(ymin, ymax, gridsize)
ycoarse = coarse_bin(yorig, C, coarse)
valid = ~np.isnan(ycoarse)
verts, values = [], []
for i, val in enumerate(ycoarse):
thismin = coarse[i]
if i < len(coarse) - 1:
thismax = coarse[i + 1]
else:
thismax = thismin + np.diff(coarse)[-1]
if not valid[i]:
continue
verts.append([(0, thismin), (0.0, thismax),
(0.05, thismax), (0.05, thismin)])
values.append(val)
values = np.array(values)
trans = mtransforms.blended_transform_factory(
self.transAxes, self.transData)
vbar = mcoll.PolyCollection(verts, transform=trans, edgecolors='face')
vbar.set_array(values)
vbar.set_cmap(cmap)
vbar.set_norm(norm)
vbar.set_alpha(alpha)
vbar.update(kwargs)
self.add_collection(vbar)
collection.hbar = hbar
collection.vbar = vbar
def on_changed(collection):
hbar.set_cmap(collection.get_cmap())
hbar.set_clim(collection.get_clim())
vbar.set_cmap(collection.get_cmap())
vbar.set_clim(collection.get_clim())
collection.callbacksSM.connect('changed', on_changed)
return collection
@docstring.dedent_interpd
def arrow(self, x, y, dx, dy, **kwargs):
"""
Add an arrow to the axes.
Call signature::
arrow(x, y, dx, dy, **kwargs)
Draws arrow on specified axis from (*x*, *y*) to (*x* + *dx*,
*y* + *dy*). Uses FancyArrow patch to construct the arrow.
The resulting arrow is affected by the axes aspect ratio and limits.
This may produce an arrow whose head is not square with its stem. To
create an arrow whose head is square with its stem, use
:meth:`annotate`.
Optional kwargs control the arrow construction and properties:
%(FancyArrow)s
**Example:**
.. plot:: mpl_examples/pylab_examples/arrow_demo.py
"""
# Strip away units for the underlying patch since units
# do not make sense to most patch-like code
x = self.convert_xunits(x)
y = self.convert_yunits(y)
dx = self.convert_xunits(dx)
dy = self.convert_yunits(dy)
a = mpatches.FancyArrow(x, y, dx, dy, **kwargs)
self.add_artist(a)
return a
def quiverkey(self, *args, **kw):
qk = mquiver.QuiverKey(*args, **kw)
self.add_artist(qk)
return qk
quiverkey.__doc__ = mquiver.QuiverKey.quiverkey_doc
def quiver(self, *args, **kw):
if not self._hold:
self.cla()
q = mquiver.Quiver(self, *args, **kw)
self.add_collection(q, False)
self.update_datalim(q.XY)
self.autoscale_view()
return q
quiver.__doc__ = mquiver.Quiver.quiver_doc
def stackplot(self, x, *args, **kwargs):
return mstack.stackplot(self, x, *args, **kwargs)
stackplot.__doc__ = mstack.stackplot.__doc__
def streamplot(self, x, y, u, v, density=1, linewidth=None, color=None,
cmap=None, norm=None, arrowsize=1, arrowstyle='-|>',
minlength=0.1, transform=None):
if not self._hold:
self.cla()
stream_container = mstream.streamplot(self, x, y, u, v,
density=density,
linewidth=linewidth,
color=color,
cmap=cmap,
norm=norm,
arrowsize=arrowsize,
arrowstyle=arrowstyle,
minlength=minlength,
transform=transform)
return stream_container
streamplot.__doc__ = mstream.streamplot.__doc__
@docstring.dedent_interpd
def barbs(self, *args, **kw):
"""
%(barbs_doc)s
**Example:**
.. plot:: mpl_examples/pylab_examples/barb_demo.py
"""
if not self._hold:
self.cla()
b = mquiver.Barbs(self, *args, **kw)
self.add_collection(b)
self.update_datalim(b.get_offsets())
self.autoscale_view()
return b
@docstring.dedent_interpd
def fill(self, *args, **kwargs):
"""
Plot filled polygons.
Call signature::
fill(*args, **kwargs)
*args* is a variable length argument, allowing for multiple
*x*, *y* pairs with an optional color format string; see
:func:`~matplotlib.pyplot.plot` for details on the argument
parsing. For example, to plot a polygon with vertices at *x*,
*y* in blue.::
ax.fill(x,y, 'b' )
An arbitrary number of *x*, *y*, *color* groups can be specified::
ax.fill(x1, y1, 'g', x2, y2, 'r')
Return value is a list of :class:`~matplotlib.patches.Patch`
instances that were added.
The same color strings that :func:`~matplotlib.pyplot.plot`
supports are supported by the fill format string.
If you would like to fill below a curve, e.g., shade a region
between 0 and *y* along *x*, use :meth:`fill_between`
The *closed* kwarg will close the polygon when *True* (default).
kwargs control the :class:`~matplotlib.patches.Polygon` properties:
%(Polygon)s
**Example:**
.. plot:: mpl_examples/lines_bars_and_markers/fill_demo.py
"""
if not self._hold:
self.cla()
patches = []
for poly in self._get_patches_for_fill(*args, **kwargs):
self.add_patch(poly)
patches.append(poly)
self.autoscale_view()
return patches
@docstring.dedent_interpd
def fill_between(self, x, y1, y2=0, where=None, interpolate=False,
**kwargs):
"""
Make filled polygons between two curves.
Call signature::
fill_between(x, y1, y2=0, where=None, **kwargs)
Create a :class:`~matplotlib.collections.PolyCollection`
filling the regions between *y1* and *y2* where
``where==True``
*x* :
An N-length array of the x data
*y1* :
An N-length array (or scalar) of the y data
*y2* :
An N-length array (or scalar) of the y data
*where* :
If *None*, default to fill between everywhere. If not *None*,
it is an N-length numpy boolean array and the fill will
only happen over the regions where ``where==True``.
*interpolate* :
If *True*, interpolate between the two lines to find the
precise point of intersection. Otherwise, the start and
end points of the filled region will only occur on explicit
values in the *x* array.
*kwargs* :
Keyword args passed on to the
:class:`~matplotlib.collections.PolyCollection`.
kwargs control the :class:`~matplotlib.patches.Polygon` properties:
%(PolyCollection)s
.. plot:: mpl_examples/pylab_examples/fill_between_demo.py
.. seealso::
:meth:`fill_betweenx`
for filling between two sets of x-values
"""
# Handle united data, such as dates
self._process_unit_info(xdata=x, ydata=y1, kwargs=kwargs)
self._process_unit_info(ydata=y2)
# Convert the arrays so we can work with them
x = ma.masked_invalid(self.convert_xunits(x))
y1 = ma.masked_invalid(self.convert_yunits(y1))
y2 = ma.masked_invalid(self.convert_yunits(y2))
if y1.ndim == 0:
y1 = np.ones_like(x) * y1
if y2.ndim == 0:
y2 = np.ones_like(x) * y2
if where is None:
where = np.ones(len(x), np.bool)
else:
where = np.asarray(where, np.bool)
if not (x.shape == y1.shape == y2.shape == where.shape):
raise ValueError("Argument dimensions are incompatible")
mask = reduce(ma.mask_or, [ma.getmask(a) for a in (x, y1, y2)])
if mask is not ma.nomask:
where &= ~mask
polys = []
for ind0, ind1 in mlab.contiguous_regions(where):
xslice = x[ind0:ind1]
y1slice = y1[ind0:ind1]
y2slice = y2[ind0:ind1]
if not len(xslice):
continue
N = len(xslice)
X = np.zeros((2 * N + 2, 2), np.float)
if interpolate:
def get_interp_point(ind):
im1 = max(ind - 1, 0)
x_values = x[im1:ind + 1]
diff_values = y1[im1:ind + 1] - y2[im1:ind + 1]
y1_values = y1[im1:ind + 1]
if len(diff_values) == 2:
if np.ma.is_masked(diff_values[1]):
return x[im1], y1[im1]
elif np.ma.is_masked(diff_values[0]):
return x[ind], y1[ind]
diff_order = diff_values.argsort()
diff_root_x = np.interp(
0, diff_values[diff_order], x_values[diff_order])
diff_root_y = np.interp(diff_root_x, x_values, y1_values)
return diff_root_x, diff_root_y
start = get_interp_point(ind0)
end = get_interp_point(ind1)
else:
# the purpose of the next two lines is for when y2 is a
# scalar like 0 and we want the fill to go all the way
# down to 0 even if none of the y1 sample points do
start = xslice[0], y2slice[0]
end = xslice[-1], y2slice[-1]
X[0] = start
X[N + 1] = end
X[1:N + 1, 0] = xslice
X[1:N + 1, 1] = y1slice
X[N + 2:, 0] = xslice[::-1]
X[N + 2:, 1] = y2slice[::-1]
polys.append(X)
collection = mcoll.PolyCollection(polys, **kwargs)
# now update the datalim and autoscale
XY1 = np.array([x[where], y1[where]]).T
XY2 = np.array([x[where], y2[where]]).T
self.dataLim.update_from_data_xy(XY1, self.ignore_existing_data_limits,
updatex=True, updatey=True)
self.dataLim.update_from_data_xy(XY2, self.ignore_existing_data_limits,
updatex=False, updatey=True)
self.add_collection(collection)
self.autoscale_view()
return collection
@docstring.dedent_interpd
def fill_betweenx(self, y, x1, x2=0, where=None, **kwargs):
"""
Make filled polygons between two horizontal curves.
Call signature::
fill_betweenx(y, x1, x2=0, where=None, **kwargs)
Create a :class:`~matplotlib.collections.PolyCollection`
filling the regions between *x1* and *x2* where
``where==True``
*y* :
An N-length array of the y data
*x1* :
An N-length array (or scalar) of the x data
*x2* :
An N-length array (or scalar) of the x data
*where* :
If *None*, default to fill between everywhere. If not *None*,
it is a N length numpy boolean array and the fill will
only happen over the regions where ``where==True``
*kwargs* :
keyword args passed on to the
:class:`~matplotlib.collections.PolyCollection`
kwargs control the :class:`~matplotlib.patches.Polygon` properties:
%(PolyCollection)s
.. plot:: mpl_examples/pylab_examples/fill_betweenx_demo.py
.. seealso::
:meth:`fill_between`
for filling between two sets of y-values
"""
# Handle united data, such as dates
self._process_unit_info(ydata=y, xdata=x1, kwargs=kwargs)
self._process_unit_info(xdata=x2)
# Convert the arrays so we can work with them
y = ma.masked_invalid(self.convert_yunits(y))
x1 = ma.masked_invalid(self.convert_xunits(x1))
x2 = ma.masked_invalid(self.convert_xunits(x2))
if x1.ndim == 0:
x1 = np.ones_like(y) * x1
if x2.ndim == 0:
x2 = np.ones_like(y) * x2
if where is None:
where = np.ones(len(y), np.bool)
else:
where = np.asarray(where, np.bool)
if not (y.shape == x1.shape == x2.shape == where.shape):
raise ValueError("Argument dimensions are incompatible")
mask = reduce(ma.mask_or, [ma.getmask(a) for a in (y, x1, x2)])
if mask is not ma.nomask:
where &= ~mask
polys = []
for ind0, ind1 in mlab.contiguous_regions(where):
yslice = y[ind0:ind1]
x1slice = x1[ind0:ind1]
x2slice = x2[ind0:ind1]
if not len(yslice):
continue
N = len(yslice)
Y = np.zeros((2 * N + 2, 2), np.float)
# the purpose of the next two lines is for when x2 is a
# scalar like 0 and we want the fill to go all the way
# down to 0 even if none of the x1 sample points do
Y[0] = x2slice[0], yslice[0]
Y[N + 1] = x2slice[-1], yslice[-1]
Y[1:N + 1, 0] = x1slice
Y[1:N + 1, 1] = yslice
Y[N + 2:, 0] = x2slice[::-1]
Y[N + 2:, 1] = yslice[::-1]
polys.append(Y)
collection = mcoll.PolyCollection(polys, **kwargs)
# now update the datalim and autoscale
X1Y = np.array([x1[where], y[where]]).T
X2Y = np.array([x2[where], y[where]]).T
self.dataLim.update_from_data_xy(X1Y, self.ignore_existing_data_limits,
updatex=True, updatey=True)
self.dataLim.update_from_data_xy(X2Y, self.ignore_existing_data_limits,
updatex=False, updatey=True)
self.add_collection(collection)
self.autoscale_view()
return collection
#### plotting z(x,y): imshow, pcolor and relatives, contour
@docstring.dedent_interpd
def imshow(self, X, cmap=None, norm=None, aspect=None,
interpolation=None, alpha=None, vmin=None, vmax=None,
origin=None, extent=None, shape=None, filternorm=1,
filterrad=4.0, imlim=None, resample=None, url=None, **kwargs):
"""
Display an image on the axes.
Parameters
-----------
X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4)
Display the image in `X` to current axes. `X` may be a float
array, a uint8 array or a PIL image. If `X` is an array, it
can have the following shapes:
- MxN -- luminance (grayscale, float array only)
- MxNx3 -- RGB (float or uint8 array)
- MxNx4 -- RGBA (float or uint8 array)
The value for each component of MxNx3 and MxNx4 float arrays
should be in the range 0.0 to 1.0; MxN float arrays may be
normalised.
cmap : `~matplotlib.colors.Colormap`, optional, default: None
If None, default to rc `image.cmap` value. `cmap` is ignored when
`X` has RGB(A) information
aspect : ['auto' | 'equal' | scalar], optional, default: None
If 'auto', changes the image aspect ratio to match that of the
axes.
If 'equal', and `extent` is None, changes the axes aspect ratio to
match that of the image. If `extent` is not `None`, the axes
aspect ratio is changed to match that of the extent.
If None, default to rc ``image.aspect`` value.
interpolation : string, optional, default: None
Acceptable values are 'none', 'nearest', 'bilinear', 'bicubic',
'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser',
'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc',
'lanczos'
If `interpolation` is None, default to rc `image.interpolation`.
See also the `filternorm` and `filterrad` parameters.
If `interpolation` is 'none', then no interpolation is performed
on the Agg, ps and pdf backends. Other backends will fall back to
'nearest'.
norm : `~matplotlib.colors.Normalize`, optional, default: None
A `~matplotlib.colors.Normalize` instance is used to scale
luminance data to 0, 1. If `None`, use the default
func:`normalize`. `norm` is only used if `X` is an array of
floats.
vmin, vmax : scalar, optional, default: None
`vmin` and `vmax` are used in conjunction with norm to normalize
luminance data. Note if you pass a `norm` instance, your
settings for `vmin` and `vmax` will be ignored.
alpha : scalar, optional, default: None
The alpha blending value, between 0 (transparent) and 1 (opaque)
origin : ['upper' | 'lower'], optional, default: None
Place the [0,0] index of the array in the upper left or lower left
corner of the axes. If None, default to rc `image.origin`.
extent : scalars (left, right, bottom, top), optional, default: None
Data limits for the axes. The default assigns zero-based row,
column indices to the `x`, `y` centers of the pixels.
shape : scalars (columns, rows), optional, default: None
For raw buffer images
filternorm : scalar, optional, default: 1
A parameter for the antigrain image resize filter. From the
antigrain documentation, if `filternorm` = 1, the filter
normalizes integer values and corrects the rounding errors. It
doesn't do anything with the source floating point values, it
corrects only integers according to the rule of 1.0 which means
that any sum of pixel weights must be equal to 1.0. So, the
filter function must produce a graph of the proper shape.
filterrad : scalar, optional, default: 4.0
The filter radius for filters that have a radius parameter, i.e.
when interpolation is one of: 'sinc', 'lanczos' or 'blackman'
Returns
--------
image : `~matplotlib.image.AxesImage`
Other parameters
----------------
kwargs : `~matplotlib.artist.Artist` properties.
See also
--------
matshow : Plot a matrix or an array as an image.
Examples
--------
.. plot:: mpl_examples/pylab_examples/image_demo.py
"""
if not self._hold:
self.cla()
if norm is not None:
assert(isinstance(norm, mcolors.Normalize))
if aspect is None:
aspect = rcParams['image.aspect']
self.set_aspect(aspect)
im = mimage.AxesImage(self, cmap, norm, interpolation, origin, extent,
filternorm=filternorm,
filterrad=filterrad, resample=resample, **kwargs)
im.set_data(X)
im.set_alpha(alpha)
self._set_artist_props(im)
if im.get_clip_path() is None:
# image does not already have clipping set, clip to axes patch
im.set_clip_path(self.patch)
#if norm is None and shape is None:
# im.set_clim(vmin, vmax)
if vmin is not None or vmax is not None:
im.set_clim(vmin, vmax)
else:
im.autoscale_None()
im.set_url(url)
# update ax.dataLim, and, if autoscaling, set viewLim
# to tightly fit the image, regardless of dataLim.
im.set_extent(im.get_extent())
self.images.append(im)
im._remove_method = lambda h: self.images.remove(h)
return im
@staticmethod
def _pcolorargs(funcname, *args, **kw):
# This takes one kwarg, allmatch.
# If allmatch is True, then the incoming X, Y, C must
# have matching dimensions, taking into account that
# X and Y can be 1-D rather than 2-D. This perfect
# match is required for Gouroud shading. For flat
# shading, X and Y specify boundaries, so we need
# one more boundary than color in each direction.
# For convenience, and consistent with Matlab, we
# discard the last row and/or column of C if necessary
# to meet this condition. This is done if allmatch
# is False.
allmatch = kw.pop("allmatch", False)
if len(args) == 1:
C = args[0]
numRows, numCols = C.shape
if allmatch:
X, Y = np.meshgrid(np.arange(numCols), np.arange(numRows))
else:
X, Y = np.meshgrid(np.arange(numCols + 1),
np.arange(numRows + 1))
return X, Y, C
if len(args) == 3:
X, Y, C = args
numRows, numCols = C.shape
else:
raise TypeError(
'Illegal arguments to %s; see help(%s)' % (funcname, funcname))
Nx = X.shape[-1]
Ny = Y.shape[0]
if len(X.shape) != 2 or X.shape[0] == 1:
x = X.reshape(1, Nx)
X = x.repeat(Ny, axis=0)
if len(Y.shape) != 2 or Y.shape[1] == 1:
y = Y.reshape(Ny, 1)
Y = y.repeat(Nx, axis=1)
if X.shape != Y.shape:
raise TypeError(
'Incompatible X, Y inputs to %s; see help(%s)' % (
funcname, funcname))
if allmatch:
if not (Nx == numCols and Ny == numRows):
raise TypeError('Dimensions of C %s are incompatible with'
' X (%d) and/or Y (%d); see help(%s)' % (
C.shape, Nx, Ny, funcname))
else:
if not (numCols in (Nx, Nx-1) and numRows in (Ny, Ny-1)):
raise TypeError('Dimensions of C %s are incompatible with'
' X (%d) and/or Y (%d); see help(%s)' % (
C.shape, Nx, Ny, funcname))
C = C[:Ny-1, :Nx-1]
return X, Y, C
@docstring.dedent_interpd
def pcolor(self, *args, **kwargs):
"""
Create a pseudocolor plot of a 2-D array.
.. note::
pcolor can be very slow for large arrays; consider
using the similar but much faster
:func:`~matplotlib.pyplot.pcolormesh` instead.
Call signatures::
pcolor(C, **kwargs)
pcolor(X, Y, C, **kwargs)
*C* is the array of color values.
*X* and *Y*, if given, specify the (*x*, *y*) coordinates of
the colored quadrilaterals; the quadrilateral for C[i,j] has
corners at::
(X[i, j], Y[i, j]),
(X[i, j+1], Y[i, j+1]),
(X[i+1, j], Y[i+1, j]),
(X[i+1, j+1], Y[i+1, j+1]).
Ideally the dimensions of *X* and *Y* should be one greater
than those of *C*; if the dimensions are the same, then the
last row and column of *C* will be ignored.
Note that the the column index corresponds to the
*x*-coordinate, and the row index corresponds to *y*; for
details, see the :ref:`Grid Orientation
<axes-pcolor-grid-orientation>` section below.
If either or both of *X* and *Y* are 1-D arrays or column vectors,
they will be expanded as needed into the appropriate 2-D arrays,
making a rectangular grid.
*X*, *Y* and *C* may be masked arrays. If either C[i, j], or one
of the vertices surrounding C[i,j] (*X* or *Y* at [i, j], [i+1, j],
[i, j+1],[i+1, j+1]) is masked, nothing is plotted.
Keyword arguments:
*cmap*: [ *None* | Colormap ]
A :class:`matplotlib.colors.Colormap` instance. If *None*, use
rc settings.
*norm*: [ *None* | Normalize ]
An :class:`matplotlib.colors.Normalize` instance is used
to scale luminance data to 0,1. If *None*, defaults to
:func:`normalize`.
*vmin*/*vmax*: [ *None* | scalar ]
*vmin* and *vmax* are used in conjunction with *norm* to
normalize luminance data. If either is *None*, it
is autoscaled to the respective min or max
of the color array *C*. If not *None*, *vmin* or
*vmax* passed in here override any pre-existing values
supplied in the *norm* instance.
*shading*: [ 'flat' | 'faceted' ]
If 'faceted', a black grid is drawn around each rectangle; if
'flat', edges are not drawn. Default is 'flat', contrary to
MATLAB.
This kwarg is deprecated; please use 'edgecolors' instead:
* shading='flat' -- edgecolors='none'
* shading='faceted -- edgecolors='k'
*edgecolors*: [ *None* | ``'none'`` | color | color sequence]
If *None*, the rc setting is used by default.
If ``'none'``, edges will not be visible.
An mpl color or sequence of colors will set the edge color
*alpha*: ``0 <= scalar <= 1`` or *None*
the alpha blending value
Return value is a :class:`matplotlib.collections.Collection`
instance.
.. _axes-pcolor-grid-orientation:
The grid orientation follows the MATLAB convention: an
array *C* with shape (*nrows*, *ncolumns*) is plotted with
the column number as *X* and the row number as *Y*, increasing
up; hence it is plotted the way the array would be printed,
except that the *Y* axis is reversed. That is, *C* is taken
as *C*(*y*, *x*).
Similarly for :func:`meshgrid`::
x = np.arange(5)
y = np.arange(3)
X, Y = np.meshgrid(x, y)
is equivalent to::
X = array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
Y = array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2]])
so if you have::
C = rand(len(x), len(y))
then you need to transpose C::
pcolor(X, Y, C.T)
or::
pcolor(C.T)
MATLAB :func:`pcolor` always discards the last row and column
of *C*, but matplotlib displays the last row and column if *X* and
*Y* are not specified, or if *X* and *Y* have one more row and
column than *C*.
kwargs can be used to control the
:class:`~matplotlib.collections.PolyCollection` properties:
%(PolyCollection)s
.. note::
The default *antialiaseds* is False if the default
*edgecolors*="none" is used. This eliminates artificial lines
at patch boundaries, and works regardless of the value of
alpha. If *edgecolors* is not "none", then the default
*antialiaseds* is taken from
rcParams['patch.antialiased'], which defaults to *True*.
Stroking the edges may be preferred if *alpha* is 1, but
will cause artifacts otherwise.
.. seealso::
:func:`~matplotlib.pyplot.pcolormesh`
For an explanation of the differences between
pcolor and pcolormesh.
"""
if not self._hold:
self.cla()
alpha = kwargs.pop('alpha', None)
norm = kwargs.pop('norm', None)
cmap = kwargs.pop('cmap', None)
vmin = kwargs.pop('vmin', None)
vmax = kwargs.pop('vmax', None)
if 'shading' in kwargs:
cbook.warn_deprecated(
'1.2', name='shading', alternative='edgecolors',
obj_type='option')
shading = kwargs.pop('shading', 'flat')
X, Y, C = self._pcolorargs('pcolor', *args, allmatch=False)
Ny, Nx = X.shape
# convert to MA, if necessary.
C = ma.asarray(C)
X = ma.asarray(X)
Y = ma.asarray(Y)
mask = ma.getmaskarray(X) + ma.getmaskarray(Y)
xymask = (mask[0:-1, 0:-1] + mask[1:, 1:] +
mask[0:-1, 1:] + mask[1:, 0:-1])
# don't plot if C or any of the surrounding vertices are masked.
mask = ma.getmaskarray(C) + xymask
newaxis = np.newaxis
compress = np.compress
ravelmask = (mask == 0).ravel()
X1 = compress(ravelmask, ma.filled(X[0:-1, 0:-1]).ravel())
Y1 = compress(ravelmask, ma.filled(Y[0:-1, 0:-1]).ravel())
X2 = compress(ravelmask, ma.filled(X[1:, 0:-1]).ravel())
Y2 = compress(ravelmask, ma.filled(Y[1:, 0:-1]).ravel())
X3 = compress(ravelmask, ma.filled(X[1:, 1:]).ravel())
Y3 = compress(ravelmask, ma.filled(Y[1:, 1:]).ravel())
X4 = compress(ravelmask, ma.filled(X[0:-1, 1:]).ravel())
Y4 = compress(ravelmask, ma.filled(Y[0:-1, 1:]).ravel())
npoly = len(X1)
xy = np.concatenate((X1[:, newaxis], Y1[:, newaxis],
X2[:, newaxis], Y2[:, newaxis],
X3[:, newaxis], Y3[:, newaxis],
X4[:, newaxis], Y4[:, newaxis],
X1[:, newaxis], Y1[:, newaxis]),
axis=1)
verts = xy.reshape((npoly, 5, 2))
C = compress(ravelmask, ma.filled(C[0:Ny - 1, 0:Nx - 1]).ravel())
linewidths = (0.25,)
if 'linewidth' in kwargs:
kwargs['linewidths'] = kwargs.pop('linewidth')
kwargs.setdefault('linewidths', linewidths)
if shading == 'faceted':
edgecolors = 'k',
else:
edgecolors = 'none'
if 'edgecolor' in kwargs:
kwargs['edgecolors'] = kwargs.pop('edgecolor')
ec = kwargs.setdefault('edgecolors', edgecolors)
# aa setting will default via collections to patch.antialiased
# unless the boundary is not stroked, in which case the
# default will be False; with unstroked boundaries, aa
# makes artifacts that are often disturbing.
if 'antialiased' in kwargs:
kwargs['antialiaseds'] = kwargs.pop('antialiased')
if 'antialiaseds' not in kwargs and (is_string_like(ec) and
ec.lower() == "none"):
kwargs['antialiaseds'] = False
collection = mcoll.PolyCollection(verts, **kwargs)
collection.set_alpha(alpha)
collection.set_array(C)
if norm is not None:
assert(isinstance(norm, mcolors.Normalize))
collection.set_cmap(cmap)
collection.set_norm(norm)
collection.set_clim(vmin, vmax)
collection.autoscale_None()
self.grid(False)
x = X.compressed()
y = Y.compressed()
# Transform from native to data coordinates?
t = collection._transform
if (not isinstance(t, mtransforms.Transform)
and hasattr(t, '_as_mpl_transform')):
t = t._as_mpl_transform(self.axes)
if t and any(t.contains_branch_seperately(self.transData)):
trans_to_data = t - self.transData
pts = np.vstack([x, y]).T.astype(np.float)
transformed_pts = trans_to_data.transform(pts)
x = transformed_pts[..., 0]
y = transformed_pts[..., 1]
minx = np.amin(x)
maxx = np.amax(x)
miny = np.amin(y)
maxy = np.amax(y)
corners = (minx, miny), (maxx, maxy)
self.update_datalim(corners)
self.autoscale_view()
self.add_collection(collection)
return collection
@docstring.dedent_interpd
def pcolormesh(self, *args, **kwargs):
"""
Plot a quadrilateral mesh.
Call signatures::
pcolormesh(C)
pcolormesh(X, Y, C)
pcolormesh(C, **kwargs)
Create a pseudocolor plot of a 2-D array.
pcolormesh is similar to :func:`~matplotlib.pyplot.pcolor`,
but uses a different mechanism and returns a different
object; pcolor returns a
:class:`~matplotlib.collections.PolyCollection` but pcolormesh
returns a
:class:`~matplotlib.collections.QuadMesh`. It is much faster,
so it is almost always preferred for large arrays.
*C* may be a masked array, but *X* and *Y* may not. Masked
array support is implemented via *cmap* and *norm*; in
contrast, :func:`~matplotlib.pyplot.pcolor` simply does not
draw quadrilaterals with masked colors or vertices.
Keyword arguments:
*cmap*: [ *None* | Colormap ]
A :class:`matplotlib.colors.Colormap` instance. If *None*, use
rc settings.
*norm*: [ *None* | Normalize ]
A :class:`matplotlib.colors.Normalize` instance is used to
scale luminance data to 0,1. If *None*, defaults to
:func:`normalize`.
*vmin*/*vmax*: [ *None* | scalar ]
*vmin* and *vmax* are used in conjunction with *norm* to
normalize luminance data. If either is *None*, it
is autoscaled to the respective min or max
of the color array *C*. If not *None*, *vmin* or
*vmax* passed in here override any pre-existing values
supplied in the *norm* instance.
*shading*: [ 'flat' | 'gouraud' ]
'flat' indicates a solid color for each quad. When
'gouraud', each quad will be Gouraud shaded. When gouraud
shading, edgecolors is ignored.
*edgecolors*: [*None* | ``'None'`` | ``'face'`` | color |
color sequence]
If *None*, the rc setting is used by default.
If ``'None'``, edges will not be visible.
If ``'face'``, edges will have the same color as the faces.
An mpl color or sequence of colors will set the edge color
*alpha*: ``0 <= scalar <= 1`` or *None*
the alpha blending value
Return value is a :class:`matplotlib.collections.QuadMesh`
object.
kwargs can be used to control the
:class:`matplotlib.collections.QuadMesh` properties:
%(QuadMesh)s
.. seealso::
:func:`~matplotlib.pyplot.pcolor`
For an explanation of the grid orientation and the
expansion of 1-D *X* and/or *Y* to 2-D arrays.
"""
if not self._hold:
self.cla()
alpha = kwargs.pop('alpha', None)
norm = kwargs.pop('norm', None)
cmap = kwargs.pop('cmap', None)
vmin = kwargs.pop('vmin', None)
vmax = kwargs.pop('vmax', None)
shading = kwargs.pop('shading', 'flat').lower()
antialiased = kwargs.pop('antialiased', False)
kwargs.setdefault('edgecolors', 'None')
allmatch = (shading == 'gouraud')
X, Y, C = self._pcolorargs('pcolormesh', *args, allmatch=allmatch)
Ny, Nx = X.shape
# convert to one dimensional arrays
C = C.ravel()
X = X.ravel()
Y = Y.ravel()
coords = np.zeros(((Nx * Ny), 2), dtype=float)
coords[:, 0] = X
coords[:, 1] = Y
collection = mcoll.QuadMesh(
Nx - 1, Ny - 1, coords,
antialiased=antialiased, shading=shading, **kwargs)
collection.set_alpha(alpha)
collection.set_array(C)
if norm is not None:
assert(isinstance(norm, mcolors.Normalize))
collection.set_cmap(cmap)
collection.set_norm(norm)
collection.set_clim(vmin, vmax)
collection.autoscale_None()
self.grid(False)
# Transform from native to data coordinates?
t = collection._transform
if (not isinstance(t, mtransforms.Transform)
and hasattr(t, '_as_mpl_transform')):
t = t._as_mpl_transform(self.axes)
if t and any(t.contains_branch_seperately(self.transData)):
trans_to_data = t - self.transData
pts = np.vstack([X, Y]).T.astype(np.float)
transformed_pts = trans_to_data.transform(pts)
X = transformed_pts[..., 0]
Y = transformed_pts[..., 1]
minx = np.amin(X)
maxx = np.amax(X)
miny = np.amin(Y)
maxy = np.amax(Y)
corners = (minx, miny), (maxx, maxy)
self.update_datalim(corners)
self.autoscale_view()
self.add_collection(collection)
return collection
@docstring.dedent_interpd
def pcolorfast(self, *args, **kwargs):
"""
pseudocolor plot of a 2-D array
Experimental; this is a pcolor-type method that
provides the fastest possible rendering with the Agg
backend, and that can handle any quadrilateral grid.
It supports only flat shading (no outlines), it lacks
support for log scaling of the axes, and it does not
have a pyplot wrapper.
Call signatures::
ax.pcolorfast(C, **kwargs)
ax.pcolorfast(xr, yr, C, **kwargs)
ax.pcolorfast(x, y, C, **kwargs)
ax.pcolorfast(X, Y, C, **kwargs)
C is the 2D array of color values corresponding to quadrilateral
cells. Let (nr, nc) be its shape. C may be a masked array.
``ax.pcolorfast(C, **kwargs)`` is equivalent to
``ax.pcolorfast([0,nc], [0,nr], C, **kwargs)``
*xr*, *yr* specify the ranges of *x* and *y* corresponding to the
rectangular region bounding *C*. If::
xr = [x0, x1]
and::
yr = [y0,y1]
then *x* goes from *x0* to *x1* as the second index of *C* goes
from 0 to *nc*, etc. (*x0*, *y0*) is the outermost corner of
cell (0,0), and (*x1*, *y1*) is the outermost corner of cell
(*nr*-1, *nc*-1). All cells are rectangles of the same size.
This is the fastest version.
*x*, *y* are 1D arrays of length *nc* +1 and *nr* +1, respectively,
giving the x and y boundaries of the cells. Hence the cells are
rectangular but the grid may be nonuniform. The speed is
intermediate. (The grid is checked, and if found to be
uniform the fast version is used.)
*X* and *Y* are 2D arrays with shape (*nr* +1, *nc* +1) that specify
the (x,y) coordinates of the corners of the colored
quadrilaterals; the quadrilateral for C[i,j] has corners at
(X[i,j],Y[i,j]), (X[i,j+1],Y[i,j+1]), (X[i+1,j],Y[i+1,j]),
(X[i+1,j+1],Y[i+1,j+1]). The cells need not be rectangular.
This is the most general, but the slowest to render. It may
produce faster and more compact output using ps, pdf, and
svg backends, however.
Note that the the column index corresponds to the x-coordinate,
and the row index corresponds to y; for details, see
the "Grid Orientation" section below.
Optional keyword arguments:
*cmap*: [ *None* | Colormap ]
A :class:`matplotlib.colors.Colormap` instance from cm. If *None*,
use rc settings.
*norm*: [ *None* | Normalize ]
A :class:`matplotlib.colors.Normalize` instance is used to scale
luminance data to 0,1. If *None*, defaults to normalize()
*vmin*/*vmax*: [ *None* | scalar ]
*vmin* and *vmax* are used in conjunction with norm to normalize
luminance data. If either are *None*, the min and max
of the color array *C* is used. If you pass a norm instance,
*vmin* and *vmax* will be *None*.
*alpha*: ``0 <= scalar <= 1`` or *None*
the alpha blending value
Return value is an image if a regular or rectangular grid
is specified, and a :class:`~matplotlib.collections.QuadMesh`
collection in the general quadrilateral case.
"""
if not self._hold:
self.cla()
alpha = kwargs.pop('alpha', None)
norm = kwargs.pop('norm', None)
cmap = kwargs.pop('cmap', None)
vmin = kwargs.pop('vmin', None)
vmax = kwargs.pop('vmax', None)
if norm is not None:
assert(isinstance(norm, mcolors.Normalize))
C = args[-1]
nr, nc = C.shape
if len(args) == 1:
style = "image"
x = [0, nc]
y = [0, nr]
elif len(args) == 3:
x, y = args[:2]
x = np.asarray(x)
y = np.asarray(y)
if x.ndim == 1 and y.ndim == 1:
if x.size == 2 and y.size == 2:
style = "image"
else:
dx = np.diff(x)
dy = np.diff(y)
if (np.ptp(dx) < 0.01 * np.abs(dx.mean()) and
np.ptp(dy) < 0.01 * np.abs(dy.mean())):
style = "image"
else:
style = "pcolorimage"
elif x.ndim == 2 and y.ndim == 2:
style = "quadmesh"
else:
raise TypeError("arguments do not match valid signatures")
else:
raise TypeError("need 1 argument or 3 arguments")
if style == "quadmesh":
# convert to one dimensional arrays
# This should also be moved to the QuadMesh class
C = ma.ravel(C) # data point in each cell is value
# at lower left corner
X = x.ravel()
Y = y.ravel()
Nx = nc + 1
Ny = nr + 1
# The following needs to be cleaned up; the renderer
# requires separate contiguous arrays for X and Y,
# but the QuadMesh class requires the 2D array.
coords = np.empty(((Nx * Ny), 2), np.float64)
coords[:, 0] = X
coords[:, 1] = Y
# The QuadMesh class can also be changed to
# handle relevant superclass kwargs; the initializer
# should do much more than it does now.
collection = mcoll.QuadMesh(nc, nr, coords, 0, edgecolors="None")
collection.set_alpha(alpha)
collection.set_array(C)
collection.set_cmap(cmap)
collection.set_norm(norm)
self.add_collection(collection)
xl, xr, yb, yt = X.min(), X.max(), Y.min(), Y.max()
ret = collection
else:
# One of the image styles:
xl, xr, yb, yt = x[0], x[-1], y[0], y[-1]
if style == "image":
im = mimage.AxesImage(self, cmap, norm,
interpolation='nearest',
origin='lower',
extent=(xl, xr, yb, yt),
**kwargs)
im.set_data(C)
im.set_alpha(alpha)
self.images.append(im)
ret = im
if style == "pcolorimage":
im = mimage.PcolorImage(self, x, y, C,
cmap=cmap,
norm=norm,
alpha=alpha,
**kwargs)
self.images.append(im)
ret = im
self._set_artist_props(ret)
if vmin is not None or vmax is not None:
ret.set_clim(vmin, vmax)
else:
ret.autoscale_None()
self.update_datalim(np.array([[xl, yb], [xr, yt]]))
self.autoscale_view(tight=True)
return ret
def contour(self, *args, **kwargs):
if not self._hold:
self.cla()
kwargs['filled'] = False
return mcontour.QuadContourSet(self, *args, **kwargs)
contour.__doc__ = mcontour.QuadContourSet.contour_doc
def contourf(self, *args, **kwargs):
if not self._hold:
self.cla()
kwargs['filled'] = True
return mcontour.QuadContourSet(self, *args, **kwargs)
contourf.__doc__ = mcontour.QuadContourSet.contour_doc
def clabel(self, CS, *args, **kwargs):
return CS.clabel(*args, **kwargs)
clabel.__doc__ = mcontour.ContourSet.clabel.__doc__
@docstring.dedent_interpd
def table(self, **kwargs):
"""
Add a table to the current axes.
Call signature::
table(cellText=None, cellColours=None,
cellLoc='right', colWidths=None,
rowLabels=None, rowColours=None, rowLoc='left',
colLabels=None, colColours=None, colLoc='center',
loc='bottom', bbox=None):
Returns a :class:`matplotlib.table.Table` instance. For finer
grained control over tables, use the
:class:`~matplotlib.table.Table` class and add it to the axes
with :meth:`~matplotlib.axes.Axes.add_table`.
Thanks to John Gill for providing the class and table.
kwargs control the :class:`~matplotlib.table.Table`
properties:
%(Table)s
"""
return mtable.table(self, **kwargs)
def _make_twin_axes(self, *kl, **kwargs):
"""
make a twinx axes of self. This is used for twinx and twiny.
"""
ax2 = self.figure.add_axes(self.get_position(True), *kl, **kwargs)
return ax2
def twinx(self):
"""
Call signature::
ax = twinx()
create a twin of Axes for generating a plot with a sharex
x-axis but independent y axis. The y-axis of self will have
ticks on left and the returned axes will have ticks on the
right.
.. note::
For those who are 'picking' artists while using twinx, pick
events are only called for the artists in the top-most axes.
"""
ax2 = self._make_twin_axes(sharex=self, frameon=False)
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position('right')
ax2.yaxis.set_offset_position('right')
self.yaxis.tick_left()
ax2.xaxis.set_visible(False)
return ax2
def twiny(self):
"""
Call signature::
ax = twiny()
create a twin of Axes for generating a plot with a shared
y-axis but independent x axis. The x-axis of self will have
ticks on bottom and the returned axes will have ticks on the
top.
.. note::
For those who are 'picking' artists while using twiny, pick
events are only called for the artists in the top-most axes.
"""
ax2 = self._make_twin_axes(sharey=self, frameon=False)
ax2.xaxis.tick_top()
ax2.xaxis.set_label_position('top')
self.xaxis.tick_bottom()
ax2.yaxis.set_visible(False)
return ax2
def get_shared_x_axes(self):
'Return a copy of the shared axes Grouper object for x axes'
return self._shared_x_axes
def get_shared_y_axes(self):
'Return a copy of the shared axes Grouper object for y axes'
return self._shared_y_axes
#### Data analysis
@docstring.dedent_interpd
def hist(self, x, bins=10, range=None, normed=False, weights=None,
cumulative=False, bottom=None, histtype='bar', align='mid',
orientation='vertical', rwidth=None, log=False,
color=None, label=None, stacked=False,
**kwargs):
"""
Plot a histogram.
Compute and draw the histogram of *x*. The return value is a
tuple (*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*,
[*patches0*, *patches1*,...]) if the input contains multiple
data.
Multiple data can be provided via *x* as a list of datasets
of potentially different length ([*x0*, *x1*, ...]), or as
a 2-D ndarray in which each column is a dataset. Note that
the ndarray form is transposed relative to the list form.
Masked arrays are not supported at present.
Parameters
----------
x : array_like, shape (n, )
Input values.
bins : integer or array_like, optional, default: 10
If an integer is given, `bins + 1` bin edges are returned,
consistently with :func:`numpy.histogram` for numpy version >=
1.3.
Unequally spaced bins are supported if `bins` is a sequence.
range : tuple, optional, default: None
The lower and upper range of the bins. Lower and upper outliers
are ignored. If not provided, `range` is (x.min(), x.max()). Range
has no effect if `bins` is a sequence.
If `bins` is a sequence or `range` is specified, autoscaling
is based on the specified bin range instead of the
range of x.
normed : boolean, optional, default: False
If `True`, the first element of the return tuple will
be the counts normalized to form a probability density, i.e.,
``n/(len(x)`dbin)``, ie the integral of the histogram will sum to
1. If *stacked* is also *True*, the sum of the histograms is
normalized to 1.
weights : array_like, shape (n, ), optional, default: None
An array of weights, of the same shape as `x`. Each value in `x`
only contributes its associated weight towards the bin count
(instead of 1). If `normed` is True, the weights are normalized,
so that the integral of the density over the range remains 1.
cumulative : boolean, optional, default : True
If `True`, then a histogram is computed where each bin gives the
counts in that bin plus all bins for smaller values. The last bin
gives the total number of datapoints. If `normed` is also `True`
then the histogram is normalized such that the last bin equals 1.
If `cumulative` evaluates to less than 0 (e.g., -1), the direction
of accumulation is reversed. In this case, if `normed` is also
`True`, then the histogram is normalized such that the first bin
equals 1.
histtype : ['bar' | 'barstacked' | 'step' | 'stepfilled'], optional
The type of histogram to draw.
- 'bar' is a traditional bar-type histogram. If multiple data
are given the bars are aranged side by side.
- 'barstacked' is a bar-type histogram where multiple
data are stacked on top of each other.
- 'step' generates a lineplot that is by default
unfilled.
- 'stepfilled' generates a lineplot that is by default
filled.
align : ['left' | 'mid' | 'right'], optional, default: 'mid'
Controls how the histogram is plotted.
- 'left': bars are centered on the left bin edges.
- 'mid': bars are centered between the bin edges.
- 'right': bars are centered on the right bin edges.
orientation : ['horizontal' | 'vertical'], optional
If 'horizontal', `~matplotlib.pyplot.barh` will be used for
bar-type histograms and the *bottom* kwarg will be the left edges.
rwidth : scalar, optional, default: None
The relative width of the bars as a fraction of the bin width. If
`None`, automatically compute the width. Ignored if `histtype` =
'step' or 'stepfilled'.
log : boolean, optional, default : False
If `True`, the histogram axis will be set to a log scale. If `log`
is `True` and `x` is a 1D array, empty bins will be filtered out
and only the non-empty (`n`, `bins`, `patches`) will be returned.
color : color or array_like of colors, optional, default: None
Color spec or sequence of color specs, one per dataset. Default
(`None`) uses the standard line color sequence.
label : string, optional, default: ''
String, or sequence of strings to match multiple datasets. Bar
charts yield multiple patches per dataset, but only the first gets
the label, so that the legend command will work as expected.
stacked : boolean, optional, default : False
If `True`, multiple data are stacked on top of each other If
`False` multiple data are aranged side by side if histtype is
'bar' or on top of each other if histtype is 'step'
Returns
-------
tuple : (n, bins, patches) or ([n0, n1, ...], bins, [patches0, patches1,...])
Other Parameters
----------------
kwargs : `~matplotlib.patches.Patch` properties
See also
--------
hist2d : 2D histograms
Notes
-----
Until numpy release 1.5, the underlying numpy histogram function was
incorrect with `normed`=`True` if bin sizes were unequal. MPL
inherited that error. It is now corrected within MPL when using
earlier numpy versions.
Examples
--------
.. plot:: mpl_examples/statistics/histogram_demo_features.py
"""
if not self._hold:
self.cla()
# xrange becomes range after 2to3
bin_range = range
range = __builtins__["range"]
# NOTE: the range keyword overwrites the built-in func range !!!
# needs to be fixed in numpy !!!
# Validate string inputs here so we don't have to clutter
# subsequent code.
if histtype not in ['bar', 'barstacked', 'step', 'stepfilled']:
raise ValueError("histtype %s is not recognized" % histtype)
if align not in ['left', 'mid', 'right']:
raise ValueError("align kwarg %s is not recognized" % align)
if orientation not in ['horizontal', 'vertical']:
raise ValueError(
"orientation kwarg %s is not recognized" % orientation)
if histtype == 'barstacked' and not stacked:
stacked = True
# Massage 'x' for processing.
# NOTE: Be sure any changes here is also done below to 'weights'
if isinstance(x, np.ndarray) or not iterable(x[0]):
# TODO: support masked arrays;
x = np.asarray(x)
if x.ndim == 2:
x = x.T # 2-D input with columns as datasets; switch to rows
elif x.ndim == 1:
x = x.reshape(1, x.shape[0]) # new view, single row
else:
raise ValueError("x must be 1D or 2D")
if x.shape[1] < x.shape[0]:
warnings.warn(
'2D hist input should be nsamples x nvariables;\n '
'this looks transposed (shape is %d x %d)' % x.shape[::-1])
else:
# multiple hist with data of different length
x = [np.asarray(xi) for xi in x]
nx = len(x) # number of datasets
if color is None:
color = [self._get_lines.color_cycle.next()
for i in xrange(nx)]
else:
color = mcolors.colorConverter.to_rgba_array(color)
if len(color) != nx:
raise ValueError("color kwarg must have one color per dataset")
# We need to do to 'weights' what was done to 'x'
if weights is not None:
if isinstance(weights, np.ndarray) or not iterable(weights[0]):
w = np.array(weights)
if w.ndim == 2:
w = w.T
elif w.ndim == 1:
w.shape = (1, w.shape[0])
else:
raise ValueError("weights must be 1D or 2D")
else:
w = [np.asarray(wi) for wi in weights]
if len(w) != nx:
raise ValueError('weights should have the same shape as x')
for i in xrange(nx):
if len(w[i]) != len(x[i]):
raise ValueError(
'weights should have the same shape as x')
else:
w = [None]*nx
# Save the datalimits for the same reason:
_saved_bounds = self.dataLim.bounds
# Check whether bins or range are given explicitly. In that
# case use those values for autoscaling.
binsgiven = (cbook.iterable(bins) or bin_range is not None)
# If bins are not specified either explicitly or via range,
# we need to figure out the range required for all datasets,
# and supply that to np.histogram.
if not binsgiven:
xmin = np.inf
xmax = -np.inf
for xi in x:
xmin = min(xmin, xi.min())
xmax = max(xmax, xi.max())
bin_range = (xmin, xmax)
#hist_kwargs = dict(range=range, normed=bool(normed))
# We will handle the normed kwarg within mpl until we
# get to the point of requiring numpy >= 1.5.
hist_kwargs = dict(range=bin_range)
n = []
mlast = bottom
for i in xrange(nx):
# this will automatically overwrite bins,
# so that each histogram uses the same bins
m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)
m = m.astype(float) # causes problems later if it's an int
if mlast is None:
mlast = np.zeros(len(bins)-1, m.dtype)
if normed and not stacked:
db = np.diff(bins)
m = (m.astype(float) / db) / m.sum()
if stacked:
m += mlast
mlast[:] = m
n.append(m)
if stacked and normed:
db = np.diff(bins)
for m in n:
m[:] = (m.astype(float) / db) / n[-1].sum()
if cumulative:
slc = slice(None)
if cbook.is_numlike(cumulative) and cumulative < 0:
slc = slice(None, None, -1)
if normed:
n = [(m * np.diff(bins))[slc].cumsum()[slc] for m in n]
else:
n = [m[slc].cumsum()[slc] for m in n]
patches = []
if histtype.startswith('bar'):
# Save autoscale state for later restoration; turn autoscaling
# off so we can do it all a single time at the end, instead
# of having it done by bar or fill and then having to be redone.
_saved_autoscalex = self.get_autoscalex_on()
_saved_autoscaley = self.get_autoscaley_on()
self.set_autoscalex_on(False)
self.set_autoscaley_on(False)
totwidth = np.diff(bins)
if rwidth is not None:
dr = min(1.0, max(0.0, rwidth))
elif len(n) > 1:
dr = 0.8
else:
dr = 1.0
if histtype == 'bar' and not stacked:
width = dr*totwidth/nx
dw = width
if nx > 1:
boffset = -0.5*dr*totwidth*(1.0-1.0/nx)
else:
boffset = 0.0
stacked = False
elif histtype == 'barstacked' or stacked:
width = dr*totwidth
boffset, dw = 0.0, 0.0
if align == 'mid' or align == 'edge':
boffset += 0.5*totwidth
elif align == 'right':
boffset += totwidth
if orientation == 'horizontal':
_barfunc = self.barh
bottom_kwarg = 'left'
else: # orientation == 'vertical'
_barfunc = self.bar
bottom_kwarg = 'bottom'
for m, c in zip(n, color):
if bottom is None:
bottom = np.zeros(len(m), np.float)
if stacked:
height = m - bottom
else:
height = m
patch = _barfunc(bins[:-1]+boffset, height, width,
align='center', log=log,
color=c, **{bottom_kwarg: bottom})
patches.append(patch)
if stacked:
bottom[:] = m
boffset += dw
self.set_autoscalex_on(_saved_autoscalex)
self.set_autoscaley_on(_saved_autoscaley)
self.autoscale_view()
elif histtype.startswith('step'):
# these define the perimeter of the polygon
x = np.zeros(4 * len(bins) - 3, np.float)
y = np.zeros(4 * len(bins) - 3, np.float)
x[0:2*len(bins)-1:2], x[1:2*len(bins)-1:2] = bins, bins[:-1]
x[2*len(bins)-1:] = x[1:2*len(bins)-1][::-1]
if log:
if orientation == 'horizontal':
self.set_xscale('log', nonposx='clip')
logbase = self.xaxis._scale.base
else: # orientation == 'vertical'
self.set_yscale('log', nonposy='clip')
logbase = self.yaxis._scale.base
# Setting a minimum of 0 results in problems for log plots
if normed:
# For normed data, set to log base * minimum data value
# (gives 1 full tick-label unit for the lowest filled bin)
ndata = np.array(n)
minimum = (np.min(ndata[ndata > 0])) / logbase
else:
# For non-normed data, set the min to log base,
# again so that there is 1 full tick-label unit
# for the lowest bin
minimum = 1.0 / logbase
y[0], y[-1] = minimum, minimum
else:
minimum = np.min(bins)
if align == 'left' or align == 'center':
x -= 0.5*(bins[1]-bins[0])
elif align == 'right':
x += 0.5*(bins[1]-bins[0])
# If fill kwarg is set, it will be passed to the patch collection,
# overriding this
fill = (histtype == 'stepfilled')
xvals, yvals = [], []
for m in n:
# starting point for drawing polygon
y[0] = y[1]
# top of the previous polygon becomes the bottom
y[2*len(bins)-1:] = y[1:2*len(bins)-1][::-1]
# set the top of this polygon
y[1:2*len(bins)-1:2], y[2:2*len(bins)-1:2] = m, m
if log:
y[y < minimum] = minimum
if orientation == 'horizontal':
x, y = y, x
xvals.append(x.copy())
yvals.append(y.copy())
if fill:
# add patches in reverse order so that when stacking,
# items lower in the stack are plottted on top of
# items higher in the stack
for x, y, c in reversed(zip(xvals, yvals, color)):
patches.append(self.fill(
x, y,
closed=True,
facecolor=c))
else:
for x, y, c in reversed(zip(xvals, yvals, color)):
split = 2 * len(bins)
patches.append(self.fill(
x[:split], y[:split],
closed=False, edgecolor=c,
fill=False))
# we return patches, so put it back in the expected order
patches.reverse()
# adopted from adjust_x/ylim part of the bar method
if orientation == 'horizontal':
xmin0 = max(_saved_bounds[0]*0.9, minimum)
xmax = self.dataLim.intervalx[1]
for m in n:
xmin = np.amin(m[m != 0]) # filter out the 0 height bins
xmin = max(xmin*0.9, minimum)
xmin = min(xmin0, xmin)
self.dataLim.intervalx = (xmin, xmax)
elif orientation == 'vertical':
ymin0 = max(_saved_bounds[1]*0.9, minimum)
ymax = self.dataLim.intervaly[1]
for m in n:
ymin = np.amin(m[m != 0]) # filter out the 0 height bins
ymin = max(ymin*0.9, minimum)
ymin = min(ymin0, ymin)
self.dataLim.intervaly = (ymin, ymax)
if label is None:
labels = [None]
elif is_string_like(label):
labels = [label]
elif is_sequence_of_strings(label):
labels = list(label)
else:
raise ValueError(
'invalid label: must be string or sequence of strings')
if len(labels) < nx:
labels += [None] * (nx - len(labels))
for (patch, lbl) in zip(patches, labels):
if patch:
p = patch[0]
p.update(kwargs)
if lbl is not None:
p.set_label(lbl)
p.set_snap(False)
for p in patch[1:]:
p.update(kwargs)
p.set_label('_nolegend_')
if binsgiven:
if orientation == 'vertical':
self.update_datalim(
[(bins[0], 0), (bins[-1], 0)], updatey=False)
else:
self.update_datalim(
[(0, bins[0]), (0, bins[-1])], updatex=False)
if nx == 1:
return n[0], bins, cbook.silent_list('Patch', patches[0])
else:
return n, bins, cbook.silent_list('Lists of Patches', patches)
@docstring.dedent_interpd
def hist2d(self, x, y, bins=10, range=None, normed=False, weights=None,
cmin=None, cmax=None, **kwargs):
"""
Make a 2D histogram plot.
Parameters
----------
x, y: array_like, shape (n, )
Input values
bins: [None | int | [int, int] | array_like | [array, array]]
The bin specification:
- If int, the number of bins for the two dimensions
(nx=ny=bins).
- If [int, int], the number of bins in each dimension
(nx, ny = bins).
- If array_like, the bin edges for the two dimensions
(x_edges=y_edges=bins).
- If [array, array], the bin edges in each dimension
(x_edges, y_edges = bins).
The default value is 10.
range : array_like shape(2, 2), optional, default: None
The leftmost and rightmost edges of the bins along each dimension
(if not specified explicitly in the bins parameters): [[xmin,
xmax], [ymin, ymax]]. All values outside of this range will be
considered outliers and not tallied in the histogram.
normed : boolean, optional, default: False
Normalize histogram.
weights : array_like, shape (n, ), optional, default: None
An array of values w_i weighing each sample (x_i, y_i).
cmin : scalar, optional, default: None
All bins that has count less than cmin will not be displayed and
these count values in the return value count histogram will also
be set to nan upon return
cmax : scalar, optional, default: None
All bins that has count more than cmax will not be displayed (set
to none before passing to imshow) and these count values in the
return value count histogram will also be set to nan upon return
Returns
-------
The return value is ``(counts, xedges, yedges, Image)``.
Other parameters
-----------------
kwargs : :meth:`pcolorfast` properties.
See also
--------
hist : 1D histogram
Notes
-----
Rendering the histogram with a logarithmic color scale is
accomplished by passing a :class:`colors.LogNorm` instance to
the *norm* keyword argument.
Examples
--------
.. plot:: mpl_examples/pylab_examples/hist2d_demo.py
"""
# xrange becomes range after 2to3
bin_range = range
range = __builtins__["range"]
h, xedges, yedges = np.histogram2d(x, y, bins=bins, range=bin_range,
normed=normed, weights=weights)
if cmin is not None:
h[h < cmin] = None
if cmax is not None:
h[h > cmax] = None
pc = self.pcolorfast(xedges, yedges, h.T, **kwargs)
self.set_xlim(xedges[0], xedges[-1])
self.set_ylim(yedges[0], yedges[-1])
return h, xedges, yedges, pc
@docstring.dedent_interpd
def psd(self, x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=0, pad_to=None,
sides='default', scale_by_freq=None, **kwargs):
"""
Plot the power spectral density.
Call signature::
psd(x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=0, pad_to=None,
sides='default', scale_by_freq=None, **kwargs)
The power spectral density by Welch's average periodogram
method. The vector *x* is divided into *NFFT* length
segments. Each segment is detrended by function *detrend* and
windowed by function *window*. *noverlap* gives the length of
the overlap between segments. The :math:`|\mathrm{fft}(i)|^2`
of each segment :math:`i` are averaged to compute *Pxx*, with a
scaling to correct for power loss due to windowing. *Fs* is the
sampling frequency.
%(PSD)s
*noverlap*: integer
The number of points of overlap between blocks. The default value
is 0 (no overlap).
*Fc*: integer
The center frequency of *x* (defaults to 0), which offsets
the x extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered and downsampled to
baseband.
Returns the tuple (*Pxx*, *freqs*).
For plotting, the power is plotted as
:math:`10\log_{10}(P_{xx})` for decibels, though *Pxx* itself
is returned.
References:
Bendat & Piersol -- Random Data: Analysis and Measurement
Procedures, John Wiley & Sons (1986)
kwargs control the :class:`~matplotlib.lines.Line2D` properties:
%(Line2D)s
**Example:**
.. plot:: mpl_examples/pylab_examples/psd_demo.py
"""
if not self._hold:
self.cla()
pxx, freqs = mlab.psd(x, NFFT, Fs, detrend, window, noverlap, pad_to,
sides, scale_by_freq)
pxx.shape = len(freqs),
freqs += Fc
if scale_by_freq in (None, True):
psd_units = 'dB/Hz'
else:
psd_units = 'dB'
self.plot(freqs, 10 * np.log10(pxx), **kwargs)
self.set_xlabel('Frequency')
self.set_ylabel('Power Spectral Density (%s)' % psd_units)
self.grid(True)
vmin, vmax = self.viewLim.intervaly
intv = vmax - vmin
logi = int(np.log10(intv))
if logi == 0:
logi = .1
step = 10 * logi
#print vmin, vmax, step, intv, math.floor(vmin), math.ceil(vmax)+1
ticks = np.arange(math.floor(vmin), math.ceil(vmax) + 1, step)
self.set_yticks(ticks)
return pxx, freqs
@docstring.dedent_interpd
def csd(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=0, pad_to=None,
sides='default', scale_by_freq=None, **kwargs):
"""
Plot cross-spectral density.
Call signature::
csd(x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=0, pad_to=None,
sides='default', scale_by_freq=None, **kwargs)
The cross spectral density :math:`P_{xy}` by Welch's average
periodogram method. The vectors *x* and *y* are divided into
*NFFT* length segments. Each segment is detrended by function
*detrend* and windowed by function *window*. The product of
the direct FFTs of *x* and *y* are averaged over each segment
to compute :math:`P_{xy}`, with a scaling to correct for power
loss due to windowing.
Returns the tuple (*Pxy*, *freqs*). *P* is the cross spectrum
(complex valued), and :math:`10\log_{10}|P_{xy}|` is
plotted.
%(PSD)s
*noverlap*: integer
The number of points of overlap between blocks. The
default value is 0 (no overlap).
*Fc*: integer
The center frequency of *x* (defaults to 0), which offsets
the x extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered and downsampled to
baseband.
References:
Bendat & Piersol -- Random Data: Analysis and Measurement
Procedures, John Wiley & Sons (1986)
kwargs control the Line2D properties:
%(Line2D)s
**Example:**
.. plot:: mpl_examples/pylab_examples/csd_demo.py
.. seealso:
:meth:`psd`
For a description of the optional parameters.
"""
if not self._hold:
self.cla()
pxy, freqs = mlab.csd(x, y, NFFT, Fs, detrend, window, noverlap,
pad_to, sides, scale_by_freq)
pxy.shape = len(freqs),
# pxy is complex
freqs += Fc
self.plot(freqs, 10 * np.log10(np.absolute(pxy)), **kwargs)
self.set_xlabel('Frequency')
self.set_ylabel('Cross Spectrum Magnitude (dB)')
self.grid(True)
vmin, vmax = self.viewLim.intervaly
intv = vmax - vmin
step = 10 * int(np.log10(intv))
ticks = np.arange(math.floor(vmin), math.ceil(vmax) + 1, step)
self.set_yticks(ticks)
return pxy, freqs
@docstring.dedent_interpd
def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=0, pad_to=None,
sides='default', scale_by_freq=None, **kwargs):
"""
Plot the coherence between *x* and *y*.
Call signature::
cohere(x, y, NFFT=256, Fs=2, Fc=0, detrend = mlab.detrend_none,
window = mlab.window_hanning, noverlap=0, pad_to=None,
sides='default', scale_by_freq=None, **kwargs)
Plot the coherence between *x* and *y*. Coherence is the
normalized cross spectral density:
.. math::
C_{xy} = \\frac{|P_{xy}|^2}{P_{xx}P_{yy}}
%(PSD)s
*noverlap*: integer
The number of points of overlap between blocks. The
default value is 0 (no overlap).
*Fc*: integer
The center frequency of *x* (defaults to 0), which offsets
the x extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered and downsampled to
baseband.
The return value is a tuple (*Cxy*, *f*), where *f* are the
frequencies of the coherence vector.
kwargs are applied to the lines.
References:
* Bendat & Piersol -- Random Data: Analysis and Measurement
Procedures, John Wiley & Sons (1986)
kwargs control the :class:`~matplotlib.lines.Line2D`
properties of the coherence plot:
%(Line2D)s
**Example:**
.. plot:: mpl_examples/pylab_examples/cohere_demo.py
"""
if not self._hold:
self.cla()
cxy, freqs = mlab.cohere(x, y, NFFT, Fs, detrend, window, noverlap,
scale_by_freq)
freqs += Fc
self.plot(freqs, cxy, **kwargs)
self.set_xlabel('Frequency')
self.set_ylabel('Coherence')
self.grid(True)
return cxy, freqs
@docstring.dedent_interpd
def specgram(self, x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=128,
cmap=None, xextent=None, pad_to=None, sides='default',
scale_by_freq=None, **kwargs):
"""
Plot a spectrogram.
Call signature::
specgram(x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=128,
cmap=None, xextent=None, pad_to=None, sides='default',
scale_by_freq=None, **kwargs)
Compute and plot a spectrogram of data in *x*. Data are split into
*NFFT* length segments and the PSD of each section is
computed. The windowing function *window* is applied to each
segment, and the amount of overlap of each segment is
specified with *noverlap*. The spectrogram is plotted in decibels
as a colormap (using imshow).
%(PSD)s
*noverlap*: integer
The number of points of overlap between blocks. The
default value is 128.
*Fc*: integer
The center frequency of *x* (defaults to 0), which offsets
the y extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered and downsampled to
baseband.
*cmap*:
A :class:`matplotlib.colors.Colormap` instance; if *None*, use
default determined by rc
*xextent*:
The image extent along the x-axis. xextent = (xmin,xmax)
The default is (0,max(bins)), where bins is the return
value from :func:`~matplotlib.mlab.specgram`
*kwargs*:
Additional kwargs are passed on to imshow which makes the
specgram image
Return value is (*Pxx*, *freqs*, *bins*, *im*):
- *bins* are the time points the spectrogram is calculated over
- *freqs* is an array of frequencies
- *Pxx* is an array of shape `(len(times), len(freqs))` of power
- *im* is a :class:`~matplotlib.image.AxesImage` instance
.. note::
If *x* is real (i.e. non-complex), only the positive
spectrum is shown. If *x* is complex, both positive and
negative parts of the spectrum are shown. This can be
overridden using the *sides* keyword argument.
Also note that while the plot is in dB, the *Pxx* array returned is
linear in power.
**Example:**
.. plot:: mpl_examples/pylab_examples/specgram_demo.py
"""
if not self._hold:
self.cla()
Pxx, freqs, bins = mlab.specgram(x, NFFT, Fs, detrend,
window, noverlap, pad_to, sides, scale_by_freq)
Z = 10. * np.log10(Pxx)
Z = np.flipud(Z)
if xextent is None:
xextent = 0, np.amax(bins)
xmin, xmax = xextent
freqs += Fc
extent = xmin, xmax, freqs[0], freqs[-1]
im = self.imshow(Z, cmap, extent=extent, **kwargs)
self.axis('auto')
return Pxx, freqs, bins, im
def spy(self, Z, precision=0, marker=None, markersize=None,
aspect='equal', **kwargs):
"""
Plot the sparsity pattern on a 2-D array.
Call signature::
spy(Z, precision=0, marker=None, markersize=None,
aspect='equal', **kwargs)
``spy(Z)`` plots the sparsity pattern of the 2-D array *Z*.
If *precision* is 0, any non-zero value will be plotted;
else, values of :math:`|Z| > precision` will be plotted.
For :class:`scipy.sparse.spmatrix` instances, there is a
special case: if *precision* is 'present', any value present in
the array will be plotted, even if it is identically zero.
The array will be plotted as it would be printed, with
the first index (row) increasing down and the second
index (column) increasing to the right.
By default aspect is 'equal', so that each array element
occupies a square space; set the aspect kwarg to 'auto'
to allow the plot to fill the plot box, or to any scalar
number to specify the aspect ratio of an array element
directly.
Two plotting styles are available: image or marker. Both
are available for full arrays, but only the marker style
works for :class:`scipy.sparse.spmatrix` instances.
If *marker* and *markersize* are *None*, an image will be
returned and any remaining kwargs are passed to
:func:`~matplotlib.pyplot.imshow`; else, a
:class:`~matplotlib.lines.Line2D` object will be returned with
the value of marker determining the marker type, and any
remaining kwargs passed to the
:meth:`~matplotlib.axes.Axes.plot` method.
If *marker* and *markersize* are *None*, useful kwargs include:
* *cmap*
* *alpha*
.. seealso::
:func:`~matplotlib.pyplot.imshow`
For image options.
For controlling colors, e.g., cyan background and red marks,
use::
cmap = mcolors.ListedColormap(['c','r'])
If *marker* or *markersize* is not *None*, useful kwargs include:
* *marker*
* *markersize*
* *color*
Useful values for *marker* include:
* 's' square (default)
* 'o' circle
* '.' point
* ',' pixel
.. seealso::
:func:`~matplotlib.pyplot.plot`
For plotting options
"""
if marker is None and markersize is None and hasattr(Z, 'tocoo'):
marker = 's'
if marker is None and markersize is None:
Z = np.asarray(Z)
mask = np.absolute(Z) > precision
if 'cmap' not in kwargs:
kwargs['cmap'] = mcolors.ListedColormap(['w', 'k'],
name='binary')
nr, nc = Z.shape
extent = [-0.5, nc - 0.5, nr - 0.5, -0.5]
ret = self.imshow(mask, interpolation='nearest', aspect=aspect,
extent=extent, origin='upper', **kwargs)
else:
if hasattr(Z, 'tocoo'):
c = Z.tocoo()
if precision == 'present':
y = c.row
x = c.col
else:
nonzero = np.absolute(c.data) > precision
y = c.row[nonzero]
x = c.col[nonzero]
else:
Z = np.asarray(Z)
nonzero = np.absolute(Z) > precision
y, x = np.nonzero(nonzero)
if marker is None:
marker = 's'
if markersize is None:
markersize = 10
marks = mlines.Line2D(x, y, linestyle='None',
marker=marker, markersize=markersize, **kwargs)
self.add_line(marks)
nr, nc = Z.shape
self.set_xlim(xmin=-0.5, xmax=nc - 0.5)
self.set_ylim(ymin=nr - 0.5, ymax=-0.5)
self.set_aspect(aspect)
ret = marks
self.title.set_y(1.05)
self.xaxis.tick_top()
self.xaxis.set_ticks_position('both')
self.xaxis.set_major_locator(mticker.MaxNLocator(nbins=9,
steps=[1, 2, 5, 10],
integer=True))
self.yaxis.set_major_locator(mticker.MaxNLocator(nbins=9,
steps=[1, 2, 5, 10],
integer=True))
return ret
def matshow(self, Z, **kwargs):
"""
Plot a matrix or array as an image.
The matrix will be shown the way it would be printed, with the first
row at the top. Row and column numbering is zero-based.
Parameters
----------
Z : array_like shape (n, m)
The matrix to be displayed.
Returns
-------
image : `~matplotlib.image.AxesImage`
Other parameters
----------------
kwargs : `~matplotlib.axes.Axes.imshow` arguments
Sets `origin` to 'upper', 'interpolation' to 'nearest' and
'aspect' to equal.
See also
--------
imshow : plot an image
Examples
--------
.. plot:: mpl_examples/pylab_examples/matshow.py
"""
Z = np.asanyarray(Z)
nr, nc = Z.shape
kw = {'origin': 'upper',
'interpolation': 'nearest',
'aspect': 'equal'} # (already the imshow default)
kw.update(kwargs)
im = self.imshow(Z, **kw)
self.title.set_y(1.05)
self.xaxis.tick_top()
self.xaxis.set_ticks_position('both')
self.xaxis.set_major_locator(mticker.MaxNLocator(nbins=9,
steps=[1, 2, 5, 10],
integer=True))
self.yaxis.set_major_locator(mticker.MaxNLocator(nbins=9,
steps=[1, 2, 5, 10],
integer=True))
return im
def get_default_bbox_extra_artists(self):
return [artist for artist in self.get_children()
if artist.get_visible()]
def get_tightbbox(self, renderer, call_axes_locator=True):
"""
Return the tight bounding box of the axes.
The dimension of the Bbox in canvas coordinate.
If *call_axes_locator* is *False*, it does not call the
_axes_locator attribute, which is necessary to get the correct
bounding box. ``call_axes_locator==False`` can be used if the
caller is only intereted in the relative size of the tightbbox
compared to the axes bbox.
"""
bb = []
if not self.get_visible():
return None
locator = self.get_axes_locator()
if locator and call_axes_locator:
pos = locator(self, renderer)
self.apply_aspect(pos)
else:
self.apply_aspect()
bb.append(self.get_window_extent(renderer))
if self.title.get_visible():
bb.append(self.title.get_window_extent(renderer))
if self._left_title.get_visible():
bb.append(self._left_title.get_window_extent(renderer))
if self._right_title.get_visible():
bb.append(self._right_title.get_window_extent(renderer))
bb_xaxis = self.xaxis.get_tightbbox(renderer)
if bb_xaxis:
bb.append(bb_xaxis)
bb_yaxis = self.yaxis.get_tightbbox(renderer)
if bb_yaxis:
bb.append(bb_yaxis)
_bbox = mtransforms.Bbox.union(
[b for b in bb if b.width != 0 or b.height != 0])
return _bbox
def minorticks_on(self):
'Add autoscaling minor ticks to the axes.'
for ax in (self.xaxis, self.yaxis):
if ax.get_scale() == 'log':
s = ax._scale
ax.set_minor_locator(mticker.LogLocator(s.base, s.subs))
else:
ax.set_minor_locator(mticker.AutoMinorLocator())
def minorticks_off(self):
"""Remove minor ticks from the axes."""
self.xaxis.set_minor_locator(mticker.NullLocator())
self.yaxis.set_minor_locator(mticker.NullLocator())
def tricontour(self, *args, **kwargs):
return mtri.tricontour(self, *args, **kwargs)
tricontour.__doc__ = mtri.TriContourSet.tricontour_doc
def tricontourf(self, *args, **kwargs):
return mtri.tricontourf(self, *args, **kwargs)
tricontourf.__doc__ = mtri.TriContourSet.tricontour_doc
def tripcolor(self, *args, **kwargs):
return mtri.tripcolor(self, *args, **kwargs)
tripcolor.__doc__ = mtri.tripcolor.__doc__
def triplot(self, *args, **kwargs):
mtri.triplot(self, *args, **kwargs)
triplot.__doc__ = mtri.triplot.__doc__
from matplotlib.gridspec import GridSpec, SubplotSpec
class SubplotBase:
"""
Base class for subplots, which are :class:`Axes` instances with
additional methods to facilitate generating and manipulating a set
of :class:`Axes` within a figure.
"""
def __init__(self, fig, *args, **kwargs):
"""
*fig* is a :class:`matplotlib.figure.Figure` instance.
*args* is the tuple (*numRows*, *numCols*, *plotNum*), where
the array of subplots in the figure has dimensions *numRows*,
*numCols*, and where *plotNum* is the number of the subplot
being created. *plotNum* starts at 1 in the upper left
corner and increases to the right.
If *numRows* <= *numCols* <= *plotNum* < 10, *args* can be the
decimal integer *numRows* * 100 + *numCols* * 10 + *plotNum*.
"""
self.figure = fig
if len(args) == 1:
if isinstance(args[0], SubplotSpec):
self._subplotspec = args[0]
else:
try:
s = str(int(args[0]))
rows, cols, num = map(int, s)
except ValueError:
raise ValueError(
'Single argument to subplot must be a 3-digit '
'integer')
self._subplotspec = GridSpec(rows, cols)[num - 1]
# num - 1 for converting from MATLAB to python indexing
elif len(args) == 3:
rows, cols, num = args
rows = int(rows)
cols = int(cols)
if isinstance(num, tuple) and len(num) == 2:
num = [int(n) for n in num]
self._subplotspec = GridSpec(rows, cols)[num[0] - 1:num[1]]
else:
self._subplotspec = GridSpec(rows, cols)[int(num) - 1]
# num - 1 for converting from MATLAB to python indexing
else:
raise ValueError('Illegal argument(s) to subplot: %s' % (args,))
self.update_params()
# _axes_class is set in the subplot_class_factory
self._axes_class.__init__(self, fig, self.figbox, **kwargs)
def __reduce__(self):
# get the first axes class which does not inherit from a subplotbase
not_subplotbase = lambda c: issubclass(c, Axes) and \
not issubclass(c, SubplotBase)
axes_class = [c for c in self.__class__.mro() if not_subplotbase(c)][0]
r = [_PicklableSubplotClassConstructor(),
(axes_class,),
self.__getstate__()]
return tuple(r)
def get_geometry(self):
"""get the subplot geometry, eg 2,2,3"""
rows, cols, num1, num2 = self.get_subplotspec().get_geometry()
return rows, cols, num1 + 1 # for compatibility
# COVERAGE NOTE: Never used internally or from examples
def change_geometry(self, numrows, numcols, num):
"""change subplot geometry, e.g., from 1,1,1 to 2,2,3"""
self._subplotspec = GridSpec(numrows, numcols)[num - 1]
self.update_params()
self.set_position(self.figbox)
def get_subplotspec(self):
"""get the SubplotSpec instance associated with the subplot"""
return self._subplotspec
def set_subplotspec(self, subplotspec):
"""set the SubplotSpec instance associated with the subplot"""
self._subplotspec = subplotspec
def update_params(self):
"""update the subplot position from fig.subplotpars"""
self.figbox, self.rowNum, self.colNum, self.numRows, self.numCols = \
self.get_subplotspec().get_position(self.figure,
return_all=True)
def is_first_col(self):
return self.colNum == 0
def is_first_row(self):
return self.rowNum == 0
def is_last_row(self):
return self.rowNum == self.numRows - 1
def is_last_col(self):
return self.colNum == self.numCols - 1
# COVERAGE NOTE: Never used internally or from examples
def label_outer(self):
"""
set the visible property on ticklabels so xticklabels are
visible only if the subplot is in the last row and yticklabels
are visible only if the subplot is in the first column
"""
lastrow = self.is_last_row()
firstcol = self.is_first_col()
for label in self.get_xticklabels():
label.set_visible(lastrow)
for label in self.get_yticklabels():
label.set_visible(firstcol)
def _make_twin_axes(self, *kl, **kwargs):
"""
make a twinx axes of self. This is used for twinx and twiny.
"""
from matplotlib.projections import process_projection_requirements
kl = (self.get_subplotspec(),) + kl
projection_class, kwargs, key = process_projection_requirements(
self.figure, *kl, **kwargs)
ax2 = subplot_class_factory(projection_class)(self.figure,
*kl, **kwargs)
self.figure.add_subplot(ax2)
return ax2
_subplot_classes = {}
def subplot_class_factory(axes_class=None):
# This makes a new class that inherits from SubplotBase and the
# given axes_class (which is assumed to be a subclass of Axes).
# This is perhaps a little bit roundabout to make a new class on
# the fly like this, but it means that a new Subplot class does
# not have to be created for every type of Axes.
if axes_class is None:
axes_class = Axes
new_class = _subplot_classes.get(axes_class)
if new_class is None:
new_class = type("%sSubplot" % (axes_class.__name__),
(SubplotBase, axes_class),
{'_axes_class': axes_class})
_subplot_classes[axes_class] = new_class
return new_class
# This is provided for backward compatibility
Subplot = subplot_class_factory()
class _PicklableSubplotClassConstructor(object):
"""
This stub class exists to return the appropriate subplot
class when __call__-ed with an axes class. This is purely to
allow Pickling of Axes and Subplots.
"""
def __call__(self, axes_class):
# create a dummy object instance
subplot_instance = _PicklableSubplotClassConstructor()
subplot_class = subplot_class_factory(axes_class)
# update the class to the desired subplot class
subplot_instance.__class__ = subplot_class
return subplot_instance
docstring.interpd.update(Axes=martist.kwdoc(Axes))
docstring.interpd.update(Subplot=martist.kwdoc(Axes))
"""
# this is some discarded code I was using to find the minimum positive
# data point for some log scaling fixes. I realized there was a
# cleaner way to do it, but am keeping this around as an example for
# how to get the data out of the axes. Might want to make something
# like this a method one day, or better yet make get_verts an Artist
# method
minx, maxx = self.get_xlim()
if minx<=0 or maxx<=0:
# find the min pos value in the data
xs = []
for line in self.lines:
xs.extend(line.get_xdata(orig=False))
for patch in self.patches:
xs.extend([x for x,y in patch.get_verts()])
for collection in self.collections:
xs.extend([x for x,y in collection.get_verts()])
posx = [x for x in xs if x>0]
if len(posx):
minx = min(posx)
maxx = max(posx)
# warning, probably breaks inverted axis
self.set_xlim((0.1*minx, maxx))
"""
| {
"content_hash": "065c746ca0c5339e54ffeb683e5d7c3f",
"timestamp": "",
"source": "github",
"line_count": 9408,
"max_line_length": 89,
"avg_line_length": 35.55846088435374,
"alnum_prop": 0.5344210155021613,
"repo_name": "RobertABT/heightmap",
"id": "a3a92ee54d1f0502a49f8d1d0f69d2cbfa03e217",
"size": "334534",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "build/matplotlib/lib/matplotlib/axes.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "25165856"
},
{
"name": "C++",
"bytes": "5251754"
},
{
"name": "CSS",
"bytes": "17123"
},
{
"name": "FORTRAN",
"bytes": "6353469"
},
{
"name": "JavaScript",
"bytes": "816504"
},
{
"name": "M",
"bytes": "66"
},
{
"name": "Matlab",
"bytes": "4280"
},
{
"name": "Objective-C",
"bytes": "284551"
},
{
"name": "Python",
"bytes": "13223936"
},
{
"name": "TeX",
"bytes": "37261"
}
],
"symlink_target": ""
} |
"""Tests for gree component."""
from datetime import timedelta
from unittest.mock import DEFAULT as DEFAULT_MOCK, AsyncMock, patch
from greeclimate.device import HorizontalSwing, VerticalSwing
from greeclimate.exceptions import DeviceNotBoundError, DeviceTimeoutError
import pytest
from homeassistant.components.climate import ClimateEntityFeature
from homeassistant.components.climate.const import (
ATTR_CURRENT_TEMPERATURE,
ATTR_FAN_MODE,
ATTR_HVAC_MODE,
ATTR_PRESET_MODE,
ATTR_SWING_MODE,
DOMAIN,
FAN_AUTO,
FAN_HIGH,
FAN_LOW,
FAN_MEDIUM,
PRESET_AWAY,
PRESET_BOOST,
PRESET_ECO,
PRESET_NONE,
PRESET_SLEEP,
SERVICE_SET_FAN_MODE,
SERVICE_SET_HVAC_MODE,
SERVICE_SET_PRESET_MODE,
SERVICE_SET_SWING_MODE,
SERVICE_SET_TEMPERATURE,
SWING_BOTH,
SWING_HORIZONTAL,
SWING_OFF,
SWING_VERTICAL,
HVACMode,
)
from homeassistant.components.gree.climate import FAN_MODES_REVERSE, HVAC_MODES_REVERSE
from homeassistant.components.gree.const import FAN_MEDIUM_HIGH, FAN_MEDIUM_LOW
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
ATTR_SUPPORTED_FEATURES,
ATTR_TEMPERATURE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_UNAVAILABLE,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
import homeassistant.util.dt as dt_util
from .common import async_setup_gree, build_device_mock
from tests.common import async_fire_time_changed
ENTITY_ID = f"{DOMAIN}.fake_device_1"
@pytest.fixture
def mock_now():
"""Fixture for dtutil.now."""
return dt_util.utcnow()
async def test_discovery_called_once(hass, discovery, device):
"""Test discovery is only ever called once."""
await async_setup_gree(hass)
assert discovery.call_count == 1
await async_setup_gree(hass)
assert discovery.call_count == 1
async def test_discovery_setup(hass, discovery, device):
"""Test setup of platform."""
MockDevice1 = build_device_mock(
name="fake-device-1", ipAddress="1.1.1.1", mac="aabbcc112233"
)
MockDevice2 = build_device_mock(
name="fake-device-2", ipAddress="2.2.2.2", mac="bbccdd223344"
)
discovery.return_value.mock_devices = [MockDevice1, MockDevice2]
device.side_effect = [MockDevice1, MockDevice2]
await async_setup_gree(hass)
await hass.async_block_till_done()
assert discovery.call_count == 1
assert len(hass.states.async_all(DOMAIN)) == 2
async def test_discovery_setup_connection_error(hass, discovery, device, mock_now):
"""Test gree integration is setup."""
MockDevice1 = build_device_mock(
name="fake-device-1", ipAddress="1.1.1.1", mac="aabbcc112233"
)
MockDevice1.bind = AsyncMock(side_effect=DeviceNotBoundError)
MockDevice1.update_state = AsyncMock(side_effect=DeviceNotBoundError)
discovery.return_value.mock_devices = [MockDevice1]
device.return_value = MockDevice1
await async_setup_gree(hass)
await hass.async_block_till_done()
assert len(hass.states.async_all(DOMAIN)) == 1
state = hass.states.get(ENTITY_ID)
assert state.name == "fake-device-1"
assert state.state == STATE_UNAVAILABLE
async def test_discovery_after_setup(hass, discovery, device, mock_now):
"""Test gree devices don't change after multiple discoveries."""
MockDevice1 = build_device_mock(
name="fake-device-1", ipAddress="1.1.1.1", mac="aabbcc112233"
)
MockDevice1.bind = AsyncMock(side_effect=DeviceNotBoundError)
MockDevice2 = build_device_mock(
name="fake-device-2", ipAddress="2.2.2.2", mac="bbccdd223344"
)
MockDevice2.bind = AsyncMock(side_effect=DeviceTimeoutError)
discovery.return_value.mock_devices = [MockDevice1, MockDevice2]
device.side_effect = [MockDevice1, MockDevice2]
await async_setup_gree(hass)
await hass.async_block_till_done()
assert discovery.return_value.scan_count == 1
assert len(hass.states.async_all(DOMAIN)) == 2
# rediscover the same devices shouldn't change anything
discovery.return_value.mock_devices = [MockDevice1, MockDevice2]
device.side_effect = [MockDevice1, MockDevice2]
next_update = mock_now + timedelta(minutes=6)
with patch("homeassistant.util.dt.utcnow", return_value=next_update):
async_fire_time_changed(hass, next_update)
await hass.async_block_till_done()
assert discovery.return_value.scan_count == 2
assert len(hass.states.async_all(DOMAIN)) == 2
async def test_discovery_add_device_after_setup(hass, discovery, device, mock_now):
"""Test gree devices can be added after initial setup."""
MockDevice1 = build_device_mock(
name="fake-device-1", ipAddress="1.1.1.1", mac="aabbcc112233"
)
MockDevice1.bind = AsyncMock(side_effect=DeviceNotBoundError)
MockDevice2 = build_device_mock(
name="fake-device-2", ipAddress="2.2.2.2", mac="bbccdd223344"
)
MockDevice2.bind = AsyncMock(side_effect=DeviceTimeoutError)
discovery.return_value.mock_devices = [MockDevice1]
device.side_effect = [MockDevice1]
await async_setup_gree(hass)
await hass.async_block_till_done()
assert discovery.return_value.scan_count == 1
assert len(hass.states.async_all(DOMAIN)) == 1
# rediscover the same devices shouldn't change anything
discovery.return_value.mock_devices = [MockDevice2]
device.side_effect = [MockDevice2]
next_update = mock_now + timedelta(minutes=6)
with patch("homeassistant.util.dt.utcnow", return_value=next_update):
async_fire_time_changed(hass, next_update)
await hass.async_block_till_done()
assert discovery.return_value.scan_count == 2
assert len(hass.states.async_all(DOMAIN)) == 2
async def test_discovery_device_bind_after_setup(hass, discovery, device, mock_now):
"""Test gree devices can be added after a late device bind."""
MockDevice1 = build_device_mock(
name="fake-device-1", ipAddress="1.1.1.1", mac="aabbcc112233"
)
MockDevice1.bind = AsyncMock(side_effect=DeviceNotBoundError)
MockDevice1.update_state = AsyncMock(side_effect=DeviceNotBoundError)
discovery.return_value.mock_devices = [MockDevice1]
device.return_value = MockDevice1
await async_setup_gree(hass)
await hass.async_block_till_done()
assert len(hass.states.async_all(DOMAIN)) == 1
state = hass.states.get(ENTITY_ID)
assert state.name == "fake-device-1"
assert state.state == STATE_UNAVAILABLE
# Now the device becomes available
MockDevice1.bind.side_effect = None
MockDevice1.update_state.side_effect = None
next_update = mock_now + timedelta(minutes=5)
with patch("homeassistant.util.dt.utcnow", return_value=next_update):
async_fire_time_changed(hass, next_update)
await hass.async_block_till_done()
state = hass.states.get(ENTITY_ID)
assert state.state != STATE_UNAVAILABLE
async def test_update_connection_failure(hass, device, mock_now):
"""Testing update hvac connection failure exception."""
device().update_state.side_effect = [
DEFAULT_MOCK,
DeviceTimeoutError,
DeviceTimeoutError,
]
await async_setup_gree(hass)
next_update = mock_now + timedelta(minutes=5)
with patch("homeassistant.util.dt.utcnow", return_value=next_update):
async_fire_time_changed(hass, next_update)
await hass.async_block_till_done()
# First update to make the device available
state = hass.states.get(ENTITY_ID)
assert state.name == "fake-device-1"
assert state.state != STATE_UNAVAILABLE
next_update = mock_now + timedelta(minutes=10)
with patch("homeassistant.util.dt.utcnow", return_value=next_update):
async_fire_time_changed(hass, next_update)
await hass.async_block_till_done()
next_update = mock_now + timedelta(minutes=15)
with patch("homeassistant.util.dt.utcnow", return_value=next_update):
async_fire_time_changed(hass, next_update)
await hass.async_block_till_done()
# Then two more update failures to make the device unavailable
state = hass.states.get(ENTITY_ID)
assert state.name == "fake-device-1"
assert state.state == STATE_UNAVAILABLE
async def test_update_connection_failure_recovery(hass, discovery, device, mock_now):
"""Testing update hvac connection failure recovery."""
device().update_state.side_effect = [
DeviceTimeoutError,
DeviceTimeoutError,
DEFAULT_MOCK,
]
await async_setup_gree(hass)
# First update becomes unavailable
next_update = mock_now + timedelta(minutes=5)
with patch("homeassistant.util.dt.utcnow", return_value=next_update):
async_fire_time_changed(hass, next_update)
await hass.async_block_till_done()
state = hass.states.get(ENTITY_ID)
assert state.name == "fake-device-1"
assert state.state == STATE_UNAVAILABLE
# Second update restores the connection
next_update = mock_now + timedelta(minutes=10)
with patch("homeassistant.util.dt.utcnow", return_value=next_update):
async_fire_time_changed(hass, next_update)
await hass.async_block_till_done()
state = hass.states.get(ENTITY_ID)
assert state.name == "fake-device-1"
assert state.state != STATE_UNAVAILABLE
async def test_update_unhandled_exception(hass, discovery, device, mock_now):
"""Testing update hvac connection unhandled response exception."""
device().update_state.side_effect = [DEFAULT_MOCK, Exception]
await async_setup_gree(hass)
state = hass.states.get(ENTITY_ID)
assert state.name == "fake-device-1"
assert state.state != STATE_UNAVAILABLE
next_update = mock_now + timedelta(minutes=10)
with patch("homeassistant.util.dt.utcnow", return_value=next_update):
async_fire_time_changed(hass, next_update)
await hass.async_block_till_done()
state = hass.states.get(ENTITY_ID)
assert state.name == "fake-device-1"
assert state.state == STATE_UNAVAILABLE
async def test_send_command_device_timeout(hass, discovery, device, mock_now):
"""Test for sending power on command to the device with a device timeout."""
await async_setup_gree(hass)
# First update to make the device available
next_update = mock_now + timedelta(minutes=5)
with patch("homeassistant.util.dt.utcnow", return_value=next_update):
async_fire_time_changed(hass, next_update)
await hass.async_block_till_done()
state = hass.states.get(ENTITY_ID)
assert state.name == "fake-device-1"
assert state.state != STATE_UNAVAILABLE
device().push_state_update.side_effect = DeviceTimeoutError
# Send failure should not raise exceptions or change device state
assert await hass.services.async_call(
DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: ENTITY_ID},
blocking=True,
)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.state != STATE_UNAVAILABLE
async def test_send_power_on(hass, discovery, device, mock_now):
"""Test for sending power on command to the device."""
await async_setup_gree(hass)
assert await hass.services.async_call(
DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: ENTITY_ID},
blocking=True,
)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.state == HVACMode.OFF
async def test_send_power_off_device_timeout(hass, discovery, device, mock_now):
"""Test for sending power off command to the device with a device timeout."""
device().push_state_update.side_effect = DeviceTimeoutError
await async_setup_gree(hass)
assert await hass.services.async_call(
DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: ENTITY_ID},
blocking=True,
)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.state == HVACMode.OFF
@pytest.mark.parametrize(
"units,temperature", [(TEMP_CELSIUS, 26), (TEMP_FAHRENHEIT, 74)]
)
async def test_send_target_temperature(hass, discovery, device, units, temperature):
"""Test for sending target temperature command to the device."""
hass.config.units.temperature_unit = units
fake_device = device()
if units == TEMP_FAHRENHEIT:
fake_device.temperature_units = 1
await async_setup_gree(hass)
# Make sure we're trying to test something that isn't the default
assert fake_device.current_temperature != temperature
assert await hass.services.async_call(
DOMAIN,
SERVICE_SET_TEMPERATURE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_TEMPERATURE: temperature},
blocking=True,
)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.attributes.get(ATTR_TEMPERATURE) == temperature
assert (
state.attributes.get(ATTR_CURRENT_TEMPERATURE)
== fake_device.current_temperature
)
# Reset config temperature_unit back to CELSIUS, required for
# additional tests outside this component.
hass.config.units.temperature_unit = TEMP_CELSIUS
@pytest.mark.parametrize(
"units,temperature", [(TEMP_CELSIUS, 25), (TEMP_FAHRENHEIT, 74)]
)
async def test_send_target_temperature_device_timeout(
hass, discovery, device, units, temperature
):
"""Test for sending target temperature command to the device with a device timeout."""
hass.config.units.temperature_unit = units
if units == TEMP_FAHRENHEIT:
device().temperature_units = 1
device().push_state_update.side_effect = DeviceTimeoutError
await async_setup_gree(hass)
assert await hass.services.async_call(
DOMAIN,
SERVICE_SET_TEMPERATURE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_TEMPERATURE: temperature},
blocking=True,
)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.attributes.get(ATTR_TEMPERATURE) == temperature
# Reset config temperature_unit back to CELSIUS, required for additional tests outside this component.
hass.config.units.temperature_unit = TEMP_CELSIUS
@pytest.mark.parametrize(
"units,temperature", [(TEMP_CELSIUS, 25), (TEMP_FAHRENHEIT, 74)]
)
async def test_update_target_temperature(hass, discovery, device, units, temperature):
"""Test for updating target temperature from the device."""
hass.config.units.temperature_unit = units
if units == TEMP_FAHRENHEIT:
device().temperature_units = 1
device().target_temperature = temperature
await async_setup_gree(hass)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.attributes.get(ATTR_TEMPERATURE) == temperature
# Reset config temperature_unit back to CELSIUS, required for additional tests outside this component.
hass.config.units.temperature_unit = TEMP_CELSIUS
@pytest.mark.parametrize(
"preset", (PRESET_AWAY, PRESET_ECO, PRESET_SLEEP, PRESET_BOOST, PRESET_NONE)
)
async def test_send_preset_mode(hass, discovery, device, mock_now, preset):
"""Test for sending preset mode command to the device."""
await async_setup_gree(hass)
assert await hass.services.async_call(
DOMAIN,
SERVICE_SET_PRESET_MODE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_PRESET_MODE: preset},
blocking=True,
)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.attributes.get(ATTR_PRESET_MODE) == preset
async def test_send_invalid_preset_mode(hass, discovery, device, mock_now):
"""Test for sending preset mode command to the device."""
await async_setup_gree(hass)
with pytest.raises(ValueError):
await hass.services.async_call(
DOMAIN,
SERVICE_SET_PRESET_MODE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_PRESET_MODE: "invalid"},
blocking=True,
)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.attributes.get(ATTR_PRESET_MODE) != "invalid"
@pytest.mark.parametrize(
"preset", (PRESET_AWAY, PRESET_ECO, PRESET_SLEEP, PRESET_BOOST, PRESET_NONE)
)
async def test_send_preset_mode_device_timeout(
hass, discovery, device, mock_now, preset
):
"""Test for sending preset mode command to the device with a device timeout."""
device().push_state_update.side_effect = DeviceTimeoutError
await async_setup_gree(hass)
assert await hass.services.async_call(
DOMAIN,
SERVICE_SET_PRESET_MODE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_PRESET_MODE: preset},
blocking=True,
)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.attributes.get(ATTR_PRESET_MODE) == preset
@pytest.mark.parametrize(
"preset", (PRESET_AWAY, PRESET_ECO, PRESET_SLEEP, PRESET_BOOST, PRESET_NONE)
)
async def test_update_preset_mode(hass, discovery, device, mock_now, preset):
"""Test for updating preset mode from the device."""
device().steady_heat = preset == PRESET_AWAY
device().power_save = preset == PRESET_ECO
device().sleep = preset == PRESET_SLEEP
device().turbo = preset == PRESET_BOOST
await async_setup_gree(hass)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.attributes.get(ATTR_PRESET_MODE) == preset
@pytest.mark.parametrize(
"hvac_mode",
(
HVACMode.OFF,
HVACMode.AUTO,
HVACMode.COOL,
HVACMode.DRY,
HVACMode.FAN_ONLY,
HVACMode.HEAT,
),
)
async def test_send_hvac_mode(hass, discovery, device, mock_now, hvac_mode):
"""Test for sending hvac mode command to the device."""
await async_setup_gree(hass)
assert await hass.services.async_call(
DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_HVAC_MODE: hvac_mode},
blocking=True,
)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.state == hvac_mode
@pytest.mark.parametrize(
"hvac_mode",
(HVACMode.AUTO, HVACMode.COOL, HVACMode.DRY, HVACMode.FAN_ONLY, HVACMode.HEAT),
)
async def test_send_hvac_mode_device_timeout(
hass, discovery, device, mock_now, hvac_mode
):
"""Test for sending hvac mode command to the device with a device timeout."""
device().push_state_update.side_effect = DeviceTimeoutError
await async_setup_gree(hass)
assert await hass.services.async_call(
DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_HVAC_MODE: hvac_mode},
blocking=True,
)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.state == hvac_mode
@pytest.mark.parametrize(
"hvac_mode",
(
HVACMode.OFF,
HVACMode.AUTO,
HVACMode.COOL,
HVACMode.DRY,
HVACMode.FAN_ONLY,
HVACMode.HEAT,
),
)
async def test_update_hvac_mode(hass, discovery, device, mock_now, hvac_mode):
"""Test for updating hvac mode from the device."""
device().power = hvac_mode != HVACMode.OFF
device().mode = HVAC_MODES_REVERSE.get(hvac_mode)
await async_setup_gree(hass)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.state == hvac_mode
@pytest.mark.parametrize(
"fan_mode",
(FAN_AUTO, FAN_LOW, FAN_MEDIUM_LOW, FAN_MEDIUM, FAN_MEDIUM_HIGH, FAN_HIGH),
)
async def test_send_fan_mode(hass, discovery, device, mock_now, fan_mode):
"""Test for sending fan mode command to the device."""
await async_setup_gree(hass)
assert await hass.services.async_call(
DOMAIN,
SERVICE_SET_FAN_MODE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_FAN_MODE: fan_mode},
blocking=True,
)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.attributes.get(ATTR_FAN_MODE) == fan_mode
async def test_send_invalid_fan_mode(hass, discovery, device, mock_now):
"""Test for sending fan mode command to the device."""
await async_setup_gree(hass)
with pytest.raises(ValueError):
await hass.services.async_call(
DOMAIN,
SERVICE_SET_FAN_MODE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_FAN_MODE: "invalid"},
blocking=True,
)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.attributes.get(ATTR_FAN_MODE) != "invalid"
@pytest.mark.parametrize(
"fan_mode",
(FAN_AUTO, FAN_LOW, FAN_MEDIUM_LOW, FAN_MEDIUM, FAN_MEDIUM_HIGH, FAN_HIGH),
)
async def test_send_fan_mode_device_timeout(
hass, discovery, device, mock_now, fan_mode
):
"""Test for sending fan mode command to the device with a device timeout."""
device().push_state_update.side_effect = DeviceTimeoutError
await async_setup_gree(hass)
assert await hass.services.async_call(
DOMAIN,
SERVICE_SET_FAN_MODE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_FAN_MODE: fan_mode},
blocking=True,
)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.attributes.get(ATTR_FAN_MODE) == fan_mode
@pytest.mark.parametrize(
"fan_mode",
(FAN_AUTO, FAN_LOW, FAN_MEDIUM_LOW, FAN_MEDIUM, FAN_MEDIUM_HIGH, FAN_HIGH),
)
async def test_update_fan_mode(hass, discovery, device, mock_now, fan_mode):
"""Test for updating fan mode from the device."""
device().fan_speed = FAN_MODES_REVERSE.get(fan_mode)
await async_setup_gree(hass)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.attributes.get(ATTR_FAN_MODE) == fan_mode
@pytest.mark.parametrize(
"swing_mode", (SWING_OFF, SWING_BOTH, SWING_VERTICAL, SWING_HORIZONTAL)
)
async def test_send_swing_mode(hass, discovery, device, mock_now, swing_mode):
"""Test for sending swing mode command to the device."""
await async_setup_gree(hass)
assert await hass.services.async_call(
DOMAIN,
SERVICE_SET_SWING_MODE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_SWING_MODE: swing_mode},
blocking=True,
)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.attributes.get(ATTR_SWING_MODE) == swing_mode
async def test_send_invalid_swing_mode(hass, discovery, device, mock_now):
"""Test for sending swing mode command to the device."""
await async_setup_gree(hass)
with pytest.raises(ValueError):
await hass.services.async_call(
DOMAIN,
SERVICE_SET_SWING_MODE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_SWING_MODE: "invalid"},
blocking=True,
)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.attributes.get(ATTR_SWING_MODE) != "invalid"
@pytest.mark.parametrize(
"swing_mode", (SWING_OFF, SWING_BOTH, SWING_VERTICAL, SWING_HORIZONTAL)
)
async def test_send_swing_mode_device_timeout(
hass, discovery, device, mock_now, swing_mode
):
"""Test for sending swing mode command to the device with a device timeout."""
device().push_state_update.side_effect = DeviceTimeoutError
await async_setup_gree(hass)
assert await hass.services.async_call(
DOMAIN,
SERVICE_SET_SWING_MODE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_SWING_MODE: swing_mode},
blocking=True,
)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.attributes.get(ATTR_SWING_MODE) == swing_mode
@pytest.mark.parametrize(
"swing_mode", (SWING_OFF, SWING_BOTH, SWING_VERTICAL, SWING_HORIZONTAL)
)
async def test_update_swing_mode(hass, discovery, device, mock_now, swing_mode):
"""Test for updating swing mode from the device."""
device().horizontal_swing = (
HorizontalSwing.FullSwing
if swing_mode in (SWING_BOTH, SWING_HORIZONTAL)
else HorizontalSwing.Default
)
device().vertical_swing = (
VerticalSwing.FullSwing
if swing_mode in (SWING_BOTH, SWING_VERTICAL)
else VerticalSwing.Default
)
await async_setup_gree(hass)
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.attributes.get(ATTR_SWING_MODE) == swing_mode
async def test_name(hass, discovery, device):
"""Test for name property."""
await async_setup_gree(hass)
state = hass.states.get(ENTITY_ID)
assert state.attributes[ATTR_FRIENDLY_NAME] == "fake-device-1"
async def test_supported_features_with_turnon(hass, discovery, device):
"""Test for supported_features property."""
await async_setup_gree(hass)
state = hass.states.get(ENTITY_ID)
assert state.attributes[ATTR_SUPPORTED_FEATURES] == (
ClimateEntityFeature.TARGET_TEMPERATURE
| ClimateEntityFeature.FAN_MODE
| ClimateEntityFeature.PRESET_MODE
| ClimateEntityFeature.SWING_MODE
)
| {
"content_hash": "e223e5c6851dcca39b469d15a28eb7c0",
"timestamp": "",
"source": "github",
"line_count": 771,
"max_line_length": 106,
"avg_line_length": 32.09597924773022,
"alnum_prop": 0.6841509738947709,
"repo_name": "toddeye/home-assistant",
"id": "ac818c7fd32713116474f21aeb580c5b4b0a760e",
"size": "24746",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "tests/components/gree/test_climate.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "3005"
},
{
"name": "PLSQL",
"bytes": "840"
},
{
"name": "Python",
"bytes": "47414832"
},
{
"name": "Shell",
"bytes": "6252"
}
],
"symlink_target": ""
} |
"""SCons.Tool.GettextCommon module
Used by several tools of `gettext` toolset.
"""
# __COPYRIGHT__
#
# 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.
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import SCons.Warnings
import re
#############################################################################
class XgettextToolWarning(SCons.Warnings.Warning): pass
class XgettextNotFound(XgettextToolWarning): pass
class MsginitToolWarning(SCons.Warnings.Warning): pass
class MsginitNotFound(MsginitToolWarning): pass
class MsgmergeToolWarning(SCons.Warnings.Warning): pass
class MsgmergeNotFound(MsgmergeToolWarning): pass
class MsgfmtToolWarning(SCons.Warnings.Warning): pass
class MsgfmtNotFound(MsgfmtToolWarning): pass
#############################################################################
SCons.Warnings.enableWarningClass(XgettextToolWarning)
SCons.Warnings.enableWarningClass(XgettextNotFound)
SCons.Warnings.enableWarningClass(MsginitToolWarning)
SCons.Warnings.enableWarningClass(MsginitNotFound)
SCons.Warnings.enableWarningClass(MsgmergeToolWarning)
SCons.Warnings.enableWarningClass(MsgmergeNotFound)
SCons.Warnings.enableWarningClass(MsgfmtToolWarning)
SCons.Warnings.enableWarningClass(MsgfmtNotFound)
#############################################################################
#############################################################################
class _POTargetFactory(object):
""" A factory of `PO` target files.
Factory defaults differ from these of `SCons.Node.FS.FS`. We set `precious`
(this is required by builders and actions gettext) and `noclean` flags by
default for all produced nodes.
"""
def __init__( self, env, nodefault = True, alias = None, precious = True
, noclean = True ):
""" Object constructor.
**Arguments**
- *env* (`SCons.Environment.Environment`)
- *nodefault* (`boolean`) - if `True`, produced nodes will be ignored
from default target `'.'`
- *alias* (`string`) - if provided, produced nodes will be automatically
added to this alias, and alias will be set as `AlwaysBuild`
- *precious* (`boolean`) - if `True`, the produced nodes will be set as
`Precious`.
- *noclen* (`boolean`) - if `True`, the produced nodes will be excluded
from `Clean`.
"""
self.env = env
self.alias = alias
self.precious = precious
self.noclean = noclean
self.nodefault = nodefault
def _create_node(self, name, factory, directory = None, create = 1):
""" Create node, and set it up to factory settings. """
import SCons.Util
node = factory(name, directory, create)
node.set_noclean(self.noclean)
node.set_precious(self.precious)
if self.nodefault:
self.env.Ignore('.', node)
if self.alias:
self.env.AlwaysBuild(self.env.Alias(self.alias, node))
return node
def Entry(self, name, directory = None, create = 1):
""" Create `SCons.Node.FS.Entry` """
return self._create_node(name, self.env.fs.Entry, directory, create)
def File(self, name, directory = None, create = 1):
""" Create `SCons.Node.FS.File` """
return self._create_node(name, self.env.fs.File, directory, create)
#############################################################################
#############################################################################
_re_comment = re.compile(r'(#[^\n\r]+)$', re.M)
_re_lang = re.compile(r'([a-zA-Z0-9_]+)', re.M)
#############################################################################
def _read_linguas_from_files(env, linguas_files = None):
""" Parse `LINGUAS` file and return list of extracted languages """
import SCons.Util
import SCons.Environment
global _re_comment
global _re_lang
if not SCons.Util.is_List(linguas_files) \
and not SCons.Util.is_String(linguas_files) \
and not isinstance(linguas_files, SCons.Node.FS.Base) \
and linguas_files:
# If, linguas_files==True or such, then read 'LINGUAS' file.
linguas_files = [ 'LINGUAS' ]
if linguas_files is None:
return []
fnodes = env.arg2nodes(linguas_files)
linguas = []
for fnode in fnodes:
contents = _re_comment.sub("", fnode.get_text_contents())
ls = [ l for l in _re_lang.findall(contents) if l ]
linguas.extend(ls)
return linguas
#############################################################################
#############################################################################
from SCons.Builder import BuilderBase
#############################################################################
class _POFileBuilder(BuilderBase):
""" `PO` file builder.
This is multi-target single-source builder. In typical situation the source
is single `POT` file, e.g. `messages.pot`, and there are multiple `PO`
targets to be updated from this `POT`. We must run
`SCons.Builder.BuilderBase._execute()` separatelly for each target to track
dependencies separatelly for each target file.
**NOTE**: if we call `SCons.Builder.BuilderBase._execute(.., target, ...)`
with target being list of all targets, all targets would be rebuilt each time
one of the targets from this list is missing. This would happen, for example,
when new language `ll` enters `LINGUAS_FILE` (at this moment there is no
`ll.po` file yet). To avoid this, we override
`SCons.Builder.BuilerBase._execute()` and call it separatelly for each
target. Here we also append to the target list the languages read from
`LINGUAS_FILE`.
"""
#
#* The argument for overriding _execute(): We must use environment with
# builder overrides applied (see BuilderBase.__init__(). Here it comes for
# free.
#* The argument against using 'emitter': The emitter is called too late
# by BuilderBase._execute(). If user calls, for example:
#
# env.POUpdate(LINGUAS_FILE = 'LINGUAS')
#
# the builder throws error, because it is called with target=None,
# source=None and is trying to "generate" sources or target list first.
# If user calls
#
# env.POUpdate(['foo', 'baz'], LINGUAS_FILE = 'LINGUAS')
#
# the env.BuilderWrapper() calls our builder with target=None,
# source=['foo', 'baz']. The BuilderBase._execute() then splits execution
# and execute iterativelly (recursion) self._execute(None, source[i]).
# After that it calls emitter (which is quite too late). The emitter is
# also called in each iteration, what makes things yet worse.
def __init__(self, env, **kw):
if not 'suffix' in kw:
kw['suffix'] = '$POSUFFIX'
if not 'src_suffix' in kw:
kw['src_suffix'] = '$POTSUFFIX'
if not 'src_builder' in kw:
kw['src_builder'] = '_POTUpdateBuilder'
if not 'single_source' in kw:
kw['single_source'] = True
alias = None
if 'target_alias' in kw:
alias = kw['target_alias']
del kw['target_alias']
if not 'target_factory' in kw:
kw['target_factory'] = _POTargetFactory(env, alias=alias).File
BuilderBase.__init__(self, **kw)
def _execute(self, env, target, source, *args, **kw):
""" Execute builder's actions.
Here we append to `target` the languages read from `$LINGUAS_FILE` and
apply `SCons.Builder.BuilderBase._execute()` separatelly to each target.
The arguments and return value are same as for
`SCons.Builder.BuilderBase._execute()`.
"""
import SCons.Util
import SCons.Node
linguas_files = None
if env.has_key('LINGUAS_FILE') and env['LINGUAS_FILE']:
linguas_files = env['LINGUAS_FILE']
# This prevents endless recursion loop (we'll be invoked once for
# each target appended here, we must not extend the list again).
env['LINGUAS_FILE'] = None
linguas = _read_linguas_from_files(env,linguas_files)
if SCons.Util.is_List(target):
target.extend(linguas)
elif target is not None:
target = [target] + linguas
else:
target = linguas
if not target:
# Let the SCons.BuilderBase to handle this patologic situation
return BuilderBase._execute( self, env, target, source, *args, **kw)
# The rest is ours
if not SCons.Util.is_List(target):
target = [ target ]
result = []
for tgt in target:
r = BuilderBase._execute( self, env, [tgt], source, *args, **kw)
result.extend(r)
if linguas_files is not None:
env['LINGUAS_FILE'] = linguas_files
return SCons.Node.NodeList(result)
#############################################################################
import SCons.Environment
#############################################################################
def _translate(env, target=None, source=SCons.Environment._null, *args, **kw):
""" Function for `Translate()` pseudo-builder """
if target is None: target = []
pot = env.POTUpdate(None, source, *args, **kw)
po = env.POUpdate(target, pot, *args, **kw)
return po
#############################################################################
#############################################################################
class RPaths(object):
""" Callable object, which returns pathnames relative to SCons current
working directory.
It seems like `SCons.Node.FS.Base.get_path()` returns absolute paths
for nodes that are outside of current working directory (`env.fs.getcwd()`).
Here, we often have `SConscript`, `POT` and `PO` files within `po/`
directory and source files (e.g. `*.c`) outside of it. When generating `POT`
template file, references to source files are written to `POT` template, so
a translator may later quickly jump to appropriate source file and line from
its `PO` editor (e.g. `poedit`). Relative paths in `PO` file are usually
interpreted by `PO` editor as paths relative to the place, where `PO` file
lives. The absolute paths would make resultant `POT` file nonportable, as
the references would be correct only on the machine, where `POT` file was
recently re-created. For such reason, we need a function, which always
returns relative paths. This is the purpose of `RPaths` callable object.
The `__call__` method returns paths relative to current woking directory, but
we assume, that *xgettext(1)* is run from the directory, where target file is
going to be created.
Note, that this may not work for files distributed over several hosts or
across different drives on windows. We assume here, that single local
filesystem holds both source files and target `POT` templates.
Intended use of `RPaths` - in `xgettext.py`::
def generate(env):
from GettextCommon import RPaths
...
sources = '$( ${_concat( "", SOURCES, "", __env__, XgettextRPaths, TARGET, SOURCES)} $)'
env.Append(
...
XGETTEXTCOM = 'XGETTEXT ... ' + sources,
...
XgettextRPaths = RPaths(env)
)
"""
# NOTE: This callable object returns pathnames of dirs/files relative to
# current working directory. The pathname remains relative also for entries
# that are outside of current working directory (node, that
# SCons.Node.FS.File and siblings return absolute path in such case). For
# simplicity we compute path relative to current working directory, this
# seems be enough for our purposes (don't need TARGET variable and
# SCons.Defaults.Variable_Caller stuff).
def __init__(self, env):
""" Initialize `RPaths` callable object.
**Arguments**:
- *env* - a `SCons.Environment.Environment` object, defines *current
working dir*.
"""
self.env = env
# FIXME: I'm not sure, how it should be implemented (what the *args are in
# general, what is **kw).
def __call__(self, nodes, *args, **kw):
""" Return nodes' paths (strings) relative to current working directory.
**Arguments**:
- *nodes* ([`SCons.Node.FS.Base`]) - list of nodes.
- *args* - currently unused.
- *kw* - currently unused.
**Returns**:
- Tuple of strings, which represent paths relative to current working
directory (for given environment).
"""
# os.path.relpath is available only on python >= 2.6. We use our own
# implementation. It's taken from BareNecessities package:
# http://jimmyg.org/work/code/barenecessities/index.html
from posixpath import curdir
def relpath(path, start=curdir):
import posixpath
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
start_list = posixpath.abspath(start).split(posixpath.sep)
path_list = posixpath.abspath(path).split(posixpath.sep)
# Work out how much of the filepath is shared by start and path.
i = len(posixpath.commonprefix([start_list, path_list]))
rel_list = [posixpath.pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return posixpath.curdir
return posixpath.join(*rel_list)
import os
import SCons.Node.FS
rpaths = ()
cwd = self.env.fs.getcwd().get_abspath()
for node in nodes:
rpath = None
if isinstance(node, SCons.Node.FS.Base):
rpath = relpath(node.get_abspath(), cwd)
# FIXME: Other types possible here?
if rpath is not None:
rpaths += (rpath,)
return rpaths
#############################################################################
#############################################################################
def _init_po_files(target, source, env):
""" Action function for `POInit` builder. """
nop = lambda target, source, env : 0
if env.has_key('POAUTOINIT'):
autoinit = env['POAUTOINIT']
else:
autoinit = False
# Well, if everything outside works well, this loop should do single
# iteration. Otherwise we are rebuilding all the targets even, if just
# one has changed (but is this out fault?).
for tgt in target:
if not tgt.exists():
if autoinit:
action = SCons.Action.Action('$MSGINITCOM', '$MSGINITCOMSTR')
else:
msg = 'File ' + repr(str(tgt)) + ' does not exist. ' \
+ 'If you are a translator, you can create it through: \n' \
+ '$MSGINITCOM'
action = SCons.Action.Action(nop, msg)
status = action([tgt], source, env)
if status: return status
return 0
#############################################################################
#############################################################################
def _detect_xgettext(env):
""" Detects *xgettext(1)* binary """
if env.has_key('XGETTEXT'):
return env['XGETTEXT']
xgettext = env.Detect('xgettext');
if xgettext:
return xgettext
raise SCons.Errors.StopError(XgettextNotFound,"Could not detect xgettext")
return None
#############################################################################
def _xgettext_exists(env):
return _detect_xgettext(env)
#############################################################################
#############################################################################
def _detect_msginit(env):
""" Detects *msginit(1)* program. """
if env.has_key('MSGINIT'):
return env['MSGINIT']
msginit = env.Detect('msginit');
if msginit:
return msginit
raise SCons.Errors.StopError(MsginitNotFound, "Could not detect msginit")
return None
#############################################################################
def _msginit_exists(env):
return _detect_msginit(env)
#############################################################################
#############################################################################
def _detect_msgmerge(env):
""" Detects *msgmerge(1)* program. """
if env.has_key('MSGMERGE'):
return env['MSGMERGE']
msgmerge = env.Detect('msgmerge');
if msgmerge:
return msgmerge
raise SCons.Errors.StopError(MsgmergeNotFound, "Could not detect msgmerge")
return None
#############################################################################
def _msgmerge_exists(env):
return _detect_msgmerge(env)
#############################################################################
#############################################################################
def _detect_msgfmt(env):
""" Detects *msgmfmt(1)* program. """
if env.has_key('MSGFMT'):
return env['MSGFMT']
msgfmt = env.Detect('msgfmt');
if msgfmt:
return msgfmt
raise SCons.Errors.StopError(MsgfmtNotFound, "Could not detect msgfmt")
return None
#############################################################################
def _msgfmt_exists(env):
return _detect_msgfmt(env)
#############################################################################
#############################################################################
def tool_list(platform, env):
""" List tools that shall be generated by top-level `gettext` tool """
return [ 'xgettext', 'msginit', 'msgmerge', 'msgfmt' ]
#############################################################################
| {
"content_hash": "ee6bc5f00e8dfc0fdde5611d2d9c7a77",
"timestamp": "",
"source": "github",
"line_count": 430,
"max_line_length": 96,
"avg_line_length": 42.00232558139535,
"alnum_prop": 0.588837827362826,
"repo_name": "Distrotech/scons",
"id": "cd2f306cf0d518158151d9dee2d4ba580c72dce0",
"size": "18061",
"binary": false,
"copies": "3",
"ref": "refs/heads/distrotech-scons",
"path": "src/engine/SCons/Tool/GettextCommon.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "259"
},
{
"name": "JavaScript",
"bytes": "17316"
},
{
"name": "Perl",
"bytes": "45214"
},
{
"name": "Python",
"bytes": "12517068"
},
{
"name": "Shell",
"bytes": "20589"
}
],
"symlink_target": ""
} |
"""
WSGI config for icecream_project project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
from os.path import abspath, dirname
from sys import path
SITE_ROOT = dirname(dirname(abspath(__file__)))
path.append(SITE_ROOT)
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "jajaja.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "icecream_project.settings.production")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
| {
"content_hash": "2b3671d99194ecc99eeacac3b6acd00d",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 87,
"avg_line_length": 42.7027027027027,
"alnum_prop": 0.7917721518987342,
"repo_name": "resalisbury/twoscoops",
"id": "8b6b34a66caaa1f96a30306a13c12910b4f18ea0",
"size": "1580",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "icecream_project/icecream_project/wsgi.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "39"
},
{
"name": "HTML",
"bytes": "2830"
},
{
"name": "JavaScript",
"bytes": "45"
},
{
"name": "Python",
"bytes": "14661"
}
],
"symlink_target": ""
} |
import datetime
from vcms.www.managers import ContentManager
from django.utils.translation import ugettext_lazy as _
from django.db import models
from django.contrib.auth.models import User
from vcms.www.models.page import BasicPage
from site_language.models import Language
# -- CONTENT
# ----------
class Content(models.Model):
#CONTENT
name = models.CharField(max_length="40", help_text="Max 40 characters")
excerpt = models.TextField(verbose_name="Preview")
content = models.TextField()
published = models.BooleanField(default=False)
#position
POSITION_HELP_TEXT = _("Supported value are 'Default', px, em or %")
width = models.CharField(max_length="40", default='Default', help_text=POSITION_HELP_TEXT)
height = models.CharField(max_length="40", default='Default', help_text=POSITION_HELP_TEXT)
margin_top = models.CharField(max_length="40", default='Default', help_text=POSITION_HELP_TEXT)
margin_left = models.CharField(max_length="40", default='Default', help_text=POSITION_HELP_TEXT)
position = models.IntegerField(default=5, help_text="Priority to display. 0=top, 9=bottom")
#appearance
TEXT_ONLY = 0
BOXED = 1
DARK = 2
AVAILABLE_STYLES = ((TEXT_ONLY, _('Text only'))
,(BOXED, _('Box'))
,(DARK, _('Bright text on dark background'))
)
style = models.IntegerField(default=TEXT_ONLY, choices=AVAILABLE_STYLES)
minimized = models.BooleanField(default=False, choices=((True, _('Minimized')),(False, _('Show'))))
#INFORMATION
date = models.DateField(auto_now=True, editable=True)
author = models.ForeignKey(User, editable=False, null=True, blank=True)
#page = models.ForeignKey(BasicPage)
objects = ContentManager()
class Meta:
verbose_name_plural = "Page content"
ordering = [ 'position', 'date']
app_label = "www"
def __unicode__(self):
return self.name
def get_absolute_url(self):
self.page.get_absolute_url()
| {
"content_hash": "2cd39fa1aeb494696233ff1205488188",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 103,
"avg_line_length": 35.12068965517241,
"alnum_prop": 0.6666666666666666,
"repo_name": "francisl/vcms",
"id": "e931b5b5a8bb98fb4e0122fb097d7b8d8d2684a8",
"size": "2156",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/vcms/www/models/old.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "1125438"
},
{
"name": "Perl",
"bytes": "696"
},
{
"name": "Python",
"bytes": "197188"
},
{
"name": "Shell",
"bytes": "3588"
}
],
"symlink_target": ""
} |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Invoice.date_of_issue'
db.alter_column('books_invoice', 'date_of_issue', self.gf('django.db.models.fields.DateTimeField')())
def backwards(self, orm):
# Changing field 'Invoice.date_of_issue'
db.alter_column('books_invoice', 'date_of_issue', self.gf('django.db.models.fields.DateField')())
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'books.category': {
'Meta': {'object_name': 'Category'},
'description': ('django.db.models.fields.CharField', [], {'max_length': '140'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'books.client': {
'Meta': {'object_name': 'Client'},
'city': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'country': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '100'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'organization_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'phone': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'postal_code': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'state': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'street_adress': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'})
},
'books.expense': {
'Meta': {'object_name': 'Expense'},
'amount': ('django.db.models.fields.DecimalField', [], {'max_digits': '8', 'decimal_places': '2'}),
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'category': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['books.Category']", 'null': 'True', 'blank': 'True'}),
'client': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['books.Client']", 'null': 'True', 'blank': 'True'}),
'date': ('django.db.models.fields.DateField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'notes': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'null': 'True', 'blank': 'True'}),
'receipt': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'taxes': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['books.Tax']", 'null': 'True', 'blank': 'True'}),
'vendor': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['books.Vendor']", 'null': 'True', 'blank': 'True'})
},
'books.invoice': {
'Meta': {'object_name': 'Invoice'},
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'client': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['books.Client']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_of_issue': ('django.db.models.fields.DateTimeField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'invoice_number': ('django.db.models.fields.PositiveIntegerField', [], {'blank': 'True'}),
'last_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}),
'notes': ('django.db.models.fields.CharField', [], {'max_length': '1000'}),
'paid_notes': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'blank': 'True'}),
'status': ('django.db.models.fields.CharField', [], {'default': "'Dr'", 'max_length': '2', 'null': 'True'}),
'sub_description': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}),
'sub_notes': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'blank': 'True'}),
'terms': ('django.db.models.fields.CharField', [], {'max_length': '1000'})
},
'books.item': {
'Meta': {'object_name': 'Item'},
'client': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['books.Client']", 'null': 'True'}),
'cost': ('django.db.models.fields.DecimalField', [], {'max_digits': '8', 'decimal_places': '2'}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'quantity': ('django.db.models.fields.PositiveIntegerField', [], {'blank': 'True'})
},
'books.project': {
'Meta': {'object_name': 'Project'},
'client': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['books.Client']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'rate_per_hour': ('django.db.models.fields.DecimalField', [], {'max_digits': '5', 'decimal_places': '2'})
},
'books.report': {
'Meta': {'object_name': 'Report'},
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'end_date': ('django.db.models.fields.DateField', [], {}),
'expense': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'invoice': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'start_date': ('django.db.models.fields.DateField', [], {}),
'taxes': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'timesheet': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
'books.task': {
'Meta': {'object_name': 'Task'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['books.Project']"}),
'rate_per_hour': ('django.db.models.fields.DecimalField', [], {'max_digits': '5', 'decimal_places': '2'})
},
'books.tax': {
'Meta': {'object_name': 'Tax'},
'compound_tax': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'gouv_number': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'number': ('django.db.models.fields.PositiveIntegerField', [], {}),
'rate': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2', 'blank': 'True'})
},
'books.time': {
'Meta': {'object_name': 'Time'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'invoice': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['books.Invoice']", 'null': 'True', 'blank': 'True'}),
'notes': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '1000', 'blank': 'True'}),
'rate_per_hour': ('django.db.models.fields.DecimalField', [], {'max_digits': '5', 'decimal_places': '2'}),
'task': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['books.Task']", 'null': 'True', 'blank': 'True'}),
'time': ('django.db.models.fields.DecimalField', [], {'max_digits': '5', 'decimal_places': '2', 'blank': 'True'})
},
'books.vendor': {
'Meta': {'object_name': 'Vendor'},
'description': ('django.db.models.fields.CharField', [], {'max_length': '140'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['books'] | {
"content_hash": "e3e3d2d10868e754274913600d1ce523",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 182,
"avg_line_length": 74.49397590361446,
"alnum_prop": 0.5384117742196345,
"repo_name": "carquois/blobon",
"id": "a4096c28d50c8fd79e87710e076fb77390c3ef71",
"size": "12390",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "blobon/books/migrations/0028_auto__chg_field_invoice_date_of_issue.py",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
"""Queues api module"""
from src.core import storage
from .helpers import *
class Api:
"""Api root class"""
def __init__(self):
self.queues = Queues()
def config(self):
queues_routes = cherrypy.dispatch.RoutesDispatcher()
queues_routes.explicit = False
queues_routes.connect("queues_list", "/queues", self.queues, action='list')
queues_routes.connect("queues_actions", "/queues/{name}/{action}", self.queues)
queues_routes.connect("queues_msg_body", "/queues/{name}/{msg_id}/body", self.queues, action='msg_body')
return {
'/queues': {
'request.dispatch': queues_routes,
'cors.expose.on': True
}
}
@cherrypy.expose
@cherrypy.tools.json_out()
class Queues:
"""Queues class"""
def list(self):
if cherrypy.request.method != 'GET':
return method_not_allowed()
return ok(storage.Queues.get_all())
def details(self, name):
if cherrypy.request.method != 'GET':
return method_not_allowed()
queue = storage.Queues.get(name)
if queue:
return ok(queue)
return not_found()
def delete(self, name):
if cherrypy.request.method != 'DELETE':
return method_not_allowed()
if storage.Queues.delete(name):
return ok({})
return not_found()
def messages(self, name):
if cherrypy.request.method != 'GET':
return method_not_allowed()
queue = storage.Queues.get(name)
if queue:
return ok(storage.Queues.get_head_msgs(name))
return not_found()
def msg_body(self, name, msg_id):
if cherrypy.request.method != 'GET':
return method_not_allowed()
body = storage.Queues.get_msg_body(name, msg_id)
if body:
cherrypy.response.headers['Content-Type'] = 'text/plain'
return body
return not_found()
@cherrypy.tools.json_in()
def put(self, name):
if cherrypy.request.method != 'PUT':
return method_not_allowed()
data = cherrypy.request.json
if 'application' not in data:
return bad_request({'code': ErrorCodes.APPLICATION_REQUIRED})
if 'body' not in data:
return bad_request({'code': ErrorCodes.BODY_REQUIRED})
add_result = storage.Queues.add_msg(name, data['application'], data['body'])
channel = "queue-%s-put" % name
cherrypy.engine.publish(channel)
return created(add_result)
| {
"content_hash": "89e52d3c5d84f6095814355144198455",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 112,
"avg_line_length": 31.048192771084338,
"alnum_prop": 0.5801319363601086,
"repo_name": "meeron/norimq",
"id": "ac236536c5fd3ce05146e7a1d1f826c117f9b75b",
"size": "2577",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/api/apiroot.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "95"
},
{
"name": "Python",
"bytes": "27149"
}
],
"symlink_target": ""
} |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from protobuf import types_pb2 as protobuf_dot_types__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='protobuf/identification.proto',
package='data',
syntax='proto2',
serialized_pb=_b('\n\x1dprotobuf/identification.proto\x12\x04\x64\x61ta\x1a\x14protobuf/types.proto\"\x83\x01\n\x0cPbIdentifier\x12\x14\n\x0c\x65\x63osystem_id\x18\x01 \x02(\x04\x12\"\n\x07\x63reated\x18\x02 \x02(\x0b\x32\x11.PbSystemDateTime\x12(\n\rlast_modified\x18\x03 \x02(\x0b\x32\x11.PbSystemDateTime\x12\x0f\n\x07\x64\x65leted\x18\x04 \x01(\x08')
,
dependencies=[protobuf_dot_types__pb2.DESCRIPTOR,])
_PBIDENTIFIER = _descriptor.Descriptor(
name='PbIdentifier',
full_name='data.PbIdentifier',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='ecosystem_id', full_name='data.PbIdentifier.ecosystem_id', index=0,
number=1, type=4, cpp_type=4, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='created', full_name='data.PbIdentifier.created', index=1,
number=2, type=11, cpp_type=10, label=2,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='last_modified', full_name='data.PbIdentifier.last_modified', index=2,
number=3, type=11, cpp_type=10, label=2,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='deleted', full_name='data.PbIdentifier.deleted', index=3,
number=4, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=62,
serialized_end=193,
)
_PBIDENTIFIER.fields_by_name['created'].message_type = protobuf_dot_types__pb2._PBSYSTEMDATETIME
_PBIDENTIFIER.fields_by_name['last_modified'].message_type = protobuf_dot_types__pb2._PBSYSTEMDATETIME
DESCRIPTOR.message_types_by_name['PbIdentifier'] = _PBIDENTIFIER
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
PbIdentifier = _reflection.GeneratedProtocolMessageType('PbIdentifier', (_message.Message,), dict(
DESCRIPTOR = _PBIDENTIFIER,
__module__ = 'protobuf.identification_pb2'
# @@protoc_insertion_point(class_scope:data.PbIdentifier)
))
_sym_db.RegisterMessage(PbIdentifier)
# @@protoc_insertion_point(module_scope)
| {
"content_hash": "14e14b538253e4c868798d5065bbf06a",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 356,
"avg_line_length": 37.08791208791209,
"alnum_prop": 0.7235555555555555,
"repo_name": "esno/polartray",
"id": "c39f327ae5d40c45eb49b6ca498ea2ba307c725b",
"size": "3475",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/protobuf/identification_pb2.py",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
r"""Replace variables in InfoPlist.strings with file.
% python tweak_info_plist_strings.py --output=out.txt --input=in.txt \
--branding=Mozc
"""
import codecs
import datetime
import logging
import optparse
import sys
from build_tools import tweak_data
_COPYRIGHT_YEAR = datetime.date.today().year
def ParseOptions():
"""Parse command line options.
Returns:
An options data.
"""
parser = optparse.OptionParser()
parser.add_option('--output', dest='output')
parser.add_option('--input', dest='input')
parser.add_option('--branding', dest='branding')
(options, unused_args) = parser.parse_args()
return options
def main():
"""The main function."""
options = ParseOptions()
if options.output is None:
logging.error('--output is not specified.')
sys.exit(-1)
if options.input is None:
logging.error('--input is not specified.')
sys.exit(-1)
if options.branding is None:
logging.error('--branding is not specified.')
sys.exit(-1)
copyright_message = '© %d Google Inc.' % _COPYRIGHT_YEAR
if options.branding == 'GoogleJapaneseInput':
variables = {
'CF_BUNDLE_NAME_EN': 'Google Japanese Input',
'CF_BUNDLE_NAME_JA': 'Google 日本語入力',
'NS_HUMAN_READABLE_COPYRIGHT': copyright_message,
'INPUT_MODE_ANNOTATION': 'Google',
}
else:
variables = {
'CF_BUNDLE_NAME_EN': 'Mozc',
'CF_BUNDLE_NAME_JA': 'Mozc',
'NS_HUMAN_READABLE_COPYRIGHT': copyright_message,
'INPUT_MODE_ANNOTATION': 'Mozc',
}
codecs.open(options.output, 'w', encoding='utf-8').write(
tweak_data.ReplaceVariables(
codecs.open(options.input, encoding='utf-8').read(), variables))
if __name__ == '__main__':
main()
| {
"content_hash": "347ce04689c7f86177dda2d6745dbfb4",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 74,
"avg_line_length": 26.134328358208954,
"alnum_prop": 0.6436322101656197,
"repo_name": "fcitx/mozc",
"id": "f659a99db01a62916ba4f20a35e6508c1a59e05f",
"size": "3320",
"binary": false,
"copies": "2",
"ref": "refs/heads/fcitx",
"path": "src/build_tools/tweak_info_plist_strings.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "69980"
},
{
"name": "C++",
"bytes": "11468671"
},
{
"name": "Dockerfile",
"bytes": "3319"
},
{
"name": "Emacs Lisp",
"bytes": "80236"
},
{
"name": "HTML",
"bytes": "60487"
},
{
"name": "Objective-C",
"bytes": "39737"
},
{
"name": "Objective-C++",
"bytes": "211656"
},
{
"name": "Python",
"bytes": "953072"
},
{
"name": "Shell",
"bytes": "13316"
},
{
"name": "Starlark",
"bytes": "538427"
},
{
"name": "Yacc",
"bytes": "1967"
}
],
"symlink_target": ""
} |
import httplib2
import gspread
import os
import praw
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
# https://github.com/burnash/gspread
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly https://spreadsheets.google.com/feeds https://docs.google.com/feeds'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Drive API Python Quickstart'
LOSEIT_ID = '1-EKK8u-6lP7eaaMSmuPeadhg44rgyhkf0EMXPo7wHgw'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'drive-python-quickstart.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
credentials = tools.run(flow, store)
return credentials
def main():
credentials = get_credentials()
credentials.authorize(httplib2.Http())
gc = gspread.authorize(credentials)
r = praw.Reddit(user_agent='Send message to loseit weight loss challenge subscribers who have not weighed in by /u/jeffles2')
username = input('Enter your reddit username: ')
password = input('Enter your password: ')
r.login(username, password, disable_warning=True)
sheet = gc.open("Spring into Summer Challenge")
wks = sheet.get_worksheet(1)
c3_name_list = wks.range('C2:C3500')
upper_name_list = []
for i in range(len(c3_name_list)):
name = c3_name_list[i].value
if not name:
continue
if name.upper() in upper_name_list:
continue
upper_name_list.append(name.upper().strip())
print(len(upper_name_list), " have registered already")
messages = r.get_content('https://www.reddit.com/message/sent/', '', 1000)
total = 0
enrolled = 0
for message in messages:
total += 1
if message.dest.upper() in upper_name_list:
enrolled += 1
continue
upper_name_list.append(message.dest.upper().strip())
print("I sent ", total, " message and ", enrolled, " enrolled")
if __name__ == '__main__':
main()
| {
"content_hash": "117ab1b7916839f18d818844ebe580b6",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 134,
"avg_line_length": 33.5,
"alnum_prop": 0.6712686567164179,
"repo_name": "jeffles/LI",
"id": "999c5e3ad7cae79c5da5ad99837043a749a854fe",
"size": "2680",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PercentEnrolled.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "76593"
}
],
"symlink_target": ""
} |
import random
from django.conf import settings
from django.contrib.auth.models import AnonymousUser, Group, User
from django.db import connection
import mock
from nose.tools import eq_
from test_utils import RequestFactory
from test_app import views
import waffle
from waffle.middleware import WaffleMiddleware
from waffle.models import Flag, Sample, Switch
from waffle.tests.base import TestCase
def get(**kw):
request = RequestFactory().get('/foo', data=kw)
request.user = AnonymousUser()
return request
def process_request(request, view):
response = view(request)
return WaffleMiddleware().process_response(request, response)
class WaffleTests(TestCase):
def test_persist_active_flag(self):
Flag.objects.create(name='myflag', percent='0.1')
request = get()
# Flag stays on.
request.COOKIES['dwf_myflag'] = 'True'
response = process_request(request, views.flag_in_view)
eq_('on', response.content)
assert 'dwf_myflag' in response.cookies
eq_('True', response.cookies['dwf_myflag'].value)
def test_persist_inactive_flag(self):
Flag.objects.create(name='myflag', percent='99.9')
request = get()
# Flag stays off.
request.COOKIES['dwf_myflag'] = 'False'
response = process_request(request, views.flag_in_view)
eq_('off', response.content)
assert 'dwf_myflag' in response.cookies
eq_('False', response.cookies['dwf_myflag'].value)
def test_no_set_unused_flag(self):
"""An unused flag shouldn't have its cookie reset."""
request = get()
request.COOKIES['dwf_unused'] = 'True'
response = process_request(request, views.flag_in_view)
assert not 'dwf_unused' in response.cookies
def test_superuser(self):
"""Test the superuser switch."""
Flag.objects.create(name='myflag', superusers=True)
request = get()
response = process_request(request, views.flag_in_view)
eq_('off', response.content)
assert not 'dwf_myflag' in response.cookies
superuser = User(username='foo', is_superuser=True)
request.user = superuser
response = process_request(request, views.flag_in_view)
eq_('on', response.content)
assert not 'dwf_myflag' in response.cookies
non_superuser = User(username='bar', is_superuser=False)
non_superuser.save()
request.user = non_superuser
response = process_request(request, views.flag_in_view)
eq_('off', response.content)
assert not 'dwf_myflag' in response.cookies
def test_staff(self):
"""Test the staff switch."""
Flag.objects.create(name='myflag', staff=True)
request = get()
response = process_request(request, views.flag_in_view)
eq_('off', response.content)
assert not 'dwf_myflag' in response.cookies
staff = User(username='foo', is_staff=True)
request.user = staff
response = process_request(request, views.flag_in_view)
eq_('on', response.content)
assert not 'dwf_myflag' in response.cookies
non_staff = User(username='foo', is_staff=False)
non_staff.save()
request.user = non_staff
response = process_request(request, views.flag_in_view)
eq_('off', response.content)
assert not 'dwf_myflag' in response.cookies
def test_languages(self):
Flag.objects.create(name='myflag', languages='en,fr')
request = get()
response = process_request(request, views.flag_in_view)
eq_('off', response.content)
request.LANGUAGE_CODE = 'en'
response = process_request(request, views.flag_in_view)
eq_('on', response.content)
request.LANGUAGE_CODE = 'de'
response = process_request(request, views.flag_in_view)
eq_('off', response.content)
def test_user(self):
"""Test the per-user switch."""
user = User.objects.create(username='foo')
flag = Flag.objects.create(name='myflag')
flag.users.add(user)
request = get()
request.user = user
response = process_request(request, views.flag_in_view)
eq_('on', response.content)
assert not 'dwf_myflag' in response.cookies
request.user = User.objects.create(username='someone_else')
response = process_request(request, views.flag_in_view)
eq_('off', response.content)
assert not 'dwf_myflag' in response.cookies
def test_group(self):
"""Test the per-group switch."""
group = Group.objects.create(name='foo')
user = User.objects.create(username='bar')
user.groups.add(group)
flag = Flag.objects.create(name='myflag')
flag.groups.add(group)
request = get()
request.user = user
response = process_request(request, views.flag_in_view)
eq_('on', response.content)
assert not 'dwf_myflag' in response.cookies
request.user = User(username='someone_else')
request.user.save()
response = process_request(request, views.flag_in_view)
eq_('off', response.content)
assert not 'dwf_myflag' in response.cookies
def test_authenticated(self):
"""Test the authenticated/anonymous switch."""
Flag.objects.create(name='myflag', authenticated=True)
request = get()
response = process_request(request, views.flag_in_view)
eq_('off', response.content)
assert not 'dwf_myflag' in response.cookies
request.user = User(username='foo')
assert request.user.is_authenticated()
response = process_request(request, views.flag_in_view)
eq_('on', response.content)
assert not 'dwf_myflag' in response.cookies
def test_everyone_on(self):
"""Test the 'everyone' switch on."""
Flag.objects.create(name='myflag', everyone=True)
request = get()
request.COOKIES['dwf_myflag'] = 'False'
response = process_request(request, views.flag_in_view)
eq_('on', response.content)
assert not 'dwf_myflag' in response.cookies
request.user = User(username='foo')
assert request.user.is_authenticated()
response = process_request(request, views.flag_in_view)
eq_('on', response.content)
assert not 'dwf_myflag' in response.cookies
def test_everyone_off(self):
"""Test the 'everyone' switch off."""
Flag.objects.create(name='myflag', everyone=False,
authenticated=True)
request = get()
request.COOKIES['dwf_myflag'] = 'True'
response = process_request(request, views.flag_in_view)
eq_('off', response.content)
assert not 'dwf_myflag' in response.cookies
request.user = User(username='foo')
assert request.user.is_authenticated()
response = process_request(request, views.flag_in_view)
eq_('off', response.content)
assert not 'dwf_myflag' in response.cookies
def test_percent(self):
"""If you have no cookie, you get a cookie!"""
Flag.objects.create(name='myflag', percent='50.0')
request = get()
response = process_request(request, views.flag_in_view)
assert 'dwf_myflag' in response.cookies
@mock.patch.object(random, 'uniform')
def test_reroll(self, uniform):
"""Even without a cookie, calling flag_is_active twice should return
the same value."""
Flag.objects.create(name='myflag', percent='50.0')
# Make sure we're not really random.
request = get() # Create a clean request.
assert not hasattr(request, 'waffles')
uniform.return_value = '10' # < 50. Flag is True.
assert waffle.flag_is_active(request, 'myflag')
assert hasattr(request, 'waffles') # We should record this flag.
assert 'myflag' in request.waffles
assert request.waffles['myflag'][0]
uniform.return_value = '70' # > 50. Normally, Flag would be False.
assert waffle.flag_is_active(request, 'myflag')
assert request.waffles['myflag'][0]
def test_undefined(self):
"""Undefined flags are always false."""
request = get()
assert not waffle.flag_is_active(request, 'foo')
@mock.patch.object(settings._wrapped, 'WAFFLE_FLAG_DEFAULT', True)
def test_undefined_default(self):
"""WAFFLE_FLAG_DEFAULT controls undefined flags."""
request = get()
assert waffle.flag_is_active(request, 'foo')
@mock.patch.object(settings._wrapped, 'WAFFLE_OVERRIDE', True)
def test_override(self):
request = get(foo='1')
Flag.objects.create(name='foo') # Off for everyone.
assert waffle.flag_is_active(request, 'foo')
def test_testing_flag(self):
Flag.objects.create(name='foo', testing=True)
request = get(dwft_foo='1')
assert waffle.flag_is_active(request, 'foo')
assert 'foo' in request.waffle_tests
assert request.waffle_tests['foo']
# GET param should override cookie
request = get(dwft_foo='0')
request.COOKIES['dwft_foo'] = 'True'
assert not waffle.flag_is_active(request, 'foo')
assert 'foo' in request.waffle_tests
assert not request.waffle_tests['foo']
def test_testing_disabled_flag(self):
Flag.objects.create(name='foo')
request = get(dwft_foo='1')
assert not waffle.flag_is_active(request, 'foo')
assert not hasattr(request, 'waffle_tests')
request = get(dwft_foo='0')
assert not waffle.flag_is_active(request, 'foo')
assert not hasattr(request, 'waffle_tests')
def test_set_then_unset_testing_flag(self):
Flag.objects.create(name='myflag', testing=True)
response = self.client.get('/flag_in_view?dwft_myflag=1')
eq_('on', response.content)
response = self.client.get('/flag_in_view')
eq_('on', response.content)
response = self.client.get('/flag_in_view?dwft_myflag=0')
eq_('off', response.content)
response = self.client.get('/flag_in_view')
eq_('off', response.content)
response = self.client.get('/flag_in_view?dwft_myflag=1')
eq_('on', response.content)
class SwitchTests(TestCase):
def test_switch_active(self):
switch = Switch.objects.create(name='myswitch', active=True)
assert waffle.switch_is_active(switch.name)
def test_switch_inactive(self):
switch = Switch.objects.create(name='myswitch', active=False)
assert not waffle.switch_is_active(switch.name)
def test_switch_active_from_cache(self):
"""Do not make two queries for an existing active switch."""
switch = Switch.objects.create(name='myswitch', active=True)
# Get the value once so that it will be put into the cache
assert waffle.switch_is_active(switch.name)
queries = len(connection.queries)
assert waffle.switch_is_active(switch.name)
eq_(queries, len(connection.queries), 'We should only make one query.')
def test_switch_inactive_from_cache(self):
"""Do not make two queries for an existing inactive switch."""
switch = Switch.objects.create(name='myswitch', active=False)
# Get the value once so that it will be put into the cache
assert not waffle.switch_is_active(switch.name)
queries = len(connection.queries)
assert not waffle.switch_is_active(switch.name)
eq_(queries, len(connection.queries), 'We should only make one query.')
def test_undefined(self):
assert not waffle.switch_is_active('foo')
@mock.patch.object(settings._wrapped, 'WAFFLE_SWITCH_DEFAULT', True)
def test_undefined_default(self):
assert waffle.switch_is_active('foo')
@mock.patch.object(settings._wrapped, 'DEBUG', True)
def test_no_query(self):
"""Do not make two queries for a non-existent switch."""
assert not Switch.objects.filter(name='foo').exists()
queries = len(connection.queries)
assert not waffle.switch_is_active('foo')
assert len(connection.queries) > queries, 'We should make one query.'
queries = len(connection.queries)
assert not waffle.switch_is_active('foo')
eq_(queries, len(connection.queries), 'We should only make one query.')
class SampleTests(TestCase):
def test_sample_100(self):
sample = Sample.objects.create(name='sample', percent='100.0')
assert waffle.sample_is_active(sample.name)
def test_sample_0(self):
sample = Sample.objects.create(name='sample', percent='0.0')
assert not waffle.sample_is_active(sample.name)
def test_undefined(self):
assert not waffle.sample_is_active('foo')
@mock.patch.object(settings._wrapped, 'WAFFLE_SAMPLE_DEFAULT', True)
def test_undefined_default(self):
assert waffle.sample_is_active('foo')
| {
"content_hash": "5e9c6cccc2b9f7b12147c29e3fea1650",
"timestamp": "",
"source": "github",
"line_count": 344,
"max_line_length": 79,
"avg_line_length": 37.973837209302324,
"alnum_prop": 0.636454107019827,
"repo_name": "ekohl/django-waffle",
"id": "a3bbeee016339bb47f48282070a5fa80c9c11bc7",
"size": "13063",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "waffle/tests/test_waffle.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "1247"
},
{
"name": "Python",
"bytes": "113348"
}
],
"symlink_target": ""
} |
"""Commands that can be used to operate on explorations.
All functions here should be agnostic of how ExplorationModel objects are
stored in the database. In particular, the various query methods should
delegate to the Exploration model class. This will enable the exploration
storage model to be changed without affecting this module and others above it.
"""
from __future__ import annotations
import collections
import datetime
import io
import logging
import math
import os
import pprint
import zipfile
from core import android_validation_constants
from core import feconf
from core import utils
from core.constants import constants
from core.domain import activity_services
from core.domain import caching_services
from core.domain import classifier_services
from core.domain import draft_upgrade_services
from core.domain import email_manager
from core.domain import email_subscription_services
from core.domain import exp_domain
from core.domain import exp_fetchers
from core.domain import feedback_services
from core.domain import fs_domain
from core.domain import html_cleaner
from core.domain import html_validation_service
from core.domain import opportunity_services
from core.domain import param_domain
from core.domain import recommendations_services
from core.domain import rights_domain
from core.domain import rights_manager
from core.domain import search_services
from core.domain import state_domain
from core.domain import stats_services
from core.domain import taskqueue_services
from core.domain import user_services
from core.platform import models
datastore_services = models.Registry.import_datastore_services()
(exp_models, feedback_models, user_models) = models.Registry.import_models([
models.NAMES.exploration, models.NAMES.feedback, models.NAMES.user
])
# Name for the exploration search index.
SEARCH_INDEX_EXPLORATIONS = 'explorations'
# The maximum number of iterations allowed for populating the results of a
# search query.
MAX_ITERATIONS = 10
# NOTE TO DEVELOPERS: The get_story_ids_linked_to_explorations function was
# removed in #13021 as part of the migration to Apache Beam. Please refer to
# that PR if you need to reinstate it.
def is_exp_summary_editable(exp_summary, user_id=None):
"""Checks if a given user has permissions to edit the exploration.
Args:
exp_summary: ExplorationSummary. An ExplorationSummary domain object.
user_id: str. The id of the user whose permissions are being checked.
Returns:
bool. Whether the user has permissions to edit the exploration.
"""
return user_id is not None and (
user_id in exp_summary.editor_ids
or user_id in exp_summary.owner_ids
or exp_summary.community_owned)
# Query methods.
def get_exploration_titles_and_categories(exp_ids):
"""Returns exploration titles and categories for the given ids.
The result is a dict with exploration ids as keys. The corresponding values
are dicts with the keys 'title' and 'category'.
Any invalid exp_ids will not be included in the return dict. No error will
be raised.
Args:
exp_ids: list(str). A list of exploration ids of exploration domain
objects.
Returns:
dict. The keys are exploration ids and the corresponding values are
dicts with the keys 'title' and 'category'. Any invalid exploration
ids are excluded.
"""
explorations = [
(exp_fetchers.get_exploration_from_model(e) if e else None)
for e in exp_models.ExplorationModel.get_multi(exp_ids)]
result = {}
for exploration in explorations:
if exploration is None:
logging.error(
'Could not find exploration corresponding to id')
else:
result[exploration.id] = {
'title': exploration.title,
'category': exploration.category,
}
return result
def get_exploration_ids_matching_query(
query_string, categories, language_codes, offset=None):
"""Returns a list with all exploration ids matching the given search query
string, as well as a search offset for future fetches.
This method returns exactly feconf.SEARCH_RESULTS_PAGE_SIZE results if
there are at least that many, otherwise it returns all remaining results.
(If this behaviour does not occur, an error will be logged.) The method
also returns a search offset.
Args:
query_string: str. A search query string.
categories: list(str). The list of categories to query for. If it is
empty, no category filter is applied to the results. If it is not
empty, then a result is considered valid if it matches at least one
of these categories.
language_codes: list(str). The list of language codes to query for. If
it is empty, no language code filter is applied to the results. If
it is not empty, then a result is considered valid if it matches at
least one of these language codes.
offset: int or None. Optional offset from which to start the search
query. If no offset is supplied, the first N results matching
the query are returned.
Returns:
2-tuple of (returned_exploration_ids, search_offset). Where:
returned_exploration_ids : list(str). A list with all
exploration ids matching the given search query string,
as well as a search offset for future fetches.
The list contains exactly feconf.SEARCH_RESULTS_PAGE_SIZE
results if there are at least that many, otherwise it
contains all remaining results. (If this behaviour does
not occur, an error will be logged.)
search_offset: int. Search offset for future fetches.
"""
returned_exploration_ids = []
search_offset = offset
for _ in range(MAX_ITERATIONS):
remaining_to_fetch = feconf.SEARCH_RESULTS_PAGE_SIZE - len(
returned_exploration_ids)
exp_ids, search_offset = search_services.search_explorations(
query_string, categories, language_codes, remaining_to_fetch,
offset=search_offset)
invalid_exp_ids = []
for ind, model in enumerate(
exp_models.ExpSummaryModel.get_multi(exp_ids)):
if model is not None:
returned_exploration_ids.append(exp_ids[ind])
else:
invalid_exp_ids.append(exp_ids[ind])
if (len(returned_exploration_ids) == feconf.SEARCH_RESULTS_PAGE_SIZE
or search_offset is None):
break
logging.error(
'Search index contains stale exploration ids: %s' %
', '.join(invalid_exp_ids))
if (len(returned_exploration_ids) < feconf.SEARCH_RESULTS_PAGE_SIZE
and search_offset is not None):
logging.error(
'Could not fulfill search request for query string %s; at least '
'%s retries were needed.' % (query_string, MAX_ITERATIONS))
return (returned_exploration_ids, search_offset)
def get_non_private_exploration_summaries():
"""Returns a dict with all non-private exploration summary domain objects,
keyed by their id.
Returns:
dict. The keys are exploration ids and the values are corresponding
non-private ExplorationSummary domain objects.
"""
return exp_fetchers.get_exploration_summaries_from_models(
exp_models.ExpSummaryModel.get_non_private())
def get_top_rated_exploration_summaries(limit):
"""Returns a dict with top rated exploration summary model instances,
keyed by their id. At most 'limit' entries are returned.
Args:
limit: int. The maximum number of exploration summary model instances to
be returned.
Returns:
dict. The keys are exploration ids and the values are the corresponding
top rated ExplorationSummary domain model instances. At most limit
entries are returned.
"""
return exp_fetchers.get_exploration_summaries_from_models(
exp_models.ExpSummaryModel.get_top_rated(limit))
def get_recently_published_exp_summaries(limit):
"""Returns a dict with recently published ExplorationSummary model
instances, keyed by their exploration id. At most 'limit' entries are
returned.
Args:
limit: int. The maximum number of exploration summary model instances to
be returned.
Returns:
dict. The dict contains recently published ExplorationSummary model
instances as a value keyed by their exploration id. At most 'limit'
entries are returned.
"""
return exp_fetchers.get_exploration_summaries_from_models(
exp_models.ExpSummaryModel.get_recently_published(limit))
def get_story_id_linked_to_exploration(exp_id):
"""Returns the ID of the story that the exploration is a part of, or None if
the exploration is not part of a story.
Args:
exp_id: str. The ID of the exploration.
Returns:
str|None. The ID of the story if the exploration is linked to some
story, otherwise None.
"""
exploration_context_model = exp_models.ExplorationContextModel.get(
exp_id, strict=False)
if exploration_context_model is not None:
return exploration_context_model.story_id
return None
def get_all_exploration_summaries():
"""Returns a dict with all exploration summary domain objects,
keyed by their id.
Returns:
dict. A dict with all ExplorationSummary domain objects keyed by their
exploration id.
"""
return exp_fetchers.get_exploration_summaries_from_models(
exp_models.ExpSummaryModel.get_all())
# Methods for exporting states and explorations to other formats.
def export_to_zip_file(exploration_id, version=None):
"""Returns a ZIP archive of the exploration.
Args:
exploration_id: str. The id of the exploration to export.
version: int or None. If provided, this indicates which version of
the exploration to export. Otherwise, the latest version of the
exploration is exported.
Returns:
BytesIO. The contents of the ZIP archive of the exploration
(which can be subsequently converted into a zip file via
zipfile.ZipFile()).
"""
exploration = exp_fetchers.get_exploration_by_id(
exploration_id, version=version)
yaml_repr = exploration.to_yaml()
temp_file = io.BytesIO()
with zipfile.ZipFile(
temp_file, mode='w', compression=zipfile.ZIP_DEFLATED) as zfile:
if not exploration.title:
zfile.writestr('Unpublished_exploration.yaml', yaml_repr)
else:
zfile.writestr('%s.yaml' % exploration.title, yaml_repr)
fs = fs_domain.AbstractFileSystem(
fs_domain.GcsFileSystem(
feconf.ENTITY_TYPE_EXPLORATION, exploration_id))
html_string_list = exploration.get_all_html_content_strings()
image_filenames = (
html_cleaner.get_image_filenames_from_html_strings(
html_string_list))
for filename in image_filenames:
filepath = 'image/%s' % filename
file_contents = fs.get(filepath)
str_filepath = 'assets/%s' % filepath
logging.error(str_filepath)
zfile.writestr(str_filepath, file_contents)
return temp_file
def export_states_to_yaml(exploration_id, version=None, width=80):
"""Returns a dictionary of the exploration, whose keys are state
names and values are yaml strings representing the state contents with
lines wrapped at 'width' characters.
Args:
exploration_id: str. The id of the exploration whose states should
be exported.
version: int or None. The version of the exploration to be returned.
If None, the latest version of the exploration is returned.
width: int. Width for the yaml representation, default value
is set to be of 80.
Returns:
dict. The keys are state names, and the values are YAML strings
representing the corresponding state's contents.
"""
exploration = exp_fetchers.get_exploration_by_id(
exploration_id, version=version)
exploration_dict = {}
for state in exploration.states:
exploration_dict[state] = utils.yaml_from_dict(
exploration.states[state].to_dict(),
width=width
)
return exploration_dict
# Repository SAVE and DELETE methods.
def apply_change_list(exploration_id, change_list):
"""Applies a changelist to a pristine exploration and returns the result.
Each entry in change_list is a dict that represents an ExplorationChange
object.
Args:
exploration_id: str. The id of the exploration to which the change list
is to be applied.
change_list: list(ExplorationChange). The list of changes to apply.
Returns:
Exploration. The exploration domain object that results from applying
the given changelist to the existing version of the exploration.
Raises:
Exception. Any entries in the changelist are invalid.
"""
exploration = exp_fetchers.get_exploration_by_id(exploration_id)
try:
to_param_domain = param_domain.ParamChange.from_dict
for change in change_list:
if change.cmd == exp_domain.CMD_ADD_STATE:
exploration.add_states([change.state_name])
elif change.cmd == exp_domain.CMD_RENAME_STATE:
exploration.rename_state(
change.old_state_name, change.new_state_name)
elif change.cmd == exp_domain.CMD_DELETE_STATE:
exploration.delete_state(change.state_name)
elif change.cmd == exp_domain.CMD_EDIT_STATE_PROPERTY:
state = exploration.states[change.state_name]
if (change.property_name ==
exp_domain.STATE_PROPERTY_PARAM_CHANGES):
state.update_param_changes(list(map(
to_param_domain, change.new_value)))
elif change.property_name == exp_domain.STATE_PROPERTY_CONTENT:
content = (
state_domain.SubtitledHtml.from_dict(change.new_value))
content.validate()
state.update_content(content)
elif (change.property_name ==
exp_domain.STATE_PROPERTY_INTERACTION_ID):
state.update_interaction_id(change.new_value)
elif (change.property_name ==
exp_domain.STATE_PROPERTY_NEXT_CONTENT_ID_INDEX):
next_content_id_index = max(
change.new_value, state.next_content_id_index)
state.update_next_content_id_index(next_content_id_index)
elif (change.property_name ==
exp_domain.STATE_PROPERTY_LINKED_SKILL_ID):
state.update_linked_skill_id(change.new_value)
elif (change.property_name ==
exp_domain.STATE_PROPERTY_INTERACTION_CUST_ARGS):
state.update_interaction_customization_args(
change.new_value)
elif (change.property_name ==
exp_domain.STATE_PROPERTY_INTERACTION_HANDLERS):
raise utils.InvalidInputException(
'Editing interaction handlers is no longer supported')
elif (change.property_name ==
exp_domain.STATE_PROPERTY_INTERACTION_ANSWER_GROUPS):
new_answer_groups = [
state_domain.AnswerGroup.from_dict(answer_groups)
for answer_groups in change.new_value
]
state.update_interaction_answer_groups(new_answer_groups)
elif (change.property_name ==
exp_domain.STATE_PROPERTY_INTERACTION_DEFAULT_OUTCOME):
new_outcome = None
if change.new_value:
new_outcome = state_domain.Outcome.from_dict(
change.new_value
)
state.update_interaction_default_outcome(new_outcome)
elif (change.property_name ==
exp_domain.STATE_PROPERTY_UNCLASSIFIED_ANSWERS):
state.update_interaction_confirmed_unclassified_answers(
change.new_value)
elif (change.property_name ==
exp_domain.STATE_PROPERTY_INTERACTION_HINTS):
if not isinstance(change.new_value, list):
raise Exception(
'Expected hints_list to be a list,'
' received %s' % change.new_value)
new_hints_list = [
state_domain.Hint.from_dict(hint_dict)
for hint_dict in change.new_value
]
state.update_interaction_hints(new_hints_list)
elif (change.property_name ==
exp_domain.STATE_PROPERTY_INTERACTION_SOLUTION):
new_solution = None
if change.new_value is not None:
new_solution = state_domain.Solution.from_dict(
state.interaction.id, change.new_value)
state.update_interaction_solution(new_solution)
elif (change.property_name ==
exp_domain.STATE_PROPERTY_SOLICIT_ANSWER_DETAILS):
if not isinstance(change.new_value, bool):
raise Exception(
'Expected solicit_answer_details to be a ' +
'bool, received %s' % change.new_value)
state.update_solicit_answer_details(change.new_value)
elif (change.property_name ==
exp_domain.STATE_PROPERTY_CARD_IS_CHECKPOINT):
if not isinstance(change.new_value, bool):
raise Exception(
'Expected card_is_checkpoint to be a ' +
'bool, received %s' % change.new_value)
state.update_card_is_checkpoint(change.new_value)
elif (change.property_name ==
exp_domain.STATE_PROPERTY_RECORDED_VOICEOVERS):
if not isinstance(change.new_value, dict):
raise Exception(
'Expected recorded_voiceovers to be a dict, '
'received %s' % change.new_value)
# Explicitly convert the duration_secs value from
# int to float. Reason for this is the data from
# the frontend will be able to match the backend
# state model for Voiceover properly. Also js
# treats any number that can be float and int as
# int (no explicit types). For example,
# 10.000 is not 10.000 it is 10.
new_voiceovers_mapping = (
change.new_value['voiceovers_mapping'])
language_codes_to_audio_metadata = (
new_voiceovers_mapping.values())
for language_codes in language_codes_to_audio_metadata:
for audio_metadata in language_codes.values():
audio_metadata['duration_secs'] = (
float(audio_metadata['duration_secs'])
)
recorded_voiceovers = (
state_domain.RecordedVoiceovers.from_dict(
change.new_value))
state.update_recorded_voiceovers(recorded_voiceovers)
elif (change.property_name ==
exp_domain.STATE_PROPERTY_WRITTEN_TRANSLATIONS):
if not isinstance(change.new_value, dict):
raise Exception(
'Expected written_translations to be a dict, '
'received %s' % change.new_value)
cleaned_written_translations_dict = (
state_domain.WrittenTranslations
.convert_html_in_written_translations(
change.new_value, html_cleaner.clean))
written_translations = (
state_domain.WrittenTranslations.from_dict(
cleaned_written_translations_dict))
state.update_written_translations(written_translations)
elif change.cmd == exp_domain.DEPRECATED_CMD_ADD_TRANSLATION:
# DEPRECATED: This command is deprecated. Please do not use.
# The command remains here to support old suggestions.
exploration.states[change.state_name].add_translation(
change.content_id, change.language_code,
change.translation_html)
elif change.cmd == exp_domain.CMD_ADD_WRITTEN_TRANSLATION:
exploration.states[change.state_name].add_written_translation(
change.content_id, change.language_code,
change.translation_html, change.data_format)
elif (change.cmd ==
exp_domain.CMD_MARK_WRITTEN_TRANSLATION_AS_NEEDING_UPDATE):
exploration.states[
change.state_name
].mark_written_translation_as_needing_update(
change.content_id,
change.language_code
)
elif (change.cmd ==
exp_domain.CMD_MARK_WRITTEN_TRANSLATIONS_AS_NEEDING_UPDATE):
exploration.states[
change.state_name
].mark_written_translations_as_needing_update(change.content_id)
elif change.cmd == exp_domain.CMD_EDIT_EXPLORATION_PROPERTY:
if change.property_name == 'title':
exploration.update_title(change.new_value)
elif change.property_name == 'category':
exploration.update_category(change.new_value)
elif change.property_name == 'objective':
exploration.update_objective(change.new_value)
elif change.property_name == 'language_code':
exploration.update_language_code(change.new_value)
elif change.property_name == 'tags':
exploration.update_tags(change.new_value)
elif change.property_name == 'blurb':
exploration.update_blurb(change.new_value)
elif change.property_name == 'author_notes':
exploration.update_author_notes(change.new_value)
elif change.property_name == 'param_specs':
exploration.update_param_specs(change.new_value)
elif change.property_name == 'param_changes':
exploration.update_param_changes(list(
map(to_param_domain, change.new_value)))
elif change.property_name == 'init_state_name':
exploration.update_init_state_name(change.new_value)
elif change.property_name == 'auto_tts_enabled':
exploration.update_auto_tts_enabled(change.new_value)
elif change.property_name == 'correctness_feedback_enabled':
exploration.update_correctness_feedback_enabled(
change.new_value)
elif (change.cmd ==
exp_domain.CMD_MIGRATE_STATES_SCHEMA_TO_LATEST_VERSION):
# Loading the exploration model from the datastore into an
# Exploration domain object automatically converts it to use
# the latest states schema version. As a result, simply
# resaving the exploration is sufficient to apply the states
# schema update. Thus, no action is needed here other than
# to make sure that the version that the user is trying to
# migrate to is the latest version.
target_version_is_current_state_schema_version = (
change.to_version ==
str(feconf.CURRENT_STATE_SCHEMA_VERSION))
if not target_version_is_current_state_schema_version:
raise Exception(
'Expected to migrate to the latest state schema '
'version %s, received %s' % (
feconf.CURRENT_STATE_SCHEMA_VERSION,
change.to_version))
return exploration
except Exception as e:
logging.error(
'%s %s %s %s' % (
e.__class__.__name__, e, exploration_id,
pprint.pprint(change_list))
)
raise e
def _save_exploration(committer_id, exploration, commit_message, change_list):
"""Validates an exploration and commits it to persistent storage.
If successful, increments the version number of the incoming exploration
domain object by 1.
Args:
committer_id: str. The id of the user who made the commit.
exploration: Exploration. The exploration to be saved.
commit_message: str. The commit message.
change_list: list(ExplorationChange). A list of changes introduced in
this commit.
Raises:
Exception. The versions of the given exploration and the currently
stored exploration model do not match.
"""
exploration_rights = rights_manager.get_exploration_rights(exploration.id)
if exploration_rights.status != rights_domain.ACTIVITY_STATUS_PRIVATE:
exploration.validate(strict=True)
else:
exploration.validate()
exploration_model = exp_models.ExplorationModel.get(exploration.id)
if exploration.version > exploration_model.version:
raise Exception(
'Unexpected error: trying to update version %s of exploration '
'from version %s. Please reload the page and try again.'
% (exploration_model.version, exploration.version))
if exploration.version < exploration_model.version:
raise Exception(
'Trying to update version %s of exploration from version %s, '
'which is too old. Please reload the page and try again.'
% (exploration_model.version, exploration.version))
old_states = exp_fetchers.get_exploration_from_model(
exploration_model).states
exploration_model.category = exploration.category
exploration_model.title = exploration.title
exploration_model.objective = exploration.objective
exploration_model.language_code = exploration.language_code
exploration_model.tags = exploration.tags
exploration_model.blurb = exploration.blurb
exploration_model.author_notes = exploration.author_notes
exploration_model.states_schema_version = exploration.states_schema_version
exploration_model.init_state_name = exploration.init_state_name
exploration_model.states = {
state_name: state.to_dict()
for (state_name, state) in exploration.states.items()}
exploration_model.param_specs = exploration.param_specs_dict
exploration_model.param_changes = exploration.param_change_dicts
exploration_model.auto_tts_enabled = exploration.auto_tts_enabled
exploration_model.correctness_feedback_enabled = (
exploration.correctness_feedback_enabled)
change_list_dict = [change.to_dict() for change in change_list]
exploration_model.commit(committer_id, commit_message, change_list_dict)
caching_services.delete_multi(
caching_services.CACHE_NAMESPACE_EXPLORATION,
None,
[exploration.id])
exploration.version += 1
exp_versions_diff = exp_domain.ExplorationVersionsDiff(change_list)
# Trigger statistics model update.
new_exp_stats = stats_services.get_stats_for_new_exp_version(
exploration.id, exploration.version, exploration.states,
exp_versions_diff, None)
stats_services.create_stats_model(new_exp_stats)
if feconf.ENABLE_ML_CLASSIFIERS:
trainable_states_dict = exploration.get_trainable_states_dict(
old_states, exp_versions_diff)
state_names_with_changed_answer_groups = trainable_states_dict[
'state_names_with_changed_answer_groups']
state_names_with_unchanged_answer_groups = trainable_states_dict[
'state_names_with_unchanged_answer_groups']
state_names_to_train_classifier = state_names_with_changed_answer_groups
if state_names_with_unchanged_answer_groups:
state_names_without_classifier = (
classifier_services.handle_non_retrainable_states(
exploration, state_names_with_unchanged_answer_groups,
exp_versions_diff))
state_names_to_train_classifier.extend(
state_names_without_classifier)
if state_names_to_train_classifier:
classifier_services.handle_trainable_states(
exploration, state_names_to_train_classifier)
# Trigger exploration issues model updation.
stats_services.update_exp_issues_for_new_exp_version(
exploration, exp_versions_diff, None)
def _create_exploration(
committer_id, exploration, commit_message, commit_cmds):
"""Ensures that rights for a new exploration are saved first.
This is because _save_exploration() depends on the rights object being
present to tell it whether to do strict validation or not.
Args:
committer_id: str. The id of the user who made the commit.
exploration: Exploration. The exploration domain object.
commit_message: str. The commit description message.
commit_cmds: list(ExplorationChange). A list of commands, describing
changes made in this model, which should give sufficient information
to reconstruct the commit.
"""
# This line is needed because otherwise a rights object will be created,
# but the creation of an exploration object will fail.
exploration.validate()
rights_manager.create_new_exploration_rights(exploration.id, committer_id)
model = exp_models.ExplorationModel(
id=exploration.id,
category=exploration.category,
title=exploration.title,
objective=exploration.objective,
language_code=exploration.language_code,
tags=exploration.tags,
blurb=exploration.blurb,
author_notes=exploration.author_notes,
states_schema_version=exploration.states_schema_version,
init_state_name=exploration.init_state_name,
states={
state_name: state.to_dict()
for (state_name, state) in exploration.states.items()},
param_specs=exploration.param_specs_dict,
param_changes=exploration.param_change_dicts,
auto_tts_enabled=exploration.auto_tts_enabled,
correctness_feedback_enabled=exploration.correctness_feedback_enabled
)
commit_cmds_dict = [commit_cmd.to_dict() for commit_cmd in commit_cmds]
model.commit(committer_id, commit_message, commit_cmds_dict)
exploration.version += 1
# Trigger statistics model creation.
exploration_stats = stats_services.get_stats_for_new_exploration(
exploration.id, exploration.version, exploration.states)
stats_services.create_stats_model(exploration_stats)
if feconf.ENABLE_ML_CLASSIFIERS:
# Find out all states that need a classifier to be trained.
state_names_to_train = []
for state_name in exploration.states:
state = exploration.states[state_name]
if state.can_undergo_classification():
state_names_to_train.append(state_name)
if state_names_to_train:
classifier_services.handle_trainable_states(
exploration, state_names_to_train)
# Trigger exploration issues model creation.
stats_services.create_exp_issues_for_new_exploration(
exploration.id, exploration.version)
regenerate_exploration_summary_with_new_contributor(
exploration.id, committer_id)
def save_new_exploration(committer_id, exploration):
"""Saves a newly created exploration.
Args:
committer_id: str. The id of the user who made the commit.
exploration: Exploration. The exploration domain object to be saved.
"""
commit_message = (
('New exploration created with title \'%s\'.' % exploration.title)
if exploration.title else 'New exploration created.')
_create_exploration(
committer_id, exploration, commit_message, [
exp_domain.ExplorationChange({
'cmd': exp_domain.CMD_CREATE_NEW,
'title': exploration.title,
'category': exploration.category,
})])
user_services.add_created_exploration_id(committer_id, exploration.id)
user_services.add_edited_exploration_id(committer_id, exploration.id)
user_services.record_user_created_an_exploration(committer_id)
def delete_exploration(committer_id, exploration_id, force_deletion=False):
"""Deletes the exploration with the given exploration_id.
IMPORTANT: Callers of this function should ensure that committer_id has
permissions to delete this exploration, prior to calling this function.
If force_deletion is True the exploration and its history are fully deleted
and are unrecoverable. Otherwise, the exploration and all its history are
marked as deleted, but the corresponding models are still retained in the
datastore. This last option is the preferred one.
Args:
committer_id: str. The id of the user who made the commit.
exploration_id: str. The id of the exploration to be deleted.
force_deletion: bool. If True, completely deletes the storage models
corresponding to the exploration. Otherwise, marks them as deleted
but keeps the corresponding models in the datastore.
"""
delete_explorations(
committer_id, [exploration_id], force_deletion=force_deletion)
def delete_explorations(committer_id, exploration_ids, force_deletion=False):
"""Delete the explorations with the given exploration_ids.
IMPORTANT: Callers of this function should ensure that committer_id has
permissions to delete these explorations, prior to calling this function.
If force_deletion is True the explorations and its histories are fully
deleted and are unrecoverable. Otherwise, the explorations and all its
histories are marked as deleted, but the corresponding models are still
retained in the datastore. This last option is the preferred one.
Args:
committer_id: str. The id of the user who made the commit.
exploration_ids: list(str). The ids of the explorations to be deleted.
force_deletion: bool. If True, completely deletes the storage models
corresponding to the explorations. Otherwise, marks them as deleted
but keeps the corresponding models in the datastore.
"""
# TODO(sll): Delete the files too?
exp_models.ExplorationRightsModel.delete_multi(
exploration_ids, committer_id, '', force_deletion=force_deletion)
exp_models.ExplorationModel.delete_multi(
exploration_ids, committer_id,
feconf.COMMIT_MESSAGE_EXPLORATION_DELETED,
force_deletion=force_deletion)
caching_services.delete_multi(
caching_services.CACHE_NAMESPACE_EXPLORATION, None,
exploration_ids)
# Delete the explorations from search.
search_services.delete_explorations_from_search_index(exploration_ids)
# Delete the exploration summaries, recommendations and opportunities
# regardless of whether or not force_deletion is True.
delete_exploration_summaries(exploration_ids)
recommendations_services.delete_explorations_from_recommendations(
exploration_ids)
opportunity_services.delete_exploration_opportunities(exploration_ids)
feedback_services.delete_exploration_feedback_analytics(exploration_ids)
# Remove the explorations from the featured activity references, if
# necessary.
activity_services.remove_featured_activities(
constants.ACTIVITY_TYPE_EXPLORATION, exploration_ids)
feedback_services.delete_threads_for_multiple_entities(
feconf.ENTITY_TYPE_EXPLORATION, exploration_ids)
# Remove from subscribers.
taskqueue_services.defer(
taskqueue_services.FUNCTION_ID_DELETE_EXPS_FROM_USER_MODELS,
taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS, exploration_ids)
# Remove from activities.
taskqueue_services.defer(
taskqueue_services.FUNCTION_ID_DELETE_EXPS_FROM_ACTIVITIES,
taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS, exploration_ids)
def delete_explorations_from_user_models(exploration_ids):
"""Remove explorations from all subscribers' exploration_ids.
Args:
exploration_ids: list(str). The ids of the explorations to delete.
"""
if not exploration_ids:
return
subscription_models = user_models.UserSubscriptionsModel.query(
user_models.UserSubscriptionsModel.exploration_ids.IN(exploration_ids)
).fetch()
for model in subscription_models:
model.exploration_ids = [
id_ for id_ in model.exploration_ids if id_ not in exploration_ids]
user_models.UserSubscriptionsModel.update_timestamps_multi(
subscription_models)
user_models.UserSubscriptionsModel.put_multi(subscription_models)
exp_user_data_models = (
user_models.ExplorationUserDataModel.get_all().filter(
user_models.ExplorationUserDataModel.exploration_id.IN(
exploration_ids
)
).fetch()
)
user_models.ExplorationUserDataModel.delete_multi(exp_user_data_models)
user_contributions_models = (
user_models.UserContributionsModel.get_all().filter(
datastore_services.any_of(
user_models.UserContributionsModel.created_exploration_ids.IN(
exploration_ids
),
user_models.UserContributionsModel.edited_exploration_ids.IN(
exploration_ids
)
)
).fetch()
)
for model in user_contributions_models:
model.created_exploration_ids = [
exp_id for exp_id in model.created_exploration_ids
if exp_id not in exploration_ids
]
model.edited_exploration_ids = [
exp_id for exp_id in model.edited_exploration_ids
if exp_id not in exploration_ids
]
user_models.UserContributionsModel.update_timestamps_multi(
user_contributions_models)
user_models.UserContributionsModel.put_multi(user_contributions_models)
def delete_explorations_from_activities(exploration_ids):
"""Remove explorations from exploration_ids field in completed and
incomplete activities models.
Args:
exploration_ids: list(str). The ids of the explorations to delete.
"""
if not exploration_ids:
return
model_classes = (
user_models.CompletedActivitiesModel,
user_models.IncompleteActivitiesModel,
)
all_entities = []
for model_class in model_classes:
entities = model_class.query(
model_class.exploration_ids.IN(exploration_ids)
).fetch()
for model in entities:
model.exploration_ids = [
id_ for id_ in model.exploration_ids
if id_ not in exploration_ids
]
all_entities.extend(entities)
datastore_services.update_timestamps_multi(all_entities)
datastore_services.put_multi(all_entities)
# Operations on exploration snapshots.
def get_exploration_snapshots_metadata(exploration_id, allow_deleted=False):
"""Returns the snapshots for this exploration, as dicts, up to and including
the latest version of the exploration.
Args:
exploration_id: str. The id of the exploration whose snapshots_metadata
is required.
allow_deleted: bool. Whether to allow retrieval of deleted snapshots.
Returns:
list(dict). List of dicts, each representing a recent snapshot. Each
dict has the following keys: committer_id, commit_message, commit_cmds,
commit_type, created_on_ms, version_number. The version numbers are
consecutive and in ascending order. There are exploration.version_number
items in the returned list.
"""
exploration = exp_fetchers.get_exploration_by_id(exploration_id)
current_version = exploration.version
version_nums = list(range(1, current_version + 1))
return exp_models.ExplorationModel.get_snapshots_metadata(
exploration_id, version_nums, allow_deleted=allow_deleted)
def get_last_updated_by_human_ms(exp_id):
"""Return the last time, in milliseconds, when the given exploration was
updated by a human.
Args:
exp_id: str. The id of the exploration.
Returns:
float. The last time in milliseconds when a given exploration was
updated by a human.
"""
# Iterate backwards through the exploration history metadata until we find
# the most recent snapshot that was committed by a human.
last_human_update_ms = 0
snapshots_metadata = get_exploration_snapshots_metadata(exp_id)
for snapshot_metadata in reversed(snapshots_metadata):
if snapshot_metadata['committer_id'] != feconf.MIGRATION_BOT_USER_ID:
last_human_update_ms = snapshot_metadata['created_on_ms']
break
return last_human_update_ms
def publish_exploration_and_update_user_profiles(committer, exp_id):
"""Publishes the exploration with publish_exploration() function in
rights_manager.py, as well as updates first_contribution_msec. Sends an
email to the subscribers of the committer informing them that an exploration
has been published.
It is the responsibility of the caller to check that the exploration is
valid prior to publication.
Args:
committer: UserActionsInfo. UserActionsInfo object for the user who
made the commit.
exp_id: str. The id of the exploration to be published.
"""
rights_manager.publish_exploration(committer, exp_id)
exp_title = exp_fetchers.get_exploration_by_id(exp_id).title
email_subscription_services.inform_subscribers(
committer.user_id, exp_id, exp_title)
contribution_time_msec = utils.get_current_time_in_millisecs()
contributor_ids = exp_fetchers.get_exploration_summary_by_id(
exp_id).contributor_ids
for contributor in contributor_ids:
user_services.update_first_contribution_msec_if_not_set(
contributor, contribution_time_msec)
def validate_exploration_for_story(exp, strict):
"""Validates an exploration with story validations.
Args:
exp: Exploration. Exploration object to be validated.
strict: bool. Whether to raise an Exception when a validation error
is encountered. If not, a list of the error messages are
returned. strict should be True when this is called before
saving the story and False when this function is called from the
frontend.
Returns:
list(str). The various validation error messages (if strict is
False).
Raises:
ValidationError. Invalid language found for exploration.
ValidationError. Expected no exploration to have parameter values in it.
ValidationError. Invalid interaction in exploration.
ValidationError. RTE content in state of exploration with ID is not
supported on mobile.
"""
validation_error_messages = []
if (
exp.language_code not in
android_validation_constants.SUPPORTED_LANGUAGES):
error_string = (
'Invalid language %s found for exploration '
'with ID %s. This language is not supported for explorations '
'in a story on the mobile app.' % (exp.language_code, exp.id))
if strict:
raise utils.ValidationError(error_string)
validation_error_messages.append(error_string)
if exp.param_specs or exp.param_changes:
error_string = (
'Expected no exploration in a story to have parameter '
'values in it. Invalid exploration: %s' % exp.id)
if strict:
raise utils.ValidationError(error_string)
validation_error_messages.append(error_string)
if not exp.correctness_feedback_enabled:
error_string = (
'Expected all explorations in a story to '
'have correctness feedback '
'enabled. Invalid exploration: %s' % exp.id)
if strict:
raise utils.ValidationError(error_string)
validation_error_messages.append(error_string)
for state_name in exp.states:
state = exp.states[state_name]
if not state.interaction.is_supported_on_android_app():
error_string = (
'Invalid interaction %s in exploration '
'with ID: %s. This interaction is not supported for '
'explorations in a story on the '
'mobile app.' % (state.interaction.id, exp.id))
if strict:
raise utils.ValidationError(error_string)
validation_error_messages.append(error_string)
if not state.is_rte_content_supported_on_android():
error_string = (
'RTE content in state %s of exploration '
'with ID %s is not supported on mobile for explorations '
'in a story.' % (state_name, exp.id))
if strict:
raise utils.ValidationError(error_string)
validation_error_messages.append(error_string)
if state.interaction.id == 'EndExploration':
recommended_exploration_ids = (
state.interaction.customization_args[
'recommendedExplorationIds'].value)
if len(recommended_exploration_ids) != 0:
error_string = (
'Explorations in a story are not expected to contain '
'exploration recommendations. Exploration with ID: '
'%s contains exploration recommendations in its '
'EndExploration interaction.' % (exp.id))
if strict:
raise utils.ValidationError(error_string)
validation_error_messages.append(error_string)
return validation_error_messages
def update_exploration(
committer_id, exploration_id, change_list, commit_message,
is_suggestion=False, is_by_voice_artist=False):
"""Update an exploration. Commits changes.
Args:
committer_id: str. The id of the user who is performing the update
action.
exploration_id: str. The id of the exploration to be updated.
change_list: list(ExplorationChange) or None. A change list to be
applied to the given exploration. If None, it corresponds to an
empty list.
commit_message: str or None. A description of changes made to the state.
For published explorations, this must be present; for unpublished
explorations, it should be equal to None. For suggestions that are
being accepted, and only for such commits, it should start with
feconf.COMMIT_MESSAGE_ACCEPTED_SUGGESTION_PREFIX.
is_suggestion: bool. Whether the update is due to a suggestion being
accepted.
is_by_voice_artist: bool. Whether the changes are made by a
voice artist.
Raises:
ValueError. No commit message is supplied and the exploration is public.
ValueError. The update is due to a suggestion and the commit message is
invalid.
ValueError. The update is not due to a suggestion, and the commit
message starts with the same prefix as the commit message for
accepted suggestions.
"""
if change_list is None:
change_list = []
if is_by_voice_artist and not is_voiceover_change_list(change_list):
raise utils.ValidationError(
'Voice artist does not have permission to make some '
'changes in the change list.')
is_public = rights_manager.is_exploration_public(exploration_id)
if is_public and not commit_message:
raise ValueError(
'Exploration is public so expected a commit message but '
'received none.')
if (is_suggestion and (
not commit_message or
not commit_message.startswith(
feconf.COMMIT_MESSAGE_ACCEPTED_SUGGESTION_PREFIX))):
raise ValueError('Invalid commit message for suggestion.')
if (not is_suggestion and commit_message and commit_message.startswith(
feconf.COMMIT_MESSAGE_ACCEPTED_SUGGESTION_PREFIX)):
raise ValueError(
'Commit messages for non-suggestions may not start with \'%s\'' %
feconf.COMMIT_MESSAGE_ACCEPTED_SUGGESTION_PREFIX)
updated_exploration = apply_change_list(exploration_id, change_list)
if get_story_id_linked_to_exploration(exploration_id) is not None:
validate_exploration_for_story(updated_exploration, True)
_save_exploration(
committer_id, updated_exploration, commit_message, change_list)
discard_draft(exploration_id, committer_id)
# Update summary of changed exploration in a deferred task.
taskqueue_services.defer(
taskqueue_services.FUNCTION_ID_REGENERATE_EXPLORATION_SUMMARY,
taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS, exploration_id,
committer_id)
if committer_id != feconf.MIGRATION_BOT_USER_ID:
user_services.add_edited_exploration_id(committer_id, exploration_id)
user_services.record_user_edited_an_exploration(committer_id)
if not rights_manager.is_exploration_private(exploration_id):
user_services.update_first_contribution_msec_if_not_set(
committer_id, utils.get_current_time_in_millisecs())
if opportunity_services.is_exploration_available_for_contribution(
exploration_id):
opportunity_services.update_opportunity_with_updated_exploration(
exploration_id)
def regenerate_exploration_summary_with_new_contributor(
exploration_id, contributor_id):
"""Regenerate a summary of the given exploration and add a new contributor
to the contributors summary. If the summary does not exist, this function
generates a new one.
Args:
exploration_id: str. The id of the exploration.
contributor_id: str. ID of the contributor to be added to
the exploration summary.
"""
exploration = exp_fetchers.get_exploration_by_id(
exploration_id, strict=False)
if exploration is not None:
exp_summary = _compute_summary_of_exploration(exploration)
exp_summary.add_contribution_by_user(contributor_id)
save_exploration_summary(exp_summary)
else:
logging.error('Could not find exploration with ID %s', exploration_id)
def regenerate_exploration_and_contributors_summaries(exploration_id):
"""Regenerate a summary of the given exploration and also regenerate
the contributors summary from the snapshots. If the summary does not exist,
this function generates a new one.
Args:
exploration_id: str. ID of the exploration.
"""
exploration = exp_fetchers.get_exploration_by_id(exploration_id)
exp_summary = _compute_summary_of_exploration(exploration)
exp_summary.contributors_summary = (
compute_exploration_contributors_summary(exp_summary.id))
save_exploration_summary(exp_summary)
def _compute_summary_of_exploration(exploration):
"""Create an ExplorationSummary domain object for a given Exploration
domain object and return it.
Args:
exploration: Exploration. The exploration whose summary is to be
computed.
Returns:
ExplorationSummary. The resulting exploration summary domain object.
"""
exp_rights = exp_models.ExplorationRightsModel.get_by_id(exploration.id)
exp_summary_model = exp_models.ExpSummaryModel.get_by_id(exploration.id)
if exp_summary_model:
old_exp_summary = exp_fetchers.get_exploration_summary_from_model(
exp_summary_model)
ratings = old_exp_summary.ratings or feconf.get_empty_ratings()
scaled_average_rating = get_scaled_average_rating(ratings)
else:
ratings = feconf.get_empty_ratings()
scaled_average_rating = feconf.EMPTY_SCALED_AVERAGE_RATING
contributors_summary = (
exp_summary_model.contributors_summary if exp_summary_model else {})
contributor_ids = list(contributors_summary.keys())
exploration_model_last_updated = datetime.datetime.fromtimestamp(
get_last_updated_by_human_ms(exploration.id) / 1000.0)
exploration_model_created_on = exploration.created_on
first_published_msec = exp_rights.first_published_msec
exp_summary = exp_domain.ExplorationSummary(
exploration.id, exploration.title, exploration.category,
exploration.objective, exploration.language_code,
exploration.tags, ratings, scaled_average_rating, exp_rights.status,
exp_rights.community_owned, exp_rights.owner_ids,
exp_rights.editor_ids, exp_rights.voice_artist_ids,
exp_rights.viewer_ids, contributor_ids, contributors_summary,
exploration.version, exploration_model_created_on,
exploration_model_last_updated, first_published_msec)
return exp_summary
def compute_exploration_contributors_summary(exploration_id):
"""Returns a dict whose keys are user_ids and whose values are
the number of (non-revert) commits made to the given exploration
by that user_id. This does not count commits which have since been reverted.
Args:
exploration_id: str. The id of the exploration.
Returns:
dict. The keys are all user_ids who have made commits to the given
exploration. The corresponding values are the number of commits made by
each user. Commits that revert to an earlier version, or forward
commits which have since been reverted, are excluded.
"""
snapshots_metadata = get_exploration_snapshots_metadata(exploration_id)
current_version = len(snapshots_metadata)
contributors_summary = collections.defaultdict(int)
while True:
snapshot_metadata = snapshots_metadata[current_version - 1]
committer_id = snapshot_metadata['committer_id']
is_revert = (snapshot_metadata['commit_type'] == 'revert')
if not is_revert and committer_id not in constants.SYSTEM_USER_IDS:
contributors_summary[committer_id] += 1
if current_version == 1:
break
if is_revert:
current_version = snapshot_metadata['commit_cmds'][0][
'version_number']
else:
current_version -= 1
contributor_ids = list(contributors_summary)
# Remove IDs that are deleted or do not exist.
users_settings = user_services.get_users_settings(contributor_ids)
for contributor_id, user_settings in zip(contributor_ids, users_settings):
if user_settings is None:
del contributors_summary[contributor_id]
return contributors_summary
def save_exploration_summary(exp_summary):
"""Save an exploration summary domain object as an ExpSummaryModel entity
in the datastore.
Args:
exp_summary: ExplorationSummary. The exploration summary to save.
"""
exp_summary_dict = {
'title': exp_summary.title,
'category': exp_summary.category,
'objective': exp_summary.objective,
'language_code': exp_summary.language_code,
'tags': exp_summary.tags,
'ratings': exp_summary.ratings,
'scaled_average_rating': exp_summary.scaled_average_rating,
'status': exp_summary.status,
'community_owned': exp_summary.community_owned,
'owner_ids': exp_summary.owner_ids,
'editor_ids': exp_summary.editor_ids,
'voice_artist_ids': exp_summary.voice_artist_ids,
'viewer_ids': exp_summary.viewer_ids,
'contributor_ids': list(exp_summary.contributors_summary.keys()),
'contributors_summary': exp_summary.contributors_summary,
'version': exp_summary.version,
'exploration_model_last_updated': (
exp_summary.exploration_model_last_updated),
'exploration_model_created_on': (
exp_summary.exploration_model_created_on),
'first_published_msec': (
exp_summary.first_published_msec)
}
exp_summary_model = (exp_models.ExpSummaryModel.get_by_id(exp_summary.id))
if exp_summary_model is not None:
exp_summary_model.populate(**exp_summary_dict)
exp_summary_model.update_timestamps()
exp_summary_model.put()
else:
exp_summary_dict['id'] = exp_summary.id
model = exp_models.ExpSummaryModel(**exp_summary_dict)
model.update_timestamps()
model.put()
# The index should be updated after saving the exploration
# summary instead of after saving the exploration since the
# index contains documents computed on basis of exploration
# summary.
index_explorations_given_ids([exp_summary.id])
def delete_exploration_summaries(exploration_ids):
"""Delete multiple exploration summary models.
Args:
exploration_ids: list(str). The id of the exploration summaries to be
deleted.
"""
summary_models = exp_models.ExpSummaryModel.get_multi(exploration_ids)
existing_summary_models = [
summary_model for summary_model in summary_models
if summary_model is not None
]
exp_models.ExpSummaryModel.delete_multi(existing_summary_models)
def revert_exploration(
committer_id, exploration_id, current_version, revert_to_version):
"""Reverts an exploration to the given version number. Commits changes.
Args:
committer_id: str. The id of the user who made the commit.
exploration_id: str. The id of the exploration to be reverted to the
current version.
current_version: int. The current version of the exploration.
revert_to_version: int. The version to which the given exploration
is to be reverted.
Raises:
Exception. Version of exploration does not match the version of the
currently-stored exploration model.
"""
exploration_model = exp_models.ExplorationModel.get(
exploration_id, strict=False)
if current_version > exploration_model.version:
raise Exception(
'Unexpected error: trying to update version %s of exploration '
'from version %s. Please reload the page and try again.'
% (exploration_model.version, current_version))
if current_version < exploration_model.version:
raise Exception(
'Trying to update version %s of exploration from version %s, '
'which is too old. Please reload the page and try again.'
% (exploration_model.version, current_version))
# Validate the previous version of the exploration before committing the
# change.
exploration = exp_fetchers.get_exploration_by_id(
exploration_id, version=revert_to_version)
exploration_rights = rights_manager.get_exploration_rights(exploration.id)
if exploration_rights.status != rights_domain.ACTIVITY_STATUS_PRIVATE:
exploration.validate(strict=True)
else:
exploration.validate()
exp_models.ExplorationModel.revert(
exploration_model, committer_id,
'Reverted exploration to version %s' % revert_to_version,
revert_to_version)
caching_services.delete_multi(
caching_services.CACHE_NAMESPACE_EXPLORATION, None,
[exploration.id])
regenerate_exploration_and_contributors_summaries(exploration_id)
exploration_stats = stats_services.get_stats_for_new_exp_version(
exploration.id, current_version + 1, exploration.states,
None, revert_to_version)
stats_services.create_stats_model(exploration_stats)
current_exploration = exp_fetchers.get_exploration_by_id(
exploration_id, version=current_version)
stats_services.update_exp_issues_for_new_exp_version(
current_exploration, None, revert_to_version)
if feconf.ENABLE_ML_CLASSIFIERS:
exploration_to_revert_to = exp_fetchers.get_exploration_by_id(
exploration_id, version=revert_to_version)
classifier_services.create_classifier_training_job_for_reverted_exploration( # pylint: disable=line-too-long
current_exploration, exploration_to_revert_to)
# Creation and deletion methods.
def get_demo_exploration_components(demo_path):
"""Gets the content of `demo_path` in the sample explorations folder.
Args:
demo_path: str. The file or folder path for the content of an
exploration in SAMPLE_EXPLORATIONS_DIR. E.g.: 'adventure.yaml' or
'tar/'.
Returns:
tuple. A 2-tuple, the first element of which is a yaml string, and the
second element of which is a list of (filepath, content) 2-tuples. The
filepath does not include the assets/ prefix.
Raises:
Exception. The path of the file is unrecognized or does not exist.
"""
demo_filepath = os.path.join(feconf.SAMPLE_EXPLORATIONS_DIR, demo_path)
if demo_filepath.endswith('yaml'):
file_contents = utils.get_file_contents(demo_filepath)
return file_contents, []
elif os.path.isdir(demo_filepath):
return utils.get_exploration_components_from_dir(demo_filepath)
else:
raise Exception('Unrecognized file path: %s' % demo_path)
def save_new_exploration_from_yaml_and_assets(
committer_id, yaml_content, exploration_id, assets_list,
strip_voiceovers=False):
"""Saves a new exploration given its representation in YAML form and the
list of assets associated with it.
Args:
committer_id: str. The id of the user who made the commit.
yaml_content: str. The YAML representation of the exploration.
exploration_id: str. The id of the exploration.
assets_list: list(list(str)). A list of lists of assets, which contains
asset's filename and content.
strip_voiceovers: bool. Whether to strip away all audio voiceovers
from the imported exploration.
Raises:
Exception. The yaml file is invalid due to a missing schema version.
"""
if assets_list is None:
assets_list = []
yaml_dict = utils.dict_from_yaml(yaml_content)
if 'schema_version' not in yaml_dict:
raise Exception('Invalid YAML file: missing schema version')
# The assets are committed before the exploration is created because the
# migrating to state schema version 25 involves adding dimensions to
# images. So we need to have images in the datastore before we could
# perform the migration.
for (asset_filename, asset_content) in assets_list:
fs = fs_domain.AbstractFileSystem(
fs_domain.GcsFileSystem(
feconf.ENTITY_TYPE_EXPLORATION, exploration_id))
fs.commit(asset_filename, asset_content)
exploration = exp_domain.Exploration.from_yaml(exploration_id, yaml_content)
# Check whether audio translations should be stripped.
if strip_voiceovers:
for state in exploration.states.values():
state.recorded_voiceovers.strip_all_existing_voiceovers()
create_commit_message = (
'New exploration created from YAML file with title \'%s\'.'
% exploration.title)
_create_exploration(
committer_id, exploration, create_commit_message, [
exp_domain.ExplorationChange({
'cmd': exp_domain.CMD_CREATE_NEW,
'title': exploration.title,
'category': exploration.category,
})])
def delete_demo(exploration_id):
"""Deletes a single demo exploration.
Args:
exploration_id: str. The id of the exploration to be deleted.
Raises:
Exception. The exploration id is invalid.
"""
if not exp_domain.Exploration.is_demo_exploration_id(exploration_id):
raise Exception('Invalid demo exploration id %s' % exploration_id)
exploration = exp_fetchers.get_exploration_by_id(
exploration_id, strict=False)
if not exploration:
logging.info(
'Exploration with id %s was not deleted, because it '
'does not exist.' % exploration_id)
else:
delete_exploration(
feconf.SYSTEM_COMMITTER_ID, exploration_id, force_deletion=True)
def load_demo(exploration_id):
"""Loads a demo exploration.
The resulting exploration will have two commits in its history (one for
its initial creation and one for its subsequent modification.)
Args:
exploration_id: str. The id of the demo exploration.
Raises:
Exception. The exploration id provided is invalid.
"""
if not exp_domain.Exploration.is_demo_exploration_id(exploration_id):
raise Exception('Invalid demo exploration id %s' % exploration_id)
delete_demo(exploration_id)
exp_filename = feconf.DEMO_EXPLORATIONS[exploration_id]
yaml_content, assets_list = get_demo_exploration_components(exp_filename)
save_new_exploration_from_yaml_and_assets(
feconf.SYSTEM_COMMITTER_ID, yaml_content, exploration_id, assets_list)
publish_exploration_and_update_user_profiles(
user_services.get_system_user(), exploration_id)
index_explorations_given_ids([exploration_id])
logging.info('Exploration with id %s was loaded.' % exploration_id)
def get_next_page_of_all_non_private_commits(
page_size=feconf.COMMIT_LIST_PAGE_SIZE, urlsafe_start_cursor=None,
max_age=None):
"""Returns a page of non-private commits in reverse time order. If max_age
is given, it should be a datetime.timedelta instance.
The return value is a tuple (results, cursor, more) as described in
fetch_page() at:
https://developers.google.com/appengine/docs/python/ndb/queryclass
Args:
page_size: int. Number of commits that are in the commit list page.
urlsafe_start_cursor: str. If this is not None, then the returned
commits start from cursor location. Otherwise they start from the
beginning of the list of commits.
max_age: datetime.timedelta. The maximum age to which all non private
commits are fetch from the ExplorationCommitLogEntry.
Returns:
tuple. A 3-tuple consisting of:
- list(ExplorationCommitLogEntry). A list containing
ExplorationCommitlogEntry domain objects.
- str. The postion of the cursor.
- bool. indicating whether there are (likely) more results after
this batch. If False, there are no more results; if True, there
are probably more results.
Raises:
ValueError. The argument max_age is not datetime.timedelta or None.
"""
if max_age is not None and not isinstance(max_age, datetime.timedelta):
raise ValueError(
'max_age must be a datetime.timedelta instance. or None.')
results, new_urlsafe_start_cursor, more = (
exp_models.ExplorationCommitLogEntryModel.get_all_non_private_commits(
page_size, urlsafe_start_cursor, max_age=max_age))
return ([exp_domain.ExplorationCommitLogEntry(
entry.created_on, entry.last_updated, entry.user_id,
entry.exploration_id, entry.commit_type, entry.commit_message,
entry.commit_cmds, entry.version, entry.post_commit_status,
entry.post_commit_community_owned, entry.post_commit_is_private
) for entry in results], new_urlsafe_start_cursor, more)
def get_image_filenames_from_exploration(exploration):
"""Get the image filenames from the exploration.
Args:
exploration: Exploration. The exploration to get the image filenames.
Returns:
list(str). List containing the name of the image files in exploration.
"""
filenames = []
for state in exploration.states.values():
if state.interaction.id == 'ImageClickInput':
filenames.append(state.interaction.customization_args[
'imageAndRegions'].value['imagePath'])
html_list = exploration.get_all_html_content_strings()
filenames.extend(
html_cleaner.get_image_filenames_from_html_strings(html_list))
return filenames
def get_number_of_ratings(ratings):
"""Gets the total number of ratings represented by the given ratings
object.
Args:
ratings: dict. A dict whose keys are '1', '2', '3', '4', '5' and whose
values are nonnegative integers representing frequency counts.
Returns:
int. The total number of ratings given.
"""
return sum(ratings.values()) if ratings else 0
def get_average_rating(ratings):
"""Returns the average rating of the ratings as a float.
If there are no ratings, it will return 0.
Args:
ratings: dict. A dict whose keys are '1', '2', '3', '4', '5' and whose
values are nonnegative integers representing frequency counts.
Returns:
float. The average of the all the ratings given, or 0
if there are no rating.
"""
rating_weightings = {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5}
if ratings:
rating_sum = 0.0
number_of_ratings = get_number_of_ratings(ratings)
if number_of_ratings == 0:
return 0
for rating_value, rating_count in ratings.items():
rating_sum += rating_weightings[rating_value] * rating_count
return rating_sum / number_of_ratings
def get_scaled_average_rating(ratings):
"""Returns the lower bound wilson score of the ratings. If there are
no ratings, it will return 0. The confidence of this result is 95%.
Args:
ratings: dict. A dict whose keys are '1', '2', '3', '4', '5' and whose
values are nonnegative integers representing frequency counts.
Returns:
float. The lower bound wilson score of the ratings.
"""
# The following is the number of ratings.
n = get_number_of_ratings(ratings)
if n == 0:
return 0
average_rating = get_average_rating(ratings)
z = 1.9599639715843482
x = (average_rating - 1) / 4
# The following calculates the lower bound Wilson Score as documented
# http://www.goproblems.com/test/wilson/wilson.php?v1=0&v2=0&v3=0&v4=&v5=1
a = x + ((z**2) / (2 * n))
b = z * math.sqrt(((x * (1 - x)) / n) + ((z**2) / (4 * n**2)))
wilson_score_lower_bound = (a - b) / (1 + ((z**2) / n))
return 1 + 4 * wilson_score_lower_bound
def index_explorations_given_ids(exp_ids):
"""Indexes the explorations corresponding to the given exploration ids.
Args:
exp_ids: list(str). List of ids of the explorations to be indexed.
"""
exploration_summaries = exp_fetchers.get_exploration_summaries_matching_ids(
exp_ids)
search_services.index_exploration_summaries([
exploration_summary for exploration_summary in exploration_summaries
if exploration_summary is not None])
def is_voiceover_change_list(change_list):
"""Checks whether the change list contains only the changes which are
allowed for voice artist to do.
Args:
change_list: list(ExplorationChange). A list that contains the changes
to be made to the ExplorationUserDataModel object.
Returns:
bool. Whether the change_list contains only the changes which are
allowed for voice artist to do.
"""
for change in change_list:
if (change.property_name !=
exp_domain.STATE_PROPERTY_RECORDED_VOICEOVERS):
return False
return True
def get_composite_change_list(exp_id, from_version, to_version):
"""Returns a list of ExplorationChange domain objects consisting of
changes from from_version to to_version in an exploration.
Args:
exp_id: str. The id of the exploration.
from_version: int. The version of the exploration from where we
want to start the change list.
to_version: int. The version of the exploration till which we
want are change list.
Returns:
list(ExplorationChange). List of ExplorationChange domain objects
consisting of changes from from_version to to_version.
Raises:
Exception. From version is higher than to version.
"""
if from_version > to_version:
raise Exception(
'Unexpected error: Trying to find change list from version %s '
'of exploration to version %s.'
% (from_version, to_version))
version_nums = list(range(from_version + 1, to_version + 1))
snapshots_metadata = exp_models.ExplorationModel.get_snapshots_metadata(
exp_id, version_nums, allow_deleted=False)
composite_change_list_dict = []
for snapshot in snapshots_metadata:
composite_change_list_dict += snapshot['commit_cmds']
composite_change_list = [
exp_domain.ExplorationChange(change)
for change in composite_change_list_dict]
return composite_change_list
def are_changes_mergeable(exp_id, change_list_version, change_list):
"""Checks whether the change list can be merged when the
intended exploration version of changes_list is not same as
the current exploration version.
Args:
exp_id: str. The id of the exploration where the change_list is to
be applied.
change_list_version: int. Version of an exploration on which the change
list was applied.
change_list: list(ExplorationChange). List of the changes made by the
user on the frontend, which needs to be checked for mergeability.
Returns:
boolean. Whether the changes are mergeable.
"""
current_exploration = exp_fetchers.get_exploration_by_id(exp_id)
if current_exploration.version == change_list_version:
return True
if current_exploration.version < change_list_version:
return False
# A complete list of changes from one version to another
# is composite_change_list.
composite_change_list = get_composite_change_list(
exp_id, change_list_version,
current_exploration.version)
exp_at_change_list_version = exp_fetchers.get_exploration_by_id(
exp_id, version=change_list_version)
changes_are_mergeable, send_email = (
exp_domain.ExplorationChangeMergeVerifier(
composite_change_list).is_change_list_mergeable(
change_list, exp_at_change_list_version,
current_exploration))
if send_email:
change_list_dict = [change.to_dict() for change in change_list]
email_manager.send_not_mergeable_change_list_to_admin_for_review(
exp_id, change_list_version, current_exploration.version,
change_list_dict)
return changes_are_mergeable
def is_version_of_draft_valid(exp_id, version):
"""Checks if the draft version is the same as the latest version of the
exploration.
Args:
exp_id: str. The id of the exploration.
version: int. The draft version which is to be validate.
Returns:
bool. Whether the given version number is the same as the current
version number of the exploration in the datastore.
"""
return exp_fetchers.get_exploration_by_id(exp_id).version == version
def get_user_exploration_data(
user_id, exploration_id, apply_draft=False, version=None):
"""Returns a description of the given exploration."""
exp_user_data = user_models.ExplorationUserDataModel.get(
user_id, exploration_id)
is_valid_draft_version = (
is_version_of_draft_valid(
exploration_id, exp_user_data.draft_change_list_exp_version)
if exp_user_data and exp_user_data.draft_change_list_exp_version
else None)
if apply_draft:
updated_exploration = (
get_exp_with_draft_applied(exploration_id, user_id))
if updated_exploration is None:
exploration = exp_fetchers.get_exploration_by_id(
exploration_id, version=version)
else:
exploration = updated_exploration
is_valid_draft_version = True
else:
exploration = exp_fetchers.get_exploration_by_id(
exploration_id, version=version)
states = {}
for state_name in exploration.states:
state_dict = exploration.states[state_name].to_dict()
states[state_name] = state_dict
draft_changes = (
exp_user_data.draft_change_list if exp_user_data
and exp_user_data.draft_change_list else None)
draft_change_list_id = (
exp_user_data.draft_change_list_id if exp_user_data else 0)
exploration_email_preferences = (
user_services.get_email_preferences_for_exploration(
user_id, exploration_id))
editor_dict = {
'auto_tts_enabled': exploration.auto_tts_enabled,
'category': exploration.category,
'correctness_feedback_enabled': (
exploration.correctness_feedback_enabled),
'draft_change_list_id': draft_change_list_id,
'exploration_id': exploration_id,
'init_state_name': exploration.init_state_name,
'language_code': exploration.language_code,
'objective': exploration.objective,
'param_changes': exploration.param_change_dicts,
'param_specs': exploration.param_specs_dict,
'rights': rights_manager.get_exploration_rights(
exploration_id).to_dict(),
'show_state_editor_tutorial_on_load': None,
'show_state_translation_tutorial_on_load': None,
'states': states,
'tags': exploration.tags,
'title': exploration.title,
'version': exploration.version,
'is_version_of_draft_valid': is_valid_draft_version,
'draft_changes': draft_changes,
'email_preferences': exploration_email_preferences.to_dict(),
}
return editor_dict
def create_or_update_draft(
exp_id, user_id, change_list, exp_version, current_datetime,
is_by_voice_artist=False):
"""Create a draft with the given change list, or update the change list
of the draft if it already exists. A draft is updated only if the change
list timestamp of the new change list is greater than the change list
timestamp of the draft.
The method assumes that a ExplorationUserDataModel object exists for the
given user and exploration.
Args:
exp_id: str. The id of the exploration.
user_id: str. The id of the user.
change_list: list(ExplorationChange). A list that contains the changes
to be made to the ExplorationUserDataModel object.
exp_version: int. The current version of the exploration.
current_datetime: datetime.datetime. The current date and time.
is_by_voice_artist: bool. Whether the changes are made by a
voice artist.
"""
if is_by_voice_artist and not is_voiceover_change_list(change_list):
raise utils.ValidationError(
'Voice artist does not have permission to make some '
'changes in the change list.')
exp_user_data = user_models.ExplorationUserDataModel.get(user_id, exp_id)
if (exp_user_data and exp_user_data.draft_change_list and
exp_user_data.draft_change_list_last_updated > current_datetime):
return
updated_exploration = apply_change_list(exp_id, change_list)
updated_exploration.validate(strict=False)
if exp_user_data is None:
exp_user_data = user_models.ExplorationUserDataModel.create(
user_id, exp_id)
draft_change_list_id = exp_user_data.draft_change_list_id
draft_change_list_id += 1
change_list_dict = [change.to_dict() for change in change_list]
exp_user_data.draft_change_list = change_list_dict
exp_user_data.draft_change_list_last_updated = current_datetime
exp_user_data.draft_change_list_exp_version = exp_version
exp_user_data.draft_change_list_id = draft_change_list_id
exp_user_data.update_timestamps()
exp_user_data.put()
def get_exp_with_draft_applied(exp_id, user_id):
"""If a draft exists for the given user and exploration,
apply it to the exploration.
Args:
exp_id: str. The id of the exploration.
user_id: str. The id of the user whose draft is to be applied.
Returns:
Exploration or None. Returns the exploration domain object with draft
applied, or None if draft can not be applied.
"""
# TODO(#15075): Refactor this function.
exp_user_data = user_models.ExplorationUserDataModel.get(user_id, exp_id)
exploration = exp_fetchers.get_exploration_by_id(exp_id)
draft_change_list = None
draft_change_list_exp_version = None
if exp_user_data:
if exp_user_data.draft_change_list:
draft_change_list_exp_version = (
exp_user_data.draft_change_list_exp_version)
draft_change_list = [
exp_domain.ExplorationChange(change)
for change in exp_user_data.draft_change_list]
if (exploration.version >
exp_user_data.draft_change_list_exp_version):
logging.info(
'Exploration and draft versions out of sync, trying '
'to upgrade draft version to match exploration\'s.')
new_draft_change_list = (
draft_upgrade_services.try_upgrading_draft_to_exp_version(
draft_change_list,
exp_user_data.draft_change_list_exp_version,
exploration.version, exploration.id))
if new_draft_change_list is not None:
draft_change_list = new_draft_change_list
draft_change_list_exp_version = exploration.version
updated_exploration = None
if (exp_user_data and exp_user_data.draft_change_list and
are_changes_mergeable(
exp_id, draft_change_list_exp_version, draft_change_list)):
updated_exploration = apply_change_list(
exp_id, draft_change_list)
updated_exploration_has_no_invalid_math_tags = True
# verify that all the math-tags are valid before returning the
# updated exploration.
for state in updated_exploration.states.values():
html_string = ''.join(state.get_all_html_content_strings())
error_list = (
html_validation_service.
validate_math_tags_in_html_with_attribute_math_content(
html_string))
if len(error_list) > 0:
updated_exploration_has_no_invalid_math_tags = False
break
if not updated_exploration_has_no_invalid_math_tags:
updated_exploration = None
return updated_exploration
def discard_draft(exp_id, user_id):
"""Discard the draft for the given user and exploration.
Args:
exp_id: str. The id of the exploration.
user_id: str. The id of the user whose draft is to be discarded.
"""
exp_user_data = user_models.ExplorationUserDataModel.get(
user_id, exp_id)
if exp_user_data:
exp_user_data.draft_change_list = None
exp_user_data.draft_change_list_last_updated = None
exp_user_data.draft_change_list_exp_version = None
exp_user_data.update_timestamps()
exp_user_data.put()
def get_interaction_id_for_state(exp_id, state_name):
"""Returns the interaction id for the given state name.
Args:
exp_id: str. The ID of the exp.
state_name: str. The name of the state.
Returns:
str. The ID of the interaction.
Raises:
Exception. If the state with the given state name does not exist in
the exploration.
"""
exploration = exp_fetchers.get_exploration_by_id(exp_id)
if exploration.has_state_name(state_name):
return exploration.get_interaction_id_by_state_name(state_name)
raise Exception(
'There exist no state in the exploration with the given state name.')
| {
"content_hash": "3445e86c5c95f7904bd91b528cae96f2",
"timestamp": "",
"source": "github",
"line_count": 2032,
"max_line_length": 116,
"avg_line_length": 42.10088582677165,
"alnum_prop": 0.6534500695507838,
"repo_name": "brianrodri/oppia",
"id": "7319ae1cb445e0e252fecf1e8419cf88abf158bc",
"size": "86172",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "core/domain/exp_services.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "487903"
},
{
"name": "HTML",
"bytes": "1748056"
},
{
"name": "JavaScript",
"bytes": "1176446"
},
{
"name": "PEG.js",
"bytes": "71377"
},
{
"name": "Python",
"bytes": "14169091"
},
{
"name": "Shell",
"bytes": "2239"
},
{
"name": "TypeScript",
"bytes": "13316709"
}
],
"symlink_target": ""
} |
import theano
import unittest
import numpy as np
from theano import tensor
from numpy import random as rnd
from theano.gradient import verify_grad
from utils.complex_expm import complex_expm
from utils.complex_matrix_inverse import complex_matrix_inverse
from utils.theano_complex_extension import complex_reshape, complex_tensordot, apply_mat_to_kronecker
from utils.theano_complex_extension import apply_complex_mat_to_kronecker, np_complex_tensordot
from utils.theano_complex_extension import np_apply_complex_mat_to_kronecker
class TensorDotFunction(unittest.TestCase):
def test_complex_reshape(self):
print("cheburek")
def get_all_prod_pairs(n):
return [(i, n // i) for i in range(1, n+1) if n % i == 0]
size = 2**3 * 3 * 4**2 * 5**2 * 6
all_prod_pairs = get_all_prod_pairs(size)
initial_shape = all_prod_pairs[len(all_prod_pairs) // 2]
re = rnd.normal(size=initial_shape)
im = rnd.normal(size=initial_shape)
X = tensor.tensor3('X')
x = np.stack([re, im])
ethalon = re + 1j * im
abstract_shape = tensor.ivector('shape')
func = theano.function([X, abstract_shape], complex_reshape(X, abstract_shape, ndim=2))
self.assertEqual(x.shape[1:], ethalon.shape)
self.assertTrue(np.allclose(x[0, ...] + 1j * x[1, ...], ethalon))
for next_shape in all_prod_pairs:
x = func(x, next_shape)
ethalon = np.reshape(ethalon, next_shape)
self.assertEqual(x.shape[1:], ethalon.shape)
self.assertTrue(np.allclose(x[0, ...] + 1j * x[1, ...], ethalon))
def test_complex_tensordot(self):
ms = (3, 5, 7, 9)
ns = (4, 6, 8, 10)
m = int(np.prod(ms))
n = int(np.prod(ns))
l = 100
X = tensor.tensor3('X')
Factors = [tensor.tensor3('factor_{}_{}'.format(mm, nn)) for (mm, nn) in zip(ms, ns)]
x = rnd.normal(size=(2, l, m))
factors = [rnd.normal(size=(2, mm, nn)) for (mm, nn) in zip(ms, ns)]
x = np.reshape(x, (2, l,) + ms)
X_reshaped = tensor.reshape(X, (2, l) + ms)
def gen_index_dot(X, Factor, i):
func = theano.function([X, Factor], complex_tensordot(X, Factor, axes=([i + 1], [0])))
return func
x_etha = x[0, ...] + 1j * x[1, ...]
for i, factor in enumerate(factors):
args = [x, factor]
func = gen_index_dot(X_reshaped, Factors[i], i)
computed = func(*args)
computed_with_np = np_complex_tensordot(x, factor, axes=[[i+1], 0])
ethalon = np.tensordot(x_etha, factor[0, ...] + 1j * factor[1, ...], axes=[[i + 1], [0]])
self.assertEqual(computed.shape[1:], ethalon.shape)
self.assertTrue(np.allclose(computed[0, ...] + 1j * computed[1, ...], ethalon))
self.assertTrue(np.allclose(computed_with_np[0, ...] + 1j * computed_with_np[1, ...], ethalon))
def test_apply_mat_to_kronecker(self):
ms = (3, 5, 7, 9)
ns = (4, 6, 8, 10)
m = int(np.prod(ms))
n = int(np.prod(ns))
l = 100
X = tensor.tensor3('X')
Factors = [tensor.tensor3('factor_{}_{}'.format(mm, nn)) for (mm, nn) in zip(ms, ns)]
x = rnd.normal(size=(2, l, m))
factors = [rnd.normal(size=(2, mm, nn)) for (mm, nn) in zip(ms, ns)]
func = theano.function([X,] + Factors, apply_complex_mat_to_kronecker(X, Factors))
x_etha = x[0, ...] + 1j * x[1, ...]
etha_factors = [factor[0, ...] + 1j * factor[1, ...] for factor in factors]
print(x.shape)
print([fac.shape for fac in factors])
computed_with_np = np_apply_complex_mat_to_kronecker(x, factors)
computed = func(x, *factors)
ethalon = apply_mat_to_kronecker(x_etha, etha_factors)
self.assertEqual(computed.shape[1:], ethalon.shape)
self.assertTrue(np.allclose(computed[0, ...] + 1j * computed[1, ...], ethalon))
self.assertTrue(np.allclose(computed_with_np[0, ...] + 1j * computed_with_np[1, ...], ethalon))
class TensorComplexExpm(unittest.TestCase):
def test_complex_expm(self):
print("kek")
x_shape = (2, 10, 10)
x = rnd.normal(size=x_shape)
verify_grad(complex_expm, (x,), rng=rnd)
class TensorComplexMatInv(unittest.TestCase):
def test_complex_matrix_inverse(self):
print("shpek")
x_shape = (2, 10, 10)
x = rnd.normal(size=x_shape)
verify_grad(complex_matrix_inverse, (x,), rng=rnd)
if __name__ == '__main__':
unittest.main() | {
"content_hash": "10504772077c0b40fb15192f6370d107",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 107,
"avg_line_length": 37.07258064516129,
"alnum_prop": 0.5747226452033936,
"repo_name": "Nehoroshiy/urnn",
"id": "76763cd954c5ed2c773b5c8abe35b61631443883",
"size": "4597",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/tensor_operations_test.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "340613"
},
{
"name": "Python",
"bytes": "109409"
}
],
"symlink_target": ""
} |
import sqlalchemy as sa
from sqlalchemy import orm
from sqlalchemy.orm import exc as orm_exc
from sqlalchemy.sql import expression as expr
from quantum.common import exceptions as q_exc
from quantum import context
from quantum.db import api as db
from quantum.db import model_base
from quantum.db import models_v2
from quantum.openstack.common import cfg
from quantum.openstack.common import log as logging
from quantum import policy
LOG = logging.getLogger(__name__)
DEFAULT_SVCTYPE_NAME = 'default'
default_servicetype_opts = [
cfg.StrOpt('description',
default='',
help=_('Textual description for the default service type')),
cfg.MultiStrOpt('service_definition',
help=_('Defines a provider for an advanced service '
'using the format: <service>:<plugin>[:<driver>]'))
]
cfg.CONF.register_opts(default_servicetype_opts, 'DEFAULT_SERVICETYPE')
def parse_service_definition_opt():
""" parse service definition opts and returns result """
results = []
svc_def_opt = cfg.CONF.DEFAULT_SERVICETYPE.service_definition
try:
for svc_def_str in svc_def_opt:
split = svc_def_str.split(':')
svc_def = {'service_class': split[0],
'plugin': split[1]}
try:
svc_def['driver'] = split[2]
except IndexError:
# Never mind, driver is optional
LOG.debug(_("Default service type - no driver for service "
"%(service_class)s and plugin %(plugin)s"),
svc_def)
results.append(svc_def)
return results
except (TypeError, IndexError):
raise q_exc.InvalidConfigurationOption(opt_name='service_definition',
opt_value=svc_def_opt)
class NoDefaultServiceDefinition(q_exc.QuantumException):
message = _("No default service definition in configuration file. "
"Please add service definitions using the service_definition "
"variable in the [DEFAULT_SERVICETYPE] section")
class ServiceTypeNotFound(q_exc.NotFound):
message = _("Service type %(service_type_id)s could not be found ")
class ServiceTypeInUse(q_exc.InUse):
message = _("There are still active instances of service type "
"'%(service_type_id)s'. Therefore it cannot be removed.")
class ServiceDefinition(model_base.BASEV2, models_v2.HasId):
service_class = sa.Column(sa.String(255), primary_key=True)
plugin = sa.Column(sa.String(255))
driver = sa.Column(sa.String(255))
service_type_id = sa.Column(sa.String(36),
sa.ForeignKey('servicetypes.id',
ondelete='CASCADE'),
primary_key=True)
class ServiceType(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant):
""" Service Type Object Model """
name = sa.Column(sa.String(255))
description = sa.Column(sa.String(255))
default = sa.Column(sa.Boolean(), nullable=False, default=False)
service_definitions = orm.relationship(ServiceDefinition,
backref='servicetypes',
lazy='joined',
cascade='all')
# Keep track of number of instances for this service type
num_instances = sa.Column(sa.Integer(), default=0)
def as_dict(self):
""" Convert a row into a dict """
ret_dict = {}
for c in self.__table__.columns:
ret_dict[c.name] = getattr(self, c.name)
return ret_dict
class ServiceTypeManager(object):
""" Manage service type objects in Quantum database """
_instance = None
@classmethod
def get_instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
def __init__(self):
self._initialize_db()
ctx = context.get_admin_context()
# Init default service type from configuration file
svc_defs = cfg.CONF.DEFAULT_SERVICETYPE.service_definition
if not svc_defs:
raise NoDefaultServiceDefinition()
def_service_type = {'name': DEFAULT_SVCTYPE_NAME,
'description':
cfg.CONF.DEFAULT_SERVICETYPE.description,
'service_definitions':
parse_service_definition_opt(),
'default': True}
# Create or update record in database
def_svc_type_db = self._get_default_service_type(ctx)
if not def_svc_type_db:
def_svc_type_db = self._create_service_type(ctx, def_service_type)
else:
self._update_service_type(ctx,
def_svc_type_db['id'],
def_service_type,
svc_type_db=def_svc_type_db)
LOG.debug(_("Default service type record updated in Quantum database. "
"identifier is '%s'"), def_svc_type_db['id'])
def _initialize_db(self):
db.configure_db()
# Register models for service type management
# Note this might have been already done if configure_db also
# created the engine
db.register_models(models_v2.model_base.BASEV2)
def _create_service_type(self, context, service_type):
svc_defs = service_type.pop('service_definitions')
with context.session.begin(subtransactions=True):
svc_type_db = ServiceType(**service_type)
# and now insert provided service type definitions
for svc_def in svc_defs:
svc_type_db.service_definitions.append(
ServiceDefinition(**svc_def))
# sqlalchemy save-update on relationship is on by
# default, the following will save both the service
# type and its service definitions
context.session.add(svc_type_db)
return svc_type_db
def _update_service_type(self, context, id, service_type,
svc_type_db=None):
with context.session.begin(subtransactions=True):
if not svc_type_db:
svc_type_db = self._get_service_type(context, id)
try:
svc_defs_map = dict([(svc_def['service'], svc_def)
for svc_def in
service_type.pop('service_definitions')])
except KeyError:
# No service defs in request
svc_defs_map = {}
svc_type_db.update(service_type)
for svc_def_db in svc_type_db.service_definitions:
try:
svc_def_db.update(svc_defs_map.pop(
svc_def_db['service_class']))
except KeyError:
# too bad, the service def was not there
# then we should delete it.
context.session.delete(svc_def_db)
# Add remaining service definitions
for svc_def in svc_defs_map:
context.session.add(ServiceDefinition(**svc_def))
return svc_type_db
def _check_service_type_view_auth(self, context, service_type):
# FIXME(salvatore-orlando): This should be achieved via policy
# engine without need for explicit checks in manager code.
# Also, the policy in this way does not make a lot of sense
return policy.check(context,
"extension:service_type:view_extended",
service_type)
def _get_service_type(self, context, svc_type_id):
try:
query = context.session.query(ServiceType)
return query.filter(ServiceType.id == svc_type_id).one()
# filter is on primary key, do not catch MultipleResultsFound
except orm_exc.NoResultFound:
raise ServiceTypeNotFound(service_type_id=svc_type_id)
def _get_default_service_type(self, context):
try:
query = context.session.query(ServiceType)
return query.filter(ServiceType.default == expr.true()).one()
except orm_exc.NoResultFound:
return
except orm_exc.MultipleResultsFound:
# This should never happen. If it does, take the first instance
query2 = context.session.query(ServiceType)
results = query2.filter(ServiceType.default == expr.true()).all()
LOG.warning(_("Multiple default service type instances found."
"Will use instance '%s'"), results[0]['id'])
return results[0]
def _make_svc_type_dict(self, context, svc_type, fields=None):
def _make_svc_def_dict(svc_def_db):
svc_def = {'service_class': svc_def_db['service_class']}
if self._check_service_type_view_auth(context,
svc_type.as_dict()):
svc_def.update({'plugin': svc_def_db['plugin'],
'driver': svc_def_db['driver']})
return svc_def
res = {'id': svc_type['id'],
'name': svc_type['name'],
'default': svc_type['default'],
'service_definitions':
[_make_svc_def_dict(svc_def) for svc_def
in svc_type['service_definitions']]}
if self._check_service_type_view_auth(context,
svc_type.as_dict()):
res['num_instances'] = svc_type['num_instances']
# Field selection
if fields:
return dict(((k, v) for k, v in res.iteritems()
if k in fields))
return res
def get_service_type(self, context, id, fields=None):
""" Retrieve a service type record """
return self._make_svc_type_dict(context,
self._get_service_type(context, id),
fields)
def get_service_types(self, context, fields=None, filters=None):
""" Retrieve a possibly filtered list of service types """
query = context.session.query(ServiceType)
if filters:
for key, value in filters.iteritems():
column = getattr(ServiceType, key, None)
if column:
query = query.filter(column.in_(value))
return [self._make_svc_type_dict(context, svc_type, fields)
for svc_type in query.all()]
def create_service_type(self, context, service_type):
""" Create a new service type """
svc_type_data = service_type['service_type']
svc_type_db = self._create_service_type(context, svc_type_data)
LOG.debug(_("Created service type object:%s"), svc_type_db['id'])
return self._make_svc_type_dict(context, svc_type_db)
def update_service_type(self, context, id, service_type):
""" Update a service type """
svc_type_data = service_type['service_type']
svc_type_db = self._update_service_type(context, id,
svc_type_data)
return self._make_svc_type_dict(context, svc_type_db)
def delete_service_type(self, context, id):
""" Delete a service type """
# Verify that the service type is not in use.
svc_type_db = self._get_service_type(context, id)
if svc_type_db['num_instances'] > 0:
raise ServiceTypeInUse(service_type_id=svc_type_db['id'])
with context.session.begin(subtransactions=True):
context.session.delete(svc_type_db)
def increase_service_type_refcount(self, context, id):
""" Increase references count for a service type object
This method should be invoked by plugins using the service
type concept everytime an instance of an object associated
with a given service type is created.
"""
#TODO(salvatore-orlando): Devise a better solution than this
#refcount mechanisms. Perhaps adding hooks into models which
#use service types in order to enforce ref. integrity and cascade
with context.session.begin(subtransactions=True):
svc_type_db = self._get_service_type(context, id)
svc_type_db['num_instances'] = svc_type_db['num_instances'] + 1
return svc_type_db['num_instances']
def decrease_service_type_refcount(self, context, id):
""" Decrease references count for a service type object
This method should be invoked by plugins using the service
type concept everytime an instance of an object associated
with a given service type is removed
"""
#TODO(salvatore-orlando): Devise a better solution than this
#refcount mechanisms. Perhaps adding hooks into models which
#use service types in order to enforce ref. integrity and cascade
with context.session.begin(subtransactions=True):
svc_type_db = self._get_service_type(context, id)
if svc_type_db['num_instances'] == 0:
LOG.warning(_("Number of instances for service type "
"'%s' is already 0."), svc_type_db['name'])
return
svc_type_db['num_instances'] = svc_type_db['num_instances'] - 1
return svc_type_db['num_instances']
| {
"content_hash": "c3007ff5fd8469bbc7e70479d7b7155f",
"timestamp": "",
"source": "github",
"line_count": 309,
"max_line_length": 79,
"avg_line_length": 43.996763754045304,
"alnum_prop": 0.5765354909893343,
"repo_name": "rossella/neutron",
"id": "04318a3650fa8d61c274639972c5f4fa55a2657e",
"size": "14313",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "quantum/db/servicetype_db.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "37307"
},
{
"name": "JavaScript",
"bytes": "67928"
},
{
"name": "Perl",
"bytes": "235"
},
{
"name": "Python",
"bytes": "3048930"
},
{
"name": "Shell",
"bytes": "7843"
},
{
"name": "XSLT",
"bytes": "50907"
}
],
"symlink_target": ""
} |
import os
import fast_brute
# read constant
NUM_READS = 1 # change to 30
READ_LEN = 100
# seed constants
SEED_LEN_MIN = 5
SEED_LEN_MAX = 20
MIN_ERRORS = 2
MAX_ERRORS = 5
# input file constants
DATA_DIR = "./Freq-data/"
# output file constants
OUTPUT_FILE = "optimal_seeds.out"
"""
"" begin the main program
"""
# compute the optimal seeds for each read one at a time
f_out = open(OUTPUT_FILE, "w")
for i in range(NUM_READS):
# initialize the data list
seed_freq = []
# read in the necessary data
for j in range(SEED_LEN_MIN, SEED_LEN_MAX + 1):
file_name = DATA_DIR + "seed_" + str(j) + "_" + str(i) + ".dat"
f = open(file_name, "r")
file_lines = f.read().strip("\n").split("\n")
seed_freq_tmp = []
for line in file_lines:
frequency = line.split("\t")[-1]
seed_freq_tmp.append(frequency)
seed_freq.append(seed_freq_tmp)
# call the optimal seed finder routine
for errors in range(MIN_ERRORS, MAX_ERRORS + 1):
optimal_seed_loc = fast_brute.find_optimal_seeds(seed_freq, READ_LEN, SEED_LEN_MIN, SEED_LEN_MAX, errors, 10000)
# print solution to a file!
f_out.write("Errors: " + str(errors) + "\n--------\n" + optimal_seed_loc + "--------")
f_out.flush()
| {
"content_hash": "19b2485341ac0ec7ec54fbf636368141",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 120,
"avg_line_length": 26.73469387755102,
"alnum_prop": 0.5877862595419847,
"repo_name": "xhongyi/toybrick",
"id": "bebe0c144960ee9e8f690c7185b287e4507fc996",
"size": "1328",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Seed-frequency/Optimal-seed/Optimal-seed-C/optimal_seed_finder.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "1922198"
},
{
"name": "C++",
"bytes": "227263"
},
{
"name": "Cuda",
"bytes": "60179"
},
{
"name": "Gnuplot",
"bytes": "46042"
},
{
"name": "JavaScript",
"bytes": "599"
},
{
"name": "Objective-C",
"bytes": "23649"
},
{
"name": "Python",
"bytes": "112101"
},
{
"name": "Shell",
"bytes": "10062"
},
{
"name": "TeX",
"bytes": "46311"
}
],
"symlink_target": ""
} |
"""All exceptions used in the Cookiecutter code base are defined here."""
class CookiecutterException(Exception):
"""
Base exception class.
All Cookiecutter-specific exceptions should subclass this class.
"""
class NonTemplatedInputDirException(CookiecutterException):
"""
Exception for when a project's input dir is not templated.
The name of the input directory should always contain a string that is
rendered to something else, so that input_dir != output_dir.
"""
class UnknownTemplateDirException(CookiecutterException):
"""
Exception for ambiguous project template directory.
Raised when Cookiecutter cannot determine which directory is the project
template, e.g. more than one dir appears to be a template dir.
"""
# unused locally
class MissingProjectDir(CookiecutterException):
"""
Exception for missing generated project directory.
Raised during cleanup when remove_repo() can't find a generated project
directory inside of a repo.
"""
# unused locally
class ConfigDoesNotExistException(CookiecutterException):
"""
Exception for missing config file.
Raised when get_config() is passed a path to a config file, but no file
is found at that path.
"""
class InvalidConfiguration(CookiecutterException):
"""
Exception for invalid configuration file.
Raised if the global configuration file is not valid YAML or is
badly constructed.
"""
class UnknownRepoType(CookiecutterException):
"""
Exception for unknown repo types.
Raised if a repo's type cannot be determined.
"""
class VCSNotInstalled(CookiecutterException):
"""
Exception when version control is unavailable.
Raised if the version control system (git or hg) is not installed.
"""
class ContextDecodingException(CookiecutterException):
"""
Exception for failed JSON decoding.
Raised when a project's JSON context file can not be decoded.
"""
class OutputDirExistsException(CookiecutterException):
"""
Exception for existing output directory.
Raised when the output directory of the project exists already.
"""
class InvalidModeException(CookiecutterException):
"""
Exception for incompatible modes.
Raised when cookiecutter is called with both `no_input==True` and
`replay==True` at the same time.
"""
class FailedHookException(CookiecutterException):
"""
Exception for hook failures.
Raised when a hook script fails.
"""
class UndefinedVariableInTemplate(CookiecutterException):
"""
Exception for out-of-scope variables.
Raised when a template uses a variable which is not defined in the
context.
"""
def __init__(self, message, error, context):
"""Exception for out-of-scope variables."""
self.message = message
self.error = error
self.context = context
def __str__(self):
"""Text representation of UndefinedVariableInTemplate."""
return (
"{self.message}. "
"Error message: {self.error.message}. "
"Context: {self.context}"
).format(**locals())
class UnknownExtension(CookiecutterException):
"""
Exception for un-importable extention.
Raised when an environment is unable to import a required extension.
"""
class RepositoryNotFound(CookiecutterException):
"""
Exception for missing repo.
Raised when the specified cookiecutter repository doesn't exist.
"""
class RepositoryCloneFailed(CookiecutterException):
"""
Exception for un-cloneable repo.
Raised when a cookiecutter template can't be cloned.
"""
class InvalidZipRepository(CookiecutterException):
"""
Exception for bad zip repo.
Raised when the specified cookiecutter repository isn't a valid
Zip archive.
"""
| {
"content_hash": "3e3b04a483dd731d4dc5d1201d796bf4",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 76,
"avg_line_length": 23.938650306748468,
"alnum_prop": 0.6960533059969246,
"repo_name": "audreyr/cookiecutter",
"id": "9461aa9851cda30fbd2e1fe6aa0b67ca5ca02ee8",
"size": "3902",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "cookiecutter/exceptions.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Makefile",
"bytes": "3206"
},
{
"name": "Python",
"bytes": "215812"
},
{
"name": "Shell",
"bytes": "161"
}
],
"symlink_target": ""
} |
import scrapy
from scrapy import signals, Spider
from urllib.parse import urlencode
import time
from random import randint
import datetime
import logging
from copy import copy
from dateutil.relativedelta import relativedelta
import collections
import json
from bs4 import BeautifulSoup
from random import randint
from zoneinfo import ZoneInfo
# for cloud function call && scrapy crawl command call
# softlink package folder to root
try:
from package.tools import is_settle, format_number, getDateObj
from package.storage import Storage
except:
from spiders.package.tools import is_settle, format_number, getDateObj
from spiders.package.storage import Storage
class StockFuturesListSpider(scrapy.Spider):
name = 'stock_futures_list'
def __init__(self, category=None, *args, **kwargs):
super(StockFuturesListSpider, self).__init__(*args, **kwargs)
self.dataStorage = Storage(self.name)
self.data = collections.OrderedDict()
self.url = 'https://www.taifex.com.tw/cht/2/stockLists'
def start_requests(self):
print('start request - %s' % self.name)
time.sleep(randint(2,3))
yield scrapy.FormRequest(
url=self.url,
callback=self.parse,
errback=self.handle_failure)
def handle_failure(self, failure):
self.log(failure, level=logging.ERROR)
# try with a new proxy
self.log('restart from the failed url {}'.format(failure.request.url))
time.sleep(120)
yield scrapy.FormRequest(
url=failure.request.url,
callback=self.parse,
errback=self.handle_failure)
def parse(self, response):
soup = BeautifulSoup(response.text, "lxml")
table = soup.select_one("#myTable tbody")
self.stockList = []
try:
trList = table.select("tr")
for tr in trList:
stockData = {}
stockData['productCode'] = tr.select("td")[0].text.strip()
stockData['code'] = tr.select("td")[2].text.strip()
stockData['name'] = tr.select("td")[3].text.strip()
stockData['isFutures'] = True if len(tr.select("td")[4].contents) > 1 else False
stockData['isOption'] = True if len(tr.select("td")[5].contents) > 1 else False
stockData['stockNumber'] = tr.select("td")[9].text.strip()
self.stockList.append(stockData)
except Exception as e:
print('error - %s' % self.name)
print(e)
@classmethod
def from_crawler(cls, crawler, *args, **kwargs):
spider = super(StockFuturesListSpider, cls).from_crawler(crawler, *args, **kwargs)
crawler.signals.connect(spider.spider_closed, signal=signals.spider_closed)
return spider
def spider_closed(self, spider):
fileName = self.name
self.dataStorage.saveData(fileName, self.stockList)
| {
"content_hash": "6011368b2444cf1ba645762e6901eb1a",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 96,
"avg_line_length": 33.111111111111114,
"alnum_prop": 0.6332214765100671,
"repo_name": "ChuangYuMing/futures_spread_analysis",
"id": "2b0f4a69b8c46c39d8ce80e80cfd8f44f4178167",
"size": "3090",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "crawler/spiders/stock_futures_list_spider.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "283"
},
{
"name": "HTML",
"bytes": "2797"
},
{
"name": "JavaScript",
"bytes": "50376"
},
{
"name": "Python",
"bytes": "55015"
}
],
"symlink_target": ""
} |
"""
Implementation of a feature which maps integers to binary-valued vectors, with
the resulting vector having all entries zero except at the index indicated by
the supplied integer.
Can be used to represent the tabular case in terms of arrays, for example.
"""
import numpy as np
from flib.abstract import UnaryFeature
class Int2Unary(UnaryFeature):
def __init__(self, length):
self.length = length
self._array = np.eye(length)
def __call__(self, x):
# TODO: Implement using the `apply` style, with `__call__` as dispatch
return self._array[x] | {
"content_hash": "558daa9e8d42ed638ff0c314930dad27",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 78,
"avg_line_length": 31,
"alnum_prop": 0.7011884550084889,
"repo_name": "rldotai/flib",
"id": "3f08c3db47668724674f853ffde2ea263a7f8fab",
"size": "589",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "flib/int2unary.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Makefile",
"bytes": "1984"
},
{
"name": "Python",
"bytes": "24614"
}
],
"symlink_target": ""
} |
import _plotly_utils.basevalidators
class CmidValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="cmid", parent_name="scatter3d.marker", **kwargs):
super(CmidValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
implied_edits=kwargs.pop("implied_edits", {}),
role=kwargs.pop("role", "info"),
**kwargs
)
| {
"content_hash": "a9cd4970a3f3ea73a34c884343f7f1b1",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 85,
"avg_line_length": 38.46153846153846,
"alnum_prop": 0.6,
"repo_name": "plotly/python-api",
"id": "740983d49d2c621a72a78c7d9d89e45da217fd29",
"size": "500",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/python/plotly/plotly/validators/scatter3d/marker/_cmid.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "6870"
},
{
"name": "Makefile",
"bytes": "1708"
},
{
"name": "Python",
"bytes": "823245"
},
{
"name": "Shell",
"bytes": "3238"
}
],
"symlink_target": ""
} |
'''
Comparison of Continuous No-Regret Algorithms for the 2nd NIPS paper
@author: Maximilian Balandat
@date: May 11, 2015
'''
# Set up infrastructure and basic problem parameters
import multiprocessing as mp
import numpy as np
import datetime, os
from ContNoRegret.Domains import nBox, UnionOfDisjointnBoxes, DifferenceOfnBoxes, unitbox, hollowbox
from ContNoRegret.LossFunctions import random_PolynomialLosses
from ContNoRegret.NoRegretAlgos import ContNoRegretProblem
from ContNoRegret.utils import CNR_worker, plot_results, save_results, circular_tour
from ContNoRegret.animate import save_animations
from ContNoRegret.Potentials import (ExponentialPotential, IdentityPotential, pNormPotential, CompositePotential,
ExpPPotential, PExpPotential, HuberPotential, LogtasticPotential, FractionalLinearPotential)
# this is the location of the folder for the results
results_path = '/Users/balandat/Documents/Code/Continuous_No-Regret/results/'
desc = 'NIPS2_CNR_ConvQuad'
tmpfolder = '/Volumes/tmp/' # if possible, choose this to be a RamDisk
# some flags for keeping a record of the simulation parameters
save_res = True
show_plots = True
save_anims = False
show_anims = False
T = 2500 # Time horizon
M = 10.0 # Uniform bound on the function (in the dual norm)
L = 5.0 # Uniform bound on the Lipschitz constant
N = 2500 # Number of parallel algorithm instances
Ngrid = 250000 # Number of gridpoints for the sampling step
H = 0.1 # strict convexity parameter (lower bound on evals of Q)
dom = unitbox(2)
# before running the computation, read this file so we can later save a copy in the results folder
with open(__file__, 'r') as f:
thisfile = f.read()
# # Now create some random loss functions
lossfuncs = random_PolynomialLosses(dom, T, M, L, 3, [0,1,2,3])
# # compute bounds on the norms
# normbounds = {'{}'.format(p): [lossfunc.norm(p, tmpfolder=tmpfolder) for lossfunc in lossfuncs] for p in [1,2,np.Infinity]}
# normmax = {key:np.max(val) for key,val in normbounds.items()}
# print(normmax)
# create Continuous No-Regret problem
prob = ContNoRegretProblem(dom, lossfuncs, L, M, desc=desc)
# Select a number of potentials for the Dual Averaging algorithm
potentials = [ExponentialPotential(), pNormPotential(1.25), pNormPotential(1.75),
FractionalLinearPotential(1.25), FractionalLinearPotential(2.5), FractionalLinearPotential(10)]
# the following runs fine if the script is the __main__ method, but crashes when running from ipython
pool = mp.Pool(processes=mp.cpu_count()-1)
processes = []
DAkwargs = [{'opt_rate':True, 'Ngrid':Ngrid, 'potential':pot, 'pid':i,
'tmpfolder':tmpfolder, 'label':pot.desc} for i,pot in enumerate(potentials)]
processes += [pool.apply_async(CNR_worker, (prob, N, 'DA'), kwarg) for kwarg in DAkwargs]
# GPkwargs = {'Ngrid':Ngrid, 'pid':len(processes), 'tmpfolder':tmpfolder, 'label':'GP'}
# processes.append(pool.apply_async(CNR_worker, (prob, N, 'GP'), GPkwargs))
# OGDkwargs = {'H':H, 'Ngrid':Ngrid, 'pid':len(processes), 'tmpfolder':tmpfolder, 'label':'OGD'}
# processes.append(pool.apply_async(CNR_worker, (prob, N, 'OGD'), OGDkwargs))
#
# ONSkwargs = {'alpha':alpha_ec, 'Ngrid':Ngrid, 'pid':len(processes), 'tmpfolder':tmpfolder, 'label':'ONS'}
# processes.append(pool.apply_async(CNR_worker, (prob, N, 'ONS'), ONSkwargs))
#
# FTALkwargs = {'alpha':alpha_ec, 'Ngrid':Ngrid, 'pid':len(processes), 'tmpfolder':tmpfolder, 'label':'FTAL'}
# processes.append(pool.apply_async(CNR_worker, (prob, N, 'FTAL'), FTALkwargs))
#
# EWOOkwargs = {'alpha':alpha_ec, 'Ngrid':Ngrid, 'pid':len(processes), 'tmpfolder':tmpfolder, 'label':'EWOO'}
# processes.append(pool.apply_async(CNR_worker, (prob, N, 'EWOO'), EWOOkwargs))
# wait for the processes to finish an collect the results
results = [process.get() for process in processes]
# plot results and/or save a persistent copy (pickled) of the detailed results
timenow = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M')# create a time stamp for unambiguously naming the results folder
results_directory = '{}{}/'.format(results_path, timenow)
if save_res:
os.makedirs(results_directory, exist_ok=True) # this could probably use a safer implementation
plot_results(results, 100, results_directory, show_plots)
if save_anims:
save_animations(results, 10, results_directory, show_anims)
save_results(results, results_directory)
# store the previously read-in contents of this file in the results folder
with open(results_directory+str(__file__), 'w') as f:
f.write(thisfile)
else:
plot_results(results, offset=100)
| {
"content_hash": "24f02cabe5ccdd5b0428d7336a2b4620",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 132,
"avg_line_length": 46.58,
"alnum_prop": 0.7241305281236582,
"repo_name": "Balandat/cont_no_regret",
"id": "f41fc3d73cbef552f6ceb02abbc2a14a6cd7d2d9",
"size": "4658",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "NIPS2_CNR_Polynomial.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "3557"
},
{
"name": "Python",
"bytes": "379837"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import, print_function, unicode_literals
from django.conf.urls import patterns, url, include
from .core import Upload
urlpatterns = patterns(
'',
url(r'^qq/', include('api.qq.urls', namespace='qq')),
url(r'^members/', include('api.member.urls', namespace='member')),
url(r'^books/', include('api.book.urls', namespace='book')),
url(r'^blog/', include('api.blog.urls', namespace='blog')),
url(r'^upload/$', Upload.as_view(), name='upload'),
)
| {
"content_hash": "0e9071640e3b39dd07840d26786bdb24",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 72,
"avg_line_length": 35.785714285714285,
"alnum_prop": 0.656686626746507,
"repo_name": "mozillazg/chendian-plus",
"id": "2c307626d7923d3f931eaa12834ae28867089639",
"size": "547",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chendian/api/urls.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6402"
},
{
"name": "CoffeeScript",
"bytes": "25108"
},
{
"name": "HTML",
"bytes": "76739"
},
{
"name": "JavaScript",
"bytes": "94942"
},
{
"name": "Makefile",
"bytes": "1286"
},
{
"name": "Python",
"bytes": "169588"
}
],
"symlink_target": ""
} |
import unittest
from absl.testing import absltest
from absl.testing import parameterized
import tensorflow as tf
from tensorflow_federated.python.core.impl.compiler import building_block_factory
from tensorflow_federated.python.core.impl.executors import eager_tf_executor
from tensorflow_federated.python.core.impl.executors import executor_test_utils
from tensorflow_federated.python.core.impl.executors import executor_utils
from tensorflow_federated.python.core.impl.executors import executor_value_base
from tensorflow_federated.python.core.impl.executors import federated_composing_strategy
from tensorflow_federated.python.core.impl.executors import federated_resolving_strategy
from tensorflow_federated.python.core.impl.executors import federating_executor
from tensorflow_federated.python.core.impl.executors import reference_resolving_executor
from tensorflow_federated.python.core.impl.types import computation_types
from tensorflow_federated.python.core.impl.types import placements
def create_test_federated_stack(
num_clients=3) -> federating_executor.FederatingExecutor:
def create_bottom_stack():
executor = eager_tf_executor.EagerTFExecutor()
return reference_resolving_executor.ReferenceResolvingExecutor(executor)
factory = federated_resolving_strategy.FederatedResolvingStrategy.factory({
placements.SERVER: create_bottom_stack(),
placements.CLIENTS: [create_bottom_stack() for _ in range(num_clients)],
})
return federating_executor.FederatingExecutor(factory, create_bottom_stack())
def create_test_aggregated_stack(
clients_per_stack=3,
stacks_per_layer=3,
num_layers=3) -> federating_executor.FederatingExecutor:
def create_bottom_stack():
executor = eager_tf_executor.EagerTFExecutor()
return reference_resolving_executor.ReferenceResolvingExecutor(executor)
def create_worker_stack():
factroy = federated_resolving_strategy.FederatedResolvingStrategy.factory({
placements.SERVER:
create_bottom_stack(),
placements.CLIENTS: [
create_bottom_stack() for _ in range(clients_per_stack)
],
})
return federating_executor.FederatingExecutor(factroy,
create_bottom_stack())
def create_aggregation_stack(children):
factory = federated_composing_strategy.FederatedComposingStrategy.factory(
create_bottom_stack(), children)
return federating_executor.FederatingExecutor(factory,
create_bottom_stack())
def create_aggregation_layer(num_stacks):
return create_aggregation_stack(
[create_worker_stack() for _ in range(num_stacks)])
return create_aggregation_stack(
[create_aggregation_layer(stacks_per_layer) for _ in range(num_layers)])
# pyformat: disable
@parameterized.named_parameters([
('federated_stack',
create_test_federated_stack(),
3),
('aggregated_stack_9_clients',
create_test_aggregated_stack(
clients_per_stack=3, stacks_per_layer=3, num_layers=1),
9),
('aggregated_stack_27_clients',
create_test_aggregated_stack(
clients_per_stack=3, stacks_per_layer=3, num_layers=3),
27),
])
# pyformat: enable
class ComputeIntrinsicFederatedBroadcastTest(unittest.IsolatedAsyncioTestCase,
parameterized.TestCase):
async def test_returns_value_with_federated_type_at_server(
self, executor, num_clients):
del num_clients # Unused.
value, type_signature = executor_test_utils.create_whimsy_value_at_server()
value = await executor.create_value(value, type_signature)
result = await executor_utils.compute_intrinsic_federated_broadcast(
executor, value)
self.assertIsInstance(result, executor_value_base.ExecutorValue)
expected_type = computation_types.at_clients(
type_signature.member, all_equal=True)
self.assertEqual(result.type_signature.compact_representation(),
expected_type.compact_representation())
actual_result = await result.compute()
self.assertEqual(actual_result, 10.0)
async def test_raises_type_error_with_federated_type_at_clients(
self, executor, num_clients):
value, type_signature = executor_test_utils.create_whimsy_value_at_clients(
num_clients)
value = await executor.create_value(value, type_signature)
with self.assertRaises(TypeError):
await executor_utils.compute_intrinsic_federated_broadcast(
executor, value)
async def test_raises_type_error_with_unplaced_type(self, executor,
num_clients):
del num_clients # Unused.
value, type_signature = executor_test_utils.create_whimsy_value_unplaced()
value = await executor.create_value(value, type_signature)
with self.assertRaises(TypeError):
await executor_utils.compute_intrinsic_federated_broadcast(
executor, value)
# pyformat: disable
@parameterized.named_parameters([
('federated_stack',
create_test_federated_stack()),
('aggregated_stack_9_clients',
create_test_aggregated_stack(
clients_per_stack=3, stacks_per_layer=3, num_layers=1)),
('aggregated_stack_27_clients',
create_test_aggregated_stack(
clients_per_stack=3, stacks_per_layer=3, num_layers=3)),
])
# pyformat: enable
class ComputeIntrinsicFederatedValueTest(unittest.IsolatedAsyncioTestCase,
parameterized.TestCase):
async def test_returns_value_with_unplaced_type_and_clients(self, executor):
value, type_signature = executor_test_utils.create_whimsy_value_unplaced()
value = await executor.create_value(value, type_signature)
result = await executor_utils.compute_intrinsic_federated_value(
executor, value, placements.CLIENTS)
self.assertIsInstance(result, executor_value_base.ExecutorValue)
expected_type = computation_types.at_clients(type_signature, all_equal=True)
self.assertEqual(result.type_signature.compact_representation(),
expected_type.compact_representation())
actual_result = await result.compute()
self.assertEqual(actual_result, 10.0)
async def test_returns_value_with_unplaced_type_and_server(self, executor):
value, type_signature = executor_test_utils.create_whimsy_value_unplaced()
value = await executor.create_value(value, type_signature)
result = await executor_utils.compute_intrinsic_federated_value(
executor, value, placements.SERVER)
self.assertIsInstance(result, executor_value_base.ExecutorValue)
expected_type = computation_types.at_server(type_signature)
self.assertEqual(result.type_signature.compact_representation(),
expected_type.compact_representation())
actual_result = await result.compute()
self.assertEqual(actual_result, 10.0)
class ComputeIntrinsicFederatedWeightedMeanTest(
unittest.IsolatedAsyncioTestCase, parameterized.TestCase):
# pyformat: disable
@parameterized.named_parameters([
('default_strategy_3_clients',
create_test_federated_stack(3),
3),
('default_strategy_10_clients',
create_test_federated_stack(10),
10),
('aggregated_stack_9_clients',
create_test_aggregated_stack(
clients_per_stack=3, stacks_per_layer=3, num_layers=1),
9),
('aggregated_stack_27_clients',
create_test_aggregated_stack(
clients_per_stack=3, stacks_per_layer=3, num_layers=3),
27),
])
# pyformat: enable
async def test_computes_weighted_mean(
self,
executor,
num_clients,
):
value, type_signature = executor_test_utils.create_whimsy_value_at_clients(
num_clients)
# Weighted mean computed in Python
expected_result = sum([x**2 for x in value]) / sum(value)
value = await executor.create_value(value, type_signature)
arg = await executor.create_struct([value, value])
result = await executor_utils.compute_intrinsic_federated_weighted_mean(
executor, arg)
self.assertIsInstance(result, executor_value_base.ExecutorValue)
expected_type = computation_types.at_server(type_signature.member)
self.assertEqual(result.type_signature.compact_representation(),
expected_type.compact_representation())
actual_result = await result.compute()
self.assertEqual(actual_result, expected_result)
# pyformat: disable
@parameterized.named_parameters([
('default_strategy_unplaced_type',
create_test_federated_stack(),
executor_test_utils.create_whimsy_value_unplaced()),
('composing_strategy_unplaced_type',
create_test_aggregated_stack(),
executor_test_utils.create_whimsy_value_unplaced()),
('default_strategy_server_placement',
create_test_federated_stack(),
executor_test_utils.create_whimsy_value_at_server()),
('composing_strategy_server_placement',
create_test_aggregated_stack(),
executor_test_utils.create_whimsy_value_at_server()),
])
# pyformat: enable
async def test_raises_type_error(self, executor, value_and_type_signature):
value, type_signature = value_and_type_signature
value = await executor.create_value(value, type_signature)
arg = await executor.create_struct([value, value])
with self.assertRaises(TypeError):
await executor_utils.compute_intrinsic_federated_weighted_mean(
executor, arg)
# pyformat: disable
@parameterized.named_parameters([
('federated_stack',
create_test_federated_stack(),
3),
('composing_strategy',
create_test_aggregated_stack(),
27),
])
# pyformat: enable
async def test_raises_type_error_with_singleton_tuple(
self,
executor,
num_clients,
):
value, type_signature = executor_test_utils.create_whimsy_value_at_clients(
num_clients)
value = await executor.create_value(value, type_signature)
arg = await executor.create_struct([value])
with self.assertRaises(TypeError):
await executor_utils.compute_intrinsic_federated_weighted_mean(
executor, arg)
class TypeUtilsTest(parameterized.TestCase):
# pyformat: disable
@parameterized.named_parameters([
('buiding_block_and_type_spec',
building_block_factory.create_compiled_identity(
computation_types.TensorType(tf.int32)),
computation_types.FunctionType(tf.int32, tf.int32),
computation_types.FunctionType(tf.int32, tf.int32)),
('buiding_block_and_none',
building_block_factory.create_compiled_identity(
computation_types.TensorType(tf.int32)),
None,
computation_types.FunctionType(tf.int32, tf.int32)),
('int_and_type_spec',
10,
computation_types.TensorType(tf.int32),
computation_types.TensorType(tf.int32)),
])
# pyformat: enable
def test_reconcile_value_with_type_spec_returns_type(self, value, type_spec,
expected_type):
actual_type = executor_utils.reconcile_value_with_type_spec(
value, type_spec)
self.assertEqual(actual_type, expected_type)
# pyformat: disable
@parameterized.named_parameters([
('building_block_and_bad_type_spec',
building_block_factory.create_compiled_identity(
computation_types.TensorType(tf.int32)),
computation_types.TensorType(tf.int32)),
('int_and_none', 10, None),
])
# pyformat: enable
def test_reconcile_value_with_type_spec_raises_type_error(
self, value, type_spec):
with self.assertRaises(TypeError):
executor_utils.reconcile_value_with_type_spec(value, type_spec)
# pyformat: disable
@parameterized.named_parameters([
('value_type_and_type_spec',
computation_types.TensorType(tf.int32),
computation_types.TensorType(tf.int32),
computation_types.TensorType(tf.int32)),
('value_type_and_none',
computation_types.TensorType(tf.int32),
None,
computation_types.TensorType(tf.int32)),
])
# pyformat: enable
def test_reconcile_value_type_with_type_spec_returns_type(
self, value_type, type_spec, expected_type):
actual_type = executor_utils.reconcile_value_type_with_type_spec(
value_type, type_spec)
self.assertEqual(actual_type, expected_type)
def test_reconcile_value_type_with_type_spec_raises_type_error_value_type_and_bad_type_spec(
self):
value_type = computation_types.TensorType(tf.int32)
type_spec = computation_types.TensorType(tf.string)
with self.assertRaises(TypeError):
executor_utils.reconcile_value_type_with_type_spec(value_type, type_spec)
if __name__ == '__main__':
absltest.main()
| {
"content_hash": "c1721f42674174618d3a9c7e0a9ab9d5",
"timestamp": "",
"source": "github",
"line_count": 332,
"max_line_length": 94,
"avg_line_length": 38.70783132530121,
"alnum_prop": 0.6985448603221539,
"repo_name": "tensorflow/federated",
"id": "dfe991bc16bd9e84adf6f2f6109b9cd560eac329",
"size": "13451",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "tensorflow_federated/python/core/impl/executors/executor_utils_test.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "729470"
},
{
"name": "Dockerfile",
"bytes": "1983"
},
{
"name": "Python",
"bytes": "6700736"
},
{
"name": "Shell",
"bytes": "7123"
},
{
"name": "Starlark",
"bytes": "387382"
}
],
"symlink_target": ""
} |
"""
Publish a digital object as a public resource for anyone
NOTE: this package will be loaded only if IRODS_ANONYMOUS is set
"""
from b2stage.apis.commons.endpoint import EudatEndpoint
from restapi import decorators as decorate
from restapi.protocols.bearer import authentication
from b2stage.apis.commons import path
from restapi.utilities.htmlcodes import hcodes
from restapi.utilities.logs import log
class Publish(EudatEndpoint):
# schema_expose = True
labels = ['eudat', 'publish']
depends_on = ['IRODS_ANONYMOUS', 'ENABLE_PUBLIC_ENDPOINT']
GET = {
'/publish/<path:location>': {
'custom': {},
'summary': 'Check if the path is currently readable for the anonymous user',
'responses': {'200': {'description': "return a boolean 'published'"}},
}
}
PUT = {
'/publish/<path:location>': {
'custom': {},
'summary': 'set the path to be readable for the anonymous user',
'responses': {'200': {'description': "return a boolean 'published'"}},
}
}
DELETE = {
'/publish/<path:location>': {
'custom': {},
'summary': 'Ensure that the path is not accessible for the anonymous user',
'responses': {'200': {'description': "return a boolean 'published'"}},
}
}
def base(self, location):
if location is None:
return (
self.send_errors(
'Location: missing filepath inside URI',
code=hcodes.HTTP_BAD_REQUEST,
),
None,
None,
)
else:
location = self.fix_location(location)
r = self.init_endpoint()
if r.errors is not None:
return self.send_errors(errors=r.errors), None, None
path, resource, filename, _ = self.get_file_parameters(
r.icommands, path=location
)
# if r.icommands.is_collection(path):
# return self.send_errors(
# 'Provided path is a collection. ' +
# 'Publishing is not allowed as recursive.',
# code=hcodes.HTTP_NOT_IMPLEMENTED
# ), None, None
# Does this path exist?
if not r.icommands.exists(path):
return (
self.send_errors(
errors=[
{'path': "'{}': not existing or no permissions".format(path)}
],
code=hcodes.HTTP_BAD_NOTFOUND,
),
None,
None,
)
return None, r, path
def single_path_check(self, icom, zone, abs_path, check=True):
permissions = icom.get_permissions(abs_path)
acls = permissions.get('ACL', [])
published = False
for acl_user, acl_zone, acl_mode in acls:
if acl_zone == zone and acl_user == icom.anonymous_user:
if check:
if 'read' in acl_mode:
published = True
break
return published
def single_permission(self, icom, ipath, permission=None):
icom.set_permissions(
ipath,
# NOTE: permission could be: read, write, null/None
permission=permission,
userOrGroup=icom.anonymous_user,
) # , recursive=False)
# FIXME: should we publish recursively to subfiles and subfolders?
# NOTE: It looks dangerous to me
def publish_helper(self, icom, ipath, check_only=True, unpublish=False):
current_zone = icom.get_current_zone()
ipath_steps = path.parts(ipath)
current = ''
for ipath_step in ipath_steps:
current = path.join(current, ipath_step, return_str=True)
# print("PUB STEP:", ipath_step, current, len(current))
# to skip: root dir, zone and home
if (
len(ipath_step) == 1
or ipath_step == current_zone
or ipath_step == 'home'
):
continue
# find out if already published
check = self.single_path_check(icom, current_zone, str(current))
# if only checking
if check_only and not check:
return False
# otherwise you want to publish/unpublish this path
else:
if unpublish:
self.single_permission(icom, current, permission=None)
else:
self.single_permission(icom, current, permission='read')
return True
@staticmethod
def public_path(path):
# prepare the url to access
from b2stage.apis.commons import CURRENT_HTTPAPI_SERVER
from b2stage.apis.commons import PUBLIC_ENDPOINT
return '{}{}{}'.format(CURRENT_HTTPAPI_SERVER, PUBLIC_ENDPOINT, path)
@decorate.catch_error()
@authentication.required()
def get(self, location):
error, handler, path = self.base(location)
if error is not None:
return error
icom = handler.icommands
user = icom.get_current_user()
log.info("user '{}' requested to check '{}'", user, path)
if icom.is_collection(path):
return self.send_errors(
'Collections are not allowed to be published',
code=hcodes.HTTP_BAD_REQUEST,
)
else:
published = self.publish_helper(icom, path)
response = {'published': published}
if published:
response['public_url'] = self.public_path(path)
return response
@decorate.catch_error()
@authentication.required()
def put(self, location=None):
error, handler, path = self.base(location)
if error is not None:
return error
icom = handler.icommands
user = icom.get_current_user()
log.info("user '{}' requested to publish '{}'", user, path)
if icom.is_collection(path):
return self.send_errors(
'Collections are not allowed to be published',
code=hcodes.HTTP_BAD_REQUEST,
)
# if already set as the same don't do anything
if not self.publish_helper(icom, path):
self.publish_helper(icom, path, check_only=False, unpublish=False)
# # If you'd like to check again:
# return {'published': self.publish_helper(icom, path)}
return {'published': True, 'public_url': self.public_path(path)}
@decorate.catch_error()
@authentication.required()
def delete(self, location):
error, handler, path = self.base(location)
if error is not None:
return error
icom = handler.icommands
user = icom.get_current_user()
log.info("user '{}' requested to UNpublish '{}'", user, path)
if icom.is_collection(path):
return self.send_errors(
'Collections are not allowed to be published',
code=hcodes.HTTP_BAD_REQUEST,
)
# if not already set as the same don't do anything
if self.publish_helper(icom, path):
self.publish_helper(icom, path, check_only=False, unpublish=True)
# # If you'd like to check again:
# return {'published': self.publish_helper(icom, path)}
return {'published': False}
| {
"content_hash": "7f7832d052932e74d8162d09f8aec6f0",
"timestamp": "",
"source": "github",
"line_count": 228,
"max_line_length": 88,
"avg_line_length": 32.85964912280702,
"alnum_prop": 0.5525894287239722,
"repo_name": "EUDAT-B2STAGE/http-api",
"id": "3f3091ccc248f814e7ca26eb2c369d6f2bcf32c3",
"size": "7517",
"binary": false,
"copies": "1",
"ref": "refs/heads/1.1.1",
"path": "projects/b2stage/backend/apis/publish.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "2409"
},
{
"name": "HTML",
"bytes": "984"
},
{
"name": "Python",
"bytes": "304207"
},
{
"name": "Shell",
"bytes": "7226"
}
],
"symlink_target": ""
} |
"""
This module defines constants that don't fit into tool or inteferface
categories
"""
from pfp.native import predefine
predefine(
"""
const int true = 1;
const int True = 1;
const int TRUE = 1;
const int false = 0;
const int False = 0;
const int FALSE = 0;
"""
)
| {
"content_hash": "4b8fb2bed26cc6f5f69cd8b8df4693b4",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 69,
"avg_line_length": 14.95,
"alnum_prop": 0.6220735785953178,
"repo_name": "d0c-s4vage/pfp",
"id": "2e3cbbeb12bda0462f0e196d08ee80d72e508d77",
"size": "347",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pfp/native/compat_consts.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "456356"
},
{
"name": "Shell",
"bytes": "293"
}
],
"symlink_target": ""
} |
"""Set module version.
<Major>.<Minor>.<maintenance>[alpha/beta/..]
Alphas will be numbered like this -> 0.4.0a0
"""
VERSION = '0.1'
| {
"content_hash": "02706167d1d47719a1fa744ece13a6ad",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 44,
"avg_line_length": 22.333333333333332,
"alnum_prop": 0.6567164179104478,
"repo_name": "Parsl/parsl",
"id": "e78007161adfa817699b7d47fe311b7a4c169739",
"size": "134",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "parsl/monitoring/visualization/version.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1263"
},
{
"name": "CSS",
"bytes": "337"
},
{
"name": "HTML",
"bytes": "12706"
},
{
"name": "Makefile",
"bytes": "4908"
},
{
"name": "Python",
"bytes": "1173869"
},
{
"name": "Shell",
"bytes": "12057"
}
],
"symlink_target": ""
} |
from dp_tornado.engine.controller import Controller
class DynamodbController(Controller):
def get(self):
for _ in range(3):
try:
table_name = 'dp_test_%s' % self.ini.server.identifier
index_columns = [
('key1', self.helper.web.aws.dynamodb.table.column.number, self.helper.web.aws.dynamodb.table.indexing.partition),
('key2', self.helper.web.aws.dynamodb.table.column.string)
]
created = self.helper.web.aws.dynamodb.table.create(
access_key_id=self.ini.static.aws_id,
secret_access_key=self.ini.static.aws_secret,
region_name=self.ini.static.aws_region,
table_name=table_name,
index_columns=index_columns,
wait_until_exists=True)
assert created
described = self.helper.web.aws.dynamodb.table.describe(
access_key_id=self.ini.static.aws_id,
secret_access_key=self.ini.static.aws_secret,
region_name=self.ini.static.aws_region,
table_name=table_name,
wait_until_exists=True)
assert described and described['Table']['TableStatus'] == 'ACTIVE'
items = (
{
'key1': 100,
'key2': 'a',
'ts': self.helper.datetime.timestamp.now(ms=True),
'identifier': self.ini.server.identifier
},
{
'key1': 110,
'key2': 'a',
'p1': 123,
'p2': 'abc',
'p3': None,
'p4': True,
'p5': False,
'p6': [1, 2],
'p7': ['한글', 123],
'p8': {
'a1': 123,
'a2': 'abc',
'a3': '한글',
'a4': [1, 2, 3],
'a5': ['abc', 123, 'def'],
'a6': True,
'a7': None
},
'ts': self.helper.datetime.timestamp.now(ms=True),
'identifier': self.ini.server.identifier
},
{
'key1': 120,
'key2': 'b',
'desc': 'will be deleted.',
'identifier': self.ini.server.identifier
}
)
inserted = self.helper.web.aws.dynamodb.item.put(
access_key_id=self.ini.static.aws_id,
secret_access_key=self.ini.static.aws_secret,
region_name=self.ini.static.aws_region,
table_name=table_name,
items=items)
assert inserted
got = self.helper.web.aws.dynamodb.item.get(
access_key_id=self.ini.static.aws_id,
secret_access_key=self.ini.static.aws_secret,
region_name=self.ini.static.aws_region,
table_name=table_name,
keys={'key1': 120, 'key2': 'b'})
assert got['identifier'] == self.ini.server.identifier
removed = self.helper.web.aws.dynamodb.item.remove(
access_key_id=self.ini.static.aws_id,
secret_access_key=self.ini.static.aws_secret,
region_name=self.ini.static.aws_region,
table_name=table_name,
keys={'key1': 120, 'key2': 'b'})
assert removed
row = self.helper.web.aws.dynamodb.item.get(
access_key_id=self.ini.static.aws_id,
secret_access_key=self.ini.static.aws_secret,
region_name=self.ini.static.aws_region,
table_name=table_name,
keys={'key1': 120, 'key2': 'b'})
assert not row
rows = self.helper.web.aws.dynamodb.item.get(
access_key_id=self.ini.static.aws_id,
secret_access_key=self.ini.static.aws_secret,
region_name=self.ini.static.aws_region,
table_name=table_name,
keys=({'key1': 100, 'key2': 'a'}, {'key1': 110, 'key2': 'a'}))
assert len(rows) == 2
rows = self.helper.web.aws.dynamodb.item.query(
access_key_id=self.ini.static.aws_id,
secret_access_key=self.ini.static.aws_secret,
region_name=self.ini.static.aws_region,
table_name=table_name,
ExpressionAttributeNames={
'#key1': 'key1'
},
ExpressionAttributeValues={
':key1': 100
},
KeyConditionExpression='#key1 = :key1')
assert len(rows) == 1
count = self.helper.web.aws.dynamodb.item.query(
access_key_id=self.ini.static.aws_id,
secret_access_key=self.ini.static.aws_secret,
region_name=self.ini.static.aws_region,
table_name=table_name,
count=True,
ExpressionAttributeNames={
'#key1': 'key1'
},
ExpressionAttributeValues={
':key1': 100
},
KeyConditionExpression='#key1 = :key1')
assert count == 1
rows = self.helper.web.aws.dynamodb.item.scan(
access_key_id=self.ini.static.aws_id,
secret_access_key=self.ini.static.aws_secret,
region_name=self.ini.static.aws_region,
table_name=table_name)
assert len(rows) == 2
count = self.helper.web.aws.dynamodb.item.scan(
access_key_id=self.ini.static.aws_id,
secret_access_key=self.ini.static.aws_secret,
region_name=self.ini.static.aws_region,
table_name=table_name,
count=True)
assert count == 2
deleted = self.helper.web.aws.dynamodb.table.remove(
access_key_id=self.ini.static.aws_id,
secret_access_key=self.ini.static.aws_secret,
region_name=self.ini.static.aws_region,
table_name=table_name,
wait_until_not_exists=True)
assert deleted
return self.finish('done')
except Exception as e:
self.logging.exception(e)
import time
time.sleep(10)
return self.finish_with_error(500)
| {
"content_hash": "7f31b1dff659a2f20ce5d1aac005b34a",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 134,
"avg_line_length": 40.011049723756905,
"alnum_prop": 0.4370339685169843,
"repo_name": "why2pac/dp-tornado",
"id": "dd5afe3500be6298851023e889f0e94224105f98",
"size": "7276",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "example/controller/tests/helper/web/aws/dynamodb/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3715"
},
{
"name": "Dockerfile",
"bytes": "2157"
},
{
"name": "HTML",
"bytes": "9880"
},
{
"name": "JavaScript",
"bytes": "41639"
},
{
"name": "Python",
"bytes": "567608"
},
{
"name": "Shell",
"bytes": "9068"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import models
from patient.models import Patient
from clinic.models import Clinic
class XRay(models.Model):
clinic = models.ForeignKey(Clinic)
patient = models.ForeignKey(Patient)
time = models.DateTimeField(auto_now=True)
FULL = 'f'
ANTERIORS_AND_BITEWINGS = 'a'
PANORAMIC_VIEW = 'p'
CEPHALOMETRIC = 'c'
TYPE_CHOICES = ((FULL, "full"),
(ANTERIORS_AND_BITEWINGS, "anteriors_bitewings"),
(PANORAMIC_VIEW, "panoramic_view"),
(CEPHALOMETRIC, "cephalometric"),
)
type = models.CharField(
max_length = 16, # allow 16 types for possible expansion
choices = TYPE_CHOICES,
default = FULL,
)
ADULT = 'a'
CHILD = 'c'
MOUTH_TYPE_CHOICES = ((ADULT, "adult"), (CHILD, "child"))
mouthtype = models.CharField(
max_length = 1,
choices = MOUTH_TYPE_CHOICES,
default = CHILD,
)
teeth = models.BigIntegerField(default = 0)
| {
"content_hash": "2833225e28960473109f22bd6298c571",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 72,
"avg_line_length": 27.657894736842106,
"alnum_prop": 0.6013320647002854,
"repo_name": "slogan621/tscharts",
"id": "5ab88f1decf7ca4e6e540981a35af0c57a06e00e",
"size": "1672",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xray/models.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "763"
},
{
"name": "Python",
"bytes": "1690774"
},
{
"name": "Shell",
"bytes": "2706"
}
],
"symlink_target": ""
} |
import os
import sys
import django
def main():
"""
Standalone django model test with a 'memory-only-django-installation'.
You can play with a django model without a complete django app installation.
http://www.djangosnippets.org/snippets/1044/
"""
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
os.environ["DJANGO_SETTINGS_MODULE"] = "django.conf.global_settings"
from django.conf import global_settings
global_settings.INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.sites',
'django.contrib.contenttypes',
'websettings',
)
global_settings.DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
global_settings.MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
global_settings.SECRET_KEY = "secret_key_for_testing"
global_settings.ROOT_URLCONF = "websettings.urls"
global_settings.WEBSETTINGS_MODULE = 'websettings.tests.settingstore'
from django.test.utils import get_runner
test_runner = get_runner(global_settings)
test_runner = test_runner()
failures = test_runner.run_tests(['websettings'])
sys.exit(failures)
if __name__ == '__main__':
main()
| {
"content_hash": "9fcfba931b2ac5625a7fcd78224f714c",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 80,
"avg_line_length": 31.933333333333334,
"alnum_prop": 0.662491301322199,
"repo_name": "hirokiky/django-websettings",
"id": "6c3422c87161bc0105d89ef72fc3d60c2ddd6bbd",
"size": "1437",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "runtest.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "25580"
},
{
"name": "Shell",
"bytes": "5129"
}
],
"symlink_target": ""
} |
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '2=ejgw$ytij5oh#i$eeg237okk8m3nkm@5a!j%&1(s2j7yl2xm'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'tests.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'tests/templates',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'blackhole',
'tests',
)
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
| {
"content_hash": "bd3ff1beb6d655dba390f4b6f2b5673e",
"timestamp": "",
"source": "github",
"line_count": 156,
"max_line_length": 127,
"avg_line_length": 34.09615384615385,
"alnum_prop": 0.6843391614965219,
"repo_name": "anler/django-blackhole",
"id": "3ce82bc208f8a1ece5e2f143cf9d375e43631316",
"size": "5319",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/settings.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "49"
},
{
"name": "Python",
"bytes": "231779"
}
],
"symlink_target": ""
} |
"""Support for Envisalink zone bypass switches."""
from __future__ import annotations
import logging
from homeassistant.components.switch import SwitchEntity
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from . import (
CONF_ZONENAME,
DATA_EVL,
SIGNAL_ZONE_BYPASS_UPDATE,
ZONE_SCHEMA,
EnvisalinkDevice,
)
_LOGGER = logging.getLogger(__name__)
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the Envisalink switch entities."""
if not discovery_info:
return
configured_zones = discovery_info["zones"]
entities = []
for zone_num in configured_zones:
entity_config_data = ZONE_SCHEMA(configured_zones[zone_num])
zone_name = f"{entity_config_data[CONF_ZONENAME]}_bypass"
_LOGGER.debug("Setting up zone_bypass switch: %s", zone_name)
entity = EnvisalinkSwitch(
hass,
zone_num,
zone_name,
hass.data[DATA_EVL].alarm_state["zone"][zone_num],
hass.data[DATA_EVL],
)
entities.append(entity)
async_add_entities(entities)
class EnvisalinkSwitch(EnvisalinkDevice, SwitchEntity):
"""Representation of an Envisalink switch."""
def __init__(self, hass, zone_number, zone_name, info, controller):
"""Initialize the switch."""
self._zone_number = zone_number
super().__init__(zone_name, info, controller)
async def async_added_to_hass(self):
"""Register callbacks."""
self.async_on_remove(
async_dispatcher_connect(
self.hass, SIGNAL_ZONE_BYPASS_UPDATE, self.async_update_callback
)
)
@property
def is_on(self):
"""Return the boolean response if the zone is bypassed."""
return self._info["bypassed"]
async def async_turn_on(self, **kwargs):
"""Send the bypass keypress sequence to toggle the zone bypass."""
self._controller.toggle_zone_bypass(self._zone_number)
async def async_turn_off(self, **kwargs):
"""Send the bypass keypress sequence to toggle the zone bypass."""
self._controller.toggle_zone_bypass(self._zone_number)
@callback
def async_update_callback(self, bypass_map):
"""Update the zone bypass state in HA, if needed."""
if bypass_map is None or self._zone_number in bypass_map:
_LOGGER.debug("Bypass state changed for zone %d", self._zone_number)
self.async_write_ha_state()
| {
"content_hash": "49226e3eb61586f7e99c66854890fb54",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 80,
"avg_line_length": 32.57471264367816,
"alnum_prop": 0.6587861679604798,
"repo_name": "rohitranjan1991/home-assistant",
"id": "6f5179a8649a3af78bf8977c340f577ebc3f97c4",
"size": "2834",
"binary": false,
"copies": "3",
"ref": "refs/heads/dev",
"path": "homeassistant/components/envisalink/switch.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1017265"
},
{
"name": "Python",
"bytes": "1051086"
},
{
"name": "Shell",
"bytes": "3946"
}
],
"symlink_target": ""
} |
import os.path
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
README_FILE = os.path.join(ROOT_DIR, "README.rst")
with open(README_FILE) as f:
long_description = f.read()
setup(
name="xutils",
version="2.2.2",
description="A Fragmentary Python Library, no any third-part dependencies.",
long_description=long_description,
author="xgfone",
author_email="xgfone@126.com",
maintainer="xgfone",
maintainer_email="xgfone@126.com",
url="https://github.com/xgfone/xutils",
packages=["xutils", "xutils.gunicorn_workers"],
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
],
)
| {
"content_hash": "a28ec3a1cc5f1f279b3626205c6fcac7",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 80,
"avg_line_length": 30.81578947368421,
"alnum_prop": 0.6285226302305722,
"repo_name": "xgfone/pycom",
"id": "5562b5f4c6ffee86fc2a16e3dbaf270f0de98e6a",
"size": "1171",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "77330"
}
],
"symlink_target": ""
} |
import pytest
from nltk import config_megam
from nltk.classify.rte_classify import RTEFeatureExtractor, rte_classifier, rte_features
from nltk.corpus import rte as rte_corpus
expected_from_rte_feature_extration = """
alwayson => True
ne_hyp_extra => 0
ne_overlap => 1
neg_hyp => 0
neg_txt => 0
word_hyp_extra => 3
word_overlap => 3
alwayson => True
ne_hyp_extra => 0
ne_overlap => 1
neg_hyp => 0
neg_txt => 0
word_hyp_extra => 2
word_overlap => 1
alwayson => True
ne_hyp_extra => 1
ne_overlap => 1
neg_hyp => 0
neg_txt => 0
word_hyp_extra => 1
word_overlap => 2
alwayson => True
ne_hyp_extra => 1
ne_overlap => 0
neg_hyp => 0
neg_txt => 0
word_hyp_extra => 6
word_overlap => 2
alwayson => True
ne_hyp_extra => 1
ne_overlap => 0
neg_hyp => 0
neg_txt => 0
word_hyp_extra => 4
word_overlap => 0
alwayson => True
ne_hyp_extra => 1
ne_overlap => 0
neg_hyp => 0
neg_txt => 0
word_hyp_extra => 3
word_overlap => 1
"""
class TestRTEClassifier:
# Test the feature extraction method.
def test_rte_feature_extraction(self):
pairs = rte_corpus.pairs(["rte1_dev.xml"])[:6]
test_output = [
f"{key:<15} => {rte_features(pair)[key]}"
for pair in pairs
for key in sorted(rte_features(pair))
]
expected_output = expected_from_rte_feature_extration.strip().split("\n")
# Remove null strings.
expected_output = list(filter(None, expected_output))
assert test_output == expected_output
# Test the RTEFeatureExtractor object.
def test_feature_extractor_object(self):
rtepair = rte_corpus.pairs(["rte3_dev.xml"])[33]
extractor = RTEFeatureExtractor(rtepair)
assert extractor.hyp_words == {"member", "China", "SCO."}
assert extractor.overlap("word") == set()
assert extractor.overlap("ne") == {"China"}
assert extractor.hyp_extra("word") == {"member"}
# Test the RTE classifier training.
def test_rte_classification_without_megam(self):
# Use a sample size for unit testing, since we
# don't need to fully train these classifiers
clf = rte_classifier("IIS", sample_N=100)
clf = rte_classifier("GIS", sample_N=100)
def test_rte_classification_with_megam(self):
try:
config_megam()
except (LookupError, AttributeError) as e:
pytest.skip("Skipping tests with dependencies on MEGAM")
clf = rte_classifier("megam", sample_N=100)
| {
"content_hash": "3d9281915d7ca18fdd8430d696d74a3a",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 88,
"avg_line_length": 28.414893617021278,
"alnum_prop": 0.5859228753275927,
"repo_name": "nltk/nltk",
"id": "0a573ea7e291c46e22ceb9ae39fc4aff880c6398",
"size": "2671",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "nltk/test/unit/test_rte_classify.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "705"
},
{
"name": "HTML",
"bytes": "24786"
},
{
"name": "Jupyter Notebook",
"bytes": "55608"
},
{
"name": "Makefile",
"bytes": "7983"
},
{
"name": "Python",
"bytes": "4831858"
},
{
"name": "Shell",
"bytes": "10877"
}
],
"symlink_target": ""
} |
import os
import sys
import re
import datetime
import string
from scriptCommon import catchPath
versionParser = re.compile( r'(\s*Version\slibraryVersion)\s*\(\s*(.*)\s*,\s*(.*)\s*,\s*(.*)\s*,\s*\"(.*)\"\s*\).*' )
includesParser = re.compile( r'\s*#include\s*"(.*)"' )
guardParser = re.compile( r'\s*#.*TWOBLUECUBES_CATCH_.*_INCLUDED')
defineParser = re.compile( r'\s*#define')
ifParser = re.compile( r'\s*#ifndef TWOBLUECUBES_CATCH_.*_INCLUDED')
endIfParser = re.compile( r'\s*#endif // TWOBLUECUBES_CATCH_.*_INCLUDED')
ifImplParser = re.compile( r'\s*#if.*(CATCH_CONFIG_MAIN|CATCH_CONFIG_RUNNER)')
commentParser1 = re.compile( r'^\s*/\*')
commentParser2 = re.compile( r'^\s*\*')
blankParser = re.compile( r'^\s*$')
seenHeaders = set([])
rootPath = os.path.join( catchPath, 'include/' )
versionPath = os.path.join( rootPath, "internal/catch_version.hpp" )
readmePath = os.path.join( catchPath, "README.md" )
outputPath = os.path.join( catchPath, 'single_include/catch.hpp' )
bumpVersion = True
includeImpl = True
for arg in sys.argv[1:]:
arg = string.lower(arg)
if arg == "nobump":
bumpVersion = False
print( "Not bumping version number" )
elif arg == "noimpl":
includeImpl = False
bumpVersion = False
print "Not including impl code (and not bumping version)"
else:
print "\n** Unrecognised argument: " + arg + " **\n"
exit(1)
out = open( outputPath, 'w' )
ifdefs = 0
implIfDefs = -1
def write( line ):
if includeImpl or implIfDefs == -1:
out.write( line )
def parseFile( path, filename ):
global ifdefs
global implIfDefs
f = open( path + filename, 'r' )
blanks = 0
for line in f:
if ifParser.match( line ):
ifdefs = ifdefs + 1
elif endIfParser.match( line ):
ifdefs = ifdefs - 1
m = includesParser.match( line )
if m:
header = m.group(1)
headerPath, sep, headerFile = header.rpartition( "/" )
if not headerFile in seenHeaders:
if headerFile != "tbc_text_format.h" and headerFile != "clara.h":
seenHeaders.add( headerFile )
write( "// #included from: {0}\n".format( header ) )
if( headerPath == "internal" and path.endswith( "internal/" ) ):
headerPath = ""
sep = ""
if os.path.exists( path + headerPath + sep + headerFile ):
parseFile( path + headerPath + sep, headerFile )
else:
parseFile( rootPath + headerPath + sep, headerFile )
else:
if ifImplParser.match(line):
implIfDefs = ifdefs
if (not guardParser.match( line ) or defineParser.match( line ) ) and not commentParser1.match( line )and not commentParser2.match( line ):
if blankParser.match( line ):
blanks = blanks + 1
else:
blanks = 0
if blanks < 2:
write( line.rstrip() + "\n" )
class Version:
def __init__(self):
f = open( versionPath, 'r' )
for line in f:
m = versionParser.match( line )
if m:
self.variableDecl = m.group(1)
self.majorVersion = int(m.group(2))
self.minorVersion = int(m.group(3))
self.buildNumber = int(m.group(4))
self.branchName = m.group(5)
f.close()
def incrementBuildNumber(self):
self.buildNumber = self.buildNumber+1
def updateVersionFile(self):
f = open( versionPath, 'r' )
lines = []
for line in f:
m = versionParser.match( line )
if m:
lines.append( '{0}( {1}, {2}, {3}, "{4}" );'.format( self.variableDecl, self.majorVersion, self.minorVersion, self.buildNumber, self.branchName ) )
else:
lines.append( line.rstrip() )
f.close()
f = open( versionPath, 'w' )
for line in lines:
f.write( line + "\n" )
def updateReadmeFile(self):
f = open( readmePath, 'r' )
lines = []
for line in f:
lines.append( line.rstrip() )
f.close()
f = open( readmePath, 'w' )
for line in lines:
if line.startswith( "*v" ):
f.write( '*v{0}.{1} build {2} ({3} branch)*\n'.format( self.majorVersion, self.minorVersion, self.buildNumber, self.branchName ) )
else:
f.write( line + "\n" )
def generateSingleInclude():
v = Version()
if bumpVersion:
v.incrementBuildNumber()
v.updateVersionFile()
v.updateReadmeFile()
out.write( "\n" )
out.write( "#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED\n" )
out.write( "#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED\n" )
parseFile( rootPath, 'catch.hpp' )
out.write( "#endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED\n\n" )
generateSingleInclude()
| {
"content_hash": "77ee00a4f1ec61657c012891e9ba4986",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 163,
"avg_line_length": 35.51048951048951,
"alnum_prop": 0.5571090980701063,
"repo_name": "rao1219/Vedio",
"id": "8930c45e3c2dede44b78902bdeb58ffd57e67a4d",
"size": "5806",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "node_modules/aglio/node_modules/drafter/node_modules/protagonist/drafter/ext/snowcrash/ext/markdown-parser/test/ext/Catch/scripts/generateSingleHeader.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1758"
},
{
"name": "CoffeeScript",
"bytes": "36282"
},
{
"name": "HTML",
"bytes": "132235"
},
{
"name": "JavaScript",
"bytes": "12776"
}
],
"symlink_target": ""
} |
"""Miscellaneous utility functions."""
from __future__ import division
import os
import sys
import re
import shutil
import fnmatch
from collections import defaultdict
import traceback
import subprocess
MAX_FILENAME_LENGTH = 200
WINDOWS_MAGIC_PREFIX = u'\\\\?\\'
class HumanReadableException(Exception):
"""An Exception that can include a human-readable error message to
be logged without a traceback. Can preserve a traceback for
debugging purposes as well.
Has at least two fields: `reason`, the underlying exception or a
string describing the problem; and `verb`, the action being
performed during the error.
If `tb` is provided, it is a string containing a traceback for the
associated exception. (Note that this is not necessary in Python 3.x
and should be removed when we make the transition.)
"""
error_kind = 'Error' # Human-readable description of error type.
def __init__(self, reason, verb, tb=None):
self.reason = reason
self.verb = verb
self.tb = tb
super(HumanReadableException, self).__init__(self.get_message())
def _gerund(self):
"""Generate a (likely) gerund form of the English verb.
"""
if ' ' in self.verb:
return self.verb
gerund = self.verb[:-1] if self.verb.endswith('e') else self.verb
gerund += 'ing'
return gerund
def _reasonstr(self):
"""Get the reason as a string."""
if isinstance(self.reason, unicode):
return self.reason
elif isinstance(self.reason, basestring): # Byte string.
return self.reason.decode('utf8', 'ignore')
elif hasattr(self.reason, 'strerror'): # i.e., EnvironmentError
return self.reason.strerror
else:
return u'"{0}"'.format(unicode(self.reason))
def get_message(self):
"""Create the human-readable description of the error, sans
introduction.
"""
raise NotImplementedError
def log(self, logger):
"""Log to the provided `logger` a human-readable message as an
error and a verbose traceback as a debug message.
"""
if self.tb:
logger.debug(self.tb)
logger.error(u'{0}: {1}'.format(self.error_kind, self.args[0]))
class FilesystemError(HumanReadableException):
"""An error that occurred while performing a filesystem manipulation
via a function in this module. The `paths` field is a sequence of
pathnames involved in the operation.
"""
def __init__(self, reason, verb, paths, tb=None):
self.paths = paths
super(FilesystemError, self).__init__(reason, verb, tb)
def get_message(self):
# Use a nicer English phrasing for some specific verbs.
if self.verb in ('move', 'copy', 'rename'):
clause = 'while {0} {1} to {2}'.format(
self._gerund(), repr(self.paths[0]), repr(self.paths[1])
)
elif self.verb in ('delete', 'write', 'create', 'read'):
clause = 'while {0} {1}'.format(
self._gerund(), repr(self.paths[0])
)
else:
clause = 'during {0} of paths {1}'.format(
self.verb, u', '.join(repr(p) for p in self.paths)
)
return u'{0} {1}'.format(self._reasonstr(), clause)
def normpath(path):
"""Provide the canonical form of the path suitable for storing in
the database.
"""
path = syspath(path, prefix=False)
path = os.path.normpath(os.path.abspath(os.path.expanduser(path)))
return bytestring_path(path)
def ancestry(path, pathmod=None):
"""Return a list consisting of path's parent directory, its
grandparent, and so on. For instance:
>>> ancestry('/a/b/c')
['/', '/a', '/a/b']
The argument should *not* be the result of a call to `syspath`.
"""
pathmod = pathmod or os.path
out = []
last_path = None
while path:
path = pathmod.dirname(path)
if path == last_path:
break
last_path = path
if path: # don't yield ''
out.insert(0, path)
return out
def sorted_walk(path, ignore=(), logger=None):
"""Like `os.walk`, but yields things in case-insensitive sorted,
breadth-first order. Directory and file names matching any glob
pattern in `ignore` are skipped. If `logger` is provided, then
warning messages are logged there when a directory cannot be listed.
"""
# Make sure the path isn't a Unicode string.
path = bytestring_path(path)
# Get all the directories and files at this level.
try:
contents = os.listdir(syspath(path))
except OSError as exc:
if logger:
logger.warn(u'could not list directory {0}: {1}'.format(
displayable_path(path), exc.strerror
))
return
dirs = []
files = []
for base in contents:
base = bytestring_path(base)
# Skip ignored filenames.
skip = False
for pat in ignore:
if fnmatch.fnmatch(base, pat):
skip = True
break
if skip:
continue
# Add to output as either a file or a directory.
cur = os.path.join(path, base)
if os.path.isdir(syspath(cur)):
dirs.append(base)
else:
files.append(base)
# Sort lists (case-insensitive) and yield the current level.
dirs.sort(key=bytes.lower)
files.sort(key=bytes.lower)
yield (path, dirs, files)
# Recurse into directories.
for base in dirs:
cur = os.path.join(path, base)
# yield from sorted_walk(...)
for res in sorted_walk(cur, ignore, logger):
yield res
def mkdirall(path):
"""Make all the enclosing directories of path (like mkdir -p on the
parent).
"""
for ancestor in ancestry(path):
if not os.path.isdir(syspath(ancestor)):
try:
os.mkdir(syspath(ancestor))
except (OSError, IOError) as exc:
raise FilesystemError(exc, 'create', (ancestor,),
traceback.format_exc())
def fnmatch_all(names, patterns):
"""Determine whether all strings in `names` match at least one of
the `patterns`, which should be shell glob expressions.
"""
for name in names:
matches = False
for pattern in patterns:
matches = fnmatch.fnmatch(name, pattern)
if matches:
break
if not matches:
return False
return True
def prune_dirs(path, root=None, clutter=('.DS_Store', 'Thumbs.db')):
"""If path is an empty directory, then remove it. Recursively remove
path's ancestry up to root (which is never removed) where there are
empty directories. If path is not contained in root, then nothing is
removed. Glob patterns in clutter are ignored when determining
emptiness. If root is not provided, then only path may be removed
(i.e., no recursive removal).
"""
path = normpath(path)
if root is not None:
root = normpath(root)
ancestors = ancestry(path)
if root is None:
# Only remove the top directory.
ancestors = []
elif root in ancestors:
# Only remove directories below the root.
ancestors = ancestors[ancestors.index(root)+1:]
else:
# Remove nothing.
return
# Traverse upward from path.
ancestors.append(path)
ancestors.reverse()
for directory in ancestors:
directory = syspath(directory)
if not os.path.exists(directory):
# Directory gone already.
continue
if fnmatch_all(os.listdir(directory), clutter):
# Directory contains only clutter (or nothing).
try:
shutil.rmtree(directory)
except OSError:
break
else:
break
def components(path, pathmod=None):
"""Return a list of the path components in path. For instance:
>>> components('/a/b/c')
['a', 'b', 'c']
The argument should *not* be the result of a call to `syspath`.
"""
pathmod = pathmod or os.path
comps = []
ances = ancestry(path, pathmod)
for anc in ances:
comp = pathmod.basename(anc)
if comp:
comps.append(comp)
else: # root
comps.append(anc)
last = pathmod.basename(path)
if last:
comps.append(last)
return comps
def _fsencoding():
"""Get the system's filesystem encoding. On Windows, this is always
UTF-8 (not MBCS).
"""
encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
if encoding == 'mbcs':
# On Windows, a broken encoding known to Python as "MBCS" is
# used for the filesystem. However, we only use the Unicode API
# for Windows paths, so the encoding is actually immaterial so
# we can avoid dealing with this nastiness. We arbitrarily
# choose UTF-8.
encoding = 'utf8'
return encoding
def bytestring_path(path, pathmod=None):
"""Given a path, which is either a str or a unicode, returns a str
path (ensuring that we never deal with Unicode pathnames).
"""
pathmod = pathmod or os.path
windows = pathmod.__name__ == 'ntpath'
# Pass through bytestrings.
if isinstance(path, str):
return path
# On Windows, remove the magic prefix added by `syspath`. This makes
# ``bytestring_path(syspath(X)) == X``, i.e., we can safely
# round-trip through `syspath`.
if windows and path.startswith(WINDOWS_MAGIC_PREFIX):
path = path[len(WINDOWS_MAGIC_PREFIX):]
# Try to encode with default encodings, but fall back to UTF8.
try:
return path.encode(_fsencoding())
except (UnicodeError, LookupError):
return path.encode('utf8')
def displayable_path(path, separator=u'; '):
"""Attempts to decode a bytestring path to a unicode object for the
purpose of displaying it to the user. If the `path` argument is a
list or a tuple, the elements are joined with `separator`.
"""
if isinstance(path, (list, tuple)):
return separator.join(displayable_path(p) for p in path)
elif isinstance(path, unicode):
return path
elif not isinstance(path, str):
# A non-string object: just get its unicode representation.
return unicode(path)
try:
return path.decode(_fsencoding(), 'ignore')
except (UnicodeError, LookupError):
return path.decode('utf8', 'ignore')
def syspath(path, prefix=True, pathmod=None):
"""Convert a path for use by the operating system. In particular,
paths on Windows must receive a magic prefix and must be converted
to Unicode before they are sent to the OS. To disable the magic
prefix on Windows, set `prefix` to False---but only do this if you
*really* know what you're doing.
"""
pathmod = pathmod or os.path
windows = pathmod.__name__ == 'ntpath'
# Don't do anything if we're not on windows
if not windows:
return path
if not isinstance(path, unicode):
# Beets currently represents Windows paths internally with UTF-8
# arbitrarily. But earlier versions used MBCS because it is
# reported as the FS encoding by Windows. Try both.
try:
path = path.decode('utf8')
except UnicodeError:
# The encoding should always be MBCS, Windows' broken
# Unicode representation.
encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
path = path.decode(encoding, 'replace')
# Add the magic prefix if it isn't already there
if prefix and not path.startswith(WINDOWS_MAGIC_PREFIX):
path = WINDOWS_MAGIC_PREFIX + path
return path
def samefile(p1, p2):
"""Safer equality for paths."""
return shutil._samefile(syspath(p1), syspath(p2))
def remove(path, soft=True):
"""Remove the file. If `soft`, then no error will be raised if the
file does not exist.
"""
path = syspath(path)
if soft and not os.path.exists(path):
return
try:
os.remove(path)
except (OSError, IOError) as exc:
raise FilesystemError(exc, 'delete', (path,), traceback.format_exc())
def copy(path, dest, replace=False, pathmod=os.path):
"""Copy a plain file. Permissions are not copied. If `dest` already
exists, raises a FilesystemError unless `replace` is True. Has no
effect if `path` is the same as `dest`. Paths are translated to
system paths before the syscall.
"""
if samefile(path, dest):
return
path = syspath(path)
dest = syspath(dest)
if not replace and pathmod.exists(dest):
raise FilesystemError('file exists', 'copy', (path, dest))
try:
shutil.copyfile(path, dest)
except (OSError, IOError) as exc:
raise FilesystemError(exc, 'copy', (path, dest),
traceback.format_exc())
def move(path, dest, replace=False, pathmod=os.path):
"""Rename a file. `dest` may not be a directory. If `dest` already
exists, raises an OSError unless `replace` is True. Has no effect if
`path` is the same as `dest`. If the paths are on different
filesystems (or the rename otherwise fails), a copy is attempted
instead, in which case metadata will *not* be preserved. Paths are
translated to system paths.
"""
if samefile(path, dest):
return
path = syspath(path)
dest = syspath(dest)
if pathmod.exists(dest) and not replace:
raise FilesystemError('file exists', 'rename', (path, dest),
traceback.format_exc())
# First, try renaming the file.
try:
os.rename(path, dest)
except OSError:
# Otherwise, copy and delete the original.
try:
shutil.copyfile(path, dest)
os.remove(path)
except (OSError, IOError) as exc:
raise FilesystemError(exc, 'move', (path, dest),
traceback.format_exc())
def unique_path(path):
"""Returns a version of ``path`` that does not exist on the
filesystem. Specifically, if ``path` itself already exists, then
something unique is appended to the path.
"""
if not os.path.exists(syspath(path)):
return path
base, ext = os.path.splitext(path)
match = re.search(r'\.(\d)+$', base)
if match:
num = int(match.group(1))
base = base[:match.start()]
else:
num = 0
while True:
num += 1
new_path = '%s.%i%s' % (base, num, ext)
if not os.path.exists(new_path):
return new_path
# Note: The Windows "reserved characters" are, of course, allowed on
# Unix. They are forbidden here because they cause problems on Samba
# shares, which are sufficiently common as to cause frequent problems.
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx
CHAR_REPLACE = [
(re.compile(ur'[\\/]'), u'_'), # / and \ -- forbidden everywhere.
(re.compile(ur'^\.'), u'_'), # Leading dot (hidden files on Unix).
(re.compile(ur'[\x00-\x1f]'), u''), # Control characters.
(re.compile(ur'[<>:"\?\*\|]'), u'_'), # Windows "reserved characters".
(re.compile(ur'\.$'), u'_'), # Trailing dots.
(re.compile(ur'\s+$'), u''), # Trailing whitespace.
]
def sanitize_path(path, pathmod=None, replacements=None):
"""Takes a path (as a Unicode string) and makes sure that it is
legal. Returns a new path. Only works with fragments; won't work
reliably on Windows when a path begins with a drive letter. Path
separators (including altsep!) should already be cleaned from the
path components. If replacements is specified, it is used *instead*
of the default set of replacements; it must be a list of (compiled
regex, replacement string) pairs.
"""
pathmod = pathmod or os.path
replacements = replacements or CHAR_REPLACE
comps = components(path, pathmod)
if not comps:
return ''
for i, comp in enumerate(comps):
for regex, repl in replacements:
comp = regex.sub(repl, comp)
comps[i] = comp
return pathmod.join(*comps)
def truncate_path(path, pathmod=None, length=MAX_FILENAME_LENGTH):
"""Given a bytestring path or a Unicode path fragment, truncate the
components to a legal length. In the last component, the extension
is preserved.
"""
pathmod = pathmod or os.path
comps = components(path, pathmod)
out = [c[:length] for c in comps]
base, ext = pathmod.splitext(comps[-1])
if ext:
# Last component has an extension.
base = base[:length - len(ext)]
out[-1] = base + ext
return pathmod.join(*out)
def str2bool(value):
"""Returns a boolean reflecting a human-entered string."""
if value.lower() in ('yes', '1', 'true', 't', 'y'):
return True
else:
return False
def as_string(value):
"""Convert a value to a Unicode object for matching with a query.
None becomes the empty string. Bytestrings are silently decoded.
"""
if value is None:
return u''
elif isinstance(value, buffer):
return str(value).decode('utf8', 'ignore')
elif isinstance(value, str):
return value.decode('utf8', 'ignore')
else:
return unicode(value)
def levenshtein(s1, s2):
"""A nice DP edit distance implementation from Wikibooks:
http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/
Levenshtein_distance#Python
"""
if len(s1) < len(s2):
return levenshtein(s2, s1)
if not s1:
return len(s2)
previous_row = xrange(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1
substitutions = previous_row[j] + (c1 != c2)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1]
def plurality(objs):
"""Given a sequence of comparable objects, returns the object that
is most common in the set and the frequency of that object. The
sequence must contain at least one object.
"""
# Calculate frequencies.
freqs = defaultdict(int)
for obj in objs:
freqs[obj] += 1
if not freqs:
raise ValueError('sequence must be non-empty')
# Find object with maximum frequency.
max_freq = 0
res = None
for obj, freq in freqs.items():
if freq > max_freq:
max_freq = freq
res = obj
return res, max_freq
def cpu_count():
"""Return the number of hardware thread contexts (cores or SMT
threads) in the system.
"""
# Adapted from the soundconverter project:
# https://github.com/kassoulet/soundconverter
if sys.platform == 'win32':
try:
num = int(os.environ['NUMBER_OF_PROCESSORS'])
except (ValueError, KeyError):
num = 0
elif sys.platform == 'darwin':
try:
num = int(os.popen('sysctl -n hw.ncpu').read())
except ValueError:
num = 0
else:
try:
num = os.sysconf('SC_NPROCESSORS_ONLN')
except (ValueError, OSError, AttributeError):
num = 0
if num >= 1:
return num
else:
return 1
def command_output(cmd):
"""Wraps the `subprocess` module to invoke a command (given as a
list of arguments starting with the command name) and collect
stdout. The stderr stream is ignored. May raise
`subprocess.CalledProcessError` or an `OSError`.
This replaces `subprocess.check_output`, which isn't available in
Python 2.6 and which can have problems if lots of output is sent to
stderr.
"""
with open(os.devnull, 'w') as devnull:
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=devnull)
stdout, _ = proc.communicate()
if proc.returncode:
raise subprocess.CalledProcessError(proc.returncode, cmd)
return stdout
def max_filename_length(path, limit=MAX_FILENAME_LENGTH):
"""Attempt to determine the maximum filename length for the
filesystem containing `path`. If the value is greater than `limit`,
then `limit` is used instead (to prevent errors when a filesystem
misreports its capacity). If it cannot be determined (e.g., on
Windows), return `limit`.
"""
if hasattr(os, 'statvfs'):
try:
res = os.statvfs(path)
except OSError:
return limit
return min(res[9], limit)
else:
return limit
| {
"content_hash": "76990c0c03fa6ba0c6890e023060eae0",
"timestamp": "",
"source": "github",
"line_count": 611,
"max_line_length": 78,
"avg_line_length": 34.12602291325695,
"alnum_prop": 0.6177641360126612,
"repo_name": "jayme-github/beets",
"id": "0efd5ae448a37ca2ae849c1102e96bffebd5b0b3",
"size": "21498",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "beets/util/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "85314"
},
{
"name": "Python",
"bytes": "878962"
}
],
"symlink_target": ""
} |
"""
Loads Section Status change events from SQS
"""
import logging
import traceback
from django.core.mail import send_mail
from django.core.management.base import BaseCommand
from myuw.event.section_status import SectionStatusProcessor
from myuw.logger.timer import Timer
from myuw.util.settings import get_cronjob_recipient, get_cronjob_sender
from aws_message.gather import Gather
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **options):
timer = Timer()
try:
Gather(processor=SectionStatusProcessor()).gather_events()
logger.info("Total Time: {} seconds".format(timer.get_elapsed()))
except Exception as ex:
logger.error(ex)
send_mail("Loads Section Status change Cron",
"{}".format(traceback.format_exc(chain=False)),
"{}@uw.edu".format(get_cronjob_sender()),
["{}@uw.edu".format(get_cronjob_recipient())])
| {
"content_hash": "9e45fa6407713d0b45dca6b024b70b16",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 77,
"avg_line_length": 34.51724137931034,
"alnum_prop": 0.6593406593406593,
"repo_name": "uw-it-aca/myuw",
"id": "8c4287bc53d48bb7271f0043b3c1999d8bbfdd7d",
"size": "1089",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "myuw/management/commands/load_section_status_changes.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1353"
},
{
"name": "Dockerfile",
"bytes": "1182"
},
{
"name": "HTML",
"bytes": "87842"
},
{
"name": "JavaScript",
"bytes": "362025"
},
{
"name": "Python",
"bytes": "1057335"
},
{
"name": "SCSS",
"bytes": "5763"
},
{
"name": "Shell",
"bytes": "838"
},
{
"name": "Vue",
"bytes": "522119"
}
],
"symlink_target": ""
} |
import pytest
from pandas.errors import AbstractMethodError
import pandas as pd
@pytest.mark.parametrize(
"exc",
[
"UnsupportedFunctionCall",
"UnsortedIndexError",
"OutOfBoundsDatetime",
"ParserError",
"PerformanceWarning",
"DtypeWarning",
"EmptyDataError",
"ParserWarning",
"MergeError",
"OptionError",
"NumbaUtilError",
],
)
def test_exception_importable(exc):
from pandas import errors
err = getattr(errors, exc)
assert err is not None
# check that we can raise on them
msg = "^$"
with pytest.raises(err, match=msg):
raise err()
def test_catch_oob():
from pandas import errors
msg = "Out of bounds nanosecond timestamp: 1500-01-01 00:00:00"
with pytest.raises(errors.OutOfBoundsDatetime, match=msg):
pd.Timestamp("15000101")
class Foo:
@classmethod
def classmethod(cls):
raise AbstractMethodError(cls, methodtype="classmethod")
@property
def property(self):
raise AbstractMethodError(self, methodtype="property")
def method(self):
raise AbstractMethodError(self)
def test_AbstractMethodError_classmethod():
xpr = "This classmethod must be defined in the concrete class Foo"
with pytest.raises(AbstractMethodError, match=xpr):
Foo.classmethod()
xpr = "This property must be defined in the concrete class Foo"
with pytest.raises(AbstractMethodError, match=xpr):
Foo().property
xpr = "This method must be defined in the concrete class Foo"
with pytest.raises(AbstractMethodError, match=xpr):
Foo().method()
| {
"content_hash": "8c3458579984b0b29f9ef366aa0c1bcc",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 70,
"avg_line_length": 23.857142857142858,
"alnum_prop": 0.6592814371257485,
"repo_name": "gfyoung/pandas",
"id": "6207b886b95c71569d56d28028d856bc9d63ac91",
"size": "1670",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "pandas/tests/test_errors.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "4912"
},
{
"name": "C",
"bytes": "404689"
},
{
"name": "C++",
"bytes": "17194"
},
{
"name": "HTML",
"bytes": "551714"
},
{
"name": "Makefile",
"bytes": "574"
},
{
"name": "Python",
"bytes": "14336547"
},
{
"name": "Shell",
"bytes": "29174"
},
{
"name": "Smarty",
"bytes": "2069"
}
],
"symlink_target": ""
} |
import numpy as np
import matplotlib.pyplot as plt
import illustris_python as ilpy
import translate_coordinates as tc #renato's code for camera projections
import tng_api_utils as tau
# Used only sparingly (maybe remove dependencies?)
import os
import astropy.io.ascii as ascii
import astropy
import astropy.io.fits as fits
import astropy.units as u
from astropy.cosmology import WMAP7,z_at_value
import copy
# Constants
ilh = tau.tngh # Little H (H_0/100) is set to 0.704
illcos = tau.tngcos # Our cosmology is taken from astropy.
# It uses astropy.cosmology.FlatLambdaCDM(H0=70.4,Om0=0.2726,Ob0=0.0456)
#======================================================================================================================
class lightcone_catalog:
# This class holds the
def __init__(self,lightconefile,base_dir,mass_limit=(10.0**9.5),sfr_limit=0.0,mag_limit=None):
lc_data = ascii.read(lightconefile)
print("Initializing Lightcone File: ", lightconefile)
print(lc_data)
self.lightconefile = lightconefile
self.cylinder_number = np.int32(lc_data['col1'].data)
self.snapshot_string = lc_data['col2'].data
self.snapshot_redshift = lc_data['col3'].data
self.v_Ingress_x_cmh = lc_data['col4'].data
self.v_Ingress_y_cmh = lc_data['col5'].data
self.v_Ingress_z_cmh = lc_data['col6'].data
self.v_Egress_x_cmh = lc_data['col7'].data
self.v_Egress_y_cmh = lc_data['col8'].data
self.v_Egress_z_cmh = lc_data['col9'].data
self.v_Ingress_x_kpc = lc_data['col10'].data
self.v_Ingress_y_kpc = lc_data['col11'].data
self.v_Ingress_z_kpc = lc_data['col12'].data
self.v_Camera_x_kpc = lc_data['col13'].data
self.v_Camera_y_kpc = lc_data['col14'].data
self.v_Camera_z_kpc = lc_data['col15'].data
self.v_Offset_x_kpc = lc_data['col16'].data
self.v_Offset_y_kpc = lc_data['col17'].data
self.v_Offset_z_kpc = lc_data['col18'].data
self.fov_kpc = lc_data['col19'].data
self.center_redshift = lc_data['col20'].data
self.radius_buffer_cmh = lc_data['col21'].data
xs = None
xd = None
self.L_comoving = None
lines = open(lightconefile,'r')
for l in lines:
if "Comoving Single Box L" in l:
self.L_comoving = np.float32(l.split()[-1])
self.L_comovingh = round(self.L_comoving*ilh,4)
if "Delta Unit Vector" in l:
ss = l.split("[")[-1].split("]")[0].split()
xs = ss[0]
ys = ss[1]
zs = ss[2]
if "Direction Unit Vector" in l:
ss = l.split("[")[-1].split("]")[0].split()
xd = ss[0]
yd = ss[1]
zd = ss[2]
if "del B" in l:
self.delb_arcmin = np.float32(l.split()[-1])
if "del A" in l:
self.dela_arcmin = np.float32(l.split()[-1])
lines.close()
assert xs is not None
assert xd is not None
assert self.L_comoving is not None
#camdir
#just the direction unit vector from the lightcone file
self.camdir_x = np.float32(xd)
self.camdir_y = np.float32(yd)
self.camdir_z = np.float32(zd)
#camup
#just the delta unit vector from the lightcone file
self.camup_x = np.float32(xs)
self.camup_y = np.float32(ys)
self.camup_z = np.float32(zs)
print(" Direction vector: ", self.camdir_x, self.camdir_y, self.camdir_z)
print(" Up vector: ", self.camup_x, self.camup_y, self.camup_z)
print(" B FOV, arcmin: ", self.delb_arcmin)
print(" A FOV, arcmin: ", self.dela_arcmin)
print(" Ls, Mpc: ", self.L_comoving, self.L_comovingh)
self.norm_degrees = self.delb_arcmin/60.0
self.cylinder_object_list = []
self.base_dir = base_dir
self.mass_limit = mass_limit
self.sfr_limit = sfr_limit
self.mag_limit = mag_limit
return
#0 - gas
#1 - DM
#4 - stars & WIND
#5 - BHs
def process_lightcone(self,minz=0.0,maxz=20.0):
cmd_total = 0.0
cmx = 0.0
cmy = 0.0
cmz = 0.0
for i,cyl in enumerate(self.cylinder_number):
cmd_thiscyl = ( (self.v_Egress_x_cmh[i]/ilh - self.v_Ingress_x_cmh[i]/ilh)**2 + (self.v_Egress_y_cmh[i]/ilh - self.v_Ingress_y_cmh[i]/ilh)**2 + (self.v_Egress_z_cmh[i]/ilh - self.v_Ingress_z_cmh[i]/ilh)**2 )**0.5
cmd_begin = cmd_total
cmd_end = cmd_begin + cmd_thiscyl
cmd_total = cmd_end
cz=self.center_redshift[i]
#world coordinates of ingress point
cmx_begin = 1.0*cmx
cmy_begin = 1.0*cmy
cmz_begin = 1.0*cmz
#world coordinates of egress points
cmx = cmx_begin + (self.v_Egress_x_cmh[i]/ilh - self.v_Ingress_x_cmh[i]/ilh)
cmy = cmy_begin + (self.v_Egress_y_cmh[i]/ilh - self.v_Ingress_y_cmh[i]/ilh)
cmz = cmz_begin + (self.v_Egress_z_cmh[i]/ilh - self.v_Ingress_z_cmh[i]/ilh)
if i > 1000:
continue
if cz < minz:
continue
if cz > maxz:
continue
testf = 'test_'+str(cyl)+'.pdf'
f1 = plt.figure(figsize=(10.5,10.5), dpi=150)
plt.subplots_adjust(left=0.11, right=0.98, bottom=0.08, top=0.99,wspace=0.25,hspace=0.25)
skip = 500
#determine snapshot of interest
print("Processing Cylinder: ", cyl, i, self.snapshot_redshift[i])
snapnum = self.snapshot_string[i]
# Not relevant for us because we're doing tng simulations
#old corrupt snaps for illustris-1
#if snapnum==53:
# snapnum=52
#if snapnum==55:
# snapnum=54
print(" Snapshot Number: ", snapnum)
# Load the data
fields=['SubhaloMass','SubhaloMassInMaxRad','SubhaloMassInRadType','SubhaloMassInMaxRadType','SubhaloPos','SubhaloSFR','SubhaloSFRinRad','SubhaloVel','SubhaloBHMass','SubhaloBHMdot','SubhaloStellarPhotometrics','SubhaloWindMass']
subhalos = ilpy.groupcat.loadSubhalos(self.base_dir,snapnum,fields=fields)
print(" Loaded subhalos: ", subhalos['count'], subhalos['SubhaloMassInRadType'].shape)
# Clean the loaded subhalo dictionaries
mstar_msun = subhalos['SubhaloMassInRadType'][:,4]*(1.0e10)/ilh
mgas_msun = subhalos['SubhaloMassInRadType'][:,0]*(1.0e10)/ilh #includes wind mass
mbh_msun = subhalos['SubhaloMassInRadType'][:,5]*(1.0e10)/ilh
baryonmass_msun = mstar_msun + mgas_msun + mbh_msun #within 2x stellar half mass radius... best?
mhalo_msun = subhalos['SubhaloMass']*(1.0e10)/ilh
sfr = subhalos['SubhaloSFR']*1.0
gmag_ABabs=subhalos['SubhaloStellarPhotometrics'][:,4]*1.0
distmod=illcos.distmod(cz).value
gmag=gmag_ABabs+distmod
if self.mag_limit is None:
mi = np.where(np.logical_and(baryonmass_msun > self.mass_limit, sfr >self.sfr_limit))[0]
else:
mi = np.where(np.logical_and(gmag < self.mag_limit,baryonmass_msun > 0.0))[0]
if mi.shape[0]==0:
cylinder_obj = None
self.cylinder_object_list.append(cylinder_obj)
continue
f1.close()
print(" Selected number: ", mi.shape)
print(" Mstar statistics: ", np.min(mstar_msun[mi]), np.max(mstar_msun[mi]), np.median(mstar_msun[mi]))
print(" Mgas statistics: ", np.min(mgas_msun[mi]), np.max(mgas_msun[mi]), np.median(mgas_msun[mi]))
print(" Mag statistics : ", np.min(gmag[mi]), np.max(gmag[mi]), np.median(gmag[mi]))
for key in subhalos.keys():
if key == 'count':
continue
filtered_data = subhalos[key][mi]
subhalos[key] = filtered_data
# Now, periodicize
subhalos = self.periodicize(subhalos,self.L_comovingh*1000.0)
xpos = subhalos['SubhaloPos'][:,0] #in cKpc/h of max bound part
ypos = subhalos['SubhaloPos'][:,1]
zpos = subhalos['SubhaloPos'][:,2]
#project geometry
#campos
#in phys kpc, offset values from lightcone file!
xoff = self.v_Offset_x_kpc[i]
yoff = self.v_Offset_y_kpc[i]
zoff = self.v_Offset_z_kpc[i]
#the position here I think doesn't matter???
camera = tc.Camera([0,0,0],[self.camdir_x,self.camdir_y,self.camdir_z],[self.camup_x,self.camup_y,self.camup_z])
#galaxy world position
#convert to phys kpc following Renato's lead in translate_coordinates.py
#note there's an extra translation in the sunrise calcs, so we can discard that here
#box coordinates relative to ingress coordinate
boxX = (xpos/ilh) - self.v_Ingress_x_cmh[i]/ilh
boxY = (ypos/ilh) - self.v_Ingress_y_cmh[i]/ilh
boxZ = (zpos/ilh) - self.v_Ingress_z_cmh[i]/ilh
axi = f1.add_subplot(2,2,1)
axi.set_ylabel('boxI X',size=7,labelpad=1)
axi.set_xlabel('boxI Z',size=7,labelpad=1)
axi.tick_params(axis='both',which='major',labelsize=7)
axi.plot(boxZ[::skip],boxX[::skip],'ok')
#add box coordinate to world coordinate of ingress point
worldX = boxX+cmx_begin
worldY = boxY+cmy_begin
worldZ = boxZ+cmz_begin
axi = f1.add_subplot(2,2,2)
axi.set_ylabel('world X',size=7,labelpad=1)
axi.set_xlabel('world Z',size=7,labelpad=1)
axi.tick_params(axis='both',which='major',labelsize=7)
axi.plot(worldZ[::skip],worldX[::skip],'ok')
axi.plot([np.min(worldZ),np.max(worldZ)],[cmx_begin,cmx_begin],color='red')
velX = subhalos['SubhaloVel'][:,0]
velY = subhalos['SubhaloVel'][:,1]
velZ = subhalos['SubhaloVel'][:,2]
#galaxy cam position, in comoving kpc
galaxy_camera_posx,galaxy_camera_posy,galaxy_camera_posz = camera.cameraCoordinates_vector(worldX,worldY,worldZ)
galaxy_camera_velx,galaxy_camera_vely,galaxy_camera_velz = camera.cameraCoordinates_vector(velX,velY,velZ)
axi = f1.add_subplot(2,2,3)
axi.set_ylabel('cam X',size=7,labelpad=1)
axi.set_xlabel('cam Z',size=7,labelpad=1)
axi.tick_params(axis='both',which='major',labelsize=7)
axi.plot(galaxy_camera_posz[::skip],galaxy_camera_posx[::skip],'ok')
#galaxy projection using spherical coords
y1 = np.arctan2(galaxy_camera_posx,galaxy_camera_posz)/(0.5*(self.delb_arcmin/60.0)*(np.pi/180.0))
y2 = np.arctan2(galaxy_camera_posy,galaxy_camera_posz)/(0.5*(self.delb_arcmin/60.0)*(np.pi/180.0))
#range = [-1,1] = FOV = self.norm_degrees
axi = f1.add_subplot(2,2,4)
axi.set_ylabel('cam Y1',size=7,labelpad=1)
axi.set_xlabel('cam Y2',size=7,labelpad=1)
axi.set_xlim(-3,3)
axi.set_ylim(-3,3)
axi.tick_params(axis='both',which='major',labelsize=7)
axi.plot(y1,y2,'ok',markersize=0.5,mew=0.0)
axi.plot([-1,-1],[-1,1],color='red')
axi.plot([-1,1],[-1,-1],color='red')
axi.plot([1,1],[-1,1],color='red')
axi.plot([-1,1],[1,1],color='red')
#all values correspond to mi vector
#cull by RA, DEC, and segment length
ci = np.where(np.logical_and(np.logical_and(np.logical_and(np.abs(y1) <= 1.0, np.abs(y2) <= 1.0),galaxy_camera_posz <= cmd_end),galaxy_camera_posz > cmd_begin))[0]
print(" Selected N galaxies in FOV: ", ci.shape)
axi.plot(y1[ci],y2[ci],'or',markersize=0.7,mew=0.0)
RA_deg = y1[ci]*self.norm_degrees/2.0
DEC_deg = y2[ci]*self.norm_degrees/2.0
#save interesting quantities
if ci.shape[0] > 0:
print(cyl, cmd_begin, np.min(galaxy_camera_posz[ci]))
print(cyl, cmd_end, np.max(galaxy_camera_posz[ci]))
cylinder_obj = cylinder_catalog(snapnum,subhalos,ci,RA_deg,DEC_deg, self.snapshot_redshift[i],
galaxy_camera_posx,galaxy_camera_posy,galaxy_camera_posz,self.center_redshift[i],
galaxy_camera_velx,galaxy_camera_vely,galaxy_camera_velz,cyl,gmag[mi])
else:
cylinder_obj = None
self.cylinder_object_list.append(cylinder_obj)
#f1.savefig(testf)
plt.close(f1)
return self
def periodicize(self,subhalos,boxL):
xpos = subhalos['SubhaloPos'][:,0].flatten() #in cKpc/h of max bound part
ypos = subhalos['SubhaloPos'][:,1].flatten()
zpos = subhalos['SubhaloPos'][:,2].flatten()
N = xpos.shape[0]
sid = np.arange(N)
new_subhalos = copy.copy(subhalos)
new_x = copy.copy(xpos)
new_y = copy.copy(ypos)
new_z = copy.copy(zpos)
new_subhalos['SubFindID'] = np.concatenate((sid,sid))
new_subhalos['SubFindID'] = np.concatenate((new_subhalos['SubFindID'],sid))
new_subhalos['SubFindID'] = np.concatenate((new_subhalos['SubFindID'],sid))
new_subhalos['SubFindID'] = np.concatenate((new_subhalos['SubFindID'],sid))
new_subhalos['SubFindID'] = np.concatenate((new_subhalos['SubFindID'],sid))
new_subhalos['SubFindID'] = np.concatenate((new_subhalos['SubFindID'],sid))
keys = subhalos.keys()
for key in keys:
if key=='SubhaloPos':
#special
#x repeat
new_x = np.concatenate((new_x,xpos+boxL))
new_x = np.concatenate((new_x,xpos-boxL))
new_y = np.concatenate((new_y,ypos))
new_y = np.concatenate((new_y,ypos))
new_z = np.concatenate((new_z,zpos))
new_z = np.concatenate((new_z,zpos))
#y repeat
new_x = np.concatenate((new_x,xpos))
new_x = np.concatenate((new_x,xpos))
new_y = np.concatenate((new_y,ypos+boxL))
new_y = np.concatenate((new_y,ypos-boxL))
new_z = np.concatenate((new_z,zpos))
new_z = np.concatenate((new_z,zpos))
#z repeat
new_x = np.concatenate((new_x,xpos))
new_x = np.concatenate((new_x,xpos))
new_y = np.concatenate((new_y,ypos))
new_y = np.concatenate((new_y,ypos))
new_z = np.concatenate((new_z,zpos+boxL))
new_z = np.concatenate((new_z,zpos-boxL))
new_pos = np.column_stack((new_x,new_y,new_z))
new_subhalos[key] = new_pos
elif key=='count':
new_subhalos[key] = 7*subhalos[key]
else:
new_subhalos[key] = np.concatenate((new_subhalos[key],subhalos[key]))
new_subhalos[key] = np.concatenate((new_subhalos[key],subhalos[key]))
new_subhalos[key] = np.concatenate((new_subhalos[key],subhalos[key]))
new_subhalos[key] = np.concatenate((new_subhalos[key],subhalos[key]))
new_subhalos[key] = np.concatenate((new_subhalos[key],subhalos[key]))
new_subhalos[key] = np.concatenate((new_subhalos[key],subhalos[key])) #7 total boxes
return new_subhalos
def output_catalog(self,outfile):
print(" Saving catalog: ", outfile)
fobj = open(outfile,'w')
fobj.write('## Lightcone Catalog File for input geometry: '+self.lightconefile+'\n')
fobj.write('## Catalog source directory: '+self.base_dir+'\n')
fobj.write('## Square FOV (arcmin): {:12.6f}'.format(self.delb_arcmin)+'\n')
fobj.write('## Area (arcmin^2): {:12.6f}'.format(self.delb_arcmin**2)+'\n')
fobj.write('## Baryonic Mass Lower Limit (Msun) : {:10.5e}'.format(self.mass_limit)+'\n')
fobj.write('## Assumed Cosmology: '+WMAP7.__str__()+'\n')
fobj.write('## Creator: Teddy Pena (STScI) \n')
fobj.write('## Catalog & Data Release Reference: Nelson et al. (2019) \n')
fobj.write('## Catalog & Data Release URL: tng-project.org/data \n')
fobj.write('## Column 01: Snapshot number \n')
fobj.write('## Column 02: Subhalo Index \n')
fobj.write('## Column 03: RA (degrees) \n')
fobj.write('## Column 04: DEC (degrees) \n')
fobj.write('## Column 05: RA (proper kpc at true z) \n')
fobj.write('## Column 06: DEC (proper kpc at true z) \n')
fobj.write('## Column 07: RA (proper kpc at inferred z) \n')
fobj.write('## Column 08: DEC (proper kpc at inferred z) \n')
fobj.write('## Column 09: True cosmological redshift \n')
fobj.write('## Column 10: Inferred redshift (includes peculiar v) \n')
fobj.write('## Column 11: Peculiar redshift; Peculiar Velocity / Speed of Light \n')
fobj.write('## Column 12: True scale at cosmological z, in kpc/arcsec \n')
fobj.write('## Column 13: [Mpc] Comoving X in Observer Coordinates \n')
fobj.write('## Column 14: [Mpc] Comoving Y in Observer Coordinates \n')
fobj.write('## Column 15: [Mpc] Comoving Z in Observer Coordinates \n')
fobj.write('## Column 16: [Mpc] True Angular Diameter Distance to observer \n')
fobj.write('## Column 17: [Mpc] Inferred Angular Diameter Distance to observer \n')
fobj.write('## Column 18: Snapshot redshift \n')
fobj.write('## Column 19: Geometrically appropriate redshift at center of this cylinder \n')
fobj.write('## Column 20: Lightcone cylinder number \n')
fobj.write('## Column 21: [Msun] Stellar mass within 2X stellar half mass radius\n')
fobj.write('## Column 22: [Msun] Total gas mass within 2X stellar half mass radius\n')
fobj.write('## Column 23: [Msun] Total mass of this subhalo (excludes children subhalos) \n')
fobj.write('## Column 24: [Msun] Total BH mass within 2X stellar half mass radius\n')
fobj.write('## Column 25: [Msun] Total baryon mass within 2X stellar half mass radius\n')
fobj.write('## Column 26: [Msun/year] SFR within 2X stellar half mass radius\n')
fobj.write('## Column 27: [(10^10 Msun/h) / (0.978 Gyr/h)] Total BH accretion rate within subhalo\n')
fobj.write('## Column 28: [Mpc] Camera X in Observer Coordinates (Proper X at z; a transverse coordinate) \n')
fobj.write('## Column 29: [Mpc] Camera Y in Observer Coordinates (Proper Y at z; a transverse coordinate)\n')
fobj.write('## Column 30: [Mpc] Camera Z in Observer Coordinates (Proper Z at z; should be almost exactly Column 16)\n')
fobj.write('## Column 31: [AB Mag] Intrinsic stellar g absolute magnitude (BC03) \n')
fobj.write('## Column 32: [AB Mag] Intrinsic stellar r absolute magnitude (BC03) \n')
fobj.write('## Column 33: [AB Mag] Intrinsic stellar i absolute magnitude (BC03) \n')
fobj.write('## Column 34: [AB Mag] Intrinsic stellar z absolute magnitude (BC03) \n')
fobj.write('## Column 35: [km/s] Galaxy motion in transverse Camera X direction \n')
fobj.write('## Column 36: [km/s] Galaxy motion in transverse Camera Y direction \n')
fobj.write('## Column 37: [km/s] Galaxy motion in line-of-sight Camera Z direction ; the Peculiar Velocity \n')
fobj.write('## Column 38: [km/s] Cosmological expansion velocity at true z (Column 10 measures Column 37+38)\n')
fobj.write('## Column 39: [AB Mag] Apparent total rest-frame g-band magnitude (BC03) \n')
for cylobj in self.cylinder_object_list:
if cylobj is not None:
cylobj.print_cylinder(fobj)
fobj.close()
return
class cylinder_catalog:
def __init__(self,snapnum,subhalos,ci,RA_deg,DEC_deg,snapz,galaxy_camera_posx,galaxy_camera_posy,galaxy_camera_posz,centerz,galaxy_camera_velx,galaxy_camera_vely,galaxy_camera_velz,cyl,gmag):
#fields=['SubhaloMass','SubhaloMassInMaxRad','SubhaloMassInRadType','SubhaloMassInMaxRadType','SubhaloPos','SubhaloSFR','SubhaloSFRinRad','SubhaloVel','SubhaloBHMass','SubhaloBHMdot','SubhaloStellarPhotometrics','SubhaloWindMass']
self.snapshot_number = snapnum + np.zeros_like(ci)
self.subhalo_index = subhalos['SubFindID'][ci]
self.RA_deg = RA_deg
self.DEC_deg = DEC_deg
self.snapz = snapz + np.zeros_like(RA_deg)
self.center_z = centerz + np.zeros_like(RA_deg)
self.cylinder_number = cyl + np.zeros_like(self.subhalo_index)
self.galaxy_comoving_x_mpc = galaxy_camera_posx[ci]/1000.0
self.galaxy_comoving_y_mpc = galaxy_camera_posy[ci]/1000.0
self.galaxy_comoving_z_mpc = galaxy_camera_posz[ci]/1000.0
#self.galaxy_camera_posx = galaxy_camera_posx[ci]/1000.0
#self.galaxy_camera_posy = galaxy_camera_posy[ci]/1000.0
#self.galaxy_camera_posz = galaxy_camera_posz[ci]/1000.0
self.galaxy_camera_velx = galaxy_camera_velx[ci]
self.galaxy_camera_vely = galaxy_camera_vely[ci]
self.galaxy_camera_velz = galaxy_camera_velz[ci]
self.galaxy_peculiar_vr = 1.0*self.galaxy_camera_velz
self.galaxy_peculiar_z = 1.0*self.galaxy_peculiar_vr/(astropy.constants.c.value/1.0e3)
self.cosmological_redshift = np.zeros_like(self.RA_deg)
for i,index in enumerate(ci):
self.cosmological_redshift[i] = np.float64(z_at_value(WMAP7.comoving_distance, self.galaxy_comoving_z_mpc[i]*u.megaparsec,ztol=1e-12,maxfun=2000))
self.hubble_velocity = self.cosmological_redshift*astropy.constants.c.value/1.0e3 #in km/s
self.galaxy_observed_z = 1.0*self.cosmological_redshift + self.galaxy_peculiar_z
#self.galaxy_comoving_x_mpc = self.galaxy_camera_posx*(1.0 + self.cosmological_redshift)
#self.galaxy_comoving_y_mpc = self.galaxy_camera_posy*(1.0 + self.cosmological_redshift)
#self.galaxy_comoving_z_mpc = self.galaxy_camera_posz*(1.0 + self.cosmological_redshift)
self.galaxy_camera_posx = self.galaxy_comoving_x_mpc/(1.0 + self.cosmological_redshift)
self.galaxy_camera_posy = self.galaxy_comoving_y_mpc/(1.0 + self.cosmological_redshift)
self.galaxy_camera_posz = self.galaxy_comoving_z_mpc/(1.0 + self.cosmological_redshift)
self.angdiam_mpc = np.asarray(WMAP7.angular_diameter_distance(self.cosmological_redshift))
self.kpc_per_arcsec = np.asarray(WMAP7.kpc_proper_per_arcmin(self.cosmological_redshift)/60.0)
self.observed_angdiam_mpc = np.asarray(WMAP7.angular_diameter_distance(self.galaxy_observed_z))
self.observed_comoving_mpc = np.asarray(WMAP7.comoving_distance(self.galaxy_observed_z))
self.observed_kpc_per_arcsec = np.asarray(WMAP7.kpc_proper_per_arcmin(self.galaxy_observed_z)/60.0)
self.RA_kpc = self.RA_deg*3600.0*self.kpc_per_arcsec
self.DEC_kpc = self.DEC_deg*3600.0*self.kpc_per_arcsec
self.observed_RA_kpc = self.RA_deg*3600.0*self.observed_kpc_per_arcsec
self.observed_DEC_kpc = self.DEC_deg*3600.0*self.observed_kpc_per_arcsec
self.mstar_msun = subhalos['SubhaloMassInRadType'][self.subhalo_index,4]*(1.0e10)/ilh
self.mgas_msun = subhalos['SubhaloMassInRadType'][self.subhalo_index,0]*(1.0e10)/ilh #includes wind mass
self.mbh_msun = subhalos['SubhaloMassInRadType'][self.subhalo_index,5]*(1.0e10)/ilh
self.mhalo_msun = subhalos['SubhaloMass'][self.subhalo_index]*(1.0e10)/ilh
self.baryonmass_msun = self.mstar_msun + self.mgas_msun + self.mbh_msun #within 2x stellar half mass radius... best?
self.xpos_ckh = subhalos['SubhaloPos'][self.subhalo_index,0] #in cKpc/h of max bound part
self.ypos_ckh = subhalos['SubhaloPos'][self.subhalo_index,1]
self.zpos_ckh = subhalos['SubhaloPos'][self.subhalo_index,2]
self.xpos_pmpc = (self.xpos_ckh*1.0/(1.0 + snapz )/ilh)/1.0e3
self.ypos_pmpc = (self.ypos_ckh*1.0/(1.0 + snapz )/ilh)/1.0e3
self.zpos_pmpc = (self.zpos_ckh*1.0/(1.0 + snapz )/ilh)/1.0e3
self.xvel_kms = subhalos['SubhaloVel'][self.subhalo_index,0]
self.yvel_kms = subhalos['SubhaloVel'][self.subhalo_index,1]
self.zvel_kms = subhalos['SubhaloVel'][self.subhalo_index,2]
self.sfr = subhalos['SubhaloSFRinRad'][self.subhalo_index]
self.bhmdot = subhalos['SubhaloBHMdot'][self.subhalo_index]
self.gmag = subhalos['SubhaloStellarPhotometrics'][self.subhalo_index,4]
self.rmag = subhalos['SubhaloStellarPhotometrics'][self.subhalo_index,5]
self.imag = subhalos['SubhaloStellarPhotometrics'][self.subhalo_index,6]
self.zmag = subhalos['SubhaloStellarPhotometrics'][self.subhalo_index,7]
self.gmag_apparent=gmag[ci]
#self.total_redshift =
return
def print_cylinder(self,outobj):
for i,shi in enumerate(self.subhalo_index):
thisline = '{:8d}{:12d} {:12.6f} {:12.6f} {:10.2f} {:10.2f} {:10.2f} {:10.2f} '\
'{:12.8f} {:12.8f} {:12.4e} {:8.4f} '\
'{:10.4f} {:10.4f} {:16.4f} {:16.4f} {:16.4f} {:12.8f} {:12.8f} {:8d}'\
'{:12.4e} {:12.4e} {:12.4e} {:12.4e} {:12.4e} {:16.4f} {:10.4e}'\
' {:10.4f} {:10.4f} {:16.4f} {:8.2f} {:8.2f} {:8.2f} {:8.2f} {:8.2f} {:8.2f} {:8.2f} {:12.4e} {:8.2f}'\
'\n'.format(self.snapshot_number[i],shi,self.RA_deg[i],self.DEC_deg[i],self.RA_kpc[i],self.DEC_kpc[i],self.observed_RA_kpc[i],self.observed_DEC_kpc[i],
self.cosmological_redshift[i],self.galaxy_observed_z[i],self.galaxy_peculiar_z[i],self.kpc_per_arcsec[i],
self.galaxy_comoving_x_mpc[i],self.galaxy_comoving_y_mpc[i],self.galaxy_comoving_z_mpc[i],self.angdiam_mpc[i],self.observed_angdiam_mpc[i],self.snapz[i],self.center_z[i],self.cylinder_number[i],
self.mstar_msun[i],self.mgas_msun[i],self.mhalo_msun[i],self.mbh_msun[i],self.baryonmass_msun[i],self.sfr[i],self.bhmdot[i],
self.galaxy_camera_posx[i],self.galaxy_camera_posy[i],self.galaxy_camera_posz[i],
self.gmag[i],self.rmag[i],self.imag[i],self.zmag[i],
self.galaxy_camera_velx[i],self.galaxy_camera_vely[i],self.galaxy_camera_velz[i],self.hubble_velocity[i],self.gmag_apparent[i])
outobj.write(thisline)
return
def process_lightcone_catalog(lightcone=None,base_dir=None,mass_limit=10.0**9.5,sfr_limit=0.0,mag_limit=None):
assert (lightcone is not None) and (base_dir is not None)
assert os.path.lexists(base_dir)
catalog_object = lightcone_catalog(lightcone,base_dir,mass_limit=mass_limit,sfr_limit=sfr_limit,mag_limit=mag_limit)
return catalog_object
if __name__=="__main__":
#start with conservative limits -- should be relatively few sources
magl=30
minz=0.1
maxz=8.8
catalog_xyz = process_lightcone_catalog(lightcone="./tng300_6_5_xyz.txt",base_dir='/home/tnguser/sims.TNG/TNG300-1/output/',mag_limit=magl)
catalog_xyz = catalog_xyz.process_lightcone(minz=minz,maxz=maxz)
catalog_xyz.output_catalog('./Lightcone_TNG300-1_mag30_6_5_xyz_TEST.txt')
| {
"content_hash": "7ae1e5facefc92ef637d744054583fd2",
"timestamp": "",
"source": "github",
"line_count": 622,
"max_line_length": 241,
"avg_line_length": 44.90192926045016,
"alnum_prop": 0.5910344086791507,
"repo_name": "gsnyder206/mock-surveys",
"id": "4858ade892b6741465d32aa0200492ae16d035d9",
"size": "28096",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mocks_from_publicdata/summer2020/tng_lightcone_catalogs2.0.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "IDL",
"bytes": "42610"
},
{
"name": "Jupyter Notebook",
"bytes": "7514654"
},
{
"name": "Prolog",
"bytes": "24960"
},
{
"name": "Python",
"bytes": "664895"
},
{
"name": "Roff",
"bytes": "19364"
},
{
"name": "Shell",
"bytes": "465"
}
],
"symlink_target": ""
} |
from msrest.serialization import Model
class EdifactFramingSettings(Model):
"""The Edifact agreement framing settings.
:param service_code_list_directory_version: The service code list
directory version.
:type service_code_list_directory_version: str
:param character_encoding: The character encoding.
:type character_encoding: str
:param protocol_version: The protocol version.
:type protocol_version: int
:param data_element_separator: The data element separator.
:type data_element_separator: int
:param component_separator: The component separator.
:type component_separator: int
:param segment_terminator: The segment terminator.
:type segment_terminator: int
:param release_indicator: The release indicator.
:type release_indicator: int
:param repetition_separator: The repetition separator.
:type repetition_separator: int
:param character_set: The EDIFACT frame setting characterSet. Possible
values include: 'NotSpecified', 'UNOB', 'UNOA', 'UNOC', 'UNOD', 'UNOE',
'UNOF', 'UNOG', 'UNOH', 'UNOI', 'UNOJ', 'UNOK', 'UNOX', 'UNOY', 'KECA'
:type character_set: str or :class:`EdifactCharacterSet
<azure.mgmt.logic.models.EdifactCharacterSet>`
:param decimal_point_indicator: The EDIFACT frame setting decimal
indicator. Possible values include: 'NotSpecified', 'Comma', 'Decimal'
:type decimal_point_indicator: str or :class:`EdifactDecimalIndicator
<azure.mgmt.logic.models.EdifactDecimalIndicator>`
:param segment_terminator_suffix: The EDIFACT frame setting segment
terminator suffix. Possible values include: 'NotSpecified', 'None', 'CR',
'LF', 'CRLF'
:type segment_terminator_suffix: str or :class:`SegmentTerminatorSuffix
<azure.mgmt.logic.models.SegmentTerminatorSuffix>`
"""
_validation = {
'protocol_version': {'required': True},
'data_element_separator': {'required': True},
'component_separator': {'required': True},
'segment_terminator': {'required': True},
'release_indicator': {'required': True},
'repetition_separator': {'required': True},
'character_set': {'required': True},
'decimal_point_indicator': {'required': True},
'segment_terminator_suffix': {'required': True},
}
_attribute_map = {
'service_code_list_directory_version': {'key': 'serviceCodeListDirectoryVersion', 'type': 'str'},
'character_encoding': {'key': 'characterEncoding', 'type': 'str'},
'protocol_version': {'key': 'protocolVersion', 'type': 'int'},
'data_element_separator': {'key': 'dataElementSeparator', 'type': 'int'},
'component_separator': {'key': 'componentSeparator', 'type': 'int'},
'segment_terminator': {'key': 'segmentTerminator', 'type': 'int'},
'release_indicator': {'key': 'releaseIndicator', 'type': 'int'},
'repetition_separator': {'key': 'repetitionSeparator', 'type': 'int'},
'character_set': {'key': 'characterSet', 'type': 'EdifactCharacterSet'},
'decimal_point_indicator': {'key': 'decimalPointIndicator', 'type': 'EdifactDecimalIndicator'},
'segment_terminator_suffix': {'key': 'segmentTerminatorSuffix', 'type': 'SegmentTerminatorSuffix'},
}
def __init__(self, protocol_version, data_element_separator, component_separator, segment_terminator, release_indicator, repetition_separator, character_set, decimal_point_indicator, segment_terminator_suffix, service_code_list_directory_version=None, character_encoding=None):
self.service_code_list_directory_version = service_code_list_directory_version
self.character_encoding = character_encoding
self.protocol_version = protocol_version
self.data_element_separator = data_element_separator
self.component_separator = component_separator
self.segment_terminator = segment_terminator
self.release_indicator = release_indicator
self.repetition_separator = repetition_separator
self.character_set = character_set
self.decimal_point_indicator = decimal_point_indicator
self.segment_terminator_suffix = segment_terminator_suffix
| {
"content_hash": "4031c549904b80dfaaa1f06f64435a00",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 281,
"avg_line_length": 54.57142857142857,
"alnum_prop": 0.6899095668729177,
"repo_name": "SUSE/azure-sdk-for-python",
"id": "59bfcf4c3c911c3631cac5d56b222b62f3ba0b66",
"size": "4676",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "azure-mgmt-logic/azure/mgmt/logic/models/edifact_framing_settings.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "9090161"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
if __name__ == "__main__":
import time
import gc
import timeit
import functools
from v8cffi.platform import platform
OPS_NUMBER = 110000
def do_all():
with platform as pm:
with pm.create_vm() as vm:
with vm.create_context() as context:
# hello = b'hi' * 10000
hello = b'hi'
context.run_script(b"var hello = '" + hello + b"';")
# 110000 ops/s on a 1.8Ghz CPU
print(timeit.timeit(functools.partial(context.run_script, b"hello"), number=OPS_NUMBER))
print('ok')
do_all()
#gc.collect()
#time.sleep(30)
| {
"content_hash": "edf724f3c93e44f667d183cde62ddeab",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 108,
"avg_line_length": 25.586206896551722,
"alnum_prop": 0.5094339622641509,
"repo_name": "nitely/v8-cffi",
"id": "38766db8a9a8f2c655fb09e7de0b482523cc5bbd",
"size": "767",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "benchmarks.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2407"
},
{
"name": "C++",
"bytes": "365725"
},
{
"name": "Makefile",
"bytes": "743"
},
{
"name": "Python",
"bytes": "38364"
}
],
"symlink_target": ""
} |
from GameLogic import BarrackFactory
from GameLogic import UnitFactory
from GameLogic.Player import Player
class GameLogic:
def __init__(self, players, _turn=0):
self.Players = players
self._turn = _turn
from GameLogic.Map import Map
self._map = Map(self)
@property
def Map(self):
return self._map
@property
def Turns(self) -> int:
return self._turn
@property
def Round(self) -> int:
return self._turn / self.TotalPlayers
@property
def TotalPlayers(self) -> int:
return len(self.Players)
@property
def PlayingPlayer(self) -> Player:
return self.Players[self._turn % self.TotalPlayers]
_gamestarted = False
def StartGame(self):
if self._gamestarted:
raise Exception("game already started")
else:
self._gamestarted = True
self.PlayingPlayer.Moves = 4
def AddNewPlayer(self, Name) -> Player:
if not self._gamestarted:
characterIndex = self.Players[-1].Character + 1
player = Player(Name, characterIndex, 0, 0)
self.Players.append(player)
return player
else:
raise Exception("game already started")
def EndTurn(self):
self.PlayingPlayer.Moves = 0
self._turn += 1
self.PlayingPlayer.Moves = 4
self.PlayingPlayer.Money += self.GetIncome()
def GetIncome(self, player: Player = None):
player = player if player is not None else self.PlayingPlayer
tilesWithUnit = list(set([unit.Tile for unit in player.Units]))
return sum([tile.GetMoney(player) for tile in tilesWithUnit])
def BuyUnit(self, unitType, tile):
if self.PlayingPlayer.Moves > 0:
unit = UnitFactory.BuyUnit(self, unitType, tile, self.PlayingPlayer)
if unit is not None:
self.PlayingPlayer.Moves -= 1
return unit
def BuyBarrack(self, tile):
if self.PlayingPlayer.Moves > 0:
BarrackFactory.BuyBarrack(self, tile, self.PlayingPlayer)
def CheckWinner(self):
return next((player for player in self.Players if player.Money >= 50000), None)
| {
"content_hash": "029738be880554b1352d5dd9cb4fa73c",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 87,
"avg_line_length": 28.53846153846154,
"alnum_prop": 0.6159029649595688,
"repo_name": "HRODEV/Frequency",
"id": "ddd952e1265dd3dfc189c1fa9faace803585f623",
"size": "2226",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Frequency/GameLogic/GameLogic.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "112720"
}
],
"symlink_target": ""
} |
import copy, sys
import numpy
if sys.version_info[0] > 2:
xrange = range
def preserve_doc(f):
f.__doc__ = eval('numpy.ndarray.%s.__doc__' % f.__name__)
return f
class TaggedArray(numpy.ndarray):
'''
TaggedArray extends numpy.ndarray with an attribute 'axistags'. Any
axistags object must support the standard sequence interface, and its
length must match the number of dimensions of the array. Each item in
the axistags sequence is supposed to provide a description of the
corresponding array axis. All array functions that change the number or
ordering of an array's axes (such as transpose() and __getitem__()) are
overloaded so that they apply the same transformation to the axistags
object.
Example:
>>> axistags = ['x', 'y']
>>> a = TaggedArray((2,3), axistags=axistags)
>>> a.axistags
['x', 'y']
>>> a[:,0].axistags
['x']
>>> a[1,...].axistags
['y']
>>> a.transpose().axistags
['y', 'x']
Except for the new 'axistags' keyword, the 'TaggedArray' constructor is identical to the constructor
of 'numpy.ndarray'.
'''
def __new__(subtype, shape, dtype=float, buffer=None, offset=0, strides=None, order=None, axistags=None):
res = numpy.ndarray.__new__(subtype, shape, dtype, buffer, offset, strides, order)
if axistags is None:
res.axistags = res.default_axistags()
else:
if len(axistags) != res.ndim:
raise RuntimeError('TaggedArray(): len(axistags) must match ndim')
res.axistags = copy.copy(axistags)
return res
def default_axistags(self):
'''Create an axistags object with non-informative entries.
'''
return [None]*self.ndim
def copy_axistags(self):
'''Create a copy of 'self.axistags'. If the array doesn't have axistags, default_axistags()
will be returned.
'''
return copy.copy(getattr(self, 'axistags', self.default_axistags()))
def transpose_axistags(self, axes=None):
'''Create a copy of 'self.axistags' according to the given axes permutation
(internally called in transpose()).
'''
axistags = self.default_axistags()
if hasattr(self, 'axistags'):
if axes is None:
axes = range(self.ndim-1, -1, -1)
for k in xrange(self.ndim):
axistags[k] = self.axistags[int(axes[k])]
return axistags
def transform_axistags(self, index):
'''Create a copy of 'self.axistags' according to the given index or slice object
(internally called in __getitem__()).
'''
# we assume that self.ndim is already set to its new value, whereas
# self.axistags has just been copied by __array_finalize__
new_axistags = self.default_axistags()
if hasattr(self, 'axistags'):
old_axistags = self.axistags
old_ndim = len(old_axistags)
new_ndim = len(new_axistags)
try:
# make sure that 'index' is a tuple
len_index = len(index)
except:
index = (index,)
len_index = 1
len_index -= index.count(numpy.newaxis)
if len_index < old_ndim and index.count(Ellipsis) == 0:
index += (Ellipsis,)
len_index += 1
# how many missing axes are represented by an Ellipsis ?
len_ellipsis = old_ndim - len_index
knew, kold, kindex = 0, 0, 0
while knew < new_ndim:
try:
# if index[kindex] is int, the dimension is bound => drop this axis
int(index[kindex])
kold += 1
kindex += 1
except:
if index[kindex] is not numpy.newaxis:
# copy the tag
new_axistags[knew] = old_axistags[kold]
kold += 1
knew += 1
# the first ellipsis represents all missing axes
if len_ellipsis > 0 and index[kindex] is Ellipsis:
len_ellipsis -= 1
else:
kindex += 1
return new_axistags
__array_priority__ = 10.0
def __array_finalize__(self, obj):
if hasattr(obj, 'axistags'):
self.axistags = obj.axistags
@preserve_doc
def __copy__(self, order = 'C'):
result = numpy.ndarray.__copy__(self, order)
result.axistags = result.copy_axistags()
return result
@preserve_doc
def __deepcopy__(self, memo):
result = numpy.ndarray.__deepcopy__(self, memo)
memo[id(self)] = result
result.__dict__ = copy.deepcopy(self.__dict__, memo)
return result
def __repr__(self):
return "%s(shape=%s, axistags=%s, dtype=%s, data=\n%s)" % \
(self.__class__.__name__, str(self.shape), repr(self.axistags), str(self.dtype), str(self))
@preserve_doc
def all(self, axis=None, out=None):
res = numpy.ndarray.all(self, axis, out)
if axis is not None:
res.axistags = res.copy_axistags()
del res.axistags[axis]
return res
@preserve_doc
def any(self, axis=None, out=None):
res = numpy.ndarray.any(self, axis, out)
if axis is not None:
res.axistags = res.copy_axistags()
del res.axistags[axis]
return res
@preserve_doc
def argmax(self, axis=None, out=None):
res = numpy.ndarray.argmax(self, axis, out)
if axis is not None:
res.axistags = res.copy_axistags()
del res.axistags[axis]
return res
@preserve_doc
def argmin(self, axis=None, out=None):
res = numpy.ndarray.argmin(self, axis, out)
if axis is not None:
res.axistags = res.copy_axistags()
del res.axistags[axis]
return res
@preserve_doc
def cumsum(self, axis=None, dtype=None, out=None):
res = numpy.ndarray.cumsum(self, axis, dtype, out)
if res.ndim != self.ndim:
res.axistags = res.default_axistags()
return res
@preserve_doc
def cumprod(self, axis=None, dtype=None, out=None):
res = numpy.ndarray.cumprod(self, axis, dtype, out)
if res.ndim != self.ndim:
res.axistags = res.default_axistags()
return res
# FIXME: we should also provide a possibility to determine flattening order by axistags
# (the same applies to flat and ravel)
@preserve_doc
def flatten(self, order='C'):
res = numpy.ndarray.flatten(self, order)
res.axistags = res.default_axistags()
return res
@preserve_doc
def max(self, axis=None, out=None):
res = numpy.ndarray.max(self, axis, out)
if axis is not None:
res.axistags = res.copy_axistags()
del res.axistags[axis]
return res
@preserve_doc
def mean(self, axis=None, out=None):
res = numpy.ndarray.mean(self, axis, out)
if axis is not None:
res.axistags = res.copy_axistags()
del res.axistags[axis]
return res
@preserve_doc
def min(self, axis=None, out=None):
res = numpy.ndarray.min(self, axis, out)
if axis is not None:
res.axistags = res.copy_axistags()
del res.axistags[axis]
return res
@preserve_doc
def nonzero(self):
res = numpy.ndarray.nonzero(self)
for k in xrange(len(res)):
res[k].axistags = copy.copy(self.axistags[k])
return res
@preserve_doc
def prod(self, axis=None, dtype=None, out=None):
res = numpy.ndarray.prod(self, axis, dtype, out)
if axis is not None:
res.axistags = res.copy_axistags()
del res.axistags[axis]
return res
@preserve_doc
def ptp(self, axis=None, out=None):
res = numpy.ndarray.ptp(self, axis, out)
if axis is not None:
res.axistags = res.copy_axistags()
del res.axistags[axis]
return res
@preserve_doc
def ravel(self, order='C'):
res = numpy.ndarray.ravel(self, order)
res.axistags = res.default_axistags()
return res
@preserve_doc
def repeat(self, repeats, axis=None):
res = numpy.ndarray.repeat(self, repeats, axis)
if axis is None:
res.axistags = res.default_axistags()
return res
@preserve_doc
def reshape(self, shape, order='C'):
res = numpy.ndarray.reshape(self, shape, order)
res.axistags = res.default_axistags()
return res
@preserve_doc
def resize(self, new_shape, refcheck=True, order=False):
res = numpy.ndarray.reshape(self, new_shape, refcheck, order)
res.axistags = res.default_axistags()
return res
@preserve_doc
def squeeze(self):
res = numpy.ndarray.squeeze(self)
if self.ndim != res.ndim:
res.axistags = res.copy_axistags()
for k in xrange(self.ndim-1, -1, -1):
if self.shape[k] == 1:
del res.axistags[k]
return res
@preserve_doc
def std(self, axis=None, dtype=None, out=None, ddof=0):
res = numpy.ndarray.std(self, axis, dtype, out, ddof)
if axis is not None:
res.axistags = res.copy_axistags()
del res.axistags[axis]
if len(res.shape) == 0:
res = res.item()
return res
@preserve_doc
def sum(self, axis=None, dtype=None, out=None):
res = numpy.ndarray.sum(self, axis, dtype, out)
if axis is not None:
res.axistags = res.copy_axistags()
del res.axistags[axis]
return res
@preserve_doc
def swapaxes(self, i, j):
res = numpy.ndarray.swapaxes(self, i, j)
res.axistags = res.copy_axistags()
res.axistags[i], res.axistags[j] = res.axistags[j], res.axistags[i]
return res
@preserve_doc
def take(self, indices, axis=None, out=None, mode='raise'):
res = numpy.ndarray.take(self, indices, axis, out, mode)
if axis is None:
res.axistags = res.default_axistags()
return res
@preserve_doc
def transpose(self, *axes):
res = numpy.ndarray.transpose(self, *axes)
res.axistags = res.transpose_axistags(*axes)
return res
@preserve_doc
def var(self, axis=None, dtype=None, out=None, ddof=0):
res = numpy.ndarray.var(self, axis, dtype, out, ddof)
if axis is not None:
res.axistags = res.copy_axistags()
del res.axistags[axis]
if len(res.shape) == 0:
res = res.item()
return res
@property
def T(self):
return self.transpose()
def __getitem__(self, index):
'''x.__getitem__(y) <==> x[y]
In addition to the usual indexing functionality, this function
also updates the axistags of the result array. There are three cases:
* getitem creates a scalar value => no axistags are required
* getitem creates an arrayview => axistags are transferred from the
corresponding axes of the base array,
axes resulting from 'newaxis' get tag 'None'
* getitem creates a copy of an array (fancy indexing) => all axistags are 'None'
'''
res = numpy.ndarray.__getitem__(self, index)
if res is not self and hasattr(res, 'axistags'):
if res.base is self:
res.axistags = res.transform_axistags(index)
else:
res.axistags = res.default_axistags()
return res
| {
"content_hash": "06c24d94c493e37b7c32f8a41e5361bf",
"timestamp": "",
"source": "github",
"line_count": 345,
"max_line_length": 109,
"avg_line_length": 34.333333333333336,
"alnum_prop": 0.5666525960320811,
"repo_name": "funkey/vigra",
"id": "b5aa9546f96f2d3ab959c559b9184b4aa727c84b",
"size": "13458",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "vigranumpy/lib/tagged_array.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "3203"
},
{
"name": "C",
"bytes": "113143"
},
{
"name": "C++",
"bytes": "21347233"
},
{
"name": "CMake",
"bytes": "105731"
},
{
"name": "CSS",
"bytes": "65018"
},
{
"name": "HTML",
"bytes": "471605"
},
{
"name": "Inno Setup",
"bytes": "6501"
},
{
"name": "JavaScript",
"bytes": "24066"
},
{
"name": "Jupyter Notebook",
"bytes": "3391055"
},
{
"name": "Matlab",
"bytes": "32719"
},
{
"name": "Python",
"bytes": "464059"
},
{
"name": "Shell",
"bytes": "809"
},
{
"name": "TeX",
"bytes": "15209"
}
],
"symlink_target": ""
} |
import tensorflow as tf
from data_generator import DataGenerator
from models import Model
import os,sys
import time
from mlperf_logging import mllog
from threading import Thread
###### npu ######
from npu_bridge.estimator import npu_ops
from tensorflow.core.protobuf.rewriter_config_pb2 import RewriterConfig
from npu_bridge.estimator.npu import util
# HCCL
from npu_bridge.hccl import hccl_ops
from hccl.manage.api import get_local_rank_id
from hccl.manage.api import get_rank_size
from hccl.manage.api import get_rank_id
from npu_bridge.estimator.npu import npu_compile
from npu_bridge.helper import helper
gen_npu_ops = helper.get_gen_ops();
###### npu ######
rank_size = int(os.getenv('RANK_SIZE'))
rank_id = int(os.getenv('RANK_ID').split("-")[-1])
device_id = int(os.getenv('DEVICE_ID')) + rank_id * 8
###############################
# MLperf log
if device_id == 0:
mllogger = mllog.get_mllogger()
mllog.config(filename='resnet_close.log')
mllog.config(
default_namespace='worker1',
default_stack_offset=1,
default_clear_line=False,
root_dir=os.path.normpath(os.path.dirname(os.path.realpath(__file__)))
)
mllogger.event(key=mllog.constants.SUBMISSION_BENCHMARK, value="resnet" )
mllogger.event(key=mllog.constants.SUBMISSION_DIVISION, value="open" )
mllogger.event(key=mllog.constants.SUBMISSION_ORG, value="SIAT" )
mllogger.event(key=mllog.constants.SUBMISSION_PLATFORM, value="Ascend 910" )
mllogger.event(key=mllog.constants.SUBMISSION_STATUS, value="cloud" )
mllogger.event(key=mllog.constants.CACHE_CLEAR )
params = {
# 'data_dir': '/opt/dataset/imagenet_TF',
# 'data_dir': '/cache/ImageNet',
'data_dir': '/home/work/datasets/Dataset',
'num_classes': 1001,
'batch_size': 32,
'num_threads': 96,
'use_synthetic': False,
'model_name': 'resnet50',
'data_format': 'channels_last',
'arch_type': 'Original',
'resnet_version': 'v1.5',
'ckpt_path': './results',
'learning_rate': 25.0,
'momentum': 0.95,
'weight_decay': 0.0001,
'train_epochs': 24,
'eval_interval_epochs':4,
'print_interval':1,
# distributed config
'use_lars': True,
'dtype': tf.float32,
# --- lr ----
'mode':'cosine',
'warmup_epochs': 7.6,
# #### npu #####
'iterations_per_loop_train': 10,
}
params['global_batch_size'] = rank_size * params['batch_size']
eval_graph = tf.Graph()
config = tf.ConfigProto()
config.allow_soft_placement = True
train_data_gen = DataGenerator(params)
eval_data_gen = DataGenerator(params)
###################### npu ##########################
config.graph_options.rewrite_options.remapping = RewriterConfig.OFF
custom_op = config.graph_options.rewrite_options.custom_optimizers.add()
custom_op.name = "NpuOptimizer"
custom_op.parameter_map["enable_data_pre_proc"].b = True
custom_op.parameter_map["use_off_line"].b = True
custom_op.parameter_map["hcom_parallel"].b = True
custom_op.parameter_map["min_group_size"].b = 1
custom_op.parameter_map["precision_mode"].s = tf.compat.as_bytes("allow_mix_precision")
custom_op.parameter_map["iterations_per_loop"].i = params['total_steps']
#custom_op.parameter_map["iterations_per_loop"].i = params['iterations_per_loop_train']
################ npu ###################
config.intra_op_parallelism_threads=96
config.inter_op_parallelism_threads=96
def main():
main_graph = tf.Graph()
model = Model(params)
input_queues = []
with main_graph.as_default():
tf.set_random_seed(1)
train_input_iterator = train_data_gen.make_iterator_initialize(training=True)
print ('--- train make iterator -----')
eval_input_iterator = eval_data_gen.make_iterator_initialize(training=False)
print ('--- eval make iterator -----')
train_input_init_op = train_input_iterator.initializer
eval_input_init_op = eval_input_iterator.initializer
train_sample = train_input_iterator.get_next()
eval_sample = eval_input_iterator.get_next()
# Flags to indicate train or eval
float_status = tf.constant([0.0], dtype=tf.float32)
total_steps = tf.Variable(initial_value=tf.constant(0,tf.int32), trainable=False)
train_steps = tf.train.get_or_create_global_step()
total_steps = tf.assign_add(total_steps, 1)
with tf.control_dependencies([total_steps]):
eval_flag = tf.mod(total_steps - 1, params['total_steps_per_eval'] )
init_local_flag = tf.equal( eval_flag, params['training_steps_between_evals']-1 )
def train_fn():
with tf.variable_scope('Res', reuse=False):
train_op, predicted_label, base_loss, lr, training_s, labels = model.model_func(train_sample[0], train_sample[1], is_training=True, train_steps=train_steps)
# train_op, predicted_label, base_loss, labels = model.model_func(train_data, train_label, is_training=True)
with tf.control_dependencies([train_op]):
# train_steps = tf.train.get_or_create_global_step()
increase_train_steps_op = tf.assign_add(train_steps, 1, name='NpuCompile')
with tf.control_dependencies([increase_train_steps_op]):
train_fn_op = tf.no_op(name='train_op_0')
return train_fn_op, predicted_label, base_loss,lr, training_s, labels
def eval_fn():
with tf.variable_scope('Res', reuse=True):
eval_op, predicted_label, base_loss, lr, training_s, labels = model.model_func(eval_sample[0], eval_sample[1], is_training=False, train_steps=train_steps)
with tf.control_dependencies([eval_op]):
eval_fn_op = tf.no_op(name='eval_op_0')
return eval_fn_op, predicted_label, base_loss,lr, training_s, labels
# choose to exe train or eval
final_op, predicted_label, final_base_loss, lr, training_s, labels = tf.cond( eval_flag < params['training_steps_between_evals'], train_fn, eval_fn)
with tf.control_dependencies([final_op]):
final_op = tf.no_op(name='Final_op')
# when eval, initial metric's local vars
float_status = gen_npu_ops.npu_alloc_float_status() # when first step, avoid NaN
weights = tf.greater(labels, -1)
eval_value, metric_update_op = tf.metrics.accuracy( labels = labels, predictions=predicted_label, weights=weights )
with tf.control_dependencies([metric_update_op]):
# local_float_status = gen_npu_ops.npu_get_float_status(float_status)
# cleared_float_status = gen_npu_ops.npu_clear_float_status(local_float_status)
# no_nan = tf.reduce_all( tf.equal( float_status, cleared_float_status ) )
# def allreduce_no_nan():
# return eval_accuracy
# def allreduce_nan():
# return tf.constant(0.0, tf.float32)
# eval_accuracy = tf.cond( no_nan, allreduce_no_nan, allreduce_nan )
local_vars = tf.local_variables() # VAR total and count in Metric
eval_accuracy = tf.divide(local_vars[0],local_vars[1])
eval_accuracy = hccl_ops.allreduce( eval_accuracy, "sum", fusion=0 )
print_op = tf.print(eval_accuracy, eval_flag, init_local_flag, total_steps, train_steps, local_vars[0], local_vars[1])
with tf.control_dependencies([print_op]):
print_op_2 = tf.identity( eval_accuracy )
def clear_local_vars_true():
clear_op_1 = tf.assign( local_vars[0], tf.constant(0, tf.float32) )
clear_op_2 = tf.assign( local_vars[1], tf.constant(0, tf.float32) )
with tf.control_dependencies([clear_op_1, clear_op_2]):
clear_op = tf.no_op(name='clear_local_vars_true')
return clear_op
def clear_local_vars_false():
clear_op = tf.no_op(name='clear_local_vars_false')
return clear_op
with tf.control_dependencies([print_op_2]):
clear_op_final = tf.cond( init_local_flag, clear_local_vars_true, clear_local_vars_false )
saver = tf.train.Saver()
main_sess = tf.Session(graph=main_graph, config = config)
with main_sess as sess:
if device_id == 0:
mllogger.start(key=mllog.constants.INIT_START)
mllogger.event(key=mllog.constants.GLOBAL_BATCH_SIZE, value=params['global_batch_size'])
mllogger.event(key="opt_name", value="lars")
mllogger.event(key="lars_opt_weight_decay", value=params['weight_decay'])
mllogger.event(key="lars_epsilon", value=0.0)
mllogger.event(key="lars_opt_base_learning_rate", value=params['learning_rate'])
mllogger.event(key="lars_opt_end_learning_rate", value=0.0001)
mllogger.event(key="lars_opt_learning_rate_decay_poly_power", value=2)
decay_steps = (params['train_epochs'] - params['warmup_epochs'])*params['training_steps_per_epoch']
mllogger.event(key="lars_opt_learning_rate_decay_steps", value=decay_steps)
mllogger.event(key="lars_opt_learning_rate_warmup_epochs", value=params['warmup_epochs'])
mllogger.event(key="lars_opt_momentum", value=params['momentum'])
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
sess.run(tf.tables_initializer())
# ################# npu ##################
# final_op = util.set_iteration_per_loop(sess, final_op, params['iterations_per_loop_train'])
final_op = util.set_iteration_per_loop(sess, final_op, params['total_steps'])
# ################# npu ##################
time_start = time.time()
real_steps = int( float(params['total_steps']) / float( params['iterations_per_loop_train'] ))
# compile graph
fetches = [final_op, clear_op_final,eval_accuracy, total_steps, train_steps, final_base_loss, eval_flag, lr, training_s]
npu_compile.npu_compile( sess, fetches )
sess.run(train_input_init_op)
sess.run(eval_input_init_op)
if device_id == 0:
mllogger.end(key=mllog.constants.INIT_STOP)
mllogger.start(key=mllog.constants.RUN_START)
mllogger.event(key='train_samples', value=params['num_training_samples'])
mllogger.event(key='eval_samples', value=params['num_evaluate_samples'])
# start to train & eval
sess.run( fetches )
def dequeue():
global config
tf.reset_default_graph()
outfeed_log_tensors = npu_ops.outfeed_dequeue_op(
channel_name="_npu_log",
output_types=[tf.string],
output_shapes=[()])
with tf.Session() as sess:
time_start = time.time()
step_count = 0
current_epoch = 0
i = 0
while True:
# if step_count >= 0 :
# cal flags
current_block = (step_count // params['total_steps_per_eval']) + 1
step_in_block = step_count % params['total_steps_per_eval']
step_in_epoch = step_in_block % params['training_steps_per_epoch']
epoch_in_block = step_in_block // params['training_steps_per_epoch'] + 1
current_epoch = (current_block - 1) * params['eval_interval_epochs'] + epoch_in_block
time_end = time.time()
time_duration = time_end - time_start
fps = float( params['global_batch_size'] ) / time_duration
time_start = time.time()
result = sess.run( outfeed_log_tensors )
if device_id == 0:
# count block
if step_in_block == 0:
mllogger.start(key=mllog.constants.BLOCK_START, metadata={'first_epoch_num':current_epoch-1, 'epoch_count':params['eval_interval_epochs']})
if step_in_block == params['training_steps_between_evals']-1:
mllogger.end(key=mllog.constants.BLOCK_STOP, metadata={'first_epoch_num':current_epoch-1} )
# count eval
# if step_in_block == params['training_steps_between_evals']-1:
# mllogger.start(key=mllog.constants.EVAL_START)
if step_in_block == params['total_steps_per_eval']-1:
a = result[0].decode('UTF-8')
acc = float( a.split(' ')[0] ) / float(rank_size)
# mllogger.end(key=mllog.constants.EVAL_STOP)
mllogger.event(key=mllog.constants.EVAL_ACCURACY, value = acc, metadata={'epoch_num': current_epoch - 1})
if acc > 0.759:
mllogger.end(key=mllog.constants.RUN_STOP)
break
# finish running
if step_count == params['total_steps']-1:
mllogger.end(key=mllog.constants.RUN_STOP, metadata={'status':'success'})
break
# regular printings
print ( '----LOGGING---- step:', step_count , ' epoch:', current_epoch, ' fps:', fps, ' time_duration(ms):', time_duration * 1000)
step_count = step_count + 1
# if (i % params['total_steps_per_eval']) == params['total_steps_per_eval'] - 1:
# a = result[0].decode('UTF-8')
# acc = float( a.split(' ')[0] ) / float(rank_size)
# print ( '----Eval Result---- step:', i , ' fps:', fps, ' time_duration(ms):', time_duration * 1000, 'Accuracy:', acc, 'result:', result )
# if acc > 0.759:
# print ('TIME_LOG: acheive 75.9% accuracy, training STOP,', time.time())
# elif i % 1 == 0:
# a = result[0].decode('UTF-8')
# acc = float( a.split(' ')[0] ) / float(rank_size)
# print ( '----Training---- step:', i , ' fps:', fps, ' time_duration(ms):', time_duration * 1000, 'Accuracy:', acc, 'result:', result)
# if i == params['total_steps']-1:
# print ('TIME_LOG: training End:', time.time())
# break
# if i == 0:
# print ('TIME_LOG: training Start:', time.time())
#
#
# i = i + 1
if __name__ == "__main__":
t1 = Thread( target=dequeue )
t1.start()
main()
| {
"content_hash": "fea2938b7081447ec5b4349e435ebca6",
"timestamp": "",
"source": "github",
"line_count": 322,
"max_line_length": 172,
"avg_line_length": 44.661490683229815,
"alnum_prop": 0.5932132675057368,
"repo_name": "mlperf/training_results_v0.7",
"id": "90b3961b771415d2eedf25e81153a307ef10c851",
"size": "14381",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SIAT/benchmarks/resnet/implementations/tensorflow_open_src/main.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "1731"
},
{
"name": "Awk",
"bytes": "14530"
},
{
"name": "Batchfile",
"bytes": "13130"
},
{
"name": "C",
"bytes": "172914"
},
{
"name": "C++",
"bytes": "13037795"
},
{
"name": "CMake",
"bytes": "113458"
},
{
"name": "CSS",
"bytes": "70255"
},
{
"name": "Clojure",
"bytes": "622652"
},
{
"name": "Cuda",
"bytes": "1974745"
},
{
"name": "Dockerfile",
"bytes": "149523"
},
{
"name": "Groovy",
"bytes": "160449"
},
{
"name": "HTML",
"bytes": "171537"
},
{
"name": "Java",
"bytes": "189275"
},
{
"name": "JavaScript",
"bytes": "98224"
},
{
"name": "Julia",
"bytes": "430755"
},
{
"name": "Jupyter Notebook",
"bytes": "11091342"
},
{
"name": "Lua",
"bytes": "17720"
},
{
"name": "MATLAB",
"bytes": "34903"
},
{
"name": "Makefile",
"bytes": "215967"
},
{
"name": "Perl",
"bytes": "1551186"
},
{
"name": "PowerShell",
"bytes": "13906"
},
{
"name": "Python",
"bytes": "36943114"
},
{
"name": "R",
"bytes": "134921"
},
{
"name": "Raku",
"bytes": "7280"
},
{
"name": "Ruby",
"bytes": "4930"
},
{
"name": "SWIG",
"bytes": "140111"
},
{
"name": "Scala",
"bytes": "1304960"
},
{
"name": "Shell",
"bytes": "1312832"
},
{
"name": "Smalltalk",
"bytes": "3497"
},
{
"name": "Starlark",
"bytes": "69877"
},
{
"name": "TypeScript",
"bytes": "243012"
}
],
"symlink_target": ""
} |
"""Convert a rectangular file to a JSON file ready for mongoimport
Usage:
./rectangular_file_to_json.py data.tab [data_set_id] > output.mongoexport
"""
# pip install bson
from bson.objectid import ObjectId
import json
import sys
def main():
argv = sys.argv
if len(argv) == 3:
firstLine = True
sampleLabels = []
dataSetId = argv[2]
with open(argv[1]) as f:
for line in f:
cells = line.split("\t");
if firstLine:
sampleLabels = cells[1:]
firstLine = False
else:
geneExpressionDoc = {}
geneExpressionDoc["_id"] = str(ObjectId())
geneExpressionDoc["data_set_id"] = dataSetId
geneExpressionDoc["feature_label"] = cells[0]
geneExpressionDoc["values"] = [float(num) for num in cells[1:]]
print(str(geneExpressionDoc))
# magical incantation to import into mongodb
# batchSize makes sure each bulk operation is smaller than 16mb
sys.stderr.write("Use this command to imoprt into mongo:\n")
sys.stderr.write("mongoimport --db MedBook --collection genomic_expression --file OUTPUTFILE.mongoexport --batchSize 50\n")
sys.stderr.write("\nUse this command to get the sample labels:\n")
sys.stderr.write("./get_data_set_sample_labels data.tab | pbcopy\n")
sys.stderr.write("\nUse this command to get the gene_expression_genes:\n")
sys.stderr.write("./get_data_set_genes data.tab | pbcopy\n")
sys.exit(0)
print __doc__
if __name__ == "__main__":
main()
| {
"content_hash": "70fc3f3fdc90411cf54198e4b67ec101",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 131,
"avg_line_length": 31.90566037735849,
"alnum_prop": 0.5807214665878179,
"repo_name": "UCSC-MedBook/MedBook_",
"id": "c3e249f84f2d3aa57928e5825dd8375327fd0f22",
"size": "1715",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/old-external-tools/importers/rectangular_file_to_json.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "9767"
},
{
"name": "HTML",
"bytes": "171802"
},
{
"name": "Java",
"bytes": "846"
},
{
"name": "JavaScript",
"bytes": "1483680"
},
{
"name": "Python",
"bytes": "11603"
},
{
"name": "R",
"bytes": "7872"
},
{
"name": "Shell",
"bytes": "31978"
}
],
"symlink_target": ""
} |
from botocore.client import ClientError
from collections import Counter
from concurrent.futures import as_completed
from datetime import datetime, timedelta
from dateutil.parser import parse
from dateutil.tz import tzutc
import logging
import itertools
import time
from c7n.actions import ActionRegistry, BaseAction, AutoTagUser
from c7n.filters import (
FilterRegistry, ValueFilter, AgeFilter, Filter, FilterValidationError,
OPERATORS)
from c7n.manager import resources
from c7n.query import QueryResourceManager
from c7n.offhours import Time, OffHour, OnHour
from c7n.tags import TagActionFilter, DEFAULT_TAG, TagCountFilter, TagTrim
from c7n.utils import local_session, query_instances, type_schema, chunks
log = logging.getLogger('custodian.asg')
filters = FilterRegistry('asg.filters')
actions = ActionRegistry('asg.actions')
filters.register('time', Time)
filters.register('offhour', OffHour)
filters.register('onhour', OnHour)
filters.register('tag-count', TagCountFilter)
filters.register('marked-for-op', TagActionFilter)
actions.register('auto-tag-user', AutoTagUser)
@resources.register('asg')
class ASG(QueryResourceManager):
resource_type = "aws.autoscaling.autoScalingGroup"
filter_registry = filters
action_registry = actions
class LaunchConfigFilterBase(object):
"""Mixin base class for querying asg launch configs."""
def initialize(self, asgs):
"""Get launch configs for the set of asgs"""
config_names = set()
skip = []
for a in asgs:
# Per https://github.com/capitalone/cloud-custodian/issues/143
if 'LaunchConfigurationName' not in a:
skip.append(a)
continue
config_names.add(a['LaunchConfigurationName'])
for a in skip:
asgs.remove(a)
session = local_session(self.manager.session_factory)
client = session.client('autoscaling')
self.configs = {}
self.log.debug(
"Querying launch configs for filter %s",
self.__class__.__name__)
config_manager = LaunchConfig(self.manager.ctx, {})
if len(asgs) < 20:
configs = config_manager.get_resources(
[asg['LaunchConfigurationName'] for asg in asgs])
else:
configs = config_manager.resources()
self.configs = {
cfg['LaunchConfigurationName']: cfg for cfg in configs}
@filters.register('launch-config')
class LaunchConfigFilter(ValueFilter, LaunchConfigFilterBase):
"""Filter asg by launch config attributes."""
schema = type_schema(
'launch-config', rinherit=ValueFilter.schema)
config = None
def process(self, asgs, event=None):
self.initialize(asgs)
return super(LaunchConfigFilter, self).process(asgs, event)
def __call__(self, asg):
# Active launch configs can be deleted..
cfg = self.configs.get(asg['LaunchConfigurationName'])
return self.match(cfg)
@filters.register('invalid')
class InvalidConfigFilter(Filter, LaunchConfigFilterBase):
"""Filter autoscale groups to find those that are structurally invalid.
Structurally invalid means that the auto scale group will not be able
to launch an instance succesfully as the configuration has
- invalid subnets
- invalid security groups
- invalid key pair name
- invalid launch config volume snapshots
- invalid amis
- invalid health check elb (slower)
Internally this tries to reuse other resource managers for better
cache utilization.
"""
schema = type_schema('invalid')
def validate(self):
if self.manager.data.get('mode'):
raise FilterValidationError(
"invalid-config makes too many queries to be run efficiently in lambda")
return self
def initialize(self, asgs):
super(InvalidConfigFilter, self).initialize(asgs)
self.subnets = self.get_subnets()
self.security_groups = self.get_security_groups()
self.key_pairs = self.get_key_pairs()
self.elbs = self.get_elbs()
self.images = self.get_images()
self.snapshots = self.get_snapshots()
def get_subnets(self):
from c7n.resources.vpc import Subnet
manager = Subnet(self.manager.ctx, {})
return set([s['SubnetId'] for s in manager.resources()])
def get_security_groups(self):
from c7n.resources.vpc import SecurityGroup
manager = SecurityGroup(self.manager.ctx, {})
return set([s['GroupId'] for s in manager.resources()])
def get_key_pairs(self):
from c7n.resources.vpc import KeyPair
manager = KeyPair(self.manager.ctx, {})
return set([k['KeyName'] for k in manager.resources()])
def get_elbs(self):
from c7n.resources.elb import ELB
manager = ELB(self.manager.ctx, {})
return set([e['LoadBalancerName'] for e in manager.resources()])
def get_images(self):
from c7n.resources.ami import AMI
manager = AMI(self.manager.ctx, {})
return set([i['ImageId'] for i in manager.resources()])
def get_snapshots(self):
from c7n.resources.ebs import Snapshot
manager = Snapshot(self.manager.ctx, {})
return set([s['SnapshotId'] for s in manager.resources()])
def process(self, asgs, event=None):
self.initialize(asgs)
return super(InvalidConfigFilter, self).process(asgs, event)
def __call__(self, asg):
errors = []
subnets = asg.get('VPCZoneIdentifier', '').split(',')
for s in subnets:
if not s in self.subnets:
errors.append(('invalid-subnet', s))
for elb in asg['LoadBalancerNames']:
if elb not in self.elbs:
errors.append(('invalid-elb', elb))
cfg_id = asg.get(
'LaunchConfigurationName', asg['AutoScalingGroupName'])
cfg = self.configs.get(cfg_id)
if cfg is None:
errors.append(('invalid-config', cfg_id))
self.log.debug(
"asg:%s no launch config found" % asg['AutoScalingGroupName'])
asg['Invalid'] = errors
return True
for sg in cfg['SecurityGroups']:
if sg not in self.security_groups:
errors.append(('invalid-security-group', sg))
if cfg['KeyName'] and cfg['KeyName'] not in self.key_pairs:
errors.append(('invalid-key-pair', cfg['KeyName']))
if cfg['ImageId'] not in self.images:
errors.append(('invalid-image', cfg['ImageId']))
for bd in cfg['BlockDeviceMappings']:
if 'SnapshotId' not in bd:
continue
if bd['SnapshotId'] not in self.snapshots:
errors.append(('invalid-snapshot', cfg['SnapshotId']))
if errors:
asg['Invalid'] = errors
return True
@filters.register('not-encrypted')
class NotEncryptedFilter(Filter, LaunchConfigFilterBase):
"""Check if an asg is configured to have unencrypted volumes.
Checks both the ami snapshots and the launch configuration.
"""
schema = type_schema('encrypted', exclude_image={'type': 'boolean'})
images = unencrypted_configs = unencrypted_images = None
def process(self, asgs, event=None):
self.initialize(asgs)
return super(NotEncryptedFilter, self).process(asgs, event)
def __call__(self, asg):
cfg = self.configs.get(asg['LaunchConfigurationName'])
if not cfg:
self.log.warning(
"ASG %s instances: %d has missing config: %s",
asg['AutoScalingGroupName'], len(asg['Instances']),
asg['LaunchConfigurationName'])
return False
unencrypted = []
if (not self.data.get('exclude_image')
and cfg['ImageId'] in self.unencrypted_images):
unencrypted.append('Image')
if cfg['LaunchConfigurationName'] in self.unencrypted_configs:
unencrypted.append('LaunchConfig')
if unencrypted:
asg['Unencrypted'] = unencrypted
return bool(unencrypted)
def initialize(self, asgs):
super(NotEncryptedFilter, self).initialize(asgs)
ec2 = local_session(self.manager.session_factory).client('ec2')
self.unencrypted_images = self.get_unencrypted_images(ec2)
self.unencrypted_configs = self.get_unencrypted_configs(ec2)
def _fetch_images(self, ec2, image_ids):
while True:
try:
return ec2.describe_images(ImageIds=list(image_ids))
except ClientError as e:
if e.response['Error']['Code'] == 'InvalidAMIID.NotFound':
msg = e.response['Error']['Message']
e_ami_ids = [
e_ami_id.strip() for e_ami_id
in msg[msg.find("'[")+2:msg.rfind("]'")].split(',')]
self.log.warning(
"asg:not-encrypted filter image not found %s",
e_ami_ids)
for e_ami_id in e_ami_ids:
image_ids.remove(e_ami_id)
continue
raise
def get_unencrypted_images(self, ec2):
"""retrieve images which have unencrypted snapshots referenced."""
image_ids = set()
for cfg in self.configs.values():
image_ids.add(cfg['ImageId'])
self.log.debug("querying %d images", len(image_ids))
results = self._fetch_images(ec2, image_ids)
self.images = {i['ImageId']: i for i in results['Images']}
unencrypted_images = set()
for i in self.images.values():
for bd in i['BlockDeviceMappings']:
if 'Ebs' in bd and not bd['Ebs'].get('Encrypted'):
unencrypted_images.add(i['ImageId'])
break
return unencrypted_images
def get_unencrypted_configs(self, ec2):
"""retrieve configs that have unencrypted ebs voluems referenced."""
unencrypted_configs = set()
snaps = {}
for cid, c in self.configs.items():
image = self.images.get(c['ImageId'])
# image deregistered/unavailable
if image is not None:
image_block_devs = {
bd['DeviceName']: bd['Ebs']
for bd in image['BlockDeviceMappings'] if 'Ebs' in bd}
else:
image_block_devs = {}
for bd in c['BlockDeviceMappings']:
if 'Ebs' not in bd:
continue
# Launch configs can shadow image devices, images have
# precedence.
if bd['DeviceName'] in image_block_devs:
continue
if 'SnapshotId' in bd['Ebs']:
snaps.setdefault(
bd['Ebs']['SnapshotId'].strip(), []).append(cid)
elif not bd['Ebs'].get('Encrypted'):
unencrypted_configs.add(cid)
if not snaps:
return unencrypted_configs
self.log.debug("querying %d snapshots", len(snaps))
for s in self.get_snapshots(ec2, snaps.keys()):
if not s.get('Encrypted'):
unencrypted_configs.update(snaps[s['SnapshotId']])
return unencrypted_configs
def get_snapshots(self, ec2, snap_ids):
"""get snapshots corresponding to id, but tolerant of missing."""
while True:
try:
result = ec2.describe_snapshots(SnapshotIds=snap_ids)
except ClientError as e:
if e.response['Error']['Code'] == 'InvalidSnapshot.NotFound':
msg = e.response['Error']['Message']
e_snap_id = msg[msg.find("'")+1:msg.rfind("'")]
self.log.warning("Snapshot not found %s" % e_snap_id)
snap_ids.remove(e_snap_id)
continue
raise
else:
return result.get('Snapshots', ())
@filters.register('image-age')
class ImageAgeFilter(AgeFilter, LaunchConfigFilterBase):
"""Filter asg by image age."""
date_attribute = "CreationDate"
schema = type_schema(
'image-age',
op={'type': 'string', 'enum': OPERATORS.keys()},
days={'type': 'number'})
def process(self, asgs, event=None):
self.initialize(asgs)
return super(ImageAgeFilter, self).process(asgs, event)
def initialize(self, asgs):
super(ImageAgeFilter, self).initialize(asgs)
image_ids = set()
for cfg in self.configs.values():
image_ids.add(cfg['ImageId'])
ec2 = local_session(self.manager.session_factory).client('ec2')
results = ec2.describe_images(ImageIds=list(image_ids))
self.images = {i['ImageId']: i for i in results['Images']}
def get_resource_date(self, i):
cfg = self.configs[i['LaunchConfigurationName']]
ami = self.images[cfg['ImageId']]
return parse(ami[self.date_attribute])
@filters.register('vpc-id')
class VpcIdFilter(ValueFilter):
schema = type_schema(
'vpc-id', rinherit=ValueFilter.schema)
schema['properties'].pop('key')
def __init__(self, data, manager=None):
super(VpcIdFilter, self).__init__(data, manager)
self.data['key'] = 'VpcId'
def process(self, asgs, event=None):
subnets = {}
for a in asgs:
subnet_ids = a.get('VPCZoneIdentifier', '')
if not subnet_ids:
continue
subnets.setdefault(subnet_ids.split(',')[0], []).append(a)
session = local_session(self.manager.session_factory)
ec2 = session.client('ec2')
# Invalid subnets on asgs happen, so query all
all_subnets = {s['SubnetId']: s for s in ec2.describe_subnets()[
'Subnets']}
for s, s_asgs in subnets.items():
if s not in all_subnets:
self.log.warning(
"invalid subnet %s for asgs: %s",
s, [a['AutoScalingGroupName'] for a in s_asgs])
continue
for a in s_asgs:
a['VpcId'] = all_subnets[s]['VpcId']
return super(VpcIdFilter, self).process(asgs)
@actions.register('tag-trim')
class GroupTagTrim(TagTrim):
def process_tag_removal(self, resource, candidates):
client = local_session(
self.manager.session_factory).client('autoscaling')
tags = []
for t in candidates:
tags.append(
dict(Key=t, ResourceType='auto-scaling-group',
ResourceId=resource['AutoScalingGroupName']))
client.delete_tags(Tags=tags)
@actions.register('remove-tag')
@actions.register('untag')
@actions.register('unmark')
class RemoveTag(BaseAction):
schema = type_schema(
'remove-tag',
aliases=('untag', 'unmark'),
key={'type': 'string'})
batch_size = 1
def process(self, asgs):
error = False
key = self.data.get('key', DEFAULT_TAG)
with self.executor_factory(max_workers=3) as w:
futures = {}
for asg_set in chunks(asgs, self.batch_size):
futures[w.submit(self.process_asg_set, asg_set, key)] = asg_set
for f in as_completed(futures):
asg_set = futures[f]
if f.exception():
error = f.exception()
self.log.exception(
"Exception untagging asg:%s tag:%s error:%s" % (
", ".join([a['AutoScalingGroupName']
for a in asg_set]),
self.data.get('key', DEFAULT_TAG),
f.exception()))
if error:
raise error
# retry on error code - ResourceInUse
def process_asg_set(self, asgs, key):
session = local_session(self.manager.session_factory)
client = session.client('autoscaling')
tags= [dict(Key=key, ResourceType='auto-scaling-group',
ResourceId=a['AutoScalingGroupName']) for a in asgs]
client.delete_tags(Tags=tags)
@actions.register('tag')
@actions.register('mark')
class Tag(BaseAction):
schema = type_schema(
'tag',
key={'type': 'string'},
value={'type': 'string'},
# Backwards compatibility
tag={'type': 'string'},
msg={'type': 'string'},
propagate={'type': 'boolean'})
batch_size = 1
def process(self, asgs):
error = False
key = self.data.get('key', self.data.get('tag', DEFAULT_TAG))
value = self.data.get(
'value', self.data.get(
'msg', 'AutoScaleGroup does not meet policy guidelines'))
return self.tag(asgs, key, value)
def tag(self, asgs, key, value):
error = None
with self.executor_factory(max_workers=3) as w:
futures = {}
for asg_set in chunks(asgs, self.batch_size):
futures[w.submit(
self.process_asg_set, asg_set, key, value)] = asg_set
for f in as_completed(futures):
asg_set = futures[f]
if f.exception():
error = f.exception()
self.log.exception(
"Exception untagging tag:%s error:%s asg:%s" % (
self.data.get('key', DEFAULT_TAG),
f.exception(),
", ".join([a['AutoScalingGroupName']
for a in asg_set])))
if error:
raise error
def process_asg_set(self, asgs, key, value):
session = local_session(self.manager.session_factory)
client = session.client('autoscaling')
propagate = self.data.get('propagate_launch', True)
tags= [dict(Key=key, ResourceType='auto-scaling-group', Value=value,
PropagateAtLaunch=propagate,
ResourceId=a['AutoScalingGroupName']) for a in asgs]
client.create_or_update_tags(Tags=tags)
@actions.register('propagate-tags')
class PropagateTags(BaseAction):
"""Propagate tags to an asg instances.
In AWS changing an asg tag does not propagate to instances.
This action exists to do that, and can also trim older tags
not present on the asg anymore that are present on instances.
"""
schema = type_schema(
'propagate-tags',
tags={'type': 'array', 'items': {'type': 'string'}},
trim={'type': 'boolean'})
def validate(self):
if not isinstance(self.data.get('tags', []), (list, tuple)):
raise ValueError("No tags specified")
return self
def process(self, asgs):
if not asgs:
return
if self.data.get('trim', False):
self.instance_map = self.get_instance_map(asgs)
with self.executor_factory(max_workers=10) as w:
instance_count = sum(list(w.map(self.process_asg, asgs)))
self.log.info("Applied tags to %d instances" % instance_count)
def process_asg(self, asg):
client = local_session(self.manager.session_factory).client('ec2')
instance_ids = [i['InstanceId'] for i in asg['Instances']]
tag_map = {t['Key']: t['Value'] for t in asg.get('Tags', [])
if t['PropagateAtLaunch']
and not t['Key'].startswith('aws:')}
if self.data.get('tags'):
tag_map = {
k: v for k, v in tag_map.items()
if k in self.data['tags']}
tag_set = set(tag_map)
if self.data.get('trim', False):
instances = [self.instance_map[i] for i in instance_ids]
self.prune_instance_tags(client, asg, tag_set, instances)
if not self.manager.config.dryrun:
client.create_tags(
Resources=instance_ids,
Tags=[{'Key': k, 'Value': v} for k, v in tag_map.items()])
return len(instance_ids)
def prune_instance_tags(self, client, asg, tag_set, instances):
"""Remove tags present on all asg instances which are not present
on the asg.
"""
instance_tags = Counter()
instance_count = len(instances)
remove_tags = []
extra_tags = []
for i in instances:
instance_tags.update([
t['Key'] for t in i['Tags']
if not t['Key'].startswith('aws:')])
for k, v in instance_tags.items():
if not v >= instance_count:
extra_tags.append(k)
continue
if k not in tag_set:
remove_tags.append(k)
if remove_tags:
log.debug("Pruning asg:%s instances:%d of old tags: %s" % (
asg['AutoScalingGroupName'], instance_count, remove_tags))
if extra_tags:
log.debug("Asg: %s has uneven tags population: %s" % (
asg['AutoScalingGroupName'], instance_tags))
# Remove orphan tags
remove_tags.extend(extra_tags)
if not self.manager.config.dryrun:
client.delete_tags(
Resources=[i['InstanceId'] for i in instances],
Tags=[{'Key': t} for t in remove_tags])
def get_instance_map(self, asgs):
instance_ids = [
i['InstanceId'] for i in
list(itertools.chain(*[
g['Instances']
for g in asgs if g['Instances']]))]
if not instance_ids:
return {}
instances = query_instances(
local_session(self.manager.session_factory),
InstanceIds=instance_ids)
return {i['InstanceId']: i for i in instances}
@actions.register('rename-tag')
class RenameTag(BaseAction):
"""Rename a tag on an AutoScaleGroup.
"""
schema = type_schema(
'rename-tag', required=['source', 'dest'],
propagate={'type': 'boolean'},
source={'type': 'string'},
dest={'type': 'string'})
def process(self, asgs):
source = self.data.get('source')
dest = self.data.get('dest')
count = len(asgs)
filtered = []
for a in asgs:
for t in a.get('Tags'):
if t['Key'] == source:
filtered.append(a)
break
asgs = filtered
self.log.info("Filtered from %d asgs to %d" % (
count, len(asgs)))
self.log.info("Renaming %s to %s on %d asgs" % (
source, dest, len(filtered)))
with self.executor_factory(max_workers=3) as w:
list(w.map(self.process_asg, asgs))
def process_asg(self, asg):
"""Move source tag to destination tag.
Check tag count on asg
Create new tag tag
Delete old tag
Check tag count on instance
Create new tag
Delete old tag
"""
source_tag = self.data.get('source')
tag_map = {t['Key']: t for t in asg.get('Tags', [])}
source = tag_map[source_tag]
destination_tag = self.data.get('dest')
propagate = self.data.get('propagate', True)
client = local_session(
self.manager.session_factory).client('autoscaling')
# technically safer to create first, but running into
# max tags constraints, otherwise.
#
# delete_first = len([t for t in tag_map if not t.startswith('aws:')])
client.delete_tags(Tags=[
{'ResourceId': asg['AutoScalingGroupName'],
'ResourceType': 'auto-scaling-group',
'Key': source_tag,
'Value': source['Value']}])
client.create_or_update_tags(Tags=[
{'ResourceId': asg['AutoScalingGroupName'],
'ResourceType': 'auto-scaling-group',
'PropagateAtLaunch': propagate,
'Key': destination_tag,
'Value': source['Value']}])
self.propogate_instance_tag(source, destination_tag, asg)
def propogate_instance_tag(self, source, destination_tag, asg):
client = local_session(self.manager.session_factory).client('ec2')
client.delete_tags(
Resources=[i['InstanceId'] for i in asg['Instances']],
Tags=[{"Key": source['Key']}])
client.create_tags(
Resources=[i['InstanceId'] for i in asg['Instances']],
Tags=[{'Key': source['Key'], 'Value': source['Value']}])
@actions.register('mark-for-op')
class MarkForOp(Tag):
schema = type_schema(
'mark-for-op',
op={'enum': ['suspend', 'resume', 'delete']},
key={'type': 'string'},
tag={'type': 'string'},
message={'type': 'string'},
days={'type': 'number', 'minimum': 0})
default_template = (
'AutoScaleGroup does not meet org policy: {op}@{action_date}')
def process(self, asgs):
msg_tmpl = self.data.get('message', self.default_template)
key = self.data.get('key', self.data.get('tag', DEFAULT_TAG))
op = self.data.get('op', 'suspend')
date = self.data.get('days', 4)
n = datetime.now(tz=tzutc())
stop_date = n + timedelta(days=date)
try:
msg = msg_tmpl.format(
op=op, action_date=stop_date.strftime('%Y/%m/%d'))
except Exception:
self.log.warning("invalid template %s" % msg_tmpl)
msg = self.default_template.format(
op=op, action_date=stop_date.strftime('%Y/%m/%d'))
self.log.info("Tagging %d asgs for %s on %s" % (
len(asgs), op, stop_date.strftime('%Y/%m/%d')))
self.tag(asgs, key, msg)
@actions.register('suspend')
class Suspend(BaseAction):
schema = type_schema('suspend')
def process(self, asgs):
original_count = len(asgs)
asgs = [a for a in asgs if a['Instances']]
self.log.debug("Filtered from %d to %d asgs with instances" % (
original_count, len(asgs)))
with self.executor_factory(max_workers=3) as w:
list(w.map(self.process_asg, asgs))
def process_asg(self, asg):
"""Multistep process to stop an asg aprori of setup
- suspend processes
- stop instances
"""
session = local_session(self.manager.session_factory)
asg_client = session.client('autoscaling')
asg_client.suspend_processes(
AutoScalingGroupName=asg['AutoScalingGroupName'])
ec2_client = session.client('ec2')
try:
instance_ids = [i['InstanceId'] for i in asg['Instances']]
if not instance_ids:
return
ec2_client.stop_instances(
InstanceIds=instance_ids)
except ClientError as e:
if e.response['Error']['Code'] in (
'InvalidInstanceID.NotFound',
'IncorrectInstanceState'):
log.warning("Erroring stopping asg instances %s %s" % (
asg['AutoScalingGroupName'], e))
return
raise
@actions.register('resume')
class Resume(BaseAction):
"""Resume a suspended autoscale group and its instances
"""
schema = type_schema('resume', delay={'type': 'integer'})
def process(self, asgs):
original_count = len(asgs)
asgs = [a for a in asgs if a['SuspendedProcesses']]
self.delay = self.data.get('delay', 30)
self.log.debug("Filtered from %d to %d suspended asgs" % (
original_count, len(asgs)))
with self.executor_factory(max_workers=3) as w:
futures = {}
for a in asgs:
futures[w.submit(self.resume_asg_instances, a)] = a
for f in as_completed(futures):
if f.exception():
log.error("Traceback resume asg:%s instances error:%s" % (
futures[f]['AutoScalingGroupName'],
f.exception()))
continue
log.debug("Sleeping for asg health check grace")
time.sleep(self.delay)
with self.executor_factory(max_workers=3) as w:
futures = {}
for a in asgs:
futures[w.submit(self.resume_asg, a)] = a
for f in as_completed(futures):
if f.exception():
log.error("Traceback resume asg:%s error:%s" % (
futures[f]['AutoScalingGroupName'],
f.exception()))
def resume_asg_instances(self, asg):
"""Resume asg instances.
"""
session = local_session(self.manager.session_factory)
ec2_client = session.client('ec2')
instance_ids = [i['InstanceId'] for i in asg['Instances']]
if not instance_ids:
return
ec2_client.start_instances(InstanceIds=instance_ids)
def resume_asg(self, asg):
"""Resume asg processes.
"""
session = local_session(self.manager.session_factory)
asg_client = session.client('autoscaling')
asg_client.resume_processes(
AutoScalingGroupName=asg['AutoScalingGroupName'])
@actions.register('delete')
class Delete(BaseAction):
schema = type_schema('delete', force={'type': 'boolean'})
def process(self, asgs):
with self.executor_factory(max_workers=5) as w:
list(w.map(self.process_asg, asgs))
def process_asg(self, asg):
force_delete = self.data.get('force', False)
if force_delete:
log.info('Forcing deletion of Auto Scaling group %s' % (
asg['AutoScalingGroupName']))
session = local_session(self.manager.session_factory)
asg_client = session.client('autoscaling')
try:
asg_client.delete_auto_scaling_group(
AutoScalingGroupName=asg['AutoScalingGroupName'],
ForceDelete=force_delete)
except ClientError as e:
if e.response['Error']['Code'] == 'ValidationError':
log.warning("Erroring deleting asg %s %s" % (
asg['AutoScalingGroupName'], e))
return
raise
@resources.register('launch-config')
class LaunchConfig(QueryResourceManager):
resource_type = "aws.autoscaling.launchConfigurationName"
def augment(self, resources):
for r in resources:
r.pop('UserData', None)
return resources
@LaunchConfig.filter_registry.register('age')
class LaunchConfigAge(AgeFilter):
date_attribute = "CreatedTime"
schema = type_schema(
'age',
op={'type': 'string', 'enum': OPERATORS.keys()},
days={'type': 'number'})
@LaunchConfig.filter_registry.register('unused')
class UnusedLaunchConfig(Filter):
schema = type_schema('unused')
def process(self, configs, event=None):
asgs = self.manager._cache.get(
{'region': self.manager.config.region,
'resource': 'asg'})
if asgs is None:
self.log.debug(
"Querying asgs to determine unused launch configs")
asg_manager = ASG(self.manager.ctx, {})
asgs = asg_manager.resources()
self.used = set([
a.get('LaunchConfigurationName', a['AutoScalingGroupName'])
for a in asgs])
return super(UnusedLaunchConfig, self).process(configs)
def __call__(self, config):
return config['LaunchConfigurationName'] not in self.used
@LaunchConfig.action_registry.register('delete')
class LaunchConfigDelete(BaseAction):
schema = type_schema('delete')
def process(self, configs):
with self.executor_factory(max_workers=2) as w:
list(w.map(self.process_config, configs))
def process_config(self, config):
session = local_session(self.manager.session_factory)
client = session.client('autoscaling')
try:
client.delete_launch_configuration(
LaunchConfigurationName=config[
'LaunchConfigurationName'])
except ClientError as e:
# Catch already deleted
if e.response['Error']['Code'] == 'ValidationError':
return
| {
"content_hash": "ae1f370cac44df2c16e365bb33b95e38",
"timestamp": "",
"source": "github",
"line_count": 909,
"max_line_length": 88,
"avg_line_length": 35.66776677667767,
"alnum_prop": 0.5724508050089445,
"repo_name": "gwh59/cloud-custodian",
"id": "8e59c0a6ffb558cd35d35ce66c9cb825643b4645",
"size": "33007",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "c7n/resources/asg.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "1122"
},
{
"name": "Python",
"bytes": "610848"
}
],
"symlink_target": ""
} |
from mock import *
from gp_unittest import *
from gpconfig_modules.compare_segment_guc import MultiValueGuc
from gpconfig_modules.database_segment_guc import DatabaseSegmentGuc
from gpconfig_modules.file_segment_guc import FileSegmentGuc
class CompareSegmentGucTest(GpTestCase):
def setUp(self):
row = ['contentid', 'guc_name', 'file_value', "dbid"]
self.file_seg_guc = FileSegmentGuc(row)
row = ['contentid', 'guc_name', 'sql_value']
self.db_seg_guc = DatabaseSegmentGuc(row)
self.subject = MultiValueGuc(self.file_seg_guc, self.db_seg_guc)
def test_init_when_comparison_guc_supplied(self):
row = ['contentid', 'guc_name', 'file_value', "diff_dbid"]
file_seg_guc = FileSegmentGuc(row)
old = self.subject
self.subject = MultiValueGuc(self.subject, file_seg_guc)
self.assertEquals(self.subject.db_seg_guc, old.db_seg_guc)
self.assertEquals(self.subject.primary_file_seg_guc, old.primary_file_seg_guc)
self.assertEquals(self.subject.mirror_file_seg_guc, file_seg_guc)
def test_init_with_wrong_content_id_raises(self):
row = ['contentid', 'guc_name', 'file_value', "dbid"]
file_seg_guc = FileSegmentGuc(row)
row = ['different', 'guc_name', 'sql_value']
db_seg_guc = DatabaseSegmentGuc(row)
with self.assertRaisesRegexp(Exception, "Not the same context"):
MultiValueGuc(file_seg_guc, db_seg_guc)
def test_init_handles_both_orders(self):
self.assertEquals(self.file_seg_guc, self.subject.primary_file_seg_guc)
self.assertEquals(self.db_seg_guc, self.subject.db_seg_guc)
self.assertTrue(isinstance(self.subject.primary_file_seg_guc, FileSegmentGuc))
self.assertTrue(isinstance(self.subject.db_seg_guc, DatabaseSegmentGuc))
self.subject = MultiValueGuc(self.db_seg_guc, self.file_seg_guc)
self.assertEquals(self.file_seg_guc, self.subject.primary_file_seg_guc)
self.assertEquals(self.db_seg_guc, self.subject.db_seg_guc)
self.assertTrue(isinstance(self.subject.primary_file_seg_guc, FileSegmentGuc))
self.assertTrue(isinstance(self.subject.db_seg_guc, DatabaseSegmentGuc))
def test_init_when_none_raises(self):
with self.assertRaisesRegexp(Exception, "comparison requires two gucs"):
self.subject = MultiValueGuc(self.db_seg_guc, None)
with self.assertRaisesRegexp(Exception, "comparison requires two gucs"):
self.subject = MultiValueGuc(None, self.db_seg_guc)
def test_report_fail_format_for_database_and_file_gucs(self):
self.assertEquals(self.subject.report_fail_format(),
["[context: contentid] [dbid: dbid] [name: guc_name] [value: sql_value | file: file_value]"])
def test_report_fail_format_file_segment_guc_only(self):
self.subject.db_seg_guc = None
row = ['contentid', 'guc_name', 'primary_value', "dbid1"]
self.subject.set_primary_file_segment(FileSegmentGuc(row))
row = ['contentid', 'guc_name', 'mirror_value', "dbid2"]
self.subject.set_mirror_file_segment(FileSegmentGuc(row))
self.assertEquals(self.subject.report_fail_format(),
["[context: contentid] [dbid: dbid1] [name: guc_name] [value: primary_value]",
"[context: contentid] [dbid: dbid2] [name: guc_name] [value: mirror_value]"])
def test_when_segment_report_success_format(self):
self.assertEquals(self.subject.report_success_format(),
"Segment value: sql_value | file: file_value")
def test_when_values_match_report_success_format_file_compare(self):
self.subject.db_seg_guc.value = 'value'
self.subject.primary_file_seg_guc.value = 'value'
self.assertEquals(self.subject.report_success_format(), "Segment value: value | file: value")
def test_is_internally_consistent_fails(self):
self.assertEquals(self.subject.is_internally_consistent(), False)
def test_is_internally_consistent_when_file_value_is_none_succeeds(self):
self.file_seg_guc.value = None
self.assertEquals(self.subject.is_internally_consistent(), True)
def test_is_internally_consistent_when_primary_is_same_succeeds(self):
self.subject.primary_file_seg_guc.value = "sql_value"
self.assertEquals(self.subject.is_internally_consistent(), True)
def test_is_internally_consistent_when_mirror_is_different_fails(self):
self.subject.primary_file_seg_guc.value = "sql_value"
row = ['contentid', 'guc_name', 'diffvalue', "dbid1"]
self.subject.set_mirror_file_segment(FileSegmentGuc(row))
self.assertEquals(self.subject.is_internally_consistent(), False)
def test_is_internally_consistent_with_quotes_and_escaping(self):
cases = [
{'file_value': "'value'", 'db_value': 'value'},
{'file_value': "''", 'db_value': ''},
{'file_value': "'\\n\\r\\b\\f\\t'", 'db_value': '\n\r\b\f\t'},
{'file_value': "'\\0\\1\\2\\3\\4\\5\\6\\7'", 'db_value': '\0\1\2\3\4\5\6\7'},
{'file_value': "'\\8'", 'db_value': '8'},
{'file_value': "'\\01\\001\\377\\777\\7777'", 'db_value': '\x01\x01\xFF\xFF\xFF7'},
]
for case in cases:
file_seg_guc = FileSegmentGuc(['contentid', 'guc_name', case['file_value'], "dbid"])
db_seg_guc = DatabaseSegmentGuc(['contentid', 'guc_name', case['db_value']])
subject = MultiValueGuc(file_seg_guc, db_seg_guc)
error_message = "expected file value: %r to be equal to db value: %r" % (case['file_value'], case['db_value'])
self.assertEquals(subject.is_internally_consistent(), True, error_message)
def test_is_internally_consistent_when_there_is_no_quoting(self):
cases = [
{'file_value': "value123", 'db_value': 'value123'},
{'file_value': "value-._:/", 'db_value': 'value-._:/'},
]
for case in cases:
file_seg_guc = FileSegmentGuc(['contentid', 'guc_name', case['file_value'], "dbid"])
db_seg_guc = DatabaseSegmentGuc(['contentid', 'guc_name', case['db_value']])
subject = MultiValueGuc(file_seg_guc, db_seg_guc)
error_message = "expected file value: %r to be equal to db value: %r" % (case['file_value'], case['db_value'])
self.assertEquals(subject.is_internally_consistent(), True, error_message)
def test_is_internally_consistent_when_gucs_are_different_returns_false(self):
file_seg_guc = FileSegmentGuc(['contentid', 'guc_name', "'hello", "dbid"])
db_seg_guc = DatabaseSegmentGuc(['contentid', 'guc_name', "hello"])
subject = MultiValueGuc(file_seg_guc, db_seg_guc)
self.assertFalse(subject.is_internally_consistent())
def test__unquote(self):
cases = [
('hello', 'hello'),
("''", ''),
("'hello'", 'hello'),
("'a\\b\\f\\n\\r\\tb'", 'a\b\f\n\r\tb'),
("'\\0\\1\\2\\3\\4\\5\\6\\7\\8\\9'", '\0\1\2\3\4\5\6\789'),
("'\\1\\01\\001\\0001'", '\x01\x01\x01\x001'),
("'\\1a1'", '\x01a1'),
("'\\377\\400\\776\\7777'", '\xFF\x00\xFE\xFF7'),
("''''", "'"),
]
for quoted, unquoted in cases:
self.assertEqual(MultiValueGuc._unquote(quoted), unquoted)
def test__unquote_failure_cases(self):
cases = [
"'hello",
"",
"'",
"'hello\\'",
"'hel'lo'",
"'''",
]
for quoted in cases:
with self.assertRaises(MultiValueGuc.ParseError):
MultiValueGuc._unquote(quoted)
def test_set_file_segment_succeeds(self):
row = ['contentid', 'guc_name', 'file_value', "diff_dbid"]
file_seg_guc = FileSegmentGuc(row)
self.subject.set_mirror_file_segment(file_seg_guc)
self.assertEquals(self.subject.mirror_file_seg_guc, file_seg_guc)
def test_get_value_returns_unique(self):
self.assertEquals(self.subject.get_value(), "sql_value||file_value")
| {
"content_hash": "33cc7913804f90a215174d1546b64692",
"timestamp": "",
"source": "github",
"line_count": 173,
"max_line_length": 122,
"avg_line_length": 47.283236994219656,
"alnum_prop": 0.6135696821515892,
"repo_name": "jmcatamney/gpdb",
"id": "870d56b2976e3dcf240600d2c1585fa5d2fc57b4",
"size": "8180",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "gpMgmt/bin/gppylib/test/unit/test_unit_compare_segment_guc.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "3724"
},
{
"name": "Awk",
"bytes": "836"
},
{
"name": "Batchfile",
"bytes": "12854"
},
{
"name": "C",
"bytes": "42498841"
},
{
"name": "C++",
"bytes": "14366259"
},
{
"name": "CMake",
"bytes": "38452"
},
{
"name": "Csound Score",
"bytes": "223"
},
{
"name": "DTrace",
"bytes": "3873"
},
{
"name": "Dockerfile",
"bytes": "11932"
},
{
"name": "Emacs Lisp",
"bytes": "3488"
},
{
"name": "Fortran",
"bytes": "14863"
},
{
"name": "GDB",
"bytes": "576"
},
{
"name": "Gherkin",
"bytes": "335208"
},
{
"name": "HTML",
"bytes": "53484"
},
{
"name": "JavaScript",
"bytes": "23969"
},
{
"name": "Lex",
"bytes": "229556"
},
{
"name": "M4",
"bytes": "111147"
},
{
"name": "Makefile",
"bytes": "496239"
},
{
"name": "Objective-C",
"bytes": "38376"
},
{
"name": "PLpgSQL",
"bytes": "8009512"
},
{
"name": "Perl",
"bytes": "798767"
},
{
"name": "PowerShell",
"bytes": "422"
},
{
"name": "Python",
"bytes": "3000118"
},
{
"name": "Raku",
"bytes": "698"
},
{
"name": "Roff",
"bytes": "32437"
},
{
"name": "Ruby",
"bytes": "77585"
},
{
"name": "SCSS",
"bytes": "339"
},
{
"name": "Shell",
"bytes": "451713"
},
{
"name": "XS",
"bytes": "6983"
},
{
"name": "Yacc",
"bytes": "674092"
},
{
"name": "sed",
"bytes": "1231"
}
],
"symlink_target": ""
} |
from functools import partial
import zlib
import json
from io import BytesIO
import sys
import platform
from electrum_arg.plugins import BasePlugin, hook
from electrum_arg_gui.qt.util import WaitingDialog, EnterButton, WindowModalDialog
from electrum_arg.util import print_msg, print_error
from electrum_arg.i18n import _
from PyQt4.QtGui import *
from PyQt4.QtCore import *
try:
import amodem.audio
import amodem.main
import amodem.config
print_error('Audio MODEM is available.')
amodem.log.addHandler(amodem.logging.StreamHandler(sys.stderr))
amodem.log.setLevel(amodem.logging.INFO)
except ImportError:
amodem = None
print_error('Audio MODEM is not found.')
class Plugin(BasePlugin):
def __init__(self, parent, config, name):
BasePlugin.__init__(self, parent, config, name)
if self.is_available():
self.modem_config = amodem.config.slowest()
self.library_name = {
'Linux': 'libportaudio.so'
}[platform.system()]
def is_available(self):
return amodem is not None
def requires_settings(self):
return True
def settings_widget(self, window):
return EnterButton(_('Settings'), partial(self.settings_dialog, window))
def settings_dialog(self, window):
d = WindowModalDialog(window, _("Audio Modem Settings"))
layout = QGridLayout(d)
layout.addWidget(QLabel(_('Bit rate [kbps]: ')), 0, 0)
bitrates = list(sorted(amodem.config.bitrates.keys()))
def _index_changed(index):
bitrate = bitrates[index]
self.modem_config = amodem.config.bitrates[bitrate]
combo = QComboBox()
combo.addItems(map(str, bitrates))
combo.currentIndexChanged.connect(_index_changed)
layout.addWidget(combo, 0, 1)
ok_button = QPushButton(_("OK"))
ok_button.clicked.connect(d.accept)
layout.addWidget(ok_button, 1, 1)
return bool(d.exec_())
@hook
def transaction_dialog(self, dialog):
b = QPushButton()
b.setIcon(QIcon(":icons/speaker.png"))
def handler():
blob = json.dumps(dialog.tx.as_dict())
self._send(parent=dialog, blob=blob)
b.clicked.connect(handler)
dialog.sharing_buttons.insert(-1, b)
@hook
def scan_text_edit(self, parent):
parent.addButton(':icons/microphone.png', partial(self._recv, parent),
_("Read from microphone"))
@hook
def show_text_edit(self, parent):
def handler():
blob = str(parent.toPlainText())
self._send(parent=parent, blob=blob)
parent.addButton(':icons/speaker.png', handler, _("Send to speaker"))
def _audio_interface(self):
interface = amodem.audio.Interface(config=self.modem_config)
return interface.load(self.library_name)
def _send(self, parent, blob):
def sender_thread():
with self._audio_interface() as interface:
src = BytesIO(blob)
dst = interface.player()
amodem.main.send(config=self.modem_config, src=src, dst=dst)
print_msg('Sending:', repr(blob))
blob = zlib.compress(blob)
kbps = self.modem_config.modem_bps / 1e3
msg = 'Sending to Audio MODEM ({0:.1f} kbps)...'.format(kbps)
WaitingDialog(parent, msg, sender_thread)
def _recv(self, parent):
def receiver_thread():
with self._audio_interface() as interface:
src = interface.recorder()
dst = BytesIO()
amodem.main.recv(config=self.modem_config, src=src, dst=dst)
return dst.getvalue()
def on_finished(blob):
if blob:
blob = zlib.decompress(blob)
print_msg('Received:', repr(blob))
parent.setText(blob)
kbps = self.modem_config.modem_bps / 1e3
msg = 'Receiving from Audio MODEM ({0:.1f} kbps)...'.format(kbps)
WaitingDialog(parent, msg, receiver_thread, on_finished)
| {
"content_hash": "014caaf744a27491a2b5ebac8d4a624e",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 82,
"avg_line_length": 32.2992125984252,
"alnum_prop": 0.6126279863481229,
"repo_name": "argentumproject/electrum-arg",
"id": "39cbf465d8822186baeaf54860e10fa230762fe8",
"size": "4102",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugins/audio_modem/qt.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "GLSL",
"bytes": "289"
},
{
"name": "HTML",
"bytes": "3869"
},
{
"name": "Makefile",
"bytes": "848"
},
{
"name": "NSIS",
"bytes": "7179"
},
{
"name": "PHP",
"bytes": "404"
},
{
"name": "Python",
"bytes": "1244527"
},
{
"name": "Shell",
"bytes": "7098"
}
],
"symlink_target": ""
} |
from PySide import QtCore, QtGui
class Ui_RunStringDock(object):
def setupUi(self, RunStringDock):
RunStringDock.setObjectName("RunStringDock")
RunStringDock.resize(375, 285)
self.dockWidgetContents = QtGui.QWidget()
self.dockWidgetContents.setObjectName("dockWidgetContents")
self.verticalLayout_2 = QtGui.QVBoxLayout(self.dockWidgetContents)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.textEdit = QtGui.QTextEdit(self.dockWidgetContents)
self.textEdit.setObjectName("textEdit")
self.verticalLayout_2.addWidget(self.textEdit)
self.horizontalWidget = QtGui.QWidget(self.dockWidgetContents)
self.horizontalWidget.setMinimumSize(QtCore.QSize(30, 30))
self.horizontalWidget.setObjectName("horizontalWidget")
self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalWidget)
self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout.setObjectName("horizontalLayout")
self.label = QtGui.QLabel(self.horizontalWidget)
self.label.setObjectName("label")
self.horizontalLayout.addWidget(self.label)
self.btnlocal = QtGui.QPushButton(self.horizontalWidget)
self.btnlocal.setObjectName("btnlocal")
self.horizontalLayout.addWidget(self.btnlocal)
self.btnremote = QtGui.QPushButton(self.horizontalWidget)
self.btnremote.setObjectName("btnremote")
self.horizontalLayout.addWidget(self.btnremote)
self.verticalLayout_2.addWidget(self.horizontalWidget)
RunStringDock.setWidget(self.dockWidgetContents)
self.retranslateUi(RunStringDock)
QtCore.QMetaObject.connectSlotsByName(RunStringDock)
def retranslateUi(self, RunStringDock):
RunStringDock.setWindowTitle(QtGui.QApplication.translate("RunStringDock", "Run String", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("RunStringDock", "Run String:", None, QtGui.QApplication.UnicodeUTF8))
self.btnlocal.setText(QtGui.QApplication.translate("RunStringDock", "Local", None, QtGui.QApplication.UnicodeUTF8))
self.btnremote.setText(QtGui.QApplication.translate("RunStringDock", "Remote", None, QtGui.QApplication.UnicodeUTF8))
| {
"content_hash": "8964d24d05efb09b030156b012ce548c",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 135,
"avg_line_length": 57.375,
"alnum_prop": 0.743355119825708,
"repo_name": "cloudteampro/juma-editor",
"id": "3bc1b170ed8531e92ad45705e991b44ea7715a80",
"size": "2542",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "editor/lib/ui/runstring_dock_ui.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "490405"
},
{
"name": "C++",
"bytes": "15076"
},
{
"name": "Lua",
"bytes": "223218"
},
{
"name": "Makefile",
"bytes": "6088"
},
{
"name": "Objective-C",
"bytes": "25470"
},
{
"name": "Python",
"bytes": "1033362"
},
{
"name": "Shell",
"bytes": "2792"
}
],
"symlink_target": ""
} |
from .chomsky import generate_chomsky
from .wordfinder import word_finder
from .minimalset import MinimalSet
from .babelfish import babelize_shell
| {
"content_hash": "38b60d743f4dfa273d1f6c22e61b0189",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 37,
"avg_line_length": 36.75,
"alnum_prop": 0.8435374149659864,
"repo_name": "haya14busa/alc-etm-searcher",
"id": "880ed9f5b189489a6604fed793c1edc961db2e6e",
"size": "354",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "nltk-3.0a3/nltk/misc/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11448"
},
{
"name": "Java",
"bytes": "30518"
},
{
"name": "Python",
"bytes": "6856183"
}
],
"symlink_target": ""
} |
import urllib2
'''
Top 10000 words in the german language
Nasty iso something encoding. Should be able to strip that in the future
'''
URL_DE = 'http://wortschatz.uni-leipzig.de/Papers/top10000de.txt'
class German_words:
def __init__(self, max_num = 10000):
if max_num > 10000:
print 'Truncating, maximum wordcount is 10000'
max_num = 10000
self.max_num = max_num
self.page = urllib2.urlopen(URL_DE)
self.word_list = [item.decode('latin-1').replace('\n','')
for item in self.page][:max_num]
def is_in_list(self, word):
return word.decode('utf-8') in self.word_list
#########################################################################################
# Test code follows here
#########################################################################################
def get_test(max_num = 10000):
gw = German_words(max_num)
print gw.word_list
def is_in_test(string, max_num = 10000):
gw = German_words(max_num)
print gw.is_in_list(string)
if __name__ == '__main__':
get_test(1)
get_test(2)
get_test(4)
is_in_test('über')
is_in_test('Elefant')
| {
"content_hash": "9760a348828e5ca55d050b8d079106dc",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 89,
"avg_line_length": 26.902439024390244,
"alnum_prop": 0.5548504079782411,
"repo_name": "thomi137/Python-Samples",
"id": "8cf50ccc1a73953f59afcd50cc3a92afc2d408a8",
"size": "2032",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "german_words.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "10013"
}
],
"symlink_target": ""
} |
"""A sample application for cmd2.
Thanks to cmd2's built-in transtript testing capability, it also serves as a test suite for example.py when used with
the exampleSession.txt transcript.
Running `python example.py -t exampleSession.txt` will run all the commands in the transcript against example.py,
verifying that the output produced matches the transcript.
"""
from cmd2 import Cmd, make_option, options
class CmdLineApp(Cmd):
""" Example cmd2 application. """
# Build-in Cmd attributes
intro = 'Welcome to the NP shell. Type help or ? to list commands.\n'
prompt = '(NP) '
multilineCommands = ['orate']
Cmd.shortcuts.update({'&': 'speak'})
maxrepeats = 3
Cmd.settable.append('maxrepeats')
# Setting this true makes it run a shell command if a cmd2/cmd command doesn't exist
# default_to_shell = True
@options([make_option('-p', '--piglatin', action="store_true", help="atinLay"),
make_option('-s', '--shout', action="store_true", help="N00B EMULATION MODE"),
make_option('-r', '--repeat', type="int", help="output [n] times")
])
def do_speak(self, arg, opts=None):
"""Repeats what you tell me to."""
arg = ''.join(arg)
if opts.piglatin:
arg = '%s%say' % (arg[1:], arg[0])
if opts.shout:
arg = arg.upper()
repetitions = opts.repeat or 1
for i in range(min(repetitions, self.maxrepeats)):
self.stdout.write(arg)
self.stdout.write('\n')
# self.stdout.write is better than "print", because Cmd can be
# initialized with a non-standard output destination
do_say = do_speak # now "say" is a synonym for "speak"
do_orate = do_speak # another synonym, but this one takes multi-line input
def do_greet(self, person):
"""greet [person]
Greet the named person"""
if person:
print("type(arg) = {}, arg={}, arg.split()={}".format(type(person), person,
person.split()))
print("hi, {}".format(person))
else:
print('hi')
@options([make_option('-d', '--depth', type="int", help="depth")],
arg_desc='test_args')
def do_test(self, arg, opts=None):
""" Prints out information about the arguments you give it. """
if arg:
print("type(arg) = {}, arg={}, arg.split()={}".format(type(arg), arg, arg.split()))
arg_join = ''.join(arg)
print("''.join(arg) = {}".format(arg_join))
else:
print('No arg')
if __name__ == '__main__':
c = CmdLineApp()
c.cmdloop()
| {
"content_hash": "6de731702c6b18f9905c9f2606353f65",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 117,
"avg_line_length": 38.25352112676056,
"alnum_prop": 0.5688512518409425,
"repo_name": "tleonhardt/CodingPlayground",
"id": "2de104a0059a07f7bcf28f07b1fb57f419d9b9b6",
"size": "2754",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "python/cmd2/CmdLineApp.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "30533"
},
{
"name": "C++",
"bytes": "2514"
},
{
"name": "CMake",
"bytes": "3607"
},
{
"name": "Cython",
"bytes": "3972"
},
{
"name": "HTML",
"bytes": "1700"
},
{
"name": "Jupyter Notebook",
"bytes": "2056095"
},
{
"name": "Makefile",
"bytes": "161"
},
{
"name": "Python",
"bytes": "244507"
},
{
"name": "Ruby",
"bytes": "296"
},
{
"name": "SWIG",
"bytes": "1120"
},
{
"name": "Shell",
"bytes": "893"
}
],
"symlink_target": ""
} |
import os
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponse
from django.shortcuts import render
# Explicitly get the 500 template outside the Django template
# loading mechanism. We do this so there is absolutely no
# chance that Django will attempt to do any parsing of this
# file.
for template_dir in settings.TEMPLATE_DIRS:
template_name = os.path.join(template_dir, "500.html")
if os.path.exists(template_name):
with open(template_name) as f:
text = f.read()
break
else:
msg = "Please add a 500.html to your base templates directory"
raise ImproperlyConfigured(msg)
def error_500(request):
# Display 500.html template as a text file, not as a Django template.
# Written as a Function-Based View so it handles all HTTP methods simply.
response = HttpResponse(text)
response.status_code = 500
return response
def error_404(request):
# Written as a Function-Based View so it handles all HTTP methods simply.
response = render(request, "404.html")
response.status_code = 404
return response | {
"content_hash": "632a66daa0989143cc9ea2f82270aa79",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 77,
"avg_line_length": 35.06060606060606,
"alnum_prop": 0.7277441659464131,
"repo_name": "pydanny/django-blarg",
"id": "aa79f36fcfa759ba67fd4c02d885db42a23dfbb9",
"size": "1157",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "blarg.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Makefile",
"bytes": "1202"
},
{
"name": "Python",
"bytes": "3143"
}
],
"symlink_target": ""
} |
import hashlib
from math import ceil
__author__ = 'Iurii Sergiichuk'
'''
The ANSI X9.63 key derivation function
We assume that we use SHA-512 hash function
'''
HASH_LEN = 512
MAX_INPUT = HASH_LEN * (2 << 32 - 1)
class SharedInfo(object):
def __init__(self, algorithm_id, counter=0, entityAinfo=None, entityBinfo=None, suppPrivInfo=None,
suppPubInfo=None):
"""
:arg algorithm_id: unique identifier of used hash algorithm
:arg counter: counter of iteration
:type algorithm_id: int
:type counter: int
:type entityAinfo: long
:type entityBinfo: long
:type suppPrivInfo: long
:type suppPubInfo: long
:rtype : SharedInfo
"""
self.algorithm_id = algorithm_id
self.counter = counter
self.entityAinfo = entityAinfo
self.entityBinfo = entityBinfo
self.suppPrivInfo = suppPrivInfo
self.suppPubInfo = suppPubInfo
def __str__(self):
result = str(self.algorithm_id) + str(self.counter)
if self.entityAinfo is not None:
result += bin(self.entityAinfo)[2:]
if self.entityBinfo is not None:
result += bin(self.entityBinfo)[2:]
if self.suppPrivInfo is not None:
result += bin(self.suppPrivInfo)[2:]
if self.suppPubInfo is not None:
result += bin(self.suppPubInfo)[2:]
return result
def is_whole(number):
'''
Check whether given number is whole or not
:param number: number to check
:type number: number
:return: true, if given number is whole
:rtype: bool
'''
if number % 1 == 0:
return True
return False
def derivate_key(Z, keydatalen, shared_info):
"""
Process key derivation
:arg Z: shared secret as long number
:arg keydatalen: integer that point ZZ bit length
:arg shared_info: possible additional information
:type Z: long
:type keydatalen: int
:type SharedInfo: SharedInfo
:return: derivated key in bit-string format
:rtype : str
"""
if keydatalen > MAX_INPUT:
raise ValueError("Keydatalen should be less than HASH_LEN*(2^32-1), but was:" + str(keydatalen))
shared_info.counter = 0x00000001
hash_parts = []
for i in xrange(int(ceil(keydatalen * 1.0 / HASH_LEN))):
value_to_hash = bin(Z)[2:]
value_to_hash += str(shared_info)
h = hashlib.sha512()
h.update(value_to_hash)
hex_digest = h.hexdigest()
long_digest = long(hex_digest, base=16)
h_i = bin(long_digest)[2:]
hash_parts.append(h_i)
shared_info.counter += 1
r = ''
for i in xrange(len(hash_parts) - 1):
r += hash_parts[i]
h_hash = hash_parts[len(hash_parts) - 1]
if not is_whole(keydatalen * 1.0 / HASH_LEN):
h_hash = h_hash[:keydatalen - HASH_LEN * (len(hash_parts) - 1)]
r += h_hash
return r
| {
"content_hash": "b385d0b44f95fb815953a903f12c8599",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 104,
"avg_line_length": 31.138297872340427,
"alnum_prop": 0.6081311923471131,
"repo_name": "xSAVIKx/ISO-IEC-11770-3",
"id": "1a6b217f92005e5ae149291d0dcc86baff523476",
"size": "2927",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "key_derivation/ANSI_X9_63.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "13524"
}
],
"symlink_target": ""
} |
import argparse
import importlib
import os
import types
import dcm.agent.plugins.builtin as builtins
filelist = [f for f in os.listdir(os.path.dirname(builtins.__file__))
if not f.startswith("__")
and not f.endswith(".pyc")]
def dynamic_import(f):
"""
:param f: this is the filename
:return: reference to the imported module
"""
filename = f[:-3]
fpath = "dcm.agent.plugins.builtin." + filename
x = importlib.import_module(fpath)
return x
def get_protocol_argument_dict(x):
"""
:param x: reference to imported module
:return: protocol_arguments dict which is an
attribute of the class in the module
"""
for thing in dir(x):
o = getattr(x, thing)
z = getattr(o, 'protocol_arguments', None)
if z is not None:
return z
def output_markdown(f, pa_dict):
"""
:param f: this is the filename
:param pa_dict: this is the protocol_arguments dict
:return: the function prints to stdout the
protocol_arguments dict in markdown format
"""
flatstring = '## ' + f + ' parameters:\n'
for key in sorted(list(pa_dict.keys())):
value = pa_dict[key]
flatstring += '- ' + key + ': ' + value[0] + '\n'
flatstring += ' - optional: ' + '%s' % value[1] + '\n'
flatstring += ' - type: ' + '%s' % get_type_string(value[2]) + '\n'
flatstring += ' - default: ' + '%s' % str(value[3]) + '\n'
flatstring += ''
print(flatstring)
return flatstring
def get_type_string(x):
"""
:param x: this is object of type in
the protocol_arguments dict
in the builtins
:return: if type is FunctionType then
we'll return a descriptive docstring __doc__
otherwise just return __name__
"""
if isinstance(x, types.FunctionType):
return x.__doc__
else:
return x.__name__
def main():
"""
:return: handler for the module
"""
parser = argparse.ArgumentParser(
prog='dcm-agent-gen-docs',
description='A utility to output the agent protocol arguments in '
'an easy to read format.',
usage='dcm-agent-gen-docs [> output file]')
parser.parse_args()
for f in filelist:
x = dynamic_import(f)
pa_dict = get_protocol_argument_dict(x)
output_markdown(f, pa_dict)
if __name__ == "__main__":
main() | {
"content_hash": "f74916064ba2e52914cd0b2de1cdb334",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 78,
"avg_line_length": 26.655913978494624,
"alnum_prop": 0.5679709560306575,
"repo_name": "JPWKU/unix-agent",
"id": "0af26705437c9535efd739c6d40fc43eb74ae08e",
"size": "3062",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/dcm/agent/cmd/gen_docs.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "172"
},
{
"name": "Python",
"bytes": "743804"
},
{
"name": "Ruby",
"bytes": "79677"
},
{
"name": "Shell",
"bytes": "81231"
}
],
"symlink_target": ""
} |
import os
import sys
from django.conf import settings
from django.db.backends.creation import BaseDatabaseCreation
class DatabaseCreation(BaseDatabaseCreation):
# SQLite doesn't actually support most of these types, but it "does the right
# thing" given more verbose field definitions, so leave them as is so that
# schema inspection is more useful.
data_types = {
'AutoField': 'integer',
'BooleanField': 'bool',
'CharField': 'varchar(%(max_length)s)',
'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
'DateField': 'date',
'DateTimeField': 'datetime',
'DecimalField': 'decimal',
'FileField': 'varchar(%(max_length)s)',
'FilePathField': 'varchar(%(max_length)s)',
'FloatField': 'real',
'IntegerField': 'integer',
'IPAddressField': 'char(15)',
'NullBooleanField': 'bool',
'OneToOneField': 'integer',
'PositiveIntegerField': 'integer unsigned',
'PositiveSmallIntegerField': 'smallint unsigned',
'SlugField': 'varchar(%(max_length)s)',
'SmallIntegerField': 'smallint',
'TextField': 'text',
'TimeField': 'time',
}
def sql_for_pending_references(self, model, style, pending_references):
"SQLite3 doesn't support constraints"
return []
def sql_remove_table_constraints(self, model, references_to_delete, style):
"SQLite3 doesn't support constraints"
return []
def _create_test_db(self, verbosity, autoclobber):
if settings.TEST_DATABASE_NAME and settings.TEST_DATABASE_NAME != ":memory:":
test_database_name = settings.TEST_DATABASE_NAME
# Erase the old test database
if verbosity >= 1:
print "Destroying old test database..."
if os.access(test_database_name, os.F_OK):
if not autoclobber:
confirm = raw_input("Type 'yes' if you would like to try deleting the test database '%s', or 'no' to cancel: " % test_database_name)
if autoclobber or confirm == 'yes':
try:
if verbosity >= 1:
print "Destroying old test database..."
os.remove(test_database_name)
except Exception, e:
sys.stderr.write("Got an error deleting the old test database: %s\n" % e)
sys.exit(2)
else:
print "Tests cancelled."
sys.exit(1)
if verbosity >= 1:
print "Creating test database..."
else:
test_database_name = ":memory:"
return test_database_name
def _destroy_test_db(self, test_database_name, verbosity):
if test_database_name and test_database_name != ":memory:":
# Remove the SQLite database file
os.remove(test_database_name)
| {
"content_hash": "40b862df4c73771d240b6ba69001a9c3",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 152,
"avg_line_length": 47.7,
"alnum_prop": 0.512428870919437,
"repo_name": "greggian/TapdIn",
"id": "7312264224943a83bd7ed3532c6ac33c6753bf6f",
"size": "3339",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "django/db/backends/sqlite3/creation.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "82525"
},
{
"name": "Python",
"bytes": "3585862"
},
{
"name": "Shell",
"bytes": "227"
}
],
"symlink_target": ""
} |
import compileall
import os
from importlib import import_module
from django.db import connection, connections
from django.db.migrations.exceptions import (
AmbiguityError, InconsistentMigrationHistory, NodeNotFoundError,
)
from django.db.migrations.loader import MigrationLoader
from django.db.migrations.recorder import MigrationRecorder
from django.test import TestCase, modify_settings, override_settings
from .test_base import MigrationTestBase
class RecorderTests(TestCase):
"""
Tests recording migrations as applied or not.
"""
databases = {'default', 'other'}
def test_apply(self):
"""
Tests marking migrations as applied/unapplied.
"""
recorder = MigrationRecorder(connection)
self.assertEqual(
{(x, y) for (x, y) in recorder.applied_migrations() if x == "myapp"},
set(),
)
recorder.record_applied("myapp", "0432_ponies")
self.assertEqual(
{(x, y) for (x, y) in recorder.applied_migrations() if x == "myapp"},
{("myapp", "0432_ponies")},
)
# That should not affect records of another database
recorder_other = MigrationRecorder(connections['other'])
self.assertEqual(
{(x, y) for (x, y) in recorder_other.applied_migrations() if x == "myapp"},
set(),
)
recorder.record_unapplied("myapp", "0432_ponies")
self.assertEqual(
{(x, y) for (x, y) in recorder.applied_migrations() if x == "myapp"},
set(),
)
class LoaderTests(TestCase):
"""
Tests the disk and database loader, and running through migrations
in memory.
"""
def setUp(self):
self.applied_records = []
def tearDown(self):
# Unapply records on databases that don't roll back changes after each
# test method.
if not connection.features.supports_transactions:
for recorder, app, name in self.applied_records:
recorder.record_unapplied(app, name)
def record_applied(self, recorder, app, name):
recorder.record_applied(app, name)
self.applied_records.append((recorder, app, name))
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
@modify_settings(INSTALLED_APPS={'append': 'basic'})
def test_load(self):
"""
Makes sure the loader can load the migrations for the test apps,
and then render them out to a new Apps.
"""
# Load and test the plan
migration_loader = MigrationLoader(connection)
self.assertEqual(
migration_loader.graph.forwards_plan(("migrations", "0002_second")),
[
("migrations", "0001_initial"),
("migrations", "0002_second"),
],
)
# Now render it out!
project_state = migration_loader.project_state(("migrations", "0002_second"))
self.assertEqual(len(project_state.models), 2)
author_state = project_state.models["migrations", "author"]
self.assertEqual(
list(author_state.fields),
["id", "name", "slug", "age", "rating"]
)
book_state = project_state.models["migrations", "book"]
self.assertEqual(list(book_state.fields), ['id', 'author'])
# Ensure we've included unmigrated apps in there too
self.assertIn("basic", project_state.real_apps)
@override_settings(MIGRATION_MODULES={
'migrations': 'migrations.test_migrations',
'migrations2': 'migrations2.test_migrations_2',
})
@modify_settings(INSTALLED_APPS={'append': 'migrations2'})
def test_plan_handles_repeated_migrations(self):
"""
_generate_plan() doesn't readd migrations already in the plan (#29180).
"""
migration_loader = MigrationLoader(connection)
nodes = [('migrations', '0002_second'), ('migrations2', '0001_initial')]
self.assertEqual(
migration_loader.graph._generate_plan(nodes, at_end=True),
[('migrations', '0001_initial'), ('migrations', '0002_second'), ('migrations2', '0001_initial')]
)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_unmigdep"})
def test_load_unmigrated_dependency(self):
"""
Makes sure the loader can load migrations with a dependency on an unmigrated app.
"""
# Load and test the plan
migration_loader = MigrationLoader(connection)
self.assertEqual(
migration_loader.graph.forwards_plan(("migrations", "0001_initial")),
[
('contenttypes', '0001_initial'),
('auth', '0001_initial'),
("migrations", "0001_initial"),
],
)
# Now render it out!
project_state = migration_loader.project_state(("migrations", "0001_initial"))
self.assertEqual(len([m for a, m in project_state.models if a == "migrations"]), 1)
book_state = project_state.models["migrations", "book"]
self.assertEqual(list(book_state.fields), ['id', 'user'])
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_run_before"})
def test_run_before(self):
"""
Makes sure the loader uses Migration.run_before.
"""
# Load and test the plan
migration_loader = MigrationLoader(connection)
self.assertEqual(
migration_loader.graph.forwards_plan(("migrations", "0002_second")),
[
("migrations", "0001_initial"),
("migrations", "0003_third"),
("migrations", "0002_second"),
],
)
@override_settings(MIGRATION_MODULES={
"migrations": "migrations.test_migrations_first",
"migrations2": "migrations2.test_migrations_2_first",
})
@modify_settings(INSTALLED_APPS={'append': 'migrations2'})
def test_first(self):
"""
Makes sure the '__first__' migrations build correctly.
"""
migration_loader = MigrationLoader(connection)
self.assertEqual(
migration_loader.graph.forwards_plan(("migrations", "second")),
[
("migrations", "thefirst"),
("migrations2", "0001_initial"),
("migrations2", "0002_second"),
("migrations", "second"),
],
)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
def test_name_match(self):
"Tests prefix name matching"
migration_loader = MigrationLoader(connection)
self.assertEqual(
migration_loader.get_migration_by_prefix("migrations", "0001").name,
"0001_initial",
)
msg = "There is more than one migration for 'migrations' with the prefix '0'"
with self.assertRaisesMessage(AmbiguityError, msg):
migration_loader.get_migration_by_prefix("migrations", "0")
msg = "There is no migration for 'migrations' with the prefix 'blarg'"
with self.assertRaisesMessage(KeyError, msg):
migration_loader.get_migration_by_prefix("migrations", "blarg")
def test_load_import_error(self):
with override_settings(MIGRATION_MODULES={"migrations": "import_error_package"}):
with self.assertRaises(ImportError):
MigrationLoader(connection)
def test_load_module_file(self):
with override_settings(MIGRATION_MODULES={"migrations": "migrations.faulty_migrations.file"}):
loader = MigrationLoader(connection)
self.assertIn(
"migrations", loader.unmigrated_apps,
"App with migrations module file not in unmigrated apps."
)
def test_load_empty_dir(self):
with override_settings(MIGRATION_MODULES={"migrations": "migrations.faulty_migrations.namespace"}):
loader = MigrationLoader(connection)
self.assertIn(
"migrations", loader.unmigrated_apps,
"App missing __init__.py in migrations module not in unmigrated apps."
)
@override_settings(
INSTALLED_APPS=['migrations.migrations_test_apps.migrated_app'],
)
def test_marked_as_migrated(self):
"""
Undefined MIGRATION_MODULES implies default migration module.
"""
migration_loader = MigrationLoader(connection)
self.assertEqual(migration_loader.migrated_apps, {'migrated_app'})
self.assertEqual(migration_loader.unmigrated_apps, set())
@override_settings(
INSTALLED_APPS=['migrations.migrations_test_apps.migrated_app'],
MIGRATION_MODULES={"migrated_app": None},
)
def test_marked_as_unmigrated(self):
"""
MIGRATION_MODULES allows disabling of migrations for a particular app.
"""
migration_loader = MigrationLoader(connection)
self.assertEqual(migration_loader.migrated_apps, set())
self.assertEqual(migration_loader.unmigrated_apps, {'migrated_app'})
@override_settings(
INSTALLED_APPS=['migrations.migrations_test_apps.migrated_app'],
MIGRATION_MODULES={'migrated_app': 'missing-module'},
)
def test_explicit_missing_module(self):
"""
If a MIGRATION_MODULES override points to a missing module, the error
raised during the importation attempt should be propagated unless
`ignore_no_migrations=True`.
"""
with self.assertRaisesMessage(ImportError, 'missing-module'):
migration_loader = MigrationLoader(connection)
migration_loader = MigrationLoader(connection, ignore_no_migrations=True)
self.assertEqual(migration_loader.migrated_apps, set())
self.assertEqual(migration_loader.unmigrated_apps, {'migrated_app'})
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"})
def test_loading_squashed(self):
"Tests loading a squashed migration"
migration_loader = MigrationLoader(connection)
recorder = MigrationRecorder(connection)
self.addCleanup(recorder.flush)
# Loading with nothing applied should just give us the one node
self.assertEqual(
len([x for x in migration_loader.graph.nodes if x[0] == "migrations"]),
1,
)
# However, fake-apply one migration and it should now use the old two
self.record_applied(recorder, 'migrations', '0001_initial')
migration_loader.build_graph()
self.assertEqual(
len([x for x in migration_loader.graph.nodes if x[0] == "migrations"]),
2,
)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed_complex"})
def test_loading_squashed_complex(self):
"Tests loading a complex set of squashed migrations"
loader = MigrationLoader(connection)
recorder = MigrationRecorder(connection)
self.addCleanup(recorder.flush)
def num_nodes():
plan = set(loader.graph.forwards_plan(('migrations', '7_auto')))
return len(plan - loader.applied_migrations.keys())
# Empty database: use squashed migration
loader.build_graph()
self.assertEqual(num_nodes(), 5)
# Starting at 1 or 2 should use the squashed migration too
self.record_applied(recorder, 'migrations', '1_auto')
loader.build_graph()
self.assertEqual(num_nodes(), 4)
self.record_applied(recorder, 'migrations', '2_auto')
loader.build_graph()
self.assertEqual(num_nodes(), 3)
# However, starting at 3 to 5 cannot use the squashed migration
self.record_applied(recorder, 'migrations', '3_auto')
loader.build_graph()
self.assertEqual(num_nodes(), 4)
self.record_applied(recorder, 'migrations', '4_auto')
loader.build_graph()
self.assertEqual(num_nodes(), 3)
# Starting at 5 to 7 we are past the squashed migrations.
self.record_applied(recorder, 'migrations', '5_auto')
loader.build_graph()
self.assertEqual(num_nodes(), 2)
self.record_applied(recorder, 'migrations', '6_auto')
loader.build_graph()
self.assertEqual(num_nodes(), 1)
self.record_applied(recorder, 'migrations', '7_auto')
loader.build_graph()
self.assertEqual(num_nodes(), 0)
@override_settings(MIGRATION_MODULES={
"app1": "migrations.test_migrations_squashed_complex_multi_apps.app1",
"app2": "migrations.test_migrations_squashed_complex_multi_apps.app2",
})
@modify_settings(INSTALLED_APPS={'append': [
"migrations.test_migrations_squashed_complex_multi_apps.app1",
"migrations.test_migrations_squashed_complex_multi_apps.app2",
]})
def test_loading_squashed_complex_multi_apps(self):
loader = MigrationLoader(connection)
loader.build_graph()
plan = set(loader.graph.forwards_plan(('app1', '4_auto')))
expected_plan = {
('app1', '1_auto'),
('app2', '1_squashed_2'),
('app1', '2_squashed_3'),
('app1', '4_auto'),
}
self.assertEqual(plan, expected_plan)
@override_settings(MIGRATION_MODULES={
"app1": "migrations.test_migrations_squashed_complex_multi_apps.app1",
"app2": "migrations.test_migrations_squashed_complex_multi_apps.app2",
})
@modify_settings(INSTALLED_APPS={'append': [
"migrations.test_migrations_squashed_complex_multi_apps.app1",
"migrations.test_migrations_squashed_complex_multi_apps.app2",
]})
def test_loading_squashed_complex_multi_apps_partially_applied(self):
loader = MigrationLoader(connection)
recorder = MigrationRecorder(connection)
self.record_applied(recorder, 'app1', '1_auto')
self.record_applied(recorder, 'app1', '2_auto')
loader.build_graph()
plan = set(loader.graph.forwards_plan(('app1', '4_auto')))
plan = plan - loader.applied_migrations.keys()
expected_plan = {
('app2', '1_squashed_2'),
('app1', '3_auto'),
('app1', '4_auto'),
}
self.assertEqual(plan, expected_plan)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed_erroneous"})
def test_loading_squashed_erroneous(self):
"Tests loading a complex but erroneous set of squashed migrations"
loader = MigrationLoader(connection)
recorder = MigrationRecorder(connection)
self.addCleanup(recorder.flush)
def num_nodes():
plan = set(loader.graph.forwards_plan(('migrations', '7_auto')))
return len(plan - loader.applied_migrations.keys())
# Empty database: use squashed migration
loader.build_graph()
self.assertEqual(num_nodes(), 5)
# Starting at 1 or 2 should use the squashed migration too
self.record_applied(recorder, 'migrations', '1_auto')
loader.build_graph()
self.assertEqual(num_nodes(), 4)
self.record_applied(recorder, 'migrations', '2_auto')
loader.build_graph()
self.assertEqual(num_nodes(), 3)
# However, starting at 3 or 4, nonexistent migrations would be needed.
msg = ("Migration migrations.6_auto depends on nonexistent node ('migrations', '5_auto'). "
"Django tried to replace migration migrations.5_auto with any of "
"[migrations.3_squashed_5] but wasn't able to because some of the replaced "
"migrations are already applied.")
self.record_applied(recorder, 'migrations', '3_auto')
with self.assertRaisesMessage(NodeNotFoundError, msg):
loader.build_graph()
self.record_applied(recorder, 'migrations', '4_auto')
with self.assertRaisesMessage(NodeNotFoundError, msg):
loader.build_graph()
# Starting at 5 to 7 we are passed the squashed migrations
self.record_applied(recorder, 'migrations', '5_auto')
loader.build_graph()
self.assertEqual(num_nodes(), 2)
self.record_applied(recorder, 'migrations', '6_auto')
loader.build_graph()
self.assertEqual(num_nodes(), 1)
self.record_applied(recorder, 'migrations', '7_auto')
loader.build_graph()
self.assertEqual(num_nodes(), 0)
@override_settings(
MIGRATION_MODULES={'migrations': 'migrations.test_migrations'},
INSTALLED_APPS=['migrations'],
)
def test_check_consistent_history(self):
loader = MigrationLoader(connection=None)
loader.check_consistent_history(connection)
recorder = MigrationRecorder(connection)
self.record_applied(recorder, 'migrations', '0002_second')
msg = (
"Migration migrations.0002_second is applied before its dependency "
"migrations.0001_initial on database 'default'."
)
with self.assertRaisesMessage(InconsistentMigrationHistory, msg):
loader.check_consistent_history(connection)
@override_settings(
MIGRATION_MODULES={'migrations': 'migrations.test_migrations_squashed_extra'},
INSTALLED_APPS=['migrations'],
)
def test_check_consistent_history_squashed(self):
"""
MigrationLoader.check_consistent_history() should ignore unapplied
squashed migrations that have all of their `replaces` applied.
"""
loader = MigrationLoader(connection=None)
recorder = MigrationRecorder(connection)
self.record_applied(recorder, 'migrations', '0001_initial')
self.record_applied(recorder, 'migrations', '0002_second')
loader.check_consistent_history(connection)
self.record_applied(recorder, 'migrations', '0003_third')
loader.check_consistent_history(connection)
@override_settings(MIGRATION_MODULES={
"app1": "migrations.test_migrations_squashed_ref_squashed.app1",
"app2": "migrations.test_migrations_squashed_ref_squashed.app2",
})
@modify_settings(INSTALLED_APPS={'append': [
"migrations.test_migrations_squashed_ref_squashed.app1",
"migrations.test_migrations_squashed_ref_squashed.app2",
]})
def test_loading_squashed_ref_squashed(self):
"Tests loading a squashed migration with a new migration referencing it"
r"""
The sample migrations are structured like this:
app_1 1 --> 2 ---------------------*--> 3 *--> 4
\ / /
*-------------------*----/--> 2_sq_3 --*
\ / /
=============== \ ============= / == / ======================
app_2 *--> 1_sq_2 --* /
\ /
*--> 1 --> 2 --*
Where 2_sq_3 is a replacing migration for 2 and 3 in app_1,
as 1_sq_2 is a replacing migration for 1 and 2 in app_2.
"""
loader = MigrationLoader(connection)
recorder = MigrationRecorder(connection)
self.addCleanup(recorder.flush)
# Load with nothing applied: both migrations squashed.
loader.build_graph()
plan = set(loader.graph.forwards_plan(('app1', '4_auto')))
plan = plan - loader.applied_migrations.keys()
expected_plan = {
('app1', '1_auto'),
('app2', '1_squashed_2'),
('app1', '2_squashed_3'),
('app1', '4_auto'),
}
self.assertEqual(plan, expected_plan)
# Load with nothing applied and migrate to a replaced migration.
# Not possible if loader.replace_migrations is True (default).
loader.build_graph()
msg = "Node ('app1', '3_auto') not a valid node"
with self.assertRaisesMessage(NodeNotFoundError, msg):
loader.graph.forwards_plan(('app1', '3_auto'))
# Possible if loader.replace_migrations is False.
loader.replace_migrations = False
loader.build_graph()
plan = set(loader.graph.forwards_plan(('app1', '3_auto')))
plan = plan - loader.applied_migrations.keys()
expected_plan = {
('app1', '1_auto'),
('app2', '1_auto'),
('app2', '2_auto'),
('app1', '2_auto'),
('app1', '3_auto'),
}
self.assertEqual(plan, expected_plan)
loader.replace_migrations = True
# Fake-apply a few from app1: unsquashes migration in app1.
self.record_applied(recorder, 'app1', '1_auto')
self.record_applied(recorder, 'app1', '2_auto')
loader.build_graph()
plan = set(loader.graph.forwards_plan(('app1', '4_auto')))
plan = plan - loader.applied_migrations.keys()
expected_plan = {
('app2', '1_squashed_2'),
('app1', '3_auto'),
('app1', '4_auto'),
}
self.assertEqual(plan, expected_plan)
# Fake-apply one from app2: unsquashes migration in app2 too.
self.record_applied(recorder, 'app2', '1_auto')
loader.build_graph()
plan = set(loader.graph.forwards_plan(('app1', '4_auto')))
plan = plan - loader.applied_migrations.keys()
expected_plan = {
('app2', '2_auto'),
('app1', '3_auto'),
('app1', '4_auto'),
}
self.assertEqual(plan, expected_plan)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_private'})
def test_ignore_files(self):
"""Files prefixed with underscore, tilde, or dot aren't loaded."""
loader = MigrationLoader(connection)
loader.load_disk()
migrations = [name for app, name in loader.disk_migrations if app == 'migrations']
self.assertEqual(migrations, ['0001_initial'])
@override_settings(
MIGRATION_MODULES={'migrations': 'migrations.test_migrations_namespace_package'},
)
def test_loading_namespace_package(self):
"""Migration directories without an __init__.py file are ignored."""
loader = MigrationLoader(connection)
loader.load_disk()
migrations = [name for app, name in loader.disk_migrations if app == 'migrations']
self.assertEqual(migrations, [])
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'})
def test_loading_package_without__file__(self):
"""
To support frozen environments, MigrationLoader loads migrations from
regular packages with no __file__ attribute.
"""
test_module = import_module('migrations.test_migrations')
loader = MigrationLoader(connection)
# __file__ == __spec__.origin or the latter is None and former is
# undefined.
module_file = test_module.__file__
module_origin = test_module.__spec__.origin
module_has_location = test_module.__spec__.has_location
try:
del test_module.__file__
test_module.__spec__.origin = None
test_module.__spec__.has_location = False
loader.load_disk()
migrations = [
name
for app, name in loader.disk_migrations
if app == 'migrations'
]
self.assertCountEqual(migrations, ['0001_initial', '0002_second'])
finally:
test_module.__file__ = module_file
test_module.__spec__.origin = module_origin
test_module.__spec__.has_location = module_has_location
class PycLoaderTests(MigrationTestBase):
def test_valid(self):
"""
To support frozen environments, MigrationLoader loads .pyc migrations.
"""
with self.temporary_migration_module(module='migrations.test_migrations') as migration_dir:
# Compile .py files to .pyc files and delete .py files.
compileall.compile_dir(migration_dir, force=True, quiet=1, legacy=True)
for name in os.listdir(migration_dir):
if name.endswith('.py'):
os.remove(os.path.join(migration_dir, name))
loader = MigrationLoader(connection)
self.assertIn(('migrations', '0001_initial'), loader.disk_migrations)
def test_invalid(self):
"""
MigrationLoader reraises ImportErrors caused by "bad magic number" pyc
files with a more helpful message.
"""
with self.temporary_migration_module(module='migrations.test_migrations_bad_pyc') as migration_dir:
# The -tpl suffix is to avoid the pyc exclusion in MANIFEST.in.
os.rename(
os.path.join(migration_dir, '0001_initial.pyc-tpl'),
os.path.join(migration_dir, '0001_initial.pyc'),
)
msg = (
r"Couldn't import '\w+.migrations.0001_initial' as it appears "
"to be a stale .pyc file."
)
with self.assertRaisesRegex(ImportError, msg):
MigrationLoader(connection)
| {
"content_hash": "ecd792befa57dff946348a159416f0aa",
"timestamp": "",
"source": "github",
"line_count": 613,
"max_line_length": 108,
"avg_line_length": 41.27569331158238,
"alnum_prop": 0.6073432930203146,
"repo_name": "ghickman/django",
"id": "03a98506e3e27bbc087fdbdff13259e7e8b7f321",
"size": "25302",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "tests/migrations/test_loader.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "52334"
},
{
"name": "HTML",
"bytes": "170436"
},
{
"name": "JavaScript",
"bytes": "255321"
},
{
"name": "Makefile",
"bytes": "125"
},
{
"name": "Python",
"bytes": "11414242"
},
{
"name": "Shell",
"bytes": "809"
},
{
"name": "Smarty",
"bytes": "130"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import
import ssl
import threading
import pytest
from thriftpy._compat import MODERN_SSL
from thriftpy.transport import TTransportException, create_thriftpy_context
from thriftpy.transport.sslsocket import TSSLSocket, TSSLServerSocket
def _echo_server(sock):
c = sock.accept()
try:
b = c.read(1024)
c.write(b)
except TTransportException:
pass
finally:
c.close()
def _test_socket(server_socket, client_socket):
server_socket.listen()
t = threading.Thread(target=_echo_server, args=(server_socket,))
t.start()
try:
buff = b"Hello World!"
client_socket.open()
client_socket.write(buff)
buff2 = client_socket.read(1024)
assert buff == buff2
finally:
t.join(0)
client_socket.close()
server_socket.close()
def test_inet_ssl_socket():
server_socket = TSSLServerSocket(host="localhost", port=12345,
certfile="ssl/server.pem")
client_socket = TSSLSocket(
host="localhost", port=12345, socket_timeout=3000,
cafile="ssl/CA.pem", certfile="ssl/client.crt",
keyfile="ssl/client.key")
_test_socket(server_socket, client_socket)
@pytest.mark.skipif(not MODERN_SSL,
reason="check hostname not supported")
def test_ssl_hostname_validate():
server_socket = TSSLServerSocket(host="localhost", port=12345,
certfile="ssl/server.pem")
# the ssl cert lock hostname to "localhost"
client_socket = TSSLSocket(
host="127.0.0.1", port=12345, socket_timeout=3000,
cafile="ssl/CA.pem", certfile="ssl/client.crt",
keyfile="ssl/client.key")
with pytest.raises(ssl.CertificateError):
_test_socket(server_socket, client_socket)
# bypass check with validate False
client_socket = TSSLSocket(
host="127.0.0.1", port=12345, socket_timeout=3000,
validate=False,
cafile="ssl/CA.pem", certfile="ssl/client.crt",
keyfile="ssl/client.key")
_test_socket(server_socket, client_socket)
def test_persist_ssl_context():
server_ssl_context = create_thriftpy_context(server_side=True)
server_ssl_context.load_cert_chain(certfile="ssl/server.pem")
server_socket = TSSLServerSocket(host="localhost", port=12345,
ssl_context=server_ssl_context)
client_ssl_context = create_thriftpy_context(server_side=False)
client_ssl_context.load_verify_locations(cafile="ssl/CA.pem")
client_ssl_context.load_cert_chain(certfile="ssl/client.crt",
keyfile="ssl/client.key")
client_socket = TSSLSocket(host="localhost", port=12345,
ssl_context=client_ssl_context)
_test_socket(server_socket, client_socket)
| {
"content_hash": "664133818ff1059add69d61f706a2ba8",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 75,
"avg_line_length": 32.41573033707865,
"alnum_prop": 0.6357019064124784,
"repo_name": "keitheis/thriftpy",
"id": "15af2e984273ae589840ed34c51a661bd2a213cc",
"size": "2910",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "tests/test_sslsocket.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "705"
},
{
"name": "Makefile",
"bytes": "356"
},
{
"name": "Python",
"bytes": "261144"
},
{
"name": "Thrift",
"bytes": "22343"
}
],
"symlink_target": ""
} |
from pytelemetry import Pytelemetry
import queue
import pytest
import unittest.mock as mock
class transportMock:
def __init__(self):
self.queue = queue.Queue()
def read(self, maxbytes=1):
data = []
amount = 0
while amount < maxbytes and not self.queue.empty():
c = self.queue.get()
data.append(c)
amount += 1
return data
def readable(self):
return self.queue.qsize()
def write(self, data):
for i in range(len(data)):
self.queue.put(data[i])
return 0
def writeable(self):
return not self.queue.full()
def test_wrong_type():
# Setup
t = transportMock()
c = Pytelemetry(t)
with pytest.raises(Exception) as excinfo:
c.publish('sometopic',12,'string')
# TODO : Assert exception
assert t.queue.qsize() == 0
def test_unexisting_type():
# Setup
t = transportMock()
c = Pytelemetry(t)
with pytest.raises(IndexError):
c.publish('sometopic',12,'int323')
assert t.queue.qsize() == 0
def test_hardcoded():
t = transportMock()
c = Pytelemetry(t)
cb = mock.Mock(spec=["topic","data"])
c.subscribe('sometopic ',cb)
# Apply hardcoded frame directly generated by the c library
# SOF head sometopic..................................... eol 12457........ crc..... eof
t.write([247, 6, 0, 115, 111, 109, 101, 116, 111, 112, 105, 99, 32, 0, 169, 48, 0, 0, 111, 249, 127])
c.update()
assert t.queue.qsize() == 0
cb.assert_called_once_with('sometopic ',12457, None)
# TODO : Check what happens is string is non null terminated
# TODO : Check what happens if there are spaces in name
# TODO Check wrong crc
| {
"content_hash": "cabbb2e76a75e3a2d00bd9f8f81a33c7",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 105,
"avg_line_length": 26.876923076923077,
"alnum_prop": 0.5884373211219233,
"repo_name": "Overdrivr/pytelemetry",
"id": "d93752d245a5601e3223b55b960d0c72a7c3331d",
"size": "1747",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pytelemetry/test/test_typing.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "52254"
}
],
"symlink_target": ""
} |
class Student(object):
def __init__(self, name, levels_list):
self.name = name
self.levels = levels_list
def __str__(self):
return "{} ==> {}".format(self.name, str(self.levels))
def __repr__(self):
return str(self.__dict__)
def path(self, domain_order, number=5):
a = domain_order[:]
for lvl in self.levels:
a = filter(lambda x: not (lvl.domain == x.domain and
x.grade < lvl.grade), a)
return a[:number]
| {
"content_hash": "6c8e11d66c58f77189d9fe48a52e8106",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 64,
"avg_line_length": 28,
"alnum_prop": 0.5056390977443609,
"repo_name": "ganeshkbalaji/eSpark-coding-challenge",
"id": "92ed36eb0f3709a252176ae9e79445c4a3b784b3",
"size": "532",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "build/lib/espark/student.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "7337"
},
{
"name": "Ruby",
"bytes": "2187"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('legislature', '0004_auto_20161214_0237'),
('questing', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Bill',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('sunlight_id', models.CharField(max_length=63)),
('official_title', models.TextField()),
('popular_title', models.CharField(max_length=127)),
('summary', models.TextField()),
('url', models.CharField(help_text='Permalink with more info', max_length=127)),
('chamber', models.CharField(choices=[('S', 'Senate'), ('H', 'House')], max_length=3)),
('sponsor', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='legislature.Representative')),
('topics', models.ManyToManyField(to='questing.Topic')),
],
),
]
| {
"content_hash": "dec2a15f1d06330246a316b432cd894d",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 137,
"avg_line_length": 38.41935483870968,
"alnum_prop": 0.5793450881612091,
"repo_name": "gnmerritt/dailyrippl",
"id": "cecbc657ceb653d7d6de95292c98488fdfc40e3b",
"size": "1264",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rippl/bills/migrations/0001_initial.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "319"
},
{
"name": "CoffeeScript",
"bytes": "796"
},
{
"name": "HTML",
"bytes": "7370"
},
{
"name": "JavaScript",
"bytes": "18435"
},
{
"name": "Python",
"bytes": "52400"
},
{
"name": "Shell",
"bytes": "1074"
}
],
"symlink_target": ""
} |
from sklearn.utils.estimator_checks import check_estimator
from id3 import Id3Estimator
def test_estimator():
return check_estimator(Id3Estimator)
| {
"content_hash": "161f784e599c3a77059e0d7e5efb687f",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 58,
"avg_line_length": 25.5,
"alnum_prop": 0.8104575163398693,
"repo_name": "svaante/decision-tree-id3",
"id": "014621db465cfbec9fea88d72248c8afde5c0da6",
"size": "153",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "id3/tests/test_common.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "3366"
},
{
"name": "Python",
"bytes": "48338"
},
{
"name": "Shell",
"bytes": "3170"
}
],
"symlink_target": ""
} |
from concurrent import futures
import os
import signal
with futures.ProcessPoolExecutor(max_workers=2) as ex:
print('getting the pid for one worker')
f1 = ex.submit(os.getpid)
pid1 = f1.result()
print('killing process {}'.format(pid1))
os.kill(pid1, signal.SIGHUP)
print('submitting another task')
f2 = ex.submit(os.getpid)
try:
pid2 = f2.result()
except futures.process.BrokenProcessPool as e:
print('could not start new tasks: {}'.format(e))
| {
"content_hash": "faae2695b436087f91e4d09184a5be31",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 56,
"avg_line_length": 26.31578947368421,
"alnum_prop": 0.67,
"repo_name": "jasonwee/asus-rt-n14uhp-mrtg",
"id": "f9a9b43e013d1ce50cddf961b687ccf281ce2cd5",
"size": "500",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/lesson_concurrency_with_processes_threads_and_coroutines/futures_process_pool_broken.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "45876"
},
{
"name": "HTML",
"bytes": "107072"
},
{
"name": "JavaScript",
"bytes": "161335"
},
{
"name": "Python",
"bytes": "6923750"
},
{
"name": "Shell",
"bytes": "7616"
}
],
"symlink_target": ""
} |
"""
Solve day 24 of Advent of Code.
http://adventofcode.com/2016/day/24
"""
from collections import deque
from itertools import permutations
def make_grid(data):
grid = [list(line) for line in data]
return grid
def find_goals(grid):
goals = {}
for row in range(len(grid)):
for col in range(len(grid[0])):
if grid[row][col].isdigit():
goals[int(grid[row][col])] = (row, col)
return goals
def measure_segments(grid, goals):
segments = {}
goal_positions = goals.values()
moves = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for goal_id, position in goals.items():
queue = deque([[position]])
visited = set(position)
while queue:
path = queue.popleft()
row, col = path[-1]
# Found a path from one goal to another
if (row, col) in goal_positions and len(path) > 1 and \
goal_id != int(grid[row][col]):
segments[(goal_id, int(grid[row][col]))] = len(path) - 1
#continue
for d_row, d_col in moves:
if can_move(grid, row + d_row, col + d_col) and \
(row + d_row, col + d_col) not in visited:
queue.append(path + [(row + d_row, col + d_col)])
visited.add((row + d_row, col + d_col))
return segments
def can_move(grid, row, col):
return 0 <= row < len(grid) and \
0 <= col < len(grid[0]) and \
grid[row][col] in '.01234567'
def shortest_path(segments, start_at=0, return_to=None):
num_goals = sorted(segments.keys())[-1][0] + 1
distances = []
for path in permutations(range(1, num_goals)):
path = (start_at,) + path + (return_to,)
steps = 0
for i in range(len(path) - 2):
steps += segments[(path[i], path[i+1])]
if return_to is not None:
steps += segments[(path[-2], path[-1])]
distances.append(steps)
return min(distances)
"""
print('Part1:', min(distances1))
print('Part2:', min(distances2))
"""
if __name__ == '__main__':
with open('input.txt') as f:
grid = make_grid(f.read().splitlines())
goals = find_goals(grid)
segments = measure_segments(grid, goals)
print("Part 1:", shortest_path(segments))
print("Part 2:", shortest_path(segments, return_to=0))
| {
"content_hash": "59b99c0e41203cb95c4cb46ae5331e46",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 72,
"avg_line_length": 26.184782608695652,
"alnum_prop": 0.5325861353258613,
"repo_name": "mpirnat/aoc2016",
"id": "898aa19ea8abf9f095f15ff5049135ccc95ea305",
"size": "2432",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "day24/day24.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "70457"
}
],
"symlink_target": ""
} |
__author__ = 'qinpeng'
import random
from datetime import datetime, timedelta
import scrapy
from country.models import Country
from dealcrawler.spiders.BaseSpider import BaseSpider
from dealcrawler.util import *
from region.models import Region
from retailer.models import RetailerProperty
from source.models import DataSource
from supersaver.constants import *
from .lasoo.util import *
from ..data.retailer_repository import RetailerRepository
UTC_TO_NZ_TIMEZONE_DELTA = timedelta(seconds=12*3600)
class LasooCoNzRetailerSpider(BaseSpider):
"""
Crawl retailer and stores from lasoo.co.nz
"""
name = 'retailer.lasoo.co.nz'
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/48.0.2564.97 Safari/537.36',
custom_settings = {
'ROBOTSTXT_OBEY': False,
}
ORIGIN_URL = 'https://www.lasoo.co.nz/retailers.html'
INITIAL_REFERER_URL = 'https://www.lasoo.co.nz/retailers.html'
REQUEST_HOST = 'www.lasoo.co.nz'
# Filter parameter is single capital character 'ABCD...XYZ' or 0(zero)
RETAILER_LIST_URL_FORMAT = 'https://www.lasoo.co.nz/retailers.html?filter={0}&requestType=ajax'
NAME_INITIAL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0"
# 1. Browser retailer list with initial character.
# Filter parameter is single capital character 'ABCD...XYZ' or 0(zero)
# 2. Crawler retailer landing page.
# Retailer website link and logo may be found from retailer landing page:
# https://www.lasoo.co.nz/retailer/{retailer_name}.html
# 3. Extract store lists link from retailer landing page, and get list of stores with pagination.
# https://www.lasoo.co.nz/storelocator.html?pid=findstores%28top%29
# You can get store lasoo id, name, geo location here.
# 4. Get store location (Some retailer may not have store)
# https://www.lasoo.co.nz/storelocator/{retailer_name}/location/{region}.html
# 5. Parse store name, id, address, open hours, phone number, fax
def __init__(self, *args, **kwargs):
start_urls = []
for ch in self.__class__.NAME_INITIAL_CHARS:
# Ajax requests on website to get retailer list
start_urls.append(self.__class__.RETAILER_LIST_URL_FORMAT.format(ch))
super().__init__(
start_urls,
self.__class__.REQUEST_HOST,
*args, **kwargs)
self.datasource = DataSource.objects.get(id=DATASOURCE_ID_LASOO_CO_NZ)
self.country = Country.objects.get(country_code='NZ')
self.retailer_repo = RetailerRepository(self.datasource, self.country)
random.seed(datetime.now().timestamp())
# TODO: Identify proper region for retailer stores
self.region = Region.objects.get(name="all new zealand")
def start_requests(self):
for url in self.start_urls:
yield self.create_request(url, self.parse, referer=self.__class__.INITIAL_REFERER_URL, dont_filter=True)
def parse(self, response):
for retailer_li in response.xpath('//div[@class="tab-pane"]/ul/li'):
data = extract_first_value_with_xpath(retailer_li, "a/@data")
retailer_id = json_loads(data)['objectid']
display_name = extract_first_value_with_xpath(retailer_li, "a/@title")
link = extract_first_value_with_xpath(retailer_li, "a/@href")
retailer_detail_url = response.urljoin(link)
retailer_data = {
'id': retailer_id,
'name': display_name,
'lasoo_url': retailer_detail_url,
}
meta = {
'retailer': retailer_data,
}
yield scrapy.Request(retailer_detail_url,
callback=self.parse_retailer_details_from_response,
headers=self.__class__._get_http_headers(self.__class__.INITIAL_REFERER_URL),
meta=meta)
def parse_retailer_details_from_response(self, response):
elem = first_elem_with_xpath(response, '//div[@class="container"]//div[@class="banner"]//div[@class="content"]')
data = response.meta["retailer"]
logo_url = extract_first_value_with_xpath(elem, "img/@src")
website = None
store_list_url = None
anchors = elem.xpath('a')
for anchor_elem in anchors:
text = extract_first_value_with_xpath(anchor_elem, 'span/text()')
href = extract_first_value_with_xpath(anchor_elem, '@href')
if text and "view website" == text.lower():
if href:
if href.startswith('http'):
# External website
website = href
elif website != '#':
website = response.urljoin(href)
elif href and href.startswith("/storelocator"):
store_list_url = response.urljoin(href)
props = []
prop = RetailerProperty()
prop.name = make_internal_property_name("lasoo_id")
prop.value = data['id']
props.append(prop)
prop = RetailerProperty()
prop.name = make_internal_property_name("lasoo_url")
prop.value = data['lasoo_url']
props.append(prop)
retailer = self.retailer_repo.add_or_update_retailer_in_db(data['name'], website, logo_url, props)
if store_list_url:
meta = {
"retailer": retailer
}
return scrapy.Request(store_list_url,
callback=self.parse_stores_from_response,
headers=self.__class__._get_http_headers(response.url),
meta=meta)
else:
return None
def parse_stores_from_response(self, response):
retailer = response.meta["retailer"]
script_elems = response.xpath("//section[contains(@class, 'store_listing')]/div/script/text()")
stores_by_id = {}
for elem in script_elems:
script_text = elem.extract()
idx = script_text.find("showOfferDetailNearStoreMap")
if idx >= 0:
store_json = substr_surrounded_by_chars(script_text, ('[', ']'), idx)
stores = parse_lasoo_store_js(store_json)
stores_by_id = {s['lasoo_id']: s for s in stores}
break
store_list_elems = response.xpath(
"//section/div/div[contains(@class,'store-listing-table')]//tr[contains(@class,'ctr-storeitem')]")
for elem in store_list_elems:
# Get store url and address
store_id = extract_first_value_with_xpath(elem, "@data-storeid")
store = stores_by_id[store_id]
store_url = extract_first_value_with_xpath(elem, "@data-url")
address = extract_first_value_with_xpath(elem, "td[2]/text()")
store['lasoo_url'] = response.urljoin(store_url)
store['address'] = normalize_lasoo_store_address(address)
meta = {
"retailer": retailer,
"store": store
}
yield scrapy.Request(response.urljoin(store_url),
callback=self.parse_store_details_from_response,
headers=self.__class__._get_http_headers(response.url),
meta=meta)
# Is there pagination button? If so, we can get more stores.
next_page = extract_first_value_with_xpath(response, "//div[@class='pagination']//a[@class='next']/@href")
if not next_page:
return None
meta = {
"retailer": retailer
}
# Crawl stores in next page
next_stores_page_url = response.urljoin(next_page)
return scrapy.Request(next_stores_page_url,
callback=self.parse_stores_from_response,
headers=self.__class__._get_http_headers(response.url),
meta=meta)
def parse_store_details_from_response(self, response):
retailer = response.meta['retailer']
store = response.meta['store']
values = response.xpath(
'//div[@class="storemap-holder"]/div[@class="storemap-info"]/div/strong/text()').extract()
for v in values:
if v.lower().startswith('ph:'):
normalised_tel = v[3:].strip().replace(' ', '')
store['tel'] = normalised_tel
break
working_hours_node = first_elem_with_xpath(response, '//section//div[@class="store_hour"]/div[@class="content"]')
working_hours = self.__class__.extract_working_hours(working_hours_node)
if working_hours:
store['working_hours'] = working_hours
# Save and update store and its properties in database
add_or_update_store_in_db(store, self.region, retailer)
return None
@staticmethod
def extract_working_hours(html_node):
if exists_elem_with_xpath(html_node, '//table[@id="storeHours"]'):
# A working hours table
working_hours = ""
is_header = True
for row_node in html_node.xpath('//table[@id="storeHours"]//tr'):
if is_header:
is_header = False
continue
values = list(extract_values_with_xpath(row_node, 'td/text()'))
if len(working_hours) > 0:
working_hours += "\n"
working_hours += "{0} {1} - {2}".format(values[0], values[1], values[2])
if len(working_hours) > 0:
return working_hours
else:
working_hours = extract_first_value_with_xpath(html_node, 'text()')
if working_hours.lower().find("no store hours") < 0:
nv = working_hours.strip()
return nv
return None
@classmethod
def _get_http_headers(cls, referer):
return {
'Accept': '*/*',
'Accept-Language': 'en-US,en;q=0.8',
'Host': cls.REQUEST_HOST,
'Referer': referer,
}
| {
"content_hash": "b0ac3264cade5ddc7ac185983fa4d6f0",
"timestamp": "",
"source": "github",
"line_count": 234,
"max_line_length": 121,
"avg_line_length": 43.67094017094017,
"alnum_prop": 0.5756923378021332,
"repo_name": "ftkghost/SuperSaver",
"id": "a7c48fe25847cb1b89a713ad07529a7225d7b583",
"size": "10243",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "crawler/dealcrawler/spiders/nz/LasooCoNzRetailerSpider.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Python",
"bytes": "45502"
},
{
"name": "Shell",
"bytes": "714"
}
],
"symlink_target": ""
} |
"""
jsonapi.asyncio.handler.collection
==================================
"""
# std
import asyncio
from collections import OrderedDict
# local
from jsonapi.base import errors
from jsonapi.base import validators
from jsonapi.base.serializer import serialize_many
from jsonapi.base.pagination import Pagination
from .base import BaseHandler
class CollectionHandler(BaseHandler):
"""
Handles the collection endpoint.
"""
def __init__(self, api, db, request):
"""
"""
super().__init__(api, db, request)
self.typename = request.japi_uri_arguments.get("type")
return None
@asyncio.coroutine
def prepare(self):
"""
"""
if self.request.content_type[0] != "application/vnd.api+json":
raise errors.UnsupportedMediaType()
if not self.api.has_type(self.typename):
raise errors.NotFound()
return None
@asyncio.coroutine
def get(self):
"""
Handles a GET request. This means to fetch many resourcs from the
collection and return it.
http://jsonapi.org/format/#fetching-resources
"""
# Fetch the requested resources.
if self.request.japi_paginate:
offset = self.request.japi_page_offset
limit = self.request.japi_page_limit
else:
offset = self.request.japi_offset
limit = self.request.japi_limit
resources = yield from self.db.query(
self.typename, order=self.request.japi_sort, limit=limit,
offset=offset, filters=self.request.japi_filters
)
# Fetch all related resources, which should be included.
included_resources = yield from self.db.get_relatives(
resources, self.request.japi_include
)
# Build the response.
data = serialize_many(resources, fields=self.request.japi_fields)
included = serialize_many(
included_resources.values(), fields=self.request.japi_fields
)
meta = OrderedDict()
links = OrderedDict()
# Add the pagination links, if necessairy.
if self.request.japi_paginate:
total_resources = yield from self.db.query_size(
self.typename, filters=self.request.japi_filters
)
pagination = Pagination(self.request, total_resources)
meta.update(pagination.json_meta)
links.update(pagination.json_links)
# Put all together
self.response.headers["content-type"] = "application/vnd.api+json"
self.response.status_code = 200
self.response.body = self.api.dump_json(OrderedDict([
("data", data),
("included", included),
("meta", meta),
("links", links),
("jsonapi", self.api.jsonapi_object)
]))
return None
@asyncio.coroutine
def post(self):
"""
Handles a POST request. This means to create a new resource and to
return it.
http://jsonapi.org/format/#crud-creating
.. todo:: Support the *include* parameter?
"""
# Make sure the request contains a valid JSON resource object.
resource_object = self.request.json.get("data", dict())
validators.assert_resource_object(
resource_object, source_pointer="/data/"
)
# Check if the *type* is supported by this collection endpoint.
if resource_object["type"] != self.typename:
raise errors.Conflict()
# Create the new resource.
unserializer = self.api.get_unserializer(self.typename)
resource = yield from unserializer.create_resource(
self.db, resource_object
)
# Save the resources.
self.db.save([resource])
yield from self.db.commit()
# Crate the response.
serializer = self.api.get_serializer(self.typename)
data = serializer.serialize_resource(
resource, fields=self.request.japi_fields.get(self.typename)
)
links = data.setdefault("links", dict())
links["self"] = self.api.reverse_url(
typename=self.typename, endpoint="resource", id=data["id"]
)
# Put everything together.
self.response.headers["content-type"] = "application/vnd.api+json"
self.response.headers["location"] = links["self"]
self.response.status_code = 201
self.response.body = self.api.dump_json(OrderedDict([
("data", data),
("links", links),
("jsonapi", self.api.jsonapi_object)
]))
return None
| {
"content_hash": "8f7a16ee6d48ac82feb23e02277b0a22",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 74,
"avg_line_length": 32.02739726027397,
"alnum_prop": 0.5966638152266894,
"repo_name": "benediktschmitt/py-jsonapi",
"id": "c994ad6fbe8b837a6fe40508d0c65bd0283fb48a",
"size": "5822",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jsonapi/asyncio/handler/collection.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "266616"
}
],
"symlink_target": ""
} |
"""The test for light device automation."""
from datetime import timedelta
import pytest
import homeassistant.components.automation as automation
from homeassistant.components.light import DOMAIN
from homeassistant.const import CONF_PLATFORM, STATE_OFF, STATE_ON
from homeassistant.helpers import device_registry
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
from tests.common import (
MockConfigEntry,
async_fire_time_changed,
async_get_device_automation_capabilities,
async_get_device_automations,
async_mock_service,
mock_device_registry,
mock_registry,
)
@pytest.fixture
def device_reg(hass):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass)
@pytest.fixture
def entity_reg(hass):
"""Return an empty, loaded, registry."""
return mock_registry(hass)
@pytest.fixture
def calls(hass):
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation")
async def test_get_triggers(hass, device_reg, entity_reg):
"""Test we get the expected triggers from a light."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_reg.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_reg.async_get_or_create(DOMAIN, "test", "5678", device_id=device_entry.id)
expected_triggers = [
{
"platform": "device",
"domain": DOMAIN,
"type": "turned_off",
"device_id": device_entry.id,
"entity_id": f"{DOMAIN}.test_5678",
},
{
"platform": "device",
"domain": DOMAIN,
"type": "turned_on",
"device_id": device_entry.id,
"entity_id": f"{DOMAIN}.test_5678",
},
]
triggers = await async_get_device_automations(hass, "trigger", device_entry.id)
assert triggers == expected_triggers
async def test_get_trigger_capabilities(hass, device_reg, entity_reg):
"""Test we get the expected capabilities from a light trigger."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_reg.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_reg.async_get_or_create(DOMAIN, "test", "5678", device_id=device_entry.id)
expected_capabilities = {
"extra_fields": [
{"name": "for", "optional": True, "type": "positive_time_period_dict"}
]
}
triggers = await async_get_device_automations(hass, "trigger", device_entry.id)
for trigger in triggers:
capabilities = await async_get_device_automation_capabilities(
hass, "trigger", trigger
)
assert capabilities == expected_capabilities
async def test_if_fires_on_state_change(hass, calls):
"""Test for turn_on and turn_off triggers firing."""
platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init()
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
ent1, ent2, ent3 = platform.ENTITIES
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": ent1.entity_id,
"type": "turned_on",
},
"action": {
"service": "test.automation",
"data_template": {
"some": "turn_on {{ trigger.%s }}"
% "}} - {{ trigger.".join(
(
"platform",
"entity_id",
"from_state.state",
"to_state.state",
"for",
)
)
},
},
},
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": ent1.entity_id,
"type": "turned_off",
},
"action": {
"service": "test.automation",
"data_template": {
"some": "turn_off {{ trigger.%s }}"
% "}} - {{ trigger.".join(
(
"platform",
"entity_id",
"from_state.state",
"to_state.state",
"for",
)
)
},
},
},
]
},
)
await hass.async_block_till_done()
assert hass.states.get(ent1.entity_id).state == STATE_ON
assert len(calls) == 0
hass.states.async_set(ent1.entity_id, STATE_OFF)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["some"] == "turn_off device - {} - on - off - None".format(
ent1.entity_id
)
hass.states.async_set(ent1.entity_id, STATE_ON)
await hass.async_block_till_done()
assert len(calls) == 2
assert calls[1].data["some"] == "turn_on device - {} - off - on - None".format(
ent1.entity_id
)
async def test_if_fires_on_state_change_with_for(hass, calls):
"""Test for triggers firing with delay."""
platform = getattr(hass.components, f"test.{DOMAIN}")
platform.init()
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
ent1, ent2, ent3 = platform.ENTITIES
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {
"platform": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": ent1.entity_id,
"type": "turned_off",
"for": {"seconds": 5},
},
"action": {
"service": "test.automation",
"data_template": {
"some": "turn_off {{ trigger.%s }}"
% "}} - {{ trigger.".join(
(
"platform",
"entity_id",
"from_state.state",
"to_state.state",
"for",
)
)
},
},
}
]
},
)
await hass.async_block_till_done()
assert hass.states.get(ent1.entity_id).state == STATE_ON
assert len(calls) == 0
hass.states.async_set(ent1.entity_id, STATE_OFF)
await hass.async_block_till_done()
assert len(calls) == 0
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done()
assert len(calls) == 1
await hass.async_block_till_done()
assert calls[0].data["some"] == "turn_off device - {} - on - off - 0:00:05".format(
ent1.entity_id
)
| {
"content_hash": "e825482f9911aa99bc5321e90b80225f",
"timestamp": "",
"source": "github",
"line_count": 232,
"max_line_length": 87,
"avg_line_length": 34.75,
"alnum_prop": 0.47618456958571076,
"repo_name": "Teagan42/home-assistant",
"id": "969b4278aebc1bd5510bdac514225333e38a30e1",
"size": "8062",
"binary": false,
"copies": "2",
"ref": "refs/heads/dev",
"path": "tests/components/light/test_device_trigger.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "19774313"
},
{
"name": "Shell",
"bytes": "6846"
}
],
"symlink_target": ""
} |
from integration_tests import AgentlessTestCase
from integration_tests.tests.utils import get_resource as resource
class TestUninstallDeployment(AgentlessTestCase):
def test_uninstall_application_single_node_no_host(self):
dsl_path = resource("dsl/single_node_no_host.yaml")
deployment, _ = self.deploy_application(dsl_path)
deployment_id = deployment.id
self.undeploy_application(deployment_id)
states = self.get_plugin_data(
plugin_name='testmockoperations',
deployment_id=deployment_id
)['state']
node_id = states[0]['id']
unreachable_call_order = self.get_plugin_data(
plugin_name='testmockoperations',
deployment_id=deployment_id
)['unreachable_call_order']
unreachable_called = is_unreachable_called(
node_id,
unreachable_call_order)
self.assertTrue(unreachable_called)
node_instance = self.client.node_instances.get(node_id)
self.assertEqual('deleted', node_instance['state'])
def test_uninstall_application_single_host_node(self):
dsl_path = resource("dsl/basic.yaml")
deployment, _ = self.deploy_application(dsl_path)
deployment_id = deployment.id
self.undeploy_application(deployment_id)
machines = self.get_plugin_data(
plugin_name='cloudmock',
deployment_id=deployment_id
)['machines']
self.assertEquals(0, len(machines))
def test_uninstall_with_dependency_order(self):
dsl_path = resource(
"dsl/uninstall_dependencies-order-with-three-nodes.yaml")
deployment, _ = self.deploy_application(dsl_path)
deployment_id = deployment.id
self.undeploy_application(deployment_id)
# Checking that uninstall wasn't called on the contained node
states = self.get_plugin_data(
plugin_name='testmockoperations',
deployment_id=deployment_id
)['state']
node1_id = states[0]['id']
node2_id = states[1]['id']
node3_id = states[2]['id']
unreachable_call_order = self.get_plugin_data(
plugin_name='testmockoperations',
deployment_id=deployment_id
)['unreachable_call_order']
self.assertEquals(3, len(unreachable_call_order))
self.assertEquals(node3_id, unreachable_call_order[0]['id'])
self.assertEquals(node2_id, unreachable_call_order[1]['id'])
self.assertEquals(node1_id, unreachable_call_order[2]['id'])
configurer_state = self.get_plugin_data(
plugin_name='connection_configurer_mock',
deployment_id=deployment_id
)['state']
self.assertEquals(2, len(configurer_state))
self.assertTrue(
configurer_state[0]['source_id'].startswith('contained_in_node2'))
self.assertTrue(
configurer_state[0]['target_id'].startswith('contained_in_node1'))
self.assertTrue(
configurer_state[1]['target_id'].startswith('containing_node'))
self.assertTrue(
configurer_state[1]['source_id'].startswith('contained_in_node1'))
def test_stop_monitor_node_operation(self):
dsl_path = resource(
"dsl/hardcoded_operation_properties.yaml")
deployment, _ = self.deploy_application(dsl_path)
deployment_id = deployment.id
self.undeploy_application(deployment_id)
# test stop monitor invocations
invocations = self.get_plugin_data(
plugin_name='testmockoperations',
deployment_id=deployment_id
)['monitoring_operations_invocation']
self.assertEqual(2, len(invocations))
self.assertTrue('single_node' in invocations[0]['id'])
self.assertEquals('start_monitor', invocations[0]['operation'])
self.assertTrue('single_node' in invocations[1]['id'])
self.assertEquals('stop_monitor', invocations[1]['operation'])
def test_failed_uninstall_task(self):
dsl_path = resource('dsl/basic_stop_error.yaml')
deployment, _ = self.deploy_application(dsl_path)
deployment_id = deployment.id
self.undeploy_application(deployment_id,
parameters={'ignore_failure': True})
machines = self.get_plugin_data(
plugin_name='cloudmock',
deployment_id=deployment_id
)['machines']
self.assertEquals(0, len(machines))
def is_unreachable_called(node_id,
unreachable_call_order):
return next((x for x in
unreachable_call_order if x['id'] == node_id), None)
| {
"content_hash": "b2bdbed8345285b9a52ce9740039fd51",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 78,
"avg_line_length": 39.436974789915965,
"alnum_prop": 0.627743447688046,
"repo_name": "isaac-s/cloudify-manager",
"id": "e1eefc625e13cf3c0dd5bf518296e52ebbe490ea",
"size": "5338",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/integration_tests/tests/agentless_tests/test_uninstall_deployment.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Clojure",
"bytes": "4067"
},
{
"name": "Mako",
"bytes": "541"
},
{
"name": "Python",
"bytes": "1793118"
},
{
"name": "Ruby",
"bytes": "40193"
},
{
"name": "Shell",
"bytes": "41526"
}
],
"symlink_target": ""
} |
class TestStateLookup(object):
def test_simple_lookup(self):
from schedule.window import AWS_INSTANCE_STATES
assert AWS_INSTANCE_STATES.STOPPED == [80, 'stopped']
def test_state_value_matches_dict_values(self):
from schedule.window import AWS_INSTANCE_STATES
di = {u'Code': 16, u'Name': u'running'}
assert AWS_INSTANCE_STATES.RUNNING == di.values()
| {
"content_hash": "d8428ce98023e69ebb06f9ab715e6ff9",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 61,
"avg_line_length": 39.9,
"alnum_prop": 0.6716791979949874,
"repo_name": "LostProperty/schedule",
"id": "b8cf3f0e874204d08ba64408ad2ca641b0ae7f10",
"size": "399",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "tests.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "12441"
},
{
"name": "Shell",
"bytes": "1972"
}
],
"symlink_target": ""
} |
from collections import OrderedDict
import functools
import re
from typing import (
Dict,
Mapping,
Optional,
AsyncIterable,
Awaitable,
AsyncIterator,
Sequence,
Tuple,
Type,
Union,
)
import pkg_resources
from google.api_core.client_options import ClientOptions
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
try:
OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object] # type: ignore
from google.cloud.dialogflow_v2.types import audio_config
from google.cloud.dialogflow_v2.types import session
from google.cloud.dialogflow_v2.types import session as gcd_session
from google.cloud.location import locations_pb2 # type: ignore
from google.longrunning import operations_pb2
from google.rpc import status_pb2 # type: ignore
from .transports.base import SessionsTransport, DEFAULT_CLIENT_INFO
from .transports.grpc_asyncio import SessionsGrpcAsyncIOTransport
from .client import SessionsClient
class SessionsAsyncClient:
"""A service used for session interactions.
For more information, see the `API interactions
guide <https://cloud.google.com/dialogflow/docs/api-overview>`__.
"""
_client: SessionsClient
DEFAULT_ENDPOINT = SessionsClient.DEFAULT_ENDPOINT
DEFAULT_MTLS_ENDPOINT = SessionsClient.DEFAULT_MTLS_ENDPOINT
context_path = staticmethod(SessionsClient.context_path)
parse_context_path = staticmethod(SessionsClient.parse_context_path)
intent_path = staticmethod(SessionsClient.intent_path)
parse_intent_path = staticmethod(SessionsClient.parse_intent_path)
session_path = staticmethod(SessionsClient.session_path)
parse_session_path = staticmethod(SessionsClient.parse_session_path)
session_entity_type_path = staticmethod(SessionsClient.session_entity_type_path)
parse_session_entity_type_path = staticmethod(
SessionsClient.parse_session_entity_type_path
)
common_billing_account_path = staticmethod(
SessionsClient.common_billing_account_path
)
parse_common_billing_account_path = staticmethod(
SessionsClient.parse_common_billing_account_path
)
common_folder_path = staticmethod(SessionsClient.common_folder_path)
parse_common_folder_path = staticmethod(SessionsClient.parse_common_folder_path)
common_organization_path = staticmethod(SessionsClient.common_organization_path)
parse_common_organization_path = staticmethod(
SessionsClient.parse_common_organization_path
)
common_project_path = staticmethod(SessionsClient.common_project_path)
parse_common_project_path = staticmethod(SessionsClient.parse_common_project_path)
common_location_path = staticmethod(SessionsClient.common_location_path)
parse_common_location_path = staticmethod(SessionsClient.parse_common_location_path)
@classmethod
def from_service_account_info(cls, info: dict, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
info.
Args:
info (dict): The service account private key info.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
SessionsAsyncClient: The constructed client.
"""
return SessionsClient.from_service_account_info.__func__(SessionsAsyncClient, info, *args, **kwargs) # type: ignore
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
SessionsAsyncClient: The constructed client.
"""
return SessionsClient.from_service_account_file.__func__(SessionsAsyncClient, filename, *args, **kwargs) # type: ignore
from_service_account_json = from_service_account_file
@classmethod
def get_mtls_endpoint_and_cert_source(
cls, client_options: Optional[ClientOptions] = None
):
"""Return the API endpoint and client cert source for mutual TLS.
The client cert source is determined in the following order:
(1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
client cert source is None.
(2) if `client_options.client_cert_source` is provided, use the provided one; if the
default client cert source exists, use the default one; otherwise the client cert
source is None.
The API endpoint is determined in the following order:
(1) if `client_options.api_endpoint` if provided, use the provided one.
(2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
default mTLS endpoint; if the environment variabel is "never", use the default API
endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
use the default API endpoint.
More details can be found at https://google.aip.dev/auth/4114.
Args:
client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. Only the `api_endpoint` and `client_cert_source` properties may be used
in this method.
Returns:
Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
client cert source to use.
Raises:
google.auth.exceptions.MutualTLSChannelError: If any errors happen.
"""
return SessionsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
@property
def transport(self) -> SessionsTransport:
"""Returns the transport used by the client instance.
Returns:
SessionsTransport: The transport used by the client instance.
"""
return self._client.transport
get_transport_class = functools.partial(
type(SessionsClient).get_transport_class, type(SessionsClient)
)
def __init__(
self,
*,
credentials: ga_credentials.Credentials = None,
transport: Union[str, SessionsTransport] = "grpc_asyncio",
client_options: ClientOptions = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
"""Instantiates the sessions client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
transport (Union[str, ~.SessionsTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
client_options (ClientOptions): Custom options for the client. It
won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
environment variable can also be used to override the endpoint:
"always" (always use the default mTLS endpoint), "never" (always
use the default regular endpoint) and "auto" (auto switch to the
default mTLS endpoint if client certificate is present, this is
the default value). However, the ``api_endpoint`` property takes
precedence if provided.
(2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
is "true", then the ``client_cert_source`` property can be used
to provide client certificate for mutual TLS transport. If
not provided, the default SSL client certificate will be used if
present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
set, no client certificate will be used.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
"""
self._client = SessionsClient(
credentials=credentials,
transport=transport,
client_options=client_options,
client_info=client_info,
)
async def detect_intent(
self,
request: Union[gcd_session.DetectIntentRequest, dict] = None,
*,
session: str = None,
query_input: gcd_session.QueryInput = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> gcd_session.DetectIntentResponse:
r"""Processes a natural language query and returns structured,
actionable data as a result. This method is not idempotent,
because it may cause contexts and session entity types to be
updated, which in turn might affect results of future queries.
If you might use `Agent
Assist <https://cloud.google.com/dialogflow/docs/#aa>`__ or
other CCAI products now or in the future, consider using
[AnalyzeContent][google.cloud.dialogflow.v2.Participants.AnalyzeContent]
instead of ``DetectIntent``. ``AnalyzeContent`` has additional
functionality for Agent Assist and other CCAI products.
Note: Always use agent versions for production traffic. See
`Versions and
environments <https://cloud.google.com/dialogflow/es/docs/agents-versions>`__.
.. code-block:: python
# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in:
# https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import dialogflow_v2
async def sample_detect_intent():
# Create a client
client = dialogflow_v2.SessionsAsyncClient()
# Initialize request argument(s)
request = dialogflow_v2.DetectIntentRequest(
session="session_value",
)
# Make the request
response = await client.detect_intent(request=request)
# Handle the response
print(response)
Args:
request (Union[google.cloud.dialogflow_v2.types.DetectIntentRequest, dict]):
The request object. The request to detect user's intent.
session (:class:`str`):
Required. The name of the session this query is sent to.
Format:
``projects/<Project ID>/agent/sessions/<Session ID>``,
or
``projects/<Project ID>/agent/environments/<Environment ID>/users/<User ID>/sessions/<Session ID>``.
If ``Environment ID`` is not specified, we assume
default 'draft' environment (``Environment ID`` might be
referred to as environment name at some places). If
``User ID`` is not specified, we are using "-". It's up
to the API caller to choose an appropriate
``Session ID`` and ``User Id``. They can be a random
number or some type of user and session identifiers
(preferably hashed). The length of the ``Session ID``
and ``User ID`` must not exceed 36 characters.
For more information, see the `API interactions
guide <https://cloud.google.com/dialogflow/docs/api-overview>`__.
Note: Always use agent versions for production traffic.
See `Versions and
environments <https://cloud.google.com/dialogflow/es/docs/agents-versions>`__.
This corresponds to the ``session`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
query_input (:class:`google.cloud.dialogflow_v2.types.QueryInput`):
Required. The input specification. It
can be set to:
1. an audio config
which instructs the speech
recognizer how to process the speech
audio,
2. a conversational query in the form
of text, or
3. an event that specifies which intent
to trigger.
This corresponds to the ``query_input`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.dialogflow_v2.types.DetectIntentResponse:
The message returned from the
DetectIntent method.
"""
# Create or coerce a protobuf request object.
# Quick check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([session, query_input])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
request = gcd_session.DetectIntentRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if session is not None:
request.session = session
if query_input is not None:
request.query_input = query_input
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method_async.wrap_method(
self._client._transport.detect_intent,
default_retry=retries.Retry(
initial=0.1,
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
core_exceptions.ServiceUnavailable,
),
deadline=220.0,
),
default_timeout=220.0,
client_info=DEFAULT_CLIENT_INFO,
)
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("session", request.session),)),
)
# Send the request.
response = await rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Done; return the response.
return response
def streaming_detect_intent(
self,
requests: AsyncIterator[session.StreamingDetectIntentRequest] = None,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> Awaitable[AsyncIterable[session.StreamingDetectIntentResponse]]:
r"""Processes a natural language query in audio format in a
streaming fashion and returns structured, actionable data as a
result. This method is only available via the gRPC API (not
REST).
If you might use `Agent
Assist <https://cloud.google.com/dialogflow/docs/#aa>`__ or
other CCAI products now or in the future, consider using
[StreamingAnalyzeContent][google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent]
instead of ``StreamingDetectIntent``.
``StreamingAnalyzeContent`` has additional functionality for
Agent Assist and other CCAI products.
Note: Always use agent versions for production traffic. See
`Versions and
environments <https://cloud.google.com/dialogflow/es/docs/agents-versions>`__.
.. code-block:: python
# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in:
# https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import dialogflow_v2
async def sample_streaming_detect_intent():
# Create a client
client = dialogflow_v2.SessionsAsyncClient()
# Initialize request argument(s)
request = dialogflow_v2.StreamingDetectIntentRequest(
session="session_value",
)
# This method expects an iterator which contains
# 'dialogflow_v2.StreamingDetectIntentRequest' objects
# Here we create a generator that yields a single `request` for
# demonstrative purposes.
requests = [request]
def request_generator():
for request in requests:
yield request
# Make the request
stream = await client.streaming_detect_intent(requests=request_generator())
# Handle the response
async for response in stream:
print(response)
Args:
requests (AsyncIterator[`google.cloud.dialogflow_v2.types.StreamingDetectIntentRequest`]):
The request object AsyncIterator. The top-level message sent by the
client to the
[Sessions.StreamingDetectIntent][google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent]
method.
Multiple request messages should be sent in order:
1. The first message must contain
[session][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.session],
[query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input]
plus optionally
[query_params][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_params].
If the client wants to receive an audio response, it
should also contain
[output_audio_config][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.output_audio_config].
The message must not contain
[input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio].
2. If
[query_input][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.query_input]
was set to
[query_input.audio_config][google.cloud.dialogflow.v2.InputAudioConfig],
all subsequent messages must contain
[input_audio][google.cloud.dialogflow.v2.StreamingDetectIntentRequest.input_audio]
to continue with Speech recognition.
If you decide to rather detect an intent from text
input after you already started Speech recognition,
please send a message with
[query_input.text][google.cloud.dialogflow.v2.QueryInput.text].
However, note that:
* Dialogflow will bill you for the audio duration so
far. * Dialogflow discards all Speech recognition
results in favor of the input text.
* Dialogflow will use the language code from the
first message.
After you sent all input, you must half-close or abort
the request stream.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
AsyncIterable[google.cloud.dialogflow_v2.types.StreamingDetectIntentResponse]:
The top-level message returned from the
StreamingDetectIntent method.
Multiple response messages can be returned in order:
1. If the StreamingDetectIntentRequest.input_audio
field was set, the recognition_result field is
populated for one or more messages. See the
[StreamingRecognitionResult][google.cloud.dialogflow.v2.StreamingRecognitionResult]
message for details about the result message
sequence.
2. The next message contains response_id,
query_result and optionally webhook_status if a
WebHook was called.
"""
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method_async.wrap_method(
self._client._transport.streaming_detect_intent,
default_timeout=220.0,
client_info=DEFAULT_CLIENT_INFO,
)
# Send the request.
response = rpc(
requests,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Done; return the response.
return response
async def list_operations(
self,
request: operations_pb2.ListOperationsRequest = None,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> operations_pb2.ListOperationsResponse:
r"""Lists operations that match the specified filter in the request.
Args:
request (:class:`~.operations_pb2.ListOperationsRequest`):
The request object. Request message for
`ListOperations` method.
retry (google.api_core.retry.Retry): Designation of what errors,
if any, should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.operations_pb2.ListOperationsResponse:
Response message for ``ListOperations`` method.
"""
# Create or coerce a protobuf request object.
# The request isn't a proto-plus wrapped type,
# so it must be constructed via keyword expansion.
if isinstance(request, dict):
request = operations_pb2.ListOperationsRequest(**request)
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method.wrap_method(
self._client._transport.list_operations,
default_timeout=None,
client_info=DEFAULT_CLIENT_INFO,
)
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
response = await rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Done; return the response.
return response
async def get_operation(
self,
request: operations_pb2.GetOperationRequest = None,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> operations_pb2.Operation:
r"""Gets the latest state of a long-running operation.
Args:
request (:class:`~.operations_pb2.GetOperationRequest`):
The request object. Request message for
`GetOperation` method.
retry (google.api_core.retry.Retry): Designation of what errors,
if any, should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.operations_pb2.Operation:
An ``Operation`` object.
"""
# Create or coerce a protobuf request object.
# The request isn't a proto-plus wrapped type,
# so it must be constructed via keyword expansion.
if isinstance(request, dict):
request = operations_pb2.GetOperationRequest(**request)
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method.wrap_method(
self._client._transport.get_operation,
default_timeout=None,
client_info=DEFAULT_CLIENT_INFO,
)
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
response = await rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Done; return the response.
return response
async def cancel_operation(
self,
request: operations_pb2.CancelOperationRequest = None,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> None:
r"""Starts asynchronous cancellation on a long-running operation.
The server makes a best effort to cancel the operation, but success
is not guaranteed. If the server doesn't support this method, it returns
`google.rpc.Code.UNIMPLEMENTED`.
Args:
request (:class:`~.operations_pb2.CancelOperationRequest`):
The request object. Request message for
`CancelOperation` method.
retry (google.api_core.retry.Retry): Designation of what errors,
if any, should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
None
"""
# Create or coerce a protobuf request object.
# The request isn't a proto-plus wrapped type,
# so it must be constructed via keyword expansion.
if isinstance(request, dict):
request = operations_pb2.CancelOperationRequest(**request)
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method.wrap_method(
self._client._transport.cancel_operation,
default_timeout=None,
client_info=DEFAULT_CLIENT_INFO,
)
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
await rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
async def get_location(
self,
request: locations_pb2.GetLocationRequest = None,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> locations_pb2.Location:
r"""Gets information about a location.
Args:
request (:class:`~.location_pb2.GetLocationRequest`):
The request object. Request message for
`GetLocation` method.
retry (google.api_core.retry.Retry): Designation of what errors,
if any, should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.location_pb2.Location:
Location object.
"""
# Create or coerce a protobuf request object.
# The request isn't a proto-plus wrapped type,
# so it must be constructed via keyword expansion.
if isinstance(request, dict):
request = locations_pb2.GetLocationRequest(**request)
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method.wrap_method(
self._client._transport.get_location,
default_timeout=None,
client_info=DEFAULT_CLIENT_INFO,
)
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
response = await rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Done; return the response.
return response
async def list_locations(
self,
request: locations_pb2.ListLocationsRequest = None,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> locations_pb2.ListLocationsResponse:
r"""Lists information about the supported locations for this service.
Args:
request (:class:`~.location_pb2.ListLocationsRequest`):
The request object. Request message for
`ListLocations` method.
retry (google.api_core.retry.Retry): Designation of what errors,
if any, should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
~.location_pb2.ListLocationsResponse:
Response message for ``ListLocations`` method.
"""
# Create or coerce a protobuf request object.
# The request isn't a proto-plus wrapped type,
# so it must be constructed via keyword expansion.
if isinstance(request, dict):
request = locations_pb2.ListLocationsRequest(**request)
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = gapic_v1.method.wrap_method(
self._client._transport.list_locations,
default_timeout=None,
client_info=DEFAULT_CLIENT_INFO,
)
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
response = await rpc(
request,
retry=retry,
timeout=timeout,
metadata=metadata,
)
# Done; return the response.
return response
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc, tb):
await self.transport.close()
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution(
"google-cloud-dialogflow",
).version,
)
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
__all__ = ("SessionsAsyncClient",)
| {
"content_hash": "b248ce70c78ef509ce3d51577689bc44",
"timestamp": "",
"source": "github",
"line_count": 801,
"max_line_length": 128,
"avg_line_length": 41.6354556803995,
"alnum_prop": 0.6145427286356822,
"repo_name": "googleapis/python-dialogflow",
"id": "1671567cedfe3ada89bb74b551347ed1cd94192a",
"size": "33950",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "google/cloud/dialogflow_v2/services/sessions/async_client.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2050"
},
{
"name": "Python",
"bytes": "11184005"
},
{
"name": "Shell",
"bytes": "30672"
}
],
"symlink_target": ""
} |
from pydantic import BaseModel
class SubmissionBase(BaseModel):
survey_service_type: str
survey_outages: str
survey_disruptions: str
survey_subscribe_upload: str
survey_subscribe_download: str
survey_bundle: str
survey_current_cost: str
survey_satisfaction: str
survey_carrier_choice: str
survey_story: str
survey_email: str
survey_phone: str
actual_download: int
actual_upload: int
min_rtt: int
latitude: float
longitude: float
bigquery_key: str
class SubmissionCreate(SubmissionBase):
pass
class SubmissionUpdate(SubmissionBase):
id: int
# owner_id: int
class Config:
orm_mode = True
| {
"content_hash": "a2001b38229cea36dc6d35f86551efbc",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 39,
"avg_line_length": 19.714285714285715,
"alnum_prop": 0.6869565217391305,
"repo_name": "critzo/piecewise",
"id": "dd74a826c6c23a2c63333e4f3d0a2d4bb1a298de",
"size": "690",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "backend/piecewise/db/schemas/submission.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "57288"
},
{
"name": "Dockerfile",
"bytes": "996"
},
{
"name": "HTML",
"bytes": "66575"
},
{
"name": "JavaScript",
"bytes": "66481"
},
{
"name": "Mako",
"bytes": "494"
},
{
"name": "PLpgSQL",
"bytes": "1075"
},
{
"name": "Python",
"bytes": "72962"
},
{
"name": "Shell",
"bytes": "899"
}
],
"symlink_target": ""
} |
from __future__ import print_function
from setuptools import setup
from setuptools.command.test import test as TestCommand
import codecs
import os
import sys
import coolcantonese
here = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
# intentionally *not* adding an encoding option to open
return codecs.open(os.path.join(here, *parts), 'r').read()
long_description = ''
# long_description = read('readme.md')
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errcode = pytest.main(self.test_args)
sys.exit(errcode)
class Tox(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
# import here, cause outside the eggs aren't loaded
import tox
errcode = tox.cmdline(self.test_args)
sys.exit(errcode)
install_requires = """
werobot>=0.6.0
beautifulsoup4>=4.3.2
lxml>=3.3.3
redis>=2.10.3
sh>=1.0.8
six>=1.10.0
requests>=2.8.1
logutils>=0.3.3
enum34==1.1.6
"""
setup(
name='coolcantonese',
version=coolcantonese.__version__,
url='http://github.com/kk17/coolcantonese/',
license='Apache Software License',
author='Zhike Chan',
# tests_require=['pytest', 'pytest-cov', 'webtest'],
# cmdclass={'test': PyTest},
tests_require=['tox'],
cmdclass={'test': Tox},
install_requires=install_requires,
author_email='zk.chan007@gmail.com',
description='A wechat robot for learning Cantonese.',
long_description=long_description,
packages=['coolcantonese'],
include_package_data=True,
platforms='any',
# test_suite='tests.test_coolcantonese',
classifiers=[
'Programming Language :: Python',
'Development Status :: 4 - Beta',
'Natural Language :: Chinese',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: The MIT License (MIT)',
'Operating System :: Linux',
'Topic :: Software Development :: Libraries :: Python Application',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
extras_require={
'testing': ['pytest'],
}
)
| {
"content_hash": "d1bb7b8b28960b24199d6915dbcaab2c",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 75,
"avg_line_length": 26.764044943820224,
"alnum_prop": 0.6389588581024349,
"repo_name": "kk17/CoolCantonese",
"id": "7dcda318d379d97f02fb640f2611f534e143b568",
"size": "2382",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "529"
},
{
"name": "Python",
"bytes": "53868"
},
{
"name": "Shell",
"bytes": "369"
}
],
"symlink_target": ""
} |
'''
New Integration test for image replication.
Check Image Replication after All BS recovering from network unreachable
@author: Legion
'''
import os
import time
import random
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
image_name = 'image-replication-test-' + time.strftime('%y%m%d%H%M%S', time.localtime())
test_stub = test_lib.lib_get_test_stub()
img_repl = test_stub.ImageReplication()
def test():
os.environ['ZSTACK_BUILT_IN_HTTP_SERVER_IP'] = os.getenv('zstackHaVip')
bs_list = img_repl.get_bs_list()
bs = random.choice(bs_list)
bs_list.remove(bs)
bs2 = bs_list[0]
img_repl.add_image(image_name, bs_uuid=bs.uuid, url=os.getenv('imageUrl_raw'))
img_repl.wait_for_downloading(image_name)
test_stub.down_host_network(bs2.hostname, test_lib.all_scenario_config, "managment_net")
test_stub.down_host_network(bs.hostname, test_lib.all_scenario_config, "managment_net")
time.sleep(90)
test_stub.up_host_network(bs.hostname, test_lib.all_scenario_config, "managment_net")
test_stub.up_host_network(bs2.hostname, test_lib.all_scenario_config, "managment_net")
test_stub.recover_vlan_in_host(bs.hostname, test_lib.all_scenario_config, test_lib.deploy_config)
time.sleep(300)
img_repl.wait_for_bs_status_change('Connected')
img_repl.wait_for_image_replicated(image_name)
img_repl.check_image_data(image_name)
img_repl.wait_for_host_connected()
img_repl.create_vm(image_name)
test_util.test_pass('Image Replication After NIC Recovering Test Success')
img_repl.clean_on_expunge()
def env_recover():
img_repl.delete_image()
img_repl.expunge_image()
img_repl.reclaim_space_from_bs()
try:
img_repl.vm.destroy()
except:
pass
#Will be called only if exception happens in test().
def error_cleanup():
try:
img_repl.delete_image()
img_repl.expunge_image()
img_repl.reclaim_space_from_bs()
img_repl.vm.destroy()
except:
pass
| {
"content_hash": "b74dc24743750e839ae1ab5713541a94",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 101,
"avg_line_length": 29.214285714285715,
"alnum_prop": 0.6948655256723716,
"repo_name": "zstackio/zstack-woodpecker",
"id": "e659eefa85057753da994ad5cb3fd4720bd5cef9",
"size": "2045",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "integrationtest/vm/mini/image_replication/test_replicating_image_both_bs_nic_down.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2356"
},
{
"name": "Go",
"bytes": "49822"
},
{
"name": "Makefile",
"bytes": "687"
},
{
"name": "Puppet",
"bytes": "875"
},
{
"name": "Python",
"bytes": "13070596"
},
{
"name": "Shell",
"bytes": "177861"
}
],
"symlink_target": ""
} |
"""
python-social-auth application, allows OpenId or OAuth user
registration/authentication just adding a few configurations.
"""
version = (0, 2, 2)
extra = '-dev'
__version__ = '.'.join(map(str, version)) + extra
| {
"content_hash": "574259b4ccaf481383f8020ba92f166b",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 61,
"avg_line_length": 30.714285714285715,
"alnum_prop": 0.7023255813953488,
"repo_name": "SeanHayes/python-social-auth",
"id": "d5d5847c99af1256a84d64dc5d922b0c8deaa2f3",
"size": "215",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "social/__init__.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "54"
},
{
"name": "Makefile",
"bytes": "4735"
},
{
"name": "Python",
"bytes": "594456"
},
{
"name": "Shell",
"bytes": "122"
}
],
"symlink_target": ""
} |
from Tkinter import *
import SearchEngine
from SearchDialogBase import SearchDialogBase
def replace(text):
root = text._root()
engine = SearchEngine.get(root)
if not hasattr(engine, "_replacedialog"):
engine._replacedialog = ReplaceDialog(root, engine)
dialog = engine._replacedialog
dialog.open(text)
class ReplaceDialog(SearchDialogBase):
title = "Replace Dialog"
icon = "Replace"
def __init__(self, root, engine):
SearchDialogBase.__init__(self, root, engine)
self.replvar = StringVar(root)
def open(self, text):
SearchDialogBase.open(self, text)
try:
first = text.index("sel.first")
except TclError:
first = None
try:
last = text.index("sel.last")
except TclError:
last = None
first = first or text.index("insert")
last = last or first
self.show_hit(first, last)
self.ok = 1
def create_entries(self):
SearchDialogBase.create_entries(self)
self.replent = self.make_entry("Replace with:", self.replvar)
def create_command_buttons(self):
SearchDialogBase.create_command_buttons(self)
self.make_button("Find", self.find_it)
self.make_button("Replace", self.replace_it)
self.make_button("Replace+Find", self.default_command, 1)
self.make_button("Replace All", self.replace_all)
def find_it(self, event=None):
self.do_find(0)
def replace_it(self, event=None):
if self.do_find(self.ok):
self.do_replace()
def default_command(self, event=None):
if self.do_find(self.ok):
self.do_replace()
self.do_find(0)
def replace_all(self, event=None):
prog = self.engine.getprog()
if not prog:
return
repl = self.replvar.get()
text = self.text
res = self.engine.search_text(text, prog)
if not res:
text.bell()
return
text.tag_remove("sel", "1.0", "end")
text.tag_remove("hit", "1.0", "end")
line = res[0]
col = res[1].start()
if self.engine.iswrap():
line = 1
col = 0
ok = 1
first = last = None
# XXX ought to replace circular instead of top-to-bottom when wrapping
text.undo_block_start()
while 1:
res = self.engine.search_forward(text, prog, line, col, 0, ok)
if not res:
break
line, m = res
chars = text.get("%d.0" % line, "%d.0" % (line+1))
orig = m.group()
new = m.expand(repl)
i, j = m.span()
first = "%d.%d" % (line, i)
last = "%d.%d" % (line, j)
if new == orig:
text.mark_set("insert", last)
else:
text.mark_set("insert", first)
if first != last:
text.delete(first, last)
if new:
text.insert(first, new)
col = i + len(new)
ok = 0
text.undo_block_stop()
if first and last:
self.show_hit(first, last)
self.close()
def do_find(self, ok=0):
if not self.engine.getprog():
return False
text = self.text
res = self.engine.search_text(text, None, ok)
if not res:
text.bell()
return False
line, m = res
i, j = m.span()
first = "%d.%d" % (line, i)
last = "%d.%d" % (line, j)
self.show_hit(first, last)
self.ok = 1
return True
def do_replace(self):
prog = self.engine.getprog()
if not prog:
return False
text = self.text
try:
first = pos = text.index("sel.first")
last = text.index("sel.last")
except TclError:
pos = None
if not pos:
first = last = pos = text.index("insert")
line, col = SearchEngine.get_line_col(pos)
chars = text.get("%d.0" % line, "%d.0" % (line+1))
m = prog.match(chars, col)
if not prog:
return False
new = m.expand(self.replvar.get())
text.mark_set("insert", first)
text.undo_block_start()
if m.group():
text.delete(first, last)
if new:
text.insert(first, new)
text.undo_block_stop()
self.show_hit(first, text.index("insert"))
self.ok = 0
return True
def show_hit(self, first, last):
text = self.text
text.mark_set("insert", first)
text.tag_remove("sel", "1.0", "end")
text.tag_add("sel", first, last)
text.tag_remove("hit", "1.0", "end")
if first == last:
text.tag_add("hit", first)
else:
text.tag_add("hit", first, last)
text.see("insert")
text.update_idletasks()
def close(self, event=None):
SearchDialogBase.close(self, event)
self.text.tag_remove("hit", "1.0", "end")
| {
"content_hash": "d7c598115b5e3a3a735765c03a07b304",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 78,
"avg_line_length": 31.610778443113773,
"alnum_prop": 0.5004735745406327,
"repo_name": "ericlink/adms-server",
"id": "1f35414fb0575ed5efa76d3a06d075346f1a3ff9",
"size": "5279",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "playframework-dist/play-1.1/python/Lib/idlelib/ReplaceDialog.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "408"
},
{
"name": "C",
"bytes": "152256"
},
{
"name": "CSS",
"bytes": "97486"
},
{
"name": "HTML",
"bytes": "553901"
},
{
"name": "Java",
"bytes": "3086962"
},
{
"name": "JavaScript",
"bytes": "736134"
},
{
"name": "Python",
"bytes": "15750302"
},
{
"name": "SQLPL",
"bytes": "10111"
},
{
"name": "Scala",
"bytes": "1432"
},
{
"name": "Shell",
"bytes": "1369"
}
],
"symlink_target": ""
} |
"""Default variable filters."""
from __future__ import unicode_literals
import re
import random as random_module
from decimal import Decimal, InvalidOperation, Context, ROUND_HALF_UP
from functools import wraps
from pprint import pformat
import warnings
from django.template.base import Variable, Library, VariableDoesNotExist
from django.conf import settings
from django.utils import formats
from django.utils.dateformat import format, time_format
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.encoding import force_text, iri_to_uri
from django.utils.html import (conditional_escape, escapejs,
escape, urlize as _urlize, linebreaks, strip_tags, avoid_wrapping,
remove_tags)
from django.utils.http import urlquote
from django.utils.text import Truncator, wrap, phone2numeric
from django.utils.safestring import mark_safe, SafeData, mark_for_escaping
from django.utils import six
from django.utils.timesince import timesince, timeuntil
from django.utils.translation import ugettext, ungettext
from django.utils.text import normalize_newlines, slugify as _slugify
register = Library()
#######################
# STRING DECORATOR #
#######################
def stringfilter(func):
"""
Decorator for filters which should only receive unicode objects. The object
passed as the first positional argument will be converted to a unicode
object.
"""
def _dec(*args, **kwargs):
if args:
args = list(args)
args[0] = force_text(args[0])
if (isinstance(args[0], SafeData) and
getattr(_dec._decorated_function, 'is_safe', False)):
return mark_safe(func(*args, **kwargs))
return func(*args, **kwargs)
# Include a reference to the real function (used to check original
# arguments by the template parser, and to bear the 'is_safe' attribute
# when multiple decorators are applied).
_dec._decorated_function = getattr(func, '_decorated_function', func)
return wraps(func)(_dec)
###################
# STRINGS #
###################
@register.filter(is_safe=True)
@stringfilter
def addslashes(value):
"""
Adds slashes before quotes. Useful for escaping strings in CSV, for
example. Less useful for escaping JavaScript; use the ``escapejs``
filter instead.
"""
return value.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'")
@register.filter(is_safe=True)
@stringfilter
def capfirst(value):
"""Capitalizes the first character of the value."""
return value and value[0].upper() + value[1:]
@register.filter("escapejs")
@stringfilter
def escapejs_filter(value):
"""Hex encodes characters for use in JavaScript strings."""
return escapejs(value)
# Values for testing floatformat input against infinity and NaN representations,
# which differ across platforms and Python versions. Some (i.e. old Windows
# ones) are not recognized by Decimal but we want to return them unchanged vs.
# returning an empty string as we do for completely invalid input. Note these
# need to be built up from values that are not inf/nan, since inf/nan values do
# not reload properly from .pyc files on Windows prior to some level of Python 2.5
# (see Python Issue757815 and Issue1080440).
pos_inf = 1e200 * 1e200
neg_inf = -1e200 * 1e200
nan = (1e200 * 1e200) // (1e200 * 1e200)
special_floats = [str(pos_inf), str(neg_inf), str(nan)]
@register.filter(is_safe=True)
def floatformat(text, arg=-1):
"""
Displays a float to a specified number of decimal places.
If called without an argument, it displays the floating point number with
one decimal place -- but only if there's a decimal place to be displayed:
* num1 = 34.23234
* num2 = 34.00000
* num3 = 34.26000
* {{ num1|floatformat }} displays "34.2"
* {{ num2|floatformat }} displays "34"
* {{ num3|floatformat }} displays "34.3"
If arg is positive, it will always display exactly arg number of decimal
places:
* {{ num1|floatformat:3 }} displays "34.232"
* {{ num2|floatformat:3 }} displays "34.000"
* {{ num3|floatformat:3 }} displays "34.260"
If arg is negative, it will display arg number of decimal places -- but
only if there are places to be displayed:
* {{ num1|floatformat:"-3" }} displays "34.232"
* {{ num2|floatformat:"-3" }} displays "34"
* {{ num3|floatformat:"-3" }} displays "34.260"
If the input float is infinity or NaN, the (platform-dependent) string
representation of that value will be displayed.
"""
try:
input_val = force_text(text)
d = Decimal(input_val)
except UnicodeEncodeError:
return ''
except InvalidOperation:
if input_val in special_floats:
return input_val
try:
d = Decimal(force_text(float(text)))
except (ValueError, InvalidOperation, TypeError, UnicodeEncodeError):
return ''
try:
p = int(arg)
except ValueError:
return input_val
try:
m = int(d) - d
except (ValueError, OverflowError, InvalidOperation):
return input_val
if not m and p < 0:
return mark_safe(formats.number_format('%d' % (int(d)), 0))
if p == 0:
exp = Decimal(1)
else:
exp = Decimal('1.0') / (Decimal(10) ** abs(p))
try:
# Set the precision high enough to avoid an exception, see #15789.
tupl = d.as_tuple()
units = len(tupl[1]) - tupl[2]
prec = abs(p) + units + 1
# Avoid conversion to scientific notation by accessing `sign`, `digits`
# and `exponent` from `Decimal.as_tuple()` directly.
sign, digits, exponent = d.quantize(exp, ROUND_HALF_UP,
Context(prec=prec)).as_tuple()
digits = [six.text_type(digit) for digit in reversed(digits)]
while len(digits) <= abs(exponent):
digits.append('0')
digits.insert(-exponent, '.')
if sign:
digits.append('-')
number = ''.join(reversed(digits))
return mark_safe(formats.number_format(number, abs(p)))
except InvalidOperation:
return input_val
@register.filter(is_safe=True)
@stringfilter
def iriencode(value):
"""Escapes an IRI value for use in a URL."""
return force_text(iri_to_uri(value))
@register.filter(is_safe=True, needs_autoescape=True)
@stringfilter
def linenumbers(value, autoescape=None):
"""Displays text with line numbers."""
lines = value.split('\n')
# Find the maximum width of the line count, for use with zero padding
# string format command
width = six.text_type(len(six.text_type(len(lines))))
if not autoescape or isinstance(value, SafeData):
for i, line in enumerate(lines):
lines[i] = ("%0" + width + "d. %s") % (i + 1, line)
else:
for i, line in enumerate(lines):
lines[i] = ("%0" + width + "d. %s") % (i + 1, escape(line))
return mark_safe('\n'.join(lines))
@register.filter(is_safe=True)
@stringfilter
def lower(value):
"""Converts a string into all lowercase."""
return value.lower()
@register.filter(is_safe=False)
@stringfilter
def make_list(value):
"""
Returns the value turned into a list.
For an integer, it's a list of digits.
For a string, it's a list of characters.
"""
return list(value)
@register.filter(is_safe=True)
@stringfilter
def slugify(value):
"""
Converts to lowercase, removes non-word characters (alphanumerics and
underscores) and converts spaces to hyphens. Also strips leading and
trailing whitespace.
"""
return _slugify(value)
@register.filter(is_safe=True)
def stringformat(value, arg):
"""
Formats the variable according to the arg, a string formatting specifier.
This specifier uses Python string formating syntax, with the exception that
the leading "%" is dropped.
See http://docs.python.org/lib/typesseq-strings.html for documentation
of Python string formatting
"""
try:
return ("%" + six.text_type(arg)) % value
except (ValueError, TypeError):
return ""
@register.filter(is_safe=True)
@stringfilter
def title(value):
"""Converts a string into titlecase."""
t = re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title())
return re.sub("\d([A-Z])", lambda m: m.group(0).lower(), t)
@register.filter(is_safe=True)
@stringfilter
def truncatechars(value, arg):
"""
Truncates a string after a certain number of characters.
Argument: Number of characters to truncate after.
"""
try:
length = int(arg)
except ValueError: # Invalid literal for int().
return value # Fail silently.
return Truncator(value).chars(length)
@register.filter(is_safe=True)
@stringfilter
def truncatechars_html(value, arg):
"""
Truncates HTML after a certain number of chars.
Argument: Number of chars to truncate after.
Newlines in the HTML are preserved.
"""
try:
length = int(arg)
except ValueError: # invalid literal for int()
return value # Fail silently.
return Truncator(value).chars(length, html=True)
@register.filter(is_safe=True)
@stringfilter
def truncatewords(value, arg):
"""
Truncates a string after a certain number of words.
Argument: Number of words to truncate after.
Newlines within the string are removed.
"""
try:
length = int(arg)
except ValueError: # Invalid literal for int().
return value # Fail silently.
return Truncator(value).words(length, truncate=' ...')
@register.filter(is_safe=True)
@stringfilter
def truncatewords_html(value, arg):
"""
Truncates HTML after a certain number of words.
Argument: Number of words to truncate after.
Newlines in the HTML are preserved.
"""
try:
length = int(arg)
except ValueError: # invalid literal for int()
return value # Fail silently.
return Truncator(value).words(length, html=True, truncate=' ...')
@register.filter(is_safe=False)
@stringfilter
def upper(value):
"""Converts a string into all uppercase."""
return value.upper()
@register.filter(is_safe=False)
@stringfilter
def urlencode(value, safe=None):
"""
Escapes a value for use in a URL.
Takes an optional ``safe`` parameter used to determine the characters which
should not be escaped by Django's ``urlquote`` method. If not provided, the
default safe characters will be used (but an empty string can be provided
when *all* characters should be escaped).
"""
kwargs = {}
if safe is not None:
kwargs['safe'] = safe
return urlquote(value, **kwargs)
@register.filter(is_safe=True, needs_autoescape=True)
@stringfilter
def urlize(value, autoescape=None):
"""Converts URLs in plain text into clickable links."""
return mark_safe(_urlize(value, nofollow=True, autoescape=autoescape))
@register.filter(is_safe=True, needs_autoescape=True)
@stringfilter
def urlizetrunc(value, limit, autoescape=None):
"""
Converts URLs into clickable links, truncating URLs to the given character
limit, and adding 'rel=nofollow' attribute to discourage spamming.
Argument: Length to truncate URLs to.
"""
return mark_safe(_urlize(value, trim_url_limit=int(limit), nofollow=True,
autoescape=autoescape))
@register.filter(is_safe=False)
@stringfilter
def wordcount(value):
"""Returns the number of words."""
return len(value.split())
@register.filter(is_safe=True)
@stringfilter
def wordwrap(value, arg):
"""
Wraps words at specified line length.
Argument: number of characters to wrap the text at.
"""
return wrap(value, int(arg))
@register.filter(is_safe=True)
@stringfilter
def ljust(value, arg):
"""
Left-aligns the value in a field of a given width.
Argument: field size.
"""
return value.ljust(int(arg))
@register.filter(is_safe=True)
@stringfilter
def rjust(value, arg):
"""
Right-aligns the value in a field of a given width.
Argument: field size.
"""
return value.rjust(int(arg))
@register.filter(is_safe=True)
@stringfilter
def center(value, arg):
"""Centers the value in a field of a given width."""
return value.center(int(arg))
@register.filter
@stringfilter
def cut(value, arg):
"""
Removes all values of arg from the given string.
"""
safe = isinstance(value, SafeData)
value = value.replace(arg, '')
if safe and arg != ';':
return mark_safe(value)
return value
###################
# HTML STRINGS #
###################
@register.filter("escape", is_safe=True)
@stringfilter
def escape_filter(value):
"""
Marks the value as a string that should not be auto-escaped.
"""
return mark_for_escaping(value)
@register.filter(is_safe=True)
@stringfilter
def force_escape(value):
"""
Escapes a string's HTML. This returns a new string containing the escaped
characters (as opposed to "escape", which marks the content for later
possible escaping).
"""
return escape(value)
@register.filter("linebreaks", is_safe=True, needs_autoescape=True)
@stringfilter
def linebreaks_filter(value, autoescape=None):
"""
Replaces line breaks in plain text with appropriate HTML; a single
newline becomes an HTML line break (``<br />``) and a new line
followed by a blank line becomes a paragraph break (``</p>``).
"""
autoescape = autoescape and not isinstance(value, SafeData)
return mark_safe(linebreaks(value, autoescape))
@register.filter(is_safe=True, needs_autoescape=True)
@stringfilter
def linebreaksbr(value, autoescape=None):
"""
Converts all newlines in a piece of plain text to HTML line breaks
(``<br />``).
"""
autoescape = autoescape and not isinstance(value, SafeData)
value = normalize_newlines(value)
if autoescape:
value = escape(value)
return mark_safe(value.replace('\n', '<br />'))
@register.filter(is_safe=True)
@stringfilter
def safe(value):
"""
Marks the value as a string that should not be auto-escaped.
"""
return mark_safe(value)
@register.filter(is_safe=True)
def safeseq(value):
"""
A "safe" filter for sequences. Marks each element in the sequence,
individually, as safe, after converting them to unicode. Returns a list
with the results.
"""
return [mark_safe(force_text(obj)) for obj in value]
@register.filter(is_safe=True)
@stringfilter
def removetags(value, tags):
"""Removes a space separated list of [X]HTML tags from the output."""
return remove_tags(value, tags)
@register.filter(is_safe=True)
@stringfilter
def striptags(value):
"""Strips all [X]HTML tags."""
return strip_tags(value)
###################
# LISTS #
###################
@register.filter(is_safe=False)
def dictsort(value, arg):
"""
Takes a list of dicts, returns that list sorted by the property given in
the argument.
"""
try:
return sorted(value, key=Variable(arg).resolve)
except (TypeError, VariableDoesNotExist):
return ''
@register.filter(is_safe=False)
def dictsortreversed(value, arg):
"""
Takes a list of dicts, returns that list sorted in reverse order by the
property given in the argument.
"""
try:
return sorted(value, key=Variable(arg).resolve, reverse=True)
except (TypeError, VariableDoesNotExist):
return ''
@register.filter(is_safe=False)
def first(value):
"""Returns the first item in a list."""
try:
return value[0]
except IndexError:
return ''
@register.filter(is_safe=True, needs_autoescape=True)
def join(value, arg, autoescape=None):
"""
Joins a list with a string, like Python's ``str.join(list)``.
"""
value = map(force_text, value)
if autoescape:
value = [conditional_escape(v) for v in value]
try:
data = conditional_escape(arg).join(value)
except AttributeError: # fail silently but nicely
return value
return mark_safe(data)
@register.filter(is_safe=True)
def last(value):
"Returns the last item in a list"
try:
return value[-1]
except IndexError:
return ''
@register.filter(is_safe=False)
def length(value):
"""Returns the length of the value - useful for lists."""
try:
return len(value)
except (ValueError, TypeError):
return 0
@register.filter(is_safe=False)
def length_is(value, arg):
"""Returns a boolean of whether the value's length is the argument."""
try:
return len(value) == int(arg)
except (ValueError, TypeError):
return ''
@register.filter(is_safe=True)
def random(value):
"""Returns a random item from the list."""
return random_module.choice(value)
@register.filter("slice", is_safe=True)
def slice_filter(value, arg):
"""
Returns a slice of the list.
Uses the same syntax as Python's list slicing; see
http://www.diveintopython3.net/native-datatypes.html#slicinglists
for an introduction.
"""
try:
bits = []
for x in arg.split(':'):
if len(x) == 0:
bits.append(None)
else:
bits.append(int(x))
return value[slice(*bits)]
except (ValueError, TypeError):
return value # Fail silently.
@register.filter(is_safe=True, needs_autoescape=True)
def unordered_list(value, autoescape=None):
"""
Recursively takes a self-nested list and returns an HTML unordered list --
WITHOUT opening and closing <ul> tags.
The list is assumed to be in the proper format. For example, if ``var``
contains: ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``,
then ``{{ var|unordered_list }}`` would return::
<li>States
<ul>
<li>Kansas
<ul>
<li>Lawrence</li>
<li>Topeka</li>
</ul>
</li>
<li>Illinois</li>
</ul>
</li>
"""
if autoescape:
escaper = conditional_escape
else:
escaper = lambda x: x
def convert_old_style_list(list_):
"""
Converts old style lists to the new easier to understand format.
The old list format looked like:
['Item 1', [['Item 1.1', []], ['Item 1.2', []]]
And it is converted to:
['Item 1', ['Item 1.1', 'Item 1.2]]
"""
if not isinstance(list_, (tuple, list)) or len(list_) != 2:
return list_, False
first_item, second_item = list_
if second_item == []:
return [first_item], True
try:
# see if second item is iterable
iter(second_item)
except TypeError:
return list_, False
old_style_list = True
new_second_item = []
for sublist in second_item:
item, old_style_list = convert_old_style_list(sublist)
if not old_style_list:
break
new_second_item.extend(item)
if old_style_list:
second_item = new_second_item
return [first_item, second_item], old_style_list
def walk_items(item_list):
item_iterator = iter(item_list)
for item in item_iterator:
try:
next_item = next(item_iterator)
except StopIteration:
next_item = None
if not isinstance(next_item, six.string_types):
try:
iter(next_item)
except TypeError:
pass
else:
yield item, next_item
continue
yield item, None
if next_item:
yield next_item, None
def list_formatter(item_list, tabs=1):
indent = '\t' * tabs
output = []
for item, children in walk_items(item_list):
sublist = ''
if children:
sublist = '\n%s<ul>\n%s\n%s</ul>\n%s' % (
indent, list_formatter(children, tabs + 1), indent, indent)
output.append('%s<li>%s%s</li>' % (
indent, escaper(force_text(item)), sublist))
return '\n'.join(output)
value, converted = convert_old_style_list(value)
if converted:
warnings.warn(
"The old style syntax in `unordered_list` is deprecated and will "
"be removed in Django 2.0. Use the the new format instead.",
RemovedInDjango20Warning)
return mark_safe(list_formatter(value))
###################
# INTEGERS #
###################
@register.filter(is_safe=False)
def add(value, arg):
"""Adds the arg to the value."""
try:
return int(value) + int(arg)
except (ValueError, TypeError):
try:
return value + arg
except Exception:
return ''
@register.filter(is_safe=False)
def get_digit(value, arg):
"""
Given a whole number, returns the requested digit of it, where 1 is the
right-most digit, 2 is the second-right-most digit, etc. Returns the
original value for invalid input (if input or argument is not an integer,
or if argument is less than 1). Otherwise, output is always an integer.
"""
try:
arg = int(arg)
value = int(value)
except ValueError:
return value # Fail silently for an invalid argument
if arg < 1:
return value
try:
return int(str(value)[-arg])
except IndexError:
return 0
###################
# DATES #
###################
@register.filter(expects_localtime=True, is_safe=False)
def date(value, arg=None):
"""Formats a date according to the given format."""
if value in (None, ''):
return ''
if arg is None:
arg = settings.DATE_FORMAT
try:
return formats.date_format(value, arg)
except AttributeError:
try:
return format(value, arg)
except AttributeError:
return ''
@register.filter(expects_localtime=True, is_safe=False)
def time(value, arg=None):
"""Formats a time according to the given format."""
if value in (None, ''):
return ''
if arg is None:
arg = settings.TIME_FORMAT
try:
return formats.time_format(value, arg)
except AttributeError:
try:
return time_format(value, arg)
except AttributeError:
return ''
@register.filter("timesince", is_safe=False)
def timesince_filter(value, arg=None):
"""Formats a date as the time since that date (i.e. "4 days, 6 hours")."""
if not value:
return ''
try:
if arg:
return timesince(value, arg)
return timesince(value)
except (ValueError, TypeError):
return ''
@register.filter("timeuntil", is_safe=False)
def timeuntil_filter(value, arg=None):
"""Formats a date as the time until that date (i.e. "4 days, 6 hours")."""
if not value:
return ''
try:
return timeuntil(value, arg)
except (ValueError, TypeError):
return ''
###################
# LOGIC #
###################
@register.filter(is_safe=False)
def default(value, arg):
"""If value is unavailable, use given default."""
return value or arg
@register.filter(is_safe=False)
def default_if_none(value, arg):
"""If value is None, use given default."""
if value is None:
return arg
return value
@register.filter(is_safe=False)
def divisibleby(value, arg):
"""Returns True if the value is devisible by the argument."""
return int(value) % int(arg) == 0
@register.filter(is_safe=False)
def yesno(value, arg=None):
"""
Given a string mapping values for true, false and (optionally) None,
returns one of those strings according to the value:
========== ====================== ==================================
Value Argument Outputs
========== ====================== ==================================
``True`` ``"yeah,no,maybe"`` ``yeah``
``False`` ``"yeah,no,maybe"`` ``no``
``None`` ``"yeah,no,maybe"`` ``maybe``
``None`` ``"yeah,no"`` ``"no"`` (converts None to False
if no mapping for None is given.
========== ====================== ==================================
"""
if arg is None:
arg = ugettext('yes,no,maybe')
bits = arg.split(',')
if len(bits) < 2:
return value # Invalid arg.
try:
yes, no, maybe = bits
except ValueError:
# Unpack list of wrong size (no "maybe" value provided).
yes, no, maybe = bits[0], bits[1], bits[1]
if value is None:
return maybe
if value:
return yes
return no
###################
# MISC #
###################
@register.filter(is_safe=True)
def filesizeformat(bytes):
"""
Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
102 bytes, etc).
"""
try:
bytes = float(bytes)
except (TypeError, ValueError, UnicodeDecodeError):
value = ungettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0}
return avoid_wrapping(value)
filesize_number_format = lambda value: formats.number_format(round(value, 1), 1)
KB = 1 << 10
MB = 1 << 20
GB = 1 << 30
TB = 1 << 40
PB = 1 << 50
if bytes < KB:
value = ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes}
elif bytes < MB:
value = ugettext("%s KB") % filesize_number_format(bytes / KB)
elif bytes < GB:
value = ugettext("%s MB") % filesize_number_format(bytes / MB)
elif bytes < TB:
value = ugettext("%s GB") % filesize_number_format(bytes / GB)
elif bytes < PB:
value = ugettext("%s TB") % filesize_number_format(bytes / TB)
else:
value = ugettext("%s PB") % filesize_number_format(bytes / PB)
return avoid_wrapping(value)
@register.filter(is_safe=False)
def pluralize(value, arg='s'):
"""
Returns a plural suffix if the value is not 1. By default, 's' is used as
the suffix:
* If value is 0, vote{{ value|pluralize }} displays "0 votes".
* If value is 1, vote{{ value|pluralize }} displays "1 vote".
* If value is 2, vote{{ value|pluralize }} displays "2 votes".
If an argument is provided, that string is used instead:
* If value is 0, class{{ value|pluralize:"es" }} displays "0 classes".
* If value is 1, class{{ value|pluralize:"es" }} displays "1 class".
* If value is 2, class{{ value|pluralize:"es" }} displays "2 classes".
If the provided argument contains a comma, the text before the comma is
used for the singular case and the text after the comma is used for the
plural case:
* If value is 0, cand{{ value|pluralize:"y,ies" }} displays "0 candies".
* If value is 1, cand{{ value|pluralize:"y,ies" }} displays "1 candy".
* If value is 2, cand{{ value|pluralize:"y,ies" }} displays "2 candies".
"""
if ',' not in arg:
arg = ',' + arg
bits = arg.split(',')
if len(bits) > 2:
return ''
singular_suffix, plural_suffix = bits[:2]
try:
if float(value) != 1:
return plural_suffix
except ValueError: # Invalid string that's not a number.
pass
except TypeError: # Value isn't a string or a number; maybe it's a list?
try:
if len(value) != 1:
return plural_suffix
except TypeError: # len() of unsized object.
pass
return singular_suffix
@register.filter("phone2numeric", is_safe=True)
def phone2numeric_filter(value):
"""Takes a phone number and converts it in to its numerical equivalent."""
return phone2numeric(value)
@register.filter(is_safe=True)
def pprint(value):
"""A wrapper around pprint.pprint -- for debugging, really."""
try:
return pformat(value)
except Exception as e:
return "Error in formatting: %s: %s" % (e.__class__.__name__, force_text(e, errors="replace"))
| {
"content_hash": "b97db0597a7663f9570bafd907001bb7",
"timestamp": "",
"source": "github",
"line_count": 972,
"max_line_length": 102,
"avg_line_length": 29.17695473251029,
"alnum_prop": 0.6135049365303245,
"repo_name": "kswiat/django",
"id": "3e35e67bd0f2a3751e3328d1235a35c0fa978387",
"size": "28360",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "django/template/defaultfilters.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "53429"
},
{
"name": "JavaScript",
"bytes": "103526"
},
{
"name": "Python",
"bytes": "10026764"
},
{
"name": "Shell",
"bytes": "10452"
}
],
"symlink_target": ""
} |
"""Module for compiling codegen output, and wrap the binary for use in
python.
.. note:: To use the autowrap module it must first be imported
>>> from sympy.utilities.autowrap import autowrap
This module provides a common interface for different external backends, such
as f2py, fwrap, Cython, SWIG(?) etc. (Currently only f2py and Cython are
implemented) The goal is to provide access to compiled binaries of acceptable
performance with a one-button user interface, i.e.
>>> from sympy.abc import x,y
>>> expr = ((x - y)**(25)).expand()
>>> binary_callable = autowrap(expr)
>>> binary_callable(1, 2)
-1.0
The callable returned from autowrap() is a binary python function, not a
SymPy object. If it is desired to use the compiled function in symbolic
expressions, it is better to use binary_function() which returns a SymPy
Function object. The binary callable is attached as the _imp_ attribute and
invoked when a numerical evaluation is requested with evalf(), or with
lambdify().
>>> from sympy.utilities.autowrap import binary_function
>>> f = binary_function('f', expr)
>>> 2*f(x, y) + y
y + 2*f(x, y)
>>> (2*f(x, y) + y).evalf(2, subs={x: 1, y:2})
0.e-110
The idea is that a SymPy user will primarily be interested in working with
mathematical expressions, and should not have to learn details about wrapping
tools in order to evaluate expressions numerically, even if they are
computationally expensive.
When is this useful?
1) For computations on large arrays, Python iterations may be too slow,
and depending on the mathematical expression, it may be difficult to
exploit the advanced index operations provided by NumPy.
2) For *really* long expressions that will be called repeatedly, the
compiled binary should be significantly faster than SymPy's .evalf()
3) If you are generating code with the codegen utility in order to use
it in another project, the automatic python wrappers let you test the
binaries immediately from within SymPy.
4) To create customized ufuncs for use with numpy arrays.
See *ufuncify*.
When is this module NOT the best approach?
1) If you are really concerned about speed or memory optimizations,
you will probably get better results by working directly with the
wrapper tools and the low level code. However, the files generated
by this utility may provide a useful starting point and reference
code. Temporary files will be left intact if you supply the keyword
tempdir="path/to/files/".
2) If the array computation can be handled easily by numpy, and you
don't need the binaries for another project.
"""
from __future__ import print_function, division
import sys
import os
import shutil
import tempfile
from subprocess import STDOUT, CalledProcessError, check_output
from string import Template
from warnings import warn
from sympy.core.cache import cacheit
from sympy.core.compatibility import range, iterable
from sympy.core.function import Lambda
from sympy.core.relational import Eq
from sympy.core.symbol import Dummy, Symbol
from sympy.tensor.indexed import Idx, IndexedBase
from sympy.utilities.codegen import (make_routine, get_code_generator,
OutputArgument, InOutArgument,
InputArgument, CodeGenArgumentListError,
Result, ResultBase, C99CodeGen)
from sympy.utilities.lambdify import implemented_function
from sympy.utilities.decorator import doctest_depends_on
_doctest_depends_on = {'exe': ('f2py', 'gfortran', 'gcc'),
'modules': ('numpy',)}
class CodeWrapError(Exception):
pass
class CodeWrapper(object):
"""Base Class for code wrappers"""
_filename = "wrapped_code"
_module_basename = "wrapper_module"
_module_counter = 0
@property
def filename(self):
return "%s_%s" % (self._filename, CodeWrapper._module_counter)
@property
def module_name(self):
return "%s_%s" % (self._module_basename, CodeWrapper._module_counter)
def __init__(self, generator, filepath=None, flags=[], verbose=False):
"""
generator -- the code generator to use
"""
self.generator = generator
self.filepath = filepath
self.flags = flags
self.quiet = not verbose
@property
def include_header(self):
return bool(self.filepath)
@property
def include_empty(self):
return bool(self.filepath)
def _generate_code(self, main_routine, routines):
routines.append(main_routine)
self.generator.write(
routines, self.filename, True, self.include_header,
self.include_empty)
def wrap_code(self, routine, helpers=None):
helpers = helpers or []
if self.filepath:
workdir = os.path.abspath(self.filepath)
else:
workdir = tempfile.mkdtemp("_sympy_compile")
if not os.access(workdir, os.F_OK):
os.mkdir(workdir)
oldwork = os.getcwd()
os.chdir(workdir)
try:
sys.path.append(workdir)
self._generate_code(routine, helpers)
self._prepare_files(routine)
self._process_files(routine)
mod = __import__(self.module_name)
finally:
sys.path.remove(workdir)
CodeWrapper._module_counter += 1
os.chdir(oldwork)
if not self.filepath:
try:
shutil.rmtree(workdir)
except OSError:
# Could be some issues on Windows
pass
return self._get_wrapped_function(mod, routine.name)
def _process_files(self, routine):
command = self.command
command.extend(self.flags)
try:
retoutput = check_output(command, stderr=STDOUT)
except CalledProcessError as e:
raise CodeWrapError(
"Error while executing command: %s. Command output is:\n%s" % (
" ".join(command), e.output.decode('utf-8')))
if not self.quiet:
print(retoutput)
class DummyWrapper(CodeWrapper):
"""Class used for testing independent of backends """
template = """# dummy module for testing of SymPy
def %(name)s():
return "%(expr)s"
%(name)s.args = "%(args)s"
%(name)s.returns = "%(retvals)s"
"""
def _prepare_files(self, routine):
return
def _generate_code(self, routine, helpers):
with open('%s.py' % self.module_name, 'w') as f:
printed = ", ".join(
[str(res.expr) for res in routine.result_variables])
# convert OutputArguments to return value like f2py
args = filter(lambda x: not isinstance(
x, OutputArgument), routine.arguments)
retvals = []
for val in routine.result_variables:
if isinstance(val, Result):
retvals.append('nameless')
else:
retvals.append(val.result_var)
print(DummyWrapper.template % {
'name': routine.name,
'expr': printed,
'args': ", ".join([str(a.name) for a in args]),
'retvals': ", ".join([str(val) for val in retvals])
}, end="", file=f)
def _process_files(self, routine):
return
@classmethod
def _get_wrapped_function(cls, mod, name):
return getattr(mod, name)
class CythonCodeWrapper(CodeWrapper):
"""Wrapper that uses Cython"""
setup_template = """\
try:
from setuptools import setup
from setuptools import Extension
except ImportError:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
cy_opts = {cythonize_options}
{np_import}
ext_mods = [Extension(
{ext_args},
include_dirs={include_dirs},
library_dirs={library_dirs},
libraries={libraries},
extra_compile_args={extra_compile_args},
extra_link_args={extra_link_args}
)]
setup(ext_modules=cythonize(ext_mods, **cy_opts))
"""
pyx_imports = (
"import numpy as np\n"
"cimport numpy as np\n\n")
pyx_header = (
"cdef extern from '{header_file}.h':\n"
" {prototype}\n\n")
pyx_func = (
"def {name}_c({arg_string}):\n"
"\n"
"{declarations}"
"{body}")
std_compile_flag = '-std=c99'
def __init__(self, *args, **kwargs):
"""Instantiates a Cython code wrapper.
The following optional parameters get passed to ``distutils.Extension``
for building the Python extension module. Read its documentation to
learn more.
Parameters
==========
include_dirs : [list of strings]
A list of directories to search for C/C++ header files (in Unix
form for portability).
library_dirs : [list of strings]
A list of directories to search for C/C++ libraries at link time.
libraries : [list of strings]
A list of library names (not filenames or paths) to link against.
extra_compile_args : [list of strings]
Any extra platform- and compiler-specific information to use when
compiling the source files in 'sources'. For platforms and
compilers where "command line" makes sense, this is typically a
list of command-line arguments, but for other platforms it could be
anything. Note that the attribute ``std_compile_flag`` will be
appended to this list.
extra_link_args : [list of strings]
Any extra platform- and compiler-specific information to use when
linking object files together to create the extension (or to create
a new static Python interpreter). Similar interpretation as for
'extra_compile_args'.
cythonize_options : [dictionary]
Keyword arguments passed on to cythonize.
"""
self._include_dirs = kwargs.pop('include_dirs', [])
self._library_dirs = kwargs.pop('library_dirs', [])
self._libraries = kwargs.pop('libraries', [])
self._extra_compile_args = kwargs.pop('extra_compile_args', [])
self._extra_compile_args.append(self.std_compile_flag)
self._extra_link_args = kwargs.pop('extra_link_args', [])
self._cythonize_options = kwargs.pop('cythonize_options', {})
self._need_numpy = False
super(CythonCodeWrapper, self).__init__(*args, **kwargs)
@property
def command(self):
command = [sys.executable, "setup.py", "build_ext", "--inplace"]
return command
def _prepare_files(self, routine, build_dir=os.curdir):
# NOTE : build_dir is used for testing purposes.
pyxfilename = self.module_name + '.pyx'
codefilename = "%s.%s" % (self.filename, self.generator.code_extension)
# pyx
with open(os.path.join(build_dir, pyxfilename), 'w') as f:
self.dump_pyx([routine], f, self.filename)
# setup.py
ext_args = [repr(self.module_name), repr([pyxfilename, codefilename])]
if self._need_numpy:
np_import = 'import numpy as np\n'
self._include_dirs.append('np.get_include()')
else:
np_import = ''
with open(os.path.join(build_dir, 'setup.py'), 'w') as f:
includes = str(self._include_dirs).replace("'np.get_include()'",
'np.get_include()')
f.write(self.setup_template.format(
ext_args=", ".join(ext_args),
np_import=np_import,
include_dirs=includes,
library_dirs=self._library_dirs,
libraries=self._libraries,
extra_compile_args=self._extra_compile_args,
extra_link_args=self._extra_link_args,
cythonize_options=self._cythonize_options
))
@classmethod
def _get_wrapped_function(cls, mod, name):
return getattr(mod, name + '_c')
def dump_pyx(self, routines, f, prefix):
"""Write a Cython file with python wrappers
This file contains all the definitions of the routines in c code and
refers to the header file.
Arguments
---------
routines
List of Routine instances
f
File-like object to write the file to
prefix
The filename prefix, used to refer to the proper header file.
Only the basename of the prefix is used.
"""
headers = []
functions = []
for routine in routines:
prototype = self.generator.get_prototype(routine)
# C Function Header Import
headers.append(self.pyx_header.format(header_file=prefix,
prototype=prototype))
# Partition the C function arguments into categories
py_rets, py_args, py_loc, py_inf = self._partition_args(routine.arguments)
# Function prototype
name = routine.name
arg_string = ", ".join(self._prototype_arg(arg) for arg in py_args)
# Local Declarations
local_decs = []
for arg, val in py_inf.items():
proto = self._prototype_arg(arg)
mat, ind = [self._string_var(v) for v in val]
local_decs.append(" cdef {0} = {1}.shape[{2}]".format(proto, mat, ind))
local_decs.extend([" cdef {0}".format(self._declare_arg(a)) for a in py_loc])
declarations = "\n".join(local_decs)
if declarations:
declarations = declarations + "\n"
# Function Body
args_c = ", ".join([self._call_arg(a) for a in routine.arguments])
rets = ", ".join([self._string_var(r.name) for r in py_rets])
if routine.results:
body = ' return %s(%s)' % (routine.name, args_c)
if rets:
body = body + ', ' + rets
else:
body = ' %s(%s)\n' % (routine.name, args_c)
body = body + ' return ' + rets
functions.append(self.pyx_func.format(name=name, arg_string=arg_string,
declarations=declarations, body=body))
# Write text to file
if self._need_numpy:
# Only import numpy if required
f.write(self.pyx_imports)
f.write('\n'.join(headers))
f.write('\n'.join(functions))
def _partition_args(self, args):
"""Group function arguments into categories."""
py_args = []
py_returns = []
py_locals = []
py_inferred = {}
for arg in args:
if isinstance(arg, OutputArgument):
py_returns.append(arg)
py_locals.append(arg)
elif isinstance(arg, InOutArgument):
py_returns.append(arg)
py_args.append(arg)
else:
py_args.append(arg)
# Find arguments that are array dimensions. These can be inferred
# locally in the Cython code.
if isinstance(arg, (InputArgument, InOutArgument)) and arg.dimensions:
dims = [d[1] + 1 for d in arg.dimensions]
sym_dims = [(i, d) for (i, d) in enumerate(dims) if
isinstance(d, Symbol)]
for (i, d) in sym_dims:
py_inferred[d] = (arg.name, i)
for arg in args:
if arg.name in py_inferred:
py_inferred[arg] = py_inferred.pop(arg.name)
# Filter inferred arguments from py_args
py_args = [a for a in py_args if a not in py_inferred]
return py_returns, py_args, py_locals, py_inferred
def _prototype_arg(self, arg):
mat_dec = "np.ndarray[{mtype}, ndim={ndim}] {name}"
np_types = {'double': 'np.double_t',
'int': 'np.int_t'}
t = arg.get_datatype('c')
if arg.dimensions:
self._need_numpy = True
ndim = len(arg.dimensions)
mtype = np_types[t]
return mat_dec.format(mtype=mtype, ndim=ndim, name=self._string_var(arg.name))
else:
return "%s %s" % (t, self._string_var(arg.name))
def _declare_arg(self, arg):
proto = self._prototype_arg(arg)
if arg.dimensions:
shape = '(' + ','.join(self._string_var(i[1] + 1) for i in arg.dimensions) + ')'
return proto + " = np.empty({shape})".format(shape=shape)
else:
return proto + " = 0"
def _call_arg(self, arg):
if arg.dimensions:
t = arg.get_datatype('c')
return "<{0}*> {1}.data".format(t, self._string_var(arg.name))
elif isinstance(arg, ResultBase):
return "&{0}".format(self._string_var(arg.name))
else:
return self._string_var(arg.name)
def _string_var(self, var):
printer = self.generator.printer.doprint
return printer(var)
class F2PyCodeWrapper(CodeWrapper):
"""Wrapper that uses f2py"""
def __init__(self, *args, **kwargs):
ext_keys = ['include_dirs', 'library_dirs', 'libraries',
'extra_compile_args', 'extra_link_args']
msg = ('The compilation option kwarg {} is not supported with the f2py '
'backend.')
for k in ext_keys:
if k in kwargs.keys():
warn(msg.format(k))
kwargs.pop(k, None)
super(F2PyCodeWrapper, self).__init__(*args, **kwargs)
@property
def command(self):
filename = self.filename + '.' + self.generator.code_extension
args = ['-c', '-m', self.module_name, filename]
command = [sys.executable, "-c", "import numpy.f2py as f2py2e;f2py2e.main()"]+args
return command
def _prepare_files(self, routine):
pass
@classmethod
def _get_wrapped_function(cls, mod, name):
return getattr(mod, name)
# Here we define a lookup of backends -> tuples of languages. For now, each
# tuple is of length 1, but if a backend supports more than one language,
# the most preferable language is listed first.
_lang_lookup = {'CYTHON': ('C99', 'C89', 'C'),
'F2PY': ('F95',),
'NUMPY': ('C99', 'C89', 'C'),
'DUMMY': ('F95',)} # Dummy here just for testing
def _infer_language(backend):
"""For a given backend, return the top choice of language"""
langs = _lang_lookup.get(backend.upper(), False)
if not langs:
raise ValueError("Unrecognized backend: " + backend)
return langs[0]
def _validate_backend_language(backend, language):
"""Throws error if backend and language are incompatible"""
langs = _lang_lookup.get(backend.upper(), False)
if not langs:
raise ValueError("Unrecognized backend: " + backend)
if language.upper() not in langs:
raise ValueError(("Backend {0} and language {1} are "
"incompatible").format(backend, language))
@cacheit
@doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',))
def autowrap(expr, language=None, backend='f2py', tempdir=None, args=None,
flags=None, verbose=False, helpers=None, code_gen=None, **kwargs):
"""Generates python callable binaries based on the math expression.
Parameters
==========
expr
The SymPy expression that should be wrapped as a binary routine.
language : string, optional
If supplied, (options: 'C' or 'F95'), specifies the language of the
generated code. If ``None`` [default], the language is inferred based
upon the specified backend.
backend : string, optional
Backend used to wrap the generated code. Either 'f2py' [default],
or 'cython'.
tempdir : string, optional
Path to directory for temporary files. If this argument is supplied,
the generated code and the wrapper input files are left intact in the
specified path.
args : iterable, optional
An ordered iterable of symbols. Specifies the argument sequence for the
function.
flags : iterable, optional
Additional option flags that will be passed to the backend.
verbose : bool, optional
If True, autowrap will not mute the command line backends. This can be
helpful for debugging.
helpers : 3-tuple or iterable of 3-tuples, optional
Used to define auxiliary expressions needed for the main expr. If the
main expression needs to call a specialized function it should be
passed in via ``helpers``. Autowrap will then make sure that the
compiled main expression can link to the helper routine. Items should
be 3-tuples with (<function_name>, <sympy_expression>,
<argument_tuple>). It is mandatory to supply an argument sequence to
helper routines.
code_gen : CodeGen instance
An instance of a CodeGen subclass. Overrides ``language``.
include_dirs : [string]
A list of directories to search for C/C++ header files (in Unix form
for portability).
library_dirs : [string]
A list of directories to search for C/C++ libraries at link time.
libraries : [string]
A list of library names (not filenames or paths) to link against.
extra_compile_args : [string]
Any extra platform- and compiler-specific information to use when
compiling the source files in 'sources'. For platforms and compilers
where "command line" makes sense, this is typically a list of
command-line arguments, but for other platforms it could be anything.
extra_link_args : [string]
Any extra platform- and compiler-specific information to use when
linking object files together to create the extension (or to create a
new static Python interpreter). Similar interpretation as for
'extra_compile_args'.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.utilities.autowrap import autowrap
>>> expr = ((x - y + z)**(13)).expand()
>>> binary_func = autowrap(expr)
>>> binary_func(1, 4, 2)
-1.0
"""
if language:
if not isinstance(language, type):
_validate_backend_language(backend, language)
else:
language = _infer_language(backend)
# two cases 1) helpers is an iterable of 3-tuples and 2) helpers is a
# 3-tuple
if iterable(helpers) and len(helpers) != 0 and iterable(helpers[0]):
helpers = helpers if helpers else ()
else:
helpers = [helpers] if helpers else ()
args = list(args) if iterable(args, exclude=set) else args
if code_gen is None:
code_gen = get_code_generator(language, "autowrap")
CodeWrapperClass = {
'F2PY': F2PyCodeWrapper,
'CYTHON': CythonCodeWrapper,
'DUMMY': DummyWrapper
}[backend.upper()]
code_wrapper = CodeWrapperClass(code_gen, tempdir, flags if flags else (),
verbose, **kwargs)
helps = []
for name_h, expr_h, args_h in helpers:
helps.append(code_gen.routine(name_h, expr_h, args_h))
for name_h, expr_h, args_h in helpers:
if expr.has(expr_h):
name_h = binary_function(name_h, expr_h, backend='dummy')
expr = expr.subs(expr_h, name_h(*args_h))
try:
routine = code_gen.routine('autofunc', expr, args)
except CodeGenArgumentListError as e:
# if all missing arguments are for pure output, we simply attach them
# at the end and try again, because the wrappers will silently convert
# them to return values anyway.
new_args = []
for missing in e.missing_args:
if not isinstance(missing, OutputArgument):
raise
new_args.append(missing.name)
routine = code_gen.routine('autofunc', expr, args + new_args)
return code_wrapper.wrap_code(routine, helpers=helps)
@doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',))
def binary_function(symfunc, expr, **kwargs):
"""Returns a sympy function with expr as binary implementation
This is a convenience function that automates the steps needed to
autowrap the SymPy expression and attaching it to a Function object
with implemented_function().
Parameters
==========
symfunc : sympy Function
The function to bind the callable to.
expr : sympy Expression
The expression used to generate the function.
kwargs : dict
Any kwargs accepted by autowrap.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.utilities.autowrap import binary_function
>>> expr = ((x - y)**(25)).expand()
>>> f = binary_function('f', expr)
>>> type(f)
<class 'sympy.core.function.UndefinedFunction'>
>>> 2*f(x, y)
2*f(x, y)
>>> f(x, y).evalf(2, subs={x: 1, y: 2})
-1.0
"""
binary = autowrap(expr, **kwargs)
return implemented_function(symfunc, binary)
#################################################################
# UFUNCIFY #
#################################################################
_ufunc_top = Template("""\
#include "Python.h"
#include "math.h"
#include "numpy/ndarraytypes.h"
#include "numpy/ufuncobject.h"
#include "numpy/halffloat.h"
#include ${include_file}
static PyMethodDef ${module}Methods[] = {
{NULL, NULL, 0, NULL}
};""")
_ufunc_outcalls = Template("*((double *)out${outnum}) = ${funcname}(${call_args});")
_ufunc_body = Template("""\
static void ${funcname}_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data)
{
npy_intp i;
npy_intp n = dimensions[0];
${declare_args}
${declare_steps}
for (i = 0; i < n; i++) {
${outcalls}
${step_increments}
}
}
PyUFuncGenericFunction ${funcname}_funcs[1] = {&${funcname}_ufunc};
static char ${funcname}_types[${n_types}] = ${types}
static void *${funcname}_data[1] = {NULL};""")
_ufunc_bottom = Template("""\
#if PY_VERSION_HEX >= 0x03000000
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"${module}",
NULL,
-1,
${module}Methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC PyInit_${module}(void)
{
PyObject *m, *d;
${function_creation}
m = PyModule_Create(&moduledef);
if (!m) {
return NULL;
}
import_array();
import_umath();
d = PyModule_GetDict(m);
${ufunc_init}
return m;
}
#else
PyMODINIT_FUNC init${module}(void)
{
PyObject *m, *d;
${function_creation}
m = Py_InitModule("${module}", ${module}Methods);
if (m == NULL) {
return;
}
import_array();
import_umath();
d = PyModule_GetDict(m);
${ufunc_init}
}
#endif\
""")
_ufunc_init_form = Template("""\
ufunc${ind} = PyUFunc_FromFuncAndData(${funcname}_funcs, ${funcname}_data, ${funcname}_types, 1, ${n_in}, ${n_out},
PyUFunc_None, "${module}", ${docstring}, 0);
PyDict_SetItemString(d, "${funcname}", ufunc${ind});
Py_DECREF(ufunc${ind});""")
_ufunc_setup = Template("""\
def configuration(parent_package='', top_path=None):
import numpy
from numpy.distutils.misc_util import Configuration
config = Configuration('',
parent_package,
top_path)
config.add_extension('${module}', sources=['${module}.c', '${filename}.c'])
return config
if __name__ == "__main__":
from numpy.distutils.core import setup
setup(configuration=configuration)""")
class UfuncifyCodeWrapper(CodeWrapper):
"""Wrapper for Ufuncify"""
def __init__(self, *args, **kwargs):
ext_keys = ['include_dirs', 'library_dirs', 'libraries',
'extra_compile_args', 'extra_link_args']
msg = ('The compilation option kwarg {} is not supported with the numpy'
' backend.')
for k in ext_keys:
if k in kwargs.keys():
warn(msg.format(k))
kwargs.pop(k, None)
super(UfuncifyCodeWrapper, self).__init__(*args, **kwargs)
@property
def command(self):
command = [sys.executable, "setup.py", "build_ext", "--inplace"]
return command
def wrap_code(self, routines, helpers=None):
# This routine overrides CodeWrapper because we can't assume funcname == routines[0].name
# Therefore we have to break the CodeWrapper private API.
# There isn't an obvious way to extend multi-expr support to
# the other autowrap backends, so we limit this change to ufuncify.
helpers = helpers if helpers is not None else []
# We just need a consistent name
funcname = 'wrapped_' + str(id(routines) + id(helpers))
workdir = self.filepath or tempfile.mkdtemp("_sympy_compile")
if not os.access(workdir, os.F_OK):
os.mkdir(workdir)
oldwork = os.getcwd()
os.chdir(workdir)
try:
sys.path.append(workdir)
self._generate_code(routines, helpers)
self._prepare_files(routines, funcname)
self._process_files(routines)
mod = __import__(self.module_name)
finally:
sys.path.remove(workdir)
CodeWrapper._module_counter += 1
os.chdir(oldwork)
if not self.filepath:
try:
shutil.rmtree(workdir)
except OSError:
# Could be some issues on Windows
pass
return self._get_wrapped_function(mod, funcname)
def _generate_code(self, main_routines, helper_routines):
all_routines = main_routines + helper_routines
self.generator.write(
all_routines, self.filename, True, self.include_header,
self.include_empty)
def _prepare_files(self, routines, funcname):
# C
codefilename = self.module_name + '.c'
with open(codefilename, 'w') as f:
self.dump_c(routines, f, self.filename, funcname=funcname)
# setup.py
with open('setup.py', 'w') as f:
self.dump_setup(f)
@classmethod
def _get_wrapped_function(cls, mod, name):
return getattr(mod, name)
def dump_setup(self, f):
setup = _ufunc_setup.substitute(module=self.module_name,
filename=self.filename)
f.write(setup)
def dump_c(self, routines, f, prefix, funcname=None):
"""Write a C file with python wrappers
This file contains all the definitions of the routines in c code.
Arguments
---------
routines
List of Routine instances
f
File-like object to write the file to
prefix
The filename prefix, used to name the imported module.
funcname
Name of the main function to be returned.
"""
if funcname is None:
if len(routines) == 1:
funcname = routines[0].name
else:
msg = 'funcname must be specified for multiple output routines'
raise ValueError(msg)
functions = []
function_creation = []
ufunc_init = []
module = self.module_name
include_file = "\"{0}.h\"".format(prefix)
top = _ufunc_top.substitute(include_file=include_file, module=module)
name = funcname
# Partition the C function arguments into categories
# Here we assume all routines accept the same arguments
r_index = 0
py_in, _ = self._partition_args(routines[0].arguments)
n_in = len(py_in)
n_out = len(routines)
# Declare Args
form = "char *{0}{1} = args[{2}];"
arg_decs = [form.format('in', i, i) for i in range(n_in)]
arg_decs.extend([form.format('out', i, i+n_in) for i in range(n_out)])
declare_args = '\n '.join(arg_decs)
# Declare Steps
form = "npy_intp {0}{1}_step = steps[{2}];"
step_decs = [form.format('in', i, i) for i in range(n_in)]
step_decs.extend([form.format('out', i, i+n_in) for i in range(n_out)])
declare_steps = '\n '.join(step_decs)
# Call Args
form = "*(double *)in{0}"
call_args = ', '.join([form.format(a) for a in range(n_in)])
# Step Increments
form = "{0}{1} += {0}{1}_step;"
step_incs = [form.format('in', i) for i in range(n_in)]
step_incs.extend([form.format('out', i, i) for i in range(n_out)])
step_increments = '\n '.join(step_incs)
# Types
n_types = n_in + n_out
types = "{" + ', '.join(["NPY_DOUBLE"]*n_types) + "};"
# Docstring
docstring = '"Created in SymPy with Ufuncify"'
# Function Creation
function_creation.append("PyObject *ufunc{0};".format(r_index))
# Ufunc initialization
init_form = _ufunc_init_form.substitute(module=module,
funcname=name,
docstring=docstring,
n_in=n_in, n_out=n_out,
ind=r_index)
ufunc_init.append(init_form)
outcalls = [_ufunc_outcalls.substitute(
outnum=i, call_args=call_args, funcname=routines[i].name) for i in
range(n_out)]
body = _ufunc_body.substitute(module=module, funcname=name,
declare_args=declare_args,
declare_steps=declare_steps,
call_args=call_args,
step_increments=step_increments,
n_types=n_types, types=types,
outcalls='\n '.join(outcalls))
functions.append(body)
body = '\n\n'.join(functions)
ufunc_init = '\n '.join(ufunc_init)
function_creation = '\n '.join(function_creation)
bottom = _ufunc_bottom.substitute(module=module,
ufunc_init=ufunc_init,
function_creation=function_creation)
text = [top, body, bottom]
f.write('\n\n'.join(text))
def _partition_args(self, args):
"""Group function arguments into categories."""
py_in = []
py_out = []
for arg in args:
if isinstance(arg, OutputArgument):
py_out.append(arg)
elif isinstance(arg, InOutArgument):
raise ValueError("Ufuncify doesn't support InOutArguments")
else:
py_in.append(arg)
return py_in, py_out
@cacheit
@doctest_depends_on(exe=('f2py', 'gfortran', 'gcc'), modules=('numpy',))
def ufuncify(args, expr, language=None, backend='numpy', tempdir=None,
flags=None, verbose=False, helpers=None, **kwargs):
"""Generates a binary function that supports broadcasting on numpy arrays.
Parameters
==========
args : iterable
Either a Symbol or an iterable of symbols. Specifies the argument
sequence for the function.
expr
A SymPy expression that defines the element wise operation.
language : string, optional
If supplied, (options: 'C' or 'F95'), specifies the language of the
generated code. If ``None`` [default], the language is inferred based
upon the specified backend.
backend : string, optional
Backend used to wrap the generated code. Either 'numpy' [default],
'cython', or 'f2py'.
tempdir : string, optional
Path to directory for temporary files. If this argument is supplied,
the generated code and the wrapper input files are left intact in
the specified path.
flags : iterable, optional
Additional option flags that will be passed to the backend.
verbose : bool, optional
If True, autowrap will not mute the command line backends. This can
be helpful for debugging.
helpers : iterable, optional
Used to define auxiliary expressions needed for the main expr. If
the main expression needs to call a specialized function it should
be put in the ``helpers`` iterable. Autowrap will then make sure
that the compiled main expression can link to the helper routine.
Items should be tuples with (<funtion_name>, <sympy_expression>,
<arguments>). It is mandatory to supply an argument sequence to
helper routines.
kwargs : dict
These kwargs will be passed to autowrap if the `f2py` or `cython`
backend is used and ignored if the `numpy` backend is used.
Notes
=====
The default backend ('numpy') will create actual instances of
``numpy.ufunc``. These support ndimensional broadcasting, and implicit type
conversion. Use of the other backends will result in a "ufunc-like"
function, which requires equal length 1-dimensional arrays for all
arguments, and will not perform any type conversions.
References
==========
.. [1] http://docs.scipy.org/doc/numpy/reference/ufuncs.html
Examples
========
>>> from sympy.utilities.autowrap import ufuncify
>>> from sympy.abc import x, y
>>> import numpy as np
>>> f = ufuncify((x, y), y + x**2)
>>> type(f)
<class 'numpy.ufunc'>
>>> f([1, 2, 3], 2)
array([ 3., 6., 11.])
>>> f(np.arange(5), 3)
array([ 3., 4., 7., 12., 19.])
For the 'f2py' and 'cython' backends, inputs are required to be equal length
1-dimensional arrays. The 'f2py' backend will perform type conversion, but
the Cython backend will error if the inputs are not of the expected type.
>>> f_fortran = ufuncify((x, y), y + x**2, backend='f2py')
>>> f_fortran(1, 2)
array([ 3.])
>>> f_fortran(np.array([1, 2, 3]), np.array([1.0, 2.0, 3.0]))
array([ 2., 6., 12.])
>>> f_cython = ufuncify((x, y), y + x**2, backend='Cython')
>>> f_cython(1, 2) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: Argument '_x' has incorrect type (expected numpy.ndarray, got int)
>>> f_cython(np.array([1.0]), np.array([2.0]))
array([ 3.])
"""
if isinstance(args, Symbol):
args = (args,)
else:
args = tuple(args)
if language:
_validate_backend_language(backend, language)
else:
language = _infer_language(backend)
helpers = helpers if helpers else ()
flags = flags if flags else ()
if backend.upper() == 'NUMPY':
# maxargs is set by numpy compile-time constant NPY_MAXARGS
# If a future version of numpy modifies or removes this restriction
# this variable should be changed or removed
maxargs = 32
helps = []
for name, expr, args in helpers:
helps.append(make_routine(name, expr, args))
code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify"), tempdir,
flags, verbose)
if not isinstance(expr, (list, tuple)):
expr = [expr]
if len(expr) == 0:
raise ValueError('Expression iterable has zero length')
if len(expr) + len(args) > maxargs:
msg = ('Cannot create ufunc with more than {0} total arguments: '
'got {1} in, {2} out')
raise ValueError(msg.format(maxargs, len(args), len(expr)))
routines = [make_routine('autofunc{}'.format(idx), exprx, args) for
idx, exprx in enumerate(expr)]
return code_wrapper.wrap_code(routines, helpers=helps)
else:
# Dummies are used for all added expressions to prevent name clashes
# within the original expression.
y = IndexedBase(Dummy('y'))
m = Dummy('m', integer=True)
i = Idx(Dummy('i', integer=True), m)
f_dummy = Dummy('f')
f = implemented_function('%s_%d' % (f_dummy.name, f_dummy.dummy_index), Lambda(args, expr))
# For each of the args create an indexed version.
indexed_args = [IndexedBase(Dummy(str(a))) for a in args]
# Order the arguments (out, args, dim)
args = [y] + indexed_args + [m]
args_with_indices = [a[i] for a in indexed_args]
return autowrap(Eq(y[i], f(*args_with_indices)), language, backend,
tempdir, args, flags, verbose, helpers, **kwargs)
| {
"content_hash": "5494870a1b3cb6f88c05f22a560ddcac",
"timestamp": "",
"source": "github",
"line_count": 1121,
"max_line_length": 115,
"avg_line_length": 36.570026761819804,
"alnum_prop": 0.587169166971582,
"repo_name": "kaushik94/sympy",
"id": "bd6afb12d13b85cefa488fab2da5e08cb5790462",
"size": "40995",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sympy/utilities/autowrap.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Makefile",
"bytes": "5094"
},
{
"name": "Python",
"bytes": "13553568"
},
{
"name": "Ruby",
"bytes": "304"
},
{
"name": "Scheme",
"bytes": "125"
},
{
"name": "Shell",
"bytes": "4008"
},
{
"name": "TeX",
"bytes": "32356"
},
{
"name": "XSLT",
"bytes": "366202"
}
],
"symlink_target": ""
} |
"""An MNIST example using the Adam optimizer and lookahead wrapper."""
import functools
from absl import app
import jax
from jax import random
import jax.numpy as jnp
import optax
# pylint: disable=g-bad-import-order
import datasets # Located in the examples folder.
import mnist # Located in the examples folder.
# pylint: enable=g-bad-import-order
LEARNING_RATE = 0.002
SLOW_LEARNING_RATE = 0.5
SYNC_PERIOD = 5
HIDDEN_SIZES = (1000, 1000)
BATCH_SIZE = 128
N_EPOCHS = 5
SEED = 1
def main(unused_argv) -> None:
train_dataset = datasets.load_image_dataset('mnist', BATCH_SIZE)
test_dataset = datasets.load_image_dataset('mnist', BATCH_SIZE,
datasets.Split.TEST)
num_classes = train_dataset.element_spec['label'].shape[1]
init_params_fn, apply_params_fn = mnist.build_model(
(*HIDDEN_SIZES, num_classes))
# Set up the fast optimizer (adam) and wrap lookahead around it.
fast_optimizer = optax.adam(LEARNING_RATE)
optimizer = optax.lookahead(fast_optimizer, SYNC_PERIOD, SLOW_LEARNING_RATE)
def get_loss(fast_params, batch):
logits = apply_params_fn(fast_params, batch['image'])
return jnp.mean(optax.softmax_cross_entropy(logits, batch['label']))
@jax.jit
def train_step(params, optimizer_state, batch):
grads = jax.grad(get_loss)(params.fast, batch)
updates, opt_state = optimizer.update(grads, optimizer_state, params)
return optax.apply_updates(params, updates), opt_state
example_input = next(train_dataset.as_numpy_iterator())['image']
initial_params = init_params_fn(random.PRNGKey(SEED), example_input)
# The lookahead optimizer wrapper keeps a pair of slow and fast parameters. To
# initialize them, we create a pair of synchronized parameters from the
# initial model parameters. The first line below is only necessary for the
# lookahead wrapper; without it the initial parameters could be used in the
# initialization function of the optimizer directly.
params = optax.LookaheadParams.init_synced(initial_params)
opt_state = optimizer.init(params)
# Training loop
for epoch in range(N_EPOCHS):
for batch in train_dataset.as_numpy_iterator():
params, opt_state = train_step(params, opt_state, batch)
# Validation is done on the slow lookahead parameters.
eval_model = functools.partial(apply_params_fn, params.slow)
test_acc = mnist.model_accuracy(eval_model,
test_dataset.as_numpy_iterator())
print(f'Epoch {epoch+1}: test acc: {test_acc:.2f}')
return test_acc
if __name__ == '__main__':
app.run(main)
| {
"content_hash": "2bc9e0fdb0a83d3c94a53a3ee642b9b8",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 80,
"avg_line_length": 35.726027397260275,
"alnum_prop": 0.7055214723926381,
"repo_name": "deepmind/optax",
"id": "fce49efae5e851205de281b03abdf7d0b8ca256c",
"size": "3304",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/lookahead_mnist.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "441507"
},
{
"name": "Shell",
"bytes": "3172"
}
],
"symlink_target": ""
} |
import unittest
from tests.tools.client.fixtures import topic_metadata_v0
class MetadataV0ResponseTest(unittest.TestCase):
def setUp(self):
self.metadata = topic_metadata_v0()
def test_topic_names(self):
val = self.metadata.topic_names()
assert val == ['topic1']
def test_broker_ids(self):
val = self.metadata.broker_ids()
assert val == [1, 101]
| {
"content_hash": "ce7fe26f4b5f02189d92c0338a98c4de",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 57,
"avg_line_length": 25.1875,
"alnum_prop": 0.652605459057072,
"repo_name": "toddpalino/kafka-tools",
"id": "b46ef80dc661641bb94566b159304eecfbf7d34e",
"size": "403",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/tools/protocol/responses/test_metadata_v0.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "707729"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Class',
fields=[
('cls_id', models.AutoField(serialize=False, verbose_name=b'ClassManagement id', primary_key=True)),
('name', models.CharField(max_length=100, verbose_name=b'ClassManagement Name')),
('description', models.CharField(max_length=100, verbose_name=b'ClassManagement Description')),
('students', models.ManyToManyField(to=settings.AUTH_USER_MODEL, blank=True)),
('teacher', models.ManyToManyField(related_name='teacher', to=settings.AUTH_USER_MODEL, blank=True)),
],
options={
},
bases=(models.Model,),
),
]
| {
"content_hash": "d6171c7809d8a1f541665bf6f039282a",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 117,
"avg_line_length": 36.81481481481482,
"alnum_prop": 0.6146881287726358,
"repo_name": "Mihai925/EduCoding",
"id": "59f68063f8f1a3d2a6d8e3620199faac49e4d5b3",
"size": "1018",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Class/migrations/0001_initial.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "103299"
},
{
"name": "HTML",
"bytes": "79484"
},
{
"name": "JavaScript",
"bytes": "47731"
},
{
"name": "Python",
"bytes": "72639"
},
{
"name": "Shell",
"bytes": "130"
}
],
"symlink_target": ""
} |
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import mock
import datetime
import logging
import unittest
import webapp2
import webtest
from dashboard import alert_groups
from dashboard import sheriff_config_client
from dashboard.common import testing_common
from dashboard.common import utils
from dashboard.models import alert_group
from dashboard.models import alert_group_workflow
from dashboard.models import anomaly
from dashboard.models import graph_data
from dashboard.models import subscription
from dashboard.services import crrev_service
from dashboard.services import pinpoint_service
_SERVICE_ACCOUNT_EMAIL = 'service-account@chromium.org'
@mock.patch.object(utils, 'ServiceAccountEmail',
lambda: _SERVICE_ACCOUNT_EMAIL)
class GroupReportTestBase(testing_common.TestCase):
def __init__(self, *args, **kwargs):
# TODO(https://crbug.com/1262292): Change to super() after Python2 trybots retire.
# pylint: disable=super-with-arguments
super(GroupReportTestBase, self).__init__(*args, **kwargs)
self.fake_issue_tracker = testing_common.FakeIssueTrackerService()
self.fake_issue_tracker.comments.append({
'id': 1,
'author': _SERVICE_ACCOUNT_EMAIL,
'updates': {
'status': 'WontFix',
},
})
self.mock_get_sheriff_client = mock.MagicMock()
self.fake_revision_info = testing_common.FakeRevisionInfoClient(
infos={}, revisions={})
def setUp(self):
# TODO(https://crbug.com/1262292): Change to super() after Python2 trybots retire.
# pylint: disable=super-with-arguments
super(GroupReportTestBase, self).setUp()
self.maxDiff = None
app = webapp2.WSGIApplication([('/alert_groups_update',
alert_groups.AlertGroupsHandler)])
self.testapp = webtest.TestApp(app)
def _CallHandler(self):
result = self.testapp.get('/alert_groups_update')
self.ExecuteDeferredTasks('update-alert-group-queue')
return result
def _SetUpMocks(self, mock_get_sheriff_client):
sheriff = subscription.Subscription(name='sheriff',
auto_triage_enable=True)
mock_get_sheriff_client().Match.return_value = ([sheriff], None)
self.PatchObject(alert_group_workflow, '_IssueTracker',
lambda: self.fake_issue_tracker)
self.PatchObject(crrev_service, 'GetNumbering',
lambda *args, **kargs: {'git_sha': 'abcd'})
new_job = mock.MagicMock(return_value={'jobId': '123456'})
self.PatchObject(pinpoint_service, 'NewJob', new_job)
self.PatchObject(alert_group_workflow, 'revision_info_client',
self.fake_revision_info)
self.PatchObject(alert_group, 'NONOVERLAP_THRESHOLD', 100)
def _AddAnomaly(self, **kargs):
default = {
'test': 'master/bot/test_suite/measurement/test_case',
'start_revision': 1,
'end_revision': 100,
'is_improvement': False,
'median_before_anomaly': 1.1,
'median_after_anomaly': 1.3,
'ownership': {
'component': 'Foo>Bar',
'emails': ['x@google.com', 'y@google.com'],
},
}
default.update(kargs)
default['test'] = utils.TestKey(default['test'])
graph_data.TestMetadata(
key=default['test'],
unescaped_story_name='story',
).put()
a = anomaly.Anomaly(**default)
clt = sheriff_config_client.GetSheriffConfigClient()
subscriptions, _ = clt.Match(a)
a.groups = alert_group.AlertGroup.GetGroupsForAnomaly(a, subscriptions)
return a.put()
@mock.patch.object(utils, 'ServiceAccountEmail',
lambda: _SERVICE_ACCOUNT_EMAIL)
@mock.patch('dashboard.sheriff_config_client.GetSheriffConfigClient')
class GroupReportTest(GroupReportTestBase):
def testNoGroup(self, mock_get_sheriff_client):
self._SetUpMocks(mock_get_sheriff_client)
# Put an anomaly before Ungrouped is created
self._AddAnomaly()
def testCreatingUngrouped(self, _):
self.assertIs(
len(
alert_group.AlertGroup.Get(
'Ungrouped',
alert_group.AlertGroup.Type.reserved,
)), 0)
response = self._CallHandler()
self.assertEqual(response.status_code, 200)
self.assertIs(
len(
alert_group.AlertGroup.Get(
'Ungrouped',
alert_group.AlertGroup.Type.reserved,
)), 1)
def testCreatingGroup(self, mock_get_sheriff_client):
self._SetUpMocks(mock_get_sheriff_client)
# Ungrouped is created in first run
self._CallHandler()
# Put an anomaly after Ungrouped is created
a1 = self._AddAnomaly()
# Anomaly is associated with Ungrouped and AlertGroup Created
self._CallHandler()
# Anomaly is associated with its AlertGroup
self._CallHandler()
self.assertEqual(len(a1.get().groups), 1)
self.assertEqual(a1.get().groups[0].get().name, 'test_suite')
def testMultipleAltertsGroupingDifferentDomain_BeforeGroupCreated(
self, mock_get_sheriff_client):
self._SetUpMocks(mock_get_sheriff_client)
self.testapp.get('/alert_groups_update')
self.ExecuteDeferredTasks('update-alert-group-queue')
# Add anomalies
a1 = self._AddAnomaly()
a2 = self._AddAnomaly(start_revision=50, end_revision=150)
a3 = self._AddAnomaly(test='other/bot/test_suite/measurement/test_case')
a4 = self._AddAnomaly(median_before_anomaly=0)
# Create Group
self._CallHandler()
# Update Group to associate alerts
self._CallHandler()
groups = {
g.domain: g
for g in alert_group.AlertGroup.Get(
'test_suite', alert_group.AlertGroup.Type.test_suite)
}
self.assertItemsEqual(groups['master'].anomalies, [a1, a2, a4])
self.assertItemsEqual(groups['other'].anomalies, [a3])
def testMultipleAltertsGroupingDifferentDomain_AfterGroupCreated(
self, mock_get_sheriff_client):
self._SetUpMocks(mock_get_sheriff_client)
self.testapp.get('/alert_groups_update')
self.ExecuteDeferredTasks('update-alert-group-queue')
# Add anomalies
a1 = self._AddAnomaly()
a2 = self._AddAnomaly(start_revision=50, end_revision=150)
a4 = self._AddAnomaly(median_before_anomaly=0)
# Create Group
self._CallHandler()
# Update Group to associate alerts
self._CallHandler()
# Add anomalies in other domain
a3 = self._AddAnomaly(test='other/bot/test_suite/measurement/test_case')
# Create Group
self._CallHandler()
# Update Group to associate alerts
self._CallHandler()
groups = {
g.domain: g
for g in alert_group.AlertGroup.Get(
'test_suite', alert_group.AlertGroup.Type.test_suite)
}
self.assertItemsEqual(groups['master'].anomalies, [a1, a2, a4])
self.assertItemsEqual(groups['other'].anomalies, [a3])
def testMultipleAltertsGroupingDifferentBot(self, mock_get_sheriff_client):
self._SetUpMocks(mock_get_sheriff_client)
self.testapp.get('/alert_groups_update')
self.ExecuteDeferredTasks('update-alert-group-queue')
# Add anomalies
a1 = self._AddAnomaly()
a2 = self._AddAnomaly(start_revision=50, end_revision=150)
a3 = self._AddAnomaly(test='master/other/test_suite/measurement/test_case')
a4 = self._AddAnomaly(median_before_anomaly=0)
# Create Group
self._CallHandler()
# Update Group to associate alerts
self._CallHandler()
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)[0]
self.assertItemsEqual(group.anomalies, [a1, a2, a3, a4])
def testMultipleAltertsGroupingDifferentSuite(self, mock_get_sheriff_client):
self._SetUpMocks(mock_get_sheriff_client)
self.testapp.get('/alert_groups_update')
self.ExecuteDeferredTasks('update-alert-group-queue')
# Add anomalies
a1 = self._AddAnomaly()
a2 = self._AddAnomaly(start_revision=50, end_revision=150)
a3 = self._AddAnomaly(test='master/bot/other/measurement/test_case')
a4 = self._AddAnomaly(median_before_anomaly=0)
# Create Group
self._CallHandler()
# Update Group to associate alerts
self._CallHandler()
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)[0]
self.assertItemsEqual(group.anomalies, [a1, a2, a4])
group = alert_group.AlertGroup.Get(
'other',
alert_group.AlertGroup.Type.test_suite,
)[0]
self.assertItemsEqual(group.anomalies, [a3])
def testMultipleAltertsGroupingOverrideSuite(self, mock_get_sheriff_client):
self._SetUpMocks(mock_get_sheriff_client)
self.testapp.get('/alert_groups_update')
self.ExecuteDeferredTasks('update-alert-group-queue')
# Add anomalies
a1 = self._AddAnomaly(test='master/bot/test_suite/measurement/test_case', )
a2 = self._AddAnomaly(
test='master/bot/test_suite/measurement/test_case',
start_revision=50,
end_revision=150,
)
a3 = self._AddAnomaly(
test='master/bot/other/measurement/test_case',
alert_grouping=['test_suite', 'test_suite_other1'],
)
a4 = self._AddAnomaly(
test='master/bot/test_suite/measurement/test_case',
median_before_anomaly=0,
alert_grouping=['test_suite_other1', 'test_suite_other2'],
)
# Create Group
self._CallHandler()
# Update Group to associate alerts
self._CallHandler()
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)[0]
self.assertItemsEqual(group.anomalies, [a1, a2])
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.logical,
)[0]
self.assertItemsEqual(group.anomalies, [a3])
group = alert_group.AlertGroup.Get(
'test_suite_other1',
alert_group.AlertGroup.Type.logical,
)[0]
self.assertItemsEqual(group.anomalies, [a3, a4])
group = alert_group.AlertGroup.Get(
'test_suite_other2',
alert_group.AlertGroup.Type.logical,
)[0]
self.assertItemsEqual(group.anomalies, [a4])
def testMultipleAltertsGroupingMultipleSheriff(self,
mock_get_sheriff_client):
self._SetUpMocks(mock_get_sheriff_client)
mock_get_sheriff_client().Match.return_value = ([
subscription.Subscription(name='sheriff1',
auto_triage_enable=True,
auto_bisect_enable=True),
subscription.Subscription(name='sheriff2',
auto_triage_enable=True,
auto_bisect_enable=True),
], None)
self.testapp.get('/alert_groups_update')
self.ExecuteDeferredTasks('update-alert-group-queue')
# Add anomaly
a1 = self._AddAnomaly()
# Create Group
self._CallHandler()
# Update Group to associate alerts
self._CallHandler()
# Add another anomaly with part of the subscription
mock_get_sheriff_client().Match.return_value = ([
subscription.Subscription(name='sheriff1',
auto_triage_enable=True,
auto_bisect_enable=True),
], None)
a2 = self._AddAnomaly()
# Update Group to associate alerts
self._CallHandler()
# Add another anomaly with different subscription
mock_get_sheriff_client().Match.return_value = ([
subscription.Subscription(name='sheriff2',
auto_triage_enable=True,
auto_bisect_enable=True),
subscription.Subscription(name='sheriff3',
auto_triage_enable=True,
auto_bisect_enable=True),
], None)
a3 = self._AddAnomaly()
# Create Group
self._CallHandler()
# Update Group to associate alerts
self._CallHandler()
groups = {
g.subscription_name: g
for g in alert_group.AlertGroup.Get(
'test_suite', alert_group.AlertGroup.Type.test_suite)
}
self.assertItemsEqual(
list(groups.keys()), ['sheriff1', 'sheriff2', 'sheriff3'])
self.assertItemsEqual(groups['sheriff1'].anomalies, [a1, a2])
self.assertItemsEqual(groups['sheriff2'].anomalies, [a1, a3])
self.assertItemsEqual(groups['sheriff3'].anomalies, [a3])
def testMultipleAltertsGroupingPointRange(self, mock_get_sheriff_client):
self._SetUpMocks(mock_get_sheriff_client)
self.testapp.get('/alert_groups_update')
self.ExecuteDeferredTasks('update-alert-group-queue')
# Add anomalies
a1 = self._AddAnomaly(start_revision=100, end_revision=100)
a2 = self._AddAnomaly(start_revision=100, end_revision=100)
# Create Group
self._CallHandler()
# Update Group to associate alerts
self._CallHandler()
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)[0]
self.assertItemsEqual(group.anomalies, [a1, a2])
def testArchiveAltertsGroup(self, mock_get_sheriff_client):
self._SetUpMocks(mock_get_sheriff_client)
self._CallHandler()
# Add anomalies
self._AddAnomaly()
# Create Group
self._CallHandler()
# Update Group to associate alerts
self._CallHandler()
# Set Update timestamp to 10 days ago
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)[0]
group.updated = datetime.datetime.utcnow() - datetime.timedelta(days=10)
group.put()
# Archive Group
self._CallHandler()
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
active=False,
)[0]
self.assertEqual(group.name, 'test_suite')
def testArchiveAltertsGroupIssueClosed(self, mock_get_sheriff_client):
self._SetUpMocks(mock_get_sheriff_client)
self.fake_issue_tracker.issue['state'] = 'open'
self._CallHandler()
# Add anomalies
self._AddAnomaly()
# Create Group
self._CallHandler()
# Update Group to associate alerts
self._CallHandler()
# Set Create timestamp to 2 hours ago
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)[0]
group.created = datetime.datetime.utcnow() - datetime.timedelta(hours=2)
group.put()
# Create Issue
self._CallHandler()
# Out of active window
group.updated = datetime.datetime.utcnow() - datetime.timedelta(days=10)
# Archive Group
self._CallHandler()
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
active=False,
)[0]
self.assertEqual(group.name, 'test_suite')
def testTriageAltertsGroup(self, mock_get_sheriff_client):
self._SetUpMocks(mock_get_sheriff_client)
self._CallHandler()
# Add anomalies
a = self._AddAnomaly()
# Create Group
self._CallHandler()
# Update Group to associate alerts
self._CallHandler()
# Set Create timestamp to 2 hours ago
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)[0]
group.created = datetime.datetime.utcnow() - datetime.timedelta(hours=2)
group.put()
# Submit issue
self._CallHandler()
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)[0]
self.assertEqual(group.status, alert_group.AlertGroup.Status.triaged)
self.assertItemsEqual(self.fake_issue_tracker.new_bug_kwargs['components'],
['Foo>Bar'])
self.assertItemsEqual(self.fake_issue_tracker.new_bug_kwargs['labels'], [
'Pri-2', 'Restrict-View-Google', 'Type-Bug-Regression',
'Chromeperf-Auto-Triaged'
])
logging.debug('Rendered:\n%s', self.fake_issue_tracker.new_bug_args[1])
# TODO(https://crbug.com/1262295): Update this after Python2 trybots retire.
# pylint: disable=deprecated-method
self.assertRegexpMatches(self.fake_issue_tracker.new_bug_args[1],
r'Top 1 affected measurements in bot:')
self.assertEqual(a.get().bug_id, 12345)
self.assertEqual(group.bug.bug_id, 12345)
# Make sure we don't file the issue again for this alert group.
self.fake_issue_tracker.new_bug_args = None
self.fake_issue_tracker.new_bug_kwargs = None
self._CallHandler()
self.assertIsNone(self.fake_issue_tracker.new_bug_args)
self.assertIsNone(self.fake_issue_tracker.new_bug_kwargs)
# TODO(dberris): Re-enable this when we start supporting multiple benchmarks
# in the same alert group in the future.
@unittest.expectedFailure
def testTriageAltertsGroup_MultipleBenchmarks(self, mock_get_sheriff_client):
self._SetUpMocks(mock_get_sheriff_client)
self._CallHandler()
# Add anomalies
a = self._AddAnomaly()
_ = self._AddAnomaly(
test='master/bot/other_test_suite/measurement/test_case')
# Create Group
self._CallHandler()
# Update Group to associate alerts
self._CallHandler()
# Set Create timestamp to 2 hours ago
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)[0]
group.created = datetime.datetime.utcnow() - datetime.timedelta(hours=2)
group.put()
# Submit issue
self._CallHandler()
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)[0]
self.assertEqual(group.status, alert_group.AlertGroup.Status.triaged)
self.assertItemsEqual(self.fake_issue_tracker.new_bug_kwargs['components'],
['Foo>Bar'])
self.assertItemsEqual(self.fake_issue_tracker.new_bug_kwargs['labels'], [
'Pri-2', 'Restrict-View-Google', 'Type-Bug-Regression',
'Chromeperf-Auto-Triaged'
])
logging.debug('Rendered:\n%s', self.fake_issue_tracker.new_bug_args[1])
# TODO(https://crbug.com/1262295): Update this after Python2 trybots retire.
# pylint: disable=deprecated-method
self.assertRegexpMatches(self.fake_issue_tracker.new_bug_args[1],
r'Top 4 affected measurements in bot:')
# TODO(https://crbug.com/1262295): Update this after Python2 trybots retire.
# pylint: disable=deprecated-method
self.assertRegexpMatches(self.fake_issue_tracker.new_bug_args[1],
r'Top 1 affected in test_suite:')
# TODO(https://crbug.com/1262295): Update this after Python2 trybots retire.
# pylint: disable=deprecated-method
self.assertRegexpMatches(self.fake_issue_tracker.new_bug_args[1],
r'Top 1 affected in other_test_suite:')
self.assertEqual(a.get().bug_id, 12345)
self.assertEqual(group.bug.bug_id, 12345)
# Make sure we don't file the issue again for this alert group.
self.fake_issue_tracker.new_bug_args = None
self.fake_issue_tracker.new_bug_kwargs = None
self._CallHandler()
self.assertIsNone(self.fake_issue_tracker.new_bug_args)
self.assertIsNone(self.fake_issue_tracker.new_bug_kwargs)
def testTriageAltertsGroupNoOwners(self, mock_get_sheriff_client):
self._SetUpMocks(mock_get_sheriff_client)
self._CallHandler()
# Add anomalies
a = self._AddAnomaly(ownership={
'component': 'Foo>Bar',
'emails': None,
})
# Create Group
self._CallHandler()
# Update Group to associate alerts
self._CallHandler()
# Set Create timestamp to 2 hours ago
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)[0]
group.created = datetime.datetime.utcnow() - datetime.timedelta(hours=2)
group.put()
# Submit issue
self._CallHandler()
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)[0]
self.assertEqual(group.status, alert_group.AlertGroup.Status.triaged)
self.assertItemsEqual(self.fake_issue_tracker.new_bug_kwargs['components'],
['Foo>Bar'])
self.assertItemsEqual(self.fake_issue_tracker.new_bug_kwargs['labels'], [
'Pri-2', 'Restrict-View-Google', 'Type-Bug-Regression',
'Chromeperf-Auto-Triaged'
])
self.assertEqual(a.get().bug_id, 12345)
def testAddAlertsAfterTriage(self, mock_get_sheriff_client):
self._SetUpMocks(mock_get_sheriff_client)
self._CallHandler()
# Add anomalies
a = self._AddAnomaly()
# Create Group
self._CallHandler()
# Update Group to associate alerts
self._CallHandler()
# Set Create timestamp to 2 hours ago
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)[0]
group.created = datetime.datetime.utcnow() - datetime.timedelta(hours=2)
group.put()
# Submit issue
self._CallHandler()
# Add anomalies
anomalies = [
self._AddAnomaly(),
self._AddAnomaly(median_before_anomaly=0),
]
self._CallHandler()
for a in anomalies:
self.assertEqual(a.get().bug_id, 12345)
logging.debug('Rendered:\n%s', self.fake_issue_tracker.add_comment_args[1])
self.assertEqual(self.fake_issue_tracker.add_comment_args[0], 12345)
self.assertItemsEqual(
self.fake_issue_tracker.add_comment_kwargs['components'], ['Foo>Bar'])
# TODO(https://crbug.com/1262295): Update this after Python2 trybots retire.
# pylint: disable=deprecated-method
self.assertRegexpMatches(self.fake_issue_tracker.add_comment_args[1],
r'Top 2 affected measurements in bot:')
def testMultipleAltertsNonoverlapThreshold(self, mock_get_sheriff_client):
self._SetUpMocks(mock_get_sheriff_client)
self._CallHandler()
perf_test = 'ChromiumPerf/bot/test_suite/measurement/test_case'
# Anomalies without range overlap.
a1 = self._AddAnomaly(start_revision=10, end_revision=40, test=perf_test)
a2 = self._AddAnomaly(start_revision=50, end_revision=150, test=perf_test)
a4 = self._AddAnomaly(start_revision=200, end_revision=300, test=perf_test)
self._CallHandler()
# Anomaly that overlaps with first 2 alert groups.
a5 = self._AddAnomaly(start_revision=5, end_revision=100, test=perf_test)
# Anomaly that exceeds nonoverlap threshold of all existing alert groups.
a6 = self._AddAnomaly(start_revision=5, end_revision=305, test=perf_test)
self._CallHandler()
# Anomaly that binds to a6's group.
a7 = self._AddAnomaly(start_revision=10, end_revision=300, test=perf_test)
self._CallHandler()
self._CallHandler()
groups = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)
anomaly_groups = [group.anomalies for group in groups]
expected_anomaly_groups = [[a1, a5], [a2, a5], [a4], [a6, a7]]
self.assertItemsEqual(anomaly_groups, expected_anomaly_groups)
@mock.patch.object(utils, 'ServiceAccountEmail',
lambda: _SERVICE_ACCOUNT_EMAIL)
@mock.patch('dashboard.sheriff_config_client.GetSheriffConfigClient')
class RecoveredAlertsTests(GroupReportTestBase):
def __init__(self, *args, **kwargs):
# TODO(https://crbug.com/1262292): Change to super() after Python2 trybots retire.
# pylint: disable=super-with-arguments
super(RecoveredAlertsTests, self).__init__(*args, **kwargs)
self.anomalies = []
def InitAfterMocks(self):
# First create the 'Ungrouped' AlertGroup.
self._CallHandler()
# Then create the alert group which has a regression and recovered
# regression.
self.anomalies = [
self._AddAnomaly(),
self._AddAnomaly(recovered=True, start_revision=50, end_revision=150),
]
self._CallHandler()
# Then we update the group to associate alerts.
self._CallHandler()
# Set Create timestamp to 2 hours ago, so that the next time the handler is
# called, we'd trigger the update processing.
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)[0]
group.created = datetime.datetime.utcnow() - datetime.timedelta(hours=2)
group.put()
def testNoRecovered(self, mock_get_sheriff_client):
# Ensure that we only include the non-recovered regressions in the filing.
self._SetUpMocks(mock_get_sheriff_client)
self.InitAfterMocks()
self._CallHandler()
logging.debug('Rendered:\n%s', self.fake_issue_tracker.new_bug_args[1])
# TODO(https://crbug.com/1262295): Update this after Python2 trybots retire.
# pylint: disable=deprecated-method
self.assertRegexpMatches(self.fake_issue_tracker.new_bug_args[1],
r'Top 1 affected measurements in bot:')
def testClosesIssueOnAllRecovered(self, mock_get_sheriff_client):
# Ensure that we close the issue if all regressions in the group have been
# marked 'recovered'.
self._SetUpMocks(mock_get_sheriff_client)
self.InitAfterMocks()
self._CallHandler()
logging.debug('Rendered:\n%s', self.fake_issue_tracker.new_bug_args[1])
# TODO(https://crbug.com/1262295): Update this after Python2 trybots retire.
# pylint: disable=deprecated-method
self.assertRegexpMatches(self.fake_issue_tracker.new_bug_args[1],
r'Top 1 affected measurements in bot:')
# Mark one of the anomalies recovered.
recovered_anomaly = self.anomalies[0].get()
recovered_anomaly.recovered = True
recovered_anomaly.put()
self._CallHandler()
self.assertEqual(self.fake_issue_tracker.issue['state'], 'closed')
# TODO(https://crbug.com/1262295): Update this after Python2 trybots retire.
# pylint: disable=deprecated-method
self.assertRegexpMatches(
self.fake_issue_tracker.add_comment_args[1],
r'All regressions for this issue have been marked recovered; closing.')
def testReopensClosedIssuesWithNewRegressions(self, mock_get_sheriff_client):
# pylint: disable=no-value-for-parameter
self.testClosesIssueOnAllRecovered()
self._SetUpMocks(mock_get_sheriff_client)
mock_get_sheriff_client().Match.return_value = ([
subscription.Subscription(name='sheriff',
auto_triage_enable=True,
auto_bisect_enable=True)
], None)
# Then we add a new anomaly which should cause the issue to be reopened.
self._AddAnomaly(start_revision=50,
end_revision=75,
test='master/bot/test_suite/measurement/other_test_case')
self._CallHandler()
logging.debug('Rendered:\n%s', self.fake_issue_tracker.add_comment_args[1])
self.assertEqual(self.fake_issue_tracker.issue["state"], 'open')
# TODO(https://crbug.com/1262295): Update this after Python2 trybots retire.
# pylint: disable=deprecated-method
self.assertRegexpMatches(
self.fake_issue_tracker.add_comment_args[1],
r'Reopened due to new regressions detected for this alert group:')
# TODO(https://crbug.com/1262295): Update this after Python2 trybots retire.
# pylint: disable=deprecated-method
self.assertRegexpMatches(self.fake_issue_tracker.add_comment_args[1],
r'test_suite/measurement/other_test_case')
def testManualClosedIssuesWithNewRegressions(self, mock_get_sheriff_client):
# pylint: disable=no-value-for-parameter
self.testClosesIssueOnAllRecovered()
self._SetUpMocks(mock_get_sheriff_client)
mock_get_sheriff_client().Match.return_value = ([
subscription.Subscription(name='sheriff',
auto_triage_enable=True,
auto_bisect_enable=True)
], None)
self.fake_issue_tracker.comments.append({
'id': 2,
'author': "sheriff@chromium.org",
'updates': {
'status': 'WontFix',
},
})
# Then we add a new anomaly which should cause the issue to be reopened.
self._AddAnomaly(start_revision=50,
end_revision=75,
test='master/bot/test_suite/measurement/other_test_case')
self._CallHandler()
logging.debug('Rendered:\n%s', self.fake_issue_tracker.add_comment_args[1])
self.assertEqual(self.fake_issue_tracker.issue["state"], 'closed')
# TODO(https://crbug.com/1262295): Update this after Python2 trybots retire.
# pylint: disable=deprecated-method
self.assertRegexpMatches(self.fake_issue_tracker.add_comment_args[1],
r'test_suite/measurement/other_test_case')
def testStartAutoBisection(self, mock_get_sheriff_client):
self._SetUpMocks(mock_get_sheriff_client)
mock_get_sheriff_client().Match.return_value = ([
subscription.Subscription(name='sheriff',
auto_triage_enable=True,
auto_bisect_enable=True)
], None)
self._CallHandler()
# Add anomalies
self._AddAnomaly()
# Create Group
self._CallHandler()
# Update Group to associate alerts
self._CallHandler()
# Set Create timestamp to 2 hours ago
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)[0]
group.created = datetime.datetime.utcnow() - datetime.timedelta(hours=2)
group.put()
# Submit issue
self._CallHandler()
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)[0]
# Start bisection
self._CallHandler()
group = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)[0]
self.assertItemsEqual(group.bisection_ids, ['123456'])
@mock.patch.object(utils, 'ServiceAccountEmail',
lambda: _SERVICE_ACCOUNT_EMAIL)
class NonChromiumAutoTriage(GroupReportTestBase):
def testFileIssue_InChromiumExplicitly(self):
self.mock_get_sheriff_client.Match.return_value = ([
subscription.Subscription(name='sheriff',
auto_triage_enable=True,
monorail_project_id='chromium')
], None)
self.PatchObject(alert_group.sheriff_config_client,
'GetSheriffConfigClient',
lambda: self.mock_get_sheriff_client)
self._SetUpMocks(self.mock_get_sheriff_client)
self._CallHandler()
a = self._AddAnomaly()
self._CallHandler()
grouped_anomaly = a.get()
self.assertEqual(grouped_anomaly.project_id, 'chromium')
def testAlertGroups_OnePerProject(self):
self.mock_get_sheriff_client.Match.return_value = ([
subscription.Subscription(name='chromium sheriff',
auto_triage_enable=True,
monorail_project_id='chromium'),
subscription.Subscription(name='v8 sheriff',
auto_triage_enable=True,
monorail_project_id='v8')
], None)
self.PatchObject(alert_group.sheriff_config_client,
'GetSheriffConfigClient',
lambda: self.mock_get_sheriff_client)
self._SetUpMocks(self.mock_get_sheriff_client)
# First create the 'Ungrouped' AlertGroup.
self._CallHandler()
# Then create an anomaly.
self._AddAnomaly()
self._CallHandler()
# Ensure that we have two different groups on different projects.
groups = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)
self.assertEqual(2, len(groups))
self.assertItemsEqual(['chromium', 'v8'], [g.project_id for g in groups])
for group in groups:
group.created = datetime.datetime.utcnow() - datetime.timedelta(hours=2)
group.put()
# And that we've filed two issues.
self._CallHandler()
self.assertItemsEqual([{
'method': 'NewBug',
'args': (mock.ANY, mock.ANY),
'kwargs': {
'project': 'v8',
'cc': [],
'labels': mock.ANY,
'components': mock.ANY,
},
}, {
'method': 'NewBug',
'args': (mock.ANY, mock.ANY),
'kwargs': {
'project': 'chromium',
'cc': [],
'labels': mock.ANY,
'components': mock.ANY,
},
}], self.fake_issue_tracker.calls)
def testAlertGroups_NonChromium(self):
self.mock_get_sheriff_client.Match.return_value = ([
subscription.Subscription(name='non-chromium sheriff',
auto_triage_enable=True,
monorail_project_id='non-chromium')
], None)
self.PatchObject(alert_group.sheriff_config_client,
'GetSheriffConfigClient',
lambda: self.mock_get_sheriff_client)
self._SetUpMocks(self.mock_get_sheriff_client)
self._CallHandler()
a = self._AddAnomaly()
self._CallHandler()
groups = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)
self.assertEqual(1, len(groups))
self.assertEqual(['non-chromium'], [g.project_id for g in groups])
for group in groups:
group.created = datetime.datetime.utcnow() - datetime.timedelta(hours=2)
group.put()
self._CallHandler()
self.assertItemsEqual([{
'method': 'NewBug',
'args': (mock.ANY, mock.ANY),
'kwargs': {
'project': 'non-chromium',
'cc': [],
'labels': mock.ANY,
'components': mock.ANY,
}
}], self.fake_issue_tracker.calls)
a = a.get()
self.assertEqual(a.project_id, 'non-chromium')
stored_issue = self.fake_issue_tracker.GetIssue(a.bug_id, 'non-chromium')
logging.debug('bug_id = %s', a.bug_id)
self.assertIsNotNone(stored_issue)
# Now let's ensure that when new anomalies come in, that we're grouping
# them into the same group for non-chromium alerts.
self._AddAnomaly(start_revision=2)
self._CallHandler()
groups = alert_group.AlertGroup.Get(
'test_suite',
alert_group.AlertGroup.Type.test_suite,
)
self.assertEqual(1, len(groups))
self.assertEqual(groups[0].project_id, 'non-chromium')
| {
"content_hash": "0de6bfa40652fcc15514749270727fc9",
"timestamp": "",
"source": "github",
"line_count": 886,
"max_line_length": 86,
"avg_line_length": 38.909706546275395,
"alnum_prop": 0.6501711434704415,
"repo_name": "catapult-project/catapult",
"id": "568c92c6fa3095544f764c0c6d62305e8fdedda2",
"size": "34637",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "dashboard/dashboard/alert_groups_test.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "1324"
},
{
"name": "C++",
"bytes": "46069"
},
{
"name": "CSS",
"bytes": "23376"
},
{
"name": "Dockerfile",
"bytes": "1541"
},
{
"name": "Go",
"bytes": "114396"
},
{
"name": "HTML",
"bytes": "12394298"
},
{
"name": "JavaScript",
"bytes": "1559584"
},
{
"name": "Makefile",
"bytes": "1774"
},
{
"name": "Python",
"bytes": "6778695"
},
{
"name": "Shell",
"bytes": "2288"
}
],
"symlink_target": ""
} |
import logging
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from vio.pub.msapi import extsys
from vio.pub.vim.vimapi.keystone import OperateTenant
from vio.pub.exceptions import VimDriverVioException
logger = logging.getLogger(__name__)
class ListTenantsView(APIView):
def get(self, request, vimid):
try:
vim_info = extsys.get_vim_by_id(vimid)
except VimDriverVioException as e:
return Response(data={'error': str(e)}, status=e.status_code)
data = {}
data['vimId'] = vim_info['vimId']
data['vimName'] = vim_info['name']
data['username'] = vim_info['userName']
data['password'] = vim_info['password']
data['url'] = vim_info['url']
data['project_name'] = vim_info['tenant']
query = dict(request.query_params)
tenant_instance = OperateTenant.OperateTenant()
try:
projects = tenant_instance.get_projects(data, **query)
except Exception as e:
return Response(data={'error': str(e)},
status=status.HTTP_500_INTERNAL_SERVER_ERROR)
rsp = {}
rsp['vimId'] = vim_info['vimId']
rsp['vimName'] = vim_info['name']
rsp['tenants'] = []
for project in projects:
tenant = {}
tenant['id'] = project.id
tenant['name'] = project.name
rsp['tenants'].append(tenant)
return Response(data=rsp, status=status.HTTP_200_OK)
| {
"content_hash": "c70bd618de9acdcd56698eaca18a0fc4",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 73,
"avg_line_length": 33.891304347826086,
"alnum_prop": 0.6023091725465042,
"repo_name": "onesafe/multivimdriver-vmware-vio",
"id": "3eff77f9270f76f44197272a1d8243fa6b914ea2",
"size": "2041",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vio/vio/swagger/views/tenant/views.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "140848"
},
{
"name": "Shell",
"bytes": "1658"
}
],
"symlink_target": ""
} |
import sys
import os
import random
import csv
import tensorflow as tf
import numpy as np
from PIL import Image
import cv2
import face_pb2
FAC_DATA = 'fac_data'
IMAGE_DIR = 'Images'
AU_DIR = 'AUs'
BUFFER_SIZE = 50
TRAINING_PERCENT = 70
TESTING_PERCENT = (100 - TRAINING_PERCENT) / 2.0
VALIDATION_PERCENT = (100 - TRAINING_PERCENT) / 2.0
AUS = [1,2,4,5,6,9,12,15,17,20,25,26]
TRAINING_DIR = 'training'
TESTING_DIR = 'testing'
VALIDATION_DIR = 'validation'
def write_records(root_dir, dest_dir):
print("Beginning writing")
#Images divided into subjects, so loop over those dirs
images_dir = os.path.join(root_dir, IMAGE_DIR)
if not os.path.isdir(images_dir):
raise ValueError("There is no 'Images' directory in the specified dataset directory")
for subj in sorted(os.listdir(images_dir)):
print("Processing subject:%s" % subj)
#Subject image dirs have same name as csv files...
subj_image_dir = os.path.join(images_dir, subj)
subject_csv_file = os.path.join(root_dir, AU_DIR, subj)
subject_ptr = open(subject_csv_file)
#Read in the CSV
labels = _get_labels_for_subject(subject_ptr)
#then for every image per subject read it in
for i, filename in enumerate(sorted(os.listdir(subj_image_dir))):
print("Processing %s" % filename)
#Load the image
file_path = os.path.join(subj_image_dir, filename)
frame = int(filename.split('_')[2][:-4])
image = cv2.imread(file_path, cv2.IMREAD_GRAYSCALE)
location = TRAINING_DIR
rand = random.random() * 100
if rand > TRAINING_PERCENT + VALIDATION_PERCENT:
location = VALIDATION_DIR
elif rand > TRAINING_PERCENT:
location = TESTING_DIR
#Write to tfrecord
dataId = filename.split('.')[0]
record_path = os.path.join(dest_dir, location, dataId)
print("Writing %s" % record_path)
faceBuffer = face_pb2.Face()
faceBuffer.facs.extend(labels[i])
faceBuffer.image = image.tostring()
faceBuffer.id = dataId
fp = open(record_path, 'wb')
fp.write(faceBuffer.SerializeToString())
fp.close()
def _get_labels_for_subject(file_ptr):
""" Reads the CSV file and organizes it into a list
:param file_ptr: pointer to a subject's csv
:type file_ptr: file pointer
:returns: list of FACLabel objects
"""
labels = []
#Open CSC
reader = csv.reader(file_ptr, delimiter=',')
for i, row in enumerate(reader):
facs = []
for j, intensity in enumerate(row):
if j == 0:
continue
facs.append(int(intensity))
labels.append(facs)
return labels
def main():
# params:
# root_dir: The root directory of the dataset to be converted
# dest_dir: The destination directory for the dataset
root_dir = sys.argv[1]
dest_dir = sys.argv[2]
write_records(root_dir, dest_dir)
if __name__ == '__main__':
main()
| {
"content_hash": "4486862d22beb297fdcf0c1457102fa8",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 93,
"avg_line_length": 28.75229357798165,
"alnum_prop": 0.6049776643267389,
"repo_name": "cosanlab/emote",
"id": "04b62be168374ed42f888eab78d926b8c2c2aa1c",
"size": "3135",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "v2/ghosh/difsa_to_proto.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Protocol Buffer",
"bytes": "124"
},
{
"name": "Python",
"bytes": "93872"
},
{
"name": "Shell",
"bytes": "2788"
}
],
"symlink_target": ""
} |
from checks import Check
# 3rd party
import uptime
try:
import psutil
except ImportError:
psutil = None
try:
from checks.libs.wmi.sampler import WMISampler
except Exception:
def WMISampler(*args, **kwargs):
"""
Fallback with a 'None' callable object.
"""
return
# datadog
from utils.timeout import TimeoutException
# Device WMI drive types
class DriveType(object):
UNKNOWN, NOROOT, REMOVEABLE, LOCAL, NETWORK, CD, RAM = (0, 1, 2, 3, 4, 5, 6)
B2MB = float(1048576)
KB2MB = B2KB = float(1024)
def should_ignore_disk(name, blacklist_re):
# blacklist_re is a compiled regex, compilation done at config loading time
return name == '_total' or blacklist_re is not None and blacklist_re.match(name)
class Processes(Check):
def __init__(self, logger):
Check.__init__(self, logger)
# Sampler(s)
self.wmi_sampler = WMISampler(
logger,
"Win32_PerfRawData_PerfOS_System",
["ProcessorQueueLength", "Processes"]
)
self.gauge('system.proc.queue_length')
self.gauge('system.proc.count')
def check(self, agentConfig):
try:
self.wmi_sampler.sample()
except TimeoutException:
self.logger.warning(
u"Timeout while querying Win32_PerfRawData_PerfOS_System WMI class."
u" Processes metrics will be returned at next iteration."
)
return []
if not (len(self.wmi_sampler)):
self.logger.warning('Missing Win32_PerfRawData_PerfOS_System WMI class.'
' No process metrics will be returned.')
return []
os = self.wmi_sampler[0]
processor_queue_length = os.get('ProcessorQueueLength')
processes = os.get('Processes')
if processor_queue_length is not None:
self.save_sample('system.proc.queue_length', processor_queue_length)
if processes is not None:
self.save_sample('system.proc.count', processes)
return self.get_metrics()
class Memory(Check):
def __init__(self, logger):
Check.__init__(self, logger)
# Sampler(s)
self.os_wmi_sampler = WMISampler(
logger,
"Win32_OperatingSystem",
["TotalVisibleMemorySize", "FreePhysicalMemory"]
)
self.mem_wmi_sampler = WMISampler(
logger,
"Win32_PerfRawData_PerfOS_Memory",
["CacheBytes", "CommittedBytes", "PoolPagedBytes", "PoolNonpagedBytes"])
self.gauge('system.mem.free')
self.gauge('system.mem.used')
self.gauge('system.mem.total')
# area of physical memory that stores recently used pages of data
# for applications
self.gauge('system.mem.cached')
# Committed memory is physical memory for which space has been
# reserved on the disk paging file in case it must be written
# back to disk
self.gauge('system.mem.committed')
# physical memory used by the operating system, for objects
# that can be written to disk when they are not being used
self.gauge('system.mem.paged')
# physical memory used by the operating system for objects that
# cannot be written to disk, but must remain in physical memory
# as long as they are allocated.
self.gauge('system.mem.nonpaged')
# usable = free + cached
self.gauge('system.mem.usable')
self.gauge('system.mem.pct_usable')
# details about the usage of the pagefile.
self.gauge('system.mem.page_total')
self.gauge('system.mem.page_used')
self.gauge('system.mem.page_free')
self.gauge('system.mem.page_pct_free')
def check(self, agentConfig):
try:
self.os_wmi_sampler.sample()
except TimeoutException:
self.logger.warning(
u"Timeout while querying Win32_OperatingSystem WMI class."
u" Memory metrics will be returned at next iteration."
)
return []
if not (len(self.os_wmi_sampler)):
self.logger.warning('Missing Win32_OperatingSystem WMI class.'
' No memory metrics will be returned.')
return []
os = self.os_wmi_sampler[0]
total = 0
free = 0
cached = 0
total_visible_memory_size = os.get('TotalVisibleMemorySize')
free_physical_memory = os.get('FreePhysicalMemory')
if total_visible_memory_size is not None and free_physical_memory is not None:
total = int(total_visible_memory_size) / KB2MB
free = int(free_physical_memory) / KB2MB
self.save_sample('system.mem.total', total)
self.save_sample('system.mem.free', free)
self.save_sample('system.mem.used', total - free)
try:
self.mem_wmi_sampler.sample()
except TimeoutException:
self.logger.warning(
u"Timeout while querying Win32_PerfRawData_PerfOS_Memory WMI class."
u" Memory metrics will be returned at next iteration."
)
return
if not (len(self.mem_wmi_sampler)):
self.logger.info('Missing Win32_PerfRawData_PerfOS_Memory WMI class.'
' No memory metrics will be returned.')
return self.get_metrics()
mem = self.mem_wmi_sampler[0]
cache_bytes = mem.get('CacheBytes')
committed_bytes = mem.get('CommittedBytes')
pool_paged_bytes = mem.get('PoolPagedBytes')
pool_non_paged_bytes = mem.get('PoolNonpagedBytes')
if cache_bytes is not None:
cached = int(cache_bytes) / B2MB
self.save_sample('system.mem.cached', cached)
if committed_bytes is not None:
self.save_sample('system.mem.committed', int(committed_bytes) / B2MB)
if pool_paged_bytes is not None:
self.save_sample('system.mem.paged', int(pool_paged_bytes) / B2MB)
if pool_non_paged_bytes is not None:
self.save_sample('system.mem.nonpaged', int(pool_non_paged_bytes) / B2MB)
usable = free + cached
self.save_sample('system.mem.usable', usable)
if total > 0:
pct_usable = float(usable) / total
self.save_sample('system.mem.pct_usable', pct_usable)
page = psutil.virtual_memory()
if page.total is not None:
self.save_sample('system.mem.page_total', page.total / B2MB)
self.save_sample('system.mem.page_used', page.used / B2MB)
self.save_sample('system.mem.page_free', page.available / B2MB)
self.save_sample('system.mem.page_pct_free', (100 - page.percent) / 100)
return self.get_metrics()
class Cpu(Check):
def __init__(self, logger):
Check.__init__(self, logger)
# Sampler(s)
self.wmi_sampler = WMISampler(
logger,
"Win32_PerfRawData_PerfOS_Processor",
["Name", "PercentInterruptTime"]
)
self.counter('system.cpu.user')
self.counter('system.cpu.idle')
self.gauge('system.cpu.interrupt')
self.counter('system.cpu.system')
def check(self, agentConfig):
try:
self.wmi_sampler.sample()
except TimeoutException:
self.logger.warning(
u"Timeout while querying Win32_PerfRawData_PerfOS_Processor WMI class."
u" CPU metrics will be returned at next iteration."
)
return []
if not (len(self.wmi_sampler)):
self.logger.warning('Missing Win32_PerfRawData_PerfOS_Processor WMI class.'
' No CPU metrics will be returned')
return []
cpu_interrupt = self._average_metric(self.wmi_sampler, 'PercentInterruptTime')
if cpu_interrupt is not None:
self.save_sample('system.cpu.interrupt', cpu_interrupt)
cpu_percent = psutil.cpu_times()
self.save_sample('system.cpu.user', 100 * cpu_percent.user / psutil.cpu_count())
self.save_sample('system.cpu.idle', 100 * cpu_percent.idle / psutil.cpu_count())
self.save_sample('system.cpu.system', 100 * cpu_percent.system / psutil.cpu_count())
return self.get_metrics()
def _average_metric(self, sampler, wmi_prop):
''' Sum all of the values of a metric from a WMI class object, excluding
the value for "_Total"
'''
val = 0
counter = 0
for wmi_object in sampler:
if wmi_object['Name'] == '_Total':
# Skip the _Total value
continue
wmi_prop_value = wmi_object.get(wmi_prop)
if wmi_prop_value is not None:
counter += 1
val += float(wmi_prop_value)
if counter > 0:
return val / counter
return val
class Network(Check):
def __init__(self, logger):
Check.__init__(self, logger)
# Sampler(s)
self.wmi_sampler = WMISampler(
logger,
"Win32_PerfRawData_Tcpip_NetworkInterface",
["Name", "BytesReceivedPerSec", "BytesSentPerSec"]
)
self.gauge('system.net.bytes_rcvd')
self.gauge('system.net.bytes_sent')
def check(self, agentConfig):
try:
self.wmi_sampler.sample()
except TimeoutException:
self.logger.warning(
u"Timeout while querying Win32_PerfRawData_Tcpip_NetworkInterface WMI class."
u" Network metrics will be returned at next iteration."
)
return []
if not (len(self.wmi_sampler)):
self.logger.warning('Missing Win32_PerfRawData_Tcpip_NetworkInterface WMI class.'
' No network metrics will be returned')
return []
for iface in self.wmi_sampler:
name = iface.get('Name')
bytes_received_per_sec = iface.get('BytesReceivedPerSec')
bytes_sent_per_sec = iface.get('BytesSentPerSec')
name = self.normalize_device_name(name)
if bytes_received_per_sec is not None:
self.save_sample('system.net.bytes_rcvd', bytes_received_per_sec,
device_name=name)
if bytes_sent_per_sec is not None:
self.save_sample('system.net.bytes_sent', bytes_sent_per_sec,
device_name=name)
return self.get_metrics()
class IO(Check):
def __init__(self, logger):
Check.__init__(self, logger)
# Sampler(s)
self.wmi_sampler = WMISampler(
logger,
"Win32_PerfRawData_PerfDisk_LogicalDisk",
["Name", "DiskWriteBytesPerSec", "DiskWritesPerSec", "DiskReadBytesPerSec",
"DiskReadsPerSec", "CurrentDiskQueueLength"]
)
self.gauge('system.io.wkb_s')
self.gauge('system.io.w_s')
self.gauge('system.io.rkb_s')
self.gauge('system.io.r_s')
self.gauge('system.io.avg_q_sz')
def check(self, agentConfig):
try:
self.wmi_sampler.sample()
except TimeoutException:
self.logger.warning(
u"Timeout while querying Win32_PerfRawData_PerfDisk_LogicalDiskUnable WMI class."
u" I/O metrics will be returned at next iteration."
)
return []
if not (len(self.wmi_sampler)):
self.logger.warning('Missing Win32_PerfRawData_PerfDisk_LogicalDiskUnable WMI class.'
' No I/O metrics will be returned.')
return []
blacklist_re = agentConfig.get('device_blacklist_re', None)
for device in self.wmi_sampler:
name = device.get('Name')
disk_write_bytes_per_sec = device.get('DiskWriteBytesPerSec')
disk_writes_per_sec = device.get('DiskWritesPerSec')
disk_read_bytes_per_sec = device.get('DiskReadBytesPerSec')
disk_reads_per_sec = device.get('DiskReadsPerSec')
current_disk_queue_length = device.get('CurrentDiskQueueLength')
name = self.normalize_device_name(name)
if should_ignore_disk(name, blacklist_re):
continue
if disk_write_bytes_per_sec is not None:
self.save_sample('system.io.wkb_s', int(disk_write_bytes_per_sec) / B2KB,
device_name=name)
if disk_writes_per_sec is not None:
self.save_sample('system.io.w_s', int(disk_writes_per_sec),
device_name=name)
if disk_read_bytes_per_sec is not None:
self.save_sample('system.io.rkb_s', int(disk_read_bytes_per_sec) / B2KB,
device_name=name)
if disk_reads_per_sec is not None:
self.save_sample('system.io.r_s', int(disk_reads_per_sec),
device_name=name)
if current_disk_queue_length is not None:
self.save_sample('system.io.avg_q_sz', current_disk_queue_length,
device_name=name)
return self.get_metrics()
class System(Check):
def __init__(self, logger):
Check.__init__(self, logger)
self.gauge('system.uptime')
def check(self, agentConfig):
self.save_sample('system.uptime', uptime.uptime())
return self.get_metrics()
| {
"content_hash": "22afd3aab025bd04b285439c401ae4be",
"timestamp": "",
"source": "github",
"line_count": 375,
"max_line_length": 97,
"avg_line_length": 36.384,
"alnum_prop": 0.5786426267956611,
"repo_name": "tebriel/dd-agent",
"id": "0cc647eb1b7c878de0398d91aa68afb6654de91b",
"size": "13761",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "checks/system/win32.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "2717"
},
{
"name": "Go",
"bytes": "2389"
},
{
"name": "HTML",
"bytes": "9060"
},
{
"name": "Nginx",
"bytes": "3908"
},
{
"name": "PowerShell",
"bytes": "2665"
},
{
"name": "Python",
"bytes": "2175373"
},
{
"name": "Ruby",
"bytes": "102404"
},
{
"name": "Shell",
"bytes": "58131"
},
{
"name": "XSLT",
"bytes": "2222"
}
],
"symlink_target": ""
} |
"""
Modularized detection suite containing the phase_0 classes.
Authors: Johan Mickos jmickos@bu.edu
Josh Navon navonj@bu.edu
"""
# Standard library
import copy
import itertools
# External dependencies
import numpy as np
import cv2 as cv
# Project-specific
import utility
from utility import log
from generic import Detector
from config import DEBUG_LEVEL
class BoxExtractor(Detector):
"""This class locates and stores box coordinates in frames."""
def __init__(self,):
""""Class constructor. Overrides superclass method."""
self.set = False
def detect(self, cur_frame, frame_cnt):
"""Perform box extraction. Overrides superclass method."""
OFFSET = 10
# Force black frame to ensure first coord is top left of frame
border_frame = cv.copyMakeBorder(cur_frame, OFFSET, OFFSET, OFFSET, OFFSET, cv.BORDER_CONSTANT, (0, 0, 0))
# Treshold + grayscale for binary image
gray = cv.cvtColor(border_frame, cv.COLOR_BGR2GRAY)
_, gray = cv.threshold(gray, 30, 255, cv.THRESH_BINARY)
points = [None] * 2
# Evaluate black lines & extract box coordinates
for axis in (0, 1):
projection = gray.sum(axis=axis)
projection *= 255/(projection.max() + 1)
black_lines = np.where(projection <= 80)[0] - OFFSET + 1
clumps = np.split(black_lines, np.where(np.diff(black_lines) != 1)[0]+1)
black_lines = np.where(projection <= 25)[0] - OFFSET + 1
clumps = np.split(black_lines, np.where(np.diff(black_lines) != 1)[0] + 1)
coords = [(clumps[i][-1], clumps[i+1][0]) for i in range(len(clumps) - 1)]
filtered_coords = [coords[i] for i in np.where(np.diff(coords) > 125)[0]]
points[axis] = filtered_coords
if utility.in_range(len(points[0]), 0, 2) and \
utility.in_range(len(points[1]), 0, 2):
self.variables['player_regions'][:] = []
local = list()
for coord in itertools.product(points[0], points[1]):
local.append([(int(str(coord[0][0]), 10), int(str(coord[0][1]), 10)),
(int(str(coord[1][0]), 10), int(str(coord[1][1]), 10))])
self.variables['player_regions'] = self.sort_boxes(local, cur_frame)
if not self.set and self.variables['is_started']:
self.variables['locked_regions'] = copy.deepcopy(self.variables['player_regions'][0:self.variables['num_players']])
self.set = True
else:
# Completely black frame
self.variables['player_regions'] = [[(0, cur_frame.shape[1]), (0, cur_frame.shape[0])]]
def sort_boxes(self, boxes, cur_frame):
"""Sorting algorithm that places priority on "top left" boxes"""
if len(boxes) != 0:
ordered = list()
upper = np.max(boxes).astype(float)
for box in boxes:
box_normed = np.divide(box, upper)
rank = np.sum(100 * box_normed[1]) + np.sum(10 * box_normed[0])
ordered.append((box, rank))
ordered = sorted(ordered, key=lambda x:x[1])
result = [el[0] for el in ordered]
return result
else:
return [[(0, cur_frame.shape[1]), (0, cur_frame.shape[0])]]
class Characters(Detector):
"""Detector for detecting characters in MK64."""
def __init__(self, masks_dir, freq, threshold, default_shape, buf_len=None):
"""
Instantiates necessary variables and passes control off to superclass constructor.
Overrides superclass method.
"""
self.waiting_black = False
super(Characters, self).__init__(masks_dir, freq, threshold, default_shape, buf_len)
def detect(self, frame, cur_count, player):
"""Determines whether and how to process current frame. Overrides superclass method."""
height, width, _ = frame.shape
focus_region = frame[np.ceil(height * 0.25) : np.ceil(height * 0.95),
np.ceil(width * 0.25) : np.ceil(width * 0.75)]
if self.variables['is_black']:
if self.waiting_black:
self.store_players(focus_region)
else:
return
if not self.variables['is_started'] and (cur_count % self.freq == 0):
self.process(focus_region, cur_count, player)
if DEBUG_LEVEL > 3:
cv.imshow(self.name(), focus_region)
cv.waitKey(1)
def process(self, frame, cur_count, player):
""" Compares pre-loaded masks to current frame. Overrides superclass method."""
player = 0
if len(self.default_shape) != 1:
for mask, shape in zip(self.masks, self.default_shape):
if frame.shape != shape:
scaled_mask = (utility.scaleImage(frame,mask[0], shape), mask[1])
else:
scaled_mask = mask
distances = cv.matchTemplate(frame, scaled_mask[0], cv.TM_SQDIFF_NORMED)
minval, _, minloc, _ = cv.minMaxLoc(distances)
if minval <= self.threshold:
self.handle(frame, player, mask, cur_count, minloc)
if DEBUG_LEVEL > 1:
log("[%s]: Found %s :-) ------> %s" % (self.name(), mask[1], minval))
else:
for mask in self.masks:
if frame.shape != self.default_shape[0]:
scaled_mask = (utility.scaleImage(frame,mask[0], self.default_shape[0]), mask[1])
else:
scaled_mask = mask
distances = cv.matchTemplate(frame, scaled_mask[0], cv.TM_SQDIFF_NORMED)
minval, _, minloc, _ = cv.minMaxLoc(distances)
if minval <= self.threshold:
self.handle(frame, player, mask, cur_count, minloc)
if DEBUG_LEVEL > 1:
log("[%s]: Found %s :-) ------> %s" % (self.name(), mask[1], minval))
def handle(self, frame, player, mask, cur_count, location):
"""Perform checks and store variables. Overrides superclass method."""
self.waiting_black = True
timestamp = cur_count / self.variables['frame_rate']
idx = self.buffer.exists(mask[1])
if idx != -1:
self.buffer[idx] = (mask[1], location, timestamp)
else:
self.buffer.append((mask[1], location, timestamp))
def store_players(self, frame):
"""Stores players in the state variable."""
self.waiting_black = False
self.deactivate()
ordered = list()
max_place = 0
characters = utility.find_unique(self.buffer, 0)
semi_ordered = self.sort_characters(characters, frame)
# Find the largest rank in the list.
for element in semi_ordered:
if element[1] > max_place:
max_place = element[1]
# For every possible player number, find the most recent match
try:
for ii in xrange(1, (max_place + 1)):
timestamp = 0
for element in semi_ordered:
# Check if the char is player ii and if it was found after <timestamp>
if element[1] == ii and element[2] > timestamp:
timestamp = element[2]
temp = (element[0], element[1])
ordered.append(temp)
chars = [image[0].split(".", 1)[0] for image in ordered]
if DEBUG_LEVEL > 0:
for p, ch in enumerate(chars):
log("Player %i is %s" % ((p+1), ch))
self.variables['characters'] = chars
self.variables['num_players'] = len(ordered)
except UnboundLocalError:
# No chars detected?
self.variables['characters'] = None
self.variables['num_players'] = 0
def sort_characters(self, characters, frame):
"""Sorting algorithm that ranks based on quadrant."""
ordered = list()
center_y, center_x, _ = frame.shape
center_x /= 2
center_y /= 2
for char in characters:
# Quadrant 2 (Player 1)
if characters[char][0][1] < (center_x - 10) and characters[char][0][0] < (center_y - 10):
ordered.append((char, 1, characters[char][1]))
elif characters[char][0][1] > (center_x + 10) and characters[char][0][0] < (center_y - 10):
ordered.append((char, 2, characters[char][1]))
elif characters[char][0][1] < (center_x - 10) and characters[char][0][0] > (center_y + 10):
ordered.append((char, 3, characters[char][1]))
else:
ordered.append((char, 4, characters[char][1]))
ordered = sorted(ordered, key=lambda x: x[1])
return ordered
class Map(Detector):
"""Determines which map is being played."""
def __init__(self, masks_dir, freq, threshold, default_shape, buf_len=None):
"""
Instantiates necessary variables and passes control off to superclass constructor.
Overrides superclass method.
"""
self.waiting_black = False
self.map = ''
super(Map, self).__init__(masks_dir, freq, threshold, default_shape, buf_len)
def detect(self, frame, cur_count, player):
"""Determines whether and how to process current frame. Overrides superclass method."""
if self.variables['is_black']:
if self.waiting_black:
self.variables['map'] = self.map.split('.')[0]
self.waiting_black = False
if DEBUG_LEVEL > 0:
log('Locked in map as %s' % (self.map.split('.')[0]))
else:
return
if (cur_count % self.freq) == 0:
self.process(frame, cur_count, player)
def process(self, frame, cur_count, player):
""" Compares pre-loaded masks to current frame. Overrides superclass method."""
best_val = 1
best_mask = None
if frame != None:
# Convert to grayscale and threshold
binary = cv.cvtColor(frame , cv.COLOR_BGR2GRAY)
_, binary = cv.threshold(binary, 120, 255, cv.THRESH_BINARY)
binary = cv.GaussianBlur(binary, (3, 3), 1)
# Scale and grayscale the masks
if len(self.default_shape) != 1:
binary_roi = self.constrain_roi(binary)
for mask, shape in zip(self.masks, self.default_shape):
if frame.shape != shape:
scaled_mask = (cv.cvtColor(utility.scaleImage(frame, mask[0], shape),
cv.COLOR_BGR2GRAY), mask[1])
else:
scaled_mask = (cv.cvtColor(mask[0], cv.COLOR_BGR2GRAY), mask[1])
distances = cv.matchTemplate(binary_roi, scaled_mask[0], cv.TM_SQDIFF_NORMED)
minval, _, minloc, _ = cv.minMaxLoc(distances)
if minval <= self.threshold and minval < best_val:
best_val = minval
best_mask = scaled_mask
if DEBUG_LEVEL > 3:
cv.imshow('Map Thresh', binary_roi)
cv.waitKey(1)
if best_mask is not None:
self.handle(frame, player, best_mask, cur_count, minloc)
if DEBUG_LEVEL > 1:
log("[%s]: Found %s :-) ------> %s" % (self.name(), best_mask[1], best_val))
else:
binary_roi = self.constrain_roi(binary)
for mask in self.masks:
if frame.shape != self.default_shape[0]:
scaled_mask = (cv.cvtColor(utility.scaleImage(frame,mask[0], self.default_shape[0]),
cv.COLOR_BGR2GRAY), mask[1])
else:
scaled_mask = (cv.cvtColor(mask[0], cv.COLOR_BGR2GRAY), mask[1])
distances = cv.matchTemplate(binary_roi, scaled_mask[0], cv.TM_SQDIFF_NORMED)
minval, _, minloc, _ = cv.minMaxLoc(distances)
if minval <= self.threshold and minval < best_val:
best_val = minval
best_mask = scaled_mask
if DEBUG_LEVEL > 3:
cv.imshow('Map Thresh', binary_roi)
cv.waitKey(1)
if best_mask is not None:
self.handle(frame, player, best_mask, cur_count, minloc)
if DEBUG_LEVEL > 1:
log("[%s]: Found %s :-) ------> %s" % (self.name(), best_mask[1], best_val))
def handle(self, frame, player, mask, cur_count, location):
"""Set variables. Overrides superclass method."""
self.map = mask[1]
self.waiting_black = True
if DEBUG_LEVEL > 0:
log('[%s]: Map is: %s' % (self.name(), mask[1].split('.')[0]))
def constrain_roi(self, frame):
""""Constrains frame w.r.t. Maps. Overrides superclass method."""
h, w = frame.shape
frame = frame[np.ceil(h * 0.4):, np.ceil(w * 0.45):np.ceil(w * 0.92)]
return frame
class StartRace(Detector):
"""Handles the beginning of a race in phase_0"""
def handle(self, frame, player, mask, cur_count, location):
"""Store variables and toggle detectors. Overrides superclass method."""
self.variables['is_started'] = True
self.deactivate()
self.activate('EndRace')
self.deactivate('Characters')
self.deactivate('Map')
# Lock in player boxes (should be sorted alreadY)
self.variables['player_regions'] = self.variables['player_regions'][0:self.variables['num_players']]
# Populate dictionary with start time
self.variables['start_time'] = np.floor(cur_count / self.variables['frame_rate']) - 2
if DEBUG_LEVEL > 0:
log('[%s]: Started at %d seconds' % (self.name(), self.variables['start_time']))
def constrain_roi(self, frame):
"""Constrains frame w.r.t. StartRace/BeginRace. Overrides superclass method."""
h, w, _ = frame.shape
frame = frame[0:np.ceil(h * 0.5), np.ceil(w * 0.4):np.ceil(w * 0.75)]
return frame
class EndRace(Detector):
"""Handles the end of a race (phase_0)"""
def __init__(self):
"""Class constructor. Overrides superclass method."""
pass
def detect(self, frame, cur_count, player):
"""Determines whether and how to process current frame. Overrides superclass method."""
if self.variables['is_started']:
if self.variables['is_black']:
# Either rage-quit or clean race finish (we'll handle rage quits later)
self.handle(cur_count)
else:
self.deactivate()
def handle(self, cur_count):
"""Store variables and toggle detectors. Overrides superclass method."""
self.variables['is_started'] = False
# Populate dictionary with race duration
self.variables['duration'] = np.ceil((cur_count / self.variables['frame_rate']) - self.variables['start_time'])
# On end race, deactivate EndRaceDetector, activate StartRaceDetector, BoxExtractor, and CharDetector
self.deactivate()
self.activate('StartRace')
self.activate('Characters')
self.activate('Map')
self.activate('BoxExtractor')
# Store as event for splitting
self.create_event(start_time=self.variables['start_time'],
duration=self.variables['duration'],
course=self.variables['map'])
if DEBUG_LEVEL > 0:
log("[%s] Duration = %2.2f seconds" % (self.name(), self.variables['duration']))
| {
"content_hash": "6dbf134af848591069ddf8189f593158",
"timestamp": "",
"source": "github",
"line_count": 344,
"max_line_length": 131,
"avg_line_length": 46.42732558139535,
"alnum_prop": 0.5493081209692567,
"repo_name": "kartyboyz/n64-img-processing",
"id": "4e66cf81b65625c1cb91d0afaf442ef605103392",
"size": "15971",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "detection/splitting.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "1637"
}
],
"symlink_target": ""
} |
import unittest
from Cython.Compiler import Code, UtilityCode
def strip_2tup(tup):
return tup[0] and tup[0].strip(), tup[1] and tup[1].strip()
class TestUtilityLoader(unittest.TestCase):
"""
Test loading UtilityCodes
"""
expected = "test {{loader}} prototype", "test {{loader}} impl"
required = "req {{loader}} proto", "req {{loader}} impl"
context = dict(loader='Loader')
name = "TestUtilityLoader"
filename = "TestUtilityLoader.c"
cls = Code.UtilityCode
def test_load_as_string(self):
got = strip_2tup(self.cls.load_as_string(self.name))
self.assertEqual(got, self.expected)
got = strip_2tup(self.cls.load_as_string(self.name, self.filename))
self.assertEqual(got, self.expected)
def test_load(self):
utility = self.cls.load(self.name)
got = strip_2tup((utility.proto, utility.impl))
self.assertEqual(got, self.expected)
required, = utility.requires
got = strip_2tup((required.proto, required.impl))
self.assertEqual(got, self.required)
utility = self.cls.load(self.name, from_file=self.filename)
got = strip_2tup((utility.proto, utility.impl))
self.assertEqual(got, self.expected)
utility = self.cls.load_cached(self.name, from_file=self.filename)
got = strip_2tup((utility.proto, utility.impl))
self.assertEqual(got, self.expected)
class TestTempitaUtilityLoader(TestUtilityLoader):
"""
Test loading UtilityCodes with Tempita substitution
"""
expected_tempita = (TestUtilityLoader.expected[0].replace('{{loader}}', 'Loader'),
TestUtilityLoader.expected[1].replace('{{loader}}', 'Loader'))
required_tempita = (TestUtilityLoader.required[0].replace('{{loader}}', 'Loader'),
TestUtilityLoader.required[1].replace('{{loader}}', 'Loader'))
cls = Code.TempitaUtilityCode
def test_load_as_string(self):
got = strip_2tup(self.cls.load_as_string(self.name, context=self.context))
self.assertEqual(got, self.expected_tempita)
def test_load(self):
utility = self.cls.load(self.name, context=self.context)
got = strip_2tup((utility.proto, utility.impl))
self.assertEqual(got, self.expected_tempita)
required, = utility.requires
got = strip_2tup((required.proto, required.impl))
self.assertEqual(got, self.required_tempita)
utility = self.cls.load(self.name, from_file=self.filename, context=self.context)
got = strip_2tup((utility.proto, utility.impl))
self.assertEqual(got, self.expected_tempita)
class TestCythonUtilityLoader(TestTempitaUtilityLoader):
"""
Test loading CythonUtilityCodes
"""
# Just change the attributes and run the same tests
expected = None, "test {{cy_loader}} impl"
expected_tempita = None, "test CyLoader impl"
required = None, "req {{cy_loader}} impl"
required_tempita = None, "req CyLoader impl"
context = dict(cy_loader='CyLoader')
name = "TestCyUtilityLoader"
filename = "TestCyUtilityLoader.pyx"
cls = UtilityCode.CythonUtilityCode
# Small hack to pass our tests above
cls.proto = None
test_load = TestUtilityLoader.test_load
test_load_tempita = TestTempitaUtilityLoader.test_load
| {
"content_hash": "52254da48b95700df0c583c15e787a91",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 89,
"avg_line_length": 33.07920792079208,
"alnum_prop": 0.6623765339718647,
"repo_name": "ryfeus/lambda-packs",
"id": "3d1906ca0b4af934a969a2b2499d3adcbaea1df7",
"size": "3341",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "HDF4_H5_NETCDF/source2.7/Cython/Compiler/Tests/TestUtilityLoad.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "9768343"
},
{
"name": "C++",
"bytes": "76566960"
},
{
"name": "CMake",
"bytes": "191097"
},
{
"name": "CSS",
"bytes": "153538"
},
{
"name": "Cuda",
"bytes": "61768"
},
{
"name": "Cython",
"bytes": "3110222"
},
{
"name": "Fortran",
"bytes": "110284"
},
{
"name": "HTML",
"bytes": "248658"
},
{
"name": "JavaScript",
"bytes": "62920"
},
{
"name": "MATLAB",
"bytes": "17384"
},
{
"name": "Makefile",
"bytes": "152150"
},
{
"name": "Python",
"bytes": "549307737"
},
{
"name": "Roff",
"bytes": "26398"
},
{
"name": "SWIG",
"bytes": "142"
},
{
"name": "Shell",
"bytes": "7790"
},
{
"name": "Smarty",
"bytes": "4090"
},
{
"name": "TeX",
"bytes": "152062"
},
{
"name": "XSLT",
"bytes": "305540"
}
],
"symlink_target": ""
} |
from __future__ import division
import warnings
from qiita_core.exceptions import QiitaError
class QiitaDBError(QiitaError):
"""Base class for all qiita_db exceptions"""
pass
class QiitaDBNotImplementedError(QiitaDBError):
""""""
pass
class QiitaDBExecutionError(QiitaDBError):
"""Exception for error when executing SQL queries"""
pass
class QiitaDBConnectionError(QiitaDBError):
"""Exception for error when connecting to the db"""
pass
class QiitaDBColumnError(QiitaDBError):
"""Exception when missing table information or excess information passed"""
pass
class QiitaDBLookupError(QiitaDBError, LookupError):
"""Exception when converting or getting non-existant values in DB"""
pass
class QiitaDBOperationNotPermittedError(QiitaDBError):
"""Exception when perofrming an operation not permitted"""
pass
class QiitaDBArtifactCreationError(QiitaDBError):
"""Exception when creating an artifact"""
def __init__(self, reason):
super(QiitaDBArtifactCreationError, self).__init__()
self.args = ("Cannot create artifact: %s" % reason,)
class QiitaDBArtifactDeletionError(QiitaDBError):
"""Exception when deleting an artifact"""
def __init__(self, a_id, reason):
super(QiitaDBArtifactDeletionError, self).__init__()
self.args = ("Cannot delete artifact %d: %s" % (a_id, reason),)
class QiitaDBDuplicateError(QiitaDBError):
"""Exception when duplicating something in the database"""
def __init__(self, obj_name, attributes):
super(QiitaDBDuplicateError, self).__init__()
self.args = ("The '%s' object with attributes (%s) already exists."
% (obj_name, attributes),)
class QiitaDBStatusError(QiitaDBError):
"""Exception when editing is done with an unallowed status"""
pass
class QiitaDBUnknownIDError(QiitaDBError):
"""Exception for error when an object does not exists in the DB"""
def __init__(self, missing_id, table):
super(QiitaDBUnknownIDError, self).__init__()
self.args = ("The object with ID '%s' does not exists in table '%s'"
% (missing_id, table),)
class QiitaDBDuplicateHeaderError(QiitaDBError):
"""Exception for error when a MetadataTemplate has duplicate columns"""
def __init__(self, repeated_headers):
super(QiitaDBDuplicateHeaderError, self).__init__()
self.args = ("Duplicate headers found in MetadataTemplate. Note "
"that the headers are not case-sensitive, repeated "
"header(s): %s." % ', '.join(repeated_headers),)
class QiitaDBDuplicateSamplesError(QiitaDBError):
"""Exception for error when a MetadataTemplate has duplicate columns"""
def __init__(self, repeated_samples):
super(QiitaDBDuplicateSamplesError, self).__init__()
self.args = ("Duplicate samples found in MetadataTemplate: %s."
% ', '.join(repeated_samples),)
class QiitaDBIncompatibleDatatypeError(QiitaDBError):
"""When arguments are used with incompatible operators in a query"""
def __init__(self, operator, argument_type):
super(QiitaDBIncompatibleDatatypeError, self).__init__()
self.args = ("The %s operator is not for use with data of type %s" %
(operator, str(argument_type)))
class QiitaDBWarning(UserWarning):
"""Warning specific for the QiitaDB domain"""
pass
warnings.simplefilter('always', QiitaDBWarning)
| {
"content_hash": "c05f3963461213a5d77c95445e4fb926",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 79,
"avg_line_length": 33.028301886792455,
"alnum_prop": 0.6783776063981719,
"repo_name": "squirrelo/qiita",
"id": "eea058c864c9a68700fffec321be050924b6a4ac",
"size": "3852",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "qiita_db/exceptions.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "1692"
},
{
"name": "HTML",
"bytes": "449930"
},
{
"name": "JavaScript",
"bytes": "5876"
},
{
"name": "Makefile",
"bytes": "6838"
},
{
"name": "PLSQL",
"bytes": "2359"
},
{
"name": "PLpgSQL",
"bytes": "45311"
},
{
"name": "Python",
"bytes": "1696427"
},
{
"name": "SQLPL",
"bytes": "6192"
},
{
"name": "Shell",
"bytes": "3062"
}
],
"symlink_target": ""
} |
"""
OpenStack Client interface. Handles the REST calls and responses.
"""
# E0202: An attribute inherited from %s hide this method
# pylint: disable=E0202
import hashlib
import logging
import time
try:
import simplejson as json
except ImportError:
import json
from oslo_utils import encodeutils
from oslo_utils import importutils
import requests
from bileanclient.openstack.common._i18n import _
from bileanclient.openstack.common.apiclient import exceptions
_logger = logging.getLogger(__name__)
SENSITIVE_HEADERS = ('X-Auth-Token', 'X-Subject-Token',)
class HTTPClient(object):
"""This client handles sending HTTP requests to OpenStack servers.
Features:
- share authentication information between several clients to different
services (e.g., for compute and image clients);
- reissue authentication request for expired tokens;
- encode/decode JSON bodies;
- raise exceptions on HTTP errors;
- pluggable authentication;
- store authentication information in a keyring;
- store time spent for requests;
- register clients for particular services, so one can use
`http_client.identity` or `http_client.compute`;
- log requests and responses in a format that is easy to copy-and-paste
into terminal and send the same request with curl.
"""
user_agent = "bileanclient.openstack.common.apiclient"
def __init__(self,
auth_plugin,
region_name=None,
endpoint_type="publicURL",
original_ip=None,
verify=True,
cert=None,
timeout=None,
timings=False,
keyring_saver=None,
debug=False,
user_agent=None,
http=None):
self.auth_plugin = auth_plugin
self.endpoint_type = endpoint_type
self.region_name = region_name
self.original_ip = original_ip
self.timeout = timeout
self.verify = verify
self.cert = cert
self.keyring_saver = keyring_saver
self.debug = debug
self.user_agent = user_agent or self.user_agent
self.times = [] # [("item", starttime, endtime), ...]
self.timings = timings
# requests within the same session can reuse TCP connections from pool
self.http = http or requests.Session()
self.cached_token = None
self.last_request_id = None
def _safe_header(self, name, value):
if name in SENSITIVE_HEADERS:
# because in python3 byte string handling is ... ug
v = value.encode('utf-8')
h = hashlib.sha1(v)
d = h.hexdigest()
return encodeutils.safe_decode(name), "{SHA1}%s" % d
else:
return (encodeutils.safe_decode(name),
encodeutils.safe_decode(value))
def _http_log_req(self, method, url, kwargs):
if not self.debug:
return
string_parts = [
"curl -g -i",
"-X '%s'" % method,
"'%s'" % url,
]
for element in kwargs['headers']:
header = ("-H '%s: %s'" %
self._safe_header(element, kwargs['headers'][element]))
string_parts.append(header)
_logger.debug("REQ: %s" % " ".join(string_parts))
if 'data' in kwargs:
_logger.debug("REQ BODY: %s\n" % (kwargs['data']))
def _http_log_resp(self, resp):
if not self.debug:
return
_logger.debug(
"RESP: [%s] %s\n",
resp.status_code,
resp.headers)
if resp._content_consumed:
_logger.debug(
"RESP BODY: %s\n",
resp.text)
def serialize(self, kwargs):
if kwargs.get('json') is not None:
kwargs['headers']['Content-Type'] = 'application/json'
kwargs['data'] = json.dumps(kwargs['json'])
try:
del kwargs['json']
except KeyError:
pass
def get_timings(self):
return self.times
def reset_timings(self):
self.times = []
def request(self, method, url, **kwargs):
"""Send an http request with the specified characteristics.
Wrapper around `requests.Session.request` to handle tasks such as
setting headers, JSON encoding/decoding, and error handling.
:param method: method of HTTP request
:param url: URL of HTTP request
:param kwargs: any other parameter that can be passed to
requests.Session.request (such as `headers`) or `json`
that will be encoded as JSON and used as `data` argument
"""
kwargs.setdefault("headers", {})
kwargs["headers"]["User-Agent"] = self.user_agent
if self.original_ip:
kwargs["headers"]["Forwarded"] = "for=%s;by=%s" % (
self.original_ip, self.user_agent)
if self.timeout is not None:
kwargs.setdefault("timeout", self.timeout)
kwargs.setdefault("verify", self.verify)
if self.cert is not None:
kwargs.setdefault("cert", self.cert)
self.serialize(kwargs)
self._http_log_req(method, url, kwargs)
if self.timings:
start_time = time.time()
resp = self.http.request(method, url, **kwargs)
if self.timings:
self.times.append(("%s %s" % (method, url),
start_time, time.time()))
self._http_log_resp(resp)
self.last_request_id = resp.headers.get('x-openstack-request-id')
if resp.status_code >= 400:
_logger.debug(
"Request returned failure status: %s",
resp.status_code)
raise exceptions.from_response(resp, method, url)
return resp
@staticmethod
def concat_url(endpoint, url):
"""Concatenate endpoint and final URL.
E.g., "http://keystone/v2.0/" and "/tokens" are concatenated to
"http://keystone/v2.0/tokens".
:param endpoint: the base URL
:param url: the final URL
"""
return "%s/%s" % (endpoint.rstrip("/"), url.strip("/"))
def client_request(self, client, method, url, **kwargs):
"""Send an http request using `client`'s endpoint and specified `url`.
If request was rejected as unauthorized (possibly because the token is
expired), issue one authorization attempt and send the request once
again.
:param client: instance of BaseClient descendant
:param method: method of HTTP request
:param url: URL of HTTP request
:param kwargs: any other parameter that can be passed to
`HTTPClient.request`
"""
filter_args = {
"endpoint_type": client.endpoint_type or self.endpoint_type,
"service_type": client.service_type,
}
token, endpoint = (self.cached_token, client.cached_endpoint)
just_authenticated = False
if not (token and endpoint):
try:
token, endpoint = self.auth_plugin.token_and_endpoint(
**filter_args)
except exceptions.EndpointException:
pass
if not (token and endpoint):
self.authenticate()
just_authenticated = True
token, endpoint = self.auth_plugin.token_and_endpoint(
**filter_args)
if not (token and endpoint):
raise exceptions.AuthorizationFailure(
_("Cannot find endpoint or token for request"))
old_token_endpoint = (token, endpoint)
kwargs.setdefault("headers", {})["X-Auth-Token"] = token
self.cached_token = token
client.cached_endpoint = endpoint
# Perform the request once. If we get Unauthorized, then it
# might be because the auth token expired, so try to
# re-authenticate and try again. If it still fails, bail.
try:
return self.request(
method, self.concat_url(endpoint, url), **kwargs)
except exceptions.Unauthorized as unauth_ex:
if just_authenticated:
raise
self.cached_token = None
client.cached_endpoint = None
if self.auth_plugin.opts.get('token'):
self.auth_plugin.opts['token'] = None
if self.auth_plugin.opts.get('endpoint'):
self.auth_plugin.opts['endpoint'] = None
self.authenticate()
try:
token, endpoint = self.auth_plugin.token_and_endpoint(
**filter_args)
except exceptions.EndpointException:
raise unauth_ex
if (not (token and endpoint) or
old_token_endpoint == (token, endpoint)):
raise unauth_ex
self.cached_token = token
client.cached_endpoint = endpoint
kwargs["headers"]["X-Auth-Token"] = token
return self.request(
method, self.concat_url(endpoint, url), **kwargs)
def add_client(self, base_client_instance):
"""Add a new instance of :class:`BaseClient` descendant.
`self` will store a reference to `base_client_instance`.
Example:
>>> def test_clients():
... from keystoneclient.auth import keystone
... from openstack.common.apiclient import client
... auth = keystone.KeystoneAuthPlugin(
... username="user", password="pass", tenant_name="tenant",
... auth_url="http://auth:5000/v2.0")
... openstack_client = client.HTTPClient(auth)
... # create nova client
... from novaclient.v1_1 import client
... client.Client(openstack_client)
... # create keystone client
... from keystoneclient.v2_0 import client
... client.Client(openstack_client)
... # use them
... openstack_client.identity.tenants.list()
... openstack_client.compute.servers.list()
"""
service_type = base_client_instance.service_type
if service_type and not hasattr(self, service_type):
setattr(self, service_type, base_client_instance)
def authenticate(self):
self.auth_plugin.authenticate(self)
# Store the authentication results in the keyring for later requests
if self.keyring_saver:
self.keyring_saver.save(self)
class BaseClient(object):
"""Top-level object to access the OpenStack API.
This client uses :class:`HTTPClient` to send requests. :class:`HTTPClient`
will handle a bunch of issues such as authentication.
"""
service_type = None
endpoint_type = None # "publicURL" will be used
cached_endpoint = None
def __init__(self, http_client, extensions=None):
self.http_client = http_client
http_client.add_client(self)
# Add in any extensions...
if extensions:
for extension in extensions:
if extension.manager_class:
setattr(self, extension.name,
extension.manager_class(self))
def client_request(self, method, url, **kwargs):
return self.http_client.client_request(
self, method, url, **kwargs)
@property
def last_request_id(self):
return self.http_client.last_request_id
def head(self, url, **kwargs):
return self.client_request("HEAD", url, **kwargs)
def get(self, url, **kwargs):
return self.client_request("GET", url, **kwargs)
def post(self, url, **kwargs):
return self.client_request("POST", url, **kwargs)
def put(self, url, **kwargs):
return self.client_request("PUT", url, **kwargs)
def delete(self, url, **kwargs):
return self.client_request("DELETE", url, **kwargs)
def patch(self, url, **kwargs):
return self.client_request("PATCH", url, **kwargs)
@staticmethod
def get_class(api_name, version, version_map):
"""Returns the client class for the requested API version
:param api_name: the name of the API, e.g. 'compute', 'image', etc
:param version: the requested API version
:param version_map: a dict of client classes keyed by version
:rtype: a client class for the requested API version
"""
try:
client_path = version_map[str(version)]
except (KeyError, ValueError):
msg = _("Invalid %(api_name)s client version '%(version)s'. "
"Must be one of: %(version_map)s") % {
'api_name': api_name,
'version': version,
'version_map': ', '.join(version_map.keys())}
raise exceptions.UnsupportedVersion(msg)
return importutils.import_class(client_path)
| {
"content_hash": "2a23a573de1902794ae9d118d17eb0ae",
"timestamp": "",
"source": "github",
"line_count": 368,
"max_line_length": 78,
"avg_line_length": 35.51086956521739,
"alnum_prop": 0.5772115090296909,
"repo_name": "lvdongbing/python-bileanclient",
"id": "c6e4ddc6d180aa57f6b432d4ddee5a1ae48823b6",
"size": "13888",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bileanclient/openstack/common/apiclient/client.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "218266"
}
],
"symlink_target": ""
} |
from distutils.core import setup
setup(
name="s3ts",
version="0.1.0",
author="Tim Docker",
author_email="timd@helixta.com.au",
# Contents
packages=["s3ts"],
package_dir={'' : 'src'},
include_package_data=False,
# Details
url="https://bitbucket.org/helix-collective/s3ts/wiki/Home",
description="A library to manage versioned tree based data on S3",
install_requires=[
"boto",
"requests"
],
)
| {
"content_hash": "80ec0a2f99bb403e75d7d11218d43dec",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 70,
"avg_line_length": 18,
"alnum_prop": 0.6047008547008547,
"repo_name": "helix-collective/s3ts",
"id": "b39b88709ecccba48a4d572c04cac5128244dccb",
"size": "468",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "91049"
},
{
"name": "Shell",
"bytes": "1369"
}
],
"symlink_target": ""
} |
"""Leetcode 438. Find All Anagrams in a String
Medium
URL: https://leetcode.com/problems/find-all-anagrams-in-a-string/
Given a string s and a non-empty string p, find all the start indices of p's
anagrams in s.
Strings consists of lowercase English letters only and the length of both strings
s and p will not be larger than 20,100.
The order of output does not matter.
Example 1:
Input:
s: "cbaebabacd" p: "abc"
Output:
[0, 6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
Example 2:
Input:
s: "abab" p: "ab"
Output:
[0, 1, 2]
Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".
"""
class SolutionCharCountListSlidingWindow(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
Time complexity: O(n), where n is length of s.
Space complexity: O(1).
"""
# Edge case.
if not s or len(s) < len(p):
return []
result = []
len_p = len(p)
len_s = len(s)
# Create array of length 26 to aggregate char's count for p.
p_char_counts = [0] * 26
for i in range(len_p):
p_char_counts[ord(p[i]) - ord('a')] += 1
# In s, apply sliding window of length p to get char's count.
s_char_counts = [0] * 26
# Initialize sliding window except the p's last char.
for i in range(len_p - 1):
s_char_counts[ord(s[i]) - ord('a')] += 1
for i in range(len_p - 1, len_s):
# Increment by RHS char of sliding window of s.
s_char_counts[ord(s[i]) - ord('a')] += 1
# Decrement by LHS char of sliding window of s.
if i - len_p >= 0:
s_char_counts[ord(s[i - len_p]) - ord('a')] -= 1
if s_char_counts == p_char_counts:
# Append start index of sliding window.
result.append(i - len_p + 1)
return result
def main():
# Output: [0, 6]
s = "cbaebabacd"
p = "abc"
print SolutionCharCountListSlidingWindow().findAnagrams(s, p)
# Output: [0, 1, 2]
s = "abab"
p = "ab"
print SolutionCharCountListSlidingWindow().findAnagrams(s, p)
if __name__ == '__main__':
main()
| {
"content_hash": "9e0149f904f05ae3bc776660209db2ce",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 81,
"avg_line_length": 27.129032258064516,
"alnum_prop": 0.5798652397938961,
"repo_name": "bowen0701/algorithms_data_structures",
"id": "6e4b445c9e1ac5bccc613b5bae98e1959d907df3",
"size": "2523",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lc0438_find_all_anagrams_in_a_string.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Python",
"bytes": "108750"
}
],
"symlink_target": ""
} |
'''
This case can not execute parallelly
@author: Legion
'''
import os
import time
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.operations.host_operations as host_ops
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.volume_operations as vol_ops
import zstackwoodpecker.operations.vm_operations as vm_ops
_config_ = {
'timeout' : 600,
'noparallel' : True
}
test_stub = test_lib.lib_get_test_stub()
test_obj_dict = test_state.TestStateDict()
new_offering_uuid = None
def test():
global new_offering_uuid
test_util.test_dsc('Test VM disk bandwidth QoS by 20MB')
#unit is KB
write_bandwidth = 15*1024*1024
read_bandwidth = 20*1024*1024
new_offering = test_lib.lib_create_instance_offering(read_bandwidth=read_bandwidth, write_bandwidth=write_bandwidth)
new_offering_uuid = new_offering.uuid
vm = test_stub.create_vm(vm_name = 'vm_volume_qos', \
instance_offering_uuid = new_offering.uuid)
test_obj_dict.add_vm(vm)
vm.check()
volume_creation_option = test_util.VolumeOption()
disk_offering = test_lib.lib_get_disk_offering_by_name(os.environ.get('largeDiskOfferingName'))
volume_creation_option.set_disk_offering_uuid(disk_offering.uuid)
volume_creation_option.set_name('volume-1')
volume = test_stub.create_volume(volume_creation_option)
test_obj_dict.add_volume(volume)
vm_inv = vm.get_vm()
# test_lib.lib_mkfs_for_volume(volume.get_volume().uuid, vm_inv)
# mount_point = '/tmp/zstack/test'
# test_stub.attach_mount_volume(volume, vm, mount_point)
test_stub.make_ssh_no_password(vm_inv)
test_stub.install_fio(vm_inv)
if vm_ops.get_vm_disk_qos(test_lib.lib_get_root_volume(vm_inv).uuid).volumeBandwidthRead != read_bandwidth and \
vm_ops.get_vm_disk_qos(test_lib.lib_get_root_volume(vm_inv).uuid).volumeBandwidthWrite != write_bandwidth:
test_util.test_fail('Retrieved disk qos not match')
test_stub.test_fio_bandwidth(vm_inv, read_bandwidth, '/dev/vda')
time.sleep(10)
test_stub.test_fio_bandwidth(vm_inv, write_bandwidth)
vm_ops.delete_instance_offering(new_offering_uuid)
test_lib.lib_robot_cleanup(test_obj_dict)
test_util.test_pass('VM Disk read & write QoS Test Pass')
#Will be called only if exception happens in test().
def error_cleanup():
test_lib.lib_error_cleanup(test_obj_dict)
try:
vm_ops.delete_instance_offering(new_offering_uuid)
except:
pass
| {
"content_hash": "eabf13175735d02fe95fc07cc075c6f3",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 120,
"avg_line_length": 37.11267605633803,
"alnum_prop": 0.7157495256166982,
"repo_name": "zstackio/zstack-woodpecker",
"id": "381e0b48cf4fc32bf6fb76bb553422cf2fe30384",
"size": "2635",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "integrationtest/vm/virt_plus/qos/test_disk_rw_qos.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2356"
},
{
"name": "Go",
"bytes": "49822"
},
{
"name": "Makefile",
"bytes": "687"
},
{
"name": "Puppet",
"bytes": "875"
},
{
"name": "Python",
"bytes": "13070596"
},
{
"name": "Shell",
"bytes": "177861"
}
],
"symlink_target": ""
} |
from insights.parsers import krb5
from insights.tests import context_wrap
KRB5CONFIG = """
# Configuration snippets may be placed in this directory as well
includedir /etc/krb5.conf.d/
include /etc/krb5test.conf
module /etc/krb5test.conf:residual
[logging]
default = FILE:/var/log/krb5libs.log
kdc = FILE:/var/log/krb5kdc.log
admin_server = FILE:/var/log/kadmind.log
[realms]
dns_lookup_realm = false
default_ccache_name = KEYRING:persistent:%{uid}
default_ccache_name2 = KEYRING:%{uid}:persistent
kdc_default_options = default.example.com
kdc_default_options = default2.example.com
EXAMPLE.COM = {
kdc = kerberos.example.com
admin_server = kerberos.example.com
auth_to_local = RULE:[1:$1@$0](.*@.*EXAMPLE.ORG)s/@.*//
}
EXAMPLE4.COM = {
kdc = kerberos.example4.com
admin_server = kerberos.example4.com
}
ticket_lifetime = 24h
[libdefaults]
dnsdsd = false
tilnvs = 24h
default_ccache_name = KEYRING:%{uid}:persistent
EXAMPLE2.COM = {
kdc = kerberos.example2.com
admin_server = kerberos.example2.com
}
EXAMPLE3.COM = {
kdc = kerberos.example3.com
admin_server = kerberos.example3.com *
}
# renew_lifetime = 7d
# forwardable = true
# rdns = false
""".strip()
KRB5CONFIG2 = """
# Configuration snippets may be placed in this directory as well
""".strip()
KRB5DCONFIG = """
# Configuration snippets may be placed in this directory as well
[logging]
default = FILE:/var/log/krb5libs.log
kdc = FILE:/var/log/krb5kdc.log
[realms]
dns_lookup_realm = false
ticket_lifetime = 24h
# default_ccache_name = KEYRING:persistent:%{uid}
EXAMPLE.COM = {
kdc = kerberos.example.com
kdc = test2.example.com
kdc = test3.example.com
admin_server = kerberos.example.com
}
[logging]
default = FILE:/var/log/krb5libs.log
kdc = FILE:/var/log/krb5kdc.log *
admin_server = FILE:/var/log/kadmind.log
""".strip()
KRB5_CONF_PATH = "etc/krb5.conf"
KRB5_DCONF_PATH = "etc/krb5.conf.d/test.conf"
def test_krb5configuration():
common_conf_info = krb5.Krb5Configuration(context_wrap(KRB5CONFIG, path=KRB5_CONF_PATH))
assert common_conf_info["libdefaults"]["dnsdsd"] == "false"
assert "renew_lifetime" not in common_conf_info.data.keys()
assert common_conf_info["realms"]["EXAMPLE.COM"]["kdc"] == "kerberos.example.com"
assert common_conf_info["realms"]["default_ccache_name"] == "KEYRING:persistent:%{uid}"
assert common_conf_info["libdefaults"]["default_ccache_name"] == "KEYRING:%{uid}:persistent"
assert common_conf_info["realms"]["kdc_default_options"] == ["default.example.com", "default2.example.com"]
assert "realms" in common_conf_info.sections()
assert "realmstest" not in common_conf_info.sections()
assert common_conf_info.has_section("realms")
assert not common_conf_info.has_option("realms", "nosuchoption")
assert not common_conf_info.has_option("nosucsection", "nosuchoption")
assert not common_conf_info.options("realmsno")
assert common_conf_info.options("logging") == ['default', 'admin_server', 'kdc']
assert common_conf_info.include == ["/etc/krb5test.conf"]
assert common_conf_info.includedir == ["/etc/krb5.conf.d/"]
assert common_conf_info.module == ["/etc/krb5test.conf:residual"]
def test2_krb5configuration():
common_conf_info = krb5.Krb5Configuration(context_wrap(KRB5CONFIG2, path=KRB5_CONF_PATH))
assert common_conf_info.data == {}
def test_krb5Dconfiguration():
common_conf_info = krb5.Krb5Configuration(context_wrap(KRB5DCONFIG, path=KRB5_DCONF_PATH))
assert common_conf_info["realms"]["ticket_lifetime"] == "24h"
assert "default_ccache_name" not in common_conf_info.data.keys()
assert common_conf_info["realms"]["EXAMPLE.COM"]["kdc"] == ['kerberos.example.com', 'test2.example.com', 'test3.example.com']
assert not common_conf_info.has_option("logging", "admin_server")
| {
"content_hash": "66d9a305af05cced9ca51e0079063963",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 129,
"avg_line_length": 34.223214285714285,
"alnum_prop": 0.7117140620923559,
"repo_name": "wcmitchell/insights-core",
"id": "22153a3368adcfb838df1246c3e74b2f11af5f67",
"size": "3833",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "insights/parsers/tests/test_krb5.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Clojure",
"bytes": "19339"
},
{
"name": "Jupyter Notebook",
"bytes": "91793"
},
{
"name": "Python",
"bytes": "3414025"
},
{
"name": "Shell",
"bytes": "2274"
}
],
"symlink_target": ""
} |
from ._models_py3 import Operation
from ._models_py3 import OperationDisplay
from ._models_py3 import OperationListResult
from ._models_py3 import ResourceLink
from ._models_py3 import ResourceLinkFilter
from ._models_py3 import ResourceLinkProperties
from ._models_py3 import ResourceLinkResult
from ._patch import __all__ as _patch_all
from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import
from ._patch import patch_sdk as _patch_sdk
__all__ = [
"Operation",
"OperationDisplay",
"OperationListResult",
"ResourceLink",
"ResourceLinkFilter",
"ResourceLinkProperties",
"ResourceLinkResult",
]
__all__.extend([p for p in _patch_all if p not in __all__])
_patch_sdk()
| {
"content_hash": "5b8c392f314eadc6ec8184b53b808b54",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 78,
"avg_line_length": 32.68181818181818,
"alnum_prop": 0.7315716272600834,
"repo_name": "Azure/azure-sdk-for-python",
"id": "07cdd79d75c791b6de560b693cf324dab4e78973",
"size": "1187",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/v2016_09_01/models/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1224"
},
{
"name": "Bicep",
"bytes": "24196"
},
{
"name": "CSS",
"bytes": "6089"
},
{
"name": "Dockerfile",
"bytes": "4892"
},
{
"name": "HTML",
"bytes": "12058"
},
{
"name": "JavaScript",
"bytes": "8137"
},
{
"name": "Jinja",
"bytes": "10377"
},
{
"name": "Jupyter Notebook",
"bytes": "272022"
},
{
"name": "PowerShell",
"bytes": "518535"
},
{
"name": "Python",
"bytes": "715484989"
},
{
"name": "Shell",
"bytes": "3631"
}
],
"symlink_target": ""
} |
"""Unit tests for core.domain.exp_fetchers."""
from __future__ import annotations
from core import feconf
from core.domain import caching_services
from core.domain import exp_domain
from core.domain import exp_fetchers
from core.domain import exp_services
from core.platform import models
from core.tests import test_utils
(exp_models,) = models.Registry.import_models([models.NAMES.exploration])
class ExplorationRetrievalTests(test_utils.GenericTestBase):
"""Test the exploration retrieval methods."""
EXP_1_ID = 'exploration_1_id'
EXP_2_ID = 'exploration_2_id'
EXP_3_ID = 'exploration_3_id'
def setUp(self):
super(ExplorationRetrievalTests, self).setUp()
self.signup(self.OWNER_EMAIL, self.OWNER_USERNAME)
self.owner_id = self.get_user_id_from_email(self.OWNER_EMAIL)
self.exploration_1 = self.save_new_default_exploration(
self.EXP_1_ID, self.owner_id, title='Aa')
self.exploration_2 = self.save_new_default_exploration(
self.EXP_2_ID, self.owner_id, title='Bb')
self.exploration_3 = self.save_new_default_exploration(
self.EXP_3_ID, self.owner_id, title='Cc')
def test_get_exploration_summaries_matching_ids(self):
summaries = exp_fetchers.get_exploration_summaries_matching_ids([
self.EXP_1_ID, self.EXP_2_ID, self.EXP_3_ID, 'nonexistent'])
self.assertEqual(summaries[0].title, self.exploration_1.title)
self.assertEqual(summaries[1].title, self.exploration_2.title)
self.assertEqual(summaries[2].title, self.exploration_3.title)
self.assertIsNone(summaries[3])
def test_get_exploration_summaries_subscribed_to(self):
summaries = exp_fetchers.get_exploration_summaries_subscribed_to(
self.owner_id)
self.assertEqual(summaries[0].title, self.exploration_1.title)
self.assertEqual(summaries[1].title, self.exploration_2.title)
self.assertEqual(summaries[2].title, self.exploration_3.title)
def test_retrieval_of_explorations(self):
"""Test the get_exploration_by_id() method."""
with self.assertRaisesRegexp(Exception, 'Entity .* not found'):
exp_fetchers.get_exploration_by_id('fake_eid')
retrieved_exploration = (
exp_fetchers.get_exploration_by_id(self.EXP_1_ID))
self.assertEqual(self.exploration_1.id, retrieved_exploration.id)
self.assertEqual(self.exploration_1.title, retrieved_exploration.title)
with self.assertRaisesRegexp(
Exception,
'Entity for class ExplorationModel with id fake_exploration'
' not found'):
exp_fetchers.get_exploration_by_id('fake_exploration')
def test_retrieval_of_multiple_exploration_versions_for_fake_exp_id(self):
with self.assertRaisesRegexp(
ValueError, 'The given entity_id fake_exp_id is invalid'):
(
exp_fetchers
.get_multiple_versioned_exp_interaction_ids_mapping_by_version(
'fake_exp_id', [1, 2, 3]))
def test_retrieval_of_multiple_exploration_versions(self):
# Update exploration to version 2.
change_list = [exp_domain.ExplorationChange({
'cmd': exp_domain.CMD_ADD_STATE,
'state_name': 'New state',
})]
exp_services.update_exploration(
feconf.SYSTEM_COMMITTER_ID, self.EXP_1_ID, change_list, '')
# Update exploration to version 3.
change_list = [exp_domain.ExplorationChange({
'cmd': exp_domain.CMD_ADD_STATE,
'state_name': 'New state 2',
})]
exp_services.update_exploration(
feconf.SYSTEM_COMMITTER_ID, self.EXP_1_ID, change_list, '')
exploration_latest = exp_fetchers.get_exploration_by_id(self.EXP_1_ID)
latest_version = exploration_latest.version
explorations = (
exp_fetchers
.get_multiple_versioned_exp_interaction_ids_mapping_by_version(
self.EXP_1_ID, list(range(1, latest_version + 1)))
)
self.assertEqual(len(explorations), 3)
self.assertEqual(explorations[0].version, 1)
self.assertEqual(explorations[1].version, 2)
self.assertEqual(explorations[2].version, 3)
def test_version_number_errors_for_get_multiple_exploration_versions(self):
# Update exploration to version 2.
change_list = [exp_domain.ExplorationChange({
'cmd': exp_domain.CMD_ADD_STATE,
'state_name': 'New state',
})]
exp_services.update_exploration(
feconf.SYSTEM_COMMITTER_ID, self.EXP_1_ID, change_list, '')
# Update exploration to version 3.
change_list = [exp_domain.ExplorationChange({
'cmd': exp_domain.CMD_ADD_STATE,
'state_name': 'New state 2',
})]
exp_services.update_exploration(
feconf.SYSTEM_COMMITTER_ID, self.EXP_1_ID, change_list, '')
with self.assertRaisesRegexp(
ValueError,
'Requested version number 4 cannot be higher than the current '
'version number 3.'):
(
exp_fetchers
.get_multiple_versioned_exp_interaction_ids_mapping_by_version(
self.EXP_1_ID, [1, 2, 3, 4]))
with self.assertRaisesRegexp(
ValueError,
'At least one version number is invalid'):
(
exp_fetchers
.get_multiple_versioned_exp_interaction_ids_mapping_by_version(
self.EXP_1_ID, [1, 2, 2.5, 3]))
def test_retrieval_of_multiple_explorations(self):
exps = {}
chars = 'abcde'
exp_ids = ['%s%s' % (self.EXP_1_ID, c) for c in chars]
for _id in exp_ids:
exp = self.save_new_valid_exploration(_id, self.owner_id)
exps[_id] = exp
result = exp_fetchers.get_multiple_explorations_by_id(
exp_ids)
for _id in exp_ids:
self.assertEqual(result.get(_id).title, exps.get(_id).title)
# Test retrieval of non-existent ids.
result = exp_fetchers.get_multiple_explorations_by_id(
exp_ids + ['doesnt_exist'], strict=False
)
for _id in exp_ids:
self.assertEqual(result.get(_id).title, exps.get(_id).title)
self.assertNotIn('doesnt_exist', result)
with self.assertRaisesRegexp(
Exception,
'Couldn\'t find explorations with the following ids:\n'
'doesnt_exist'):
exp_fetchers.get_multiple_explorations_by_id(
exp_ids + ['doesnt_exist'])
class ExplorationConversionPipelineTests(test_utils.GenericTestBase):
"""Tests the exploration model -> exploration conversion pipeline."""
OLD_EXP_ID = 'exp_id0'
NEW_EXP_ID = 'exp_id1'
UPGRADED_EXP_YAML = (
"""author_notes: ''
auto_tts_enabled: true
blurb: ''
category: A category
correctness_feedback_enabled: false
init_state_name: Introduction
language_code: en
objective: An objective
param_changes: []
param_specs: {}
schema_version: %d
states:
End:
card_is_checkpoint: false
classifier_model_id: null
content:
content_id: content
html: ''
interaction:
answer_groups: []
confirmed_unclassified_answers: []
customization_args:
recommendedExplorationIds:
value: []
default_outcome: null
hints: []
id: EndExploration
solution: null
linked_skill_id: null
next_content_id_index: 0
param_changes: []
recorded_voiceovers:
voiceovers_mapping:
content: {}
solicit_answer_details: false
written_translations:
translations_mapping:
content: {}
%s:
card_is_checkpoint: true
classifier_model_id: null
content:
content_id: content
html: ''
interaction:
answer_groups: []
confirmed_unclassified_answers: []
customization_args:
placeholder:
value:
content_id: ca_placeholder_0
unicode_str: ''
rows:
value: 1
default_outcome:
dest: End
feedback:
content_id: default_outcome
html: ''
labelled_as_correct: false
missing_prerequisite_skill_id: null
param_changes: []
refresher_exploration_id: null
hints: []
id: TextInput
solution: null
linked_skill_id: null
next_content_id_index: 1
param_changes: []
recorded_voiceovers:
voiceovers_mapping:
ca_placeholder_0: {}
content: {}
default_outcome: {}
solicit_answer_details: false
written_translations:
translations_mapping:
ca_placeholder_0: {}
content: {}
default_outcome: {}
states_schema_version: %d
tags: []
title: Old Title
""") % (
exp_domain.Exploration.CURRENT_EXP_SCHEMA_VERSION,
feconf.DEFAULT_INIT_STATE_NAME,
feconf.CURRENT_STATE_SCHEMA_VERSION)
ALBERT_EMAIL = 'albert@example.com'
ALBERT_NAME = 'albert'
def setUp(self):
super(ExplorationConversionPipelineTests, self).setUp()
# Setup user who will own the test explorations.
self.signup(self.ALBERT_EMAIL, self.ALBERT_NAME)
self.albert_id = self.get_user_id_from_email(self.ALBERT_EMAIL)
# Create exploration that uses an old states schema version and ensure
# it is properly converted.
swap_states_schema_41 = self.swap(
feconf, 'CURRENT_STATE_SCHEMA_VERSION', 41)
swap_exp_schema_46 = self.swap(
exp_domain.Exploration, 'CURRENT_EXP_SCHEMA_VERSION', 46)
with swap_states_schema_41, swap_exp_schema_46:
self.save_new_valid_exploration(
self.OLD_EXP_ID, self.albert_id, title='Old Title',
end_state_name='End')
# Create standard exploration that should not be converted.
new_exp = self.save_new_valid_exploration(
self.NEW_EXP_ID, self.albert_id)
self._up_to_date_yaml = new_exp.to_yaml()
# Clear the cache to prevent fetches of old data under the previous
# state schema version scheme.
caching_services.delete_multi(
caching_services.CACHE_NAMESPACE_EXPLORATION, None,
[self.OLD_EXP_ID, self.NEW_EXP_ID])
def test_converts_exp_model_with_default_states_schema_version(self):
exploration = exp_fetchers.get_exploration_by_id(self.OLD_EXP_ID)
self.assertEqual(
exploration.states_schema_version,
feconf.CURRENT_STATE_SCHEMA_VERSION)
self.assertEqual(exploration.to_yaml(), self.UPGRADED_EXP_YAML)
def test_does_not_convert_up_to_date_exploration(self):
exploration = exp_fetchers.get_exploration_by_id(self.NEW_EXP_ID)
self.assertEqual(
exploration.states_schema_version,
feconf.CURRENT_STATE_SCHEMA_VERSION)
self.assertEqual(exploration.to_yaml(), self._up_to_date_yaml)
def test_migration_then_reversion_maintains_valid_exploration(self):
"""This integration test simulates the behavior of the domain layer
prior to the introduction of a states schema. In particular, it deals
with an exploration that was created before any states schema
migrations occur. The exploration is constructed using multiple change
lists, then a migration is run. The test thereafter tests if
reverting to a version prior to the migration still maintains a valid
exploration. It tests both the exploration domain object and the
exploration model stored in the datastore for validity.
Note: It is important to distinguish between when the test is testing
the exploration domain versus its model. It is operating at the domain
layer when using exp_fetchers.get_exploration_by_id. Otherwise, it
loads the model explicitly using exp_models.ExplorationModel.get and
then converts it to an exploration domain object for validation using
exp_fetchers.get_exploration_from_model. This is NOT the same process
as exp_fetchers.get_exploration_by_id as it skips many steps which
include the conversion pipeline (which is crucial to this test).
"""
exp_id = 'exp_id2'
end_state_name = 'End'
# Create an exploration with an old states schema version.
swap_states_schema_41 = self.swap(
feconf, 'CURRENT_STATE_SCHEMA_VERSION', 41)
swap_exp_schema_46 = self.swap(
exp_domain.Exploration, 'CURRENT_EXP_SCHEMA_VERSION', 46)
with swap_states_schema_41, swap_exp_schema_46:
self.save_new_valid_exploration(
exp_id, self.albert_id, title='Old Title',
end_state_name=end_state_name)
caching_services.delete_multi(
caching_services.CACHE_NAMESPACE_EXPLORATION, None,
[exp_id])
# Load the exploration without using the conversion pipeline. All of
# these changes are to happen on an exploration with states schema
# version 41.
exploration_model = exp_models.ExplorationModel.get(
exp_id, strict=True, version=None)
# In version 1, the title was 'Old title'.
# In version 2, the title becomes 'New title'.
exploration_model.title = 'New title'
exploration_model.commit(self.albert_id, 'Changed title.', [])
# Version 2 of exploration.
exploration_model = exp_models.ExplorationModel.get(
exp_id, strict=True, version=None)
# Store state id mapping model for new exploration.
exp_fetchers.get_exploration_from_model(exploration_model)
# In version 3, a new state is added.
exploration_model.states['New state'] = {
'solicit_answer_details': False,
'written_translations': {
'translations_mapping': {
'content': {},
'default_outcome': {},
'ca_placeholder_0': {},
}
},
'recorded_voiceovers': {
'voiceovers_mapping': {
'content': {},
'default_outcome': {},
'ca_placeholder_0': {},
}
},
'param_changes': [],
'classifier_model_id': None,
'content': {
'content_id': 'content',
'html': '<p>Unicode Characters 😍😍😍😍</p>'
},
'next_content_id_index': 5,
'interaction': {
'answer_groups': [],
'confirmed_unclassified_answers': [],
'customization_args': {
'buttonText': {
'value': {
'content_id': 'ca_placeholder_0',
'unicode_str': 'Click me!',
},
},
},
'default_outcome': {
'dest': end_state_name,
'feedback': {
'content_id': 'default_outcome',
'html': '',
},
'labelled_as_correct': False,
'missing_prerequisite_skill_id': None,
'param_changes': [],
'refresher_exploration_id': None,
},
'hints': [],
'id': 'Continue',
'solution': None,
},
}
# Properly link in the new state to avoid an invalid exploration.
init_state = exploration_model.states[feconf.DEFAULT_INIT_STATE_NAME]
init_state['interaction']['default_outcome']['dest'] = 'New state'
exploration_model.commit('committer_id_v3', 'Added new state', [])
# Version 3 of exploration.
exploration_model = exp_models.ExplorationModel.get(
exp_id, strict=True, version=None)
# Version 4 is an upgrade based on the migration job.
commit_cmds = [exp_domain.ExplorationChange({
'cmd': exp_domain.CMD_MIGRATE_STATES_SCHEMA_TO_LATEST_VERSION,
'from_version': str(exploration_model.states_schema_version),
'to_version': str(feconf.CURRENT_STATE_SCHEMA_VERSION)
})]
exp_services.update_exploration(
feconf.MIGRATION_BOT_USERNAME, exploration_model.id, commit_cmds,
'Update exploration states from schema version %d to %d.' % (
exploration_model.states_schema_version,
feconf.CURRENT_STATE_SCHEMA_VERSION))
# Verify the latest version of the exploration has the most up-to-date
# states schema version.
exploration_model = exp_models.ExplorationModel.get(
exp_id, strict=True, version=None)
exploration = exp_fetchers.get_exploration_from_model(
exploration_model, run_conversion=False)
self.assertEqual(
exploration.states_schema_version,
feconf.CURRENT_STATE_SCHEMA_VERSION)
# The exploration should be valid after conversion.
exploration.validate(strict=True)
# Version 5 is a reversion to version 1.
exp_services.revert_exploration('committer_id_v4', exp_id, 4, 1)
# The exploration model itself should now be the old version
# (pre-migration).
exploration_model = exp_models.ExplorationModel.get(
exp_id, strict=True, version=None)
self.assertEqual(exploration_model.states_schema_version, 41)
# The exploration domain object should be updated since it ran through
# the conversion pipeline.
exploration = exp_fetchers.get_exploration_by_id(exp_id)
# The reversion after migration should still be an up-to-date
# exploration. exp_fetchers.get_exploration_by_id will automatically
# keep it up-to-date.
self.assertEqual(exploration.to_yaml(), self.UPGRADED_EXP_YAML)
# The exploration should be valid after reversion.
exploration.validate(strict=True)
snapshots_metadata = exp_services.get_exploration_snapshots_metadata(
exp_id)
# These are used to verify the correct history has been recorded after
# both migration and reversion.
commit_dict_5 = {
'committer_id': 'committer_id_v4',
'commit_message': 'Reverted exploration to version 1',
'version_number': 5,
}
commit_dict_4 = {
'committer_id': feconf.MIGRATION_BOT_USERNAME,
'commit_message':
'Update exploration states from schema version 41 to %d.' %
feconf.CURRENT_STATE_SCHEMA_VERSION,
'commit_cmds': [{
'cmd': exp_domain.CMD_MIGRATE_STATES_SCHEMA_TO_LATEST_VERSION,
'from_version': '41',
'to_version': str(feconf.CURRENT_STATE_SCHEMA_VERSION)
}],
'version_number': 4,
}
# Ensure there have been 5 commits.
self.assertEqual(len(snapshots_metadata), 5)
# Ensure the correct commit logs were entered during both migration and
# reversion. Also, ensure the correct commit command was written during
# migration.
# These asserts check whether one dict is subset of the other.
# The format is assertDictEqual(a, {**a, **b}) where a is the superset
# and b is the subset.
self.assertDictEqual(
snapshots_metadata[3], {**snapshots_metadata[3], **commit_dict_4})
self.assertDictEqual(
snapshots_metadata[4], {**snapshots_metadata[4], **commit_dict_5})
self.assertLess(
snapshots_metadata[3]['created_on_ms'],
snapshots_metadata[4]['created_on_ms'])
# Ensure that if a converted, then reverted, then converted exploration
# is saved, it will be the up-to-date version within the datastore.
exp_services.update_exploration(
self.albert_id, exp_id, [], 'Resave after reversion')
exploration_model = exp_models.ExplorationModel.get(
exp_id, strict=True, version=None)
exploration = exp_fetchers.get_exploration_from_model(
exploration_model, run_conversion=False)
# This exploration should be both up-to-date and valid.
self.assertEqual(exploration.to_yaml(), self.UPGRADED_EXP_YAML)
exploration.validate()
| {
"content_hash": "3330beb36ec142f0f41b5403bb65b03a",
"timestamp": "",
"source": "github",
"line_count": 520,
"max_line_length": 79,
"avg_line_length": 39.70384615384615,
"alnum_prop": 0.6065097355419936,
"repo_name": "kevinlee12/oppia",
"id": "66efcfef82fd1741796feb0b3c9cdc2643a2145b",
"size": "21281",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "core/domain/exp_fetchers_test.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "205771"
},
{
"name": "HTML",
"bytes": "1835761"
},
{
"name": "JavaScript",
"bytes": "1182599"
},
{
"name": "PEG.js",
"bytes": "71377"
},
{
"name": "Python",
"bytes": "13670639"
},
{
"name": "Shell",
"bytes": "2239"
},
{
"name": "TypeScript",
"bytes": "13024194"
}
],
"symlink_target": ""
} |
"""
Common Policy Engine Implementation
Policies can be expressed in one of two forms: A list of lists, or a
string written in the new policy language.
In the list-of-lists representation, each check inside the innermost
list is combined as with an "and" conjunction--for that check to pass,
all the specified checks must pass. These innermost lists are then
combined as with an "or" conjunction. This is the original way of
expressing policies, but there now exists a new way: the policy
language.
In the policy language, each check is specified the same way as in the
list-of-lists representation: a simple "a:b" pair that is matched to
the correct code to perform that check. However, conjunction
operators are available, allowing for more expressiveness in crafting
policies.
As an example, take the following rule, expressed in the list-of-lists
representation::
[["role:admin"], ["project_id:%(project_id)s", "role:projectadmin"]]
In the policy language, this becomes::
role:admin or (project_id:%(project_id)s and role:projectadmin)
The policy language also has the "not" operator, allowing a richer
policy rule::
project_id:%(project_id)s and not role:dunce
It is possible to perform policy checks on the following user
attributes (obtained through the token): user_id, domain_id or
project_id::
domain_id:<some_value>
Attributes sent along with API calls can be used by the policy engine
(on the right side of the expression), by using the following syntax::
<some_value>:user.id
Contextual attributes of objects identified by their IDs are loaded
from the database. They are also available to the policy engine and
can be checked through the `target` keyword::
<some_value>:target.role.name
All these attributes (related to users, API calls, and context) can be
checked against each other or against constants, be it literals (True,
<a_number>) or strings.
Finally, two special policy checks should be mentioned; the policy
check "@" will always accept an access, and the policy check "!" will
always reject an access. (Note that if a rule is either the empty
list ("[]") or the empty string, this is equivalent to the "@" policy
check.) Of these, the "!" policy check is probably the most useful,
as it allows particular rules to be explicitly disabled.
"""
import abc
import ast
import copy
import os
import re
from oslo.config import cfg
from oslo.serialization import jsonutils
import six
import six.moves.urllib.parse as urlparse
import six.moves.urllib.request as urlrequest
from cinder.openstack.common import fileutils
from cinder.openstack.common._i18n import _, _LE, _LW
from cinder.openstack.common import log as logging
policy_opts = [
cfg.StrOpt('policy_file',
default='policy.json',
help=_('The JSON file that defines policies.')),
cfg.StrOpt('policy_default_rule',
default='default',
help=_('Default rule. Enforced when a requested rule is not '
'found.')),
cfg.MultiStrOpt('policy_dirs',
default=['policy.d'],
help=_('Directories where policy configuration files are '
'stored. They can be relative to any directory '
'in the search path defined by the config_dir '
'option, or absolute paths. The file defined by '
'policy_file must exist for these directories to '
'be searched.')),
]
CONF = cfg.CONF
CONF.register_opts(policy_opts)
LOG = logging.getLogger(__name__)
_checks = {}
def list_opts():
"""Entry point for oslo.config-generator."""
return [(None, copy.deepcopy(policy_opts))]
class PolicyNotAuthorized(Exception):
def __init__(self, rule):
msg = _("Policy doesn't allow %s to be performed.") % rule
super(PolicyNotAuthorized, self).__init__(msg)
class Rules(dict):
"""A store for rules. Handles the default_rule setting directly."""
@classmethod
def load_json(cls, data, default_rule=None):
"""Allow loading of JSON rule data."""
# Suck in the JSON data and parse the rules
rules = dict((k, parse_rule(v)) for k, v in
jsonutils.loads(data).items())
return cls(rules, default_rule)
def __init__(self, rules=None, default_rule=None):
"""Initialize the Rules store."""
super(Rules, self).__init__(rules or {})
self.default_rule = default_rule
def __missing__(self, key):
"""Implements the default rule handling."""
if isinstance(self.default_rule, dict):
raise KeyError(key)
# If the default rule isn't actually defined, do something
# reasonably intelligent
if not self.default_rule:
raise KeyError(key)
if isinstance(self.default_rule, BaseCheck):
return self.default_rule
# We need to check this or we can get infinite recursion
if self.default_rule not in self:
raise KeyError(key)
elif isinstance(self.default_rule, six.string_types):
return self[self.default_rule]
def __str__(self):
"""Dumps a string representation of the rules."""
# Start by building the canonical strings for the rules
out_rules = {}
for key, value in self.items():
# Use empty string for singleton TrueCheck instances
if isinstance(value, TrueCheck):
out_rules[key] = ''
else:
out_rules[key] = str(value)
# Dump a pretty-printed JSON representation
return jsonutils.dumps(out_rules, indent=4)
class Enforcer(object):
"""Responsible for loading and enforcing rules.
:param policy_file: Custom policy file to use, if none is
specified, `CONF.policy_file` will be
used.
:param rules: Default dictionary / Rules to use. It will be
considered just in the first instantiation. If
`load_rules(True)`, `clear()` or `set_rules(True)`
is called this will be overwritten.
:param default_rule: Default rule to use, CONF.default_rule will
be used if none is specified.
:param use_conf: Whether to load rules from cache or config file.
"""
def __init__(self, policy_file=None, rules=None,
default_rule=None, use_conf=True):
self.default_rule = default_rule or CONF.policy_default_rule
self.rules = Rules(rules, self.default_rule)
self.policy_path = None
self.policy_file = policy_file or CONF.policy_file
self.use_conf = use_conf
def set_rules(self, rules, overwrite=True, use_conf=False):
"""Create a new Rules object based on the provided dict of rules.
:param rules: New rules to use. It should be an instance of dict.
:param overwrite: Whether to overwrite current rules or update them
with the new rules.
:param use_conf: Whether to reload rules from cache or config file.
"""
if not isinstance(rules, dict):
raise TypeError(_("Rules must be an instance of dict or Rules, "
"got %s instead") % type(rules))
self.use_conf = use_conf
if overwrite:
self.rules = Rules(rules, self.default_rule)
else:
self.rules.update(rules)
def clear(self):
"""Clears Enforcer rules, policy's cache and policy's path."""
self.set_rules({})
fileutils.delete_cached_file(self.policy_path)
self.default_rule = None
self.policy_path = None
def load_rules(self, force_reload=False):
"""Loads policy_path's rules.
Policy file is cached and will be reloaded if modified.
:param force_reload: Whether to overwrite current rules.
"""
if force_reload:
self.use_conf = force_reload
if self.use_conf:
if not self.policy_path:
self.policy_path = self._get_policy_path(self.policy_file)
self._load_policy_file(self.policy_path, force_reload)
for path in CONF.policy_dirs:
try:
path = self._get_policy_path(path)
except cfg.ConfigFilesNotFoundError:
LOG.warn(_LW("Can not find policy directory: %s"), path)
continue
self._walk_through_policy_directory(path,
self._load_policy_file,
force_reload, False)
@staticmethod
def _walk_through_policy_directory(path, func, *args):
# We do not iterate over sub-directories.
policy_files = next(os.walk(path))[2]
policy_files.sort()
for policy_file in [p for p in policy_files if not p.startswith('.')]:
func(os.path.join(path, policy_file), *args)
def _load_policy_file(self, path, force_reload, overwrite=True):
reloaded, data = fileutils.read_cached_file(
path, force_reload=force_reload)
if reloaded or not self.rules:
rules = Rules.load_json(data, self.default_rule)
self.set_rules(rules, overwrite)
LOG.debug("Rules successfully reloaded")
def _get_policy_path(self, path):
"""Locate the policy json data file/path.
:param path: It's value can be a full path or related path. When
full path specified, this function just returns the full
path. When related path specified, this function will
search configuration directories to find one that exists.
:returns: The policy path
:raises: ConfigFilesNotFoundError if the file/path couldn't
be located.
"""
policy_path = CONF.find_file(path)
if policy_path:
return policy_path
raise cfg.ConfigFilesNotFoundError((path,))
def enforce(self, rule, target, creds, do_raise=False,
exc=None, *args, **kwargs):
"""Checks authorization of a rule against the target and credentials.
:param rule: A string or BaseCheck instance specifying the rule
to evaluate.
:param target: As much information about the object being operated
on as possible, as a dictionary.
:param creds: As much information about the user performing the
action as possible, as a dictionary.
:param do_raise: Whether to raise an exception or not if check
fails.
:param exc: Class of the exception to raise if the check fails.
Any remaining arguments passed to enforce() (both
positional and keyword arguments) will be passed to
the exception class. If not specified, PolicyNotAuthorized
will be used.
:return: Returns False if the policy does not allow the action and
exc is not provided; otherwise, returns a value that
evaluates to True. Note: for rules using the "case"
expression, this True value will be the specified string
from the expression.
"""
self.load_rules()
# Allow the rule to be a Check tree
if isinstance(rule, BaseCheck):
result = rule(target, creds, self)
elif not self.rules:
# No rules to reference means we're going to fail closed
result = False
else:
try:
# Evaluate the rule
result = self.rules[rule](target, creds, self)
except KeyError:
LOG.debug("Rule [%s] doesn't exist" % rule)
# If the rule doesn't exist, fail closed
result = False
# If it is False, raise the exception if requested
if do_raise and not result:
if exc:
raise exc(*args, **kwargs)
raise PolicyNotAuthorized(rule)
return result
@six.add_metaclass(abc.ABCMeta)
class BaseCheck(object):
"""Abstract base class for Check classes."""
@abc.abstractmethod
def __str__(self):
"""String representation of the Check tree rooted at this node."""
pass
@abc.abstractmethod
def __call__(self, target, cred, enforcer):
"""Triggers if instance of the class is called.
Performs the check. Returns False to reject the access or a
true value (not necessary True) to accept the access.
"""
pass
class FalseCheck(BaseCheck):
"""A policy check that always returns False (disallow)."""
def __str__(self):
"""Return a string representation of this check."""
return "!"
def __call__(self, target, cred, enforcer):
"""Check the policy."""
return False
class TrueCheck(BaseCheck):
"""A policy check that always returns True (allow)."""
def __str__(self):
"""Return a string representation of this check."""
return "@"
def __call__(self, target, cred, enforcer):
"""Check the policy."""
return True
class Check(BaseCheck):
"""A base class to allow for user-defined policy checks."""
def __init__(self, kind, match):
"""Initiates Check instance.
:param kind: The kind of the check, i.e., the field before the
':'.
:param match: The match of the check, i.e., the field after
the ':'.
"""
self.kind = kind
self.match = match
def __str__(self):
"""Return a string representation of this check."""
return "%s:%s" % (self.kind, self.match)
class NotCheck(BaseCheck):
"""Implements the "not" logical operator.
A policy check that inverts the result of another policy check.
"""
def __init__(self, rule):
"""Initialize the 'not' check.
:param rule: The rule to negate. Must be a Check.
"""
self.rule = rule
def __str__(self):
"""Return a string representation of this check."""
return "not %s" % self.rule
def __call__(self, target, cred, enforcer):
"""Check the policy.
Returns the logical inverse of the wrapped check.
"""
return not self.rule(target, cred, enforcer)
class AndCheck(BaseCheck):
"""Implements the "and" logical operator.
A policy check that requires that a list of other checks all return True.
"""
def __init__(self, rules):
"""Initialize the 'and' check.
:param rules: A list of rules that will be tested.
"""
self.rules = rules
def __str__(self):
"""Return a string representation of this check."""
return "(%s)" % ' and '.join(str(r) for r in self.rules)
def __call__(self, target, cred, enforcer):
"""Check the policy.
Requires that all rules accept in order to return True.
"""
for rule in self.rules:
if not rule(target, cred, enforcer):
return False
return True
def add_check(self, rule):
"""Adds rule to be tested.
Allows addition of another rule to the list of rules that will
be tested. Returns the AndCheck object for convenience.
"""
self.rules.append(rule)
return self
class OrCheck(BaseCheck):
"""Implements the "or" operator.
A policy check that requires that at least one of a list of other
checks returns True.
"""
def __init__(self, rules):
"""Initialize the 'or' check.
:param rules: A list of rules that will be tested.
"""
self.rules = rules
def __str__(self):
"""Return a string representation of this check."""
return "(%s)" % ' or '.join(str(r) for r in self.rules)
def __call__(self, target, cred, enforcer):
"""Check the policy.
Requires that at least one rule accept in order to return True.
"""
for rule in self.rules:
if rule(target, cred, enforcer):
return True
return False
def add_check(self, rule):
"""Adds rule to be tested.
Allows addition of another rule to the list of rules that will
be tested. Returns the OrCheck object for convenience.
"""
self.rules.append(rule)
return self
def _parse_check(rule):
"""Parse a single base check rule into an appropriate Check object."""
# Handle the special checks
if rule == '!':
return FalseCheck()
elif rule == '@':
return TrueCheck()
try:
kind, match = rule.split(':', 1)
except Exception:
LOG.exception(_LE("Failed to understand rule %s") % rule)
# If the rule is invalid, we'll fail closed
return FalseCheck()
# Find what implements the check
if kind in _checks:
return _checks[kind](kind, match)
elif None in _checks:
return _checks[None](kind, match)
else:
LOG.error(_LE("No handler for matches of kind %s") % kind)
return FalseCheck()
def _parse_list_rule(rule):
"""Translates the old list-of-lists syntax into a tree of Check objects.
Provided for backwards compatibility.
"""
# Empty rule defaults to True
if not rule:
return TrueCheck()
# Outer list is joined by "or"; inner list by "and"
or_list = []
for inner_rule in rule:
# Elide empty inner lists
if not inner_rule:
continue
# Handle bare strings
if isinstance(inner_rule, six.string_types):
inner_rule = [inner_rule]
# Parse the inner rules into Check objects
and_list = [_parse_check(r) for r in inner_rule]
# Append the appropriate check to the or_list
if len(and_list) == 1:
or_list.append(and_list[0])
else:
or_list.append(AndCheck(and_list))
# If we have only one check, omit the "or"
if not or_list:
return FalseCheck()
elif len(or_list) == 1:
return or_list[0]
return OrCheck(or_list)
# Used for tokenizing the policy language
_tokenize_re = re.compile(r'\s+')
def _parse_tokenize(rule):
"""Tokenizer for the policy language.
Most of the single-character tokens are specified in the
_tokenize_re; however, parentheses need to be handled specially,
because they can appear inside a check string. Thankfully, those
parentheses that appear inside a check string can never occur at
the very beginning or end ("%(variable)s" is the correct syntax).
"""
for tok in _tokenize_re.split(rule):
# Skip empty tokens
if not tok or tok.isspace():
continue
# Handle leading parens on the token
clean = tok.lstrip('(')
for i in range(len(tok) - len(clean)):
yield '(', '('
# If it was only parentheses, continue
if not clean:
continue
else:
tok = clean
# Handle trailing parens on the token
clean = tok.rstrip(')')
trail = len(tok) - len(clean)
# Yield the cleaned token
lowered = clean.lower()
if lowered in ('and', 'or', 'not'):
# Special tokens
yield lowered, clean
elif clean:
# Not a special token, but not composed solely of ')'
if len(tok) >= 2 and ((tok[0], tok[-1]) in
[('"', '"'), ("'", "'")]):
# It's a quoted string
yield 'string', tok[1:-1]
else:
yield 'check', _parse_check(clean)
# Yield the trailing parens
for i in range(trail):
yield ')', ')'
class ParseStateMeta(type):
"""Metaclass for the ParseState class.
Facilitates identifying reduction methods.
"""
def __new__(mcs, name, bases, cls_dict):
"""Create the class.
Injects the 'reducers' list, a list of tuples matching token sequences
to the names of the corresponding reduction methods.
"""
reducers = []
for key, value in cls_dict.items():
if not hasattr(value, 'reducers'):
continue
for reduction in value.reducers:
reducers.append((reduction, key))
cls_dict['reducers'] = reducers
return super(ParseStateMeta, mcs).__new__(mcs, name, bases, cls_dict)
def reducer(*tokens):
"""Decorator for reduction methods.
Arguments are a sequence of tokens, in order, which should trigger running
this reduction method.
"""
def decorator(func):
# Make sure we have a list of reducer sequences
if not hasattr(func, 'reducers'):
func.reducers = []
# Add the tokens to the list of reducer sequences
func.reducers.append(list(tokens))
return func
return decorator
@six.add_metaclass(ParseStateMeta)
class ParseState(object):
"""Implement the core of parsing the policy language.
Uses a greedy reduction algorithm to reduce a sequence of tokens into
a single terminal, the value of which will be the root of the Check tree.
Note: error reporting is rather lacking. The best we can get with
this parser formulation is an overall "parse failed" error.
Fortunately, the policy language is simple enough that this
shouldn't be that big a problem.
"""
def __init__(self):
"""Initialize the ParseState."""
self.tokens = []
self.values = []
def reduce(self):
"""Perform a greedy reduction of the token stream.
If a reducer method matches, it will be executed, then the
reduce() method will be called recursively to search for any more
possible reductions.
"""
for reduction, methname in self.reducers:
if (len(self.tokens) >= len(reduction) and
self.tokens[-len(reduction):] == reduction):
# Get the reduction method
meth = getattr(self, methname)
# Reduce the token stream
results = meth(*self.values[-len(reduction):])
# Update the tokens and values
self.tokens[-len(reduction):] = [r[0] for r in results]
self.values[-len(reduction):] = [r[1] for r in results]
# Check for any more reductions
return self.reduce()
def shift(self, tok, value):
"""Adds one more token to the state. Calls reduce()."""
self.tokens.append(tok)
self.values.append(value)
# Do a greedy reduce...
self.reduce()
@property
def result(self):
"""Obtain the final result of the parse.
Raises ValueError if the parse failed to reduce to a single result.
"""
if len(self.values) != 1:
raise ValueError("Could not parse rule")
return self.values[0]
@reducer('(', 'check', ')')
@reducer('(', 'and_expr', ')')
@reducer('(', 'or_expr', ')')
def _wrap_check(self, _p1, check, _p2):
"""Turn parenthesized expressions into a 'check' token."""
return [('check', check)]
@reducer('check', 'and', 'check')
def _make_and_expr(self, check1, _and, check2):
"""Create an 'and_expr'.
Join two checks by the 'and' operator.
"""
return [('and_expr', AndCheck([check1, check2]))]
@reducer('and_expr', 'and', 'check')
def _extend_and_expr(self, and_expr, _and, check):
"""Extend an 'and_expr' by adding one more check."""
return [('and_expr', and_expr.add_check(check))]
@reducer('check', 'or', 'check')
def _make_or_expr(self, check1, _or, check2):
"""Create an 'or_expr'.
Join two checks by the 'or' operator.
"""
return [('or_expr', OrCheck([check1, check2]))]
@reducer('or_expr', 'or', 'check')
def _extend_or_expr(self, or_expr, _or, check):
"""Extend an 'or_expr' by adding one more check."""
return [('or_expr', or_expr.add_check(check))]
@reducer('not', 'check')
def _make_not_expr(self, _not, check):
"""Invert the result of another check."""
return [('check', NotCheck(check))]
def _parse_text_rule(rule):
"""Parses policy to the tree.
Translates a policy written in the policy language into a tree of
Check objects.
"""
# Empty rule means always accept
if not rule:
return TrueCheck()
# Parse the token stream
state = ParseState()
for tok, value in _parse_tokenize(rule):
state.shift(tok, value)
try:
return state.result
except ValueError:
# Couldn't parse the rule
LOG.exception(_LE("Failed to understand rule %s") % rule)
# Fail closed
return FalseCheck()
def parse_rule(rule):
"""Parses a policy rule into a tree of Check objects."""
# If the rule is a string, it's in the policy language
if isinstance(rule, six.string_types):
return _parse_text_rule(rule)
return _parse_list_rule(rule)
def register(name, func=None):
"""Register a function or Check class as a policy check.
:param name: Gives the name of the check type, e.g., 'rule',
'role', etc. If name is None, a default check type
will be registered.
:param func: If given, provides the function or class to register.
If not given, returns a function taking one argument
to specify the function or class to register,
allowing use as a decorator.
"""
# Perform the actual decoration by registering the function or
# class. Returns the function or class for compliance with the
# decorator interface.
def decorator(func):
_checks[name] = func
return func
# If the function or class is given, do the registration
if func:
return decorator(func)
return decorator
@register("rule")
class RuleCheck(Check):
def __call__(self, target, creds, enforcer):
"""Recursively checks credentials based on the defined rules."""
try:
return enforcer.rules[self.match](target, creds, enforcer)
except KeyError:
# We don't have any matching rule; fail closed
return False
@register("role")
class RoleCheck(Check):
def __call__(self, target, creds, enforcer):
"""Check that there is a matching role in the cred dict."""
return self.match.lower() in [x.lower() for x in creds['roles']]
@register('http')
class HttpCheck(Check):
def __call__(self, target, creds, enforcer):
"""Check http: rules by calling to a remote server.
This example implementation simply verifies that the response
is exactly 'True'.
"""
url = ('http:' + self.match) % target
data = {'target': jsonutils.dumps(target),
'credentials': jsonutils.dumps(creds)}
post_data = urlparse.urlencode(data)
f = urlrequest.urlopen(url, post_data)
return f.read() == "True"
@register(None)
class GenericCheck(Check):
def __call__(self, target, creds, enforcer):
"""Check an individual match.
Matches look like:
tenant:%(tenant_id)s
role:compute:admin
True:%(user.enabled)s
'Member':%(role.name)s
"""
try:
match = self.match % target
except KeyError:
# While doing GenericCheck if key not
# present in Target return false
return False
try:
# Try to interpret self.kind as a literal
leftval = ast.literal_eval(self.kind)
except ValueError:
try:
kind_parts = self.kind.split('.')
leftval = creds
for kind_part in kind_parts:
leftval = leftval[kind_part]
except KeyError:
return False
return match == six.text_type(leftval)
| {
"content_hash": "d8f13e5f79477834061ee32566b1ec2d",
"timestamp": "",
"source": "github",
"line_count": 920,
"max_line_length": 78,
"avg_line_length": 30.982608695652175,
"alnum_prop": 0.5947235475722705,
"repo_name": "Accelerite/cinder",
"id": "cf45ffa1df3dbf374ba12c6bf28169b1f91fcdf1",
"size": "29145",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "cinder/openstack/common/policy.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "3322"
},
{
"name": "Python",
"bytes": "10152545"
},
{
"name": "Shell",
"bytes": "9905"
}
],
"symlink_target": ""
} |
"""Relations system field.
The field consists of:
- The system field itself.
- A relation mapping which is an object returned when accessing the system
field from an instance (e.g. ``record.relations``).
- Relations (e.g. PKRelation) used for defining a relationship to a specific
record type.
- Results, values returned when accessing a field (e.g.
``record.relations.languages``).
"""
from .errors import InvalidCheckValue, InvalidRelationValue, RelationError
from .field import MultiRelationsField, RelationsField
from .mapping import RelationsMapping
from .modelrelations import ModelRelation
from .relations import (
ListRelation,
NestedListRelation,
PKListRelation,
PKNestedListRelation,
PKRelation,
RelationBase,
)
from .results import RelationListResult, RelationNestedListResult, RelationResult
__all__ = (
"InvalidCheckValue",
"InvalidRelationValue",
"ListRelation",
"ModelRelation",
"MultiRelationsField",
"NestedListRelation",
"PKListRelation",
"PKNestedListRelation",
"PKRelation",
"RelationBase",
"RelationError",
"RelationListResult",
"RelationNestedListResult",
"RelationResult",
"RelationsField",
"RelationsMapping",
)
| {
"content_hash": "60676021b66986297bb9df808611edfd",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 81,
"avg_line_length": 27.42222222222222,
"alnum_prop": 0.7374392220421394,
"repo_name": "inveniosoftware/invenio-records",
"id": "987b332b4366d0768079eee07aaab1d1e3c86f39",
"size": "1469",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "invenio_records/systemfields/relations/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "269858"
},
{
"name": "Shell",
"bytes": "785"
}
],
"symlink_target": ""
} |
from io import BytesIO
from openslide import OpenSlideError
from cache import slide_cache
import os
class PILBytesIO(BytesIO):
def fileno(self):
'''Classic PIL doesn't understand io.UnsupportedOperation.'''
raise AttributeError('Not supported')
def get_slide(path):
if not os.path.exists(path):
return None
try:
slide = slide_cache.get(path)
if slide != None:
slide.filename = os.path.basename(path)
return slide
else:
return None
except OpenSlideError:
return None
| {
"content_hash": "b92feb281f4c7b5511692650caa3067a",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 69,
"avg_line_length": 25.08695652173913,
"alnum_prop": 0.6360485268630849,
"repo_name": "dgutman/ADRCPathViewer",
"id": "dd3c6df127e99ea98ff7dff1e5b5761d1a9da4f4",
"size": "577",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "api/utils/deepzoom.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "542"
},
{
"name": "HTML",
"bytes": "2395"
},
{
"name": "JavaScript",
"bytes": "110030"
},
{
"name": "Jupyter Notebook",
"bytes": "548677"
},
{
"name": "Python",
"bytes": "68756"
},
{
"name": "Shell",
"bytes": "342"
}
],
"symlink_target": ""
} |
from netforce.model import Model, fields, get_model
import time
from netforce.access import get_active_user
import datetime
class WorkTime(Model):
_name = "work.time"
_string = "Work Time"
_key = ["project_id","resource_id","date"]
_fields = {
"resource_id": fields.Many2One("service.resource", "Resource", required=True, search=True, on_delete="cascade"),
"resource_type": fields.Selection([["person","Person"],["machine","Machine"]],"Resource Type",function="_get_related",function_search="_search_related",function_context={"path":"resource_id.type"},search=True),
"project_id": fields.Many2One("project", "Project", search=True),
"related_id": fields.Reference([["job","Service Order"],["sale.order","Sales Order"],["rental.order","Rental Order"]],"Related To",search=True),
"job_id": fields.Many2One("job", "Service Order", search=True), # XXX: deprecated
"service_item_id": fields.Many2One("service.item","Service Item"), # XXX: deprecated
"service_type_id": fields.Many2One("service.type", "Service Type", function="_get_related", function_context={"path": "job_id.service_type_id"}, function_search="_search_related", search=True),
"date": fields.Date("Date", required=True, search=True),
"actual_hours": fields.Decimal("Actual Hours", required=True),
"bill_hours": fields.Decimal("Billable Hours"),
"work_type_id": fields.Many2One("work.type", "Work Type"),
"description": fields.Text("Description"),
"week": fields.Date("Week", function="get_week", store=True),
"comments": fields.One2Many("message", "related_id", "Comments"),
"is_today": fields.Boolean("Today", store=False, function_search="search_today"),
"is_this_week": fields.Boolean("This Week", store=False, function_search="search_this_week"),
"is_last_week": fields.Boolean("Last Week", store=False, function_search="search_last_week"),
"state": fields.Selection([["waiting_approval", "Waiting Approval"], ["approved", "Approved"], ["rejected", "Rejected"]], "Status", required=True),
"agg_actual_hours_total": fields.Decimal("Actual Hours Total", agg_function=["sum", "actual_hours"]),
"agg_bill_hours_total": fields.Decimal("Billable Hours Total", agg_function=["sum", "bill_hours"]),
"track_entries": fields.One2Many("account.track.entry","related_id","Tracking Entries"),
"track_id": fields.Many2One("account.track.categ","Tracking",function="get_track_categ"),
"cost_amount": fields.Decimal("Cost Amount",function="get_cost_amount"),
#"agg_cost_amount": fields.Decimal("Cost Amount", agg_function=["sum", "cost_amount"]),
"sale_price": fields.Decimal("Hourly Rate"),
}
_order = "date,resource_id.name"
def get_resource(self, context={}):
user_id = get_active_user()
res = get_model("service.resource").search([["user_id", "=", user_id]])
if not res:
return None
return res[0]
def get_default_project(self, context={}):
defaults=context.get('defaults', {})
data=context.get('data',{})
return data.get('project_id')
def get_default_related(self, context={}):
defaults = context.get('defaults', {})
data = context.get('data',{})
job_number = data.get("number")
job_id = None
if job_number:
for job_id in get_model("job").search([['number','=', job_number]]):
data['job_id']=job_id
return "job,%s"%(job_id) if job_id else None
_defaults = {
"date": lambda *a: time.strftime("%Y-%m-%d"),
"resource_id": get_resource,
"project_id": get_default_project,
"related_id": get_default_related,
"state": "waiting_approval",
}
def name_get(self,ids,context={}):
res=[]
for obj in self.browse(ids):
res.append((obj.id,"Work Time %s / %s"%(obj.resource_id.name,obj.date)))
return res
def create(self, vals, **kw):
if 'related_id' in vals and 'job' in vals['related_id']:
job_id = int(vals['related_id'].split(',')[1])
vals['job_id'] = job_id
#auto assign project
if not 'project_id' in vals and job_id:
for job in get_model("job").search_read([['id','=', job_id]],['project_id']):
if job['project_id']:
vals['project_id']=job['project_id'][0]
new_id = super().create(vals, **kw)
self.function_store([new_id])
if 'job_id' in vals:
get_model('job').function_store([vals['job_id']])
return new_id
def write(self, ids, vals, **kw):
#auto assign project
job_ids=[]
for obj in self.browse(ids):
if not obj.project_id:
if obj.job_id and obj.job_id.project_id:
vals['project_id']=obj.job_id.project_id.id
job_ids.append(obj.job_id.id)
elif obj.related_id and obj.related_id._model=='job':
vals['project_id']=obj.related_id.project_id.id
super().write(ids, vals, **kw)
self.function_store(ids)
if job_ids:
get_model('job').function_store(job_ids)
def delete(self, ids, context={}):
job_ids=[]
for obj in self.browse(ids):
if obj.job_id:
job_ids.append(obj.job_id.id)
super().delete(ids)
get_model('job').function_store(job_ids)
def get_week(self, ids, context={}):
vals = {}
for obj in self.browse(ids):
d = datetime.datetime.strptime(obj.date, "%Y-%m-%d")
d -= datetime.timedelta(d.weekday())
vals[obj.id] = d.strftime("%Y-%m-%d")
return vals
def search_today(self, clause, context={}):
t = time.strftime("%Y-%m-%d")
return [["date", "=", t]]
def search_this_week(self, clause, context={}):
d = datetime.datetime.today()
d0 = d - datetime.timedelta(days=d.weekday())
d1 = d0 + datetime.timedelta(days=6)
return [["date", ">=", d0.strftime("%Y-%m-%d")], ["date", "<=", d1.strftime("%Y-%m-%d")]]
def search_last_week(self, clause, context={}):
d = datetime.datetime.today()
d0 = d - datetime.timedelta(days=d.weekday() + 7)
d1 = d0 + datetime.timedelta(days=6)
return [["date", ">=", d0.strftime("%Y-%m-%d")], ["date", "<=", d1.strftime("%Y-%m-%d")]]
def approve(self, ids, context={}):
res=get_model("uom").search([["name","=","Hour"]])
if not res:
raise Exception("Hour UoM not found")
hour_uom_id=res[0]
for obj in self.browse(ids):
obj.write({"state": "approved"})
if obj.track_id and obj.cost_amount:
vals={
"track_id": obj.track_id.id,
"date": obj.date,
"amount": -obj.cost_amount,
"product_id": obj.resource_id.product_id.id,
"qty": obj.actual_hours or 0,
"uom_id": hour_uom_id,
"related_id": "work.time,%s"%obj.id,
}
get_model("account.track.entry").create(vals)
def reject(self, ids, context={}):
for obj in self.browse(ids):
obj.write({"state": "rejected"})
def waiting_approval(self, ids, context={}):
for obj in self.browse(ids):
obj.write({"state": "waiting_approval"})
obj.track_entries.delete()
def onchange_product(self, context={}):
data = context["data"]
prod_id = data["product_id"]
prod = get_model("product").browse(prod_id)
data["unit_price"] = prod.cost_price
return data
def get_track_categ(self,ids,context={}):
vals={}
for obj in self.browse(ids):
track_id=None
project_id=obj.project_id
if project_id and project_id.track_id:
track_id=project_id.track_id.id
rel=obj.related_id
if rel.track_id:
track_id=rel.track_id.id
vals[obj.id]=track_id
return vals
def get_cost_amount(self,ids,context={}):
vals={}
for obj in self.browse(ids):
# Use standard price in product in resource
prod=obj.resource_id.product_id
amt=(prod.cost_price or 0)*(obj.actual_hours or 0)
vals[obj.id]=amt
return vals
def copy_to_invoice_group(self,ids,context={}):
inv_vals = {
"type": "out",
"inv_type": "invoice",
"lines": [],
}
res_hours={}
for obj in self.browse(ids):
if obj.invoice_id:
raise Exception("Invoice already created for work time %s"%obj.id)
project=obj.project_id
contact_id=project.contact_id.id
if not contact_id and obj.related_id._model=="rental.order": # XXX
contact_id=obj.related_id.contact_id.id
if not contact_id:
raise Exception("Contact not found for worktime %s"%obj.id)
if inv_vals.get("contact_id"):
if contact_id!=inv_vals["contact_id"]:
raise Exception("Different contacts")
else:
inv_vals["contact_id"]=contact_id
if obj.related_id:
related_id="%s,%d"%(obj.related_id._model,obj.related_id.id)
else:
related_id=None
if inv_vals.get("related_id"):
if related_id!=inv_vals["related_id"]:
raise Exception("Different related documents")
else:
inv_vals["related_id"]=related_id
if obj.related_id._model=="rental.order": # XXX
currency_id=obj.related_id.currency_id.id
else:
currency_id=None
if currency_id:
if inv_vals.get("currency_id"):
if currency_id!=inv_vals["currency_id"]:
raise Exception("Different currencies")
else:
inv_vals["currency_id"]=currency_id
resource=obj.resource_id
k=(resource.id,obj.sale_price or 0)
res_hours.setdefault(k,0)
res_hours[k]+=obj.bill_hours or 0
for (resource_id,sale_price),bill_hours in res_hours.items():
if not bill_hours:
continue
resource=get_model("service.resource").browse(resource_id)
prod=resource.product_id
if not prod:
raise Exception("Missing product for resource %s"%resource.name)
sale_acc_id=prod.sale_account_id.id
if not sale_acc_id and prod.categ_id:
sale_acc_id=prod.categ_id.sale_account_id.id
if not sale_acc_id:
raise Exception("Missing sales account in product %s"%prod.code)
line_vals = {
"product_id": prod.id,
"description": resource.name,
"qty": bill_hours or 0,
"uom_id": prod.uom_id.id,
"unit_price": sale_price,
"account_id": sale_acc_id,
"tax_id": prod.sale_tax_id.id if prod else None,
"amount": (bill_hours or 0)*(sale_price or 0),
}
inv_vals["lines"].append(("create", line_vals))
if not inv_vals["lines"]:
raise Exception("Nothing to invoice")
inv_id = get_model("account.invoice").create(inv_vals, {"type": "out", "inv_type": "invoice"})
self.write(ids,{"invoice_id": inv_id})
inv = get_model("account.invoice").browse(inv_id)
return {
"next": {
"name": "view_invoice",
"active_id": inv_id,
},
"flash": "Invoice %s created from work time" % inv.number,
}
WorkTime.register()
| {
"content_hash": "f9896bb6f67e597c200d473183679515",
"timestamp": "",
"source": "github",
"line_count": 275,
"max_line_length": 218,
"avg_line_length": 43.96727272727273,
"alnum_prop": 0.5449507898436854,
"repo_name": "bank-netforce/netforce",
"id": "dd64f7ef2de6129c3dd0ac42f74e0bf24f9bf326",
"size": "13196",
"binary": false,
"copies": "1",
"ref": "refs/heads/stable-3.1",
"path": "netforce_service/netforce_service/models/work_time.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "73"
},
{
"name": "CSS",
"bytes": "407336"
},
{
"name": "HTML",
"bytes": "478918"
},
{
"name": "Java",
"bytes": "11870"
},
{
"name": "JavaScript",
"bytes": "3712147"
},
{
"name": "Makefile",
"bytes": "353"
},
{
"name": "PHP",
"bytes": "2274"
},
{
"name": "Python",
"bytes": "3469514"
},
{
"name": "Roff",
"bytes": "15858"
},
{
"name": "Shell",
"bytes": "117"
}
],
"symlink_target": ""
} |
from enum import Enum
# VK TWO FACTOR AUTH TYPE
class VKAuthApp(Enum):
APP = 0
SMS = 1
def parse_validation_method(param):
if param == '2fa_app':
return VKAuthApp.APP
else:
return VKAuthApp.SMS | {
"content_hash": "dc8cf98ed7e9468e73082cc9bca15e12",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 35,
"avg_line_length": 17.53846153846154,
"alnum_prop": 0.6359649122807017,
"repo_name": "ihydrogen/hydrogen-chat-bot-py",
"id": "3507e3315ed641efba8e8bf2ab8a2ea4edcf8691",
"size": "228",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vk_auth/vk_2fa_type.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "77801"
}
],
"symlink_target": ""
} |
"""empty message
Revision ID: 9e8429737ba0
Revises: ecbe7bbcbd6c
Create Date: 2017-08-12 19:53:27.652000
"""
# revision identifiers, used by Alembic.
revision = '9e8429737ba0'
down_revision = 'ecbe7bbcbd6c'
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('bit_facebook_ad',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('ad_set_id', sa.Integer(), nullable=True),
sa.Column('native_id', sa.String(length=255), nullable=True),
sa.Column('account_id', sa.String(length=255), nullable=True),
sa.Column('campaign_id', sa.String(length=255), nullable=True),
sa.Column('adset_id', sa.String(length=255), nullable=True),
sa.Column('name', sa.String(length=255), nullable=True),
sa.Column('bid_amount', sa.Integer(), nullable=True),
sa.Column('bid_info', sa.String(length=255), nullable=True),
sa.Column('bid_type', sa.String(length=255), nullable=True),
sa.Column('configured_status', sa.String(length=255), nullable=True),
sa.Column('effective_status', sa.String(length=255), nullable=True),
sa.Column('status', sa.String(length=255), nullable=True),
sa.Column('created_time', sa.DateTime(), nullable=True),
sa.Column('updated_time', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['ad_set_id'], ['bit_facebook_ad_sets.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_bit_facebook_ad_native_id'), 'bit_facebook_ad', ['native_id'], unique=True)
op.add_column(u'bit_facebook_ad_campaigns', sa.Column('ad_account_id', sa.Integer(), nullable=True))
op.drop_index('ix_bit_facebook_ad_campaigns_account_id', table_name='bit_facebook_ad_campaigns')
op.create_foreign_key(None, 'bit_facebook_ad_campaigns', 'bit_facebook_ad_account', ['ad_account_id'], ['id'])
op.add_column(u'bit_facebook_ad_sets', sa.Column('ad_campaign_id', sa.Integer(), nullable=True))
op.drop_index('ix_bit_facebook_ad_sets_account_id', table_name='bit_facebook_ad_sets')
op.drop_index('ix_bit_facebook_ad_sets_campaign_id', table_name='bit_facebook_ad_sets')
op.create_foreign_key(None, 'bit_facebook_ad_sets', 'bit_facebook_ad_campaigns', ['ad_campaign_id'], ['id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'bit_facebook_ad_sets', type_='foreignkey')
op.create_index('ix_bit_facebook_ad_sets_campaign_id', 'bit_facebook_ad_sets', ['campaign_id'], unique=True)
op.create_index('ix_bit_facebook_ad_sets_account_id', 'bit_facebook_ad_sets', ['account_id'], unique=True)
op.drop_column(u'bit_facebook_ad_sets', 'ad_campaign_id')
op.drop_constraint(None, 'bit_facebook_ad_campaigns', type_='foreignkey')
op.create_index('ix_bit_facebook_ad_campaigns_account_id', 'bit_facebook_ad_campaigns', ['account_id'], unique=True)
op.drop_column(u'bit_facebook_ad_campaigns', 'ad_account_id')
op.drop_index(op.f('ix_bit_facebook_ad_native_id'), table_name='bit_facebook_ad')
op.drop_table('bit_facebook_ad')
# ### end Alembic commands ###
| {
"content_hash": "788901b14e2f4728b94069d6e36259a0",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 120,
"avg_line_length": 52.442622950819676,
"alnum_prop": 0.6874023132228821,
"repo_name": "codesmart-co/bit",
"id": "768da29a3929a184fadb01ee6b6da49abb4130ea",
"size": "3199",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bit/migrations/versions/9e8429737ba0_.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "334"
},
{
"name": "HTML",
"bytes": "4695"
},
{
"name": "JavaScript",
"bytes": "7662"
},
{
"name": "Mako",
"bytes": "436"
},
{
"name": "Python",
"bytes": "285159"
}
],
"symlink_target": ""
} |
import hashlib
import hmac
import json
import uuid
import urlparse
from django import http
from django.conf import settings
from django.contrib import auth
from django.contrib.auth.signals import user_logged_in
from django.utils.datastructures import MultiValueDictKeyError
import basket
import commonware.log
from django_browserid import get_audience
from django_statsd.clients import statsd
from requests_oauthlib import OAuth2Session
from rest_framework import status
from rest_framework.exceptions import AuthenticationFailed, ParseError
from rest_framework.generics import (CreateAPIView, DestroyAPIView,
RetrieveAPIView, RetrieveUpdateAPIView)
from rest_framework.mixins import ListModelMixin
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle
from rest_framework.viewsets import GenericViewSet
import mkt
from lib.metrics import record_action
from mkt.users.models import UserProfile
from mkt.users.views import browserid_authenticate
from mkt.account.serializers import (AccountSerializer, FeedbackSerializer,
FxALoginSerializer, LoginSerializer,
NewsletterSerializer,
PermissionsSerializer)
from mkt.api.authentication import (RestAnonymousAuthentication,
RestOAuthAuthentication,
RestSharedSecretAuthentication)
from mkt.api.authorization import AllowSelf, AllowOwner
from mkt.api.base import CORSMixin, MarketplaceView
from mkt.constants.apps import INSTALL_TYPE_USER
from mkt.site.mail import send_mail_jinja
from mkt.site.utils import log_cef
from mkt.webapps.serializers import SimpleAppSerializer
from mkt.webapps.models import Installed, Webapp
log = commonware.log.getLogger('z.account')
def user_relevant_apps(user):
return {
'developed': list(user.addonuser_set.filter(
role=mkt.AUTHOR_ROLE_OWNER).values_list('addon_id', flat=True)),
'installed': list(user.installed_set.values_list(
'addon_id', flat=True)),
'purchased': list(user.purchase_ids()),
}
class MineMixin(object):
def get_object(self, queryset=None):
pk = self.kwargs.get('pk')
if pk == 'mine':
self.kwargs['pk'] = self.request.user.pk
return super(MineMixin, self).get_object(queryset)
class InstalledViewSet(CORSMixin, MarketplaceView, ListModelMixin,
GenericViewSet):
cors_allowed_methods = ['get']
serializer_class = SimpleAppSerializer
permission_classes = [AllowSelf]
authentication_classes = [RestOAuthAuthentication,
RestSharedSecretAuthentication]
def get_queryset(self):
return Webapp.objects.filter(
installed__user=self.request.user,
installed__install_type=INSTALL_TYPE_USER).order_by(
'-installed__created')
def remove_app(self, request, **kwargs):
self.cors_allowed_methods = ['post']
try:
to_remove = Webapp.objects.get(pk=request.DATA['app'])
except (KeyError, MultiValueDictKeyError):
raise ParseError(detail='`app` was not provided.')
except Webapp.DoesNotExist:
raise ParseError(detail='`app` does not exist.')
try:
installed = request.user.installed_set.get(
install_type=INSTALL_TYPE_USER, addon_id=to_remove.pk)
installed.delete()
except Installed.DoesNotExist:
raise ParseError(detail='`app` is not installed or not removable.')
return Response(status=status.HTTP_202_ACCEPTED)
class CreateAPIViewWithoutModel(MarketplaceView, CreateAPIView):
"""
A base class for APIs that need to support a create-like action, but
without being tied to a Django Model.
"""
authentication_classes = [RestOAuthAuthentication,
RestSharedSecretAuthentication,
RestAnonymousAuthentication]
cors_allowed_methods = ['post']
permission_classes = (AllowAny,)
def response_success(self, request, serializer, data=None):
if data is None:
data = serializer.data
return Response(data, status=status.HTTP_201_CREATED)
def response_error(self, request, serializer):
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.DATA)
if serializer.is_valid():
data = self.create_action(request, serializer)
return self.response_success(request, serializer, data=data)
return self.response_error(request, serializer)
class AccountView(MineMixin, CORSMixin, RetrieveUpdateAPIView):
authentication_classes = [RestOAuthAuthentication,
RestSharedSecretAuthentication]
cors_allowed_methods = ['get', 'patch', 'put']
model = UserProfile
permission_classes = (AllowOwner,)
serializer_class = AccountSerializer
class AnonymousUserMixin(object):
def get_object(self, *args, **kwargs):
try:
user = super(AnonymousUserMixin, self).get_object(*args, **kwargs)
except http.Http404:
# The base get_object() will raise Http404 instead of DoesNotExist.
# Treat no object as an anonymous user (source: unknown).
user = UserProfile(is_verified=False)
return user
class FeedbackView(CORSMixin, CreateAPIViewWithoutModel):
class FeedbackThrottle(UserRateThrottle):
THROTTLE_RATES = {
'user': '30/hour',
}
serializer_class = FeedbackSerializer
throttle_classes = (FeedbackThrottle,)
throttle_scope = 'user'
def create_action(self, request, serializer):
context_data = self.get_context_data(request, serializer)
sender = getattr(request.user, 'email', settings.NOBODY_EMAIL)
send_mail_jinja(u'Marketplace Feedback', 'account/email/feedback.txt',
context_data, headers={'Reply-To': sender},
recipient_list=[settings.MKT_APPS_FEEDBACK_EMAIL])
def get_context_data(self, request, serializer):
context_data = {
'user_agent': request.META.get('HTTP_USER_AGENT', ''),
'ip_address': request.META.get('REMOTE_ADDR', '')
}
context_data.update(serializer.data)
context_data['user'] = request.user
return context_data
def commonplace_token(email):
unique_id = uuid.uuid4().hex
consumer_id = hashlib.sha1(
email + settings.SECRET_KEY).hexdigest()
hm = hmac.new(
unique_id + settings.SECRET_KEY,
consumer_id, hashlib.sha512)
return ','.join((email, hm.hexdigest(), unique_id))
def fxa_oauth_api(name):
return urlparse.urljoin(settings.FXA_OAUTH_URL, 'v1/' + name)
def find_or_create_user(email, fxa_uid):
def find_user(**kwargs):
try:
return UserProfile.objects.get(**kwargs)
except UserProfile.DoesNotExist:
return None
profile = find_user(fxa_uid=fxa_uid) or find_user(email=email)
if profile:
created = False
profile.update(fxa_uid=fxa_uid, email=email)
else:
created = True
profile = UserProfile.objects.create(
fxa_uid=fxa_uid,
email=email,
source=mkt.LOGIN_SOURCE_FXA,
display_name=email.partition('@')[0],
is_verified=True)
if profile.source != mkt.LOGIN_SOURCE_FXA:
log.info('Set account to FxA for {0}'.format(email))
statsd.incr('z.mkt.user.fxa')
profile.update(source=mkt.LOGIN_SOURCE_FXA)
return profile, created
def fxa_authorize(session, client_secret, auth_response):
token = session.fetch_token(
fxa_oauth_api('token'),
authorization_response=auth_response,
client_secret=client_secret)
res = session.post(
fxa_oauth_api('verify'),
data=json.dumps({'token': token['access_token']}),
headers={'Content-Type': 'application/json'})
return res.json()
class FxALoginView(CORSMixin, CreateAPIViewWithoutModel):
authentication_classes = []
serializer_class = FxALoginSerializer
def create_action(self, request, serializer):
client_id = request.POST.get('client_id', settings.FXA_CLIENT_ID)
secret = settings.FXA_SECRETS[client_id]
session = OAuth2Session(
client_id,
scope=u'profile',
state=serializer.data['state'])
auth_response = serializer.data['auth_response']
fxa_authorization = fxa_authorize(session, secret, auth_response)
if 'user' in fxa_authorization:
email = fxa_authorization['email']
fxa_uid = fxa_authorization['user']
profile, created = find_or_create_user(email, fxa_uid)
if created:
log_cef('New Account', 5, request, username=fxa_uid,
signature='AUTHNOTICE',
msg='User created a new account (from FxA)')
record_action('new-user', request)
auth.login(request, profile)
profile.update(last_login_ip=request.META.get('REMOTE_ADDR', ''))
auth.signals.user_logged_in.send(sender=profile.__class__,
request=request,
user=profile)
else:
raise AuthenticationFailed('No profile.')
request.user = profile
request.groups = profile.groups.all()
# Remember whether the user has logged in to highlight the register or
# sign in nav button. 31536000 == one year.
request.set_cookie('has_logged_in', '1', max_age=5 * 31536000)
# We want to return completely custom data, not the serializer's.
data = {
'error': None,
'token': commonplace_token(request.user.email),
'settings': {
'display_name': request.user.display_name,
'email': request.user.email,
'enable_recommendations': request.user.enable_recommendations,
'source': 'firefox-accounts',
}
}
# Serializers give up if they aren't passed an instance, so we
# do that here despite PermissionsSerializer not needing one
# really.
permissions = PermissionsSerializer(context={'request': request},
instance=True)
data.update(permissions.data)
# Add ids of installed/purchased/developed apps.
data['apps'] = user_relevant_apps(profile)
return data
class LoginView(CORSMixin, CreateAPIViewWithoutModel):
authentication_classes = []
serializer_class = LoginSerializer
def create_action(self, request, serializer):
with statsd.timer('auth.browserid.verify'):
profile, msg = browserid_authenticate(
request, serializer.data['assertion'],
browserid_audience=(serializer.data['audience'] or
get_audience(request)),
is_mobile=serializer.data['is_mobile'],
)
if profile is None:
# Authentication failure.
log.info('No profile: %s' % (msg or ''))
raise AuthenticationFailed('No profile.')
request.user = profile
request.groups = profile.groups.all()
auth.login(request, profile)
user_logged_in.send(sender=profile.__class__, request=request,
user=profile)
# We want to return completely custom data, not the serializer's.
data = {
'error': None,
'token': commonplace_token(request.user.email),
'settings': {
'display_name': request.user.display_name,
'email': request.user.email,
'enable_recommendations': request.user.enable_recommendations,
}
}
# Serializers give up if they aren't passed an instance, so we
# do that here despite PermissionsSerializer not needing one
# really.
permissions = PermissionsSerializer(context={'request': request},
instance=True)
data.update(permissions.data)
# Add ids of installed/purchased/developed apps.
data['apps'] = user_relevant_apps(profile)
return data
class LogoutView(CORSMixin, DestroyAPIView):
authentication_classes = [RestOAuthAuthentication,
RestSharedSecretAuthentication]
permission_classes = (IsAuthenticated,)
cors_allowed_methods = ['delete']
def delete(self, request):
auth.logout(request)
return Response(status=status.HTTP_204_NO_CONTENT)
class NewsletterView(CORSMixin, CreateAPIViewWithoutModel):
class NewsletterThrottle(UserRateThrottle):
scope = 'newsletter'
THROTTLE_RATES = {
'newsletter': '30/hour',
}
serializer_class = NewsletterSerializer
throttle_classes = (NewsletterThrottle,)
def get_region(self):
return self.request.REGION.slug
def get_country(self):
region = self.get_region()
return '' if region == 'restofworld' else region
def response_success(self, request, serializer, data=None):
return Response({}, status=status.HTTP_204_NO_CONTENT)
def create_action(self, request, serializer):
email = serializer.data['email']
newsletter = serializer.data['newsletter']
lang = serializer.data['lang']
country = self.get_country()
basket.subscribe(email, newsletter, format='H', country=country,
lang=lang, optin='Y', trigger_welcome='Y')
class PermissionsView(CORSMixin, MineMixin, RetrieveAPIView):
authentication_classes = [RestOAuthAuthentication,
RestSharedSecretAuthentication]
cors_allowed_methods = ['get']
permission_classes = (AllowSelf,)
model = UserProfile
serializer_class = PermissionsSerializer
| {
"content_hash": "73459079193a3ba1d26e798b542c381a",
"timestamp": "",
"source": "github",
"line_count": 391,
"max_line_length": 79,
"avg_line_length": 36.8618925831202,
"alnum_prop": 0.6317907444668008,
"repo_name": "ayushagrawal288/zamboni",
"id": "ae11f21e60a4e8660456989d8706924d6333e11c",
"size": "14413",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "mkt/account/views.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "357271"
},
{
"name": "HTML",
"bytes": "2278028"
},
{
"name": "JavaScript",
"bytes": "533454"
},
{
"name": "Makefile",
"bytes": "4281"
},
{
"name": "Python",
"bytes": "4302621"
},
{
"name": "Shell",
"bytes": "11156"
},
{
"name": "Smarty",
"bytes": "1369"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.