code
stringlengths 1
25.8M
| language
stringclasses 18
values | source
stringclasses 4
values | repo
stringclasses 78
values | path
stringlengths 0
268
|
|---|---|---|---|---|
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth import views
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.urls import urlpatterns as auth_urlpatterns
from django.contrib.messages.api import info
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render
from django.template import RequestContext, Template
from django.views.decorators.cache import never_cache
class CustomRequestAuthenticationForm(AuthenticationForm):
def __init__(self, request, *args, **kwargs):
assert isinstance(request, HttpRequest)
super(CustomRequestAuthenticationForm, self).__init__(request, *args, **kwargs)
@never_cache
def remote_user_auth_view(request):
"Dummy view for remote user tests"
t = Template("Username is {{ user }}.")
c = RequestContext(request, {})
return HttpResponse(t.render(c))
def auth_processor_no_attr_access(request):
render(request, 'context_processors/auth_attrs_no_access.html')
# *After* rendering, we check whether the session was accessed
return render(request,
'context_processors/auth_attrs_test_access.html',
{'session_accessed': request.session.accessed})
def auth_processor_attr_access(request):
render(request, 'context_processors/auth_attrs_access.html')
return render(request,
'context_processors/auth_attrs_test_access.html',
{'session_accessed': request.session.accessed})
def auth_processor_user(request):
return render(request, 'context_processors/auth_attrs_user.html')
def auth_processor_perms(request):
return render(request, 'context_processors/auth_attrs_perms.html')
def auth_processor_perm_in_perms(request):
return render(request, 'context_processors/auth_attrs_perm_in_perms.html')
def auth_processor_messages(request):
info(request, "Message 1")
return render(request, 'context_processors/auth_attrs_messages.html')
def userpage(request):
pass
def custom_request_auth_login(request):
return views.login(request, authentication_form=CustomRequestAuthenticationForm)
# special urls for auth test cases
urlpatterns = auth_urlpatterns + [
url(r'^logout/custom_query/$', views.logout, dict(redirect_field_name='follow')),
url(r'^logout/next_page/$', views.logout, dict(next_page='/somewhere/')),
url(r'^logout/next_page/named/$', views.logout, dict(next_page='password_reset')),
url(r'^remote_user/$', remote_user_auth_view),
url(r'^password_reset_from_email/$', views.password_reset, dict(from_email='staffmember@example.com')),
url(r'^password_reset_extra_email_context/$', views.password_reset,
dict(extra_email_context=dict(greeting='Hello!'))),
url(r'^password_reset/custom_redirect/$', views.password_reset, dict(post_reset_redirect='/custom/')),
url(r'^password_reset/custom_redirect/named/$', views.password_reset, dict(post_reset_redirect='password_reset')),
url(r'^password_reset/html_email_template/$', views.password_reset,
dict(html_email_template_name='registration/html_password_reset_email.html')),
url(r'^reset/custom/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
views.password_reset_confirm,
dict(post_reset_redirect='/custom/')),
url(r'^reset/custom/named/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
views.password_reset_confirm,
dict(post_reset_redirect='password_reset')),
url(r'^password_change/custom/$', views.password_change, dict(post_change_redirect='/custom/')),
url(r'^password_change/custom/named/$', views.password_change, dict(post_change_redirect='password_reset')),
url(r'^login_required/$', login_required(views.password_reset)),
url(r'^login_required_login_url/$', login_required(views.password_reset, login_url='/somewhere/')),
url(r'^auth_processor_no_attr_access/$', auth_processor_no_attr_access),
url(r'^auth_processor_attr_access/$', auth_processor_attr_access),
url(r'^auth_processor_user/$', auth_processor_user),
url(r'^auth_processor_perms/$', auth_processor_perms),
url(r'^auth_processor_perm_in_perms/$', auth_processor_perm_in_perms),
url(r'^auth_processor_messages/$', auth_processor_messages),
url(r'^custom_request_auth_login/$', custom_request_auth_login),
url(r'^userpage/(.+)/$', userpage, name="userpage"),
# This line is only required to render the password reset with is_admin=True
url(r'^admin/', admin.site.urls),
]
|
unknown
|
codeparrot/codeparrot-clean
| ||
// mksysnum_openbsd.pl
// Code generated by the command above; DO NOT EDIT.
package syscall
const (
SYS_EXIT = 1 // { void sys_exit(int rval); }
SYS_FORK = 2 // { int sys_fork(void); }
SYS_READ = 3 // { ssize_t sys_read(int fd, void *buf, size_t nbyte); }
SYS_WRITE = 4 // { ssize_t sys_write(int fd, const void *buf, \
SYS_OPEN = 5 // { int sys_open(const char *path, \
SYS_CLOSE = 6 // { int sys_close(int fd); }
SYS_GETENTROPY = 7 // { int sys_getentropy(void *buf, size_t nbyte); }
SYS___TFORK = 8 // { int sys___tfork(const struct __tfork *param, \
SYS_LINK = 9 // { int sys_link(const char *path, const char *link); }
SYS_UNLINK = 10 // { int sys_unlink(const char *path); }
SYS_WAIT4 = 11 // { pid_t sys_wait4(pid_t pid, int *status, \
SYS_CHDIR = 12 // { int sys_chdir(const char *path); }
SYS_FCHDIR = 13 // { int sys_fchdir(int fd); }
SYS_MKNOD = 14 // { int sys_mknod(const char *path, mode_t mode, \
SYS_CHMOD = 15 // { int sys_chmod(const char *path, mode_t mode); }
SYS_CHOWN = 16 // { int sys_chown(const char *path, uid_t uid, \
SYS_OBREAK = 17 // { int sys_obreak(char *nsize); } break
SYS_GETDTABLECOUNT = 18 // { int sys_getdtablecount(void); }
SYS_GETRUSAGE = 19 // { int sys_getrusage(int who, \
SYS_GETPID = 20 // { pid_t sys_getpid(void); }
SYS_MOUNT = 21 // { int sys_mount(const char *type, const char *path, \
SYS_UNMOUNT = 22 // { int sys_unmount(const char *path, int flags); }
SYS_SETUID = 23 // { int sys_setuid(uid_t uid); }
SYS_GETUID = 24 // { uid_t sys_getuid(void); }
SYS_GETEUID = 25 // { uid_t sys_geteuid(void); }
SYS_PTRACE = 26 // { int sys_ptrace(int req, pid_t pid, caddr_t addr, \
SYS_RECVMSG = 27 // { ssize_t sys_recvmsg(int s, struct msghdr *msg, \
SYS_SENDMSG = 28 // { ssize_t sys_sendmsg(int s, \
SYS_RECVFROM = 29 // { ssize_t sys_recvfrom(int s, void *buf, size_t len, \
SYS_ACCEPT = 30 // { int sys_accept(int s, struct sockaddr *name, \
SYS_GETPEERNAME = 31 // { int sys_getpeername(int fdes, struct sockaddr *asa, \
SYS_GETSOCKNAME = 32 // { int sys_getsockname(int fdes, struct sockaddr *asa, \
SYS_ACCESS = 33 // { int sys_access(const char *path, int amode); }
SYS_CHFLAGS = 34 // { int sys_chflags(const char *path, u_int flags); }
SYS_FCHFLAGS = 35 // { int sys_fchflags(int fd, u_int flags); }
SYS_SYNC = 36 // { void sys_sync(void); }
SYS_MSYSCALL = 37 // { int sys_msyscall(void *addr, size_t len); }
SYS_STAT = 38 // { int sys_stat(const char *path, struct stat *ub); }
SYS_GETPPID = 39 // { pid_t sys_getppid(void); }
SYS_LSTAT = 40 // { int sys_lstat(const char *path, struct stat *ub); }
SYS_DUP = 41 // { int sys_dup(int fd); }
SYS_FSTATAT = 42 // { int sys_fstatat(int fd, const char *path, \
SYS_GETEGID = 43 // { gid_t sys_getegid(void); }
SYS_PROFIL = 44 // { int sys_profil(caddr_t samples, size_t size, \
SYS_KTRACE = 45 // { int sys_ktrace(const char *fname, int ops, \
SYS_SIGACTION = 46 // { int sys_sigaction(int signum, \
SYS_GETGID = 47 // { gid_t sys_getgid(void); }
SYS_SIGPROCMASK = 48 // { int sys_sigprocmask(int how, sigset_t mask); }
SYS_SETLOGIN = 50 // { int sys_setlogin(const char *namebuf); }
SYS_ACCT = 51 // { int sys_acct(const char *path); }
SYS_SIGPENDING = 52 // { int sys_sigpending(void); }
SYS_FSTAT = 53 // { int sys_fstat(int fd, struct stat *sb); }
SYS_IOCTL = 54 // { int sys_ioctl(int fd, \
SYS_REBOOT = 55 // { int sys_reboot(int opt); }
SYS_REVOKE = 56 // { int sys_revoke(const char *path); }
SYS_SYMLINK = 57 // { int sys_symlink(const char *path, \
SYS_READLINK = 58 // { ssize_t sys_readlink(const char *path, \
SYS_EXECVE = 59 // { int sys_execve(const char *path, \
SYS_UMASK = 60 // { mode_t sys_umask(mode_t newmask); }
SYS_CHROOT = 61 // { int sys_chroot(const char *path); }
SYS_GETFSSTAT = 62 // { int sys_getfsstat(struct statfs *buf, size_t bufsize, \
SYS_STATFS = 63 // { int sys_statfs(const char *path, \
SYS_FSTATFS = 64 // { int sys_fstatfs(int fd, struct statfs *buf); }
SYS_FHSTATFS = 65 // { int sys_fhstatfs(const fhandle_t *fhp, \
SYS_VFORK = 66 // { int sys_vfork(void); }
SYS_GETTIMEOFDAY = 67 // { int sys_gettimeofday(struct timeval *tp, \
SYS_SETTIMEOFDAY = 68 // { int sys_settimeofday(const struct timeval *tv, \
SYS_SETITIMER = 69 // { int sys_setitimer(int which, \
SYS_GETITIMER = 70 // { int sys_getitimer(int which, \
SYS_SELECT = 71 // { int sys_select(int nd, fd_set *in, fd_set *ou, \
SYS_KEVENT = 72 // { int sys_kevent(int fd, \
SYS_MUNMAP = 73 // { int sys_munmap(void *addr, size_t len); }
SYS_MPROTECT = 74 // { int sys_mprotect(void *addr, size_t len, \
SYS_MADVISE = 75 // { int sys_madvise(void *addr, size_t len, \
SYS_UTIMES = 76 // { int sys_utimes(const char *path, \
SYS_FUTIMES = 77 // { int sys_futimes(int fd, \
SYS_GETGROUPS = 79 // { int sys_getgroups(int gidsetsize, \
SYS_SETGROUPS = 80 // { int sys_setgroups(int gidsetsize, \
SYS_GETPGRP = 81 // { int sys_getpgrp(void); }
SYS_SETPGID = 82 // { int sys_setpgid(pid_t pid, pid_t pgid); }
SYS_FUTEX = 83 // { int sys_futex(uint32_t *f, int op, int val, \
SYS_UTIMENSAT = 84 // { int sys_utimensat(int fd, const char *path, \
SYS_FUTIMENS = 85 // { int sys_futimens(int fd, \
SYS_KBIND = 86 // { int sys_kbind(const struct __kbind *param, \
SYS_CLOCK_GETTIME = 87 // { int sys_clock_gettime(clockid_t clock_id, \
SYS_CLOCK_SETTIME = 88 // { int sys_clock_settime(clockid_t clock_id, \
SYS_CLOCK_GETRES = 89 // { int sys_clock_getres(clockid_t clock_id, \
SYS_DUP2 = 90 // { int sys_dup2(int from, int to); }
SYS_NANOSLEEP = 91 // { int sys_nanosleep(const struct timespec *rqtp, \
SYS_FCNTL = 92 // { int sys_fcntl(int fd, int cmd, ... void *arg); }
SYS_ACCEPT4 = 93 // { int sys_accept4(int s, struct sockaddr *name, \
SYS___THRSLEEP = 94 // { int sys___thrsleep(const volatile void *ident, \
SYS_FSYNC = 95 // { int sys_fsync(int fd); }
SYS_SETPRIORITY = 96 // { int sys_setpriority(int which, id_t who, int prio); }
SYS_SOCKET = 97 // { int sys_socket(int domain, int type, int protocol); }
SYS_CONNECT = 98 // { int sys_connect(int s, const struct sockaddr *name, \
SYS_GETDENTS = 99 // { int sys_getdents(int fd, void *buf, size_t buflen); }
SYS_GETPRIORITY = 100 // { int sys_getpriority(int which, id_t who); }
SYS_PIPE2 = 101 // { int sys_pipe2(int *fdp, int flags); }
SYS_DUP3 = 102 // { int sys_dup3(int from, int to, int flags); }
SYS_SIGRETURN = 103 // { int sys_sigreturn(struct sigcontext *sigcntxp); }
SYS_BIND = 104 // { int sys_bind(int s, const struct sockaddr *name, \
SYS_SETSOCKOPT = 105 // { int sys_setsockopt(int s, int level, int name, \
SYS_LISTEN = 106 // { int sys_listen(int s, int backlog); }
SYS_CHFLAGSAT = 107 // { int sys_chflagsat(int fd, const char *path, \
SYS_PLEDGE = 108 // { int sys_pledge(const char *promises, \
SYS_PPOLL = 109 // { int sys_ppoll(struct pollfd *fds, \
SYS_PSELECT = 110 // { int sys_pselect(int nd, fd_set *in, fd_set *ou, \
SYS_SIGSUSPEND = 111 // { int sys_sigsuspend(int mask); }
SYS_SENDSYSLOG = 112 // { int sys_sendsyslog(const char *buf, size_t nbyte, \
SYS_UNVEIL = 114 // { int sys_unveil(const char *path, \
SYS___REALPATH = 115 // { int sys___realpath(const char *pathname, \
SYS_GETSOCKOPT = 118 // { int sys_getsockopt(int s, int level, int name, \
SYS_THRKILL = 119 // { int sys_thrkill(pid_t tid, int signum, void *tcb); }
SYS_READV = 120 // { ssize_t sys_readv(int fd, \
SYS_WRITEV = 121 // { ssize_t sys_writev(int fd, \
SYS_KILL = 122 // { int sys_kill(int pid, int signum); }
SYS_FCHOWN = 123 // { int sys_fchown(int fd, uid_t uid, gid_t gid); }
SYS_FCHMOD = 124 // { int sys_fchmod(int fd, mode_t mode); }
SYS_SETREUID = 126 // { int sys_setreuid(uid_t ruid, uid_t euid); }
SYS_SETREGID = 127 // { int sys_setregid(gid_t rgid, gid_t egid); }
SYS_RENAME = 128 // { int sys_rename(const char *from, const char *to); }
SYS_FLOCK = 131 // { int sys_flock(int fd, int how); }
SYS_MKFIFO = 132 // { int sys_mkfifo(const char *path, mode_t mode); }
SYS_SENDTO = 133 // { ssize_t sys_sendto(int s, const void *buf, \
SYS_SHUTDOWN = 134 // { int sys_shutdown(int s, int how); }
SYS_SOCKETPAIR = 135 // { int sys_socketpair(int domain, int type, \
SYS_MKDIR = 136 // { int sys_mkdir(const char *path, mode_t mode); }
SYS_RMDIR = 137 // { int sys_rmdir(const char *path); }
SYS_ADJTIME = 140 // { int sys_adjtime(const struct timeval *delta, \
SYS_GETLOGIN_R = 141 // { int sys_getlogin_r(char *namebuf, u_int namelen); }
SYS_SETSID = 147 // { int sys_setsid(void); }
SYS_QUOTACTL = 148 // { int sys_quotactl(const char *path, int cmd, \
SYS_NFSSVC = 155 // { int sys_nfssvc(int flag, void *argp); }
SYS_GETFH = 161 // { int sys_getfh(const char *fname, fhandle_t *fhp); }
SYS___TMPFD = 164 // { int sys___tmpfd(int flags); }
SYS_SYSARCH = 165 // { int sys_sysarch(int op, void *parms); }
SYS_PREAD = 173 // { ssize_t sys_pread(int fd, void *buf, \
SYS_PWRITE = 174 // { ssize_t sys_pwrite(int fd, const void *buf, \
SYS_SETGID = 181 // { int sys_setgid(gid_t gid); }
SYS_SETEGID = 182 // { int sys_setegid(gid_t egid); }
SYS_SETEUID = 183 // { int sys_seteuid(uid_t euid); }
SYS_PATHCONF = 191 // { long sys_pathconf(const char *path, int name); }
SYS_FPATHCONF = 192 // { long sys_fpathconf(int fd, int name); }
SYS_SWAPCTL = 193 // { int sys_swapctl(int cmd, const void *arg, int misc); }
SYS_GETRLIMIT = 194 // { int sys_getrlimit(int which, \
SYS_SETRLIMIT = 195 // { int sys_setrlimit(int which, \
SYS_MMAP = 197 // { void *sys_mmap(void *addr, size_t len, int prot, \
SYS_LSEEK = 199 // { off_t sys_lseek(int fd, int pad, off_t offset, \
SYS_TRUNCATE = 200 // { int sys_truncate(const char *path, int pad, \
SYS_FTRUNCATE = 201 // { int sys_ftruncate(int fd, int pad, off_t length); }
SYS_SYSCTL = 202 // { int sys_sysctl(const int *name, u_int namelen, \
SYS_MLOCK = 203 // { int sys_mlock(const void *addr, size_t len); }
SYS_MUNLOCK = 204 // { int sys_munlock(const void *addr, size_t len); }
SYS_GETPGID = 207 // { pid_t sys_getpgid(pid_t pid); }
SYS_UTRACE = 209 // { int sys_utrace(const char *label, const void *addr, \
SYS_SEMGET = 221 // { int sys_semget(key_t key, int nsems, int semflg); }
SYS_MSGGET = 225 // { int sys_msgget(key_t key, int msgflg); }
SYS_MSGSND = 226 // { int sys_msgsnd(int msqid, const void *msgp, size_t msgsz, \
SYS_MSGRCV = 227 // { int sys_msgrcv(int msqid, void *msgp, size_t msgsz, \
SYS_SHMAT = 228 // { void *sys_shmat(int shmid, const void *shmaddr, \
SYS_SHMDT = 230 // { int sys_shmdt(const void *shmaddr); }
SYS_MINHERIT = 250 // { int sys_minherit(void *addr, size_t len, \
SYS_POLL = 252 // { int sys_poll(struct pollfd *fds, \
SYS_ISSETUGID = 253 // { int sys_issetugid(void); }
SYS_LCHOWN = 254 // { int sys_lchown(const char *path, uid_t uid, gid_t gid); }
SYS_GETSID = 255 // { pid_t sys_getsid(pid_t pid); }
SYS_MSYNC = 256 // { int sys_msync(void *addr, size_t len, int flags); }
SYS_PIPE = 263 // { int sys_pipe(int *fdp); }
SYS_FHOPEN = 264 // { int sys_fhopen(const fhandle_t *fhp, int flags); }
SYS_PREADV = 267 // { ssize_t sys_preadv(int fd, \
SYS_PWRITEV = 268 // { ssize_t sys_pwritev(int fd, \
SYS_KQUEUE = 269 // { int sys_kqueue(void); }
SYS_MLOCKALL = 271 // { int sys_mlockall(int flags); }
SYS_MUNLOCKALL = 272 // { int sys_munlockall(void); }
SYS_GETRESUID = 281 // { int sys_getresuid(uid_t *ruid, uid_t *euid, \
SYS_SETRESUID = 282 // { int sys_setresuid(uid_t ruid, uid_t euid, \
SYS_GETRESGID = 283 // { int sys_getresgid(gid_t *rgid, gid_t *egid, \
SYS_SETRESGID = 284 // { int sys_setresgid(gid_t rgid, gid_t egid, \
SYS_MQUERY = 286 // { void *sys_mquery(void *addr, size_t len, int prot, \
SYS_CLOSEFROM = 287 // { int sys_closefrom(int fd); }
SYS_SIGALTSTACK = 288 // { int sys_sigaltstack(const struct sigaltstack *nss, \
SYS_SHMGET = 289 // { int sys_shmget(key_t key, size_t size, int shmflg); }
SYS_SEMOP = 290 // { int sys_semop(int semid, struct sembuf *sops, \
SYS_FHSTAT = 294 // { int sys_fhstat(const fhandle_t *fhp, \
SYS___SEMCTL = 295 // { int sys___semctl(int semid, int semnum, int cmd, \
SYS_SHMCTL = 296 // { int sys_shmctl(int shmid, int cmd, \
SYS_MSGCTL = 297 // { int sys_msgctl(int msqid, int cmd, \
SYS_SCHED_YIELD = 298 // { int sys_sched_yield(void); }
SYS_GETTHRID = 299 // { pid_t sys_getthrid(void); }
SYS___THRWAKEUP = 301 // { int sys___thrwakeup(const volatile void *ident, \
SYS___THREXIT = 302 // { void sys___threxit(pid_t *notdead); }
SYS___THRSIGDIVERT = 303 // { int sys___thrsigdivert(sigset_t sigmask, \
SYS___GETCWD = 304 // { int sys___getcwd(char *buf, size_t len); }
SYS_ADJFREQ = 305 // { int sys_adjfreq(const int64_t *freq, \
SYS_SETRTABLE = 310 // { int sys_setrtable(int rtableid); }
SYS_GETRTABLE = 311 // { int sys_getrtable(void); }
SYS_FACCESSAT = 313 // { int sys_faccessat(int fd, const char *path, \
SYS_FCHMODAT = 314 // { int sys_fchmodat(int fd, const char *path, \
SYS_FCHOWNAT = 315 // { int sys_fchownat(int fd, const char *path, \
SYS_LINKAT = 317 // { int sys_linkat(int fd1, const char *path1, int fd2, \
SYS_MKDIRAT = 318 // { int sys_mkdirat(int fd, const char *path, \
SYS_MKFIFOAT = 319 // { int sys_mkfifoat(int fd, const char *path, \
SYS_MKNODAT = 320 // { int sys_mknodat(int fd, const char *path, \
SYS_OPENAT = 321 // { int sys_openat(int fd, const char *path, int flags, \
SYS_READLINKAT = 322 // { ssize_t sys_readlinkat(int fd, const char *path, \
SYS_RENAMEAT = 323 // { int sys_renameat(int fromfd, const char *from, \
SYS_SYMLINKAT = 324 // { int sys_symlinkat(const char *path, int fd, \
SYS_UNLINKAT = 325 // { int sys_unlinkat(int fd, const char *path, \
SYS___SET_TCB = 329 // { void sys___set_tcb(void *tcb); }
SYS___GET_TCB = 330 // { void *sys___get_tcb(void); }
)
|
go
|
github
|
https://github.com/golang/go
|
src/syscall/zsysnum_openbsd_mips64.go
|
from StringIO import StringIO
import pickle
import sys
import platform
import gc
import copy
from os import path
from numpy.testing import *
from numpy.testing.utils import _assert_valid_refcount, WarningManager
from numpy.compat import asbytes, asunicode, asbytes_nested
import warnings
import tempfile
import numpy as np
if sys.version_info[0] >= 3:
import io
StringIO = io.BytesIO
rlevel = 1
class TestRegression(TestCase):
def test_invalid_round(self,level=rlevel):
"""Ticket #3"""
v = 4.7599999999999998
assert_array_equal(np.array([v]),np.array(v))
def test_mem_empty(self,level=rlevel):
"""Ticket #7"""
np.empty((1,),dtype=[('x',np.int64)])
def test_pickle_transposed(self,level=rlevel):
"""Ticket #16"""
a = np.transpose(np.array([[2,9],[7,0],[3,8]]))
f = StringIO()
pickle.dump(a,f)
f.seek(0)
b = pickle.load(f)
f.close()
assert_array_equal(a,b)
def test_typeNA(self,level=rlevel):
"""Ticket #31"""
assert_equal(np.typeNA[np.int64],'Int64')
assert_equal(np.typeNA[np.uint64],'UInt64')
def test_dtype_names(self,level=rlevel):
"""Ticket #35"""
dt = np.dtype([(('name','label'),np.int32,3)])
def test_reduce(self,level=rlevel):
"""Ticket #40"""
assert_almost_equal(np.add.reduce([1.,.5],dtype=None), 1.5)
def test_zeros_order(self,level=rlevel):
"""Ticket #43"""
np.zeros([3], int, 'C')
np.zeros([3], order='C')
np.zeros([3], int, order='C')
def test_sort_bigendian(self,level=rlevel):
"""Ticket #47"""
a = np.linspace(0, 10, 11)
c = a.astype(np.dtype('<f8'))
c.sort()
assert_array_almost_equal(c, a)
def test_negative_nd_indexing(self,level=rlevel):
"""Ticket #49"""
c = np.arange(125).reshape((5,5,5))
origidx = np.array([-1, 0, 1])
idx = np.array(origidx)
c[idx]
assert_array_equal(idx, origidx)
def test_char_dump(self,level=rlevel):
"""Ticket #50"""
f = StringIO()
ca = np.char.array(np.arange(1000,1010),itemsize=4)
ca.dump(f)
f.seek(0)
ca = np.load(f)
f.close()
def test_noncontiguous_fill(self,level=rlevel):
"""Ticket #58."""
a = np.zeros((5,3))
b = a[:,:2,]
def rs():
b.shape = (10,)
self.assertRaises(AttributeError,rs)
def test_bool(self,level=rlevel):
"""Ticket #60"""
x = np.bool_(1)
def test_indexing1(self,level=rlevel):
"""Ticket #64"""
descr = [('x', [('y', [('z', 'c16', (2,)),]),]),]
buffer = ((([6j,4j],),),)
h = np.array(buffer, dtype=descr)
h['x']['y']['z']
def test_indexing2(self,level=rlevel):
"""Ticket #65"""
descr = [('x', 'i4', (2,))]
buffer = ([3,2],)
h = np.array(buffer, dtype=descr)
h['x']
def test_round(self,level=rlevel):
"""Ticket #67"""
x = np.array([1+2j])
assert_almost_equal(x**(-1), [1/(1+2j)])
def test_scalar_compare(self,level=rlevel):
"""Ticket #72"""
a = np.array(['test', 'auto'])
assert_array_equal(a == 'auto', np.array([False,True]))
self.assertTrue(a[1] == 'auto')
self.assertTrue(a[0] != 'auto')
b = np.linspace(0, 10, 11)
self.assertTrue(b != 'auto')
self.assertTrue(b[0] != 'auto')
def test_unicode_swapping(self,level=rlevel):
"""Ticket #79"""
ulen = 1
ucs_value = u'\U0010FFFF'
ua = np.array([[[ucs_value*ulen]*2]*3]*4, dtype='U%s' % ulen)
ua2 = ua.newbyteorder()
def test_object_array_fill(self,level=rlevel):
"""Ticket #86"""
x = np.zeros(1, 'O')
x.fill([])
def test_mem_dtype_align(self,level=rlevel):
"""Ticket #93"""
self.assertRaises(TypeError,np.dtype,
{'names':['a'],'formats':['foo']},align=1)
@dec.knownfailureif((sys.version_info[0] >= 3) or
(sys.platform == "win32" and platform.architecture()[0] == "64bit"),
"numpy.intp('0xff', 16) not supported on Py3, "
"as it does not inherit from Python int")
def test_intp(self,level=rlevel):
"""Ticket #99"""
i_width = np.int_(0).nbytes*2 - 1
np.intp('0x' + 'f'*i_width,16)
self.assertRaises(OverflowError,np.intp,'0x' + 'f'*(i_width+1),16)
self.assertRaises(ValueError,np.intp,'0x1',32)
assert_equal(255,np.intp('0xFF',16))
assert_equal(1024,np.intp(1024))
def test_endian_bool_indexing(self,level=rlevel):
"""Ticket #105"""
a = np.arange(10.,dtype='>f8')
b = np.arange(10.,dtype='<f8')
xa = np.where((a>2) & (a<6))
xb = np.where((b>2) & (b<6))
ya = ((a>2) & (a<6))
yb = ((b>2) & (b<6))
assert_array_almost_equal(xa,ya.nonzero())
assert_array_almost_equal(xb,yb.nonzero())
assert_(np.all(a[ya] > 0.5))
assert_(np.all(b[yb] > 0.5))
def test_mem_dot(self,level=rlevel):
"""Ticket #106"""
x = np.random.randn(0,1)
y = np.random.randn(10,1)
z = np.dot(x, np.transpose(y))
def test_arange_endian(self,level=rlevel):
"""Ticket #111"""
ref = np.arange(10)
x = np.arange(10,dtype='<f8')
assert_array_equal(ref,x)
x = np.arange(10,dtype='>f8')
assert_array_equal(ref,x)
# Longfloat support is not consistent enough across
# platforms for this test to be meaningful.
# def test_longfloat_repr(self,level=rlevel):
# """Ticket #112"""
# if np.longfloat(0).itemsize > 8:
# a = np.exp(np.array([1000],dtype=np.longfloat))
# assert_(str(a)[1:9] == str(a[0])[:8])
def test_argmax(self,level=rlevel):
"""Ticket #119"""
a = np.random.normal(0,1,(4,5,6,7,8))
for i in xrange(a.ndim):
aargmax = a.argmax(i)
def test_mem_divmod(self,level=rlevel):
"""Ticket #126"""
for i in range(10):
divmod(np.array([i])[0],10)
def test_hstack_invalid_dims(self,level=rlevel):
"""Ticket #128"""
x = np.arange(9).reshape((3,3))
y = np.array([0,0,0])
self.assertRaises(ValueError,np.hstack,(x,y))
def test_squeeze_type(self,level=rlevel):
"""Ticket #133"""
a = np.array([3])
b = np.array(3)
assert_(type(a.squeeze()) is np.ndarray)
assert_(type(b.squeeze()) is np.ndarray)
def test_add_identity(self,level=rlevel):
"""Ticket #143"""
assert_equal(0,np.add.identity)
def test_binary_repr_0(self,level=rlevel):
"""Ticket #151"""
assert_equal('0',np.binary_repr(0))
def test_rec_iterate(self,level=rlevel):
"""Ticket #160"""
descr = np.dtype([('i',int),('f',float),('s','|S3')])
x = np.rec.array([(1,1.1,'1.0'),
(2,2.2,'2.0')],dtype=descr)
x[0].tolist()
[i for i in x[0]]
def test_unicode_string_comparison(self,level=rlevel):
"""Ticket #190"""
a = np.array('hello',np.unicode_)
b = np.array('world')
a == b
def test_tostring_FORTRANORDER_discontiguous(self,level=rlevel):
"""Fix in r2836"""
# Create discontiguous Fortran-ordered array
x = np.array(np.random.rand(3,3),order='F')[:,:2]
assert_array_almost_equal(x.ravel(),np.fromstring(x.tostring()))
def test_flat_assignment(self,level=rlevel):
"""Correct behaviour of ticket #194"""
x = np.empty((3,1))
x.flat = np.arange(3)
assert_array_almost_equal(x,[[0],[1],[2]])
x.flat = np.arange(3,dtype=float)
assert_array_almost_equal(x,[[0],[1],[2]])
def test_broadcast_flat_assignment(self,level=rlevel):
"""Ticket #194"""
x = np.empty((3,1))
def bfa(): x[:] = np.arange(3)
def bfb(): x[:] = np.arange(3,dtype=float)
self.assertRaises(ValueError, bfa)
self.assertRaises(ValueError, bfb)
def test_unpickle_dtype_with_object(self,level=rlevel):
"""Implemented in r2840"""
dt = np.dtype([('x',int),('y',np.object_),('z','O')])
f = StringIO()
pickle.dump(dt,f)
f.seek(0)
dt_ = pickle.load(f)
f.close()
assert_equal(dt,dt_)
def test_mem_array_creation_invalid_specification(self,level=rlevel):
"""Ticket #196"""
dt = np.dtype([('x',int),('y',np.object_)])
# Wrong way
self.assertRaises(ValueError, np.array, [1,'object'], dt)
# Correct way
np.array([(1,'object')],dt)
def test_recarray_single_element(self,level=rlevel):
"""Ticket #202"""
a = np.array([1,2,3],dtype=np.int32)
b = a.copy()
r = np.rec.array(a,shape=1,formats=['3i4'],names=['d'])
assert_array_equal(a,b)
assert_equal(a,r[0][0])
def test_zero_sized_array_indexing(self,level=rlevel):
"""Ticket #205"""
tmp = np.array([])
def index_tmp(): tmp[np.array(10)]
self.assertRaises(IndexError, index_tmp)
def test_chararray_rstrip(self,level=rlevel):
"""Ticket #222"""
x = np.chararray((1,),5)
x[0] = asbytes('a ')
x = x.rstrip()
assert_equal(x[0], asbytes('a'))
def test_object_array_shape(self,level=rlevel):
"""Ticket #239"""
assert_equal(np.array([[1,2],3,4],dtype=object).shape, (3,))
assert_equal(np.array([[1,2],[3,4]],dtype=object).shape, (2,2))
assert_equal(np.array([(1,2),(3,4)],dtype=object).shape, (2,2))
assert_equal(np.array([],dtype=object).shape, (0,))
assert_equal(np.array([[],[],[]],dtype=object).shape, (3,0))
assert_equal(np.array([[3,4],[5,6],None],dtype=object).shape, (3,))
def test_mem_around(self,level=rlevel):
"""Ticket #243"""
x = np.zeros((1,))
y = [0]
decimal = 6
np.around(abs(x-y),decimal) <= 10.0**(-decimal)
def test_character_array_strip(self,level=rlevel):
"""Ticket #246"""
x = np.char.array(("x","x ","x "))
for c in x: assert_equal(c,"x")
def test_lexsort(self,level=rlevel):
"""Lexsort memory error"""
v = np.array([1,2,3,4,5,6,7,8,9,10])
assert_equal(np.lexsort(v),0)
def test_pickle_dtype(self,level=rlevel):
"""Ticket #251"""
import pickle
pickle.dumps(np.float)
def test_swap_real(self, level=rlevel):
"""Ticket #265"""
assert_equal(np.arange(4,dtype='>c8').imag.max(),0.0)
assert_equal(np.arange(4,dtype='<c8').imag.max(),0.0)
assert_equal(np.arange(4,dtype='>c8').real.max(),3.0)
assert_equal(np.arange(4,dtype='<c8').real.max(),3.0)
def test_object_array_from_list(self, level=rlevel):
"""Ticket #270"""
a = np.array([1,'A',None])
def test_multiple_assign(self, level=rlevel):
"""Ticket #273"""
a = np.zeros((3,1),int)
a[[1,2]] = 1
def test_empty_array_type(self, level=rlevel):
assert_equal(np.array([]).dtype, np.zeros(0).dtype)
def test_void_copyswap(self, level=rlevel):
dt = np.dtype([('one', '<i4'),('two', '<i4')])
x = np.array((1,2), dtype=dt)
x = x.byteswap()
assert_(x['one'] > 1 and x['two'] > 2)
def test_method_args(self, level=rlevel):
# Make sure methods and functions have same default axis
# keyword and arguments
funcs1= ['argmax', 'argmin', 'sum', ('product', 'prod'),
('sometrue', 'any'),
('alltrue', 'all'), 'cumsum', ('cumproduct', 'cumprod'),
'ptp', 'cumprod', 'prod', 'std', 'var', 'mean',
'round', 'min', 'max', 'argsort', 'sort']
funcs2 = ['compress', 'take', 'repeat']
for func in funcs1:
arr = np.random.rand(8,7)
arr2 = arr.copy()
if isinstance(func, tuple):
func_meth = func[1]
func = func[0]
else:
func_meth = func
res1 = getattr(arr, func_meth)()
res2 = getattr(np, func)(arr2)
if res1 is None:
assert abs(arr-res2).max() < 1e-8, func
else:
assert abs(res1-res2).max() < 1e-8, func
for func in funcs2:
arr1 = np.random.rand(8,7)
arr2 = np.random.rand(8,7)
res1 = None
if func == 'compress':
arr1 = arr1.ravel()
res1 = getattr(arr2, func)(arr1)
else:
arr2 = (15*arr2).astype(int).ravel()
if res1 is None:
res1 = getattr(arr1, func)(arr2)
res2 = getattr(np, func)(arr1, arr2)
assert abs(res1-res2).max() < 1e-8, func
def test_mem_lexsort_strings(self, level=rlevel):
"""Ticket #298"""
lst = ['abc','cde','fgh']
np.lexsort((lst,))
def test_fancy_index(self, level=rlevel):
"""Ticket #302"""
x = np.array([1,2])[np.array([0])]
assert_equal(x.shape,(1,))
def test_recarray_copy(self, level=rlevel):
"""Ticket #312"""
dt = [('x',np.int16),('y',np.float64)]
ra = np.array([(1,2.3)], dtype=dt)
rb = np.rec.array(ra, dtype=dt)
rb['x'] = 2.
assert ra['x'] != rb['x']
def test_rec_fromarray(self, level=rlevel):
"""Ticket #322"""
x1 = np.array([[1,2],[3,4],[5,6]])
x2 = np.array(['a','dd','xyz'])
x3 = np.array([1.1,2,3])
np.rec.fromarrays([x1,x2,x3], formats="(2,)i4,a3,f8")
def test_object_array_assign(self, level=rlevel):
x = np.empty((2,2),object)
x.flat[2] = (1,2,3)
assert_equal(x.flat[2],(1,2,3))
def test_ndmin_float64(self, level=rlevel):
"""Ticket #324"""
x = np.array([1,2,3],dtype=np.float64)
assert_equal(np.array(x,dtype=np.float32,ndmin=2).ndim,2)
assert_equal(np.array(x,dtype=np.float64,ndmin=2).ndim,2)
def test_mem_axis_minimization(self, level=rlevel):
"""Ticket #327"""
data = np.arange(5)
data = np.add.outer(data,data)
def test_mem_float_imag(self, level=rlevel):
"""Ticket #330"""
np.float64(1.0).imag
def test_dtype_tuple(self, level=rlevel):
"""Ticket #334"""
assert np.dtype('i4') == np.dtype(('i4',()))
def test_dtype_posttuple(self, level=rlevel):
"""Ticket #335"""
np.dtype([('col1', '()i4')])
def test_numeric_carray_compare(self, level=rlevel):
"""Ticket #341"""
assert_equal(np.array(['X'], 'c'), asbytes('X'))
def test_string_array_size(self, level=rlevel):
"""Ticket #342"""
self.assertRaises(ValueError,
np.array,[['X'],['X','X','X']],'|S1')
def test_dtype_repr(self, level=rlevel):
"""Ticket #344"""
dt1=np.dtype(('uint32', 2))
dt2=np.dtype(('uint32', (2,)))
assert_equal(dt1.__repr__(), dt2.__repr__())
def test_reshape_order(self, level=rlevel):
"""Make sure reshape order works."""
a = np.arange(6).reshape(2,3,order='F')
assert_equal(a,[[0,2,4],[1,3,5]])
a = np.array([[1,2],[3,4],[5,6],[7,8]])
b = a[:,1]
assert_equal(b.reshape(2,2,order='F'), [[2,6],[4,8]])
def test_repeat_discont(self, level=rlevel):
"""Ticket #352"""
a = np.arange(12).reshape(4,3)[:,2]
assert_equal(a.repeat(3), [2,2,2,5,5,5,8,8,8,11,11,11])
def test_array_index(self, level=rlevel):
"""Make sure optimization is not called in this case."""
a = np.array([1,2,3])
a2 = np.array([[1,2,3]])
assert_equal(a[np.where(a==3)], a2[np.where(a2==3)])
def test_object_argmax(self, level=rlevel):
a = np.array([1,2,3],dtype=object)
assert a.argmax() == 2
def test_recarray_fields(self, level=rlevel):
"""Ticket #372"""
dt0 = np.dtype([('f0','i4'),('f1','i4')])
dt1 = np.dtype([('f0','i8'),('f1','i8')])
for a in [np.array([(1,2),(3,4)],"i4,i4"),
np.rec.array([(1,2),(3,4)],"i4,i4"),
np.rec.array([(1,2),(3,4)]),
np.rec.fromarrays([(1,2),(3,4)],"i4,i4"),
np.rec.fromarrays([(1,2),(3,4)])]:
assert_(a.dtype in [dt0,dt1])
def test_random_shuffle(self, level=rlevel):
"""Ticket #374"""
a = np.arange(5).reshape((5,1))
b = a.copy()
np.random.shuffle(b)
assert_equal(np.sort(b, axis=0),a)
def test_refcount_vdot(self, level=rlevel):
"""Changeset #3443"""
_assert_valid_refcount(np.vdot)
def test_startswith(self, level=rlevel):
ca = np.char.array(['Hi','There'])
assert_equal(ca.startswith('H'),[True,False])
def test_noncommutative_reduce_accumulate(self, level=rlevel):
"""Ticket #413"""
tosubtract = np.arange(5)
todivide = np.array([2.0, 0.5, 0.25])
assert_equal(np.subtract.reduce(tosubtract), -10)
assert_equal(np.divide.reduce(todivide), 16.0)
assert_array_equal(np.subtract.accumulate(tosubtract),
np.array([0, -1, -3, -6, -10]))
assert_array_equal(np.divide.accumulate(todivide),
np.array([2., 4., 16.]))
def test_convolve_empty(self, level=rlevel):
"""Convolve should raise an error for empty input array."""
self.assertRaises(ValueError,np.convolve,[],[1])
self.assertRaises(ValueError,np.convolve,[1],[])
def test_multidim_byteswap(self, level=rlevel):
"""Ticket #449"""
r=np.array([(1,(0,1,2))], dtype="i2,3i2")
assert_array_equal(r.byteswap(),
np.array([(256,(0,256,512))],r.dtype))
def test_string_NULL(self, level=rlevel):
"""Changeset 3557"""
assert_equal(np.array("a\x00\x0b\x0c\x00").item(),
'a\x00\x0b\x0c')
def test_junk_in_string_fields_of_recarray(self, level=rlevel):
"""Ticket #483"""
r = np.array([[asbytes('abc')]], dtype=[('var1', '|S20')])
assert asbytes(r['var1'][0][0]) == asbytes('abc')
def test_take_output(self, level=rlevel):
"""Ensure that 'take' honours output parameter."""
x = np.arange(12).reshape((3,4))
a = np.take(x,[0,2],axis=1)
b = np.zeros_like(a)
np.take(x,[0,2],axis=1,out=b)
assert_array_equal(a,b)
def test_array_str_64bit(self, level=rlevel):
"""Ticket #501"""
s = np.array([1, np.nan],dtype=np.float64)
errstate = np.seterr(all='raise')
try:
sstr = np.array_str(s)
finally:
np.seterr(**errstate)
def test_frompyfunc_endian(self, level=rlevel):
"""Ticket #503"""
from math import radians
uradians = np.frompyfunc(radians, 1, 1)
big_endian = np.array([83.4, 83.5], dtype='>f8')
little_endian = np.array([83.4, 83.5], dtype='<f8')
assert_almost_equal(uradians(big_endian).astype(float),
uradians(little_endian).astype(float))
def test_mem_string_arr(self, level=rlevel):
"""Ticket #514"""
s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
t = []
np.hstack((t, s ))
def test_arr_transpose(self, level=rlevel):
"""Ticket #516"""
x = np.random.rand(*(2,)*16)
y = x.transpose(range(16))
def test_string_mergesort(self, level=rlevel):
"""Ticket #540"""
x = np.array(['a']*32)
assert_array_equal(x.argsort(kind='m'), np.arange(32))
def test_argmax_byteorder(self, level=rlevel):
"""Ticket #546"""
a = np.arange(3, dtype='>f')
assert a[a.argmax()] == a.max()
def test_rand_seed(self, level=rlevel):
"""Ticket #555"""
for l in np.arange(4):
np.random.seed(l)
def test_mem_deallocation_leak(self, level=rlevel):
"""Ticket #562"""
a = np.zeros(5,dtype=float)
b = np.array(a,dtype=float)
del a, b
def test_mem_on_invalid_dtype(self):
"Ticket #583"
self.assertRaises(ValueError, np.fromiter, [['12',''],['13','']], str)
def test_dot_negative_stride(self, level=rlevel):
"""Ticket #588"""
x = np.array([[1,5,25,125.,625]])
y = np.array([[20.],[160.],[640.],[1280.],[1024.]])
z = y[::-1].copy()
y2 = y[::-1]
assert_equal(np.dot(x,z),np.dot(x,y2))
def test_object_casting(self, level=rlevel):
# This used to trigger the object-type version of
# the bitwise_or operation, because float64 -> object
# casting succeeds
def rs():
x = np.ones([484,286])
y = np.zeros([484,286])
x |= y
self.assertRaises(TypeError,rs)
def test_unicode_scalar(self, level=rlevel):
"""Ticket #600"""
import cPickle
x = np.array(["DROND", "DROND1"], dtype="U6")
el = x[1]
new = cPickle.loads(cPickle.dumps(el))
assert_equal(new, el)
def test_arange_non_native_dtype(self, level=rlevel):
"""Ticket #616"""
for T in ('>f4','<f4'):
dt = np.dtype(T)
assert_equal(np.arange(0,dtype=dt).dtype,dt)
assert_equal(np.arange(0.5,dtype=dt).dtype,dt)
assert_equal(np.arange(5,dtype=dt).dtype,dt)
def test_bool_indexing_invalid_nr_elements(self, level=rlevel):
s = np.ones(10,dtype=float)
x = np.array((15,),dtype=float)
def ia(x,s): x[(s>0)]=1.0
self.assertRaises(ValueError,ia,x,s)
def test_mem_scalar_indexing(self, level=rlevel):
"""Ticket #603"""
x = np.array([0],dtype=float)
index = np.array(0,dtype=np.int32)
x[index]
def test_binary_repr_0_width(self, level=rlevel):
assert_equal(np.binary_repr(0,width=3),'000')
def test_fromstring(self, level=rlevel):
assert_equal(np.fromstring("12:09:09", dtype=int, sep=":"),
[12,9,9])
def test_searchsorted_variable_length(self, level=rlevel):
x = np.array(['a','aa','b'])
y = np.array(['d','e'])
assert_equal(x.searchsorted(y), [3,3])
def test_string_argsort_with_zeros(self, level=rlevel):
"""Check argsort for strings containing zeros."""
x = np.fromstring("\x00\x02\x00\x01", dtype="|S2")
assert_array_equal(x.argsort(kind='m'), np.array([1,0]))
assert_array_equal(x.argsort(kind='q'), np.array([1,0]))
def test_string_sort_with_zeros(self, level=rlevel):
"""Check sort for strings containing zeros."""
x = np.fromstring("\x00\x02\x00\x01", dtype="|S2")
y = np.fromstring("\x00\x01\x00\x02", dtype="|S2")
assert_array_equal(np.sort(x, kind="q"), y)
def test_copy_detection_zero_dim(self, level=rlevel):
"""Ticket #658"""
np.indices((0,3,4)).T.reshape(-1,3)
def test_flat_byteorder(self, level=rlevel):
"""Ticket #657"""
x = np.arange(10)
assert_array_equal(x.astype('>i4'),x.astype('<i4').flat[:])
assert_array_equal(x.astype('>i4').flat[:],x.astype('<i4'))
def test_uint64_from_negative(self, level=rlevel) :
assert_equal(np.uint64(-2), np.uint64(18446744073709551614))
def test_sign_bit(self, level=rlevel):
x = np.array([0,-0.0,0])
assert_equal(str(np.abs(x)),'[ 0. 0. 0.]')
def test_flat_index_byteswap(self, level=rlevel):
for dt in (np.dtype('<i4'),np.dtype('>i4')):
x = np.array([-1,0,1],dtype=dt)
assert_equal(x.flat[0].dtype, x[0].dtype)
def test_copy_detection_corner_case(self, level=rlevel):
"""Ticket #658"""
np.indices((0,3,4)).T.reshape(-1,3)
def test_copy_detection_corner_case2(self, level=rlevel):
"""Ticket #771: strides are not set correctly when reshaping 0-sized
arrays"""
b = np.indices((0,3,4)).T.reshape(-1,3)
assert_equal(b.strides, (3 * b.itemsize, b.itemsize))
def test_object_array_refcounting(self, level=rlevel):
"""Ticket #633"""
if not hasattr(sys, 'getrefcount'):
return
# NB. this is probably CPython-specific
cnt = sys.getrefcount
a = object()
b = object()
c = object()
cnt0_a = cnt(a)
cnt0_b = cnt(b)
cnt0_c = cnt(c)
# -- 0d -> 1d broadcasted slice assignment
arr = np.zeros(5, dtype=np.object_)
arr[:] = a
assert_equal(cnt(a), cnt0_a + 5)
arr[:] = b
assert_equal(cnt(a), cnt0_a)
assert_equal(cnt(b), cnt0_b + 5)
arr[:2] = c
assert_equal(cnt(b), cnt0_b + 3)
assert_equal(cnt(c), cnt0_c + 2)
del arr
# -- 1d -> 2d broadcasted slice assignment
arr = np.zeros((5, 2), dtype=np.object_)
arr0 = np.zeros(2, dtype=np.object_)
arr0[0] = a
assert cnt(a) == cnt0_a + 1
arr0[1] = b
assert cnt(b) == cnt0_b + 1
arr[:,:] = arr0
assert cnt(a) == cnt0_a + 6
assert cnt(b) == cnt0_b + 6
arr[:,0] = None
assert cnt(a) == cnt0_a + 1
del arr, arr0
# -- 2d copying + flattening
arr = np.zeros((5, 2), dtype=np.object_)
arr[:,0] = a
arr[:,1] = b
assert cnt(a) == cnt0_a + 5
assert cnt(b) == cnt0_b + 5
arr2 = arr.copy()
assert cnt(a) == cnt0_a + 10
assert cnt(b) == cnt0_b + 10
arr2 = arr[:,0].copy()
assert cnt(a) == cnt0_a + 10
assert cnt(b) == cnt0_b + 5
arr2 = arr.flatten()
assert cnt(a) == cnt0_a + 10
assert cnt(b) == cnt0_b + 10
del arr, arr2
# -- concatenate, repeat, take, choose
arr1 = np.zeros((5, 1), dtype=np.object_)
arr2 = np.zeros((5, 1), dtype=np.object_)
arr1[...] = a
arr2[...] = b
assert cnt(a) == cnt0_a + 5
assert cnt(b) == cnt0_b + 5
arr3 = np.concatenate((arr1, arr2))
assert cnt(a) == cnt0_a + 5 + 5
assert cnt(b) == cnt0_b + 5 + 5
arr3 = arr1.repeat(3, axis=0)
assert cnt(a) == cnt0_a + 5 + 3*5
arr3 = arr1.take([1,2,3], axis=0)
assert cnt(a) == cnt0_a + 5 + 3
x = np.array([[0],[1],[0],[1],[1]], int)
arr3 = x.choose(arr1, arr2)
assert cnt(a) == cnt0_a + 5 + 2
assert cnt(b) == cnt0_b + 5 + 3
def test_mem_custom_float_to_array(self, level=rlevel):
"""Ticket 702"""
class MyFloat:
def __float__(self):
return 1.0
tmp = np.atleast_1d([MyFloat()])
tmp2 = tmp.astype(float)
def test_object_array_refcount_self_assign(self, level=rlevel):
"""Ticket #711"""
class VictimObject(object):
deleted = False
def __del__(self):
self.deleted = True
d = VictimObject()
arr = np.zeros(5, dtype=np.object_)
arr[:] = d
del d
arr[:] = arr # refcount of 'd' might hit zero here
assert not arr[0].deleted
arr[:] = arr # trying to induce a segfault by doing it again...
assert not arr[0].deleted
def test_mem_fromiter_invalid_dtype_string(self, level=rlevel):
x = [1,2,3]
self.assertRaises(ValueError,
np.fromiter, [xi for xi in x], dtype='S')
def test_reduce_big_object_array(self, level=rlevel):
"""Ticket #713"""
oldsize = np.setbufsize(10*16)
a = np.array([None]*161, object)
assert not np.any(a)
np.setbufsize(oldsize)
def test_mem_0d_array_index(self, level=rlevel):
"""Ticket #714"""
np.zeros(10)[np.array(0)]
def test_floats_from_string(self, level=rlevel):
"""Ticket #640, floats from string"""
fsingle = np.single('1.234')
fdouble = np.double('1.234')
flongdouble = np.longdouble('1.234')
assert_almost_equal(fsingle, 1.234)
assert_almost_equal(fdouble, 1.234)
assert_almost_equal(flongdouble, 1.234)
def test_complex_dtype_printing(self, level=rlevel):
dt = np.dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)),
('rtile', '>f4', (64, 36))], (3,)),
('bottom', [('bleft', ('>f4', (8, 64)), (1,)),
('bright', '>f4', (8, 36))])])
assert_equal(str(dt),
"[('top', [('tiles', ('>f4', (64, 64)), (1,)), "
"('rtile', '>f4', (64, 36))], (3,)), "
"('bottom', [('bleft', ('>f4', (8, 64)), (1,)), "
"('bright', '>f4', (8, 36))])]")
def test_nonnative_endian_fill(self, level=rlevel):
""" Non-native endian arrays were incorrectly filled with scalars before
r5034.
"""
if sys.byteorder == 'little':
dtype = np.dtype('>i4')
else:
dtype = np.dtype('<i4')
x = np.empty([1], dtype=dtype)
x.fill(1)
assert_equal(x, np.array([1], dtype=dtype))
def test_dot_alignment_sse2(self, level=rlevel):
"""Test for ticket #551, changeset r5140"""
x = np.zeros((30,40))
y = pickle.loads(pickle.dumps(x))
# y is now typically not aligned on a 8-byte boundary
z = np.ones((1, y.shape[0]))
# This shouldn't cause a segmentation fault:
np.dot(z, y)
def test_astype_copy(self, level=rlevel):
"""Ticket #788, changeset r5155"""
# The test data file was generated by scipy.io.savemat.
# The dtype is float64, but the isbuiltin attribute is 0.
data_dir = path.join(path.dirname(__file__), 'data')
filename = path.join(data_dir, "astype_copy.pkl")
if sys.version_info[0] >= 3:
xp = pickle.load(open(filename, 'rb'), encoding='latin1')
else:
xp = pickle.load(open(filename))
xpd = xp.astype(np.float64)
assert (xp.__array_interface__['data'][0] !=
xpd.__array_interface__['data'][0])
def test_compress_small_type(self, level=rlevel):
"""Ticket #789, changeset 5217.
"""
# compress with out argument segfaulted if cannot cast safely
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.zeros((2, 1), dtype = np.single)
try:
a.compress([True, False], axis = 1, out = b)
raise AssertionError("compress with an out which cannot be " \
"safely casted should not return "\
"successfully")
except TypeError:
pass
def test_attributes(self, level=rlevel):
"""Ticket #791
"""
class TestArray(np.ndarray):
def __new__(cls, data, info):
result = np.array(data)
result = result.view(cls)
result.info = info
return result
def __array_finalize__(self, obj):
self.info = getattr(obj, 'info', '')
dat = TestArray([[1,2,3,4],[5,6,7,8]],'jubba')
assert_(dat.info == 'jubba')
dat.resize((4,2))
assert_(dat.info == 'jubba')
dat.sort()
assert_(dat.info == 'jubba')
dat.fill(2)
assert_(dat.info == 'jubba')
dat.put([2,3,4],[6,3,4])
assert_(dat.info == 'jubba')
dat.setfield(4, np.int32,0)
assert_(dat.info == 'jubba')
dat.setflags()
assert_(dat.info == 'jubba')
assert_(dat.all(1).info == 'jubba')
assert_(dat.any(1).info == 'jubba')
assert_(dat.argmax(1).info == 'jubba')
assert_(dat.argmin(1).info == 'jubba')
assert_(dat.argsort(1).info == 'jubba')
assert_(dat.astype(TestArray).info == 'jubba')
assert_(dat.byteswap().info == 'jubba')
assert_(dat.clip(2,7).info == 'jubba')
assert_(dat.compress([0,1,1]).info == 'jubba')
assert_(dat.conj().info == 'jubba')
assert_(dat.conjugate().info == 'jubba')
assert_(dat.copy().info == 'jubba')
dat2 = TestArray([2, 3, 1, 0],'jubba')
choices = [[0, 1, 2, 3], [10, 11, 12, 13],
[20, 21, 22, 23], [30, 31, 32, 33]]
assert_(dat2.choose(choices).info == 'jubba')
assert_(dat.cumprod(1).info == 'jubba')
assert_(dat.cumsum(1).info == 'jubba')
assert_(dat.diagonal().info == 'jubba')
assert_(dat.flatten().info == 'jubba')
assert_(dat.getfield(np.int32,0).info == 'jubba')
assert_(dat.imag.info == 'jubba')
assert_(dat.max(1).info == 'jubba')
assert_(dat.mean(1).info == 'jubba')
assert_(dat.min(1).info == 'jubba')
assert_(dat.newbyteorder().info == 'jubba')
assert_(dat.nonzero()[0].info == 'jubba')
assert_(dat.nonzero()[1].info == 'jubba')
assert_(dat.prod(1).info == 'jubba')
assert_(dat.ptp(1).info == 'jubba')
assert_(dat.ravel().info == 'jubba')
assert_(dat.real.info == 'jubba')
assert_(dat.repeat(2).info == 'jubba')
assert_(dat.reshape((2,4)).info == 'jubba')
assert_(dat.round().info == 'jubba')
assert_(dat.squeeze().info == 'jubba')
assert_(dat.std(1).info == 'jubba')
assert_(dat.sum(1).info == 'jubba')
assert_(dat.swapaxes(0,1).info == 'jubba')
assert_(dat.take([2,3,5]).info == 'jubba')
assert_(dat.transpose().info == 'jubba')
assert_(dat.T.info == 'jubba')
assert_(dat.var(1).info == 'jubba')
assert_(dat.view(TestArray).info == 'jubba')
def test_recarray_tolist(self, level=rlevel):
"""Ticket #793, changeset r5215
"""
# Comparisons fail for NaN, so we can't use random memory
# for the test.
buf = np.zeros(40, dtype=np.int8)
a = np.recarray(2, formats="i4,f8,f8", names="id,x,y", buf=buf)
b = a.tolist()
assert_( a[0].tolist() == b[0])
assert_( a[1].tolist() == b[1])
def test_char_array_creation(self, level=rlevel):
a = np.array('123', dtype='c')
b = np.array(asbytes_nested(['1','2','3']))
assert_equal(a,b)
def test_unaligned_unicode_access(self, level=rlevel) :
"""Ticket #825"""
for i in range(1,9) :
msg = 'unicode offset: %d chars'%i
t = np.dtype([('a','S%d'%i),('b','U2')])
x = np.array([(asbytes('a'),u'b')], dtype=t)
if sys.version_info[0] >= 3:
assert_equal(str(x), "[(b'a', 'b')]", err_msg=msg)
else:
assert_equal(str(x), "[('a', u'b')]", err_msg=msg)
def test_sign_for_complex_nan(self, level=rlevel):
"""Ticket 794."""
C = np.array([-np.inf, -2+1j, 0, 2-1j, np.inf, np.nan])
have = np.sign(C)
want = np.array([-1+0j, -1+0j, 0+0j, 1+0j, 1+0j, np.nan])
assert_equal(have, want)
def test_for_equal_names(self, level=rlevel):
"""Ticket #674"""
dt = np.dtype([('foo', float), ('bar', float)])
a = np.zeros(10, dt)
b = list(a.dtype.names)
b[0] = "notfoo"
a.dtype.names = b
assert a.dtype.names[0] == "notfoo"
assert a.dtype.names[1] == "bar"
def test_for_object_scalar_creation(self, level=rlevel):
"""Ticket #816"""
a = np.object_()
b = np.object_(3)
b2 = np.object_(3.0)
c = np.object_([4,5])
d = np.object_([None, {}, []])
assert a is None
assert type(b) is int
assert type(b2) is float
assert type(c) is np.ndarray
assert c.dtype == object
assert d.dtype == object
def test_array_resize_method_system_error(self):
"""Ticket #840 - order should be an invalid keyword."""
x = np.array([[0,1],[2,3]])
self.assertRaises(TypeError, x.resize, (2,2), order='C')
def test_for_zero_length_in_choose(self, level=rlevel):
"Ticket #882"
a = np.array(1)
self.assertRaises(ValueError, lambda x: x.choose([]), a)
def test_array_ndmin_overflow(self):
"Ticket #947."
self.assertRaises(ValueError, lambda: np.array([1], ndmin=33))
def test_errobj_reference_leak(self, level=rlevel):
"""Ticket #955"""
old_err = np.seterr(all="ignore")
try:
z = int(0)
p = np.int32(-1)
gc.collect()
n_before = len(gc.get_objects())
z**p # this shouldn't leak a reference to errobj
gc.collect()
n_after = len(gc.get_objects())
assert n_before >= n_after, (n_before, n_after)
finally:
np.seterr(**old_err)
def test_void_scalar_with_titles(self, level=rlevel):
"""No ticket"""
data = [('john', 4), ('mary', 5)]
dtype1 = [(('source:yy', 'name'), 'O'), (('source:xx', 'id'), int)]
arr = np.array(data, dtype=dtype1)
assert arr[0][0] == 'john'
assert arr[0][1] == 4
def test_blasdot_uninitialized_memory(self):
"""Ticket #950"""
for m in [0, 1, 2]:
for n in [0, 1, 2]:
for k in xrange(3):
# Try to ensure that x->data contains non-zero floats
x = np.array([123456789e199], dtype=np.float64)
x.resize((m, 0))
y = np.array([123456789e199], dtype=np.float64)
y.resize((0, n))
# `dot` should just return zero (m,n) matrix
z = np.dot(x, y)
assert np.all(z == 0)
assert z.shape == (m, n)
def test_zeros(self):
"""Regression test for #1061."""
# Set a size which cannot fit into a 64 bits signed integer
sz = 2 ** 64
good = 'Maximum allowed dimension exceeded'
try:
np.empty(sz)
except ValueError, e:
if not str(e) == good:
self.fail("Got msg '%s', expected '%s'" % (e, good))
except Exception, e:
self.fail("Got exception of type %s instead of ValueError" % type(e))
def test_huge_arange(self):
"""Regression test for #1062."""
# Set a size which cannot fit into a 64 bits signed integer
sz = 2 ** 64
good = 'Maximum allowed size exceeded'
try:
a = np.arange(sz)
self.assertTrue(np.size == sz)
except ValueError, e:
if not str(e) == good:
self.fail("Got msg '%s', expected '%s'" % (e, good))
except Exception, e:
self.fail("Got exception of type %s instead of ValueError" % type(e))
def test_fromiter_bytes(self):
"""Ticket #1058"""
a = np.fromiter(range(10), dtype='b')
b = np.fromiter(range(10), dtype='B')
assert np.alltrue(a == np.array([0,1,2,3,4,5,6,7,8,9]))
assert np.alltrue(b == np.array([0,1,2,3,4,5,6,7,8,9]))
def test_array_from_sequence_scalar_array(self):
"""Ticket #1078: segfaults when creating an array with a sequence of 0d
arrays."""
a = np.array((np.ones(2), np.array(2)))
assert_equal(a.shape, (2,))
assert_equal(a.dtype, np.dtype(object))
assert_equal(a[0], np.ones(2))
assert_equal(a[1], np.array(2))
a = np.array(((1,), np.array(1)))
assert_equal(a.shape, (2,))
assert_equal(a.dtype, np.dtype(object))
assert_equal(a[0], (1,))
assert_equal(a[1], np.array(1))
def test_array_from_sequence_scalar_array2(self):
"""Ticket #1081: weird array with strange input..."""
t = np.array([np.array([]), np.array(0, object)])
assert_equal(t.shape, (2,))
assert_equal(t.dtype, np.dtype(object))
def test_array_too_big(self):
"""Ticket #1080."""
assert_raises(ValueError, np.zeros, [975]*7, np.int8)
assert_raises(ValueError, np.zeros, [26244]*5, np.int8)
def test_dtype_keyerrors_(self):
"""Ticket #1106."""
dt = np.dtype([('f1', np.uint)])
assert_raises(KeyError, dt.__getitem__, "f2")
assert_raises(IndexError, dt.__getitem__, 1)
assert_raises(ValueError, dt.__getitem__, 0.0)
def test_lexsort_buffer_length(self):
"""Ticket #1217, don't segfault."""
a = np.ones(100, dtype=np.int8)
b = np.ones(100, dtype=np.int32)
i = np.lexsort((a[::-1], b))
assert_equal(i, np.arange(100, dtype=np.int))
def test_object_array_to_fixed_string(self):
"""Ticket #1235."""
a = np.array(['abcdefgh', 'ijklmnop'], dtype=np.object_)
b = np.array(a, dtype=(np.str_, 8))
assert_equal(a, b)
c = np.array(a, dtype=(np.str_, 5))
assert_equal(c, np.array(['abcde', 'ijklm']))
d = np.array(a, dtype=(np.str_, 12))
assert_equal(a, d)
e = np.empty((2, ), dtype=(np.str_, 8))
e[:] = a[:]
assert_equal(a, e)
def test_unicode_to_string_cast(self):
"""Ticket #1240."""
a = np.array([[u'abc', u'\u03a3'], [u'asdf', u'erw']], dtype='U')
def fail():
b = np.array(a, 'S4')
self.assertRaises(UnicodeEncodeError, fail)
def test_mixed_string_unicode_array_creation(self):
a = np.array(['1234', u'123'])
assert a.itemsize == 16
a = np.array([u'123', '1234'])
assert a.itemsize == 16
a = np.array(['1234', u'123', '12345'])
assert a.itemsize == 20
a = np.array([u'123', '1234', u'12345'])
assert a.itemsize == 20
a = np.array([u'123', '1234', u'1234'])
assert a.itemsize == 16
def test_misaligned_objects_segfault(self):
"""Ticket #1198 and #1267"""
a1 = np.zeros((10,), dtype='O,c')
a2 = np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], 'S10')
a1['f0'] = a2
r = repr(a1)
np.argmax(a1['f0'])
a1['f0'][1] = "FOO"
a1['f0'] = "FOO"
a3 = np.array(a1['f0'], dtype='S')
np.nonzero(a1['f0'])
a1.sort()
a4 = copy.deepcopy(a1)
def test_misaligned_scalars_segfault(self):
"""Ticket #1267"""
s1 = np.array(('a', 'Foo'), dtype='c,O')
s2 = np.array(('b', 'Bar'), dtype='c,O')
s1['f1'] = s2['f1']
s1['f1'] = 'Baz'
def test_misaligned_dot_product_objects(self):
"""Ticket #1267"""
# This didn't require a fix, but it's worth testing anyway, because
# it may fail if .dot stops enforcing the arrays to be BEHAVED
a = np.array([[(1, 'a'), (0, 'a')], [(0, 'a'), (1, 'a')]], dtype='O,c')
b = np.array([[(4, 'a'), (1, 'a')], [(2, 'a'), (2, 'a')]], dtype='O,c')
np.dot(a['f0'], b['f0'])
def test_byteswap_complex_scalar(self):
"""Ticket #1259"""
z = np.array([-1j], '<c8')
x = z[0] # always native-endian
y = x.byteswap()
if x.dtype.byteorder == z.dtype.byteorder:
# little-endian machine
assert_equal(x, np.fromstring(y.tostring(), dtype='>c8'))
else:
# big-endian machine
assert_equal(x, np.fromstring(y.tostring(), dtype='<c8'))
def test_structured_arrays_with_objects1(self):
"""Ticket #1299"""
stra = 'aaaa'
strb = 'bbbb'
x = np.array([[(0,stra),(1,strb)]], 'i8,O')
x[x.nonzero()] = x.ravel()[:1]
assert x[0,1] == x[0,0]
def test_structured_arrays_with_objects2(self):
"""Ticket #1299 second test"""
stra = 'aaaa'
strb = 'bbbb'
numb = sys.getrefcount(strb)
numa = sys.getrefcount(stra)
x = np.array([[(0,stra),(1,strb)]], 'i8,O')
x[x.nonzero()] = x.ravel()[:1]
assert sys.getrefcount(strb) == numb
assert sys.getrefcount(stra) == numa + 2
def test_duplicate_title_and_name(self):
"""Ticket #1254"""
def func():
x = np.dtype([(('a', 'a'), 'i'), ('b', 'i')])
self.assertRaises(ValueError, func)
def test_signed_integer_division_overflow(self):
"""Ticket #1317."""
def test_type(t):
min = np.array([np.iinfo(t).min])
min //= -1
old_err = np.seterr(divide="ignore")
try:
for t in (np.int8, np.int16, np.int32, np.int64, np.int, np.long):
test_type(t)
finally:
np.seterr(**old_err)
def test_buffer_hashlib(self):
try:
from hashlib import md5
except ImportError:
from md5 import new as md5
x = np.array([1,2,3], dtype=np.dtype('<i4'))
assert_equal(md5(x).hexdigest(), '2a1dd1e1e59d0a384c26951e316cd7e6')
def test_numeric_handleError(self):
"""Ticket #1405"""
from numpy import numarray
# Just make sure this doesn't throw an exception
numarray.handleError(0, "")
def test_0d_string_scalar(self):
# Bug #1436; the following should succeed
np.asarray('x', '>c')
def test_log1p_compiler_shenanigans(self):
# Check if log1p is behaving on 32 bit intel systems.
assert_(np.isfinite(np.log1p(np.exp2(-53))))
def test_fromiter_comparison(self, level=rlevel):
a = np.fromiter(range(10), dtype='b')
b = np.fromiter(range(10), dtype='B')
assert np.alltrue(a == np.array([0,1,2,3,4,5,6,7,8,9]))
assert np.alltrue(b == np.array([0,1,2,3,4,5,6,7,8,9]))
def test_fromstring_crash(self):
# Ticket #1345: the following should not cause a crash
np.fromstring(asbytes('aa, aa, 1.0'), sep=',')
def test_ticket_1539(self):
dtypes = [x for x in np.typeDict.values()
if (issubclass(x, np.number)
and not issubclass(x, np.timeinteger))]
a = np.array([], dtypes[0])
failures = []
for x in dtypes:
b = a.astype(x)
for y in dtypes:
c = a.astype(y)
try:
np.dot(b, c)
except TypeError, e:
failures.append((x, y))
if failures:
raise AssertionError("Failures: %r" % failures)
def test_ticket_1538(self):
x = np.finfo(np.float32)
for name in 'eps epsneg max min resolution tiny'.split():
assert_equal(type(getattr(x, name)), np.float32,
err_msg=name)
def test_ticket_1434(self):
# Check that the out= argument in var and std has an effect
data = np.array(((1,2,3),(4,5,6),(7,8,9)))
out = np.zeros((3,))
ret = data.var(axis=1, out=out)
assert_(ret is out)
assert_array_equal(ret, data.var(axis=1))
ret = data.std(axis=1, out=out)
assert_(ret is out)
assert_array_equal(ret, data.std(axis=1))
def test_complex_nan_maximum(self):
cnan = complex(0, np.nan)
assert_equal(np.maximum(1, cnan), cnan)
def test_subclass_int_tuple_assignment(self):
# ticket #1563
class Subclass(np.ndarray):
def __new__(cls,i):
return np.ones((i,)).view(cls)
x = Subclass(5)
x[(0,)] = 2 # shouldn't raise an exception
assert_equal(x[0], 2)
def test_ufunc_no_unnecessary_views(self):
# ticket #1548
class Subclass(np.ndarray):
pass
x = np.array([1,2,3]).view(Subclass)
y = np.add(x, x, x)
assert_equal(id(x), id(y))
def test_take_refcount(self):
# ticket #939
a = np.arange(16, dtype=np.float)
a.shape = (4,4)
lut = np.ones((5 + 3, 4), np.float)
rgba = np.empty(shape=a.shape + (4,), dtype=lut.dtype)
c1 = sys.getrefcount(rgba)
try:
lut.take(a, axis=0, mode='clip', out=rgba)
except TypeError:
pass
c2 = sys.getrefcount(rgba)
assert_equal(c1, c2)
def test_fromfile_tofile_seeks(self):
# On Python 3, tofile/fromfile used to get (#1610) the Python
# file handle out of sync
f0 = tempfile.NamedTemporaryFile()
f = f0.file
f.write(np.arange(255, dtype='u1').tostring())
f.seek(20)
ret = np.fromfile(f, count=4, dtype='u1')
assert_equal(ret, np.array([20, 21, 22, 23], dtype='u1'))
assert_equal(f.tell(), 24)
f.seek(40)
np.array([1, 2, 3], dtype='u1').tofile(f)
assert_equal(f.tell(), 43)
f.seek(40)
data = f.read(3)
assert_equal(data, asbytes("\x01\x02\x03"))
f.seek(80)
f.read(4)
data = np.fromfile(f, dtype='u1', count=4)
assert_equal(data, np.array([84, 85, 86, 87], dtype='u1'))
f.close()
def test_complex_scalar_warning(self):
for tp in [np.csingle, np.cdouble, np.clongdouble]:
x = tp(1+2j)
assert_warns(np.ComplexWarning, float, x)
ctx = WarningManager()
ctx.__enter__()
warnings.simplefilter('ignore')
assert_equal(float(x), float(x.real))
ctx.__exit__()
def test_complex_scalar_complex_cast(self):
for tp in [np.csingle, np.cdouble, np.clongdouble]:
x = tp(1+2j)
assert_equal(complex(x), 1+2j)
def test_uint_int_conversion(self):
x = 2**64 - 1
assert_equal(int(np.uint64(x)), x)
def test_duplicate_field_names_assign(self):
ra = np.fromiter(((i*3, i*2) for i in xrange(10)), dtype='i8,f8')
ra.dtype.names = ('f1', 'f2')
rep = repr(ra) # should not cause a segmentation fault
assert_raises(ValueError, setattr, ra.dtype, 'names', ('f1', 'f1'))
def test_eq_string_and_object_array(self):
# From e-mail thread "__eq__ with str and object" (Keith Goodman)
a1 = np.array(['a', 'b'], dtype=object)
a2 = np.array(['a', 'c'])
assert_array_equal(a1 == a2, [True, False])
assert_array_equal(a2 == a1, [True, False])
def test_nonzero_byteswap(self):
a = np.array([0x80000000, 0x00000080, 0], dtype=np.uint32)
a.dtype = np.float32
assert_equal(a.nonzero()[0], [1])
a = a.byteswap().newbyteorder()
assert_equal(a.nonzero()[0], [1]) # [0] if nonzero() ignores swap
def test_find_common_type_boolean(self):
# Ticket #1695
assert_(np.find_common_type([],['?','?']) == '?')
def test_empty_mul(self):
a = np.array([1.])
a[1:1] *= 2
assert_equal(a, [1.])
def test_array_side_effect(self):
assert_equal(np.dtype('S10').itemsize, 10)
A = np.array([['abc', 2], ['long ', '0123456789']], dtype=np.string_)
# This was throwing an exception because in ctors.c,
# discover_itemsize was calling PyObject_Length without checking
# the return code. This failed to get the length of the number 2,
# and the exception hung around until something checked
# PyErr_Occurred() and returned an error.
assert_equal(np.dtype('S10').itemsize, 10)
def test_any_float(self):
# all and any for floats
a = np.array([0.1, 0.9])
assert_(np.any(a))
assert_(np.all(a))
def test_large_float_sum(self):
a = np.arange(10000, dtype='f')
assert_equal(a.sum(dtype='d'), a.astype('d').sum())
def test_ufunc_casting_out(self):
a = np.array(1.0, dtype=np.float32)
b = np.array(1.0, dtype=np.float64)
c = np.array(1.0, dtype=np.float32)
np.add(a, b, out=c)
assert_equal(c, 2.0)
def test_array_scalar_contiguous(self):
# Array scalars are both C and Fortran contiguous
assert_(np.array(1.0).flags.c_contiguous)
assert_(np.array(1.0).flags.f_contiguous)
assert_(np.array(np.float32(1.0)).flags.c_contiguous)
assert_(np.array(np.float32(1.0)).flags.f_contiguous)
def test_object_array_self_reference(self):
# Object arrays with references to themselves can cause problems
a = np.array(0, dtype=object)
a[()] = a
assert_raises(TypeError, int, a)
assert_raises(TypeError, long, a)
assert_raises(TypeError, float, a)
assert_raises(TypeError, oct, a)
assert_raises(TypeError, hex, a)
# This was causing a to become like the above
a = np.array(0, dtype=object)
a[...] += 1
assert_equal(a, 1)
def test_zerosize_accumulate(self):
"Ticket #1733"
x = np.array([[42, 0]], dtype=np.uint32)
assert_equal(np.add.accumulate(x[:-1,0]), [])
def test_objectarray_setfield(self):
# Setfield directly manipulates the raw array data,
# so is invalid for object arrays.
x = np.array([1,2,3], dtype=object)
assert_raises(RuntimeError, x.setfield, 4, np.int32, 0)
def test_setting_rank0_string(self):
"Ticket #1736"
s1 = asbytes("hello1")
s2 = asbytes("hello2")
a = np.zeros((), dtype="S10")
a[()] = s1
assert_equal(a, np.array(s1))
a[()] = np.array(s2)
assert_equal(a, np.array(s2))
a = np.zeros((), dtype='f4')
a[()] = 3
assert_equal(a, np.array(3))
a[()] = np.array(4)
assert_equal(a, np.array(4))
@dec.knownfailureif(sys.version_info[0] >= 3,
"a.dtype is U5 for Py 3.x. Knownfail for 1.6.x")
def test_string_astype(self):
"Ticket #1748"
s1 = asbytes('black')
s2 = asbytes('white')
s3 = asbytes('other')
a = np.array([[s1],[s2],[s3]])
assert_equal(a.dtype, np.dtype('S5'))
b = a.astype('str')
assert_equal(b.dtype, np.dtype('S5'))
def test_ticket_1756(self):
"""Ticket #1756 """
s = asbytes('0123456789abcdef')
a = np.array([s]*5)
for i in range(1,17):
a1 = np.array(a, "|S%d"%i)
a2 = np.array([s[:i]]*5)
assert_equal(a1, a2)
def test_fields_strides(self):
"Ticket #1760"
r=np.fromstring('abcdefghijklmnop'*4*3, dtype='i4,(2,3)u2')
assert_equal(r[0:3:2]['f1'], r['f1'][0:3:2])
assert_equal(r[0:3:2]['f1'][0], r[0:3:2][0]['f1'])
assert_equal(r[0:3:2]['f1'][0][()], r[0:3:2][0]['f1'][()])
assert_equal(r[0:3:2]['f1'][0].strides, r[0:3:2][0]['f1'].strides)
def test_ticket_1770(self):
"Should not segfault on python 3k"
import numpy as np
try:
a = np.zeros((1,), dtype=[('f1', 'f')])
a['f1'] = 1
a['f2'] = 1
except ValueError:
pass
except:
raise AssertionError
if __name__ == "__main__":
run_module_suite()
|
unknown
|
codeparrot/codeparrot-clean
| ||
---
- hosts: localhost
connection: local
gather_facts: no
tasks:
- add_host:
name: host1
ansible_connection: local
ansible_host: 127.0.0.1
- hosts: all
gather_facts: no
tasks:
- debug:
msg: "{{ hostvars['host1']['x'] }}"
register: x_1
- debug:
msg: "{{ hostvars['host1']['y'] }}"
register: y_1
- debug:
msg: "{{ hostvars_['x'] }}"
vars:
hostvars_: "{{ hostvars['host1'] }}"
register: x_2
- debug:
msg: "{{ hostvars_['y'] }}"
vars:
hostvars_: "{{ hostvars['host1'] }}"
register: y_2
- assert:
that:
- x_1 == x_2
- y_1 == y_2
- x_1 == y_1
- debug:
msg: "{{ hostvars['host1']['nested_x']['value'] }}"
register: x_1
- debug:
msg: "{{ hostvars['host1']['nested_y']['value'] }}"
register: y_1
- debug:
msg: "{{ hostvars_['nested_x']['value'] }}"
vars:
hostvars_: "{{ hostvars['host1'] }}"
register: x_2
- debug:
msg: "{{ hostvars_['nested_y']['value'] }}"
vars:
hostvars_: "{{ hostvars['host1'] }}"
register: y_2
- assert:
that:
- x_1 == x_2
- y_1 == y_2
- x_1 == y_1
|
unknown
|
github
|
https://github.com/ansible/ansible
|
test/integration/targets/var_templating/task_vars_templating.yml
|
from __future__ import unicode_literals
import re
from django.core.exceptions import FieldDoesNotExist
from django.db.models.constants import LOOKUP_SEP
from django.db.models.expressions import Col, Expression
from django.db.models.lookups import Lookup
from django.utils import six
gis_lookups = {}
class GISLookup(Lookup):
sql_template = None
transform_func = None
distance = False
def __init__(self, *args, **kwargs):
super(GISLookup, self).__init__(*args, **kwargs)
self.template_params = {}
@classmethod
def _check_geo_field(cls, opts, lookup):
"""
Utility for checking the given lookup with the given model options.
The lookup is a string either specifying the geographic field, e.g.
'point, 'the_geom', or a related lookup on a geographic field like
'address__point'.
If a GeometryField exists according to the given lookup on the model
options, it will be returned. Otherwise returns None.
"""
from django.contrib.gis.db.models.fields import GeometryField
# This takes into account the situation where the lookup is a
# lookup to a related geographic field, e.g., 'address__point'.
field_list = lookup.split(LOOKUP_SEP)
# Reversing so list operates like a queue of related lookups,
# and popping the top lookup.
field_list.reverse()
fld_name = field_list.pop()
try:
geo_fld = opts.get_field(fld_name)
# If the field list is still around, then it means that the
# lookup was for a geometry field across a relationship --
# thus we keep on getting the related model options and the
# model field associated with the next field in the list
# until there's no more left.
while len(field_list):
opts = geo_fld.remote_field.model._meta
geo_fld = opts.get_field(field_list.pop())
except (FieldDoesNotExist, AttributeError):
return False
# Finally, make sure we got a Geographic field and return.
if isinstance(geo_fld, GeometryField):
return geo_fld
else:
return False
def get_db_prep_lookup(self, value, connection):
# get_db_prep_lookup is called by process_rhs from super class
if isinstance(value, (tuple, list)):
# First param is assumed to be the geometric object
params = [connection.ops.Adapter(value[0])] + list(value)[1:]
else:
params = [connection.ops.Adapter(value)]
return ('%s', params)
def process_rhs(self, compiler, connection):
rhs, rhs_params = super(GISLookup, self).process_rhs(compiler, connection)
if hasattr(self.rhs, '_as_sql'):
# If rhs is some QuerySet, don't touch it
return rhs, rhs_params
geom = self.rhs
if isinstance(self.rhs, Col):
# Make sure the F Expression destination field exists, and
# set an `srid` attribute with the same as that of the
# destination.
geo_fld = self.rhs.output_field
if not hasattr(geo_fld, 'srid'):
raise ValueError('No geographic field found in expression.')
self.rhs.srid = geo_fld.srid
elif isinstance(self.rhs, Expression):
raise ValueError('Complex expressions not supported for GeometryField')
elif isinstance(self.rhs, (list, tuple)):
geom = self.rhs[0]
rhs = connection.ops.get_geom_placeholder(self.lhs.output_field, geom, compiler)
return rhs, rhs_params
def get_rhs_op(self, connection, rhs):
# Unlike BuiltinLookup, the GIS get_rhs_op() implementation should return
# an object (SpatialOperator) with an as_sql() method to allow for more
# complex computations (where the lhs part can be mixed in).
return connection.ops.gis_operators[self.lookup_name]
def as_sql(self, compiler, connection):
lhs_sql, sql_params = self.process_lhs(compiler, connection)
rhs_sql, rhs_params = self.process_rhs(compiler, connection)
sql_params.extend(rhs_params)
template_params = {'lhs': lhs_sql, 'rhs': rhs_sql, 'value': '%s'}
template_params.update(self.template_params)
rhs_op = self.get_rhs_op(connection, rhs_sql)
return rhs_op.as_sql(connection, self, template_params, sql_params)
# ------------------
# Geometry operators
# ------------------
class OverlapsLeftLookup(GISLookup):
"""
The overlaps_left operator returns true if A's bounding box overlaps or is to the
left of B's bounding box.
"""
lookup_name = 'overlaps_left'
gis_lookups['overlaps_left'] = OverlapsLeftLookup
class OverlapsRightLookup(GISLookup):
"""
The 'overlaps_right' operator returns true if A's bounding box overlaps or is to the
right of B's bounding box.
"""
lookup_name = 'overlaps_right'
gis_lookups['overlaps_right'] = OverlapsRightLookup
class OverlapsBelowLookup(GISLookup):
"""
The 'overlaps_below' operator returns true if A's bounding box overlaps or is below
B's bounding box.
"""
lookup_name = 'overlaps_below'
gis_lookups['overlaps_below'] = OverlapsBelowLookup
class OverlapsAboveLookup(GISLookup):
"""
The 'overlaps_above' operator returns true if A's bounding box overlaps or is above
B's bounding box.
"""
lookup_name = 'overlaps_above'
gis_lookups['overlaps_above'] = OverlapsAboveLookup
class LeftLookup(GISLookup):
"""
The 'left' operator returns true if A's bounding box is strictly to the left
of B's bounding box.
"""
lookup_name = 'left'
gis_lookups['left'] = LeftLookup
class RightLookup(GISLookup):
"""
The 'right' operator returns true if A's bounding box is strictly to the right
of B's bounding box.
"""
lookup_name = 'right'
gis_lookups['right'] = RightLookup
class StrictlyBelowLookup(GISLookup):
"""
The 'strictly_below' operator returns true if A's bounding box is strictly below B's
bounding box.
"""
lookup_name = 'strictly_below'
gis_lookups['strictly_below'] = StrictlyBelowLookup
class StrictlyAboveLookup(GISLookup):
"""
The 'strictly_above' operator returns true if A's bounding box is strictly above B's
bounding box.
"""
lookup_name = 'strictly_above'
gis_lookups['strictly_above'] = StrictlyAboveLookup
class SameAsLookup(GISLookup):
"""
The "~=" operator is the "same as" operator. It tests actual geometric
equality of two features. So if A and B are the same feature,
vertex-by-vertex, the operator returns true.
"""
lookup_name = 'same_as'
gis_lookups['same_as'] = SameAsLookup
class ExactLookup(SameAsLookup):
# Alias of same_as
lookup_name = 'exact'
gis_lookups['exact'] = ExactLookup
class BBContainsLookup(GISLookup):
"""
The 'bbcontains' operator returns true if A's bounding box completely contains
by B's bounding box.
"""
lookup_name = 'bbcontains'
gis_lookups['bbcontains'] = BBContainsLookup
class BBOverlapsLookup(GISLookup):
"""
The 'bboverlaps' operator returns true if A's bounding box overlaps B's bounding box.
"""
lookup_name = 'bboverlaps'
gis_lookups['bboverlaps'] = BBOverlapsLookup
class ContainedLookup(GISLookup):
"""
The 'contained' operator returns true if A's bounding box is completely contained
by B's bounding box.
"""
lookup_name = 'contained'
gis_lookups['contained'] = ContainedLookup
# ------------------
# Geometry functions
# ------------------
class ContainsLookup(GISLookup):
lookup_name = 'contains'
gis_lookups['contains'] = ContainsLookup
class ContainsProperlyLookup(GISLookup):
lookup_name = 'contains_properly'
gis_lookups['contains_properly'] = ContainsProperlyLookup
class CoveredByLookup(GISLookup):
lookup_name = 'coveredby'
gis_lookups['coveredby'] = CoveredByLookup
class CoversLookup(GISLookup):
lookup_name = 'covers'
gis_lookups['covers'] = CoversLookup
class CrossesLookup(GISLookup):
lookup_name = 'crosses'
gis_lookups['crosses'] = CrossesLookup
class DisjointLookup(GISLookup):
lookup_name = 'disjoint'
gis_lookups['disjoint'] = DisjointLookup
class EqualsLookup(GISLookup):
lookup_name = 'equals'
gis_lookups['equals'] = EqualsLookup
class IntersectsLookup(GISLookup):
lookup_name = 'intersects'
gis_lookups['intersects'] = IntersectsLookup
class OverlapsLookup(GISLookup):
lookup_name = 'overlaps'
gis_lookups['overlaps'] = OverlapsLookup
class RelateLookup(GISLookup):
lookup_name = 'relate'
sql_template = '%(func)s(%(lhs)s, %(rhs)s, %%s)'
pattern_regex = re.compile(r'^[012TF\*]{9}$')
def get_db_prep_lookup(self, value, connection):
if len(value) != 2:
raise ValueError('relate must be passed a two-tuple')
# Check the pattern argument
backend_op = connection.ops.gis_operators[self.lookup_name]
if hasattr(backend_op, 'check_relate_argument'):
backend_op.check_relate_argument(value[1])
else:
pattern = value[1]
if not isinstance(pattern, six.string_types) or not self.pattern_regex.match(pattern):
raise ValueError('Invalid intersection matrix pattern "%s".' % pattern)
return super(RelateLookup, self).get_db_prep_lookup(value, connection)
gis_lookups['relate'] = RelateLookup
class TouchesLookup(GISLookup):
lookup_name = 'touches'
gis_lookups['touches'] = TouchesLookup
class WithinLookup(GISLookup):
lookup_name = 'within'
gis_lookups['within'] = WithinLookup
class DistanceLookupBase(GISLookup):
distance = True
sql_template = '%(func)s(%(lhs)s, %(rhs)s) %(op)s %(value)s'
def process_rhs(self, compiler, connection):
if not isinstance(self.rhs, (tuple, list)) or not 2 <= len(self.rhs) <= 3:
raise ValueError("2 or 3-element tuple required for '%s' lookup." % self.lookup_name)
params = [connection.ops.Adapter(self.rhs[0])]
# Getting the distance parameter in the units of the field.
dist_param = self.rhs[1]
if hasattr(dist_param, 'resolve_expression'):
dist_param = dist_param.resolve_expression(compiler.query)
sql, expr_params = compiler.compile(dist_param)
self.template_params['value'] = sql
params.extend(expr_params)
else:
params += connection.ops.get_distance(
self.lhs.output_field, (dist_param,) + self.rhs[2:],
self.lookup_name, handle_spheroid=False
)
rhs = connection.ops.get_geom_placeholder(self.lhs.output_field, params[0], compiler)
return (rhs, params)
class DWithinLookup(DistanceLookupBase):
lookup_name = 'dwithin'
sql_template = '%(func)s(%(lhs)s, %(rhs)s, %%s)'
gis_lookups['dwithin'] = DWithinLookup
class DistanceGTLookup(DistanceLookupBase):
lookup_name = 'distance_gt'
gis_lookups['distance_gt'] = DistanceGTLookup
class DistanceGTELookup(DistanceLookupBase):
lookup_name = 'distance_gte'
gis_lookups['distance_gte'] = DistanceGTELookup
class DistanceLTLookup(DistanceLookupBase):
lookup_name = 'distance_lt'
gis_lookups['distance_lt'] = DistanceLTLookup
class DistanceLTELookup(DistanceLookupBase):
lookup_name = 'distance_lte'
gis_lookups['distance_lte'] = DistanceLTELookup
|
unknown
|
codeparrot/codeparrot-clean
| ||
/*
* 'OpenSSL for Ruby' project
* Copyright (C) 2001-2002 Michal Rokos <m.rokos@sh.cvut.cz>
* All rights reserved.
*/
/*
* This program is licensed under the same licence as Ruby.
* (See the file 'COPYING'.)
*/
#include "ossl.h"
#define NewSPKI(klass) \
TypedData_Wrap_Struct((klass), &ossl_netscape_spki_type, 0)
#define SetSPKI(obj, spki) do { \
if (!(spki)) { \
ossl_raise(rb_eRuntimeError, "SPKI wasn't initialized!"); \
} \
RTYPEDDATA_DATA(obj) = (spki); \
} while (0)
#define GetSPKI(obj, spki) do { \
TypedData_Get_Struct((obj), NETSCAPE_SPKI, &ossl_netscape_spki_type, (spki)); \
if (!(spki)) { \
ossl_raise(rb_eRuntimeError, "SPKI wasn't initialized!"); \
} \
} while (0)
/*
* Classes
*/
static VALUE mNetscape;
static VALUE cSPKI;
static VALUE eSPKIError;
/*
* Public functions
*/
/*
* Private functions
*/
static void
ossl_netscape_spki_free(void *spki)
{
NETSCAPE_SPKI_free(spki);
}
static const rb_data_type_t ossl_netscape_spki_type = {
"OpenSSL/NETSCAPE_SPKI",
{
0, ossl_netscape_spki_free,
},
0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED,
};
static VALUE
ossl_spki_alloc(VALUE klass)
{
NETSCAPE_SPKI *spki;
VALUE obj;
obj = NewSPKI(klass);
if (!(spki = NETSCAPE_SPKI_new())) {
ossl_raise(eSPKIError, NULL);
}
SetSPKI(obj, spki);
return obj;
}
/*
* call-seq:
* SPKI.new([request]) => spki
*
* === Parameters
* * _request_ - optional raw request, either in PEM or DER format.
*/
static VALUE
ossl_spki_initialize(int argc, VALUE *argv, VALUE self)
{
NETSCAPE_SPKI *spki;
VALUE buffer;
const unsigned char *p;
if (rb_scan_args(argc, argv, "01", &buffer) == 0) {
return self;
}
StringValue(buffer);
if (!(spki = NETSCAPE_SPKI_b64_decode(RSTRING_PTR(buffer), RSTRING_LENINT(buffer)))) {
ossl_clear_error();
p = (unsigned char *)RSTRING_PTR(buffer);
if (!(spki = d2i_NETSCAPE_SPKI(NULL, &p, RSTRING_LEN(buffer)))) {
ossl_raise(eSPKIError, NULL);
}
}
NETSCAPE_SPKI_free(DATA_PTR(self));
SetSPKI(self, spki);
return self;
}
/*
* call-seq:
* spki.to_der => DER-encoded string
*
* Returns the DER encoding of this SPKI.
*/
static VALUE
ossl_spki_to_der(VALUE self)
{
NETSCAPE_SPKI *spki;
VALUE str;
long len;
unsigned char *p;
GetSPKI(self, spki);
if ((len = i2d_NETSCAPE_SPKI(spki, NULL)) <= 0)
ossl_raise(eSPKIError, "i2d_NETSCAPE_SPKI");
str = rb_str_new(0, len);
p = (unsigned char *)RSTRING_PTR(str);
if (i2d_NETSCAPE_SPKI(spki, &p) <= 0)
ossl_raise(eSPKIError, "i2d_NETSCAPE_SPKI");
ossl_str_adjust(str, p);
return str;
}
/*
* call-seq:
* spki.to_pem => PEM-encoded string
*
* Returns the PEM encoding of this SPKI.
*/
static VALUE
ossl_spki_to_pem(VALUE self)
{
NETSCAPE_SPKI *spki;
char *data;
VALUE str;
GetSPKI(self, spki);
if (!(data = NETSCAPE_SPKI_b64_encode(spki))) {
ossl_raise(eSPKIError, NULL);
}
str = ossl_buf2str(data, rb_long2int(strlen(data)));
return str;
}
/*
* call-seq:
* spki.to_text => string
*
* Returns a textual representation of this SPKI, useful for debugging
* purposes.
*/
static VALUE
ossl_spki_print(VALUE self)
{
NETSCAPE_SPKI *spki;
BIO *out;
GetSPKI(self, spki);
if (!(out = BIO_new(BIO_s_mem()))) {
ossl_raise(eSPKIError, NULL);
}
if (!NETSCAPE_SPKI_print(out, spki)) {
BIO_free(out);
ossl_raise(eSPKIError, NULL);
}
return ossl_membio2str(out);
}
/*
* call-seq:
* spki.public_key => pkey
*
* Returns the public key associated with the SPKI, an instance of
* OpenSSL::PKey.
*/
static VALUE
ossl_spki_get_public_key(VALUE self)
{
NETSCAPE_SPKI *spki;
EVP_PKEY *pkey;
GetSPKI(self, spki);
if (!(pkey = NETSCAPE_SPKI_get_pubkey(spki))) { /* adds an reference */
ossl_raise(eSPKIError, NULL);
}
return ossl_pkey_wrap(pkey);
}
/*
* call-seq:
* spki.public_key = pub => pkey
*
* === Parameters
* * _pub_ - the public key to be set for this instance
*
* Sets the public key to be associated with the SPKI, an instance of
* OpenSSL::PKey. This should be the public key corresponding to the
* private key used for signing the SPKI.
*/
static VALUE
ossl_spki_set_public_key(VALUE self, VALUE key)
{
NETSCAPE_SPKI *spki;
EVP_PKEY *pkey;
GetSPKI(self, spki);
pkey = GetPKeyPtr(key);
ossl_pkey_check_public_key(pkey);
if (!NETSCAPE_SPKI_set_pubkey(spki, pkey))
ossl_raise(eSPKIError, "NETSCAPE_SPKI_set_pubkey");
return key;
}
/*
* call-seq:
* spki.challenge => string
*
* Returns the challenge string associated with this SPKI.
*/
static VALUE
ossl_spki_get_challenge(VALUE self)
{
NETSCAPE_SPKI *spki;
GetSPKI(self, spki);
if (ASN1_STRING_length(spki->spkac->challenge) <= 0) {
OSSL_Debug("Challenge.length <= 0?");
return rb_str_new(0, 0);
}
return asn1str_to_str(spki->spkac->challenge);
}
/*
* call-seq:
* spki.challenge = str => string
*
* === Parameters
* * _str_ - the challenge string to be set for this instance
*
* Sets the challenge to be associated with the SPKI. May be used by the
* server, e.g. to prevent replay.
*/
static VALUE
ossl_spki_set_challenge(VALUE self, VALUE str)
{
NETSCAPE_SPKI *spki;
StringValue(str);
GetSPKI(self, spki);
if (!ASN1_STRING_set(spki->spkac->challenge, RSTRING_PTR(str),
RSTRING_LENINT(str))) {
ossl_raise(eSPKIError, NULL);
}
return str;
}
/*
* call-seq:
* spki.sign(key, digest) => spki
*
* === Parameters
* * _key_ - the private key to be used for signing this instance
* * _digest_ - the digest to be used for signing this instance
*
* To sign an SPKI, the private key corresponding to the public key set
* for this instance should be used, in addition to a digest algorithm in
* the form of an OpenSSL::Digest. The private key should be an instance of
* OpenSSL::PKey.
*/
static VALUE
ossl_spki_sign(VALUE self, VALUE key, VALUE digest)
{
NETSCAPE_SPKI *spki;
EVP_PKEY *pkey;
const EVP_MD *md;
VALUE md_holder;
pkey = GetPrivPKeyPtr(key); /* NO NEED TO DUP */
md = ossl_evp_md_fetch(digest, &md_holder);
GetSPKI(self, spki);
if (!NETSCAPE_SPKI_sign(spki, pkey, md))
ossl_raise(eSPKIError, "NETSCAPE_SPKI_sign");
return self;
}
/*
* call-seq:
* spki.verify(key) => boolean
*
* === Parameters
* * _key_ - the public key to be used for verifying the SPKI signature
*
* Returns +true+ if the signature is valid, +false+ otherwise. To verify an
* SPKI, the public key contained within the SPKI should be used.
*/
static VALUE
ossl_spki_verify(VALUE self, VALUE key)
{
NETSCAPE_SPKI *spki;
EVP_PKEY *pkey;
GetSPKI(self, spki);
pkey = GetPKeyPtr(key);
ossl_pkey_check_public_key(pkey);
switch (NETSCAPE_SPKI_verify(spki, pkey)) {
case 0:
ossl_clear_error();
return Qfalse;
case 1:
return Qtrue;
default:
ossl_raise(eSPKIError, "NETSCAPE_SPKI_verify");
}
}
/* Document-class: OpenSSL::Netscape::SPKI
*
* A Simple Public Key Infrastructure implementation (pronounced "spooky").
* The structure is defined as
* PublicKeyAndChallenge ::= SEQUENCE {
* spki SubjectPublicKeyInfo,
* challenge IA5STRING
* }
*
* SignedPublicKeyAndChallenge ::= SEQUENCE {
* publicKeyAndChallenge PublicKeyAndChallenge,
* signatureAlgorithm AlgorithmIdentifier,
* signature BIT STRING
* }
* where the definitions of SubjectPublicKeyInfo and AlgorithmIdentifier can
* be found in RFC5280. SPKI is typically used in browsers for generating
* a public/private key pair and a subsequent certificate request, using
* the HTML <keygen> element.
*
* == Examples
*
* === Creating an SPKI
* key = OpenSSL::PKey::RSA.new 2048
* spki = OpenSSL::Netscape::SPKI.new
* spki.challenge = "RandomChallenge"
* spki.public_key = key.public_key
* spki.sign(key, OpenSSL::Digest.new('SHA256'))
* #send a request containing this to a server generating a certificate
* === Verifying an SPKI request
* request = #...
* spki = OpenSSL::Netscape::SPKI.new request
* unless spki.verify(spki.public_key)
* # signature is invalid
* end
* #proceed
*/
/* Document-module: OpenSSL::Netscape
*
* OpenSSL::Netscape is a namespace for SPKI (Simple Public Key
* Infrastructure) which implements Signed Public Key and Challenge.
* See {RFC 2692}[https://www.rfc-editor.org/rfc/rfc2692] and {RFC
* 2693}[https://www.rfc-editor.org/rfc/rfc2692] for details.
*/
/* Document-class: OpenSSL::Netscape::SPKIError
*
* Generic Exception class that is raised if an error occurs during an
* operation on an instance of OpenSSL::Netscape::SPKI.
*/
void
Init_ossl_ns_spki(void)
{
mNetscape = rb_define_module_under(mOSSL, "Netscape");
eSPKIError = rb_define_class_under(mNetscape, "SPKIError", eOSSLError);
cSPKI = rb_define_class_under(mNetscape, "SPKI", rb_cObject);
rb_define_alloc_func(cSPKI, ossl_spki_alloc);
rb_define_method(cSPKI, "initialize", ossl_spki_initialize, -1);
rb_define_method(cSPKI, "to_der", ossl_spki_to_der, 0);
rb_define_method(cSPKI, "to_pem", ossl_spki_to_pem, 0);
rb_define_alias(cSPKI, "to_s", "to_pem");
rb_define_method(cSPKI, "to_text", ossl_spki_print, 0);
rb_define_method(cSPKI, "public_key", ossl_spki_get_public_key, 0);
rb_define_method(cSPKI, "public_key=", ossl_spki_set_public_key, 1);
rb_define_method(cSPKI, "sign", ossl_spki_sign, 2);
rb_define_method(cSPKI, "verify", ossl_spki_verify, 1);
rb_define_method(cSPKI, "challenge", ossl_spki_get_challenge, 0);
rb_define_method(cSPKI, "challenge=", ossl_spki_set_challenge, 1);
}
|
c
|
github
|
https://github.com/ruby/ruby
|
ext/openssl/ossl_ns_spki.c
|
<?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Downloader;
use Composer\Downloader\GitDownloader;
use Composer\Config;
use Composer\Pcre\Preg;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
use Composer\Util\Platform;
class GitDownloaderTest extends TestCase
{
/** @var Filesystem */
private $fs;
/** @var string */
private $workingDir;
protected function setUp(): void
{
$this->skipIfNotExecutable('git');
$this->initGitVersion('1.0.0');
$this->fs = new Filesystem;
$this->workingDir = self::getUniqueTmpDirectory();
}
protected function tearDown(): void
{
parent::tearDown();
if (is_dir($this->workingDir)) {
$this->fs->removeDirectory($this->workingDir);
}
$this->initGitVersion(false);
}
/**
* @param string|bool $version
*/
private function initGitVersion($version): void
{
// reset the static version cache
$refl = new \ReflectionProperty('Composer\Util\Git', 'version');
(\PHP_VERSION_ID < 80100) and $refl->setAccessible(true);
$refl->setValue(null, $version);
}
/**
* @param ?Config $config
*/
protected function setupConfig($config = null): Config
{
if (!$config) {
$config = new Config();
}
if (!$config->has('home')) {
$tmpDir = realpath(sys_get_temp_dir()).DIRECTORY_SEPARATOR.'cmptest-'.bin2hex(random_bytes(5));
$config->merge(['config' => ['home' => $tmpDir]]);
}
return $config;
}
protected function getDownloaderMock(?\Composer\IO\IOInterface $io = null, ?Config $config = null, ?\Composer\Test\Mock\ProcessExecutorMock $executor = null, ?Filesystem $filesystem = null): GitDownloader
{
$io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$executor = $executor ?: $this->getProcessExecutorMock();
$filesystem = $filesystem ?: $this->getMockBuilder('Composer\Util\Filesystem')->getMock();
$config = $this->setupConfig($config);
return new GitDownloader($io, $config, $executor, $filesystem);
}
public function testDownloadForPackageWithoutSourceReference(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->once())
->method('getSourceReference')
->will($this->returnValue(null));
self::expectException('InvalidArgumentException');
$downloader = $this->getDownloaderMock();
$downloader->download($packageMock, '/path');
$downloader->prepare('install', $packageMock, '/path');
$downloader->install($packageMock, '/path');
$downloader->cleanup('install', $packageMock, '/path');
}
public function testDownload(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('1234567890123456789012345678901234567890'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://example.com/composer/composer']));
$packageMock->expects($this->any())
->method('getSourceUrl')
->will($this->returnValue('https://example.com/composer/composer'));
$packageMock->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('dev-master'));
$process = $this->getProcessExecutorMock();
$expectedPath = Platform::isWindows() ? Platform::getCwd().'/composerPath' : 'composerPath';
$process->expects([
['git', 'clone', '--no-checkout', '--', 'https://example.com/composer/composer', $expectedPath],
['git', 'remote', 'add', 'composer', '--', 'https://example.com/composer/composer'],
['git', 'fetch', 'composer'],
['git', 'remote', 'set-url', 'origin', '--', 'https://example.com/composer/composer'],
['git', 'remote', 'set-url', 'composer', '--', 'https://example.com/composer/composer'],
['git', 'branch', '-r'],
['git', 'checkout', 'master', '--'],
['git', 'reset', '--hard', '1234567890123456789012345678901234567890', '--'],
], true);
$downloader = $this->getDownloaderMock(null, null, $process);
$downloader->download($packageMock, 'composerPath');
$downloader->prepare('install', $packageMock, 'composerPath');
$downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath');
}
public function testDownloadWithCache(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('1234567890123456789012345678901234567890'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://example.com/composer/composer']));
$packageMock->expects($this->any())
->method('getSourceUrl')
->will($this->returnValue('https://example.com/composer/composer'));
$packageMock->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('dev-master'));
$this->initGitVersion('2.17.0');
$config = new Config;
$this->setupConfig($config);
$cachePath = $config->get('cache-vcs-dir').'/'.Preg::replace('{[^a-z0-9.]}i', '-', 'https://example.com/composer/composer').'/';
$filesystem = new Filesystem;
$filesystem->removeDirectory($cachePath);
$expectedPath = Platform::isWindows() ? Platform::getCwd().'/composerPath' : 'composerPath';
$process = $this->getProcessExecutorMock();
$process->expects([
[
'cmd' => ['git', 'clone', '--mirror', '--', 'https://example.com/composer/composer', $cachePath],
'callback' => static function () use ($cachePath): void {
@mkdir($cachePath, 0777, true);
},
],
['cmd' => ['git', 'rev-parse', '--git-dir'], 'stdout' => '.'],
['git', 'rev-parse', '--quiet', '--verify', '1234567890123456789012345678901234567890^{commit}'],
['git', 'clone', '--no-checkout', $cachePath, $expectedPath, '--dissociate', '--reference', $cachePath],
['git', 'remote', 'set-url', 'origin', '--', 'https://example.com/composer/composer'],
['git', 'remote', 'add', 'composer', '--', 'https://example.com/composer/composer'],
['git', 'branch', '-r'],
['cmd' => ['git', 'checkout', 'master', '--'], 'return' => 1],
['git', 'checkout', '-B', 'master', 'composer/master', '--'],
['git', 'reset', '--hard', '1234567890123456789012345678901234567890', '--'],
], true);
$downloader = $this->getDownloaderMock(null, $config, $process);
$downloader->download($packageMock, 'composerPath');
$downloader->prepare('install', $packageMock, 'composerPath');
$downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath');
@rmdir($cachePath);
}
public function testDownloadUsesVariousProtocolsAndSetsPushUrlForGithub(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://github.com/mirrors/composer', 'https://github.com/composer/composer']));
$packageMock->expects($this->any())
->method('getSourceUrl')
->will($this->returnValue('https://github.com/composer/composer'));
$packageMock->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('1.0.0'));
$process = $this->getProcessExecutorMock();
$expectedPath = Platform::isWindows() ? Platform::getCwd().'/composerPath' : 'composerPath';
$process->expects([
['cmd' => ['git', 'clone', '--no-checkout', '--', 'https://github.com/mirrors/composer', $expectedPath], 'return' => 1, 'stderr' => 'Error1'],
['git', 'clone', '--no-checkout', '--', 'git@github.com:mirrors/composer', $expectedPath],
['git', 'remote', 'add', 'composer', '--', 'git@github.com:mirrors/composer'],
['git', 'fetch', 'composer'],
['git', 'remote', 'set-url', 'origin', '--', 'git@github.com:mirrors/composer'],
['git', 'remote', 'set-url', 'composer', '--', 'git@github.com:mirrors/composer'],
['git', 'remote', 'set-url', 'origin', '--', 'https://github.com/composer/composer'],
['git', 'remote', 'set-url', '--push', 'origin', '--', 'git@github.com:composer/composer.git'],
['git', 'branch', '-r'],
['git', 'checkout', 'ref', '--'],
['git', 'reset', '--hard', 'ref', '--'],
], true);
$downloader = $this->getDownloaderMock(null, new Config(), $process);
$downloader->download($packageMock, 'composerPath');
$downloader->prepare('install', $packageMock, 'composerPath');
$downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath');
}
public static function pushUrlProvider(): array
{
return [
// ssh proto should use git@ all along
[['ssh'], 'git@github.com:composer/composer', 'git@github.com:composer/composer.git'],
// auto-proto uses git@ by default for push url, but not fetch
[['https', 'ssh', 'git'], 'https://github.com/composer/composer', 'git@github.com:composer/composer.git'],
// if restricted to https then push url is not overwritten to git@
[['https'], 'https://github.com/composer/composer', 'https://github.com/composer/composer.git'],
];
}
/**
* @dataProvider pushUrlProvider
* @param string[] $protocols
*/
public function testDownloadAndSetPushUrlUseCustomVariousProtocolsForGithub(array $protocols, string $url, string $pushUrl): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://github.com/composer/composer']));
$packageMock->expects($this->any())
->method('getSourceUrl')
->will($this->returnValue('https://github.com/composer/composer'));
$packageMock->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('1.0.0'));
$process = $this->getProcessExecutorMock();
$expectedPath = Platform::isWindows() ? Platform::getCwd().'/composerPath' : 'composerPath';
$process->expects([
['git', 'clone', '--no-checkout', '--', $url, $expectedPath],
['git', 'remote', 'add', 'composer', '--', $url],
['git', 'fetch', 'composer'],
['git', 'remote', 'set-url', 'origin', '--', $url],
['git', 'remote', 'set-url', 'composer', '--', $url],
['git', 'remote', 'set-url', '--push', 'origin', '--', $pushUrl],
['git', 'branch', '-r'],
['git', 'checkout', 'ref', '--'],
['git', 'reset', '--hard', 'ref', '--'],
], true);
$config = new Config();
$config->merge(['config' => ['github-protocols' => $protocols]]);
$downloader = $this->getDownloaderMock(null, $config, $process);
$downloader->download($packageMock, 'composerPath');
$downloader->prepare('install', $packageMock, 'composerPath');
$downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath');
}
public function testDownloadThrowsRuntimeExceptionIfGitCommandFails(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://example.com/composer/composer']));
$packageMock->expects($this->any())
->method('getSourceUrl')
->will($this->returnValue('https://example.com/composer/composer'));
$packageMock->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('1.0.0'));
$process = $this->getProcessExecutorMock();
$expectedPath = Platform::isWindows() ? Platform::getCwd().'/composerPath' : 'composerPath';
$process->expects([
[
'cmd' => ['git', 'clone', '--no-checkout', '--', 'https://example.com/composer/composer', $expectedPath],
'return' => 1,
],
]);
self::expectException('RuntimeException');
self::expectExceptionMessage('Failed to execute git clone --no-checkout -- https://example.com/composer/composer '.$expectedPath);
$downloader = $this->getDownloaderMock(null, null, $process);
$downloader->download($packageMock, 'composerPath');
$downloader->prepare('install', $packageMock, 'composerPath');
$downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath');
}
public function testUpdateforPackageWithoutSourceReference(): void
{
$initialPackageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$sourcePackageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$sourcePackageMock->expects($this->once())
->method('getSourceReference')
->will($this->returnValue(null));
self::expectException('InvalidArgumentException');
$downloader = $this->getDownloaderMock();
$downloader->download($sourcePackageMock, '/path', $initialPackageMock);
$downloader->prepare('update', $sourcePackageMock, '/path', $initialPackageMock);
$downloader->update($initialPackageMock, $sourcePackageMock, '/path');
$downloader->cleanup('update', $sourcePackageMock, '/path', $initialPackageMock);
}
public function testUpdate(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://github.com/composer/composer']));
$packageMock->expects($this->any())
->method('getVersion')
->will($this->returnValue('1.0.0.0'));
$packageMock->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('1.0.0'));
$process = $this->getProcessExecutorMock();
$process->expects([
['git', 'show-ref', '--head', '-d'],
['git', 'status', '--porcelain', '--untracked-files=no'],
['cmd' => ['git', 'rev-parse', '--quiet', '--verify', 'ref^{commit}'], 'return' => 1],
// fallback commands for the above failing
['git', 'remote', '-v'],
['git', 'remote', 'set-url', 'composer', '--', 'https://github.com/composer/composer'],
['git', 'fetch', 'composer'],
['git', 'fetch', '--tags', 'composer'],
['git', 'remote', '-v'],
['git', 'remote', 'set-url', 'composer', '--', 'https://github.com/composer/composer'],
['git', 'branch', '-r'],
['git', 'checkout', 'ref', '--'],
['git', 'reset', '--hard', 'ref', '--'],
['git', 'remote', '-v'],
], true);
$this->fs->ensureDirectoryExists($this->workingDir.'/.git');
$downloader = $this->getDownloaderMock(null, new Config(), $process);
$downloader->download($packageMock, $this->workingDir, $packageMock);
$downloader->prepare('update', $packageMock, $this->workingDir, $packageMock);
$downloader->update($packageMock, $packageMock, $this->workingDir);
$downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock);
}
public function testUpdateWithNewRepoUrl(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://github.com/composer/composer']));
$packageMock->expects($this->any())
->method('getSourceUrl')
->will($this->returnValue('https://github.com/composer/composer'));
$packageMock->expects($this->any())
->method('getVersion')
->will($this->returnValue('1.0.0.0'));
$packageMock->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('1.0.0'));
$process = $this->getProcessExecutorMock();
$process->expects([
['git', 'show-ref', '--head', '-d'],
['git', 'status', '--porcelain', '--untracked-files=no'],
['cmd' => ['git', 'rev-parse', '--quiet', '--verify', 'ref^{commit}'], 'return' => 0],
['git', 'remote', '-v'],
['git', 'remote', 'set-url', 'composer', '--', 'https://github.com/composer/composer'],
['git', 'branch', '-r'],
['git', 'checkout', 'ref', '--'],
['git', 'reset', '--hard', 'ref', '--'],
[
'cmd' => ['git', 'remote', '-v'],
'stdout' => 'origin https://github.com/old/url (fetch)
origin https://github.com/old/url (push)
composer https://github.com/old/url (fetch)
composer https://github.com/old/url (push)
',
],
['git', 'remote', 'set-url', 'origin', '--', 'https://github.com/composer/composer'],
['git', 'remote', 'set-url', '--push', 'origin', '--', 'git@github.com:composer/composer.git'],
], true);
$this->fs->ensureDirectoryExists($this->workingDir.'/.git');
$downloader = $this->getDownloaderMock(null, new Config(), $process);
$downloader->download($packageMock, $this->workingDir, $packageMock);
$downloader->prepare('update', $packageMock, $this->workingDir, $packageMock);
$downloader->update($packageMock, $packageMock, $this->workingDir);
$downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock);
}
/**
* @group failing
*/
public function testUpdateThrowsRuntimeExceptionIfGitCommandFails(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://github.com/composer/composer']));
$packageMock->expects($this->any())
->method('getVersion')
->will($this->returnValue('1.0.0.0'));
$process = $this->getProcessExecutorMock();
$process->expects([
['git', 'show-ref', '--head', '-d'],
['git', 'status', '--porcelain', '--untracked-files=no'],
// commit not yet in so we try to fetch
['cmd' => ['git', 'rev-parse', '--quiet', '--verify', 'ref^{commit}'], 'return' => 1],
// fail first fetch
['git', 'remote', '-v'],
['git', 'remote', 'set-url', 'composer', '--', 'https://github.com/composer/composer'],
['cmd' => ['git', 'fetch', 'composer'], 'return' => 1],
// fail second fetch
['git', 'remote', 'set-url', 'composer', '--', 'git@github.com:composer/composer'],
['cmd' => ['git', 'fetch', 'composer'], 'return' => 1],
['git', '--version'],
], true);
$this->fs->ensureDirectoryExists($this->workingDir.'/.git');
self::expectException('RuntimeException');
self::expectExceptionMessage('Failed to clone https://github.com/composer/composer via https, ssh protocols, aborting.');
self::expectExceptionMessageMatches('{git@github\.com:composer/composer}');
$downloader = $this->getDownloaderMock(null, new Config(), $process);
$downloader->download($packageMock, $this->workingDir, $packageMock);
$downloader->prepare('update', $packageMock, $this->workingDir, $packageMock);
$downloader->update($packageMock, $packageMock, $this->workingDir);
$downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock);
}
public function testUpdateDoesntThrowsRuntimeExceptionIfGitCommandFailsAtFirstButIsAbleToRecover(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$packageMock->expects($this->any())
->method('getVersion')
->will($this->returnValue('1.0.0.0'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue([Platform::isWindows() ? 'C:\\' : '/', 'https://github.com/composer/composer']));
$packageMock->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('1.0.0'));
$process = $this->getProcessExecutorMock();
$process->expects([
['git', 'show-ref', '--head', '-d'],
['git', 'status', '--porcelain', '--untracked-files=no'],
// commit not yet in so we try to fetch
['cmd' => ['git', 'rev-parse', '--quiet', '--verify', 'ref^{commit}'], 'return' => 1],
// fail first source URL
['git', 'remote', '-v'],
['git', 'remote', 'set-url', 'composer', '--', Platform::isWindows() ? 'C:\\' : '/'],
['cmd' => ['git', 'fetch', 'composer'], 'return' => 1],
['git', '--version'],
// commit not yet in so we try to fetch
['cmd' => ['git', 'rev-parse', '--quiet', '--verify', 'ref^{commit}'], 'return' => 1],
// pass second source URL
['git', 'remote', '-v'],
['git', 'remote', 'set-url', 'composer', '--', 'https://github.com/composer/composer'],
['cmd' => ['git', 'fetch', 'composer'], 'return' => 0],
['git', 'fetch', '--tags', 'composer'],
['git', 'remote', '-v'],
['git', 'remote', 'set-url', 'composer', '--', 'https://github.com/composer/composer'],
['git', 'branch', '-r'],
['git', 'checkout', 'ref', '--'],
['git', 'reset', '--hard', 'ref', '--'],
['git', 'remote', '-v'],
], true);
$this->fs->ensureDirectoryExists($this->workingDir.'/.git');
$downloader = $this->getDownloaderMock(null, new Config(), $process);
$downloader->download($packageMock, $this->workingDir, $packageMock);
$downloader->prepare('update', $packageMock, $this->workingDir, $packageMock);
$downloader->update($packageMock, $packageMock, $this->workingDir);
$downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock);
}
public function testDowngradeShowsAppropriateMessage(): void
{
$oldPackage = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$oldPackage->expects($this->any())
->method('getVersion')
->will($this->returnValue('1.2.0.0'));
$oldPackage->expects($this->any())
->method('getFullPrettyVersion')
->will($this->returnValue('1.2.0'));
$oldPackage->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$oldPackage->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['/foo/bar', 'https://github.com/composer/composer']));
$newPackage = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$newPackage->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$newPackage->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://github.com/composer/composer']));
$newPackage->expects($this->any())
->method('getVersion')
->will($this->returnValue('1.0.0.0'));
$newPackage->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('1.0.0'));
$newPackage->expects($this->any())
->method('getFullPrettyVersion')
->will($this->returnValue('1.0.0'));
$process = $this->getProcessExecutorMock();
$ioMock = $this->getIOMock();
$ioMock->expects([
['text' => '{Downgrading .*}', 'regex' => true],
]);
$this->fs->ensureDirectoryExists($this->workingDir.'/.git');
$downloader = $this->getDownloaderMock($ioMock, null, $process);
$downloader->download($newPackage, $this->workingDir, $oldPackage);
$downloader->prepare('update', $newPackage, $this->workingDir, $oldPackage);
$downloader->update($oldPackage, $newPackage, $this->workingDir);
$downloader->cleanup('update', $newPackage, $this->workingDir, $oldPackage);
}
public function testNotUsingDowngradingWithReferences(): void
{
$oldPackage = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$oldPackage->expects($this->any())
->method('getVersion')
->will($this->returnValue('dev-ref'));
$oldPackage->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$oldPackage->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['/foo/bar', 'https://github.com/composer/composer']));
$newPackage = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$newPackage->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$newPackage->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://github.com/composer/composer']));
$newPackage->expects($this->any())
->method('getVersion')
->will($this->returnValue('dev-ref2'));
$newPackage->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('dev-ref2'));
$process = $this->getProcessExecutorMock();
$ioMock = $this->getIOMock();
$ioMock->expects([
['text' => '{Upgrading .*}', 'regex' => true],
]);
$this->fs->ensureDirectoryExists($this->workingDir.'/.git');
$downloader = $this->getDownloaderMock($ioMock, null, $process);
$downloader->download($newPackage, $this->workingDir, $oldPackage);
$downloader->prepare('update', $newPackage, $this->workingDir, $oldPackage);
$downloader->update($oldPackage, $newPackage, $this->workingDir);
$downloader->cleanup('update', $newPackage, $this->workingDir, $oldPackage);
}
public function testRemove(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$process = $this->getProcessExecutorMock();
$process->expects([
['git', 'show-ref', '--head', '-d'],
['git', 'status', '--porcelain', '--untracked-files=no'],
], true);
$this->fs->ensureDirectoryExists($this->workingDir.'/.git');
$filesystem = $this->getMockBuilder('Composer\Util\Filesystem')->getMock();
$filesystem->expects($this->once())
->method('removeDirectoryAsync')
->with($this->equalTo($this->workingDir))
->will($this->returnValue(\React\Promise\resolve(true)));
$downloader = $this->getDownloaderMock(null, null, $process, $filesystem);
$downloader->prepare('uninstall', $packageMock, $this->workingDir);
$downloader->remove($packageMock, $this->workingDir);
$downloader->cleanup('uninstall', $packageMock, $this->workingDir);
}
public function testGetInstallationSource(): void
{
$downloader = $this->getDownloaderMock();
self::assertEquals('source', $downloader->getInstallationSource());
}
}
|
php
|
github
|
https://github.com/composer/composer
|
tests/Composer/Test/Downloader/GitDownloaderTest.php
|
#!/usr/bin/python
#
# Copyright (c) 2019 Zim Kalinowski, (@zikalino)
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: azure_rm_hdinsightcluster_info
version_added: "2.9"
short_description: Get Azure HDInsight Cluster facts
description:
- Get facts of Azure HDInsight Cluster.
options:
resource_group:
description:
- Name of an Azure resource group.
name:
description:
- HDInsight cluster name.
tags:
description:
- Limit results by providing a list of tags. Format tags as 'key' or 'key:value'.
extends_documentation_fragment:
- azure
author:
- Zim Kalinowski (@zikalino)
'''
EXAMPLES = '''
- name: Get instance of HDInsight Cluster
azure_rm_hdinsightcluster_info:
resource_group: myResourceGroup
name: myCluster
- name: List instances of HDInsight Cluster
azure_rm_hdinsightcluster_info:
resource_group: myResourceGroup
'''
RETURN = '''
clusters:
description:
- A list of dictionaries containing facts for HDInsight Cluster.
returned: always
type: complex
contains:
id:
description:
- The unique resource identifier of the HDInsight Cluster.
returned: always
type: str
sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/myResourceGroup/providers/Microsoft.HDInsight/clusters/myCluster"
resource_group:
description:
- Name of an Azure resource group.
returned: always
type: str
sample: myResourceGroup
name:
description:
- The name of the HDInsight Cluster.
returned: always
type: str
sample: testaccount
location:
description:
- The location of the resource group to which the resource belongs.
returned: always
type: str
sample: westus
cluster_version:
description:
- The version of the cluster.
returned: always
type: str
sample: 3.6.1000.67
os_type:
description:
- The type of operating system.
returned: always
type: str
sample: linux
tier:
description:
- The cluster tier.
returned: always
type: str
sample: standard
cluster_definition:
description:
- The cluster definition.
contains:
kind:
description:
- The type of cluster.
returned: always
type: str
sample: spark
compute_profile_roles:
description:
- The list of roles in the cluster.
type: list
suboptions:
name:
description:
- The name of the role.
returned: always
type: str
sample: headnode
target_instance_count:
description:
- The instance count of the cluster.
returned: always
type: int
sample: 2
vm_size:
description:
- The size of the VM.
returned: always
type: str
sample: Standard_D3
linux_profile:
description:
- The Linux OS profile.
contains:
username:
description:
- User name.
returned: always
type: str
sample: myuser
connectivity_endpoints:
description:
- Cluster's connectivity endpoints.
type: list
contains:
location:
description:
- Endpoint location.
returned: always
type: str
sample: myCluster-ssh.azurehdinsight.net
name:
description:
- Endpoint name.
returned: always
type: str
sample: SSH
port:
description:
- Endpoint port.
returned: always
type: int
sample: 22
protocol:
description:
- Endpoint protocol.
returned: always
type: str
sample: TCP
tags:
description:
- The tags of the resource.
returned: always
type: complex
sample: {}
'''
from ansible.module_utils.azure_rm_common import AzureRMModuleBase
from ansible.module_utils.common.dict_transformations import _camel_to_snake
try:
from msrestazure.azure_exceptions import CloudError
from azure.mgmt.hdinsight import HDInsightManagementClient
from msrest.serialization import Model
except ImportError:
# This is handled in azure_rm_common
pass
class AzureRMHDInsightclusterInfo(AzureRMModuleBase):
def __init__(self):
# define user inputs into argument
self.module_arg_spec = dict(
resource_group=dict(
type='str'
),
name=dict(
type='str'
),
tags=dict(
type='list'
)
)
# store the results of the module operation
self.results = dict(
changed=False
)
self.mgmt_client = None
self.resource_group = None
self.name = None
self.tags = None
super(AzureRMHDInsightclusterInfo, self).__init__(self.module_arg_spec, supports_tags=False)
def exec_module(self, **kwargs):
is_old_facts = self.module._name == 'azure_rm_hdinsightcluster_facts'
if is_old_facts:
self.module.deprecate("The 'azure_rm_hdinsightcluster_facts' module has been renamed to 'azure_rm_hdinsightcluster_info'",
version='2.13')
for key in self.module_arg_spec:
setattr(self, key, kwargs[key])
self.mgmt_client = self.get_mgmt_svc_client(HDInsightManagementClient,
base_url=self._cloud_environment.endpoints.resource_manager)
if self.name is not None:
self.results['clusters'] = self.get()
elif self.resource_group is not None:
self.results['clusters'] = self.list_by_resource_group()
else:
self.results['clusters'] = self.list_all()
return self.results
def get(self):
response = None
results = []
try:
response = self.mgmt_client.clusters.get(resource_group_name=self.resource_group,
cluster_name=self.name)
self.log("Response : {0}".format(response))
except CloudError as e:
self.log('Could not get facts for HDInsight Cluster.')
if response and self.has_tags(response.tags, self.tags):
results.append(self.format_response(response))
return results
def list_by_resource_group(self):
response = None
results = []
try:
response = self.mgmt_client.clusters.list_by_resource_group(resource_group_name=self.resource_group)
self.log("Response : {0}".format(response))
except CloudError as e:
self.log('Could not get facts for HDInsight Cluster.')
if response is not None:
for item in response:
if self.has_tags(item.tags, self.tags):
results.append(self.format_response(item))
return results
def list_all(self):
response = None
results = []
try:
response = self.mgmt_client.clusters.list()
self.log("Response : {0}".format(response))
except CloudError as e:
self.log('Could not get facts for HDInsight Cluster.')
if response is not None:
for item in response:
if self.has_tags(item.tags, self.tags):
results.append(self.format_response(item))
return results
def format_response(self, item):
d = item.as_dict()
d = {
'id': d.get('id'),
'resource_group': self.parse_resource_to_dict(d.get('id')).get('resource_group'),
'name': d.get('name', None),
'location': d.get('location', '').replace(' ', '').lower(),
'cluster_version': d.get('properties', {}).get('cluster_version'),
'os_type': d.get('properties', {}).get('os_type'),
'tier': d.get('properties', {}).get('tier'),
'cluster_definition': {
'kind': d.get('properties', {}).get('cluster_definition', {}).get('kind')
},
'compute_profile_roles': [{
'name': item.get('name'),
'target_instance_count': item.get('target_instance_count'),
'vm_size': item.get('hardware_profile', {}).get('vm_size'),
'linux_profile': {
'username': item.get('os_profile', {}).get('linux_operating_system_profile', {}).get('username')
}
} for item in d.get('properties', []).get('compute_profile', {}).get('roles', [])],
'connectivity_endpoints': d.get('properties', {}).get('connectivity_endpoints'),
'tags': d.get('tags', None)
}
return d
def main():
AzureRMHDInsightclusterInfo()
if __name__ == '__main__':
main()
|
unknown
|
codeparrot/codeparrot-clean
| ||
from __future__ import unicode_literals
from django.core import serializers
from django.db import connection
from django.test import TestCase
from .models import FKDataNaturalKey, NaturalKeyAnchor
from .tests import register_tests
class NaturalKeySerializerTests(TestCase):
pass
def natural_key_serializer_test(format, self):
# Create all the objects defined in the test data
with connection.constraint_checks_disabled():
objects = [
NaturalKeyAnchor.objects.create(id=1100, data="Natural Key Anghor"),
FKDataNaturalKey.objects.create(id=1101, data_id=1100),
FKDataNaturalKey.objects.create(id=1102, data_id=None),
]
# Serialize the test database
serialized_data = serializers.serialize(format, objects, indent=2, use_natural_foreign_keys=True)
for obj in serializers.deserialize(format, serialized_data):
obj.save()
# Assert that the deserialized data is the same
# as the original source
for obj in objects:
instance = obj.__class__.objects.get(id=obj.pk)
self.assertEqual(
obj.data, instance.data,
"Objects with PK=%d not equal; expected '%s' (%s), got '%s' (%s)" % (
obj.pk, obj.data, type(obj.data), instance, type(instance.data),
)
)
def natural_key_test(format, self):
book1 = {
'data': '978-1590597255',
'title': 'The Definitive Guide to Django: Web Development Done Right',
}
book2 = {'data': '978-1590599969', 'title': 'Practical Django Projects'}
# Create the books.
adrian = NaturalKeyAnchor.objects.create(**book1)
james = NaturalKeyAnchor.objects.create(**book2)
# Serialize the books.
string_data = serializers.serialize(
format, NaturalKeyAnchor.objects.all(), indent=2,
use_natural_foreign_keys=True, use_natural_primary_keys=True,
)
# Delete one book (to prove that the natural key generation will only
# restore the primary keys of books found in the database via the
# get_natural_key manager method).
james.delete()
# Deserialize and test.
books = list(serializers.deserialize(format, string_data))
self.assertEqual(len(books), 2)
self.assertEqual(books[0].object.title, book1['title'])
self.assertEqual(books[0].object.pk, adrian.pk)
self.assertEqual(books[1].object.title, book2['title'])
self.assertEqual(books[1].object.pk, None)
# Dynamically register tests for each serializer
register_tests(NaturalKeySerializerTests, 'test_%s_natural_key_serializer', natural_key_serializer_test)
register_tests(NaturalKeySerializerTests, 'test_%s_serializer_natural_keys', natural_key_test)
|
unknown
|
codeparrot/codeparrot-clean
| ||
import cp from "node:child_process";
import type { Page, Response, Request } from "@playwright/test";
import { test } from "@playwright/test";
import { load } from "cheerio";
import prettier from "prettier";
let cheerio = load("");
import type { AppFixture } from "./create-fixture.js";
export class PlaywrightFixture {
readonly page: Page;
readonly app: AppFixture;
constructor(app: AppFixture, page: Page) {
this.page = page;
this.app = app;
}
/**
* Visits the href with a document request.
*
* @param href The href you want to visit
* @param waitForHydration Wait for the page to full load/hydrate?
* - `undefined` to wait for the document `load` event
* - `true` wait for the network to be idle, so everything should be loaded
* and ready to go
* - `false` to wait only until the initial doc to be returned and the document
* to start loading (mostly useful for testing deferred responses)
*/
async goto(href: string, waitForHydration?: boolean): Promise<Response> {
let response = await this.page.goto(this.app.serverUrl + href, {
waitUntil:
waitForHydration === true
? "networkidle"
: waitForHydration === false
? "commit"
: "load",
});
if (response == null)
throw new Error(
"Unexpected null response, possible about:blank request or same-URL redirect",
);
return response;
}
/**
* Finds a link on the page with a matching href, clicks it, and waits for
* the network to be idle before continuing.
*
* @param href The href of the link you want to click
* @param options `{ wait }` waits for the network to be idle before moving on
*/
async clickLink(href: string, options: { wait: boolean } = { wait: true }) {
let selector = `a[href="${href}"]`;
let el = await this.page.$(selector);
if (!el) {
throw new Error(`Could not find link for ${selector}`);
}
if (options.wait) {
await doAndWait(this.page, () => el!.click());
} else {
await el.click();
}
}
/**
* Find the input element and fill for file uploads.
*
* @param inputSelector The selector of the input you want to fill
* @param filePaths The paths to the files you want to upload
*/
async uploadFile(inputSelector: string, ...filePaths: string[]) {
let el = await this.page.$(inputSelector);
if (!el) {
throw new Error(`Could not find input for: ${inputSelector}`);
}
await el.setInputFiles(filePaths);
}
/**
* Finds the first submit button with `formAction` that matches the
* `action` supplied, clicks it, and optionally waits for the network to
* be idle before continuing.
*
* @param action The formAction of the button you want to click
* @param options `{ wait }` waits for the network to be idle before moving on
*/
async clickSubmitButton(
action: string,
options: { wait?: boolean; method?: string } = { wait: true },
) {
let selector: string;
if (options.method) {
selector = `button[formAction="${action}"][formMethod="${options.method}"]`;
} else {
selector = `button[formAction="${action}"]`;
}
let el = await this.page.$(selector);
if (!el) {
if (options.method) {
selector = `form[action="${action}"] button[type="submit"][formMethod="${options.method}"]`;
} else {
selector = `form[action="${action}"] button[type="submit"]`;
}
el = await this.page.$(selector);
if (!el) {
throw new Error(`Can't find button for: ${action}`);
}
}
if (options.wait) {
await doAndWait(this.page, () => el!.click());
} else {
await el.click();
}
}
/**
* Clicks any element and waits for the network to be idle.
*/
async clickElement(selector: string) {
let el = await this.page.$(selector);
if (!el) {
throw new Error(`Can't find element for: ${selector}`);
}
await doAndWait(this.page, () => el!.click());
}
/**
* Perform any interaction and wait for the network to be idle:
*
* ```ts
* await app.waitForNetworkAfter(page, () => app.page.focus("#el"))
* ```
*/
async waitForNetworkAfter(fn: () => Promise<unknown>) {
await doAndWait(this.page, fn);
}
/**
* "Clicks" the back button and optionally waits for the network to be
* idle (defaults to waiting).
*/
async goBack(options: { wait: boolean } = { wait: true }) {
if (options.wait) {
await doAndWait(this.page, () => this.page.goBack());
} else {
await this.page.goBack();
}
}
/**
* "Clicks" the refresh button.
*/
async reload(options: { wait: boolean } = { wait: true }) {
if (options.wait) {
await doAndWait(this.page, () => this.page.reload());
} else {
await this.page.reload();
}
}
/**
* Collects single fetch data responses from the network, usually after a
* link click or form submission. This is useful for asserting that specific
* loaders were called (or not).
*/
collectSingleFetchResponses() {
return this.collectResponses(
(url) => url.pathname.endsWith(".data") || url.pathname.endsWith(".rsc"),
);
}
/**
* Collects all responses from the network, usually after a link click or
* form submission. A filter can be provided to only collect responses
* that meet a certain criteria.
*/
collectResponses(filter?: (url: URL) => boolean) {
let responses: Response[] = [];
this.page.on("response", (res) => {
if (!filter || filter(new URL(res.url()))) {
responses.push(res);
}
});
return responses;
}
/**
* Get HTML from the page. Useful for asserting something rendered that
* you expected.
*
* @param selector CSS Selector for the element's HTML you want
*/
getHtml(selector?: string) {
return getHtml(this.page, selector);
}
/**
* Get a cheerio instance of an element from the page.
*
* @param selector CSS Selector for the element's HTML you want
*/
async getElement(selector: string) {
return getElement(await getHtml(this.page), selector);
}
/**
* Keeps the fixture running for as many seconds as you want so you can go
* poke around in the browser to see what's up.
*
* @param seconds How long you want the app to stay open
*/
async poke(seconds: number = 10, href: string = "/") {
let ms = seconds * 1000;
test.setTimeout(ms);
console.log(
`🙈 Poke around for ${seconds} seconds 👉 ${this.app.serverUrl}`,
);
cp.exec(`open ${this.app.serverUrl}${href}`);
return new Promise((res) => setTimeout(res, ms));
}
}
export async function getHtml(page: Page, selector?: string) {
let html = await page.content();
let selectedHtml = selector
? await selectHtml(html, selector)
: await prettyHtml(html);
return selectedHtml;
}
export function getElement(source: string, selector: string) {
let el = cheerio(selector, source);
if (!el.length) {
throw new Error(`No element matches selector "${selector}"`);
}
return el;
}
export async function selectHtml(source: string, selector: string) {
let el = getElement(source, selector);
let html = await prettyHtml(cheerio.html(el));
return html.trim();
}
export async function prettyHtml(source: string) {
return prettier.format(source, { parser: "html" });
}
async function doAndWait(
page: Page,
action: () => Promise<unknown>,
longPolls = 0,
) {
let DEBUG = !!process.env.DEBUG;
let networkSettledCallback: any;
let networkSettledPromise = new Promise((resolve) => {
networkSettledCallback = resolve;
});
let requestCounter = 0;
let actionDone = false;
let pending = new Set<Request>();
let maybeSettle = () => {
if (actionDone && requestCounter <= longPolls) networkSettledCallback();
};
let onRequest = (request: Request) => {
++requestCounter;
if (DEBUG) {
pending.add(request);
console.log(`+[${requestCounter}]: ${request.url()}`);
}
};
let onRequestDone = (request: Request) => {
// Let the page handle responses asynchronously (via setTimeout(0)).
//
// Note: this might be changed to use delay, e.g. setTimeout(f, 100),
// when the page uses delay itself.
let evaluate = page.evaluate(() => {
return new Promise((resolve) => setTimeout(resolve, 0));
});
evaluate
.catch(() => null)
.then(() => {
--requestCounter;
maybeSettle();
if (DEBUG) {
pending.delete(request);
console.log(`-[${requestCounter}]: ${request.url()}`);
}
});
};
page.on("request", onRequest);
page.on("requestfinished", onRequestDone);
page.on("requestfailed", onRequestDone);
page.on("load", networkSettledCallback); // e.g. navigation with javascript disabled
let timeoutId = DEBUG
? setInterval(() => {
console.log(`${requestCounter} requests pending:`);
for (let request of pending) console.log(` ${request.url()}`);
}, 5000)
: undefined;
let result = await action();
actionDone = true;
maybeSettle();
if (DEBUG) {
console.log(`action done, ${requestCounter} requests pending`);
}
await networkSettledPromise;
// I wish I knew why but Safari seems to get all screwed up without this.
// When you run doAndWait (via clicking a blink or submitting a form) and
// then waitForSelector(). It finds the selector element but thinks it's
// hidden for some unknown reason. It's intermittent, but waiting for the
// next animation frame delaying slightly before the waitForSelector() calls
// seems to fix it 🤷♂️
//
// Test timeout of 30000ms exceeded.
//
// Error: page.waitForSelector: Target closed
// =========================== logs ===========================
// waiting for locator('text=ROOT_BOUNDARY_TEXT') to be visible
// locator resolved to hidden <div id="root-boundary">ROOT_BOUNDARY_TEXT</div>
// locator resolved to hidden <div id="root-boundary">ROOT_BOUNDARY_TEXT</div>
// ... and so on until the test times out
let userAgent = await page.evaluate(() => navigator.userAgent);
if (/Safari\//i.test(userAgent) && !/Chrome\//i.test(userAgent)) {
await page.evaluate(() => new Promise((r) => requestAnimationFrame(r)));
}
if (DEBUG) {
console.log(`action done, network settled`);
}
page.removeListener("request", onRequest);
page.removeListener("requestfinished", onRequestDone);
page.removeListener("requestfailed", onRequestDone);
page.removeListener("load", networkSettledCallback);
if (DEBUG && timeoutId) {
clearTimeout(timeoutId);
}
return result;
}
|
typescript
|
github
|
https://github.com/remix-run/react-router
|
integration/helpers/playwright-fixture.ts
|
#! /usr/bin/env python2.5
# -*- coding: latin-1 -*-
import axiom_rules
import fact_groups
import instantiate
import pddl
import sas_tasks
import simplify
# TODO: The translator may generate trivial derived variables which are always true,
# for example if there ia a derived predicate in the input that only depends on
# (non-derived) variables which are detected as always true.
# Such a situation was encountered in the PSR-STRIPS-DerivedPredicates domain.
# Such "always-true" variables should best be compiled away, but it is
# not clear what the best place to do this should be. Similar
# simplifications might be possible elsewhere, for example if a
# derived variable is synonymous with another variable (derived or
# non-derived).
ALLOW_CONFLICTING_EFFECTS = False
USE_PARTIAL_ENCODING = True
WRITE_ALL_MUTEXES = True
def strips_to_sas_dictionary(groups):
dictionary = {}
for var_no, group in enumerate(groups):
for val_no, atom in enumerate(group):
dictionary.setdefault(atom, []).append((var_no, val_no))
if USE_PARTIAL_ENCODING:
assert all(len(sas_pairs) == 1
for sas_pairs in dictionary.itervalues())
return [len(group) + 1 for group in groups], dictionary
def translate_strips_conditions(conditions, dictionary, ranges):
if not conditions:
return {} # Quick exit for common case.
condition = {}
for fact in conditions:
atom = pddl.Atom(fact.predicate, fact.args) # force positive
for var, val in dictionary[atom]:
if fact.negated:
assert False, "neg. precondition: task not in positive normal form"
if condition.get(var) not in (None, val):
# Conflicting conditions on this variable: Operator invalid.
return None
condition[var] = val
return condition
def translate_strips_operator(operator, dictionary, ranges):
# NOTE: This function does not really deal with the intricacies of properly
# encoding delete effects for grouped propositions in the presence of
# conditional effects. It should work ok but will bail out in more
# complicated cases even though a conflict does not necessarily exist.
possible_add_conflict = False
condition = translate_strips_conditions(operator.precondition, dictionary, ranges)
if condition is None:
return None
effect = {}
for conditions, fact in operator.add_effects:
eff_condition = translate_strips_conditions(conditions, dictionary, ranges)
if eff_condition is None: # Impossible condition for this effect.
continue
eff_condition = eff_condition.items()
for var, val in dictionary[fact]:
effect_pair = effect.get(var)
if not effect_pair:
effect[var] = (val, [eff_condition])
else:
other_val, eff_conditions = effect_pair
# Don't flag conflict just yet... the operator might be invalid
# because of conflicting add/delete effects (see pipesworld).
if other_val != val:
possible_add_conflict = True
eff_conditions.append(eff_condition)
for conditions, fact in operator.del_effects:
eff_condition_dict = translate_strips_conditions(conditions, dictionary, ranges)
if eff_condition_dict is None:
continue
eff_condition = eff_condition_dict.items()
for var, val in dictionary[fact]:
none_of_those = ranges[var] - 1
other_val, eff_conditions = effect.get(var, (none_of_those, []))
if other_val != none_of_those:
# Look for matching add effect; ignore this del effect if found.
assert eff_condition in eff_conditions or [] in eff_conditions, \
"Add effect with uncertain del effect partner?"
if other_val == val:
if ALLOW_CONFLICTING_EFFECTS:
# Conflicting ADD and DEL effect. This is *only* allowed if
# this is also a precondition, in which case there is *no*
# effect (the ADD takes precedence). We delete the add effect here.
if condition.get(var) != val:
# HACK HACK HACK!
# There used to be an assertion here that actually
# forbid this, but this was wrong in Pipesworld-notankage
# (e.g. task 01). The thing is, it *is* possible for
# an operator with proven (with the given invariants)
# inconsistent preconditions to actually end up here if
# the inconsistency of the preconditions is not obvious at
# the SAS+ encoding level.
#
# Example: Pipes-Notank-01, operator
# (pop-unitarypipe s12 b4 a1 a2 b4 lco lco).
# This has precondition last(b4, s12) and on(b4, a2) which
# is inconsistent because b4 can only be in one place.
# However, the chosen encoding encodes *what is last in s12*
# separately, and so the precondition translates to
# "last(s12) = b4 and on(b4) = a2", which does not look
# inconsistent at first glance.
#
# Something reasonable to do here would be to make a
# decent check that the precondition is indeed inconsistent
# (using *all* mutexes), but that seems tough with this
# convoluted code, so we just warn and reject the operator.
print "Warning: %s rejected. Cross your fingers." % (
operator.name)
return None
assert False
assert eff_conditions == [[]]
del effect[var]
else:
assert not eff_condition and not eff_conditions[0], "Uncertain conflict"
return None # Definite conflict otherwise.
# else:
# if condition.get(var) != val and eff_condition_dict.get(var) != val:
# # Need a guard for this delete effect.
# assert var not in condition and var not in eff_condition, "Oops?"
# eff_condition.append((var, val))
# eff_conditions.append(eff_condition)
if possible_add_conflict:
print operator.name
assert not possible_add_conflict, "Conflicting add effects?"
pre_post = []
for var, (post, eff_condition_lists) in effect.iteritems():
pre = condition.get(var, -1)
if pre != -1:
del condition[var]
for eff_condition in eff_condition_lists:
pre_post.append((var, pre, post, eff_condition))
prevail = condition.items()
return sas_tasks.SASOperator(operator.name, prevail, pre_post)
def translate_strips_axiom(axiom, dictionary, ranges):
condition = translate_strips_conditions(axiom.condition, dictionary, ranges)
if condition is None:
return None
if axiom.effect.negated:
[(var, _)] = dictionary[axiom.effect.positive()]
effect = (var, ranges[var] - 1)
else:
[effect] = dictionary[axiom.effect]
return sas_tasks.SASAxiom(condition.items(), effect)
def translate_strips_operators(actions, strips_to_sas, ranges):
result = []
for action in actions:
sas_op = translate_strips_operator(action, strips_to_sas, ranges)
if sas_op:
result.append(sas_op)
return result
def translate_strips_axioms(axioms, strips_to_sas, ranges):
result = []
for axiom in axioms:
sas_axiom = translate_strips_axiom(axiom, strips_to_sas, ranges)
if sas_axiom:
result.append(sas_axiom)
return result
def translate_task(strips_to_sas, ranges, init, goals, actions, axioms):
axioms, axiom_init, axiom_layer_dict = axiom_rules.handle_axioms(
actions, axioms, goals)
init = init + axiom_init
#axioms.sort(key=lambda axiom: axiom.name)
#for axiom in axioms:
# axiom.dump()
init_values = [rang - 1 for rang in ranges]
# Closed World Assumption: Initialize to "range - 1" == Nothing.
for fact in init:
pair = strips_to_sas.get(fact)
pairs = strips_to_sas.get(fact, []) # empty for static init facts
for var, val in pairs:
assert init_values[var] == ranges[var] - 1, "Inconsistent init facts!"
init_values[var] = val
init = sas_tasks.SASInit(init_values)
goal_pairs = translate_strips_conditions(goals, strips_to_sas, ranges).items()
goal = sas_tasks.SASGoal(goal_pairs)
operators = translate_strips_operators(actions, strips_to_sas, ranges)
axioms = translate_strips_axioms(axioms, strips_to_sas, ranges)
axiom_layers = [-1] * len(ranges)
for atom, layer in axiom_layer_dict.iteritems():
assert layer >= 0
[(var, val)] = strips_to_sas[atom]
axiom_layers[var] = layer
variables = sas_tasks.SASVariables(ranges, axiom_layers)
return sas_tasks.SASTask(variables, init, goal, operators, axioms)
def unsolvable_sas_task(msg):
print "%s! Generating unsolvable task..." % msg
variables = sas_tasks.SASVariables([2], [-1])
init = sas_tasks.SASInit([0])
goal = sas_tasks.SASGoal([(0, 1)])
operators = []
axioms = []
return sas_tasks.SASTask(variables, init, goal, operators, axioms)
def pddl_to_sas(task):
print "Instantiating..."
relaxed_reachable, atoms, actions, axioms = instantiate.explore(task)
if not relaxed_reachable:
return unsolvable_sas_task("No relaxed solution")
# HACK! Goals should be treated differently (see TODO file).
if isinstance(task.goal, pddl.Conjunction):
goal_list = task.goal.parts
else:
goal_list = [task.goal]
for item in goal_list:
assert isinstance(item, pddl.Literal)
# groups, mutex_groups, translation_key = fact_groups.compute_groups(
# task, atoms, return_mutex_groups=WRITE_ALL_MUTEXES,
# partial_encoding=USE_PARTIAL_ENCODING)
# switched off invariant syntheses -> one group for each fluent fact
groups = [[fact] for fact in atoms]
translation_key = [[str(fact),str(fact.negate())] for group in groups
for fact in group]
print "Building STRIPS to SAS dictionary..."
ranges, strips_to_sas = strips_to_sas_dictionary(groups)
print "Translating task..."
sas_task = translate_task(strips_to_sas, ranges, task.init, goal_list,
actions, axioms)
try:
simplify.filter_unreachable_propositions(
sas_task, [], translation_key)
except simplify.Impossible:
return unsolvable_sas_task("Simplified to trivially false goal")
write_translation_key(translation_key)
return sas_task
def build_mutex_key(strips_to_sas, groups):
group_keys = []
for group in groups:
group_key = []
for fact in group:
if strips_to_sas.get(fact):
for var, val in strips_to_sas[fact]:
group_key.append((var, val, str(fact)))
else:
print "not in strips_to_sas, left out:", fact
group_keys.append(group_key)
return group_keys
def write_translation_key(translation_key):
groups_file = file("test.groups", "w")
for var_no, var_key in enumerate(translation_key):
print >> groups_file, "var%d:" % var_no
for value, value_name in enumerate(var_key):
print >> groups_file, " %d: %s" % (value, value_name)
groups_file.close()
def write_mutex_key(mutex_key):
invariants_file = file("all.groups", "w")
print >> invariants_file, "begin_groups"
print >> invariants_file, len(mutex_key)
for group in mutex_key:
#print map(str, group)
no_facts = len(group)
print >> invariants_file, "group"
print >> invariants_file, no_facts
for var, val, fact in group:
#print fact
assert str(fact).startswith("Atom ")
predicate = str(fact)[5:].split("(")[0]
#print predicate
rest = str(fact).split("(")[1]
rest = rest.strip(")").strip()
if not rest == "":
#print "there are args" , rest
args = rest.split(",")
else:
args = []
print_line = "%d %d %s %d " % (var, val, predicate, len(args))
for arg in args:
print_line += str(arg).strip() + " "
#print fact
#print print_line
print >> invariants_file, print_line
print >> invariants_file, "end_groups"
invariants_file.close()
if __name__ == "__main__":
import pddl
print "Parsing..."
task = pddl.open()
if task.domain_name in ["protocol", "rover"]:
# This is, of course, a HACK HACK HACK!
# The real issue is that ALLOW_CONFLICTING_EFFECTS = True
# is actually the correct semantics, but then we don't get to filter
# out operators that are impossible to apply due to mutexes between
# different SAS+ variables. For example,
# ALLOW_CONFLICTING_EFFECTS = True does not filter on(a,a) in
# blocksworld/4-0.
ALLOW_CONFLICTING_EFFECTS = True
# EXPERIMENTAL!
# import psyco
# psyco.full()
sas_task = pddl_to_sas(task)
print "Writing output..."
sas_task.output(file("output.sas", "w"))
print "Done!"
print "Creating dummy output:"
open("all.groups", "w").write("dummy file expected by our scripts\n")
|
unknown
|
codeparrot/codeparrot-clean
| ||
# Copyright (c) 2012 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Package defining the data connector for YAML.
The data connector (subclass of DataConnector) is described in
the file ./connector.py .
"""
from dc.yaml.connector import YAMLConnector
|
unknown
|
codeparrot/codeparrot-clean
| ||
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Guillaume Martinez (lunik@tiwabbit.fr)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import
import pytest
from ansible.modules.source_control.gitlab.gitlab_hook import GitLabHook
def _dummy(x):
"""Dummy function. Only used as a placeholder for toplevel definitions when the test is going
to be skipped anyway"""
return x
pytestmark = []
try:
from .gitlab import (GitlabModuleTestCase,
python_version_match_requirement,
resp_get_project, resp_find_project_hook,
resp_create_project_hook, resp_delete_project_hook)
# GitLab module requirements
if python_version_match_requirement():
from gitlab.v4.objects import ProjectHook
except ImportError:
pytestmark.append(pytest.mark.skip("Could not load gitlab module required for testing"))
# Need to set these to something so that we don't fail when parsing
GitlabModuleTestCase = object
resp_get_project = _dummy
resp_find_project_hook = _dummy
resp_create_project_hook = _dummy
resp_delete_project_hook = _dummy
# Unit tests requirements
try:
from httmock import with_httmock # noqa
except ImportError:
pytestmark.append(pytest.mark.skip("Could not load httmock module required for testing"))
with_httmock = _dummy
class TestGitlabHook(GitlabModuleTestCase):
def setUp(self):
super(TestGitlabHook, self).setUp()
self.moduleUtil = GitLabHook(module=self.mock_module, gitlab_instance=self.gitlab_instance)
@with_httmock(resp_get_project)
@with_httmock(resp_find_project_hook)
def test_hook_exist(self):
project = self.gitlab_instance.projects.get(1)
rvalue = self.moduleUtil.existsHook(project, "http://example.com/hook")
self.assertEqual(rvalue, True)
rvalue = self.moduleUtil.existsHook(project, "http://gitlab.com/hook")
self.assertEqual(rvalue, False)
@with_httmock(resp_get_project)
@with_httmock(resp_create_project_hook)
def test_create_hook(self):
project = self.gitlab_instance.projects.get(1)
hook = self.moduleUtil.createHook(project, {"url": "http://example.com/hook"})
self.assertEqual(type(hook), ProjectHook)
self.assertEqual(hook.url, "http://example.com/hook")
@with_httmock(resp_get_project)
@with_httmock(resp_find_project_hook)
def test_update_hook(self):
project = self.gitlab_instance.projects.get(1)
hook = self.moduleUtil.findHook(project, "http://example.com/hook")
changed, newHook = self.moduleUtil.updateHook(hook, {"url": "http://gitlab.com/hook"})
self.assertEqual(changed, True)
self.assertEqual(type(newHook), ProjectHook)
self.assertEqual(newHook.url, "http://gitlab.com/hook")
changed, newHook = self.moduleUtil.updateHook(hook, {"url": "http://gitlab.com/hook"})
self.assertEqual(changed, False)
self.assertEqual(newHook.url, "http://gitlab.com/hook")
@with_httmock(resp_get_project)
@with_httmock(resp_find_project_hook)
@with_httmock(resp_delete_project_hook)
def test_delete_hook(self):
project = self.gitlab_instance.projects.get(1)
self.moduleUtil.existsHook(project, "http://example.com/hook")
rvalue = self.moduleUtil.deleteHook()
self.assertEqual(rvalue, None)
|
unknown
|
codeparrot/codeparrot-clean
| ||
from django.db.utils import DatabaseError
from django.db.backends.sqlite3.schema import DatabaseSchemaEditor
class SpatialiteSchemaEditor(DatabaseSchemaEditor):
sql_add_geometry_column = (
"SELECT AddGeometryColumn(%(table)s, %(column)s, %(srid)s, "
"%(geom_type)s, %(dim)s, %(null)s)"
)
sql_add_spatial_index = "SELECT CreateSpatialIndex(%(table)s, %(column)s)"
sql_drop_spatial_index = "DROP TABLE idx_%(table)s_%(column)s"
sql_remove_geometry_metadata = "SELECT DiscardGeometryColumn(%(table)s, %(column)s)"
sql_discard_geometry_columns = "DELETE FROM %(geom_table)s WHERE f_table_name = %(table)s"
sql_update_geometry_columns = (
"UPDATE %(geom_table)s SET f_table_name = %(new_table)s "
"WHERE f_table_name = %(old_table)s"
)
geometry_tables = [
"geometry_columns",
"geometry_columns_auth",
"geometry_columns_time",
"geometry_columns_statistics",
]
def __init__(self, *args, **kwargs):
super(SpatialiteSchemaEditor, self).__init__(*args, **kwargs)
self.geometry_sql = []
def geo_quote_name(self, name):
return self.connection.ops.geo_quote_name(name)
def column_sql(self, model, field, include_default=False):
from django.contrib.gis.db.models.fields import GeometryField
if not isinstance(field, GeometryField):
return super(SpatialiteSchemaEditor, self).column_sql(model, field, include_default)
# Geometry columns are created by the `AddGeometryColumn` function
self.geometry_sql.append(
self.sql_add_geometry_column % {
"table": self.geo_quote_name(model._meta.db_table),
"column": self.geo_quote_name(field.column),
"srid": field.srid,
"geom_type": self.geo_quote_name(field.geom_type),
"dim": field.dim,
"null": int(not field.null),
}
)
if field.spatial_index:
self.geometry_sql.append(
self.sql_add_spatial_index % {
"table": self.quote_name(model._meta.db_table),
"column": self.quote_name(field.column),
}
)
return None, None
def remove_geometry_metadata(self, model, field):
self.execute(
self.sql_remove_geometry_metadata % {
"table": self.quote_name(model._meta.db_table),
"column": self.quote_name(field.column),
}
)
self.execute(
self.sql_drop_spatial_index % {
"table": model._meta.db_table,
"column": field.column,
}
)
def create_model(self, model):
super(SpatialiteSchemaEditor, self).create_model(model)
# Create geometry columns
for sql in self.geometry_sql:
self.execute(sql)
self.geometry_sql = []
def delete_model(self, model, **kwargs):
from django.contrib.gis.db.models.fields import GeometryField
# Drop spatial metadata (dropping the table does not automatically remove them)
for field in model._meta.local_fields:
if isinstance(field, GeometryField):
self.remove_geometry_metadata(model, field)
# Make sure all geom stuff is gone
for geom_table in self.geometry_tables:
try:
self.execute(
self.sql_discard_geometry_columns % {
"geom_table": geom_table,
"table": self.quote_name(model._meta.db_table),
}
)
except DatabaseError:
pass
super(SpatialiteSchemaEditor, self).delete_model(model, **kwargs)
def add_field(self, model, field):
from django.contrib.gis.db.models.fields import GeometryField
if isinstance(field, GeometryField):
# Populate self.geometry_sql
self.column_sql(model, field)
for sql in self.geometry_sql:
self.execute(sql)
self.geometry_sql = []
else:
super(SpatialiteSchemaEditor, self).add_field(model, field)
def remove_field(self, model, field):
from django.contrib.gis.db.models.fields import GeometryField
# NOTE: If the field is a geometry field, the table is just recreated,
# the parent's remove_field can't be used cause it will skip the
# recreation if the field does not have a database type. Geometry fields
# do not have a db type cause they are added and removed via stored
# procedures.
if isinstance(field, GeometryField):
self._remake_table(model, delete_fields=[field])
else:
super(SpatialiteSchemaEditor, self).remove_field(model, field)
def alter_db_table(self, model, old_db_table, new_db_table):
from django.contrib.gis.db.models.fields import GeometryField
# Remove geometry-ness from temp table
for field in model._meta.local_fields:
if isinstance(field, GeometryField):
self.execute(
self.sql_remove_geometry_metadata % {
"table": self.quote_name(old_db_table),
"column": self.quote_name(field.column),
}
)
# Alter table
super(SpatialiteSchemaEditor, self).alter_db_table(model, old_db_table, new_db_table)
# Repoint any straggler names
for geom_table in self.geometry_tables:
try:
self.execute(
self.sql_update_geometry_columns % {
"geom_table": geom_table,
"old_table": self.quote_name(old_db_table),
"new_table": self.quote_name(new_db_table),
}
)
except DatabaseError:
pass
# Re-add geometry-ness and rename spatial index tables
for field in model._meta.local_fields:
if isinstance(field, GeometryField):
self.execute(self.sql_add_geometry_column % {
"table": self.geo_quote_name(new_db_table),
"column": self.geo_quote_name(field.column),
"srid": field.srid,
"geom_type": self.geo_quote_name(field.geom_type),
"dim": field.dim,
"null": int(not field.null),
})
if getattr(field, 'spatial_index', False):
self.execute(self.sql_rename_table % {
"old_table": self.quote_name("idx_%s_%s" % (old_db_table, field.column)),
"new_table": self.quote_name("idx_%s_%s" % (new_db_table, field.column)),
})
|
unknown
|
codeparrot/codeparrot-clean
| ||
# (c) 2014, Brian Coca, Josh Drake, et al
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
cache: jsonfile
short_description: JSON formatted files.
description:
- This cache uses JSON formatted, per host, files saved to the filesystem.
version_added: "1.9"
author: Ansible Core (@ansible-core)
options:
_uri:
required: True
description:
- Path in which the cache plugin will save the JSON files
env:
- name: ANSIBLE_CACHE_PLUGIN_CONNECTION
ini:
- key: fact_caching_connection
section: defaults
_prefix:
description: User defined prefix to use when creating the JSON files
env:
- name: ANSIBLE_CACHE_PLUGIN_PREFIX
ini:
- key: fact_caching_prefix
section: defaults
_timeout:
default: 86400
description: Expiration timeout for the cache plugin data
env:
- name: ANSIBLE_CACHE_PLUGIN_TIMEOUT
ini:
- key: fact_caching_timeout
section: defaults
type: integer
'''
import codecs
import json
from ansible.parsing.ajson import AnsibleJSONEncoder, AnsibleJSONDecoder
from ansible.plugins.cache import BaseFileCacheModule
class CacheModule(BaseFileCacheModule):
"""
A caching module backed by json files.
"""
def _load(self, filepath):
# Valid JSON is always UTF-8 encoded.
with codecs.open(filepath, 'r', encoding='utf-8') as f:
return json.load(f, cls=AnsibleJSONDecoder)
def _dump(self, value, filepath):
with codecs.open(filepath, 'w', encoding='utf-8') as f:
f.write(json.dumps(value, cls=AnsibleJSONEncoder, sort_keys=True, indent=4))
|
unknown
|
codeparrot/codeparrot-clean
| ||
{
"css": null,
"js": [],
"start": 0,
"end": 324,
"type": "Root",
"fragment": {
"type": "Fragment",
"nodes": [
{
"type": "RegularElement",
"start": 0,
"end": 14,
"name": "div",
"name_loc": {
"start": {
"line": 1,
"column": 1,
"character": 1
},
"end": {
"line": 1,
"column": 4,
"character": 4
}
},
"attributes": [
{
"type": "Attribute",
"start": 5,
"end": 7,
"name": "",
"name_loc": {
"start": {
"line": 1,
"column": 6,
"character": 6
},
"end": {
"line": 1,
"column": 6,
"character": 6
}
},
"value": {
"type": "ExpressionTag",
"start": 6,
"end": 6,
"expression": {
"type": "Identifier",
"name": "",
"start": 6,
"end": 6,
"loc": {
"start": {
"line": 1,
"column": 6,
"character": 6
},
"end": {
"line": 1,
"column": 6,
"character": 6
}
}
}
}
}
],
"fragment": {
"type": "Fragment",
"nodes": []
}
},
{
"type": "Text",
"start": 14,
"end": 15,
"raw": "\n",
"data": "\n"
},
{
"type": "RegularElement",
"start": 15,
"end": 33,
"name": "div",
"name_loc": {
"start": {
"line": 2,
"column": 1,
"character": 16
},
"end": {
"line": 2,
"column": 4,
"character": 19
}
},
"attributes": [
{
"type": "Attribute",
"start": 20,
"end": 26,
"name": "foo",
"name_loc": {
"start": {
"line": 2,
"column": 5,
"character": 20
},
"end": {
"line": 2,
"column": 8,
"character": 23
}
},
"value": {
"type": "ExpressionTag",
"start": 24,
"end": 26,
"expression": {
"type": "Identifier",
"start": 25,
"end": 25,
"name": ""
}
}
}
],
"fragment": {
"type": "Fragment",
"nodes": []
}
},
{
"type": "Text",
"start": 33,
"end": 35,
"raw": "\n\n",
"data": "\n\n"
},
{
"type": "RegularElement",
"start": 35,
"end": 55,
"name": "div",
"name_loc": {
"start": {
"line": 4,
"column": 1,
"character": 36
},
"end": {
"line": 4,
"column": 4,
"character": 39
}
},
"attributes": [
{
"type": "Attribute",
"start": 40,
"end": 48,
"name": "foo",
"name_loc": {
"start": {
"line": 4,
"column": 5,
"character": 40
},
"end": {
"line": 4,
"column": 8,
"character": 43
}
},
"value": {
"type": "ExpressionTag",
"start": 44,
"end": 48,
"expression": {
"type": "Identifier",
"start": 45,
"end": 47,
"name": ""
}
}
}
],
"fragment": {
"type": "Fragment",
"nodes": []
}
},
{
"type": "Text",
"start": 55,
"end": 56,
"raw": "\n",
"data": "\n"
},
{
"type": "RegularElement",
"start": 56,
"end": 80,
"name": "div",
"name_loc": {
"start": {
"line": 5,
"column": 1,
"character": 57
},
"end": {
"line": 5,
"column": 4,
"character": 60
}
},
"attributes": [
{
"type": "Attribute",
"start": 61,
"end": 73,
"name": "foo",
"name_loc": {
"start": {
"line": 5,
"column": 5,
"character": 61
},
"end": {
"line": 5,
"column": 8,
"character": 64
}
},
"value": {
"type": "ExpressionTag",
"start": 65,
"end": 73,
"expression": {
"type": "Identifier",
"start": 66,
"end": 72,
"name": ""
}
}
}
],
"fragment": {
"type": "Fragment",
"nodes": []
}
},
{
"type": "Text",
"start": 80,
"end": 81,
"raw": "\n",
"data": "\n"
},
{
"type": "Component",
"start": 81,
"end": 113,
"name": "Component",
"name_loc": {
"start": {
"line": 6,
"column": 1,
"character": 82
},
"end": {
"line": 6,
"column": 10,
"character": 91
}
},
"attributes": [
{
"type": "Attribute",
"start": 92,
"end": 110,
"name": "onclick",
"name_loc": {
"start": {
"line": 6,
"column": 11,
"character": 92
},
"end": {
"line": 6,
"column": 18,
"character": 99
}
},
"value": {
"type": "ExpressionTag",
"start": 100,
"end": 110,
"expression": {
"type": "Identifier",
"start": 101,
"end": 109,
"name": ""
}
}
}
],
"fragment": {
"type": "Fragment",
"nodes": []
}
},
{
"type": "Text",
"start": 113,
"end": 115,
"raw": "\n\n",
"data": "\n\n"
},
{
"type": "RegularElement",
"start": 115,
"end": 140,
"name": "input",
"name_loc": {
"start": {
"line": 8,
"column": 1,
"character": 116
},
"end": {
"line": 8,
"column": 6,
"character": 121
}
},
"attributes": [
{
"start": 122,
"end": 137,
"type": "BindDirective",
"name": "value",
"name_loc": {
"start": {
"line": 8,
"column": 7,
"character": 122
},
"end": {
"line": 8,
"column": 17,
"character": 132
}
},
"expression": {
"type": "Identifier",
"start": 134,
"end": 136,
"name": ""
},
"modifiers": []
}
],
"fragment": {
"type": "Fragment",
"nodes": []
}
},
{
"type": "Text",
"start": 140,
"end": 145,
"raw": "\n\nasd",
"data": "\n\nasd"
},
{
"type": "ExpressionTag",
"start": 145,
"end": 149,
"expression": {
"type": "Identifier",
"start": 146,
"end": 148,
"name": ""
}
},
{
"type": "Text",
"start": 149,
"end": 153,
"raw": "asd\n",
"data": "asd\n"
},
{
"type": "ExpressionTag",
"start": 153,
"end": 164,
"expression": {
"type": "Identifier",
"start": 154,
"end": 163,
"name": ""
}
},
{
"type": "Text",
"start": 164,
"end": 166,
"raw": "\n\n",
"data": "\n\n"
},
{
"type": "IfBlock",
"elseif": false,
"start": 166,
"end": 179,
"test": {
"type": "Identifier",
"start": 171,
"end": 173,
"name": ""
},
"consequent": {
"type": "Fragment",
"nodes": []
},
"alternate": null
},
{
"type": "Text",
"start": 179,
"end": 181,
"raw": "\n\n",
"data": "\n\n"
},
{
"type": "EachBlock",
"start": 181,
"end": 217,
"expression": {
"type": "Identifier",
"start": 188,
"end": 193,
"loc": {
"start": {
"line": 15,
"column": 7
},
"end": {
"line": 15,
"column": 12
}
},
"name": "array"
},
"body": {
"type": "Fragment",
"nodes": []
},
"context": {
"type": "Identifier",
"name": "item",
"start": 197,
"end": 201,
"loc": {
"start": {
"line": 15,
"column": 16,
"character": 197
},
"end": {
"line": 15,
"column": 20,
"character": 201
}
}
},
"key": {
"type": "Identifier",
"start": 203,
"end": 208,
"name": ""
}
},
{
"type": "Text",
"start": 217,
"end": 219,
"raw": "\n\n",
"data": "\n\n"
},
{
"type": "EachBlock",
"start": 219,
"end": 246,
"expression": {
"type": "Identifier",
"name": "",
"start": 226,
"end": 230
},
"body": {
"type": "Fragment",
"nodes": []
},
"context": {
"type": "Identifier",
"name": "item",
"start": 234,
"end": 238,
"loc": {
"start": {
"line": 17,
"column": 15,
"character": 234
},
"end": {
"line": 17,
"column": 19,
"character": 238
}
}
}
},
{
"type": "Text",
"start": 246,
"end": 248,
"raw": "\n\n",
"data": "\n\n"
},
{
"type": "AwaitBlock",
"start": 248,
"end": 267,
"expression": {
"type": "Identifier",
"start": 256,
"end": 258,
"name": ""
},
"value": null,
"error": null,
"pending": {
"type": "Fragment",
"nodes": []
},
"then": null,
"catch": null
},
{
"type": "Text",
"start": 267,
"end": 269,
"raw": "\n\n",
"data": "\n\n"
},
{
"type": "AwaitBlock",
"start": 269,
"end": 295,
"expression": {
"type": "Identifier",
"name": "",
"start": 277,
"end": 279
},
"value": {
"type": "Identifier",
"name": "y",
"start": 285,
"end": 286,
"loc": {
"start": {
"line": 21,
"column": 16,
"character": 285
},
"end": {
"line": 21,
"column": 17,
"character": 286
}
}
},
"error": null,
"pending": null,
"then": {
"type": "Fragment",
"nodes": []
},
"catch": null
},
{
"type": "Text",
"start": 295,
"end": 297,
"raw": "\n\n",
"data": "\n\n"
},
{
"type": "AwaitBlock",
"start": 297,
"end": 324,
"expression": {
"type": "Identifier",
"name": "",
"start": 305,
"end": 307
},
"value": null,
"error": {
"type": "Identifier",
"name": "y",
"start": 314,
"end": 315,
"loc": {
"start": {
"line": 23,
"column": 17,
"character": 314
},
"end": {
"line": 23,
"column": 18,
"character": 315
}
}
},
"pending": null,
"then": null,
"catch": {
"type": "Fragment",
"nodes": []
}
}
]
},
"options": null
}
|
json
|
github
|
https://github.com/sveltejs/svelte
|
packages/svelte/tests/parser-modern/samples/loose-invalid-expression/output.json
|
# -*- coding: utf-8 -*-
import gettext as gettext_module
import os
import shutil
import stat
import unittest
from django.core.management import (
CommandError, call_command, execute_from_command_line,
)
from django.core.management.utils import find_command
from django.test import SimpleTestCase, override_settings
from django.test.utils import captured_stderr, captured_stdout
from django.utils import translation
from django.utils._os import upath
from django.utils.encoding import force_text
from django.utils.six import StringIO
from django.utils.translation import ugettext
has_msgfmt = find_command('msgfmt')
@unittest.skipUnless(has_msgfmt, 'msgfmt is mandatory for compilation tests')
class MessageCompilationTests(SimpleTestCase):
test_dir = os.path.abspath(os.path.join(os.path.dirname(upath(__file__)), 'commands'))
def setUp(self):
self._cwd = os.getcwd()
self.addCleanup(os.chdir, self._cwd)
os.chdir(self.test_dir)
def _rmrf(self, dname):
if os.path.commonprefix([self.test_dir, os.path.abspath(dname)]) != self.test_dir:
return
shutil.rmtree(dname)
def rmfile(self, filepath):
if os.path.exists(filepath):
os.remove(filepath)
class PoFileTests(MessageCompilationTests):
LOCALE = 'es_AR'
MO_FILE = 'locale/%s/LC_MESSAGES/django.mo' % LOCALE
def test_bom_rejection(self):
with self.assertRaises(CommandError) as cm:
call_command('compilemessages', locale=[self.LOCALE], stdout=StringIO())
self.assertIn("file has a BOM (Byte Order Mark)", cm.exception.args[0])
self.assertFalse(os.path.exists(self.MO_FILE))
def test_no_write_access(self):
mo_file_en = 'locale/en/LC_MESSAGES/django.mo'
err_buffer = StringIO()
# put file in read-only mode
old_mode = os.stat(mo_file_en).st_mode
os.chmod(mo_file_en, stat.S_IREAD)
try:
call_command('compilemessages', locale=['en'], stderr=err_buffer, verbosity=0)
err = err_buffer.getvalue()
self.assertIn("not writable location", err)
finally:
os.chmod(mo_file_en, old_mode)
class PoFileContentsTests(MessageCompilationTests):
# Ticket #11240
LOCALE = 'fr'
MO_FILE = 'locale/%s/LC_MESSAGES/django.mo' % LOCALE
def setUp(self):
super(PoFileContentsTests, self).setUp()
self.addCleanup(os.unlink, os.path.join(self.test_dir, self.MO_FILE))
def test_percent_symbol_in_po_file(self):
call_command('compilemessages', locale=[self.LOCALE], stdout=StringIO())
self.assertTrue(os.path.exists(self.MO_FILE))
class PercentRenderingTests(MessageCompilationTests):
# Ticket #11240 -- Testing rendering doesn't belong here but we are trying
# to keep tests for all the stack together
LOCALE = 'it'
MO_FILE = 'locale/%s/LC_MESSAGES/django.mo' % LOCALE
def setUp(self):
super(PercentRenderingTests, self).setUp()
self.addCleanup(os.unlink, os.path.join(self.test_dir, self.MO_FILE))
def test_percent_symbol_escaping(self):
with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]):
from django.template import Template, Context
call_command('compilemessages', locale=[self.LOCALE], stdout=StringIO())
with translation.override(self.LOCALE):
t = Template('{% load i18n %}{% trans "Looks like a str fmt spec %% o but shouldn\'t be interpreted as such" %}')
rendered = t.render(Context({}))
self.assertEqual(rendered, 'IT translation contains %% for the above string')
t = Template('{% load i18n %}{% trans "Completed 50%% of all the tasks" %}')
rendered = t.render(Context({}))
self.assertEqual(rendered, 'IT translation of Completed 50%% of all the tasks')
class MultipleLocaleCompilationTests(MessageCompilationTests):
MO_FILE_HR = None
MO_FILE_FR = None
def setUp(self):
super(MultipleLocaleCompilationTests, self).setUp()
localedir = os.path.join(self.test_dir, 'locale')
self.MO_FILE_HR = os.path.join(localedir, 'hr/LC_MESSAGES/django.mo')
self.MO_FILE_FR = os.path.join(localedir, 'fr/LC_MESSAGES/django.mo')
self.addCleanup(self.rmfile, os.path.join(localedir, self.MO_FILE_HR))
self.addCleanup(self.rmfile, os.path.join(localedir, self.MO_FILE_FR))
def test_one_locale(self):
with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]):
call_command('compilemessages', locale=['hr'], stdout=StringIO())
self.assertTrue(os.path.exists(self.MO_FILE_HR))
def test_multiple_locales(self):
with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]):
call_command('compilemessages', locale=['hr', 'fr'], stdout=StringIO())
self.assertTrue(os.path.exists(self.MO_FILE_HR))
self.assertTrue(os.path.exists(self.MO_FILE_FR))
class ExcludedLocaleCompilationTests(MessageCompilationTests):
test_dir = os.path.abspath(os.path.join(os.path.dirname(upath(__file__)), 'exclude'))
MO_FILE = 'locale/%s/LC_MESSAGES/django.mo'
def setUp(self):
super(ExcludedLocaleCompilationTests, self).setUp()
shutil.copytree('canned_locale', 'locale')
self.addCleanup(self._rmrf, os.path.join(self.test_dir, 'locale'))
def test_command_help(self):
with captured_stdout(), captured_stderr():
# `call_command` bypasses the parser; by calling
# `execute_from_command_line` with the help subcommand we
# ensure that there are no issues with the parser itself.
execute_from_command_line(['django-admin', 'help', 'compilemessages'])
def test_one_locale_excluded(self):
call_command('compilemessages', exclude=['it'], stdout=StringIO())
self.assertTrue(os.path.exists(self.MO_FILE % 'en'))
self.assertTrue(os.path.exists(self.MO_FILE % 'fr'))
self.assertFalse(os.path.exists(self.MO_FILE % 'it'))
def test_multiple_locales_excluded(self):
call_command('compilemessages', exclude=['it', 'fr'], stdout=StringIO())
self.assertTrue(os.path.exists(self.MO_FILE % 'en'))
self.assertFalse(os.path.exists(self.MO_FILE % 'fr'))
self.assertFalse(os.path.exists(self.MO_FILE % 'it'))
def test_one_locale_excluded_with_locale(self):
call_command('compilemessages', locale=['en', 'fr'], exclude=['fr'], stdout=StringIO())
self.assertTrue(os.path.exists(self.MO_FILE % 'en'))
self.assertFalse(os.path.exists(self.MO_FILE % 'fr'))
self.assertFalse(os.path.exists(self.MO_FILE % 'it'))
def test_multiple_locales_excluded_with_locale(self):
call_command('compilemessages', locale=['en', 'fr', 'it'], exclude=['fr', 'it'],
stdout=StringIO())
self.assertTrue(os.path.exists(self.MO_FILE % 'en'))
self.assertFalse(os.path.exists(self.MO_FILE % 'fr'))
self.assertFalse(os.path.exists(self.MO_FILE % 'it'))
class CompilationErrorHandling(MessageCompilationTests):
LOCALE = 'ja'
MO_FILE = 'locale/%s/LC_MESSAGES/django.mo' % LOCALE
def setUp(self):
super(CompilationErrorHandling, self).setUp()
self.addCleanup(self.rmfile, os.path.join(self.test_dir, self.MO_FILE))
def test_error_reported_by_msgfmt(self):
with self.assertRaises(CommandError):
call_command('compilemessages', locale=[self.LOCALE], stdout=StringIO())
class ProjectAndAppTests(MessageCompilationTests):
LOCALE = 'ru'
PROJECT_MO_FILE = 'locale/%s/LC_MESSAGES/django.mo' % LOCALE
APP_MO_FILE = 'app_with_locale/locale/%s/LC_MESSAGES/django.mo' % LOCALE
def setUp(self):
super(ProjectAndAppTests, self).setUp()
self.addCleanup(self.rmfile, os.path.join(self.test_dir, self.PROJECT_MO_FILE))
self.addCleanup(self.rmfile, os.path.join(self.test_dir, self.APP_MO_FILE))
class FuzzyTranslationTest(ProjectAndAppTests):
def setUp(self):
super(FuzzyTranslationTest, self).setUp()
gettext_module._translations = {} # flush cache or test will be useless
def test_nofuzzy_compiling(self):
with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]):
call_command('compilemessages', locale=[self.LOCALE], stdout=StringIO())
with translation.override(self.LOCALE):
self.assertEqual(ugettext('Lenin'), force_text('Ленин'))
self.assertEqual(ugettext('Vodka'), force_text('Vodka'))
def test_fuzzy_compiling(self):
with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]):
call_command('compilemessages', locale=[self.LOCALE], fuzzy=True, stdout=StringIO())
with translation.override(self.LOCALE):
self.assertEqual(ugettext('Lenin'), force_text('Ленин'))
self.assertEqual(ugettext('Vodka'), force_text('Водка'))
class AppCompilationTest(ProjectAndAppTests):
def test_app_locale_compiled(self):
call_command('compilemessages', locale=[self.LOCALE], stdout=StringIO())
self.assertTrue(os.path.exists(self.PROJECT_MO_FILE))
self.assertTrue(os.path.exists(self.APP_MO_FILE))
|
unknown
|
codeparrot/codeparrot-clean
| ||
from datetime import datetime
from sqlalchemy.orm import relationship, backref
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.types import Integer, Unicode, DateTime
from spendb.core import db, url_for
from spendb.model.dataset import Dataset
class Run(db.Model):
""" A run is a generic grouping object for background operations
that perform logging to the frontend. """
__tablename__ = 'run'
# Status values
STATUS_RUNNING = 'running'
STATUS_COMPLETE = 'complete'
STATUS_FAILED = 'failed'
id = Column(Integer, primary_key=True)
operation = Column(Unicode())
status = Column(Unicode())
source = Column(Unicode())
time_start = Column(DateTime, default=datetime.utcnow)
time_end = Column(DateTime)
dataset_id = Column(Integer, ForeignKey('dataset.id'), nullable=True)
dataset = relationship(Dataset,
backref=backref('runs',
order_by='Run.time_start.desc()',
lazy='dynamic'))
def __init__(self, operation, status, dataset):
self.operation = operation
self.status = status
self.dataset = dataset
def to_dict(self):
return {
'id': self.id,
'api_url': url_for('runs_api.view', dataset=self.dataset.name,
id=self.id),
'operation': self.operation,
'status': self.status,
'source': self.source,
'time_start': self.time_start,
'time_end': self.time_end
}
@classmethod
def all(cls, dataset):
q = db.session.query(cls).filter_by(dataset=dataset)
return q.order_by(cls.time_start.asc())
@classmethod
def by_id(cls, dataset, id):
return cls.all(dataset).filter_by(id=id).first()
def __repr__(self):
return "<Run(%r, %r, %r)>" % (self.source, self.id, self.status)
|
unknown
|
codeparrot/codeparrot-clean
| ||
# This file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = "j. F Y"
TIME_FORMAT = "H:i"
DATETIME_FORMAT = "j. F Y H:i"
YEAR_MONTH_FORMAT = "F Y"
MONTH_DAY_FORMAT = "j. F"
SHORT_DATE_FORMAT = "d.m.Y"
SHORT_DATETIME_FORMAT = "d.m.Y H:i"
FIRST_DAY_OF_WEEK = 1 # Monday
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see https://docs.python.org/library/datetime.html#strftime-strptime-behavior
DATE_INPUT_FORMATS = [
"%d.%m.%Y", # '25.10.2006'
"%d.%m.%y", # '25.10.06'
# "%d. %B %Y", # '25. October 2006'
# "%d. %b. %Y", # '25. Oct. 2006'
]
DATETIME_INPUT_FORMATS = [
"%d.%m.%Y %H:%M:%S", # '25.10.2006 14:30:59'
"%d.%m.%Y %H:%M:%S.%f", # '25.10.2006 14:30:59.000200'
"%d.%m.%Y %H:%M", # '25.10.2006 14:30'
]
# Swiss number formatting can vary based on context (e.g. Fr. 23.50 vs 22,5 m).
# Django does not support context-specific formatting and uses generic
# separators.
DECIMAL_SEPARATOR = ","
THOUSAND_SEPARATOR = "\xa0" # non-breaking space
NUMBER_GROUPING = 3
|
python
|
github
|
https://github.com/django/django
|
django/conf/locale/de_CH/formats.py
|
/*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.api.fir.test.cases.generated.cases.components.expressionTypeProvider;
import com.intellij.testFramework.TestDataPath;
import org.jetbrains.kotlin.test.util.KtTestUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.analysis.api.fir.test.configurators.AnalysisApiFirTestConfiguratorFactory;
import org.jetbrains.kotlin.analysis.test.framework.test.configurators.AnalysisApiTestConfiguratorFactoryData;
import org.jetbrains.kotlin.analysis.test.framework.test.configurators.AnalysisApiTestConfigurator;
import org.jetbrains.kotlin.analysis.test.framework.test.configurators.TestModuleKind;
import org.jetbrains.kotlin.analysis.test.framework.test.configurators.FrontendKind;
import org.jetbrains.kotlin.analysis.test.framework.test.configurators.AnalysisSessionMode;
import org.jetbrains.kotlin.analysis.test.framework.test.configurators.AnalysisApiMode;
import org.jetbrains.kotlin.analysis.api.impl.base.test.cases.components.expressionTypeProvider.AbstractExpectedExpressionTypeTest;
import org.jetbrains.kotlin.test.TestMetadata;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.regex.Pattern;
/** This class is generated by {@link org.jetbrains.kotlin.generators.tests.analysis.api.GenerateAnalysisApiTestsKt}. DO NOT MODIFY MANUALLY */
@SuppressWarnings("all")
@TestMetadata("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType")
@TestDataPath("$PROJECT_ROOT")
public class FirIdeNormalAnalysisSourceModuleExpectedExpressionTypeTestGenerated extends AbstractExpectedExpressionTypeTest {
@NotNull
@Override
public AnalysisApiTestConfigurator getConfigurator() {
return AnalysisApiFirTestConfiguratorFactory.INSTANCE.createConfigurator(
new AnalysisApiTestConfiguratorFactoryData(
FrontendKind.Fir,
TestModuleKind.Source,
AnalysisSessionMode.Normal,
AnalysisApiMode.Ide
)
);
}
@Test
@TestMetadata("afterExclOperand.kt")
public void testAfterExclOperand() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/afterExclOperand.kt");
}
@Test
public void testAllFilesPresentInExpectedExpressionType() {
KtTestUtil.assertAllTestsPresentByMetadataWithExcluded(this.getClass(), new File("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType"), Pattern.compile("^(.+)\\.kt$"), null, true);
}
@Test
@TestMetadata("annotationPositionalArgument.kt")
public void testAnnotationPositionalArgument() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/annotationPositionalArgument.kt");
}
@Test
@TestMetadata("arrayAccessExpressionGet.kt")
public void testArrayAccessExpressionGet() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/arrayAccessExpressionGet.kt");
}
@Test
@TestMetadata("arrayAccessExpressionGetWithTypeParameters.kt")
public void testArrayAccessExpressionGetWithTypeParameters() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/arrayAccessExpressionGetWithTypeParameters.kt");
}
@Test
@TestMetadata("arrayAccessExpressionSet.kt")
public void testArrayAccessExpressionSet() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/arrayAccessExpressionSet.kt");
}
@Test
@TestMetadata("arrayAccessExpressionSetWithTypeParameters.kt")
public void testArrayAccessExpressionSetWithTypeParameters() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/arrayAccessExpressionSetWithTypeParameters.kt");
}
@Test
@TestMetadata("callableReference_consumer.kt")
public void testCallableReference_consumer() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/callableReference_consumer.kt");
}
@Test
@TestMetadata("callableReference_function.kt")
public void testCallableReference_function() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/callableReference_function.kt");
}
@Test
@TestMetadata("collectionLiteralInAnnotation.kt")
public void testCollectionLiteralInAnnotation() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/collectionLiteralInAnnotation.kt");
}
@Test
@TestMetadata("conditionInWhenWithSubject.kt")
public void testConditionInWhenWithSubject() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/conditionInWhenWithSubject.kt");
}
@Test
@TestMetadata("conditionInWhenWithoutSubject.kt")
public void testConditionInWhenWithoutSubject() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/conditionInWhenWithoutSubject.kt");
}
@Test
@TestMetadata("delegatedConstructorCall.kt")
public void testDelegatedConstructorCall() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/delegatedConstructorCall.kt");
}
@Test
@TestMetadata("delegatedSuperEntry.kt")
public void testDelegatedSuperEntry() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/delegatedSuperEntry.kt");
}
@Test
@TestMetadata("elvisExpressionLeftOperand.kt")
public void testElvisExpressionLeftOperand() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/elvisExpressionLeftOperand.kt");
}
@Test
@TestMetadata("elvisExpressionLeftOperandWithoutExplicitType.kt")
public void testElvisExpressionLeftOperandWithoutExplicitType() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/elvisExpressionLeftOperandWithoutExplicitType.kt");
}
@Test
@TestMetadata("elvisExpressionRightOperand.kt")
public void testElvisExpressionRightOperand() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/elvisExpressionRightOperand.kt");
}
@Test
@TestMetadata("elvisExpressionRightOperandWithoutExplicitType.kt")
public void testElvisExpressionRightOperandWithoutExplicitType() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/elvisExpressionRightOperandWithoutExplicitType.kt");
}
@Test
@TestMetadata("enumEntryInitialization.kt")
public void testEnumEntryInitialization() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/enumEntryInitialization.kt");
}
@Test
@TestMetadata("enumEntryInitializationGeneric.kt")
public void testEnumEntryInitializationGeneric() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/enumEntryInitializationGeneric.kt");
}
@Test
@TestMetadata("firstVarargArgument.kt")
public void testFirstVarargArgument() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/firstVarargArgument.kt");
}
@Test
@TestMetadata("functionExpressionBody.kt")
public void testFunctionExpressionBody() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/functionExpressionBody.kt");
}
@Test
@TestMetadata("functionExpressionBodyBlockExpression.kt")
public void testFunctionExpressionBodyBlockExpression() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/functionExpressionBodyBlockExpression.kt");
}
@Test
@TestMetadata("functionExpressionBodyQualified.kt")
public void testFunctionExpressionBodyQualified() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/functionExpressionBodyQualified.kt");
}
@Test
@TestMetadata("functionExpressionBodyWithTypeFromRHS.kt")
public void testFunctionExpressionBodyWithTypeFromRHS() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/functionExpressionBodyWithTypeFromRHS.kt");
}
@Test
@TestMetadata("functionExpressionBodyWithoutExplicitType.kt")
public void testFunctionExpressionBodyWithoutExplicitType() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/functionExpressionBodyWithoutExplicitType.kt");
}
@Test
@TestMetadata("functionLambdaParam.kt")
public void testFunctionLambdaParam() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/functionLambdaParam.kt");
}
@Test
@TestMetadata("functionNamedlParam.kt")
public void testFunctionNamedlParam() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/functionNamedlParam.kt");
}
@Test
@TestMetadata("functionParamWithTypeParam.kt")
public void testFunctionParamWithTypeParam() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/functionParamWithTypeParam.kt");
}
@Test
@TestMetadata("functionPositionalParam.kt")
public void testFunctionPositionalParam() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/functionPositionalParam.kt");
}
@Test
@TestMetadata("functionPositionalParamQualified.kt")
public void testFunctionPositionalParamQualified() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/functionPositionalParamQualified.kt");
}
@Test
@TestMetadata("functionalTypeSubstitution.kt")
public void testFunctionalTypeSubstitution() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/functionalTypeSubstitution.kt");
}
@Test
@TestMetadata("ifCondition.kt")
public void testIfCondition() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/ifCondition.kt");
}
@Test
@TestMetadata("ifConditionQualified.kt")
public void testIfConditionQualified() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/ifConditionQualified.kt");
}
@Test
@TestMetadata("infixFunctionAsRegularCallParam.kt")
public void testInfixFunctionAsRegularCallParam() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/infixFunctionAsRegularCallParam.kt");
}
@Test
@TestMetadata("infixFunctionParam.kt")
public void testInfixFunctionParam() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/infixFunctionParam.kt");
}
@Test
@TestMetadata("infixFunctionParamQualified.kt")
public void testInfixFunctionParamQualified() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/infixFunctionParamQualified.kt");
}
@Test
@TestMetadata("infixFunctionTypeParameter.kt")
public void testInfixFunctionTypeParameter() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/infixFunctionTypeParameter.kt");
}
@Test
@TestMetadata("invokeOperatorCall.kt")
public void testInvokeOperatorCall() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/invokeOperatorCall.kt");
}
@Test
@TestMetadata("lambdaReturnToExplicitLabel.kt")
public void testLambdaReturnToExplicitLabel() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/lambdaReturnToExplicitLabel.kt");
}
@Test
@TestMetadata("lambdaReturnToImplicitLabel.kt")
public void testLambdaReturnToImplicitLabel() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/lambdaReturnToImplicitLabel.kt");
}
@Test
@TestMetadata("lambdaWithExplicitTypeFromVariable.kt")
public void testLambdaWithExplicitTypeFromVariable() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/lambdaWithExplicitTypeFromVariable.kt");
}
@Test
@TestMetadata("lambdaWithoutReturnNorExplicitType.kt")
public void testLambdaWithoutReturnNorExplicitType() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/lambdaWithoutReturnNorExplicitType.kt");
}
@Test
@TestMetadata("lastStatementInFunctionBlockBody.kt")
public void testLastStatementInFunctionBlockBody() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/lastStatementInFunctionBlockBody.kt");
}
@Test
@TestMetadata("lastStatementInLambda.kt")
public void testLastStatementInLambda() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/lastStatementInLambda.kt");
}
@Test
@TestMetadata("lastStatementInLambdaWithTypeMismatch.kt")
public void testLastStatementInLambdaWithTypeMismatch() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/lastStatementInLambdaWithTypeMismatch.kt");
}
@Test
@TestMetadata("lastStatementInLambdaWithoutExplicitType.kt")
public void testLastStatementInLambdaWithoutExplicitType() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/lastStatementInLambdaWithoutExplicitType.kt");
}
@Test
@TestMetadata("lastStatementInTry.kt")
public void testLastStatementInTry() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/lastStatementInTry.kt");
}
@Test
@TestMetadata("lastStatementInTryWithoutExplicitType.kt")
public void testLastStatementInTryWithoutExplicitType() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/lastStatementInTryWithoutExplicitType.kt");
}
@Test
@TestMetadata("multipleSpreadArguments.kt")
public void testMultipleSpreadArguments() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/multipleSpreadArguments.kt");
}
@Test
@TestMetadata("namedSpreadArgument.kt")
public void testNamedSpreadArgument() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/namedSpreadArgument.kt");
}
@Test
@TestMetadata("namedVarargArgument.kt")
public void testNamedVarargArgument() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/namedVarargArgument.kt");
}
@Test
@TestMetadata("overrideFunctionWithoutExplicitType.kt")
public void testOverrideFunctionWithoutExplicitType() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/overrideFunctionWithoutExplicitType.kt");
}
@Test
@TestMetadata("overrideFunctionWithoutExplicitTypeGeneric.kt")
public void testOverrideFunctionWithoutExplicitTypeGeneric() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/overrideFunctionWithoutExplicitTypeGeneric.kt");
}
@Test
@TestMetadata("overridePropertyGetterWithoutExplicitType.kt")
public void testOverridePropertyGetterWithoutExplicitType() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/overridePropertyGetterWithoutExplicitType.kt");
}
@Test
@TestMetadata("overridePropertyWithoutExplicitType.kt")
public void testOverridePropertyWithoutExplicitType() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/overridePropertyWithoutExplicitType.kt");
}
@Test
@TestMetadata("parameterDefaultValue.kt")
public void testParameterDefaultValue() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/parameterDefaultValue.kt");
}
@Test
@TestMetadata("propertyAssignmentQualified.kt")
public void testPropertyAssignmentQualified() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/propertyAssignmentQualified.kt");
}
@Test
@TestMetadata("propertyAssignmentThis.kt")
public void testPropertyAssignmentThis() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/propertyAssignmentThis.kt");
}
@Test
@TestMetadata("propertyDeclaration.kt")
public void testPropertyDeclaration() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/propertyDeclaration.kt");
}
@Test
@TestMetadata("propertyDeclarationNoExplicitType.kt")
public void testPropertyDeclarationNoExplicitType() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/propertyDeclarationNoExplicitType.kt");
}
@Test
@TestMetadata("propertyDeclarationQualified.kt")
public void testPropertyDeclarationQualified() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/propertyDeclarationQualified.kt");
}
@Test
@TestMetadata("propertyDeclarationWithSafeCast.kt")
public void testPropertyDeclarationWithSafeCast() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/propertyDeclarationWithSafeCast.kt");
}
@Test
@TestMetadata("propertyDeclarationWithTypeCast.kt")
public void testPropertyDeclarationWithTypeCast() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/propertyDeclarationWithTypeCast.kt");
}
@Test
@TestMetadata("propertyDeclarationWithTypeFromRHS.kt")
public void testPropertyDeclarationWithTypeFromRHS() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/propertyDeclarationWithTypeFromRHS.kt");
}
@Test
@TestMetadata("propertyDeclarationWithoutExplicitType.kt")
public void testPropertyDeclarationWithoutExplicitType() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/propertyDeclarationWithoutExplicitType.kt");
}
@Test
@TestMetadata("propertyGetter.kt")
public void testPropertyGetter() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/propertyGetter.kt");
}
@Test
@TestMetadata("propertyGetterExpressionBody.kt")
public void testPropertyGetterExpressionBody() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/propertyGetterExpressionBody.kt");
}
@Test
@TestMetadata("propertyGetterExpressionBodyGetterExpectedType.kt")
public void testPropertyGetterExpressionBodyGetterExpectedType() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/propertyGetterExpressionBodyGetterExpectedType.kt");
}
@Test
@TestMetadata("propertyGetterExpressionBodyNoExpectedType.kt")
public void testPropertyGetterExpressionBodyNoExpectedType() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/propertyGetterExpressionBodyNoExpectedType.kt");
}
@Test
@TestMetadata("rangeToEndChar.kt")
public void testRangeToEndChar() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/rangeToEndChar.kt");
}
@Test
@TestMetadata("rangeToEndInt.kt")
public void testRangeToEndInt() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/rangeToEndInt.kt");
}
@Test
@TestMetadata("rangeUntilEndChar.kt")
public void testRangeUntilEndChar() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/rangeUntilEndChar.kt");
}
@Test
@TestMetadata("rangeUntilEndInt.kt")
public void testRangeUntilEndInt() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/rangeUntilEndInt.kt");
}
@Test
@TestMetadata("returnFromFunction.kt")
public void testReturnFromFunction() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/returnFromFunction.kt");
}
@Test
@TestMetadata("returnFromFunctionQualifiedReceiver.kt")
public void testReturnFromFunctionQualifiedReceiver() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/returnFromFunctionQualifiedReceiver.kt");
}
@Test
@TestMetadata("returnFromFunctionQualifiedSelector.kt")
public void testReturnFromFunctionQualifiedSelector() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/returnFromFunctionQualifiedSelector.kt");
}
@Test
@TestMetadata("returnFromLambda.kt")
public void testReturnFromLambda() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/returnFromLambda.kt");
}
@Test
@TestMetadata("safeCallArgument.kt")
public void testSafeCallArgument() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/safeCallArgument.kt");
}
@Test
@TestMetadata("sam.kt")
public void testSam() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/sam.kt");
}
@Test
@TestMetadata("samAsArgument.kt")
public void testSamAsArgument() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/samAsArgument.kt");
}
@Test
@TestMetadata("samAsConstructorArgument.kt")
public void testSamAsConstructorArgument() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/samAsConstructorArgument.kt");
}
@Test
@TestMetadata("samAsReturn.kt")
public void testSamAsReturn() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/samAsReturn.kt");
}
@Test
@TestMetadata("samReferenceAsArgument.kt")
public void testSamReferenceAsArgument() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/samReferenceAsArgument.kt");
}
@Test
@TestMetadata("samReferenceAsVararg.kt")
public void testSamReferenceAsVararg() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/samReferenceAsVararg.kt");
}
@Test
@TestMetadata("samReferenceWithTypeCast.kt")
public void testSamReferenceWithTypeCast() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/samReferenceWithTypeCast.kt");
}
@Test
@TestMetadata("samWithExplicitTypeFromProperty.kt")
public void testSamWithExplicitTypeFromProperty() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/samWithExplicitTypeFromProperty.kt");
}
@Test
@TestMetadata("samWithReturnToExplicitLabel.kt")
public void testSamWithReturnToExplicitLabel() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/samWithReturnToExplicitLabel.kt");
}
@Test
@TestMetadata("samWithReturnToImplicitLabel.kt")
public void testSamWithReturnToImplicitLabel() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/samWithReturnToImplicitLabel.kt");
}
@Test
@TestMetadata("samWithTypeCast.kt")
public void testSamWithTypeCast() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/samWithTypeCast.kt");
}
@Test
@TestMetadata("secondVarargArgument.kt")
public void testSecondVarargArgument() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/secondVarargArgument.kt");
}
@Test
@TestMetadata("statementInIf.kt")
public void testStatementInIf() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/statementInIf.kt");
}
@Test
@TestMetadata("statementInIfBlockExpression.kt")
public void testStatementInIfBlockExpression() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/statementInIfBlockExpression.kt");
}
@Test
@TestMetadata("statementInIfWithoutExplicitType.kt")
public void testStatementInIfWithoutExplicitType() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/statementInIfWithoutExplicitType.kt");
}
@Test
@TestMetadata("statementInWhen.kt")
public void testStatementInWhen() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/statementInWhen.kt");
}
@Test
@TestMetadata("statementInWhenBlockExpression.kt")
public void testStatementInWhenBlockExpression() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/statementInWhenBlockExpression.kt");
}
@Test
@TestMetadata("statementInWhenWithoutExplicitType.kt")
public void testStatementInWhenWithoutExplicitType() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/statementInWhenWithoutExplicitType.kt");
}
@Test
@TestMetadata("throwExpression.kt")
public void testThrowExpression() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/throwExpression.kt");
}
@Test
@TestMetadata("variableAssignment.kt")
public void testVariableAssignment() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/variableAssignment.kt");
}
@Test
@TestMetadata("variableAssignmentQualified.kt")
public void testVariableAssignmentQualified() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/variableAssignmentQualified.kt");
}
@Test
@TestMetadata("whileCondition.kt")
public void testWhileCondition() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/whileCondition.kt");
}
@Test
@TestMetadata("whileConditionQualified.kt")
public void testWhileConditionQualified() {
runTest("analysis/analysis-api/testData/components/expressionTypeProvider/expectedExpressionType/whileConditionQualified.kt");
}
}
|
java
|
github
|
https://github.com/JetBrains/kotlin
|
analysis/analysis-api-fir/tests-gen/org/jetbrains/kotlin/analysis/api/fir/test/cases/generated/cases/components/expressionTypeProvider/FirIdeNormalAnalysisSourceModuleExpectedExpressionTypeTestGenerated.java
|
try:
from scipy import special
available_cpu = True
except ImportError as e:
available_cpu = False
_import_error = e
import math
import chainer
from chainer.backends import cuda
from chainer import function_node
from chainer import utils
from chainer.utils import type_check
class Ndtri(function_node.FunctionNode):
@property
def label(self):
return 'ndtri'
def check_type_forward(self, in_types):
type_check.expect(in_types.size() == 1)
type_check.expect(in_types[0].dtype.kind == 'f')
def forward_cpu(self, x):
if not available_cpu:
raise ImportError("SciPy is not available. Forward computation"
" of ndtri in CPU can not be done." +
str(_import_error))
self.retain_outputs((0,))
return utils.force_array(special.ndtri(x[0]), dtype=x[0].dtype),
def forward_gpu(self, x):
self.retain_outputs((0,))
return cuda.elementwise(
'T x', 'T y',
'y = normcdfinv(x)',
'elementwise_ndtri',
)(x[0]),
def backward(self, indexes, gy):
y, = self.get_retained_outputs()
sqrt_2pi = (2 * math.pi) ** 0.5
return sqrt_2pi * chainer.functions.exp(0.5 * y ** 2) * gy[0],
def ndtri(x):
"""Elementwise inverse function of ndtr.
.. note::
Forward computation in CPU can not be done if
`SciPy <https://www.scipy.org/>`_ is not available.
Args:
x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \
:class:`cupy.ndarray`): Input variable.
Returns:
~chainer.Variable: Output variable.
"""
return Ndtri().apply((x,))[0]
|
unknown
|
codeparrot/codeparrot-clean
| ||
# Copyright 2015 The Switch Authors. All rights reserved.
# Licensed under the Apache License, Version 2, which is in the LICENSE file.
"""
This modules writes out output tables with certain processing.
This tables are mostly useful for quick iterations when testing code.
"""
import os, time, sys
from pyomo.environ import *
from switch_mod.financials import *
from csv import reader
import matplotlib.pyplot as plt
import pandas as pd
from cycler import cycler
import switch_mod.export as export
def define_arguments(argparser):
argparser.add_argument(
"--export-marginal-costs", action='store_true', default=False,
help="Exports energy marginal costs in US$/MWh per load zone and timepoint, calculated as dual variable values from the energy balance constraint."
)
argparser.add_argument(
"--export-capacities", action='store_true', default=False,
help="Exports cummulative installed generating capacity in MW per technology per period."
)
argparser.add_argument(
"--export-tech-dispatch", action='store_true', default=False,
help="Exports dispatched capacity per generator technology in MW per timepoint."
)
argparser.add_argument(
"--export-reservoirs", action='store_true', default=False,
help="Exports final reservoir volumes in cubic meters per timepoint."
)
def define_components(mod):
#Define dual variables, so that marginal costs can be computed eventually
if not hasattr(mod, 'dual'):
mod.dual = Suffix(direction=Suffix.IMPORT)
def define_dynamic_components(mod):
#Separate the computation of Investment and Operations cost, for comparison with stochastic problem
import switch_mod.financials as fin
def calc_tp_costs_in_period(m, t):
return sum(
getattr(m, tp_cost)[t] * m.tp_weight_in_year[t]
for tp_cost in m.cost_components_tp)
def calc_annual_costs_in_period(m, p):
return sum(
getattr(m, annual_cost)[p]
for annual_cost in m.cost_components_annual)
mod.TotalInvestmentCost = Expression(rule=lambda m: sum(calc_annual_costs_in_period(m, p) * fin.uniform_series_to_present_value(
m.discount_rate, m.period_length_years[p]) * fin.future_to_present_value(
m.discount_rate, (m.period_start[p] - m.base_financial_year)) for p in m.PERIODS))
mod.TotalOperationsCost = Expression(rule=lambda m: sum(m.SystemCostPerPeriod[p] for p in m.PERIODS) - m.TotalInvestmentCost)
def post_solve(instance, outdir):
summaries_dir = os.path.join(outdir,"Summaries")
if not os.path.exists(summaries_dir):
os.makedirs(summaries_dir)
print "\nStarting to print summaries"
start=time.time()
if instance.options.export_marginal_costs:
"""
This table writes out the marginal costs of supplying energy in each timepoint in US$/MWh.
"""
print "marginal_costs_lz_tp.csv..."
export.write_table(
instance, instance.TIMEPOINTS, instance.LOAD_ZONES,
output_file=os.path.join(summaries_dir, "marginal_costs_lz_tp.csv"),
headings=("timepoint","load_zones","marginal_cost"),
values=lambda m, tp, lz: (m.tp_timestamp[tp], lz, m.dual[m.Energy_Balance[lz, tp]] / (m.tp_weight_in_year[tp] * uniform_series_to_present_value(
m.discount_rate, m.period_length_years[m.tp_period[tp]]) * future_to_present_value(
m.discount_rate, (m.period_start[m.tp_period[tp]] - m.base_financial_year)))
))
df = pd.read_csv('outputs/Summaries/marginal_costs_lz_tp.csv',sep='\t')
lz_dfs = []
for lz in instance.LOAD_ZONES:
lz_dfs.append(df[df.load_zones == lz].drop(['load_zones','timepoint'],axis=1).reset_index(drop=True))
lz_dfs[-1].columns = [lz]
DF = pd.concat(lz_dfs, axis=1)
fig = plt.figure(1)
mc_ax = fig.add_subplot(211)
# GO cycling through the rainbow to get line colours
cm = plt.get_cmap('gist_rainbow')
# You have to play with the color map and the line style list to get enough combinations for your particular plot
mc_ax.set_prop_cycle(cycler('linestyle',['-',':','--','-.']) * cycler('color',[cm(i/5.0) for i in range(0,6)]))
# to locate the legend: "loc" is the point of the legend for which you will specify cooridnates. These coords are specified in bbox_to_anchor (can be only 1 point or couple)
mc_plot = DF.plot(ax=mc_ax,linewidth=1.5).legend(loc='upper center', fontsize=10, bbox_to_anchor=(0.,-0.15,1.,-0.15), ncol=3, mode="expand")
plt.xticks([i*24 for i in range(1,len(instance.TIMEPOINTS)/24+1)],[instance.tp_timestamp[instance.TIMEPOINTS[i*24]] for i in range(1,len(instance.TIMEPOINTS)/24+1)],rotation=40,fontsize=7)
plt.savefig('outputs/Summaries/marginal_costs.pdf',bbox_extra_artists=(mc_plot,))
"""
This table writes out the fuel consumption in MMBTU per hour.
"""
# print "energy_produced_in_period_by_each_project.csv..."
# export.write_table(
# instance, instance.PERIODS, instance.PROJECTS,
# output_file=os.path.join(summaries_dir, "energy_produced_in_period_by_each_project.csv"),
# headings=("period", "project", "energy_produced_GWh"),
# values=lambda m, p, proj: (p, proj,) + tuple(
# sum(m.DispatchProj[proj,tp]*m.tp_weight[tp] for tp in m.PERIOD_TPS[p])/1000)
# )
# """
# This table writes out the fuel consumption in MMBTU per hour.
# """
# print "fuel_consumption_tp_hourly.csv..."
# export.write_table(
# instance, instance.TIMEPOINTS,
# output_file=os.path.join(summaries_dir, "fuel_consumption_tp_hourly.csv"),
# headings=("timepoint",) + tuple(f for f in instance.FUELS),
# values=lambda m, tp: (m.tp_timestamp[tp],) + tuple(
# sum(m.ProjFuelUseRate[proj, t, f] for (proj,t) in m.PROJ_WITH_FUEL_DISPATCH_POINTS
# if m.g_energy_source[m.proj_gen_tech[proj]] == f and t == tp)
# for f in m.FUELS)
# )
# """
# This table writes out the fuel consumption in total MMBTU consumed in each period.
# """
# print "fuel_consumption_periods_total.csv..."
# export.write_table(
# instance, instance.PERIODS,
# output_file=os.path.join(summaries_dir, "fuel_consumption_periods_total.csv"),
# headings=("period",) + tuple(f for f in instance.FUELS),
# values=lambda m, p: (p,) + tuple(
# sum(m.ProjFuelUseRate[proj, tp, f] * m.tp_weight[tp] for (proj, tp) in m.PROJ_WITH_FUEL_DISPATCH_POINTS
# if tp in m.PERIOD_TPS[p] and m.g_energy_source[m.proj_gen_tech[proj]] == f)
# for f in m.FUELS)
# )
if instance.options.export_capacities:
"""
This table writes out the capacity that it available in each period
by technology.
"""
print "build_proj_by_tech_p.csv..."
export.write_table(
instance, instance.GENERATION_TECHNOLOGIES,
output_file=os.path.join(summaries_dir, "build_proj_by_tech_p.csv"),
headings=("gentech","Legacy") + tuple(p for p in instance.PERIODS),
values=lambda m, g: (g, sum(m.BuildProj[proj, bldyr] for (proj, bldyr) in m.PROJECT_BUILDYEARS
if m.proj_gen_tech[proj] == g and bldyr not in m.PERIODS)) + tuple(
sum(m.ProjCapacity[proj, p] for proj in m.PROJECTS if m.proj_gen_tech[proj] == g)
for p in m.PERIODS)
)
DF = pd.read_csv('outputs/Summaries/build_proj_by_tech_p.csv',sep='\t').transpose()
DF.columns = DF.iloc[0]
DF=DF.drop('gentech')
fig = plt.figure(2)
tech_ax = fig.add_subplot(211)
# GO cycling through the rainbow to get line colours
cm = plt.get_cmap('gist_rainbow')
# You have to play with the color map and the line style list to get enough combinations for your particular plot
tech_ax.set_prop_cycle(cycler('color',[cm(i/7.0) for i in range(0,8)]))
# to locate the legend: "loc" is the point of the legend for which you will specify cooridnates. These coords are specified in bbox_to_anchor (can be only 1 point or couple)
tech_plot = DF.plot(ax=tech_ax,kind='bar').legend(loc='upper center', fontsize=10, bbox_to_anchor=(0.,-0.07,1.,-0.07), ncol=2, mode="expand")
plt.xticks(rotation=0,fontsize=12)
plt.savefig('outputs/Summaries/gentech_capacities.pdf',bbox_extra_artists=(tech_plot,))
if instance.options.export_tech_dispatch:
"""
This table writes out the aggregated dispatch of each gen tech on each timepoint.
"""
print "dispatch_proj_by_tech_tp.csv..."
export.write_table(
instance, instance.TIMEPOINTS,
output_file=os.path.join(summaries_dir, "dispatch_proj_by_tech_tp.csv"),
headings=("gentech",) + tuple(g for g in instance.GENERATION_TECHNOLOGIES) + ("total",),
values=lambda m, tp: (m.tp_timestamp[tp],) + tuple(
sum(m.DispatchProj[proj, t] for (proj, t) in m.PROJ_DISPATCH_POINTS
if m.proj_gen_tech[proj] == g and t == tp)
for g in m.GENERATION_TECHNOLOGIES) + (
sum(m.DispatchProj[proj, t] for (proj, t) in m.PROJ_DISPATCH_POINTS if t == tp),)
)
DF = pd.read_csv('outputs/Summaries/dispatch_proj_by_tech_tp.csv',sep='\t').drop(['gentech'],axis=1)
fig = plt.figure(3)
dis_ax = fig.add_subplot(211)
# GO cycling through the rainbow to get line colours
cm = plt.get_cmap('gist_rainbow')
# You have to play with the color map and the line style list to get enough combinations for your particular plot
dis_ax.set_prop_cycle(cycler('linestyle',['-','--',':']) * cycler('color',[cm(i/5.0) for i in range(0,6)]))
# to locate the legend: "loc" is the point of the legend for which you will specify cooridnates. These coords are specified in bbox_to_anchor (can be only 1 point or couple)
dis_plot = DF.plot(ax=dis_ax,linewidth=1.5).legend(loc='upper center', fontsize=10, bbox_to_anchor=(0.,-0.15,1.,-0.15), ncol=2, mode="expand")
plt.xticks([i*5 for i in range(1,len(instance.TIMEPOINTS)/5+1)],[instance.tp_timestamp[instance.TIMEPOINTS[i*5]] for i in range(1,len(instance.TIMEPOINTS)/5+1)],rotation=40,fontsize=7)
plt.savefig('outputs/Summaries/gentech_dispatch.pdf',bbox_extra_artists=(dis_plot,))
if instance.options.export_reservoirs:
"""
This table writes out reservoir levels in cubic meters per tp.
"""
print "reservoir_final_vols_tp.csv..."
export.write_table(
instance, instance.TIMEPOINTS,
output_file=os.path.join(summaries_dir, "reservoir_final_vols_tp.csv"),
headings=("timepoints",) + tuple(r for r in instance.RESERVOIRS) + ("total",),
values=lambda m, tp: (m.tp_timestamp[tp],) + tuple(m.ReservoirFinalvol[r, tp] - m.initial_res_vol[r] for r in m.RESERVOIRS) + (
sum(m.ReservoirFinalvol[r, tp] - m.initial_res_vol[r] for r in m.RESERVOIRS),)
)
DF = pd.read_csv('outputs/Summaries/reservoir_final_vols_tp.csv',sep='\t').drop(['timepoints'],axis=1)
fig2 = plt.figure(4)
res_ax = fig2.add_subplot(211)
# GO cycling through the rainbow to get line colours
cm = plt.get_cmap('gist_rainbow')
# You have to play with the color map and the line style list to get enough combinations for your particular plot
res_ax.set_prop_cycle(cycler('linestyle',['-',':','--']) * cycler('color',[cm(i/5.0) for i in range(0,6)]))
# to locate the legend: "loc" is the point of the legend for which you will specify cooridnates. These coords are specified in bbox_to_anchor (can be only 1 point or couple)
res_plot = DF.plot(ax=res_ax,linewidth=1.5).legend(loc='upper center', fontsize=10, bbox_to_anchor=(0.,-0.15,1.,-0.15), ncol=2, mode="expand")
plt.xticks([i*24 for i in range(1,len(instance.TIMEPOINTS)/24+1)],[instance.tp_timestamp[instance.TIMEPOINTS[i*24]] for i in range(1,len(instance.TIMEPOINTS)/24+1)],rotation=40,fontsize=7)
plt.savefig('outputs/Summaries/reservoir_levels.pdf',bbox_extra_artists=(res_plot,))
"""
Writing Objective Function value.
"""
print "total_system_costs.txt..."
with open(os.path.join(summaries_dir, "total_system_costs.txt"),'w+') as f:
f.write("Total System Costs: "+str(instance.SystemCost())+"\n")
f.write("Total Investment Costs: "+str(instance.TotalInvestmentCost())+"\n")
f.write("Total Operations Costs: "+str(instance.TotalOperationsCost()))
# # This table writes out the dispatch of each gen tech on each timepoint and load zone.
# #This process is extremely slow, need to make it efficient
# print "dispatch_proj_by_tech_lz_tp.csv..."
# export.write_table(
# instance, instance.TIMEPOINTS, instance.LOAD_ZONES,
# output_file=os.path.join(summaries_dir, "dispatch_proj_by_tech_lz_tp.csv"),
# headings=("load zone", "timepoint",) + tuple(g for g in instance.GENERATION_TECHNOLOGIES),
# values=lambda m, tp, lz: (lz, m.tp_timestamp[tp],) + tuple(
# sum(m.DispatchProj[proj, t] for (proj, t) in m.PROJ_DISPATCH_POINTS
# if m.proj_gen_tech[proj] == g and t == tp and m.proj_load_zone[proj] == lz)
# for g in m.GENERATION_TECHNOLOGIES)
# )
print "Time taken writing summaries: {dur:.2f}s".format(dur=time.time()-start)
|
unknown
|
codeparrot/codeparrot-clean
| ||
import numpy as np
from collections import deque
from PIL import Image
import gym
from gym import spaces
class NoopResetEnv(gym.Wrapper):
def __init__(self, env, noop_max=30):
"""Sample initial states by taking random number of no-ops on reset.
No-op is assumed to be action 0.
"""
gym.Wrapper.__init__(self, env)
self.noop_max = noop_max
self.override_num_noops = None
assert env.unwrapped.get_action_meanings()[0] == 'NOOP'
def _reset(self):
""" Do no-op action for a number of steps in [1, noop_max]."""
self.env.reset()
if self.override_num_noops is not None:
noops = self.override_num_noops
else:
noops = self.unwrapped.np_random.randint(1, self.noop_max + 1) #pylint: disable=E1101
assert noops > 0
obs = None
for _ in range(noops):
obs, _, done, _ = self.env.step(0)
if done:
obs = self.env.reset()
return obs
class FireResetEnv(gym.Wrapper):
def __init__(self, env):
"""Take action on reset for environments that are fixed until firing."""
gym.Wrapper.__init__(self, env)
assert env.unwrapped.get_action_meanings()[1] == 'FIRE'
assert len(env.unwrapped.get_action_meanings()) >= 3
def _reset(self):
self.env.reset()
obs, _, done, _ = self.env.step(1)
if done:
self.env.reset()
obs, _, done, _ = self.env.step(2)
if done:
self.env.reset()
return obs
class EpisodicLifeEnv(gym.Wrapper):
def __init__(self, env):
"""Make end-of-life == end-of-episode, but only reset on true game over.
Done by DeepMind for the DQN and co. since it helps value estimation.
"""
gym.Wrapper.__init__(self, env)
self.lives = 0
self.was_real_done = True
def _step(self, action):
obs, reward, done, info = self.env.step(action)
self.was_real_done = done
# check current lives, make loss of life terminal,
# then update lives to handle bonus lives
lives = self.env.unwrapped.ale.lives()
if lives < self.lives and lives > 0:
# for Qbert somtimes we stay in lives == 0 condtion for a few frames
# so its important to keep lives > 0, so that we only reset once
# the environment advertises done.
done = True
self.lives = lives
return obs, reward, done, info
def _reset(self):
"""Reset only when lives are exhausted.
This way all states are still reachable even though lives are episodic,
and the learner need not know about any of this behind-the-scenes.
"""
if self.was_real_done:
obs = self.env.reset()
else:
# no-op step to advance from terminal/lost life state
obs, _, _, _ = self.env.step(0)
self.lives = self.env.unwrapped.ale.lives()
return obs
class MaxAndSkipEnv(gym.Wrapper):
def __init__(self, env, skip=4):
"""Return only every `skip`-th frame"""
gym.Wrapper.__init__(self, env)
# most recent raw observations (for max pooling across time steps)
self._obs_buffer = deque(maxlen=2)
self._skip = skip
def _step(self, action):
"""Repeat action, sum reward, and max over last observations."""
total_reward = 0.0
done = None
for _ in range(self._skip):
obs, reward, done, info = self.env.step(action)
self._obs_buffer.append(obs)
total_reward += reward
if done:
break
max_frame = np.max(np.stack(self._obs_buffer), axis=0)
return max_frame, total_reward, done, info
def _reset(self):
"""Clear past frame buffer and init. to first obs. from inner env."""
self._obs_buffer.clear()
obs = self.env.reset()
self._obs_buffer.append(obs)
return obs
class ClipRewardEnv(gym.RewardWrapper):
def _reward(self, reward):
"""Bin reward to {+1, 0, -1} by its sign."""
return np.sign(reward)
class WarpFrame(gym.ObservationWrapper):
def __init__(self, env):
"""Warp frames to 84x84 as done in the Nature paper and later work."""
gym.ObservationWrapper.__init__(self, env)
self.res = 84
self.observation_space = spaces.Box(low=0, high=255, shape=(self.res, self.res, 1))
def _observation(self, obs):
frame = np.dot(obs.astype('float32'), np.array([0.299, 0.587, 0.114], 'float32'))
frame = np.array(Image.fromarray(frame).resize((self.res, self.res),
resample=Image.BILINEAR), dtype=np.uint8)
return frame.reshape((self.res, self.res, 1))
class FrameStack(gym.Wrapper):
def __init__(self, env, k):
"""Buffer observations and stack across channels (last axis)."""
gym.Wrapper.__init__(self, env)
self.k = k
self.frames = deque([], maxlen=k)
shp = env.observation_space.shape
assert shp[2] == 1 # can only stack 1-channel frames
self.observation_space = spaces.Box(low=0, high=255, shape=(shp[0], shp[1], k))
def _reset(self):
"""Clear buffer and re-fill by duplicating the first observation."""
ob = self.env.reset()
for _ in range(self.k): self.frames.append(ob)
return self._observation()
def _step(self, action):
ob, reward, done, info = self.env.step(action)
self.frames.append(ob)
return self._observation(), reward, done, info
def _observation(self):
assert len(self.frames) == self.k
return np.concatenate(self.frames, axis=2)
def wrap_deepmind(env, episode_life=True, clip_rewards=True):
"""Configure environment for DeepMind-style Atari.
Note: this does not include frame stacking!"""
assert 'NoFrameskip' in env.spec.id # required for DeepMind-style skip
if episode_life:
env = EpisodicLifeEnv(env)
# env = NoopResetEnv(env, noop_max=30)
env = MaxAndSkipEnv(env, skip=4)
if 'FIRE' in env.unwrapped.get_action_meanings():
env = FireResetEnv(env)
env = WarpFrame(env)
if clip_rewards:
env = ClipRewardEnv(env)
return env
|
unknown
|
codeparrot/codeparrot-clean
| ||
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from Define import Global
from Define import IMocca
from Define import Utility
# from qqbot import qqbotsched
def onQQMessage(bot, contact, member, content):
""" QQBot 全局调用入口 """
# print(bot)
# print(contact)
# print(member)
# print(content)
# 获取群名称
group_name = str(contact)
group_name = group_name[2:-1]
# print(group_name)
# 只接收指定群消息
if contact.ctype == 'group' and group_name == IMocca.group_name:
# 获得消息内容
message = str(content)
# 只处理触发器开头的消息
if message.startswith(IMocca.group_trigger):
# 去掉触发器
message = message.replace(IMocca.group_trigger, '')
# 去掉 空格 及 @ 符号
message = message.replace(' ', '')
message = message.replace('[@ME]', '')
# 获得处理完成后,等待发送的消息
result = handle_msg(bot, contact, member, message)
# 消息非空则回复
if len(result) > 0:
bot.SendTo(contact, result)
def handle_msg(bot, contact, member, message):
""" 处理消息程序 """
# 处理空消息
if len(message) == 0:
return '@' + member.name + ' 需要我为您做什么?\n直接发言「' + IMocca.group_trigger + ' 你能做什么」查看相关帮助'
if message == '你能做什么':
return '@' + member.name + '\n' + IMocca.help
if message == '生成星盘':
return '@' + member.name + ' 点击链接生成星盘:\nhttp://www.i-mocca.com/wap/astrolog/'
if message == '星座匹配':
return '@' + member.name + ' 点击链接进行星座匹配:\nhttp://www.i-mocca.com/wap/astromatchlite/'
if message == '星盘匹配':
return '@' + member.name + ' 点击链接进行星盘匹配:\nhttp://www.i-mocca.com/wap/astromatch/'
if message in Global.fate_astro_list:
# 获取指定星座运势
return Utility.get_fate(bot, contact, member, message)
# if message.startswith('roll') or message.startswith('Roll') or message.startswith('ROLL'):
# # ROLL
# m = message.replace('roll', '')
# m = m.replace('Roll', '')
# m = m.replace('ROLL', '')
# return Utility.roll(bot, contact, member, m)
#
# if message.startswith('钦点一人'):
# # 获得钦点的目的用于反馈
# return Utility.qin_dian(bot, contact, member, message.replace('钦点一人', ''), IMocca.group_name, IMocca.group_nickname)
else:
# 调用 聚合数据 问答机器人 接口
return Utility.turing(bot, contact, member, message)
# @qqbotsched(hour='0', minute='0')
# def task(bot):
#
# """ 计划任务 """
#
# try:
# group = bot.List('group', IMocca.group_name)[0]
# bot.SendTo(group, '计划任务')
# except Exception as e:
# print('QQBOT_TASK_E: ' + str(e))
|
unknown
|
codeparrot/codeparrot-clean
| ||
//! This defines the syntax of MIR, i.e., the set of available MIR operations, and other definitions
//! closely related to MIR semantics.
//! This is in a dedicated file so that changes to this file can be reviewed more carefully.
//! The intention is that this file only contains datatype declarations, no code.
use rustc_abi::{FieldIdx, VariantIdx};
use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece, Mutability};
use rustc_data_structures::packed::Pu128;
use rustc_hir::CoroutineKind;
use rustc_hir::def_id::DefId;
use rustc_index::IndexVec;
use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable};
use rustc_span::def_id::LocalDefId;
use rustc_span::source_map::Spanned;
use rustc_span::{Span, Symbol};
use rustc_target::asm::InlineAsmRegOrRegClass;
use smallvec::SmallVec;
use super::{BasicBlock, Const, Local, UserTypeProjection};
use crate::mir::coverage::CoverageKind;
use crate::ty::adjustment::PointerCoercion;
use crate::ty::{self, GenericArgsRef, List, Region, Ty, UserTypeAnnotationIndex};
/// Represents the "flavors" of MIR.
///
/// The MIR pipeline is structured into a few major dialects, with one or more phases within each
/// dialect. A MIR flavor is identified by a dialect-phase pair. A single `MirPhase` value
/// specifies such a pair. All flavors of MIR use the same data structure to represent the program.
///
/// Different MIR dialects have different semantics. (The differences between dialects are small,
/// but they do exist.) The progression from one MIR dialect to the next is technically a lowering
/// from one IR to another. In other words, a single well-formed [`Body`](crate::mir::Body) might
/// have different semantic meaning and different behavior at runtime in the different dialects.
/// The specific differences between dialects are described on the variants below.
///
/// Phases exist only to place restrictions on what language constructs are permitted in
/// well-formed MIR, and subsequent phases mostly increase those restrictions. I.e. to convert MIR
/// from one phase to the next might require removing/replacing certain MIR constructs.
///
/// When adding dialects or phases, remember to update [`MirPhase::index`].
#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[derive(HashStable)]
pub enum MirPhase {
/// The "built MIR" dialect, as generated by MIR building.
///
/// The only things that operate on this dialect are unsafeck, the various MIR lints, and const
/// qualifs.
///
/// This dialect has just the one (implicit) phase, which places few restrictions on what MIR
/// constructs are allowed.
Built,
/// The "analysis MIR" dialect, used for borrowck and friends.
///
/// The only semantic difference between built MIR and analysis MIR relates to constant
/// promotion. In built MIR, sequences of statements that would generally be subject to
/// constant promotion are semantically constants, while in analysis MIR all constants are
/// explicit.
///
/// The result of const promotion is available from the `mir_promoted` and `promoted_mir`
/// queries.
///
/// The phases of this dialect are described in `AnalysisPhase`.
Analysis(AnalysisPhase),
/// The "runtime MIR" dialect, used for CTFE, optimizations, and codegen.
///
/// The semantic differences between analysis MIR and runtime MIR are as follows.
///
/// - Drops: In analysis MIR, `Drop` terminators represent *conditional* drops; roughly
/// speaking, if dataflow analysis determines that the place being dropped is uninitialized,
/// the drop will not be executed. The exact semantics of this aren't written down anywhere,
/// which means they are essentially "what drop elaboration does." In runtime MIR, the drops
/// are unconditional; when a `Drop` terminator is reached, if the type has drop glue that
/// drop glue is always executed. This may be UB if the underlying place is not initialized.
/// - Packed drops: Places might in general be misaligned - in most cases this is UB, the
/// exception is fields of packed structs. In analysis MIR, `Drop(P)` for a `P` that might be
/// misaligned for this reason implicitly moves `P` to a temporary before dropping. Runtime
/// MIR has no such rules, and dropping a misaligned place is simply UB.
/// - Async drops: after drop elaboration some drops may become async (`drop`, `async_fut` fields).
/// StateTransform pass will expand those async drops or reset to sync.
/// - Unwinding: in analysis MIR, unwinding from a function which may not unwind aborts. In
/// runtime MIR, this is UB.
/// - Retags: If `-Zmir-emit-retag` is enabled, analysis MIR has "implicit" retags in the same
/// way that Rust itself has them. Where exactly these are is generally subject to change,
/// and so we don't document this here. Runtime MIR has most retags explicit (though implicit
/// retags can still occur at `Rvalue::{Ref,AddrOf}`).
/// - Coroutine bodies: In analysis MIR, locals may actually be behind a pointer that user code
/// has access to. This occurs in coroutine bodies. Such locals do not behave like other
/// locals, because they e.g. may be aliased in surprising ways. Runtime MIR has no such
/// special locals. All coroutine bodies are lowered and so all places that look like locals
/// really are locals.
///
/// Also note that the lint pass which reports eg `200_u8 + 200_u8` as an error is run as a part
/// of analysis to runtime MIR lowering. To ensure lints are reported reliably, this means that
/// transformations that can suppress such errors should not run on analysis MIR.
///
/// The phases of this dialect are described in `RuntimePhase`.
Runtime(RuntimePhase),
}
/// See [`MirPhase::Analysis`].
#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[derive(HashStable)]
pub enum AnalysisPhase {
Initial = 0,
/// Beginning in this phase, the following variants are disallowed:
/// * [`TerminatorKind::FalseUnwind`]
/// * [`TerminatorKind::FalseEdge`]
/// * [`StatementKind::FakeRead`]
/// * [`StatementKind::AscribeUserType`]
/// * [`StatementKind::Coverage`] with [`CoverageKind::BlockMarker`] or
/// [`CoverageKind::SpanMarker`]
/// * [`Rvalue::Ref`] with `BorrowKind::Fake`
/// * [`CastKind::PointerCoercion`] with any of the following:
/// * [`PointerCoercion::ArrayToPointer`]
/// * [`PointerCoercion::MutToConstPointer`]
///
/// Furthermore, `Deref` projections must be the first projection within any place (if they
/// appear at all)
PostCleanup = 1,
}
/// See [`MirPhase::Runtime`].
#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[derive(HashStable)]
pub enum RuntimePhase {
/// In addition to the semantic changes, beginning with this phase, the following variants are
/// disallowed:
/// * [`TerminatorKind::Yield`]
/// * [`TerminatorKind::CoroutineDrop`]
/// * [`Rvalue::Aggregate`] for any `AggregateKind` except `Array`
/// * [`Rvalue::CopyForDeref`]
/// * [`PlaceElem::OpaqueCast`]
/// * [`LocalInfo::DerefTemp`](super::LocalInfo::DerefTemp)
///
/// And the following variants are allowed:
/// * [`StatementKind::Retag`]
/// * [`StatementKind::SetDiscriminant`]
/// * [`PlaceElem::ConstantIndex`] / [`PlaceElem::Subslice`] after [`PlaceElem::Subslice`]
///
/// Furthermore, `Copy` operands are allowed for non-`Copy` types.
Initial = 0,
/// Beginning with this phase, the following variant is disallowed:
/// * [`ProjectionElem::Deref`] of `Box`
PostCleanup = 1,
Optimized = 2,
}
///////////////////////////////////////////////////////////////////////////
// Borrow kinds
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
#[derive(Hash, HashStable)]
pub enum BorrowKind {
/// Data must be immutable and is aliasable.
Shared,
/// An immutable, aliasable borrow that is discarded after borrow-checking. Can behave either
/// like a normal shared borrow or like a special shallow borrow (see [`FakeBorrowKind`]).
///
/// This is used when lowering index expressions and matches. This is used to prevent code like
/// the following from compiling:
/// ```compile_fail,E0510
/// let mut x: &[_] = &[[0, 1]];
/// let y: &[_] = &[];
/// let _ = x[0][{x = y; 1}];
/// ```
/// ```compile_fail,E0510
/// let mut x = &Some(0);
/// match *x {
/// None => (),
/// Some(_) if { x = &None; false } => (),
/// Some(_) => (),
/// }
/// ```
/// We can also report errors with this kind of borrow differently.
Fake(FakeBorrowKind),
/// Data is mutable and not aliasable.
Mut { kind: MutBorrowKind },
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
#[derive(Hash, HashStable)]
pub enum RawPtrKind {
Mut,
Const,
/// Creates a raw pointer to a place that will only be used to access its metadata,
/// not the data behind the pointer. Note that this limitation is *not* enforced
/// by the validator.
///
/// The borrow checker allows overlap of these raw pointers with references to the
/// data. This is sound even if the pointer is "misused" since any such use is anyway
/// unsafe. In terms of the operational semantics (i.e., Miri), this is equivalent
/// to `RawPtrKind::Mut`, but will never incur a retag.
FakeForPtrMetadata,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
#[derive(Hash, HashStable)]
pub enum MutBorrowKind {
Default,
/// This borrow arose from method-call auto-ref. (i.e., `adjustment::Adjust::Borrow`)
TwoPhaseBorrow,
/// Data must be immutable but not aliasable. This kind of borrow
/// cannot currently be expressed by the user and is used only in
/// implicit closure bindings. It is needed when the closure is
/// borrowing or mutating a mutable referent, e.g.:
/// ```
/// let mut z = 3;
/// let x: &mut isize = &mut z;
/// let y = || *x += 5;
/// ```
/// If we were to try to translate this closure into a more explicit
/// form, we'd encounter an error with the code as written:
/// ```compile_fail,E0594
/// struct Env<'a> { x: &'a &'a mut isize }
/// let mut z = 3;
/// let x: &mut isize = &mut z;
/// let y = (&mut Env { x: &x }, fn_ptr); // Closure is pair of env and fn
/// fn fn_ptr(env: &mut Env) { **env.x += 5; }
/// ```
/// This is then illegal because you cannot mutate an `&mut` found
/// in an aliasable location. To solve, you'd have to translate with
/// an `&mut` borrow:
/// ```compile_fail,E0596
/// struct Env<'a> { x: &'a mut &'a mut isize }
/// let mut z = 3;
/// let x: &mut isize = &mut z;
/// let y = (&mut Env { x: &mut x }, fn_ptr); // changed from &x to &mut x
/// fn fn_ptr(env: &mut Env) { **env.x += 5; }
/// ```
/// Now the assignment to `**env.x` is legal, but creating a
/// mutable pointer to `x` is not because `x` is not mutable. We
/// could fix this by declaring `x` as `let mut x`. This is ok in
/// user code, if awkward, but extra weird for closures, since the
/// borrow is hidden.
///
/// So we introduce a `ClosureCapture` borrow -- user will not have to mark the variable
/// containing the mutable reference as `mut`, as they didn't ever
/// intend to mutate the mutable reference itself. We still mutable capture it in order to
/// mutate the pointed value through it (but not mutating the reference itself).
///
/// This solves the problem. For simplicity, we don't give users the way to express this
/// borrow, it's just used when translating closures.
ClosureCapture,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)]
#[derive(Hash, HashStable)]
pub enum FakeBorrowKind {
/// A shared shallow borrow. The immediately borrowed place must be immutable, but projections
/// from it don't need to be. For example, a shallow borrow of `a.b` doesn't conflict with a
/// mutable borrow of `a.b.c`.
///
/// This is used when lowering matches: when matching on a place we want to ensure that place
/// have the same value from the start of the match until an arm is selected. This prevents this
/// code from compiling:
/// ```compile_fail,E0510
/// let mut x = &Some(0);
/// match *x {
/// None => (),
/// Some(_) if { x = &None; false } => (),
/// Some(_) => (),
/// }
/// ```
/// This can't be a shared borrow because mutably borrowing `(*x as Some).0` should not checking
/// the discriminant or accessing other variants, because the mutating `(*x as Some).0` can't
/// affect the discriminant of `x`. E.g. the following is allowed:
/// ```rust
/// let mut x = Some(0);
/// match x {
/// Some(_)
/// if {
/// if let Some(ref mut y) = x {
/// *y += 1;
/// };
/// true
/// } => {}
/// _ => {}
/// }
/// ```
Shallow,
/// A shared (deep) borrow. Data must be immutable and is aliasable.
///
/// This is used when lowering deref patterns, where shallow borrows wouldn't prevent something
/// like:
/// ```compile_fail
/// let mut b = Box::new(false);
/// match b {
/// deref!(true) => {} // not reached because `*b == false`
/// _ if { *b = true; false } => {} // not reached because the guard is `false`
/// deref!(false) => {} // not reached because the guard changed it
/// // UB because we reached the unreachable.
/// }
/// ```
Deep,
}
///////////////////////////////////////////////////////////////////////////
// Statements
/// The various kinds of statements that can appear in MIR.
///
/// Not all of these are allowed at every [`MirPhase`]. Check the documentation there to see which
/// ones you do not have to worry about. The MIR validator will generally enforce such restrictions,
/// causing an ICE if they are violated.
#[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
#[derive(TypeFoldable, TypeVisitable)]
pub enum StatementKind<'tcx> {
/// Assign statements roughly correspond to an assignment in Rust proper (`x = ...`) except
/// without the possibility of dropping the previous value (that must be done separately, if at
/// all). The *exact* way this works is undecided. It probably does something like evaluating
/// the LHS to a place and the RHS to a value, and then storing the value to the place. Various
/// parts of this may do type specific things that are more complicated than simply copying
/// bytes.
///
/// **Needs clarification**: The implication of the above idea would be that assignment implies
/// that the resulting value is initialized. I believe we could commit to this separately from
/// committing to whatever part of the memory model we would need to decide on to make the above
/// paragraph precise. Do we want to?
///
/// Assignments in which the types of the place and rvalue differ are not well-formed.
///
/// **Needs clarification**: Do we ever want to worry about non-free (in the body) lifetimes for
/// the typing requirement in post drop-elaboration MIR? I think probably not - I'm not sure we
/// could meaningfully require this anyway. How about free lifetimes? Is ignoring this
/// interesting for optimizations? Do we want to allow such optimizations?
///
/// **Needs clarification**: We currently require that the LHS place not overlap with any place
/// read as part of computation of the RHS for some rvalues. This requirement is under
/// discussion in [#68364]. Specifically, overlap is permitted only for assignments of a type
/// with `BackendRepr::Scalar | BackendRepr::ScalarPair` where all the scalar fields are
/// [`Scalar::Initialized`][rustc_abi::Scalar::Initialized]. As a part of this discussion, it is
/// also unclear in what order the components are evaluated.
///
/// [#68364]: https://github.com/rust-lang/rust/issues/68364
///
/// See [`Rvalue`] documentation for details on each of those.
Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>),
/// When executed at runtime, this is a nop.
///
/// During static analysis, a fake read:
/// - requires that the value being read is initialized (or, in the case
/// of closures, that it was fully initialized at some point in the past)
/// - constitutes a use of a value for the purposes of NLL (i.e. if the
/// value being fake-read is a reference, the lifetime of that reference
/// will be extended to cover the `FakeRead`)
/// - but, unlike an actual read, does *not* invalidate any exclusive
/// borrows.
///
/// See [`FakeReadCause`] for more details on the situations in which a
/// `FakeRead` is emitted.
///
/// Disallowed after drop elaboration.
FakeRead(Box<(FakeReadCause, Place<'tcx>)>),
/// Write the discriminant for a variant to the enum Place.
///
/// This is permitted for both coroutines and ADTs. This does not necessarily write to the
/// entire place; instead, it writes to the minimum set of bytes as required by the layout for
/// the type.
SetDiscriminant { place: Box<Place<'tcx>>, variant_index: VariantIdx },
/// `StorageLive` and `StorageDead` statements mark the live range of a local.
///
/// At any point during the execution of a function, each local is either allocated or
/// unallocated. Except as noted below, all locals except function parameters are initially
/// unallocated. `StorageLive` statements cause memory to be allocated for the local while
/// `StorageDead` statements cause the memory to be freed. In other words,
/// `StorageLive`/`StorageDead` act like the heap operations `allocate`/`deallocate`, but for
/// stack-allocated local variables. Using a local in any way (not only reading/writing from it)
/// while it is unallocated is UB.
///
/// Some locals have no `StorageLive` or `StorageDead` statements within the entire MIR body.
/// These locals are implicitly allocated for the full duration of the function. There is a
/// convenience method at `rustc_mir_dataflow::storage::always_storage_live_locals` for
/// computing these locals.
///
/// If the local is already allocated, calling `StorageLive` again will implicitly free the
/// local and then allocate fresh uninitialized memory. If a local is already deallocated,
/// calling `StorageDead` again is a NOP.
StorageLive(Local),
/// See `StorageLive` above.
StorageDead(Local),
/// Retag references in the given place, ensuring they got fresh tags.
///
/// This is part of the Stacked Borrows model. These statements are currently only interpreted
/// by miri and only generated when `-Z mir-emit-retag` is passed. See
/// <https://internals.rust-lang.org/t/stacked-borrows-an-aliasing-model-for-rust/8153/> for
/// more details.
///
/// For code that is not specific to stacked borrows, you should consider retags to read and
/// modify the place in an opaque way.
///
/// Only `RetagKind::Default` and `RetagKind::FnEntry` are permitted.
Retag(RetagKind, Box<Place<'tcx>>),
/// This statement exists to preserve a trace of a scrutinee matched against a wildcard binding.
/// This is especially useful for `let _ = PLACE;` bindings that desugar to a single
/// `PlaceMention(PLACE)`.
///
/// When executed at runtime, this computes the given place, but then discards
/// it without doing a load. `let _ = *ptr;` is fine even if the pointer is dangling.
PlaceMention(Box<Place<'tcx>>),
/// Encodes a user's type ascription. These need to be preserved
/// intact so that NLL can respect them. For example:
/// ```ignore (illustrative)
/// let a: T = y;
/// ```
/// The effect of this annotation is to relate the type `T_y` of the place `y`
/// to the user-given type `T`. The effect depends on the specified variance:
///
/// - `Covariant` -- requires that `T_y <: T`
/// - `Contravariant` -- requires that `T_y :> T`
/// - `Invariant` -- requires that `T_y == T`
/// - `Bivariant` -- no effect
///
/// When executed at runtime this is a nop.
///
/// Disallowed after drop elaboration.
AscribeUserType(Box<(Place<'tcx>, UserTypeProjection)>, ty::Variance),
/// Carries control-flow-sensitive information injected by `-Cinstrument-coverage`,
/// such as where to generate physical coverage-counter-increments during codegen.
///
/// Coverage statements are used in conjunction with the coverage mappings and other
/// information stored in the function's
/// [`mir::Body::function_coverage_info`](crate::mir::Body::function_coverage_info).
/// (For inlined MIR, take care to look up the *original function's* coverage info.)
///
/// Interpreters and codegen backends that don't support coverage instrumentation
/// can usually treat this as a no-op.
Coverage(
// Coverage statements are unlikely to ever contain type information in
// the foreseeable future, so excluding them from TypeFoldable/TypeVisitable
// avoids some unhelpful derive boilerplate.
#[type_foldable(identity)]
#[type_visitable(ignore)]
CoverageKind,
),
/// Denotes a call to an intrinsic that does not require an unwind path and always returns.
/// This avoids adding a new block and a terminator for simple intrinsics.
Intrinsic(Box<NonDivergingIntrinsic<'tcx>>),
/// Instructs the const eval interpreter to increment a counter; this counter is used to track
/// how many steps the interpreter has taken. It is used to prevent the user from writing const
/// code that runs for too long or infinitely. Other than in the const eval interpreter, this
/// is a no-op.
ConstEvalCounter,
/// No-op. Useful for deleting instructions without affecting statement indices.
Nop,
/// Marker statement indicating where `place` would be dropped.
/// This is semantically equivalent to `Nop`, so codegen and MIRI should interpret this
/// statement as such.
/// The only use case of this statement is for linting in MIR to detect temporary lifetime
/// changes.
BackwardIncompatibleDropHint {
/// Place to drop
place: Box<Place<'tcx>>,
/// Reason for backward incompatibility
reason: BackwardIncompatibleDropReason,
},
}
#[derive(
Clone,
TyEncodable,
TyDecodable,
Debug,
PartialEq,
Hash,
HashStable,
TypeFoldable,
TypeVisitable
)]
pub enum NonDivergingIntrinsic<'tcx> {
/// Denotes a call to the intrinsic function `assume`.
///
/// The operand must be a boolean. Optimizers may use the value of the boolean to backtrack its
/// computation to infer information about other variables. So if the boolean came from a
/// `x < y` operation, subsequent operations on `x` and `y` could elide various bound checks.
/// If the argument is `false`, this operation is equivalent to `TerminatorKind::Unreachable`.
Assume(Operand<'tcx>),
/// Denotes a call to the intrinsic function `copy_nonoverlapping`.
///
/// First, all three operands are evaluated. `src` and `dest` must each be a reference, pointer,
/// or `Box` pointing to the same type `T`. `count` must evaluate to a `usize`. Then, `src` and
/// `dest` are dereferenced, and `count * size_of::<T>()` bytes beginning with the first byte of
/// the `src` place are copied to the contiguous range of bytes beginning with the first byte
/// of `dest`.
///
/// **Needs clarification**: In what order are operands computed and dereferenced? It should
/// probably match the order for assignment, but that is also undecided.
///
/// **Needs clarification**: Is this typed or not, ie is there a typed load and store involved?
/// I vaguely remember Ralf saying somewhere that he thought it should not be.
CopyNonOverlapping(CopyNonOverlapping<'tcx>),
}
/// Describes what kind of retag is to be performed.
#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, Hash, HashStable)]
#[rustc_pass_by_value]
pub enum RetagKind {
/// The initial retag of arguments when entering a function.
FnEntry,
/// Retag preparing for a two-phase borrow.
TwoPhase,
/// Retagging raw pointers.
Raw,
/// A "normal" retag.
Default,
}
/// The `FakeReadCause` describes the type of pattern why a FakeRead statement exists.
#[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, Hash, HashStable, PartialEq)]
pub enum FakeReadCause {
/// A fake read injected into a match guard to ensure that the discriminants
/// that are being matched on aren't modified while the match guard is being
/// evaluated.
///
/// At the beginning of each match guard, a [fake borrow][FakeBorrowKind] is
/// inserted for each discriminant accessed in the entire `match` statement.
///
/// Then, at the end of the match guard, a `FakeRead(ForMatchGuard)` is
/// inserted to keep the fake borrows alive until that point.
///
/// This should ensure that you cannot change the variant for an enum while
/// you are in the midst of matching on it.
ForMatchGuard,
/// Fake read of the scrutinee of a `match` or destructuring `let`
/// (i.e. `let` with non-trivial pattern).
///
/// In `match x { ... }`, we generate a `FakeRead(ForMatchedPlace, x)`
/// and insert it into the `otherwise_block` (which is supposed to be
/// unreachable for irrefutable pattern-matches like `match` or `let`).
///
/// This is necessary because `let x: !; match x {}` doesn't generate any
/// actual read of x, so we need to generate a `FakeRead` to check that it
/// is initialized.
///
/// If the `FakeRead(ForMatchedPlace)` is being performed with a closure
/// that doesn't capture the required upvars, the `FakeRead` within the
/// closure is omitted entirely.
///
/// To make sure that this is still sound, if a closure matches against
/// a Place starting with an Upvar, we hoist the `FakeRead` to the
/// definition point of the closure.
///
/// If the `FakeRead` comes from being hoisted out of a closure like this,
/// we record the `LocalDefId` of the closure. Otherwise, the `Option` will be `None`.
//
// We can use LocalDefId here since fake read statements are removed
// before codegen in the `CleanupNonCodegenStatements` pass.
ForMatchedPlace(Option<LocalDefId>),
/// A fake read injected into a match guard to ensure that the places
/// bound by the pattern are immutable for the duration of the match guard.
///
/// Within a match guard, references are created for each place that the
/// pattern creates a binding for — this is known as the `RefWithinGuard`
/// version of the variables. To make sure that the references stay
/// alive until the end of the match guard, and properly prevent the
/// places in question from being modified, a `FakeRead(ForGuardBinding)`
/// is inserted at the end of the match guard.
///
/// For details on how these references are created, see the extensive
/// documentation on `bind_matched_candidate_for_guard` in
/// `rustc_mir_build`.
ForGuardBinding,
/// Officially, the semantics of
///
/// `let pattern = <expr>;`
///
/// is that `<expr>` is evaluated into a temporary and then this temporary is
/// into the pattern.
///
/// However, if we see the simple pattern `let var = <expr>`, we optimize this to
/// evaluate `<expr>` directly into the variable `var`. This is mostly unobservable,
/// but in some cases it can affect the borrow checker, as in #53695.
///
/// Therefore, we insert a `FakeRead(ForLet)` immediately after each `let`
/// with a trivial pattern.
///
/// FIXME: `ExprUseVisitor` has an entirely different opinion on what `FakeRead(ForLet)`
/// is supposed to mean. If it was accurate to what MIR lowering does,
/// would it even make sense to hoist these out of closures like
/// `ForMatchedPlace`?
ForLet(Option<LocalDefId>),
/// Currently, index expressions overloaded through the `Index` trait
/// get lowered differently than index expressions with builtin semantics
/// for arrays and slices — the latter will emit code to perform
/// bound checks, and then return a MIR place that will only perform the
/// indexing "for real" when it gets incorporated into an instruction.
///
/// This is observable in the fact that the following compiles:
///
/// ```
/// fn f(x: &mut [&mut [u32]], i: usize) {
/// x[i][x[i].len() - 1] += 1;
/// }
/// ```
///
/// However, we need to be careful to not let the user invalidate the
/// bound check with an expression like
///
/// `(*x)[1][{ x = y; 4}]`
///
/// Here, the first bounds check would be invalidated when we evaluate the
/// second index expression. To make sure that this doesn't happen, we
/// create a fake borrow of `x` and hold it while we evaluate the second
/// index.
///
/// This borrow is kept alive by a `FakeRead(ForIndex)` at the end of its
/// scope.
ForIndex,
}
#[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
#[derive(TypeFoldable, TypeVisitable)]
pub struct CopyNonOverlapping<'tcx> {
pub src: Operand<'tcx>,
pub dst: Operand<'tcx>,
/// Number of elements to copy from src to dest, not bytes.
pub count: Operand<'tcx>,
}
/// Represents how a [`TerminatorKind::Call`] was constructed.
/// Used only for diagnostics.
#[derive(Clone, Copy, TyEncodable, TyDecodable, Debug, PartialEq, Hash, HashStable)]
#[derive(TypeFoldable, TypeVisitable)]
pub enum CallSource {
/// This came from something such as `a > b` or `a + b`. In THIR, if `from_hir_call`
/// is false then this is the desugaring.
OverloadedOperator,
/// This was from comparison generated by a match, used by const-eval for better errors
/// when the comparison cannot be done in compile time.
///
/// (see <https://github.com/rust-lang/rust/issues/90237>)
MatchCmp,
/// Other types of desugaring that did not come from the HIR, but we don't care about
/// for diagnostics (yet).
Misc,
/// Use of value, generating a clone function call
Use,
/// Normal function call, no special source
Normal,
}
#[derive(Clone, Copy, Debug, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
#[derive(TypeFoldable, TypeVisitable)]
/// The macro that an inline assembly block was created by
pub enum InlineAsmMacro {
/// The `asm!` macro
Asm,
/// The `naked_asm!` macro
NakedAsm,
}
///////////////////////////////////////////////////////////////////////////
// Terminators
/// The various kinds of terminators, representing ways of exiting from a basic block.
///
/// A note on unwinding: Panics may occur during the execution of some terminators. Depending on the
/// `-C panic` flag, this may either cause the program to abort or the call stack to unwind. Such
/// terminators have a `unwind: UnwindAction` field on them. If stack unwinding occurs, then
/// once the current function is reached, an action will be taken based on the `unwind` field.
/// If the action is `Cleanup`, then the execution continues at the given basic block. If the
/// action is `Continue` then no cleanup is performed, and the stack continues unwinding.
///
/// The basic block pointed to by a `Cleanup` unwind action must have its `cleanup` flag set.
/// `cleanup` basic blocks have a couple restrictions:
/// 1. All `unwind` fields in them must be `UnwindAction::Terminate` or `UnwindAction::Unreachable`.
/// 2. `Return` terminators are not allowed in them. `Terminate` and `Resume` terminators are.
/// 3. All other basic blocks (in the current body) that are reachable from `cleanup` basic blocks
/// must also be `cleanup`. This is a part of the type system and checked statically, so it is
/// still an error to have such an edge in the CFG even if it's known that it won't be taken at
/// runtime.
/// 4. The control flow between cleanup blocks must look like an upside down tree. Roughly
/// speaking, this means that control flow that looks like a V is allowed, while control flow
/// that looks like a W is not. This is necessary to ensure that landing pad information can be
/// correctly codegened on MSVC. More precisely:
///
/// Begin with the standard control flow graph `G`. Modify `G` as follows: for any two cleanup
/// vertices `u` and `v` such that `u` dominates `v`, contract `u` and `v` into a single vertex,
/// deleting self edges and duplicate edges in the process. Now remove all vertices from `G`
/// that are not cleanup vertices or are not reachable. The resulting graph must be an inverted
/// tree, that is each vertex may have at most one successor and there may be no cycles.
#[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, TypeFoldable, TypeVisitable)]
pub enum TerminatorKind<'tcx> {
/// Block has one successor; we continue execution there.
Goto { target: BasicBlock },
/// Switches based on the computed value.
///
/// First, evaluates the `discr` operand. The type of the operand must be a signed or unsigned
/// integer, char, or bool, and must match the given type. Then, if the list of switch targets
/// contains the computed value, continues execution at the associated basic block. Otherwise,
/// continues execution at the "otherwise" basic block.
///
/// Target values may not appear more than once.
SwitchInt {
/// The discriminant value being tested.
discr: Operand<'tcx>,
targets: SwitchTargets,
},
/// Indicates that the landing pad is finished and that the process should continue unwinding.
///
/// Like a return, this marks the end of this invocation of the function.
///
/// Only permitted in cleanup blocks. `Resume` is not permitted with `-C unwind=abort` after
/// deaggregation runs.
UnwindResume,
/// Indicates that the landing pad is finished and that the process should terminate.
///
/// Used to prevent unwinding for foreign items or with `-C unwind=abort`. Only permitted in
/// cleanup blocks.
UnwindTerminate(UnwindTerminateReason),
/// Returns from the function.
///
/// Like function calls, the exact semantics of returns in Rust are unclear. Returning very
/// likely at least assigns the value currently in the return place (`_0`) to the place
/// specified in the associated `Call` terminator in the calling function, as if assigned via
/// `dest = move _0`. It might additionally do other things, like have side-effects in the
/// aliasing model.
///
/// If the body is a coroutine body, this has slightly different semantics; it instead causes a
/// `CoroutineState::Returned(_0)` to be created (as if by an `Aggregate` rvalue) and assigned
/// to the return place.
Return,
/// Indicates a terminator that can never be reached.
///
/// Executing this terminator is UB.
Unreachable,
/// The behavior of this statement differs significantly before and after drop elaboration.
///
/// After drop elaboration: `Drop` terminators are a complete nop for types that have no drop
/// glue. For other types, `Drop` terminators behave exactly like a call to
/// `core::mem::drop_in_place` with a pointer to the given place.
///
/// `Drop` before drop elaboration is a *conditional* execution of the drop glue. Specifically,
/// the `Drop` will be executed if...
///
/// **Needs clarification**: End of that sentence. This in effect should document the exact
/// behavior of drop elaboration. The following sounds vaguely right, but I'm not quite sure:
///
/// > The drop glue is executed if, among all statements executed within this `Body`, an assignment to
/// > the place or one of its "parents" occurred more recently than a move out of it. This does not
/// > consider indirect assignments.
///
/// The `replace` flag indicates whether this terminator was created as part of an assignment.
/// This should only be used for diagnostic purposes, and does not have any operational
/// meaning.
///
/// Async drop processing:
/// In compiler/rustc_mir_build/src/build/scope.rs we detect possible async drop:
/// drop of object with `needs_async_drop`.
/// Async drop later, in StateTransform pass, may be expanded into additional yield-point
/// for poll-loop of async drop future.
/// So we need prepared 'drop' target block in the similar way as for `Yield` terminator
/// (see `drops.build_mir::<CoroutineDrop>` in scopes.rs).
/// In compiler/rustc_mir_transform/src/elaborate_drops.rs for object implementing `AsyncDrop` trait
/// we need to prepare async drop feature - resolve `AsyncDrop::drop` and codegen call.
/// `async_fut` is set to the corresponding local.
/// For coroutine drop we don't need this logic because coroutine drop works with the same
/// layout object as coroutine itself. So `async_fut` will be `None` for coroutine drop.
/// Both `drop` and `async_fut` fields are only used in compiler/rustc_mir_transform/src/coroutine.rs,
/// StateTransform pass. In `expand_async_drops` async drops are expanded
/// into one or two yield points with poll ready/pending switch.
/// When a coroutine has any internal async drop, the coroutine drop function will be async
/// (generated by `create_coroutine_drop_shim_async`, not `create_coroutine_drop_shim`).
Drop {
place: Place<'tcx>,
target: BasicBlock,
unwind: UnwindAction,
replace: bool,
/// Cleanup to be done if the coroutine is dropped at this suspend point (for async drop).
drop: Option<BasicBlock>,
/// Prepared async future local (for async drop)
async_fut: Option<Local>,
},
/// Roughly speaking, evaluates the `func` operand and the arguments, and starts execution of
/// the referred to function. The operand types must match the argument types of the function.
/// The return place type must match the return type. The type of the `func` operand must be
/// callable, meaning either a function pointer, a function type, or a closure type.
///
/// **Needs clarification**: The exact semantics of this. Current backends rely on `move`
/// operands not aliasing the return place. It is unclear how this is justified in MIR, see
/// [#71117].
///
/// [#71117]: https://github.com/rust-lang/rust/issues/71117
Call {
/// The function that’s being called.
func: Operand<'tcx>,
/// Arguments the function is called with.
/// These are owned by the callee, which is free to modify them.
/// This allows the memory occupied by "by-value" arguments to be
/// reused across function calls without duplicating the contents.
/// The span for each arg is also included
/// (e.g. `a` and `b` in `x.foo(a, b)`).
args: Box<[Spanned<Operand<'tcx>>]>,
/// Where the returned value will be written
destination: Place<'tcx>,
/// Where to go after this call returns. If none, the call necessarily diverges.
target: Option<BasicBlock>,
/// Action to be taken if the call unwinds.
unwind: UnwindAction,
/// Where this call came from in HIR/THIR.
call_source: CallSource,
/// This `Span` is the span of the function, without the dot and receiver
/// e.g. `foo(a, b)` in `x.foo(a, b)`
fn_span: Span,
},
/// Tail call.
///
/// Roughly speaking this is a chimera of [`Call`] and [`Return`], with some caveats.
/// Semantically tail calls consists of two actions:
/// - pop of the current stack frame
/// - a call to the `func`, with the return address of the **current** caller
/// - so that a `return` inside `func` returns to the caller of the caller
/// of the function that is currently being executed
///
/// Note that in difference with [`Call`] this is missing
/// - `destination` (because it's always the return place)
/// - `target` (because it's always taken from the current stack frame)
/// - `unwind` (because it's always taken from the current stack frame)
///
/// [`Call`]: TerminatorKind::Call
/// [`Return`]: TerminatorKind::Return
TailCall {
/// The function that’s being called.
func: Operand<'tcx>,
/// Arguments the function is called with.
/// These are owned by the callee, which is free to modify them.
/// This allows the memory occupied by "by-value" arguments to be
/// reused across function calls without duplicating the contents.
args: Box<[Spanned<Operand<'tcx>>]>,
// FIXME(explicit_tail_calls): should we have the span for `become`? is this span accurate? do we need it?
/// This `Span` is the span of the function, without the dot and receiver
/// (e.g. `foo(a, b)` in `x.foo(a, b)`
fn_span: Span,
},
/// Evaluates the operand, which must have type `bool`. If it is not equal to `expected`,
/// initiates a panic. Initiating a panic corresponds to a `Call` terminator with some
/// unspecified constant as the function to call, all the operands stored in the `AssertMessage`
/// as parameters, and `None` for the destination. Keep in mind that the `cleanup` path is not
/// necessarily executed even in the case of a panic, for example in `-C panic=abort`. If the
/// assertion does not fail, execution continues at the specified basic block.
///
/// When overflow checking is disabled and this is run-time MIR (as opposed to compile-time MIR
/// that is used for CTFE), the following variants of this terminator behave as `goto target`:
/// - `OverflowNeg(..)`,
/// - `Overflow(op, ..)` if op is add, sub, mul, shl, shr, but NOT div or rem.
Assert {
cond: Operand<'tcx>,
expected: bool,
msg: Box<AssertMessage<'tcx>>,
target: BasicBlock,
unwind: UnwindAction,
},
/// Marks a suspend point.
///
/// Like `Return` terminators in coroutine bodies, this computes `value` and then a
/// `CoroutineState::Yielded(value)` as if by `Aggregate` rvalue. That value is then assigned to
/// the return place of the function calling this one, and execution continues in the calling
/// function. When next invoked with the same first argument, execution of this function
/// continues at the `resume` basic block, with the second argument written to the `resume_arg`
/// place. If the coroutine is dropped before then, the `drop` basic block is invoked.
///
/// Note that coroutines can be (unstably) cloned under certain conditions, which means that
/// this terminator can **return multiple times**! MIR optimizations that reorder code into
/// different basic blocks needs to be aware of that.
/// See <https://github.com/rust-lang/rust/issues/95360>.
///
/// Not permitted in bodies that are not coroutine bodies, or after coroutine lowering.
///
/// **Needs clarification**: What about the evaluation order of the `resume_arg` and `value`?
Yield {
/// The value to return.
value: Operand<'tcx>,
/// Where to resume to.
resume: BasicBlock,
/// The place to store the resume argument in.
resume_arg: Place<'tcx>,
/// Cleanup to be done if the coroutine is dropped at this suspend point.
drop: Option<BasicBlock>,
},
/// Indicates the end of dropping a coroutine.
///
/// Semantically just a `return` (from the coroutines drop glue). Only permitted in the same situations
/// as `yield`.
///
/// **Needs clarification**: Is that even correct? The coroutine drop code is always confusing
/// to me, because it's not even really in the current body.
///
/// **Needs clarification**: Are there type system constraints on these terminators? Should
/// there be a "block type" like `cleanup` blocks for them?
CoroutineDrop,
/// A block where control flow only ever takes one real path, but borrowck needs to be more
/// conservative.
///
/// At runtime this is semantically just a goto.
///
/// Disallowed after drop elaboration.
FalseEdge {
/// The target normal control flow will take.
real_target: BasicBlock,
/// A block control flow could conceptually jump to, but won't in
/// practice.
imaginary_target: BasicBlock,
},
/// A terminator for blocks that only take one path in reality, but where we reserve the right
/// to unwind in borrowck, even if it won't happen in practice. This can arise in infinite loops
/// with no function calls for example.
///
/// At runtime this is semantically just a goto.
///
/// Disallowed after drop elaboration.
FalseUnwind {
/// The target normal control flow will take.
real_target: BasicBlock,
/// The imaginary cleanup block link. This particular path will never be taken
/// in practice, but in order to avoid fragility we want to always
/// consider it in borrowck. We don't want to accept programs which
/// pass borrowck only when `panic=abort` or some assertions are disabled
/// due to release vs. debug mode builds.
unwind: UnwindAction,
},
/// Block ends with an inline assembly block. This is a terminator since
/// inline assembly is allowed to diverge.
InlineAsm {
/// Macro used to create this inline asm: one of `asm!` or `naked_asm!`
asm_macro: InlineAsmMacro,
/// The template for the inline assembly, with placeholders.
#[type_foldable(identity)]
#[type_visitable(ignore)]
template: &'tcx [InlineAsmTemplatePiece],
/// The operands for the inline assembly, as `Operand`s or `Place`s.
operands: Box<[InlineAsmOperand<'tcx>]>,
/// Miscellaneous options for the inline assembly.
options: InlineAsmOptions,
/// Source spans for each line of the inline assembly code. These are
/// used to map assembler errors back to the line in the source code.
#[type_foldable(identity)]
#[type_visitable(ignore)]
line_spans: &'tcx [Span],
/// Valid targets for the inline assembly.
/// The first element is the fallthrough destination, unless
/// asm_macro == InlineAsmMacro::NakedAsm or InlineAsmOptions::NORETURN is set.
targets: Box<[BasicBlock]>,
/// Action to be taken if the inline assembly unwinds. This is present
/// if and only if InlineAsmOptions::MAY_UNWIND is set.
unwind: UnwindAction,
},
}
#[derive(
Clone,
Debug,
TyEncodable,
TyDecodable,
Hash,
HashStable,
PartialEq,
TypeFoldable,
TypeVisitable
)]
pub enum BackwardIncompatibleDropReason {
Edition2024,
}
#[derive(Debug, Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)]
pub struct SwitchTargets {
/// Possible values. For each value, the location to branch to is found in
/// the corresponding element in the `targets` vector.
pub(super) values: SmallVec<[Pu128; 1]>,
/// Possible branch targets. The last element of this vector is used for
/// the "otherwise" branch, so `targets.len() == values.len() + 1` always
/// holds.
//
// Note: This invariant is non-obvious and easy to violate. This would be a
// more rigorous representation:
//
// normal: SmallVec<[(Pu128, BasicBlock); 1]>,
// otherwise: BasicBlock,
//
// But it's important to have the targets in a sliceable type, because
// target slices show up elsewhere. E.g. `TerminatorKind::InlineAsm` has a
// boxed slice, and `TerminatorKind::FalseEdge` has a single target that
// can be converted to a slice with `slice::from_ref`.
//
// Why does this matter? In functions like `TerminatorKind::successors` we
// return `impl Iterator` and a non-slice-of-targets representation here
// causes problems because multiple different concrete iterator types would
// be involved and we would need a boxed trait object, which requires an
// allocation, which is expensive if done frequently.
pub(super) targets: SmallVec<[BasicBlock; 2]>,
}
/// Action to be taken when a stack unwind happens.
#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
#[derive(TypeFoldable, TypeVisitable)]
pub enum UnwindAction {
/// No action is to be taken. Continue unwinding.
///
/// This is similar to `Cleanup(bb)` where `bb` does nothing but `Resume`, but they are not
/// equivalent, as presence of `Cleanup(_)` will make a frame non-POF.
Continue,
/// Triggers undefined behavior if unwind happens.
Unreachable,
/// Terminates the execution if unwind happens.
///
/// Depending on the platform and situation this may cause a non-unwindable panic or abort.
Terminate(UnwindTerminateReason),
/// Cleanups to be done.
Cleanup(BasicBlock),
}
/// The reason we are terminating the process during unwinding.
#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
#[derive(TypeFoldable, TypeVisitable)]
pub enum UnwindTerminateReason {
/// Unwinding is just not possible given the ABI of this function.
Abi,
/// We were already cleaning up for an ongoing unwind, and a *second*, *nested* unwind was
/// triggered by the drop glue.
InCleanup,
}
/// Information about an assertion failure.
#[derive(Clone, Hash, HashStable, PartialEq, Debug)]
#[derive(TyEncodable, TyDecodable, TypeFoldable, TypeVisitable)]
pub enum AssertKind<O> {
BoundsCheck { len: O, index: O },
Overflow(BinOp, O, O),
OverflowNeg(O),
DivisionByZero(O),
RemainderByZero(O),
ResumedAfterReturn(CoroutineKind),
ResumedAfterPanic(CoroutineKind),
ResumedAfterDrop(CoroutineKind),
MisalignedPointerDereference { required: O, found: O },
NullPointerDereference,
InvalidEnumConstruction(O),
}
#[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
#[derive(TypeFoldable, TypeVisitable)]
pub enum InlineAsmOperand<'tcx> {
In {
reg: InlineAsmRegOrRegClass,
value: Operand<'tcx>,
},
Out {
reg: InlineAsmRegOrRegClass,
late: bool,
place: Option<Place<'tcx>>,
},
InOut {
reg: InlineAsmRegOrRegClass,
late: bool,
in_value: Operand<'tcx>,
out_place: Option<Place<'tcx>>,
},
Const {
value: Box<ConstOperand<'tcx>>,
},
SymFn {
value: Box<ConstOperand<'tcx>>,
},
SymStatic {
def_id: DefId,
},
Label {
/// This represents the index into the `targets` array in `TerminatorKind::InlineAsm`.
target_index: usize,
},
}
/// Type for MIR `Assert` terminator error messages.
pub type AssertMessage<'tcx> = AssertKind<Operand<'tcx>>;
///////////////////////////////////////////////////////////////////////////
// Places
/// Places roughly correspond to a "location in memory." Places in MIR are the same mathematical
/// object as places in Rust. This of course means that what exactly they are is undecided and part
/// of the Rust memory model. However, they will likely contain at least the following pieces of
/// information in some form:
///
/// 1. The address in memory that the place refers to.
/// 2. The provenance with which the place is being accessed.
/// 3. The type of the place and an optional variant index. See [`PlaceTy`][super::PlaceTy].
/// 4. Optionally, some metadata. This exists if and only if the type of the place is not `Sized`.
///
/// We'll give a description below of how all pieces of the place except for the provenance are
/// calculated. We cannot give a description of the provenance, because that is part of the
/// undecided aliasing model - we only include it here at all to acknowledge its existence.
///
/// Each local naturally corresponds to the place `Place { local, projection: [] }`. This place has
/// the address of the local's allocation and the type of the local.
///
/// For places that are not locals, ie they have a non-empty list of projections, we define the
/// values as a function of the parent place, that is the place with its last [`ProjectionElem`]
/// stripped. The way this is computed of course depends on the kind of that last projection
/// element:
///
/// - [`Downcast`](ProjectionElem::Downcast): This projection sets the place's variant index to the
/// given one, and makes no other changes. A `Downcast` projection must always be followed
/// immediately by a `Field` projection.
/// - [`Field`](ProjectionElem::Field): `Field` projections take their parent place and create a
/// place referring to one of the fields of the type. The resulting address is the parent
/// address, plus the offset of the field. The type becomes the type of the field. If the parent
/// was unsized and so had metadata associated with it, then the metadata is retained if the
/// field is unsized and thrown out if it is sized.
///
/// These projections are only legal for tuples, ADTs, closures, and coroutines. If the ADT or
/// coroutine has more than one variant, the parent place's variant index must be set, indicating
/// which variant is being used. If it has just one variant, the variant index may or may not be
/// included - the single possible variant is inferred if it is not included.
/// - [`OpaqueCast`](ProjectionElem::OpaqueCast): This projection changes the place's type to the
/// given one, and makes no other changes. A `OpaqueCast` projection on any type other than an
/// opaque type from the current crate is not well-formed.
/// - [`ConstantIndex`](ProjectionElem::ConstantIndex): Computes an offset in units of `T` into the
/// place as described in the documentation for the `ProjectionElem`. The resulting address is
/// the parent's address plus that offset, and the type is `T`. This is only legal if the parent
/// place has type `[T; N]` or `[T]` (*not* `&[T]`). Since such a `T` is always sized, any
/// resulting metadata is thrown out.
/// - [`Subslice`](ProjectionElem::Subslice): This projection calculates an offset and a new
/// address in a similar manner as `ConstantIndex`. It is also only legal on `[T; N]` and `[T]`.
/// However, this yields a `Place` of type `[T]`, and additionally sets the metadata to be the
/// length of the subslice.
/// - [`Index`](ProjectionElem::Index): Like `ConstantIndex`, only legal on `[T; N]` or `[T]`.
/// However, `Index` additionally takes a local from which the value of the index is computed at
/// runtime. Computing the value of the index involves interpreting the `Local` as a
/// `Place { local, projection: [] }`, and then computing its value as if done via
/// [`Operand::Copy`]. The array/slice is then indexed with the resulting value. The local must
/// have type `usize`.
/// - [`Deref`](ProjectionElem::Deref): Derefs are the last type of projection, and the most
/// complicated. They are only legal on parent places that are references, pointers, or `Box`. A
/// `Deref` projection begins by loading a value from the parent place, as if by
/// [`Operand::Copy`]. It then dereferences the resulting pointer, creating a place of the
/// pointee's type. The resulting address is the address that was stored in the pointer. If the
/// pointee type is unsized, the pointer additionally stored the value of the metadata.
///
/// The "validity invariant" of places is the same as that of raw pointers, meaning that e.g.
/// `*ptr` on a dangling or unaligned pointer is never UB. (Later doing a load/store on that place
/// or turning it into a reference can be UB though!) The only ways for a place computation can
/// cause UB are:
/// - On a `Deref` projection, we do an actual load of the inner place, with all the usual
/// consequences (the inner place must be based on an aligned pointer, it must point to allocated
/// memory, the aliasig model must allow reads, this must not be a data race).
/// - For the projections that perform pointer arithmetic, the offset must in-bounds of an
/// allocation (i.e., the preconditions of `ptr::offset` must be met).
#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, HashStable, TypeFoldable, TypeVisitable)]
pub struct Place<'tcx> {
pub local: Local,
/// projection out of a place (access a field, deref a pointer, etc)
pub projection: &'tcx List<PlaceElem<'tcx>>,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[derive(TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
pub enum ProjectionElem<V, T> {
Deref,
/// A field (e.g., `f` in `_1.f`) is one variant of [`ProjectionElem`]. Conceptually,
/// rustc can identify that a field projection refers to either two different regions of memory
/// or the same one between the base and the 'projection element'.
/// Read more about projections in the [rustc-dev-guide][mir-datatypes]
///
/// [mir-datatypes]: https://rustc-dev-guide.rust-lang.org/mir/index.html#mir-data-types
Field(FieldIdx, T),
/// Index into a slice/array.
///
/// Note that this does not also dereference, and so it does not exactly correspond to slice
/// indexing in Rust. In other words, in the below Rust code:
///
/// ```rust
/// let x = &[1, 2, 3, 4];
/// let i = 2;
/// x[i];
/// ```
///
/// The `x[i]` is turned into a `Deref` followed by an `Index`, not just an `Index`. The same
/// thing is true of the `ConstantIndex` and `Subslice` projections below.
Index(V),
/// These endpoint-relative indices are generated by slice/array patterns.
///
/// For array types, `offset` is always relative to the start of the array.
/// For slice types, `from_end` determines whether `offset` is relative to
/// the start or the end of the slice being inspected.
///
/// Slice-pattern indices are easiest to explain by the position of `X` in
/// these examples:
///
/// ```ignore (illustrative)
/// [X, _, .., _, _] => { offset: 0, min_length: 4, from_end: false },
/// [_, X, .., _, _] => { offset: 1, min_length: 4, from_end: false },
/// [_, _, .., X, _] => { offset: 2, min_length: 4, from_end: true },
/// [_, _, .., _, X] => { offset: 1, min_length: 4, from_end: true },
/// ```
ConstantIndex {
/// - If `from_end == false`, this is a 0-based offset from the start of the array/slice.
/// - If `from_end == true`, this is a 1-based offset from the end of the slice.
offset: u64,
/// The thing being indexed must be at least this long -- otherwise, the
/// projection is UB.
///
/// For arrays this is always the exact length.
min_length: u64,
/// If `true`, `offset` is a 1-based offset from the end of the slice.
/// Always false when indexing an array.
from_end: bool,
},
/// These indices are generated by slice patterns.
///
/// If `from_end` is true `slice[from..slice.len() - to]`.
/// Otherwise `array[from..to]`.
///
/// This projection cannot have `ConstantIndex` or additional `Subslice` projections after it
/// before runtime MIR.
Subslice {
from: u64,
to: u64,
/// Whether `to` counts from the start or end of the array/slice.
/// For `PlaceElem`s this is `true` if and only if the base is a slice.
/// For `ProjectionKind`, this can also be `true` for arrays.
from_end: bool,
},
/// "Downcast" to a variant of an enum or a coroutine.
///
/// The included Symbol is the name of the variant, used for printing MIR.
///
/// This operation itself is never UB, all it does is change the type of the place.
Downcast(Option<Symbol>, VariantIdx),
/// Like an explicit cast from an opaque type to a concrete type, but without
/// requiring an intermediate variable.
///
/// This is unused with `-Znext-solver`.
OpaqueCast(T),
/// A transmute from an unsafe binder to the type that it wraps. This is a projection
/// of a place, so it doesn't necessarily constitute a move out of the binder.
UnwrapUnsafeBinder(T),
}
/// Alias for projections as they appear in places, where the base is a place
/// and the index is a local.
pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>;
///////////////////////////////////////////////////////////////////////////
// Operands
/// An operand in MIR represents a "value" in Rust, the definition of which is undecided and part of
/// the memory model. One proposal for a definition of values can be found [on UCG][value-def].
///
/// [value-def]: https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/value-domain.md
///
/// The most common way to create values is via loading a place. Loading a place is an operation
/// which reads the memory of the place and converts it to a value. This is a fundamentally *typed*
/// operation. The nature of the value produced depends on the type of the conversion. Furthermore,
/// there may be other effects: if the type has a validity constraint loading the place might be UB
/// if the validity constraint is not met.
///
/// **Needs clarification:** Is loading a place that has its variant index set well-formed? Miri
/// currently implements it, but it seems like this may be something to check against in the
/// validator.
#[derive(Clone, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable, TypeVisitable)]
pub enum Operand<'tcx> {
/// Creates a value by loading the given place.
///
/// Before drop elaboration, the type of the place must be `Copy`. After drop elaboration there
/// is no such requirement.
Copy(Place<'tcx>),
/// Creates a value by performing loading the place, just like the `Copy` operand.
///
/// This *may* additionally overwrite the place with `uninit` bytes, depending on how we decide
/// in [UCG#188]. You should not emit MIR that may attempt a subsequent second load of this
/// place without first re-initializing it.
///
/// **Needs clarification:** The operational impact of `Move` is unclear. Currently (both in
/// Miri and codegen) it has no effect at all unless it appears in an argument to `Call`; for
/// `Call` it allows the argument to be passed to the callee "in-place", i.e. the callee might
/// just get a reference to this place instead of a full copy. Miri implements this with a
/// combination of aliasing model "protectors" and putting `uninit` into the place. Ralf
/// proposes that we don't want these semantics for `Move` in regular assignments, because
/// loading a place should not have side-effects, and the aliasing model "protectors" are
/// inherently tied to a function call. Are these the semantics we want for MIR? Is this
/// something we can even decide without knowing more about Rust's memory model?
///
/// [UCG#188]: https://github.com/rust-lang/unsafe-code-guidelines/issues/188
Move(Place<'tcx>),
/// Constants are already semantically values, and remain unchanged.
Constant(Box<ConstOperand<'tcx>>),
/// Query the compilation session of the current crate for a particular flag. This is not quite
/// a const since its value can differ across crates within a single crate graph.
RuntimeChecks(RuntimeChecks),
}
#[derive(Clone, Copy, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)]
#[derive(TypeFoldable, TypeVisitable)]
pub struct ConstOperand<'tcx> {
pub span: Span,
/// Optional user-given type: for something like
/// `collect::<Vec<_>>`, this would be present and would
/// indicate that `Vec<_>` was explicitly specified.
///
/// Needed for NLL to impose user-given type constraints.
pub user_ty: Option<UserTypeAnnotationIndex>,
pub const_: Const<'tcx>,
}
///////////////////////////////////////////////////////////////////////////
// Rvalues
/// The various kinds of rvalues that can appear in MIR.
///
/// Not all of these are allowed at every [`MirPhase`] - when this is the case, it's stated below.
///
/// Computing any rvalue begins by evaluating the places and operands in some order (**Needs
/// clarification**: Which order?). These are then used to produce a "value" - the same kind of
/// value that an [`Operand`] produces.
#[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, TypeFoldable, TypeVisitable)]
pub enum Rvalue<'tcx> {
/// Yields the operand unchanged
Use(Operand<'tcx>),
/// Creates an array where each element is the value of the operand.
///
/// Corresponds to source code like `[x; 32]`.
Repeat(Operand<'tcx>, ty::Const<'tcx>),
/// Creates a reference of the indicated kind to the place.
///
/// There is not much to document here, because besides the obvious parts the semantics of this
/// are essentially entirely a part of the aliasing model. There are many UCG issues discussing
/// exactly what the behavior of this operation should be.
///
/// `Shallow` borrows are disallowed after drop lowering.
Ref(Region<'tcx>, BorrowKind, Place<'tcx>),
/// Creates a pointer/reference to the given thread local.
///
/// The yielded type is a `*mut T` if the static is mutable, otherwise if the static is extern a
/// `*const T`, and if neither of those apply a `&T`.
///
/// **Note:** This is a runtime operation that actually executes code and is in this sense more
/// like a function call. Also, eliminating dead stores of this rvalue causes `fn main() {}` to
/// SIGILL for some reason that I (JakobDegen) never got a chance to look into.
///
/// **Needs clarification**: Are there weird additional semantics here related to the runtime
/// nature of this operation?
ThreadLocalRef(DefId),
/// Creates a raw pointer with the indicated mutability to the place.
///
/// This is generated by pointer casts like `&v as *const _` or raw borrow expressions like
/// `&raw const v`.
///
/// Like with references, the semantics of this operation are heavily dependent on the aliasing
/// model.
RawPtr(RawPtrKind, Place<'tcx>),
/// Performs essentially all of the casts that can be performed via `as`.
///
/// This allows for casts from/to a variety of types.
///
/// **FIXME**: Document exactly which `CastKind`s allow which types of casts.
Cast(CastKind, Operand<'tcx>, Ty<'tcx>),
/// * `Offset` has the same semantics as [`offset`](pointer::offset), except that the second
/// parameter may be a `usize` as well.
/// * The comparison operations accept `bool`s, `char`s, signed or unsigned integers, floats,
/// raw pointers, or function pointers and return a `bool`. The types of the operands must be
/// matching, up to the usual caveat of the lifetimes in function pointers.
/// * Left and right shift operations accept signed or unsigned integers not necessarily of the
/// same type and return a value of the same type as their LHS. Like in Rust, the RHS is
/// truncated as needed.
/// * The `Bit*` operations accept signed integers, unsigned integers, or bools with matching
/// types and return a value of that type.
/// * The `FooWithOverflow` are like the `Foo`, but returning `(T, bool)` instead of just `T`,
/// where the `bool` is true if the result is not equal to the infinite-precision result.
/// * The remaining operations accept signed integers, unsigned integers, or floats with
/// matching types and return a value of that type.
BinaryOp(BinOp, Box<(Operand<'tcx>, Operand<'tcx>)>),
/// Exactly like `BinaryOp`, but less operands.
///
/// Also does two's-complement arithmetic. Negation requires a signed integer or a float;
/// bitwise not requires a signed integer, unsigned integer, or bool. Both operation kinds
/// return a value with the same type as their operand.
UnaryOp(UnOp, Operand<'tcx>),
/// Computes the discriminant of the place, returning it as an integer of type
/// [`discriminant_ty`]. Returns zero for types without discriminant.
///
/// The validity requirements for the underlying value are undecided for this rvalue, see
/// [#91095]. Note too that the value of the discriminant is not the same thing as the
/// variant index; use [`discriminant_for_variant`] to convert.
///
/// [`discriminant_ty`]: crate::ty::Ty::discriminant_ty
/// [#91095]: https://github.com/rust-lang/rust/issues/91095
/// [`discriminant_for_variant`]: crate::ty::Ty::discriminant_for_variant
Discriminant(Place<'tcx>),
/// Creates an aggregate value, like a tuple or struct.
///
/// This is needed because dataflow analysis needs to distinguish
/// `dest = Foo { x: ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case that `Foo`
/// has a destructor.
///
/// Disallowed after deaggregation for all aggregate kinds except `Array` and `Coroutine`. After
/// coroutine lowering, `Coroutine` aggregate kinds are disallowed too.
Aggregate(Box<AggregateKind<'tcx>>, IndexVec<FieldIdx, Operand<'tcx>>),
/// Transmutes a `*mut u8` into shallow-initialized `Box<T>`.
///
/// This is different from a normal transmute because dataflow analysis will treat the box as
/// initialized but its content as uninitialized. Like other pointer casts, this in general
/// affects alias analysis.
ShallowInitBox(Operand<'tcx>, Ty<'tcx>),
/// A CopyForDeref is equivalent to a read from a place at the
/// codegen level, but is treated specially by drop elaboration. When such a read happens, it
/// is guaranteed (via nature of the mir_opt `Derefer` in rustc_mir_transform/src/deref_separator)
/// that the returned value is written into a `DerefTemp` local and that its only use is a deref operation,
/// immediately followed by one or more projections. Drop elaboration treats this rvalue as if the
/// read never happened and just projects further. This allows simplifying various MIR
/// optimizations and codegen backends that previously had to handle deref operations anywhere
/// in a place.
///
/// Disallowed in runtime MIR and is replaced by normal copies.
CopyForDeref(Place<'tcx>),
/// Wraps a value in an unsafe binder.
WrapUnsafeBinder(Operand<'tcx>, Ty<'tcx>),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
pub enum CastKind {
/// An exposing pointer to address cast. A cast between a pointer and an integer type, or
/// between a function pointer and an integer type.
/// See the docs on `expose_provenance` for more details.
PointerExposeProvenance,
/// An address-to-pointer cast that picks up an exposed provenance.
/// See the docs on `with_exposed_provenance` for more details.
PointerWithExposedProvenance,
/// Pointer related casts that are done by coercions. Note that reference-to-raw-ptr casts are
/// translated into `&raw mut/const *r`, i.e., they are not actually casts.
///
/// The following are allowed in [`AnalysisPhase::Initial`] as they're needed for borrowck,
/// but after that are forbidden (including in all phases of runtime MIR):
/// * [`PointerCoercion::ArrayToPointer`]
/// * [`PointerCoercion::MutToConstPointer`]
///
/// Both are runtime nops, so should be [`CastKind::PtrToPtr`] instead in runtime MIR.
PointerCoercion(PointerCoercion, CoercionSource),
IntToInt,
FloatToInt,
FloatToFloat,
IntToFloat,
PtrToPtr,
FnPtrToPtr,
/// Reinterpret the bits of the input as a different type.
///
/// MIR is well-formed if the input and output types have different sizes,
/// but running a transmute between differently-sized types is UB.
Transmute,
/// A `Subtype` cast is applied to any `StatementKind::Assign` where
/// type of lvalue doesn't match the type of rvalue, the primary goal is making subtyping
/// explicit during optimizations and codegen.
///
/// This cast doesn't impact the runtime behavior of the program except for potentially changing
/// some type metadata of the interpreter or codegen backend.
///
/// This goal is achieved with mir_transform pass `Subtyper`, which runs right after
/// borrowchecker, as we only care about subtyping that can affect trait selection and
/// `TypeId`.
Subtype,
}
/// Represents how a [`CastKind::PointerCoercion`] was constructed.
/// Used only for diagnostics.
#[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
pub enum CoercionSource {
/// The coercion was manually written by the user with an `as` cast.
AsCast,
/// The coercion was automatically inserted by the compiler.
Implicit,
}
#[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
#[derive(TypeFoldable, TypeVisitable)]
pub enum AggregateKind<'tcx> {
/// The type is of the element
Array(Ty<'tcx>),
Tuple,
/// The second field is the variant index. It's equal to 0 for struct
/// and union expressions. The last field is the
/// active field number and is present only for union expressions
/// -- e.g., for a union expression `SomeUnion { c: .. }`, the
/// active field index would identity the field `c`
Adt(DefId, VariantIdx, GenericArgsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<FieldIdx>),
Closure(DefId, GenericArgsRef<'tcx>),
Coroutine(DefId, GenericArgsRef<'tcx>),
CoroutineClosure(DefId, GenericArgsRef<'tcx>),
/// Construct a raw pointer from the data pointer and metadata.
///
/// The `Ty` here is the type of the *pointee*, not the pointer itself.
/// The `Mutability` indicates whether this produces a `*const` or `*mut`.
///
/// The [`Rvalue::Aggregate`] operands for thus must be
///
/// 0. A raw pointer of matching mutability with any [`core::ptr::Thin`] pointee
/// 1. A value of the appropriate [`core::ptr::Pointee::Metadata`] type
///
/// *Both* operands must always be included, even the unit value if this is
/// creating a thin pointer. If you're just converting between thin pointers,
/// you may want an [`Rvalue::Cast`] with [`CastKind::PtrToPtr`] instead.
RawPtr(Ty<'tcx>, Mutability),
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)]
pub enum RuntimeChecks {
/// Returns whether we should perform some UB-checking at runtime.
/// See the `ub_checks` intrinsic docs for details.
UbChecks,
/// Returns whether we should perform contract-checking at runtime.
/// See the `contract_checks` intrinsic docs for details.
ContractChecks,
/// Returns whether we should perform some overflow-checking at runtime.
/// See the `overflow_checks` intrinsic docs for details.
OverflowChecks,
}
impl RuntimeChecks {
pub fn value(self, sess: &rustc_session::Session) -> bool {
match self {
Self::UbChecks => sess.ub_checks(),
Self::ContractChecks => sess.contract_checks(),
Self::OverflowChecks => sess.overflow_checks(),
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable, TypeVisitable)]
pub enum UnOp {
/// The `!` operator for logical inversion
Not,
/// The `-` operator for negation
Neg,
/// Gets the metadata `M` from a `*const`/`*mut`/`&`/`&mut` to
/// `impl Pointee<Metadata = M>`.
///
/// For example, this will give a `()` from `*const i32`, a `usize` from
/// `&mut [u8]`, or a `ptr::DynMetadata<dyn Foo>` (internally a pointer)
/// from a `*mut dyn Foo`.
///
/// Allowed only in [`MirPhase::Runtime`]; earlier it's an intrinsic.
PtrMetadata,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
#[derive(TyEncodable, TyDecodable, HashStable, TypeFoldable, TypeVisitable)]
pub enum BinOp {
/// The `+` operator (addition)
Add,
/// Like `Add`, but with UB on overflow. (Integers only.)
AddUnchecked,
/// Like `Add`, but returns `(T, bool)` of both the wrapped result
/// and a bool indicating whether it overflowed.
AddWithOverflow,
/// The `-` operator (subtraction)
Sub,
/// Like `Sub`, but with UB on overflow. (Integers only.)
SubUnchecked,
/// Like `Sub`, but returns `(T, bool)` of both the wrapped result
/// and a bool indicating whether it overflowed.
SubWithOverflow,
/// The `*` operator (multiplication)
Mul,
/// Like `Mul`, but with UB on overflow. (Integers only.)
MulUnchecked,
/// Like `Mul`, but returns `(T, bool)` of both the wrapped result
/// and a bool indicating whether it overflowed.
MulWithOverflow,
/// The `/` operator (division)
///
/// For integer types, division by zero is UB, as is `MIN / -1` for signed.
/// The compiler should have inserted checks prior to this.
///
/// Floating-point division by zero is safe, and does not need guards.
Div,
/// The `%` operator (modulus)
///
/// For integer types, using zero as the modulus (second operand) is UB,
/// as is `MIN % -1` for signed.
/// The compiler should have inserted checks prior to this.
///
/// Floating-point remainder by zero is safe, and does not need guards.
Rem,
/// The `^` operator (bitwise xor)
BitXor,
/// The `&` operator (bitwise and)
BitAnd,
/// The `|` operator (bitwise or)
BitOr,
/// The `<<` operator (shift left)
///
/// The offset is given by `RHS.rem_euclid(LHS::BITS)`.
/// In other words, it is (uniquely) determined as follows:
/// - it is "equal modulo LHS::BITS" to the RHS
/// - it is in the range `0..LHS::BITS`
Shl,
/// Like `Shl`, but is UB if the RHS >= LHS::BITS or RHS < 0
ShlUnchecked,
/// The `>>` operator (shift right)
///
/// The offset is given by `RHS.rem_euclid(LHS::BITS)`.
/// In other words, it is (uniquely) determined as follows:
/// - it is "equal modulo LHS::BITS" to the RHS
/// - it is in the range `0..LHS::BITS`
///
/// This is an arithmetic shift if the LHS is signed
/// and a logical shift if the LHS is unsigned.
Shr,
/// Like `Shl`, but is UB if the RHS >= LHS::BITS or RHS < 0
ShrUnchecked,
/// The `==` operator (equality)
Eq,
/// The `<` operator (less than)
Lt,
/// The `<=` operator (less than or equal to)
Le,
/// The `!=` operator (not equal to)
Ne,
/// The `>=` operator (greater than or equal to)
Ge,
/// The `>` operator (greater than)
Gt,
/// The `<=>` operator (three-way comparison, like `Ord::cmp`)
///
/// This is supported only on the integer types and `char`, always returning
/// [`rustc_hir::LangItem::OrderingEnum`] (aka [`std::cmp::Ordering`]).
///
/// [`Rvalue::BinaryOp`]`(BinOp::Cmp, A, B)` returns
/// - `Ordering::Less` (`-1_i8`, as a Scalar) if `A < B`
/// - `Ordering::Equal` (`0_i8`, as a Scalar) if `A == B`
/// - `Ordering::Greater` (`+1_i8`, as a Scalar) if `A > B`
Cmp,
/// The `ptr.offset` operator
Offset,
}
// Assignment operators, e.g. `+=`. See comments on the corresponding variants
// in `BinOp` for details.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
pub enum AssignOp {
AddAssign,
SubAssign,
MulAssign,
DivAssign,
RemAssign,
BitXorAssign,
BitAndAssign,
BitOrAssign,
ShlAssign,
ShrAssign,
}
// Sometimes `BinOp` and `AssignOp` need the same treatment. The operations
// covered by `AssignOp` are a subset of those covered by `BinOp`, so it makes
// sense to convert `AssignOp` to `BinOp`.
impl From<AssignOp> for BinOp {
fn from(op: AssignOp) -> BinOp {
match op {
AssignOp::AddAssign => BinOp::Add,
AssignOp::SubAssign => BinOp::Sub,
AssignOp::MulAssign => BinOp::Mul,
AssignOp::DivAssign => BinOp::Div,
AssignOp::RemAssign => BinOp::Rem,
AssignOp::BitXorAssign => BinOp::BitXor,
AssignOp::BitAndAssign => BinOp::BitAnd,
AssignOp::BitOrAssign => BinOp::BitOr,
AssignOp::ShlAssign => BinOp::Shl,
AssignOp::ShrAssign => BinOp::Shr,
}
}
}
// Some nodes are used a lot. Make sure they don't unintentionally get bigger.
#[cfg(target_pointer_width = "64")]
mod size_asserts {
use rustc_data_structures::static_assert_size;
use super::*;
// tidy-alphabetical-start
static_assert_size!(AggregateKind<'_>, 32);
static_assert_size!(Operand<'_>, 24);
static_assert_size!(Place<'_>, 16);
static_assert_size!(PlaceElem<'_>, 24);
static_assert_size!(Rvalue<'_>, 40);
static_assert_size!(StatementKind<'_>, 16);
static_assert_size!(TerminatorKind<'_>, 80);
// tidy-alphabetical-end
}
|
rust
|
github
|
https://github.com/rust-lang/rust
|
compiler/rustc_middle/src/mir/syntax.rs
|
#### Note: this error code is no longer emitted by the compiler.
A trait object has some specific lifetime `'1`, but it was used in a way that
requires it to have a `'static` lifetime.
Example of erroneous code:
```compile_fail
trait BooleanLike {}
trait Person {}
impl BooleanLike for bool {}
impl dyn Person {
fn is_cool(&self) -> bool {
// hey you, you're pretty cool
true
}
}
fn get_is_cool<'p>(person: &'p dyn Person) -> impl BooleanLike {
// error: `person` has an anonymous lifetime `'p` but calling
// `print_cool_fn` introduces an implicit `'static` lifetime
// requirement
person.is_cool()
}
```
The trait object `person` in the function `get_is_cool`, while already being
behind a reference with lifetime `'p`, also has it's own implicit lifetime,
`'2`.
Lifetime `'2` represents the data the trait object might hold inside, for
example:
```
trait MyTrait {}
struct MyStruct<'a>(&'a i32);
impl<'a> MyTrait for MyStruct<'a> {}
```
With this scenario, if a trait object of `dyn MyTrait + '2` was made from
`MyStruct<'a>`, `'a` must live as long, if not longer than `'2`. This allows the
trait object's internal data to be accessed safely from any trait methods. This
rule also goes for any lifetime any struct made into a trait object may have.
In the implementation for `dyn Person`, the `'2` lifetime representing the
internal data was omitted, meaning that the compiler inferred the lifetime
`'static`. As a result, the implementation's `is_cool` is inferred by the
compiler to look like this:
```
# trait Person {}
#
# impl dyn Person {
fn is_cool<'a>(self: &'a (dyn Person + 'static)) -> bool {unimplemented!()}
# }
```
While the `get_is_cool` function is inferred to look like this:
```
# trait Person {}
# trait BooleanLike {}
#
fn get_is_cool<'p, R: BooleanLike>(person: &'p (dyn Person + 'p)) -> R {
unimplemented!()
}
```
Which brings us to the core of the problem; the assignment of type
`&'_ (dyn Person + '_)` to type `&'_ (dyn Person + 'static)` is impossible.
Fixing it is as simple as being generic over lifetime `'2`, as to prevent the
compiler from inferring it as `'static`:
```
# trait Person {}
#
impl<'d> dyn Person + 'd {/* ... */}
// This works too, and is more elegant:
//impl dyn Person + '_ {/* ... */}
```
See the [Rust Reference on Trait Object Lifetime Bounds][trait-objects] for
more information on trait object lifetimes.
[trait-object-lifetime-bounds]: https://doc.rust-lang.org/reference/types/trait-object.html#trait-object-lifetime-bounds
|
unknown
|
github
|
https://github.com/rust-lang/rust
|
compiler/rustc_error_codes/src/error_codes/E0772.md
|
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
DOCUMENTATION = '''
---
module: nxos_acl
extends_documentation_fragment: nxos
version_added: "2.2"
short_description: Manages access list entries for ACLs.
description:
- Manages access list entries for ACLs.
author:
- Jason Edelman (@jedelman8)
- Gabriele Gerbino (@GGabriele)
notes:
- Tested against NXOSv 7.3.(0)D1(1) on VIRL
- C(state=absent) removes the ACE if it exists.
- C(state=delete_acl) deletes the ACL if it exists.
- For idempotency, use port numbers for the src/dest port
params like I(src_port1) and names for the well defined protocols
for the I(proto) param.
- Although this module is idempotent in that if the ace as presented in
the task is identical to the one on the switch, no changes will be made.
If there is any difference, what is in Ansible will be pushed (configured
options will be overridden). This is to improve security, but at the
same time remember an ACE is removed, then re-added, so if there is a
change, the new ACE will be exactly what parameters you are sending to
the module.
options:
seq:
description:
- Sequence number of the entry (ACE).
name:
description:
- Case sensitive name of the access list (ACL).
required: true
action:
description:
- Action of the ACE.
choices: ['permit', 'deny', 'remark']
remark:
description:
- If action is set to remark, this is the description.
proto:
description:
- Port number or protocol (as supported by the switch).
src:
description:
- Source ip and mask using IP/MASK notation and
supports keyword 'any'.
src_port_op:
description:
- Source port operands such as eq, neq, gt, lt, range.
choices: ['any', 'eq', 'gt', 'lt', 'neq', 'range']
src_port1:
description:
- Port/protocol and also first (lower) port when using range
operand.
src_port2:
description:
- Second (end) port when using range operand.
dest:
description:
- Destination ip and mask using IP/MASK notation and supports the
keyword 'any'.
dest_port_op:
description:
- Destination port operands such as eq, neq, gt, lt, range.
choices: ['any', 'eq', 'gt', 'lt', 'neq', 'range']
dest_port1:
description:
- Port/protocol and also first (lower) port when using range
operand.
dest_port2:
description:
- Second (end) port when using range operand.
log:
description:
- Log matches against this entry.
choices: ['enable']
urg:
description:
- Match on the URG bit.
choices: ['enable']
ack:
description:
- Match on the ACK bit.
choices: ['enable']
psh:
description:
- Match on the PSH bit.
choices: ['enable']
rst:
description:
- Match on the RST bit.
choices: ['enable']
syn:
description:
- Match on the SYN bit.
choices: ['enable']
fin:
description:
- Match on the FIN bit.
choices: ['enable']
established:
description:
- Match established connections.
choices: ['enable']
fragments:
description:
- Check non-initial fragments.
choices: ['enable']
time_range:
description:
- Name of time-range to apply.
precedence:
description:
- Match packets with given precedence.
choices: ['critical', 'flash', 'flash-override', 'immediate',
'internet', 'network', 'priority', 'routine']
dscp:
description:
- Match packets with given dscp value.
choices: ['af11', 'af12', 'af13', 'af21', 'af22', 'af23','af31','af32',
'af33', 'af41', 'af42', 'af43', 'cs1', 'cs2', 'cs3', 'cs4',
'cs5', 'cs6', 'cs7', 'default', 'ef']
state:
description:
- Specify desired state of the resource.
default: present
choices: ['present','absent','delete_acl']
'''
EXAMPLES = '''
# configure ACL ANSIBLE
- nxos_acl:
name: ANSIBLE
seq: 10
action: permit
proto: tcp
src: 1.1.1.1/24
dest: any
state: present
'''
RETURN = '''
commands:
description: commands sent to the device
returned: always
type: list
sample: ["ip access-list ANSIBLE", "10 permit tcp 1.1.1.1/24 any"]
'''
from ansible.module_utils.network.nxos.nxos import load_config, run_commands
from ansible.module_utils.network.nxos.nxos import nxos_argument_spec, check_args
from ansible.module_utils.basic import AnsibleModule
def execute_show_command(command, module):
command += ' | json'
cmds = [command]
body = run_commands(module, cmds)
return body
def get_acl(module, acl_name, seq_number):
command = 'show ip access-list'
new_acl = []
saveme = {}
acl_body = {}
body = execute_show_command(command, module)[0]
if body:
all_acl_body = body['TABLE_ip_ipv6_mac']['ROW_ip_ipv6_mac']
else:
# no access-lists configured on the device
return {}, []
if isinstance(all_acl_body, dict):
# Only 1 ACL configured.
if all_acl_body.get('acl_name') == acl_name:
acl_body = all_acl_body
else:
for acl in all_acl_body:
if acl.get('acl_name') == acl_name:
acl_body = acl
break
try:
acl_entries = acl_body['TABLE_seqno']['ROW_seqno']
acl_name = acl_body.get('acl_name')
except KeyError: # could be raised if no ACEs are configured for an ACL
return {}, [{'acl': 'no_entries'}]
if isinstance(acl_entries, dict):
acl_entries = [acl_entries]
for each in acl_entries:
temp = {}
options = {}
remark = each.get('remark')
temp['name'] = acl_name
temp['seq'] = str(each.get('seqno'))
if remark:
temp['remark'] = remark
temp['action'] = 'remark'
else:
temp['action'] = each.get('permitdeny')
temp['proto'] = str(each.get('proto', each.get('proto_str', each.get('ip'))))
temp['src'] = each.get('src_any', each.get('src_ip_prefix'))
temp['src_port_op'] = each.get('src_port_op')
temp['src_port1'] = each.get('src_port1_num')
temp['src_port2'] = each.get('src_port2_num')
temp['dest'] = each.get('dest_any', each.get('dest_ip_prefix'))
temp['dest_port_op'] = each.get('dest_port_op')
temp['dest_port1'] = each.get('dest_port1_num')
temp['dest_port2'] = each.get('dest_port2_num')
options['log'] = each.get('log')
options['urg'] = each.get('urg')
options['ack'] = each.get('ack')
options['psh'] = each.get('psh')
options['rst'] = each.get('rst')
options['syn'] = each.get('syn')
options['fin'] = each.get('fin')
options['established'] = each.get('established')
options['dscp'] = each.get('dscp_str')
options['precedence'] = each.get('precedence_str')
options['fragments'] = each.get('fragments')
options['time_range'] = each.get('timerange')
keep = {}
for key, value in temp.items():
if value:
keep[key] = value
options_no_null = {}
for key, value in options.items():
if value is not None:
options_no_null[key] = value
keep['options'] = options_no_null
if keep.get('seq') == seq_number:
saveme = dict(keep)
new_acl.append(keep)
return saveme, new_acl
def _acl_operand(operand, srcp1, sprcp2):
sub_entry = ' ' + operand
if operand == 'range':
sub_entry += ' ' + srcp1 + ' ' + sprcp2
else:
sub_entry += ' ' + srcp1
return sub_entry
def config_core_acl(proposed):
seq = proposed.get('seq')
action = proposed.get('action')
remark = proposed.get('remark')
proto = proposed.get('proto')
src = proposed.get('src')
src_port_op = proposed.get('src_port_op')
src_port1 = proposed.get('src_port1')
src_port2 = proposed.get('src_port2')
dest = proposed.get('dest')
dest_port_op = proposed.get('dest_port_op')
dest_port1 = proposed.get('dest_port1')
dest_port2 = proposed.get('dest_port2')
ace_start_entries = [action, proto, src]
if not remark:
ace = seq + ' ' + ' '.join(ace_start_entries)
if src_port_op:
ace += _acl_operand(src_port_op, src_port1, src_port2)
ace += ' ' + dest
if dest_port_op:
ace += _acl_operand(dest_port_op, dest_port1, dest_port2)
else:
ace = seq + ' remark ' + remark
return ace
def config_acl_options(options):
ENABLE_ONLY = ['psh', 'urg', 'log', 'ack', 'syn',
'established', 'rst', 'fin', 'fragments',
'log']
OTHER = ['dscp', 'precedence', 'time-range']
# packet-length is the only option not currently supported
if options.get('time_range'):
options['time-range'] = options.get('time_range')
options.pop('time_range')
command = ''
for option, value in options.items():
if option in ENABLE_ONLY:
if value == 'enable':
command += ' ' + option
elif option in OTHER:
command += ' ' + option + ' ' + value
if command:
command = command.strip()
return command
def flatten_list(command_lists):
flat_command_list = []
for command in command_lists:
if isinstance(command, list):
flat_command_list.extend(command)
else:
flat_command_list.append(command)
return flat_command_list
def main():
argument_spec = dict(
seq=dict(required=False, type='str'),
name=dict(required=True, type='str'),
action=dict(required=False, choices=['remark', 'permit', 'deny']),
remark=dict(required=False, type='str'),
proto=dict(required=False, type='str'),
src=dict(required=False, type='str'),
src_port_op=dict(required=False),
src_port1=dict(required=False, type='str'),
src_port2=dict(required=False, type='str'),
dest=dict(required=False, type='str'),
dest_port_op=dict(required=False),
dest_port1=dict(required=False, type='str'),
dest_port2=dict(required=False, type='str'),
log=dict(required=False, choices=['enable']),
urg=dict(required=False, choices=['enable']),
ack=dict(required=False, choices=['enable']),
psh=dict(required=False, choices=['enable']),
rst=dict(required=False, choices=['enable']),
syn=dict(required=False, choices=['enable']),
fragments=dict(required=False, choices=['enable']),
fin=dict(required=False, choices=['enable']),
established=dict(required=False, choices=['enable']),
time_range=dict(required=False),
precedence=dict(required=False, choices=['critical', 'flash',
'flash-override',
'immediate', 'internet',
'network', 'priority',
'routine']),
dscp=dict(required=False, choices=['af11', 'af12', 'af13', 'af21',
'af22', 'af23', 'af31', 'af32',
'af33', 'af41', 'af42', 'af43',
'cs1', 'cs2', 'cs3', 'cs4',
'cs5', 'cs6', 'cs7', 'default',
'ef']),
state=dict(choices=['absent', 'present', 'delete_acl'], default='present')
)
argument_spec.update(nxos_argument_spec)
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True)
warnings = list()
check_args(module, warnings)
results = dict(changed=False, warnings=warnings)
state = module.params['state']
action = module.params['action']
remark = module.params['remark']
dscp = module.params['dscp']
precedence = module.params['precedence']
seq = module.params['seq']
name = module.params['name']
seq = module.params['seq']
if action == 'remark' and not remark:
module.fail_json(msg='when state is action, remark param is also required')
REQUIRED = ['seq', 'name', 'action', 'proto', 'src', 'dest']
ABSENT = ['name', 'seq']
if state == 'present':
if action and remark and seq:
pass
else:
for each in REQUIRED:
if module.params[each] is None:
module.fail_json(msg="req'd params when state is present:",
params=REQUIRED)
elif state == 'absent':
for each in ABSENT:
if module.params[each] is None:
module.fail_json(msg='require params when state is absent',
params=ABSENT)
elif state == 'delete_acl':
if module.params['name'] is None:
module.fail_json(msg="param name req'd when state is delete_acl")
if dscp and precedence:
module.fail_json(msg='only one of the params dscp/precedence '
'are allowed')
OPTIONS_NAMES = ['log', 'urg', 'ack', 'psh', 'rst', 'syn', 'fin',
'established', 'dscp', 'precedence', 'fragments',
'time_range']
CORE = ['seq', 'name', 'action', 'proto', 'src', 'src_port_op',
'src_port1', 'src_port2', 'dest', 'dest_port_op',
'dest_port1', 'dest_port2', 'remark']
proposed_core = dict((param, value) for (param, value) in
module.params.items()
if param in CORE and value is not None)
proposed_options = dict((param, value) for (param, value) in
module.params.items()
if param in OPTIONS_NAMES and value is not None)
proposed = {}
proposed.update(proposed_core)
proposed.update(proposed_options)
existing_options = {}
# getting existing existing_core=dict, acl=list, seq=list
existing_core, acl = get_acl(module, name, seq)
if existing_core:
existing_options = existing_core.get('options')
existing_core.pop('options')
commands = []
delta_core = {}
delta_options = {}
if not existing_core.get('remark'):
dcore = dict(
set(proposed_core.items()).difference(
existing_core.items())
)
if not dcore:
# check the diff in the other way just in case
dcore = dict(
set(existing_core.items()).difference(
proposed_core.items())
)
delta_core = dcore
if delta_core:
delta_options = proposed_options
else:
doptions = dict(
set(proposed_options.items()).difference(
existing_options.items())
)
# check the diff in the other way just in case
if not doptions:
doptions = dict(
set(existing_options.items()).difference(
proposed_options.items())
)
delta_options = doptions
else:
delta_core = dict(
set(proposed_core.items()).difference(
existing_core.items())
)
if state == 'present':
if delta_core or delta_options:
if existing_core: # if the ace exists already
commands.append(['no {0}'.format(seq)])
if delta_options:
myacl_str = config_core_acl(proposed_core)
myacl_str += ' ' + config_acl_options(proposed_options)
else:
myacl_str = config_core_acl(proposed_core)
command = [myacl_str]
commands.append(command)
elif state == 'absent':
if existing_core:
commands.append(['no {0}'.format(seq)])
elif state == 'delete_acl':
if acl[0].get('acl') != 'no_entries':
commands.append(['no ip access-list {0}'.format(name)])
cmds = []
if commands:
preface = []
if state in ['present', 'absent']:
preface = ['ip access-list {0}'.format(name)]
commands.insert(0, preface)
cmds = flatten_list(commands)
if module.check_mode:
module.exit_json(changed=True, commands=cmds)
else:
load_config(module, cmds)
results['changed'] = True
if 'configure' in cmds:
cmds.pop(0)
results['commands'] = cmds
module.exit_json(**results)
if __name__ == '__main__':
main()
|
unknown
|
codeparrot/codeparrot-clean
| ||
# constantPropagation
## File
`src/Optimization/ConstantPropagation.ts`
## Purpose
Applies Sparse Conditional Constant Propagation (SCCP) to fold compile-time evaluable expressions to constant values, propagate those constants through the program, and eliminate unreachable branches when conditionals have known constant values.
## Input Invariants
- HIR must be in SSA form (runs after `enterSSA`)
- Redundant phi nodes should be eliminated (runs after `eliminateRedundantPhi`)
- Consistent identifiers must be ensured (`assertConsistentIdentifiers`)
- Terminal successors must exist (`assertTerminalSuccessorsExist`)
## Output Guarantees
- Instructions with compile-time evaluable operands are replaced with `Primitive` constants
- `ComputedLoad`/`ComputedStore` with constant string/number properties are converted to `PropertyLoad`/`PropertyStore`
- `LoadLocal` and `StoreLocal` propagate known constant values
- `IfTerminal` with constant boolean test values are replaced with `goto` terminals
- Unreachable blocks are removed and the CFG is minimized
- Phi nodes with unreachable predecessor operands are pruned
- Nested functions (`FunctionExpression`, `ObjectMethod`) are recursively processed
## Algorithm
The pass uses Sparse Conditional Constant Propagation (SCCP) with fixpoint iteration:
1. **Data Structure**: A `Constants` map (`Map<IdentifierId, Constant>`) tracks known constant values (either `Primitive` or `LoadGlobal`)
2. **Single Pass per Iteration**: Visits all blocks in order:
- Evaluates phi nodes - if all operands have the same constant value, the phi result is constant
- Evaluates instructions - replaces evaluable expressions with constants
- Evaluates terminals - if an `IfTerminal` test is a constant, replaces it with a `goto`
3. **Fixpoint Loop**: If any terminals changed (branch elimination):
- Recomputes block ordering (`reversePostorderBlocks`)
- Removes unreachable code (`removeUnreachableForUpdates`, `removeDeadDoWhileStatements`, `removeUnnecessaryTryCatch`)
- Renumbers instructions (`markInstructionIds`)
- Updates predecessors (`markPredecessors`)
- Prunes phi operands from unreachable predecessors
- Eliminates newly-redundant phis (`eliminateRedundantPhi`)
- Merges consecutive blocks (`mergeConsecutiveBlocks`)
- Repeats until no more changes
4. **Instruction Evaluation**: Handles various instruction types:
- **Primitives/LoadGlobal**: Directly constant
- **BinaryExpression**: Folds arithmetic (`+`, `-`, `*`, `/`, `%`, `**`), bitwise (`|`, `&`, `^`, `<<`, `>>`, `>>>`), and comparison (`<`, `<=`, `>`, `>=`, `==`, `===`, `!=`, `!==`) operators
- **UnaryExpression**: Folds `!` (boolean negation) and `-` (numeric negation)
- **PostfixUpdate/PrefixUpdate**: Folds `++`/`--` on constant numbers
- **PropertyLoad**: Folds `.length` on constant strings
- **TemplateLiteral**: Folds template strings with constant interpolations
- **ComputedLoad/ComputedStore**: Converts to property access when property is constant string/number
## Key Data Structures
- `Constant = Primitive | LoadGlobal` - The lattice values (no top/bottom, absence means unknown)
- `Constants = Map<IdentifierId, Constant>` - Maps identifier IDs to their known constant values
- Uses HIR types: `Instruction`, `Phi`, `Place`, `Primitive`, `LoadGlobal`, `InstructionValue`
## Edge Cases
- **Last instruction of sequence blocks**: Skipped to preserve evaluation order
- **Phi nodes with back-edges**: Single-pass analysis means loop back-edges won't have constant values propagated
- **Template literals with Symbol**: Not folded (would throw at runtime)
- **Template literals with objects/arrays**: Not folded (custom toString behavior)
- **Division results**: Computed at compile time (may produce `NaN`, `Infinity`, etc.)
- **LoadGlobal in phis**: Only propagated if all operands reference the same global name
- **Nested functions**: Constants from outer scope are propagated into nested function expressions
## TODOs
- `// TODO: handle more cases` - The default case in `evaluateInstruction` has room for additional instruction types
## Example
**Input:**
```javascript
function Component() {
let a = 1;
let b;
if (a === 1) {
b = true;
} else {
b = false;
}
let c;
if (b) {
c = 'hello';
} else {
c = null;
}
return c;
}
```
**After ConstantPropagation:**
- `a === 1` evaluates to `true`
- The `if (a === 1)` branch is eliminated, only consequent remains
- `b` is known to be `true`
- `if (b)` branch is eliminated, only consequent remains
- `c` is known to be `'hello'`
- All intermediate blocks are merged
**Output:**
```javascript
function Component() {
return "hello";
}
```
The pass performs iterative simplification: first iteration determines `a === 1` is `true` and eliminates that branch. The CFG is updated, phi for `b` is pruned to single operand making `b = true`. Second iteration uses `b = true` to eliminate the next branch. This continues until no more branches can be eliminated.
|
unknown
|
github
|
https://github.com/facebook/react
|
compiler/packages/babel-plugin-react-compiler/docs/passes/04-constantPropagation.md
|
from datetime import datetime, timedelta
import os
import jwt
import json
import requests
from functools import wraps
from urlparse import parse_qs, parse_qsl
from urllib import urlencode
from flask import Flask, g, send_file, request, redirect, url_for, jsonify
from flask.ext.sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from requests_oauthlib import OAuth1
# Configuration
current_path = os.path.dirname(__file__)
client_path = os.path.abspath(os.path.join(current_path, '..', '..', 'client'))
app = Flask(__name__, static_url_path='', static_folder=client_path)
app.config.from_object('config')
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True)
password = db.Column(db.String(120))
display_name = db.Column(db.String(120))
facebook = db.Column(db.String(120))
google = db.Column(db.String(120))
linkedin = db.Column(db.String(120))
twitter = db.Column(db.String(120))
def __init__(self, email=None, password=None, display_name=None,
facebook=None, google=None, linkedin=None, twitter=None):
if email:
self.email = email.lower()
if password:
self.set_password(password)
if display_name:
self.display_name = display_name
if facebook:
self.facebook = facebook
if google:
self.google = google
if linkedin:
self.linkedin = linkedin
if twitter:
self.twitter = twitter
def set_password(self, password):
self.password = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password, password)
def to_json(self):
return dict(id=self.id, email=self.email, displayName=self.display_name,
facebook=self.facebook, google=self.google,
linkedin=self.linkedin, twitter=self.twitter)
db.create_all()
def create_jwt_token(user):
payload = {
'iss': 'localhost',
'sub': user.id,
'iat': datetime.now(),
'exp': datetime.now() + timedelta(days=14)
}
token = jwt.encode(payload, app.config['TOKEN_SECRET'])
return token.decode('unicode_escape')
def parse_token(req):
token = req.headers.get('Authorization').split()[1]
return jwt.decode(token, app.config['TOKEN_SECRET'])
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not request.headers.get('Authorization'):
response = jsonify(message='Missing authorization header')
response.status_code = 401
return response
payload = parse_token(request)
if datetime.fromtimestamp(payload['exp']) < datetime.now():
response = jsonify(message='Token has expired')
response.status_code = 401
return response
g.user_id = payload['sub']
return f(*args, **kwargs)
return decorated_function
# Routes
@app.route('/')
def index():
return send_file('../../client/index.html')
@app.route('/api/me')
@login_required
def me():
user = User.query.filter_by(id=g.user_id).first()
return jsonify(user.to_json())
@app.route('/auth/login', methods=['POST'])
def login():
user = User.query.filter_by(email=request.json['email']).first()
if not user or not user.check_password(request.json['password']):
response = jsonify(message='Wrong Email or Password')
response.status_code = 401
return response
token = create_jwt_token(user)
return jsonify(token=token)
@app.route('/auth/signup', methods=['POST'])
def signup():
user = User(email=request.json['email'], password=request.json['password'])
db.session.add(user)
db.session.commit()
token = create_jwt_token(user)
return jsonify(token=token)
@app.route('/auth/facebook', methods=['POST'])
def facebook():
access_token_url = 'https://graph.facebook.com/oauth/access_token'
graph_api_url = 'https://graph.facebook.com/me'
params = {
'client_id': request.json['clientId'],
'redirect_uri': request.json['redirectUri'],
'client_secret': app.config['FACEBOOK_SECRET'],
'code': request.json['code']
}
# Step 1. Exchange authorization code for access token.
r = requests.get(access_token_url, params=params)
access_token = dict(parse_qsl(r.text))
# Step 2. Retrieve information about the current user.
r = requests.get(graph_api_url, params=access_token)
profile = json.loads(r.text)
# Step 3. (optional) Link accounts.
if request.headers.get('Authorization'):
user = User.query.filter_by(facebook=profile['id']).first()
if user:
response = jsonify(message='There is already a Facebook account that belongs to you')
response.status_code = 409
return response
payload = parse_token(request)
user = User.query.filter_by(id=payload['sub']).first()
if not user:
response = jsonify(message='User not found')
response.status_code = 400
return response
u = User(facebook=profile['id'], display_name=profile['name'])
db.session.add(u)
db.session.commit()
token = create_jwt_token(u)
return jsonify(token=token)
# Step 4. Create a new account or return an existing one.
user = User.query.filter_by(facebook=profile['id']).first()
if user:
token = create_jwt_token(user)
return jsonify(token=token)
u = User(facebook=profile['id'], display_name=profile['name'])
db.session.add(u)
db.session.commit()
token = create_jwt_token(u)
return jsonify(token=token)
@app.route('/auth/google', methods=['POST'])
def google():
access_token_url = 'https://accounts.google.com/o/oauth2/token'
people_api_url = 'https://www.googleapis.com/plus/v1/people/me/openIdConnect'
payload = dict(client_id=request.json['clientId'],
redirect_uri=request.json['redirectUri'],
client_secret=app.config['GOOGLE_SECRET'],
code=request.json['code'],
grant_type='authorization_code')
# Step 1. Exchange authorization code for access token.
r = requests.post(access_token_url, data=payload)
token = json.loads(r.text)
headers = {'Authorization': 'Bearer {0}'.format(token['access_token'])}
# Step 2. Retrieve information about the current user.
r = requests.get(people_api_url, headers=headers)
profile = json.loads(r.text)
user = User.query.filter_by(google=profile['sub']).first()
if user:
token = create_jwt_token(user)
return jsonify(token=token)
u = User(google=profile['sub'],
display_name=profile['displayName'])
db.session.add(u)
db.session.commit()
token = create_jwt_token(u)
return jsonify(token=token)
@app.route('/auth/linkedin', methods=['POST'])
def linkedin():
access_token_url = 'https://www.linkedin.com/uas/oauth2/accessToken'
people_api_url = 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address)'
payload = dict(client_id=request.json['clientId'],
redirect_uri=request.json['redirectUri'],
client_secret=app.config['LINKEDIN_SECRET'],
code=request.json['code'],
grant_type='authorization_code')
# Step 1. Exchange authorization code for access token.
r = requests.post(access_token_url, data=payload)
access_token = json.loads(r.text)
params = dict(oauth2_access_token=access_token['access_token'],
format='json')
# Step 2. Retrieve information about the current user.
r = requests.get(people_api_url, params=params)
profile = json.loads(r.text)
user = User.query.filter_by(linkedin=profile['id']).first()
if user:
token = create_jwt_token(user)
return jsonify(token=token)
u = User(linkedin=profile['id'],
display_name=profile['firstName'] + ' ' + profile['lastName'])
db.session.add(u)
db.session.commit()
token = create_jwt_token(u)
return jsonify(token=token)
@app.route('/auth/twitter')
def twitter():
request_token_url = 'https://api.twitter.com/oauth/request_token'
access_token_url = 'https://api.twitter.com/oauth/access_token'
authenticate_url = 'https://api.twitter.com/oauth/authenticate'
if request.args.get('oauth_token') and request.args.get('oauth_verifier'):
auth = OAuth1(app.config['TWITTER_CONSUMER_KEY'],
client_secret=app.config['TWITTER_CONSUMER_SECRET'],
resource_owner_key=request.args.get('oauth_token'),
verifier=request.args.get('oauth_verifier'))
r = requests.post(access_token_url, auth=auth)
profile = dict(parse_qsl(r.text))
user = User.query.filter_by(twitter=profile['user_id']).first()
if user:
token = create_jwt_token(user)
return jsonify(token=token)
u = User(twitter=profile['user_id'],
display_name=profile['screen_name'])
db.session.add(u)
db.session.commit()
token = create_jwt_token(u)
return jsonify(token=token)
else:
oauth = OAuth1(app.config['TWITTER_CONSUMER_KEY'],
client_secret=app.config['TWITTER_CONSUMER_SECRET'],
callback_uri=app.config['TWITTER_CALLBACK_URL'])
r = requests.post(request_token_url, auth=oauth)
oauth_token = dict(parse_qsl(r.text))
qs = urlencode(dict(oauth_token=oauth_token['oauth_token']))
return redirect(authenticate_url + '?' + qs)
if __name__ == '__main__':
app.run(port=3000)
|
unknown
|
codeparrot/codeparrot-clean
| ||
"""
A refactored implementation of Boids from a deliberately bad implementation of
[Boids](http://dl.acm.org/citation.cfm?doid=37401.37406): an exercise for class.
"""
from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np
class Boids(object):
def __init__(self,
boid_count=50,
x_positions=[-450, 50.0],
y_positions=[300.0, 600.0],
x_velocities=[0, 10.0],
y_velocities=[-20.0, 20.0],
move_to_middle_strength=0.01,
alert_distance=100,
formation_flying_distance=10000,
formation_flying_strength=0.125):
self.boid_count = boid_count
self.move_to_middle_strength = move_to_middle_strength
self.alert_distance = alert_distance
self.formation_flying_distance = formation_flying_distance
self.formation_flying_strength = formation_flying_strength
self.boids_x = np.random.uniform(size=boid_count, *x_positions)
self.boids_y = np.random.uniform(size=boid_count, *y_positions)
self.positions = np.stack((self.boids_x, self.boids_y))
self.boid_x_velocities = np.random.uniform(size=boid_count, *x_velocities)
self.boid_y_velocities = np.random.uniform(size=boid_count, *y_velocities)
self.velocities = np.stack((self.boid_x_velocities, self.boid_y_velocities))
self.boids = (self.positions, self.velocities)
def fly_towards_the_middle(self, boids, move_to_middle_strength=0.01):
(positions, velocities) = boids
middle = np.mean(positions, 1)
move_to_middle = (middle[:, np.newaxis] - positions) * move_to_middle_strength
velocities += move_to_middle
def separation(self, coords):
separations = np.array(coords)[:, np.newaxis, :] - np.array(coords)[:, :, np.newaxis]
separation_distance_squared = separations[0, :, :] ** 2 + separations[1, :, :] ** 2
return separations, separation_distance_squared
def fly_away_from_nearby_boids(self, boids, alert_distance=100):
(positions, velocities) = boids
separations, separation_distance_squared = self.separation(positions)
birds_outside_alert = separation_distance_squared > alert_distance
close_separations = np.copy(separations)
close_separations[0, :, :][birds_outside_alert] = 0 # x positions
close_separations[1, :, :][birds_outside_alert] = 0 # y positions
velocities += np.sum(close_separations, 1)
def match_speed_with_nearby_boids(self, boids,
formation_flying_distance=10000,
formation_flying_strength=0.125):
(positions, velocities) = boids
separations, separation_distance_squared = self.separation(positions)
birds_outside_formation = separation_distance_squared > formation_flying_distance
velocity_difference = velocities[:, np.newaxis, :] - velocities[:, :, np.newaxis]
close_formation = np.copy(velocity_difference)
close_formation[0, :, :][birds_outside_formation] = 0
close_formation[1, :, :][birds_outside_formation] = 0
velocities += -1 * np.mean(close_formation, 1) * formation_flying_strength
def update_boids(self, boids):
(positions, velocities) = boids
# Fly towards the middle
self.fly_towards_the_middle(boids, self.move_to_middle_strength)
# Fly away from nearby boids
self.fly_away_from_nearby_boids(boids, self.alert_distance)
# Try to match speed with nearby boids
self.match_speed_with_nearby_boids(boids, self.formation_flying_distance, self.formation_flying_strength)
# Update positions
positions += velocities
def _animate(self, frame):
self.update_boids(self.boids)
(positions, velocities) = self.boids
self.scatter.set_offsets(np.transpose(positions))
def model(self, xlim=(-500, 1500), ylim=(-500, 1500), frames=50, interval=50, savefile=None):
colors = np.random.rand(self.boid_count)
boidsize = np.pi * (2 * np.random.rand(self.boid_count) + 2) ** 2
figure = plt.figure()
axes = plt.axes(xlim=xlim, ylim=ylim)
self.scatter = axes.scatter(self.boids_x, self.boids_y,
s=boidsize, c=colors, alpha=0.5, edgecolors=None)
anim = animation.FuncAnimation(figure, self._animate,
frames=frames, interval=interval)
plt.xlabel('x (arbitrary units)')
plt.ylabel('y (arbitrary units)')
plt.title("Boids a'Flocking")
if savefile != None:
anim.save(savefile)
plt.show()
if __name__ == "__main__":
boidsobject = Boids()
boidsobject.model()
|
unknown
|
codeparrot/codeparrot-clean
| ||
#!/usr/bin/env python3
# Copyright (C) 2012-2015 ASTRON (Netherlands Institute for Radio Astronomy)
# P.O. Box 2, 7990 AA Dwingeloo, The Netherlands
#
# This file is part of the LOFAR software suite.
# The LOFAR software suite is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# The LOFAR software suite is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with the LOFAR software suite. If not, see <http://www.gnu.org/licenses/>.
# $Id$
from datetime import datetime
import time
from pprint import pformat
import unittest
from lofar.lta.ltastorageoverview.testing.common_test_ltastoragedb import LTAStorageDbTestMixin
from lofar.common.postgres import FETCH_ALL, PostgresDBQueryExecutionError
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.INFO)
class TestLTAStorageDb(LTAStorageDbTestMixin, unittest.TestCase):
def testSites(self):
siteA_id = self.db.insertSiteIfNotExists('siteA', 'srm://siteA.org')
siteB_id = self.db.insertSiteIfNotExists('siteB', 'srm://siteB.org')
sites = self.db.sites()
siteNames = [x['name'] for x in sites]
self.assertEqual(2, len(siteNames))
self.assertTrue('siteA' in siteNames)
self.assertTrue('siteB' in siteNames)
site = self.db.site(siteA_id)
self.assertEqual('siteA', site['name'])
site = self.db.site(siteB_id)
self.assertEqual('siteB', site['name'])
def testRootDirs(self):
siteA_id = self.db.insertSiteIfNotExists('siteA', 'srm://siteA.org')
siteB_id = self.db.insertSiteIfNotExists('siteB', 'srm://siteB.org')
dirA1_id = self.db.insertRootDirectory('siteA', 'rootDir1')
dirA2_id = self.db.insertRootDirectory('siteA', 'rootDir2')
dirA3_id = self.db.insertRootDirectory('siteA', 'path/to/rootDir3')
dirB1_id = self.db.insertRootDirectory('siteB', 'rootDir1')
dirB2_id = self.db.insertRootDirectory('siteB', 'path/to/otherRootDir')
rootDirs = self.db.rootDirectories()
self.assertEqual(5, len(rootDirs))
rootDirsDict = {rd['root_dir_id']:rd for rd in rootDirs}
self.assertEqual('rootDir1', rootDirsDict[dirA1_id]['dir_name'])
self.assertEqual(siteA_id, rootDirsDict[dirA1_id]['site_id'])
self.assertEqual('siteA', rootDirsDict[dirA1_id]['site_name'])
self.assertEqual('rootDir2', rootDirsDict[dirA2_id]['dir_name'])
self.assertEqual(siteA_id, rootDirsDict[dirA2_id]['site_id'])
self.assertEqual('siteA', rootDirsDict[dirA2_id]['site_name'])
self.assertEqual('path/to/rootDir3', rootDirsDict[dirA3_id]['dir_name'])
self.assertEqual(siteA_id, rootDirsDict[dirA3_id]['site_id'])
self.assertEqual('siteA', rootDirsDict[dirA3_id]['site_name'])
self.assertEqual('rootDir1', rootDirsDict[dirB1_id]['dir_name'])
self.assertEqual(siteB_id, rootDirsDict[dirB1_id]['site_id'])
self.assertEqual('siteB', rootDirsDict[dirB1_id]['site_name'])
self.assertEqual('path/to/otherRootDir', rootDirsDict[dirB2_id]['dir_name'])
self.assertEqual(siteB_id, rootDirsDict[dirB2_id]['site_id'])
self.assertEqual('siteB', rootDirsDict[dirB2_id]['site_name'])
root_dir_ids_siteA = set(d['root_dir_id'] for d in self.db.rootDirectoriesForSite(siteA_id))
self.assertEqual(set([dirA1_id, dirA2_id, dirA3_id]), root_dir_ids_siteA)
root_dir_ids_siteB = set(d['root_dir_id'] for d in self.db.rootDirectoriesForSite(siteB_id))
self.assertEqual(set([dirB1_id, dirB2_id]), root_dir_ids_siteB)
root_dirs_non_existing_site = self.db.rootDirectoriesForSite(999)
self.assertEqual([], root_dirs_non_existing_site)
def testNonExistingDir(self):
dir = self.db.directoryByName('fjsdka;58432aek5843rfsjd8-sa')
self.assertEqual(None, dir)
def testLeastRecentlyVisitedDirectory(self):
self.db.insertSiteIfNotExists('siteA', 'srm://siteA.org')
dir_ids = []
for i in range(3):
dir_id = self.db.insertRootDirectory('siteA', 'rootDir_%d' % i)
dir_ids.append(dir_id)
self.db.updateDirectoryLastVisitTime(dir_id, datetime.utcnow())
time.sleep(0.002)
visitStats = self.db.visitStats()
self.assertTrue('siteA' in visitStats)
self.assertTrue('least_recent_visited_dir_id' in visitStats['siteA'])
lvr_dir_id = visitStats['siteA']['least_recent_visited_dir_id']
self.assertEqual(dir_ids[0], lvr_dir_id)
self.db.updateDirectoryLastVisitTime(dir_ids[0], datetime.utcnow())
self.db.updateDirectoryLastVisitTime(dir_ids[1], datetime.utcnow())
visitStats = self.db.visitStats()
lvr_dir_id = visitStats['siteA']['least_recent_visited_dir_id']
self.assertEqual(dir_ids[2], lvr_dir_id)
def testDuplicateSubDirs(self):
self.db.insertSiteIfNotExists('siteA', 'srm://siteA.org')
self.db.insertSiteIfNotExists('siteB', 'srm://siteB.org')
dirA_id = self.db.insertRootDirectory('siteA', 'rootDir1')
dirB_id = self.db.insertRootDirectory('siteB', 'rootDir1')
subDirA1_id = self.db.insertSubDirectory('foo', dirA_id)
subDirA2_id = self.db.insertSubDirectory('bar', dirA_id)
subDirB1_id = self.db.insertSubDirectory('foo', dirB_id)
self.assertNotEquals(None, subDirA1_id)
self.assertNotEquals(None, subDirA2_id)
self.assertNotEquals(None, subDirB1_id)
with self.assertRaises(PostgresDBQueryExecutionError):
self.db.insertSubDirectory('foo', dirA_id)
def _fill_test_db_with_sites_and_root_dirs(self):
"""
helper method to fill empty database with simple sites and root dirs
"""
self.db.insertSiteIfNotExists('siteA', 'srm://siteA.foo.bar:8443')
self.db.insertSiteIfNotExists('siteB', 'srm://siteB.foo.bar:8443')
self.db.insertRootDirectory('siteA', '/root_dir_1')
self.db.insertRootDirectory('siteA', '/root_dir_2')
self.db.insertRootDirectory('siteA', '/long/path/to/root_dir_3')
self.db.insertRootDirectory('siteB', '/root_dir_1')
def test_insert_missing_directory_tree_if_needed(self):
""" Test core method _insertMissingDirectoryTreeIfNeeded for all known root dirs.
Should result in new directory entries in the database for the new sub directories only.
"""
self._fill_test_db_with_sites_and_root_dirs()
for site in self.db.sites():
site_id = site['id']
for root_dir in self.db.rootDirectoriesForSite(site_id):
root_dir_path = root_dir['dir_name']
# root dir should already exist
dir = self.db.directoryByName(root_dir_path, site_id)
self.assertIsNotNone(dir)
# insert the not-so-missing root dir.
# nothing should happen, because the root dir already exists
new_dir_ids = self.db.insert_missing_directory_tree_if_needed(root_dir_path, site_id)
self.assertEqual(0, len(new_dir_ids))
# now insert some new subdirs, with multiple levels.
for subdir_path in ['/foo', '/bar/xyz']:
dir_path = root_dir_path + subdir_path
# dir should not exist yet
self.assertIsNone(self.db.directoryByName(dir_path, site_id))
# let the handler insert the missing dirs.
self.db.insert_missing_directory_tree_if_needed(dir_path, site_id)
# dir should exist now
dir = self.db.directoryByName(dir_path, site_id)
self.assertIsNotNone(dir)
# check if new dir has expected root dir
parents = self.db.parentDirectories(dir['dir_id'])
self.assertEqual(root_dir['root_dir_id'], parents[0]['id'])
def test_insert_missing_directory_tree_if_needed_for_path_with_unknown_rootdir(self):
""" Test core method _insertMissingDirectoryTreeIfNeeded for a path with an unknown root dir
Should raise LookupError.
"""
self._fill_test_db_with_sites_and_root_dirs()
for site in self.db.sites():
site_id = site['id']
with self.assertRaises(LookupError) as context:
incorrect_dir_path = '/fdjsalfja5h43535h3oiu/5u905u3f'
self.db.insert_missing_directory_tree_if_needed(incorrect_dir_path, site_id)
self.assertTrue('Could not find parent root dir' in str(context.exception))
def testProjectsAndObservations(self):
#first insert a lot of data...
self.db.insertSiteIfNotExists('juelich', 'srm://lofar-srm.fz-juelich.de:8443')
self.db.insertSiteIfNotExists('sara', 'srm://srm.grid.sara.nl:8443')
juelich_root_dir_id = self.db.insertRootDirectory('juelich', '/pnfs/fz-juelich.de/data/lofar/ops/')
sara_root_dir_id = self.db.insertRootDirectory('sara', '/pnfs/grid.sara.nl/data/lofar/ops')
juelich_projects_dir_id = self.db.insertSubDirectory('/pnfs/fz-juelich.de/data/lofar/ops/projects', juelich_root_dir_id)
sara_projects_dir_id = self.db.insertSubDirectory('/pnfs/grid.sara.nl/data/lofar/ops/projects', sara_root_dir_id)
for project_nr, project_name in enumerate(['lc8_001', '2017lofarobs', 'ddt5_001']):
# projects are sometimes stored at multiple sites
for projects_dir_id in [juelich_projects_dir_id, sara_projects_dir_id]:
project_dir_id = self.db.insertSubDirectory('/pnfs/fz-juelich.de/data/lofar/ops/projects/' + project_name,
projects_dir_id)
for obs_nr in range(3):
obs_name = 'L%06d' % ((project_nr+1)*1000 + obs_nr)
obs_dir_id = self.db.insertSubDirectory('/pnfs/fz-juelich.de/data/lofar/ops/projects/' + project_name + '/' + obs_name,
project_dir_id)
for sb_nr in range(244):
file_name = '%s_SB%03d.MS.tar' % (obs_name, sb_nr)
self.db.insertFileInfo(file_name, 1, datetime.utcnow(), obs_dir_id, False)
self.db.commit()
# then check the results
# TODO check the results
logger.info(pformat(self.db.executeQuery('select * from metainfo.project_directory', fetch=FETCH_ALL)))
logger.info(pformat(self.db.executeQuery('select * from metainfo.project_stats', fetch=FETCH_ALL)))
logger.info(pformat(self.db.executeQuery('select * from metainfo.project_observation_dataproduct', fetch=FETCH_ALL)))
# run tests if main
if __name__ == '__main__':
unittest.main()
|
unknown
|
codeparrot/codeparrot-clean
| ||
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export {inferTypes} from './InferTypes';
|
typescript
|
github
|
https://github.com/facebook/react
|
compiler/packages/babel-plugin-react-compiler/src/TypeInference/index.ts
|
<?php
namespace Illuminate\Database\Eloquent;
use RuntimeException;
class RelationNotFoundException extends RuntimeException
{
/**
* The name of the affected Eloquent model.
*
* @var string
*/
public $model;
/**
* The name of the relation.
*
* @var string
*/
public $relation;
/**
* Create a new exception instance.
*
* @param object $model
* @param string $relation
* @param string|null $type
* @return static
*/
public static function make($model, $relation, $type = null)
{
$class = get_class($model);
$instance = new static(
is_null($type)
? "Call to undefined relationship [{$relation}] on model [{$class}]."
: "Call to undefined relationship [{$relation}] on model [{$class}] of type [{$type}].",
);
$instance->model = $class;
$instance->relation = $relation;
return $instance;
}
}
|
php
|
github
|
https://github.com/laravel/framework
|
src/Illuminate/Database/Eloquent/RelationNotFoundException.php
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2011 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://babel.edgewall.org/wiki/License.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://babel.edgewall.org/log/.
import decimal
import unittest
import pytest
from babel import plural
def test_plural_rule():
rule = plural.PluralRule({'one': 'n is 1'})
assert rule(1) == 'one'
assert rule(2) == 'other'
rule = plural.PluralRule({'one': 'n is 1'})
assert rule.rules == {'one': 'n is 1'}
def test_plural_rule_operands_i():
rule = plural.PluralRule({'one': 'i is 1'})
assert rule(1.2) == 'one'
assert rule(2) == 'other'
def test_plural_rule_operands_v():
rule = plural.PluralRule({'one': 'v is 2'})
assert rule(decimal.Decimal('1.20')) == 'one'
assert rule(decimal.Decimal('1.2')) == 'other'
assert rule(2) == 'other'
def test_plural_rule_operands_w():
rule = plural.PluralRule({'one': 'w is 2'})
assert rule(decimal.Decimal('1.23')) == 'one'
assert rule(decimal.Decimal('1.20')) == 'other'
assert rule(1.2) == 'other'
def test_plural_rule_operands_f():
rule = plural.PluralRule({'one': 'f is 20'})
assert rule(decimal.Decimal('1.23')) == 'other'
assert rule(decimal.Decimal('1.20')) == 'one'
assert rule(1.2) == 'other'
def test_plural_rule_operands_t():
rule = plural.PluralRule({'one': 't = 5'})
assert rule(decimal.Decimal('1.53')) == 'other'
assert rule(decimal.Decimal('1.50')) == 'one'
assert rule(1.5) == 'one'
def test_plural_other_is_ignored():
rule = plural.PluralRule({'one': 'n is 1', 'other': '@integer 2'})
assert rule(1) == 'one'
def test_to_javascript():
assert (plural.to_javascript({'one': 'n is 1'})
== "(function(n) { return (n == 1) ? 'one' : 'other'; })")
def test_to_python():
func = plural.to_python({'one': 'n is 1', 'few': 'n in 2..4'})
assert func(1) == 'one'
assert func(3) == 'few'
func = plural.to_python({'one': 'n in 1,11', 'few': 'n in 3..10,13..19'})
assert func(11) == 'one'
assert func(15) == 'few'
def test_to_gettext():
assert (plural.to_gettext({'one': 'n is 1', 'two': 'n is 2'})
== 'nplurals=3; plural=((n == 1) ? 0 : (n == 2) ? 1 : 2)')
def test_in_range_list():
assert plural.in_range_list(1, [(1, 3)])
assert plural.in_range_list(3, [(1, 3)])
assert plural.in_range_list(3, [(1, 3), (5, 8)])
assert not plural.in_range_list(1.2, [(1, 4)])
assert not plural.in_range_list(10, [(1, 4)])
assert not plural.in_range_list(10, [(1, 4), (6, 8)])
def test_within_range_list():
assert plural.within_range_list(1, [(1, 3)])
assert plural.within_range_list(1.0, [(1, 3)])
assert plural.within_range_list(1.2, [(1, 4)])
assert plural.within_range_list(8.8, [(1, 4), (7, 15)])
assert not plural.within_range_list(10, [(1, 4)])
assert not plural.within_range_list(10.5, [(1, 4), (20, 30)])
def test_cldr_modulo():
assert plural.cldr_modulo(-3, 5) == -3
assert plural.cldr_modulo(-3, -5) == -3
assert plural.cldr_modulo(3, 5) == 3
def test_plural_within_rules():
p = plural.PluralRule({'one': 'n is 1', 'few': 'n within 2,4,7..9'})
assert repr(p) == "<PluralRule 'one: n is 1, few: n within 2,4,7..9'>"
assert plural.to_javascript(p) == (
"(function(n) { "
"return ((n == 2) || (n == 4) || (n >= 7 && n <= 9))"
" ? 'few' : (n == 1) ? 'one' : 'other'; })")
assert plural.to_gettext(p) == (
'nplurals=3; plural=(((n == 2) || (n == 4) || (n >= 7 && n <= 9))'
' ? 1 : (n == 1) ? 0 : 2)')
assert p(0) == 'other'
assert p(1) == 'one'
assert p(2) == 'few'
assert p(3) == 'other'
assert p(4) == 'few'
assert p(5) == 'other'
assert p(6) == 'other'
assert p(7) == 'few'
assert p(8) == 'few'
assert p(9) == 'few'
def test_locales_with_no_plural_rules_have_default():
from babel import Locale
aa_plural = Locale.parse('aa').plural_form
assert aa_plural(1) == 'other'
assert aa_plural(2) == 'other'
assert aa_plural(15) == 'other'
WELL_FORMED_TOKEN_TESTS = (
('', []),
('n = 1', [('value', '1'), ('symbol', '='), ('word', 'n'), ]),
('n = 1 @integer 1', [('value', '1'), ('symbol', '='), ('word', 'n'), ]),
('n is 1', [('value', '1'), ('word', 'is'), ('word', 'n'), ]),
('n % 100 = 3..10', [('value', '10'), ('ellipsis', '..'), ('value', '3'),
('symbol', '='), ('value', '100'), ('symbol', '%'),
('word', 'n'), ]),
)
@pytest.mark.parametrize('rule_text,tokens', WELL_FORMED_TOKEN_TESTS)
def test_tokenize_well_formed(rule_text, tokens):
assert plural.tokenize_rule(rule_text) == tokens
MALFORMED_TOKEN_TESTS = (
'a = 1', 'n ! 2',
)
@pytest.mark.parametrize('rule_text', MALFORMED_TOKEN_TESTS)
def test_tokenize_malformed(rule_text):
with pytest.raises(plural.RuleError):
plural.tokenize_rule(rule_text)
class TestNextTokenTestCase(unittest.TestCase):
def test_empty(self):
assert not plural.test_next_token([], '')
def test_type_ok_and_no_value(self):
assert plural.test_next_token([('word', 'and')], 'word')
def test_type_ok_and_not_value(self):
assert not plural.test_next_token([('word', 'and')], 'word', 'or')
def test_type_ok_and_value_ok(self):
assert plural.test_next_token([('word', 'and')], 'word', 'and')
def test_type_not_ok_and_value_ok(self):
assert not plural.test_next_token([('abc', 'and')], 'word', 'and')
def make_range_list(*values):
ranges = []
for v in values:
if isinstance(v, int):
val_node = plural.value_node(v)
ranges.append((val_node, val_node))
else:
assert isinstance(v, tuple)
ranges.append((plural.value_node(v[0]),
plural.value_node(v[1])))
return plural.range_list_node(ranges)
class PluralRuleParserTestCase(unittest.TestCase):
def setUp(self):
self.n = plural.ident_node('n')
def n_eq(self, v):
return 'relation', ('in', self.n, make_range_list(v))
def test_error_when_unexpected_end(self):
with pytest.raises(plural.RuleError):
plural._Parser('n =')
def test_eq_relation(self):
assert plural._Parser('n = 1').ast == self.n_eq(1)
def test_in_range_relation(self):
assert plural._Parser('n = 2..4').ast == \
('relation', ('in', self.n, make_range_list((2, 4))))
def test_negate(self):
assert plural._Parser('n != 1').ast == plural.negate(self.n_eq(1))
def test_or(self):
assert plural._Parser('n = 1 or n = 2').ast ==\
('or', (self.n_eq(1), self.n_eq(2)))
def test_and(self):
assert plural._Parser('n = 1 and n = 2').ast ==\
('and', (self.n_eq(1), self.n_eq(2)))
def test_or_and(self):
assert plural._Parser('n = 0 or n != 1 and n % 100 = 1..19').ast == \
('or', (self.n_eq(0),
('and', (plural.negate(self.n_eq(1)),
('relation', ('in',
('mod', (self.n,
plural.value_node(100))),
(make_range_list((1, 19)))))))
))
EXTRACT_OPERANDS_TESTS = (
(1, 1, 1, 0, 0, 0, 0),
('1.0', '1.0', 1, 1, 0, 0, 0),
('1.00', '1.00', 1, 2, 0, 0, 0),
('1.3', '1.3', 1, 1, 1, 3, 3),
('1.30', '1.30', 1, 2, 1, 30, 3),
('1.03', '1.03', 1, 2, 2, 3, 3),
('1.230', '1.230', 1, 3, 2, 230, 23),
(-1, 1, 1, 0, 0, 0, 0),
(1.3, '1.3', 1, 1, 1, 3, 3),
)
@pytest.mark.parametrize('source,n,i,v,w,f,t', EXTRACT_OPERANDS_TESTS)
def test_extract_operands(source, n, i, v, w, f, t):
source = decimal.Decimal(source) if isinstance(source, str) else source
assert (plural.extract_operands(source) ==
decimal.Decimal(n), i, v, w, f, t)
|
unknown
|
codeparrot/codeparrot-clean
| ||
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import proto # type: ignore
__protobuf__ = proto.module(
package='google.ads.googleads.v6.errors',
marshal='google.ads.googleads.v6',
manifest={
'PolicyViolationErrorEnum',
},
)
class PolicyViolationErrorEnum(proto.Message):
r"""Container for enum describing possible policy violation
errors.
"""
class PolicyViolationError(proto.Enum):
r"""Enum describing possible policy violation errors."""
UNSPECIFIED = 0
UNKNOWN = 1
POLICY_ERROR = 2
__all__ = tuple(sorted(__protobuf__.manifest))
|
unknown
|
codeparrot/codeparrot-clean
| ||
from __future__ import absolute_import, print_function, division
from getpass import getuser
import pytest
sa = pytest.importorskip('sqlalchemy')
pytest.importorskip('pymysql')
from odo import odo, drop, discover
import pandas as pd
from blaze import symbol, compute
from blaze.utils import example, normalize
@pytest.yield_fixture(scope='module')
def data():
try:
t = odo(
example('nyc.csv'),
'mysql+pymysql://%s@localhost/test::nyc' % getuser()
)
except sa.exc.OperationalError as e:
pytest.skip(str(e))
else:
try:
yield t.bind
finally:
drop(t)
@pytest.fixture
def db(data):
return symbol('test', discover(data))
def test_agg_sql(db, data):
subset = db.nyc[['pickup_datetime', 'dropoff_datetime', 'passenger_count']]
expr = subset[subset.passenger_count < 4].passenger_count.min()
result = compute(expr, data)
expected = """
select
min(alias.passenger_count) as passenger_count_min
from
(select
nyc.passenger_count as passenger_count
from
nyc
where nyc.passenger_count < %s) as alias
"""
assert normalize(str(result)) == normalize(expected)
def test_agg_compute(db, data):
subset = db.nyc[['pickup_datetime', 'dropoff_datetime', 'passenger_count']]
expr = subset[subset.passenger_count < 4].passenger_count.min()
result = compute(expr, data)
passenger_count = odo(compute(db.nyc.passenger_count, {db: data}), pd.Series)
assert passenger_count[passenger_count < 4].min() == result.scalar()
|
unknown
|
codeparrot/codeparrot-clean
| ||
import os
import subprocess
import sys
from GpdbBuildBase import GpdbBuildBase
class GporcacodegenBuild(GpdbBuildBase):
def __init__(self):
pass
def configure(self):
return subprocess.call(' '.join(["./configure",
"--enable-orca",
"--enable-codegen",
"--enable-mapreduce",
"--with-perl",
"--with-libxml",
"--with-python",
"--disable-gpfdist",
"--prefix=/usr/local/gpdb"]),
cwd="gpdb_src", shell=True)
def icg(self):
status = subprocess.call(
"printf '\nLD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib\nexport \
LD_LIBRARY_PATH' >> /usr/local/gpdb/greenplum_path.sh", shell=True)
if status:
return status
status = subprocess.call([
"runuser gpadmin -c \"source /usr/local/gpdb/greenplum_path.sh \
&& make cluster\""], cwd="gpdb_src/gpAux/gpdemo", shell=True)
if status:
return status
return subprocess.call([
"runuser gpadmin -c \"source /usr/local/gpdb/greenplum_path.sh \
&& source gpAux/gpdemo/gpdemo-env.sh && PGOPTIONS='-c optimizer=on -c codegen=on' \
make installcheck-good\""], cwd="gpdb_src", shell=True)
|
unknown
|
codeparrot/codeparrot-clean
| ||
#!/usr/bin/env python
# based on the 'calculator' demo in the Thrift source
import sys, os.path
sys.path.insert(0, os.path.join(os.path.abspath(os.path.split(sys.argv[0])[0]), 'gen-py'))
import tutorial.Calculator
from tutorial.ttypes import *
from thrift.transport import TTwisted, TTransport
from thrift.protocol import TBinaryProtocol
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
import txamqp.spec
from txamqp.client import TwistedDelegate
from txamqp.contrib.thrift.transport import TwistedAMQPTransport
from txamqp.contrib.thrift.protocol import ThriftAMQClient
servicesExchange = "services"
responsesExchange = "responses"
calculatorQueue = "calculator_pool"
calculatorKey = "calculator"
def gotPing(_):
print "Ping received"
def gotAddResults(results):
print "Got results to add()"
print results
def gotCalculateResults(results):
print "Got results to calculate()"
print results
def gotCalculateErrors(error):
error.trap(InvalidOperation)
print "Got a calculator error"
print error.value.why
def gotTransportError(error):
error.trap(TTransport.TTransportException)
print "Got an AMQP unroutable message error:"
print error.value.message
@defer.inlineCallbacks
def prepareClient(client, username, password):
yield client.authenticate(username, password)
channel = yield client.channel(1)
yield channel.channel_open()
yield channel.exchange_declare(exchange=servicesExchange, type="direct")
yield channel.exchange_declare(exchange=responsesExchange, type="direct")
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
# To trigger an unroutable message error (caught in the above
# gotTransportError errback), change the routing key (i.e.,
# calculatorKey) in the following to be something invalid, like
# calculatorKey + 'xxx'.
thriftClient = yield client.createThriftClient(responsesExchange,
servicesExchange, calculatorKey, tutorial.Calculator.Client,
iprot_factory=pfactory, oprot_factory=pfactory)
defer.returnValue(thriftClient)
def gotClient(client):
d1 = client.ping().addCallback(gotPing).addErrback(gotTransportError)
d2 = client.add(1, 2).addCallback(gotAddResults).addErrback(gotTransportError)
w = Work(num1=2, num2=3, op=Operation.ADD)
d3 = client.calculate(1, w).addCallbacks(gotCalculateResults,
gotCalculateErrors).addErrback(gotTransportError)
w = Work(num1=2, num2=3, op=Operation.SUBTRACT)
d4 = client.calculate(2, w).addCallbacks(gotCalculateResults,
gotCalculateErrors).addErrback(gotTransportError)
w = Work(num1=2, num2=3, op=Operation.MULTIPLY)
d5 = client.calculate(3, w).addCallbacks(gotCalculateResults,
gotCalculateErrors).addErrback(gotTransportError)
w = Work(num1=2, num2=3, op=Operation.DIVIDE)
d6 = client.calculate(4, w).addCallbacks(gotCalculateResults,
gotCalculateErrors).addErrback(gotTransportError)
# This will fire an errback
w = Work(num1=2, num2=0, op=Operation.DIVIDE)
d7 = client.calculate(5, w).addCallbacks(gotCalculateResults,
gotCalculateErrors).addErrback(gotTransportError)
d8 = client.zip()
dl = defer.DeferredList([d1, d2, d3, d4, d5, d6, d7, d8])
dl.addCallback(lambda _: reactor.stop())
if __name__ == '__main__':
import sys
if len(sys.argv) != 7:
print "%s host port vhost username password path_to_spec" % sys.argv[0]
sys.exit(1)
host = sys.argv[1]
port = int(sys.argv[2])
vhost = sys.argv[3]
username = sys.argv[4]
password = sys.argv[5]
specFile = sys.argv[6]
spec = txamqp.spec.load(specFile)
delegate = TwistedDelegate()
d = ClientCreator(reactor, ThriftAMQClient, delegate, vhost,
spec).connectTCP(host, port)
d.addCallback(prepareClient, username, password).addCallback(gotClient)
reactor.run()
|
unknown
|
codeparrot/codeparrot-clean
| ||
% This is generated by ESQL's AbstractFunctionTestCase. Do not edit it. See ../README.md for how to regenerate it.
**Description**
Converts a multi-valued input of numbers, or a hexadecimal string, to a dense_vector.
|
unknown
|
github
|
https://github.com/elastic/elasticsearch
|
docs/reference/query-languages/esql/_snippets/functions/description/to_dense_vector.md
|
#!/usr/bin/env python
#
# Copyright (c) 2018, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
import sys
import os
import time
import re
import random
import weakref
import subprocess
import socket
import asyncore
import inspect
#----------------------------------------------------------------------------------------------------------------------
# wpantund properties
WPAN_STATE = 'NCP:State'
WPAN_NAME = 'Network:Name'
WPAN_PANID = 'Network:PANID'
WPAN_XPANID = 'Network:XPANID'
WPAN_KEY = 'Network:Key'
WPAN_KEY_INDEX = 'Network:KeyIndex'
WPAN_CHANNEL = 'NCP:Channel'
WPAN_HW_ADDRESS = 'NCP:HardwareAddress'
WPAN_EXT_ADDRESS = 'NCP:ExtendedAddress'
WPAN_POLL_INTERVAL = 'NCP:SleepyPollInterval'
WPAN_NODE_TYPE = 'Network:NodeType'
WPAN_ROLE = 'Network:Role'
WPAN_PARTITION_ID = 'Network:PartitionId'
WPAN_NCP_VERSION = 'NCP:Version'
WPAN_NCP_MCU_POWER_STATE = "NCP:MCUPowerState"
WPAN_NETWORK_ALLOW_JOIN = 'com.nestlabs.internal:Network:AllowingJoin'
WPAN_NETWORK_PASSTHRU_PORT = 'com.nestlabs.internal:Network:PassthruPort'
WPAN_IP6_LINK_LOCAL_ADDRESS = "IPv6:LinkLocalAddress"
WPAN_IP6_MESH_LOCAL_ADDRESS = "IPv6:MeshLocalAddress"
WPAN_IP6_MESH_LOCAL_PREFIX = "IPv6:MeshLocalPrefix"
WPAN_IP6_ALL_ADDRESSES = "IPv6:AllAddresses"
WPAN_IP6_MULTICAST_ADDRESSES = "IPv6:MulticastAddresses"
WPAN_THREAD_RLOC16 = "Thread:RLOC16"
WPAN_THREAD_ROUTER_ID = "Thread:RouterID"
WPAN_THREAD_LEADER_ADDRESS = "Thread:Leader:Address"
WPAN_THREAD_LEADER_ROUTER_ID = "Thread:Leader:RouterID"
WPAN_THREAD_LEADER_WEIGHT = "Thread:Leader:Weight"
WPAN_THREAD_LEADER_LOCAL_WEIGHT = "Thread:Leader:LocalWeight"
WPAN_THREAD_LEADER_NETWORK_DATA = "Thread:Leader:NetworkData"
WPAN_THREAD_STABLE_LEADER_NETWORK_DATA = "Thread:Leader:StableNetworkData"
WPAN_THREAD_NETWORK_DATA = "Thread:NetworkData"
WPAN_THREAD_CHILD_TABLE = "Thread:ChildTable"
WPAN_THREAD_CHILD_TABLE_ASVALMAP = "Thread:ChildTable:AsValMap"
WPAN_THREAD_CHILD_TABLE_ADDRESSES = "Thread:ChildTable:Addresses"
WPAN_THREAD_NEIGHBOR_TABLE = "Thread:NeighborTable"
WPAN_THREAD_NEIGHBOR_TABLE_ASVALMAP = "Thread:NeighborTable:AsValMap"
WPAN_THREAD_NEIGHBOR_TABLE_ERR_RATES = "Thread:NeighborTable:ErrorRates"
WPAN_THREAD_NEIGHBOR_TABLE_ERR_RATES_AVVALMAP = "Thread:NeighborTable:ErrorRates:AsValMap"
WPAN_THREAD_ROUTER_TABLE = "Thread:RouterTable"
WPAN_THREAD_ROUTER_TABLE_ASVALMAP = "Thread:RouterTable:AsValMap"
WPAN_THREAD_CHILD_TIMEOUT = "Thread:ChildTimeout"
WPAN_THREAD_PARENT = "Thread:Parent"
WPAN_THREAD_PARENT_ASVALMAP = "Thread:Parent:AsValMap"
WPAN_THREAD_NETWORK_DATA_VERSION = "Thread:NetworkDataVersion"
WPAN_THREAD_STABLE_NETWORK_DATA = "Thread:StableNetworkData"
WPAN_THREAD_STABLE_NETWORK_DATA_VERSION = "Thread:StableNetworkDataVersion"
WPAN_THREAD_PREFERRED_ROUTER_ID = "Thread:PreferredRouterID"
WPAN_THREAD_COMMISSIONER_ENABLED = "Thread:Commissioner:Enabled"
WPAN_THREAD_DEVICE_MODE = "Thread:DeviceMode"
WPAN_THREAD_OFF_MESH_ROUTES = "Thread:OffMeshRoutes"
WPAN_THREAD_ON_MESH_PREFIXES = "Thread:OnMeshPrefixes"
WPAN_THREAD_ROUTER_ROLE_ENABLED = "Thread:RouterRole:Enabled"
WPAN_THREAD_CONFIG_FILTER_RLOC_ADDRESSES = "Thread:Config:FilterRLOCAddresses"
WPAN_THREAD_ROUTER_UPGRADE_THRESHOLD = "Thread:RouterUpgradeThreshold"
WPAN_THREAD_ROUTER_DOWNGRADE_THRESHOLD = "Thread:RouterDowngradeThreshold"
WPAN_THREAD_ACTIVE_DATASET = "Thread:ActiveDataset"
WPAN_THREAD_ACTIVE_DATASET_ASVALMAP = "Thread:ActiveDataset:AsValMap"
WPAN_THREAD_PENDING_DATASET = "Thread:PendingDataset"
WPAN_THREAD_PENDING_DATASET_ASVALMAP = "Thread:PendingDataset:AsValMap"
WPAN_THREAD_ADDRESS_CACHE_TABLE = "Thread:AddressCacheTable"
WPAN_THREAD_ADDRESS_CACHE_TABLE_ASVALMAP = "Thread:AddressCacheTable:AsValMap"
WPAN_OT_LOG_LEVEL = "OpenThread:LogLevel"
WPAN_OT_STEERING_DATA_ADDRESS = "OpenThread:SteeringData:Address"
WPAN_OT_STEERING_DATA_SET_WHEN_JOINABLE = "OpenThread:SteeringData:SetWhenJoinable"
WPAN_OT_MSG_BUFFER_COUNTERS = "OpenThread:MsgBufferCounters"
WPAN_OT_MSG_BUFFER_COUNTERS_AS_STRING = "OpenThread:MsgBufferCounters:AsString"
WPAN_OT_DEBUG_TEST_ASSERT = "OpenThread:Debug:TestAssert"
WPAN_OT_DEBUG_TEST_WATCHDOG = "OpenThread:Debug:TestWatchdog"
WPAN_NCP_COUNTER_ALL_MAC = "NCP:Counter:AllMac"
WPAN_NCP_COUNTER_ALL_MAC_ASVALMAP = "NCP:Counter:AllMac:AsValMap"
WPAN_MAC_WHITELIST_ENABLED = "MAC:Whitelist:Enabled"
WPAN_MAC_WHITELIST_ENTRIES = "MAC:Whitelist:Entries"
WPAN_MAC_WHITELIST_ENTRIES_ASVALMAP = "MAC:Whitelist:Entries:AsValMap"
WPAN_MAC_BLACKLIST_ENABLED = "MAC:Blacklist:Enabled"
WPAN_MAC_BLACKLIST_ENTRIES = "MAC:Blacklist:Entries"
WPAN_MAC_BLACKLIST_ENTRIES_ASVALMAP = "MAC:Blacklist:Entries:AsValMap"
WPAN_CHILD_SUPERVISION_INTERVAL = "ChildSupervision:Interval"
WPAN_CHILD_SUPERVISION_CHECK_TIMEOUT = "ChildSupervision:CheckTimeout"
WPAN_JAM_DETECTION_STATUS = "JamDetection:Status"
WPAN_JAM_DETECTION_ENABLE = "JamDetection:Enable"
WPAN_JAM_DETECTION_RSSI_THRESHOLD = "JamDetection:RssiThreshold"
WPAN_JAM_DETECTION_WINDOW = "JamDetection:Window"
WPAN_JAM_DETECTION_BUSY_PERIOD = "JamDetection:BusyPeriod"
WPAN_JAM_DETECTION_DEBUG_HISTORY_BITMAP = "JamDetection:Debug:HistoryBitmap"
WPAN_CHANNEL_MONITOR_SAMPLE_INTERVAL = "ChannelMonitor:SampleInterval"
WPAN_CHANNEL_MONITOR_RSSI_THRESHOLD = "ChannelMonitor:RssiThreshold"
WPAN_CHANNEL_MONITOR_SAMPLE_WINDOW = "ChannelMonitor:SampleWindow"
WPAN_CHANNEL_MONITOR_SAMPLE_COUNT = "ChannelMonitor:SampleCount"
WPAN_CHANNEL_MONITOR_CHANNEL_QUALITY = "ChannelMonitor:ChannelQuality"
WPAN_CHANNEL_MONITOR_CHANNEL_QUALITY_ASVALMAP = "ChannelMonitor:ChannelQuality:AsValMap"
WPAN_CHANNEL_MANAGER_NEW_CHANNEL = "ChannelManager:NewChannel"
WPAN_CHANNEL_MANAGER_DELAY = "ChannelManager:Delay"
WPAN_CHANNEL_MANAGER_CHANNEL_SELECT = "ChannelManager:ChannelSelect"
WPAN_CHANNEL_MANAGER_AUTO_SELECT_ENABLED = "ChannelManager:AutoSelect:Enabled"
WPAN_CHANNEL_MANAGER_AUTO_SELECT_INTERVAL = "ChannelManager:AutoSelect:Interval"
WPAN_CHANNEL_MANAGER_SUPPORTED_CHANNEL_MASK = "ChannelManager:SupportedChannelMask"
WPAN_CHANNEL_MANAGER_FAVORED_CHANNEL_MASK = "ChannelManager:FavoredChannelMask"
#----------------------------------------------------------------------------------------------------------------------
# Valid state values
STATE_UNINITIALIZED = '"uninitialized"'
STATE_FAULT = '"uninitialized:fault"'
STATE_UPGRADING = '"uninitialized:upgrading"'
STATE_DEEP_SLEEP = '"offline:deep-sleep"'
STATE_OFFLINE = '"offline"'
STATE_COMMISSIONED = '"offline:commissioned"'
STATE_ASSOCIATING = '"associating"'
STATE_CREDENTIALS_NEEDED = '"associating:credentials-needed"'
STATE_ASSOCIATED = '"associated"'
STATE_ISOLATED = '"associated:no-parent"'
STATE_NETWAKE_ASLEEP = '"associated:netwake-asleep"'
STATE_NETWAKE_WAKING = '"associated:netwake-waking"'
#-----------------------------------------------------------------------------------------------------------------------
# MCU Power state from `WPAN_NCP_MCU_POWER_STATE`
MCU_POWER_STATE_ON = '"on"'
MCU_POWER_STATE_LOW_POWER = '"low-power"'
MCU_POWER_STATE_OFF = '"off"'
#-----------------------------------------------------------------------------------------------------------------------
# Node types (from `WPAN_NODE_TYPE` property)
NODE_TYPE_UNKNOWN = '"unknown"'
NODE_TYPE_LEADER = '"leader"'
NODE_TYPE_ROUTER = '"router"'
NODE_TYPE_END_DEVICE = '"end-device"'
NODE_TYPE_SLEEPY_END_DEVICE = '"sleepy-end-device"'
NODE_TYPE_COMMISSIONER = '"commissioner"'
NODE_TYPE_NEST_LURKER = '"nl-lurker"'
#-----------------------------------------------------------------------------------------------------------------------
# Node types used by `Node.join()`
JOIN_TYPE_ROUTER = 'r'
JOIN_TYPE_END_DEVICE = 'e'
JOIN_TYPE_SLEEPY_END_DEVICE = 's'
#-----------------------------------------------------------------------------------------------------------------------
# Bit Flags for Thread Device Mode `WPAN_THREAD_DEVICE_MODE`
THREAD_MODE_FLAG_FULL_NETWORK_DATA = (1 << 0)
THREAD_MODE_FLAG_FULL_THREAD_DEV = (1 << 1)
THREAD_MODE_FLAG_SECURE_DATA_REQUEST = (1 << 2)
THREAD_MODE_FLAG_RX_ON_WHEN_IDLE = (1 << 3)
#-----------------------------------------------------------------------------------------------------------------------
def _log(text, new_line=True, flush=True):
sys.stdout.write(text)
if new_line:
sys.stdout.write('\n')
if flush:
sys.stdout.flush()
#-----------------------------------------------------------------------------------------------------------------------
# Node class
class Node(object):
""" A wpantund OT NCP instance """
_VERBOSE = False # defines the default verbosity setting (can be changed per `Node`)
_SPEED_UP_FACTOR = 1 # defines the default time speed up factor
# path to `wpantund`, `wpanctl`, `ot-ncp-ftd`,`ot-ncp` and `ot-ncp-radio`
_WPANTUND = '/usr/local/sbin/wpantund'
_WPANCTL = '/usr/local/bin/wpanctl'
_OT_NCP_FTD = '../../examples/apps/ncp/ot-ncp-ftd'
_OT_NCP_FTD_POSIX_APP = '../../src/posix/ot-ncp'
_OT_NCP_RADIO = '../../examples/apps/ncp/ot-ncp-radio'
# Environment variable used to determine how to run OpenThread
# If set to 1, then posix-app (`ot-ncp`) is used along with a posix RCP `ot-ncp-radio`.
# Otherwise, the posix NCP `ot-ncp-ftd` is used
_POSIX_APP_ENV_VAR = 'TORANJ_POSIX_APP_RCP_MODEL'
_TUND_LOG_TO_FILE = True # determines if the wpantund logs are saved in file or sent to stdout
_TUND_LOG_FNAME = 'wpantund-logs' # name of wpantund log file (if # name of wpantund _TUND_LOG_TO_FILE is True)
# interface name
_INTFC_NAME_PREFIX = 'utun' if sys.platform == 'darwin' else 'wpan'
_START_INDEX = 4 if sys.platform == 'darwin' else 1
_cur_index = _START_INDEX
_all_nodes = weakref.WeakSet()
def __init__(self, verbose=_VERBOSE):
"""Creates a new `Node` instance"""
index = Node._cur_index
Node._cur_index += 1
self._index = index
self._interface_name = self._INTFC_NAME_PREFIX + str(index)
self._verbose = verbose
# Check if env variable `TORANJ_POSIX_APP_RCP_MODEL` is defined
# and use it to determine if to use operate in "posix-ncp-app".
if self._POSIX_APP_ENV_VAR in os.environ:
use_posix_app_with_rcp = (os.environ[self._POSIX_APP_ENV_VAR] in ['1', 'yes'])
else:
use_posix_app_with_rcp = False
if use_posix_app_with_rcp:
ncp_socket_path = 'system:{} -s {} {} {}'.format(self._OT_NCP_FTD_POSIX_APP, self._SPEED_UP_FACTOR,
self._OT_NCP_RADIO, index)
else:
ncp_socket_path = 'system:{} {} {}'.format(self._OT_NCP_FTD, index, self._SPEED_UP_FACTOR)
cmd = self._WPANTUND + \
' -o Config:NCP:SocketPath \"{}\"'.format(ncp_socket_path) + \
' -o Config:TUN:InterfaceName {}'.format(self._interface_name) + \
' -o Config:NCP:DriverName spinel' + \
' -o Daemon:SyslogMask \"all -debug\"'
if Node._TUND_LOG_TO_FILE:
self._tund_log_file = open(self._TUND_LOG_FNAME + str(index) + '.log', 'wb')
else:
self._tund_log_file = None
if self._verbose:
_log('$ Node{}.__init__() cmd: {}'.format(index, cmd))
self._wpantund_process = subprocess.Popen(cmd, shell=True, stderr=self._tund_log_file)
self._wpanctl_cmd = self._WPANCTL + ' -I ' + self._interface_name + ' '
self._recvers = weakref.WeakValueDictionary() # map from local_port to `AsyncReceiver` object
Node._all_nodes.add(self)
def __del__(self):
self._wpantund_process.poll()
if self._wpantund_process.returncode is None:
self._wpantund_process.terminate()
self._wpantund_process.wait()
def __repr__(self):
return 'Node (index={}, interface_name={})'.format(self._index, self._interface_name)
@property
def index(self):
return self._index
@property
def interface_name(self):
return self._interface_name
@property
def tund_log_file(self):
return self._tund_log_file
#------------------------------------------------------------------------------------------------------------------
# Executing a `wpanctl` command
def wpanctl(self, cmd):
""" Runs a wpanctl command on the given wpantund/OT-NCP instance and returns the output """
if self._verbose:
_log('$ Node{}.wpanctl(\'{}\')'.format(self._index, cmd), new_line=False)
result = subprocess.check_output(self._wpanctl_cmd + cmd, shell=True, stderr=subprocess.STDOUT)
if len(result) >= 1 and result[-1] == '\n': # remove the last char if it is '\n',
result = result[:-1]
if self._verbose:
if '\n' in result:
_log(':')
for line in result.splitlines():
_log(' ' + line)
else:
_log(' -> \'{}\''.format(result))
return result
#------------------------------------------------------------------------------------------------------------------
# APIs matching `wpanctl` commands.
def get(self, prop_name, value_only=True):
return self.wpanctl('get ' + ('-v ' if value_only else '') + prop_name)
def set(self, prop_name, value, binary_data=False):
return self._update_prop('set', prop_name, value, binary_data)
def add(self, prop_name, value, binary_data=False):
return self._update_prop('add', prop_name, value, binary_data)
def remove(self, prop_name, value, binary_data=False):
return self._update_prop('remove', prop_name, value, binary_data)
def _update_prop(self, action, prop_name, value, binary_data):
return self.wpanctl(action + ' ' + prop_name + ' ' + ('-d ' if binary_data else '') +
'-v ' + value) # use -v to handle values starting with `-`.
def reset(self):
return self.wpanctl('reset')
def status(self):
return self.wpanctl('status')
def leave(self):
return self.wpanctl('leave')
def form(self, name, channel=None, channel_mask=None, panid=None, xpanid=None, key=None, key_index=None,
node_type=None, mesh_local_prefix=None, legacy_prefix=None):
return self.wpanctl('form \"' + name + '\"' +
(' -c {}'.format(channel) if channel is not None else '') +
(' -m {}'.format(channel_mask) if channel_mask is not None else '') +
(' -p {}'.format(panid) if panid is not None else '') +
(' -x {}'.format(xpanid) if xpanid is not None else '') +
(' -k {}'.format(key) if key is not None else '') +
(' -i {}'.format(key_index) if key_index is not None else '') +
(' -T {}'.format(node_type) if node_type is not None else '') +
(' -M {}'.format(mesh_local_prefix) if mesh_local_prefix is not None else '') +
(' -L {}'.format(legacy_prefix) if legacy_prefix is not None else ''))
def join(self, name, channel=None, node_type=None, panid=None, xpanid=None, key=None):
return self.wpanctl('join \"' + name + '\"' +
(' -c {}'.format(channel) if channel is not None else '') +
(' -T {}'.format(node_type) if node_type is not None else '') +
(' -p {}'.format(panid) if panid is not None else '') +
(' -x {}'.format(xpanid) if xpanid is not None else '') +
(' -k {}'.format(key) if key is not None else '') +
(' -n'))
def active_scan(self, channel=None):
return self.wpanctl('scan' +
(' -c {}'.format(channel) if channel is not None else ''))
def energy_scan(self, channel=None):
return self.wpanctl('scan -e' +
(' -c {}'.format(channel) if channel is not None else ''))
def discover_scan(self, channel=None, joiner_only=False, enable_filtering=False, panid_filter=None):
return self.wpanctl('scan -d' +
(' -c {}'.format(channel) if channel is not None else '') +
(' -j' if joiner_only else '') +
(' -e' if enable_filtering else '') +
(' -p {}'.format(panid_filter) if panid_filter is not None else ''))
def permit_join(self, duration_sec=None, port=None, udp=True, tcp=True):
if not udp and not tcp: # incorrect use!
return ''
traffic_type = ''
if udp and not tcp:
traffic_type = ' --udp'
if tcp and not udp:
traffic_type = ' --tcp'
if port is not None and duration_sec is None:
duration_sec = '240'
return self.wpanctl('permit-join' +
(' {}'.format(duration_sec) if duration_sec is not None else '') +
(' {}'.format(port) if port is not None else '') +
traffic_type)
def config_gateway(self, prefix, default_route=False, priority=None):
return self.wpanctl('config-gateway ' + prefix +
(' -d' if default_route else '') +
(' -P {}'.format(priority) if priority is not None else ''))
def add_prefix(self, prefix, prefix_len=None, priority=None, stable=True, on_mesh=False, slaac=False, dhcp=False,
configure=False, default_route=False, preferred=False):
return self.wpanctl('add-prefix ' + prefix +
(' -l {}'.format(prefix_len) if prefix_len is not None else '') +
(' -P {}'.format(priority) if priority is not None else '') +
(' -s' if stable else '') +
(' -f' if preferred else '') +
(' -a' if slaac else '') +
(' -d' if dhcp else '') +
(' -c' if configure else '') +
(' -r' if default_route else '') +
(' -o' if on_mesh else ''))
def remove_prefix(self, prefix, prefix_len=None):
return self.wpanctl('remove-prefix ' + prefix +
(' -l {}'.format(prefix_len) if prefix_len is not None else ''))
def add_route(self, route_prefix, prefix_len=None, priority=None, stable=True):
"""route priority [(>0 for high, 0 for medium, <0 for low)]"""
return self.wpanctl('add-route ' + route_prefix +
(' -l {}'.format(prefix_len) if prefix_len is not None else '') +
(' -p {}'.format(priority) if priority is not None else '') +
('' if stable else '-n'))
def remove_route(self, route_prefix, prefix_len=None, priority=None, stable=True):
"""route priority [(>0 for high, 0 for medium, <0 for low)]"""
return self.wpanctl('remove-route ' + route_prefix +
(' -l {}'.format(prefix_len) if prefix_len is not None else '') +
(' -p {}'.format(priority) if priority is not None else ''))
#------------------------------------------------------------------------------------------------------------------
# Helper methods
def is_associated(self):
return self.get(WPAN_STATE) == STATE_ASSOCIATED
def join_node(self, node, node_type=JOIN_TYPE_ROUTER, should_set_key=True):
"""Join a network specified by another node, `node` should be a Node"""
if not node.is_associated():
return "{} is not associated".format(node)
return self.join(
node.get(WPAN_NAME)[1:-1],
channel=node.get(WPAN_CHANNEL),
node_type=node_type,
panid=node.get(WPAN_PANID),
xpanid=node.get(WPAN_XPANID),
key=node.get(WPAN_KEY)[1:-1] if should_set_key else None)
def whitelist_node(self, node):
"""Adds a given node (of type `Node`) to the whitelist of `self` and enables whitelisting on `self`"""
self.add(WPAN_MAC_WHITELIST_ENTRIES, node.get(WPAN_EXT_ADDRESS)[1:-1])
self.set(WPAN_MAC_WHITELIST_ENABLED, '1')
def un_whitelist_node(self, node):
"""Removes a given node (of node `Node) from the whitelist"""
self.remove(WPAN_MAC_WHITELIST_ENTRIES, node.get(WPAN_EXT_ADDRESS)[1:-1])
def is_in_scan_result(self, scan_result):
"""Checks if node is in the scan results
`scan_result` must be an array of `ScanResult` object (see `parse_scan_result`).
"""
joinable = (self.get(WPAN_NETWORK_ALLOW_JOIN) == 'true')
panid = self.get(WPAN_PANID)
xpanid = self.get(WPAN_XPANID)[2:]
name = self.get(WPAN_NAME)[1:-1]
channel = self.get(WPAN_CHANNEL)
ext_address = self.get(WPAN_EXT_ADDRESS)[1:-1]
for item in scan_result:
if all( [item.network_name == name,
item.panid == panid,
item.xpanid == xpanid,
item.channel == channel,
item.ext_address == ext_address,
(item.type == ScanResult.TYPE_DISCOVERY_SCAN) or (item.joinable == joinable) ] ):
return True
return False
def find_ip6_address_with_prefix(self, prefix):
"""Find an IPv6 address on node matching a given prefix.
`prefix` should be an string containing the prefix.
Returns a string containing the IPv6 address matching the prefix or empty string if no address found.
"""
if len(prefix) > 2 and prefix[-1] == ':' and prefix[-2] == ':':
prefix = prefix[:-1]
all_addrs = parse_list(self.get(WPAN_IP6_ALL_ADDRESSES))
matched_addr = [addr for addr in all_addrs if addr.startswith(prefix)]
return matched_addr[0] if len(matched_addr) >= 1 else ''
def add_ip6_address_on_interface(self, address, prefix_len=64):
"""Adds an IPv6 interface on the network interface.
`address` should be string containing the IPv6 address.
`prefix_len` is an `int` specifying the prefix length.
NOTE: this method uses linux `ip` command.
"""
cmd = 'ip -6 addr add '+ address + '/{} dev '.format(prefix_len) + self.interface_name
if self._verbose:
_log('$ Node{} \'{}\')'.format(self._index, cmd))
result = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
return result
def remove_ip6_address_on_interface(self, address, prefix_len=64):
"""Removes an IPv6 interface on the network interface.
`address` should be string containing the IPv6 address.
`prefix_len` is an `int` specifying the prefix length.
NOTE: this method uses linux `ip` command.
"""
cmd = 'ip -6 addr del '+ address + '/{} dev '.format(prefix_len) + self.interface_name
if self._verbose:
_log('$ Node{} \'{}\')'.format(self._index, cmd))
result = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
return result
#------------------------------------------------------------------------------------------------------------------
# class methods
@classmethod
def init_all_nodes(cls, disable_logs=True, wait_time=15):
"""Issues a `wpanctl.leave` on all `Node` objects and waits for them to be ready"""
random.seed(123456)
time.sleep(0.5)
for node in Node._all_nodes:
start_time = time.time()
while True:
try:
node._wpantund_process.poll()
if node._wpantund_process.returncode is not None:
print 'Node {} wpantund instance has terminated unexpectedly'.format(node)
if disable_logs:
node.set(WPAN_OT_LOG_LEVEL, '0')
node.leave()
except subprocess.CalledProcessError as e:
if (node._verbose):
_log(' -> \'{}\' exit code: {}'.format(e.output, e.returncode))
interval = time.time() - start_time
if interval > wait_time:
print 'Took too long to init node {} ({}>{} sec)'.format(node, interval, wait_time)
raise
except:
raise
else:
break
time.sleep(0.4)
@classmethod
def finalize_all_nodes(cls):
"""Finalizes all previously created `Node` instances (stops the wpantund process)"""
for node in Node._all_nodes:
node._wpantund_process.terminate()
node._wpantund_process.wait()
@classmethod
def set_time_speedup_factor(cls, factor):
"""Sets up the time speed up factor - should be set before creating any `Node` objects"""
if len(Node._all_nodes) != 0:
raise Node._NodeError('set_time_speedup_factor() cannot be called after creating a `Node`')
Node._SPEED_UP_FACTOR = factor
#------------------------------------------------------------------------------------------------------------------
# IPv6 message Sender and Receiver class
class _NodeError(Exception):
pass
def prepare_tx(self, src, dst, data=40, count=1, mcast_hops=None):
"""Prepares an IPv6 msg transmission.
- `src` and `dst` can be either a string containing IPv6 address, or a tuple (ipv6 address as string, port),
if no port is given, a random port number is used.
- `data` can be either a string containing the message to be sent, or an int indicating size of the message (a
random message with the given length will be used).
- `count` gives number of times the message will be sent (default is 1).
- `mcast_hops` specifies multicast hop limit (only applicable for multicast tx).
Returns an `AsyncSender` object.
"""
if isinstance(src, tuple):
src_addr = src[0]
src_port = src[1]
else:
src_addr = src
src_port = random.randint(49152, 65535)
if isinstance(dst, tuple):
dst_addr = dst[0]
dst_port = dst[1]
else:
dst_addr = dst
dst_port = random.randint(49152, 65535)
if isinstance(data, int):
# create a random message with the given length.
all_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,><?;:[]=-+)(*&^%$#@'
msg = ''.join(random.choice(all_chars) for _ in range(data))
else:
msg = data
return AsyncSender(self, src_addr, src_port, dst_addr, dst_port, msg, count, mcast_hops)
def _get_receiver(self, local_port):
# Gets or creates a receiver (an `AsyncReceiver`) tied to given port number
if local_port in self._recvers:
receiver = self._recvers[local_port]
else:
receiver = AsyncReceiver(self, local_port)
self._recvers[local_port] = receiver
return receiver
def _remove_recver(self, recvr):
# Removes a receiver from weak dictionary - called when the receiver is done and its socket is closed
local_port = recvr.local_port
if local_port in self._recvers:
del self._recvers[local_port]
def prepare_rx(self, sender):
"""Prepare to receive messages from a sender (an `AsyncSender`)"""
receiver = self._get_receiver(sender.dst_port)
receiver._add_sender(sender.src_addr, sender.src_port, sender.msg, sender.count)
return receiver
def preapre_listener(self, local_port, timeout=1):
"""Prepares a listener (an `AsyncReceiver`) listening on the given `local_port` for given `timeout` (sec)"""
receiver = self._get_receiver(local_port)
receiver._set_listen_timeout(timeout)
return receiver
@staticmethod
def perform_async_tx_rx(timeout=20):
"""Called to perform all previously prepared async rx/listen and tx operations"""
try:
start_time = time.time()
while asyncore.socket_map:
elapsed_time = time.time() - start_time
if elapsed_time > timeout:
print 'Performing aysnc tx/tx took too long ({}>{} sec)'.format(elapsed_time, timeout)
raise Node._NodeError('perform_tx_rx timed out ({}>{} sec)'.format(elapsed_time, timeout))
# perform a single asyncore loop
asyncore.loop(timeout=0.5, count=1)
except:
print 'Failed to perform async rx/tx'
raise
#-----------------------------------------------------------------------------------------------------------------------
# `AsyncSender` and `AsyncReceiver classes
_SO_BINDTODEVICE = 25
def _is_ipv6_addr_link_local(ip_addr):
"""Indicates if a given IPv6 address is link-local"""
return ip_addr.lower().startswith('fe80::')
def _create_socket_address(ip_address, port):
"""Convert a given IPv6 address (string) and port number into a socket address"""
# `socket.getaddrinfo()` returns a list of `(family, socktype, proto, canonname, sockaddr)` where `sockaddr`
# (at index 4) can be used as input in socket methods (like `sendto()`, `bind()`, etc.).
return socket.getaddrinfo(ip_address, port)[0][4]
class AsyncSender(asyncore.dispatcher):
""" An IPv6 async message sender - use `Node.prepare_tx()` to create one"""
def __init__(self, node, src_addr, src_port, dst_addr, dst_port, msg, count, mcast_hops=None):
self._node = node
self._src_addr = src_addr
self._src_port = src_port
self._dst_addr = dst_addr
self._dst_port = dst_port
self._msg = msg
self._count = count
self._dst_sock_addr = _create_socket_address(dst_addr, dst_port)
self._tx_buffer = self._msg
self._tx_counter = 0
# Create a socket, bind it to the node's interface
sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, _SO_BINDTODEVICE, node.interface_name + '\0')
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
# Set the IPV6_MULTICAST_HOPS
if mcast_hops is not None:
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, mcast_hops)
# Bind the socket to the given src address
if _is_ipv6_addr_link_local(src_addr):
# If src is a link local address it requires the interface name to be specified.
src_sock_addr = _create_socket_address(src_addr + '%' + node.interface_name, src_port)
else:
src_sock_addr = _create_socket_address(src_addr, src_port)
sock.bind(src_sock_addr)
asyncore.dispatcher.__init__(self, sock)
# Property getters
@property
def node(self):
return self._node
@property
def src_addr(self):
return self._src_addr
@property
def src_port(self):
return self._src_port
@property
def dst_addr(self):
return self._dst_addr
@property
def dst_port(self):
return self._dst_port
@property
def msg(self):
return self._msg
@property
def count(self):
return self._count
@property
def was_successful(self):
"""Indicates if the transmission of IPv6 messages finished successfully"""
return self._tx_counter == self._count
# asyncore.dispatcher callbacks
def readable(self):
return False
def writable(self):
return True
def handle_write(self):
sent_len = self.sendto(self._tx_buffer, self._dst_sock_addr)
if self._node._verbose:
if sent_len < 30:
info_text = '{} bytes ("{}")'.format(sent_len, self._tx_buffer[:sent_len])
else:
info_text = '{} bytes'.format(sent_len)
_log('- Node{} sent {} to [{}]:{} from [{}]:{}'.format(self._node._index, info_text,
self._dst_addr, self._dst_port,
self._src_addr, self._src_port))
self._tx_buffer = self._tx_buffer[sent_len:]
if len(self._tx_buffer) == 0:
self._tx_counter += 1
if self._tx_counter < self._count:
self._tx_buffer = self._msg
else:
self.handle_close()
def handle_close(self):
self.close()
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class AsyncReceiver(asyncore.dispatcher):
""" An IPv6 async message receiver - use `prepare_rx()` to create one"""
_MAX_RECV_SIZE = 2048
class _SenderInfo(object):
def __init__(self, sender_addr, sender_port, msg, count):
self._sender_addr = sender_addr
self._sender_port = sender_port
self._msg = msg
self._count = count
self._rx_counter = 0
def _check_received(self, msg, sender_addr, sender_port):
if self._msg == msg and self._sender_addr == sender_addr and self._sender_port == sender_port:
self._rx_counter += 1
return self._did_recv_all()
def _did_recv_all(self):
return self._rx_counter >= self._count
def __init__(self, node, local_port):
self._node = node
self._local_port = local_port
self._senders = [] # list of `_SenderInfo` objects
self._all_rx = [] # contains all received messages as a list of (pkt, (src_addr, src_port))
self._timeout = 0 # listen timeout (zero means forever)
self._started = False
self._start_time = 0
# Create a socket, bind it to the node's interface
sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, _SO_BINDTODEVICE, node.interface_name + '\0')
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
# Bind the socket to any IPv6 address with the given local port
local_sock_addr = _create_socket_address('::', local_port)
sock.bind(local_sock_addr)
asyncore.dispatcher.__init__(self, sock)
def _add_sender(self, sender_addr, sender_port, msg, count):
self._senders.append(AsyncReceiver._SenderInfo(sender_addr, sender_port, msg, count))
def _set_listen_timeout(self, timeout):
self._timeout = timeout
# Property getters
@property
def node(self):
return self._node
@property
def local_port(self):
return self._local_port
@property
def all_rx_msg(self):
"""returns all received messages as a list of (msg, (src_addr, src_port))"""
return self._all_rx
@property
def was_successful(self):
"""Indicates if all expected IPv6 messages were received successfully"""
return len(self._senders) == 0 or all([sender._did_recv_all() for sender in self._senders])
# asyncore.dispatcher callbacks
def readable(self):
if not self._started:
self._start_time = time.time()
self._started = True
if self._timeout != 0 and time.time() - self._start_time >= self._timeout:
self.handle_close()
if self._node._verbose:
_log('- Node{} finished listening on port {} for {} sec, received {} msg(s)'.format(
self._node._index, self._local_port, self._timeout, len(self._all_rx)))
return False
return True
def writable(self):
return False
def handle_read(self):
(msg, src_sock_addr) = self.recvfrom(AsyncReceiver._MAX_RECV_SIZE)
src_addr = src_sock_addr[0]
src_port = src_sock_addr[1]
if (_is_ipv6_addr_link_local(src_addr)):
if '%' in src_addr:
src_addr = src_addr.split('%')[0] # remove the interface name from address
if self._node._verbose:
if len(msg) < 30:
info_text = '{} bytes ("{}")'.format(len(msg), msg)
else:
info_text = '{} bytes'.format(len(msg))
_log('- Node{} received {} on port {} from [{}]:{}'.format(self._node._index, info_text,
self._local_port,
src_addr, src_port))
self._all_rx.append((msg, (src_addr, src_port)))
if all([sender._check_received(msg, src_addr, src_port) for sender in self._senders]):
self.handle_close()
def handle_close(self):
self.close()
# remove the receiver from the node once the socket is closed
self._node._remove_recver(self)
#-----------------------------------------------------------------------------------------------------------------------
class VerifyError(Exception):
pass
_is_in_verify_within = False
def verify(condition):
"""Verifies that a `condition` is true, otherwise raises a VerifyError"""
global _is_in_verify_within
if not condition:
calling_frame = inspect.currentframe().f_back
error_message = 'verify() failed at line {} in "{}"'.format(calling_frame.f_lineno, calling_frame.f_code.co_filename)
if not _is_in_verify_within:
print error_message
raise VerifyError(error_message)
def verify_within(condition_checker_func, wait_time, delay_time=0.1):
"""Verifies that a given function `condition_checker_func` passes successfully within a given wait timeout.
`wait_time` is maximum time waiting for condition_checker to pass (in seconds).
`delay_time` specifies a delay interval added between failed attempts (in seconds).
"""
global _is_in_verify_within
start_time = time.time()
old_is_in_verify_within = _is_in_verify_within
_is_in_verify_within = True
while True:
try:
condition_checker_func()
except VerifyError as e:
if time.time() - start_time > wait_time:
print 'Took too long to pass the condition ({}>{} sec)'.format(time.time() - start_time, wait_time)
print e.message
raise e
except:
raise
else:
break
if delay_time != 0:
time.sleep(delay_time)
_is_in_verify_within = old_is_in_verify_within
#-----------------------------------------------------------------------------------------------------------------------
# Parsing `wpanctl` output
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class ScanResult(object):
""" This object encapsulates a scan result (active/discover/energy scan)"""
TYPE_ACTIVE_SCAN = 'active-scan'
TYPE_DISCOVERY_SCAN = 'discover-scan'
TYPE_ENERGY_SCAN = 'energy-scan'
def __init__(self, result_text):
items = [item.strip() for item in result_text.split('|')]
if len(items) == 8:
self._type = ScanResult.TYPE_ACTIVE_SCAN
self._index = items[0]
self._joinable = (items[1] == 'YES')
self._network_name = items[2][1:-1]
self._panid = items[3]
self._channel = items[4]
self._xpanid = items[5]
self._ext_address = items[6]
self._rssi = items[7]
elif len(items) == 7:
self._type = ScanResult.TYPE_DISCOVERY_SCAN
self._index = items[0]
self._network_name = items[1][1:-1]
self._panid = items[2]
self._channel = items[3]
self._xpanid = items[4]
self._ext_address = items[5]
self._rssi = items[6]
elif len(items) == 2:
self._type = ScanResult.TYPE_ENERGY_SCAN
self._channel = items[0]
self._rssi = items[1]
else:
raise ValueError('"{}" does not seem to be a valid scan result string'.result_text)
@property
def type(self):
return self._type
@property
def joinable(self):
return self._joinable
@property
def network_name(self):
return self._network_name
@property
def panid(self):
return self._panid
@property
def channel(self):
return self._channel
@property
def xpanid(self):
return self._xpanid
@property
def ext_address(self):
return self._ext_address
@property
def rssi(self):
return self._rssi
def __repr__(self):
return 'ScanResult({})'.format(self.__dict__)
def parse_scan_result(scan_result):
""" Parses scan result string and returns an array of `ScanResult` objects"""
return [ ScanResult(item) for item in scan_result.split('\n')[2:] ] # skip first two lines which are table headers
def parse_list(list_string):
"""
Parses IPv6/prefix/route list string (output of wpanctl get for properties WPAN_IP6_ALL_ADDRESSES,
IP6_MULTICAST_ADDRESSES, WPAN_THREAD_ON_MESH_PREFIXES, ...)
Returns an array of strings each containing an IPv6/prefix/route entry.
"""
# List string example (get(WPAN_IP6_ALL_ADDRESSES) output):
#
# '[\n
# \t"fdf4:5632:4940:0:8798:8701:85d4:e2be prefix_len:64 origin:ncp valid:forever preferred:forever"\n
# \t"fe80::2092:9358:97ea:71c6 prefix_len:64 origin:ncp valid:forever preferred:forever"\n
# ]'
#
# We split the lines ('\n' as separator) and skip the first and last lines which are '[' and ']'.
# For each line, skip the first two characters (which are '\t"') and last character ('"'), then split the string
# using whitespace as separator. The first entry is the IPv6 address.
#
return [line[2:-1].split()[0] for line in list_string.split('\n')[1:-1]]
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class OnMeshPrefix(object):
""" This object encapsulates an on-mesh prefix"""
def __init__(self, text):
# Example of expected text:
#
# '\t"fd00:abba:cafe:: prefix_len:64 origin:user stable:yes flags:0x31'
# ' [on-mesh:1 def-route:0 config:0 dhcp:0 slaac:1 pref:1 prio:med] rloc:0x0000"'
m = re.match('\t"([0-9a-fA-F:]+)\s*prefix_len:(\d+)\s+origin:(\w*)\s+stable:(\w*).* \[' +
'on-mesh:(\d)\s+def-route:(\d)\s+config:(\d)\s+dhcp:(\d)\s+slaac:(\d)\s+pref:(\d)\s+prio:(\w*)\]' +
'\s+rloc:(0x[0-9a-fA-F]+)',
text)
verify(m is not None)
data = m.groups()
self._prefix = data[0]
self._prefix_len = data[1]
self._origin = data[2]
self._stable = (data[3] == 'yes')
self._on_mesh = (data[4] == '1')
self._def_route = (data[5] == '1')
self._config = (data[6] == '1')
self._dhcp = (data[7] == '1')
self._slaac = (data[8] == '1')
self._preferred = (data[9] == '1')
self._priority = (data[10])
self._rloc16 = (data[11])
@property
def prefix(self):
return self._prefix
@property
def prefix_len(self):
return self._prefix_len
@property
def origin(self):
return self._origin
@property
def priority(self):
return self._priority
def is_stable(self):
return self._stable
def is_on_mesh(self):
return self._on_mesh
def is_def_route(self):
return self._def_route
def is_config(self):
return self._config
def is_dhcp(self):
return self._dhcp
def is_slaac(self):
return self._slaac
def is_preferred(self):
return self._preferred
def rloc16(self):
return self._rloc16
def __repr__(self):
return 'OnMeshPrefix({})'.format(self.__dict__)
def parse_on_mesh_prefix_result(on_mesh_prefix_list):
""" Parses on-mesh prefix list string and returns an array of `OnMeshPrefix` objects"""
return [ OnMeshPrefix(item) for item in on_mesh_prefix_list.split('\n')[1:-1] ]
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class ChildEntry(object):
""" This object encapsulates a child entry"""
def __init__(self, text):
# Example of expected text:
#
# `\t"E24C5F67F4B8CBB9, RLOC16:d402, NetDataVer:175, LQIn:3, AveRssi:-20, LastRssi:-20, Timeout:120, Age:0, `
# `RxOnIdle:no, FTD:no, SecDataReq:yes, FullNetData:yes"`
#
# We get rid of the first two chars `\t"' and last char '"', split the rest using whitespace as separator.
# Then remove any ',' at end of items in the list.
items = [item[:-1] if item[-1] ==',' else item for item in text[2:-1].split()]
# First item in the extended address
self._ext_address = items[0]
# Convert the rest into a dictionary by splitting using ':' as separator
dict = {item.split(':')[0] : item.split(':')[1] for item in items[1:]}
self._rloc16 = dict['RLOC16']
self._timeout = dict['Timeout']
self._rx_on_idle = (dict['RxOnIdle'] == 'yes')
self._ftd = (dict['FTD'] == 'yes')
self._sec_data_req = (dict['SecDataReq'] == 'yes')
self._full_net_data = (dict['FullNetData'] == 'yes')
@property
def ext_address(self):
return self._ext_address
@property
def rloc16(self):
return self._rloc16
@property
def timeout(self):
return self._timeout
def is_rx_on_when_idle(self):
return self._rx_on_idle
def is_ftd(self):
return self._ftd
def is_sec_data_req(self):
return self._sec_data_req
def is_full_net_data(self):
return self._full_net_data
def __repr__(self):
return 'ChildEntry({})'.format(self.__dict__)
def parse_child_table_result(child_table_list):
""" Parses child table list string and returns an array of `ChildEntry` objects"""
return [ ChildEntry(item) for item in child_table_list.split('\n')[1:-1] ]
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class NeighborEntry(object):
""" This object encapsulates a neighbor entry"""
def __init__(self, text):
# Example of expected text:
#
# `\t"5AC95ED4646D6565, RLOC16:9403, LQIn:3, AveRssi:-20, LastRssi:-20, Age:0, LinkFC:8, MleFC:0, IsChild:yes, '
# 'RxOnIdle:no, FTD:no, SecDataReq:yes, FullNetData:yes"'
#
# We get rid of the first two chars `\t"' and last char '"', split the rest using whitespace as separator.
# Then remove any ',' at end of items in the list.
items = [item[:-1] if item[-1] ==',' else item for item in text[2:-1].split()]
# First item in the extended address
self._ext_address = items[0]
# Convert the rest into a dictionary by splitting the text using ':' as separator
dict = {item.split(':')[0] : item.split(':')[1] for item in items[1:]}
self._rloc16 = dict['RLOC16']
self._is_child = (dict['IsChild'] == 'yes')
self._rx_on_idle = (dict['RxOnIdle'] == 'yes')
self._ftd = (dict['FTD'] == 'yes')
@property
def ext_address(self):
return self._ext_address
@property
def rloc16(self):
return self._rloc16
def is_rx_on_when_idle(self):
return self._rx_on_idle
def is_ftd(self):
return self._ftd
def is_child(self):
return self._is_child
def __repr__(self):
return 'NeighborEntry({})'.format(self.__dict__)
def parse_neighbor_table_result(neighbor_table_list):
""" Parses neighbor table list string and returns an array of `NeighborEntry` objects"""
return [ NeighborEntry(item) for item in neighbor_table_list.split('\n')[1:-1] ]
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class RouterTableEntry(object):
""" This object encapsulates a router table entry"""
def __init__(self, text):
# Example of expected text:
#
# `\t"8A970B3251810826, RLOC16:4000, RouterId:16, NextHop:43, PathCost:1, LQIn:3, LQOut:3, Age:3, LinkEst:yes"`
#
# We get rid of the first two chars `\t"' and last char '"', split the rest using whitespace as separator.
# Then remove any ',' at end of items in the list.
items = [item[:-1] if item[-1] ==',' else item for item in text[2:-1].split()]
# First item in the extended address
self._ext_address = items[0]
# Convert the rest into a dictionary by splitting the text using ':' as separator
dict = {item.split(':')[0] : item.split(':')[1] for item in items[1:]}
self._rloc16 = int(dict['RLOC16'], 16)
self._router_id = int(dict['RouterId'], 0)
self._next_hop = int(dict['NextHop'], 0)
self._path_cost = int(dict['PathCost'], 0)
self._age = int(dict['Age'], 0)
self._le = (dict['LinkEst'] == 'yes')
@property
def ext_address(self):
return self._ext_address
@property
def rloc16(self):
return self._rloc16
@property
def router_id(self):
return self._router_id
@property
def next_hop(self):
return self._next_hop
@property
def path_cost(self):
return self._path_cost
def is_link_established(self):
return self._le
def __repr__(self):
return 'RouterTableEntry({})'.format(self.__dict__)
def parse_router_table_result(router_table_list):
""" Parses router table list string and returns an array of `RouterTableEntry` objects"""
return [ RouterTableEntry(item) for item in router_table_list.split('\n')[1:-1] ]
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class AddressCacheEntry(object):
""" This object encapsulates an address cache entry"""
def __init__(self, text):
# Example of expected text:
#
# '\t"fd00:1234::d427:a1d9:6204:dbae -> 0x9c00, age:0"'
#
# We get rid of the first two chars `\t"' and last char '"', split the rest using whitespace as separator.
# Then remove any ',' at end of items in the list.
items = [item[:-1] if item[-1] ==',' else item for item in text[2:-1].split()]
# First item in the extended address
self._address = items[0]
self._rloc16 = int(items[2], 16)
# Convert the rest into a dictionary by splitting the text using ':' as separator
dict = {item.split(':')[0] : item.split(':')[1] for item in items[3:]}
self._age = int(dict['age'], 0)
@property
def address(self):
return self._address
@property
def rloc16(self):
return self._rloc16
@property
def age(self):
return self._age
def __repr__(self):
return 'AddressCacheEntry({})'.format(self.__dict__)
def parse_address_cache_table_result(addr_cache_table_list):
""" Parses address cache table list string and returns an array of `AddressCacheEntry` objects"""
return [ AddressCacheEntry(item) for item in addr_cache_table_list.split('\n')[1:-1] ]
|
unknown
|
codeparrot/codeparrot-clean
| ||
#!/usr/bin/env python
import re
import os
class PgCatalogHeader(object):
"""This class is a base class for catalog header parser class, and
provides basic methods to parse header files by regular expressions.
The result will be in self.tuplist. To extend this class, set these
three class values.
- header
- hasoid
- prefix
and call self.initialize() in __init__().
"""
catalogdir = '../../../include/catalog'
def initialize(self):
path = self.fullpath(self.header)
self.tuplist = self.readheader(path, self.hasoid, self.prefix)
if not self.tuplist:
raise Exception("no content")
def fullpath(self, filename):
"""Returns the full path name of the catalog file."""
thisdir = os.path.dirname(os.path.realpath(__file__))
path = os.path.join(thisdir, self.catalogdir)
return os.path.join(path, filename)
def readheader(self, header, hasoid, tableprefix):
"""Returns a list of dictionaries as the result of parse.
It finds lines starting with "#define Anum_" and collects
attribute names, then parse DATA() macros. All data is
parsed as string regardless of the column type.
"""
anum = re.compile(r'#define Anum_' + tableprefix + r'_(\w+)')
rebuf = list()
attlist = list()
for line in open(header):
m = anum.match(line)
if m:
# Build up regular expression.
# We capture the group by name to look up later
rebuf.append(r'(?P<' + m.group(1) + r'>\S+|"[^"]+")')
attlist.append(m.group(1))
oidpattern = ''
if hasoid:
oidpattern = r'OID\s*=\s*(?P<oid>\w+)\s*'
attlist.append('oid')
insert = re.compile(r'DATA\(insert\s+' +
oidpattern + r'\(\s*' +
'\s+'.join(rebuf) +
r'\s*\)\);')
# Collect all the DATA() lines and put them into a list
tuplist = list()
for line in open(header):
m = insert.match(line)
if m:
tup = dict()
for att in attlist:
tup[att] = m.group(att)
tuplist.append(tup)
return tuplist
class PgAmop(PgCatalogHeader):
header = 'pg_amop.h'
hasoid = False
prefix = 'pg_amop'
def __init__(self):
self.initialize()
def find_amopopr(self, amopclaid, amopstrategy):
"""Returns the operator oid that matches opclass and strategy."""
for tup in self.tuplist:
if (tup['amopclaid'] == str(amopclaid) and
tup['amopstrategy'] == str(amopstrategy)):
return tup['amopopr']
class PgOpclass(PgCatalogHeader):
header = 'pg_opclass.h'
hasoid = True
prefix = 'pg_opclass'
def __init__(self):
self.initialize()
def find_btree_oid_by_opcintype(self, opcintype):
"""Returns the opclass oid whoose input type is opcintype if it
is a btree opclass and default for the type.
"""
for tup in self.tuplist:
# 403 is the btree access method id
if (tup['opcintype'] == str(opcintype) and
tup['opcamid'] == '403' and
tup['opcdefault'] == 't'):
return tup['oid']
class PgOperator(PgCatalogHeader):
header = 'pg_operator.h'
hasoid = True
prefix = 'pg_operator'
def __init__(self):
self.initialize()
def find_oprcode(self, oid):
"""Returns the procedure oid of the operator."""
for tup in self.tuplist:
if tup['oid'] == str(oid):
return tup['oprcode']
class PgType(PgCatalogHeader):
header = 'pg_type.h'
hasoid = True
prefix = 'pg_type'
def __init__(self):
self.initialize()
self.oid_defs = self._read_oid_defs()
def findtup_by_typname(self, typname):
"""Returns a tuple that matches typname.
The input typname is normalized if it's any of quote_char, boolean,
smallint, integer, bigint, real, or timestamp_with_time_zone.
Also, if typname looks like an array type with '[]', it is normalized
to an array type name with underscore prefix.
"""
basename = typname.rstrip('[]')
isarray = False
if basename != typname:
isarray = True
typname = basename
if typname == 'quoted_char':
typname = 'char'
elif typname == 'boolean':
typname = 'bool'
elif typname == 'smallint':
typname = 'int2'
elif typname == 'integer':
typname = 'int4'
elif typname == 'bigint':
typname = 'int8'
elif typname == 'real':
typname = 'float4'
elif typname == 'timestamp_with_time_zone':
typname = 'timestamptz'
if isarray:
typname = '_' + typname
for tup in self.tuplist:
if tup['typname'] == str(typname):
return tup
def findtup_by_typid(self, typid):
for tup in self.tuplist:
if tup['oid'] == str(typid):
return tup
def oid_to_def(self, oid):
return self.oid_defs.get(int(oid), str(oid))
def _read_oid_defs(self):
"""Reads #define lines in pg_type.sql and builds up a map from
oid(int) to macro string.
"""
filename = os.path.join(self.catalogdir, 'pg_type.sql')
pat = re.compile(r'^.*#define\s+\S*OID\s+\d+')
oidmap = dict()
for line in open(filename):
m = pat.match(line)
if m:
tup = line.split()
oid = int(tup[-1])
oidname = tup[-2]
oidmap[oid] = oidname
return oidmap
class PgProc(PgCatalogHeader):
header = 'pg_proc.h'
hasoid = True
prefix = 'pg_proc'
def __init__(self):
self.initialize()
def find_prosrc_by_proname(self, proname):
for tup in self.tuplist:
if tup['proname'] == str(proname):
return tup['prosrc']
|
unknown
|
codeparrot/codeparrot-clean
| ||
import unittest
from . import load_tests
if __name__ == "__main__":
unittest.main()
|
python
|
github
|
https://github.com/python/cpython
|
Lib/test/test_zipfile/__main__.py
|
/**
* Integration with the JSR-354 <code>javax.money</code> package.
*/
@NullMarked
package org.springframework.format.number.money;
import org.jspecify.annotations.NullMarked;
|
java
|
github
|
https://github.com/spring-projects/spring-framework
|
spring-context/src/main/java/org/springframework/format/number/money/package-info.java
|
from test import TestCase, fill_redis_with_vectors, generate_random_vector
import random
class LargeScale(TestCase):
def getname(self):
return "Large Scale Comparison"
def estimated_runtime(self):
return 10
def test(self):
dim = 300
count = 20000
k = 50
# Fill Redis and get reference data for comparison
random.seed(42) # Make test deterministic
data = fill_redis_with_vectors(self.redis, self.test_key, count, dim)
# Generate query vector
query_vec = generate_random_vector(dim)
# Get results from Redis with good exploration factor
redis_raw = self.redis.execute_command('VSIM', self.test_key, 'VALUES', dim,
*[str(x) for x in query_vec],
'COUNT', k, 'WITHSCORES', 'EF', 500)
# Convert Redis results to dict
redis_results = {}
for i in range(0, len(redis_raw), 2):
key = redis_raw[i].decode()
score = float(redis_raw[i+1])
redis_results[key] = score
# Get results from linear scan
linear_results = data.find_k_nearest(query_vec, k)
linear_items = {name: score for name, score in linear_results}
# Compare overlap
redis_set = set(redis_results.keys())
linear_set = set(linear_items.keys())
overlap = len(redis_set & linear_set)
# If test fails, print comparison for debugging
if overlap < k * 0.7:
data.print_comparison({'items': redis_results, 'query_vector': query_vec}, k)
assert overlap >= k * 0.7, \
f"Expected at least 70% overlap in top {k} results, got {overlap/k*100:.1f}%"
# Verify scores for common items
for item in redis_set & linear_set:
redis_score = redis_results[item]
linear_score = linear_items[item]
assert abs(redis_score - linear_score) < 0.01, \
f"Score mismatch for {item}: Redis={redis_score:.3f} Linear={linear_score:.3f}"
|
python
|
github
|
https://github.com/redis/redis
|
modules/vector-sets/tests/large_scale.py
|
#!/usr/bin/python3
# Copyright (c) 2015 Yannick Lamarre
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
__author__ = 'Yannick Lamarre'
__license__ = 'BSD License'
import sys
import os
import io
import argparse
import curses
import xdlrc_parser
def clip_cursor(curpos_tup, maxyx_tup, ystep, xstep):
retval = [0, 0]
retval[0] = curpos_tup[0] + ystep*2
retval[1] = curpos_tup[1] + xstep*2
if retval[0] < 0:
retval[0] = maxyx[0] - retval[0] + 2
elif retval[0] > maxyx[0]:
retval[0] = retval[0] - maxyx[0] - 2
if retval[1] < 0:
retval[1] = maxyx[1] - retval[1] + 2
elif retval[1] > maxyx[1]:
retval[1] = retval[1] - maxyx[1] - 2
return retval
def main():
parser = argparse.ArgumentParser(description='fpga Reverse Engineering tool')
parser.add_argument('file', nargs='?',
help='File to edit')
args = parser.parse_args()
if args.file:
device_layout = xdlrc_parser.load_xdlrc(args.file)
else:
device_layout = None
curses.wrapper(main_window, device_layout)
def main_window(stdscr, device_layout):
tilesym_dict = {}
stdscr.clear()
cursor_posx = 0
cursor_posy = 0
if device_layout:
wrkpad = curses.newpad(device_layout.tile_rows*2, device_layout.tile_cols*2)
for irow in range(0, device_layout.tile_rows):
for icol in range(0, device_layout.tile_cols):
itile = device_layout.tile_list[irow*device_layout.tile_cols + icol]
wrkpad.addstr(irow*2, icol*2, itile[4]._val[0]+' ')
while True:
stdscr.move(cursor_posy+1, cursor_posx+1)
wrkpad.refresh(cursor_posy, cursor_posx, 1, 1, 30, 120)
curses.curs_set(1)
stdscr.refresh()
c_key = stdscr.getkey()
if c_key == 'q':
break
elif c_key == 'h':
pass
elif c_key == 'j':
pass
elif c_key == 'k':
pass
elif c_key == 'l':
pass
elif c_key == 'y':
pass
elif c_key == 'u':
pass
elif c_key == 'b':
pass
elif c_key == 'n':
pass
else:
pass
def manage_tile_dictionary(device_layout):
"""Manages the dictionary for screen's tile symbols
The dictionary mapping a character to be displayed to a tile name
I
Args:
device_layout: A DeviceLayout object containing device information
Returns:
A dict mapping a tile name to a character to be displayed
"""
return_value = []
main()
|
unknown
|
codeparrot/codeparrot-clean
| ||
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.collect.Iterators.peekingIterator;
import static com.google.common.collect.ReflectionFreeAssertThrows.assertThrows;
import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE;
import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.Collections.unmodifiableList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.testing.IteratorTester;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import junit.framework.TestCase;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
/**
* Unit test for {@link PeekingIterator}.
*
* @author Mick Killianey
*/
@SuppressWarnings("serial") // No serialization is used in this test
@GwtCompatible
@NullMarked
public class PeekingIteratorTest extends TestCase {
/**
* Version of {@link IteratorTester} that compares an iterator over a given collection of elements
* (used as the reference iterator) against a {@code PeekingIterator} that *wraps* such an
* iterator (used as the target iterator).
*
* <p>This IteratorTester makes copies of the master so that it can later verify that {@link
* PeekingIterator#remove()} removes the same elements as the reference's iterator {@code
* remove()}.
*/
private static class PeekingIteratorTester<T extends @Nullable Object> extends IteratorTester<T> {
private final Iterable<T> master;
private @Nullable List<T> targetList;
PeekingIteratorTester(Collection<T> master) {
super(master.size() + 3, MODIFIABLE, master, IteratorTester.KnownOrder.KNOWN_ORDER);
this.master = master;
}
@Override
protected Iterator<T> newTargetIterator() {
// make copy from master to verify later
targetList = Lists.newArrayList(master);
Iterator<T> iterator = targetList.iterator();
return peekingIterator(iterator);
}
@Override
protected void verify(List<T> elements) {
// verify same objects were removed from reference and target
assertEquals(elements, targetList);
}
}
private <T extends @Nullable Object> void actsLikeIteratorHelper(List<T> list) {
// Check with modifiable copies of the list
new PeekingIteratorTester<T>(list).test();
// Check with unmodifiable lists
new IteratorTester<T>(
list.size() * 2 + 2, UNMODIFIABLE, list, IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<T> newTargetIterator() {
Iterator<T> iterator = unmodifiableList(list).iterator();
return peekingIterator(iterator);
}
}.test();
}
public void testPeekingIteratorBehavesLikeIteratorOnEmptyIterable() {
actsLikeIteratorHelper(emptyList());
}
public void testPeekingIteratorBehavesLikeIteratorOnSingletonIterable() {
actsLikeIteratorHelper(singletonList(new Object()));
}
// TODO(cpovirk): instead of skipping, use a smaller number of steps
@GwtIncompatible // works but takes 5 minutes to run
public void testPeekingIteratorBehavesLikeIteratorOnThreeElementIterable() {
actsLikeIteratorHelper(Lists.newArrayList("A", "B", "C"));
}
@GwtIncompatible // works but takes 5 minutes to run
public void testPeekingIteratorAcceptsNullElements() {
actsLikeIteratorHelper(Lists.<@Nullable String>newArrayList(null, "A", null));
}
public void testPeekOnEmptyList() {
List<?> list = emptyList();
Iterator<?> iterator = list.iterator();
PeekingIterator<?> peekingIterator = peekingIterator(iterator);
assertThrows(NoSuchElementException.class, () -> peekingIterator.peek());
}
public void testPeekDoesntChangeIteration() {
List<?> list = Lists.newArrayList("A", "B", "C");
Iterator<?> iterator = list.iterator();
PeekingIterator<?> peekingIterator = peekingIterator(iterator);
assertEquals("Should be able to peek() at first element", "A", peekingIterator.peek());
assertEquals(
"Should be able to peek() first element multiple times", "A", peekingIterator.peek());
assertEquals(
"next() should still return first element after peeking", "A", peekingIterator.next());
assertEquals("Should be able to peek() at middle element", "B", peekingIterator.peek());
assertEquals(
"Should be able to peek() middle element multiple times", "B", peekingIterator.peek());
assertEquals(
"next() should still return middle element after peeking", "B", peekingIterator.next());
assertEquals("Should be able to peek() at last element", "C", peekingIterator.peek());
assertEquals(
"Should be able to peek() last element multiple times", "C", peekingIterator.peek());
assertEquals(
"next() should still return last element after peeking", "C", peekingIterator.next());
assertThrows(NoSuchElementException.class, () -> peekingIterator.peek());
assertThrows(NoSuchElementException.class, () -> peekingIterator.peek());
assertThrows(NoSuchElementException.class, () -> peekingIterator.next());
}
public void testCantRemoveAfterPeek() {
List<String> list = Lists.newArrayList("A", "B", "C");
Iterator<String> iterator = list.iterator();
PeekingIterator<?> peekingIterator = peekingIterator(iterator);
assertEquals("A", peekingIterator.next());
assertEquals("B", peekingIterator.peek());
/* Should complain on attempt to remove() after peek(). */
assertThrows(IllegalStateException.class, () -> peekingIterator.remove());
assertEquals(
"After remove() throws exception, peek should still be ok", "B", peekingIterator.peek());
/* Should recover to be able to remove() after next(). */
assertEquals("B", peekingIterator.next());
peekingIterator.remove();
assertEquals("Should have removed an element", 2, list.size());
assertFalse("Second element should be gone", list.contains("B"));
}
static class ThrowsAtEndException extends RuntimeException {
/* nothing */
}
/**
* This Iterator claims to have more elements than the underlying iterable, but when you try to
* fetch the extra elements, it throws an unchecked exception.
*/
static class ThrowsAtEndIterator<E> implements Iterator<E> {
Iterator<E> iterator;
public ThrowsAtEndIterator(Iterable<E> iterable) {
this.iterator = iterable.iterator();
}
@Override
public boolean hasNext() {
return true; // pretend that you have more...
}
@Override
public E next() {
// ...but throw an unchecked exception when you ask for it.
if (!iterator.hasNext()) {
throw new ThrowsAtEndException();
}
return iterator.next();
}
@Override
public void remove() {
iterator.remove();
}
}
public void testPeekingIteratorDoesntAdvancePrematurely() throws Exception {
/*
* This test will catch problems where the underlying iterator
* throws a RuntimeException when retrieving the nth element.
*
* If the PeekingIterator is caching elements too aggressively,
* it may throw the exception on the (n-1)th element (oops!).
*/
/* Checks the case where the first element throws an exception. */
List<Integer> list = emptyList();
Iterator<Integer> iterator = peekingIterator(new ThrowsAtEndIterator<Integer>(list));
assertNextThrows(iterator);
/* Checks the case where a later element throws an exception. */
list = Lists.newArrayList(1, 2);
iterator = peekingIterator(new ThrowsAtEndIterator<Integer>(list));
assertTrue(iterator.hasNext());
iterator.next();
assertTrue(iterator.hasNext());
iterator.next();
assertNextThrows(iterator);
}
private void assertNextThrows(Iterator<?> iterator) {
try {
iterator.next();
fail();
} catch (ThrowsAtEndException expected) {
}
}
}
|
java
|
github
|
https://github.com/google/guava
|
android/guava-tests/test/com/google/common/collect/PeekingIteratorTest.java
|
#!/usr/bin/env python
import os
import errno
import sys
import random
import logging
import pprint
import argparse
import datetime
import time
#from __future__ import print_function
import imp
try:
imp.find_module('libcloud')
except ImportError:
sys.stderr.write("Python: Apache libcloud module not available, cannot proceed\n")
exit(-1)
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
from libcloud.compute.base import NodeSize, NodeImage
from libcloud.compute.types import NodeState
import libcloud.compute.types
NODESTATES = { NodeState.RUNNING : "RUNNING",
NodeState.REBOOTING : "REBOOTING",
NodeState.TERMINATED : "TERMINATED",
NodeState.STOPPED : "STOPPED",
NodeState.PENDING : "PENDING",
NodeState.UNKNOWN : "UNKNOWN" }
WORKER_USERDATA='''#!/bin/bash
export JAVA=/usr/local/bin/jdk1.7.0_51/bin
export SWIFT=/usr/local/bin/swift-trunk/bin
export PATH=$JAVA:$SWIFT:$PATH
export WORKER_LOGGING_LEVEL=TRACE
'''
NEW_LINE='''
'''
def aws_create_security_group(driver, configs):
""" Creates security group if not present.
Currently opens all tcp/udp ports in range 0, 65000 for all sources.
args : driver instance, configs dictionary
returns: Nothing
"""
group_name = configs["ec2securitygroup"]
current = driver.ex_list_security_groups()
if group_name not in current:
logging.debug("Security group absent, creating group" + str(configs["ec2securitygroup"]));
res = driver.ex_create_security_group(name=group_name,description="Open all ports")
if not driver.ex_authorize_security_group(group_name, 0, 65000, '0.0.0.0/0'):
sys.stderr.write("Authorizing ports for security group failed \n")
if not driver.ex_authorize_security_group(group_name, 0, 65000, '0.0.0.0/0', protocol='udp'):
sys.stderr.write("Authorizing ports for security group failed \n")
def check_keypair(driver, configs):
""" Checks if valid keypairs exist, if not creates them
args : driver instance, configs dictionary
returns: Nothing
"""
if "ec2keypairname" in configs and "ec2keypairfile" in configs:
all_pairs = driver.list_key_pairs()
for pair in all_pairs:
if pair.name == configs['ec2keypairname']:
return 0
key_pair = driver.create_key_pair(name=configs['ec2keypairname'])
f = open(configs['ec2keypairfile'], 'w')
f.write(str(key_pair.private_key))
f.close()
os.chmod(configs['ec2keypairfile'], 0600)
else:
sys.stderr.write("ec2keypairname and/or ec2keypairfile missing\n")
sys.stderr.write("Cannot proceed without ec2keypairname and ec2keypairfile\n")
exit(-1)
def _read_conf(config_file):
cfile = open(config_file, 'r').read()
config = {}
for line in cfile.split('\n'):
# Checking if empty line or comment
if line.startswith('#') or not line :
continue
temp = line.split('=')
config[temp[0]] = temp[1].strip('\r')
return config
def pretty_configs(configs):
printer = pprint.PrettyPrinter(indent=4)
printer.pprint(configs)
def read_configs(config_file):
config = _read_conf(config_file)
if 'ec2credentialsfile' in config :
config['ec2credentialsfile'] = os.path.expanduser(config['ec2credentialsfile'])
config['ec2credentialsfile'] = os.path.expandvars(config['ec2credentialsfile'])
cred_lines = open(config['ec2credentialsfile']).readlines()
cred_details = cred_lines[1].split(',')
credentials = { 'AWS_Username' : cred_details[0],
'AWSAccessKeyId' : cred_details[1],
'AWSSecretKey' : cred_details[2] }
config.update(credentials)
else:
print "ec2credentialsfile , Missing"
print "ERROR: Cannot proceed without access to ec2credentialsfile"
exit(-1)
return config
def node_status(driver, node_uuids):
nodes = driver.list_nodes()
for node in nodes:
if node.uuid in node_uuids :
if node.state == NodeState.RUNNING:
print node.uuid, "R"
elif node.state == NodeState.PENDING:
print node.uuid, "Q"
elif node.state == NodeState.TERMINATED:
print node.uuid, "C"
elif node.state == NodeState.STOPPED:
print node.uuid, "C"
elif node.state == NodeState.UNKNOWN:
print node.uuid, "Q" # This state could be wrong
else:
sys.stderr.write("Node state unknown/invalid " + str(NODESTATE[node.state]))
return -1
return 0
def node_start(driver, configs, WORKER_STRING):
cloudinit = ""
if "ec2cloudinit" in configs:
logging.info("ec2cloudinit from script : " + configs['ec2cloudinit'])
cloudinit = open(configs['ec2cloudinit'],'r').read()
userdata = WORKER_USERDATA + cloudinit + NEW_LINE + WORKER_STRING.lstrip('"').rstrip('"')
image = NodeImage(id=configs['ec2workerimage'], name=None, driver=driver)
sizes = driver.list_sizes()
size = [ s for s in sizes if s.id == configs['ec2workertype'] ]
if not size:
logging.info("ec2workerimage not legal/valid : %s", configs['ec2workertype'])
sys.stderr.write("ec2workerimage not legal/valid \n")
exit(-1);
node = driver.create_node(name="swift_worker",
image=image,
size=size[0],
ex_keyname=configs['ec2keypairname'],
ex_securitygroup=configs['ec2securitygroup'],
ex_userdata=userdata )
print 'jobid={0}'.format(node.uuid)
# node_names is a list
def node_terminate(driver, node_uuids):
nodes = driver.list_nodes()
deleted_flag = False
for node in nodes:
if node.uuid in node_uuids and node.state == NodeState.RUNNING :
logging.info("Terminating node : %s", str(node))
code = driver.destroy_node(node)
deleted_flag = True
return deleted_flag
def init_checks(driver, configs):
aws_create_security_group(driver, configs)
check_keypair(driver, configs)
def init(conf_file):
logging.debug("conf_file: " + str(conf_file))
configs = read_configs(conf_file)
# Setting defaults for optional configs
if 'ec2securitygroup' not in configs :
logging.info("ec2SecurityGroup not set: Defaulting to swift-security-group")
configs['ec2securitygroup'] = "swift-security-group"
if "ec2keypairname" not in configs:
logging.info("ec2KeypairName not set: Defaulting to swift-keypaid")
configs['ec2keypairname'] = "swift-keypair"
# If $HOME/.ssh is not accessible check_keypair will throw errors
if "ec2keypairfile" not in configs:
keyfile = os.path.expandvars("$HOME/.ssh/" + configs['ec2keypairname'] + ".pem")
logging.info("ec2keypairfile not set: Defaulting to " + keyfile)
configs['ec2keypairfile'] = keyfile
driver = get_driver(Provider.EC2_US_WEST_OREGON) # was EC2
ec2_driver = driver(configs['AWSAccessKeyId'], configs['AWSSecretKey'])
return configs,ec2_driver
if __name__ == '__main__' :
parser = argparse.ArgumentParser()
mu_group = parser.add_mutually_exclusive_group(required=True)
mu_group.add_argument("-s", "--submit", default=None , help='Takes a config file. Submits the CMD_STRING in the configs for execution on a cloud resource')
mu_group.add_argument("-t", "--status", default=None , help='gets the status of the CMD_STRING in the configs for execution on a cloud resource')
mu_group.add_argument("-c", "--cancel", default=None , help='cancels the jobs with jobids')
parser.add_argument("-v", "--verbose", help="set level of verbosity, DEBUG, INFO, WARN")
parser.add_argument("-l", "--logfile", help="set path to logfile, defaults to /dev/null")
parser.add_argument("-j", "--jobid", type=str, action='append')
args = parser.parse_args()
# Setting up logging
if args.logfile:
if not os.path.exists(os.path.dirname(args.logfile)):
os.makedirs(os.path.dirname(args.logfile))
logging.basicConfig(filename=args.logfile, level=logging.DEBUG)
else:
logging.basicConfig(filename='/dev/null', level=logging.DEBUG)
config_file = ( args.status or args.submit or args.cancel )
configs, driver = init(config_file)
if args.submit :
# Init checks confirm keypairs and security groups to allow for access to ports
init_checks(driver, configs)
node_start(driver, configs, configs['CMD_STRING'])
elif args.status :
node_status(driver, args.jobid )
elif args.cancel :
node_terminate(driver, args.jobid)
else:
sys.stderr.write("ERROR: Undefined args, cannot be handled")
sys.stderr.write("ERROR: Exiting...")
exit(-1)
exit(0)
|
unknown
|
codeparrot/codeparrot-clean
| ||
# Copyright (c) 2006-2008 Mitch Garnaat http://garnaat.org/
#
# 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, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing 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 MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR 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.
"""
Represents an EC2 Availability Zone
"""
from boto.ec2.ec2object import EC2Object
class MessageSet(list):
"""
A list object that contains messages associated with
an availability zone.
"""
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'message':
self.append(value)
else:
setattr(self, name, value)
class Zone(EC2Object):
"""
Represents an Availability Zone.
:ivar name: The name of the zone.
:ivar state: The current state of the zone.
:ivar region_name: The name of the region the zone is associated with.
:ivar messages: A list of messages related to the zone.
"""
def __init__(self, connection=None):
super(Zone, self).__init__(connection)
self.name = None
self.state = None
self.region_name = None
self.messages = None
def __repr__(self):
return 'Zone:%s' % self.name
def startElement(self, name, attrs, connection):
if name == 'messageSet':
self.messages = MessageSet()
return self.messages
return None
def endElement(self, name, value, connection):
if name == 'zoneName':
self.name = value
elif name == 'zoneState':
self.state = value
elif name == 'regionName':
self.region_name = value
else:
setattr(self, name, value)
|
unknown
|
codeparrot/codeparrot-clean
| ||
<!--Copyright 2026 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
-->
*This model was released on 2024-04-05 and added to Hugging Face Transformers on 2026-01-12.*
<div style="float: right;">
<div class="flex flex-wrap space-x-1">
<img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white">
</div>
</div>
# LW-DETR
[LW-DETR](https://huggingface.co/papers/2407.17140) proposes a light-weight Detection Transformer (DETR) architecture designed to compete with and surpass the dominant YOLO series for real-time object detection. It achieves a new state-of-the-art balance between speed (latency) and accuracy (mAP) by combining recent transformer advances with efficient design choices.
The LW-DETR architecture is characterized by its simple and efficient structure: a plain ViT Encoder, a Projector, and a shallow DETR Decoder.
It enhances the DETR architecture for efficiency and speed using the following core modifications:
1. Efficient ViT Encoder: Uses a plain ViT with interleaved window/global attention and a window-major organization to drastically reduce attention complexity and latency.
2. Richer Input: Aggregates multi-level features from the encoder and uses a C2f Projector (YOLOv8) to pass two-scale features ($1/8$ and $1/32$).
3. Faster Decoder: Employs a shallow 3-layer DETR decoder with deformable cross-attention for lower latency and faster convergence.
4. Optimized Queries: Uses a mixed-query scheme combining learnable content queries and generated spatial queries.
You can find all the available LW DETR checkpoints under the [AnnaZhang](https://huggingface.co/AnnaZhang) organization.
The original code can be found [here](https://github.com/Atten4Vis/LW-DETR).
> [!TIP]
> This model was contributed by [stevenbucaille](https://huggingface.co/stevenbucaille).
>
> Click on the LW-DETR models in the right sidebar for more examples of how to apply LW-DETR to different object detection tasks.
The example below demonstrates how to perform object detection with the [`Pipeline`] and the [`AutoModel`] class.
<hfoptions id="usage">
<hfoption id="Pipeline">
```python
from transformers import pipeline
import torch
pipeline = pipeline(
"object-detection",
model="AnnaZhang/lwdetr_small_60e_coco",
dtype=torch.float16,
device_map=0
)
pipeline("http://images.cocodataset.org/val2017/000000039769.jpg")
```
</hfoption>
<hfoption id="AutoModel">
```python
from transformers import AutoImageProcessor, AutoModelForObjectDetection
from PIL import Image
import requests
import torch
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
image_processor = AutoImageProcessor.from_pretrained("AnnaZhang/lwdetr_small_60e_coco")
model = AutoModelForObjectDetection.from_pretrained("AnnaZhang/lwdetr_small_60e_coco")
# prepare image for the model
inputs = image_processor(images=image, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
results = image_processor.post_process_object_detection(outputs, target_sizes=torch.tensor([image.size[::-1]]), threshold=0.3)
for result in results:
for score, label_id, box in zip(result["scores"], result["labels"], result["boxes"]):
score, label = score.item(), label_id.item()
box = [round(i, 2) for i in box.tolist()]
print(f"{model.config.id2label[label]}: {score:.2f} {box}")
```
</hfoption>
</hfoptions>
## Resources
A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with LwDetr.
<PipelineTag pipeline="object-detection"/>
- Scripts for finetuning [`LwDetrForObjectDetection`] with [`Trainer`] or [Accelerate](https://huggingface.co/docs/accelerate/index) can be found [here](https://github.com/huggingface/transformers/tree/main/examples/pytorch/object-detection).
- See also: [Object detection task guide](../tasks/object_detection).
## LwDetrConfig
[[autodoc]] LwDetrConfig
## LwDetrViTConfig
[[autodoc]] LwDetrViTConfig
## LwDetrModel
[[autodoc]] LwDetrModel
- forward
## LwDetrForObjectDetection
[[autodoc]] LwDetrForObjectDetection
- forward
## LwDetrViTBackbone
[[autodoc]] LwDetrViTBackbone
- forward
|
unknown
|
github
|
https://github.com/huggingface/transformers
|
docs/source/en/model_doc/lw_detr.md
|
# -*- encoding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from datetime import datetime
from django.contrib.gis.geos import HAS_GEOS
from django.contrib.gis.tests.utils import no_mysql, no_spatialite
from django.contrib.gis.shortcuts import render_to_kmz
from django.contrib.gis.tests.utils import HAS_SPATIAL_DB
from django.db.models import Count, Min
from django.test import TestCase
from django.utils.unittest import skipUnless
if HAS_GEOS:
from .models import City, PennsylvaniaCity, State, Truth
@skipUnless(HAS_GEOS and HAS_SPATIAL_DB, "Geos and spatial db are required.")
class GeoRegressionTests(TestCase):
def test_update(self):
"Testing GeoQuerySet.update(). See #10411."
pnt = City.objects.get(name='Pueblo').point
bak = pnt.clone()
pnt.y += 0.005
pnt.x += 0.005
City.objects.filter(name='Pueblo').update(point=pnt)
self.assertEqual(pnt, City.objects.get(name='Pueblo').point)
City.objects.filter(name='Pueblo').update(point=bak)
self.assertEqual(bak, City.objects.get(name='Pueblo').point)
def test_kmz(self):
"Testing `render_to_kmz` with non-ASCII data. See #11624."
name = "Åland Islands"
places = [{'name' : name,
'description' : name,
'kml' : '<Point><coordinates>5.0,23.0</coordinates></Point>'
}]
kmz = render_to_kmz('gis/kml/placemarks.kml', {'places' : places})
@no_spatialite
@no_mysql
def test_extent(self):
"Testing `extent` on a table with a single point. See #11827."
pnt = City.objects.get(name='Pueblo').point
ref_ext = (pnt.x, pnt.y, pnt.x, pnt.y)
extent = City.objects.filter(name='Pueblo').extent()
for ref_val, val in zip(ref_ext, extent):
self.assertAlmostEqual(ref_val, val, 4)
def test_unicode_date(self):
"Testing dates are converted properly, even on SpatiaLite. See #16408."
founded = datetime(1857, 5, 23)
mansfield = PennsylvaniaCity.objects.create(name='Mansfield', county='Tioga', point='POINT(-77.071445 41.823881)',
founded=founded)
self.assertEqual(founded, PennsylvaniaCity.objects.datetimes('founded', 'day')[0])
self.assertEqual(founded, PennsylvaniaCity.objects.aggregate(Min('founded'))['founded__min'])
def test_empty_count(self):
"Testing that PostGISAdapter.__eq__ does check empty strings. See #13670."
# contrived example, but need a geo lookup paired with an id__in lookup
pueblo = City.objects.get(name='Pueblo')
state = State.objects.filter(poly__contains=pueblo.point)
cities_within_state = City.objects.filter(id__in=state)
# .count() should not throw TypeError in __eq__
self.assertEqual(cities_within_state.count(), 1)
def test_defer_or_only_with_annotate(self):
"Regression for #16409. Make sure defer() and only() work with annotate()"
self.assertIsInstance(list(City.objects.annotate(Count('point')).defer('name')), list)
self.assertIsInstance(list(City.objects.annotate(Count('point')).only('name')), list)
def test_boolean_conversion(self):
"Testing Boolean value conversion with the spatial backend, see #15169."
t1 = Truth.objects.create(val=True)
t2 = Truth.objects.create(val=False)
val1 = Truth.objects.get(pk=t1.pk).val
val2 = Truth.objects.get(pk=t2.pk).val
# verify types -- should't be 0/1
self.assertIsInstance(val1, bool)
self.assertIsInstance(val2, bool)
# verify values
self.assertEqual(val1, True)
self.assertEqual(val2, False)
|
unknown
|
codeparrot/codeparrot-clean
| ||
---
layout: step
title: Layouts
position: 4
---
Jekyll supports [Markdown](https://daringfireball.net/projects/markdown/syntax)
in addition to HTML when building pages. Markdown is a great choice for pages with a simple
content structure (just paragraphs, headings and images), as it's less verbose
than raw HTML.
Create a new Markdown file named `about.md` in your site's root folder.
You could copy the contents of `index` and modify it for the About page. However,
this creates duplicate code that has to be customized for each new page you add
to your site.
For example, adding a new stylesheet to your site would involve adding the link
to the stylesheet to the `<head>` of each page. For sites with many pages, this
is a waste of time.
## Creating a layout
Layouts are templates that can be used by any page in your site and wrap around page content.
They are stored in a directory called `_layouts`.
Create the `_layouts` directory in your site's root folder and create a new `default.html` file with the following content:
{% raw %}
```liquid
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>{{ page.title }}</title>
</head>
<body>
{{ content }}
</body>
</html>
```
{% endraw %}
This HTML is almost identical to `index.html` except there's
no front matter and the content of the page is replaced by a `content`
variable.
`content` is a special variable that returns the rendered
content of the page on which it's called.
## Use layouts
To make `index.html` use your new layout, set the `layout` variable in the front
matter. The file should look like this:
{% raw %}
```liquid
---
layout: default
title: Home
---
<h1>{{ "Hello World!" | downcase }}</h1>
```
{% endraw %}
When you reload the site, the output remains the same.
Since the layout wraps around the content on the page, you can call front matter like `page`
in the layout file. When you apply the layout to a page, it uses the front matter on that page.
## Build the About page
Add the following to `about.md` to use your new layout in the About page:
```markdown
---
layout: default
title: About
---
# About page
This page tells you a little bit about me.
```
Open <a href="http://localhost:4000/about.html" target="_blank" data-proofer-ignore>http://localhost:4000/about.html</a>
in your browser and view your new page.
Congratulations, you now have a two page website!
Next, you'll learn about navigating from page to page in your site.
|
unknown
|
github
|
https://github.com/jekyll/jekyll
|
docs/_docs/step-by-step/04-layouts.md
|
<!--Copyright 2020 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.
-->
*This model was released on 2020-04-06 and added to Hugging Face Transformers on 2020-11-16.*
<div style="float: right;">
<div class="flex flex-wrap space-x-1">
<img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white">
</div>
</div>
# MobileBERT
[MobileBERT](https://huggingface.co/papers/2004.02984) is a lightweight and efficient variant of BERT, specifically designed for resource-limited devices such as mobile phones. It retains BERT's architecture but significantly reduces model size and inference latency while maintaining strong performance on NLP tasks. MobileBERT achieves this through a bottleneck structure and carefully balanced self-attention and feedforward networks. The model is trained by knowledge transfer from a large BERT model with an inverted bottleneck structure.
You can find the original MobileBERT checkpoint under the [Google](https://huggingface.co/google/mobilebert-uncased) organization.
> [!TIP]
> Click on the MobileBERT models in the right sidebar for more examples of how to apply MobileBERT to different language tasks.
The example below demonstrates how to predict the `[MASK]` token with [`Pipeline`], [`AutoModel`], and from the command line.
<hfoptions id="usage">
<hfoption id="Pipeline">
```py
import torch
from transformers import pipeline
pipeline = pipeline(
task="fill-mask",
model="google/mobilebert-uncased",
dtype=torch.float16,
device=0
)
pipeline("The capital of France is [MASK].")
```
</hfoption>
<hfoption id="AutoModel">
```py
import torch
from transformers import AutoModelForMaskedLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(
"google/mobilebert-uncased",
)
model = AutoModelForMaskedLM.from_pretrained(
"google/mobilebert-uncased",
dtype=torch.float16,
device_map="auto",
)
inputs = tokenizer("The capital of France is [MASK].", return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model(**inputs)
predictions = outputs.logits
masked_index = torch.where(inputs['input_ids'] == tokenizer.mask_token_id)[1]
predicted_token_id = predictions[0, masked_index].argmax(dim=-1)
predicted_token = tokenizer.decode(predicted_token_id)
print(f"The predicted token is: {predicted_token}")
```
</hfoption>
<hfoption id="transformers CLI">
```bash
echo -e "The capital of France is [MASK]." | transformers run --task fill-mask --model google/mobilebert-uncased --device 0
```
</hfoption>
</hfoptions>
## Notes
- Inputs should be padded on the right because BERT uses absolute position embeddings.
## MobileBertConfig
[[autodoc]] MobileBertConfig
## MobileBertTokenizer
[[autodoc]] MobileBertTokenizer
## MobileBertTokenizerFast
[[autodoc]] MobileBertTokenizerFast
## MobileBert specific outputs
[[autodoc]] models.mobilebert.modeling_mobilebert.MobileBertForPreTrainingOutput
## MobileBertModel
[[autodoc]] MobileBertModel
- forward
## MobileBertForPreTraining
[[autodoc]] MobileBertForPreTraining
- forward
## MobileBertForMaskedLM
[[autodoc]] MobileBertForMaskedLM
- forward
## MobileBertForNextSentencePrediction
[[autodoc]] MobileBertForNextSentencePrediction
- forward
## MobileBertForSequenceClassification
[[autodoc]] MobileBertForSequenceClassification
- forward
## MobileBertForMultipleChoice
[[autodoc]] MobileBertForMultipleChoice
- forward
## MobileBertForTokenClassification
[[autodoc]] MobileBertForTokenClassification
- forward
## MobileBertForQuestionAnswering
[[autodoc]] MobileBertForQuestionAnswering
- forward
|
unknown
|
github
|
https://github.com/huggingface/transformers
|
docs/source/en/model_doc/mobilebert.md
|
/*
* Copyright 2014-2025 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.webrtc
import WebRTC.RTCConfiguration
import WebRTC.RTCIceServer
import WebRTC.RTCMediaConstraints
import WebRTC.RTCPeerConnectionFactory
import WebRTC.RTCSdpSemantics
import io.ktor.client.webrtc.media.IosMediaDevices
import kotlinx.cinterop.ExperimentalForeignApi
/**
* Configuration for the iOS WebRTC engine that extends the base WebRTC configuration.
*
* [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.client.webrtc.IosWebRtcEngineConfig)
*
* @property rtcFactory Optional custom [RTCPeerConnectionFactory] for creating peer connections.
* If not provided, the factory from the [MediaTrackFactory] will be used.
*/
public class IosWebRtcEngineConfig : WebRtcConfig() {
@OptIn(ExperimentalForeignApi::class)
public var rtcFactory: RTCPeerConnectionFactory? = null
}
/**
* iOS-specific WebRTC engine implementation that handles peer connection creation and management.
*
* This engine provides iOS-specific WebRTC functionality by wrapping the native iOS WebRTC framework
* and implementing the common WebRTC engine interface.
*
* [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.client.webrtc.IosWebRtcEngine)
*
* @param config The iOS-specific WebRTC engine configuration
* @param mediaTrackFactory Factory for creating media tracks, defaults to IosMediaDevices if not specified in config
*/
@OptIn(ExperimentalForeignApi::class)
public class IosWebRtcEngine(
override val config: IosWebRtcEngineConfig,
private val mediaTrackFactory: MediaTrackFactory = config.mediaTrackFactory ?: IosMediaDevices()
) : WebRtcEngineBase("ios-webrtc", config), MediaTrackFactory by mediaTrackFactory {
private val localFactory: RTCPeerConnectionFactory
get() = config.rtcFactory
?: (mediaTrackFactory as? IosMediaDevices)?.peerConnectionFactory
?: error("Please specify custom rtcFactory for custom MediaTrackFactory")
private fun WebRtc.IceServer.toIos(): RTCIceServer {
return RTCIceServer(urls, username, credential)
}
override suspend fun createPeerConnection(config: WebRtcConnectionConfig): WebRtcPeerConnection {
val iceServers = config.iceServers.map { it.toIos() }
val rtcConfig = RTCConfiguration().also {
it.iceServers = iceServers
it.bundlePolicy = config.bundlePolicy.toIos()
it.rtcpMuxPolicy = config.rtcpMuxPolicy.toIos()
it.iceCandidatePoolSize = config.iceCandidatePoolSize
it.iceTransportPolicy = config.iceTransportPolicy.toIos()
it.sdpSemantics = RTCSdpSemantics.RTCSdpSemanticsUnifiedPlan
}
val coroutineContext = createConnectionContext(config.exceptionHandler)
return IosWebRtcConnection(coroutineContext, config) { delegate ->
localFactory.peerConnectionWithConfiguration(
constraints = RTCMediaConstraints(),
configuration = rtcConfig,
delegate = delegate,
)
}
}
}
/**
* Factory object for creating iOS WebRTC engine instances.
*
* [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.client.webrtc.IosWebRtc)
*/
public object IosWebRtc : WebRtcClientEngineFactory<IosWebRtcEngineConfig> {
override fun create(block: IosWebRtcEngineConfig.() -> Unit): WebRtcEngine =
IosWebRtcEngine(IosWebRtcEngineConfig().apply(block))
}
|
kotlin
|
github
|
https://github.com/ktorio/ktor
|
ktor-client/ktor-client-webrtc/ios/src/io/ktor/client/webrtc/Engine.kt
|
import sys
from ctypes.util import find_library
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db.backends.sqlite3.base import (Database,
DatabaseWrapper as SQLiteDatabaseWrapper, SQLiteCursorWrapper)
from django.contrib.gis.db.backends.spatialite.client import SpatiaLiteClient
from django.contrib.gis.db.backends.spatialite.creation import SpatiaLiteCreation
from django.contrib.gis.db.backends.spatialite.introspection import SpatiaLiteIntrospection
from django.contrib.gis.db.backends.spatialite.operations import SpatiaLiteOperations
from django.utils import six
class DatabaseWrapper(SQLiteDatabaseWrapper):
def __init__(self, *args, **kwargs):
# Before we get too far, make sure pysqlite 2.5+ is installed.
if Database.version_info < (2, 5, 0):
raise ImproperlyConfigured('Only versions of pysqlite 2.5+ are '
'compatible with SpatiaLite and GeoDjango.')
# Trying to find the location of the SpatiaLite library.
# Here we are figuring out the path to the SpatiaLite library
# (`libspatialite`). If it's not in the system library path (e.g., it
# cannot be found by `ctypes.util.find_library`), then it may be set
# manually in the settings via the `SPATIALITE_LIBRARY_PATH` setting.
self.spatialite_lib = getattr(settings, 'SPATIALITE_LIBRARY_PATH',
find_library('spatialite'))
if not self.spatialite_lib:
raise ImproperlyConfigured('Unable to locate the SpatiaLite library. '
'Make sure it is in your library path, or set '
'SPATIALITE_LIBRARY_PATH in your settings.'
)
super(DatabaseWrapper, self).__init__(*args, **kwargs)
self.ops = SpatiaLiteOperations(self)
self.client = SpatiaLiteClient(self)
self.creation = SpatiaLiteCreation(self)
self.introspection = SpatiaLiteIntrospection(self)
def get_new_connection(self, conn_params):
conn = super(DatabaseWrapper, self).get_new_connection(conn_params)
# Enabling extension loading on the SQLite connection.
try:
conn.enable_load_extension(True)
except AttributeError:
raise ImproperlyConfigured(
'The pysqlite library does not support C extension loading. '
'Both SQLite and pysqlite must be configured to allow '
'the loading of extensions to use SpatiaLite.')
# Loading the SpatiaLite library extension on the connection, and returning
# the created cursor.
cur = conn.cursor(factory=SQLiteCursorWrapper)
try:
cur.execute("SELECT load_extension(%s)", (self.spatialite_lib,))
except Exception as msg:
new_msg = (
'Unable to load the SpatiaLite library extension '
'"%s" because: %s') % (self.spatialite_lib, msg)
six.reraise(ImproperlyConfigured, ImproperlyConfigured(new_msg), sys.exc_info()[2])
cur.close()
return conn
|
unknown
|
codeparrot/codeparrot-clean
| ||
#
# Copyright 2014 Google Inc. All rights reserved.
#
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#
"""Performs requests to the Google Maps Distance Matrix API."""
from googlemaps import convert
from googlemaps.convert import as_list
def distance_matrix(client, origins, destinations,
mode=None, language=None, avoid=None, units=None,
departure_time=None, arrival_time=None, transit_mode=None,
transit_routing_preference=None, traffic_model=None):
""" Gets travel distance and time for a matrix of origins and destinations.
:param origins: One or more locations and/or latitude/longitude values,
from which to calculate distance and time. If you pass an address as
a string, the service will geocode the string and convert it to a
latitude/longitude coordinate to calculate directions.
:type origins: a single location, or a list of locations, where a
location is a string, dict, list, or tuple
:param destinations: One or more addresses and/or lat/lng values, to
which to calculate distance and time. If you pass an address as a
string, the service will geocode the string and convert it to a
latitude/longitude coordinate to calculate directions.
:type destinations: a single location, or a list of locations, where a
location is a string, dict, list, or tuple
:param mode: Specifies the mode of transport to use when calculating
directions. Valid values are "driving", "walking", "transit" or
"bicycling".
:type mode: string
:param language: The language in which to return results.
:type language: string
:param avoid: Indicates that the calculated route(s) should avoid the
indicated features. Valid values are "tolls", "highways" or "ferries".
:type avoid: string
:param units: Specifies the unit system to use when displaying results.
Valid values are "metric" or "imperial".
:type units: string
:param departure_time: Specifies the desired time of departure.
:type departure_time: int or datetime.datetime
:param arrival_time: Specifies the desired time of arrival for transit
directions. Note: you can't specify both departure_time and
arrival_time.
:type arrival_time: int or datetime.datetime
:param transit_mode: Specifies one or more preferred modes of transit.
This parameter may only be specified for requests where the mode is
transit. Valid values are "bus", "subway", "train", "tram", "rail".
"rail" is equivalent to ["train", "tram", "subway"].
:type transit_mode: string or list of strings
:param transit_routing_preference: Specifies preferences for transit
requests. Valid values are "less_walking" or "fewer_transfers".
:type transit_routing_preference: string
:param traffic_model: Specifies the predictive travel time model to use.
Valid values are "best_guess" or "optimistic" or "pessimistic".
The traffic_model parameter may only be specified for requests where
the travel mode is driving, and where the request includes a
departure_time.
:rtype: matrix of distances. Results are returned in rows, each row
containing one origin paired with each destination.
"""
params = {
"origins": convert.location_list(origins),
"destinations": convert.location_list(destinations)
}
if mode:
# NOTE(broady): the mode parameter is not validated by the Maps API
# server. Check here to prevent silent failures.
if mode not in ["driving", "walking", "bicycling", "transit"]:
raise ValueError("Invalid travel mode.")
params["mode"] = mode
if language:
params["language"] = language
if avoid:
if avoid not in ["tolls", "highways", "ferries"]:
raise ValueError("Invalid route restriction.")
params["avoid"] = avoid
if units:
params["units"] = units
if departure_time:
params["departure_time"] = convert.time(departure_time)
if arrival_time:
params["arrival_time"] = convert.time(arrival_time)
if departure_time and arrival_time:
raise ValueError("Should not specify both departure_time and"
"arrival_time.")
if transit_mode:
params["transit_mode"] = convert.join_list("|", transit_mode)
if transit_routing_preference:
params["transit_routing_preference"] = transit_routing_preference
if traffic_model:
params["traffic_model"] = traffic_model
return client._get("/maps/api/distancematrix/json", params)
|
unknown
|
codeparrot/codeparrot-clean
| ||
package daemon
import (
"context"
"fmt"
"os"
"runtime"
"strconv"
"strings"
"time"
"github.com/containerd/containerd/v2/pkg/tracing"
"github.com/containerd/log"
"github.com/moby/moby/api/types/system"
"github.com/moby/moby/v2/daemon/command/debug"
"github.com/moby/moby/v2/daemon/config"
"github.com/moby/moby/v2/daemon/internal/filedescriptors"
"github.com/moby/moby/v2/daemon/internal/metrics"
"github.com/moby/moby/v2/daemon/internal/platform"
"github.com/moby/moby/v2/daemon/logger"
"github.com/moby/moby/v2/daemon/pkg/registry"
"github.com/moby/moby/v2/dockerversion"
"github.com/moby/moby/v2/pkg/meminfo"
"github.com/moby/moby/v2/pkg/parsers/kernel"
"github.com/moby/moby/v2/pkg/parsers/operatingsystem"
"github.com/moby/moby/v2/pkg/sysinfo"
"github.com/opencontainers/selinux/go-selinux"
)
func doWithTrace[T any](ctx context.Context, name string, f func() T) T {
_, span := tracing.StartSpan(ctx, name)
defer span.End()
return f()
}
// SystemInfo returns information about the host server the daemon is running on.
//
// The only error this should return is due to context cancellation/deadline.
// Anything else should be logged and ignored because this is looking up
// multiple things and is often used for debugging.
// The only case valid early return is when the caller doesn't want the result anymore (ie context cancelled).
func (daemon *Daemon) SystemInfo(ctx context.Context) (*system.Info, error) {
defer metrics.StartTimer(metrics.HostInfoFunctions.WithValues("system_info"))()
sysInfo := daemon.RawSysInfo()
cfg := daemon.config()
v := &system.Info{
ID: daemon.id,
Images: daemon.imageService.CountImages(ctx),
IPv4Forwarding: !sysInfo.IPv4ForwardingDisabled,
Name: hostName(ctx),
SystemTime: time.Now().Format(time.RFC3339Nano),
LoggingDriver: daemon.defaultLogConfig.Type,
KernelVersion: kernelVersion(ctx),
OperatingSystem: operatingSystem(ctx),
OSVersion: osVersion(ctx),
IndexServerAddress: registry.IndexServer,
OSType: runtime.GOOS,
Architecture: platform.Architecture(),
RegistryConfig: doWithTrace(ctx, "registry.ServiceConfig", daemon.registryService.ServiceConfig),
NCPU: doWithTrace(ctx, "runtime.NumCPU", runtime.NumCPU),
MemTotal: memInfo(ctx).MemTotal,
GenericResources: daemon.genericResources,
DockerRootDir: cfg.Root,
Labels: cfg.Labels,
ExperimentalBuild: cfg.Experimental,
ServerVersion: dockerversion.Version,
HTTPProxy: config.MaskCredentials(getConfigOrEnv(cfg.HTTPProxy, "HTTP_PROXY", "http_proxy")),
HTTPSProxy: config.MaskCredentials(getConfigOrEnv(cfg.HTTPSProxy, "HTTPS_PROXY", "https_proxy")),
NoProxy: getConfigOrEnv(cfg.NoProxy, "NO_PROXY", "no_proxy"),
LiveRestoreEnabled: cfg.LiveRestoreEnabled,
Isolation: daemon.defaultIsolation,
CDISpecDirs: promoteNil(cfg.CDISpecDirs),
NRI: daemon.nri.GetInfo(),
}
daemon.fillContainerStates(v)
daemon.fillDebugInfo(ctx, v)
daemon.fillContainerdInfo(v, &cfg.Config)
daemon.fillAPIInfo(v, &cfg.Config)
// Retrieve platform specific info
if err := daemon.fillPlatformInfo(ctx, v, sysInfo, cfg); err != nil {
return nil, err
}
daemon.fillDriverInfo(v)
daemon.fillPluginsInfo(ctx, v, &cfg.Config)
daemon.fillSecurityOptions(v, sysInfo, &cfg.Config)
daemon.fillLicense(v)
daemon.fillDefaultAddressPools(ctx, v, &cfg.Config)
daemon.fillFirewallInfo(v)
daemon.fillDiscoveredDevicesFromDrivers(ctx, v, &cfg.Config)
return v, nil
}
// SystemVersion returns version information about the daemon.
//
// The only error this should return is due to context cancellation/deadline.
// Anything else should be logged and ignored because this is looking up
// multiple things and is often used for debugging.
// The only case valid early return is when the caller doesn't want the result anymore (ie context cancelled).
func (daemon *Daemon) SystemVersion(ctx context.Context) (system.VersionResponse, error) {
defer metrics.StartTimer(metrics.HostInfoFunctions.WithValues("system_version"))()
kernelVer := kernelVersion(ctx)
cfg := daemon.config()
v := system.VersionResponse{
Components: []system.ComponentVersion{
{
Name: "Engine",
Version: dockerversion.Version,
Details: map[string]string{
"GitCommit": dockerversion.GitCommit,
"ApiVersion": config.MaxAPIVersion,
"MinAPIVersion": cfg.MinAPIVersion,
"GoVersion": runtime.Version(),
"Os": runtime.GOOS,
"Arch": runtime.GOARCH,
"BuildTime": dockerversion.BuildTime,
"KernelVersion": kernelVer,
"Experimental": strconv.FormatBool(cfg.Experimental),
},
},
},
// Populate deprecated fields for older clients
Version: dockerversion.Version,
GitCommit: dockerversion.GitCommit,
APIVersion: config.MaxAPIVersion,
MinAPIVersion: cfg.MinAPIVersion,
GoVersion: runtime.Version(),
Os: runtime.GOOS,
Arch: runtime.GOARCH,
BuildTime: dockerversion.BuildTime,
KernelVersion: kernelVer,
Experimental: cfg.Experimental,
}
v.Platform.Name = dockerversion.PlatformName
if err := daemon.fillPlatformVersion(ctx, &v, cfg); err != nil {
return v, err
}
return v, nil
}
func (daemon *Daemon) fillDriverInfo(v *system.Info) {
v.Driver = daemon.imageService.StorageDriver()
v.DriverStatus = daemon.imageService.LayerStoreStatus()
const warnMsg = `
WARNING: The %s storage-driver is deprecated, and will be removed in a future release.
Refer to the documentation for more information: https://docs.docker.com/go/storage-driver/`
switch v.Driver {
case "overlay":
v.Warnings = append(v.Warnings, fmt.Sprintf(warnMsg, v.Driver))
}
fillDriverWarnings(v)
}
func (daemon *Daemon) fillPluginsInfo(ctx context.Context, v *system.Info, cfg *config.Config) {
v.Plugins = system.PluginsInfo{
Volume: daemon.volumes.GetDriverList(),
Network: daemon.GetNetworkDriverList(ctx),
// The authorization plugins are returned in the order they are
// used as they constitute a request/response modification chain.
Authorization: cfg.AuthorizationPlugins,
Log: logger.ListDrivers(),
}
}
// fillSecurityOptions fills the [system.Info.SecurityOptions] field based
// on the daemon configuration.
//
// TODO(thaJeztah): consider making [system.Info.SecurityOptions] a structured response as originally intended in https://github.com/moby/moby/pull/26276
func (daemon *Daemon) fillSecurityOptions(v *system.Info, sysInfo *sysinfo.SysInfo, cfg *config.Config) {
var securityOptions []string
if sysInfo.AppArmor {
securityOptions = append(securityOptions, "name=apparmor")
}
if sysInfo.Seccomp && supportsSeccomp {
if daemon.seccompProfilePath != config.SeccompProfileDefault {
v.Warnings = append(v.Warnings, "WARNING: daemon is not using the default seccomp profile")
}
securityOptions = append(securityOptions, "name=seccomp,profile="+daemon.seccompProfilePath)
}
if selinux.GetEnabled() {
securityOptions = append(securityOptions, "name=selinux")
}
if uid, gid := daemon.idMapping.RootPair(); uid != 0 || gid != 0 {
securityOptions = append(securityOptions, "name=userns")
}
if Rootless(cfg) {
securityOptions = append(securityOptions, "name=rootless")
}
if cgroupNamespacesEnabled(sysInfo, cfg) {
securityOptions = append(securityOptions, "name=cgroupns")
}
if noNewPrivileges(cfg) {
securityOptions = append(securityOptions, "name=no-new-privileges")
}
v.SecurityOptions = securityOptions
}
func (daemon *Daemon) fillContainerStates(v *system.Info) {
cRunning, cPaused, cStopped := metrics.StateCtr.Get()
v.Containers = cRunning + cPaused + cStopped
v.ContainersPaused = cPaused
v.ContainersRunning = cRunning
v.ContainersStopped = cStopped
}
// fillDebugInfo sets the current debugging state of the daemon, and additional
// debugging information, such as the number of Go-routines, and file descriptors.
//
// Note that this currently always collects the information, but the CLI only
// prints it if the daemon has debug enabled. We should consider to either make
// this information optional (cli to request "with debugging information"), or
// only collect it if the daemon has debug enabled. For the CLI code, see
// https://github.com/docker/cli/blob/v20.10.12/cli/command/system/info.go#L239-L244
func (daemon *Daemon) fillDebugInfo(ctx context.Context, v *system.Info) {
v.Debug = debug.IsEnabled()
v.NFd = filedescriptors.GetTotalUsedFds(ctx)
v.NGoroutines = runtime.NumGoroutine()
v.NEventsListener = daemon.EventsService.SubscribersCount()
}
// fillContainerdInfo provides information about the containerd configuration
// for debugging purposes.
func (daemon *Daemon) fillContainerdInfo(v *system.Info, cfg *config.Config) {
if cfg.ContainerdAddr == "" {
return
}
v.Containerd = &system.ContainerdInfo{
Address: cfg.ContainerdAddr,
Namespaces: system.ContainerdNamespaces{
Containers: cfg.ContainerdNamespace,
Plugins: cfg.ContainerdPluginNamespace,
},
}
}
func (daemon *Daemon) fillAPIInfo(v *system.Info, cfg *config.Config) {
const warn string = `
Access to the remote API is equivalent to root access on the host. Refer
to the 'Docker daemon attack surface' section in the documentation for
more information: https://docs.docker.com/go/attack-surface/`
for _, host := range cfg.Hosts {
// cnf.Hosts is normalized during startup, so should always have a scheme/proto
proto, addr, _ := strings.Cut(host, "://")
if proto != "tcp" {
continue
}
const removal = "In future versions this will be a hard failure preventing the daemon from starting! Learn more at: https://docs.docker.com/go/api-security/"
if cfg.TLS == nil || !*cfg.TLS {
v.Warnings = append(v.Warnings, fmt.Sprintf("[DEPRECATION NOTICE]: API is accessible on http://%s without encryption.%s\n%s", addr, warn, removal))
continue
}
if cfg.TLSVerify == nil || !*cfg.TLSVerify {
v.Warnings = append(v.Warnings, fmt.Sprintf("[DEPRECATION NOTICE]: API is accessible on https://%s without TLS client verification.%s\n%s", addr, warn, removal))
continue
}
}
}
func (daemon *Daemon) fillDefaultAddressPools(ctx context.Context, v *system.Info, cfg *config.Config) {
_, span := tracing.StartSpan(ctx, "fillDefaultAddressPools")
defer span.End()
for _, pool := range cfg.DefaultAddressPools.Value() {
v.DefaultAddressPools = append(v.DefaultAddressPools, system.NetworkAddressPool{
Base: pool.Base,
Size: pool.Size,
})
}
}
func (daemon *Daemon) fillFirewallInfo(v *system.Info) {
if daemon.netController == nil {
return
}
v.FirewallBackend = daemon.netController.FirewallBackend()
}
func hostName(ctx context.Context) string {
ctx, span := tracing.StartSpan(ctx, "hostName")
defer span.End()
hn, err := os.Hostname()
if err != nil {
log.G(ctx).WithError(err).Warn("Could not get hostname")
return ""
}
return hn
}
func kernelVersion(ctx context.Context) string {
ctx, span := tracing.StartSpan(ctx, "kernelVersion")
defer span.End()
var ver string
if kv, err := kernel.GetKernelVersion(); err != nil {
log.G(ctx).WithError(err).Warn("Could not get kernel version")
} else {
ver = kv.String()
}
return ver
}
func memInfo(ctx context.Context) *meminfo.Memory {
ctx, span := tracing.StartSpan(ctx, "memInfo")
defer span.End()
mi, err := meminfo.Read()
if err != nil {
log.G(ctx).WithError(err).Error("Could not read system memory info")
return &meminfo.Memory{}
}
return mi
}
func operatingSystem(ctx context.Context) (operatingSystem string) {
ctx, span := tracing.StartSpan(ctx, "operatingSystem")
defer span.End()
defer metrics.StartTimer(metrics.HostInfoFunctions.WithValues("operating_system"))()
if s, err := operatingsystem.GetOperatingSystem(); err != nil {
log.G(ctx).WithError(err).Warn("Could not get operating system name")
} else {
operatingSystem = s
}
if inContainer, err := operatingsystem.IsContainerized(); err != nil {
log.G(ctx).WithError(err).Error("Could not determine if daemon is containerized")
operatingSystem += " (error determining if containerized)"
} else if inContainer {
operatingSystem += " (containerized)"
}
return operatingSystem
}
func osVersion(ctx context.Context) (version string) {
ctx, span := tracing.StartSpan(ctx, "osVersion")
defer span.End()
defer metrics.StartTimer(metrics.HostInfoFunctions.WithValues("os_version"))()
version, err := operatingsystem.GetOperatingSystemVersion()
if err != nil {
log.G(ctx).WithError(err).Warn("Could not get operating system version")
return ""
}
return version
}
func getEnvAny(names ...string) string {
for _, n := range names {
if val := os.Getenv(n); val != "" {
return val
}
}
return ""
}
func getConfigOrEnv(config string, env ...string) string {
if config != "" {
return config
}
return getEnvAny(env...)
}
// promoteNil converts a nil slice to an empty slice of that type.
// A non-nil slice is returned as is.
func promoteNil[S ~[]E, E any](s S) S {
if s == nil {
return S{}
}
return s
}
// fillDiscoveredDevicesFromDrivers iterates over registered device drivers
// and calls their ListDevices method (if available) to populate system info.
func (daemon *Daemon) fillDiscoveredDevicesFromDrivers(ctx context.Context, v *system.Info, cfg *config.Config) {
ctx, span := tracing.StartSpan(ctx, "daemon.fillDiscoveredDevicesFromDrivers")
defer span.End()
// Make sure v.DiscoveredDevices is initialized to an empty slice instead of nil.
// This ensures that the JSON output is always a valid array, even if no devices are discovered.
v.DiscoveredDevices = []system.DeviceInfo{}
for driverName, driver := range deviceDrivers {
if driver.ListDevices == nil {
log.G(ctx).WithField("driver", driverName).Trace("Device driver does not implement ListDevices method.")
continue
}
ls, err := driver.ListDevices(ctx, cfg)
if err != nil {
log.G(ctx).WithFields(log.Fields{
"driver": driverName,
"error": err,
}).Warn("Failed to list devices for driver")
v.Warnings = append(v.Warnings, fmt.Sprintf("Failed to list devices from driver '%s': %v", driverName, err))
continue
}
if len(ls.Warnings) > 0 {
v.Warnings = append(v.Warnings, ls.Warnings...)
}
for _, device := range ls.Devices {
device.Source = driverName
v.DiscoveredDevices = append(v.DiscoveredDevices, device)
}
}
}
|
go
|
github
|
https://github.com/moby/moby
|
daemon/info.go
|
#!/bin/sh
test_description='test <branch>@{upstream} syntax'
GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main
export GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME
. ./test-lib.sh
test_expect_success 'setup' '
test_commit 1 &&
git checkout -b side &&
test_commit 2 &&
git checkout main &&
git clone . clone &&
test_commit 3 &&
(cd clone &&
test_commit 4 &&
git branch --track my-side origin/side &&
git branch --track local-main main &&
git branch --track fun@ny origin/side &&
git branch --track @funny origin/side &&
git branch --track funny@ origin/side &&
git remote add -t main main-only .. &&
git fetch main-only &&
git branch bad-upstream &&
git config branch.bad-upstream.remote main-only &&
git config branch.bad-upstream.merge refs/heads/side
)
'
commit_subject () {
(cd clone &&
git show -s --pretty=tformat:%s "$@")
}
error_message () {
(cd clone &&
test_must_fail git rev-parse --verify "$@" 2>../error)
}
test_expect_success '@{upstream} resolves to correct full name' '
echo refs/remotes/origin/main >expect &&
git -C clone rev-parse --symbolic-full-name @{upstream} >actual &&
test_cmp expect actual &&
git -C clone rev-parse --symbolic-full-name @{UPSTREAM} >actual &&
test_cmp expect actual &&
git -C clone rev-parse --symbolic-full-name @{UpSTReam} >actual &&
test_cmp expect actual
'
test_expect_success '@{u} resolves to correct full name' '
echo refs/remotes/origin/main >expect &&
git -C clone rev-parse --symbolic-full-name @{u} >actual &&
test_cmp expect actual &&
git -C clone rev-parse --symbolic-full-name @{U} >actual &&
test_cmp expect actual
'
test_expect_success 'my-side@{upstream} resolves to correct full name' '
echo refs/remotes/origin/side >expect &&
git -C clone rev-parse --symbolic-full-name my-side@{u} >actual &&
test_cmp expect actual
'
test_expect_success 'upstream of branch with @ in middle' '
git -C clone rev-parse --symbolic-full-name fun@ny@{u} >actual &&
echo refs/remotes/origin/side >expect &&
test_cmp expect actual &&
git -C clone rev-parse --symbolic-full-name fun@ny@{U} >actual &&
test_cmp expect actual
'
test_expect_success 'upstream of branch with @ at start' '
git -C clone rev-parse --symbolic-full-name @funny@{u} >actual &&
echo refs/remotes/origin/side >expect &&
test_cmp expect actual
'
test_expect_success 'upstream of branch with @ at end' '
git -C clone rev-parse --symbolic-full-name funny@@{u} >actual &&
echo refs/remotes/origin/side >expect &&
test_cmp expect actual
'
test_expect_success 'refs/heads/my-side@{upstream} does not resolve to my-side{upstream}' '
test_must_fail git -C clone rev-parse --symbolic-full-name refs/heads/my-side@{upstream}
'
test_expect_success 'my-side@{u} resolves to correct commit' '
git checkout side &&
test_commit 5 &&
(cd clone && git fetch) &&
echo 2 >expect &&
commit_subject my-side >actual &&
test_cmp expect actual &&
echo 5 >expect &&
commit_subject my-side@{u} >actual &&
test_cmp expect actual
'
test_expect_success 'not-tracking@{u} fails' '
test_must_fail git -C clone rev-parse --symbolic-full-name non-tracking@{u} &&
(cd clone && git checkout --no-track -b non-tracking) &&
test_must_fail git -C clone rev-parse --symbolic-full-name non-tracking@{u}
'
test_expect_success '<branch>@{u}@{1} resolves correctly' '
test_commit 6 &&
(cd clone && git fetch) &&
echo 5 >expect &&
commit_subject my-side@{u}@{1} >actual &&
test_cmp expect actual &&
commit_subject my-side@{U}@{1} >actual &&
test_cmp expect actual
'
test_expect_success '@{u} without specifying branch fails on a detached HEAD' '
git checkout HEAD^0 &&
test_must_fail git rev-parse @{u} &&
test_must_fail git rev-parse @{U}
'
test_expect_success 'checkout -b new my-side@{u} forks from the same' '
(
cd clone &&
git checkout -b new my-side@{u} &&
git rev-parse --symbolic-full-name my-side@{u} >expect &&
git rev-parse --symbolic-full-name new@{u} >actual &&
test_cmp expect actual
)
'
test_expect_success 'merge my-side@{u} records the correct name' '
(
cd clone &&
git checkout main &&
test_might_fail git branch -D new &&
git branch -t new my-side@{u} &&
git merge -s ours new@{u} &&
git show -s --pretty=tformat:%s >actual &&
echo "Merge remote-tracking branch ${SQ}origin/side${SQ}" >expect &&
test_cmp expect actual
)
'
test_expect_success 'branch -d other@{u}' '
git checkout -t -b other main &&
git branch -d @{u} &&
git for-each-ref refs/heads/main >actual &&
test_must_be_empty actual
'
test_expect_success 'checkout other@{u}' '
git branch -f main HEAD &&
git checkout -t -b another main &&
git checkout @{u} &&
git symbolic-ref HEAD >actual &&
echo refs/heads/main >expect &&
test_cmp expect actual
'
test_expect_success 'branch@{u} works when tracking a local branch' '
echo refs/heads/main >expect &&
git -C clone rev-parse --symbolic-full-name local-main@{u} >actual &&
test_cmp expect actual
'
test_expect_success 'branch@{u} error message when no upstream' '
cat >expect <<-EOF &&
fatal: no upstream configured for branch ${SQ}non-tracking${SQ}
EOF
error_message non-tracking@{u} &&
test_cmp expect error
'
test_expect_success '@{u} error message when no upstream' '
cat >expect <<-EOF &&
fatal: no upstream configured for branch ${SQ}main${SQ}
EOF
test_must_fail git rev-parse --verify @{u} 2>actual &&
test_cmp expect actual
'
test_expect_success '@{u} silent error when no upstream' '
test_must_fail git rev-parse --verify --quiet @{u} 2>actual &&
test_must_be_empty actual
'
test_expect_success 'branch@{u} error message with misspelt branch' '
cat >expect <<-EOF &&
fatal: no such branch: ${SQ}no-such-branch${SQ}
EOF
error_message no-such-branch@{u} &&
test_cmp expect error
'
test_expect_success '@{u} error message when not on a branch' '
cat >expect <<-EOF &&
fatal: HEAD does not point to a branch
EOF
git checkout HEAD^0 &&
test_must_fail git rev-parse --verify @{u} 2>actual &&
test_cmp expect actual
'
test_expect_success 'branch@{u} error message if upstream branch not fetched' '
cat >expect <<-EOF &&
fatal: upstream branch ${SQ}refs/heads/side${SQ} not stored as a remote-tracking branch
EOF
error_message bad-upstream@{u} &&
test_cmp expect error
'
test_expect_success 'pull works when tracking a local branch' '
(
cd clone &&
git checkout local-main &&
git pull
)
'
# makes sense if the previous one succeeded
test_expect_success '@{u} works when tracking a local branch' '
echo refs/heads/main >expect &&
git -C clone rev-parse --symbolic-full-name @{u} >actual &&
test_cmp expect actual
'
test_expect_success 'log -g other@{u}' '
commit=$(git rev-parse HEAD) &&
cat >expect <<-EOF &&
commit $commit
Reflog: main@{0} (C O Mitter <committer@example.com>)
Reflog message: branch: Created from HEAD
Author: A U Thor <author@example.com>
Date: Thu Apr 7 15:15:13 2005 -0700
3
EOF
git log -1 -g other@{u} >actual &&
test_cmp expect actual
'
test_expect_success 'log -g other@{u}@{now}' '
commit=$(git rev-parse HEAD) &&
cat >expect <<-EOF &&
commit $commit
Reflog: main@{Thu Apr 7 15:17:13 2005 -0700} (C O Mitter <committer@example.com>)
Reflog message: branch: Created from HEAD
Author: A U Thor <author@example.com>
Date: Thu Apr 7 15:15:13 2005 -0700
3
EOF
git log -1 -g other@{u}@{now} >actual &&
test_cmp expect actual
'
test_expect_success '@{reflog}-parsing does not look beyond colon' '
echo content >@{yesterday} &&
git add @{yesterday} &&
git commit -m "funny reflog file" &&
git hash-object @{yesterday} >expect &&
git rev-parse HEAD:@{yesterday} >actual &&
test_cmp expect actual
'
test_expect_success '@{upstream}-parsing does not look beyond colon' '
echo content >@{upstream} &&
git add @{upstream} &&
git commit -m "funny upstream file" &&
git hash-object @{upstream} >expect &&
git rev-parse HEAD:@{upstream} >actual &&
test_cmp expect actual
'
test_done
|
unknown
|
github
|
https://github.com/git/git
|
t/t1507-rev-parse-upstream.sh
|
# -*- coding: utf-8 -*-
"""
Management commands for third_party_auth
"""
from django.core.management.base import BaseCommand, CommandError
import logging
from third_party_auth.models import SAMLConfiguration
from third_party_auth.tasks import fetch_saml_metadata
class Command(BaseCommand):
""" manage.py commands to manage SAML/Shibboleth SSO """
help = '''Configure/maintain/update SAML-based SSO'''
def handle(self, *args, **options):
if len(args) != 1:
raise CommandError("saml requires one argument: pull")
if not SAMLConfiguration.is_enabled():
raise CommandError("SAML support is disabled via SAMLConfiguration.")
subcommand = args[0]
if subcommand == "pull":
log_handler = logging.StreamHandler(self.stdout)
log_handler.setLevel(logging.DEBUG)
log = logging.getLogger('third_party_auth.tasks')
log.propagate = False
log.addHandler(log_handler)
num_changed, num_failed, num_total = fetch_saml_metadata()
self.stdout.write(
"\nDone. Fetched {num_total} total. {num_changed} were updated and {num_failed} failed.\n".format(
num_changed=num_changed, num_failed=num_failed, num_total=num_total
)
)
else:
raise CommandError("Unknown argment: {}".format(subcommand))
|
unknown
|
codeparrot/codeparrot-clean
| ||
def sort_sublists(list1):
list1.sort()
list1.sort(key=len)
return list1
|
unknown
|
mbpp
| ||
import asyncio
import os
import signal
import threading
import traceback
import sys
PYMPLER_ENABLED = False
if PYMPLER_ENABLED:
try:
import pympler
import pympler.muppy
import pympler.summary
import pympler.tracker
except ImportError:
pympler = None
else:
pympler = None
try:
import objgraph
except ImportError:
objgraph = None
from cloudbot import hook
from cloudbot.util import web
def get_name(thread_id):
current_thread = threading.current_thread()
if thread_id == current_thread._ident:
is_current = True
thread = current_thread
else:
is_current = False
thread = threading._active.get(thread_id)
if thread is not None:
if thread.name is not None:
name = thread.name
else:
name = "Unnamed thread"
else:
name = "Unknown thread"
name = "{} ({})".format(name, thread_id)
if is_current:
name += " - Current thread"
return name
def get_thread_dump():
code = []
threads = [(get_name(thread_id), traceback.extract_stack(stack))
for thread_id, stack in sys._current_frames().items()]
for thread_name, stack in threads:
code.append("# {}".format(thread_name))
for filename, line_num, name, line in stack:
code.append("{}:{} - {}".format(filename, line_num, name))
if line:
code.append(" {}".format(line.strip()))
code.append("") # new line
return web.paste("\n".join(code), ext='txt')
@asyncio.coroutine
@hook.command("threaddump", autohelp=False, permissions=["botcontrol"])
def threaddump_command():
return get_thread_dump()
@hook.command("objtypes", autohelp=False, permissions=["botcontrol"])
def show_types():
if objgraph is None:
return "objgraph not installed"
objgraph.show_most_common_types(limit=20)
return "Printed to console"
@hook.command("objgrowth", autohelp=False, permissions=["botcontrol"])
def show_growth():
if objgraph is None:
return "objgraph not installed"
objgraph.show_growth(limit=10)
return "Printed to console"
@hook.command("pymsummary", autohelp=False, permissions=["botcontrol"])
def pympler_summary():
if pympler is None:
return "pympler not installed / not enabled"
all_objects = pympler.muppy.get_objects()
summ = pympler.summary.summarize(all_objects)
pympler.summary.print_(summ)
return "Printed to console"
@hook.on_start()
def create_tracker():
if pympler is None:
return
global tr
tr = pympler.tracker.SummaryTracker()
@hook.command("pymdiff", autohelp=False, permissions=["botcontrol"])
def pympler_diff():
if pympler is None:
return "pympler not installed / not enabled"
tr.print_diff()
return "Printed to console"
# # Provide an easy way to get a threaddump, by using SIGUSR1 (only on POSIX systems)
if os.name == "posix":
def debug():
print(get_thread_dump())
signal.signal(signal.SIGUSR1, debug) # Register handler
|
unknown
|
codeparrot/codeparrot-clean
| ||
{
"name": "ssr",
"private": true,
"scripts": {
"dev": "cross-env NODE_ENV=development node server.js",
"build": "npm run build:client && npm run build:server",
"build:client": "vite build --outDir dist/client --ssrManifest",
"build:server": "vite build --ssr src/entry.server.tsx --outDir dist/server",
"start": "cross-env NODE_ENV=production node server.js",
"debug": "node --inspect-brk server.js"
},
"dependencies": {
"compression": "1.7.4",
"cross-env": "^7.0.3",
"express": "^4.18.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.15.0"
},
"devDependencies": {
"@rollup/plugin-replace": "^5.0.2",
"@types/node": "^18.11.18",
"@types/react": "^18.0.27",
"@types/react-dom": "^18.0.10",
"@vitejs/plugin-react": "^3.0.1",
"typescript": "^4.9.5",
"vite": "^4.0.4"
}
}
|
json
|
github
|
https://github.com/remix-run/react-router
|
examples/ssr/package.json
|
// Copyright 2016-2019 Cargo-Bundle developers <https://github.com/burtonageo/cargo-bundle>
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
bundle::{
settings::{Arch, Settings},
windows::{
sign::{should_sign, try_sign},
util::{
download_webview2_bootstrapper, download_webview2_offline_installer,
WIX_OUTPUT_FOLDER_NAME, WIX_UPDATER_OUTPUT_FOLDER_NAME,
},
},
},
error::Context,
utils::{
fs_utils::copy_file,
http_utils::{download_and_verify, extract_zip, HashAlgorithm},
CommandExt,
},
};
use handlebars::{html_escape, to_json, Handlebars};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeMap, HashMap, HashSet},
ffi::OsStr,
fs::{self, File},
io::Write,
path::{Path, PathBuf},
process::Command,
};
use tauri_utils::{config::WebviewInstallMode, display_path};
use uuid::Uuid;
// URLS for the WIX toolchain. Can be used for cross-platform compilation.
pub const WIX_URL: &str =
"https://github.com/wixtoolset/wix3/releases/download/wix3141rtm/wix314-binaries.zip";
pub const WIX_SHA256: &str = "6ac824e1642d6f7277d0ed7ea09411a508f6116ba6fae0aa5f2c7daa2ff43d31";
const WIX_REQUIRED_FILES: &[&str] = &[
"candle.exe",
"candle.exe.config",
"darice.cub",
"light.exe",
"light.exe.config",
"wconsole.dll",
"winterop.dll",
"wix.dll",
"WixUIExtension.dll",
"WixUtilExtension.dll",
];
/// Runs all of the commands to build the MSI installer.
/// Returns a vector of PathBuf that shows where the MSI was created.
pub fn bundle_project(settings: &Settings, updater: bool) -> crate::Result<Vec<PathBuf>> {
let tauri_tools_path = settings
.local_tools_directory()
.map(|d| d.join(".tauri"))
.unwrap_or_else(|| dirs::cache_dir().unwrap().join("tauri"));
let wix_path = tauri_tools_path.join("WixTools314");
if !wix_path.exists() {
get_and_extract_wix(&wix_path)?;
} else if WIX_REQUIRED_FILES
.iter()
.any(|p| !wix_path.join(p).exists())
{
log::warn!("WixTools directory is missing some files. Recreating it.");
std::fs::remove_dir_all(&wix_path)?;
get_and_extract_wix(&wix_path)?;
}
build_wix_app_installer(settings, &wix_path, updater)
}
// For Cross Platform Compilation.
// const VC_REDIST_X86_URL: &str =
// "https://download.visualstudio.microsoft.com/download/pr/c8edbb87-c7ec-4500-a461-71e8912d25e9/99ba493d660597490cbb8b3211d2cae4/vc_redist.x86.exe";
// const VC_REDIST_X86_SHA256: &str =
// "3a43e8a55a3f3e4b73d01872c16d47a19dd825756784f4580187309e7d1fcb74";
// const VC_REDIST_X64_URL: &str =
// "https://download.visualstudio.microsoft.com/download/pr/9e04d214-5a9d-4515-9960-3d71398d98c3/1e1e62ab57bbb4bf5199e8ce88f040be/vc_redist.x64.exe";
// const VC_REDIST_X64_SHA256: &str =
// "d6cd2445f68815fe02489fafe0127819e44851e26dfbe702612bc0d223cbbc2b";
// A v4 UUID that was generated specifically for tauri-bundler, to be used as a
// namespace for generating v5 UUIDs from bundle identifier strings.
const UUID_NAMESPACE: [u8; 16] = [
0xfd, 0x85, 0x95, 0xa8, 0x17, 0xa3, 0x47, 0x4e, 0xa6, 0x16, 0x76, 0x14, 0x8d, 0xfa, 0x0c, 0x7b,
];
/// Mapper between a resource directory name and its ResourceDirectory descriptor.
type ResourceMap = BTreeMap<String, ResourceDirectory>;
#[derive(Debug, Deserialize)]
struct LanguageMetadata {
#[serde(rename = "asciiCode")]
ascii_code: usize,
#[serde(rename = "langId")]
lang_id: usize,
}
/// A binary to bundle with WIX.
/// External binaries or additional project binaries are represented with this data structure.
/// This data structure is needed because WIX requires each path to have its own `id` and `guid`.
#[derive(Serialize)]
struct Binary {
/// the GUID to use on the WIX XML.
guid: String,
/// the id to use on the WIX XML.
id: String,
/// the binary path.
path: String,
}
/// A Resource file to bundle with WIX.
/// This data structure is needed because WIX requires each path to have its own `id` and `guid`.
#[derive(Serialize, Clone)]
struct ResourceFile {
/// the GUID to use on the WIX XML.
guid: String,
/// the id to use on the WIX XML.
id: String,
/// the file path.
path: PathBuf,
}
/// A resource directory to bundle with WIX.
/// This data structure is needed because WIX requires each path to have its own `id` and `guid`.
#[derive(Serialize)]
struct ResourceDirectory {
/// the directory path.
path: String,
/// the directory name of the described resource.
name: String,
/// the files of the described resource directory.
files: Vec<ResourceFile>,
/// the directories that are children of the described resource directory.
directories: Vec<ResourceDirectory>,
}
impl ResourceDirectory {
/// Adds a file to this directory descriptor.
fn add_file(&mut self, file: ResourceFile) {
self.files.push(file);
}
/// Generates the wix XML string to bundle this directory resources recursively
fn get_wix_data(self) -> crate::Result<(String, Vec<String>)> {
let mut files = String::from("");
let mut file_ids = Vec::new();
for file in self.files {
file_ids.push(file.id.clone());
files.push_str(
format!(
r#"<Component Id="{id}" Guid="{guid}" Win64="$(var.Win64)" KeyPath="yes"><File Id="PathFile_{id}" Source="{path}" /></Component>"#,
id = file.id,
guid = file.guid,
path = html_escape(&file.path.display().to_string())
).as_str()
);
}
let mut directories = String::from("");
for directory in self.directories {
let (wix_string, ids) = directory.get_wix_data()?;
for id in ids {
file_ids.push(id)
}
directories.push_str(wix_string.as_str());
}
let wix_string = if self.name.is_empty() {
format!("{files}{directories}")
} else {
format!(
r#"<Directory Id="I{id}" Name="{name}">{files}{directories}</Directory>"#,
id = Uuid::new_v4().as_simple(),
name = html_escape(&self.name),
files = files,
directories = directories,
)
};
Ok((wix_string, file_ids))
}
}
/// Copies the icon to the binary path, under the `resources` folder,
/// and returns the path to the file.
fn copy_icon(settings: &Settings, filename: &str, path: &Path) -> crate::Result<PathBuf> {
let base_dir = settings.project_out_directory();
let resource_dir = base_dir.join("resources");
fs::create_dir_all(&resource_dir)?;
let icon_target_path = resource_dir.join(filename);
let icon_path = std::env::current_dir()?.join(path);
copy_file(&icon_path, &icon_target_path)?;
Ok(icon_target_path)
}
/// The app installer output path.
fn app_installer_output_path(
settings: &Settings,
language: &str,
version: &str,
updater: bool,
) -> crate::Result<PathBuf> {
let arch = match settings.binary_arch() {
Arch::X86_64 => "x64",
Arch::X86 => "x86",
Arch::AArch64 => "arm64",
target => {
return Err(crate::Error::ArchError(format!(
"Unsupported architecture: {target:?}"
)))
}
};
let package_base_name = format!(
"{}_{}_{}_{}",
settings.product_name(),
version,
arch,
language,
);
Ok(settings.project_out_directory().to_path_buf().join(format!(
"bundle/{}/{}.msi",
if updater {
WIX_UPDATER_OUTPUT_FOLDER_NAME
} else {
WIX_OUTPUT_FOLDER_NAME
},
package_base_name
)))
}
/// Generates the UUID for the Wix template.
fn generate_package_guid(settings: &Settings) -> Uuid {
generate_guid(settings.bundle_identifier().as_bytes())
}
/// Generates a GUID.
fn generate_guid(key: &[u8]) -> Uuid {
let namespace = Uuid::from_bytes(UUID_NAMESPACE);
Uuid::new_v5(&namespace, key)
}
// Specifically goes and gets Wix and verifies the download via Sha256
pub fn get_and_extract_wix(path: &Path) -> crate::Result<()> {
log::info!("Verifying wix package");
let data = download_and_verify(WIX_URL, WIX_SHA256, HashAlgorithm::Sha256)?;
log::info!("extracting WIX");
extract_zip(&data, path)
}
fn clear_env_for_wix(cmd: &mut Command) {
cmd.env_clear();
let required_vars: Vec<std::ffi::OsString> =
vec!["SYSTEMROOT".into(), "TMP".into(), "TEMP".into()];
for (k, v) in std::env::vars_os() {
let k = k.to_ascii_uppercase();
if required_vars.contains(&k) || k.to_string_lossy().starts_with("TAURI") {
cmd.env(k, v);
}
}
}
fn validate_wix_version(version_str: &str) -> crate::Result<()> {
let components = version_str
.split('.')
.flat_map(|c| c.parse::<u64>().ok())
.collect::<Vec<_>>();
if components.len() < 3 {
crate::error::bail!(
"app wix version should be in the format major.minor.patch.build (build is optional)"
);
}
if components[0] > 255 {
crate::error::bail!("app version major number cannot be greater than 255");
}
if components[1] > 255 {
crate::error::bail!("app version minor number cannot be greater than 255");
}
if components[2] > 65535 {
crate::error::bail!("app version patch number cannot be greater than 65535");
}
if components.len() == 4 && components[3] > 65535 {
crate::error::bail!("app version build number cannot be greater than 65535");
}
Ok(())
}
// WiX requires versions to be numeric only in a `major.minor.patch.build` format
fn convert_version(version_str: &str) -> crate::Result<String> {
let version = semver::Version::parse(version_str)
.map_err(Into::into)
.context("invalid app version")?;
if !version.build.is_empty() {
let build = version.build.parse::<u64>();
if build.map(|b| b <= 65535).unwrap_or_default() {
return Ok(format!(
"{}.{}.{}.{}",
version.major, version.minor, version.patch, version.build
));
} else {
crate::error::bail!("optional build metadata in app version must be numeric-only and cannot be greater than 65535 for msi target");
}
}
if !version.pre.is_empty() {
let pre = version.pre.parse::<u64>();
if pre.is_ok() && pre.unwrap() <= 65535 {
return Ok(format!(
"{}.{}.{}.{}",
version.major, version.minor, version.patch, version.pre
));
} else {
crate::error::bail!("optional pre-release identifier in app version must be numeric-only and cannot be greater than 65535 for msi target");
}
}
Ok(version_str.to_string())
}
/// Runs the Candle.exe executable for Wix. Candle parses the wxs file and generates the code for building the installer.
fn run_candle(
settings: &Settings,
wix_toolset_path: &Path,
cwd: &Path,
wxs_file_path: PathBuf,
extensions: Vec<PathBuf>,
) -> crate::Result<()> {
let arch = match settings.binary_arch() {
Arch::X86_64 => "x64",
Arch::X86 => "x86",
Arch::AArch64 => "arm64",
target => {
return Err(crate::Error::ArchError(format!(
"unsupported architecture: {target:?}"
)))
}
};
let main_binary = settings.main_binary()?;
let mut args = vec![
"-arch".to_string(),
arch.to_string(),
wxs_file_path.to_string_lossy().to_string(),
format!(
"-dSourceDir={}",
display_path(settings.binary_path(main_binary))
),
];
if settings
.windows()
.wix
.as_ref()
.map(|w| w.fips_compliant)
.unwrap_or_default()
{
args.push("-fips".into());
}
let candle_exe = wix_toolset_path.join("candle.exe");
log::info!(action = "Running"; "candle for {:?}", wxs_file_path);
let mut cmd = Command::new(candle_exe);
for ext in extensions {
cmd.arg("-ext");
cmd.arg(ext);
}
clear_env_for_wix(&mut cmd);
cmd.args(&args).current_dir(cwd).output_ok()?;
Ok(())
}
/// Runs the Light.exe file. Light takes the generated code from Candle and produces an MSI Installer.
fn run_light(
wix_toolset_path: &Path,
build_path: &Path,
arguments: Vec<String>,
extensions: &Vec<PathBuf>,
output_path: &Path,
) -> crate::Result<()> {
let light_exe = wix_toolset_path.join("light.exe");
let mut args: Vec<String> = vec!["-o".to_string(), display_path(output_path)];
args.extend(arguments);
let mut cmd = Command::new(light_exe);
for ext in extensions {
cmd.arg("-ext");
cmd.arg(ext);
}
clear_env_for_wix(&mut cmd);
cmd.args(&args).current_dir(build_path).output_ok()?;
Ok(())
}
// fn get_icon_data() -> crate::Result<()> {
// Ok(())
// }
// Entry point for bundling and creating the MSI installer. For now the only supported platform is Windows x64.
pub fn build_wix_app_installer(
settings: &Settings,
wix_toolset_path: &Path,
updater: bool,
) -> crate::Result<Vec<PathBuf>> {
let arch = match settings.binary_arch() {
Arch::X86_64 => "x64",
Arch::X86 => "x86",
Arch::AArch64 => "arm64",
target => {
return Err(crate::Error::ArchError(format!(
"unsupported architecture: {target:?}"
)))
}
};
let app_version = if let Some(version) = settings
.windows()
.wix
.as_ref()
.and_then(|wix| wix.version.clone())
{
version
} else {
convert_version(settings.version_string())?
};
validate_wix_version(&app_version)?;
// target only supports x64.
log::info!("Target: {}", arch);
let output_path = settings.project_out_directory().join("wix").join(arch);
if output_path.exists() {
fs::remove_dir_all(&output_path)?;
}
fs::create_dir_all(&output_path)?;
// when we're performing code signing, we'll sign some WiX DLLs, so we make a local copy
let wix_toolset_path = if settings.windows().can_sign() {
let wix_path = output_path.join("wix");
crate::utils::fs_utils::copy_dir(wix_toolset_path, &wix_path)?;
wix_path
} else {
wix_toolset_path.to_path_buf()
};
let mut data = BTreeMap::new();
let silent_webview_install = if let WebviewInstallMode::DownloadBootstrapper { silent }
| WebviewInstallMode::EmbedBootstrapper { silent }
| WebviewInstallMode::OfflineInstaller { silent } =
settings.windows().webview_install_mode
{
silent
} else {
true
};
let webview_install_mode = if updater {
WebviewInstallMode::DownloadBootstrapper {
silent: silent_webview_install,
}
} else {
settings.windows().webview_install_mode.clone()
};
data.insert("install_webview", to_json(true));
data.insert(
"webview_installer_args",
to_json(if silent_webview_install {
"/silent"
} else {
""
}),
);
match webview_install_mode {
WebviewInstallMode::Skip | WebviewInstallMode::FixedRuntime { .. } => {
data.insert("install_webview", to_json(false));
}
WebviewInstallMode::DownloadBootstrapper { silent: _ } => {
data.insert("download_bootstrapper", to_json(true));
data.insert(
"webview_installer_args",
to_json(if silent_webview_install {
"'/silent',"
} else {
""
}),
);
}
WebviewInstallMode::EmbedBootstrapper { silent: _ } => {
let webview2_bootstrapper_path = download_webview2_bootstrapper(&output_path)?;
data.insert(
"webview2_bootstrapper_path",
to_json(webview2_bootstrapper_path),
);
}
WebviewInstallMode::OfflineInstaller { silent: _ } => {
let webview2_installer_path =
download_webview2_offline_installer(&output_path.join(arch), arch)?;
data.insert("webview2_installer_path", to_json(webview2_installer_path));
}
}
if let Some(license) = settings.license_file() {
if license.ends_with(".rtf") {
data.insert("license", to_json(license));
} else {
let license_contents = fs::read_to_string(license)?;
let license_rtf = format!(
r#"{{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{{\fonttbl{{\f0\fnil\fcharset0 Calibri;}}}}
{{\*\generator Riched20 10.0.18362}}\viewkind4\uc1
\pard\sa200\sl276\slmult1\f0\fs22\lang9 {}\par
}}
"#,
license_contents.replace('\n', "\\par ")
);
let rtf_output_path = settings
.project_out_directory()
.join("wix")
.join("LICENSE.rtf");
std::fs::write(&rtf_output_path, license_rtf)?;
data.insert("license", to_json(rtf_output_path));
}
}
let language_map: HashMap<String, LanguageMetadata> =
serde_json::from_str(include_str!("./languages.json")).unwrap();
let configured_languages = settings
.windows()
.wix
.as_ref()
.map(|w| w.language.clone())
.unwrap_or_default();
data.insert("product_name", to_json(settings.product_name()));
data.insert("version", to_json(app_version));
data.insert(
"long_description",
to_json(settings.long_description().unwrap_or_default()),
);
data.insert("homepage", to_json(settings.homepage_url()));
let bundle_id = settings.bundle_identifier();
let manufacturer = settings
.publisher()
.unwrap_or_else(|| bundle_id.split('.').nth(1).unwrap_or(bundle_id));
data.insert("bundle_id", to_json(bundle_id));
data.insert("manufacturer", to_json(manufacturer));
// NOTE: if this is ever changed, make sure to also update `tauri inspect wix-upgrade-code` subcommand
let upgrade_code = settings
.windows()
.wix
.as_ref()
.and_then(|w| w.upgrade_code)
.unwrap_or_else(|| {
Uuid::new_v5(
&Uuid::NAMESPACE_DNS,
format!("{}.exe.app.x64", &settings.product_name()).as_bytes(),
)
});
data.insert("upgrade_code", to_json(upgrade_code.to_string()));
data.insert(
"allow_downgrades",
to_json(settings.windows().allow_downgrades),
);
let path_guid = generate_package_guid(settings).to_string();
data.insert("path_component_guid", to_json(path_guid.as_str()));
let shortcut_guid = generate_package_guid(settings).to_string();
data.insert("shortcut_guid", to_json(shortcut_guid.as_str()));
let binaries = generate_binaries_data(settings)?;
let binaries_json = to_json(binaries);
data.insert("binaries", binaries_json);
let resources = generate_resource_data(settings)?;
let mut resources_wix_string = String::from("");
let mut files_ids = Vec::new();
for (_, dir) in resources {
let (wix_string, ids) = dir.get_wix_data()?;
resources_wix_string.push_str(wix_string.as_str());
for id in ids {
files_ids.push(id);
}
}
data.insert("resources", to_json(resources_wix_string));
data.insert("resource_file_ids", to_json(files_ids));
let merge_modules = get_merge_modules(settings)?;
data.insert("merge_modules", to_json(merge_modules));
// Note: `main_binary_name` is not used in our template but we keep it as it is potentially useful for custom temples
let main_binary_name = settings.main_binary_name()?;
data.insert("main_binary_name", to_json(main_binary_name));
let main_binary = settings.main_binary()?;
let main_binary_path = settings.binary_path(main_binary);
data.insert("main_binary_path", to_json(main_binary_path));
// copy icon from `settings.windows().icon_path` folder to resource folder near msi
#[allow(deprecated)]
let icon_path = if !settings.windows().icon_path.as_os_str().is_empty() {
settings.windows().icon_path.clone()
} else {
settings
.icon_files()
.flatten()
.find(|i| i.extension() == Some(OsStr::new("ico")))
.context("Couldn't find a .ico icon")?
};
let icon_path = copy_icon(settings, "icon.ico", &icon_path)?;
data.insert("icon_path", to_json(icon_path));
let mut fragment_paths = Vec::new();
let mut handlebars = Handlebars::new();
handlebars.register_escape_fn(handlebars::no_escape);
let mut custom_template_path = None;
let mut enable_elevated_update_task = false;
if let Some(wix) = &settings.windows().wix {
data.insert("component_group_refs", to_json(&wix.component_group_refs));
data.insert("component_refs", to_json(&wix.component_refs));
data.insert("feature_group_refs", to_json(&wix.feature_group_refs));
data.insert("feature_refs", to_json(&wix.feature_refs));
data.insert("merge_refs", to_json(&wix.merge_refs));
fragment_paths.clone_from(&wix.fragment_paths);
enable_elevated_update_task = wix.enable_elevated_update_task;
custom_template_path.clone_from(&wix.template);
if let Some(banner_path) = &wix.banner_path {
let filename = banner_path
.file_name()
.unwrap()
.to_string_lossy()
.into_owned();
data.insert(
"banner_path",
to_json(copy_icon(settings, &filename, banner_path)?),
);
}
if let Some(dialog_image_path) = &wix.dialog_image_path {
let filename = dialog_image_path
.file_name()
.unwrap()
.to_string_lossy()
.into_owned();
data.insert(
"dialog_image_path",
to_json(copy_icon(settings, &filename, dialog_image_path)?),
);
}
}
if let Some(file_associations) = settings.file_associations() {
data.insert("file_associations", to_json(file_associations));
}
if let Some(protocols) = settings.deep_link_protocols() {
let schemes = protocols
.iter()
.flat_map(|p| &p.schemes)
.collect::<Vec<_>>();
if !schemes.is_empty() {
data.insert("deep_link_protocols", to_json(schemes));
}
}
if let Some(path) = custom_template_path {
handlebars
.register_template_string("main.wxs", fs::read_to_string(path)?)
.map_err(|e| e.to_string())
.expect("Failed to setup custom handlebar template");
} else {
handlebars
.register_template_string("main.wxs", include_str!("./main.wxs"))
.map_err(|e| e.to_string())
.expect("Failed to setup handlebar template");
}
if enable_elevated_update_task {
data.insert(
"msiexec_args",
to_json(
settings
.updater()
.map(|updater| updater.msiexec_args)
.map(|args| args.join(" "))
.unwrap_or_else(|| "/passive".to_string()),
),
);
// Create the update task XML
let skip_uac_task = Handlebars::new();
let xml = include_str!("./update-task.xml");
let update_content = skip_uac_task.render_template(xml, &data)?;
let temp_xml_path = output_path.join("update.xml");
fs::write(temp_xml_path, update_content)?;
// Create the Powershell script to install the task
let mut skip_uac_task_installer = Handlebars::new();
skip_uac_task_installer.register_escape_fn(handlebars::no_escape);
let xml = include_str!("./install-task.ps1");
let install_script_content = skip_uac_task_installer.render_template(xml, &data)?;
let temp_ps1_path = output_path.join("install-task.ps1");
fs::write(temp_ps1_path, install_script_content)?;
// Create the Powershell script to uninstall the task
let mut skip_uac_task_uninstaller = Handlebars::new();
skip_uac_task_uninstaller.register_escape_fn(handlebars::no_escape);
let xml = include_str!("./uninstall-task.ps1");
let install_script_content = skip_uac_task_uninstaller.render_template(xml, &data)?;
let temp_ps1_path = output_path.join("uninstall-task.ps1");
fs::write(temp_ps1_path, install_script_content)?;
data.insert("enable_elevated_update_task", to_json(true));
}
let main_wxs_path = output_path.join("main.wxs");
fs::write(&main_wxs_path, handlebars.render("main.wxs", &data)?)?;
let mut candle_inputs = vec![];
let current_dir = std::env::current_dir()?;
let extension_regex = Regex::new("\"http://schemas.microsoft.com/wix/(\\w+)\"")?;
let input_paths =
std::iter::once(main_wxs_path).chain(fragment_paths.iter().map(|p| current_dir.join(p)));
for input_path in input_paths {
let input_content = fs::read_to_string(&input_path)?;
let input_handlebars = Handlebars::new();
let input = input_handlebars.render_template(&input_content, &data)?;
let mut extensions = Vec::new();
for cap in extension_regex.captures_iter(&input) {
let path = wix_toolset_path.join(format!("Wix{}.dll", &cap[1]));
if settings.windows().can_sign() {
try_sign(&path, settings)?;
}
extensions.push(path);
}
candle_inputs.push((input_path, extensions));
}
let mut fragment_extensions = HashSet::new();
//Default extensions
fragment_extensions.insert(wix_toolset_path.join("WixUIExtension.dll"));
fragment_extensions.insert(wix_toolset_path.join("WixUtilExtension.dll"));
// sign default extensions
if settings.windows().can_sign() {
for path in &fragment_extensions {
try_sign(path, settings)?;
}
}
for (path, extensions) in candle_inputs {
for ext in &extensions {
fragment_extensions.insert(ext.clone());
}
run_candle(settings, &wix_toolset_path, &output_path, path, extensions)?;
}
let mut output_paths = Vec::new();
for (language, language_config) in configured_languages.0 {
let language_metadata = language_map.get(&language).unwrap_or_else(|| {
panic!(
"Language {} not found. It must be one of {}",
language,
language_map
.keys()
.cloned()
.collect::<Vec<String>>()
.join(", ")
)
});
let locale_contents = match language_config.locale_path {
Some(p) => fs::read_to_string(p)?,
None => format!(
r#"<WixLocalization Culture="{}" xmlns="http://schemas.microsoft.com/wix/2006/localization"></WixLocalization>"#,
language.to_lowercase(),
),
};
let locale_strings = include_str!("./default-locale-strings.xml")
.replace("__language__", &language_metadata.lang_id.to_string())
.replace("__codepage__", &language_metadata.ascii_code.to_string())
.replace("__productName__", settings.product_name());
let mut unset_locale_strings = String::new();
let prefix_len = "<String ".len();
for locale_string in locale_strings.split('\n').filter(|s| !s.is_empty()) {
// strip `<String ` prefix and `>{value}</String` suffix.
let id = locale_string
.chars()
.skip(prefix_len)
.take(locale_string.find('>').unwrap() - prefix_len)
.collect::<String>();
if !locale_contents.contains(&id) {
unset_locale_strings.push_str(locale_string);
}
}
let locale_contents = locale_contents.replace(
"</WixLocalization>",
&format!("{unset_locale_strings}</WixLocalization>"),
);
let locale_path = output_path.join("locale.wxl");
{
let mut fileout = File::create(&locale_path).expect("Failed to create locale file");
fileout.write_all(locale_contents.as_bytes())?;
}
let arguments = vec![
format!(
"-cultures:{}",
if language == "en-US" {
language.to_lowercase()
} else {
format!("{};en-US", language.to_lowercase())
}
),
"-loc".into(),
display_path(&locale_path),
"*.wixobj".into(),
];
let msi_output_path = output_path.join("output.msi");
let msi_path =
app_installer_output_path(settings, &language, settings.version_string(), updater)?;
fs::create_dir_all(msi_path.parent().unwrap())?;
log::info!(action = "Running"; "light to produce {}", display_path(&msi_path));
run_light(
&wix_toolset_path,
&output_path,
arguments,
&(fragment_extensions.clone().into_iter().collect()),
&msi_output_path,
)?;
fs::rename(&msi_output_path, &msi_path)?;
if settings.windows().can_sign() {
try_sign(&msi_path, settings)?;
}
output_paths.push(msi_path);
}
Ok(output_paths)
}
/// Generates the data required for the external binaries and extra binaries bundling.
fn generate_binaries_data(settings: &Settings) -> crate::Result<Vec<Binary>> {
let mut binaries = Vec::new();
let cwd = std::env::current_dir()?;
let tmp_dir = std::env::temp_dir();
let regex = Regex::new(r"[^\w\d\.]")?;
for src in settings.external_binaries() {
let src = src?;
let binary_path = cwd.join(&src);
let dest_filename = src
.file_name()
.expect("failed to extract external binary filename")
.to_string_lossy()
.replace(&format!("-{}", settings.target()), "");
let dest = tmp_dir.join(&dest_filename);
std::fs::copy(binary_path, &dest)?;
binaries.push(Binary {
guid: Uuid::new_v4().to_string(),
path: dest
.into_os_string()
.into_string()
.expect("failed to read external binary path"),
id: regex
.replace_all(&dest_filename.replace('-', "_"), "")
.to_string(),
});
}
for bin in settings.binaries() {
if !bin.main() {
binaries.push(Binary {
guid: Uuid::new_v4().to_string(),
path: settings
.binary_path(bin)
.into_os_string()
.into_string()
.expect("failed to read binary path"),
id: regex
.replace_all(&bin.name().replace('-', "_"), "")
.to_string(),
})
}
}
Ok(binaries)
}
#[derive(Serialize)]
struct MergeModule {
name: String,
path: String,
}
fn get_merge_modules(settings: &Settings) -> crate::Result<Vec<MergeModule>> {
let mut merge_modules = Vec::new();
let regex = Regex::new(r"[^\w\d\.]")?;
for msm in glob::glob(
&PathBuf::from(glob::Pattern::escape(
&settings.project_out_directory().to_string_lossy(),
))
.join("*.msm")
.to_string_lossy(),
)? {
let path = msm?;
let filename = path
.file_name()
.expect("failed to extract merge module filename")
.to_os_string()
.into_string()
.expect("failed to convert merge module filename to string");
merge_modules.push(MergeModule {
name: regex.replace_all(&filename, "").to_string(),
path: path.to_string_lossy().to_string(),
});
}
Ok(merge_modules)
}
/// Generates the data required for the resource bundling on wix
fn generate_resource_data(settings: &Settings) -> crate::Result<ResourceMap> {
let mut resources = ResourceMap::new();
let cwd = std::env::current_dir()?;
let mut added_resources = Vec::new();
for resource in settings.resource_files().iter() {
let resource = resource?;
let src = cwd.join(resource.path());
let resource_path = dunce::simplified(&src).to_path_buf();
// In some glob resource paths like `assets/**/*` a file might appear twice
// because the `tauri_utils::resources::ResourcePaths` iterator also reads a directory
// when it finds one. So we must check it before processing the file.
if added_resources.contains(&resource_path) {
continue;
}
added_resources.push(resource_path.clone());
if settings.windows().can_sign() && should_sign(&resource_path)? {
try_sign(&resource_path, settings)?;
}
let resource_entry = ResourceFile {
id: format!("I{}", Uuid::new_v4().as_simple()),
guid: Uuid::new_v4().to_string(),
path: resource_path.clone(),
};
// split the resource path directories
let target_path = resource.target();
let components_count = target_path.components().count();
let directories = target_path
.components()
.take(components_count - 1) // the last component is the file
.collect::<Vec<_>>();
// transform the directory structure to a chained vec structure
let first_directory = directories
.first()
.map(|d| d.as_os_str().to_string_lossy().into_owned())
.unwrap_or_else(String::new);
if !resources.contains_key(&first_directory) {
resources.insert(
first_directory.clone(),
ResourceDirectory {
path: first_directory.clone(),
name: first_directory.clone(),
directories: vec![],
files: vec![],
},
);
}
let mut directory_entry = resources
.get_mut(&first_directory)
.expect("Unable to handle resources");
let mut path = String::new();
// the first component is already parsed on `first_directory` so we skip(1)
for directory in directories.into_iter().skip(1) {
let directory_name = directory
.as_os_str()
.to_os_string()
.into_string()
.expect("failed to read resource folder name");
path.push_str(directory_name.as_str());
path.push(std::path::MAIN_SEPARATOR);
let index = directory_entry
.directories
.iter()
.position(|f| f.path == path);
match index {
Some(i) => directory_entry = directory_entry.directories.get_mut(i).unwrap(),
None => {
directory_entry.directories.push(ResourceDirectory {
path: path.clone(),
name: directory_name,
directories: vec![],
files: vec![],
});
directory_entry = directory_entry.directories.iter_mut().last().unwrap();
}
}
}
directory_entry.add_file(resource_entry);
}
let mut dlls = Vec::new();
// TODO: The bundler should not include all DLLs it finds. Instead it should only include WebView2Loader.dll if present and leave the rest to the resources config.
let out_dir = settings.project_out_directory();
for dll in glob::glob(
&PathBuf::from(glob::Pattern::escape(&out_dir.to_string_lossy()))
.join("*.dll")
.to_string_lossy(),
)? {
let path = dll?;
let resource_path = dunce::simplified(&path);
let relative_path = path
.strip_prefix(out_dir)
.unwrap()
.to_string_lossy()
.into_owned();
if !added_resources.iter().any(|r| r.ends_with(&relative_path)) {
if settings.windows().can_sign() {
try_sign(resource_path, settings)?;
}
dlls.push(ResourceFile {
id: format!("I{}", Uuid::new_v4().as_simple()),
guid: Uuid::new_v4().to_string(),
path: resource_path.to_path_buf(),
});
}
}
if !dlls.is_empty() {
resources
.entry("".to_string())
.and_modify(|r| r.files.append(&mut dlls))
.or_insert(ResourceDirectory {
path: "".to_string(),
name: "".to_string(),
directories: vec![],
files: dlls,
});
}
Ok(resources)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn validates_wix_version() {
assert!(validate_wix_version("1.1.1").is_ok());
assert!(validate_wix_version("1.1.1.1").is_ok());
assert!(validate_wix_version("255.1.1.1").is_ok());
assert!(validate_wix_version("1.255.1.1").is_ok());
assert!(validate_wix_version("1.1.65535.1").is_ok());
assert!(validate_wix_version("1.1.1.65535").is_ok());
assert!(validate_wix_version("256.1.1.1").is_err());
assert!(validate_wix_version("1.256.1.1").is_err());
assert!(validate_wix_version("1.1.65536.1").is_err());
assert!(validate_wix_version("1.1.1.65536").is_err());
}
#[test]
fn converts_version_to_wix() {
assert_eq!(convert_version("1.1.2").unwrap(), "1.1.2");
assert_eq!(convert_version("1.1.2-4").unwrap(), "1.1.2.4");
assert_eq!(convert_version("1.1.2-65535").unwrap(), "1.1.2.65535");
assert_eq!(convert_version("1.1.2+2").unwrap(), "1.1.2.2");
assert!(convert_version("1.1.2-alpha").is_err());
assert!(convert_version("1.1.2-alpha.4").is_err());
assert!(convert_version("1.1.2+asd.3").is_err());
}
}
|
rust
|
github
|
https://github.com/tauri-apps/tauri
|
crates/tauri-bundler/src/bundle/windows/msi/mod.rs
|
from bge import logic, events
from mathutils import Matrix
from math import floor
from random import random
from particle import Particle
import acidbase
mouse = logic.mouse
keyboard = logic.keyboard
gdict = logic.globalDict
ACTIVE = logic.KX_INPUT_JUST_ACTIVATED
def saveObject(newobject,free=True):
if free:
gdict["free"][newobject.name].add(newobject)
if "doubles" in newobject:
gdict["cations"].add(newobject)
gdict["atoms"].add(newobject)
def addObject(newobject,object,velocity=None):
newobject = scene.addObject(newobject,object)
newobject["bonds"] = set()
if newobject.name in ["Carbon","Oxygen","Nitrogen"]:
newobject["doubles"] = set()
newobject["triple"] = None
if velocity != None:
newobject.localLinearVelocity = velocity
particle = Particle(newobject)
return particle
def addChild(child,parent,position):
newobject = addObject(child,parent)
# translate into local position
newobject.worldTransform = newobject.worldTransform * Matrix.Translation(position)
if "bonds" in parent:
newobject.link(parent)
if newobject.name != "Lone Pair":
saveObject(newobject)
return newobject
def main(cont):
global camera, scene
scene = logic.getCurrentScene()
camera = cont.owner
###main controls###
if keyboard.events[events.TKEY] == ACTIVE:
camera["laser"] = True
elif keyboard.events[events.TKEY] == 0:
camera["laser"] = False
if mouse.events[events.LEFTMOUSE] == ACTIVE:
logic.sendMessage("pop","","Camera")
fire_primary()
elif mouse.events[events.RIGHTMOUSE] == ACTIVE:
logic.sendMessage("pop","","Camera")
newobject = addObject("Carbon",camera,[0,0,-100])
saveObject(newobject)
newobject.add_glow()
elif keyboard.events[events.SPACEKEY] == ACTIVE:
newobject = addObject("Antimatter",camera,[0,0,-500])
elif keyboard.events[events.RKEY] == ACTIVE:
scene.restart()
return
## numkeys ##
elif keyboard.events[events.ONEKEY] == ACTIVE:
change_primary("Hydrogen")
elif keyboard.events[events.TWOKEY] == ACTIVE:
change_primary("Oxygen")
elif keyboard.events[events.THREEKEY] == ACTIVE:
change_primary("Nitrogen")
elif keyboard.events[events.FOURKEY] == ACTIVE:
change_primary("Bromine")
elif keyboard.events[events.FIVEKEY] == ACTIVE:
change_primary("Hydroxide")
elif keyboard.events[events.SIXKEY] == ACTIVE:
change_primary("Hydron")
def change_primary(type):
gdict["primary"] = type
primary_text = gdict["prim_text"]
primary_text.text = type
primary_text.visible= True
primary_text.sensors["Delay"].delay = 200
primary_text.sensors["Delay"].reset()
def fire_primary():
type = gdict["primary"]
if type == "Hydrogen":
newobject = addObject("Hydrogen",camera,[0,0,-100])
saveObject(newobject)
elif type == "Oxygen":
newobject = addObject("Oxygen",camera,[0,0,-180])
newobject.add_glow()
addChild("Lone Pair",newobject,[10,0,0])
addChild("Lone Pair",newobject,[-10,0,0])
saveObject(newobject)
newobject.molecule.undamp()
elif type == "Nitrogen":
newobject = addObject("Nitrogen",camera,[0,0,-100])
saveObject(newobject)
newobject.add_glow()
addChild("Lone Pair",newobject,[10,0,0])
newobject.molecule.undamp()
elif type == "Bromine":
newobject = addObject("Bromine",camera,[0,0,-100])
saveObject(newobject)
elif type == "Hydroxide":
newobject = addObject("Oxygen",camera,[0,0,-180])
saveObject(newobject)
newobject.add_glow()
addChild("Lone Pair",newobject,[13,7.5,0])
addChild("Lone Pair",newobject,[-13,7.5,0])
addChild("Lone Pair",newobject,[0,-15,0])
hydrogen = addChild("Hydrogen",newobject,[0,0,30])
acidbase.hydroxide(newobject)
newobject.molecule.undamp()
elif type == "Hydron":
newobject = addObject("Hydrogen",camera,[0,0,-100])
acidbase.hydron(newobject)
newobject.add_glow()
saveObject(newobject,False)
# for opening scene
def auto_spawn(cont):
global scene
scene = logic.getCurrentScene()
if "free" not in gdict:
return
obj = cont.owner
num = floor(random()*5)
x = floor(random()*10) - 5
y = floor(random()*10) - 5
if num > 0:
newobject = addObject("Hydrogen",obj,[x,y,50])
saveObject(newobject)
elif num == 0:
newobject = addObject("Carbon",obj,[x,y,50])
saveObject(newobject)
newobject.add_glow()
|
unknown
|
codeparrot/codeparrot-clean
| ||
"""Extension to the unittest package to support different loggers and parallel test execution."""
from buildscripts.resmokelib.testing import executor, suite
__all__ = ["executor", "suite"]
|
python
|
github
|
https://github.com/mongodb/mongo
|
buildscripts/resmokelib/testing/__init__.py
|
## @package layer_model_instantiator
# Module caffe2.python.layer_model_instantiator
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, schema
from caffe2.python.layers.layers import InstantiationContext
from caffe2.python.layers.tags import Tags
def _filter_layers(layers, include_tags):
if include_tags is None:
return layers
include_tags = set(include_tags)
return [l for l in layers if not include_tags.isdisjoint(l.tags)]
def shrink_output_schema(net, out_schema):
if len(out_schema.field_names()) <= 1:
return out_schema
exists = [net.BlobIsDefined(blob) for blob in out_schema.field_blobs()]
return schema.from_column_list(
[
col_name for ok, col_name in
zip(exists, out_schema.field_names()) if ok
],
[
col_type for ok, col_type in
zip(exists, out_schema.field_types()) if ok
],
[
col_blob for ok, col_blob in
zip(exists, out_schema.field_blobs()) if ok
],
[
col_meta for ok, col_meta in
zip(exists, out_schema.field_metadata()) if ok
]
)
def generate_predict_net(model, include_tags=None):
predict_net = core.Net('predict_net')
for layer in _filter_layers(model.layers, include_tags):
if Tags.EXCLUDE_FROM_PREDICTION not in layer.tags:
layer.add_operators(
predict_net, context=InstantiationContext.PREDICTION)
predict_net.set_input_record(model.input_feature_schema.clone())
output_schema = shrink_output_schema(
predict_net, model.output_schema.clone()
)
predict_net.set_output_record(output_schema)
return predict_net
def generate_eval_net(model, include_tags=None):
eval_net = core.Net('eval_net')
for layer in _filter_layers(model.layers, include_tags):
if Tags.EXCLUDE_FROM_EVAL not in layer.tags:
layer.add_operators(eval_net, context=InstantiationContext.EVAL)
input_schema = model.input_feature_schema + model.trainer_extra_schema
eval_net.set_input_record(input_schema)
output_schema = shrink_output_schema(
eval_net, model.output_schema + model.metrics_schema
)
eval_net.set_output_record(output_schema)
return eval_net
def _generate_training_net_only(model, include_tags=None):
train_net = core.Net('train_net')
train_init_net = model.create_init_net('train_init_net')
for layer in _filter_layers(model.layers, include_tags):
if Tags.EXCLUDE_FROM_TRAIN not in layer.tags:
layer.add_operators(train_net, train_init_net)
input_schema = model.input_feature_schema + model.trainer_extra_schema
train_net.set_input_record(input_schema)
output_schema = shrink_output_schema(
train_net, model.output_schema + model.metrics_schema
)
train_net.set_output_record(output_schema)
return train_init_net, train_net
def generate_training_nets_forward_only(model, include_tags=None):
train_init_net, train_net = _generate_training_net_only(model, include_tags)
return train_init_net, train_net
def generate_training_nets(model, include_tags=None):
train_init_net, train_net = _generate_training_net_only(model, include_tags)
model.apply_regularizers_on_loss(train_net, train_init_net)
if not model.has_loss():
return train_init_net, train_net
loss = model.loss
grad_map = train_net.AddGradientOperators(loss.field_blobs())
model.apply_post_grad_net_modifiers(train_net, train_init_net, grad_map)
model.apply_optimizers(train_net, train_init_net, grad_map)
model.apply_regularizers_after_optimizer(train_net, train_init_net, grad_map)
model.apply_final_net_modifiers(train_net, train_init_net, grad_map)
return train_init_net, train_net
|
unknown
|
codeparrot/codeparrot-clean
| ||
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
__metaclass__ = type
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.1'}
DOCUMENTATION = '''
---
module: fortios_system_ips_urlfilter_dns
short_description: Configure IPS URL filter DNS servers in Fortinet's FortiOS and FortiGate.
description:
- This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the
user to set and modify system feature and ips_urlfilter_dns category.
Examples include all parameters and values need to be adjusted to datasources before usage.
Tested with FOS v6.0.5
version_added: "2.9"
author:
- Miguel Angel Munoz (@mamunozgonzalez)
- Nicolas Thomas (@thomnico)
notes:
- Requires fortiosapi library developed by Fortinet
- Run as a local_action in your playbook
requirements:
- fortiosapi>=0.9.8
options:
host:
description:
- FortiOS or FortiGate IP address.
type: str
required: false
username:
description:
- FortiOS or FortiGate username.
type: str
required: false
password:
description:
- FortiOS or FortiGate password.
type: str
default: ""
vdom:
description:
- Virtual domain, among those defined previously. A vdom is a
virtual instance of the FortiGate that can be configured and
used as a different unit.
type: str
default: root
https:
description:
- Indicates if the requests towards FortiGate must use HTTPS protocol.
type: bool
default: true
ssl_verify:
description:
- Ensures FortiGate certificate must be verified by a proper CA.
type: bool
default: true
state:
description:
- Indicates whether to create or remove the object.
type: str
required: true
choices:
- present
- absent
system_ips_urlfilter_dns:
description:
- Configure IPS URL filter DNS servers.
default: null
type: dict
suboptions:
address:
description:
- DNS server IP address.
required: true
type: str
ipv6_capability:
description:
- Enable/disable this server for IPv6 queries.
type: str
choices:
- enable
- disable
status:
description:
- Enable/disable using this DNS server for IPS URL filter DNS queries.
type: str
choices:
- enable
- disable
'''
EXAMPLES = '''
- hosts: localhost
vars:
host: "192.168.122.40"
username: "admin"
password: ""
vdom: "root"
ssl_verify: "False"
tasks:
- name: Configure IPS URL filter DNS servers.
fortios_system_ips_urlfilter_dns:
host: "{{ host }}"
username: "{{ username }}"
password: "{{ password }}"
vdom: "{{ vdom }}"
https: "False"
state: "present"
system_ips_urlfilter_dns:
address: "<your_own_value>"
ipv6_capability: "enable"
status: "enable"
'''
RETURN = '''
build:
description: Build number of the fortigate image
returned: always
type: str
sample: '1547'
http_method:
description: Last method used to provision the content into FortiGate
returned: always
type: str
sample: 'PUT'
http_status:
description: Last result given by FortiGate on last operation applied
returned: always
type: str
sample: "200"
mkey:
description: Master key (id) used in the last call to FortiGate
returned: success
type: str
sample: "id"
name:
description: Name of the table used to fulfill the request
returned: always
type: str
sample: "urlfilter"
path:
description: Path of the table used to fulfill the request
returned: always
type: str
sample: "webfilter"
revision:
description: Internal revision number
returned: always
type: str
sample: "17.0.2.10658"
serial:
description: Serial number of the unit
returned: always
type: str
sample: "FGVMEVYYQT3AB5352"
status:
description: Indication of the operation's result
returned: always
type: str
sample: "success"
vdom:
description: Virtual domain used
returned: always
type: str
sample: "root"
version:
description: Version of the FortiGate
returned: always
type: str
sample: "v5.6.3"
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.connection import Connection
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG
def login(data, fos):
host = data['host']
username = data['username']
password = data['password']
ssl_verify = data['ssl_verify']
fos.debug('on')
if 'https' in data and not data['https']:
fos.https('off')
else:
fos.https('on')
fos.login(host, username, password, verify=ssl_verify)
def filter_system_ips_urlfilter_dns_data(json):
option_list = ['address', 'ipv6_capability', 'status']
dictionary = {}
for attribute in option_list:
if attribute in json and json[attribute] is not None:
dictionary[attribute] = json[attribute]
return dictionary
def underscore_to_hyphen(data):
if isinstance(data, list):
for elem in data:
elem = underscore_to_hyphen(elem)
elif isinstance(data, dict):
new_data = {}
for k, v in data.items():
new_data[k.replace('_', '-')] = underscore_to_hyphen(v)
data = new_data
return data
def system_ips_urlfilter_dns(data, fos):
vdom = data['vdom']
state = data['state']
system_ips_urlfilter_dns_data = data['system_ips_urlfilter_dns']
filtered_data = underscore_to_hyphen(filter_system_ips_urlfilter_dns_data(system_ips_urlfilter_dns_data))
if state == "present":
return fos.set('system',
'ips-urlfilter-dns',
data=filtered_data,
vdom=vdom)
elif state == "absent":
return fos.delete('system',
'ips-urlfilter-dns',
mkey=filtered_data['address'],
vdom=vdom)
def is_successful_status(status):
return status['status'] == "success" or \
status['http_method'] == "DELETE" and status['http_status'] == 404
def fortios_system(data, fos):
if data['system_ips_urlfilter_dns']:
resp = system_ips_urlfilter_dns(data, fos)
return not is_successful_status(resp), \
resp['status'] == "success", \
resp
def main():
fields = {
"host": {"required": False, "type": "str"},
"username": {"required": False, "type": "str"},
"password": {"required": False, "type": "str", "default": "", "no_log": True},
"vdom": {"required": False, "type": "str", "default": "root"},
"https": {"required": False, "type": "bool", "default": True},
"ssl_verify": {"required": False, "type": "bool", "default": True},
"state": {"required": True, "type": "str",
"choices": ["present", "absent"]},
"system_ips_urlfilter_dns": {
"required": False, "type": "dict", "default": None,
"options": {
"address": {"required": True, "type": "str"},
"ipv6_capability": {"required": False, "type": "str",
"choices": ["enable", "disable"]},
"status": {"required": False, "type": "str",
"choices": ["enable", "disable"]}
}
}
}
module = AnsibleModule(argument_spec=fields,
supports_check_mode=False)
# legacy_mode refers to using fortiosapi instead of HTTPAPI
legacy_mode = 'host' in module.params and module.params['host'] is not None and \
'username' in module.params and module.params['username'] is not None and \
'password' in module.params and module.params['password'] is not None
if not legacy_mode:
if module._socket_path:
connection = Connection(module._socket_path)
fos = FortiOSHandler(connection)
is_error, has_changed, result = fortios_system(module.params, fos)
else:
module.fail_json(**FAIL_SOCKET_MSG)
else:
try:
from fortiosapi import FortiOSAPI
except ImportError:
module.fail_json(msg="fortiosapi module is required")
fos = FortiOSAPI()
login(module.params, fos)
is_error, has_changed, result = fortios_system(module.params, fos)
fos.logout()
if not is_error:
module.exit_json(changed=has_changed, meta=result)
else:
module.fail_json(msg="Error in repo", meta=result)
if __name__ == '__main__':
main()
|
unknown
|
codeparrot/codeparrot-clean
| ||
import json
from urllib.parse import urlencode
from xml.dom.minidom import parseString
from django.contrib.auth.decorators import login_required, permission_required
from django.core import mail
from django.core.exceptions import ValidationError
from django.forms import fields
from django.forms.forms import Form
from django.http import (
HttpResponse,
HttpResponseBadRequest,
HttpResponseNotAllowed,
HttpResponseNotFound,
HttpResponseRedirect,
)
from django.shortcuts import render
from django.template import Context, Template
from django.test import Client
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
def get_view(request):
"A simple view that expects a GET request, and returns a rendered template"
t = Template("This is a test. {{ var }} is the value.", name="GET Template")
c = Context({"var": request.GET.get("var", 42)})
return HttpResponse(t.render(c))
async def async_get_view(request):
return HttpResponse(b"GET content.")
def trace_view(request):
"""
A simple view that expects a TRACE request and echoes its status line.
TRACE requests should not have an entity; the view will return a 400 status
response if it is present.
"""
if request.method.upper() != "TRACE":
return HttpResponseNotAllowed("TRACE")
elif request.body:
return HttpResponseBadRequest("TRACE requests MUST NOT include an entity")
else:
protocol = request.META["SERVER_PROTOCOL"]
t = Template(
"{{ method }} {{ uri }} {{ version }}",
name="TRACE Template",
)
c = Context(
{
"method": request.method,
"uri": request.path,
"version": protocol,
}
)
return HttpResponse(t.render(c))
def put_view(request):
if request.method == "PUT":
t = Template("Data received: {{ data }} is the body.", name="PUT Template")
c = Context(
{
"Content-Length": request.META["CONTENT_LENGTH"],
"data": request.body.decode(),
}
)
else:
t = Template("Viewing GET page.", name="Empty GET Template")
c = Context()
return HttpResponse(t.render(c))
def post_view(request):
"""A view that expects a POST, and returns a different template depending
on whether any POST data is available
"""
if request.method == "POST":
if request.POST:
t = Template(
"Data received: {{ data }} is the value.", name="POST Template"
)
c = Context({"data": request.POST["value"]})
else:
t = Template("Viewing POST page.", name="Empty POST Template")
c = Context()
else:
t = Template("Viewing GET page.", name="Empty GET Template")
# Used by test_body_read_on_get_data.
request.read(200)
c = Context()
return HttpResponse(t.render(c))
def post_then_get_view(request):
"""
A view that expects a POST request, returns a redirect response
to itself providing only a ?success=true querystring,
the value of this querystring is then rendered upon GET.
"""
if request.method == "POST":
return HttpResponseRedirect("?success=true")
t = Template("The value of success is {{ value }}.", name="GET Template")
c = Context({"value": request.GET.get("success", "false")})
return HttpResponse(t.render(c))
def json_view(request):
"""
A view that expects a request with the header 'application/json' and JSON
data, which is deserialized and included in the context.
"""
if request.META.get("CONTENT_TYPE") != "application/json":
return HttpResponse()
t = Template("Viewing {} page. With data {{ data }}.".format(request.method))
data = json.loads(request.body.decode("utf-8"))
c = Context({"data": data})
return HttpResponse(t.render(c))
def view_with_header(request):
"A view that has a custom header"
response = HttpResponse()
response.headers["X-DJANGO-TEST"] = "Slartibartfast"
return response
def raw_post_view(request):
"""A view which expects raw XML to be posted and returns content extracted
from the XML"""
if request.method == "POST":
root = parseString(request.body)
first_book = root.firstChild.firstChild
title, author = [n.firstChild.nodeValue for n in first_book.childNodes]
t = Template("{{ title }} - {{ author }}", name="Book template")
c = Context({"title": title, "author": author})
else:
t = Template("GET request.", name="Book GET template")
c = Context()
return HttpResponse(t.render(c))
def redirect_view(request):
"A view that redirects all requests to the GET view"
if request.GET:
query = "?" + urlencode(request.GET, True)
else:
query = ""
return HttpResponseRedirect("/get_view/" + query)
def method_saving_307_redirect_query_string_view(request):
return HttpResponseRedirect("/post_view/?hello=world", status=307)
def method_saving_308_redirect_query_string_view(request):
return HttpResponseRedirect("/post_view/?hello=world", status=308)
def _post_view_redirect(request, status_code):
"""Redirect to /post_view/ using the status code."""
redirect_to = request.GET.get("to", "/post_view/")
return HttpResponseRedirect(redirect_to, status=status_code)
def method_saving_307_redirect_view(request):
return _post_view_redirect(request, 307)
def method_saving_308_redirect_view(request):
return _post_view_redirect(request, 308)
def redirect_to_different_hostname(request):
return HttpResponseRedirect("https://hostname2/get_host_view/")
def get_host_view(request):
return HttpResponse(request.get_host())
def view_with_secure(request):
"A view that indicates if the request was secure"
response = HttpResponse()
response.test_was_secure_request = request.is_secure()
response.test_server_port = request.META.get("SERVER_PORT", 80)
return response
def double_redirect_view(request):
"A view that redirects all requests to a redirection view"
return HttpResponseRedirect("/permanent_redirect_view/")
def bad_view(request):
"A view that returns a 404 with some error content"
return HttpResponseNotFound("Not found!. This page contains some MAGIC content")
TestChoices = (
("a", "First Choice"),
("b", "Second Choice"),
("c", "Third Choice"),
("d", "Fourth Choice"),
("e", "Fifth Choice"),
)
class TestForm(Form):
text = fields.CharField()
email = fields.EmailField()
value = fields.IntegerField()
single = fields.ChoiceField(choices=TestChoices)
multi = fields.MultipleChoiceField(choices=TestChoices)
def clean(self):
cleaned_data = self.cleaned_data
if cleaned_data.get("text") == "Raise non-field error":
raise ValidationError("Non-field error.")
return cleaned_data
def form_view(request):
"A view that tests a simple form"
if request.method == "POST":
form = TestForm(request.POST)
if form.is_valid():
t = Template("Valid POST data.", name="Valid POST Template")
c = Context()
else:
t = Template(
"Invalid POST data. {{ form.errors }}", name="Invalid POST Template"
)
c = Context({"form": form})
else:
form = TestForm(request.GET)
t = Template("Viewing base form. {{ form }}.", name="Form GET Template")
c = Context({"form": form})
return HttpResponse(t.render(c))
def form_view_with_template(request):
"A view that tests a simple form"
if request.method == "POST":
form = TestForm(request.POST)
if form.is_valid():
message = "POST data OK"
else:
message = "POST data has errors"
else:
form = TestForm()
message = "GET form page"
return render(
request,
"form_view.html",
{
"form": form,
"message": message,
},
)
@login_required
def login_protected_view(request):
"A simple view that is login protected."
t = Template(
"This is a login protected test. Username is {{ user.username }}.",
name="Login Template",
)
c = Context({"user": request.user})
return HttpResponse(t.render(c))
@login_required(redirect_field_name="redirect_to")
def login_protected_view_changed_redirect(request):
"A simple view that is login protected with a custom redirect field set"
t = Template(
"This is a login protected test. Username is {{ user.username }}.",
name="Login Template",
)
c = Context({"user": request.user})
return HttpResponse(t.render(c))
def _permission_protected_view(request):
"A simple view that is permission protected."
t = Template(
"This is a permission protected test. "
"Username is {{ user.username }}. "
"Permissions are {{ user.get_all_permissions }}.",
name="Permissions Template",
)
c = Context({"user": request.user})
return HttpResponse(t.render(c))
permission_protected_view = permission_required("permission_not_granted")(
_permission_protected_view
)
permission_protected_view_exception = permission_required(
"permission_not_granted", raise_exception=True
)(_permission_protected_view)
class _ViewManager:
@method_decorator(login_required)
def login_protected_view(self, request):
t = Template(
"This is a login protected test using a method. "
"Username is {{ user.username }}.",
name="Login Method Template",
)
c = Context({"user": request.user})
return HttpResponse(t.render(c))
@method_decorator(permission_required("permission_not_granted"))
def permission_protected_view(self, request):
t = Template(
"This is a permission protected test using a method. "
"Username is {{ user.username }}. "
"Permissions are {{ user.get_all_permissions }}.",
name="Permissions Template",
)
c = Context({"user": request.user})
return HttpResponse(t.render(c))
_view_manager = _ViewManager()
login_protected_method_view = _view_manager.login_protected_view
permission_protected_method_view = _view_manager.permission_protected_view
def session_view(request):
"A view that modifies the session"
request.session["tobacconist"] = "hovercraft"
t = Template(
"This is a view that modifies the session.",
name="Session Modifying View Template",
)
c = Context()
return HttpResponse(t.render(c))
def broken_view(request):
"""A view which just raises an exception, simulating a broken view."""
raise KeyError("Oops! Looks like you wrote some bad code.")
def mail_sending_view(request):
mail.EmailMessage(
"Test message",
"This is a test email",
"from@example.com",
["first@example.com", "second@example.com"],
).send()
return HttpResponse("Mail sent")
def mass_mail_sending_view(request):
m1 = mail.EmailMessage(
"First Test message",
"This is the first test email",
"from@example.com",
["first@example.com", "second@example.com"],
)
m2 = mail.EmailMessage(
"Second Test message",
"This is the second test email",
"from@example.com",
["second@example.com", "third@example.com"],
)
c = mail.get_connection()
c.send_messages([m1, m2])
return HttpResponse("Mail sent")
def nesting_exception_view(request):
"""
A view that uses a nested client to call another view and then raises an
exception.
"""
client = Client()
client.get("/get_view/")
raise Exception("exception message")
def django_project_redirect(request):
return HttpResponseRedirect("https://www.djangoproject.com/")
def no_trailing_slash_external_redirect(request):
"""
RFC 3986 Section 6.2.3: Empty path should be normalized to "/".
Use https://testserver, rather than an external domain, in order to allow
use of follow=True, triggering Client._handle_redirects().
"""
return HttpResponseRedirect("https://testserver")
def index_view(request):
"""Target for no_trailing_slash_external_redirect with follow=True."""
return HttpResponse("Hello world")
def upload_view(request):
"""Prints keys of request.FILES to the response."""
return HttpResponse(", ".join(request.FILES))
class TwoArgException(Exception):
def __init__(self, one, two):
pass
def two_arg_exception(request):
raise TwoArgException("one", "two")
class CBView(TemplateView):
template_name = "base.html"
|
python
|
github
|
https://github.com/django/django
|
tests/test_client/views.py
|
import { flushSync } from 'svelte';
import { test } from '../../test';
export default test({
html: `
<button>1</button>
<button>2</button>
<button>3</button>
<p>1, 2, 3</p>
`,
test({ assert, target }) {
let buttons = target.querySelectorAll('button');
flushSync(() => buttons[2].click());
assert.htmlEqual(
target.innerHTML,
`
<button>1</button>
<button>2</button>
<button>4</button>
<p>1, 2, 4</p>
`
);
}
});
|
javascript
|
github
|
https://github.com/sveltejs/svelte
|
packages/svelte/tests/runtime-legacy/samples/each-blocks-update/_config.js
|
# Copyright 2019 Fortinet, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <https://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
from mock import ANY
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
try:
from ansible.modules.network.fortios import fortios_system_netflow
except ImportError:
pytest.skip("Could not load required modules for testing", allow_module_level=True)
@pytest.fixture(autouse=True)
def connection_mock(mocker):
connection_class_mock = mocker.patch('ansible.modules.network.fortios.fortios_system_netflow.Connection')
return connection_class_mock
fos_instance = FortiOSHandler(connection_mock)
def test_system_netflow_creation(mocker):
schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')
set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200}
set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result)
input_data = {
'username': 'admin',
'state': 'present',
'system_netflow': {
'active_flow_timeout': '3',
'collector_ip': 'test_value_4',
'collector_port': '5',
'inactive_flow_timeout': '6',
'source_ip': '84.230.14.7',
'template_tx_counter': '8',
'template_tx_timeout': '9'
},
'vdom': 'root'}
is_error, changed, response = fortios_system_netflow.fortios_system(input_data, fos_instance)
expected_data = {
'active-flow-timeout': '3',
'collector-ip': 'test_value_4',
'collector-port': '5',
'inactive-flow-timeout': '6',
'source-ip': '84.230.14.7',
'template-tx-counter': '8',
'template-tx-timeout': '9'
}
set_method_mock.assert_called_with('system', 'netflow', data=expected_data, vdom='root')
schema_method_mock.assert_not_called()
assert not is_error
assert changed
assert response['status'] == 'success'
assert response['http_status'] == 200
def test_system_netflow_creation_fails(mocker):
schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')
set_method_result = {'status': 'error', 'http_method': 'POST', 'http_status': 500}
set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result)
input_data = {
'username': 'admin',
'state': 'present',
'system_netflow': {
'active_flow_timeout': '3',
'collector_ip': 'test_value_4',
'collector_port': '5',
'inactive_flow_timeout': '6',
'source_ip': '84.230.14.7',
'template_tx_counter': '8',
'template_tx_timeout': '9'
},
'vdom': 'root'}
is_error, changed, response = fortios_system_netflow.fortios_system(input_data, fos_instance)
expected_data = {
'active-flow-timeout': '3',
'collector-ip': 'test_value_4',
'collector-port': '5',
'inactive-flow-timeout': '6',
'source-ip': '84.230.14.7',
'template-tx-counter': '8',
'template-tx-timeout': '9'
}
set_method_mock.assert_called_with('system', 'netflow', data=expected_data, vdom='root')
schema_method_mock.assert_not_called()
assert is_error
assert not changed
assert response['status'] == 'error'
assert response['http_status'] == 500
def test_system_netflow_idempotent(mocker):
schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')
set_method_result = {'status': 'error', 'http_method': 'DELETE', 'http_status': 404}
set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result)
input_data = {
'username': 'admin',
'state': 'present',
'system_netflow': {
'active_flow_timeout': '3',
'collector_ip': 'test_value_4',
'collector_port': '5',
'inactive_flow_timeout': '6',
'source_ip': '84.230.14.7',
'template_tx_counter': '8',
'template_tx_timeout': '9'
},
'vdom': 'root'}
is_error, changed, response = fortios_system_netflow.fortios_system(input_data, fos_instance)
expected_data = {
'active-flow-timeout': '3',
'collector-ip': 'test_value_4',
'collector-port': '5',
'inactive-flow-timeout': '6',
'source-ip': '84.230.14.7',
'template-tx-counter': '8',
'template-tx-timeout': '9'
}
set_method_mock.assert_called_with('system', 'netflow', data=expected_data, vdom='root')
schema_method_mock.assert_not_called()
assert not is_error
assert not changed
assert response['status'] == 'error'
assert response['http_status'] == 404
def test_system_netflow_filter_foreign_attributes(mocker):
schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')
set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200}
set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result)
input_data = {
'username': 'admin',
'state': 'present',
'system_netflow': {
'random_attribute_not_valid': 'tag',
'active_flow_timeout': '3',
'collector_ip': 'test_value_4',
'collector_port': '5',
'inactive_flow_timeout': '6',
'source_ip': '84.230.14.7',
'template_tx_counter': '8',
'template_tx_timeout': '9'
},
'vdom': 'root'}
is_error, changed, response = fortios_system_netflow.fortios_system(input_data, fos_instance)
expected_data = {
'active-flow-timeout': '3',
'collector-ip': 'test_value_4',
'collector-port': '5',
'inactive-flow-timeout': '6',
'source-ip': '84.230.14.7',
'template-tx-counter': '8',
'template-tx-timeout': '9'
}
set_method_mock.assert_called_with('system', 'netflow', data=expected_data, vdom='root')
schema_method_mock.assert_not_called()
assert not is_error
assert changed
assert response['status'] == 'success'
assert response['http_status'] == 200
|
unknown
|
codeparrot/codeparrot-clean
| ||
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# resolve.py - Resolves hostname and GeoIP data for each reachable node.
#
# Copyright (c) 2014 Addy Yeow Chin Heng <ayeowch@gmail.com>
#
# 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.
"""
Resolves hostname and GeoIP data for each reachable node.
"""
from decimal import Decimal
from gevent import socket
import gevent
import logging
import os
import pygeoip
import random
import redis
import redis.connection
import sys
from ConfigParser import ConfigParser
redis.connection.socket = socket
# Redis connection setup
REDIS_SOCKET = os.environ.get('REDIS_SOCKET', "/tmp/redis.sock")
REDIS_PASSWORD = os.environ.get('REDIS_PASSWORD', None)
REDIS_CONN = redis.StrictRedis(unix_socket_path=REDIS_SOCKET,
password=REDIS_PASSWORD)
# MaxMind databases
GEOIP4 = pygeoip.GeoIP("geoip/GeoLiteCity.dat", pygeoip.MMAP_CACHE)
GEOIP6 = pygeoip.GeoIP("geoip/GeoLiteCityv6.dat", pygeoip.MMAP_CACHE)
ASN4 = pygeoip.GeoIP("geoip/GeoIPASNum.dat", pygeoip.MMAP_CACHE)
ASN6 = pygeoip.GeoIP("geoip/GeoIPASNumv6.dat", pygeoip.MMAP_CACHE)
# Worker (resolver) status
RESOLVED = 2
FAILED = 1 # Failed socket.gethostbyaddr()
SETTINGS = {}
def resolve_nodes(nodes):
"""
Spawns workers to resolve hostname and GeoIP data for all nodes.
"""
addresses_1 = [] # Resolve hostname
addresses_2 = [] # Resolve GeoIP data
idx = 0
for node in nodes:
node = eval(node)
address = node[0]
if not REDIS_CONN.hexists('resolve:{}'.format(address), 'hostname'):
if idx < 1000:
addresses_1.append(address)
idx += 1
if not REDIS_CONN.hexists('resolve:{}'.format(address), 'geoip'):
addresses_2.append(address)
logging.info("Hostname: {} addresses".format(len(addresses_1)))
workers = [gevent.spawn(set_hostname, address) for address in addresses_1]
gevent.joinall(workers, timeout=15)
(resolved, failed, aborted) = status(workers)
logging.info("Hostname: {} resolved, {} failed, {} aborted".format(
resolved, failed, aborted))
logging.info("GeoIP: {} addresses".format(len(addresses_2)))
workers = [gevent.spawn(set_geoip, address) for address in addresses_2]
gevent.joinall(workers, timeout=15)
(resolved, failed, aborted) = status(workers)
logging.info("GeoIP: {} resolved, {} failed, {} aborted".format(
resolved, failed, aborted))
def status(workers):
"""
Summarizes resolve status for the spawned workers after a set timeout.
"""
resolved = 0
failed = 0
aborted = 0 # Timed out
for worker in workers:
if worker.value == RESOLVED:
resolved += 1
elif worker.value == FAILED:
failed += 1
else:
aborted += 1
return (resolved, failed, aborted)
def set_data(address, field, value):
"""
Stores data for an address in Redis with a randomize TTL randomize to
distribute expiring keys across multiple times.
"""
ttl = random.randint(SETTINGS['min_ttl'], SETTINGS['max_ttl'])
redis_pipe = REDIS_CONN.pipeline()
redis_pipe.hset('resolve:{}'.format(address), field, value)
redis_pipe.expire('resolve:{}'.format(address), ttl)
redis_pipe.execute()
def set_hostname(address):
"""
Caches hostname for the specified address in Redis.
"""
hostname = raw_hostname(address)
set_data(address, 'hostname', hostname)
if hostname != address:
return RESOLVED
return FAILED
def raw_hostname(address):
"""
Resolves hostname for the specified address using reverse DNS resolution.
"""
hostname = address
try:
hostname = socket.gethostbyaddr(address)[0]
except (socket.gaierror, socket.herror) as err:
logging.debug("{}: {}".format(address, err))
return hostname
def set_geoip(address):
"""
Caches GeoIP data for the specified address in Redis.
"""
geoip = raw_geoip(address)
set_data(address, 'geoip', geoip)
return RESOLVED
def raw_geoip(address):
"""
Resolves GeoIP data for the specified address using MaxMind databases.
"""
city = None
country = None
latitude = None
longitude = None
timezone = None
asn = None
org = None
geoip_record = None
prec = Decimal('.000001')
if ":" in address:
geoip_record = GEOIP6.record_by_addr(address)
else:
geoip_record = GEOIP4.record_by_addr(address)
if geoip_record:
city = geoip_record['city']
country = geoip_record['country_code']
latitude = float(Decimal(geoip_record['latitude']).quantize(prec))
longitude = float(Decimal(geoip_record['longitude']).quantize(prec))
timezone = geoip_record['time_zone']
asn_record = None
if ":" in address:
asn_record = ASN6.org_by_addr(address)
else:
asn_record = ASN4.org_by_addr(address)
if asn_record:
data = asn_record.split(" ", 1)
asn = data[0]
if len(data) > 1:
org = data[1]
return (city, country, latitude, longitude, timezone, asn, org)
def init_settings(argv):
"""
Populates SETTINGS with key-value pairs from configuration file.
"""
conf = ConfigParser()
conf.read(argv[1])
SETTINGS['logfile'] = conf.get('resolve', 'logfile')
SETTINGS['debug'] = conf.getboolean('resolve', 'debug')
SETTINGS['min_ttl'] = conf.getint('resolve', 'min_ttl')
SETTINGS['max_ttl'] = conf.getint('resolve', 'max_ttl')
def main(argv):
if len(argv) < 2 or not os.path.exists(argv[1]):
print("Usage: resolve.py [config]")
return 1
# Initialize global settings
init_settings(argv)
# Initialize logger
loglevel = logging.INFO
if SETTINGS['debug']:
loglevel = logging.DEBUG
logformat = ("%(asctime)s,%(msecs)05.1f %(levelname)s (%(funcName)s) "
"%(message)s")
logging.basicConfig(level=loglevel,
format=logformat,
filename=SETTINGS['logfile'],
filemode='w')
print("Writing output to {}, press CTRL+C to terminate..".format(
SETTINGS['logfile']))
pubsub = REDIS_CONN.pubsub()
pubsub.subscribe('snapshot')
for msg in pubsub.listen():
# 'snapshot' message is published by ping.py after establishing
# connection with nodes from a new snapshot.
if msg['channel'] == 'snapshot' and msg['type'] == 'message':
timestamp = int(msg['data'])
logging.info("Timestamp: {}".format(timestamp))
nodes = REDIS_CONN.smembers('opendata')
logging.info("Nodes: {}".format(len(nodes)))
resolve_nodes(nodes)
REDIS_CONN.publish('resolve', timestamp)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
unknown
|
codeparrot/codeparrot-clean
| ||
/*
* Copyright 2002-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.testfixture.beans;
/**
* @author Juergen Hoeller
* @since 15.03.2005
*/
public class CountingTestBean extends TestBean {
public static int count = 0;
public CountingTestBean() {
count++;
}
}
|
java
|
github
|
https://github.com/spring-projects/spring-framework
|
spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/CountingTestBean.java
|
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
try:
from urllib.parse import urlencode
except ImportError: # Python 2
from urllib import urlencode
from django.test import TestCase
from django.utils.translation import activate, get_language
from django.template import Template, Context
from django.core.urlresolvers import reverse
from i18ntools.utils import url_for_language, language_context
def build_url(path, **kwargs):
if kwargs:
path += '?' + urlencode(kwargs)
return path
class UrlForLanguageTest(TestCase):
def test_no_language(self):
activate('en')
self.assertEqual(url_for_language('/about/', 'en'), '/en/about/')
self.assertEqual(url_for_language('/about/', 'es'), '/es/about/')
def test_with_language(self):
activate('en')
self.assertEqual(url_for_language('/en/about/', 'en'), '/en/about/')
self.assertEqual(url_for_language('/en/about/', 'es'), '/es/about/')
def test_with_host(self):
activate('en')
url = 'http://example.com/en/about/'
self.assertEqual(url_for_language(url, 'es'), 'http://example.com/es/about/')
def test_with_weirder_prefix(self):
activate('en-us')
self.assertEqual(url_for_language('/en-us/about/', 'es'), '/es/about/')
activate('es')
self.assertEqual(url_for_language('/es/about/', 'es-mx'), '/es-mx/about/')
def test_possible_false_positive(self):
activate('en')
self.assertEqual(url_for_language('/enable/', 'en'), '/en/enable/')
self.assertEqual(url_for_language('/enable/', 'es'), '/es/enable/')
def test_translated_urls(self):
activate('en')
url = reverse('translated_url', kwargs={'k1': 'foo'})
self.assertEqual(url, '/en/the-url/foo/')
self.assertEqual(url_for_language(url, 'es'), '/es/el-url/foo/')
def test_translated_unnamed_urls(self):
activate('en')
url = reverse('tests.urls.unnamed_view', kwargs={'k1': 'foo'})
self.assertEqual(url, '/en/the-unnamed-url/foo/')
self.assertEqual(url_for_language(url, 'es'), '/es/el-url-sin-nombre/foo/')
class ActivateTest(TestCase):
def test_activate(self):
activate('en')
self.assertEqual(get_language(), 'en')
with language_context('es'):
self.assertEqual(get_language(), 'es')
self.assertEqual(get_language(), 'en')
class TemplateTagsTest(TestCase):
urls = 'tests.urls'
def render(self, template, **context):
t = Template("{% load i18ntools %}" + template)
return t.render(Context(context)).strip()
def test_i18nurl_no_args(self):
activate('en')
self.assertEqual(self.render("{% i18nurl 'en' 'test' %}"), '/en/')
self.assertEqual(self.render("{% i18nurl 'es' 'test' %}"), '/es/')
def test_i18nurl_with_args(self):
activate('en')
self.assertEqual(self.render("{% i18nurl 'en' 'args' 1 2 %}"), '/en/1/2/')
self.assertEqual(self.render("{% i18nurl 'es' 'args' 2 3 %}"), '/es/2/3/')
def test_i18nurl_with_kwargs(self):
activate('en')
self.assertEqual(self.render("{% i18nurl 'en' 'kwargs' k1=1 k2=2 %}"), '/en/1/2/')
self.assertEqual(self.render("{% i18nurl 'es' 'kwargs' k1=2 k2=3 %}"), '/es/2/3/')
def test_url_for_language(self):
activate('en')
self.assertEqual(self.render("{{ test|url_for_language:'en' }}", test='/en/about/'), '/en/about/')
self.assertEqual(self.render("{{ test|url_for_language:'es' }}", test='/en/about/'), '/es/about/')
class SetLanguageViewTest(TestCase):
urls = 'tests.urls'
def setUp(self):
activate('en')
self.url = reverse('set_language')
def assertRedirects(self, response, expected_url, status_code=301,
target_status_code=404, **kwargs):
return super(SetLanguageViewTest, self).assertRedirects(
response, expected_url, status_code, target_status_code, **kwargs
)
def test_no_referer(self):
resp = self.client.post(self.url, {'language': 'es'})
self.assertRedirects(resp, '/es/', 301)
resp = self.client.post(self.url, {'language': 'es'})
self.assertRedirects(resp, '/es/', 301)
def test_with_good_referer(self):
resp = self.client.post(self.url, {'language': 'es'},
HTTP_REFERER='/en/refered/')
self.assertRedirects(resp, '/es/refered/', 301)
def test_with_bad_referer(self):
resp = self.client.post(self.url, {'language': 'es'},
HTTP_REFERER='http://badexample.com/')
self.assertRedirects(resp, '/es/', 301)
def test_with_good_next_url(self):
good_url = build_url(self.url, next='/en/nexted/')
resp = self.client.post(good_url, {'language': 'es'})
self.assertRedirects(resp, '/es/nexted/', 301)
def test_with_bad_next_url(self):
bad_url = build_url(self.url, next='http://badexample.com/')
resp = self.client.post(bad_url, {'language': 'es'})
self.assertRedirects(resp, '/es/', 301)
def test_with_bad_next_url_but_good_referer(self):
bad_url = build_url(self.url, next='http://badexample.com/')
resp = self.client.post(bad_url, {'language': 'es'},
HTTP_REFERER='/en/refered/')
self.assertRedirects(resp, '/es/refered/', 301)
|
unknown
|
codeparrot/codeparrot-clean
| ||
import numpy as np
from pandas import DataFrame
from pandas.tests.copy_view.util import get_array
def test_get_array_numpy():
df = DataFrame({"a": [1, 2, 3]})
assert np.shares_memory(get_array(df, "a"), get_array(df, "a"))
def test_get_array_masked():
df = DataFrame({"a": [1, 2, 3]}, dtype="Int64")
assert np.shares_memory(get_array(df, "a"), get_array(df, "a"))
|
python
|
github
|
https://github.com/pandas-dev/pandas
|
pandas/tests/copy_view/test_util.py
|
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Feed.has_page'
db.add_column('feeds', 'has_page', self.gf('django.db.models.fields.BooleanField')(default=True), keep_default=False)
def backwards(self, orm):
# Deleting field 'Feed.has_page'
db.delete_column('feeds', 'has_page')
models = {
'rss_feeds.duplicatefeed': {
'Meta': {'object_name': 'DuplicateFeed'},
'duplicate_address': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'duplicate_feed_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
'feed': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'duplicate_addresses'", 'to': "orm['rss_feeds.Feed']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'rss_feeds.feed': {
'Meta': {'ordering': "['feed_title']", 'object_name': 'Feed', 'db_table': "'feeds'"},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}),
'active_subscribers': ('django.db.models.fields.IntegerField', [], {'default': '-1', 'db_index': 'True'}),
'average_stories_per_month': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'creation': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'days_to_trim': ('django.db.models.fields.IntegerField', [], {'default': '90'}),
'etag': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'exception_code': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'favicon_color': ('django.db.models.fields.CharField', [], {'max_length': '6', 'null': 'True', 'blank': 'True'}),
'favicon_not_found': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'feed_address': ('django.db.models.fields.URLField', [], {'unique': 'True', 'max_length': '255'}),
'feed_link': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '1000', 'null': 'True', 'blank': 'True'}),
'feed_link_locked': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'feed_title': ('django.db.models.fields.CharField', [], {'default': "'[Untitled]'", 'max_length': '255', 'null': 'True', 'blank': 'True'}),
'fetched_once': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'has_feed_exception': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'has_page': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'has_page_exception': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_load_time': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'last_modified': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'last_update': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True'}),
'min_to_decay': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'next_scheduled_update': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True'}),
'num_subscribers': ('django.db.models.fields.IntegerField', [], {'default': '-1'}),
'premium_subscribers': ('django.db.models.fields.IntegerField', [], {'default': '-1'}),
'queued_date': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True'}),
'stories_last_month': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
'rss_feeds.feeddata': {
'Meta': {'object_name': 'FeedData'},
'feed': ('utils.fields.AutoOneToOneField', [], {'related_name': "'data'", 'unique': 'True', 'to': "orm['rss_feeds.Feed']"}),
'feed_classifier_counts': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'feed_tagline': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'popular_authors': ('django.db.models.fields.CharField', [], {'max_length': '2048', 'null': 'True', 'blank': 'True'}),
'popular_tags': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'null': 'True', 'blank': 'True'}),
'story_count_history': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'})
},
'rss_feeds.feedloadtime': {
'Meta': {'object_name': 'FeedLoadtime'},
'date_accessed': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'feed': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['rss_feeds.Feed']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'loadtime': ('django.db.models.fields.FloatField', [], {})
}
}
complete_apps = ['rss_feeds']
|
unknown
|
codeparrot/codeparrot-clean
| ||
/*
Copyright 2024 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package logparse provides a parser for the klog text format:
//
// I1007 13:16:55.727802 1146763 example.go:57] "Key/value encoding" logger="example" foo="bar" duration="1s" int=42 float=3.14 string="hello world" quotedString="hello \"world\"" multiLinString=<
// hello
// world
// >
// E1007 15:20:04.343375 1157755 example.go:41] Log using Errorf, err: fail
//
// It also supports the klog/ktesting unit test log output:
//
// === RUN TestKlogr
// example_test.go:45: I1007 13:28:21.908998] hello world
// example_test.go:46: E1007 13:28:21.909034] failed err="failed: some error"
// example_test.go:47: I1007 13:28:21.909042] verbosity 1
// example_test.go:48: I1007 13:28:21.909047] main/helper: with prefix
// example_test.go:50: I1007 13:28:21.909076] key/value pairs int=1 float=2 pair="(1, 2)" raw={"Name":"joe","NS":"kube-system"} slice=[1,2,3,"str"] map={"a":1,"b":2} kobj="kube-system/joe" string="hello world" quotedString="hello \"world\"" multiLineString=<
// hello
// world
// >
// example_test.go:63: I1007 13:28:21.909085] info message level 4
// example_test.go:64: I1007 13:28:21.909089] info message level 5
// --- PASS: TestKlogr (0.00s)
// PASS
// ok k8s.io/klog/v2/ktesting/example (cached)
//
// Arbitrary indention with space or tab is supported. All lines of
// a klog log entry must be indented the same way.
package logparse
import (
"bufio"
"errors"
"fmt"
"io"
"iter"
"regexp"
"strings"
)
// Parse splits log output provided by the reader into individual log entries.
// The original log can be reconstructed verbatim by concatenating these
// entries. If the reader fails with an error, the last log entry will
// capture that error.
func Parse(in io.Reader) []Entry {
var log []Entry
for entry := range All(in) {
log = append(log, entry)
}
return log
}
// All is like Parse except that it can be used in a for/range loop:
//
// for entry := range logparse.All(reader) {
// // entry is the next log entry.
// }
func All(in io.Reader) iter.Seq[Entry] {
return func(yield func(Entry) bool) {
parse(in, yield)
}
}
// Entry is the base type for a log entry.
//
// Use type assertions to check for additional information. All
// of the instances behind this interface are pointers.
type Entry interface {
// LogData returns a verbatim copy of the original log chunk,
// including one or more line breaks. Concatenating these chunks
// from all entries will reconstruct the parsed log.
LogData() string
}
// ErrorEntry captures the error encountered while reading the log input.
type ErrorEntry struct {
Err error
}
var _ Entry = &ErrorEntry{}
var _ fmt.Stringer = &ErrorEntry{}
func (e *ErrorEntry) LogData() string { return "" }
func (e *ErrorEntry) String() string { return e.Err.Error() }
// OtherEntry captures some log line which is not part of a klog log entry.
type OtherEntry struct {
Data string
}
var _ Entry = &OtherEntry{}
var _ fmt.Stringer = &OtherEntry{}
func (e *OtherEntry) LogData() string { return e.Data }
func (e *OtherEntry) String() string { return e.Data }
// LogEntry captures some log entry which was recognized as coming from klog.
type KlogEntry struct {
Data string
Severity Severity
}
type Severity byte
const (
SeverityInfo = Severity('I')
SeverityWarning = Severity('W')
SeverityError = Severity('E')
SeverityFatal = Severity('F')
)
var _ Entry = &KlogEntry{}
var _ fmt.Stringer = &KlogEntry{}
func (e *KlogEntry) LogData() string { return e.Data }
func (e *KlogEntry) String() string { return e.Data }
func parse(in io.Reader, yield func(Entry) bool) {
// Read lines using arbitrary length, which can't be done with a
// bufio.Scanner.
reader := bufio.NewReader(in)
line, err := reader.ReadString('\n')
for {
// First deliver the current line. This may need to look
// ahead and thus returns the next line.
var nextLine string
var nextErr error
if len(line) > 0 {
var cont bool
nextLine, cont, nextErr = parseLine(reader, line, yield)
if !cont {
return
}
} else {
nextLine, nextErr = reader.ReadString('\n')
}
// Finalize parsing?
switch {
case err == nil:
// Okay.
case errors.Is(err, io.EOF):
return
default:
yield(&ErrorEntry{Err: err})
return
}
line = nextLine
err = nextErr
}
}
const (
pid = `(?<pid>[[:digit:]]+)`
source = `(?<source>[^:]+:[[:digit:]]+)`
severity = `(?<severity>[IWEF])`
datetime = `(?<month>[[:digit:]]{2})(?<day>[[:digit:]]{2}) (?<hour>[[:digit:]]{2}):(?<minutes>[[:digit:]]{2}):(?<seconds>[[:digit:]]{2})\.(?<microseconds>[[:digit:]]{6})`
)
var (
klogPrefix = regexp.MustCompile(`^(?<indention>[[:blank:]]*)` +
`(?:` + source + `: )?` + // `go test` source code
severity +
datetime +
`(?: +` + pid + ` ` + source + `)?` + // klog pid + source code
`\] `)
indentionIndex = lookupSubmatch("indention")
severityIndex = lookupSubmatch("severity")
)
func lookupSubmatch(name string) int {
names := klogPrefix.SubexpNames()
for i, n := range names {
if n == name {
return i
}
}
panic(fmt.Errorf("named submatch %q not found in %q", name, klogPrefix.String()))
}
// parseLine deals with one non-empty line. It returns the result of yield and
// potentially the next line and/or a read error. If it doesn't have any new
// data to process, it returns the empty string and a nil error.
func parseLine(reader *bufio.Reader, line string, yield func(Entry) bool) (string, bool, error) {
match := klogPrefix.FindStringSubmatchIndex(line)
if match == nil {
cont := yield(&OtherEntry{Data: line})
return "", cont, nil
}
e := &KlogEntry{
Data: line,
Severity: Severity(line[match[2*severityIndex]]),
// TODO (?): store more of the fields that have been identified
}
// Deal with potential line continuation of multi-line string value,
// if necessary.
if !strings.HasSuffix(line, "=<\n") {
return "", yield(e), nil
}
indention := line[match[2*indentionIndex]:match[2*indentionIndex+1]]
for {
var err error
line, err = reader.ReadString('\n')
if !strings.HasPrefix(line, indention) ||
!strings.HasPrefix(line[len(indention):], "\t") && !strings.HasPrefix(line[len(indention):], " >") {
// Some other line (wrong indention or wrong continuation).
// Yield what we have so far and the go back to processing that new line.
cont := yield(e)
return line, cont, err
}
e.Data += line
if err != nil {
return "", yield(e), err
}
}
}
|
go
|
github
|
https://github.com/kubernetes/kubernetes
|
cmd/prune-junit-xml/logparse/logparse.go
|
#------------------------------------------------------------------------------
# Copyright 2013 Esri
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#------------------------------------------------------------------------------
# TestUtilities.py
# Description: Common objects/methods used by test scripts
# Requirements: ArcGIS Desktop Standard
# ----------------------------------------------------------------------------
import arcpy
import os
import sys
currentPath = os.path.dirname(__file__)
toolboxesPath = os.path.normpath(os.path.join(currentPath, r"../../../capability/toolboxes/"))
toolDataPath = os.path.join(toolboxesPath, "tooldata")
layerPath = os.path.join(toolboxesPath, "layers")
layerDataPath = os.path.join(layerPath, "layerdata")
templateGDB = os.path.join(toolDataPath, "Templates.gdb")
toolbox = os.path.join(toolboxesPath, "ERG Tools.pyt")
|
unknown
|
codeparrot/codeparrot-clean
| ||
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.common.security.auth;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
/**
* Login interface for authentication.
*/
public interface Login {
/**
* Configures this login instance.
* @param configs Key-value pairs containing the parsed configuration options of
* the client or broker. Note that these are the Kafka configuration options
* and not the JAAS configuration options. The JAAS options may be obtained
* from `jaasConfiguration`.
* @param contextName JAAS context name for this login which may be used to obtain
* the login context from `jaasConfiguration`.
* @param jaasConfiguration JAAS configuration containing the login context named
* `contextName`. If static JAAS configuration is used, this `Configuration`
* may also contain other login contexts.
* @param loginCallbackHandler Login callback handler instance to use for this Login.
* Login callback handler class may be configured using
* {@link org.apache.kafka.common.config.SaslConfigs#SASL_LOGIN_CALLBACK_HANDLER_CLASS}.
*/
void configure(Map<String, ?> configs, String contextName, Configuration jaasConfiguration,
AuthenticateCallbackHandler loginCallbackHandler);
/**
* Performs login for each login module specified for the login context of this instance.
*/
LoginContext login() throws LoginException;
/**
* Returns the authenticated subject of this login context.
*/
Subject subject();
/**
* Returns the service name to be used for SASL.
*/
String serviceName();
/**
* Closes this instance.
*/
void close();
}
|
java
|
github
|
https://github.com/apache/kafka
|
clients/src/main/java/org/apache/kafka/common/security/auth/Login.java
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from django.shortcuts import render
from pootle.core.decorators import get_path_obj, permission_required
from pootle_app.views.admin import util
from pootle_store.models import Store, Unit
from .forms import term_unit_form_factory
def get_terminology_filename(translation_project):
try:
# See if a terminology store already exists
return translation_project.stores.live().filter(
name__startswith='pootle-terminology.',
).values_list('name', flat=True)[0]
except IndexError:
pass
return 'pootle-terminology.' + translation_project.project.localfiletype
def manage_store(request, ctx, language, term_store):
TermUnitForm = term_unit_form_factory(term_store)
template_name = 'translation_projects/terminology/manage.html'
return util.edit(request, template_name, Unit, ctx,
None, None, queryset=term_store.units, can_delete=True,
form=TermUnitForm)
@get_path_obj
@permission_required('administrate')
def manage(request, translation_project):
ctx = {
'page': 'admin-terminology',
'translation_project': translation_project,
'language': translation_project.language,
'project': translation_project.project,
'source_language': translation_project.project.source_language,
'directory': translation_project.directory,
}
if translation_project.project.is_terminology:
# Which file should we edit?
stores = list(Store.objects.live().filter(
translation_project=translation_project,
))
if len(stores) == 1:
# There is only one, and we're not going to offer file-level
# activities, so let's just edit the one that is there.
return manage_store(request, ctx, ctx['language'], stores[0])
elif len(stores) > 1:
for store in stores:
path_length = len(translation_project.pootle_path)
store.nice_name = store.pootle_path[path_length:]
ctx['stores'] = stores
return render(request, "translation_projects/terminology/stores.html", ctx)
try:
terminology_filename = get_terminology_filename(translation_project)
term_store = Store.objects.get(
pootle_path=translation_project.pootle_path + terminology_filename,
)
return manage_store(request, ctx, ctx['language'], term_store)
except Store.DoesNotExist:
return render(request, "translation_projects/terminology/manage.html", ctx)
|
unknown
|
codeparrot/codeparrot-clean
| ||
"""
Django settings for trialproj project.
Generated by 'django-admin startproject' using Django 1.8.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'registapp',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'trialproj.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'trialproj.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dummydb',
'USER': 'dummyuser',
'PASSWORD': 'dummypass',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
try:
from .settings_devel import *
except:
pass
|
unknown
|
codeparrot/codeparrot-clean
| ||
// Copyright IBM Corp. 2016, 2025
// SPDX-License-Identifier: BUSL-1.1
package command
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"strings"
"sync"
"time"
"github.com/hashicorp/cli"
"github.com/hashicorp/consul/api"
log "github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-kms-wrapping/entropy/v2"
"github.com/hashicorp/go-secure-stdlib/reloadutil"
"github.com/hashicorp/go-uuid"
cserver "github.com/hashicorp/vault/command/server"
"github.com/hashicorp/vault/helper/constants"
"github.com/hashicorp/vault/helper/metricsutil"
"github.com/hashicorp/vault/internalshared/configutil"
"github.com/hashicorp/vault/internalshared/listenerutil"
physconsul "github.com/hashicorp/vault/physical/consul"
"github.com/hashicorp/vault/physical/raft"
"github.com/hashicorp/vault/sdk/physical"
sr "github.com/hashicorp/vault/serviceregistration"
srconsul "github.com/hashicorp/vault/serviceregistration/consul"
"github.com/hashicorp/vault/vault"
"github.com/hashicorp/vault/vault/diagnose"
"github.com/hashicorp/vault/vault/hcp_link"
"github.com/hashicorp/vault/vault/seal"
"github.com/hashicorp/vault/version"
"github.com/posener/complete"
"golang.org/x/term"
)
const CoreConfigUninitializedErr = "Diagnose cannot attempt this step because core config could not be set."
var (
_ cli.Command = (*OperatorDiagnoseCommand)(nil)
_ cli.CommandAutocomplete = (*OperatorDiagnoseCommand)(nil)
)
type OperatorDiagnoseCommand struct {
*BaseCommand
diagnose *diagnose.Session
flagDebug bool
flagSkips []string
flagConfigs []string
cleanupGuard sync.Once
reloadFuncsLock *sync.RWMutex
reloadFuncs *map[string][]reloadutil.ReloadFunc
ServiceRegistrations map[string]sr.Factory
startedCh chan struct{} // for tests
reloadedCh chan struct{} // for tests
skipEndEnd bool // for tests
}
func (c *OperatorDiagnoseCommand) Synopsis() string {
return "Troubleshoot problems starting Vault"
}
func (c *OperatorDiagnoseCommand) Help() string {
helpText := `
Usage: vault operator diagnose
This command troubleshoots Vault startup issues, such as TLS configuration or
auto-unseal. It should be run using the same environment variables and configuration
files as the "vault server" command, so that startup problems can be accurately
reproduced.
Start diagnose with a configuration file:
$ vault operator diagnose -config=/etc/vault/config.hcl
Perform a diagnostic check while Vault is still running:
$ vault operator diagnose -config=/etc/vault/config.hcl -skip=listener
` + c.Flags().Help()
return strings.TrimSpace(helpText)
}
func (c *OperatorDiagnoseCommand) Flags() *FlagSets {
set := NewFlagSets(c.UI)
f := set.NewFlagSet("Command Options")
f.StringSliceVar(&StringSliceVar{
Name: "config",
Target: &c.flagConfigs,
Completion: complete.PredictOr(
complete.PredictFiles("*.hcl"),
complete.PredictFiles("*.json"),
complete.PredictDirs("*"),
),
Usage: "Path to a Vault configuration file or directory of configuration " +
"files. This flag can be specified multiple times to load multiple " +
"configurations. If the path is a directory, all files which end in " +
".hcl or .json are loaded.",
})
f.StringSliceVar(&StringSliceVar{
Name: "skip",
Target: &c.flagSkips,
Usage: "Skip the health checks named as arguments. May be 'listener', 'storage', or 'autounseal'.",
})
f.BoolVar(&BoolVar{
Name: "debug",
Target: &c.flagDebug,
Default: false,
Usage: "Dump all information collected by Diagnose.",
})
f.StringVar(&StringVar{
Name: "format",
Target: &c.flagFormat,
Usage: "The output format",
})
return set
}
func (c *OperatorDiagnoseCommand) AutocompleteArgs() complete.Predictor {
return complete.PredictNothing
}
func (c *OperatorDiagnoseCommand) AutocompleteFlags() complete.Flags {
return c.Flags().Completions()
}
const (
status_unknown = "[ ] "
status_ok = "\u001b[32m[ ok ]\u001b[0m "
status_failed = "\u001b[31m[failed]\u001b[0m "
status_warn = "\u001b[33m[ warn ]\u001b[0m "
same_line = "\u001b[F"
)
func (c *OperatorDiagnoseCommand) Run(args []string) int {
f := c.Flags()
if err := f.Parse(args); err != nil {
c.UI.Error(err.Error())
return 3
}
return c.RunWithParsedFlags()
}
func (c *OperatorDiagnoseCommand) RunWithParsedFlags() int {
if len(c.flagConfigs) == 0 {
c.UI.Error("Must specify a configuration file using -config.")
return 3
}
if c.diagnose == nil {
if c.flagFormat == "json" {
c.diagnose = diagnose.New(io.Discard)
} else {
c.UI.Output(version.GetVersion().FullVersionNumber(true))
c.diagnose = diagnose.New(os.Stdout)
}
}
ctx := diagnose.Context(context.Background(), c.diagnose)
c.diagnose.SkipFilters = c.flagSkips
err := c.offlineDiagnostics(ctx)
results := c.diagnose.Finalize(ctx)
if c.flagFormat == "json" {
resultsJS, err := json.MarshalIndent(results, "", " ")
if err != nil {
fmt.Fprintf(os.Stderr, "Error marshalling results: %v.", err)
return 4
}
c.UI.Output(string(resultsJS))
} else {
c.UI.Output("\nResults:")
w, _, err := term.GetSize(0)
if err == nil {
results.Write(os.Stdout, w)
} else {
results.Write(os.Stdout, 0)
}
}
if err != nil {
return 4
}
// Use a different return code
switch results.Status {
case diagnose.WarningStatus:
return 2
case diagnose.ErrorStatus:
return 1
}
return 0
}
func (c *OperatorDiagnoseCommand) offlineDiagnostics(ctx context.Context) error {
rloadFuncs := make(map[string][]reloadutil.ReloadFunc)
handlers := newVaultHandlers()
server := &ServerCommand{
// TODO: set up a different one?
// In particular, a UI instance that won't output?
BaseCommand: c.BaseCommand,
// TODO: refactor to a common place?
AuditBackends: handlers.auditBackends,
CredentialBackends: handlers.credentialBackends,
LogicalBackends: handlers.logicalBackends,
PhysicalBackends: handlers.physicalBackends,
ServiceRegistrations: handlers.serviceRegistrations,
// TODO: other ServerCommand options?
logger: log.NewInterceptLogger(&log.LoggerOptions{
Level: log.Off,
}),
allLoggers: []log.Logger{},
reloadFuncs: &rloadFuncs,
reloadFuncsLock: new(sync.RWMutex),
}
ctx, span := diagnose.StartSpan(ctx, "Vault Diagnose")
defer span.End()
// OS Specific checks
diagnose.OSChecks(ctx)
var config *cserver.Config
diagnose.Test(ctx, "Parse Configuration", func(ctx context.Context) (err error) {
server.flagConfigs = c.flagConfigs
var configErrors []configutil.ConfigError
config, configErrors, err = server.parseConfig()
if err != nil {
return fmt.Errorf("Could not parse configuration: %w.", err)
}
for _, ce := range configErrors {
diagnose.Warn(ctx, diagnose.CapitalizeFirstLetter(ce.String())+".")
}
diagnose.Success(ctx, "Vault configuration syntax is ok.")
return nil
})
if config == nil {
return fmt.Errorf("No vault server configuration found.")
}
diagnose.Test(ctx, "Check Telemetry", func(ctx context.Context) (err error) {
if config.Telemetry == nil {
diagnose.Warn(ctx, "Telemetry is using default configuration")
diagnose.Advise(ctx, "By default only Prometheus and JSON metrics are available. Ignore this warning if you are using telemetry or are using these metrics and are satisfied with the default retention time and gauge period.")
} else {
t := config.Telemetry
// If any Circonus setting is present but we're missing the basic fields...
if coalesce(t.CirconusAPIURL, t.CirconusAPIToken, t.CirconusCheckID, t.CirconusCheckTags, t.CirconusCheckSearchTag,
t.CirconusBrokerID, t.CirconusBrokerSelectTag, t.CirconusCheckForceMetricActivation, t.CirconusCheckInstanceID,
t.CirconusCheckSubmissionURL, t.CirconusCheckDisplayName) != nil {
if t.CirconusAPIURL == "" {
return errors.New("incomplete Circonus telemetry configuration, missing circonus_api_url")
} else if t.CirconusAPIToken != "" {
return errors.New("incomplete Circonus telemetry configuration, missing circonus_api_token")
}
}
if len(t.DogStatsDTags) > 0 && t.DogStatsDAddr == "" {
return errors.New("incomplete DogStatsD telemetry configuration, missing dogstatsd_addr, while dogstatsd_tags specified")
}
// If any Stackdriver setting is present but we're missing the basic fields...
if coalesce(t.StackdriverNamespace, t.StackdriverLocation, t.StackdriverDebugLogs, t.StackdriverNamespace) != nil {
if t.StackdriverProjectID == "" {
return errors.New("incomplete Stackdriver telemetry configuration, missing stackdriver_project_id")
}
if t.StackdriverLocation == "" {
return errors.New("incomplete Stackdriver telemetry configuration, missing stackdriver_location")
}
if t.StackdriverNamespace == "" {
return errors.New("incomplete Stackdriver telemetry configuration, missing stackdriver_namespace")
}
}
}
return nil
})
var metricSink *metricsutil.ClusterMetricSink
var metricsHelper *metricsutil.MetricsHelper
var backend *physical.Backend
diagnose.Test(ctx, "Check Storage", func(ctx context.Context) error {
// Ensure that there is a storage stanza
if config.Storage == nil {
diagnose.Advise(ctx, "To learn how to specify a storage backend, see the Vault server configuration documentation.")
return fmt.Errorf("No storage stanza in Vault server configuration.")
}
diagnose.Test(ctx, "Create Storage Backend", func(ctx context.Context) error {
b, err := server.setupStorage(config)
if err != nil {
return err
}
if b == nil {
diagnose.Advise(ctx, "To learn how to specify a storage backend, see the Vault server configuration documentation.")
return fmt.Errorf("Storage backend could not be initialized.")
}
backend = &b
return nil
})
if backend == nil {
diagnose.Fail(ctx, "Diagnose could not initialize storage backend.")
span.End()
return fmt.Errorf("Diagnose could not initialize storage backend.")
}
// Check for raft quorum status
if config.Storage.Type == storageTypeRaft {
path := os.Getenv(raft.EnvVaultRaftPath)
if path == "" {
path, ok := config.Storage.Config["path"]
if !ok {
diagnose.SpotError(ctx, "Check Raft Folder Permissions", fmt.Errorf("Storage folder path is required."))
}
diagnose.RaftFileChecks(ctx, path)
}
diagnose.RaftStorageQuorum(ctx, (*backend).(*raft.RaftBackend))
}
// Consul storage checks
if config.Storage != nil && config.Storage.Type == storageTypeConsul {
diagnose.Test(ctx, "Check Consul TLS", func(ctx context.Context) error {
err := physconsul.SetupSecureTLS(ctx, api.DefaultConfig(), config.Storage.Config, server.logger, true)
if err != nil {
return err
}
return nil
})
diagnose.Test(ctx, "Check Consul Direct Storage Access", func(ctx context.Context) error {
dirAccess := diagnose.ConsulDirectAccess(config.Storage.Config)
if dirAccess != "" {
diagnose.Warn(ctx, dirAccess)
}
if dirAccess == diagnose.DirAccessErr {
diagnose.Advise(ctx, diagnose.DirAccessAdvice)
}
return nil
})
}
// Attempt to use storage backend
if !c.skipEndEnd && config.Storage.Type != storageTypeRaft {
diagnose.Test(ctx, "Check Storage Access", diagnose.WithTimeout(30*time.Second, func(ctx context.Context) error {
maxDurationCrudOperation := "write"
maxDuration := time.Duration(0)
uuidSuffix, err := uuid.GenerateUUID()
if err != nil {
return err
}
uuid := "diagnose/latency/" + uuidSuffix
dur, err := diagnose.EndToEndLatencyCheckWrite(ctx, uuid, *backend)
if err != nil {
return err
}
maxDuration = dur
dur, err = diagnose.EndToEndLatencyCheckRead(ctx, uuid, *backend)
if err != nil {
return err
}
if dur > maxDuration {
maxDuration = dur
maxDurationCrudOperation = "read"
}
dur, err = diagnose.EndToEndLatencyCheckDelete(ctx, uuid, *backend)
if err != nil {
return err
}
if dur > maxDuration {
maxDuration = dur
maxDurationCrudOperation = "delete"
}
if maxDuration > time.Duration(0) {
diagnose.Warn(ctx, diagnose.LatencyWarning+fmt.Sprintf("duration: %s, operation: %s", maxDuration, maxDurationCrudOperation))
}
return nil
}))
}
return nil
})
// Return from top-level span when backend is nil
if backend == nil {
return fmt.Errorf("Diagnose could not initialize storage backend.")
}
var configSR sr.ServiceRegistration
diagnose.Test(ctx, "Check Service Discovery", func(ctx context.Context) error {
if config.ServiceRegistration == nil || config.ServiceRegistration.Config == nil {
diagnose.Skipped(ctx, "No service registration configured.")
return nil
}
srConfig := config.ServiceRegistration.Config
diagnose.Test(ctx, "Check Consul Service Discovery TLS", func(ctx context.Context) error {
// SetupSecureTLS for service discovery uses the same cert and key to set up physical
// storage. See the consul package in physical for details.
err := srconsul.SetupSecureTLS(ctx, api.DefaultConfig(), srConfig, server.logger, true)
if err != nil {
return err
}
return nil
})
if config.ServiceRegistration != nil && config.ServiceRegistration.Type == "consul" {
diagnose.Test(ctx, "Check Consul Direct Service Discovery", func(ctx context.Context) error {
dirAccess := diagnose.ConsulDirectAccess(config.ServiceRegistration.Config)
if dirAccess != "" {
diagnose.Warn(ctx, dirAccess)
}
if dirAccess == diagnose.DirAccessErr {
diagnose.Advise(ctx, diagnose.DirAccessAdvice)
}
return nil
})
}
return nil
})
sealcontext, sealspan := diagnose.StartSpan(ctx, "Create Vault Server Configuration Seals")
var setSealResponse *SetSealResponse
var err error
var existingSealGenerationInfo *seal.SealGenerationInfo
if config.IsMultisealEnabled() {
existingSealGenerationInfo, err = vault.PhysicalSealGenInfo(sealcontext, *backend)
if err != nil {
diagnose.Fail(sealcontext, fmt.Sprintf("Unable to get Seal generation information from storage: %s.", err.Error()))
goto SEALFAIL
}
}
setSealResponse, err = setSeal(server, config, make([]string, 0), make(map[string]string), existingSealGenerationInfo, false /* unsealed vault has no partially wrapped paths */)
if err != nil {
diagnose.Advise(ctx, "For assistance with the seal stanza, see the Vault configuration documentation.")
diagnose.Fail(sealcontext, fmt.Sprintf("Seal creation resulted in the following error: %s.", err.Error()))
goto SEALFAIL
}
for _, seal := range setSealResponse.getCreatedSeals() {
seal := seal // capture range variable
// Ensure that the seal finalizer is called, even if using verify-only
defer func(seal *vault.Seal) {
sealType := diagnose.CapitalizeFirstLetter((*seal).BarrierSealConfigType().String())
finalizeSealContext, finalizeSealSpan := diagnose.StartSpan(ctx, "Finalize "+sealType+" Seal")
err = (*seal).Finalize(finalizeSealContext)
if err != nil {
diagnose.Fail(finalizeSealContext, "Error finalizing seal.")
diagnose.Advise(finalizeSealContext, "This likely means that the barrier is still in use; therefore, finalizing the seal timed out.")
finalizeSealSpan.End()
}
finalizeSealSpan.End()
}(seal)
}
if setSealResponse.sealConfigError != nil {
diagnose.Fail(sealcontext, "Seal could not be configured: seals may already be initialized.")
} else if setSealResponse.barrierSeal == nil {
diagnose.Fail(sealcontext, "Could not create barrier seal. No error was generated, but it is likely that the seal stanza is misconfigured. For guidance, see Vault's configuration documentation on the seal stanza.")
}
SEALFAIL:
sealspan.End()
var barrierSeal vault.Seal
var unwrapSeal vault.Seal
if setSealResponse != nil {
barrierSeal = setSealResponse.barrierSeal
unwrapSeal = setSealResponse.unwrapSeal
}
diagnose.Test(ctx, "Check Transit Seal TLS", func(ctx context.Context) error {
var checkSealTransit bool
for _, seal := range config.Seals {
if seal.Type == "transit" {
checkSealTransit = true
tlsSkipVerify, _ := seal.Config["tls_skip_verify"]
if tlsSkipVerify == "true" {
diagnose.Warn(ctx, "TLS verification is skipped. This is highly discouraged and decreases the security of data transmissions to and from the Vault server.")
return nil
}
// Checking tls_client_cert and tls_client_key
tlsClientCert, ok := seal.Config["tls_client_cert"]
if !ok {
diagnose.Warn(ctx, "Missing tls_client_cert in the seal configuration.")
return nil
}
tlsClientKey, ok := seal.Config["tls_client_key"]
if !ok {
diagnose.Warn(ctx, "Missing tls_client_key in the seal configuration.")
return nil
}
_, err := diagnose.TLSFileChecks(tlsClientCert, tlsClientKey)
if err != nil {
return fmt.Errorf("The TLS certificate and key configured through the tls_client_cert and tls_client_key fields of the transit seal configuration are invalid: %w.", err)
}
// checking tls_ca_cert
tlsCACert, ok := seal.Config["tls_ca_cert"]
if !ok {
diagnose.Warn(ctx, "Missing tls_ca_cert in the seal configuration.")
return nil
}
warnings, err := diagnose.TLSCAFileCheck(tlsCACert)
if len(warnings) != 0 {
for _, warning := range warnings {
diagnose.Warn(ctx, warning)
}
}
if err != nil {
return fmt.Errorf("The TLS CA certificate configured through the tls_ca_cert field of the transit seal configuration is invalid: %w.", err)
}
}
}
if !checkSealTransit {
diagnose.Skipped(ctx, "No transit seal found in seal configuration.")
}
return nil
})
var coreConfig vault.CoreConfig
diagnose.Test(ctx, "Create Core Configuration", func(ctx context.Context) error {
var secureRandomReader io.Reader
// prepare a secure random reader for core
randReaderTestName := "Initialize Randomness for Core"
var sources []*configutil.EntropySourcerInfo
if barrierSeal != nil {
for _, sealWrapper := range barrierSeal.GetAccess().GetEnabledSealWrappersByPriority() {
if s, ok := sealWrapper.Wrapper.(entropy.Sourcer); ok {
sources = append(sources, &configutil.EntropySourcerInfo{
Sourcer: s,
Name: sealWrapper.Name,
})
}
}
}
secureRandomReader, err = configutil.CreateSecureRandomReaderFunc(config.SharedConfig, sources, server.logger)
if err != nil {
return diagnose.SpotError(ctx, randReaderTestName, fmt.Errorf("could not initialize randomness for core: %w", err))
}
diagnose.SpotOk(ctx, randReaderTestName, "")
coreConfig = createCoreConfig(server, config, *backend, configSR, barrierSeal, unwrapSeal, metricsHelper, metricSink, secureRandomReader)
return nil
})
var disableClustering bool
diagnose.Test(ctx, "HA Storage", func(ctx context.Context) error {
diagnose.Test(ctx, "Create HA Storage Backend", func(ctx context.Context) error {
// Initialize the separate HA storage backend, if it exists
disableClustering, err = initHaBackend(server, config, &coreConfig, *backend)
if err != nil {
return err
}
return nil
})
diagnose.Test(ctx, "Check HA Consul Direct Storage Access", func(ctx context.Context) error {
if config.HAStorage == nil {
diagnose.Skipped(ctx, "No HA storage stanza is configured.")
} else {
dirAccess := diagnose.ConsulDirectAccess(config.HAStorage.Config)
if dirAccess != "" {
diagnose.Warn(ctx, dirAccess)
}
if dirAccess == diagnose.DirAccessErr {
diagnose.Advise(ctx, diagnose.DirAccessAdvice)
}
}
return nil
})
if config.HAStorage != nil && config.HAStorage.Type == storageTypeConsul {
diagnose.Test(ctx, "Check Consul TLS", func(ctx context.Context) error {
err = physconsul.SetupSecureTLS(ctx, api.DefaultConfig(), config.HAStorage.Config, server.logger, true)
if err != nil {
return err
}
return nil
})
}
return nil
})
// Determine the redirect address from environment variables
err = determineRedirectAddr(server, &coreConfig, config)
if err != nil {
return diagnose.SpotError(ctx, "Determine Redirect Address", fmt.Errorf("Redirect Address could not be determined: %w.", err))
}
diagnose.SpotOk(ctx, "Determine Redirect Address", "")
err = findClusterAddress(server, &coreConfig, config, disableClustering)
if err != nil {
return diagnose.SpotError(ctx, "Check Cluster Address", fmt.Errorf("Cluster Address could not be determined or was invalid: %w.", err),
diagnose.Advice("Please check that the API and Cluster addresses are different, and that the API, Cluster and Redirect addresses have both a host and port."))
}
diagnose.SpotOk(ctx, "Check Cluster Address", "Cluster address is logically valid and can be found.")
var vaultCore *vault.Core
// Run all the checks that are utilized when initializing a core object
// without actually calling core.Init. These are in the init-core section
// as they are runtime checks.
diagnose.Test(ctx, "Check Core Creation", func(ctx context.Context) error {
var newCoreError error
if coreConfig.RawConfig == nil {
return fmt.Errorf(CoreConfigUninitializedErr)
}
core, newCoreError := vault.CreateCore(&coreConfig)
if newCoreError != nil {
if vault.IsFatalError(newCoreError) {
return fmt.Errorf("Error initializing core: %s.", newCoreError)
}
diagnose.Warn(ctx, wrapAtLength(
"A non-fatal error occurred during initialization. Please check the logs for more information."))
} else {
vaultCore = core
}
return nil
})
if vaultCore == nil {
return fmt.Errorf("Diagnose could not initialize the Vault core from the Vault server configuration.")
}
licenseCtx, licenseSpan := diagnose.StartSpan(ctx, "Check For Autoloaded License")
// If we are not in enterprise, return from the check
if !constants.IsEnterprise {
diagnose.Skipped(licenseCtx, "License check will not run on OSS Vault.")
} else {
// Load License from environment variables. These take precedence over the
// configured license.
if envLicensePath := os.Getenv(EnvVaultLicensePath); envLicensePath != "" {
coreConfig.LicensePath = envLicensePath
}
if envLicense := os.Getenv(EnvVaultLicense); envLicense != "" {
coreConfig.License = envLicense
}
// Load license entitlement config
coreConfig := vault.SetDiagnoseCheckLicenseEntitlement(config, coreConfig)
vault.DiagnoseCheckLicense(licenseCtx, vaultCore, coreConfig, vault.DiagnoseCheckLicenseGeneration{
Generate: false,
})
}
licenseSpan.End()
var lns []listenerutil.Listener
diagnose.Test(ctx, "Start Listeners", func(ctx context.Context) error {
disableClustering := config.HAStorage != nil && config.HAStorage.DisableClustering
infoKeys := make([]string, 0, 10)
info := make(map[string]string)
var listeners []listenerutil.Listener
var status int
diagnose.ListenerChecks(ctx, config.Listeners)
diagnose.Test(ctx, "Create Listeners", func(ctx context.Context) error {
status, listeners, _, err = server.InitListeners(config, disableClustering, &infoKeys, &info)
if status != 0 {
return err
}
return nil
})
lns = listeners
// Make sure we close all listeners from this point on
listenerCloseFunc := func() {
for _, ln := range lns {
ln.Listener.Close()
}
}
c.cleanupGuard.Do(listenerCloseFunc)
return nil
})
// TODO: Diagnose logging configuration
// The unseal diagnose check will simply attempt to use the barrier to encrypt and
// decrypt a mock value. It will not call runUnseal.
diagnose.Test(ctx, "Check Autounseal Encryption", diagnose.WithTimeout(30*time.Second, func(ctx context.Context) error {
if barrierSeal == nil {
return fmt.Errorf("Diagnose could not create a barrier seal object.")
}
if barrierSeal.BarrierSealConfigType() == vault.SealConfigTypeShamir {
diagnose.Skipped(ctx, "Skipping barrier encryption test. Only supported for auto-unseal.")
return nil
}
barrierUUID, err := uuid.GenerateUUID()
if err != nil {
return fmt.Errorf("Diagnose could not create unique UUID for unsealing.")
}
barrierEncValue := "diagnose-" + barrierUUID
ciphertext, errMap := barrierSeal.GetAccess().Encrypt(ctx, []byte(barrierEncValue), nil)
if len(errMap) > 0 {
var sealErrors []error
for name, err := range errMap {
sealErrors = append(sealErrors, fmt.Errorf("error encrypting with seal %q: %w", name, err))
}
if ciphertext == nil {
// Full failure
if len(sealErrors) == 1 {
return sealErrors[0]
} else {
return fmt.Errorf("complete seal encryption failure: %w", errors.Join())
}
} else {
// Partial failure
return fmt.Errorf("partial seal encryption failure: %w", errors.Join())
}
}
plaintext, _, err := barrierSeal.GetAccess().Decrypt(ctx, ciphertext, nil)
if err != nil {
return fmt.Errorf("Error decrypting with seal barrier: %w", err)
}
if string(plaintext) != barrierEncValue {
return fmt.Errorf("Barrier returned incorrect decrypted value for mock data.")
}
return nil
}))
// The following block contains static checks that are run during the
// startHttpServers portion of server run. In other words, they are static
// checks during resource creation. Currently there is nothing important in this
// diagnose check. For now it is a placeholder for any checks that will be done
// before server run.
diagnose.Test(ctx, "Check Server Before Runtime", func(ctx context.Context) error {
for _, ln := range lns {
if ln.Config == nil {
return fmt.Errorf("Found no listener config after parsing the Vault configuration.")
}
}
return nil
})
// Checking HCP link to make sure Vault could connect to SCADA.
// If it could not connect to SCADA in 5 seconds, diagnose reports an issue
if !constants.IsEnterprise {
diagnose.Skipped(ctx, "HCP link check will not run on OSS Vault.")
} else {
if config.HCPLinkConf != nil {
// we need to override API and Passthrough capabilities
// as they could not be initialized when Vault http handler
// is not fully initialized
config.HCPLinkConf.EnablePassThroughCapability = false
config.HCPLinkConf.EnableAPICapability = false
diagnose.Test(ctx, "Check HCP Connection", func(ctx context.Context) error {
hcpLink, err := hcp_link.NewHCPLink(config.HCPLinkConf, vaultCore, server.logger)
if err != nil || hcpLink == nil {
return fmt.Errorf("failed to start HCP link, %w", err)
}
// check if a SCADA session is established successfully
deadline := time.Now().Add(5 * time.Second)
linkSessionStatus := "disconnected"
for time.Now().Before(deadline) {
linkSessionStatus = hcpLink.GetConnectionStatusMessage(hcpLink.GetScadaSessionStatus())
if linkSessionStatus == "connected" {
break
}
time.Sleep(500 * time.Millisecond)
}
if linkSessionStatus != "connected" {
return fmt.Errorf("failed to connect to HCP in 5 seconds. HCP session status is: %s", linkSessionStatus)
}
err = hcpLink.Shutdown()
if err != nil {
return fmt.Errorf("failed to shutdown HCP link: %w", err)
}
return nil
})
}
}
return nil
}
func coalesce(values ...interface{}) interface{} {
for _, val := range values {
if val != nil && val != "" {
return val
}
}
return nil
}
|
go
|
github
|
https://github.com/hashicorp/vault
|
command/operator_diagnose.go
|
#!/usr/bin/env python
# pylint: disable=missing-docstring
# flake8: noqa: T001
# ___ ___ _ _ ___ ___ _ _____ ___ ___
# / __| __| \| | __| _ \ /_\_ _| __| \
# | (_ | _|| .` | _|| / / _ \| | | _|| |) |
# \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____
# | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _|
# | |) | (_) | | .` | (_) || | | _|| |) | | | |
# |___/ \___/ |_|\_|\___/ |_| |___|___/___| |_|
#
# Copyright 2016 Red Hat, Inc. and/or its affiliates
# and other contributors as indicated by the @author tags.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# -*- -*- -*- Begin included fragment: lib/import.py -*- -*- -*-
'''
OpenShiftCLI class that wraps the oc commands in a subprocess
'''
# pylint: disable=too-many-lines
from __future__ import print_function
import atexit
import copy
import fcntl
import json
import time
import os
import re
import shutil
import subprocess
import tempfile
# pylint: disable=import-error
try:
import ruamel.yaml as yaml
except ImportError:
import yaml
from ansible.module_utils.basic import AnsibleModule
# -*- -*- -*- End included fragment: lib/import.py -*- -*- -*-
# -*- -*- -*- Begin included fragment: doc/policy_group -*- -*- -*-
DOCUMENTATION = '''
---
module: oc_adm_policy_group
short_description: Module to manage openshift policy for groups
description:
- Manage openshift policy for groups.
options:
kubeconfig:
description:
- The path for the kubeconfig file to use for authentication
required: false
default: /etc/origin/master/admin.kubeconfig
aliases: []
namespace:
description:
- The namespace scope
required: false
default: None
aliases: []
rolebinding_name:
description:
- The name of the rolebinding object for roles
required: false
default: None
aliases: []
debug:
description:
- Turn on debug output.
required: false
default: False
aliases: []
group:
description:
- The name of the group
required: true
default: None
aliases: []
resource_kind:
description:
- The kind of policy to affect
required: true
default: None
choices: ["role", "cluster-role", "scc"]
aliases: []
resource_name:
description:
- The name of the policy
required: true
default: None
aliases: []
state:
description:
- Desired state of the policy
required: true
default: present
choices: ["present", "absent"]
aliases: []
author:
- "Kenny Woodson <kwoodson@redhat.com>"
extends_documentation_fragment: []
'''
EXAMPLES = '''
- name: oc adm policy remove-scc-from-group an-scc agroup
oc_adm_policy_group:
group: agroup
resource_kind: scc
resource_name: an-scc
state: absent
- name: oc adm policy add-cluster-role-to-group system:build-strategy-docker agroup
oc_adm_policy_group:
group: agroup
resource_kind: cluster-role
resource_name: system:build-strategy-docker
state: present
'''
# -*- -*- -*- End included fragment: doc/policy_group -*- -*- -*-
# -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
class YeditException(Exception): # pragma: no cover
''' Exception class for Yedit '''
pass
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class Yedit(object): # pragma: no cover
''' Class to modify yaml files '''
re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z{}/_-]+)"
com_sep = set(['.', '#', '|', ':'])
# pylint: disable=too-many-arguments
def __init__(self,
filename=None,
content=None,
content_type='yaml',
separator='.',
backup_ext=None,
backup=False):
self.content = content
self._separator = separator
self.filename = filename
self.__yaml_dict = content
self.content_type = content_type
self.backup = backup
if backup_ext is None:
self.backup_ext = ".{}".format(time.strftime("%Y%m%dT%H%M%S"))
else:
self.backup_ext = backup_ext
self.load(content_type=self.content_type)
if self.__yaml_dict is None:
self.__yaml_dict = {}
@property
def separator(self):
''' getter method for separator '''
return self._separator
@separator.setter
def separator(self, inc_sep):
''' setter method for separator '''
self._separator = inc_sep
@property
def yaml_dict(self):
''' getter method for yaml_dict '''
return self.__yaml_dict
@yaml_dict.setter
def yaml_dict(self, value):
''' setter method for yaml_dict '''
self.__yaml_dict = value
@staticmethod
def parse_key(key, sep='.'):
'''parse the key allowing the appropriate separator'''
common_separators = list(Yedit.com_sep - set([sep]))
return re.findall(Yedit.re_key.format(''.join(common_separators)), key)
@staticmethod
def valid_key(key, sep='.'):
'''validate the incoming key'''
common_separators = list(Yedit.com_sep - set([sep]))
if not re.match(Yedit.re_valid_key.format(''.join(common_separators)), key):
return False
return True
# pylint: disable=too-many-return-statements,too-many-branches
@staticmethod
def remove_entry(data, key, index=None, value=None, sep='.'):
''' remove data at location key '''
if key == '' and isinstance(data, dict):
if value is not None:
data.pop(value)
elif index is not None:
raise YeditException("remove_entry for a dictionary does not have an index {}".format(index))
else:
data.clear()
return True
elif key == '' and isinstance(data, list):
ind = None
if value is not None:
try:
ind = data.index(value)
except ValueError:
return False
elif index is not None:
ind = index
else:
del data[:]
if ind is not None:
data.pop(ind)
return True
if not (key and Yedit.valid_key(key, sep)) and \
isinstance(data, (list, dict)):
return None
key_indexes = Yedit.parse_key(key, sep)
for arr_ind, dict_key in key_indexes[:-1]:
if dict_key and isinstance(data, dict):
data = data.get(dict_key)
elif (arr_ind and isinstance(data, list) and
int(arr_ind) <= len(data) - 1):
data = data[int(arr_ind)]
else:
return None
# process last index for remove
# expected list entry
if key_indexes[-1][0]:
if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
del data[int(key_indexes[-1][0])]
return True
# expected dict entry
elif key_indexes[-1][1]:
if isinstance(data, dict):
del data[key_indexes[-1][1]]
return True
@staticmethod
def add_entry(data, key, item=None, sep='.'):
''' Get an item from a dictionary with key notation a.b.c
d = {'a': {'b': 'c'}}}
key = a#b
return c
'''
if key == '':
pass
elif (not (key and Yedit.valid_key(key, sep)) and
isinstance(data, (list, dict))):
return None
key_indexes = Yedit.parse_key(key, sep)
for arr_ind, dict_key in key_indexes[:-1]:
if dict_key:
if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
data = data[dict_key]
continue
elif data and not isinstance(data, dict):
raise YeditException("Unexpected item type found while going through key " +
"path: {} (at key: {})".format(key, dict_key))
data[dict_key] = {}
data = data[dict_key]
elif (arr_ind and isinstance(data, list) and
int(arr_ind) <= len(data) - 1):
data = data[int(arr_ind)]
else:
raise YeditException("Unexpected item type found while going through key path: {}".format(key))
if key == '':
data = item
# process last index for add
# expected list entry
elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
data[int(key_indexes[-1][0])] = item
# expected dict entry
elif key_indexes[-1][1] and isinstance(data, dict):
data[key_indexes[-1][1]] = item
# didn't add/update to an existing list, nor add/update key to a dict
# so we must have been provided some syntax like a.b.c[<int>] = "data" for a
# non-existent array
else:
raise YeditException("Error adding to object at path: {}".format(key))
return data
@staticmethod
def get_entry(data, key, sep='.'):
''' Get an item from a dictionary with key notation a.b.c
d = {'a': {'b': 'c'}}}
key = a.b
return c
'''
if key == '':
pass
elif (not (key and Yedit.valid_key(key, sep)) and
isinstance(data, (list, dict))):
return None
key_indexes = Yedit.parse_key(key, sep)
for arr_ind, dict_key in key_indexes:
if dict_key and isinstance(data, dict):
data = data.get(dict_key)
elif (arr_ind and isinstance(data, list) and
int(arr_ind) <= len(data) - 1):
data = data[int(arr_ind)]
else:
return None
return data
@staticmethod
def _write(filename, contents):
''' Actually write the file contents to disk. This helps with mocking. '''
tmp_filename = filename + '.yedit'
with open(tmp_filename, 'w') as yfd:
fcntl.flock(yfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
yfd.write(contents)
fcntl.flock(yfd, fcntl.LOCK_UN)
os.rename(tmp_filename, filename)
def write(self):
''' write to file '''
if not self.filename:
raise YeditException('Please specify a filename.')
if self.backup and self.file_exists():
shutil.copy(self.filename, '{}{}'.format(self.filename, self.backup_ext))
# Try to set format attributes if supported
try:
self.yaml_dict.fa.set_block_style()
except AttributeError:
pass
# Try to use RoundTripDumper if supported.
if self.content_type == 'yaml':
try:
Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
except AttributeError:
Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False))
elif self.content_type == 'json':
Yedit._write(self.filename, json.dumps(self.yaml_dict, indent=4, sort_keys=True))
else:
raise YeditException('Unsupported content_type: {}.'.format(self.content_type) +
'Please specify a content_type of yaml or json.')
return (True, self.yaml_dict)
def read(self):
''' read from file '''
# check if it exists
if self.filename is None or not self.file_exists():
return None
contents = None
with open(self.filename) as yfd:
contents = yfd.read()
return contents
def file_exists(self):
''' return whether file exists '''
if os.path.exists(self.filename):
return True
return False
def load(self, content_type='yaml'):
''' return yaml file '''
contents = self.read()
if not contents and not self.content:
return None
if self.content:
if isinstance(self.content, dict):
self.yaml_dict = self.content
return self.yaml_dict
elif isinstance(self.content, str):
contents = self.content
# check if it is yaml
try:
if content_type == 'yaml' and contents:
# Try to set format attributes if supported
try:
self.yaml_dict.fa.set_block_style()
except AttributeError:
pass
# Try to use RoundTripLoader if supported.
try:
self.yaml_dict = yaml.load(contents, yaml.RoundTripLoader)
except AttributeError:
self.yaml_dict = yaml.safe_load(contents)
# Try to set format attributes if supported
try:
self.yaml_dict.fa.set_block_style()
except AttributeError:
pass
elif content_type == 'json' and contents:
self.yaml_dict = json.loads(contents)
except yaml.YAMLError as err:
# Error loading yaml or json
raise YeditException('Problem with loading yaml file. {}'.format(err))
return self.yaml_dict
def get(self, key):
''' get a specified key'''
try:
entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
except KeyError:
entry = None
return entry
def pop(self, path, key_or_item):
''' remove a key, value pair from a dict or an item for a list'''
try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if entry is None:
return (False, self.yaml_dict)
if isinstance(entry, dict):
# AUDIT:maybe-no-member makes sense due to fuzzy types
# pylint: disable=maybe-no-member
if key_or_item in entry:
entry.pop(key_or_item)
return (True, self.yaml_dict)
return (False, self.yaml_dict)
elif isinstance(entry, list):
# AUDIT:maybe-no-member makes sense due to fuzzy types
# pylint: disable=maybe-no-member
ind = None
try:
ind = entry.index(key_or_item)
except ValueError:
return (False, self.yaml_dict)
entry.pop(ind)
return (True, self.yaml_dict)
return (False, self.yaml_dict)
def delete(self, path, index=None, value=None):
''' remove path from a dict'''
try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if entry is None:
return (False, self.yaml_dict)
result = Yedit.remove_entry(self.yaml_dict, path, index, value, self.separator)
if not result:
return (False, self.yaml_dict)
return (True, self.yaml_dict)
def exists(self, path, value):
''' check if value exists at path'''
try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if isinstance(entry, list):
if value in entry:
return True
return False
elif isinstance(entry, dict):
if isinstance(value, dict):
rval = False
for key, val in value.items():
if entry[key] != val:
rval = False
break
else:
rval = True
return rval
return value in entry
return entry == value
def append(self, path, value):
'''append value to a list'''
try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if entry is None:
self.put(path, [])
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
if not isinstance(entry, list):
return (False, self.yaml_dict)
# AUDIT:maybe-no-member makes sense due to loading data from
# a serialized format.
# pylint: disable=maybe-no-member
entry.append(value)
return (True, self.yaml_dict)
# pylint: disable=too-many-arguments
def update(self, path, value, index=None, curr_value=None):
''' put path, value into a dict '''
try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if isinstance(entry, dict):
# AUDIT:maybe-no-member makes sense due to fuzzy types
# pylint: disable=maybe-no-member
if not isinstance(value, dict):
raise YeditException('Cannot replace key, value entry in dict with non-dict type. ' +
'value=[{}] type=[{}]'.format(value, type(value)))
entry.update(value)
return (True, self.yaml_dict)
elif isinstance(entry, list):
# AUDIT:maybe-no-member makes sense due to fuzzy types
# pylint: disable=maybe-no-member
ind = None
if curr_value:
try:
ind = entry.index(curr_value)
except ValueError:
return (False, self.yaml_dict)
elif index is not None:
ind = index
if ind is not None and entry[ind] != value:
entry[ind] = value
return (True, self.yaml_dict)
# see if it exists in the list
try:
ind = entry.index(value)
except ValueError:
# doesn't exist, append it
entry.append(value)
return (True, self.yaml_dict)
# already exists, return
if ind is not None:
return (False, self.yaml_dict)
return (False, self.yaml_dict)
def put(self, path, value):
''' put path, value into a dict '''
try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if entry == value:
return (False, self.yaml_dict)
# deepcopy didn't work
# Try to use ruamel.yaml and fallback to pyyaml
try:
tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
default_flow_style=False),
yaml.RoundTripLoader)
except AttributeError:
tmp_copy = copy.deepcopy(self.yaml_dict)
# set the format attributes if available
try:
tmp_copy.fa.set_block_style()
except AttributeError:
pass
result = Yedit.add_entry(tmp_copy, path, value, self.separator)
if result is None:
return (False, self.yaml_dict)
# When path equals "" it is a special case.
# "" refers to the root of the document
# Only update the root path (entire document) when its a list or dict
if path == '':
if isinstance(result, list) or isinstance(result, dict):
self.yaml_dict = result
return (True, self.yaml_dict)
return (False, self.yaml_dict)
self.yaml_dict = tmp_copy
return (True, self.yaml_dict)
def create(self, path, value):
''' create a yaml file '''
if not self.file_exists():
# deepcopy didn't work
# Try to use ruamel.yaml and fallback to pyyaml
try:
tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
default_flow_style=False),
yaml.RoundTripLoader)
except AttributeError:
tmp_copy = copy.deepcopy(self.yaml_dict)
# set the format attributes if available
try:
tmp_copy.fa.set_block_style()
except AttributeError:
pass
result = Yedit.add_entry(tmp_copy, path, value, self.separator)
if result is not None:
self.yaml_dict = tmp_copy
return (True, self.yaml_dict)
return (False, self.yaml_dict)
@staticmethod
def get_curr_value(invalue, val_type):
'''return the current value'''
if invalue is None:
return None
curr_value = invalue
if val_type == 'yaml':
curr_value = yaml.safe_load(str(invalue))
elif val_type == 'json':
curr_value = json.loads(invalue)
return curr_value
@staticmethod
def parse_value(inc_value, vtype=''):
'''determine value type passed'''
true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
'on', 'On', 'ON', ]
false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
'off', 'Off', 'OFF']
# It came in as a string but you didn't specify value_type as string
# we will convert to bool if it matches any of the above cases
if isinstance(inc_value, str) and 'bool' in vtype:
if inc_value not in true_bools and inc_value not in false_bools:
raise YeditException('Not a boolean type. str=[{}] vtype=[{}]'.format(inc_value, vtype))
elif isinstance(inc_value, bool) and 'str' in vtype:
inc_value = str(inc_value)
# There is a special case where '' will turn into None after yaml loading it so skip
if isinstance(inc_value, str) and inc_value == '':
pass
# If vtype is not str then go ahead and attempt to yaml load it.
elif isinstance(inc_value, str) and 'str' not in vtype:
try:
inc_value = yaml.safe_load(inc_value)
except Exception:
raise YeditException('Could not determine type of incoming value. ' +
'value=[{}] vtype=[{}]'.format(type(inc_value), vtype))
return inc_value
@staticmethod
def process_edits(edits, yamlfile):
'''run through a list of edits and process them one-by-one'''
results = []
for edit in edits:
value = Yedit.parse_value(edit['value'], edit.get('value_type', ''))
if edit.get('action') == 'update':
# pylint: disable=line-too-long
curr_value = Yedit.get_curr_value(
Yedit.parse_value(edit.get('curr_value')),
edit.get('curr_value_format'))
rval = yamlfile.update(edit['key'],
value,
edit.get('index'),
curr_value)
elif edit.get('action') == 'append':
rval = yamlfile.append(edit['key'], value)
else:
rval = yamlfile.put(edit['key'], value)
if rval[0]:
results.append({'key': edit['key'], 'edit': rval[1]})
return {'changed': len(results) > 0, 'results': results}
# pylint: disable=too-many-return-statements,too-many-branches
@staticmethod
def run_ansible(params):
'''perform the idempotent crud operations'''
yamlfile = Yedit(filename=params['src'],
backup=params['backup'],
content_type=params['content_type'],
backup_ext=params['backup_ext'],
separator=params['separator'])
state = params['state']
if params['src']:
rval = yamlfile.load()
if yamlfile.yaml_dict is None and state != 'present':
return {'failed': True,
'msg': 'Error opening file [{}]. Verify that the '.format(params['src']) +
'file exists, that it is has correct permissions, and is valid yaml.'}
if state == 'list':
if params['content']:
content = Yedit.parse_value(params['content'], params['content_type'])
yamlfile.yaml_dict = content
if params['key']:
rval = yamlfile.get(params['key'])
return {'changed': False, 'result': rval, 'state': state}
elif state == 'absent':
if params['content']:
content = Yedit.parse_value(params['content'], params['content_type'])
yamlfile.yaml_dict = content
if params['update']:
rval = yamlfile.pop(params['key'], params['value'])
else:
rval = yamlfile.delete(params['key'], params['index'], params['value'])
if rval[0] and params['src']:
yamlfile.write()
return {'changed': rval[0], 'result': rval[1], 'state': state}
elif state == 'present':
# check if content is different than what is in the file
if params['content']:
content = Yedit.parse_value(params['content'], params['content_type'])
# We had no edits to make and the contents are the same
if yamlfile.yaml_dict == content and \
params['value'] is None:
return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
yamlfile.yaml_dict = content
# If we were passed a key, value then
# we enapsulate it in a list and process it
# Key, Value passed to the module : Converted to Edits list #
edits = []
_edit = {}
if params['value'] is not None:
_edit['value'] = params['value']
_edit['value_type'] = params['value_type']
_edit['key'] = params['key']
if params['update']:
_edit['action'] = 'update'
_edit['curr_value'] = params['curr_value']
_edit['curr_value_format'] = params['curr_value_format']
_edit['index'] = params['index']
elif params['append']:
_edit['action'] = 'append'
edits.append(_edit)
elif params['edits'] is not None:
edits = params['edits']
if edits:
results = Yedit.process_edits(edits, yamlfile)
# if there were changes and a src provided to us we need to write
if results['changed'] and params['src']:
yamlfile.write()
return {'changed': results['changed'], 'result': results['results'], 'state': state}
# no edits to make
if params['src']:
# pylint: disable=redefined-variable-type
rval = yamlfile.write()
return {'changed': rval[0],
'result': rval[1],
'state': state}
# We were passed content but no src, key or value, or edits. Return contents in memory
return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
return {'failed': True, 'msg': 'Unkown state passed'}
# -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
# -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
# pylint: disable=too-many-lines
# noqa: E301,E302,E303,T001
class OpenShiftCLIError(Exception):
'''Exception class for openshiftcli'''
pass
ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
def locate_oc_binary():
''' Find and return oc binary file '''
# https://github.com/openshift/openshift-ansible/issues/3410
# oc can be in /usr/local/bin in some cases, but that may not
# be in $PATH due to ansible/sudo
paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
oc_binary = 'oc'
# Use shutil.which if it is available, otherwise fallback to a naive path search
try:
which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
if which_result is not None:
oc_binary = which_result
except AttributeError:
for path in paths:
if os.path.exists(os.path.join(path, oc_binary)):
oc_binary = os.path.join(path, oc_binary)
break
return oc_binary
# pylint: disable=too-few-public-methods
class OpenShiftCLI(object):
''' Class to wrap the command line tools '''
def __init__(self,
namespace,
kubeconfig='/etc/origin/master/admin.kubeconfig',
verbose=False,
all_namespaces=False):
''' Constructor for OpenshiftCLI '''
self.namespace = namespace
self.verbose = verbose
self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
self.all_namespaces = all_namespaces
self.oc_binary = locate_oc_binary()
# Pylint allows only 5 arguments to be passed.
# pylint: disable=too-many-arguments
def _replace_content(self, resource, rname, content, edits=None, force=False, sep='.'):
''' replace the current object with the content '''
res = self._get(resource, rname)
if not res['results']:
return res
fname = Utils.create_tmpfile(rname + '-')
yed = Yedit(fname, res['results'][0], separator=sep)
updated = False
if content is not None:
changes = []
for key, value in content.items():
changes.append(yed.put(key, value))
if any([change[0] for change in changes]):
updated = True
elif edits is not None:
results = Yedit.process_edits(edits, yed)
if results['changed']:
updated = True
if updated:
yed.write()
atexit.register(Utils.cleanup, [fname])
return self._replace(fname, force)
return {'returncode': 0, 'updated': False}
def _replace(self, fname, force=False):
'''replace the current object with oc replace'''
# We are removing the 'resourceVersion' to handle
# a race condition when modifying oc objects
yed = Yedit(fname)
results = yed.delete('metadata.resourceVersion')
if results[0]:
yed.write()
cmd = ['replace', '-f', fname]
if force:
cmd.append('--force')
return self.openshift_cmd(cmd)
def _create_from_content(self, rname, content):
'''create a temporary file and then call oc create on it'''
fname = Utils.create_tmpfile(rname + '-')
yed = Yedit(fname, content=content)
yed.write()
atexit.register(Utils.cleanup, [fname])
return self._create(fname)
def _create(self, fname):
'''call oc create on a filename'''
return self.openshift_cmd(['create', '-f', fname])
def _delete(self, resource, name=None, selector=None):
'''call oc delete on a resource'''
cmd = ['delete', resource]
if selector is not None:
cmd.append('--selector={}'.format(selector))
elif name is not None:
cmd.append(name)
else:
raise OpenShiftCLIError('Either name or selector is required when calling delete.')
return self.openshift_cmd(cmd)
def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
'''process a template
template_name: the name of the template to process
create: whether to send to oc create after processing
params: the parameters for the template
template_data: the incoming template's data; instead of a file
'''
cmd = ['process']
if template_data:
cmd.extend(['-f', '-'])
else:
cmd.append(template_name)
if params:
param_str = ["{}={}".format(key, str(value).replace("'", r'"')) for key, value in params.items()]
cmd.append('-p')
cmd.extend(param_str)
results = self.openshift_cmd(cmd, output=True, input_data=template_data)
if results['returncode'] != 0 or not create:
return results
fname = Utils.create_tmpfile(template_name + '-')
yed = Yedit(fname, results['results'])
yed.write()
atexit.register(Utils.cleanup, [fname])
return self.openshift_cmd(['create', '-f', fname])
def _get(self, resource, name=None, selector=None, field_selector=None):
'''return a resource by name '''
cmd = ['get', resource]
if selector is not None:
cmd.append('--selector={}'.format(selector))
if field_selector is not None:
cmd.append('--field-selector={}'.format(field_selector))
# Name cannot be used with selector or field_selector.
if selector is None and field_selector is None and name is not None:
cmd.append(name)
cmd.extend(['-o', 'json'])
rval = self.openshift_cmd(cmd, output=True)
# Ensure results are retuned in an array
if 'items' in rval:
rval['results'] = rval['items']
elif not isinstance(rval['results'], list):
rval['results'] = [rval['results']]
return rval
def _schedulable(self, node=None, selector=None, schedulable=True):
''' perform oadm manage-node scheduable '''
cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
cmd.append('--schedulable={}'.format(schedulable))
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
def _list_pods(self, node=None, selector=None, pod_selector=None):
''' perform oadm list pods
node: the node in which to list pods
selector: the label selector filter if provided
pod_selector: the pod selector filter if provided
'''
cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
if pod_selector:
cmd.append('--pod-selector={}'.format(pod_selector))
cmd.extend(['--list-pods', '-o', 'json'])
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
# pylint: disable=too-many-arguments
def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
''' perform oadm manage-node evacuate '''
cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
if dry_run:
cmd.append('--dry-run')
if pod_selector:
cmd.append('--pod-selector={}'.format(pod_selector))
if grace_period:
cmd.append('--grace-period={}'.format(int(grace_period)))
if force:
cmd.append('--force')
cmd.append('--evacuate')
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
def _version(self):
''' return the openshift version'''
return self.openshift_cmd(['version'], output=True, output_type='raw')
def _import_image(self, url=None, name=None, tag=None):
''' perform image import '''
cmd = ['import-image']
image = '{0}'.format(name)
if tag:
image += ':{0}'.format(tag)
cmd.append(image)
if url:
cmd.append('--from={0}/{1}'.format(url, image))
cmd.append('-n{0}'.format(self.namespace))
cmd.append('--confirm')
return self.openshift_cmd(cmd)
def _run(self, cmds, input_data):
''' Actually executes the command. This makes mocking easier. '''
curr_env = os.environ.copy()
curr_env.update({'KUBECONFIG': self.kubeconfig})
proc = subprocess.Popen(cmds,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=curr_env)
stdout, stderr = proc.communicate(input_data)
return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8')
# pylint: disable=too-many-arguments,too-many-branches
def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
'''Base command for oc '''
cmds = [self.oc_binary]
if oadm:
cmds.append('adm')
cmds.extend(cmd)
if self.all_namespaces:
cmds.extend(['--all-namespaces'])
elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
cmds.extend(['-n', self.namespace])
if self.verbose:
print(' '.join(cmds))
try:
returncode, stdout, stderr = self._run(cmds, input_data)
except OSError as ex:
returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
rval = {"returncode": returncode,
"cmd": ' '.join(cmds)}
if output_type == 'json':
rval['results'] = {}
if output and stdout:
try:
rval['results'] = json.loads(stdout)
except ValueError as verr:
if "No JSON object could be decoded" in verr.args:
rval['err'] = verr.args
elif output_type == 'raw':
rval['results'] = stdout if output else ''
if self.verbose:
print("STDOUT: {0}".format(stdout))
print("STDERR: {0}".format(stderr))
if 'err' in rval or returncode != 0:
rval.update({"stderr": stderr,
"stdout": stdout})
return rval
class Utils(object): # pragma: no cover
''' utilities for openshiftcli modules '''
@staticmethod
def _write(filename, contents):
''' Actually write the file contents to disk. This helps with mocking. '''
with open(filename, 'w') as sfd:
sfd.write(str(contents))
@staticmethod
def create_tmp_file_from_contents(rname, data, ftype='yaml'):
''' create a file in tmp with name and contents'''
tmp = Utils.create_tmpfile(prefix=rname)
if ftype == 'yaml':
# AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
# pylint: disable=no-member
if hasattr(yaml, 'RoundTripDumper'):
Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
else:
Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
elif ftype == 'json':
Utils._write(tmp, json.dumps(data))
else:
Utils._write(tmp, data)
# Register cleanup when module is done
atexit.register(Utils.cleanup, [tmp])
return tmp
@staticmethod
def create_tmpfile_copy(inc_file):
'''create a temporary copy of a file'''
tmpfile = Utils.create_tmpfile('lib_openshift-')
Utils._write(tmpfile, open(inc_file).read())
# Cleanup the tmpfile
atexit.register(Utils.cleanup, [tmpfile])
return tmpfile
@staticmethod
def create_tmpfile(prefix='tmp'):
''' Generates and returns a temporary file name '''
with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
return tmp.name
@staticmethod
def create_tmp_files_from_contents(content, content_type=None):
'''Turn an array of dict: filename, content into a files array'''
if not isinstance(content, list):
content = [content]
files = []
for item in content:
path = Utils.create_tmp_file_from_contents(item['path'] + '-',
item['data'],
ftype=content_type)
files.append({'name': os.path.basename(item['path']),
'path': path})
return files
@staticmethod
def cleanup(files):
'''Clean up on exit '''
for sfile in files:
if os.path.exists(sfile):
if os.path.isdir(sfile):
shutil.rmtree(sfile)
elif os.path.isfile(sfile):
os.remove(sfile)
@staticmethod
def exists(results, _name):
''' Check to see if the results include the name '''
if not results:
return False
if Utils.find_result(results, _name):
return True
return False
@staticmethod
def find_result(results, _name):
''' Find the specified result by name'''
rval = None
for result in results:
if 'metadata' in result and result['metadata']['name'] == _name:
rval = result
break
return rval
@staticmethod
def get_resource_file(sfile, sfile_type='yaml'):
''' return the service file '''
contents = None
with open(sfile) as sfd:
contents = sfd.read()
if sfile_type == 'yaml':
# AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
# pylint: disable=no-member
if hasattr(yaml, 'RoundTripLoader'):
contents = yaml.load(contents, yaml.RoundTripLoader)
else:
contents = yaml.safe_load(contents)
elif sfile_type == 'json':
contents = json.loads(contents)
return contents
@staticmethod
def filter_versions(stdout):
''' filter the oc version output '''
version_dict = {}
version_search = ['oc', 'openshift', 'kubernetes']
for line in stdout.strip().split('\n'):
for term in version_search:
if not line:
continue
if line.startswith(term):
version_dict[term] = line.split()[-1]
# horrible hack to get openshift version in Openshift 3.2
# By default "oc version in 3.2 does not return an "openshift" version
if "openshift" not in version_dict:
version_dict["openshift"] = version_dict["oc"]
return version_dict
@staticmethod
def add_custom_versions(versions):
''' create custom versions strings '''
versions_dict = {}
for tech, version in versions.items():
# clean up "-" from version
if "-" in version:
version = version.split("-")[0]
if version.startswith('v'):
version = version[1:] # Remove the 'v' prefix
versions_dict[tech + '_numeric'] = version.split('+')[0]
# "3.3.0.33" is what we have, we want "3.3"
versions_dict[tech + '_short'] = "{}.{}".format(*version.split('.'))
return versions_dict
@staticmethod
def openshift_installed():
''' check if openshift is installed '''
import rpm
transaction_set = rpm.TransactionSet()
rpmquery = transaction_set.dbMatch("name", "atomic-openshift")
return rpmquery.count() > 0
# Disabling too-many-branches. This is a yaml dictionary comparison function
# pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
@staticmethod
def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
''' Given a user defined definition, compare it with the results given back by our query. '''
# Currently these values are autogenerated and we do not need to check them
skip = ['metadata', 'status']
if skip_keys:
skip.extend(skip_keys)
for key, value in result_def.items():
if key in skip:
continue
# Both are lists
if isinstance(value, list):
if key not in user_def:
if debug:
print('User data does not have key [%s]' % key)
print('User data: %s' % user_def)
return False
if not isinstance(user_def[key], list):
if debug:
print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
return False
if len(user_def[key]) != len(value):
if debug:
print("List lengths are not equal.")
print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
print("user_def: %s" % user_def[key])
print("value: %s" % value)
return False
for values in zip(user_def[key], value):
if isinstance(values[0], dict) and isinstance(values[1], dict):
if debug:
print('sending list - list')
print(type(values[0]))
print(type(values[1]))
result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
if not result:
print('list compare returned false')
return False
elif value != user_def[key]:
if debug:
print('value should be identical')
print(user_def[key])
print(value)
return False
# recurse on a dictionary
elif isinstance(value, dict):
if key not in user_def:
if debug:
print("user_def does not have key [%s]" % key)
return False
if not isinstance(user_def[key], dict):
if debug:
print("dict returned false: not instance of dict")
return False
# before passing ensure keys match
api_values = set(value.keys()) - set(skip)
user_values = set(user_def[key].keys()) - set(skip)
if api_values != user_values:
if debug:
print("keys are not equal in dict")
print(user_values)
print(api_values)
return False
result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
if not result:
if debug:
print("dict returned false")
print(result)
return False
# Verify each key, value pair is the same
else:
if key not in user_def or value != user_def[key]:
if debug:
print("value not equal; user_def does not have key")
print(key)
print(value)
if key in user_def:
print(user_def[key])
return False
if debug:
print('returning true')
return True
class OpenShiftCLIConfig(object):
'''Generic Config'''
def __init__(self, rname, namespace, kubeconfig, options):
self.kubeconfig = kubeconfig
self.name = rname
self.namespace = namespace
self._options = options
@property
def config_options(self):
''' return config options '''
return self._options
def to_option_list(self, ascommalist=''):
'''return all options as a string
if ascommalist is set to the name of a key, and
the value of that key is a dict, format the dict
as a list of comma delimited key=value pairs'''
return self.stringify(ascommalist)
def stringify(self, ascommalist=''):
''' return the options hash as cli params in a string
if ascommalist is set to the name of a key, and
the value of that key is a dict, format the dict
as a list of comma delimited key=value pairs '''
rval = []
for key in sorted(self.config_options.keys()):
data = self.config_options[key]
if data['include'] \
and (data['value'] is not None or isinstance(data['value'], int)):
if key == ascommalist:
val = ','.join(['{}={}'.format(kk, vv) for kk, vv in sorted(data['value'].items())])
else:
val = data['value']
rval.append('--{}={}'.format(key.replace('_', '-'), val))
return rval
# -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
# -*- -*- -*- Begin included fragment: lib/rolebinding.py -*- -*- -*-
# pylint: disable=too-many-instance-attributes
class RoleBindingConfig(object):
''' Handle rolebinding config '''
# pylint: disable=too-many-arguments
def __init__(self,
name,
namespace,
kubeconfig,
group_names=None,
role_ref=None,
subjects=None,
usernames=None):
''' constructor for handling rolebinding options '''
self.kubeconfig = kubeconfig
self.name = name
self.namespace = namespace
self.group_names = group_names
self.role_ref = role_ref
self.subjects = subjects
self.usernames = usernames
self.data = {}
self.create_dict()
def create_dict(self):
''' create a default rolebinding as a dict '''
self.data['apiVersion'] = 'v1'
self.data['kind'] = 'RoleBinding'
self.data['groupNames'] = self.group_names
self.data['metadata']['name'] = self.name
self.data['metadata']['namespace'] = self.namespace
self.data['roleRef'] = self.role_ref
self.data['subjects'] = self.subjects
self.data['userNames'] = self.usernames
# pylint: disable=too-many-instance-attributes,too-many-public-methods
class RoleBinding(Yedit):
''' Class to model a rolebinding openshift object'''
group_names_path = "groupNames"
role_ref_path = "roleRef"
subjects_path = "subjects"
user_names_path = "userNames"
kind = 'RoleBinding'
def __init__(self, content):
'''RoleBinding constructor'''
super(RoleBinding, self).__init__(content=content)
self._subjects = None
self._role_ref = None
self._group_names = None
self._user_names = None
@property
def subjects(self):
''' subjects property '''
if self._subjects is None:
self._subjects = self.get_subjects()
return self._subjects
@subjects.setter
def subjects(self, data):
''' subjects property setter'''
self._subjects = data
@property
def role_ref(self):
''' role_ref property '''
if self._role_ref is None:
self._role_ref = self.get_role_ref()
return self._role_ref
@role_ref.setter
def role_ref(self, data):
''' role_ref property setter'''
self._role_ref = data
@property
def group_names(self):
''' group_names property '''
if self._group_names is None:
self._group_names = self.get_group_names()
return self._group_names
@group_names.setter
def group_names(self, data):
''' group_names property setter'''
self._group_names = data
@property
def user_names(self):
''' user_names property '''
if self._user_names is None:
self._user_names = self.get_user_names()
return self._user_names
@user_names.setter
def user_names(self, data):
''' user_names property setter'''
self._user_names = data
def get_group_names(self):
''' return groupNames '''
return self.get(RoleBinding.group_names_path) or []
def get_user_names(self):
''' return usernames '''
return self.get(RoleBinding.user_names_path) or []
def get_role_ref(self):
''' return role_ref '''
return self.get(RoleBinding.role_ref_path) or {}
def get_subjects(self):
''' return subjects '''
return self.get(RoleBinding.subjects_path) or []
#### ADD #####
def add_subject(self, inc_subject):
''' add a subject '''
if self.subjects:
# pylint: disable=no-member
self.subjects.append(inc_subject)
else:
self.put(RoleBinding.subjects_path, [inc_subject])
return True
def add_role_ref(self, inc_role_ref):
''' add a role_ref '''
if not self.role_ref:
self.put(RoleBinding.role_ref_path, {"name": inc_role_ref})
return True
return False
def add_group_names(self, inc_group_names):
''' add a group_names '''
if self.group_names:
# pylint: disable=no-member
self.group_names.append(inc_group_names)
else:
self.put(RoleBinding.group_names_path, [inc_group_names])
return True
def add_user_name(self, inc_user_name):
''' add a username '''
if self.user_names:
# pylint: disable=no-member
self.user_names.append(inc_user_name)
else:
self.put(RoleBinding.user_names_path, [inc_user_name])
return True
#### /ADD #####
#### Remove #####
def remove_subject(self, inc_subject):
''' remove a subject '''
try:
# pylint: disable=no-member
self.subjects.remove(inc_subject)
except ValueError as _:
return False
return True
def remove_role_ref(self, inc_role_ref):
''' remove a role_ref '''
if self.role_ref and self.role_ref['name'] == inc_role_ref:
del self.role_ref['name']
return True
return False
def remove_group_name(self, inc_group_name):
''' remove a groupname '''
try:
# pylint: disable=no-member
self.group_names.remove(inc_group_name)
except ValueError as _:
return False
return True
def remove_user_name(self, inc_user_name):
''' remove a username '''
try:
# pylint: disable=no-member
self.user_names.remove(inc_user_name)
except ValueError as _:
return False
return True
#### /REMOVE #####
#### UPDATE #####
def update_subject(self, inc_subject):
''' update a subject '''
try:
# pylint: disable=no-member
index = self.subjects.index(inc_subject)
except ValueError as _:
return self.add_subject(inc_subject)
self.subjects[index] = inc_subject
return True
def update_group_name(self, inc_group_name):
''' update a groupname '''
try:
# pylint: disable=no-member
index = self.group_names.index(inc_group_name)
except ValueError as _:
return self.add_group_names(inc_group_name)
self.group_names[index] = inc_group_name
return True
def update_user_name(self, inc_user_name):
''' update a username '''
try:
# pylint: disable=no-member
index = self.user_names.index(inc_user_name)
except ValueError as _:
return self.add_user_name(inc_user_name)
self.user_names[index] = inc_user_name
return True
def update_role_ref(self, inc_role_ref):
''' update a role_ref '''
self.role_ref['name'] = inc_role_ref
return True
#### /UPDATE #####
#### FIND ####
def find_subject(self, inc_subject):
''' find a subject '''
index = None
try:
# pylint: disable=no-member
index = self.subjects.index(inc_subject)
except ValueError as _:
return index
return index
def find_group_name(self, inc_group_name):
''' find a group_name '''
index = None
try:
# pylint: disable=no-member
index = self.group_names.index(inc_group_name)
except ValueError as _:
return index
return index
def find_user_name(self, inc_user_name):
''' find a user_name '''
index = None
try:
# pylint: disable=no-member
index = self.user_names.index(inc_user_name)
except ValueError as _:
return index
return index
def find_role_ref(self, inc_role_ref):
''' find a user_name '''
if self.role_ref and self.role_ref['name'] == inc_role_ref['name']:
return self.role_ref
return None
# -*- -*- -*- End included fragment: lib/rolebinding.py -*- -*- -*-
# -*- -*- -*- Begin included fragment: lib/scc.py -*- -*- -*-
# pylint: disable=too-many-instance-attributes
class SecurityContextConstraintsConfig(object):
''' Handle scc options '''
# pylint: disable=too-many-arguments
def __init__(self,
sname,
kubeconfig,
options=None,
fs_group='MustRunAs',
default_add_capabilities=None,
groups=None,
priority=None,
required_drop_capabilities=None,
run_as_user='MustRunAsRange',
se_linux_context='MustRunAs',
supplemental_groups='RunAsAny',
users=None,
annotations=None):
''' constructor for handling scc options '''
self.kubeconfig = kubeconfig
self.name = sname
self.options = options
self.fs_group = fs_group
self.default_add_capabilities = default_add_capabilities
self.groups = groups
self.priority = priority
self.required_drop_capabilities = required_drop_capabilities
self.run_as_user = run_as_user
self.se_linux_context = se_linux_context
self.supplemental_groups = supplemental_groups
self.users = users
self.annotations = annotations
self.data = {}
self.create_dict()
def create_dict(self):
''' assign the correct properties for a scc dict '''
# allow options
if self.options:
for key, value in self.options.items():
self.data[key] = value
else:
self.data['allowHostDirVolumePlugin'] = False
self.data['allowHostIPC'] = False
self.data['allowHostNetwork'] = False
self.data['allowHostPID'] = False
self.data['allowHostPorts'] = False
self.data['allowPrivilegedContainer'] = False
self.data['allowedCapabilities'] = None
# version
self.data['apiVersion'] = 'v1'
# kind
self.data['kind'] = 'SecurityContextConstraints'
# defaultAddCapabilities
self.data['defaultAddCapabilities'] = self.default_add_capabilities
# fsGroup
self.data['fsGroup']['type'] = self.fs_group
# groups
self.data['groups'] = []
if self.groups:
self.data['groups'] = self.groups
# metadata
self.data['metadata'] = {}
self.data['metadata']['name'] = self.name
if self.annotations:
for key, value in self.annotations.items():
self.data['metadata'][key] = value
# priority
self.data['priority'] = self.priority
# requiredDropCapabilities
self.data['requiredDropCapabilities'] = self.required_drop_capabilities
# runAsUser
self.data['runAsUser'] = {'type': self.run_as_user}
# seLinuxContext
self.data['seLinuxContext'] = {'type': self.se_linux_context}
# supplementalGroups
self.data['supplementalGroups'] = {'type': self.supplemental_groups}
# users
self.data['users'] = []
if self.users:
self.data['users'] = self.users
# pylint: disable=too-many-instance-attributes,too-many-public-methods,no-member
class SecurityContextConstraints(Yedit):
''' Class to wrap the oc command line tools '''
default_add_capabilities_path = "defaultAddCapabilities"
fs_group_path = "fsGroup"
groups_path = "groups"
priority_path = "priority"
required_drop_capabilities_path = "requiredDropCapabilities"
run_as_user_path = "runAsUser"
se_linux_context_path = "seLinuxContext"
supplemental_groups_path = "supplementalGroups"
users_path = "users"
kind = 'SecurityContextConstraints'
def __init__(self, content):
'''SecurityContextConstraints constructor'''
super(SecurityContextConstraints, self).__init__(content=content)
self._users = None
self._groups = None
@property
def users(self):
''' users property getter '''
if self._users is None:
self._users = self.get_users()
return self._users
@property
def groups(self):
''' groups property getter '''
if self._groups is None:
self._groups = self.get_groups()
return self._groups
@users.setter
def users(self, data):
''' users property setter'''
self._users = data
@groups.setter
def groups(self, data):
''' groups property setter'''
self._groups = data
def get_users(self):
'''get scc users'''
return self.get(SecurityContextConstraints.users_path) or []
def get_groups(self):
'''get scc groups'''
return self.get(SecurityContextConstraints.groups_path) or []
def add_user(self, inc_user):
''' add a user '''
if self.users:
self.users.append(inc_user)
else:
self.put(SecurityContextConstraints.users_path, [inc_user])
return True
def add_group(self, inc_group):
''' add a group '''
if self.groups:
self.groups.append(inc_group)
else:
self.put(SecurityContextConstraints.groups_path, [inc_group])
return True
def remove_user(self, inc_user):
''' remove a user '''
try:
self.users.remove(inc_user)
except ValueError as _:
return False
return True
def remove_group(self, inc_group):
''' remove a group '''
try:
self.groups.remove(inc_group)
except ValueError as _:
return False
return True
def update_user(self, inc_user):
''' update a user '''
try:
index = self.users.index(inc_user)
except ValueError as _:
return self.add_user(inc_user)
self.users[index] = inc_user
return True
def update_group(self, inc_group):
''' update a group '''
try:
index = self.groups.index(inc_group)
except ValueError as _:
return self.add_group(inc_group)
self.groups[index] = inc_group
return True
def find_user(self, inc_user):
''' find a user '''
index = None
try:
index = self.users.index(inc_user)
except ValueError as _:
return index
return index
def find_group(self, inc_group):
''' find a group '''
index = None
try:
index = self.groups.index(inc_group)
except ValueError as _:
return index
return index
# -*- -*- -*- End included fragment: lib/scc.py -*- -*- -*-
# -*- -*- -*- Begin included fragment: class/oc_adm_policy_group.py -*- -*- -*-
class PolicyGroupException(Exception):
''' PolicyGroup exception'''
pass
class PolicyGroupConfig(OpenShiftCLIConfig):
''' PolicyGroupConfig is a DTO for group related policy. '''
def __init__(self, namespace, kubeconfig, policy_options):
super(PolicyGroupConfig, self).__init__(policy_options['name']['value'],
namespace, kubeconfig, policy_options)
self.kind = self.get_kind()
self.namespace = namespace
def get_kind(self):
''' return the kind we are working with '''
if self.config_options['resource_kind']['value'] == 'role':
return 'rolebinding'
elif self.config_options['resource_kind']['value'] == 'cluster-role':
return 'clusterrolebinding'
elif self.config_options['resource_kind']['value'] == 'scc':
return 'scc'
return None
# pylint: disable=too-many-return-statements
class PolicyGroup(OpenShiftCLI):
''' Class to handle attaching policies to users '''
def __init__(self,
config,
verbose=False):
''' Constructor for PolicyGroup '''
super(PolicyGroup, self).__init__(config.namespace, config.kubeconfig, verbose)
self.config = config
self.verbose = verbose
self._rolebinding = None
self._scc = None
self._cluster_role_bindings = None
self._role_bindings = None
@property
def rolebindings(self):
if self._role_bindings is None:
results = self._get('rolebindings', None)
if results['returncode'] != 0:
raise OpenShiftCLIError('Could not retrieve rolebindings')
self._role_bindings = results['results'][0]['items']
return self._role_bindings
@property
def clusterrolebindings(self):
if self._cluster_role_bindings is None:
results = self._get('clusterrolebindings', None)
if results['returncode'] != 0:
raise OpenShiftCLIError('Could not retrieve clusterrolebindings')
self._cluster_role_bindings = results['results'][0]['items']
return self._cluster_role_bindings
@property
def role_binding(self):
''' role_binding getter '''
return self._rolebinding
@role_binding.setter
def role_binding(self, binding):
''' role_binding setter '''
self._rolebinding = binding
@property
def security_context_constraint(self):
''' security_context_constraint getter '''
return self._scc
@security_context_constraint.setter
def security_context_constraint(self, scc):
''' security_context_constraint setter '''
self._scc = scc
def get(self):
'''fetch the desired kind'''
resource_name = self.config.config_options['name']['value']
if resource_name == 'cluster-reader':
resource_name += 's'
# oc adm policy add-... creates policy bindings with the name
# "[resource_name]-binding", however some bindings in the system
# simply use "[resource_name]". So try both.
results = self._get(self.config.kind, resource_name)
if results['returncode'] == 0:
return results
# Now try -binding naming convention
return self._get(self.config.kind, resource_name + "-binding")
def exists_role_binding(self):
''' return whether role_binding exists '''
bindings = None
if self.config.config_options['resource_kind']['value'] == 'cluster-role':
bindings = self.clusterrolebindings
else:
bindings = self.rolebindings
if bindings is None:
return False
for binding in bindings:
if self.config.config_options['rolebinding_name']['value'] is not None and \
binding['metadata']['name'] != self.config.config_options['rolebinding_name']['value']:
continue
if binding['roleRef']['name'] == self.config.config_options['name']['value'] and \
binding['groupNames'] is not None and \
self.config.config_options['group']['value'] in binding['groupNames']:
self.role_binding = binding
return True
return False
def exists_scc(self):
''' return whether scc exists '''
results = self.get()
if results['returncode'] == 0:
self.security_context_constraint = SecurityContextConstraints(results['results'][0])
if self.security_context_constraint.find_group(self.config.config_options['group']['value']) != None:
return True
return False
return results
def exists(self):
'''does the object exist?'''
if self.config.config_options['resource_kind']['value'] == 'cluster-role':
return self.exists_role_binding()
elif self.config.config_options['resource_kind']['value'] == 'role':
return self.exists_role_binding()
elif self.config.config_options['resource_kind']['value'] == 'scc':
return self.exists_scc()
return False
def perform(self):
'''perform action on resource'''
cmd = ['policy',
self.config.config_options['action']['value'],
self.config.config_options['name']['value'],
self.config.config_options['group']['value']]
if self.config.config_options['rolebinding_name']['value'] is not None:
cmd.extend(['--rolebinding-name', self.config.config_options['rolebinding_name']['value']])
return self.openshift_cmd(cmd, oadm=True)
@staticmethod
def run_ansible(params, check_mode):
'''run the oc_adm_policy_group module'''
state = params['state']
action = None
if state == 'present':
action = 'add-' + params['resource_kind'] + '-to-group'
else:
action = 'remove-' + params['resource_kind'] + '-from-group'
nconfig = PolicyGroupConfig(params['namespace'],
params['kubeconfig'],
{'action': {'value': action, 'include': False},
'group': {'value': params['group'], 'include': False},
'resource_kind': {'value': params['resource_kind'], 'include': False},
'name': {'value': params['resource_name'], 'include': False},
'rolebinding_name': {'value': params['rolebinding_name'], 'include': False},
})
policygroup = PolicyGroup(nconfig, params['debug'])
# Run the oc adm policy group related command
########
# Delete
########
if state == 'absent':
if not policygroup.exists():
return {'changed': False, 'state': 'absent'}
if check_mode:
return {'changed': False, 'msg': 'CHECK_MODE: would have performed a delete.'}
api_rval = policygroup.perform()
if api_rval['returncode'] != 0:
return {'msg': api_rval}
return {'changed': True, 'results' : api_rval, state:'absent'}
if state == 'present':
########
# Create
########
results = policygroup.exists()
if isinstance(results, dict) and 'returncode' in results and results['returncode'] != 0:
return {'msg': results}
if not results:
if check_mode:
return {'changed': False, 'msg': 'CHECK_MODE: would have performed a create.'}
api_rval = policygroup.perform()
if api_rval['returncode'] != 0:
return {'msg': api_rval}
return {'changed': True, 'results': api_rval, state: 'present'}
return {'changed': False, state: 'present'}
return {'failed': True, 'changed': False, 'results': 'Unknown state passed. %s' % state, state: 'unknown'}
# -*- -*- -*- End included fragment: class/oc_adm_policy_group.py -*- -*- -*-
# -*- -*- -*- Begin included fragment: ansible/oc_adm_policy_group.py -*- -*- -*-
def main():
'''
ansible oc adm module for group policy
'''
module = AnsibleModule(
argument_spec=dict(
state=dict(default='present', type='str',
choices=['present', 'absent']),
debug=dict(default=False, type='bool'),
resource_name=dict(required=True, type='str'),
namespace=dict(default='default', type='str'),
kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
group=dict(required=True, type='str'),
resource_kind=dict(required=True, choices=['role', 'cluster-role', 'scc'], type='str'),
rolebinding_name=dict(default=None, type='str'),
),
supports_check_mode=True,
)
results = PolicyGroup.run_ansible(module.params, module.check_mode)
if 'failed' in results:
module.fail_json(**results)
module.exit_json(**results)
if __name__ == "__main__":
main()
# -*- -*- -*- End included fragment: ansible/oc_adm_policy_group.py -*- -*- -*-
|
unknown
|
codeparrot/codeparrot-clean
| ||
#!/usr/bin/env python
""" This module tries to retrieve as much platform-identifying data as
possible. It makes this information available via function APIs.
If called from the command line, it prints the platform
information concatenated as single string to stdout. The output
format is useable as part of a filename.
"""
# This module is maintained by Marc-Andre Lemburg <mal@egenix.com>.
# If you find problems, please submit bug reports/patches via the
# Python bug tracker (http://bugs.python.org) and assign them to "lemburg".
#
# Note: Please keep this module compatible to Python 1.5.2.
#
# Still needed:
# * more support for WinCE
# * support for MS-DOS (PythonDX ?)
# * support for Amiga and other still unsupported platforms running Python
# * support for additional Linux distributions
#
# Many thanks to all those who helped adding platform-specific
# checks (in no particular order):
#
# Charles G Waldman, David Arnold, Gordon McMillan, Ben Darnell,
# Jeff Bauer, Cliff Crawford, Ivan Van Laningham, Josef
# Betancourt, Randall Hopper, Karl Putland, John Farrell, Greg
# Andruk, Just van Rossum, Thomas Heller, Mark R. Levinson, Mark
# Hammond, Bill Tutt, Hans Nowak, Uwe Zessin (OpenVMS support),
# Colin Kong, Trent Mick, Guido van Rossum, Anthony Baxter
#
# History:
#
# <see CVS and SVN checkin messages for history>
#
# 1.0.7 - added DEV_NULL
# 1.0.6 - added linux_distribution()
# 1.0.5 - fixed Java support to allow running the module on Jython
# 1.0.4 - added IronPython support
# 1.0.3 - added normalization of Windows system name
# 1.0.2 - added more Windows support
# 1.0.1 - reformatted to make doc.py happy
# 1.0.0 - reformatted a bit and checked into Python CVS
# 0.8.0 - added sys.version parser and various new access
# APIs (python_version(), python_compiler(), etc.)
# 0.7.2 - fixed architecture() to use sizeof(pointer) where available
# 0.7.1 - added support for Caldera OpenLinux
# 0.7.0 - some fixes for WinCE; untabified the source file
# 0.6.2 - support for OpenVMS - requires version 1.5.2-V006 or higher and
# vms_lib.getsyi() configured
# 0.6.1 - added code to prevent 'uname -p' on platforms which are
# known not to support it
# 0.6.0 - fixed win32_ver() to hopefully work on Win95,98,NT and Win2k;
# did some cleanup of the interfaces - some APIs have changed
# 0.5.5 - fixed another type in the MacOS code... should have
# used more coffee today ;-)
# 0.5.4 - fixed a few typos in the MacOS code
# 0.5.3 - added experimental MacOS support; added better popen()
# workarounds in _syscmd_ver() -- still not 100% elegant
# though
# 0.5.2 - fixed uname() to return '' instead of 'unknown' in all
# return values (the system uname command tends to return
# 'unknown' instead of just leaving the field emtpy)
# 0.5.1 - included code for slackware dist; added exception handlers
# to cover up situations where platforms don't have os.popen
# (e.g. Mac) or fail on socket.gethostname(); fixed libc
# detection RE
# 0.5.0 - changed the API names referring to system commands to *syscmd*;
# added java_ver(); made syscmd_ver() a private
# API (was system_ver() in previous versions) -- use uname()
# instead; extended the win32_ver() to also return processor
# type information
# 0.4.0 - added win32_ver() and modified the platform() output for WinXX
# 0.3.4 - fixed a bug in _follow_symlinks()
# 0.3.3 - fixed popen() and "file" command invokation bugs
# 0.3.2 - added architecture() API and support for it in platform()
# 0.3.1 - fixed syscmd_ver() RE to support Windows NT
# 0.3.0 - added system alias support
# 0.2.3 - removed 'wince' again... oh well.
# 0.2.2 - added 'wince' to syscmd_ver() supported platforms
# 0.2.1 - added cache logic and changed the platform string format
# 0.2.0 - changed the API to use functions instead of module globals
# since some action take too long to be run on module import
# 0.1.0 - first release
#
# You can always get the latest version of this module at:
#
# http://www.egenix.com/files/python/platform.py
#
# If that URL should fail, try contacting the author.
__copyright__ = """
Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:info@egenix.com
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee or royalty is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation or portions thereof, including modifications,
that you make.
EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
"""
__version__ = '1.0.7'
import sys,string,os,re
### Globals & Constants
# Determine the platform's /dev/null device
try:
DEV_NULL = os.devnull
except AttributeError:
# os.devnull was added in Python 2.4, so emulate it for earlier
# Python versions
if sys.platform in ('dos','win32','win16','os2'):
# Use the old CP/M NUL as device name
DEV_NULL = 'NUL'
else:
# Standard Unix uses /dev/null
DEV_NULL = '/dev/null'
### Platform specific APIs
_libc_search = re.compile(r'(__libc_init)'
'|'
'(GLIBC_([0-9.]+))'
'|'
'(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)')
def libc_ver(executable=sys.executable,lib='',version='',
chunksize=2048):
""" Tries to determine the libc version that the file executable
(which defaults to the Python interpreter) is linked against.
Returns a tuple of strings (lib,version) which default to the
given parameters in case the lookup fails.
Note that the function has intimate knowledge of how different
libc versions add symbols to the executable and thus is probably
only useable for executables compiled using gcc.
The file is read and scanned in chunks of chunksize bytes.
"""
if hasattr(os.path, 'realpath'):
# Python 2.2 introduced os.path.realpath(); it is used
# here to work around problems with Cygwin not being
# able to open symlinks for reading
executable = os.path.realpath(executable)
f = open(executable,'rb')
binary = f.read(chunksize)
pos = 0
while 1:
m = _libc_search.search(binary,pos)
if not m:
binary = f.read(chunksize)
if not binary:
break
pos = 0
continue
libcinit,glibc,glibcversion,so,threads,soversion = m.groups()
if libcinit and not lib:
lib = 'libc'
elif glibc:
if lib != 'glibc':
lib = 'glibc'
version = glibcversion
elif glibcversion > version:
version = glibcversion
elif so:
if lib != 'glibc':
lib = 'libc'
if soversion and soversion > version:
version = soversion
if threads and version[-len(threads):] != threads:
version = version + threads
pos = m.end()
f.close()
return lib,version
def _dist_try_harder(distname,version,id):
""" Tries some special tricks to get the distribution
information in case the default method fails.
Currently supports older SuSE Linux, Caldera OpenLinux and
Slackware Linux distributions.
"""
if os.path.exists('/var/adm/inst-log/info'):
# SuSE Linux stores distribution information in that file
info = open('/var/adm/inst-log/info').readlines()
distname = 'SuSE'
for line in info:
tv = string.split(line)
if len(tv) == 2:
tag,value = tv
else:
continue
if tag == 'MIN_DIST_VERSION':
version = string.strip(value)
elif tag == 'DIST_IDENT':
values = string.split(value,'-')
id = values[2]
return distname,version,id
if os.path.exists('/etc/.installed'):
# Caldera OpenLinux has some infos in that file (thanks to Colin Kong)
info = open('/etc/.installed').readlines()
for line in info:
pkg = string.split(line,'-')
if len(pkg) >= 2 and pkg[0] == 'OpenLinux':
# XXX does Caldera support non Intel platforms ? If yes,
# where can we find the needed id ?
return 'OpenLinux',pkg[1],id
if os.path.isdir('/usr/lib/setup'):
# Check for slackware verson tag file (thanks to Greg Andruk)
verfiles = os.listdir('/usr/lib/setup')
for n in range(len(verfiles)-1, -1, -1):
if verfiles[n][:14] != 'slack-version-':
del verfiles[n]
if verfiles:
verfiles.sort()
distname = 'slackware'
version = verfiles[-1][14:]
return distname,version,id
return distname,version,id
_release_filename = re.compile(r'(\w+)[-_](release|version)')
_lsb_release_version = re.compile(r'(.+)'
' release '
'([\d.]+)'
'[^(]*(?:\((.+)\))?')
_release_version = re.compile(r'([^0-9]+)'
'(?: release )?'
'([\d.]+)'
'[^(]*(?:\((.+)\))?')
# See also http://www.novell.com/coolsolutions/feature/11251.html
# and http://linuxmafia.com/faq/Admin/release-files.html
# and http://data.linux-ntfs.org/rpm/whichrpm
# and http://www.die.net/doc/linux/man/man1/lsb_release.1.html
_supported_dists = (
'SuSE', 'debian', 'fedora', 'redhat', 'centos',
'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo',
'UnitedLinux', 'turbolinux')
def _parse_release_file(firstline):
# Default to empty 'version' and 'id' strings. Both defaults are used
# when 'firstline' is empty. 'id' defaults to empty when an id can not
# be deduced.
version = ''
id = ''
# Parse the first line
m = _lsb_release_version.match(firstline)
if m is not None:
# LSB format: "distro release x.x (codename)"
return tuple(m.groups())
# Pre-LSB format: "distro x.x (codename)"
m = _release_version.match(firstline)
if m is not None:
return tuple(m.groups())
# Unkown format... take the first two words
l = string.split(string.strip(firstline))
if l:
version = l[0]
if len(l) > 1:
id = l[1]
return '', version, id
def linux_distribution(distname='', version='', id='',
supported_dists=_supported_dists,
full_distribution_name=1):
""" Tries to determine the name of the Linux OS distribution name.
The function first looks for a distribution release file in
/etc and then reverts to _dist_try_harder() in case no
suitable files are found.
supported_dists may be given to define the set of Linux
distributions to look for. It defaults to a list of currently
supported Linux distributions identified by their release file
name.
If full_distribution_name is true (default), the full
distribution read from the OS is returned. Otherwise the short
name taken from supported_dists is used.
Returns a tuple (distname,version,id) which default to the
args given as parameters.
"""
try:
etc = os.listdir('/etc')
except os.error:
# Probably not a Unix system
return distname,version,id
etc.sort()
for file in etc:
m = _release_filename.match(file)
if m is not None:
_distname,dummy = m.groups()
if _distname in supported_dists:
distname = _distname
break
else:
return _dist_try_harder(distname,version,id)
# Read the first line
f = open('/etc/'+file, 'r')
firstline = f.readline()
f.close()
_distname, _version, _id = _parse_release_file(firstline)
if _distname and full_distribution_name:
distname = _distname
if _version:
version = _version
if _id:
id = _id
return distname, version, id
# To maintain backwards compatibility:
def dist(distname='',version='',id='',
supported_dists=_supported_dists):
""" Tries to determine the name of the Linux OS distribution name.
The function first looks for a distribution release file in
/etc and then reverts to _dist_try_harder() in case no
suitable files are found.
Returns a tuple (distname,version,id) which default to the
args given as parameters.
"""
return linux_distribution(distname, version, id,
supported_dists=supported_dists,
full_distribution_name=0)
class _popen:
""" Fairly portable (alternative) popen implementation.
This is mostly needed in case os.popen() is not available, or
doesn't work as advertised, e.g. in Win9X GUI programs like
PythonWin or IDLE.
Writing to the pipe is currently not supported.
"""
tmpfile = ''
pipe = None
bufsize = None
mode = 'r'
def __init__(self,cmd,mode='r',bufsize=None):
if mode != 'r':
raise ValueError,'popen()-emulation only supports read mode'
import tempfile
self.tmpfile = tmpfile = tempfile.mktemp()
os.system(cmd + ' > %s' % tmpfile)
self.pipe = open(tmpfile,'rb')
self.bufsize = bufsize
self.mode = mode
def read(self):
return self.pipe.read()
def readlines(self):
if self.bufsize is not None:
return self.pipe.readlines()
def close(self,
remove=os.unlink,error=os.error):
if self.pipe:
rc = self.pipe.close()
else:
rc = 255
if self.tmpfile:
try:
remove(self.tmpfile)
except error:
pass
return rc
# Alias
__del__ = close
def popen(cmd, mode='r', bufsize=None):
""" Portable popen() interface.
"""
# Find a working popen implementation preferring win32pipe.popen
# over os.popen over _popen
popen = None
if os.environ.get('OS','') == 'Windows_NT':
# On NT win32pipe should work; on Win9x it hangs due to bugs
# in the MS C lib (see MS KnowledgeBase article Q150956)
try:
import win32pipe
except ImportError:
pass
else:
popen = win32pipe.popen
if popen is None:
if hasattr(os,'popen'):
popen = os.popen
# Check whether it works... it doesn't in GUI programs
# on Windows platforms
if sys.platform == 'win32': # XXX Others too ?
try:
popen('')
except os.error:
popen = _popen
else:
popen = _popen
if bufsize is None:
return popen(cmd,mode)
else:
return popen(cmd,mode,bufsize)
def _norm_version(version, build=''):
""" Normalize the version and build strings and return a single
version string using the format major.minor.build (or patchlevel).
"""
l = string.split(version,'.')
if build:
l.append(build)
try:
ints = map(int,l)
except ValueError:
strings = l
else:
strings = map(str,ints)
version = string.join(strings[:3],'.')
return version
_ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
'.*'
'\[.* ([\d.]+)\])')
# Examples of VER command output:
#
# Windows 2000: Microsoft Windows 2000 [Version 5.00.2195]
# Windows XP: Microsoft Windows XP [Version 5.1.2600]
# Windows Vista: Microsoft Windows [Version 6.0.6002]
#
# Note that the "Version" string gets localized on different
# Windows versions.
def _syscmd_ver(system='', release='', version='',
supported_platforms=('win32','win16','dos','os2')):
""" Tries to figure out the OS version used and returns
a tuple (system,release,version).
It uses the "ver" shell command for this which is known
to exists on Windows, DOS and OS/2. XXX Others too ?
In case this fails, the given parameters are used as
defaults.
"""
if sys.platform not in supported_platforms:
return system,release,version
# Try some common cmd strings
for cmd in ('ver','command /c ver','cmd /c ver'):
try:
pipe = popen(cmd)
info = pipe.read()
if pipe.close():
raise os.error,'command failed'
# XXX How can I suppress shell errors from being written
# to stderr ?
except os.error,why:
#print 'Command %s failed: %s' % (cmd,why)
continue
except IOError,why:
#print 'Command %s failed: %s' % (cmd,why)
continue
else:
break
else:
return system,release,version
# Parse the output
info = string.strip(info)
m = _ver_output.match(info)
if m is not None:
system,release,version = m.groups()
# Strip trailing dots from version and release
if release[-1] == '.':
release = release[:-1]
if version[-1] == '.':
version = version[:-1]
# Normalize the version and build strings (eliminating additional
# zeros)
version = _norm_version(version)
return system,release,version
def _win32_getvalue(key,name,default=''):
""" Read a value for name from the registry key.
In case this fails, default is returned.
"""
try:
# Use win32api if available
from win32api import RegQueryValueEx
except ImportError:
# On Python 2.0 and later, emulate using _winreg
import _winreg
RegQueryValueEx = _winreg.QueryValueEx
try:
return RegQueryValueEx(key,name)
except:
return default
def win32_ver(release='',version='',csd='',ptype=''):
""" Get additional version information from the Windows Registry
and return a tuple (version,csd,ptype) referring to version
number, CSD level (service pack), and OS type (multi/single
processor).
As a hint: ptype returns 'Uniprocessor Free' on single
processor NT machines and 'Multiprocessor Free' on multi
processor machines. The 'Free' refers to the OS version being
free of debugging code. It could also state 'Checked' which
means the OS version uses debugging code, i.e. code that
checks arguments, ranges, etc. (Thomas Heller).
Note: this function works best with Mark Hammond's win32
package installed, but also on Python 2.3 and later. It
obviously only runs on Win32 compatible platforms.
"""
# XXX Is there any way to find out the processor type on WinXX ?
# XXX Is win32 available on Windows CE ?
#
# Adapted from code posted by Karl Putland to comp.lang.python.
#
# The mappings between reg. values and release names can be found
# here: http://msdn.microsoft.com/library/en-us/sysinfo/base/osversioninfo_str.asp
# Import the needed APIs
try:
import win32api
from win32api import RegQueryValueEx, RegOpenKeyEx, \
RegCloseKey, GetVersionEx
from win32con import HKEY_LOCAL_MACHINE, VER_PLATFORM_WIN32_NT, \
VER_PLATFORM_WIN32_WINDOWS, VER_NT_WORKSTATION
except ImportError:
# Emulate the win32api module using Python APIs
try:
sys.getwindowsversion
except AttributeError:
# No emulation possible, so return the defaults...
return release,version,csd,ptype
else:
# Emulation using _winreg (added in Python 2.0) and
# sys.getwindowsversion() (added in Python 2.3)
import _winreg
GetVersionEx = sys.getwindowsversion
RegQueryValueEx = _winreg.QueryValueEx
RegOpenKeyEx = _winreg.OpenKeyEx
RegCloseKey = _winreg.CloseKey
HKEY_LOCAL_MACHINE = _winreg.HKEY_LOCAL_MACHINE
VER_PLATFORM_WIN32_WINDOWS = 1
VER_PLATFORM_WIN32_NT = 2
VER_NT_WORKSTATION = 1
VER_NT_SERVER = 3
REG_SZ = 1
# Find out the registry key and some general version infos
winver = GetVersionEx()
maj,min,buildno,plat,csd = winver
version = '%i.%i.%i' % (maj,min,buildno & 0xFFFF)
if hasattr(winver, "service_pack"):
if winver.service_pack != "":
csd = 'SP%s' % winver.service_pack_major
else:
if csd[:13] == 'Service Pack ':
csd = 'SP' + csd[13:]
if plat == VER_PLATFORM_WIN32_WINDOWS:
regkey = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
# Try to guess the release name
if maj == 4:
if min == 0:
release = '95'
elif min == 10:
release = '98'
elif min == 90:
release = 'Me'
else:
release = 'postMe'
elif maj == 5:
release = '2000'
elif plat == VER_PLATFORM_WIN32_NT:
regkey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'
if maj <= 4:
release = 'NT'
elif maj == 5:
if min == 0:
release = '2000'
elif min == 1:
release = 'XP'
elif min == 2:
release = '2003Server'
else:
release = 'post2003'
elif maj == 6:
if hasattr(winver, "product_type"):
product_type = winver.product_type
else:
product_type = VER_NT_WORKSTATION
# Without an OSVERSIONINFOEX capable sys.getwindowsversion(),
# or help from the registry, we cannot properly identify
# non-workstation versions.
try:
key = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
name, type = RegQueryValueEx(key, "ProductName")
# Discard any type that isn't REG_SZ
if type == REG_SZ and name.find("Server") != -1:
product_type = VER_NT_SERVER
except WindowsError:
# Use default of VER_NT_WORKSTATION
pass
if min == 0:
if product_type == VER_NT_WORKSTATION:
release = 'Vista'
else:
release = '2008Server'
elif min == 1:
if product_type == VER_NT_WORKSTATION:
release = '7'
else:
release = '2008ServerR2'
elif min == 2:
if product_type == VER_NT_WORKSTATION:
release = '8'
else:
release = '2012Server'
else:
release = 'post2012Server'
else:
if not release:
# E.g. Win3.1 with win32s
release = '%i.%i' % (maj,min)
return release,version,csd,ptype
# Open the registry key
try:
keyCurVer = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regkey)
# Get a value to make sure the key exists...
RegQueryValueEx(keyCurVer, 'SystemRoot')
except:
return release,version,csd,ptype
# Parse values
#subversion = _win32_getvalue(keyCurVer,
# 'SubVersionNumber',
# ('',1))[0]
#if subversion:
# release = release + subversion # 95a, 95b, etc.
build = _win32_getvalue(keyCurVer,
'CurrentBuildNumber',
('',1))[0]
ptype = _win32_getvalue(keyCurVer,
'CurrentType',
(ptype,1))[0]
# Normalize version
version = _norm_version(version,build)
# Close key
RegCloseKey(keyCurVer)
return release,version,csd,ptype
def _mac_ver_lookup(selectors,default=None):
from gestalt import gestalt
import MacOS
l = []
append = l.append
for selector in selectors:
try:
append(gestalt(selector))
except (RuntimeError, MacOS.Error):
append(default)
return l
def _bcd2str(bcd):
return hex(bcd)[2:]
def _mac_ver_gestalt():
"""
Thanks to Mark R. Levinson for mailing documentation links and
code examples for this function. Documentation for the
gestalt() API is available online at:
http://www.rgaros.nl/gestalt/
"""
# Check whether the version info module is available
try:
import gestalt
import MacOS
except ImportError:
return None
# Get the infos
sysv,sysa = _mac_ver_lookup(('sysv','sysa'))
# Decode the infos
if sysv:
major = (sysv & 0xFF00) >> 8
minor = (sysv & 0x00F0) >> 4
patch = (sysv & 0x000F)
if (major, minor) >= (10, 4):
# the 'sysv' gestald cannot return patchlevels
# higher than 9. Apple introduced 3 new
# gestalt codes in 10.4 to deal with this
# issue (needed because patch levels can
# run higher than 9, such as 10.4.11)
major,minor,patch = _mac_ver_lookup(('sys1','sys2','sys3'))
release = '%i.%i.%i' %(major, minor, patch)
else:
release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
if sysa:
machine = {0x1: '68k',
0x2: 'PowerPC',
0xa: 'i386'}.get(sysa,'')
versioninfo=('', '', '')
return release,versioninfo,machine
def _mac_ver_xml():
fn = '/System/Library/CoreServices/SystemVersion.plist'
if not os.path.exists(fn):
return None
try:
import plistlib
except ImportError:
return None
pl = plistlib.readPlist(fn)
release = pl['ProductVersion']
versioninfo=('', '', '')
machine = os.uname()[4]
if machine in ('ppc', 'Power Macintosh'):
# for compatibility with the gestalt based code
machine = 'PowerPC'
return release,versioninfo,machine
def mac_ver(release='',versioninfo=('','',''),machine=''):
""" Get MacOS version information and return it as tuple (release,
versioninfo, machine) with versioninfo being a tuple (version,
dev_stage, non_release_version).
Entries which cannot be determined are set to the paramter values
which default to ''. All tuple entries are strings.
"""
# First try reading the information from an XML file which should
# always be present
info = _mac_ver_xml()
if info is not None:
return info
# If that doesn't work for some reason fall back to reading the
# information using gestalt calls.
info = _mac_ver_gestalt()
if info is not None:
return info
# If that also doesn't work return the default values
return release,versioninfo,machine
def _java_getprop(name,default):
from java.lang import System
try:
value = System.getProperty(name)
if value is None:
return default
return value
except AttributeError:
return default
def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):
""" Version interface for Jython.
Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being
a tuple (vm_name,vm_release,vm_vendor) and osinfo being a
tuple (os_name,os_version,os_arch).
Values which cannot be determined are set to the defaults
given as parameters (which all default to '').
"""
# Import the needed APIs
try:
import java.lang
except ImportError:
return release,vendor,vminfo,osinfo
vendor = _java_getprop('java.vendor', vendor)
release = _java_getprop('java.version', release)
vm_name, vm_release, vm_vendor = vminfo
vm_name = _java_getprop('java.vm.name', vm_name)
vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
vm_release = _java_getprop('java.vm.version', vm_release)
vminfo = vm_name, vm_release, vm_vendor
os_name, os_version, os_arch = osinfo
os_arch = _java_getprop('java.os.arch', os_arch)
os_name = _java_getprop('java.os.name', os_name)
os_version = _java_getprop('java.os.version', os_version)
osinfo = os_name, os_version, os_arch
return release, vendor, vminfo, osinfo
### System name aliasing
def system_alias(system,release,version):
""" Returns (system,release,version) aliased to common
marketing names used for some systems.
It also does some reordering of the information in some cases
where it would otherwise cause confusion.
"""
if system == 'Rhapsody':
# Apple's BSD derivative
# XXX How can we determine the marketing release number ?
return 'MacOS X Server',system+release,version
elif system == 'SunOS':
# Sun's OS
if release < '5':
# These releases use the old name SunOS
return system,release,version
# Modify release (marketing release = SunOS release - 3)
l = string.split(release,'.')
if l:
try:
major = int(l[0])
except ValueError:
pass
else:
major = major - 3
l[0] = str(major)
release = string.join(l,'.')
if release < '6':
system = 'Solaris'
else:
# XXX Whatever the new SunOS marketing name is...
system = 'Solaris'
elif system == 'IRIX64':
# IRIX reports IRIX64 on platforms with 64-bit support; yet it
# is really a version and not a different platform, since 32-bit
# apps are also supported..
system = 'IRIX'
if version:
version = version + ' (64bit)'
else:
version = '64bit'
elif system in ('win32','win16'):
# In case one of the other tricks
system = 'Windows'
return system,release,version
### Various internal helpers
def _platform(*args):
""" Helper to format the platform string in a filename
compatible format e.g. "system-version-machine".
"""
# Format the platform string
platform = string.join(
map(string.strip,
filter(len, args)),
'-')
# Cleanup some possible filename obstacles...
replace = string.replace
platform = replace(platform,' ','_')
platform = replace(platform,'/','-')
platform = replace(platform,'\\','-')
platform = replace(platform,':','-')
platform = replace(platform,';','-')
platform = replace(platform,'"','-')
platform = replace(platform,'(','-')
platform = replace(platform,')','-')
# No need to report 'unknown' information...
platform = replace(platform,'unknown','')
# Fold '--'s and remove trailing '-'
while 1:
cleaned = replace(platform,'--','-')
if cleaned == platform:
break
platform = cleaned
while platform[-1] == '-':
platform = platform[:-1]
return platform
def _node(default=''):
""" Helper to determine the node name of this machine.
"""
try:
import socket
except ImportError:
# No sockets...
return default
try:
return socket.gethostname()
except socket.error:
# Still not working...
return default
# os.path.abspath is new in Python 1.5.2:
if not hasattr(os.path,'abspath'):
def _abspath(path,
isabs=os.path.isabs,join=os.path.join,getcwd=os.getcwd,
normpath=os.path.normpath):
if not isabs(path):
path = join(getcwd(), path)
return normpath(path)
else:
_abspath = os.path.abspath
def _follow_symlinks(filepath):
""" In case filepath is a symlink, follow it until a
real file is reached.
"""
filepath = _abspath(filepath)
while os.path.islink(filepath):
filepath = os.path.normpath(
os.path.join(os.path.dirname(filepath),os.readlink(filepath)))
return filepath
def _syscmd_uname(option,default=''):
""" Interface to the system's uname command.
"""
if sys.platform in ('dos','win32','win16','os2'):
# XXX Others too ?
return default
try:
f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
except (AttributeError,os.error):
return default
output = string.strip(f.read())
rc = f.close()
if not output or rc:
return default
else:
return output
def _syscmd_file(target,default=''):
""" Interface to the system's file command.
The function uses the -b option of the file command to have it
ommit the filename in its output and if possible the -L option
to have the command follow symlinks. It returns default in
case the command should fail.
"""
# We do the import here to avoid a bootstrap issue.
# See c73b90b6dadd changeset.
#
# [..]
# ranlib libpython2.7.a
# gcc -o python \
# Modules/python.o \
# libpython2.7.a -lsocket -lnsl -ldl -lm
# Traceback (most recent call last):
# File "./setup.py", line 8, in <module>
# from platform import machine as platform_machine
# File "[..]/build/Lib/platform.py", line 116, in <module>
# import sys,string,os,re,subprocess
# File "[..]/build/Lib/subprocess.py", line 429, in <module>
# import select
# ImportError: No module named select
import subprocess
if sys.platform in ('dos','win32','win16','os2'):
# XXX Others too ?
return default
target = _follow_symlinks(target)
try:
proc = subprocess.Popen(['file', target],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
except (AttributeError,os.error):
return default
output = proc.communicate()[0]
rc = proc.wait()
if not output or rc:
return default
else:
return output
### Information about the used architecture
# Default values for architecture; non-empty strings override the
# defaults given as parameters
_default_architecture = {
'win32': ('','WindowsPE'),
'win16': ('','Windows'),
'dos': ('','MSDOS'),
}
_architecture_split = re.compile(r'[\s,]').split
def architecture(executable=sys.executable,bits='',linkage=''):
""" Queries the given executable (defaults to the Python interpreter
binary) for various architecture information.
Returns a tuple (bits,linkage) which contains information about
the bit architecture and the linkage format used for the
executable. Both values are returned as strings.
Values that cannot be determined are returned as given by the
parameter presets. If bits is given as '', the sizeof(pointer)
(or sizeof(long) on Python version < 1.5.2) is used as
indicator for the supported pointer size.
The function relies on the system's "file" command to do the
actual work. This is available on most if not all Unix
platforms. On some non-Unix platforms where the "file" command
does not exist and the executable is set to the Python interpreter
binary defaults from _default_architecture are used.
"""
# Use the sizeof(pointer) as default number of bits if nothing
# else is given as default.
if not bits:
import struct
try:
size = struct.calcsize('P')
except struct.error:
# Older installations can only query longs
size = struct.calcsize('l')
bits = str(size*8) + 'bit'
# Get data from the 'file' system command
if executable:
output = _syscmd_file(executable, '')
else:
output = ''
if not output and \
executable == sys.executable:
# "file" command did not return anything; we'll try to provide
# some sensible defaults then...
if sys.platform in _default_architecture:
b, l = _default_architecture[sys.platform]
if b:
bits = b
if l:
linkage = l
return bits, linkage
# Split the output into a list of strings omitting the filename
fileout = _architecture_split(output)[1:]
if 'executable' not in fileout:
# Format not supported
return bits,linkage
# Bits
if '32-bit' in fileout:
bits = '32bit'
elif 'N32' in fileout:
# On Irix only
bits = 'n32bit'
elif '64-bit' in fileout:
bits = '64bit'
# Linkage
if 'ELF' in fileout:
linkage = 'ELF'
elif 'PE' in fileout:
# E.g. Windows uses this format
if 'Windows' in fileout:
linkage = 'WindowsPE'
else:
linkage = 'PE'
elif 'COFF' in fileout:
linkage = 'COFF'
elif 'MS-DOS' in fileout:
linkage = 'MSDOS'
else:
# XXX the A.OUT format also falls under this class...
pass
return bits,linkage
### Portable uname() interface
_uname_cache = None
def uname():
""" Fairly portable uname interface. Returns a tuple
of strings (system,node,release,version,machine,processor)
identifying the underlying platform.
Note that unlike the os.uname function this also returns
possible processor information as an additional tuple entry.
Entries which cannot be determined are set to ''.
"""
global _uname_cache
no_os_uname = 0
if _uname_cache is not None:
return _uname_cache
processor = ''
# Get some infos from the builtin os.uname API...
try:
system,node,release,version,machine = os.uname()
except AttributeError:
no_os_uname = 1
if no_os_uname or not filter(None, (system, node, release, version, machine)):
# Hmm, no there is either no uname or uname has returned
#'unknowns'... we'll have to poke around the system then.
if no_os_uname:
system = sys.platform
release = ''
version = ''
node = _node()
machine = ''
use_syscmd_ver = 1
# Try win32_ver() on win32 platforms
if system == 'win32':
release,version,csd,ptype = win32_ver()
if release and version:
use_syscmd_ver = 0
# Try to use the PROCESSOR_* environment variables
# available on Win XP and later; see
# http://support.microsoft.com/kb/888731 and
# http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
if not machine:
# WOW64 processes mask the native architecture
if "PROCESSOR_ARCHITEW6432" in os.environ:
machine = os.environ.get("PROCESSOR_ARCHITEW6432", '')
else:
machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
if not processor:
processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)
# Try the 'ver' system command available on some
# platforms
if use_syscmd_ver:
system,release,version = _syscmd_ver(system)
# Normalize system to what win32_ver() normally returns
# (_syscmd_ver() tends to return the vendor name as well)
if system == 'Microsoft Windows':
system = 'Windows'
elif system == 'Microsoft' and release == 'Windows':
# Under Windows Vista and Windows Server 2008,
# Microsoft changed the output of the ver command. The
# release is no longer printed. This causes the
# system and release to be misidentified.
system = 'Windows'
if '6.0' == version[:3]:
release = 'Vista'
else:
release = ''
# In case we still don't know anything useful, we'll try to
# help ourselves
if system in ('win32','win16'):
if not version:
if system == 'win32':
version = '32bit'
else:
version = '16bit'
system = 'Windows'
elif system[:4] == 'java':
release,vendor,vminfo,osinfo = java_ver()
system = 'Java'
version = string.join(vminfo,', ')
if not version:
version = vendor
# System specific extensions
if system == 'OpenVMS':
# OpenVMS seems to have release and version mixed up
if not release or release == '0':
release = version
version = ''
# Get processor information
try:
import vms_lib
except ImportError:
pass
else:
csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0)
if (cpu_number >= 128):
processor = 'Alpha'
else:
processor = 'VAX'
if not processor:
# Get processor information from the uname system command
processor = _syscmd_uname('-p','')
#If any unknowns still exist, replace them with ''s, which are more portable
if system == 'unknown':
system = ''
if node == 'unknown':
node = ''
if release == 'unknown':
release = ''
if version == 'unknown':
version = ''
if machine == 'unknown':
machine = ''
if processor == 'unknown':
processor = ''
# normalize name
if system == 'Microsoft' and release == 'Windows':
system = 'Windows'
release = 'Vista'
_uname_cache = system,node,release,version,machine,processor
return _uname_cache
### Direct interfaces to some of the uname() return values
def system():
""" Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
An empty string is returned if the value cannot be determined.
"""
return uname()[0]
def node():
""" Returns the computer's network name (which may not be fully
qualified)
An empty string is returned if the value cannot be determined.
"""
return uname()[1]
def release():
""" Returns the system's release, e.g. '2.2.0' or 'NT'
An empty string is returned if the value cannot be determined.
"""
return uname()[2]
def version():
""" Returns the system's release version, e.g. '#3 on degas'
An empty string is returned if the value cannot be determined.
"""
return uname()[3]
def machine():
""" Returns the machine type, e.g. 'i386'
An empty string is returned if the value cannot be determined.
"""
return uname()[4]
def processor():
""" Returns the (true) processor name, e.g. 'amdk6'
An empty string is returned if the value cannot be
determined. Note that many platforms do not provide this
information or simply return the same value as for machine(),
e.g. NetBSD does this.
"""
return uname()[5]
### Various APIs for extracting information from sys.version
_sys_version_parser = re.compile(
r'([\w.+]+)\s*'
'\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
'\[([^\]]+)\]?')
_ironpython_sys_version_parser = re.compile(
r'IronPython\s*'
'([\d\.]+)'
'(?: \(([\d\.]+)\))?'
' on (.NET [\d\.]+)')
_pypy_sys_version_parser = re.compile(
r'([\w.+]+)\s*'
'\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
'\[PyPy [^\]]+\]?')
_sys_version_cache = {}
def _sys_version(sys_version=None):
""" Returns a parsed version of Python's sys.version as tuple
(name, version, branch, revision, buildno, builddate, compiler)
referring to the Python implementation name, version, branch,
revision, build number, build date/time as string and the compiler
identification string.
Note that unlike the Python sys.version, the returned value
for the Python version will always include the patchlevel (it
defaults to '.0').
The function returns empty strings for tuple entries that
cannot be determined.
sys_version may be given to parse an alternative version
string, e.g. if the version was read from a different Python
interpreter.
"""
# Get the Python version
if sys_version is None:
sys_version = sys.version
# Try the cache first
result = _sys_version_cache.get(sys_version, None)
if result is not None:
return result
# Parse it
if sys_version[:10] == 'IronPython':
# IronPython
name = 'IronPython'
match = _ironpython_sys_version_parser.match(sys_version)
if match is None:
raise ValueError(
'failed to parse IronPython sys.version: %s' %
repr(sys_version))
version, alt_version, compiler = match.groups()
buildno = ''
builddate = ''
elif sys.platform[:4] == 'java':
# Jython
name = 'Jython'
match = _sys_version_parser.match(sys_version)
if match is None:
raise ValueError(
'failed to parse Jython sys.version: %s' %
repr(sys_version))
version, buildno, builddate, buildtime, _ = match.groups()
compiler = sys.platform
elif "PyPy" in sys_version:
# PyPy
name = "PyPy"
match = _pypy_sys_version_parser.match(sys_version)
if match is None:
raise ValueError("failed to parse PyPy sys.version: %s" %
repr(sys_version))
version, buildno, builddate, buildtime = match.groups()
compiler = ""
else:
# CPython
match = _sys_version_parser.match(sys_version)
if match is None:
raise ValueError(
'failed to parse CPython sys.version: %s' %
repr(sys_version))
version, buildno, builddate, buildtime, compiler = \
match.groups()
name = 'CPython'
builddate = builddate + ' ' + buildtime
if hasattr(sys, 'subversion'):
# sys.subversion was added in Python 2.5
_, branch, revision = sys.subversion
else:
branch = ''
revision = ''
# Add the patchlevel version if missing
l = string.split(version, '.')
if len(l) == 2:
l.append('0')
version = string.join(l, '.')
# Build and cache the result
result = (name, version, branch, revision, buildno, builddate, compiler)
_sys_version_cache[sys_version] = result
return result
def python_implementation():
""" Returns a string identifying the Python implementation.
Currently, the following implementations are identified:
'CPython' (C implementation of Python),
'IronPython' (.NET implementation of Python),
'Jython' (Java implementation of Python),
'PyPy' (Python implementation of Python).
"""
return _sys_version()[0]
def python_version():
""" Returns the Python version as string 'major.minor.patchlevel'
Note that unlike the Python sys.version, the returned value
will always include the patchlevel (it defaults to 0).
"""
return _sys_version()[1]
def python_version_tuple():
""" Returns the Python version as tuple (major, minor, patchlevel)
of strings.
Note that unlike the Python sys.version, the returned value
will always include the patchlevel (it defaults to 0).
"""
return tuple(string.split(_sys_version()[1], '.'))
def python_branch():
""" Returns a string identifying the Python implementation
branch.
For CPython this is the Subversion branch from which the
Python binary was built.
If not available, an empty string is returned.
"""
return _sys_version()[2]
def python_revision():
""" Returns a string identifying the Python implementation
revision.
For CPython this is the Subversion revision from which the
Python binary was built.
If not available, an empty string is returned.
"""
return _sys_version()[3]
def python_build():
""" Returns a tuple (buildno, builddate) stating the Python
build number and date as strings.
"""
return _sys_version()[4:6]
def python_compiler():
""" Returns a string identifying the compiler used for compiling
Python.
"""
return _sys_version()[6]
### The Opus Magnum of platform strings :-)
_platform_cache = {}
def platform(aliased=0, terse=0):
""" Returns a single string identifying the underlying platform
with as much useful information as possible (but no more :).
The output is intended to be human readable rather than
machine parseable. It may look different on different
platforms and this is intended.
If "aliased" is true, the function will use aliases for
various platforms that report system names which differ from
their common names, e.g. SunOS will be reported as
Solaris. The system_alias() function is used to implement
this.
Setting terse to true causes the function to return only the
absolute minimum information needed to identify the platform.
"""
result = _platform_cache.get((aliased, terse), None)
if result is not None:
return result
# Get uname information and then apply platform specific cosmetics
# to it...
system,node,release,version,machine,processor = uname()
if machine == processor:
processor = ''
if aliased:
system,release,version = system_alias(system,release,version)
if system == 'Windows':
# MS platforms
rel,vers,csd,ptype = win32_ver(version)
if terse:
platform = _platform(system,release)
else:
platform = _platform(system,release,version,csd)
elif system in ('Linux',):
# Linux based systems
distname,distversion,distid = dist('')
if distname and not terse:
platform = _platform(system,release,machine,processor,
'with',
distname,distversion,distid)
else:
# If the distribution name is unknown check for libc vs. glibc
libcname,libcversion = libc_ver(sys.executable)
platform = _platform(system,release,machine,processor,
'with',
libcname+libcversion)
elif system == 'Java':
# Java platforms
r,v,vminfo,(os_name,os_version,os_arch) = java_ver()
if terse or not os_name:
platform = _platform(system,release,version)
else:
platform = _platform(system,release,version,
'on',
os_name,os_version,os_arch)
elif system == 'MacOS':
# MacOS platforms
if terse:
platform = _platform(system,release)
else:
platform = _platform(system,release,machine)
else:
# Generic handler
if terse:
platform = _platform(system,release)
else:
bits,linkage = architecture(sys.executable)
platform = _platform(system,release,machine,processor,bits,linkage)
_platform_cache[(aliased, terse)] = platform
return platform
### Command line interface
if __name__ == '__main__':
# Default is to print the aliased verbose platform string
terse = ('terse' in sys.argv or '--terse' in sys.argv)
aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
print platform(aliased,terse)
sys.exit(0)
|
unknown
|
codeparrot/codeparrot-clean
| ||
from .channels import Channels
from .roles import Roles
from .users import Users
from twilio.rest.resources import NextGenInstanceResource, NextGenListResource
class Service(NextGenInstanceResource):
subresources = [
Channels,
Roles,
Users
]
def update(self, **kwargs):
"""
Updates this Service instance
:return: Updated instance
"""
return self.update_instance(**kwargs)
def delete(self):
"""
Delete this service
"""
return self.delete_instance()
class Services(NextGenListResource):
name = "Services"
instance = Service
def list(self, **kwargs):
"""
Returns a page of :class:`Service` resources as a list.
For paging information see :class:`ListResource`.
**NOTE**: Due to the potentially voluminous amount of data in an
alert, the full HTTP request and response data is only returned
in the Service instance resource representation.
"""
return self.get_instances(kwargs)
def create(self, friendly_name, **kwargs):
"""
Create a service.
:param str friendly_name: The friendly name for the service
:return: A :class:`Service` object
"""
kwargs["friendly_name"] = friendly_name
return self.create_instance(kwargs)
def delete(self, sid):
"""
Delete a given Service
"""
return self.delete_instance(sid)
def update(self, sid, **kwargs):
"""
Updates the Service instance identified by sid
:param sid: Service instance identifier
:return: Updated instance
"""
return self.update_instance(sid, kwargs)
|
unknown
|
codeparrot/codeparrot-clean
| ||
# engine/reflection.py
# Copyright (C) 2005-2014 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Provides an abstraction for obtaining database schema information.
Usage Notes:
Here are some general conventions when accessing the low level inspector
methods such as get_table_names, get_columns, etc.
1. Inspector methods return lists of dicts in most cases for the following
reasons:
* They're both standard types that can be serialized.
* Using a dict instead of a tuple allows easy expansion of attributes.
* Using a list for the outer structure maintains order and is easy to work
with (e.g. list comprehension [d['name'] for d in cols]).
2. Records that contain a name, such as the column name in a column record
use the key 'name'. So for most return values, each record will have a
'name' attribute..
"""
from .. import exc, sql
from ..sql import schema as sa_schema
from .. import util
from ..sql.type_api import TypeEngine
from ..util import deprecated
from ..util import topological
from .. import inspection
from .base import Connectable
@util.decorator
def cache(fn, self, con, *args, **kw):
info_cache = kw.get('info_cache', None)
if info_cache is None:
return fn(self, con, *args, **kw)
key = (
fn.__name__,
tuple(a for a in args if isinstance(a, util.string_types)),
tuple((k, v) for k, v in kw.items() if
isinstance(v,
util.string_types + util.int_types + (float, )
)
)
)
ret = info_cache.get(key)
if ret is None:
ret = fn(self, con, *args, **kw)
info_cache[key] = ret
return ret
class Inspector(object):
"""Performs database schema inspection.
The Inspector acts as a proxy to the reflection methods of the
:class:`~sqlalchemy.engine.interfaces.Dialect`, providing a
consistent interface as well as caching support for previously
fetched metadata.
A :class:`.Inspector` object is usually created via the
:func:`.inspect` function::
from sqlalchemy import inspect, create_engine
engine = create_engine('...')
insp = inspect(engine)
The inspection method above is equivalent to using the
:meth:`.Inspector.from_engine` method, i.e.::
engine = create_engine('...')
insp = Inspector.from_engine(engine)
Where above, the :class:`~sqlalchemy.engine.interfaces.Dialect` may opt
to return an :class:`.Inspector` subclass that provides additional
methods specific to the dialect's target database.
"""
def __init__(self, bind):
"""Initialize a new :class:`.Inspector`.
:param bind: a :class:`~sqlalchemy.engine.Connectable`,
which is typically an instance of
:class:`~sqlalchemy.engine.Engine` or
:class:`~sqlalchemy.engine.Connection`.
For a dialect-specific instance of :class:`.Inspector`, see
:meth:`.Inspector.from_engine`
"""
# this might not be a connection, it could be an engine.
self.bind = bind
# set the engine
if hasattr(bind, 'engine'):
self.engine = bind.engine
else:
self.engine = bind
if self.engine is bind:
# if engine, ensure initialized
bind.connect().close()
self.dialect = self.engine.dialect
self.info_cache = {}
@classmethod
def from_engine(cls, bind):
"""Construct a new dialect-specific Inspector object from the given
engine or connection.
:param bind: a :class:`~sqlalchemy.engine.Connectable`,
which is typically an instance of
:class:`~sqlalchemy.engine.Engine` or
:class:`~sqlalchemy.engine.Connection`.
This method differs from direct a direct constructor call of
:class:`.Inspector` in that the
:class:`~sqlalchemy.engine.interfaces.Dialect` is given a chance to
provide a dialect-specific :class:`.Inspector` instance, which may
provide additional methods.
See the example at :class:`.Inspector`.
"""
if hasattr(bind.dialect, 'inspector'):
return bind.dialect.inspector(bind)
return Inspector(bind)
@inspection._inspects(Connectable)
def _insp(bind):
return Inspector.from_engine(bind)
@property
def default_schema_name(self):
"""Return the default schema name presented by the dialect
for the current engine's database user.
E.g. this is typically ``public`` for Postgresql and ``dbo``
for SQL Server.
"""
return self.dialect.default_schema_name
def get_schema_names(self):
"""Return all schema names.
"""
if hasattr(self.dialect, 'get_schema_names'):
return self.dialect.get_schema_names(self.bind,
info_cache=self.info_cache)
return []
def get_table_names(self, schema=None, order_by=None):
"""Return all table names in referred to within a particular schema.
The names are expected to be real tables only, not views.
Views are instead returned using the :meth:`.Inspector.get_view_names`
method.
:param schema: Schema name. If ``schema`` is left at ``None``, the
database's default schema is
used, else the named schema is searched. If the database does not
support named schemas, behavior is undefined if ``schema`` is not
passed as ``None``. For special quoting, use :class:`.quoted_name`.
:param order_by: Optional, may be the string "foreign_key" to sort
the result on foreign key dependencies.
.. versionchanged:: 0.8 the "foreign_key" sorting sorts tables
in order of dependee to dependent; that is, in creation
order, rather than in drop order. This is to maintain
consistency with similar features such as
:attr:`.MetaData.sorted_tables` and :func:`.util.sort_tables`.
.. seealso::
:attr:`.MetaData.sorted_tables`
"""
if hasattr(self.dialect, 'get_table_names'):
tnames = self.dialect.get_table_names(self.bind,
schema, info_cache=self.info_cache)
else:
tnames = self.engine.table_names(schema)
if order_by == 'foreign_key':
tuples = []
for tname in tnames:
for fkey in self.get_foreign_keys(tname, schema):
if tname != fkey['referred_table']:
tuples.append((fkey['referred_table'], tname))
tnames = list(topological.sort(tuples, tnames))
return tnames
def get_table_options(self, table_name, schema=None, **kw):
"""Return a dictionary of options specified when the table of the
given name was created.
This currently includes some options that apply to MySQL tables.
:param table_name: string name of the table. For special quoting,
use :class:`.quoted_name`.
:param schema: string schema name; if omitted, uses the default schema
of the database connection. For special quoting,
use :class:`.quoted_name`.
"""
if hasattr(self.dialect, 'get_table_options'):
return self.dialect.get_table_options(
self.bind, table_name, schema,
info_cache=self.info_cache, **kw)
return {}
def get_view_names(self, schema=None):
"""Return all view names in `schema`.
:param schema: Optional, retrieve names from a non-default schema.
For special quoting, use :class:`.quoted_name`.
"""
return self.dialect.get_view_names(self.bind, schema,
info_cache=self.info_cache)
def get_view_definition(self, view_name, schema=None):
"""Return definition for `view_name`.
:param schema: Optional, retrieve names from a non-default schema.
For special quoting, use :class:`.quoted_name`.
"""
return self.dialect.get_view_definition(
self.bind, view_name, schema, info_cache=self.info_cache)
def get_columns(self, table_name, schema=None, **kw):
"""Return information about columns in `table_name`.
Given a string `table_name` and an optional string `schema`, return
column information as a list of dicts with these keys:
name
the column's name
type
:class:`~sqlalchemy.types.TypeEngine`
nullable
boolean
default
the column's default value
attrs
dict containing optional column attributes
:param table_name: string name of the table. For special quoting,
use :class:`.quoted_name`.
:param schema: string schema name; if omitted, uses the default schema
of the database connection. For special quoting,
use :class:`.quoted_name`.
"""
col_defs = self.dialect.get_columns(self.bind, table_name, schema,
info_cache=self.info_cache,
**kw)
for col_def in col_defs:
# make this easy and only return instances for coltype
coltype = col_def['type']
if not isinstance(coltype, TypeEngine):
col_def['type'] = coltype()
return col_defs
@deprecated('0.7', 'Call to deprecated method get_primary_keys.'
' Use get_pk_constraint instead.')
def get_primary_keys(self, table_name, schema=None, **kw):
"""Return information about primary keys in `table_name`.
Given a string `table_name`, and an optional string `schema`, return
primary key information as a list of column names.
"""
return self.dialect.get_pk_constraint(self.bind, table_name, schema,
info_cache=self.info_cache,
**kw)['constrained_columns']
def get_pk_constraint(self, table_name, schema=None, **kw):
"""Return information about primary key constraint on `table_name`.
Given a string `table_name`, and an optional string `schema`, return
primary key information as a dictionary with these keys:
constrained_columns
a list of column names that make up the primary key
name
optional name of the primary key constraint.
:param table_name: string name of the table. For special quoting,
use :class:`.quoted_name`.
:param schema: string schema name; if omitted, uses the default schema
of the database connection. For special quoting,
use :class:`.quoted_name`.
"""
return self.dialect.get_pk_constraint(self.bind, table_name, schema,
info_cache=self.info_cache,
**kw)
def get_foreign_keys(self, table_name, schema=None, **kw):
"""Return information about foreign_keys in `table_name`.
Given a string `table_name`, and an optional string `schema`, return
foreign key information as a list of dicts with these keys:
constrained_columns
a list of column names that make up the foreign key
referred_schema
the name of the referred schema
referred_table
the name of the referred table
referred_columns
a list of column names in the referred table that correspond to
constrained_columns
name
optional name of the foreign key constraint.
:param table_name: string name of the table. For special quoting,
use :class:`.quoted_name`.
:param schema: string schema name; if omitted, uses the default schema
of the database connection. For special quoting,
use :class:`.quoted_name`.
"""
return self.dialect.get_foreign_keys(self.bind, table_name, schema,
info_cache=self.info_cache,
**kw)
def get_indexes(self, table_name, schema=None, **kw):
"""Return information about indexes in `table_name`.
Given a string `table_name` and an optional string `schema`, return
index information as a list of dicts with these keys:
name
the index's name
column_names
list of column names in order
unique
boolean
:param table_name: string name of the table. For special quoting,
use :class:`.quoted_name`.
:param schema: string schema name; if omitted, uses the default schema
of the database connection. For special quoting,
use :class:`.quoted_name`.
"""
return self.dialect.get_indexes(self.bind, table_name,
schema,
info_cache=self.info_cache, **kw)
def get_unique_constraints(self, table_name, schema=None, **kw):
"""Return information about unique constraints in `table_name`.
Given a string `table_name` and an optional string `schema`, return
unique constraint information as a list of dicts with these keys:
name
the unique constraint's name
column_names
list of column names in order
:param table_name: string name of the table. For special quoting,
use :class:`.quoted_name`.
:param schema: string schema name; if omitted, uses the default schema
of the database connection. For special quoting,
use :class:`.quoted_name`.
.. versionadded:: 0.8.4
"""
return self.dialect.get_unique_constraints(
self.bind, table_name, schema, info_cache=self.info_cache, **kw)
def reflecttable(self, table, include_columns, exclude_columns=()):
"""Given a Table object, load its internal constructs based on
introspection.
This is the underlying method used by most dialects to produce
table reflection. Direct usage is like::
from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.engine import reflection
engine = create_engine('...')
meta = MetaData()
user_table = Table('user', meta)
insp = Inspector.from_engine(engine)
insp.reflecttable(user_table, None)
:param table: a :class:`~sqlalchemy.schema.Table` instance.
:param include_columns: a list of string column names to include
in the reflection process. If ``None``, all columns are reflected.
"""
dialect = self.bind.dialect
schema = table.schema
table_name = table.name
# get table-level arguments that are specifically
# intended for reflection, e.g. oracle_resolve_synonyms.
# these are unconditionally passed to related Table
# objects
reflection_options = dict(
(k, table.dialect_kwargs.get(k))
for k in dialect.reflection_options
if k in table.dialect_kwargs
)
# reflect table options, like mysql_engine
tbl_opts = self.get_table_options(table_name, schema, **table.dialect_kwargs)
if tbl_opts:
# add additional kwargs to the Table if the dialect
# returned them
table._validate_dialect_kwargs(tbl_opts)
if util.py2k:
if isinstance(schema, str):
schema = schema.decode(dialect.encoding)
if isinstance(table_name, str):
table_name = table_name.decode(dialect.encoding)
found_table = False
cols_by_orig_name = {}
for col_d in self.get_columns(table_name, schema, **table.dialect_kwargs):
found_table = True
orig_name = col_d['name']
table.dispatch.column_reflect(self, table, col_d)
name = col_d['name']
if include_columns and name not in include_columns:
continue
if exclude_columns and name in exclude_columns:
continue
coltype = col_d['type']
col_kw = dict(
(k, col_d[k])
for k in ['nullable', 'autoincrement', 'quote', 'info', 'key']
if k in col_d
)
colargs = []
if col_d.get('default') is not None:
# the "default" value is assumed to be a literal SQL
# expression, so is wrapped in text() so that no quoting
# occurs on re-issuance.
colargs.append(
sa_schema.DefaultClause(
sql.text(col_d['default']), _reflected=True
)
)
if 'sequence' in col_d:
# TODO: mssql and sybase are using this.
seq = col_d['sequence']
sequence = sa_schema.Sequence(seq['name'], 1, 1)
if 'start' in seq:
sequence.start = seq['start']
if 'increment' in seq:
sequence.increment = seq['increment']
colargs.append(sequence)
cols_by_orig_name[orig_name] = col = \
sa_schema.Column(name, coltype, *colargs, **col_kw)
if col.key in table.primary_key:
col.primary_key = True
table.append_column(col)
if not found_table:
raise exc.NoSuchTableError(table.name)
pk_cons = self.get_pk_constraint(table_name, schema, **table.dialect_kwargs)
if pk_cons:
pk_cols = [
cols_by_orig_name[pk]
for pk in pk_cons['constrained_columns']
if pk in cols_by_orig_name and pk not in exclude_columns
]
# update pk constraint name
table.primary_key.name = pk_cons.get('name')
# tell the PKConstraint to re-initialize
# it's column collection
table.primary_key._reload(pk_cols)
fkeys = self.get_foreign_keys(table_name, schema, **table.dialect_kwargs)
for fkey_d in fkeys:
conname = fkey_d['name']
# look for columns by orig name in cols_by_orig_name,
# but support columns that are in-Python only as fallback
constrained_columns = [
cols_by_orig_name[c].key
if c in cols_by_orig_name else c
for c in fkey_d['constrained_columns']
]
if exclude_columns and set(constrained_columns).intersection(
exclude_columns):
continue
referred_schema = fkey_d['referred_schema']
referred_table = fkey_d['referred_table']
referred_columns = fkey_d['referred_columns']
refspec = []
if referred_schema is not None:
sa_schema.Table(referred_table, table.metadata,
autoload=True, schema=referred_schema,
autoload_with=self.bind,
**reflection_options
)
for column in referred_columns:
refspec.append(".".join(
[referred_schema, referred_table, column]))
else:
sa_schema.Table(referred_table, table.metadata, autoload=True,
autoload_with=self.bind,
**reflection_options
)
for column in referred_columns:
refspec.append(".".join([referred_table, column]))
if 'options' in fkey_d:
options = fkey_d['options']
else:
options = {}
table.append_constraint(
sa_schema.ForeignKeyConstraint(constrained_columns, refspec,
conname, link_to_name=True,
**options))
# Indexes
indexes = self.get_indexes(table_name, schema)
for index_d in indexes:
name = index_d['name']
columns = index_d['column_names']
unique = index_d['unique']
flavor = index_d.get('type', 'unknown type')
if include_columns and \
not set(columns).issubset(include_columns):
util.warn(
"Omitting %s KEY for (%s), key covers omitted columns." %
(flavor, ', '.join(columns)))
continue
# look for columns by orig name in cols_by_orig_name,
# but support columns that are in-Python only as fallback
sa_schema.Index(name, *[
cols_by_orig_name[c] if c in cols_by_orig_name
else table.c[c]
for c in columns
],
**dict(unique=unique))
|
unknown
|
codeparrot/codeparrot-clean
| ||
__source__ = 'https://leetcode.com/problems/path-sum-ii/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/path-sum-ii.py
# Time: O(n)
# Space: O(h), h is height of binary tree
# DFS
#
# Description: Leetcode # 113. Path Sum II
#
# Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
#
# For example:
# Given the below binary tree and sum = 22,
# 5
# / \
# 4 8
# / / \
# 11 13 4
# / \ / \
# 7 2 5 1
# return
# [
# [5,4,11,2],
# [5,8,4,5]
# ]
#
#
# Companies
# Bloomberg
# Related Topics
# Tree Depth-first Search
# Similar Questions
# Path Sum Binary Tree Paths Path Sum III
#
import unittest
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a list of lists of integers
def pathSum(self, root, sum):
return self.pathSumRecu([], [], root, sum)
def pathSumRecu(self, result, cur, root, sum):
if root is None:
return result
if root.left is None and root.right is None and root.val == sum:
result.append(cur + [root.val])
return result
cur.append(root.val)
self.pathSumRecu(result, cur, root.left, sum - root.val)
self.pathSumRecu(result, cur, root.right, sum - root.val)
cur.pop()
return result
class Solution2:
# @param root, a tree node
# @param sum, an integer
# @return a list of lists of integers
def pathSum(self, root, sum):
result = []
self.pathSumRecu(result, [], root, sum)
return result
def pathSumRecu(self, result, cur, root, sum):
if root is None:
return result # if fo return, it means return null, bad behavior
if root.left is None and root.right is None and root.val == sum:
result.append(cur + [root.val])
return result
self.pathSumRecu(result, cur + [root.val], root.left, sum - root.val)
self.pathSumRecu(result, cur + [root.val], root.right, sum - root.val)
return result
class TestMethods(unittest.TestCase):
def test_Local(self):
self.assertEqual(1, 1)
root = TreeNode(5)
root.left = TreeNode(4)
root.right = TreeNode(8)
root.left.left = TreeNode(11)
root.left.left.left = TreeNode(7)
root.left.left.right = TreeNode(2)
print Solution().pathSum(root, 22)
print Solution2().pathSum(root, 77)
if __name__ == '__main__':
unittest.main()
Java = '''
# Thought:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
# DFS
# 2ms 61.15%
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
pathSum(root, sum, result, new ArrayList<>());
return result;
}
private void pathSum(TreeNode root, int sum, List<List<Integer>> result, List<Integer> list) {
sum -= root.val;
list.add(root.val);
if (root.left == null && root.right == null) {
if (sum == 0) {
result.add(new ArrayList<>(list));
}
} else {
if (root.left != null) {
pathSum(root.left, sum, result, list);
}
if (root.right != null) {
pathSum(root.right, sum, result, list);
}
}
list.remove(list.size() - 1);
}
}
# 2ms 61.15%
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
dfs(root, sum, res, path);
return res;
}
public void dfs(TreeNode root, int sum, List<List<Integer>> res, List<Integer> path){
if(root==null) return;
path.add(root.val);
if(root.left==null && root.right==null ){
if(root.val==sum)
res.add(new ArrayList<Integer>(path));
return;
}
if(root.left!=null) {
dfs(root.left,sum-root.val,res,path);
path.remove(path.size()-1);
}
if(root.right!=null) {
dfs(root.right,sum-root.val,res,path);
path.remove(path.size()-1);
}
}
}
# BFS
# 6ms 9.98%
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
Stack<TreeNode> stack = new Stack<TreeNode>();
int SUM = 0;
TreeNode cur = root;
TreeNode pre = null;
while(cur!=null || !stack.isEmpty()){
while(cur!=null){
stack.push(cur);
path.add(cur.val);
SUM+=cur.val;
cur=cur.left;
}
cur = stack.peek();
if(cur.right!=null && cur.right!=pre){
cur = cur.right;
continue;
}
if(cur.left==null && cur.right==null && SUM==sum)
res.add(new ArrayList<Integer>(path));
pre = cur;
stack.pop();
path.remove(path.size()-1);
SUM-=cur.val;
cur = null;
}
return res;
}
}
'''
|
unknown
|
codeparrot/codeparrot-clean
| ||
#!/usr/bin/env python3
#
# hyperv_wmi_generator.py: generates most of the WMI type mapping code
#
# Copyright (C) 2011 Matthias Bolte <matthias.bolte@googlemail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library. If not, see
# <http://www.gnu.org/licenses/>.
#
import sys
import os
import os.path
separator = "/*" + ("*" * 50) + "*\n"
wmi_classes_by_name = {}
class WmiClass:
"""Represents WMI class and provides methods to generate C code."""
def __init__(self, name, properties, uri_info):
self.name = name
self.properties = properties
self.uri_info = uri_info
def generate_classes_header(self):
"""Generate C header code and return it as string
Declares:
<class_name>_Data - used as hypervObject->data
<class_name>_TypeInfo - used as wsman XmlSerializerInfo
<class_name> - "inherits" hypervObject struct
"""
name_upper = self.name.upper()
header = separator
header += " * %s\n" % self.name
header += " */\n"
header += "\n"
header += "#define %s_WQL_SELECT \\\n" % name_upper
header += " \"SELECT * FROM %s \"\n" % self.name
header += "\n"
header += "extern hypervWmiClassInfo *%s_WmiInfo;\n\n" % self.name
header += self._declare_data_structs()
header += self._declare_hypervObject_struct()
return header
def generate_classes_source(self):
"""Returns a C code string defining wsman data structs
Defines:
<class_name>_Data struct
<class_name>_WmiInfo - list holding metadata (e.g. request URIs) for the WMI class
"""
source = separator
source += " * %s\n" % self.name
source += " */\n"
source += "SER_START_ITEMS(%s_Data)\n" % self.name
for property in self.properties:
source += property.generate_classes_source(self.name)
source += "SER_END_ITEMS(%s_Data);\n\n" % self.name
# also generate typemap data while we're here
source += "hypervCimType %s_Typemap[] = {\n" % self.name
for property in self.properties:
source += property.generate_typemap()
source += ' { "", "", 0 },\n' # null terminated
source += '};\n\n'
source += self._define_WmiInfo_struct()
source += "\n\n"
return source
def generate_classes_typedef(self):
"""Returns C string for typedefs"""
typedef = "typedef struct _%s %s;\n" % (self.name, self.name)
typedef += "typedef struct _%s_Data %s_Data;\n" % (self.name, self.name)
typedef += "G_DEFINE_AUTOPTR_CLEANUP_FUNC(%s, hypervFreeObject);\n" % self.name
typedef += "\n"
return typedef
def _declare_data_structs(self):
"""Returns string C code declaring data structs.
The *_Data structs are used as hypervObject->data. Each one has
corresponding *_TypeInfo that is used for wsman unserialization of
response XML into the *_Data structs.
"""
header = "#define %s_RESOURCE_URI \\\n" % self.name.upper()
header += " \"%s\"\n" % self.uri_info.resourceUri
header += "\n"
header += "struct _%s_Data {\n" % self.name
for property in self.properties:
header += property.generate_classes_header()
header += "};\n\n"
header += "SER_DECLARE_TYPE(%s_Data);\n" % self.name
return header
def _declare_hypervObject_struct(self):
"""Return string for C code declaring hypervObject instance"""
header = "\n/* must match hypervObject */\n"
header += "struct _%s {\n" % self.name
header += " %s_Data *data;\n" % self.name
header += " hypervWmiClassInfo *info;\n"
header += " %s *next;\n" % self.name
header += "};\n"
header += "\n\n\n"
return header
def _define_WmiInfo_struct(self):
"""Return string for C code defining *_WmiInfo struct
This struct holds info with meta-data needed to make wsman requests for the WMI class.
"""
source = "hypervWmiClassInfo *%s_WmiInfo = &(hypervWmiClassInfo) {\n" % self.name
source += " .name = \"%s\",\n" % self.name
source += " .rootUri = %s,\n" % self.uri_info.rootUri
source += " .resourceUri = %s_RESOURCE_URI,\n" % self.name.upper()
source += " .serializerInfo = %s_Data_TypeInfo,\n" % self.name
source += " .propertyInfo = %s_Typemap\n" % self.name
source += "};\n"
return source
class ClassUriInfo:
"""Prepares URI information needed for wsman requests."""
def __init__(self, wmi_name):
if wmi_name.startswith("Msvm_"):
self.rootUri = "ROOT_VIRTUALIZATION_V2"
baseUri = "http://schemas.microsoft.com/wbem/wsman/1/wmi/root/virtualization/v2"
else:
self.rootUri = "ROOT_CIMV2"
baseUri = "http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2"
self.resourceUri = "%s/%s" % (baseUri, wmi_name)
class Property:
typemap = {
"boolean": "BOOL",
"string": "STR",
"datetime": "STR",
"int8": "INT8",
"sint8": "INT8",
"int16": "INT16",
"sint16": "INT16",
"int32": "INT32",
"sint32": "INT32",
"int64": "INT64",
"sint64": "INT64",
"uint8": "UINT8",
"uint16": "UINT16",
"uint32": "UINT32",
"uint64": "UINT64"
}
def __init__(self, type, name, is_array):
if type not in Property.typemap:
report_error("unhandled property type %s" % type)
self.type = type
self.name = name
self.is_array = is_array
def generate_classes_header(self):
if self.is_array:
return " XML_TYPE_DYN_ARRAY %s;\n" % self.name
else:
return " XML_TYPE_%s %s;\n" \
% (Property.typemap[self.type], self.name)
def generate_classes_source(self, class_name):
if self.is_array:
return " SER_NS_DYN_ARRAY(%s_RESOURCE_URI, \"%s\", 0, 0, %s),\n" \
% (class_name.upper(), self.name, self.type)
else:
return " SER_NS_%s(%s_RESOURCE_URI, \"%s\", 1),\n" \
% (Property.typemap[self.type], class_name.upper(), self.name)
def generate_typemap(self):
return ' { "%s", "%s", %s },\n' % (self.name, self.type.lower(), str(self.is_array).lower())
def open_file(filename):
return open(filename, "wt")
def report_error(message):
print("error: " + message)
sys.exit(1)
def parse_class(block, number):
# expected format: class <name> : <optional parent>
header_items = block[0][1].split()
if len(header_items) not in [2, 4]:
report_error("line %d: invalid block header" % (number))
assert header_items[0] == "class"
name = header_items[1]
if name in wmi_classes_by_name:
report_error("class '%s' has already been defined" % name)
if len(header_items) == 4:
parent_class = header_items[3]
if parent_class not in wmi_classes_by_name:
report_error("nonexistent parent class specified: %s" % parent_class)
properties = wmi_classes_by_name[parent_class].properties.copy()
else:
properties = []
for line in block[1:]:
# expected format: <type> <name>
items = line[1].split()
if len(items) != 2:
report_error("line %d: invalid property" % line[0])
if items[1].endswith("[]"):
items[1] = items[1][:-2]
is_array = True
else:
is_array = False
properties.append(Property(type=items[0], name=items[1], is_array=is_array))
wmi_classes_by_name[name] = WmiClass(name, properties, ClassUriInfo(name))
def main():
if len(sys.argv) != 3:
report_error("usage: %s srcdir builddir" % sys.argv[0])
input_filename = os.path.join(sys.argv[1], "hyperv", "hyperv_wmi_generator.input")
output_dirname = os.path.join(sys.argv[2], "hyperv")
classes_typedef = open_file(os.path.join(output_dirname, "hyperv_wmi_classes.generated.typedef"))
classes_header = open_file(os.path.join(output_dirname, "hyperv_wmi_classes.generated.h"))
classes_source = open_file(os.path.join(output_dirname, "hyperv_wmi_classes.generated.c"))
# parse input file
number = 0
block = None
for line in open(input_filename, "rt").readlines():
number += 1
if "#" in line:
line = line[:line.index("#")]
line = line.lstrip().rstrip()
if len(line) < 1:
continue
if line.startswith("class"):
if block is not None:
report_error("line %d: nested block found" % (number))
else:
block = []
if block is not None:
if line == "end":
if block[0][1].startswith("class"):
parse_class(block, number)
block = None
else:
block.append((number, line))
# write output files
notice = "/* Generated by hyperv_wmi_generator.py */\n\n\n\n"
classes_typedef.write(notice)
classes_header.write(notice)
classes_source.write(notice)
classes_typedef.write("void hypervFreeObject(void *object);\n\n\n")
names = sorted(wmi_classes_by_name.keys())
for name in names:
cls = wmi_classes_by_name[name]
classes_typedef.write(cls.generate_classes_typedef())
classes_header.write(cls.generate_classes_header())
classes_source.write(cls.generate_classes_source())
if __name__ == "__main__":
main()
|
unknown
|
codeparrot/codeparrot-clean
| ||
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import ctypes
from pyglet import app
from pyglet.app.base import PlatformEventLoop
from pyglet.libs.darwin import *
EventLoopTimerProc = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p)
class CarbonEventLoop(PlatformEventLoop):
def __init__(self):
self._event_loop = carbon.GetMainEventLoop()
self._timer = ctypes.c_void_p()
self._timer_func = None
self._timer_func_proc = EventLoopTimerProc(self._timer_proc)
super(CarbonEventLoop, self).__init__()
def notify(self):
carbon.SetEventLoopTimerNextFireTime(
self._timer, ctypes.c_double(0.0))
def start(self):
# Create timer
timer = self._timer
carbon.InstallEventLoopTimer(self._event_loop,
ctypes.c_double(0.1), #?
ctypes.c_double(kEventDurationForever),
self._timer_func_proc,
None,
ctypes.byref(timer))
def stop(self):
carbon.RemoveEventLoopTimer(self._timer)
def step(self, timeout=None):
self.dispatch_posted_events()
event_dispatcher = carbon.GetEventDispatcherTarget()
e = ctypes.c_void_p()
if timeout is None:
timeout = kEventDurationForever
self._is_running.set()
# XXX should spin on multiple events after first timeout
if carbon.ReceiveNextEvent(0, None, ctypes.c_double(timeout),
True, ctypes.byref(e)) == 0:
carbon.SendEventToEventTarget(e, event_dispatcher)
carbon.ReleaseEvent(e)
timed_out = False
else:
timed_out = True
self._is_running.clear()
return not timed_out
def set_timer(self, func, interval):
if interval is None or func is None:
interval = kEventDurationForever
self._timer_func = func
carbon.SetEventLoopTimerNextFireTime(self._timer,
ctypes.c_double(interval))
def _timer_proc(self, timer, data):
if self._timer_func:
self._timer_func()
'''
self.dispatch_posted_events()
allow_polling = True
for window in app.windows:
# Check for live resizing
if window._resizing is not None:
allow_polling = False
old_width, old_height = window._resizing
rect = Rect()
carbon.GetWindowBounds(window._window,
kWindowContentRgn,
ctypes.byref(rect))
width = rect.right - rect.left
height = rect.bottom - rect.top
if width != old_width or height != old_height:
window._resizing = width, height
window.switch_to()
window.dispatch_event('on_resize', width, height)
# Check for live dragging
if window._dragging:
allow_polling = False
# Check for deferred recreate
if window._recreate_deferred:
# Break out of ReceiveNextEvent so it can be processed
# in next iteration.
carbon.QuitEventLoop(self._event_loop)
self._force_idle = True
sleep_time = self.idle()
if sleep_time is None:
sleep_time = kEventDurationForever
elif sleep_time < 0.01 and allow_polling and self._allow_polling:
# Switch event loop to polling.
carbon.QuitEventLoop(self._event_loop)
self._force_idle = True
sleep_time = kEventDurationForever
carbon.SetEventLoopTimerNextFireTime(timer, ctypes.c_double(sleep_time))
'''
|
unknown
|
codeparrot/codeparrot-clean
| ||
# -*- coding: utf-8 -*-
"""
requests.utils
~~~~~~~~~~~~~~
This module provides utility functions that are used within Requests
that are also useful for external consumption.
"""
import cgi
import codecs
import os
import platform
import re
import sys
import zlib
from netrc import netrc, NetrcParseError
from . import __version__
from .compat import parse_http_list as _parse_list_header
from .compat import quote, urlparse, bytes, str, OrderedDict
from .cookies import RequestsCookieJar, cookiejar_from_dict
_hush_pyflakes = (RequestsCookieJar,)
CERTIFI_BUNDLE_PATH = None
try:
# see if requests's own CA certificate bundle is installed
from . import certs
path = certs.where()
if os.path.exists(path):
CERTIFI_BUNDLE_PATH = certs.where()
except ImportError:
pass
NETRC_FILES = ('.netrc', '_netrc')
# common paths for the OS's CA certificate bundle
POSSIBLE_CA_BUNDLE_PATHS = [
# Red Hat, CentOS, Fedora and friends (provided by the ca-certificates package):
'/etc/pki/tls/certs/ca-bundle.crt',
# Ubuntu, Debian, and friends (provided by the ca-certificates package):
'/etc/ssl/certs/ca-certificates.crt',
# FreeBSD (provided by the ca_root_nss package):
'/usr/local/share/certs/ca-root-nss.crt',
# openSUSE (provided by the ca-certificates package), the 'certs' directory is the
# preferred way but may not be supported by the SSL module, thus it has 'ca-bundle.pem'
# as a fallback (which is generated from pem files in the 'certs' directory):
'/etc/ssl/ca-bundle.pem',
]
def get_os_ca_bundle_path():
"""Try to pick an available CA certificate bundle provided by the OS."""
for path in POSSIBLE_CA_BUNDLE_PATHS:
if os.path.exists(path):
return path
return None
# if certifi is installed, use its CA bundle;
# otherwise, try and use the OS bundle
DEFAULT_CA_BUNDLE_PATH = CERTIFI_BUNDLE_PATH or get_os_ca_bundle_path()
def dict_to_sequence(d):
"""Returns an internal sequence dictionary update."""
if hasattr(d, 'items'):
d = d.items()
return d
def get_netrc_auth(url):
"""Returns the Requests tuple auth for a given url from netrc."""
try:
locations = (os.path.expanduser('~/{0}'.format(f)) for f in NETRC_FILES)
netrc_path = None
for loc in locations:
if os.path.exists(loc) and not netrc_path:
netrc_path = loc
# Abort early if there isn't one.
if netrc_path is None:
return netrc_path
ri = urlparse(url)
# Strip port numbers from netloc
host = ri.netloc.split(':')[0]
try:
_netrc = netrc(netrc_path).authenticators(host)
if _netrc:
# Return with login / password
login_i = (0 if _netrc[0] else 1)
return (_netrc[login_i], _netrc[2])
except (NetrcParseError, IOError):
# If there was a parsing error or a permissions issue reading the file,
# we'll just skip netrc auth
pass
# AppEngine hackiness.
except (ImportError, AttributeError):
pass
def guess_filename(obj):
"""Tries to guess the filename of the given object."""
name = getattr(obj, 'name', None)
if name and name[0] != '<' and name[-1] != '>':
return name
def from_key_val_list(value):
"""Take an object and test to see if it can be represented as a
dictionary. Unless it can not be represented as such, return an
OrderedDict, e.g.,
::
>>> from_key_val_list([('key', 'val')])
OrderedDict([('key', 'val')])
>>> from_key_val_list('string')
ValueError: need more than 1 value to unpack
>>> from_key_val_list({'key': 'val'})
OrderedDict([('key', 'val')])
"""
if value is None:
return None
if isinstance(value, (str, bytes, bool, int)):
raise ValueError('cannot encode objects that are not 2-tuples')
return OrderedDict(value)
def to_key_val_list(value):
"""Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_list([('key', 'val')])
[('key', 'val')]
>>> to_key_val_list({'key': 'val'})
[('key', 'val')]
>>> to_key_val_list('string')
ValueError: cannot encode objects that are not 2-tuples.
"""
if value is None:
return None
if isinstance(value, (str, bytes, bool, int)):
raise ValueError('cannot encode objects that are not 2-tuples')
if isinstance(value, dict):
value = value.items()
return list(value)
# From mitsuhiko/werkzeug (used with permission).
def parse_list_header(value):
"""Parse lists as described by RFC 2068 Section 2.
In particular, parse comma-separated lists where the elements of
the list may include quoted-strings. A quoted-string could
contain a comma. A non-quoted string could have quotes in the
middle. Quotes are removed automatically after parsing.
It basically works like :func:`parse_set_header` just that items
may appear multiple times and case sensitivity is preserved.
The return value is a standard :class:`list`:
>>> parse_list_header('token, "quoted value"')
['token', 'quoted value']
To create a header from the :class:`list` again, use the
:func:`dump_header` function.
:param value: a string with a list header.
:return: :class:`list`
"""
result = []
for item in _parse_list_header(value):
if item[:1] == item[-1:] == '"':
item = unquote_header_value(item[1:-1])
result.append(item)
return result
# From mitsuhiko/werkzeug (used with permission).
def parse_dict_header(value):
"""Parse lists of key, value pairs as described by RFC 2068 Section 2 and
convert them into a python dict:
>>> d = parse_dict_header('foo="is a fish", bar="as well"')
>>> type(d) is dict
True
>>> sorted(d.items())
[('bar', 'as well'), ('foo', 'is a fish')]
If there is no value for a key it will be `None`:
>>> parse_dict_header('key_without_value')
{'key_without_value': None}
To create a header from the :class:`dict` again, use the
:func:`dump_header` function.
:param value: a string with a dict header.
:return: :class:`dict`
"""
result = {}
for item in _parse_list_header(value):
if '=' not in item:
result[item] = None
continue
name, value = item.split('=', 1)
if value[:1] == value[-1:] == '"':
value = unquote_header_value(value[1:-1])
result[name] = value
return result
# From mitsuhiko/werkzeug (used with permission).
def unquote_header_value(value, is_filename=False):
r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
This does not use the real unquoting but what browsers are actually
using for quoting.
:param value: the header value to unquote.
"""
if value and value[0] == value[-1] == '"':
# this is not the real unquoting, but fixing this so that the
# RFC is met will result in bugs with internet explorer and
# probably some other browsers as well. IE for example is
# uploading files with "C:\foo\bar.txt" as filename
value = value[1:-1]
# if this is a filename and the starting characters look like
# a UNC path, then just return the value without quotes. Using the
# replace sequence below on a UNC path has the effect of turning
# the leading double slash into a single slash and then
# _fix_ie_filename() doesn't work correctly. See #458.
if not is_filename or value[:2] != '\\\\':
return value.replace('\\\\', '\\').replace('\\"', '"')
return value
def dict_from_cookiejar(cj):
"""Returns a key/value dictionary from a CookieJar.
:param cj: CookieJar object to extract cookies from.
"""
cookie_dict = {}
for cookie in cj:
cookie_dict[cookie.name] = cookie.value
return cookie_dict
def add_dict_to_cookiejar(cj, cookie_dict):
"""Returns a CookieJar from a key/value dictionary.
:param cj: CookieJar to insert cookies into.
:param cookie_dict: Dict of key/values to insert into CookieJar.
"""
cj2 = cookiejar_from_dict(cookie_dict)
for cookie in cj2:
cj.set_cookie(cookie)
return cj
def get_encodings_from_content(content):
"""Returns encodings from given content string.
:param content: bytestring to extract encodings from.
"""
charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
return charset_re.findall(content)
def get_encoding_from_headers(headers):
"""Returns encodings from given HTTP Header Dict.
:param headers: dictionary to extract encoding from.
"""
content_type = headers.get('content-type')
if not content_type:
return None
content_type, params = cgi.parse_header(content_type)
if 'charset' in params:
return params['charset'].strip("'\"")
if 'text' in content_type:
return 'ISO-8859-1'
def stream_decode_response_unicode(iterator, r):
"""Stream decodes a iterator."""
if r.encoding is None:
for item in iterator:
yield item
return
decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace')
for chunk in iterator:
rv = decoder.decode(chunk)
if rv:
yield rv
rv = decoder.decode('', final=True)
if rv:
yield rv
def iter_slices(string, slice_length):
"""Iterate over slices of a string."""
pos = 0
while pos < len(string):
yield string[pos:pos + slice_length]
pos += slice_length
def get_unicode_from_response(r):
"""Returns the requested content back in unicode.
:param r: Response object to get unicode content from.
Tried:
1. charset from content-type
2. every encodings from ``<meta ... charset=XXX>``
3. fall back and replace all unicode characters
"""
tried_encodings = []
# Try charset from content-type
encoding = get_encoding_from_headers(r.headers)
if encoding:
try:
return str(r.content, encoding)
except UnicodeError:
tried_encodings.append(encoding)
# Fall back:
try:
return str(r.content, encoding, errors='replace')
except TypeError:
return r.content
def stream_decompress(iterator, mode='gzip'):
"""Stream decodes an iterator over compressed data
:param iterator: An iterator over compressed data
:param mode: 'gzip' or 'deflate'
:return: An iterator over decompressed data
"""
if mode not in ['gzip', 'deflate']:
raise ValueError('stream_decompress mode must be gzip or deflate')
zlib_mode = 16 + zlib.MAX_WBITS if mode == 'gzip' else -zlib.MAX_WBITS
dec = zlib.decompressobj(zlib_mode)
try:
for chunk in iterator:
rv = dec.decompress(chunk)
if rv:
yield rv
except zlib.error:
# If there was an error decompressing, just return the raw chunk
yield chunk
# Continue to return the rest of the raw data
for chunk in iterator:
yield chunk
else:
# Make sure everything has been returned from the decompression object
buf = dec.decompress(bytes())
rv = buf + dec.flush()
if rv:
yield rv
def stream_untransfer(gen, resp):
ce = resp.headers.get('content-encoding', '').lower()
if 'gzip' in ce:
gen = stream_decompress(gen, mode='gzip')
elif 'deflate' in ce:
gen = stream_decompress(gen, mode='deflate')
return gen
# The unreserved URI characters (RFC 3986)
UNRESERVED_SET = frozenset(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
+ "0123456789-._~")
def unquote_unreserved(uri):
"""Un-escape any percent-escape sequences in a URI that are unreserved
characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
"""
parts = uri.split('%')
for i in range(1, len(parts)):
h = parts[i][0:2]
if len(h) == 2 and h.isalnum():
c = chr(int(h, 16))
if c in UNRESERVED_SET:
parts[i] = c + parts[i][2:]
else:
parts[i] = '%' + parts[i]
else:
parts[i] = '%' + parts[i]
return ''.join(parts)
def requote_uri(uri):
"""Re-quote the given URI.
This function passes the given URI through an unquote/quote cycle to
ensure that it is fully and consistently quoted.
"""
# Unquote only the unreserved characters
# Then quote only illegal characters (do not quote reserved, unreserved,
# or '%')
return quote(unquote_unreserved(uri), safe="!#$%&'()*+,/:;=?@[]~")
def get_environ_proxies(url):
"""Return a dict of environment proxies."""
proxy_keys = [
'all',
'http',
'https',
'ftp',
'socks'
]
get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())
# First check whether no_proxy is defined. If it is, check that the URL
# we're getting isn't in the no_proxy list.
no_proxy = get_proxy('no_proxy')
if no_proxy:
# We need to check whether we match here. We need to see if we match
# the end of the netloc, both with and without the port.
no_proxy = no_proxy.split(',')
netloc = urlparse(url).netloc
for host in no_proxy:
if netloc.endswith(host) or netloc.split(':')[0].endswith(host):
# The URL does match something in no_proxy, so we don't want
# to apply the proxies on this URL.
return {}
# If we get here, we either didn't have no_proxy set or we're not going
# anywhere that no_proxy applies to.
proxies = [(key, get_proxy(key + '_proxy')) for key in proxy_keys]
return dict([(key, val) for (key, val) in proxies if val])
def default_user_agent():
"""Return a string representing the default user agent."""
_implementation = platform.python_implementation()
if _implementation == 'CPython':
_implementation_version = platform.python_version()
elif _implementation == 'PyPy':
_implementation_version = '%s.%s.%s' % (
sys.pypy_version_info.major,
sys.pypy_version_info.minor,
sys.pypy_version_info.micro
)
if sys.pypy_version_info.releaselevel != 'final':
_implementation_version = ''.join([_implementation_version, sys.pypy_version_info.releaselevel])
elif _implementation == 'Jython':
_implementation_version = platform.python_version() # Complete Guess
elif _implementation == 'IronPython':
_implementation_version = platform.python_version() # Complete Guess
else:
_implementation_version = 'Unknown'
try:
p_system = platform.system()
p_release = platform.release()
except IOError:
p_system = 'Unknown'
p_release = 'Unknown'
return " ".join([
'python-requests/%s' % __version__,
'%s/%s' % (_implementation, _implementation_version),
'%s/%s' % (p_system, p_release),
])
def default_headers():
return {
'User-Agent': default_user_agent(),
'Accept-Encoding': ', '.join(('gzip', 'deflate', 'compress')),
'Accept': '*/*'
}
def parse_header_links(value):
"""Return a dict of parsed link headers proxies.
i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"
"""
links = []
replace_chars = " '\""
for val in value.split(","):
try:
url, params = val.split(";", 1)
except ValueError:
url, params = val, ''
link = {}
link["url"] = url.strip("<> '\"")
for param in params.split(";"):
try:
key,value = param.split("=")
except ValueError:
break
link[key.strip(replace_chars)] = value.strip(replace_chars)
links.append(link)
return links
# Null bytes; no need to recreate these on each call to guess_json_utf
_null = '\x00'.encode('ascii') # encoding to ASCII for Python 3
_null2 = _null * 2
_null3 = _null * 3
def guess_json_utf(data):
# JSON always starts with two ASCII characters, so detection is as
# easy as counting the nulls and from their location and count
# determine the encoding. Also detect a BOM, if present.
sample = data[:4]
if sample in (codecs.BOM_UTF32_LE, codecs.BOM32_BE):
return 'utf-32' # BOM included
if sample[:3] == codecs.BOM_UTF8:
return 'utf-8-sig' # BOM included, MS style (discouraged)
if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):
return 'utf-16' # BOM included
nullcount = sample.count(_null)
if nullcount == 0:
return 'utf-8'
if nullcount == 2:
if sample[::2] == _null2: # 1st and 3rd are null
return 'utf-16-be'
if sample[1::2] == _null2: # 2nd and 4th are null
return 'utf-16-le'
# Did not detect 2 valid UTF-16 ascii-range characters
if nullcount == 3:
if sample[:3] == _null3:
return 'utf-32-be'
if sample[1:] == _null3:
return 'utf-32-le'
# Did not detect a valid UTF-32 ascii-range character
return None
|
unknown
|
codeparrot/codeparrot-clean
| ||
# This file is part of SickRage.
#
# URL: https://www.sickrage.tv
# Git: https://github.com/SiCKRAGETV/SickRage.git
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# SickRage is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with SickRage. If not, see <http://www.gnu.org/licenses/>.
from sickbeard.image_cache import ImageCache
from sickrage.media.GenericMedia import GenericMedia
class ShowFanArt(GenericMedia):
"""
Get the fan art of a show
"""
def get_default_media_name(self):
return 'fanart.png'
def get_media_path(self):
if self.get_show():
return ImageCache().fanart_path(self.indexer_id)
return ''
|
unknown
|
codeparrot/codeparrot-clean
| ||
{
"kind": "Dashboard",
"apiVersion": "dashboard.grafana.app/v2beta1",
"metadata": {
"name": "v0alpha1.graph_y_axis.v42"
},
"spec": {
"annotations": [
{
"kind": "AnnotationQuery",
"spec": {
"query": {
"kind": "DataQuery",
"group": "",
"version": "v0",
"spec": {}
},
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations \u0026 Alerts",
"builtIn": true,
"legacyOptions": {
"type": "dashboard"
}
}
}
],
"cursorSync": "Off",
"editable": true,
"elements": {
"panel-10": {
"kind": "Panel",
"spec": {
"id": 10,
"title": "Data from 0 - 1B (unit bytes)",
"description": "",
"links": [],
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"query": {
"kind": "DataQuery",
"group": "grafana-testdata-datasource",
"version": "v0",
"datasource": {
"name": "testdata-type-uid"
},
"spec": {
"scenarioId": "csv_metric_values",
"stringInput": "0,10000000000"
}
},
"refId": "A",
"hidden": false
}
}
],
"transformations": [],
"queryOptions": {}
}
},
"vizConfig": {
"kind": "VizConfig",
"group": "timeseries",
"version": "",
"spec": {
"options": {
"__angularMigration": {
"autoMigrateFrom": "graph",
"originalOptions": {
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"fill": 1,
"fillGradient": 0,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"percentage": false,
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"thresholds": [],
"timeRegions": [],
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "decbytes",
"label": "",
"logBase": 1,
"min": "0",
"show": true
},
{
"format": "short",
"logBase": 1,
"show": true
}
],
"yaxis": {
"align": false
}
}
},
"dataLinks": []
},
"fieldConfig": {
"defaults": {},
"overrides": []
}
}
}
}
},
"panel-2": {
"kind": "Panel",
"spec": {
"id": 2,
"title": "Data from 0 - 10K (unit short)",
"description": "",
"links": [],
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"query": {
"kind": "DataQuery",
"group": "grafana-testdata-datasource",
"version": "v0",
"datasource": {
"name": "testdata-type-uid"
},
"spec": {
"scenarioId": "csv_metric_values",
"stringInput": "0,500,1000,3000,2500,4000,4500,5000,7000,7500,8000,8500,9000,9500,10000"
}
},
"refId": "A",
"hidden": false
}
}
],
"transformations": [],
"queryOptions": {}
}
},
"vizConfig": {
"kind": "VizConfig",
"group": "timeseries",
"version": "",
"spec": {
"options": {
"__angularMigration": {
"autoMigrateFrom": "graph",
"originalOptions": {
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"fill": 1,
"fillGradient": 0,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"percentage": false,
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"thresholds": [],
"timeRegions": [],
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"logBase": 1,
"max": "10000",
"min": "0",
"show": true
},
{
"format": "short",
"logBase": 1,
"show": true
}
],
"yaxis": {
"align": false
}
}
},
"dataLinks": []
},
"fieldConfig": {
"defaults": {},
"overrides": []
}
}
}
}
},
"panel-3": {
"kind": "Panel",
"spec": {
"id": 3,
"title": "Data from 0.0002 - 0.001 (unit short)",
"description": "",
"links": [],
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"query": {
"kind": "DataQuery",
"group": "grafana-testdata-datasource",
"version": "v0",
"datasource": {
"name": "testdata-type-uid"
},
"spec": {
"scenarioId": "csv_metric_values",
"stringInput": "0.001,0.0002,0.0003"
}
},
"refId": "A",
"hidden": false
}
}
],
"transformations": [],
"queryOptions": {}
}
},
"vizConfig": {
"kind": "VizConfig",
"group": "timeseries",
"version": "",
"spec": {
"options": {
"__angularMigration": {
"autoMigrateFrom": "graph",
"originalOptions": {
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"fill": 1,
"fillGradient": 0,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"percentage": false,
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"thresholds": [],
"timeRegions": [],
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"logBase": 1,
"show": true
},
{
"format": "short",
"logBase": 1,
"show": true
}
],
"yaxis": {
"align": false
}
}
},
"dataLinks": []
},
"fieldConfig": {
"defaults": {},
"overrides": []
}
}
}
}
},
"panel-4": {
"kind": "Panel",
"spec": {
"id": 4,
"title": "Data from 0 - 10K (unit bytes IEC)",
"description": "",
"links": [],
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"query": {
"kind": "DataQuery",
"group": "grafana-testdata-datasource",
"version": "v0",
"datasource": {
"name": "testdata-type-uid"
},
"spec": {
"scenarioId": "csv_metric_values",
"stringInput": "0,500,1000,3000,2500,4000,4500,5000,7000,7500,8000,8500,9000,9500,10000"
}
},
"refId": "A",
"hidden": false
}
}
],
"transformations": [],
"queryOptions": {}
}
},
"vizConfig": {
"kind": "VizConfig",
"group": "timeseries",
"version": "",
"spec": {
"options": {
"__angularMigration": {
"autoMigrateFrom": "graph",
"originalOptions": {
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"fill": 1,
"fillGradient": 0,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"percentage": false,
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"thresholds": [],
"timeRegions": [],
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "bytes",
"logBase": 1,
"max": "10000",
"min": "0",
"show": true
},
{
"format": "short",
"logBase": 1,
"show": true
}
],
"yaxis": {
"align": false
}
}
},
"dataLinks": []
},
"fieldConfig": {
"defaults": {},
"overrides": []
}
}
}
}
},
"panel-5": {
"kind": "Panel",
"spec": {
"id": 5,
"title": "Data from 0 - 10K (unit bytes metric)",
"description": "",
"links": [],
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"query": {
"kind": "DataQuery",
"group": "grafana-testdata-datasource",
"version": "v0",
"datasource": {
"name": "testdata-type-uid"
},
"spec": {
"scenarioId": "csv_metric_values",
"stringInput": "0,500,1000,3000,2500,4000,4500,5000,7000,7500,8000,8500,9000,9500,10000"
}
},
"refId": "A",
"hidden": false
}
}
],
"transformations": [],
"queryOptions": {}
}
},
"vizConfig": {
"kind": "VizConfig",
"group": "timeseries",
"version": "",
"spec": {
"options": {
"__angularMigration": {
"autoMigrateFrom": "graph",
"originalOptions": {
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"fill": 1,
"fillGradient": 0,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"percentage": false,
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"thresholds": [],
"timeRegions": [],
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "decbytes",
"logBase": 1,
"max": "10000",
"min": "0",
"show": true
},
{
"format": "short",
"logBase": 1,
"show": true
}
],
"yaxis": {
"align": false
}
}
},
"dataLinks": []
},
"fieldConfig": {
"defaults": {},
"overrides": []
}
}
}
}
},
"panel-6": {
"kind": "Panel",
"spec": {
"id": 6,
"title": "Data from 12000 - 30000 (unit ms)",
"description": "",
"links": [],
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"query": {
"kind": "DataQuery",
"group": "grafana-testdata-datasource",
"version": "v0",
"datasource": {
"name": "testdata-type-uid"
},
"spec": {
"scenarioId": "csv_metric_values",
"stringInput": "12000,15000,20000"
}
},
"refId": "A",
"hidden": false
}
}
],
"transformations": [],
"queryOptions": {}
}
},
"vizConfig": {
"kind": "VizConfig",
"group": "timeseries",
"version": "",
"spec": {
"options": {
"__angularMigration": {
"autoMigrateFrom": "graph",
"originalOptions": {
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"fill": 1,
"fillGradient": 0,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"percentage": false,
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"thresholds": [],
"timeRegions": [],
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "ms",
"logBase": 1,
"show": true
},
{
"format": "short",
"logBase": 1,
"show": true
}
],
"yaxis": {
"align": false
}
}
},
"dataLinks": []
},
"fieldConfig": {
"defaults": {},
"overrides": []
}
}
}
}
},
"panel-7": {
"kind": "Panel",
"spec": {
"id": 7,
"title": "Data from 0 - 10K (unit short)",
"description": "",
"links": [],
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"query": {
"kind": "DataQuery",
"group": "grafana-testdata-datasource",
"version": "v0",
"datasource": {
"name": "testdata-type-uid"
},
"spec": {
"scenarioId": "csv_metric_values",
"stringInput": "0,500,1000,3000,2500,4000,4500,5000,7000,7500,8000,8500,9000,9500,10000"
}
},
"refId": "A",
"hidden": false
}
}
],
"transformations": [],
"queryOptions": {}
}
},
"vizConfig": {
"kind": "VizConfig",
"group": "timeseries",
"version": "",
"spec": {
"options": {
"__angularMigration": {
"autoMigrateFrom": "graph",
"originalOptions": {
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"fill": 1,
"fillGradient": 0,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"percentage": false,
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"thresholds": [],
"timeRegions": [],
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"logBase": 1,
"max": "10000",
"min": "0",
"show": true
},
{
"format": "short",
"logBase": 1,
"show": true
}
],
"yaxis": {
"align": false
}
}
},
"dataLinks": []
},
"fieldConfig": {
"defaults": {},
"overrides": []
}
}
}
}
},
"panel-8": {
"kind": "Panel",
"spec": {
"id": 8,
"title": "Data from 12000 - 30000 (unit ms)",
"description": "",
"links": [],
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"query": {
"kind": "DataQuery",
"group": "grafana-testdata-datasource",
"version": "v0",
"datasource": {
"name": "testdata-type-uid"
},
"spec": {
"scenarioId": "csv_metric_values",
"stringInput": "12000,15000,20000"
}
},
"refId": "A",
"hidden": false
}
}
],
"transformations": [],
"queryOptions": {}
}
},
"vizConfig": {
"kind": "VizConfig",
"group": "timeseries",
"version": "",
"spec": {
"options": {
"__angularMigration": {
"autoMigrateFrom": "graph",
"originalOptions": {
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"fill": 1,
"fillGradient": 0,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"percentage": false,
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"thresholds": [],
"timeRegions": [],
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "ms",
"logBase": 1,
"show": true
},
{
"format": "short",
"logBase": 1,
"show": true
}
],
"yaxis": {
"align": false
}
}
},
"dataLinks": []
},
"fieldConfig": {
"defaults": {},
"overrides": []
}
}
}
}
},
"panel-9": {
"kind": "Panel",
"spec": {
"id": 9,
"title": "Data from 0 - 1B (unit short)",
"description": "",
"links": [],
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"query": {
"kind": "DataQuery",
"group": "grafana-testdata-datasource",
"version": "v0",
"datasource": {
"name": "testdata-type-uid"
},
"spec": {
"scenarioId": "csv_metric_values",
"stringInput": "0,10000000000"
}
},
"refId": "A",
"hidden": false
}
}
],
"transformations": [],
"queryOptions": {}
}
},
"vizConfig": {
"kind": "VizConfig",
"group": "timeseries",
"version": "",
"spec": {
"options": {
"__angularMigration": {
"autoMigrateFrom": "graph",
"originalOptions": {
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"fill": 1,
"fillGradient": 0,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 1,
"nullPointMode": "null",
"percentage": false,
"pointradius": 2,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"thresholds": [],
"timeRegions": [],
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"xaxis": {
"mode": "time",
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"logBase": 1,
"min": "0",
"show": true
},
{
"format": "short",
"logBase": 1,
"show": true
}
],
"yaxis": {
"align": false
}
}
},
"dataLinks": []
},
"fieldConfig": {
"defaults": {},
"overrides": []
}
}
}
}
}
},
"layout": {
"kind": "GridLayout",
"spec": {
"items": [
{
"kind": "GridLayoutItem",
"spec": {
"x": 0,
"y": 0,
"width": 8,
"height": 7,
"element": {
"kind": "ElementReference",
"name": "panel-7"
}
}
},
{
"kind": "GridLayoutItem",
"spec": {
"x": 8,
"y": 0,
"width": 8,
"height": 7,
"element": {
"kind": "ElementReference",
"name": "panel-5"
}
}
},
{
"kind": "GridLayoutItem",
"spec": {
"x": 16,
"y": 0,
"width": 8,
"height": 7,
"element": {
"kind": "ElementReference",
"name": "panel-4"
}
}
},
{
"kind": "GridLayoutItem",
"spec": {
"x": 0,
"y": 7,
"width": 8,
"height": 9,
"element": {
"kind": "ElementReference",
"name": "panel-2"
}
}
},
{
"kind": "GridLayoutItem",
"spec": {
"x": 8,
"y": 7,
"width": 8,
"height": 9,
"element": {
"kind": "ElementReference",
"name": "panel-3"
}
}
},
{
"kind": "GridLayoutItem",
"spec": {
"x": 16,
"y": 7,
"width": 8,
"height": 9,
"element": {
"kind": "ElementReference",
"name": "panel-6"
}
}
},
{
"kind": "GridLayoutItem",
"spec": {
"x": 0,
"y": 16,
"width": 8,
"height": 9,
"element": {
"kind": "ElementReference",
"name": "panel-9"
}
}
},
{
"kind": "GridLayoutItem",
"spec": {
"x": 8,
"y": 16,
"width": 8,
"height": 9,
"element": {
"kind": "ElementReference",
"name": "panel-10"
}
}
},
{
"kind": "GridLayoutItem",
"spec": {
"x": 16,
"y": 16,
"width": 8,
"height": 11,
"element": {
"kind": "ElementReference",
"name": "panel-8"
}
}
}
]
}
},
"links": [],
"liveNow": false,
"preload": false,
"tags": [
"gdev",
"panel-tests"
],
"timeSettings": {
"timezone": "",
"from": "now-6h",
"to": "now",
"autoRefresh": "",
"autoRefreshIntervals": [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
],
"hideTimepicker": false,
"fiscalYearStartMonth": 0
},
"title": "Panel Tests - Graph - Y axis ticks",
"variables": []
},
"status": {
"conversion": {
"failed": false,
"storedVersion": "v0alpha1"
}
}
}
|
json
|
github
|
https://github.com/grafana/grafana
|
apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/panel-graph/v0alpha1.graph_y_axis.v42.v2beta1.json
|
def __boot():
import sys
import os
PYTHONPATH = os.environ.get('PYTHONPATH')
if PYTHONPATH is None or (sys.platform == 'win32' and not PYTHONPATH):
PYTHONPATH = []
else:
PYTHONPATH = PYTHONPATH.split(os.pathsep)
pic = getattr(sys, 'path_importer_cache', {})
stdpath = sys.path[len(PYTHONPATH):]
mydir = os.path.dirname(__file__)
for item in stdpath:
if item == mydir or not item:
continue # skip if current dir. on Windows, or my own directory
importer = pic.get(item)
if importer is not None:
loader = importer.find_module('site')
if loader is not None:
# This should actually reload the current module
loader.load_module('site')
break
else:
try:
import imp # Avoid import loop in Python >= 3.3
stream, path, descr = imp.find_module('site', [item])
except ImportError:
continue
if stream is None:
continue
try:
# This should actually reload the current module
imp.load_module('site', stream, path, descr)
finally:
stream.close()
break
else:
raise ImportError("Couldn't find the real 'site' module")
known_paths = dict([(makepath(item)[1], 1) for item in sys.path]) # 2.2 comp
oldpos = getattr(sys, '__egginsert', 0) # save old insertion position
sys.__egginsert = 0 # and reset the current one
for item in PYTHONPATH:
addsitedir(item)
sys.__egginsert += oldpos # restore effective old position
d, nd = makepath(stdpath[0])
insert_at = None
new_path = []
for item in sys.path:
p, np = makepath(item)
if np == nd and insert_at is None:
# We've hit the first 'system' path entry, so added entries go here
insert_at = len(new_path)
if np in known_paths or insert_at is None:
new_path.append(item)
else:
# new path after the insert point, back-insert it
new_path.insert(insert_at, item)
insert_at += 1
sys.path[:] = new_path
if __name__ == 'site':
__boot()
del __boot
|
unknown
|
codeparrot/codeparrot-clean
| ||
"""
Extended math utilities.
"""
# Authors: Gael Varoquaux
# Alexandre Gramfort
# Alexandre T. Passos
# Olivier Grisel
# Lars Buitinck
# Stefan van der Walt
# Kyle Kastner
# Giorgio Patrini
# License: BSD 3 clause
from __future__ import division
from functools import partial
import warnings
import numpy as np
from scipy import linalg
from scipy.sparse import issparse, csr_matrix
from scipy.misc import logsumexp as scipy_logsumexp
from . import check_random_state, deprecated
from .fixes import np_version
from ._logistic_sigmoid import _log_logistic_sigmoid
from ..externals.six.moves import xrange
from .sparsefuncs_fast import csr_row_norms
from .validation import check_array
from ..exceptions import NonBLASDotWarning
@deprecated("sklearn.utils.extmath.norm was deprecated in version 0.19"
"and will be removed in 0.21. Use scipy.linalg.norm instead.")
def norm(x):
"""Compute the Euclidean or Frobenius norm of x.
Returns the Euclidean norm when x is a vector, the Frobenius norm when x
is a matrix (2-d array). More precise than sqrt(squared_norm(x)).
"""
return linalg.norm(x)
# Newer NumPy has a ravel that needs less copying.
if np_version < (1, 7, 1):
_ravel = np.ravel
else:
_ravel = partial(np.ravel, order='K')
def squared_norm(x):
"""Squared Euclidean or Frobenius norm of x.
Returns the Euclidean norm when x is a vector, the Frobenius norm when x
is a matrix (2-d array). Faster than norm(x) ** 2.
"""
x = _ravel(x)
if np.issubdtype(x.dtype, np.integer):
warnings.warn('Array type is integer, np.dot may overflow. '
'Data should be float type to avoid this issue',
UserWarning)
return np.dot(x, x)
def row_norms(X, squared=False):
"""Row-wise (squared) Euclidean norm of X.
Equivalent to np.sqrt((X * X).sum(axis=1)), but also supports sparse
matrices and does not create an X.shape-sized temporary.
Performs no input validation.
"""
if issparse(X):
if not isinstance(X, csr_matrix):
X = csr_matrix(X)
norms = csr_row_norms(X)
else:
norms = np.einsum('ij,ij->i', X, X)
if not squared:
np.sqrt(norms, norms)
return norms
def fast_logdet(A):
"""Compute log(det(A)) for A symmetric
Equivalent to : np.log(nl.det(A)) but more robust.
It returns -Inf if det(A) is non positive or is not defined.
"""
sign, ld = np.linalg.slogdet(A)
if not sign > 0:
return -np.inf
return ld
def _impose_f_order(X):
"""Helper Function"""
# important to access flags instead of calling np.isfortran,
# this catches corner cases.
if X.flags.c_contiguous:
return check_array(X.T, copy=False, order='F'), True
else:
return check_array(X, copy=False, order='F'), False
def _fast_dot(A, B):
if B.shape[0] != A.shape[A.ndim - 1]: # check adopted from '_dotblas.c'
raise ValueError
if A.dtype != B.dtype or any(x.dtype not in (np.float32, np.float64)
for x in [A, B]):
warnings.warn('Falling back to np.dot. '
'Data must be of same type of either '
'32 or 64 bit float for the BLAS function, gemm, to be '
'used for an efficient dot operation. ',
NonBLASDotWarning)
raise ValueError
if min(A.shape) == 1 or min(B.shape) == 1 or A.ndim != 2 or B.ndim != 2:
raise ValueError
# scipy 0.9 compliant API
dot = linalg.get_blas_funcs(['gemm'], (A, B))[0]
A, trans_a = _impose_f_order(A)
B, trans_b = _impose_f_order(B)
return dot(alpha=1.0, a=A, b=B, trans_a=trans_a, trans_b=trans_b)
def _have_blas_gemm():
try:
linalg.get_blas_funcs(['gemm'])
return True
except (AttributeError, ValueError):
warnings.warn('Could not import BLAS, falling back to np.dot')
return False
# Only use fast_dot for older NumPy; newer ones have tackled the speed issue.
if np_version < (1, 7, 2) and _have_blas_gemm():
def fast_dot(A, B):
"""Compute fast dot products directly calling BLAS.
This function calls BLAS directly while warranting Fortran contiguity.
This helps avoiding extra copies `np.dot` would have created.
For details see section `Linear Algebra on large Arrays`:
http://wiki.scipy.org/PerformanceTips
Parameters
----------
A, B: instance of np.ndarray
Input arrays. Arrays are supposed to be of the same dtype and to
have exactly 2 dimensions. Currently only floats are supported.
In case these requirements aren't met np.dot(A, B) is returned
instead. To activate the related warning issued in this case
execute the following lines of code:
>> import warnings
>> from sklearn.exceptions import NonBLASDotWarning
>> warnings.simplefilter('always', NonBLASDotWarning)
"""
try:
return _fast_dot(A, B)
except ValueError:
# Maltyped or malformed data.
return np.dot(A, B)
else:
fast_dot = np.dot
def density(w, **kwargs):
"""Compute density of a sparse vector
Return a value between 0 and 1
"""
if hasattr(w, "toarray"):
d = float(w.nnz) / (w.shape[0] * w.shape[1])
else:
d = 0 if w is None else float((w != 0).sum()) / w.size
return d
def safe_sparse_dot(a, b, dense_output=False):
"""Dot product that handle the sparse matrix case correctly
Uses BLAS GEMM as replacement for numpy.dot where possible
to avoid unnecessary copies.
"""
if issparse(a) or issparse(b):
ret = a * b
if dense_output and hasattr(ret, "toarray"):
ret = ret.toarray()
return ret
else:
return fast_dot(a, b)
def randomized_range_finder(A, size, n_iter,
power_iteration_normalizer='auto',
random_state=None):
"""Computes an orthonormal matrix whose range approximates the range of A.
Parameters
----------
A : 2D array
The input data matrix
size : integer
Size of the return array
n_iter : integer
Number of power iterations used to stabilize the result
power_iteration_normalizer : 'auto' (default), 'QR', 'LU', 'none'
Whether the power iterations are normalized with step-by-step
QR factorization (the slowest but most accurate), 'none'
(the fastest but numerically unstable when `n_iter` is large, e.g.
typically 5 or larger), or 'LU' factorization (numerically stable
but can lose slightly in accuracy). The 'auto' mode applies no
normalization if `n_iter`<=2 and switches to LU otherwise.
.. versionadded:: 0.18
random_state : int, RandomState instance or None, optional (default=None)
The seed of the pseudo random number generator to use when shuffling
the data. If int, random_state is the seed used by the random number
generator; If RandomState instance, random_state is the random number
generator; If None, the random number generator is the RandomState
instance used by `np.random`.
Returns
-------
Q : 2D array
A (size x size) projection matrix, the range of which
approximates well the range of the input matrix A.
Notes
-----
Follows Algorithm 4.3 of
Finding structure with randomness: Stochastic algorithms for constructing
approximate matrix decompositions
Halko, et al., 2009 (arXiv:909) http://arxiv.org/pdf/0909.4061
An implementation of a randomized algorithm for principal component
analysis
A. Szlam et al. 2014
"""
random_state = check_random_state(random_state)
# Generating normal random vectors with shape: (A.shape[1], size)
Q = random_state.normal(size=(A.shape[1], size))
# Deal with "auto" mode
if power_iteration_normalizer == 'auto':
if n_iter <= 2:
power_iteration_normalizer = 'none'
else:
power_iteration_normalizer = 'LU'
# Perform power iterations with Q to further 'imprint' the top
# singular vectors of A in Q
for i in range(n_iter):
if power_iteration_normalizer == 'none':
Q = safe_sparse_dot(A, Q)
Q = safe_sparse_dot(A.T, Q)
elif power_iteration_normalizer == 'LU':
Q, _ = linalg.lu(safe_sparse_dot(A, Q), permute_l=True)
Q, _ = linalg.lu(safe_sparse_dot(A.T, Q), permute_l=True)
elif power_iteration_normalizer == 'QR':
Q, _ = linalg.qr(safe_sparse_dot(A, Q), mode='economic')
Q, _ = linalg.qr(safe_sparse_dot(A.T, Q), mode='economic')
# Sample the range of A using by linear projection of Q
# Extract an orthonormal basis
Q, _ = linalg.qr(safe_sparse_dot(A, Q), mode='economic')
return Q
def randomized_svd(M, n_components, n_oversamples=10, n_iter='auto',
power_iteration_normalizer='auto', transpose='auto',
flip_sign=True, random_state=0):
"""Computes a truncated randomized SVD
Parameters
----------
M : ndarray or sparse matrix
Matrix to decompose
n_components : int
Number of singular values and vectors to extract.
n_oversamples : int (default is 10)
Additional number of random vectors to sample the range of M so as
to ensure proper conditioning. The total number of random vectors
used to find the range of M is n_components + n_oversamples. Smaller
number can improve speed but can negatively impact the quality of
approximation of singular vectors and singular values.
n_iter : int or 'auto' (default is 'auto')
Number of power iterations. It can be used to deal with very noisy
problems. When 'auto', it is set to 4, unless `n_components` is small
(< .1 * min(X.shape)) `n_iter` in which case is set to 7.
This improves precision with few components.
.. versionchanged:: 0.18
power_iteration_normalizer : 'auto' (default), 'QR', 'LU', 'none'
Whether the power iterations are normalized with step-by-step
QR factorization (the slowest but most accurate), 'none'
(the fastest but numerically unstable when `n_iter` is large, e.g.
typically 5 or larger), or 'LU' factorization (numerically stable
but can lose slightly in accuracy). The 'auto' mode applies no
normalization if `n_iter`<=2 and switches to LU otherwise.
.. versionadded:: 0.18
transpose : True, False or 'auto' (default)
Whether the algorithm should be applied to M.T instead of M. The
result should approximately be the same. The 'auto' mode will
trigger the transposition if M.shape[1] > M.shape[0] since this
implementation of randomized SVD tend to be a little faster in that
case.
.. versionchanged:: 0.18
flip_sign : boolean, (True by default)
The output of a singular value decomposition is only unique up to a
permutation of the signs of the singular vectors. If `flip_sign` is
set to `True`, the sign ambiguity is resolved by making the largest
loadings for each component in the left singular vectors positive.
random_state : int, RandomState instance or None, optional (default=None)
The seed of the pseudo random number generator to use when shuffling
the data. If int, random_state is the seed used by the random number
generator; If RandomState instance, random_state is the random number
generator; If None, the random number generator is the RandomState
instance used by `np.random`.
Notes
-----
This algorithm finds a (usually very good) approximate truncated
singular value decomposition using randomization to speed up the
computations. It is particularly fast on large matrices on which
you wish to extract only a small number of components. In order to
obtain further speed up, `n_iter` can be set <=2 (at the cost of
loss of precision).
References
----------
* Finding structure with randomness: Stochastic algorithms for constructing
approximate matrix decompositions
Halko, et al., 2009 http://arxiv.org/abs/arXiv:0909.4061
* A randomized algorithm for the decomposition of matrices
Per-Gunnar Martinsson, Vladimir Rokhlin and Mark Tygert
* An implementation of a randomized algorithm for principal component
analysis
A. Szlam et al. 2014
"""
random_state = check_random_state(random_state)
n_random = n_components + n_oversamples
n_samples, n_features = M.shape
if n_iter == 'auto':
# Checks if the number of iterations is explicitely specified
# Adjust n_iter. 7 was found a good compromise for PCA. See #5299
n_iter = 7 if n_components < .1 * min(M.shape) else 4
if transpose == 'auto':
transpose = n_samples < n_features
if transpose:
# this implementation is a bit faster with smaller shape[1]
M = M.T
Q = randomized_range_finder(M, n_random, n_iter,
power_iteration_normalizer, random_state)
# project M to the (k + p) dimensional space using the basis vectors
B = safe_sparse_dot(Q.T, M)
# compute the SVD on the thin matrix: (k + p) wide
Uhat, s, V = linalg.svd(B, full_matrices=False)
del B
U = np.dot(Q, Uhat)
if flip_sign:
if not transpose:
U, V = svd_flip(U, V)
else:
# In case of transpose u_based_decision=false
# to actually flip based on u and not v.
U, V = svd_flip(U, V, u_based_decision=False)
if transpose:
# transpose back the results according to the input convention
return V[:n_components, :].T, s[:n_components], U[:, :n_components].T
else:
return U[:, :n_components], s[:n_components], V[:n_components, :]
@deprecated("sklearn.utils.extmath.logsumexp was deprecated in version 0.19"
"and will be removed in 0.21. Use scipy.misc.logsumexp instead.")
def logsumexp(arr, axis=0):
"""Computes the sum of arr assuming arr is in the log domain.
Returns log(sum(exp(arr))) while minimizing the possibility of
over/underflow.
Examples
--------
>>> import numpy as np
>>> from sklearn.utils.extmath import logsumexp
>>> a = np.arange(10)
>>> np.log(np.sum(np.exp(a)))
9.4586297444267107
>>> logsumexp(a)
9.4586297444267107
"""
return scipy_logsumexp(arr, axis)
def weighted_mode(a, w, axis=0):
"""Returns an array of the weighted modal (most common) value in a
If there is more than one such value, only the first is returned.
The bin-count for the modal bins is also returned.
This is an extension of the algorithm in scipy.stats.mode.
Parameters
----------
a : array_like
n-dimensional array of which to find mode(s).
w : array_like
n-dimensional array of weights for each value
axis : int, optional
Axis along which to operate. Default is 0, i.e. the first axis.
Returns
-------
vals : ndarray
Array of modal values.
score : ndarray
Array of weighted counts for each mode.
Examples
--------
>>> from sklearn.utils.extmath import weighted_mode
>>> x = [4, 1, 4, 2, 4, 2]
>>> weights = [1, 1, 1, 1, 1, 1]
>>> weighted_mode(x, weights)
(array([ 4.]), array([ 3.]))
The value 4 appears three times: with uniform weights, the result is
simply the mode of the distribution.
>>> weights = [1, 3, 0.5, 1.5, 1, 2] # deweight the 4's
>>> weighted_mode(x, weights)
(array([ 2.]), array([ 3.5]))
The value 2 has the highest score: it appears twice with weights of
1.5 and 2: the sum of these is 3.
See Also
--------
scipy.stats.mode
"""
if axis is None:
a = np.ravel(a)
w = np.ravel(w)
axis = 0
else:
a = np.asarray(a)
w = np.asarray(w)
axis = axis
if a.shape != w.shape:
w = np.zeros(a.shape, dtype=w.dtype) + w
scores = np.unique(np.ravel(a)) # get ALL unique values
testshape = list(a.shape)
testshape[axis] = 1
oldmostfreq = np.zeros(testshape)
oldcounts = np.zeros(testshape)
for score in scores:
template = np.zeros(a.shape)
ind = (a == score)
template[ind] = w[ind]
counts = np.expand_dims(np.sum(template, axis), axis)
mostfrequent = np.where(counts > oldcounts, score, oldmostfreq)
oldcounts = np.maximum(counts, oldcounts)
oldmostfreq = mostfrequent
return mostfrequent, oldcounts
@deprecated("sklearn.utils.extmath.pinvh was deprecated in version 0.19"
"and will be removed in 0.21. Use scipy.linalg.pinvh instead.")
def pinvh(a, cond=None, rcond=None, lower=True):
return linalg.pinvh(a, cond, rcond, lower)
def cartesian(arrays, out=None):
"""Generate a cartesian product of input arrays.
Parameters
----------
arrays : list of array-like
1-D arrays to form the cartesian product of.
out : ndarray
Array to place the cartesian product in.
Returns
-------
out : ndarray
2-D array of shape (M, len(arrays)) containing cartesian products
formed of input arrays.
Examples
--------
>>> cartesian(([1, 2, 3], [4, 5], [6, 7]))
array([[1, 4, 6],
[1, 4, 7],
[1, 5, 6],
[1, 5, 7],
[2, 4, 6],
[2, 4, 7],
[2, 5, 6],
[2, 5, 7],
[3, 4, 6],
[3, 4, 7],
[3, 5, 6],
[3, 5, 7]])
"""
arrays = [np.asarray(x) for x in arrays]
shape = (len(x) for x in arrays)
dtype = arrays[0].dtype
ix = np.indices(shape)
ix = ix.reshape(len(arrays), -1).T
if out is None:
out = np.empty_like(ix, dtype=dtype)
for n, arr in enumerate(arrays):
out[:, n] = arrays[n][ix[:, n]]
return out
def svd_flip(u, v, u_based_decision=True):
"""Sign correction to ensure deterministic output from SVD.
Adjusts the columns of u and the rows of v such that the loadings in the
columns in u that are largest in absolute value are always positive.
Parameters
----------
u, v : ndarray
u and v are the output of `linalg.svd` or
`sklearn.utils.extmath.randomized_svd`, with matching inner dimensions
so one can compute `np.dot(u * s, v)`.
u_based_decision : boolean, (default=True)
If True, use the columns of u as the basis for sign flipping.
Otherwise, use the rows of v. The choice of which variable to base the
decision on is generally algorithm dependent.
Returns
-------
u_adjusted, v_adjusted : arrays with the same dimensions as the input.
"""
if u_based_decision:
# columns of u, rows of v
max_abs_cols = np.argmax(np.abs(u), axis=0)
signs = np.sign(u[max_abs_cols, xrange(u.shape[1])])
u *= signs
v *= signs[:, np.newaxis]
else:
# rows of v, columns of u
max_abs_rows = np.argmax(np.abs(v), axis=1)
signs = np.sign(v[xrange(v.shape[0]), max_abs_rows])
u *= signs
v *= signs[:, np.newaxis]
return u, v
def log_logistic(X, out=None):
"""Compute the log of the logistic function, ``log(1 / (1 + e ** -x))``.
This implementation is numerically stable because it splits positive and
negative values::
-log(1 + exp(-x_i)) if x_i > 0
x_i - log(1 + exp(x_i)) if x_i <= 0
For the ordinary logistic function, use ``scipy.special.expit``.
Parameters
----------
X : array-like, shape (M, N) or (M, )
Argument to the logistic function
out : array-like, shape: (M, N) or (M, ), optional:
Preallocated output array.
Returns
-------
out : array, shape (M, N) or (M, )
Log of the logistic function evaluated at every point in x
Notes
-----
See the blog post describing this implementation:
http://fa.bianp.net/blog/2013/numerical-optimizers-for-logistic-regression/
"""
is_1d = X.ndim == 1
X = np.atleast_2d(X)
X = check_array(X, dtype=np.float64)
n_samples, n_features = X.shape
if out is None:
out = np.empty_like(X)
_log_logistic_sigmoid(n_samples, n_features, X, out)
if is_1d:
return np.squeeze(out)
return out
def softmax(X, copy=True):
"""
Calculate the softmax function.
The softmax function is calculated by
np.exp(X) / np.sum(np.exp(X), axis=1)
This will cause overflow when large values are exponentiated.
Hence the largest value in each row is subtracted from each data
point to prevent this.
Parameters
----------
X : array-like, shape (M, N)
Argument to the logistic function
copy : bool, optional
Copy X or not.
Returns
-------
out : array, shape (M, N)
Softmax function evaluated at every point in x
"""
if copy:
X = np.copy(X)
max_prob = np.max(X, axis=1).reshape((-1, 1))
X -= max_prob
np.exp(X, X)
sum_prob = np.sum(X, axis=1).reshape((-1, 1))
X /= sum_prob
return X
def safe_min(X):
"""Returns the minimum value of a dense or a CSR/CSC matrix.
Adapated from http://stackoverflow.com/q/13426580
"""
if issparse(X):
if len(X.data) == 0:
return 0
m = X.data.min()
return m if X.getnnz() == X.size else min(m, 0)
else:
return X.min()
def make_nonnegative(X, min_value=0):
"""Ensure `X.min()` >= `min_value`."""
min_ = safe_min(X)
if min_ < min_value:
if issparse(X):
raise ValueError("Cannot make the data matrix"
" nonnegative because it is sparse."
" Adding a value to every entry would"
" make it no longer sparse.")
X = X + (min_value - min_)
return X
def _incremental_mean_and_var(X, last_mean=.0, last_variance=None,
last_sample_count=0):
"""Calculate mean update and a Youngs and Cramer variance update.
last_mean and last_variance are statistics computed at the last step by the
function. Both must be initialized to 0.0. In case no scaling is required
last_variance can be None. The mean is always required and returned because
necessary for the calculation of the variance. last_n_samples_seen is the
number of samples encountered until now.
From the paper "Algorithms for computing the sample variance: analysis and
recommendations", by Chan, Golub, and LeVeque.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Data to use for variance update
last_mean : array-like, shape: (n_features,)
last_variance : array-like, shape: (n_features,)
last_sample_count : int
Returns
-------
updated_mean : array, shape (n_features,)
updated_variance : array, shape (n_features,)
If None, only mean is computed
updated_sample_count : int
References
----------
T. Chan, G. Golub, R. LeVeque. Algorithms for computing the sample
variance: recommendations, The American Statistician, Vol. 37, No. 3,
pp. 242-247
Also, see the sparse implementation of this in
`utils.sparsefuncs.incr_mean_variance_axis` and
`utils.sparsefuncs_fast.incr_mean_variance_axis0`
"""
# old = stats until now
# new = the current increment
# updated = the aggregated stats
last_sum = last_mean * last_sample_count
new_sum = X.sum(axis=0)
new_sample_count = X.shape[0]
updated_sample_count = last_sample_count + new_sample_count
updated_mean = (last_sum + new_sum) / updated_sample_count
if last_variance is None:
updated_variance = None
else:
new_unnormalized_variance = X.var(axis=0) * new_sample_count
if last_sample_count == 0: # Avoid division by 0
updated_unnormalized_variance = new_unnormalized_variance
else:
last_over_new_count = last_sample_count / new_sample_count
last_unnormalized_variance = last_variance * last_sample_count
updated_unnormalized_variance = (
last_unnormalized_variance +
new_unnormalized_variance +
last_over_new_count / updated_sample_count *
(last_sum / last_over_new_count - new_sum) ** 2)
updated_variance = updated_unnormalized_variance / updated_sample_count
return updated_mean, updated_variance, updated_sample_count
def _deterministic_vector_sign_flip(u):
"""Modify the sign of vectors for reproducibility
Flips the sign of elements of all the vectors (rows of u) such that
the absolute maximum element of each vector is positive.
Parameters
----------
u : ndarray
Array with vectors as its rows.
Returns
-------
u_flipped : ndarray with same shape as u
Array with the sign flipped vectors as its rows.
"""
max_abs_rows = np.argmax(np.abs(u), axis=1)
signs = np.sign(u[range(u.shape[0]), max_abs_rows])
u *= signs[:, np.newaxis]
return u
def stable_cumsum(arr, axis=None, rtol=1e-05, atol=1e-08):
"""Use high precision for cumsum and check that final value matches sum
Parameters
----------
arr : array-like
To be cumulatively summed as flat
axis : int, optional
Axis along which the cumulative sum is computed.
The default (None) is to compute the cumsum over the flattened array.
rtol : float
Relative tolerance, see ``np.allclose``
atol : float
Absolute tolerance, see ``np.allclose``
"""
# sum is as unstable as cumsum for numpy < 1.9
if np_version < (1, 9):
return np.cumsum(arr, axis=axis, dtype=np.float64)
out = np.cumsum(arr, axis=axis, dtype=np.float64)
expected = np.sum(arr, axis=axis, dtype=np.float64)
if not np.all(np.isclose(out.take(-1, axis=axis), expected, rtol=rtol,
atol=atol, equal_nan=True)):
warnings.warn('cumsum was found to be unstable: '
'its last element does not correspond to sum',
RuntimeWarning)
return out
|
unknown
|
codeparrot/codeparrot-clean
| ||
from django.db import models
from django.test import TestCase
class AbsoluteUrlOverrideTests(TestCase):
def test_get_absolute_url(self):
"""
get_absolute_url() functions as a normal method.
"""
get_absolute_url = lambda o: '/test-a/%s/' % o.pk
TestA = self._create_model_class('TestA', get_absolute_url)
self.assertTrue(hasattr(TestA, 'get_absolute_url'))
obj = TestA(pk=1, name='Foo')
self.assertEqual('/test-a/%s/' % obj.pk, obj.get_absolute_url())
def test_override_get_absolute_url(self):
"""
ABSOLUTE_URL_OVERRIDES should override get_absolute_url().
"""
get_absolute_url = lambda o: '/test-b/%s/' % o.pk
with self.settings(
ABSOLUTE_URL_OVERRIDES={
'absolute_url_overrides.testb': lambda o: '/overridden-test-b/%s/' % o.pk,
},
):
TestB = self._create_model_class('TestB', get_absolute_url)
obj = TestB(pk=1, name='Foo')
self.assertEqual('/overridden-test-b/%s/' % obj.pk, obj.get_absolute_url())
def test_insert_get_absolute_url(self):
"""
ABSOLUTE_URL_OVERRIDES should work even if the model doesn't have a
get_absolute_url() method.
"""
with self.settings(
ABSOLUTE_URL_OVERRIDES={
'absolute_url_overrides.testc': lambda o: '/test-c/%s/' % o.pk,
},
):
TestC = self._create_model_class('TestC')
obj = TestC(pk=1, name='Foo')
self.assertEqual('/test-c/%s/' % obj.pk, obj.get_absolute_url())
def _create_model_class(self, class_name, get_absolute_url_method=None):
attrs = {
'name': models.CharField(max_length=50),
'__module__': 'absolute_url_overrides',
}
if get_absolute_url_method:
attrs['get_absolute_url'] = get_absolute_url_method
return type(class_name, (models.Model,), attrs)
|
unknown
|
codeparrot/codeparrot-clean
| ||
#!/usr/bin/python
import unittest
import os
import sys
# simple magic for using scripts within a source tree
basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if os.path.isdir(os.path.join(basedir, 'virttest')):
sys.path.append(basedir)
from virttest import remote
from virttest import data_dir
class RemoteFileTest(unittest.TestCase):
tmp_dir = data_dir.get_tmp_dir()
test_file_path = os.path.join(tmp_dir, "remote_file")
default_data = ["RemoteFile Test.\n", "Pattern Line."]
def __del__(self):
if os.path.exists(self.test_file_path):
os.remove(self.test_file_path)
def _new_remote_file(self):
if os.path.exists(self.test_file_path):
os.remove(self.test_file_path)
test_file = open(self.test_file_path, "w")
test_file.writelines(self.default_data)
test_file.close()
remote_file = remote.RemoteFile(None, "test", None, None, None,
self.test_file_path)
return remote_file
def _read_test_file(self):
test_file = open(self.test_file_path, "r")
test_data = test_file.readlines()
test_file.close()
return test_data
def testAdd(self):
remote_file = self._new_remote_file()
_add_list = ["add_line_1", "add_line_2", "add_line_3"]
remote_file.add(_add_list)
test_data = self._read_test_file()
except_data = ["RemoteFile Test.\n",
"Pattern Line.\n",
"add_line_1\n",
"add_line_2\n",
"add_line_3"]
for index in range(len(except_data)):
self.assertEqual(except_data[index], test_data[index])
del remote_file
test_data = self._read_test_file()
self.assertEqual(test_data, self.default_data)
def testSub(self):
remote_file = self._new_remote_file()
_pattern2repl = {r"Remote": "Local", r"^Pat.*$": "Replace Line"}
remote_file.sub(_pattern2repl)
test_data = self._read_test_file()
except_data = ["LocalFile Test.\n",
"Replace Line"]
for index in range(len(except_data)):
self.assertEqual(except_data[index], test_data[index])
del remote_file
test_data = self._read_test_file()
self.assertEqual(test_data, self.default_data)
def testRemove(self):
remote_file = self._new_remote_file()
_pattern_list = [r"^Pattern"]
remote_file.remove(_pattern_list)
test_data = self._read_test_file()
except_data = ["RemoteFile Test."]
for index in range(len(except_data)):
self.assertEqual(except_data[index], test_data[index])
del remote_file
test_data = self._read_test_file()
self.assertEqual(test_data, self.default_data)
def testSEEA(self):
remote_file = self._new_remote_file()
_pattern2repl = {r"Remote": "Local", r"NoMatch": "ADD line."}
remote_file.sub_else_add(_pattern2repl)
test_data = self._read_test_file()
except_data = ["LocalFile Test.\n",
"Pattern Line.\n",
"ADD line."]
for index in range(len(except_data)):
self.assertEqual(except_data[index], test_data[index])
del remote_file
test_data = self._read_test_file()
self.assertEqual(test_data, self.default_data)
if __name__ == "__main__":
unittest.main()
|
unknown
|
codeparrot/codeparrot-clean
| ||
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the CockroachDB Software License
// included in the /LICENSE file.
package geo
import (
"bytes"
"encoding/binary"
"fmt"
"strings"
"github.com/cockroachdb/cockroach/pkg/geo/geopb"
"github.com/cockroachdb/cockroach/pkg/geo/geoprojbase"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/golang/geo/s1"
"github.com/pierrre/geohash"
"github.com/twpayne/go-geom"
"github.com/twpayne/go-geom/encoding/ewkb"
"github.com/twpayne/go-geom/encoding/geojson"
"github.com/twpayne/go-geom/encoding/kml"
"github.com/twpayne/go-geom/encoding/wkb"
"github.com/twpayne/go-geom/encoding/wkbcommon"
"github.com/twpayne/go-geom/encoding/wkbhex"
"github.com/twpayne/go-geom/encoding/wkt"
)
// FullPrecisionGeoJSON, when used in place of max decimal digits in
// GeoJSON functions, indicates to GeoJSON that it should use full
// precision when encoding JSON.
const FullPrecisionGeoJSON = -1
// SpatialObjectToWKT transforms a given SpatialObject to WKT.
func SpatialObjectToWKT(so geopb.SpatialObject, maxDecimalDigits int) (geopb.WKT, error) {
t, err := ewkb.Unmarshal([]byte(so.EWKB))
if err != nil {
return "", err
}
ret, err := wkt.Marshal(t, wkt.EncodeOptionWithMaxDecimalDigits(maxDecimalDigits))
return geopb.WKT(ret), err
}
// SpatialObjectToEWKT transforms a given SpatialObject to EWKT.
func SpatialObjectToEWKT(so geopb.SpatialObject, maxDecimalDigits int) (geopb.EWKT, error) {
t, err := ewkb.Unmarshal([]byte(so.EWKB))
if err != nil {
return "", err
}
ret, err := wkt.Marshal(t, wkt.EncodeOptionWithMaxDecimalDigits(maxDecimalDigits))
if err != nil {
return "", err
}
if t.SRID() != 0 {
ret = fmt.Sprintf("SRID=%d;%s", t.SRID(), ret)
}
return geopb.EWKT(ret), err
}
// SpatialObjectToWKB transforms a given SpatialObject to WKB.
func SpatialObjectToWKB(so geopb.SpatialObject, byteOrder binary.ByteOrder) (geopb.WKB, error) {
t, err := ewkb.Unmarshal([]byte(so.EWKB))
if err != nil {
return nil, err
}
ret, err := wkb.Marshal(t, byteOrder, wkbcommon.WKBOptionEmptyPointHandling(wkbcommon.EmptyPointHandlingNaN))
return geopb.WKB(ret), err
}
// SpatialObjectToGeoJSONFlag maps to the ST_AsGeoJSON flags for PostGIS.
type SpatialObjectToGeoJSONFlag int
// These should be kept with ST_AsGeoJSON in PostGIS.
// 0: means no option
// 1: GeoJSON BBOX
// 2: GeoJSON Short CRS (e.g EPSG:4326)
// 4: GeoJSON Long CRS (e.g urn:ogc:def:crs:EPSG::4326)
// 8: GeoJSON Short CRS if not EPSG:4326 (default)
const (
SpatialObjectToGeoJSONFlagIncludeBBox SpatialObjectToGeoJSONFlag = 1 << (iota)
SpatialObjectToGeoJSONFlagShortCRS
SpatialObjectToGeoJSONFlagLongCRS
SpatialObjectToGeoJSONFlagShortCRSIfNot4326
SpatialObjectToGeoJSONFlagZero = 0
)
// geomToGeoJSONCRS converts a geom to its CRS GeoJSON form.
func geomToGeoJSONCRS(t geom.T, long bool) (*geojson.CRS, error) {
projection, err := geoprojbase.Projection(geopb.SRID(t.SRID()))
if err != nil {
return nil, err
}
var prop string
if long {
prop = fmt.Sprintf("urn:ogc:def:crs:%s::%d", projection.AuthName, projection.AuthSRID)
} else {
prop = fmt.Sprintf("%s:%d", projection.AuthName, projection.AuthSRID)
}
crs := &geojson.CRS{
Type: "name",
Properties: map[string]interface{}{
"name": prop,
},
}
return crs, nil
}
// SpatialObjectToGeoJSON transforms a given SpatialObject to GeoJSON.
func SpatialObjectToGeoJSON(
so geopb.SpatialObject, maxDecimalDigits int, flag SpatialObjectToGeoJSONFlag,
) ([]byte, error) {
t, err := ewkb.Unmarshal([]byte(so.EWKB))
if err != nil {
return nil, err
}
options := []geojson.EncodeGeometryOption{
geojson.EncodeGeometryWithMaxDecimalDigits(maxDecimalDigits),
}
if flag&SpatialObjectToGeoJSONFlagIncludeBBox != 0 {
// Do not encoding empty bounding boxes.
if so.BoundingBox != nil {
options = append(
options,
geojson.EncodeGeometryWithBBox(),
)
}
}
// Take CRS flag in order of precedence.
if t.SRID() != 0 {
if flag&SpatialObjectToGeoJSONFlagLongCRS != 0 {
crs, err := geomToGeoJSONCRS(t, true /* long */)
if err != nil {
return nil, err
}
options = append(options, geojson.EncodeGeometryWithCRS(crs))
} else if flag&SpatialObjectToGeoJSONFlagShortCRS != 0 {
crs, err := geomToGeoJSONCRS(t, false /* long */)
if err != nil {
return nil, err
}
options = append(options, geojson.EncodeGeometryWithCRS(crs))
} else if flag&SpatialObjectToGeoJSONFlagShortCRSIfNot4326 != 0 {
if t.SRID() != 4326 {
crs, err := geomToGeoJSONCRS(t, false /* long */)
if err != nil {
return nil, err
}
options = append(options, geojson.EncodeGeometryWithCRS(crs))
}
}
}
return geojson.Marshal(t, options...)
}
// SpatialObjectToWKBHex transforms a given SpatialObject to WKBHex.
func SpatialObjectToWKBHex(so geopb.SpatialObject) (string, error) {
t, err := ewkb.Unmarshal([]byte(so.EWKB))
if err != nil {
return "", err
}
ret, err := wkbhex.Encode(t, DefaultEWKBEncodingFormat, wkbcommon.WKBOptionEmptyPointHandling(wkbcommon.EmptyPointHandlingNaN))
return strings.ToUpper(ret), err
}
// SpatialObjectToKML transforms a given SpatialObject to KML.
func SpatialObjectToKML(so geopb.SpatialObject) (string, error) {
t, err := ewkb.Unmarshal([]byte(so.EWKB))
if err != nil {
return "", err
}
kmlElement, err := kml.Encode(t)
if err != nil {
return "", err
}
var buf bytes.Buffer
if err := kmlElement.Write(&buf); err != nil {
return "", err
}
return buf.String(), nil
}
// GeoHashAutoPrecision means to calculate the precision of SpatialObjectToGeoHash
// based on input, up to 32 characters.
const GeoHashAutoPrecision = 0
// GeoHashMaxPrecision is the maximum precision for GeoHashes.
// 20 is picked as doubles have 51 decimals of precision, and each base32 position
// can contain 5 bits of data. As we have two points, we use floor((2 * 51) / 5) = 20.
const GeoHashMaxPrecision = 20
// SpatialObjectToGeoHash transforms a given SpatialObject to a GeoHash.
func SpatialObjectToGeoHash(so geopb.SpatialObject, p int) (string, error) {
if so.BoundingBox == nil {
return "", nil
}
bbox := so.BoundingBox
if so.Type == geopb.SpatialObjectType_GeographyType {
// Convert bounding box back to degrees.
bbox = &geopb.BoundingBox{
LoX: s1.Angle(bbox.LoX).Degrees(),
HiX: s1.Angle(bbox.HiX).Degrees(),
LoY: s1.Angle(bbox.LoY).Degrees(),
HiY: s1.Angle(bbox.HiY).Degrees(),
}
}
if bbox.LoX < -180 || bbox.HiX > 180 || bbox.LoY < -90 || bbox.HiY > 90 {
return "", pgerror.Newf(
pgcode.InvalidParameterValue,
"object has bounds greater than the bounds of lat/lng, got (%f %f, %f %f)",
bbox.LoX, bbox.LoY,
bbox.HiX, bbox.HiY,
)
}
// Get precision using the bounding box if required.
if p <= GeoHashAutoPrecision {
p = getPrecisionForBBox(bbox)
}
// Support up to 20, which is the same as PostGIS.
if p > GeoHashMaxPrecision {
p = GeoHashMaxPrecision
}
bbCenterLng := bbox.LoX + (bbox.HiX-bbox.LoX)/2.0
bbCenterLat := bbox.LoY + (bbox.HiY-bbox.LoY)/2.0
return geohash.Encode(bbCenterLat, bbCenterLng, p), nil
}
// getPrecisionForBBox is a function imitating PostGIS's ability to go from
// a world bounding box and truncating a GeoHash to fit the given bounding box.
// The algorithm halves the world bounding box until it intersects with the
// feature bounding box to get a precision that will encompass the entire
// bounding box.
func getPrecisionForBBox(bbox *geopb.BoundingBox) int {
bitPrecision := 0
// This is a point, for points we use the full bitPrecision.
if bbox.LoX == bbox.HiX && bbox.LoY == bbox.HiY {
return GeoHashMaxPrecision
}
// Starts from a world bounding box:
lonMin := -180.0
lonMax := 180.0
latMin := -90.0
latMax := 90.0
// Each iteration shrinks the world bounding box by half in the dimension that
// does not fit, making adjustments each iteration until it intersects with
// the object bbox.
for {
lonWidth := lonMax - lonMin
latWidth := latMax - latMin
latMaxDelta, lonMaxDelta, latMinDelta, lonMinDelta := 0.0, 0.0, 0.0, 0.0
// Look at whether the longitudes of the bbox are to the left or
// the right of the world bbox longitudes, shrinks it and makes adjustments
// for the next iteration.
if bbox.LoX > lonMin+lonWidth/2.0 {
lonMinDelta = lonWidth / 2.0
} else if bbox.HiX < lonMax-lonWidth/2.0 {
lonMaxDelta = lonWidth / -2.0
}
// Look at whether the latitudes of the bbox are to the left or
// the right of the world bbox latitudes, shrinks it and makes adjustments
// for the next iteration.
if bbox.LoY > latMin+latWidth/2.0 {
latMinDelta = latWidth / 2.0
} else if bbox.HiY < latMax-latWidth/2.0 {
latMaxDelta = latWidth / -2.0
}
// Every change we make that splits the box up adds precision.
// If we detect no change, we've intersected a box and so must exit.
precisionDelta := 0
if lonMinDelta != 0.0 || lonMaxDelta != 0.0 {
lonMin += lonMinDelta
lonMax += lonMaxDelta
precisionDelta++
} else {
break
}
if latMinDelta != 0.0 || latMaxDelta != 0.0 {
latMin += latMinDelta
latMax += latMaxDelta
precisionDelta++
} else {
break
}
bitPrecision += precisionDelta
}
// Each character can represent 5 bits of bitPrecision.
// As such, divide by 5 to get GeoHash precision.
return bitPrecision / 5
}
// StringToByteOrder returns the byte order of string.
func StringToByteOrder(s string) binary.ByteOrder {
switch strings.ToLower(s) {
case "ndr":
return binary.LittleEndian
case "xdr":
return binary.BigEndian
default:
return DefaultEWKBEncodingFormat
}
}
|
go
|
github
|
https://github.com/cockroachdb/cockroach
|
pkg/geo/encode.go
|
#!/usr/bin/env python
'''
EC2 external inventory script
=================================
Generates inventory that Ansible can understand by making API request to
AWS EC2 using the Boto library.
NOTE: This script assumes Ansible is being executed where the environment
variables needed for Boto have already been set:
export AWS_ACCESS_KEY_ID='AK123'
export AWS_SECRET_ACCESS_KEY='abc123'
This script also assumes there is an ec2.ini file alongside it. To specify a
different path to ec2.ini, define the EC2_INI_PATH environment variable:
export EC2_INI_PATH=/path/to/my_ec2.ini
If you're using eucalyptus you need to set the above variables and
you need to define:
export EC2_URL=http://hostname_of_your_cc:port/services/Eucalyptus
For more details, see: http://docs.pythonboto.org/en/latest/boto_config_tut.html
When run against a specific host, this script returns the following variables:
- ec2_ami_launch_index
- ec2_architecture
- ec2_association
- ec2_attachTime
- ec2_attachment
- ec2_attachmentId
- ec2_client_token
- ec2_deleteOnTermination
- ec2_description
- ec2_deviceIndex
- ec2_dns_name
- ec2_eventsSet
- ec2_group_name
- ec2_hypervisor
- ec2_id
- ec2_image_id
- ec2_instanceState
- ec2_instance_type
- ec2_ipOwnerId
- ec2_ip_address
- ec2_item
- ec2_kernel
- ec2_key_name
- ec2_launch_time
- ec2_monitored
- ec2_monitoring
- ec2_networkInterfaceId
- ec2_ownerId
- ec2_persistent
- ec2_placement
- ec2_platform
- ec2_previous_state
- ec2_private_dns_name
- ec2_private_ip_address
- ec2_publicIp
- ec2_public_dns_name
- ec2_ramdisk
- ec2_reason
- ec2_region
- ec2_requester_id
- ec2_root_device_name
- ec2_root_device_type
- ec2_security_group_ids
- ec2_security_group_names
- ec2_shutdown_state
- ec2_sourceDestCheck
- ec2_spot_instance_request_id
- ec2_state
- ec2_state_code
- ec2_state_reason
- ec2_status
- ec2_subnet_id
- ec2_tenancy
- ec2_virtualization_type
- ec2_vpc_id
These variables are pulled out of a boto.ec2.instance object. There is a lack of
consistency with variable spellings (camelCase and underscores) since this
just loops through all variables the object exposes. It is preferred to use the
ones with underscores when multiple exist.
In addition, if an instance has AWS Tags associated with it, each tag is a new
variable named:
- ec2_tag_[Key] = [Value]
Security groups are comma-separated in 'ec2_security_group_ids' and
'ec2_security_group_names'.
'''
# (c) 2012, Peter Sankauskas
#
# This file is part of Ansible,
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
######################################################################
import sys
import os
import argparse
import re
from time import time
import boto
from boto import ec2
from boto import rds
from boto import route53
import ConfigParser
from collections import defaultdict
try:
import json
except ImportError:
import simplejson as json
class Ec2Inventory(object):
def _empty_inventory(self):
return {"_meta" : {"hostvars" : {}}}
def __init__(self):
''' Main execution path '''
# Inventory grouped by instance IDs, tags, security groups, regions,
# and availability zones
self.inventory = self._empty_inventory()
# Index of hostname (address) to instance ID
self.index = {}
# Read settings and parse CLI arguments
self.read_settings()
self.parse_cli_args()
# Cache
if self.args.refresh_cache:
self.do_api_calls_update_cache()
elif not self.is_cache_valid():
self.do_api_calls_update_cache()
# Data to print
if self.args.host:
data_to_print = self.get_host_info()
elif self.args.list:
# Display list of instances for inventory
if self.inventory == self._empty_inventory():
data_to_print = self.get_inventory_from_cache()
else:
data_to_print = self.json_format_dict(self.inventory, True)
print data_to_print
def is_cache_valid(self):
''' Determines if the cache files have expired, or if it is still valid '''
if os.path.isfile(self.cache_path_cache):
mod_time = os.path.getmtime(self.cache_path_cache)
current_time = time()
if (mod_time + self.cache_max_age) > current_time:
if os.path.isfile(self.cache_path_index):
return True
return False
def read_settings(self):
''' Reads the settings from the ec2.ini file '''
config = ConfigParser.SafeConfigParser()
ec2_default_ini_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ec2.ini')
ec2_ini_path = os.environ.get('EC2_INI_PATH', ec2_default_ini_path)
config.read(ec2_ini_path)
# is eucalyptus?
self.eucalyptus_host = None
self.eucalyptus = False
if config.has_option('ec2', 'eucalyptus'):
self.eucalyptus = config.getboolean('ec2', 'eucalyptus')
if self.eucalyptus and config.has_option('ec2', 'eucalyptus_host'):
self.eucalyptus_host = config.get('ec2', 'eucalyptus_host')
# Regions
self.regions = []
configRegions = config.get('ec2', 'regions')
configRegions_exclude = config.get('ec2', 'regions_exclude')
if (configRegions == 'all'):
if self.eucalyptus_host:
self.regions.append(boto.connect_euca(host=self.eucalyptus_host).region.name)
else:
for regionInfo in ec2.regions():
if regionInfo.name not in configRegions_exclude:
self.regions.append(regionInfo.name)
else:
self.regions = configRegions.split(",")
# Destination addresses
self.destination_variable = config.get('ec2', 'destination_variable')
self.vpc_destination_variable = config.get('ec2', 'vpc_destination_variable')
# Route53
self.route53_enabled = config.getboolean('ec2', 'route53')
self.route53_excluded_zones = []
if config.has_option('ec2', 'route53_excluded_zones'):
self.route53_excluded_zones.extend(
config.get('ec2', 'route53_excluded_zones', '').split(','))
# Include RDS instances?
self.rds_enabled = True
if config.has_option('ec2', 'rds'):
self.rds_enabled = config.getboolean('ec2', 'rds')
# Return all EC2 and RDS instances (if RDS is enabled)
if config.has_option('ec2', 'all_instances'):
self.all_instances = config.getboolean('ec2', 'all_instances')
else:
self.all_instances = False
if config.has_option('ec2', 'all_rds_instances') and self.rds_enabled:
self.all_rds_instances = config.getboolean('ec2', 'all_rds_instances')
else:
self.all_rds_instances = False
# Cache related
cache_dir = os.path.expanduser(config.get('ec2', 'cache_path'))
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)
self.cache_path_cache = cache_dir + "/ansible-ec2.cache"
self.cache_path_index = cache_dir + "/ansible-ec2.index"
self.cache_max_age = config.getint('ec2', 'cache_max_age')
# Configure nested groups instead of flat namespace.
if config.has_option('ec2', 'nested_groups'):
self.nested_groups = config.getboolean('ec2', 'nested_groups')
else:
self.nested_groups = False
# Do we need to just include hosts that match a pattern?
try:
pattern_include = config.get('ec2', 'pattern_include')
if pattern_include and len(pattern_include) > 0:
self.pattern_include = re.compile(pattern_include)
else:
self.pattern_include = None
except ConfigParser.NoOptionError, e:
self.pattern_include = None
# Do we need to exclude hosts that match a pattern?
try:
pattern_exclude = config.get('ec2', 'pattern_exclude');
if pattern_exclude and len(pattern_exclude) > 0:
self.pattern_exclude = re.compile(pattern_exclude)
else:
self.pattern_exclude = None
except ConfigParser.NoOptionError, e:
self.pattern_exclude = None
# Instance filters (see boto and EC2 API docs)
self.ec2_instance_filters = defaultdict(list)
if config.has_option('ec2', 'instance_filters'):
for x in config.get('ec2', 'instance_filters', '').split(','):
filter_key, filter_value = x.split('=')
self.ec2_instance_filters[filter_key].append(filter_value)
def parse_cli_args(self):
''' Command line argument processing '''
parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on EC2')
parser.add_argument('--list', action='store_true', default=True,
help='List instances (default: True)')
parser.add_argument('--host', action='store',
help='Get all the variables about a specific instance')
parser.add_argument('--refresh-cache', action='store_true', default=False,
help='Force refresh of cache by making API requests to EC2 (default: False - use cache files)')
self.args = parser.parse_args()
def do_api_calls_update_cache(self):
''' Do API calls to each region, and save data in cache files '''
if self.route53_enabled:
self.get_route53_records()
for region in self.regions:
self.get_instances_by_region(region)
if self.rds_enabled:
self.get_rds_instances_by_region(region)
self.write_to_cache(self.inventory, self.cache_path_cache)
self.write_to_cache(self.index, self.cache_path_index)
def get_instances_by_region(self, region):
''' Makes an AWS EC2 API call to the list of instances in a particular
region '''
try:
if self.eucalyptus:
conn = boto.connect_euca(host=self.eucalyptus_host)
conn.APIVersion = '2010-08-31'
else:
conn = ec2.connect_to_region(region)
# connect_to_region will fail "silently" by returning None if the region name is wrong or not supported
if conn is None:
print("region name: %s likely not supported, or AWS is down. connection to region failed." % region)
sys.exit(1)
reservations = []
if self.ec2_instance_filters:
for filter_key, filter_values in self.ec2_instance_filters.iteritems():
reservations.extend(conn.get_all_instances(filters = { filter_key : filter_values }))
else:
reservations = conn.get_all_instances()
for reservation in reservations:
for instance in reservation.instances:
self.add_instance(instance, region)
except boto.exception.BotoServerError, e:
if not self.eucalyptus:
print "Looks like AWS is down again:"
print e
sys.exit(1)
def get_rds_instances_by_region(self, region):
''' Makes an AWS API call to the list of RDS instances in a particular
region '''
try:
conn = rds.connect_to_region(region)
if conn:
instances = conn.get_all_dbinstances()
for instance in instances:
self.add_rds_instance(instance, region)
except boto.exception.BotoServerError, e:
if not e.reason == "Forbidden":
print "Looks like AWS RDS is down: "
print e
sys.exit(1)
def get_instance(self, region, instance_id):
''' Gets details about a specific instance '''
if self.eucalyptus:
conn = boto.connect_euca(self.eucalyptus_host)
conn.APIVersion = '2010-08-31'
else:
conn = ec2.connect_to_region(region)
# connect_to_region will fail "silently" by returning None if the region name is wrong or not supported
if conn is None:
print("region name: %s likely not supported, or AWS is down. connection to region failed." % region)
sys.exit(1)
reservations = conn.get_all_instances([instance_id])
for reservation in reservations:
for instance in reservation.instances:
return instance
def add_instance(self, instance, region):
''' Adds an instance to the inventory and index, as long as it is
addressable '''
# Only want running instances unless all_instances is True
if not self.all_instances and instance.state != 'running':
return
# Select the best destination address
if instance.subnet_id:
dest = getattr(instance, self.vpc_destination_variable)
else:
dest = getattr(instance, self.destination_variable)
if not dest:
# Skip instances we cannot address (e.g. private VPC subnet)
return
# if we only want to include hosts that match a pattern, skip those that don't
if self.pattern_include and not self.pattern_include.match(dest):
return
# if we need to exclude hosts that match a pattern, skip those
if self.pattern_exclude and self.pattern_exclude.match(dest):
return
# Add to index
self.index[dest] = [region, instance.id]
# Inventory: Group by instance ID (always a group of 1)
self.inventory[instance.id] = [dest]
if self.nested_groups:
self.push_group(self.inventory, 'instances', instance.id)
# Inventory: Group by region
if self.nested_groups:
self.push_group(self.inventory, 'regions', region)
else:
self.push(self.inventory, region, dest)
# Inventory: Group by availability zone
self.push(self.inventory, instance.placement, dest)
if self.nested_groups:
self.push_group(self.inventory, region, instance.placement)
# Inventory: Group by instance type
type_name = self.to_safe('type_' + instance.instance_type)
self.push(self.inventory, type_name, dest)
if self.nested_groups:
self.push_group(self.inventory, 'types', type_name)
# Inventory: Group by key pair
if instance.key_name:
key_name = self.to_safe('key_' + instance.key_name)
self.push(self.inventory, key_name, dest)
if self.nested_groups:
self.push_group(self.inventory, 'keys', key_name)
# Inventory: Group by VPC
if instance.vpc_id:
self.push(self.inventory, self.to_safe('vpc_id_' + instance.vpc_id), dest)
# Inventory: Group by security group
try:
for group in instance.groups:
key = self.to_safe("security_group_" + group.name)
self.push(self.inventory, key, dest)
if self.nested_groups:
self.push_group(self.inventory, 'security_groups', key)
except AttributeError:
print 'Package boto seems a bit older.'
print 'Please upgrade boto >= 2.3.0.'
sys.exit(1)
# Inventory: Group by tag keys
for k, v in instance.tags.iteritems():
key = self.to_safe("tag_" + k + "=" + v)
self.push(self.inventory, key, dest)
if self.nested_groups:
self.push_group(self.inventory, 'tags', self.to_safe("tag_" + k))
self.push_group(self.inventory, self.to_safe("tag_" + k), key)
# Inventory: Group by Route53 domain names if enabled
if self.route53_enabled:
route53_names = self.get_instance_route53_names(instance)
for name in route53_names:
self.push(self.inventory, name, dest)
if self.nested_groups:
self.push_group(self.inventory, 'route53', name)
# Global Tag: instances without tags
if len(instance.tags) == 0:
self.push(self.inventory, 'tag_none', dest)
# Global Tag: tag all EC2 instances
self.push(self.inventory, 'ec2', dest)
self.inventory["_meta"]["hostvars"][dest] = self.get_host_info_dict_from_instance(instance)
def add_rds_instance(self, instance, region):
''' Adds an RDS instance to the inventory and index, as long as it is
addressable '''
# Only want available instances unless all_rds_instances is True
if not self.all_rds_instances and instance.status != 'available':
return
# Select the best destination address
#if instance.subnet_id:
#dest = getattr(instance, self.vpc_destination_variable)
#else:
#dest = getattr(instance, self.destination_variable)
dest = instance.endpoint[0]
if not dest:
# Skip instances we cannot address (e.g. private VPC subnet)
return
# Add to index
self.index[dest] = [region, instance.id]
# Inventory: Group by instance ID (always a group of 1)
self.inventory[instance.id] = [dest]
if self.nested_groups:
self.push_group(self.inventory, 'instances', instance.id)
# Inventory: Group by region
if self.nested_groups:
self.push_group(self.inventory, 'regions', region)
else:
self.push(self.inventory, region, dest)
# Inventory: Group by availability zone
self.push(self.inventory, instance.availability_zone, dest)
if self.nested_groups:
self.push_group(self.inventory, region, instance.availability_zone)
# Inventory: Group by instance type
type_name = self.to_safe('type_' + instance.instance_class)
self.push(self.inventory, type_name, dest)
if self.nested_groups:
self.push_group(self.inventory, 'types', type_name)
# Inventory: Group by security group
try:
if instance.security_group:
key = self.to_safe("security_group_" + instance.security_group.name)
self.push(self.inventory, key, dest)
if self.nested_groups:
self.push_group(self.inventory, 'security_groups', key)
except AttributeError:
print 'Package boto seems a bit older.'
print 'Please upgrade boto >= 2.3.0.'
sys.exit(1)
# Inventory: Group by engine
self.push(self.inventory, self.to_safe("rds_" + instance.engine), dest)
if self.nested_groups:
self.push_group(self.inventory, 'rds_engines', self.to_safe("rds_" + instance.engine))
# Inventory: Group by parameter group
self.push(self.inventory, self.to_safe("rds_parameter_group_" + instance.parameter_group.name), dest)
if self.nested_groups:
self.push_group(self.inventory, 'rds_parameter_groups', self.to_safe("rds_parameter_group_" + instance.parameter_group.name))
# Global Tag: all RDS instances
self.push(self.inventory, 'rds', dest)
self.inventory["_meta"]["hostvars"][dest] = self.get_host_info_dict_from_instance(instance)
def get_route53_records(self):
''' Get and store the map of resource records to domain names that
point to them. '''
r53_conn = route53.Route53Connection()
all_zones = r53_conn.get_zones()
route53_zones = [ zone for zone in all_zones if zone.name[:-1]
not in self.route53_excluded_zones ]
self.route53_records = {}
for zone in route53_zones:
rrsets = r53_conn.get_all_rrsets(zone.id)
for record_set in rrsets:
record_name = record_set.name
if record_name.endswith('.'):
record_name = record_name[:-1]
for resource in record_set.resource_records:
self.route53_records.setdefault(resource, set())
self.route53_records[resource].add(record_name)
def get_instance_route53_names(self, instance):
''' Check if an instance is referenced in the records we have from
Route53. If it is, return the list of domain names pointing to said
instance. If nothing points to it, return an empty list. '''
instance_attributes = [ 'public_dns_name', 'private_dns_name',
'ip_address', 'private_ip_address' ]
name_list = set()
for attrib in instance_attributes:
try:
value = getattr(instance, attrib)
except AttributeError:
continue
if value in self.route53_records:
name_list.update(self.route53_records[value])
return list(name_list)
def get_host_info_dict_from_instance(self, instance):
instance_vars = {}
for key in vars(instance):
value = getattr(instance, key)
key = self.to_safe('ec2_' + key)
# Handle complex types
# state/previous_state changed to properties in boto in https://github.com/boto/boto/commit/a23c379837f698212252720d2af8dec0325c9518
if key == 'ec2__state':
instance_vars['ec2_state'] = instance.state or ''
instance_vars['ec2_state_code'] = instance.state_code
elif key == 'ec2__previous_state':
instance_vars['ec2_previous_state'] = instance.previous_state or ''
instance_vars['ec2_previous_state_code'] = instance.previous_state_code
elif type(value) in [int, bool]:
instance_vars[key] = value
elif type(value) in [str, unicode]:
instance_vars[key] = value.strip()
elif type(value) == type(None):
instance_vars[key] = ''
elif key == 'ec2_region':
instance_vars[key] = value.name
elif key == 'ec2__placement':
instance_vars['ec2_placement'] = value.zone
elif key == 'ec2_tags':
for k, v in value.iteritems():
key = self.to_safe('ec2_tag_' + k)
instance_vars[key] = v
elif key == 'ec2_groups':
group_ids = []
group_names = []
for group in value:
group_ids.append(group.id)
group_names.append(group.name)
instance_vars["ec2_security_group_ids"] = ','.join([str(i) for i in group_ids])
instance_vars["ec2_security_group_names"] = ','.join([str(i) for i in group_names])
else:
pass
# TODO Product codes if someone finds them useful
#print key
#print type(value)
#print value
return instance_vars
def get_host_info(self):
''' Get variables about a specific host '''
if len(self.index) == 0:
# Need to load index from cache
self.load_index_from_cache()
if not self.args.host in self.index:
# try updating the cache
self.do_api_calls_update_cache()
if not self.args.host in self.index:
# host might not exist anymore
return self.json_format_dict({}, True)
(region, instance_id) = self.index[self.args.host]
instance = self.get_instance(region, instance_id)
return self.json_format_dict(self.get_host_info_dict_from_instance(instance), True)
def push(self, my_dict, key, element):
''' Push an element onto an array that may not have been defined in
the dict '''
group_info = my_dict.setdefault(key, [])
if isinstance(group_info, dict):
host_list = group_info.setdefault('hosts', [])
host_list.append(element)
else:
group_info.append(element)
def push_group(self, my_dict, key, element):
''' Push a group as a child of another group. '''
parent_group = my_dict.setdefault(key, {})
if not isinstance(parent_group, dict):
parent_group = my_dict[key] = {'hosts': parent_group}
child_groups = parent_group.setdefault('children', [])
if element not in child_groups:
child_groups.append(element)
def get_inventory_from_cache(self):
''' Reads the inventory from the cache file and returns it as a JSON
object '''
cache = open(self.cache_path_cache, 'r')
json_inventory = cache.read()
return json_inventory
def load_index_from_cache(self):
''' Reads the index from the cache file sets self.index '''
cache = open(self.cache_path_index, 'r')
json_index = cache.read()
self.index = json.loads(json_index)
def write_to_cache(self, data, filename):
''' Writes data in JSON format to a file '''
json_data = self.json_format_dict(data, True)
cache = open(filename, 'w')
cache.write(json_data)
cache.close()
def to_safe(self, word):
''' Converts 'bad' characters in a string to underscores so they can be
used as Ansible groups '''
return re.sub("[^A-Za-z0-9\-]", "_", word)
def json_format_dict(self, data, pretty=False):
''' Converts a dict to a JSON object and dumps it as a formatted
string '''
if pretty:
return json.dumps(data, sort_keys=True, indent=2)
else:
return json.dumps(data)
# Run the script
Ec2Inventory()
|
unknown
|
codeparrot/codeparrot-clean
| ||
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.clients.admin;
import org.apache.kafka.common.TopicPartition;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class MemberDescriptionTest {
private static final String MEMBER_ID = "member_id";
private static final Optional<String> INSTANCE_ID = Optional.of("instanceId");
private static final Optional<String> RACK_ID = Optional.of("rackId");
private static final String CLIENT_ID = "client_id";
private static final String HOST = "host";
private static final MemberAssignment ASSIGNMENT;
private static final MemberDescription STATIC_MEMBER_DESCRIPTION;
static {
ASSIGNMENT = new MemberAssignment(Collections.singleton(new TopicPartition("topic", 1)));
STATIC_MEMBER_DESCRIPTION = new MemberDescription(MEMBER_ID,
INSTANCE_ID,
RACK_ID,
CLIENT_ID,
HOST,
ASSIGNMENT,
Optional.empty(),
Optional.empty(),
Optional.empty());
}
@Test
public void testEqualsWithoutGroupInstanceId() {
MemberDescription dynamicMemberDescription = new MemberDescription(MEMBER_ID,
Optional.empty(),
Optional.empty(),
CLIENT_ID,
HOST,
ASSIGNMENT,
Optional.empty(),
Optional.empty(),
Optional.empty());
MemberDescription identityDescription = new MemberDescription(MEMBER_ID,
Optional.empty(),
Optional.empty(),
CLIENT_ID,
HOST,
ASSIGNMENT,
Optional.empty(),
Optional.empty(),
Optional.empty());
assertNotEquals(STATIC_MEMBER_DESCRIPTION, dynamicMemberDescription);
assertNotEquals(STATIC_MEMBER_DESCRIPTION.hashCode(), dynamicMemberDescription.hashCode());
// Check self equality.
assertEquals(dynamicMemberDescription, dynamicMemberDescription);
assertEquals(dynamicMemberDescription, identityDescription);
assertEquals(dynamicMemberDescription.hashCode(), identityDescription.hashCode());
}
@Test
public void testEqualsWithGroupInstanceId() {
// Check self equality.
assertEquals(STATIC_MEMBER_DESCRIPTION, STATIC_MEMBER_DESCRIPTION);
MemberDescription identityDescription = new MemberDescription(MEMBER_ID,
INSTANCE_ID,
RACK_ID,
CLIENT_ID,
HOST,
ASSIGNMENT,
Optional.empty(),
Optional.empty(),
Optional.empty());
assertEquals(STATIC_MEMBER_DESCRIPTION, identityDescription);
assertEquals(STATIC_MEMBER_DESCRIPTION.hashCode(), identityDescription.hashCode());
}
@Test
public void testNonEqual() {
MemberDescription newMemberDescription = new MemberDescription("new_member",
INSTANCE_ID,
RACK_ID,
CLIENT_ID,
HOST,
ASSIGNMENT,
Optional.empty(),
Optional.empty(),
Optional.empty());
assertNotEquals(STATIC_MEMBER_DESCRIPTION, newMemberDescription);
assertNotEquals(STATIC_MEMBER_DESCRIPTION.hashCode(), newMemberDescription.hashCode());
MemberDescription newInstanceDescription = new MemberDescription(MEMBER_ID,
Optional.of("new_instance"),
RACK_ID,
CLIENT_ID,
HOST,
ASSIGNMENT,
Optional.empty(),
Optional.empty(),
Optional.empty());
assertNotEquals(STATIC_MEMBER_DESCRIPTION, newInstanceDescription);
assertNotEquals(STATIC_MEMBER_DESCRIPTION.hashCode(), newInstanceDescription.hashCode());
MemberDescription newTargetAssignmentDescription = new MemberDescription(MEMBER_ID,
INSTANCE_ID,
RACK_ID,
CLIENT_ID,
HOST,
ASSIGNMENT,
Optional.of(ASSIGNMENT),
Optional.empty(),
Optional.empty());
assertNotEquals(STATIC_MEMBER_DESCRIPTION, newTargetAssignmentDescription);
assertNotEquals(STATIC_MEMBER_DESCRIPTION.hashCode(), newTargetAssignmentDescription.hashCode());
MemberDescription newMemberEpochDescription = new MemberDescription(MEMBER_ID,
INSTANCE_ID,
RACK_ID,
CLIENT_ID,
HOST,
ASSIGNMENT,
Optional.empty(),
Optional.of(1),
Optional.empty());
assertNotEquals(STATIC_MEMBER_DESCRIPTION, newMemberEpochDescription);
assertNotEquals(STATIC_MEMBER_DESCRIPTION.hashCode(), newMemberEpochDescription.hashCode());
MemberDescription newIsClassicDescription = new MemberDescription(MEMBER_ID,
INSTANCE_ID,
RACK_ID,
CLIENT_ID,
HOST,
ASSIGNMENT,
Optional.empty(),
Optional.empty(),
Optional.of(false));
assertNotEquals(STATIC_MEMBER_DESCRIPTION, newIsClassicDescription);
assertNotEquals(STATIC_MEMBER_DESCRIPTION.hashCode(), newIsClassicDescription.hashCode());
}
}
|
java
|
github
|
https://github.com/apache/kafka
|
clients/src/test/java/org/apache/kafka/clients/admin/MemberDescriptionTest.java
|
{
"kind": "Dashboard",
"apiVersion": "dashboard.grafana.app/v0alpha1",
"metadata": {
"name": "v40.refresh_not_set.v42"
},
"spec": {
"annotations": {
"list": [
{
"builtIn": 1,
"datasource": {
"type": "grafana",
"uid": "-- Grafana --"
},
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations \u0026 Alerts",
"type": "dashboard"
}
]
},
"editable": true,
"fiscalYearStartMonth": 0,
"graphTooltip": 0,
"liveNow": false,
"preload": false,
"refresh": "",
"schemaVersion": 42,
"time": {
"from": "now-6h",
"to": "now"
},
"timepicker": {
"refresh_intervals": [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
]
},
"timezone": "",
"title": "Refresh Not Set Test Dashboard"
},
"status": {
"conversion": {
"failed": false,
"storedVersion": "v2beta1"
}
}
}
|
json
|
github
|
https://github.com/grafana/grafana
|
apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dashboards_from_v0_to_v2/v2beta1.v40.refresh_not_set.v0alpha1.json
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from ..extern import six
from ..extern.six.moves import zip, range
from .index import TableIndices, TableLoc, TableILoc
import re
import sys
from collections import OrderedDict, Mapping
import warnings
from copy import deepcopy
import numpy as np
from numpy import ma
from .. import log
from ..io import registry as io_registry
from ..units import Quantity
from ..utils import isiterable, ShapedLikeNDArray
from ..utils.compat.numpy import broadcast_to as np_broadcast_to
from ..utils.console import color_print
from ..utils.metadata import MetaData
from ..utils.data_info import BaseColumnInfo, MixinInfo, ParentDtypeInfo, DataInfo
from . import groups
from .pprint import TableFormatter
from .column import (BaseColumn, Column, MaskedColumn, _auto_names, FalseArray,
col_copy)
from .row import Row
from .np_utils import fix_column_name, recarray_fromrecords
from .info import TableInfo
from .index import Index, _IndexModeContext, get_index
from . import conf
__doctest_skip__ = ['Table.read', 'Table.write',
'Table.convert_bytestring_to_unicode',
'Table.convert_unicode_to_bytestring',
]
class TableReplaceWarning(UserWarning):
"""
Warning class for cases when a table column is replaced via the
Table.__setitem__ syntax e.g. t['a'] = val.
This does not inherit from AstropyWarning because we want to use
stacklevel=3 to show the user where the issue occurred in their code.
"""
pass
def descr(col):
"""Array-interface compliant full description of a column.
This returns a 3-tuple (name, type, shape) that can always be
used in a structured array dtype definition.
"""
col_dtype = 'O' if (col.info.dtype is None) else col.info.dtype
col_shape = col.shape[1:] if hasattr(col, 'shape') else ()
return (col.info.name, col_dtype, col_shape)
def has_info_class(obj, cls):
return hasattr(obj, 'info') and isinstance(obj.info, cls)
class TableColumns(OrderedDict):
"""OrderedDict subclass for a set of columns.
This class enhances item access to provide convenient access to columns
by name or index, including slice access. It also handles renaming
of columns.
The initialization argument ``cols`` can be a list of ``Column`` objects
or any structure that is valid for initializing a Python dict. This
includes a dict, list of (key, val) tuples or [key, val] lists, etc.
Parameters
----------
cols : dict, list, tuple; optional
Column objects as data structure that can init dict (see above)
"""
def __init__(self, cols={}):
if isinstance(cols, (list, tuple)):
# `cols` should be a list of two-tuples, but it is allowed to have
# columns (BaseColumn or mixins) in the list.
newcols = []
for col in cols:
if has_info_class(col, BaseColumnInfo):
newcols.append((col.info.name, col))
else:
newcols.append(col)
cols = newcols
super(TableColumns, self).__init__(cols)
def __getitem__(self, item):
"""Get items from a TableColumns object.
::
tc = TableColumns(cols=[Column(name='a'), Column(name='b'), Column(name='c')])
tc['a'] # Column('a')
tc[1] # Column('b')
tc['a', 'b'] # <TableColumns names=('a', 'b')>
tc[1:3] # <TableColumns names=('b', 'c')>
"""
if isinstance(item, six.string_types):
return OrderedDict.__getitem__(self, item)
elif isinstance(item, (int, np.integer)):
return self.values()[item]
elif (isinstance(item, np.ndarray) and item.shape == () and item.dtype.kind == 'i'):
return self.values()[item.item()]
elif isinstance(item, tuple):
return self.__class__([self[x] for x in item])
elif isinstance(item, slice):
return self.__class__([self[x] for x in list(self)[item]])
else:
raise IndexError('Illegal key or index value for {} object'
.format(self.__class__.__name__))
def __setitem__(self, item, value):
if item in self:
raise ValueError("Cannot replace column '{0}'. Use Table.replace_column() instead."
.format(item))
super(TableColumns, self).__setitem__(item, value)
def __repr__(self):
names = ("'{0}'".format(x) for x in six.iterkeys(self))
return "<{1} names=({0})>".format(",".join(names), self.__class__.__name__)
def _rename_column(self, name, new_name):
if name == new_name:
return
if new_name in self:
raise KeyError("Column {0} already exists".format(new_name))
mapper = {name: new_name}
new_names = [mapper.get(name, name) for name in self]
cols = list(six.itervalues(self))
self.clear()
self.update(list(zip(new_names, cols)))
# Define keys and values for Python 2 and 3 source compatibility
def keys(self):
return list(OrderedDict.keys(self))
def values(self):
return list(OrderedDict.values(self))
class Table(object):
"""A class to represent tables of heterogeneous data.
`Table` provides a class for heterogeneous tabular data, making use of a
`numpy` structured array internally to store the data values. A key
enhancement provided by the `Table` class is the ability to easily modify
the structure of the table by adding or removing columns, or adding new
rows of data. In addition table and column metadata are fully supported.
`Table` differs from `~astropy.nddata.NDData` by the assumption that the
input data consists of columns of homogeneous data, where each column
has a unique identifier and may contain additional metadata such as the
data unit, format, and description.
Parameters
----------
data : numpy ndarray, dict, list, Table, or table-like object, optional
Data to initialize table.
masked : bool, optional
Specify whether the table is masked.
names : list, optional
Specify column names
dtype : list, optional
Specify column data types
meta : dict, optional
Metadata associated with the table.
copy : bool, optional
Copy the input data (default=True).
rows : numpy ndarray, list of lists, optional
Row-oriented data for table instead of ``data`` argument
copy_indices : bool, optional
Copy any indices in the input data (default=True)
**kwargs : dict, optional
Additional keyword args when converting table-like object
.. note::
If the input is a Table the ``meta`` is always copied regardless of the
``copy`` parameter.
"""
meta = MetaData()
# Define class attributes for core container objects to allow for subclass
# customization.
Row = Row
Column = Column
MaskedColumn = MaskedColumn
TableColumns = TableColumns
TableFormatter = TableFormatter
def as_array(self, keep_byteorder=False):
"""
Return a new copy of the table in the form of a structured np.ndarray or
np.ma.MaskedArray object (as appropriate).
Parameters
----------
keep_byteorder : bool, optional
By default the returned array has all columns in native byte
order. However, if this option is `True` this preserves the
byte order of all columns (if any are non-native).
Returns
-------
table_array : np.ndarray (unmasked) or np.ma.MaskedArray (masked)
Copy of table as a numpy structured array
"""
if len(self.columns) == 0:
return None
sys_byteorder = ('>', '<')[sys.byteorder == 'little']
native_order = ('=', sys_byteorder)
dtype = []
cols = self.columns.values()
for col in cols:
col_descr = descr(col)
byteorder = col.info.dtype.byteorder
if not keep_byteorder and byteorder not in native_order:
new_dt = np.dtype(col_descr[1]).newbyteorder('=')
col_descr = (col_descr[0], new_dt, col_descr[2])
dtype.append(col_descr)
empty_init = ma.empty if self.masked else np.empty
data = empty_init(len(self), dtype=dtype)
for col in cols:
# When assigning from one array into a field of a structured array,
# Numpy will automatically swap those columns to their destination
# byte order where applicable
data[col.info.name] = col
return data
def __init__(self, data=None, masked=None, names=None, dtype=None,
meta=None, copy=True, rows=None, copy_indices=True,
**kwargs):
# Set up a placeholder empty table
self._set_masked(masked)
self.columns = self.TableColumns()
self.meta = meta
self.formatter = self.TableFormatter()
self._copy_indices = True # copy indices from this Table by default
self._init_indices = copy_indices # whether to copy indices in init
self.primary_key = None
# Must copy if dtype are changing
if not copy and dtype is not None:
raise ValueError('Cannot specify dtype when copy=False')
# Row-oriented input, e.g. list of lists or list of tuples, list of
# dict, Row instance. Set data to something that the subsequent code
# will parse correctly.
is_list_of_dict = False
if rows is not None:
if data is not None:
raise ValueError('Cannot supply both `data` and `rows` values')
if all(isinstance(row, dict) for row in rows):
is_list_of_dict = True # Avoid doing the all(...) test twice.
data = rows
elif isinstance(rows, self.Row):
data = rows
else:
rec_data = recarray_fromrecords(rows)
data = [rec_data[name] for name in rec_data.dtype.names]
# Infer the type of the input data and set up the initialization
# function, number of columns, and potentially the default col names
default_names = None
if hasattr(data, '__astropy_table__'):
# Data object implements the __astropy_table__ interface method.
# Calling that method returns an appropriate instance of
# self.__class__ and respects the `copy` arg. The returned
# Table object should NOT then be copied (though the meta
# will be deep-copied anyway).
data = data.__astropy_table__(self.__class__, copy, **kwargs)
copy = False
elif kwargs:
raise TypeError('__init__() got unexpected keyword argument {!r}'
.format(list(kwargs.keys())[0]))
if (isinstance(data, np.ndarray) and
data.shape == (0,) and
not data.dtype.names):
data = None
if isinstance(data, self.Row):
data = data._table[data._index:data._index + 1]
if isinstance(data, (list, tuple)):
init_func = self._init_from_list
if data and (is_list_of_dict or all(isinstance(row, dict) for row in data)):
n_cols = len(data[0])
else:
n_cols = len(data)
elif isinstance(data, np.ndarray):
if data.dtype.names:
init_func = self._init_from_ndarray # _struct
n_cols = len(data.dtype.names)
default_names = data.dtype.names
else:
init_func = self._init_from_ndarray # _homog
if data.shape == ():
raise ValueError('Can not initialize a Table with a scalar')
elif len(data.shape) == 1:
data = data[np.newaxis, :]
n_cols = data.shape[1]
elif isinstance(data, Mapping):
init_func = self._init_from_dict
default_names = list(data)
n_cols = len(default_names)
elif isinstance(data, Table):
init_func = self._init_from_table
n_cols = len(data.colnames)
default_names = data.colnames
# don't copy indices if the input Table is in non-copy mode
self._init_indices = self._init_indices and data._copy_indices
elif data is None:
if names is None:
if dtype is None:
return # Empty table
try:
# No data nor names but dtype is available. This must be
# valid to initialize a structured array.
dtype = np.dtype(dtype)
names = dtype.names
dtype = [dtype[name] for name in names]
except Exception:
raise ValueError('dtype was specified but could not be '
'parsed for column names')
# names is guaranteed to be set at this point
init_func = self._init_from_list
n_cols = len(names)
data = [[]] * n_cols
else:
raise ValueError('Data type {0} not allowed to init Table'
.format(type(data)))
# Set up defaults if names and/or dtype are not specified.
# A value of None means the actual value will be inferred
# within the appropriate initialization routine, either from
# existing specification or auto-generated.
if names is None:
names = default_names or [None] * n_cols
if dtype is None:
dtype = [None] * n_cols
# Numpy does not support Unicode column names on Python 2, or
# bytes column names on Python 3, so fix them up now.
names = [fix_column_name(name) for name in names]
self._check_names_dtype(names, dtype, n_cols)
# Finally do the real initialization
init_func(data, names, dtype, n_cols, copy)
# Whatever happens above, the masked property should be set to a boolean
if type(self.masked) is not bool:
raise TypeError("masked property has not been set to True or False")
def __getstate__(self):
columns = OrderedDict((key, col if isinstance(col, BaseColumn) else col_copy(col))
for key, col in self.columns.items())
return (columns, self.meta)
def __setstate__(self, state):
columns, meta = state
self.__init__(columns, meta=meta)
@property
def mask(self):
# Dynamic view of available masks
if self.masked:
mask_table = Table([col.mask for col in self.columns.values()],
names=self.colnames, copy=False)
# Set hidden attribute to force inplace setitem so that code like
# t.mask['a'] = [1, 0, 1] will correctly set the underlying mask.
# See #5556 for discussion.
mask_table._setitem_inplace = True
else:
mask_table = None
return mask_table
@mask.setter
def mask(self, val):
self.mask[:] = val
@property
def _mask(self):
"""This is needed so that comparison of a masked Table and a
MaskedArray works. The requirement comes from numpy.ma.core
so don't remove this property."""
return self.as_array().mask
def filled(self, fill_value=None):
"""Return a copy of self, with masked values filled.
If input ``fill_value`` supplied then that value is used for all
masked entries in the table. Otherwise the individual
``fill_value`` defined for each table column is used.
Parameters
----------
fill_value : str
If supplied, this ``fill_value`` is used for all masked entries
in the entire table.
Returns
-------
filled_table : Table
New table with masked values filled
"""
if self.masked:
data = [col.filled(fill_value) for col in six.itervalues(self.columns)]
else:
data = self
return self.__class__(data, meta=deepcopy(self.meta))
@property
def indices(self):
'''
Return the indices associated with columns of the table
as a TableIndices object.
'''
lst = []
for column in self.columns.values():
for index in column.info.indices:
if sum([index is x for x in lst]) == 0: # ensure uniqueness
lst.append(index)
return TableIndices(lst)
@property
def loc(self):
'''
Return a TableLoc object that can be used for retrieving
rows by index in a given data range. Note that both loc
and iloc work only with single-column indices.
'''
return TableLoc(self)
@property
def iloc(self):
'''
Return a TableILoc object that can be used for retrieving
indexed rows in the order they appear in the index.
'''
return TableILoc(self)
def add_index(self, colnames, engine=None, unique=False):
'''
Insert a new index among one or more columns.
If there are no indices, make this index the
primary table index.
Parameters
----------
colnames : str or list
List of column names (or a single column name) to index
engine : type or None
Indexing engine class to use, from among SortedArray, BST,
FastBST, and FastRBT. If the supplied argument is None (by
default), use SortedArray.
unique : bool (defaults to False)
Whether the values of the index must be unique
'''
if isinstance(colnames, six.string_types):
colnames = (colnames,)
columns = self.columns[tuple(colnames)].values()
# make sure all columns support indexing
for col in columns:
if not getattr(col.info, '_supports_indexing', False):
raise ValueError('Cannot create an index on column "{0}", of '
'type "{1}"'.format(col.info.name, type(col)))
index = Index(columns, engine=engine, unique=unique)
if not self.indices:
self.primary_key = colnames
for col in columns:
col.info.indices.append(index)
def remove_indices(self, colname):
'''
Remove all indices involving the given column.
If the primary index is removed, the new primary
index will be the most recently added remaining
index.
Parameters
----------
colname : str
Name of column
'''
col = self.columns[colname]
for index in self.indices:
try:
index.col_position(col.info.name)
except ValueError:
pass
else:
for c in index.columns:
c.info.indices.remove(index)
def index_mode(self, mode):
'''
Return a context manager for an indexing mode.
Parameters
----------
mode : str
Either 'freeze', 'copy_on_getitem', or 'discard_on_copy'.
In 'discard_on_copy' mode,
indices are not copied whenever columns or tables are copied.
In 'freeze' mode, indices are not modified whenever columns are
modified; at the exit of the context, indices refresh themselves
based on column values. This mode is intended for scenarios in
which one intends to make many additions or modifications in an
indexed column.
In 'copy_on_getitem' mode, indices are copied when taking column
slices as well as table slices, so col[i0:i1] will preserve
indices.
'''
return _IndexModeContext(self, mode)
def __array__(self, dtype=None):
"""Support converting Table to np.array via np.array(table).
Coercion to a different dtype via np.array(table, dtype) is not
supported and will raise a ValueError.
"""
if dtype is not None:
raise ValueError('Datatype coercion is not allowed')
# This limitation is because of the following unexpected result that
# should have made a table copy while changing the column names.
#
# >>> d = astropy.table.Table([[1,2],[3,4]])
# >>> np.array(d, dtype=[('a', 'i8'), ('b', 'i8')])
# array([(0, 0), (0, 0)],
# dtype=[('a', '<i8'), ('b', '<i8')])
return self.as_array().data if self.masked else self.as_array()
def _check_names_dtype(self, names, dtype, n_cols):
"""Make sure that names and dtype are both iterable and have
the same length as data.
"""
for inp_list, inp_str in ((dtype, 'dtype'), (names, 'names')):
if not isiterable(inp_list):
raise ValueError('{0} must be a list or None'.format(inp_str))
if len(names) != n_cols or len(dtype) != n_cols:
raise ValueError(
'Arguments "names" and "dtype" must match number of columns'
.format(inp_str))
def _set_masked_from_cols(self, cols):
if self.masked is None:
if any(isinstance(col, (MaskedColumn, ma.MaskedArray)) for col in cols):
self._set_masked(True)
else:
self._set_masked(False)
elif not self.masked:
if any(np.any(col.mask) for col in cols if isinstance(col, (MaskedColumn, ma.MaskedArray))):
self._set_masked(True)
def _init_from_list_of_dicts(self, data, names, dtype, n_cols, copy):
names_from_data = set()
for row in data:
names_from_data.update(row)
cols = {}
for name in names_from_data:
cols[name] = []
for i, row in enumerate(data):
try:
cols[name].append(row[name])
except KeyError:
raise ValueError('Row {0} has no value for column {1}'.format(i, name))
if all(name is None for name in names):
names = sorted(names_from_data)
self._init_from_dict(cols, names, dtype, n_cols, copy)
return
def _init_from_list(self, data, names, dtype, n_cols, copy):
"""Initialize table from a list of columns. A column can be a
Column object, np.ndarray, mixin, or any other iterable object.
"""
if data and all(isinstance(row, dict) for row in data):
self._init_from_list_of_dicts(data, names, dtype, n_cols, copy)
return
# Set self.masked appropriately, then get class to create column instances.
self._set_masked_from_cols(data)
cols = []
def_names = _auto_names(n_cols)
for col, name, def_name, dtype in zip(data, names, def_names, dtype):
# Structured ndarray gets viewed as a mixin
if isinstance(col, np.ndarray) and len(col.dtype) > 1:
col = col.view(NdarrayMixin)
if isinstance(col, (Column, MaskedColumn)):
col = self.ColumnClass(name=(name or col.info.name or def_name),
data=col, dtype=dtype,
copy=copy, copy_indices=self._init_indices)
elif self._add_as_mixin_column(col):
# Copy the mixin column attributes if they exist since the copy below
# may not get this attribute.
if copy:
col = col_copy(col, copy_indices=self._init_indices)
col.info.name = name or col.info.name or def_name
elif isinstance(col, np.ndarray) or isiterable(col):
col = self.ColumnClass(name=(name or def_name), data=col, dtype=dtype,
copy=copy, copy_indices=self._init_indices)
else:
raise ValueError('Elements in list initialization must be '
'either Column or list-like')
cols.append(col)
self._init_from_cols(cols)
def _init_from_ndarray(self, data, names, dtype, n_cols, copy):
"""Initialize table from an ndarray structured array"""
data_names = data.dtype.names or _auto_names(n_cols)
struct = data.dtype.names is not None
names = [name or data_names[i] for i, name in enumerate(names)]
cols = ([data[name] for name in data_names] if struct else
[data[:, i] for i in range(n_cols)])
# Set self.masked appropriately, then get class to create column instances.
self._set_masked_from_cols(cols)
if copy:
self._init_from_list(cols, names, dtype, n_cols, copy)
else:
dtype = [(name, col.dtype, col.shape[1:]) for name, col in zip(names, cols)]
newdata = data.view(dtype).ravel()
columns = self.TableColumns()
for name in names:
columns[name] = self.ColumnClass(name=name, data=newdata[name])
columns[name].info.parent_table = self
self.columns = columns
def _init_from_dict(self, data, names, dtype, n_cols, copy):
"""Initialize table from a dictionary of columns"""
# TODO: is this restriction still needed with no ndarray?
if not copy:
raise ValueError('Cannot use copy=False with a dict data input')
data_list = [data[name] for name in names]
self._init_from_list(data_list, names, dtype, n_cols, copy)
def _init_from_table(self, data, names, dtype, n_cols, copy):
"""Initialize table from an existing Table object """
table = data # data is really a Table, rename for clarity
self.meta.clear()
self.meta.update(deepcopy(table.meta))
self.primary_key = table.primary_key
cols = list(table.columns.values())
self._init_from_list(cols, names, dtype, n_cols, copy)
def _convert_col_for_table(self, col):
"""
Make sure that all Column objects have correct class for this type of
Table. For a base Table this most commonly means setting to
MaskedColumn if the table is masked. Table subclasses like QTable
override this method.
"""
if col.__class__ is not self.ColumnClass and isinstance(col, Column):
col = self.ColumnClass(col) # copy attributes and reference data
return col
def _init_from_cols(self, cols):
"""Initialize table from a list of Column or mixin objects"""
lengths = set(len(col) for col in cols)
if len(lengths) != 1:
raise ValueError('Inconsistent data column lengths: {0}'
.format(lengths))
# Set the table masking
self._set_masked_from_cols(cols)
# Make sure that all Column-based objects have correct class. For
# plain Table this is self.ColumnClass, but for instance QTable will
# convert columns with units to a Quantity mixin.
newcols = [self._convert_col_for_table(col) for col in cols]
self._make_table_from_cols(self, newcols)
# Deduplicate indices. It may happen that after pickling or when
# initing from an existing table that column indices which had been
# references to a single index object got *copied* into an independent
# object. This results in duplicates which will cause downstream problems.
index_dict = {}
for col in self.itercols():
for i, index in enumerate(col.info.indices or []):
names = tuple(ind_col.info.name for ind_col in index.columns)
if names in index_dict:
col.info.indices[i] = index_dict[names]
else:
index_dict[names] = index
def _new_from_slice(self, slice_):
"""Create a new table as a referenced slice from self."""
table = self.__class__(masked=self.masked)
table.meta.clear()
table.meta.update(deepcopy(self.meta))
table.primary_key = self.primary_key
cols = self.columns.values()
newcols = []
for col in cols:
col.info._copy_indices = self._copy_indices
newcol = col[slice_]
if col.info.indices:
newcol = col.info.slice_indices(newcol, slice_, len(col))
newcols.append(newcol)
col.info._copy_indices = True
self._make_table_from_cols(table, newcols)
return table
@staticmethod
def _make_table_from_cols(table, cols):
"""
Make ``table`` in-place so that it represents the given list of ``cols``.
"""
colnames = set(col.info.name for col in cols)
if None in colnames:
raise TypeError('Cannot have None for column name')
if len(colnames) != len(cols):
raise ValueError('Duplicate column names')
columns = table.TableColumns((col.info.name, col) for col in cols)
for col in cols:
col.info.parent_table = table
if table.masked and not hasattr(col, 'mask'):
col.mask = FalseArray(col.shape)
table.columns = columns
def itercols(self):
"""
Iterate over the columns of this table.
Examples
--------
To iterate over the columns of a table::
>>> t = Table([[1], [2]])
>>> for col in t.itercols():
... print(col)
col0
----
1
col1
----
2
Using ``itercols()`` is similar to ``for col in t.columns.values()``
but is syntactically preferred.
"""
for colname in self.columns:
yield self[colname]
def _base_repr_(self, html=False, descr_vals=None, max_width=None,
tableid=None, show_dtype=True, max_lines=None,
tableclass=None):
if descr_vals is None:
descr_vals = [self.__class__.__name__]
if self.masked:
descr_vals.append('masked=True')
descr_vals.append('length={0}'.format(len(self)))
descr = '<' + ' '.join(descr_vals) + '>\n'
if html:
from ..utils.xml.writer import xml_escape
descr = xml_escape(descr)
if tableid is None:
tableid = 'table{id}'.format(id=id(self))
data_lines, outs = self.formatter._pformat_table(
self, tableid=tableid, html=html, max_width=max_width,
show_name=True, show_unit=None, show_dtype=show_dtype,
max_lines=max_lines, tableclass=tableclass)
out = descr + '\n'.join(data_lines)
if six.PY2 and isinstance(out, six.text_type):
out = out.encode('utf-8')
return out
def _repr_html_(self):
return self._base_repr_(html=True, max_width=-1,
tableclass=conf.default_notebook_table_class)
def __repr__(self):
return self._base_repr_(html=False, max_width=None)
def __unicode__(self):
return '\n'.join(self.pformat())
if not six.PY2:
__str__ = __unicode__
def __bytes__(self):
return six.text_type(self).encode('utf-8')
if six.PY2:
__str__ = __bytes__
@property
def has_mixin_columns(self):
"""
True if table has any mixin columns (defined as columns that are not Column
subclasses)
"""
return any(has_info_class(col, MixinInfo) for col in self.columns.values())
def _add_as_mixin_column(self, col):
"""
Determine if ``col`` should be added to the table directly as
a mixin column.
"""
if isinstance(col, BaseColumn):
return False
# Is it a mixin but not not Quantity (which gets converted to Column with
# unit set).
return has_info_class(col, MixinInfo) and not isinstance(col, Quantity)
def pprint(self, max_lines=None, max_width=None, show_name=True,
show_unit=None, show_dtype=False, align=None):
"""Print a formatted string representation of the table.
If no value of ``max_lines`` is supplied then the height of the
screen terminal is used to set ``max_lines``. If the terminal
height cannot be determined then the default is taken from the
configuration item ``astropy.conf.max_lines``. If a negative
value of ``max_lines`` is supplied then there is no line limit
applied.
The same applies for max_width except the configuration item is
``astropy.conf.max_width``.
Parameters
----------
max_lines : int
Maximum number of lines in table output
max_width : int or `None`
Maximum character width of output
show_name : bool
Include a header row for column names (default=True)
show_unit : bool
Include a header row for unit. Default is to show a row
for units only if one or more columns has a defined value
for the unit.
show_dtype : bool
Include a header row for column dtypes (default=True)
align : str or list or tuple or `None`
Left/right alignment of columns. Default is right (None) for all
columns. Other allowed values are '>', '<', '^', and '0=' for
right, left, centered, and 0-padded, respectively. A list of
strings can be provided for alignment of tables with multiple
columns.
"""
lines, outs = self.formatter._pformat_table(self, max_lines, max_width,
show_name=show_name, show_unit=show_unit,
show_dtype=show_dtype, align=align)
if outs['show_length']:
lines.append('Length = {0} rows'.format(len(self)))
n_header = outs['n_header']
for i, line in enumerate(lines):
if i < n_header:
color_print(line, 'red')
else:
print(line)
def _make_index_row_display_table(self, index_row_name):
if index_row_name not in self.columns:
idx_col = self.ColumnClass(name=index_row_name, data=np.arange(len(self)))
return self.__class__([idx_col] + self.columns.values(),
copy=False)
else:
return self
def show_in_notebook(self, tableid=None, css=None, display_length=50,
table_class='astropy-default', show_row_index='idx'):
"""Render the table in HTML and show it in the IPython notebook.
Parameters
----------
tableid : str or `None`
An html ID tag for the table. Default is ``table{id}-XXX``, where
id is the unique integer id of the table object, id(self), and XXX
is a random number to avoid conflicts when printing the same table
multiple times.
table_class : str or `None`
A string with a list of HTML classes used to style the table.
The special default string ('astropy-default') means that the string
will be retrieved from the configuration item
``astropy.table.default_notebook_table_class``. Note that these
table classes may make use of bootstrap, as this is loaded with the
notebook. See `this page <http://getbootstrap.com/css/#tables>`_
for the list of classes.
css : string
A valid CSS string declaring the formatting for the table. Default
to ``astropy.table.jsviewer.DEFAULT_CSS_NB``.
display_length : int, optional
Number or rows to show. Defaults to 50.
show_row_index : str or False
If this does not evaluate to False, a column with the given name
will be added to the version of the table that gets displayed.
This new column shows the index of the row in the table itself,
even when the displayed table is re-sorted by another column. Note
that if a column with this name already exists, this option will be
ignored. Defaults to "idx".
Notes
-----
Currently, unlike `show_in_browser` (with ``jsviewer=True``), this
method needs to access online javascript code repositories. This is due
to modern browsers' limitations on accessing local files. Hence, if you
call this method while offline (and don't have a cached version of
jquery and jquery.dataTables), you will not get the jsviewer features.
"""
from .jsviewer import JSViewer
from IPython.display import HTML
if tableid is None:
tableid = 'table{0}-{1}'.format(id(self),
np.random.randint(1, 1e6))
jsv = JSViewer(display_length=display_length)
if show_row_index:
display_table = self._make_index_row_display_table(show_row_index)
else:
display_table = self
if table_class == 'astropy-default':
table_class = conf.default_notebook_table_class
html = display_table._base_repr_(html=True, max_width=-1, tableid=tableid,
max_lines=-1, show_dtype=False,
tableclass=table_class)
columns = display_table.columns.values()
sortable_columns = [i for i, col in enumerate(columns)
if col.dtype.kind in 'iufc']
html += jsv.ipynb(tableid, css=css, sort_columns=sortable_columns)
return HTML(html)
def show_in_browser(self, max_lines=5000, jsviewer=False,
browser='default', jskwargs={'use_local_files': True},
tableid=None, table_class="display compact",
css=None, show_row_index='idx'):
"""Render the table in HTML and show it in a web browser.
Parameters
----------
max_lines : int
Maximum number of rows to export to the table (set low by default
to avoid memory issues, since the browser view requires duplicating
the table in memory). A negative value of ``max_lines`` indicates
no row limit.
jsviewer : bool
If `True`, prepends some javascript headers so that the table is
rendered as a `DataTables <https://datatables.net>`_ data table.
This allows in-browser searching & sorting.
browser : str
Any legal browser name, e.g. ``'firefox'``, ``'chrome'``,
``'safari'`` (for mac, you may need to use ``'open -a
"/Applications/Google Chrome.app" {}'`` for Chrome). If
``'default'``, will use the system default browser.
jskwargs : dict
Passed to the `astropy.table.JSViewer` init. Defaults to
``{'use_local_files': True}`` which means that the JavaScript
libraries will be served from local copies.
tableid : str or `None`
An html ID tag for the table. Default is ``table{id}``, where id
is the unique integer id of the table object, id(self).
table_class : str or `None`
A string with a list of HTML classes used to style the table.
Default is "display compact", and other possible values can be
found in http://www.datatables.net/manual/styling/classes
css : string
A valid CSS string declaring the formatting for the table. Defaults
to ``astropy.table.jsviewer.DEFAULT_CSS``.
show_row_index : str or False
If this does not evaluate to False, a column with the given name
will be added to the version of the table that gets displayed.
This new column shows the index of the row in the table itself,
even when the displayed table is re-sorted by another column. Note
that if a column with this name already exists, this option will be
ignored. Defaults to "idx".
"""
import os
import webbrowser
import tempfile
from ..extern.six.moves.urllib.parse import urljoin
from ..extern.six.moves.urllib.request import pathname2url
from .jsviewer import DEFAULT_CSS
if css is None:
css = DEFAULT_CSS
# We can't use NamedTemporaryFile here because it gets deleted as
# soon as it gets garbage collected.
tmpdir = tempfile.mkdtemp()
path = os.path.join(tmpdir, 'table.html')
with open(path, 'w') as tmp:
if jsviewer:
if show_row_index:
display_table = self._make_index_row_display_table(show_row_index)
else:
display_table = self
display_table.write(tmp, format='jsviewer', css=css,
max_lines=max_lines, jskwargs=jskwargs,
table_id=tableid, table_class=table_class)
else:
self.write(tmp, format='html')
try:
br = webbrowser.get(None if browser == 'default' else browser)
except webbrowser.Error:
log.error("Browser '{}' not found.".format(browser))
else:
br.open(urljoin('file:', pathname2url(path)))
def pformat(self, max_lines=None, max_width=None, show_name=True,
show_unit=None, show_dtype=False, html=False, tableid=None,
align=None, tableclass=None):
"""Return a list of lines for the formatted string representation of
the table.
If no value of ``max_lines`` is supplied then the height of the
screen terminal is used to set ``max_lines``. If the terminal
height cannot be determined then the default is taken from the
configuration item ``astropy.conf.max_lines``. If a negative
value of ``max_lines`` is supplied then there is no line limit
applied.
The same applies for ``max_width`` except the configuration item is
``astropy.conf.max_width``.
Parameters
----------
max_lines : int or `None`
Maximum number of rows to output
max_width : int or `None`
Maximum character width of output
show_name : bool
Include a header row for column names (default=True)
show_unit : bool
Include a header row for unit. Default is to show a row
for units only if one or more columns has a defined value
for the unit.
show_dtype : bool
Include a header row for column dtypes (default=True)
html : bool
Format the output as an HTML table (default=False)
tableid : str or `None`
An ID tag for the table; only used if html is set. Default is
"table{id}", where id is the unique integer id of the table object,
id(self)
align : str or list or tuple or `None`
Left/right alignment of columns. Default is right (None) for all
columns. Other allowed values are '>', '<', '^', and '0=' for
right, left, centered, and 0-padded, respectively. A list of
strings can be provided for alignment of tables with multiple
columns.
tableclass : str or list of str or `None`
CSS classes for the table; only used if html is set. Default is
none
Returns
-------
lines : list
Formatted table as a list of strings
"""
lines, outs = self.formatter._pformat_table(
self, max_lines, max_width, show_name=show_name,
show_unit=show_unit, show_dtype=show_dtype, html=html,
tableid=tableid, tableclass=tableclass, align=align)
if outs['show_length']:
lines.append('Length = {0} rows'.format(len(self)))
return lines
def more(self, max_lines=None, max_width=None, show_name=True,
show_unit=None, show_dtype=False):
"""Interactively browse table with a paging interface.
Supported keys::
f, <space> : forward one page
b : back one page
r : refresh same page
n : next row
p : previous row
< : go to beginning
> : go to end
q : quit browsing
h : print this help
Parameters
----------
max_lines : int
Maximum number of lines in table output
max_width : int or `None`
Maximum character width of output
show_name : bool
Include a header row for column names (default=True)
show_unit : bool
Include a header row for unit. Default is to show a row
for units only if one or more columns has a defined value
for the unit.
show_dtype : bool
Include a header row for column dtypes (default=True)
"""
self.formatter._more_tabcol(self, max_lines, max_width, show_name=show_name,
show_unit=show_unit, show_dtype=show_dtype)
def __getitem__(self, item):
if isinstance(item, six.string_types):
return self.columns[item]
elif isinstance(item, (int, np.integer)):
return self.Row(self, item)
elif (isinstance(item, np.ndarray) and item.shape == () and item.dtype.kind == 'i'):
return self.Row(self, item.item())
elif (isinstance(item, (tuple, list)) and item and
all(isinstance(x, six.string_types) for x in item)):
bad_names = [x for x in item if x not in self.colnames]
if bad_names:
raise ValueError('Slice name(s) {0} not valid column name(s)'
.format(', '.join(bad_names)))
out = self.__class__([self[x] for x in item],
meta=deepcopy(self.meta),
copy_indices=self._copy_indices)
out._groups = groups.TableGroups(out, indices=self.groups._indices,
keys=self.groups._keys)
return out
elif ((isinstance(item, np.ndarray) and item.size == 0) or
(isinstance(item, (tuple, list)) and not item)):
# If item is an empty array/list/tuple then return the table with no rows
return self._new_from_slice([])
elif (isinstance(item, slice) or
isinstance(item, np.ndarray) or
isinstance(item, list) or
isinstance(item, tuple) and all(isinstance(x, np.ndarray)
for x in item)):
# here for the many ways to give a slice; a tuple of ndarray
# is produced by np.where, as in t[np.where(t['a'] > 2)]
# For all, a new table is constructed with slice of all columns
return self._new_from_slice(item)
else:
raise ValueError('Illegal type {0} for table item access'
.format(type(item)))
def __setitem__(self, item, value):
# If the item is a string then it must be the name of a column.
# If that column doesn't already exist then create it now.
if isinstance(item, six.string_types) and item not in self.colnames:
NewColumn = self.MaskedColumn if self.masked else self.Column
# If value doesn't have a dtype and won't be added as a mixin then
# convert to a numpy array.
if not hasattr(value, 'dtype') and not self._add_as_mixin_column(value):
value = np.asarray(value)
# Structured ndarray gets viewed as a mixin
if isinstance(value, np.ndarray) and len(value.dtype) > 1:
value = value.view(NdarrayMixin)
# Make new column and assign the value. If the table currently
# has no rows (len=0) of the value is already a Column then
# define new column directly from value. In the latter case
# this allows for propagation of Column metadata. Otherwise
# define a new column with the right length and shape and then
# set it from value. This allows for broadcasting, e.g. t['a']
# = 1.
name = item
# If this is a column-like object that could be added directly to table
if isinstance(value, BaseColumn) or self._add_as_mixin_column(value):
# If we're setting a new column to a scalar, broadcast it.
# (things will fail in _init_from_cols if this doesn't work)
if (len(self) > 0 and (getattr(value, 'isscalar', False) or
getattr(value, 'shape', None) == () or
len(value) == 1)):
new_shape = (len(self),) + getattr(value, 'shape', ())[1:]
if isinstance(value, np.ndarray):
value = np_broadcast_to(value, shape=new_shape,
subok=True)
elif isinstance(value, ShapedLikeNDArray):
value = value._apply(np_broadcast_to, shape=new_shape,
subok=True)
new_column = col_copy(value)
new_column.info.name = name
elif len(self) == 0:
new_column = NewColumn(value, name=name)
else:
new_column = NewColumn(name=name, length=len(self), dtype=value.dtype,
shape=value.shape[1:],
unit=getattr(value, 'unit', None))
new_column[:] = value
# Now add new column to the table
self.add_columns([new_column], copy=False)
else:
n_cols = len(self.columns)
if isinstance(item, six.string_types):
# Set an existing column by first trying to replace, and if
# this fails do an in-place update. See definition of mask
# property for discussion of the _setitem_inplace attribute.
if (not getattr(self, '_setitem_inplace', False)
and not conf.replace_inplace):
try:
self._replace_column_warnings(item, value)
return
except Exception:
pass
self.columns[item][:] = value
elif isinstance(item, (int, np.integer)):
# Set the corresponding row assuming value is an iterable.
if not hasattr(value, '__len__'):
raise TypeError('Right side value must be iterable')
if len(value) != n_cols:
raise ValueError('Right side value needs {0} elements (one for each column)'
.format(n_cols))
for col, val in zip(self.columns.values(), value):
col[item] = val
elif (isinstance(item, slice) or
isinstance(item, np.ndarray) or
isinstance(item, list) or
(isinstance(item, tuple) and # output from np.where
all(isinstance(x, np.ndarray) for x in item))):
if isinstance(value, Table):
vals = (col for col in value.columns.values())
elif isinstance(value, np.ndarray) and value.dtype.names:
vals = (value[name] for name in value.dtype.names)
elif np.isscalar(value):
import itertools
vals = itertools.repeat(value, n_cols)
else: # Assume this is an iterable that will work
if len(value) != n_cols:
raise ValueError('Right side value needs {0} elements (one for each column)'
.format(n_cols))
vals = value
for col, val in zip(self.columns.values(), vals):
col[item] = val
else:
raise ValueError('Illegal type {0} for table item access'
.format(type(item)))
def __delitem__(self, item):
if isinstance(item, six.string_types):
self.remove_column(item)
elif isinstance(item, tuple):
self.remove_columns(item)
def field(self, item):
"""Return column[item] for recarray compatibility."""
return self.columns[item]
@property
def masked(self):
return self._masked
@masked.setter
def masked(self, masked):
raise Exception('Masked attribute is read-only (use t = Table(t, masked=True)'
' to convert to a masked table)')
def _set_masked(self, masked):
"""
Set the table masked property.
Parameters
----------
masked : bool
State of table masking (`True` or `False`)
"""
if hasattr(self, '_masked'):
# The only allowed change is from None to False or True, or False to True
if self._masked is None and masked in [False, True]:
self._masked = masked
elif self._masked is False and masked is True:
log.info("Upgrading Table to masked Table. Use Table.filled() to convert to unmasked table.")
self._masked = masked
elif self._masked is masked:
raise Exception("Masked attribute is already set to {0}".format(masked))
else:
raise Exception("Cannot change masked attribute to {0} once it is set to {1}"
.format(masked, self._masked))
else:
if masked in [True, False, None]:
self._masked = masked
else:
raise ValueError("masked should be one of True, False, None")
if self._masked:
self._column_class = self.MaskedColumn
else:
self._column_class = self.Column
@property
def ColumnClass(self):
if self._column_class is None:
return self.Column
else:
return self._column_class
@property
def dtype(self):
return np.dtype([descr(col) for col in self.columns.values()])
@property
def colnames(self):
return list(self.columns.keys())
def keys(self):
return list(self.columns.keys())
def __len__(self):
if len(self.columns) == 0:
return 0
lengths = set(len(col) for col in self.columns.values())
if len(lengths) != 1:
len_strs = [' {0} : {1}'.format(name, len(col)) for name, col in self.columns.items()]
raise ValueError('Column length mismatch:\n{0}'.format('\n'.join(len_strs)))
return lengths.pop()
def index_column(self, name):
"""
Return the positional index of column ``name``.
Parameters
----------
name : str
column name
Returns
-------
index : int
Positional index of column ``name``.
Examples
--------
Create a table with three columns 'a', 'b' and 'c'::
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']],
... names=('a', 'b', 'c'))
>>> print(t)
a b c
--- --- ---
1 0.1 x
2 0.2 y
3 0.3 z
Get index of column 'b' of the table::
>>> t.index_column('b')
1
"""
try:
return self.colnames.index(name)
except ValueError:
raise ValueError("Column {0} does not exist".format(name))
def add_column(self, col, index=None, rename_duplicate=False):
"""
Add a new Column object ``col`` to the table. If ``index``
is supplied then insert column before ``index`` position
in the list of columns, otherwise append column to the end
of the list.
Parameters
----------
col : Column
Column object to add.
index : int or `None`
Insert column before this position or at end (default)
rename_duplicate : bool
Uniquify column name if it already exist (default=False)
Examples
--------
Create a table with two columns 'a' and 'b'::
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3]], names=('a', 'b'))
>>> print(t)
a b
--- ---
1 0.1
2 0.2
3 0.3
Create a third column 'c' and append it to the end of the table::
>>> col_c = Column(name='c', data=['x', 'y', 'z'])
>>> t.add_column(col_c)
>>> print(t)
a b c
--- --- ---
1 0.1 x
2 0.2 y
3 0.3 z
Add column 'd' at position 1. Note that the column is inserted
before the given index::
>>> col_d = Column(name='d', data=['a', 'b', 'c'])
>>> t.add_column(col_d, 1)
>>> print(t)
a d b c
--- --- --- ---
1 a 0.1 x
2 b 0.2 y
3 c 0.3 z
Add second column named 'b' with rename_duplicate::
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3]], names=('a', 'b'))
>>> col_b = Column(name='b', data=[1.1, 1.2, 1.3])
>>> t.add_column(col_b, rename_duplicate=True)
>>> print(t)
a b b_1
--- --- ---
1 0.1 1.1
2 0.2 1.2
3 0.3 1.3
To add several columns use add_columns.
"""
if index is None:
index = len(self.columns)
self.add_columns([col], [index], rename_duplicate=rename_duplicate)
def add_columns(self, cols, indexes=None, copy=True, rename_duplicate=False):
"""
Add a list of new Column objects ``cols`` to the table. If a
corresponding list of ``indexes`` is supplied then insert column
before each ``index`` position in the *original* list of columns,
otherwise append columns to the end of the list.
Parameters
----------
cols : list of Columns
Column objects to add.
indexes : list of ints or `None`
Insert column before this position or at end (default)
copy : bool
Make a copy of the new columns (default=True)
rename_duplicate : bool
Uniquify new column names if they duplicate the existing ones
(default=False)
Examples
--------
Create a table with two columns 'a' and 'b'::
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3]], names=('a', 'b'))
>>> print(t)
a b
--- ---
1 0.1
2 0.2
3 0.3
Create column 'c' and 'd' and append them to the end of the table::
>>> col_c = Column(name='c', data=['x', 'y', 'z'])
>>> col_d = Column(name='d', data=['u', 'v', 'w'])
>>> t.add_columns([col_c, col_d])
>>> print(t)
a b c d
--- --- --- ---
1 0.1 x u
2 0.2 y v
3 0.3 z w
Add column 'c' at position 0 and column 'd' at position 1. Note that
the columns are inserted before the given position::
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3]], names=('a', 'b'))
>>> col_c = Column(name='c', data=['x', 'y', 'z'])
>>> col_d = Column(name='d', data=['u', 'v', 'w'])
>>> t.add_columns([col_c, col_d], [0, 1])
>>> print(t)
c a d b
--- --- --- ---
x 1 u 0.1
y 2 v 0.2
z 3 w 0.3
Add second column 'b' and column 'c' with ``rename_duplicate``::
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3]], names=('a', 'b'))
>>> col_b = Column(name='b', data=[1.1, 1.2, 1.3])
>>> col_c = Column(name='c', data=['x', 'y', 'z'])
>>> t.add_columns([col_b, col_c], rename_duplicate=True)
>>> print(t)
a b b_1 c
--- --- --- ---
1 0.1 1.1 x
2 0.2 1.2 y
3 0.3 1.3 z
"""
if indexes is None:
indexes = [len(self.columns)] * len(cols)
elif len(indexes) != len(cols):
raise ValueError('Number of indexes must match number of cols')
if copy:
cols = [col_copy(col) for col in cols]
if len(self.columns) == 0:
# No existing table data, init from cols
newcols = cols
else:
newcols = list(self.columns.values())
new_indexes = list(range(len(newcols) + 1))
for col, index in zip(cols, indexes):
i = new_indexes.index(index)
new_indexes.insert(i, None)
newcols.insert(i, col)
if rename_duplicate:
existing_names = set(self.colnames)
for col in cols:
i = 1
orig_name = col.info.name
while col.info.name in existing_names:
# If the column belongs to another table then copy it
# before renaming
if col.info.parent_table is not None:
col = col_copy(col)
new_name = '{0}_{1}'.format(orig_name, i)
col.info.name = new_name
i += 1
existing_names.add(new_name)
self._init_from_cols(newcols)
def _replace_column_warnings(self, name, col):
"""
Same as replace_column but issues warnings under various circumstances.
"""
warns = conf.replace_warnings
if 'refcount' in warns and name in self.colnames:
refcount = sys.getrefcount(self[name])
if name in self.colnames:
old_col = self[name]
# This may raise an exception (e.g. t['a'] = 1) in which case none of
# the downstream code runs.
self.replace_column(name, col)
if 'always' in warns:
warnings.warn("replaced column '{}'".format(name),
TableReplaceWarning, stacklevel=3)
if 'slice' in warns:
try:
# Check for ndarray-subclass slice. An unsliced instance
# has an ndarray for the base while sliced has the same class
# as parent.
if isinstance(old_col.base, old_col.__class__):
msg = ("replaced column '{}' which looks like an array slice. "
"The new column no longer shares memory with the "
"original array.".format(name))
warnings.warn(msg, TableReplaceWarning, stacklevel=3)
except AttributeError:
pass
if 'refcount' in warns:
# Did reference count change?
new_refcount = sys.getrefcount(self[name])
if refcount != new_refcount:
msg = ("replaced column '{}' and the number of references "
"to the column changed.".format(name))
warnings.warn(msg, TableReplaceWarning, stacklevel=3)
if 'attributes' in warns:
# Any of the standard column attributes changed?
changed_attrs = []
new_col = self[name]
# Check base DataInfo attributes that any column will have
for attr in DataInfo.attr_names:
if getattr(old_col.info, attr) != getattr(new_col.info, attr):
changed_attrs.append(attr)
if changed_attrs:
msg = ("replaced column '{}' and column attributes {} changed."
.format(name, changed_attrs))
warnings.warn(msg, TableReplaceWarning, stacklevel=3)
def replace_column(self, name, col):
"""
Replace column ``name`` with the new ``col`` object.
Parameters
----------
name : str
Name of column to replace
col : column object (list, ndarray, Column, etc)
New column object to replace the existing column
Examples
--------
Replace column 'a' with a float version of itself::
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3]], names=('a', 'b'))
>>> float_a = t['a'].astype(float)
>>> t.replace_column('a', float_a)
"""
if name not in self.colnames:
raise ValueError('column name {0} is not in the table'.format(name))
if self[name].info.indices:
raise ValueError('cannot replace a table index column')
t = self.__class__([col], names=[name])
cols = OrderedDict(self.columns)
cols[name] = t[name]
self._init_from_cols(cols.values())
def remove_row(self, index):
"""
Remove a row from the table.
Parameters
----------
index : int
Index of row to remove
Examples
--------
Create a table with three columns 'a', 'b' and 'c'::
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']],
... names=('a', 'b', 'c'))
>>> print(t)
a b c
--- --- ---
1 0.1 x
2 0.2 y
3 0.3 z
Remove row 1 from the table::
>>> t.remove_row(1)
>>> print(t)
a b c
--- --- ---
1 0.1 x
3 0.3 z
To remove several rows at the same time use remove_rows.
"""
# check the index against the types that work with np.delete
if not isinstance(index, (six.integer_types, np.integer)):
raise TypeError("Row index must be an integer")
self.remove_rows(index)
def remove_rows(self, row_specifier):
"""
Remove rows from the table.
Parameters
----------
row_specifier : slice, int, or array of ints
Specification for rows to remove
Examples
--------
Create a table with three columns 'a', 'b' and 'c'::
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']],
... names=('a', 'b', 'c'))
>>> print(t)
a b c
--- --- ---
1 0.1 x
2 0.2 y
3 0.3 z
Remove rows 0 and 2 from the table::
>>> t.remove_rows([0, 2])
>>> print(t)
a b c
--- --- ---
2 0.2 y
Note that there are no warnings if the slice operator extends
outside the data::
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']],
... names=('a', 'b', 'c'))
>>> t.remove_rows(slice(10, 20, 1))
>>> print(t)
a b c
--- --- ---
1 0.1 x
2 0.2 y
3 0.3 z
"""
# Update indices
for index in self.indices:
index.remove_rows(row_specifier)
keep_mask = np.ones(len(self), dtype=np.bool)
keep_mask[row_specifier] = False
columns = self.TableColumns()
for name, col in self.columns.items():
newcol = col[keep_mask]
newcol.info.parent_table = self
columns[name] = newcol
self._replace_cols(columns)
# Revert groups to default (ungrouped) state
if hasattr(self, '_groups'):
del self._groups
def remove_column(self, name):
"""
Remove a column from the table.
This can also be done with::
del table[name]
Parameters
----------
name : str
Name of column to remove
Examples
--------
Create a table with three columns 'a', 'b' and 'c'::
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']],
... names=('a', 'b', 'c'))
>>> print(t)
a b c
--- --- ---
1 0.1 x
2 0.2 y
3 0.3 z
Remove column 'b' from the table::
>>> t.remove_column('b')
>>> print(t)
a c
--- ---
1 x
2 y
3 z
To remove several columns at the same time use remove_columns.
"""
self.remove_columns([name])
def remove_columns(self, names):
'''
Remove several columns from the table.
Parameters
----------
names : list
A list containing the names of the columns to remove
Examples
--------
Create a table with three columns 'a', 'b' and 'c'::
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']],
... names=('a', 'b', 'c'))
>>> print(t)
a b c
--- --- ---
1 0.1 x
2 0.2 y
3 0.3 z
Remove columns 'b' and 'c' from the table::
>>> t.remove_columns(['b', 'c'])
>>> print(t)
a
---
1
2
3
Specifying only a single column also works. Remove column 'b' from the table::
>>> t = Table([[1, 2, 3], [0.1, 0.2, 0.3], ['x', 'y', 'z']],
... names=('a', 'b', 'c'))
>>> t.remove_columns('b')
>>> print(t)
a c
--- ---
1 x
2 y
3 z
This gives the same as using remove_column.
'''
if isinstance(names, six.string_types):
names = [names]
for name in names:
if name not in self.columns:
raise KeyError("Column {0} does not exist".format(name))
for name in names:
self.columns.pop(name)
def _convert_string_dtype(self, in_kind, out_kind, python3_only):
"""
Convert string-like columns to/from bytestring and unicode (internal only).
Parameters
----------
in_kind : str
Input dtype.kind
out_kind : str
Output dtype.kind
python3_only : bool
Only do this operation for Python 3
"""
if python3_only and six.PY2:
return
# If there are no `in_kind` columns then do nothing
cols = self.columns.values()
if not any(col.dtype.kind == in_kind for col in cols):
return
newcols = []
for col in cols:
if col.dtype.kind == in_kind:
newdtype = re.sub(in_kind, out_kind, col.dtype.str)
newcol = col.__class__(col, dtype=newdtype)
else:
newcol = col
newcols.append(newcol)
self._init_from_cols(newcols)
def convert_bytestring_to_unicode(self, python3_only=False):
"""
Convert bytestring columns (dtype.kind='S') to unicode (dtype.kind='U') assuming
ASCII encoding.
Internally this changes string columns to represent each character in the string
with a 4-byte UCS-4 equivalent, so it is inefficient for memory but allows Python
3 scripts to manipulate string arrays with natural syntax.
The ``python3_only`` parameter is provided as a convenience so that code can
be written in a Python 2 / 3 compatible way::
>>> t = Table.read('my_data.fits')
>>> t.convert_bytestring_to_unicode(python3_only=True)
Parameters
----------
python3_only : bool
Only do this operation for Python 3
"""
self._convert_string_dtype('S', 'U', python3_only)
def convert_unicode_to_bytestring(self, python3_only=False):
"""
Convert ASCII-only unicode columns (dtype.kind='U') to bytestring (dtype.kind='S').
When exporting a unicode string array to a file in Python 3, it may be desirable
to encode unicode columns as bytestrings. This routine takes advantage of numpy
automated conversion which works for strings that are pure ASCII.
The ``python3_only`` parameter is provided as a convenience so that code can
be written in a Python 2 / 3 compatible way::
>>> t.convert_unicode_to_bytestring(python3_only=True)
>>> t.write('my_data.fits')
Parameters
----------
python3_only : bool
Only do this operation for Python 3
"""
self._convert_string_dtype('U', 'S', python3_only)
def keep_columns(self, names):
'''
Keep only the columns specified (remove the others).
Parameters
----------
names : list
A list containing the names of the columns to keep. All other
columns will be removed.
Examples
--------
Create a table with three columns 'a', 'b' and 'c'::
>>> t = Table([[1, 2, 3],[0.1, 0.2, 0.3],['x', 'y', 'z']],
... names=('a', 'b', 'c'))
>>> print(t)
a b c
--- --- ---
1 0.1 x
2 0.2 y
3 0.3 z
Specifying only a single column name keeps only this column.
Keep only column 'a' of the table::
>>> t.keep_columns('a')
>>> print(t)
a
---
1
2
3
Specifying a list of column names is keeps is also possible.
Keep columns 'a' and 'c' of the table::
>>> t = Table([[1, 2, 3],[0.1, 0.2, 0.3],['x', 'y', 'z']],
... names=('a', 'b', 'c'))
>>> t.keep_columns(['a', 'c'])
>>> print(t)
a c
--- ---
1 x
2 y
3 z
'''
if isinstance(names, six.string_types):
names = [names]
for name in names:
if name not in self.columns:
raise KeyError("Column {0} does not exist".format(name))
remove = list(set(self.keys()) - set(names))
self.remove_columns(remove)
def rename_column(self, name, new_name):
'''
Rename a column.
This can also be done directly with by setting the ``name`` attribute
for a column::
table[name].name = new_name
TODO: this won't work for mixins
Parameters
----------
name : str
The current name of the column.
new_name : str
The new name for the column
Examples
--------
Create a table with three columns 'a', 'b' and 'c'::
>>> t = Table([[1,2],[3,4],[5,6]], names=('a','b','c'))
>>> print(t)
a b c
--- --- ---
1 3 5
2 4 6
Renaming column 'a' to 'aa'::
>>> t.rename_column('a' , 'aa')
>>> print(t)
aa b c
--- --- ---
1 3 5
2 4 6
'''
if name not in self.keys():
raise KeyError("Column {0} does not exist".format(name))
self.columns[name].info.name = new_name
def add_row(self, vals=None, mask=None):
"""Add a new row to the end of the table.
The ``vals`` argument can be:
sequence (e.g. tuple or list)
Column values in the same order as table columns.
mapping (e.g. dict)
Keys corresponding to column names. Missing values will be
filled with np.zeros for the column dtype.
`None`
All values filled with np.zeros for the column dtype.
This method requires that the Table object "owns" the underlying array
data. In particular one cannot add a row to a Table that was
initialized with copy=False from an existing array.
The ``mask`` attribute should give (if desired) the mask for the
values. The type of the mask should match that of the values, i.e. if
``vals`` is an iterable, then ``mask`` should also be an iterable
with the same length, and if ``vals`` is a mapping, then ``mask``
should be a dictionary.
Parameters
----------
vals : tuple, list, dict or `None`
Use the specified values in the new row
mask : tuple, list, dict or `None`
Use the specified mask values in the new row
Examples
--------
Create a table with three columns 'a', 'b' and 'c'::
>>> t = Table([[1,2],[4,5],[7,8]], names=('a','b','c'))
>>> print(t)
a b c
--- --- ---
1 4 7
2 5 8
Adding a new row with entries '3' in 'a', '6' in 'b' and '9' in 'c'::
>>> t.add_row([3,6,9])
>>> print(t)
a b c
--- --- ---
1 4 7
2 5 8
3 6 9
"""
self.insert_row(len(self), vals, mask)
def insert_row(self, index, vals=None, mask=None):
"""Add a new row before the given ``index`` position in the table.
The ``vals`` argument can be:
sequence (e.g. tuple or list)
Column values in the same order as table columns.
mapping (e.g. dict)
Keys corresponding to column names. Missing values will be
filled with np.zeros for the column dtype.
`None`
All values filled with np.zeros for the column dtype.
The ``mask`` attribute should give (if desired) the mask for the
values. The type of the mask should match that of the values, i.e. if
``vals`` is an iterable, then ``mask`` should also be an iterable
with the same length, and if ``vals`` is a mapping, then ``mask``
should be a dictionary.
Parameters
----------
vals : tuple, list, dict or `None`
Use the specified values in the new row
mask : tuple, list, dict or `None`
Use the specified mask values in the new row
"""
colnames = self.colnames
N = len(self)
if index < -N or index > N:
raise IndexError("Index {0} is out of bounds for table with length {1}"
.format(index, N))
if index < 0:
index += N
def _is_mapping(obj):
"""Minimal checker for mapping (dict-like) interface for obj"""
attrs = ('__getitem__', '__len__', '__iter__', 'keys', 'values', 'items')
return all(hasattr(obj, attr) for attr in attrs)
if mask is not None and not self.masked:
# Possibly issue upgrade warning and update self.ColumnClass. This
# does not change the existing columns.
self._set_masked(True)
if _is_mapping(vals) or vals is None:
# From the vals and/or mask mappings create the corresponding lists
# that have entries for each table column.
if mask is not None and not _is_mapping(mask):
raise TypeError("Mismatch between type of vals and mask")
# Now check that the mask is specified for the same keys as the
# values, otherwise things get really confusing.
if mask is not None and set(vals.keys()) != set(mask.keys()):
raise ValueError('keys in mask should match keys in vals')
if vals and any(name not in colnames for name in vals):
raise ValueError('Keys in vals must all be valid column names')
vals_list = []
mask_list = []
for name in colnames:
if vals and name in vals:
vals_list.append(vals[name])
mask_list.append(False if mask is None else mask[name])
else:
col = self[name]
if hasattr(col, 'dtype'):
# Make a placeholder zero element of the right type which is masked.
# This assumes the appropriate insert() method will broadcast a
# numpy scalar to the right shape.
vals_list.append(np.zeros(shape=(), dtype=col.dtype))
# For masked table any unsupplied values are masked by default.
mask_list.append(self.masked and vals is not None)
else:
raise ValueError("Value must be supplied for column '{0}'".format(name))
vals = vals_list
mask = mask_list
if isiterable(vals):
if mask is not None and (not isiterable(mask) or _is_mapping(mask)):
raise TypeError("Mismatch between type of vals and mask")
if len(self.columns) != len(vals):
raise ValueError('Mismatch between number of vals and columns')
if mask is not None:
if len(self.columns) != len(mask):
raise ValueError('Mismatch between number of masks and columns')
else:
mask = [False] * len(self.columns)
else:
raise TypeError('Vals must be an iterable or mapping or None')
columns = self.TableColumns()
try:
# Insert val at index for each column
for name, col, val, mask_ in zip(colnames, self.columns.values(), vals, mask):
# If the new row caused a change in self.ColumnClass then
# Column-based classes need to be converted first. This is
# typical for adding a row with mask values to an unmasked table.
if isinstance(col, Column) and not isinstance(col, self.ColumnClass):
col = self.ColumnClass(col, copy=False)
newcol = col.insert(index, val)
if not isinstance(newcol, BaseColumn):
newcol.info.name = name
if self.masked:
newcol.mask = FalseArray(newcol.shape)
if len(newcol) != N + 1:
raise ValueError('Incorrect length for column {0} after inserting {1}'
' (expected {2}, got {3})'
.format(name, val, len(newcol), N + 1))
newcol.info.parent_table = self
# Set mask if needed
if self.masked:
newcol.mask[index] = mask_
columns[name] = newcol
# insert row in indices
for table_index in self.indices:
table_index.insert_row(index, vals, self.columns.values())
except Exception as err:
raise ValueError("Unable to insert row because of exception in column '{0}':\n{1}"
.format(name, err))
else:
self._replace_cols(columns)
# Revert groups to default (ungrouped) state
if hasattr(self, '_groups'):
del self._groups
def _replace_cols(self, columns):
for col, new_col in zip(self.columns.values(), columns.values()):
new_col.info.indices = []
for index in col.info.indices:
index.columns[index.col_position(col.info.name)] = new_col
new_col.info.indices.append(index)
self.columns = columns
def argsort(self, keys=None, kind=None):
"""
Return the indices which would sort the table according to one or
more key columns. This simply calls the `numpy.argsort` function on
the table with the ``order`` parameter set to ``keys``.
Parameters
----------
keys : str or list of str
The column name(s) to order the table by
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm.
Returns
-------
index_array : ndarray, int
Array of indices that sorts the table by the specified key
column(s).
"""
if isinstance(keys, six.string_types):
keys = [keys]
# use index sorted order if possible
if keys is not None:
index = get_index(self, self[keys])
if index is not None:
return index.sorted_data()
kwargs = {}
if keys:
kwargs['order'] = keys
if kind:
kwargs['kind'] = kind
if keys:
data = self[keys].as_array()
else:
data = self.as_array()
return data.argsort(**kwargs)
def sort(self, keys=None):
'''
Sort the table according to one or more keys. This operates
on the existing table and does not return a new table.
Parameters
----------
keys : str or list of str
The key(s) to order the table by. If None, use the
primary index of the Table.
Examples
--------
Create a table with 3 columns::
>>> t = Table([['Max', 'Jo', 'John'], ['Miller','Miller','Jackson'],
... [12,15,18]], names=('firstname','name','tel'))
>>> print(t)
firstname name tel
--------- ------- ---
Max Miller 12
Jo Miller 15
John Jackson 18
Sorting according to standard sorting rules, first 'name' then 'firstname'::
>>> t.sort(['name','firstname'])
>>> print(t)
firstname name tel
--------- ------- ---
John Jackson 18
Jo Miller 15
Max Miller 12
'''
if keys is None:
if not self.indices:
raise ValueError("Table sort requires input keys or a table index")
keys = [x.info.name for x in self.indices[0].columns]
if isinstance(keys, six.string_types):
keys = [keys]
indexes = self.argsort(keys)
sort_index = get_index(self, self[keys])
if sort_index is not None:
# avoid inefficient relabelling of sorted index
prev_frozen = sort_index._frozen
sort_index._frozen = True
for col in self.columns.values():
col[:] = col.take(indexes, axis=0)
if sort_index is not None:
# undo index freeze
sort_index._frozen = prev_frozen
# now relabel the sort index appropriately
sort_index.sort()
def reverse(self):
'''
Reverse the row order of table rows. The table is reversed
in place and there are no function arguments.
Examples
--------
Create a table with three columns::
>>> t = Table([['Max', 'Jo', 'John'], ['Miller','Miller','Jackson'],
... [12,15,18]], names=('firstname','name','tel'))
>>> print(t)
firstname name tel
--------- ------- ---
Max Miller 12
Jo Miller 15
John Jackson 18
Reversing order::
>>> t.reverse()
>>> print(t)
firstname name tel
--------- ------- ---
John Jackson 18
Jo Miller 15
Max Miller 12
'''
for col in self.columns.values():
col[:] = col[::-1]
for index in self.indices:
index.reverse()
@classmethod
def read(cls, *args, **kwargs):
"""
Read and parse a data table and return as a Table.
This function provides the Table interface to the astropy unified I/O
layer. This allows easily reading a file in many supported data formats
using syntax such as::
>>> from astropy.table import Table
>>> dat = Table.read('table.dat', format='ascii')
>>> events = Table.read('events.fits', format='fits')
The arguments and keywords (other than ``format``) provided to this function are
passed through to the underlying data reader (e.g. `~astropy.io.ascii.read`).
"""
return io_registry.read(cls, *args, **kwargs)
def write(self, *args, **kwargs):
"""
Write this Table object out in the specified format.
This function provides the Table interface to the astropy unified I/O
layer. This allows easily writing a file in many supported data formats
using syntax such as::
>>> from astropy.table import Table
>>> dat = Table([[1, 2], [3, 4]], names=('a', 'b'))
>>> dat.write('table.dat', format='ascii')
The arguments and keywords (other than ``format``) provided to this function are
passed through to the underlying data reader (e.g. `~astropy.io.ascii.write`).
"""
io_registry.write(self, *args, **kwargs)
def copy(self, copy_data=True):
'''
Return a copy of the table.
Parameters
----------
copy_data : bool
If `True` (the default), copy the underlying data array.
Otherwise, use the same data array
.. note::
The ``meta`` is always deepcopied regardless of the value for
``copy_data``.
'''
out = self.__class__(self, copy=copy_data)
# If the current table is grouped then do the same in the copy
if hasattr(self, '_groups'):
out._groups = groups.TableGroups(out, indices=self._groups._indices,
keys=self._groups._keys)
return out
def __deepcopy__(self, memo=None):
return self.copy(True)
def __copy__(self):
return self.copy(False)
def __lt__(self, other):
if six.PY2:
raise TypeError("unorderable types: Table() < {0}".
format(str(type(other))))
else:
return super(Table, self).__lt__(other)
def __gt__(self, other):
if six.PY2:
raise TypeError("unorderable types: Table() > {0}".
format(str(type(other))))
else:
return super(Table, self).__gt__(other)
def __le__(self, other):
if six.PY2:
raise TypeError("unorderable types: Table() <= {0}".
format(str(type(other))))
else:
return super(Table, self).__le__(other)
def __ge__(self, other):
if six.PY2:
raise TypeError("unorderable types: Table() >= {0}".
format(str(type(other))))
else:
return super(Table, self).__ge__(other)
def __eq__(self, other):
if isinstance(other, Table):
other = other.as_array()
if self.masked:
if isinstance(other, np.ma.MaskedArray):
result = self.as_array() == other
else:
# If mask is True, then by definition the row doesn't match
# because the other array is not masked.
false_mask = np.zeros(1, dtype=[(n, bool) for n in self.dtype.names])
result = (self.as_array().data == other) & (self.mask == false_mask)
else:
if isinstance(other, np.ma.MaskedArray):
# If mask is True, then by definition the row doesn't match
# because the other array is not masked.
false_mask = np.zeros(1, dtype=[(n, bool) for n in other.dtype.names])
result = (self.as_array() == other.data) & (other.mask == false_mask)
else:
result = self.as_array() == other
return result
def __ne__(self, other):
return ~self.__eq__(other)
@property
def groups(self):
if not hasattr(self, '_groups'):
self._groups = groups.TableGroups(self)
return self._groups
def group_by(self, keys):
"""
Group this table by the specified ``keys``
This effectively splits the table into groups which correspond to
unique values of the ``keys`` grouping object. The output is a new
`TableGroups` which contains a copy of this table but sorted by row
according to ``keys``.
The ``keys`` input to `group_by` can be specified in different ways:
- String or list of strings corresponding to table column name(s)
- Numpy array (homogeneous or structured) with same length as this table
- `Table` with same length as this table
Parameters
----------
keys : str, list of str, numpy array, or `Table`
Key grouping object
Returns
-------
out : `Table`
New table with groups set
"""
if self.has_mixin_columns:
raise NotImplementedError('group_by not available for tables with mixin columns')
return groups.table_group_by(self, keys)
def to_pandas(self):
"""
Return a :class:`pandas.DataFrame` instance
Returns
-------
dataframe : :class:`pandas.DataFrame`
A pandas :class:`pandas.DataFrame` instance
Raises
------
ImportError
If pandas is not installed
ValueError
If the Table contains mixin or multi-dimensional columns
"""
from pandas import DataFrame
if self.has_mixin_columns:
raise ValueError("Cannot convert a table with mixin columns to a pandas DataFrame")
if any(getattr(col, 'ndim', 1) > 1 for col in self.columns.values()):
raise ValueError("Cannot convert a table with multi-dimensional columns to a pandas DataFrame")
out = OrderedDict()
for name, column in self.columns.items():
if isinstance(column, MaskedColumn):
if column.dtype.kind in ['i', 'u']:
out[name] = column.astype(float).filled(np.nan)
elif column.dtype.kind in ['f', 'c']:
out[name] = column.filled(np.nan)
else:
out[name] = column.astype(np.object).filled(np.nan)
else:
out[name] = column
if out[name].dtype.byteorder not in ('=', '|'):
out[name] = out[name].byteswap().newbyteorder()
return DataFrame(out)
@classmethod
def from_pandas(cls, dataframe):
"""
Create a `Table` from a :class:`pandas.DataFrame` instance
Parameters
----------
dataframe : :class:`pandas.DataFrame`
The pandas :class:`pandas.DataFrame` instance
Returns
-------
table : `Table`
A `Table` (or subclass) instance
"""
out = OrderedDict()
for name in dataframe.columns:
column = dataframe[name]
mask = np.array(column.isnull())
data = np.array(column)
if data.dtype.kind == 'O':
# If all elements of an object array are string-like or np.nan
# then coerce back to a native numpy str/unicode array.
string_types = six.string_types
if not six.PY2:
string_types += (bytes,)
nan = np.nan
if all(isinstance(x, string_types) or x is nan for x in data):
# Force any missing (null) values to b''. Numpy will
# upcast to str/unicode as needed.
data[mask] = b''
# When the numpy object array is represented as a list then
# numpy initializes to the correct string or unicode type.
data = np.array([x for x in data])
if np.any(mask):
out[name] = MaskedColumn(data=data, name=name, mask=mask)
else:
out[name] = Column(data=data, name=name)
return cls(out)
info = TableInfo()
class QTable(Table):
"""A class to represent tables of heterogeneous data.
`QTable` provides a class for heterogeneous tabular data which can be
easily modified, for instance adding columns or new rows.
The `QTable` class is identical to `Table` except that columns with an
associated ``unit`` attribute are converted to `~astropy.units.Quantity`
objects.
Parameters
----------
data : numpy ndarray, dict, list, Table, or table-like object, optional
Data to initialize table.
masked : bool, optional
Specify whether the table is masked.
names : list, optional
Specify column names
dtype : list, optional
Specify column data types
meta : dict, optional
Metadata associated with the table.
copy : bool, optional
Copy the input data (default=True).
rows : numpy ndarray, list of lists, optional
Row-oriented data for table instead of ``data`` argument
copy_indices : bool, optional
Copy any indices in the input data (default=True)
**kwargs : dict, optional
Additional keyword args when converting table-like object
"""
def _add_as_mixin_column(self, col):
"""
Determine if ``col`` should be added to the table directly as
a mixin column.
"""
return has_info_class(col, MixinInfo)
def _convert_col_for_table(self, col):
if (isinstance(col, Column) and getattr(col, 'unit', None) is not None):
# We need to turn the column into a quantity, or a subclass
# identified in the unit (such as u.mag()).
q_cls = getattr(col.unit, '_quantity_class', Quantity)
qcol = q_cls(col.data, col.unit, copy=False)
qcol.info = col.info
col = qcol
else:
col = super(QTable, self)._convert_col_for_table(col)
return col
class NdarrayMixin(np.ndarray):
"""
Mixin column class to allow storage of arbitrary numpy
ndarrays within a Table. This is a subclass of numpy.ndarray
and has the same initialization options as ndarray().
"""
info = ParentDtypeInfo()
def __new__(cls, obj, *args, **kwargs):
self = np.array(obj, *args, **kwargs).view(cls)
if 'info' in getattr(obj, '__dict__', ()):
self.info = obj.info
return self
def __array_finalize__(self, obj):
if obj is None:
return
if six.callable(super(NdarrayMixin, self).__array_finalize__):
super(NdarrayMixin, self).__array_finalize__(obj)
# Self was created from template (e.g. obj[slice] or (obj * 2))
# or viewcast e.g. obj.view(Column). In either case we want to
# init Column attributes for self from obj if possible.
if 'info' in getattr(obj, '__dict__', ()):
self.info = obj.info
def __reduce__(self):
# patch to pickle Quantity objects (ndarray subclasses), see
# http://www.mail-archive.com/numpy-discussion@scipy.org/msg02446.html
object_state = list(super(NdarrayMixin, self).__reduce__())
object_state[2] = (object_state[2], self.__dict__)
return tuple(object_state)
def __setstate__(self, state):
# patch to unpickle NdarrayMixin objects (ndarray subclasses), see
# http://www.mail-archive.com/numpy-discussion@scipy.org/msg02446.html
nd_state, own_state = state
super(NdarrayMixin, self).__setstate__(nd_state)
self.__dict__.update(own_state)
|
unknown
|
codeparrot/codeparrot-clean
| ||
import os
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=100)
class Triple(models.Model):
left = models.IntegerField()
middle = models.IntegerField()
right = models.IntegerField()
class Meta:
unique_together = (('left', 'middle'), (u'middle', u'right'))
class FilePathModel(models.Model):
path = models.FilePathField(path=os.path.dirname(__file__), match=".*\.py$", blank=True)
class Publication(models.Model):
title = models.CharField(max_length=30)
date_published = models.DateField()
def __unicode__(self):
return self.title
class Article(models.Model):
headline = models.CharField(max_length=100)
publications = models.ManyToManyField(Publication)
def __unicode__(self):
return self.headline
class CustomFileField(models.FileField):
def save_form_data(self, instance, data):
been_here = getattr(self, 'been_saved', False)
assert not been_here, "save_form_data called more than once"
setattr(self, 'been_saved', True)
class CustomFF(models.Model):
f = CustomFileField(upload_to='unused', blank=True)
|
unknown
|
codeparrot/codeparrot-clean
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.