repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
pdebuyl/lammps
src/KOKKOS/npair_copy_kokkos.cpp
1865
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include "npair_copy_kokkos.h" #include "neigh_list_kokkos.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ template<class DeviceType> NPairCopyKokkos<DeviceType>::NPairCopyKokkos(LAMMPS *lmp) : NPair(lmp) {} /* ---------------------------------------------------------------------- create list which is simply a copy of parent list ------------------------------------------------------------------------- */ template<class DeviceType> void NPairCopyKokkos<DeviceType>::build(NeighList *list) { NeighList *listcopy = list->listcopy; list->inum = listcopy->inum; list->gnum = listcopy->gnum; list->ilist = listcopy->ilist; list->numneigh = listcopy->numneigh; list->ipage = listcopy->ipage; NeighListKokkos<DeviceType>* list_kk = (NeighListKokkos<DeviceType>*) list; NeighListKokkos<DeviceType>* listcopy_kk = (NeighListKokkos<DeviceType>*) list->listcopy; list_kk->d_ilist = listcopy_kk->d_ilist; list_kk->d_numneigh = listcopy_kk->d_numneigh; list_kk->d_neighbors = listcopy_kk->d_neighbors; } namespace LAMMPS_NS { template class NPairCopyKokkos<LMPDeviceType>; #ifdef KOKKOS_ENABLE_CUDA template class NPairCopyKokkos<LMPHostType>; #endif }
gpl-2.0
phh/openswimdata
wp-content/plugins/wordpress-backup-to-dropbox/Classes/DatabaseBackup.php
8292
<?php /** * A class with functions the perform a backup of the WordPress database * * @copyright Copyright (C) 2011-2013 Michael De Wildt. All rights reserved. * @author Michael De Wildt (http://www.mikeyd.com.au/) * @license 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., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA. */ class WPB2D_DatabaseBackup { const SELECT_QUERY_LIMIT = 10; const WAIT_TIMEOUT = 600; //10 minutes const NOT_STARTED = 0; const COMPLETE = 1; const IN_PROGRESS = 2; private $temp, $database, $config ; public function __construct($processed = null) { $this->database = WPB2D_Factory::db(); $this->config = WPB2D_Factory::get('config'); $this->processed = $processed ? $processed : new WPB2D_Processed_DBTables(); $this->set_wait_timeout(); } public function get_status() { if ($this->processed->count_complete() == 0) { return self::NOT_STARTED; } $count = $this->database->get_var( $this->database->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = %s", DB_NAME) ); if ($this->processed->count_complete() < $count) { return self::IN_PROGRESS; } return self::COMPLETE; } public function execute() { if (!$this->processed->is_complete('header')) { $this->write_db_dump_header(); } $tables = $this->database->get_results('SHOW TABLES', ARRAY_N); foreach ($tables as $t) { $table = $t[0]; if (!$this->processed->is_complete($table)) { $count = $this->processed->get_table($table)->count * self::SELECT_QUERY_LIMIT; if ($count > 0) { WPB2D_Factory::get('logger')->log(sprintf(__("Resuming table '%s' at row %s.", 'wpbtd'), $table, $count)); } $this->backup_database_table($table, $count); WPB2D_Factory::get('logger')->log(sprintf(__("Processed table '%s'.", 'wpbtd'), $table)); } } } public function clean_up() { if (file_exists($this->get_file())) { unlink($this->get_file()); } } public function get_file() { $file = rtrim($this->config->get_backup_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . DB_NAME . "-backup.sql"; $files = glob($file . '*'); if (isset($files[0])) { return $files[0]; } return $file . '.' . WPB2D_Factory::secret(DB_NAME); } private function set_wait_timeout() { $this->database->query("SET SESSION wait_timeout=" . self::WAIT_TIMEOUT); } private function write_db_dump_header() { $dump_location = $this->config->get_backup_dir(); if (!is_writable($dump_location)) { $msg = sprintf(__("A database backup cannot be created because WordPress does not have write access to '%s', please ensure this directory has write access.", 'wpbtd'), $dump_location); WPB2D_Factory::get('logger')->log($msg); return false; } $blog_time = strtotime(current_time('mysql')); $this->write_to_temp("-- WordPress Backup to Dropbox SQL Dump\n"); $this->write_to_temp("-- Version " . BACKUP_TO_DROPBOX_VERSION . "\n"); $this->write_to_temp("-- http://wpb2d.com\n"); $this->write_to_temp("-- Generation Time: " . date("F j, Y", $blog_time) . " at " . date("H:i", $blog_time) . "\n\n"); $this->write_to_temp('SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";' . "\n\n"); //I got this out of the phpMyAdmin database dump to make sure charset is correct $this->write_to_temp("/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n"); $this->write_to_temp("/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n"); $this->write_to_temp("/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\n"); $this->write_to_temp("/*!40101 SET NAMES utf8 */;\n\n"); $this->write_to_temp("--\n-- Create and use the backed up database\n--\n\n"); $this->write_to_temp("CREATE DATABASE IF NOT EXISTS " . DB_NAME . ";\n"); $this->write_to_temp("USE " . DB_NAME . ";\n\n"); $this->persist(); $this->processed->update_table('header', -1); } private function backup_database_table($table, $offset) { $db_error = __('Error while accessing database.', 'wpbtd'); if ($offset == 0) { $this->write_to_temp("--\n-- Table structure for table `$table`\n--\n\n"); $table_create = $this->database->get_row("SHOW CREATE TABLE $table", ARRAY_N); if ($table_create === false) { throw new Exception($db_error . ' (ERROR_3)'); } $this->write_to_temp($table_create[1] . ";\n\n"); } $row_count = 0; $table_count = $this->database->get_var("SELECT COUNT(*) FROM $table"); if ($table_count == 0) { $this->write_to_temp("--\n-- Table `$table` is empty\n--\n\n"); $this->persist(); } else { if ($offset == 0) { $this->write_to_temp("--\n-- Dumping data for table `$table`\n--\n\n"); $this->persist(); } for ($i = $offset; $i < $table_count; $i = $i + self::SELECT_QUERY_LIMIT) { $table_data = $this->database->get_results("SELECT * FROM $table LIMIT " . self::SELECT_QUERY_LIMIT . " OFFSET $i", ARRAY_A); if ($table_data === false) { throw new Exception($db_error . ' (ERROR_4)'); } $fields = '`' . implode('`, `', array_keys($table_data[0])) . '`'; $this->write_to_temp("INSERT INTO `$table` ($fields) VALUES\n"); $out = ''; foreach ($table_data as $data) { $data_out = '('; foreach ($data as $value) { $value = addslashes($value); $value = str_replace("\n", "\\n", $value); $value = str_replace("\r", "\\r", $value); $data_out .= "'$value', "; } $out .= rtrim($data_out, ' ,') . "),\n"; $row_count++; } $this->write_to_temp(rtrim($out, ",\n") . ";\n\n"); if ($row_count >= $table_count) { $this->processed->update_table($table, -1); //Done } else { $this->processed->update_table($table, $row_count); } $this->persist(); } } } private function write_to_temp($out) { if (!$this->temp) { $this->temp = fopen('php://memory', 'rw'); } if (fwrite($this->temp, $out) === false) { throw new Exception(__('Error writing to php://memory.', 'wpbtd')); } } private function persist() { $fh = fopen($this->get_file(), 'a'); fseek($this->temp, 0); fwrite($fh, stream_get_contents($this->temp)); if (!fclose($fh)) { throw new Exception(__('Error closing sql dump file.', 'wpbtd')); } if (!fclose($this->temp)) { throw new Exception(__('Error closing php://memory.', 'wpbtd')); } $this->temp = null; } }
gpl-2.0
davex25/mednafen
src/cdrom/CDAccess_CCD.cpp
10594
/* Mednafen - Multi-system Emulator * * 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 02111-1307 USA */ #include "../mednafen.h" #include "../general.h" #include "../string/trim.h" #include "CDAccess_CCD.h" #include <trio/trio.h> #include <limits> #include <limits.h> #include <map> using namespace CDUtility; static void MDFN_strtoupper(std::string &str) { const size_t len = str.length(); for(size_t x = 0; x < len; x++) { if(str[x] >= 'a' && str[x] <= 'z') { str[x] = str[x] - 'a' + 'A'; } } } typedef std::map<std::string, std::string> CCD_Section; template<typename T> static T CCD_ReadInt(CCD_Section &s, const std::string &propname, const bool have_defval = false, const int defval = 0) { CCD_Section::iterator zit = s.find(propname); if(zit == s.end()) { if(have_defval) return defval; else throw MDFN_Error(0, _("Missing property: %s"), propname.c_str()); } const std::string &v = zit->second; int scan_base = 10; size_t scan_offset = 0; long ret = 0; if(v.length() >= 3 && v[0] == '0' && v[1] == 'x') { scan_base = 16; scan_offset = 2; } const char *vp = v.c_str() + scan_offset; char *ep = NULL; if(std::numeric_limits<T>::is_signed) ret = strtol(vp, &ep, scan_base); else ret = strtoul(vp, &ep, scan_base); if(!vp[0] || ep[0]) { throw MDFN_Error(0, _("Property %s: Malformed integer: %s"), propname.c_str(), v.c_str()); } //if(ret < minv || ret > maxv) //{ // throw MDFN_Error(0, _("Property %s: Integer %ld out of range(accepted: %d through %d)."), propname.c_str(), ret, minv, maxv); //} return ret; } CDAccess_CCD::CDAccess_CCD(const char *path, bool image_memcache) : img_stream(NULL), sub_stream(NULL), img_numsectors(0) { try { Load(path, image_memcache); } catch(...) { Cleanup(); throw; } } void CDAccess_CCD::Load(const char *path, bool image_memcache) { FileStream cf(path, FileStream::MODE_READ); std::map<std::string, CCD_Section> Sections; std::string linebuf; std::string cur_section_name; std::string dir_path, file_base, file_ext; char img_extsd[4] = { 'i', 'm', 'g', 0 }; char sub_extsd[4] = { 's', 'u', 'b', 0 }; MDFN_GetFilePathComponents(path, &dir_path, &file_base, &file_ext); if(file_ext.length() == 4 && file_ext[0] == '.') { signed char extupt[3] = { -1, -1, -1 }; for(int i = 1; i < 4; i++) { if(file_ext[i] >= 'A' && file_ext[i] <= 'Z') extupt[i - 1] = 'A' - 'a'; else if(file_ext[i] >= 'a' && file_ext[i] <= 'z') extupt[i - 1] = 0; } signed char av = -1; for(int i = 0; i < 3; i++) { if(extupt[i] != -1) av = extupt[i]; else extupt[i] = av; } if(av == -1) av = 0; for(int i = 0; i < 3; i++) { if(extupt[i] == -1) extupt[i] = av; } for(int i = 0; i < 3; i++) { img_extsd[i] += extupt[i]; sub_extsd[i] += extupt[i]; } } //printf("%s %d %d %d\n", file_ext.c_str(), extupt[0], extupt[1], extupt[2]); linebuf.reserve(256); while(cf.get_line(linebuf) >= 0) { MDFN_trim(linebuf); if(linebuf.length() == 0) // Skip blank lines. continue; if(linebuf[0] == '[') { if(linebuf.length() < 3 || linebuf[linebuf.length() - 1] != ']') throw MDFN_Error(0, _("Malformed section specifier: %s"), linebuf.c_str()); cur_section_name = linebuf.substr(1, linebuf.length() - 2); MDFN_strtoupper(cur_section_name); } else { const size_t feqpos = linebuf.find('='); const size_t leqpos = linebuf.rfind('='); std::string k, v; if(feqpos == std::string::npos || feqpos != leqpos) throw MDFN_Error(0, _("Malformed value pair specifier: %s"), linebuf.c_str()); k = linebuf.substr(0, feqpos); v = linebuf.substr(feqpos + 1); MDFN_trim(k); MDFN_trim(v); MDFN_strtoupper(k); Sections[cur_section_name][k] = v; } } { CCD_Section& ds = Sections["DISC"]; unsigned toc_entries = CCD_ReadInt<unsigned>(ds, "TOCENTRIES"); unsigned num_sessions = CCD_ReadInt<unsigned>(ds, "SESSIONS"); bool data_tracks_scrambled = CCD_ReadInt<unsigned>(ds, "DATATRACKSSCRAMBLED"); if(num_sessions != 1) throw MDFN_Error(0, _("Unsupported number of sessions: %u"), num_sessions); if(data_tracks_scrambled) throw MDFN_Error(0, _("Scrambled CCD data tracks currently not supported.")); //printf("MOO: %d\n", toc_entries); for(unsigned te = 0; te < toc_entries; te++) { char tmpbuf[64]; trio_snprintf(tmpbuf, sizeof(tmpbuf), "ENTRY %u", te); CCD_Section& ts = Sections[std::string(tmpbuf)]; unsigned session = CCD_ReadInt<unsigned>(ts, "SESSION"); uint8 point = CCD_ReadInt<uint8>(ts, "POINT"); uint8 adr = CCD_ReadInt<uint8>(ts, "ADR"); uint8 control = CCD_ReadInt<uint8>(ts, "CONTROL"); uint8 pmin = CCD_ReadInt<uint8>(ts, "PMIN"); uint8 psec = CCD_ReadInt<uint8>(ts, "PSEC"); uint8 pframe = CCD_ReadInt<uint8>(ts, "PFRAME"); signed plba = CCD_ReadInt<signed>(ts, "PLBA"); if(session != 1) throw MDFN_Error(0, "Unsupported TOC entry Session value: %u", session); // Reference: ECMA-394, page 5-14 switch(point) { default: throw MDFN_Error(0, "Unsupported TOC entry Point value: %u", point); break; case 0xA0: tocd.first_track = pmin; tocd.disc_type = psec; break; case 0xA1: tocd.last_track = pmin; break; case 0xA2: tocd.tracks[100].adr = adr; tocd.tracks[100].control = control; tocd.tracks[100].lba = plba; break; case 1 ... 99: tocd.tracks[point].adr = adr; tocd.tracks[point].control = control; tocd.tracks[point].lba = plba; break; } } } // Convenience leadout track duplication. if(tocd.last_track < 99) tocd.tracks[tocd.last_track + 1] = tocd.tracks[100]; // // Open image stream. { std::string image_path = MDFN_EvalFIP(dir_path, file_base + std::string(".") + std::string(img_extsd), true); if(image_memcache) { img_stream = new MemoryStream(new FileStream(image_path.c_str(), FileStream::MODE_READ)); } else { img_stream = new FileStream(image_path.c_str(), FileStream::MODE_READ); } int64 ss = img_stream->size(); if(ss % 2352) throw MDFN_Error(0, _("CCD image size is not evenly divisible by 2352.")); img_numsectors = ss / 2352; } // // Open subchannel stream { std::string sub_path = MDFN_EvalFIP(dir_path, file_base + std::string(".") + std::string(sub_extsd), true); if(image_memcache) sub_stream = new MemoryStream(new FileStream(sub_path.c_str(), FileStream::MODE_READ)); else sub_stream = new FileStream(sub_path.c_str(), FileStream::MODE_READ); if(sub_stream->size() != (int64)img_numsectors * 96) throw MDFN_Error(0, _("CCD SUB file size mismatch.")); } CheckSubQSanity(); } // // Checks for Q subchannel mode 1(current time) data that has a correct checksum, but the data is nonsensical or corrupted nonetheless; this is the // case for some bad rips floating around on the Internet. Allowing these bad rips to be used will cause all sorts of problems during emulation, so we // error out here if a bad rip is detected. // // This check is not as aggressive or exhaustive as it could be, and will not detect all potential Q subchannel rip errors; as such, it should definitely NOT be // used in an effort to "repair" a broken rip. // void CDAccess_CCD::CheckSubQSanity(void) { size_t checksum_pass_counter = 0; int prev_lba = INT_MAX; uint8 prev_track = 0; for(size_t s = 0; s < img_numsectors; s++) { union { uint8 full[96]; struct { uint8 pbuf[12]; uint8 qbuf[12]; }; } buf; sub_stream->seek(s * 96, SEEK_SET); sub_stream->read(buf.full, 96); if(subq_check_checksum(buf.qbuf)) { uint8 adr = buf.qbuf[0] & 0xF; if(adr == 0x01) { uint8 track_bcd = buf.qbuf[1]; uint8 index_bcd = buf.qbuf[2]; uint8 rm_bcd = buf.qbuf[3]; uint8 rs_bcd = buf.qbuf[4]; uint8 rf_bcd = buf.qbuf[5]; uint8 am_bcd = buf.qbuf[7]; uint8 as_bcd = buf.qbuf[8]; uint8 af_bcd = buf.qbuf[9]; //printf("%2x %2x %2x\n", am_bcd, as_bcd, af_bcd); if(!BCD_is_valid(track_bcd) || !BCD_is_valid(index_bcd) || !BCD_is_valid(rm_bcd) || !BCD_is_valid(rs_bcd) || !BCD_is_valid(rf_bcd) || !BCD_is_valid(am_bcd) || !BCD_is_valid(as_bcd) || !BCD_is_valid(af_bcd) || rs_bcd > 0x59 || rf_bcd > 0x74 || as_bcd > 0x59 || af_bcd > 0x74) { throw MDFN_Error(0, _("Garbage subchannel Q data detected(bad BCD/out of range): %02x:%02x:%02x %02x:%02x:%02x"), rm_bcd, rs_bcd, rf_bcd, am_bcd, as_bcd, af_bcd); } else { int lba = ((BCD_to_U8(am_bcd) * 60 + BCD_to_U8(as_bcd)) * 75 + BCD_to_U8(af_bcd)) - 150; uint8 track = BCD_to_U8(track_bcd); if(prev_lba != INT_MAX && abs(lba - prev_lba) > 100) throw MDFN_Error(0, _("Garbage subchannel Q data detected(excessively large jump in AMSF)")); if(abs(lba - s) > 100) throw MDFN_Error(0, _("Garbage subchannel Q data detected(AMSF value is out of tolerance)")); prev_lba = lba; if(track < prev_track) throw MDFN_Error(0, _("Garbage subchannel Q data detected(bad track number)")); //else if(prev_track && track - pre prev_track = track; } checksum_pass_counter++; } } } //printf("%u/%u\n", checksum_pass_counter, img_numsectors); } void CDAccess_CCD::Cleanup(void) { if(img_stream) { delete img_stream; img_stream = NULL; } if(sub_stream) { delete sub_stream; sub_stream = NULL; } } CDAccess_CCD::~CDAccess_CCD() { Cleanup(); } void CDAccess_CCD::Read_Raw_Sector(uint8 *buf, int32 lba) { if(lba < 0 || (size_t)lba >= img_numsectors) throw(MDFN_Error(0, _("LBA out of range."))); uint8 sub_buf[96]; img_stream->seek(lba * 2352, SEEK_SET); img_stream->read(buf, 2352); sub_stream->seek(lba * 96, SEEK_SET); sub_stream->read(sub_buf, 96); subpw_interleave(sub_buf, buf + 2352); } void CDAccess_CCD::Read_TOC(CDUtility::TOC *toc) { *toc = tocd; } bool CDAccess_CCD::Is_Physical(void) throw() { return false; } void CDAccess_CCD::Eject(bool eject_status) { }
gpl-2.0
emilienGallet/DrupalUnicef
vendor/drupal/console/src/Command/Database/DumpCommand.php
2851
<?php /** * @file * Contains \Drupal\Console\Command\Database\DumpCommand. */ namespace Drupal\Console\Command\Database; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Process\ProcessBuilder; use Drupal\Console\Command\ContainerAwareCommand; use Drupal\Console\Command\Database\ConnectTrait; use Drupal\Console\Style\DrupalStyle; class DumpCommand extends ContainerAwareCommand { use ConnectTrait; /** * {@inheritdoc} */ protected function configure() { $this ->setName('database:dump') ->setDescription($this->trans('commands.database.dump.description')) ->addArgument( 'database', InputArgument::OPTIONAL, $this->trans('commands.database.dump.arguments.database'), 'default' ) ->addOption( 'file', null, InputOption::VALUE_OPTIONAL, $this->trans('commands.database.dump.option.file') ) ->setHelp($this->trans('commands.database.dump.help')); } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new DrupalStyle($input, $output); $database = $input->getArgument('database'); $file = $input->getOption('file'); $learning = $input->getOption('learning'); $databaseConnection = $this->resolveConnection($io, $database); if (!$file) { $file = sprintf( '%s/%s.sql', $this->getSite()->getSiteRoot(), $databaseConnection['database'] ); } $command = sprintf( 'mysqldump --user=%s --password=%s --host=%s --port=%s %s > %s', $databaseConnection['username'], $databaseConnection['password'], $databaseConnection['host'], $databaseConnection['port'], $databaseConnection['database'], $file ); if ($learning) { $io->commentBlock($command); } $processBuilder = new ProcessBuilder(['–lock-all-tables']); $process = $processBuilder->getProcess(); $process->setTty('true'); $process->setCommandLine($command); $process->run(); if (!$process->isSuccessful()) { throw new \RuntimeException($process->getErrorOutput()); } $io->success( sprintf( '%s %s', $this->trans('commands.database.dump.messages.success'), $file ) ); } }
gpl-2.0
andysim/psi4
psi4/src/psi4/psimrcc/matrix_memory_and_io.cc
10565
/* * @BEGIN LICENSE * * Psi4: an open-source quantum chemistry software package * * Copyright (c) 2007-2017 The Psi4 Developers. * * The copyrights for code used from other parties are included in * the corresponding files. * * 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., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * @END LICENSE */ /*************************************************************************** * Copyright (C) 2007 by Francesco Evangelista and Andrew Simmonett * frank@ccc.uga.edu * SR/MRCC Code ***************************************************************************/ #include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include "psi4/psifiles.h" #include "psi4/pragma.h" PRAGMA_WARNING_PUSH PRAGMA_WARNING_IGNORE_DEPRECATED_DECLARATIONS #include <memory> PRAGMA_WARNING_POP #include "psi4/libmoinfo/libmoinfo.h" #include "psi4/libpsi4util/libpsi4util.h" #include "psi4/libpsio/psio.hpp" #include "debugging.h" #include "matrix.h" namespace psi{ namespace psimrcc{ extern MOInfo *moinfo; extern MemoryManager *memory_manager; using namespace std; /********************************************************* Memory Allocation Routines *********************************************************/ /** * Return true if all the blocks are written to core * @return */ bool CCMatrix::is_out_of_core() { for(int h=0;h<moinfo->get_nirreps();++h) if(!out_of_core[h] && (block_sizepi[h]>0)) return(false); return(true); } /** * Return true if all the blocks are allocated * @return */ bool CCMatrix::is_allocated() { for(int h=0;h<moinfo->get_nirreps();++h) if(!is_block_allocated(h) && (block_sizepi[h]>0)) return(false); return(true); } bool CCMatrix::is_block_allocated(int h) { if(matrix[h]==NULL) return(false); else return(true); } void CCMatrix::allocate_memory() { // Allocate a matrix if we are not checking for(int h=0;h<nirreps;h++) allocate_block(h); } void CCMatrix::allocate_block(int h) { if(block_sizepi[h]>0){ if(!is_block_allocated(h)){ if(memorypi2[h] < memory_manager->get_FreeMemory()){ allocate2(double,matrix[h],left_pairpi[h],right_pairpi[h]); DEBUGGING(2, outfile->Printf("\n %s[%s] <- allocated",label.c_str(),moinfo->get_irr_labs(h)); ) }else{ outfile->Printf("\n\nNot enough memory to allocate irrep %d of %s\n",h,label.c_str()); exit(1); } }else{ outfile->Printf("\n\nCCMatrix::allocate_block(): You are trying to allocate irrep %d of %s when is already allocated!!!\n",h,label.c_str()); exit(EXIT_FAILURE); } } } /** * Free the memory used to store the matrix elements */ void CCMatrix::free_memory() { for(int h=0;h<nirreps;h++) free_block(h); } void CCMatrix::free_block(int h) { if(block_sizepi[h]>0){ if(is_block_allocated(h)){ release2(matrix[h]); DEBUGGING(2, outfile->Printf("\n %s[%s] <- deallocated",label.c_str(),moinfo->get_irr_labs(h)); ) } } } /********************************************************* I/O Routines *********************************************************/ /** * Write the matrix to disk and free the memory. */ void CCMatrix::dump_to_disk() { dump_to_disk(0,moinfo->get_nirreps()); } /** * Write the matrix to disk and free the memory */ void CCMatrix::dump_to_disk(int first_irrep,int last_irrep) { for(int h=first_irrep;h<last_irrep;++h) dump_block_to_disk(h); } /** * Write a irrep block to disk and free the memory * @param h irrep to write to disk */ void CCMatrix::dump_block_to_disk(int h) { write_block_to_disk(h); free_block(h); out_of_core[h]=true; } /** * Write a irrep block to disk without freeing the memory * @param h irrep to write to disk */ void CCMatrix::write_block_to_disk(int h) { if(block_sizepi[h]>0){ // for generic matrices store the entire symmetry block on disk if(!is_integral()){ char data_label[80]; sprintf(data_label,"%s_%d",label.c_str(),h); _default_psio_lib_->write_entry(PSIF_PSIMRCC_INTEGRALS,data_label,(char*)&(matrix[h][0][0]),block_sizepi[h]*sizeof(double)); }else{ // outfile->Printf("\n CCMatrix::write_block_to_disk(): writing %s irrep %d to disk",label.c_str(),h); // outfile->Printf("\n This is a %d x %d block",left_pairpi[h],right_pairpi[h]); // for two electron integrals store strips of the symmetry block on disk size_t max_strip_size = static_cast<size_t>(fraction_of_memory_for_buffer * static_cast<double>(memory_manager->get_FreeMemory())); int strip = 0; size_t last_row = 0; // Determine the size of the strip and write the strip to disk while(last_row < left_pairpi[h]){ // Determine the size of the strip size_t first_row = last_row; size_t strip_size = 0.0; // Mb size_t strip_length = 0; while((strip_size < max_strip_size) && (last_row < left_pairpi[h]) ){ last_row++; strip_length = last_row - first_row; strip_size = sizeof(double) * strip_length * right_pairpi[h]; } // outfile->Printf("\n Writing strip %d of lenght %d (%d -> %d)",strip,strip_length,first_row,last_row); // Write the size of the strip char size_label[80]; sprintf(size_label ,"%s_%d_%d_size",label.c_str(),h,strip); _default_psio_lib_->write_entry(PSIF_PSIMRCC_INTEGRALS,size_label,(char*)&(strip_length),sizeof(size_t)); // Write the strip char data_label[80]; sprintf(data_label,"%s_%d_%d",label.c_str(),h,strip); _default_psio_lib_->write_entry(PSIF_PSIMRCC_INTEGRALS,data_label,(char*)&(matrix[h][first_row][0]), strip_length*right_pairpi[h]* sizeof(double)); strip++; } // outfile->Printf("\n Written %d strip%s",strip,strip>1 ? "" : "s"); // Write the number of strips char nstrips_label[80]; sprintf(nstrips_label ,"%s_%d_nstrips",label.c_str(),h); _default_psio_lib_->write_entry(PSIF_PSIMRCC_INTEGRALS,nstrips_label,(char*)&(strip),sizeof(int)); } } } /** * A black-box version of read_from_disk() that can be called for any matrix */ void CCMatrix::load() { if(is_out_of_core()){ if(!is_allocated()) read_from_disk(); }else if(!is_allocated()) allocate_memory(); } /** * A black-box version of read_from_disk() that can be called for any matrix * @param h irrep to read from disk */ void CCMatrix::load_irrep(int h) { if(out_of_core[h]){ if(!is_block_allocated(h)) read_block_from_disk(h); }else{ if(!is_block_allocated(h)) allocate_block(h); } } /** * Read a matrix from disk. */ void CCMatrix::read_from_disk() { read_from_disk(0,moinfo->get_nirreps()); } /** * Read irrep blocks from disk * @param h irrep to write to disk */ void CCMatrix::read_from_disk(int first_irrep,int last_irrep) { for(int h=first_irrep;h<last_irrep;++h) read_block_from_disk(h); } /** * Read an irrep block from disk * @param h irrep to write to disk */ void CCMatrix::read_block_from_disk(int h) { if(block_sizepi[h]>0){ if(!is_block_allocated(h)) allocate_block(h); // for generic matrices read the entire symmetry block on disk if(!is_integral()){ char data_label[80]; sprintf(data_label,"%s_%d",label.c_str(),h); _default_psio_lib_->read_entry(PSIF_PSIMRCC_INTEGRALS,data_label,(char*)&(matrix[h][0][0]),block_sizepi[h]*sizeof(double)); }else{ // Read the number of strips int nstrips = 0; char nstrips_label[80]; sprintf(nstrips_label ,"%s_%d_nstrips",label.c_str(),h); _default_psio_lib_->read_entry(PSIF_PSIMRCC_INTEGRALS,nstrips_label,(char*)&(nstrips),sizeof(int)); size_t first_row =0; for(int strip = 0;strip!=nstrips;++strip){ // Read the size of the strip size_t strip_length = 0; char size_label[80]; sprintf(size_label ,"%s_%d_%d_size",label.c_str(),h,strip); _default_psio_lib_->read_entry(PSIF_PSIMRCC_INTEGRALS,size_label,(char*)&(strip_length),sizeof(size_t)); // Read the strip char data_label[80]; sprintf(data_label,"%s_%d_%d",label.c_str(),h,strip); _default_psio_lib_->read_entry(PSIF_PSIMRCC_INTEGRALS,data_label,(char*)&(matrix[h][first_row][0]), strip_length*right_pairpi[h]*sizeof(double)); first_row += strip_length; } } } } /** * Read an irrep strip from disk and return a boolean that is true if there is strip * @param h irrep to write to disk */ size_t CCMatrix::read_strip_from_disk(int h, int strip, double* buffer) { size_t strip_length = 0; if(block_sizepi[h]>0){ // for generic matrices read the entire symmetry block on disk if(!is_integral()){ outfile->Printf("\nMatrix %s is not stored in strips!!!",label.c_str()); exit(EXIT_FAILURE); }else{ // Read the number of strips int nstrips = 0; char nstrips_label[80]; sprintf(nstrips_label ,"%s_%d_nstrips",label.c_str(),h); _default_psio_lib_->read_entry(PSIF_PSIMRCC_INTEGRALS,nstrips_label,(char*)&(nstrips),sizeof(int)); if(strip < nstrips){ // Read the size of the strip char size_label[80]; sprintf(size_label ,"%s_%d_%d_size",label.c_str(),h,strip); _default_psio_lib_->read_entry(PSIF_PSIMRCC_INTEGRALS,size_label,(char*)&(strip_length),sizeof(size_t)); // Read the strip char data_label[80]; sprintf(data_label,"%s_%d_%d",label.c_str(),h,strip); _default_psio_lib_->read_entry(PSIF_PSIMRCC_INTEGRALS,data_label,(char*)buffer, strip_length*right_pairpi[h]*sizeof(double)); } } } return(strip_length); } }} /* End Namespaces */
gpl-2.0
6226/wp
wp-content/themes/kleo/paid-memberships-pro/pages/billing.php
13678
<?php global $wpdb, $current_user, $pmpro_msg, $pmpro_msgt, $pmpro_currency_symbol, $show_paypal_link; global $bfirstname, $blastname, $baddress1, $baddress2, $bcity, $bstate, $bzipcode, $bcountry, $bphone, $bemail, $bconfirmemail, $CardType, $AccountNumber, $ExpirationMonth, $ExpirationYear; $gateway = pmpro_getOption("gateway"); //set to true via filter to have Stripe use the minimal billing fields $pmpro_stripe_lite = apply_filters("pmpro_stripe_lite", !pmpro_getOption("stripe_billingaddress")); //default is oposite of the stripe_billingaddress setting $level = $current_user->membership_level; if($level) { ?> <p><?php printf(__("Logged in as <strong>%s</strong>.", "pmpro"), $current_user->user_login);?> <small><a href="<?php echo wp_logout_url(get_bloginfo("url") . "/membership-checkout/?level=" . $level->id);?>"><?php _e("logout", "pmpro");?></a></small></p> <ul> <li><strong><?php _e("Level", "pmpro");?>:</strong> <?php echo $level->name?></li> <?php if($level->billing_amount > 0) { ?> <li><strong><?php _e("Membership Fee", "pmpro");?>:</strong> <?php echo $pmpro_currency_symbol?><?php echo $level->billing_amount?> <?php if($level->cycle_number > 1) { ?> per <?php echo $level->cycle_number?> <?php echo sornot($level->cycle_period,$level->cycle_number)?> <?php } elseif($level->cycle_number == 1) { ?> per <?php echo $level->cycle_period?> <?php } ?> </li> <?php } ?> <?php if($level->billing_limit) { ?> <li><strong><?php _e("Duration", "pmpro");?>:</strong> <?php echo $level->billing_limit.' '.sornot($level->cycle_period,$level->billing_limit)?></li> <?php } ?> </ul> <?php } ?> <?php if(pmpro_isLevelRecurring($level)) { ?> <?php if($show_paypal_link) { ?> <p><?php _e('Your payment subscription is managed by PayPal. Please <a href="http://www.paypal.com">login to PayPal here</a> to update your billing information.', 'pmpro');?></p> <?php } else { ?> <form class="pmpro_form" action="<?php echo pmpro_url("billing", "", "https")?>" method="post"> <input type="hidden" name="level" value="<?php echo esc_attr($level->id);?>" /> <?php if($pmpro_msg) { ?> <div class="pmpro_message <?php echo $pmpro_msgt?>"><?php echo $pmpro_msg?></div> <?php } ?> <?php if(empty($pmpro_stripe_lite) || $gateway != "stripe") { ?> <table id="pmpro_billing_address_fields" class="pmpro_checkout" width="100%" cellpadding="0" cellspacing="0" border="0"> <thead> <tr> <th><?php _e('Billing Address', 'pmpro');?></th> </tr> </thead> <tbody> <tr> <td> <div> <label for="bfirstname"><?php _e('First Name', 'pmpro');?></label> <input id="bfirstname" name="bfirstname" type="text" class="input" size="20" value="<?php echo esc_attr($bfirstname);?>" /> </div> <div> <label for="blastname"><?php _e('Last Name', 'pmpro');?></label> <input id="blastname" name="blastname" type="text" class="input" size="20" value="<?php echo esc_attr($blastname);?>" /> </div> <div> <label for="baddress1"><?php _e('Address 1', 'pmpro');?></label> <input id="baddress1" name="baddress1" type="text" class="input" size="20" value="<?php echo esc_attr($baddress1);?>" /> </div> <div> <label for="baddress2"><?php _e('Address 2', 'pmpro');?></label> <input id="baddress2" name="baddress2" type="text" class="input" size="20" value="<?php echo esc_attr($baddress2);?>" /> <small class="lite">(<?php _e('optional', 'pmpro');?>)</small> </div> <?php $longform_address = apply_filters("pmpro_longform_address", false); if($longform_address) { ?> <div> <label for="bcity"><?php _e('City', 'pmpro');?>City</label> <input id="bcity" name="bcity" type="text" class="input" size="30" value="<?php echo esc_attr($bcity)?>" /> </div> <div> <label for="bstate"><?php _e('State', 'pmpro');?>State</label> <input id="bstate" name="bstate" type="text" class="input" size="30" value="<?php echo esc_attr($bstate)?>" /> </div> <div> <label for="bzipcode"><?php _e('Postal Code', 'pmpro');?></label> <input id="bzipcode" name="bzipcode" type="text" class="input" size="30" value="<?php echo esc_attr($bzipcode)?>" /> </div> <?php } else { ?> <div> <label for="bcity_state_zip"><?php _e('City, State Zip', 'pmpro');?></label> <input id="bcity" name="bcity" type="text" class="input" size="14" value="<?php echo esc_attr($bcity)?>" />, <?php $state_dropdowns = apply_filters("pmpro_state_dropdowns", false); if($state_dropdowns === true || $state_dropdowns == "names") { global $pmpro_states; ?> <select name="bstate"> <option value="">--</option> <?php foreach($pmpro_states as $ab => $st) { ?> <option value="<?php echo esc_attr($ab);?>" <?php if($ab == $bstate) { ?>selected="selected"<?php } ?>><?php echo $st;?></option> <?php } ?> </select> <?php } elseif($state_dropdowns == "abbreviations") { global $pmpro_states_abbreviations; ?> <select name="bstate"> <option value="">--</option> <?php foreach($pmpro_states_abbreviations as $ab) { ?> <option value="<?php echo esc_attr($ab);?>" <?php if($ab == $bstate) { ?>selected="selected"<?php } ?>><?php echo $ab;?></option> <?php } ?> </select> <?php } else { ?> <input id="bstate" name="bstate" type="text" class="input" size="2" value="<?php echo esc_attr($bstate)?>" /> <?php } ?> <input id="bzipcode" name="bzipcode" type="text" class="input" size="5" value="<?php echo esc_attr($bzipcode)?>" /> </div> <?php } ?> <?php $show_country = apply_filters("pmpro_international_addresses", false); if($show_country) { ?> <div> <label for="bcountry"><?php _e('Country', 'pmpro');?></label> <select name="bcountry"> <?php global $pmpro_countries, $pmpro_default_country; foreach($pmpro_countries as $abbr => $country) { if(!$bcountry) $bcountry = $pmpro_default_country; ?> <option value="<?php echo $abbr?>" <?php if($abbr == $bcountry) { ?>selected="selected"<?php } ?>><?php echo $country?></option> <?php } ?> </select> </div> <?php } else { ?> <input type="hidden" id="bcountry" name="bcountry" value="US" /> <?php } ?> <div> <label for="bphone"><?php _e('Phone', 'pmpro');?></label> <input id="bphone" name="bphone" type="text" class="input" size="20" value="<?php echo esc_attr($bphone)?>" /> </div> <?php if($current_user->ID) { ?> <?php if(!$bemail && $current_user->user_email) $bemail = $current_user->user_email; if(!$bconfirmemail && $current_user->user_email) $bconfirmemail = $current_user->user_email; ?> <div> <label for="bemail"><?php _e('E-mail Address', 'pmpro');?></label> <input id="bemail" name="bemail" type="text" class="input" size="20" value="<?php echo esc_attr($bemail)?>" /> </div> <div> <label for="bconfirmemail"><?php _e('Confirm E-mail', 'pmpro');?></label> <input id="bconfirmemail" name="bconfirmemail" type="text" class="input" size="20" value="<?php echo esc_attr($bconfirmemail)?>" /> </div> <?php } ?> </td> </tr> </tbody> </table> <?php } ?> <?php $pmpro_accepted_credit_cards = pmpro_getOption("accepted_credit_cards"); $pmpro_accepted_credit_cards = explode(",", $pmpro_accepted_credit_cards); $pmpro_accepted_credit_cards_string = pmpro_implodeToEnglish($pmpro_accepted_credit_cards); ?> <table id="pmpro_payment_information_fields" class="pmpro_checkout top1em" width="100%" cellpadding="0" cellspacing="0" border="0"> <thead> <tr> <th colspan="2"><span class="pmpro_thead-msg"><?php printf(__('We accept %s', 'pmpro'), $pmpro_accepted_credit_cards_string);?></span><?php _e('Credit Card Information', 'pmpro');?></th> </tr> </thead> <tbody> <tr valign="top"> <td> <?php $sslseal = pmpro_getOption("sslseal"); if($sslseal) { ?> <div class="pmpro_sslseal"><?php echo stripslashes($sslseal)?></div> <?php } ?> <?php if(empty($pmpro_stripe_lite) || $gateway != "stripe") { ?> <div> <label for="CardType"><?php _e('Card Type', 'pmpro');?></label> <select id="CardType" <?php if($gateway != "stripe") { ?>name="CardType"<?php } ?>> <?php foreach($pmpro_accepted_credit_cards as $cc) { ?> <option value="<?php echo $cc?>" <?php if($CardType == $cc) { ?>selected="selected"<?php } ?>><?php echo $cc?></option> <?php } ?> </select> </div> <?php } ?> <div> <label for="AccountNumber"><?php _e('Card Number', 'pmpro');?></label> <input id="AccountNumber" <?php if($gateway != "stripe") { ?>name="AccountNumber"<?php } ?> class="input" type="text" size="25" value="<?php echo esc_attr($AccountNumber)?>" autocomplete="off" /> </div> <div> <label for="ExpirationMonth"><?php _e('Expiration Date', 'pmpro');?></label> <select id="ExpirationMonth" <?php if($gateway != "stripe") { ?>name="ExpirationMonth"<?php } ?>> <option value="01" <?php if($ExpirationMonth == "01") { ?>selected="selected"<?php } ?>>01</option> <option value="02" <?php if($ExpirationMonth == "02") { ?>selected="selected"<?php } ?>>02</option> <option value="03" <?php if($ExpirationMonth == "03") { ?>selected="selected"<?php } ?>>03</option> <option value="04" <?php if($ExpirationMonth == "04") { ?>selected="selected"<?php } ?>>04</option> <option value="05" <?php if($ExpirationMonth == "05") { ?>selected="selected"<?php } ?>>05</option> <option value="06" <?php if($ExpirationMonth == "06") { ?>selected="selected"<?php } ?>>06</option> <option value="07" <?php if($ExpirationMonth == "07") { ?>selected="selected"<?php } ?>>07</option> <option value="08" <?php if($ExpirationMonth == "08") { ?>selected="selected"<?php } ?>>08</option> <option value="09" <?php if($ExpirationMonth == "09") { ?>selected="selected"<?php } ?>>09</option> <option value="10" <?php if($ExpirationMonth == "10") { ?>selected="selected"<?php } ?>>10</option> <option value="11" <?php if($ExpirationMonth == "11") { ?>selected="selected"<?php } ?>>11</option> <option value="12" <?php if($ExpirationMonth == "12") { ?>selected="selected"<?php } ?>>12</option> </select>/<select id="ExpirationYear" <?php if($gateway != "stripe") { ?>name="ExpirationYear"<?php } ?>> <?php for($i = date("Y"); $i < date("Y") + 10; $i++) { ?> <option value="<?php echo $i?>" <?php if($ExpirationYear == $i) { ?>selected="selected"<?php } ?>><?php echo $i?></option> <?php } ?> </select> </div> <?php $pmpro_show_cvv = apply_filters("pmpro_show_cvv", true); if($pmpro_show_cvv) { ?> <div> <label for="CVV"><?php _ex('CVV', 'Credit card security code, CVV/CCV/CVV2', 'pmpro');?></label> <input class="input" id="CVV" <?php if($gateway != "stripe") { ?>name="CVV"<?php } ?> type="text" size="4" value="<?php if(!empty($_REQUEST['CVV'])) { echo esc_attr($_REQUEST['CVV']); }?>" /> <small>(<a href="#" onclick="javascript:window.open('<?php echo plugins_url( "/pages/popup-cvv.html", dirname(__FILE__))?>','cvv','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=600, height=475');"><?php _ex("what's this?", 'link to CVV help', 'pmpro');?></a>)</small> </div> <?php } ?> </td> </tr> </tbody> </table> <div> <input type="hidden" name="update-billing" value="1" /> <input type="submit" class="btn btn-default pmpro_btn pmpro_btn-submit" value="<?php _e('Update', 'pmpro');?>" /> <input type="button" name="cancel" class="btn btn-see-through pmpro_btn pmpro_btn-cancel" value="<?php _e('Cancel', 'pmpro');?>" onclick="location.href='<?php echo pmpro_url("account")?>';" /> </div> </form> <script> // Find ALL <form> tags on your page jQuery('form').submit(function(){ // On submit disable its submit button jQuery('input[type=submit]', this).attr('disabled', 'disabled'); jQuery('input[type=image]', this).attr('disabled', 'disabled'); }); </script> <?php } ?> <?php } else { ?> <p><?php _e("This subscription is not recurring. So you don't need to update your billing information.", "pmpro");?></p> <?php } ?>
gpl-2.0
antiface/ThinkBayes2
code/lincoln.py
3845
"""This file contains code used in "Think Stats", by Allen B. Downey, available from greenteapress.com Copyright 2014 Allen B. Downey License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html """ from __future__ import print_function, division import thinkbayes2 import thinkplot import numpy """ Bayesian solution to the Lincoln index, described in a blog article at Probably Overthinking It. http://tinyurl.com/lincoln14 Last year my occasional correspondent John D. Cook wrote an excellent blog post about the Lincoln index, which is a way to estimate the number of errors in a document (or program) by comparing results from two independent testers. http://www.johndcook.com/blog/2010/07/13/lincoln-index/ Here's his presentation of the problem: "Suppose you have a tester who finds 20 bugs in your program. You want to estimate how many bugs are really in the program. You know there are at least 20 bugs, and if you have supreme confidence in your tester, you may suppose there are around 20 bugs. But maybe your tester isn't very good. Maybe there are hundreds of bugs. How can you have any idea how many bugs there are? There's no way to know with one tester. But if you have two testers, you can get a good idea, even if you don't know how skilled the testers are." Then he presents the Lincoln index, an estimator "described by Frederick Charles Lincoln in 1930," where Wikpedia's use of "described" is a hint that the index is another example of Stigler's law of eponymy. "Suppose two testers independently search for bugs. Let k1 be the number of errors the first tester finds and k2 the number of errors the second tester finds. Let c be the number of errors both testers find. The Lincoln Index estimates the total number of errors as k1 k2 / c [I changed his notation to be consistent with mine]." So if the first tester finds 20 bugs, the second finds 15, and they find 3 in common, we estimate that there are about 100 bugs. Of course, whenever I see something like this, the idea that pops into my head is that there must be a (better) Bayesian solution! And there is. """ def choose(n, k, d={}): """The binomial coefficient "n choose k". Args: n: number of trials k: number of successes d: map from (n,k) tuples to cached results Returns: int """ if k == 0: return 1 if n == 0: return 0 try: return d[n, k] except KeyError: res = choose(n-1, k) + choose(n-1, k-1) d[n, k] = res return res def binom(k, n, p): """Computes the rest of the binomial PMF. k: number of hits n: number of attempts p: probability of a hit """ return p**k * (1-p)**(n-k) class Lincoln(thinkbayes2.Suite, thinkbayes2.Joint): """Represents hypotheses about the number of errors.""" def Likelihood(self, data, hypo): """Computes the likelihood of the data under the hypothesis. hypo: n, p1, p2 data: k1, k2, c """ n, p1, p2 = hypo k1, k2, c = data part1 = choose(n, k1) * binom(k1, n, p1) part2 = choose(k1, c) * choose(n-k1, k2-c) * binom(k2, n, p2) return part1 * part2 def main(): data = 20, 15, 3 probs = numpy.linspace(0, 1, 31) hypos = [] for n in range(32, 350): for p1 in probs: for p2 in probs: hypos.append((n, p1, p2)) suite = Lincoln(hypos) suite.Update(data) n_marginal = suite.Marginal(0) thinkplot.Pmf(n_marginal, label='n') thinkplot.Save(root='lincoln1', xlabel='number of bugs', ylabel='PMF', formats=['pdf', 'png']) print('post mean n', n_marginal.Mean()) print('MAP n', n_marginal.MaximumLikelihood()) if __name__ == '__main__': main()
gpl-2.0
JackPotte/xtools
public_html/common/jpgraph/Examples/testsuit.php
2780
<?php //======================================================================= // File: TESTSUIT.PHP // Description: Run all the example script in current directory // Created: 2002-07-11 // Ver: $Id: testsuit.php,v 1.1.2.1 2004/03/27 12:43:07 aditus Exp $ // // License: This code is released under QPL 1.0 // Copyright (C) 2001,2002 Johan Persson //======================================================================== //------------------------------------------------------------------------- // // Usage: testsuit.php[?type=1] Generates all non image map scripts // testsuit.php?type=2 Generates client side image map scripts // //------------------------------------------------------------------------- class TestDriver { private $iType; private $iDir; function TestDriver($aType=1,$aDir='') { $this->iType = $aType; if( $aDir == '' ) { $aDir = getcwd(); } if( !chdir($aDir) ) { die("PANIC: Can't access directory : $aDir"); } $this->iDir = $aDir; } function GetFiles() { $d = @dir($this->iDir); $a = array(); while( $entry=$d->Read() ) { if( strstr($entry,".php") && strstr($entry,"x") && !strstr($entry,"show") && !strstr($entry,"csim") ) { $a[] = $entry; } } $d->Close(); if( count($a) == 0 ) { die("PANIC: Apache/PHP does not have enough permission to read the scripts in directory: $this->iDir"); } sort($a); return $a; } function GetCSIMFiles() { $d = @dir($this->iDir); $a = array(); while( $entry=$d->Read() ) { if( strstr($entry,".php") && strstr($entry,"csim") ) { $a[] = $entry; } } $d->Close(); if( count($a) == 0 ) { die("PANIC: Apache/PHP does not have enough permission to read the CSIM scripts in directory: $this->iDir"); } sort($a); return $a; } function Run() { switch( $this->iType ) { case 1: $files = $this->GetFiles(); break; case 2: $files = $this->GetCSIMFiles(); break; default: die('Panic: Unknown type of test'); break; } $n = count($files); echo "<h2>Visual test suit for JpGraph</h2>"; echo "Testtype: " . ($this->iType==1 ? ' Standard images ':' Image map tests '); echo "<br>Number of tests: $n<p>"; echo "<ol>"; for( $i=0; $i<$n; ++$i ) { if( $this->iType ==1 ) { echo '<li><a href="show-example.php?target='.urlencode($files[$i]).'"><img src="'.$files[$i].'" border=0 align=top></a><br><strong>Filename:</strong> <i>'.basename($files[$i])."</i>\n"; } else { echo '<li><a href="show-example.php?target='.urlencode($files[$i]).'">'.$files[$i]."</a>\n"; } } echo "</ol>"; echo "<p>Done.</p>"; } } $type=@$_GET['type']; if( empty($type) ) { $type=1; } $driver = new TestDriver($type); $driver->Run(); ?>
gpl-3.0
sanger-pathogens/Artemis
src/main/java/uk/ac/sanger/artemis/EntryGroupChangeEvent.java
3204
/* EntryGroupChangeEvent.java * * created: Mon Dec 7 1998 * * This file is part of Artemis * * Copyright (C) 1998,1999,2000 Genome Research Limited * * 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 02111-1307, USA. * * $Header: //tmp/pathsoft/artemis/uk/ac/sanger/artemis/EntryGroupChangeEvent.java,v 1.1 2004-06-09 09:44:22 tjc Exp $ */ package uk.ac.sanger.artemis; /** * This event is sent when a change occurs in an EntryGroup. eg. an Entry * is deleted or added. * * @author Kim Rutherford * @version $Id: EntryGroupChangeEvent.java,v 1.1 2004-06-09 09:44:22 tjc Exp $ **/ public class EntryGroupChangeEvent extends ChangeEvent { /** * Event type - Entry removed. **/ public static final int ENTRY_DELETED = 1; /** * Event type - Entry added. **/ public static final int ENTRY_ADDED = 2; /** * Event type - Entry has been made active. **/ public static final int ENTRY_ACTIVE = 3; /** * Event type - Entry has been made inactive. **/ public static final int ENTRY_INACTIVE = 4; /** * Event type - There is now a different default Entry. **/ public static final int NEW_DEFAULT_ENTRY = 5; /** * Event type - This event means that the entry group is now not used by * anything important. **/ public static final int DONE_GONE = 6; /** * Create a new EntryChangeEvent object. * @param entry_group This EntryGroup object that this event refers to. * @param entry This Entry object that this event refers to (if any). * @param type This type of the event. **/ public EntryGroupChangeEvent (final EntryGroup entry_group, final Entry entry, final int type) { super (entry_group); this.entry = entry; this.type = type; } /** * Return the type of this event ie. the type passed to the constructor. **/ public int getType () { return type; } /** * Return the target Entry object for this event. Will return null for * DONE_GONE events. **/ public Entry getEntry () { return entry; } /** * This is a convenience method that returns the EntryGroup the generated * this event. **/ public EntryGroup getEntryGroup () { return (EntryGroup) getSource (); } /** * The Entry object that was passed to the constructor. **/ private Entry entry; /** * This is the type of this event (eg ENTRY_ADDED, ENTRY_DELETED, etc), as * passed to the constructor **/ private int type; }
gpl-3.0
fabsx00/bjoern
projects/bjoern-plugins/datadependence/src/main/java/bjoern/plugins/datadependence/DataDependenceCreator.java
2097
package bjoern.plugins.datadependence; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Vertex; import java.util.HashSet; import java.util.Map; import java.util.Set; public class DataDependenceCreator { private static final String LABEL = "REACHES"; public static void createFromReachingDefinitions( Map<Vertex, Set<ReachingDefinitionAnalyser.Definition>> reachingDefinitions) { for (Map.Entry<Vertex, Set<ReachingDefinitionAnalyser.Definition>> entry : reachingDefinitions .entrySet()) { for (ReachingDefinitionAnalyser.Definition definition : entry .getValue()) { Object object = definition.getIdentifier(); Vertex destination = entry.getKey(); Set<String> useSet = getUseSet(destination); if (useSet.contains(object)) { Vertex source = definition.getLocation(); addEdge(source, destination, object); } } } } /** * Add an data dependence edge from {@code source} to {@code destination} * with respect to the data object {@code object} (e.g. a variable/aloc). * <p> * An edge is only added if it does not exist already. * * @param source * the source node of the data dependence, i.e.the node that changes the * value of {@code object} * @param destination * the destination node of the data dependence, ie.e the node that reads * the value of {@code object} * @param object * the data object. */ private static void addEdge( Vertex source, Vertex destination, Object object) { for (Edge edge : source.getEdges(Direction.OUT, LABEL)) { if (edge.getVertex(Direction.IN).equals(destination) && edge .getProperty("aloc").equals(object)) { // edge exists -> skip return; } } Edge edge = source.addEdge(LABEL, destination); edge.setProperty("aloc", object); } private static Set<String> getUseSet(Vertex destination) { Set<String> set = new HashSet<>(); for (Vertex vertex : destination.getVertices(Direction.OUT, "READ")) { set.add(vertex.getProperty("name")); } return set; } }
gpl-3.0
hgiemza/DIRAC
RequestManagementSystem/Client/test/Test_Request.py
16952
######################################################################## # $HeadURL$ # File: RequestTests.py # Author: Krzysztof.Ciba@NOSPAMgmail.com # Date: 2012/07/24 10:23:40 ######################################################################## """ :mod: RequestTests ======================= .. module: RequestTests :synopsis: test cases for Request class .. moduleauthor:: Krzysztof.Ciba@NOSPAMgmail.com test cases for Request class """ __RCSID__ = "$Id$" # # # @file RequestTests.py # @author Krzysztof.Ciba@NOSPAMgmail.com # @date 2012/07/24 10:23:52 # @brief Definition of RequestTests class. # # imports import unittest import datetime # # from DIRAC from DIRAC.RequestManagementSystem.Client.Operation import Operation from DIRAC.RequestManagementSystem.Client.File import File # # SUT from DIRAC.RequestManagementSystem.Client.Request import Request from DIRAC.RequestManagementSystem.Client.ReqClient import printRequest def optimizeRequest( req, printOutput = None ): from DIRAC import gLogger if printOutput: if isinstance( printOutput, basestring ): gLogger.always( 'Request %s:' % printOutput ) printRequest( req ) gLogger.always( '=========== Optimized ===============' ) res = req.optimize() if printOutput: printRequest( req ) gLogger.always( '' ) return res def createRequest( reqType ): r = Request() # Simple failover op1 = Operation() f = File() f.LFN = '/This/is/an/LFN' op1.addFile( f ) op1.Type = 'ReplicateAndRegister' op1.SourceSE = 'CERN-FAILOVER' op1.TargetSE = 'CERN-BUFFER' r.addOperation( op1 ) op2 = Operation() op2.addFile( f ) op2.Type = 'RemoveReplica' op2.TargetSE = 'CERN-FAILOVER' r.addOperation( op2 ) if reqType == 0: return r # two files for Failover f1 = File() f1.LFN = '/This/is/a/second/LFN' op3 = Operation() op3.addFile( f1 ) op3.Type = 'ReplicateAndRegister' op3.SourceSE = 'CERN-FAILOVER' op3.TargetSE = 'CERN-BUFFER' r.addOperation( op3 ) op3 = Operation() op3.addFile( f1 ) op3.Type = 'RemoveReplica' op3.TargetSE = 'CERN-FAILOVER' r.addOperation( op3 ) if reqType == 1: return r op = Operation() op.Type = 'ForwardDiset' if reqType == 2: r.addOperation( op ) return r r.insertBefore( op, r[0] ) if reqType == 3: return r op4 = Operation() op4.Type = 'ForwardDiset' r.addOperation( op4 ) if reqType == 4: return r # 2 different FAILOVER SEs: removal not optimized r[1].SourceSE = 'RAL-FAILOVER' r[2].SourceSE = 'RAL-FAILOVER' if reqType == 5: return r # 2 different destinations, same FAILOVER: replication not optimized r[3].SourceSE = 'RAL-FAILOVER' r[4].SourceSE = 'RAL-FAILOVER' r[3].TargetSE = 'RAL-BUFFER' if reqType == 6: return r print 'This should not happen, reqType =', reqType ######################################################################## class RequestTests( unittest.TestCase ): """ .. class:: RequestTests """ def setUp( self ): """ set up """ self.fromDict = { "RequestName" : "test", "JobID" : 12345 } def tearDown( self ): """ tear down """ del self.fromDict def test_01CtorSerilization( self ): """ c'tor and serialization """ # # empty c'tor req = Request() self.assertEqual( isinstance( req, Request ), True ) self.assertEqual( req.JobID, 0 ) self.assertEqual( req.Status, "Waiting" ) req = Request( self.fromDict ) self.assertEqual( isinstance( req, Request ), True ) self.assertEqual( req.RequestName, "test" ) self.assertEqual( req.JobID, 12345 ) self.assertEqual( req.Status, "Waiting" ) toJSON = req.toJSON() self.assertEqual( toJSON["OK"], True, "JSON serialization failed" ) fromJSON = toJSON["Value"] req = Request( fromJSON ) def test_02Props( self ): """ props """ # # valid values req = Request() req.RequestID = 1 self.assertEqual( req.RequestID, 1 ) req.RequestName = "test" self.assertEqual( req.RequestName, "test" ) req.JobID = 1 self.assertEqual( req.JobID, 1 ) req.CreationTime = "1970-01-01 00:00:00" self.assertEqual( req.CreationTime, datetime.datetime( 1970, 1, 1, 0, 0, 0 ) ) req.CreationTime = datetime.datetime( 1970, 1, 1, 0, 0, 0 ) self.assertEqual( req.CreationTime, datetime.datetime( 1970, 1, 1, 0, 0, 0 ) ) req.SubmitTime = "1970-01-01 00:00:00" self.assertEqual( req.SubmitTime, datetime.datetime( 1970, 1, 1, 0, 0, 0 ) ) req.SubmitTime = datetime.datetime( 1970, 1, 1, 0, 0, 0 ) self.assertEqual( req.SubmitTime, datetime.datetime( 1970, 1, 1, 0, 0, 0 ) ) req.LastUpdate = "1970-01-01 00:00:00" self.assertEqual( req.LastUpdate, datetime.datetime( 1970, 1, 1, 0, 0, 0 ) ) req.LastUpdate = datetime.datetime( 1970, 1, 1, 0, 0, 0 ) self.assertEqual( req.LastUpdate, datetime.datetime( 1970, 1, 1, 0, 0, 0 ) ) req.Error = "" def test_04Operations( self ): """ operations arithmetic and state machine """ req = Request() self.assertEqual( len( req ), 0 ) transfer = Operation() transfer.Type = "ReplicateAndRegister" transfer.addFile( File( { "LFN" : "/a/b/c", "Status" : "Waiting" } ) ) getWaiting = req.getWaiting() self.assertEqual( getWaiting["OK"], True ) self.assertEqual( getWaiting["Value"], None ) req.addOperation( transfer ) self.assertEqual( len( req ), 1 ) self.assertEqual( transfer.Order, req.Order ) self.assertEqual( transfer.Status, "Waiting" ) getWaiting = req.getWaiting() self.assertEqual( getWaiting["OK"], True ) self.assertEqual( getWaiting["Value"], transfer ) removal = Operation( { "Type" : "RemoveFile" } ) removal.addFile( File( { "LFN" : "/a/b/c", "Status" : "Waiting" } ) ) req.insertBefore( removal, transfer ) getWaiting = req.getWaiting() self.assertEqual( getWaiting["OK"], True ) self.assertEqual( getWaiting["Value"], removal ) self.assertEqual( len( req ), 2 ) self.assertEqual( [ op.Status for op in req ], ["Waiting", "Queued"] ) self.assertEqual( req.subStatusList() , ["Waiting", "Queued"] ) self.assertEqual( removal.Order, 0 ) self.assertEqual( removal.Order, req.Order ) self.assertEqual( transfer.Order, 1 ) self.assertEqual( removal.Status, "Waiting" ) self.assertEqual( transfer.Status, "Queued" ) for subFile in removal: subFile.Status = "Done" removal.Status = "Done" self.assertEqual( removal.Status, "Done" ) self.assertEqual( transfer.Status, "Waiting" ) self.assertEqual( transfer.Order, req.Order ) # # len, looping self.assertEqual( len( req ), 2 ) self.assertEqual( [ op.Status for op in req ], ["Done", "Waiting"] ) self.assertEqual( req.subStatusList() , ["Done", "Waiting"] ) digest = req.toJSON() self.assertEqual( digest["OK"], True ) getWaiting = req.getWaiting() self.assertEqual( getWaiting["OK"], True ) self.assertEqual( getWaiting["Value"], transfer ) def test_05FTS( self ): """ FTS state machine """ req = Request() req.RequestName = "FTSTest" ftsTransfer = Operation() ftsTransfer.Type = "ReplicateAndRegister" ftsTransfer.TargetSE = "CERN-USER" ftsFile = File() ftsFile.LFN = "/a/b/c" ftsFile.Checksum = "123456" ftsFile.ChecksumType = "Adler32" ftsTransfer.addFile( ftsFile ) req.addOperation( ftsTransfer ) self.assertEqual( req.Status, "Waiting", "1. wrong request status: %s" % req.Status ) self.assertEqual( ftsTransfer.Status, "Waiting", "1. wrong ftsStatus status: %s" % ftsTransfer.Status ) # # scheduled ftsFile.Status = "Scheduled" self.assertEqual( ftsTransfer.Status, "Scheduled", "2. wrong status for ftsTransfer: %s" % ftsTransfer.Status ) self.assertEqual( req.Status, "Scheduled", "2. wrong status for request: %s" % req.Status ) # # add new operation before FTS insertBefore = Operation() insertBefore.Type = "RegisterReplica" insertBefore.TargetSE = "CERN-USER" insertFile = File() insertFile.LFN = "/a/b/c" insertFile.PFN = "http://foo/bar" insertBefore.addFile( insertFile ) req.insertBefore( insertBefore, ftsTransfer ) self.assertEqual( insertBefore.Status, "Waiting", "3. wrong status for insertBefore: %s" % insertBefore.Status ) self.assertEqual( ftsTransfer.Status, "Scheduled", "3. wrong status for ftsStatus: %s" % ftsTransfer.Status ) self.assertEqual( req.Status, "Waiting", "3. wrong status for request: %s" % req.Status ) # # prev done insertFile.Status = "Done" self.assertEqual( insertBefore.Status, "Done", "4. wrong status for insertBefore: %s" % insertBefore.Status ) self.assertEqual( ftsTransfer.Status, "Scheduled", "4. wrong status for ftsStatus: %s" % ftsTransfer.Status ) self.assertEqual( req.Status, "Scheduled", "4. wrong status for request: %s" % req.Status ) # # reschedule ftsFile.Status = "Waiting" self.assertEqual( insertBefore.Status, "Done", "5. wrong status for insertBefore: %s" % insertBefore.Status ) self.assertEqual( ftsTransfer.Status, "Waiting", "5. wrong status for ftsStatus: %s" % ftsTransfer.Status ) self.assertEqual( req.Status, "Waiting", "5. wrong status for request: %s" % req.Status ) # # fts done ftsFile.Status = "Done" self.assertEqual( insertBefore.Status, "Done", "5. wrong status for insertBefore: %s" % insertBefore.Status ) self.assertEqual( ftsTransfer.Status, "Done", "5. wrong status for ftsStatus: %s" % ftsTransfer.Status ) self.assertEqual( req.Status, "Done", "5. wrong status for request: %s" % req.Status ) def test_06StateMachine( self ): """ state machine tests """ r = Request( {"RequestName": "SMT"} ) self.assertEqual( r.Status, "Waiting", "1. wrong status %s" % r.Status ) r.addOperation( Operation( {"Status": "Queued"} ) ) self.assertEqual( r.Status, "Waiting", "2. wrong status %s" % r.Status ) r.addOperation( Operation( {"Status": "Queued"} ) ) self.assertEqual( r.Status, "Waiting", "3. wrong status %s" % r.Status ) r[0].Status = "Done" self.assertEqual( r.Status, "Waiting", "4. wrong status %s" % r.Status ) r[1].Status = "Done" self.assertEqual( r.Status, "Done", "5. wrong status %s" % r.Status ) r[0].Status = "Failed" self.assertEqual( r.Status, "Failed", "6. wrong status %s" % r.Status ) r[0].Status = "Queued" self.assertEqual( r.Status, "Waiting", "7. wrong status %s" % r.Status ) r.insertBefore( Operation( {"Status": "Queued"} ), r[0] ) self.assertEqual( r.Status, "Waiting", "8. wrong status %s" % r.Status ) r.insertBefore( Operation( {"Status": "Queued"} ), r[0] ) self.assertEqual( r.Status, "Waiting", "9. wrong status %s" % r.Status ) r.insertBefore( Operation( {"Status": "Scheduled"} ), r[0] ) self.assertEqual( r.Status, "Scheduled", "10. wrong status %s" % r.Status ) r.insertBefore( Operation( {"Status": "Queued" } ), r[0] ) self.assertEqual( r.Status, "Waiting", "11. wrong status %s" % r.Status ) r[0].Status = "Failed" self.assertEqual( r.Status, "Failed", "12. wrong status %s" % r.Status ) r[0].Status = "Done" self.assertEqual( r.Status, "Scheduled", "13. wrong status %s" % r.Status ) r[1].Status = "Failed" self.assertEqual( r.Status, "Failed", "14. wrong status %s" % r.Status ) r[1].Status = "Done" self.assertEqual( r.Status, "Waiting", "15. wrong status %s" % r.Status ) r[2].Status = "Scheduled" self.assertEqual( r.Status, "Scheduled", "16. wrong status %s" % r.Status ) r[2].Status = "Queued" self.assertEqual( r.Status, "Waiting", "17. wrong status %s" % r.Status ) r[2].Status = "Scheduled" self.assertEqual( r.Status, "Scheduled", "18. wrong status %s" % r.Status ) r = Request() for i in range( 5 ): r.addOperation( Operation( {"Status": "Queued" } ) ) r[0].Status = "Done" self.assertEqual( r.Status, "Waiting", "19. wrong status %s" % r.Status ) r[1].Status = "Done" self.assertEqual( r.Status, "Waiting", "20. wrong status %s" % r.Status ) r[2].Status = "Scheduled" self.assertEqual( r.Status, "Scheduled", "21. wrong status %s" % r.Status ) r[2].Status = "Done" self.assertEqual( r.Status, "Waiting", "22. wrong status %s" % r.Status ) def test_07List( self ): """ setitem, delitem, getitem and dirty """ r = Request() ops = [ Operation() for i in range( 5 ) ] for op in ops: r.addOperation( op ) for i, op in enumerate( ops ): self.assertEqual( op, r[i], "__getitem__ failed" ) op = Operation() r[0] = op self.assertEqual( op, r[0], "__setitem__ failed" ) del r[0] self.assertEqual( len( r ), 4, "__delitem__ failed" ) def test_08Optimize( self ): title = { 0: 'Simple Failover', 1: 'Double Failover', 2: 'Double Failover + ForwardDiset', 3: 'ForwardDiset + Double Failover', 4: 'ForwardDiset + Double Failover + ForwardDiset', 5: 'ForwardDiset + Double Failover (# Failover SE) + ForwardDiset', 6: 'ForwardDiset + Double Failover (# Destination SE) + ForwardDiset' } debug = False if debug != False: print '' for reqType in title: r = createRequest( reqType ) res = optimizeRequest( r, printOutput = title[reqType] if ( debug == reqType and debug is not False ) else False ) self.assertEqual( res['OK'], True ) self.assertEqual( res['Value'], True ) if reqType in ( 0, 1 ): self.assertEqual( len( r ), 2, 'Wrong number of operations: %d' % len( r ) ) self.assertEqual( r[0].Type, 'ReplicateAndRegister' ) self.assertEqual( r[1].Type, 'RemoveReplica' ) if reqType == 1: self.assertEqual( len( r[0] ), 2, 'Wrong number of files: %d' % len( r[0] ) ) self.assertEqual( len( r[1] ), 2, 'Wrong number of files: %d' % len( r[1] ) ) elif reqType == 2: self.assertEqual( len( r ), 3, 'Wrong number of operations: %d' % len( r ) ) self.assertEqual( r[0].Type, 'ReplicateAndRegister' ) self.assertEqual( r[1].Type, 'RemoveReplica' ) self.assertEqual( r[2].Type, 'ForwardDiset' ) self.assertEqual( len( r[0] ), 2, 'Wrong number of files: %d' % len( r[0] ) ) self.assertEqual( len( r[1] ), 2, 'Wrong number of files: %d' % len( r[1] ) ) elif reqType == 3: self.assertEqual( len( r ), 3, 'Wrong number of operations: %d' % len( r ) ) self.assertEqual( r[1].Type, 'ReplicateAndRegister' ) self.assertEqual( r[2].Type, 'RemoveReplica' ) self.assertEqual( r[0].Type, 'ForwardDiset' ) self.assertEqual( len( r[1] ), 2, 'Wrong number of files: %d' % len( r[0] ) ) self.assertEqual( len( r[2] ), 2, 'Wrong number of files: %d' % len( r[1] ) ) elif reqType == 4: self.assertEqual( len( r ), 4, 'Wrong number of operations: %d' % len( r ) ) self.assertEqual( r[1].Type, 'ReplicateAndRegister' ) self.assertEqual( r[2].Type, 'RemoveReplica' ) self.assertEqual( r[0].Type, 'ForwardDiset' ) self.assertEqual( r[3].Type, 'ForwardDiset' ) self.assertEqual( len( r[1] ), 2, 'Wrong number of files: %d' % len( r[0] ) ) self.assertEqual( len( r[2] ), 2, 'Wrong number of files: %d' % len( r[1] ) ) elif reqType == 5: self.assertEqual( len( r ), 5, 'Wrong number of operations: %d' % len( r ) ) self.assertEqual( r[1].Type, 'ReplicateAndRegister' ) self.assertEqual( r[2].Type, 'RemoveReplica' ) self.assertEqual( r[3].Type, 'RemoveReplica' ) self.assertEqual( r[0].Type, 'ForwardDiset' ) self.assertEqual( r[4].Type, 'ForwardDiset' ) self.assertEqual( len( r[1] ), 2, 'Wrong number of files: %d' % len( r[0] ) ) self.assertEqual( len( r[2] ), 1, 'Wrong number of files: %d' % len( r[1] ) ) self.assertEqual( len( r[3] ), 1, 'Wrong number of files: %d' % len( r[1] ) ) elif reqType == 6: self.assertEqual( len( r ), 5, 'Wrong number of operations: %d' % len( r ) ) self.assertEqual( r[1].Type, 'ReplicateAndRegister' ) self.assertEqual( r[2].Type, 'ReplicateAndRegister' ) self.assertEqual( r[3].Type, 'RemoveReplica' ) self.assertEqual( r[0].Type, 'ForwardDiset' ) self.assertEqual( r[4].Type, 'ForwardDiset' ) self.assertEqual( len( r[1] ), 1, 'Wrong number of files: %d' % len( r[0] ) ) self.assertEqual( len( r[2] ), 1, 'Wrong number of files: %d' % len( r[1] ) ) self.assertEqual( len( r[3] ), 2, 'Wrong number of files: %d' % len( r[1] ) ) # # test execution if __name__ == "__main__": suite = unittest.defaultTestLoader.loadTestsFromTestCase( RequestTests ) testResult = unittest.TextTestRunner( verbosity = 2 ).run( suite )
gpl-3.0
jjalling/domoticz
main/Helper.cpp
31334
#include "stdafx.h" #include "Helper.h" #include "Logger.h" #ifdef WIN32 #include "dirent_windows.h" #include <direct.h> #else #include <dirent.h> #include <unistd.h> #endif #if !defined(WIN32) #include <sys/ptrace.h> #endif #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <fstream> #include <math.h> #include <algorithm> #include "../main/localtime_r.h" #include <sstream> #include <openssl/md5.h> #include <chrono> #include <limits.h> #include <cstring> #if defined WIN32 #include "../msbuild/WindowsHelper.h" #endif #include "RFXtrx.h" #include "../hardware/hardwaretypes.h" // Includes for SystemUptime() #if defined(__linux__) || defined(__linux) || defined(linux) #include <sys/sysinfo.h> #elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) #include <time.h> #include <errno.h> #include <sys/sysctl.h> #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) #include <time.h> #endif #if defined(__FreeBSD__) // Check if OpenBSD or DragonFly need that at well? #include <pthread_np.h> #ifndef PTHREAD_MAX_MAMELEN_NP #define PTHREAD_MAX_NAMELEN_NP 32 // Arbitrary #endif #endif void StringSplit(std::string str, const std::string &delim, std::vector<std::string> &results) { results.clear(); size_t cutAt; while( (cutAt = str.find(delim)) != std::string::npos ) { results.push_back(str.substr(0,cutAt)); str = str.substr(cutAt+ delim.size()); } if (!str.empty()) { results.push_back(str); } } uint64_t hexstrtoui64(const std::string &str) { uint64_t ul; std::stringstream ss; ss << std::hex << str; ss >> ul; return ul; } void stdreplace( std::string &inoutstring, const std::string& replaceWhat, const std::string& replaceWithWhat) { int pos = 0; while (std::string::npos != (pos = inoutstring.find(replaceWhat, pos))) { inoutstring.replace(pos, replaceWhat.size(), replaceWithWhat); pos += replaceWithWhat.size(); } } void stdupper(std::string &inoutstring) { for (size_t i = 0; i < inoutstring.size(); ++i) inoutstring[i] = toupper(inoutstring[i]); } void stdlower(std::string &inoutstring) { std::transform(inoutstring.begin(), inoutstring.end(), inoutstring.begin(), ::tolower); } std::vector<std::string> GetSerialPorts(bool &bUseDirectPath) { bUseDirectPath=false; std::vector<std::string> ret; #if defined WIN32 //windows std::vector<int> ports; std::vector<std::string> friendlyNames; char szPortName[40]; EnumSerialFromWMI(ports, friendlyNames); bool bFoundPort = false; if (!ports.empty()) { bFoundPort = true; for (const auto & itt : ports) { sprintf(szPortName, "COM%d", itt); ret.push_back(szPortName); } } if (bFoundPort) return ret; //Scan old fashion way (SLOW!) COMMCONFIG cc; DWORD dwSize = sizeof(COMMCONFIG); for (int ii = 0; ii < 256; ii++) { sprintf(szPortName, "COM%d", ii); if (GetDefaultCommConfig(szPortName, &cc, &dwSize)) { bFoundPort = true; sprintf(szPortName, "COM%d", ii); //Check if we did not already have it bool bFound = false; for (const auto & itt : ret) { if (itt == szPortName) { bFound = true; break; } } if (!bFound) ret.push_back(szPortName); // add port } } // Method 2: CreateFile, slow // --------- if (!bFoundPort) { for (int ii = 0; ii < 256; ii++) { sprintf(szPortName, "\\\\.\\COM%d", ii); bool bSuccess = false; HANDLE hPort = ::CreateFile(szPortName, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); if (hPort == INVALID_HANDLE_VALUE) { DWORD dwError = GetLastError(); //Check to see if the error was because some other app had the port open if (dwError == ERROR_ACCESS_DENIED) bSuccess = TRUE; } else { //The port was opened successfully bSuccess = TRUE; //Don't forget to close the port, since we are going to do nothing with it anyway CloseHandle(hPort); } if (bSuccess) { bFoundPort = true; sprintf(szPortName, "COM%d", ii); ret.push_back(szPortName); // add port } // -------------- } } // Method 3: EnumSerialPortsWindows, often fails // --------- if (!bFoundPort) { std::vector<SerialPortInfo> serialports; EnumSerialPortsWindows(serialports); if (!serialports.empty()) { for (const auto & itt : serialports) { ret.push_back(itt.szPortName); // add port } } } #else //scan /dev for /dev/ttyUSB* or /dev/ttyS* or /dev/tty.usbserial* or /dev/ttyAMA* or /dev/ttySAC* or /dev/ttymxc* //also scan /dev/serial/by-id/* on Linux bool bHaveTtyAMAfree=false; std::string sLine = ""; std::ifstream infile; infile.open("/boot/cmdline.txt"); if (infile.is_open()) { if (!infile.eof()) { getline(infile, sLine); bHaveTtyAMAfree=(sLine.find("ttyAMA0")==std::string::npos); } } DIR *d=NULL; d=opendir("/dev"); if (d != NULL) { struct dirent *de=NULL; // Loop while not NULL while ((de = readdir(d))) { // Only consider character devices and symbolic links if ((de->d_type == DT_CHR) || (de->d_type == DT_LNK)) { std::string fname = de->d_name; if (fname.find("ttyUSB")!=std::string::npos) { ret.push_back("/dev/" + fname); } else if (fname.find("tty.usbserial")!=std::string::npos) { bUseDirectPath=true; ret.push_back("/dev/" + fname); } else if (fname.find("ttyACM")!=std::string::npos) { bUseDirectPath=true; ret.push_back("/dev/" + fname); } else if (fname.find("ttySAC") != std::string::npos) { bUseDirectPath = true; ret.push_back("/dev/" + fname); } else if (fname.find("ttymxc") != std::string::npos) { bUseDirectPath = true; ret.push_back("/dev/" + fname); } #if defined (__FreeBSD__) || defined (__OpenBSD__) || defined (__NetBSD__) else if (fname.find("ttyU")!=std::string::npos) { bUseDirectPath=true; ret.push_back("/dev/" + fname); } else if (fname.find("cuaU")!=std::string::npos) { bUseDirectPath=true; ret.push_back("/dev/" + fname); } #endif #ifdef __APPLE__ else if (fname.find("cu.")!=std::string::npos) { bUseDirectPath=true; ret.push_back("/dev/" + fname); } #endif if (bHaveTtyAMAfree) { if (fname.find("ttyAMA0")!=std::string::npos) { ret.push_back("/dev/" + fname); bUseDirectPath=true; } // By default, this is the "small UART" on Rasberry 3 boards if (fname.find("ttyS0")!=std::string::npos) { ret.push_back("/dev/" + fname); bUseDirectPath=true; } // serial0 and serial1 are new with Rasbian Jessie // Avoids confusion between Raspberry 2 and 3 boards // More info at http://spellfoundry.com/2016/05/29/configuring-gpio-serial-port-raspbian-jessie-including-pi-3/ if (fname.find("serial")!=std::string::npos) { ret.push_back("/dev/" + fname); bUseDirectPath=true; } } } } closedir(d); } //also scan in /dev/usb d=opendir("/dev/usb"); if (d != NULL) { struct dirent *de=NULL; // Loop while not NULL while ((de = readdir(d))) { std::string fname = de->d_name; if (fname.find("ttyUSB")!=std::string::npos) { bUseDirectPath=true; ret.push_back("/dev/usb/" + fname); } } closedir(d); } #if defined(__linux__) || defined(__linux) || defined(linux) d=opendir("/dev/serial/by-id"); if (d != NULL) { struct dirent *de=NULL; // Loop while not NULL while ((de = readdir(d))) { // Only consider symbolic links if (de->d_type == DT_LNK) { std::string fname = de->d_name; ret.push_back("/dev/serial/by-id/" + fname); } } closedir(d); } #endif #endif return ret; } bool file_exist (const char *filename) { struct stat sbuffer; return (stat(filename, &sbuffer) == 0); } double CalculateAltitudeFromPressure(double pressure) { double seaLevelPressure=101325.0; double altitude = 44330.0 * (1.0 - pow( (pressure / seaLevelPressure), 0.1903)); return altitude; } /**************************************************************************/ /*! Calculates the altitude (in meters) from the specified atmospheric pressure (in hPa), sea-level pressure (in hPa), and temperature (in °C) @param seaLevel Sea-level pressure in hPa @param atmospheric Atmospheric pressure in hPa @param temp Temperature in degrees Celsius */ /**************************************************************************/ float pressureToAltitude(float seaLevel, float atmospheric, float temp) { /* Hyposometric formula: */ /* */ /* ((P0/P)^(1/5.257) - 1) * (T + 273.15) */ /* h = ------------------------------------- */ /* 0.0065 */ /* */ /* where: h = height (in meters) */ /* P0 = sea-level pressure (in hPa) */ /* P = atmospheric pressure (in hPa) */ /* T = temperature (in °C) */ return (((float)pow((seaLevel / atmospheric), 0.190223F) - 1.0F) * (temp + 273.15F)) / 0.0065F; } /**************************************************************************/ /*! Calculates the sea-level pressure (in hPa) based on the current altitude (in meters), atmospheric pressure (in hPa), and temperature (in °C) @param altitude altitude in meters @param atmospheric Atmospheric pressure in hPa @param temp Temperature in degrees Celsius */ /**************************************************************************/ float pressureSeaLevelFromAltitude(float altitude, float atmospheric, float temp) { /* Sea-level pressure: */ /* */ /* 0.0065*h */ /* P0 = P * (1 - ----------------- ) ^ -5.257 */ /* T+0.0065*h+273.15 */ /* */ /* where: P0 = sea-level pressure (in hPa) */ /* P = atmospheric pressure (in hPa) */ /* h = altitude (in meters) */ /* T = Temperature (in °C) */ return atmospheric * (float)pow((1.0F - (0.0065F * altitude) / (temp + 0.0065F * altitude + 273.15F)), -5.257F); } std::string &stdstring_ltrim(std::string &s) { while (!s.empty()) { if (s[0] != ' ') return s; s = s.substr(1); } // s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); return s; } std::string &stdstring_rtrim(std::string &s) { while (!s.empty()) { if (s[s.size() - 1] != ' ') return s; s = s.substr(0, s.size() - 1); } //s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } // trim from both ends std::string &stdstring_trim(std::string &s) { return stdstring_ltrim(stdstring_rtrim(s)); } double CalculateDewPoint(double temp, int humidity) { if (humidity==0) return temp; double dew_numer = 243.04*(log(double(humidity)/100.0)+((17.625*temp)/(temp+243.04))); double dew_denom = 17.625-log(double(humidity)/100.0)-((17.625*temp)/(temp+243.04)); if (dew_numer==0) dew_numer=1; return dew_numer/dew_denom; } uint32_t IPToUInt(const std::string &ip) { int a, b, c, d; uint32_t addr = 0; if (sscanf(ip.c_str(), "%d.%d.%d.%d", &a, &b, &c, &d) != 4) return 0; addr = a << 24; addr |= b << 16; addr |= c << 8; addr |= d; return addr; } bool isInt(const std::string &s) { for(size_t i = 0; i < s.length(); i++){ if(!isdigit(s[i])) return false; } return true; } void sleep_seconds(const long seconds) { std::this_thread::sleep_for(std::chrono::seconds(seconds)); } void sleep_milliseconds(const long milliseconds) { std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); } int createdir(const char *szDirName, int secattr) { int ret = 0; #ifdef WIN32 ret = _mkdir(szDirName); #else ret = mkdir(szDirName, secattr); #endif return ret; } int mkdir_deep(const char *szDirName, int secattr) { char DirName[260]; DirName[0] = 0; const char* p = szDirName; char* q = DirName; int ret = 0; while(*p) { if (('\\' == *p) || ('/' == *p)) { if ((p > szDirName) && (':' != *(p-1))) { ret = createdir(DirName, secattr); } } *q++ = *p++; *q = '\0'; } if (DirName[0]) { ret = createdir(DirName, secattr); } return ret; } int RemoveDir(const std::string &dirnames, std::string &errorPath) { std::vector<std::string> splitresults; StringSplit(dirnames, "|", splitresults); int returncode = 0; if (!splitresults.empty()) { #ifdef WIN32 for (size_t i = 0; i < splitresults.size(); i++) { if (!file_exist(splitresults[i].c_str())) continue; size_t s_szLen = strlen(splitresults[i].c_str()); if (s_szLen < MAX_PATH) { char deletePath[MAX_PATH + 1]; strcpy_s(deletePath, splitresults[i].c_str()); deletePath[s_szLen + 1] = '\0'; // SHFILEOPSTRUCT needs an additional null char SHFILEOPSTRUCT shfo = { NULL, FO_DELETE, deletePath, NULL, FOF_SILENT | FOF_NOERRORUI | FOF_NOCONFIRMATION, FALSE, NULL, NULL }; if (returncode = SHFileOperation(&shfo)) { errorPath = splitresults[i]; break; } } } #else for (size_t i = 0; i < splitresults.size(); i++) { if (!file_exist(splitresults[i].c_str())) continue; ExecuteCommandAndReturn("rm -rf \"" + splitresults[i] + "\"", returncode); if (returncode) { errorPath = splitresults[i]; break; } } #endif } return returncode; } double ConvertToCelsius(const double Fahrenheit) { return (Fahrenheit-32.0) * 0.5556; } double ConvertToFahrenheit(const double Celsius) { return (Celsius*1.8)+32.0; } double RoundDouble(const long double invalue, const short numberOfPrecisions) { long long p = (long long) pow(10.0L, numberOfPrecisions); double ret= (long long)(invalue * p + 0.5L) / (double)p; return ret; } double ConvertTemperature(const double tValue, const unsigned char tSign) { if (tSign=='C') return tValue; return RoundDouble(ConvertToFahrenheit(tValue),1); } std::vector<std::string> ExecuteCommandAndReturn(const std::string &szCommand, int &returncode) { std::vector<std::string> ret; try { FILE *fp; /* Open the command for reading. */ #ifdef WIN32 fp = _popen(szCommand.c_str(), "r"); #else fp = popen(szCommand.c_str(), "r"); #endif if (fp != NULL) { char path[1035]; /* Read the output a line at a time - output it. */ while (fgets(path, sizeof(path) - 1, fp) != NULL) { ret.push_back(path); } /* close */ #ifdef WIN32 returncode = _pclose(fp); #else returncode = pclose(fp); #endif } } catch (...) { } return ret; } std::string TimeToString(const time_t *ltime, const _eTimeFormat format) { struct tm timeinfo; struct timeval tv; std::stringstream sstr; if (ltime == NULL) // current time { #ifdef CLOCK_REALTIME struct timespec ts; if (!clock_gettime(CLOCK_REALTIME, &ts)) { tv.tv_sec = ts.tv_sec; tv.tv_usec = ts.tv_nsec / 1000; } else #endif gettimeofday(&tv, NULL); #ifdef WIN32 time_t tv_sec = tv.tv_sec; localtime_r(&tv_sec, &timeinfo); #else localtime_r(&tv.tv_sec, &timeinfo); #endif } else localtime_r(ltime, &timeinfo); if (format > TF_Time) { //Date sstr << (timeinfo.tm_year + 1900) << "-" << std::setw(2) << std::setfill('0') << (timeinfo.tm_mon + 1) << "-" << std::setw(2) << std::setfill('0') << timeinfo.tm_mday; } if (format != TF_Date) { //Time if (format > TF_Time) sstr << " "; sstr << std::setw(2) << std::setfill('0') << timeinfo.tm_hour << ":" << std::setw(2) << std::setfill('0') << timeinfo.tm_min << ":" << std::setw(2) << std::setfill('0') << timeinfo.tm_sec; } if (format > TF_DateTime && ltime == NULL) sstr << "." << std::setw(3) << std::setfill('0') << ((int)tv.tv_usec / 1000); return sstr.str(); } std::string GenerateMD5Hash(const std::string &InputString, const std::string &Salt) { std::string cstring = InputString + Salt; unsigned char digest[MD5_DIGEST_LENGTH + 1]; digest[MD5_DIGEST_LENGTH] = 0; MD5((const unsigned char*)cstring.c_str(), cstring.size(), (unsigned char*)&digest); char mdString[(MD5_DIGEST_LENGTH * 2) + 1]; mdString[MD5_DIGEST_LENGTH * 2] = 0; for (int i = 0; i < 16; i++) sprintf(&mdString[i * 2], "%02x", (unsigned int)digest[i]); return mdString; } void hsb2rgb(const float hue, const float saturation, const float vlue, int &outR, int &outG, int &outB, const double maxValue/* = 100.0 */) { double hh, p, q, t, ff; long i; if(saturation <= 0.0) { outR = int(vlue*maxValue); outG = int(vlue*maxValue); outB = int(vlue*maxValue); } hh = hue; if (hh >= 360.0) hh = 0.0; hh /= 60.0; i = (long)hh; ff = hh - i; p = vlue * (1.0 - saturation); q = vlue * (1.0 - (saturation * ff)); t = vlue * (1.0 - (saturation * (1.0 - ff))); switch (i) { case 0: outR = int(vlue*maxValue); outG = int(t*maxValue); outB = int(p*maxValue); break; case 1: outR = int(q*maxValue); outG = int(vlue*maxValue); outB = int(p*maxValue); break; case 2: outR = int(p*maxValue); outG = int(vlue*maxValue); outB = int(t*maxValue); break; case 3: outR = int(p*maxValue); outG = int(q*maxValue); outB = int(vlue*maxValue); break; case 4: outR = int(t*maxValue); outG = int(p*maxValue); outB = int(vlue*maxValue); break; case 5: default: outR = int(vlue*maxValue); outG = int(p*maxValue); outB = int(q*maxValue); break; } } void rgb2hsb(const int r, const int g, const int b, float hsbvals[3]) { float hue, saturation, brightness; if (hsbvals == NULL) return; int cmax = (r > g) ? r : g; if (b > cmax) cmax = b; int cmin = (r < g) ? r : g; if (b < cmin) cmin = b; brightness = ((float)cmax) / 255.0f; if (cmax != 0) saturation = ((float)(cmax - cmin)) / ((float)cmax); else saturation = 0; if (saturation == 0) hue = 0; else { float redc = ((float)(cmax - r)) / ((float)(cmax - cmin)); float greenc = ((float)(cmax - g)) / ((float)(cmax - cmin)); float bluec = ((float)(cmax - b)) / ((float)(cmax - cmin)); if (r == cmax) hue = bluec - greenc; else if (g == cmax) hue = 2.0f + redc - bluec; else hue = 4.0f + greenc - redc; hue = hue / 6.0f; if (hue < 0) hue = hue + 1.0f; } hsbvals[0] = hue; hsbvals[1] = saturation; hsbvals[2] = brightness; } bool is_number(const std::string& s) { std::string::const_iterator it = s.begin(); while (it != s.end() && (isdigit(*it) || (*it == '.') || (*it == '-') || (*it == ' ') || (*it == 0x00))) ++it; return !s.empty() && it == s.end(); } void padLeft(std::string &str, const size_t num, const char paddingChar) { if (num > str.size()) str.insert(0, num - str.size(), paddingChar); } bool IsLightOrSwitch(const int devType, const int subType) { bool bIsLightSwitch = false; switch (devType) { case pTypeLighting1: case pTypeLighting2: case pTypeLighting3: case pTypeLighting4: case pTypeLighting5: case pTypeLighting6: case pTypeFan: case pTypeColorSwitch: case pTypeSecurity1: case pTypeSecurity2: case pTypeCurtain: case pTypeBlinds: case pTypeRFY: case pTypeThermostat2: case pTypeThermostat3: case pTypeThermostat4: case pTypeRemote: case pTypeGeneralSwitch: case pTypeHomeConfort: case pTypeFS20: bIsLightSwitch = true; break; case pTypeRadiator1: bIsLightSwitch = (subType == sTypeSmartwaresSwitchRadiator); break; } return bIsLightSwitch; } int MStoBeaufort(const float ms) { if (ms < 0.3f) return 0; if (ms < 1.5f) return 1; if (ms < 3.3f) return 2; if (ms < 5.5f) return 3; if (ms < 8.0f) return 4; if (ms < 10.8f) return 5; if (ms < 13.9f) return 6; if (ms < 17.2f) return 7; if (ms < 20.7f) return 8; if (ms < 24.5f) return 9; if (ms < 28.4f) return 10; if (ms < 32.6f) return 11; return 12; } void FixFolderEnding(std::string &folder) { #if defined(WIN32) if (folder.at(folder.length() - 1) != '\\') folder += "\\"; #else if (folder.at(folder.length() - 1) != '/') folder += "/"; #endif } bool dirent_is_directory(const std::string &dir, struct dirent *ent) { if (ent->d_type == DT_DIR) return true; #ifndef WIN32 if (ent->d_type == DT_LNK) return true; if (ent->d_type == DT_UNKNOWN) { std::string fname = dir + "/" + ent->d_name; struct stat st; if (!lstat(fname.c_str(), &st)) return S_ISDIR(st.st_mode); } #endif return false; } bool dirent_is_file(const std::string &dir, struct dirent *ent) { if (ent->d_type == DT_REG) return true; #ifndef WIN32 if (ent->d_type == DT_UNKNOWN) { std::string fname = dir + "/" + ent->d_name; struct stat st; if (!lstat(fname.c_str(), &st)) return S_ISREG(st.st_mode); } #endif return false; } /*! * List entries of a directory. * @param entries A string vector containing the result * @param dir Target directory for listing * @param bInclDirs Boolean flag to include directories in the result * @param bInclFiles Boolean flag to include regular files in the result */ void DirectoryListing(std::vector<std::string>& entries, const std::string &dir, bool bInclDirs, bool bInclFiles) { DIR *d = NULL; struct dirent *ent; if ((d = opendir(dir.c_str())) != NULL) { while ((ent = readdir(d)) != NULL) { std::string name = ent->d_name; if (bInclDirs && dirent_is_directory(dir, ent) && name != "." && name != "..") { entries.push_back(name); continue; } if (bInclFiles && dirent_is_file(dir, ent)) { entries.push_back(name); continue; } } closedir(d); } return; } std::string GenerateUserAgent() { int cversion = rand() % 0xFFFF; int mversion = rand() % 3; int sversion = rand() % 3; std::stringstream sstr; sstr << "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/" << (601 + sversion) << "." << (36+mversion) << " (KHTML, like Gecko) Chrome/" << (53 + mversion) << ".0." << cversion << ".0 Safari/" << (601 + sversion) << "." << (36+sversion); return sstr.str(); } std::string MakeHtml(const std::string &txt) { std::string sRet = txt; stdreplace(sRet, "&", "&amp;"); stdreplace(sRet, "\"", "&quot;"); stdreplace(sRet, "'", "&apos;"); stdreplace(sRet, "<", "&lt;"); stdreplace(sRet, ">", "&gt;"); stdreplace(sRet, "\r\n", "<br/>"); return sRet; } //Prevent against XSS (Cross Site Scripting) std::string SafeHtml(const std::string &txt) { std::string sRet = txt; stdreplace(sRet, "\"", "&quot;"); stdreplace(sRet, "'", "&apos;"); stdreplace(sRet, "<", "&lt;"); stdreplace(sRet, ">", "&gt;"); return sRet; } #if defined WIN32 //FILETIME of Jan 1 1970 00:00:00 static const uint64_t epoch = (const uint64_t)(116444736000000000); int gettimeofday( timeval * tp, void * tzp) { FILETIME file_time; SYSTEMTIME system_time; ULARGE_INTEGER ularge; GetSystemTime(&system_time); SystemTimeToFileTime(&system_time, &file_time); ularge.LowPart = file_time.dwLowDateTime; ularge.HighPart = file_time.dwHighDateTime; tp->tv_sec = (long)((ularge.QuadPart - epoch) / 10000000L); tp->tv_usec = (long)(system_time.wMilliseconds * 1000); return 0; } #endif int getclock(struct timeval *tv) { #ifdef CLOCK_MONOTONIC struct timespec ts; if (!clock_gettime(CLOCK_MONOTONIC, &ts)) { tv->tv_sec = ts.tv_sec; tv->tv_usec = ts.tv_nsec / 1000; return 0; } #endif return gettimeofday(tv, NULL); } int timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } const char *szInsecureArgumentOptions[] = { "import", "socket", "process", "os", "|", ";", "&", "$", "<", ">", "`", "\n", "\r", NULL }; bool IsArgumentSecure(const std::string &arg) { std::string larg(arg); std::transform(larg.begin(), larg.end(), larg.begin(), ::tolower); int ii = 0; while (szInsecureArgumentOptions[ii] != NULL) { if (larg.find(szInsecureArgumentOptions[ii]) != std::string::npos) return false; ii++; } return true; } uint32_t SystemUptime() { #if defined(WIN32) return static_cast<uint32_t>(GetTickCount64() / 1000u); #elif defined(__linux__) || defined(__linux) || defined(linux) struct sysinfo info; if (sysinfo(&info) != 0) return -1; return info.uptime; #elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) struct timeval boottime; std::size_t len = sizeof(boottime); int mib[2] = { CTL_KERN, KERN_BOOTTIME }; if (sysctl(mib, 2, &boottime, &len, NULL, 0) < 0) return -1; return time(NULL) - boottime.tv_sec; #elif (defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) && defined(CLOCK_UPTIME) struct timespec ts; if (clock_gettime(CLOCK_UPTIME, &ts) != 0) return -1; return ts.tv_sec; #else return 0; #endif } // True random number generator (source: http://www.azillionmonkeys.com/qed/random.html) static struct { int which; time_t t; clock_t c; int counter; } entropy = { 0, (time_t) 0, (clock_t) 0, 0 }; static unsigned char * p = (unsigned char *) (&entropy + 1); static int accSeed = 0; int GenerateRandomNumber(const int range) { if (p == ((unsigned char *) (&entropy + 1))) { switch (entropy.which) { case 0: entropy.t += time (NULL); accSeed ^= entropy.t; break; case 1: entropy.c += clock(); break; case 2: entropy.counter++; break; } entropy.which = (entropy.which + 1) % 3; p = (unsigned char *) &entropy.t; } accSeed = ((accSeed * (UCHAR_MAX + 2U)) | 1) + (int) *p; p++; srand (accSeed); return (rand() / (RAND_MAX / range)); } int GetDirFilesRecursive(const std::string &DirPath, std::map<std::string, int> &_Files) { DIR* dir; if ((dir = opendir(DirPath.c_str())) != NULL) { struct dirent *ent; while ((ent = readdir(dir)) != NULL) { if (dirent_is_directory(DirPath, ent)) { if ((strcmp(ent->d_name, ".") != 0) && (strcmp(ent->d_name, "..") != 0) && (strcmp(ent->d_name, ".svn") != 0)) { std::string nextdir = DirPath + ent->d_name + "/"; if (GetDirFilesRecursive(nextdir.c_str(), _Files)) { closedir(dir); return 1; } } } else { std::string fname = DirPath + ent->d_name; _Files[fname] = 1; } } } closedir(dir); return 0; } #ifdef WIN32 // From https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx const DWORD MS_VC_EXCEPTION = 0x406D1388; #pragma pack(push,8) typedef struct tagTHREADNAME_INFO { DWORD dwType; // Must be 0x1000. LPCSTR szName; // Pointer to name (in user addr space). DWORD dwThreadID; // Thread ID (-1=caller thread). DWORD dwFlags; // Reserved for future use, must be zero. } THREADNAME_INFO; #pragma pack(pop) int SetThreadName(const std::thread::native_handle_type &thread, const char* threadName) { DWORD dwThreadID = ::GetThreadId( static_cast<HANDLE>( thread ) ); THREADNAME_INFO info; info.dwType = 0x1000; info.szName = threadName; info.dwThreadID = dwThreadID; info.dwFlags = 0; #pragma warning(push) #pragma warning(disable: 6320 6322) __try{ RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info); } __except (EXCEPTION_EXECUTE_HANDLER){ } #pragma warning(pop) return 0; } #else // Based on https://stackoverflow.com/questions/2369738/how-to-set-the-name-of-a-thread-in-linux-pthreads int SetThreadName(const std::thread::native_handle_type &thread, const char *name) { #if defined(__linux__) || defined(__linux) || defined(linux) char name_trunc[16]; strncpy(name_trunc, name, sizeof(name_trunc)); name_trunc[sizeof(name_trunc)-1] = '\0'; return pthread_setname_np(thread, name_trunc); #elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) // Not possible to set name of other thread: https://stackoverflow.com/questions/2369738/how-to-set-the-name-of-a-thread-in-linux-pthreads return 0; #elif defined(__NetBSD__) char name_trunc[PTHREAD_MAX_NAMELEN_NP]; strncpy(name_trunc, name, sizeof(name_trunc)); name_trunc[sizeof(name_trunc)-1] = '\0'; return pthread_setname_np(thread, "%s", (void *)name_trunc); #elif defined(__OpenBSD__) || defined(__DragonFly__) char name_trunc[PTHREAD_MAX_NAMELEN_NP]; strncpy(name_trunc, name, sizeof(name_trunc)); name_trunc[sizeof(name_trunc)-1] = '\0'; pthread_setname_np(thread, name_trunc); return 0; #elif defined(__FreeBSD__) char name_trunc[PTHREAD_MAX_NAMELEN_NP]; strncpy(name_trunc, name, sizeof(name_trunc)); name_trunc[sizeof(name_trunc)-1] = '\0'; pthread_set_name_np(thread, name_trunc); return 0; #endif } #endif #if !defined(WIN32) bool IsDebuggerPresent(void) { #if defined(__linux__) // Linux implementation: Search for 'TracerPid:' in /proc/self/status char buf[4096]; const int status_fd = ::open("/proc/self/status", O_RDONLY); if (status_fd == -1) return false; const ssize_t num_read = ::read(status_fd, buf, sizeof(buf) - 1); if (num_read <= 0) return false; buf[num_read] = '\0'; constexpr char tracerPidString[] = "TracerPid:"; const auto tracer_pid_ptr = ::strstr(buf, tracerPidString); if (!tracer_pid_ptr) return false; for (const char* characterPtr = tracer_pid_ptr + sizeof(tracerPidString) - 1; characterPtr <= buf + num_read; ++characterPtr) { if (::isspace(*characterPtr)) continue; else return ::isdigit(*characterPtr) != 0 && *characterPtr != '0'; } return false; #else // MacOS X / BSD: TODO # ifdef _DEBUG return true; # else return false; # endif #endif } #endif #if defined(__linux__) bool IsWSL(void) { // Detect WSL according to https://github.com/Microsoft/WSL/issues/423#issuecomment-221627364 bool is_wsl = false; char buf[1024]; int status_fd = open("/proc/sys/kernel/osrelease", O_RDONLY); if (status_fd == -1) return is_wsl; ssize_t num_read = read(status_fd, buf, sizeof(buf) - 1); if (num_read > 0) { buf[num_read] = 0; is_wsl |= (strstr(buf, "Microsoft") != NULL); is_wsl |= (strstr(buf, "WSL") != NULL); } status_fd = open("/proc/version", O_RDONLY); if (status_fd == -1) return is_wsl; num_read = read(status_fd, buf, sizeof(buf) - 1); if (num_read > 0) { buf[num_read] = 0; is_wsl |= (strstr(buf, "Microsoft") != NULL); is_wsl |= (strstr(buf, "WSL") != NULL); } return is_wsl; } #endif const std::string hexCHARS = "0123456789abcdef"; std::string GenerateUUID() // DCE/RFC 4122 { std::string uuid = std::string(36, ' '); uuid[8] = '-'; uuid[13] = '-'; uuid[14] = '4'; //M uuid[18] = '-'; //uuid[19] = ' '; //N Variant 1 UUIDs (10xx N=8..b, 2 bits) uuid[23] = '-'; for (size_t ii = 0; ii < uuid.size(); ii++) { if (uuid[ii] == ' ') { uuid[ii] = hexCHARS[(ii == 19) ? (8 + (std::rand() & 0x03)) : std::rand() & 0x0F]; } } return uuid; }
gpl-3.0
CLAMP-IT/LAE
mod/quiz/report/overview/overview_table.php
14190
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * This file defines the quiz grades table. * * @package quiz * @subpackage overview * @copyright 2008 Jamie Pratt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * This is a table subclass for displaying the quiz grades report. * * @copyright 2008 Jamie Pratt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class quiz_report_overview_table extends quiz_attempt_report_table { protected $candelete; protected $regradedqs = array(); public function __construct($quiz, $context, $qmsubselect, $groupstudents, $students, $detailedmarks, $questions, $candelete, $reporturl, $displayoptions) { parent::__construct('mod-quiz-report-overview-report', $quiz , $context, $qmsubselect, $groupstudents, $students, $questions, $candelete, $reporturl, $displayoptions); $this->detailedmarks = $detailedmarks; } public function build_table() { global $DB; if ($this->rawdata) { $this->strtimeformat = str_replace(',', '', get_string('strftimedatetime')); parent::build_table(); //end of adding data from attempts data to table / download //now add averages at bottom of table : $params = array($this->quiz->id); $averagesql = ' SELECT AVG(qg.grade) AS grade, COUNT(qg.grade) AS numaveraged FROM {quiz_grades} qg WHERE quiz = ?'; $this->add_separator(); if ($this->is_downloading()) { $namekey = 'lastname'; } else { $namekey = 'fullname'; } if ($this->groupstudents) { list($usql, $uparams) = $DB->get_in_or_equal($this->groupstudents); $record = $DB->get_record_sql($averagesql . ' AND qg.userid ' . $usql, array_merge($params, $uparams)); $groupaveragerow = array( $namekey => get_string('groupavg', 'grades'), 'sumgrades' => $this->format_average($record), 'feedbacktext'=> strip_tags(quiz_report_feedback_for_grade( $record->grade, $this->quiz->id))); if ($this->detailedmarks && ($this->quiz->attempts == 1 || $this->qmsubselect)) { $avggradebyq = $this->load_average_question_grades($this->groupstudents); $groupaveragerow += $this->format_average_grade_for_questions($avggradebyq); } $this->add_data_keyed($groupaveragerow); } if ($this->students) { list($usql, $uparams) = $DB->get_in_or_equal($this->students); $record = $DB->get_record_sql($averagesql . ' AND qg.userid ' . $usql, array_merge($params, $uparams)); $overallaveragerow = array( $namekey => get_string('overallaverage', 'grades'), 'sumgrades' => $this->format_average($record), 'feedbacktext'=> strip_tags(quiz_report_feedback_for_grade( $record->grade, $this->quiz->id, $this->context))); if ($this->detailedmarks && ($this->quiz->attempts == 1 || $this->qmsubselect)) { $avggradebyq = $this->load_average_question_grades($this->students); $overallaveragerow += $this->format_average_grade_for_questions($avggradebyq); } $this->add_data_keyed($overallaveragerow); } } } protected function format_average_grade_for_questions($gradeaverages) { $row = array(); if (!$gradeaverages) { $gradeaverages = array(); } foreach ($this->questions as $question) { if (isset($gradeaverages[$question->slot]) && $question->maxmark > 0) { $record = $gradeaverages[$question->slot]; $record->grade = quiz_rescale_grade( $record->averagefraction * $question->maxmark, $this->quiz, false); } else { $record = new stdClass(); $record->grade = null; $record->numaveraged = null; } $row['qsgrade' . $question->slot] = $this->format_average($record, true); } return $row; } /** * Format an entry in an average row. * @param object $record with fields grade and numaveraged */ protected function format_average($record, $question = false) { if (is_null($record->grade)) { $average = '-'; } else if ($question) { $average = quiz_format_question_grade($this->quiz, $record->grade); } else { $average = quiz_format_grade($this->quiz, $record->grade); } if ($this->download) { return $average; } else if (is_null($record->numaveraged)) { return html_writer::tag('span', html_writer::tag('span', $average, array('class' => 'average')), array('class' => 'avgcell')); } else { return html_writer::tag('span', html_writer::tag('span', $average, array('class' => 'average')) . ' ' . html_writer::tag('span', '(' . $record->numaveraged . ')', array('class' => 'count')), array('class' => 'avgcell')); } } public function wrap_html_start() { if ($this->is_downloading() || !$this->candelete) { return; } // Start form $url = new moodle_url($this->reporturl, $this->displayoptions + array('sesskey' => sesskey())); echo '<div id="tablecontainer" class="overview-tablecontainer">'; echo '<form id="attemptsform" method="post" action="' . $this->reporturl->out_omit_querystring() . '">'; echo '<div style="display: none;">'; echo html_writer::input_hidden_params($url); echo '</div>'; echo '<div>'; } public function wrap_html_finish() { if ($this->is_downloading() || !$this->candelete) { return; } // TODO add back are you sure, and convert to html_writer. echo '<div id="commands">'; echo '<a href="javascript:select_all_in(\'DIV\', null, \'tablecontainer\');">' . get_string('selectall', 'quiz') . '</a> / '; echo '<a href="javascript:deselect_all_in(\'DIV\', null, \'tablecontainer\');">' . get_string('selectnone', 'quiz') . '</a> '; echo '&nbsp;&nbsp;'; if (has_capability('mod/quiz:regrade', $this->context)) { echo '<input type="submit" name="regrade" value="' . get_string('regradeselected', 'quiz_overview') . '"/>'; } echo '<input type="submit" name="delete" value="' . get_string('deleteselected', 'quiz_overview') . '"/>'; echo '</div>'; // Close form echo '</div>'; echo '</form></div>'; } public function col_sumgrades($attempt) { if (!$attempt->timefinish) { return '-'; } $grade = quiz_rescale_grade($attempt->sumgrades, $this->quiz); if ($this->is_downloading()) { return $grade; } if (isset($this->regradedqs[$attempt->usageid])) { $newsumgrade = 0; $oldsumgrade = 0; foreach ($this->questions as $question) { if (isset($this->regradedqs[$attempt->usageid][$question->slot])) { $newsumgrade += $this->regradedqs[$attempt->usageid] [$question->slot]->newfraction * $question->maxmark; $oldsumgrade += $this->regradedqs[$attempt->usageid] [$question->slot]->oldfraction * $question->maxmark; } else { $newsumgrade += $this->lateststeps[$attempt->usageid] [$question->slot]->fraction * $question->maxmark; $oldsumgrade += $this->lateststeps[$attempt->usageid] [$question->slot]->fraction * $question->maxmark; } } $newsumgrade = quiz_rescale_grade($newsumgrade, $this->quiz); $oldsumgrade = quiz_rescale_grade($oldsumgrade, $this->quiz); $grade = html_writer::tag('del', $oldsumgrade) . '/' . html_writer::empty_tag('br') . $newsumgrade; } return html_writer::link(new moodle_url('/mod/quiz/review.php', array('attempt' => $attempt->attempt)), $grade, array('title' => get_string('reviewattempt', 'quiz'))); } /** * @param string $colname the name of the column. * @param object $attempt the row of data - see the SQL in display() in * mod/quiz/report/overview/report.php to see what fields are present, * and what they are called. * @return string the contents of the cell. */ public function other_cols($colname, $attempt) { if (!preg_match('/^qsgrade(\d+)$/', $colname, $matches)) { return null; } $slot = $matches[1]; $question = $this->questions[$slot]; if (!isset($this->lateststeps[$attempt->usageid][$slot])) { return '-'; } $stepdata = $this->lateststeps[$attempt->usageid][$slot]; $state = question_state::get($stepdata->state); if ($question->maxmark == 0) { $grade = '-'; } else if (is_null($stepdata->fraction)) { if ($state == question_state::$needsgrading) { $grade = get_string('requiresgrading', 'question'); } else { $grade = '-'; } } else { $grade = quiz_rescale_grade( $stepdata->fraction * $question->maxmark, $this->quiz, 'question'); } if ($this->is_downloading()) { return $grade; } if (isset($this->regradedqs[$attempt->usageid][$slot])) { $gradefromdb = $grade; $newgrade = quiz_rescale_grade( $this->regradedqs[$attempt->usageid][$slot]->newfraction * $question->maxmark, $this->quiz, 'question'); $oldgrade = quiz_rescale_grade( $this->regradedqs[$attempt->usageid][$slot]->oldfraction * $question->maxmark, $this->quiz, 'question'); $grade = html_writer::tag('del', $oldgrade) . '/' . html_writer::empty_tag('br') . $newgrade; } return $this->make_review_link($grade, $attempt, $slot); } public function col_regraded($attempt) { if ($attempt->regraded == '') { return ''; } else if ($attempt->regraded == 0) { return get_string('needed', 'quiz_overview'); } else if ($attempt->regraded == 1) { return get_string('done', 'quiz_overview'); } } protected function requires_latest_steps_loaded() { return $this->detailedmarks; } protected function is_latest_step_column($column) { if (preg_match('/^qsgrade([0-9]+)/', $column, $matches)) { return $matches[1]; } return false; } protected function get_required_latest_state_fields($slot, $alias) { return "$alias.fraction * $alias.maxmark AS qsgrade$slot"; } public function query_db($pagesize, $useinitialsbar = true) { parent::query_db($pagesize, $useinitialsbar); if ($this->detailedmarks && has_capability('mod/quiz:regrade', $this->context)) { $this->regradedqs = $this->get_regraded_questions(); } } /** * Load the average grade for each question, averaged over particular users. * @param array $userids the user ids to average over. */ protected function load_average_question_grades($userids) { global $DB; $qmfilter = ''; if ($this->quiz->attempts != 1) { $qmfilter = '(' . quiz_report_qm_filter_select($this->quiz, 'quiza') . ') AND '; } list($usql, $params) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'u'); $params['quizid'] = $this->quiz->id; $qubaids = new qubaid_join( '{quiz_attempts} quiza', 'quiza.uniqueid', "quiza.userid $usql AND quiza.quiz = :quizid", $params); $dm = new question_engine_data_mapper(); return $dm->load_average_marks($qubaids, array_keys($this->questions)); } /** * Get all the questions in all the attempts being displayed that need regrading. * @return array A two dimensional array $questionusageid => $slot => $regradeinfo. */ protected function get_regraded_questions() { global $DB; $qubaids = $this->get_qubaids_condition(); $regradedqs = $DB->get_records_select('quiz_overview_regrades', 'questionusageid ' . $qubaids->usage_id_in(), $qubaids->usage_id_in_params()); return quiz_report_index_by_keys($regradedqs, array('questionusageid', 'slot')); } }
gpl-3.0
srnsw/xena
xena/ext/src/xalan-j_2_7_1/src/org/apache/xalan/xsltc/compiler/util/NodeSortRecordFactGenerator.java
1573
/* * 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. */ /* * $Id$ */ package org.apache.xalan.xsltc.compiler.util; import org.apache.xalan.xsltc.compiler.Stylesheet; /** * Generator for subclasses of NodeSortRecordFactory. * @author Santiago Pericas-Geertsen */ public final class NodeSortRecordFactGenerator extends ClassGenerator { public NodeSortRecordFactGenerator(String className, String superClassName, String fileName, int accessFlags, String[] interfaces, Stylesheet stylesheet) { super(className, superClassName, fileName, accessFlags, interfaces, stylesheet); } /** * Returns <tt>true</tt> since this class is external to the * translet. */ public boolean isExternal() { return true; } }
gpl-3.0
sirromas/lms
node_modules/cssproc/lib/index.js
2429
/* Copyright (c) 2012, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://yuilibrary.com/license/ */ var path = require('path'), url = require('url'); // url(../../foo.png) var URL_REGEX = "(?:(url\\s*\\(\\s*)([^\\s\\)]+))"; // AlphaImageLoader(src='picker_mask.png') var ALPHA_IMAGE_LOADER_REGEX = "(?:(AlphaImageLoader\\s*\\(\\s*src\\=)([^,\\s\\)]+))|(?:(AlphaImageLoader\\s*\\(.*?src\\=)([^,\\s\\)]+))"; var REGEX_FIND = new RegExp(URL_REGEX + '|' + ALPHA_IMAGE_LOADER_REGEX, 'gim'); var REGEX_PARSE = new RegExp(URL_REGEX + '|' + ALPHA_IMAGE_LOADER_REGEX, 'i'); var getBase = function(base, state) { if (base instanceof Array) { var length = base.length; if (state.index === length - 1) { state.index = 0; } else { state.index++; } return base[state.index]; } else { return base; } }; var normalize = function(options, str, m, state) { var top, resolved, relative, URI, quote, item, baseItem = m[0]; item = m[6] || m[4] || m[2]; quote = item.substr(0, 1); if (quote && (quote === '"' || quote === "'")) { item = item.substr(1); item = item.substr(0, item.length - 1); } if (!item.match(/^https?:\/\//) && !item.match(/^\/\//) && (item.indexOf('.') > -1)) { URI = url.parse(getBase(options.base, state), false, true); top = path.dirname(options.path); resolved = path.resolve(top, item); relative = resolved; if (item.charAt(0) !== '/') { relative = path.relative(options.root, resolved); } // Windows root directory handling. if (process.platform === 'win32' && relative.substr(1, 2) === ':\\') { relative = relative.substr(2); } expanded = (URI.protocol || '') + (URI.hostname ? '//' + URI.hostname : '') + path.join(URI.pathname, relative).replace(/\\\\|\\/g, '/'); str = str.replace(baseItem, baseItem.replace(item, expanded)); } return str; }; exports.parse = function(options, str, callback) { var items = str.match(REGEX_FIND), state = { index: -1 }; if (Array.isArray(items)) { items.forEach(function(matcher) { var m = matcher.match(REGEX_PARSE); str = normalize(options, str, m, state); }); } callback(null, str); };
gpl-3.0
AssociazionePrometeo/giano
vendor/bjeavons/zxcvbn-php/test/bootstrap.php
311
<?php $autoloadFile = __DIR__ . '/../vendor/autoload.php'; if (!file_exists($autoloadFile)) { throw new RuntimeException('Install dependencies to run test suite.'); } require_once $autoloadFile; $loader = new \Composer\Autoload\ClassLoader(); $loader->add('ZxcvbnPhp\Test', 'test'); $loader->register();
gpl-3.0
omeka/omeka-s
application/src/Permissions/Exception/RuntimeException.php
129
<?php namespace Omeka\Permissions\Exception; class RuntimeException extends \RuntimeException implements ExceptionInterface { }
gpl-3.0
kvakulo/Switcheroo
Core/Matchers/IndividualCharactersMatcher.cs
2077
using System.Text.RegularExpressions; namespace Switcheroo.Core.Matchers { public class IndividualCharactersMatcher : IMatcher { public MatchResult Evaluate(string input, string pattern) { if (input == null || pattern == null) { return NonMatchResult(input); } var regexPattern = BuildRegexPattern(pattern); var match = Regex.Match(input, regexPattern, RegexOptions.IgnoreCase); if (!match.Success) { return NonMatchResult(input); } var matchResult = new MatchResult(); for (var groupIndex = 1; groupIndex < match.Groups.Count; groupIndex++) { var group = match.Groups[groupIndex]; if (group.Value.Length > 0) { matchResult.StringParts.Add(new StringPart(group.Value, groupIndex%2 == 0)); } } matchResult.Matched = true; matchResult.Score = 1; return matchResult; } private static string BuildRegexPattern(string pattern) { var regexPattern = ""; char? previousChar = null; foreach (var p in pattern) { if (previousChar != null) { regexPattern += string.Format("([^{0}]*?)({1})", Regex.Escape(previousChar + ""), Regex.Escape(p + "")); } else { regexPattern += string.Format("(.*?)({0})", Regex.Escape(p + "")); } previousChar = p; } return regexPattern + "(.*)"; } private static MatchResult NonMatchResult(string input) { var matchResult = new MatchResult(); if (input != null) { matchResult.StringParts.Add(new StringPart(input)); } return matchResult; } } }
gpl-3.0
Tutul-/POL-POM-5
phoenicis-library/src/main/java/org/phoenicis/library/ShortcutRunner.java
2982
/* * Copyright (C) 2015-2017 PÂRIS Quentin * * 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., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.phoenicis.library; import org.phoenicis.library.dto.ShortcutDTO; import org.phoenicis.scripts.interpreter.InteractiveScriptSession; import org.phoenicis.scripts.interpreter.ScriptInterpreter; import jdk.nashorn.api.scripting.ScriptObjectMirror; import java.util.List; import java.util.function.Consumer; public class ShortcutRunner { private final ScriptInterpreter scriptInterpreter; private final LibraryManager libraryManager; public ShortcutRunner(ScriptInterpreter scriptInterpreter, LibraryManager libraryManager) { this.scriptInterpreter = scriptInterpreter; this.libraryManager = libraryManager; } public void run(String shortcutName, List<String> arguments, Consumer<Exception> errorCallback) { run(libraryManager.fetchShortcutsFromName(shortcutName), arguments, errorCallback); } public void run(ShortcutDTO shortcutDTO, List<String> arguments, Consumer<Exception> errorCallback) { final InteractiveScriptSession interactiveScriptSession = scriptInterpreter.createInteractiveSession(); interactiveScriptSession.eval("include([\"Engines\", \"Wine\", \"Shortcuts\", \"Reader\"]);", ignored -> interactiveScriptSession.eval("new ShortcutReader()", output -> { final ScriptObjectMirror shortcutReader = (ScriptObjectMirror) output; shortcutReader.callMember("of", shortcutDTO); shortcutReader.callMember("run", arguments); }, errorCallback), errorCallback); } public void stop(ShortcutDTO shortcutDTO, Consumer<Exception> errorCallback) { final InteractiveScriptSession interactiveScriptSession = scriptInterpreter.createInteractiveSession(); interactiveScriptSession.eval("include([\"Engines\", \"Wine\", \"Shortcuts\", \"Reader\"]);", ignored -> interactiveScriptSession.eval("new ShortcutReader()", output -> { final ScriptObjectMirror shortcutReader = (ScriptObjectMirror) output; shortcutReader.callMember("of", shortcutDTO); shortcutReader.callMember("stop"); }, errorCallback), errorCallback); } }
gpl-3.0
WordBenchNagoya/WordFes2017
wp/wp-content/themes/wfn2016/parts/content-archive.php
1075
<?php if ( is_home() ) { $dummy = get_template_directory_uri() . '/images/common/dummy-blog.png'; } else { $dummy = get_template_directory_uri() . '/images/common/dummy-topics.png'; } $thumb = pdc_get_post_thumbnail( get_the_ID(), $dummy ); $excerpt = pdc_get_excerpt( get_the_content(), 86 ); ?> <article class="section-inner text-left clearfix"> <div class="image-box col-xs-12 col-sm-3"> <img src="<?php echo esc_url( $thumb[0] ); ?>" alt="サムネール:<?php the_title(); ?>"> </div> <div class="text-box col-xs-12 col-sm-9"> <h2 class="clearfix"> <span class="date"><?php the_time('Y.n.j'); ?></span> <span class="title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></span> </h2> <p> <?php echo esc_html( $excerpt ); ?> <span>… <a href="<?php the_permalink(); ?>">続きを読む</a></span> </p> </div> </article><!-- .section-inner -->
gpl-3.0
FAIMS/faims-android
faimsandroidapp/src/main/java/org/gdal/gdalconst/gdalconst.java
528
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.4 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package org.gdal.gdalconst; public class gdalconst implements gdalconstConstants { /* Uninstanciable class */ private gdalconst() { } }
gpl-3.0
wyang651510708/yc
src/org/qii/weiciyuan/support/database/draftbean/ReplyDraftBean.java
2071
package org.qii.weiciyuan.support.database.draftbean; import org.qii.weiciyuan.bean.CommentBean; import android.os.Parcel; import android.os.Parcelable; /** * User: qii * Date: 12-10-21 */ public class ReplyDraftBean implements Parcelable { private String content; private String accountId; private CommentBean commentBean; private String id; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(content); dest.writeString(accountId); dest.writeParcelable(commentBean, flags); dest.writeString(id); } public static final Parcelable.Creator<ReplyDraftBean> CREATOR = new Parcelable.Creator<ReplyDraftBean>() { public ReplyDraftBean createFromParcel(Parcel in) { ReplyDraftBean replyDraftBean = new ReplyDraftBean(); replyDraftBean.content = in.readString(); replyDraftBean.accountId = in.readString(); replyDraftBean.commentBean = in .readParcelable(CommentBean.class.getClassLoader()); replyDraftBean.id = in.readString(); return replyDraftBean; } public ReplyDraftBean[] newArray(int size) { return new ReplyDraftBean[size]; } }; public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public CommentBean getCommentBean() { return commentBean; } public void setCommentBean(CommentBean commentBean) { this.commentBean = commentBean; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
gpl-3.0
grebaldi/PackageFactory.Guevara
packages/neos-ui-views/src/Data/ColumnView/index.js
1742
import React, {PureComponent} from 'react'; import PropTypes from 'prop-types'; import {$get} from 'plow-js'; import style from './style.css'; import dataLoader from '../DataLoader/index'; import Hero from './hero'; import Column from './column'; @dataLoader() export default class ColumnView extends PureComponent { static propTypes = { data: PropTypes.object.isRequired, options: PropTypes.shape({ hero: PropTypes.object, columns: PropTypes.array }).isRequired } getHero() { const {options, data} = this.props; if (options.hero) { return { label: options.hero.label, value: $get(options.hero.data, data) }; } return null; } getColumns() { const {options, data} = this.props; const columns = []; if (options.columns) { options.columns.forEach(column => { columns.push({ label: column.label, value: $get(column.data, data) }); }); } return columns; } render() { const hero = this.getHero(); const columns = this.getColumns(); return ( <div> {hero && <Hero label={hero.label} value={hero.value}/>} <div className={style.columnsWrap}> {columns.map((column, key) => ( <Column key={key} value={column.value} label={column.label} /> ))} </div> </div> ); } }
gpl-3.0
Mikezar/STW6
ScrewTurnWiki.AzureStorageProviders.Tests/Properties/AssemblyInfo.cs
1458
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AzureTableStorageProviders-Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("AzureTableStorageProviders-Tests")] [assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c99d598a-17c2-4a62-984e-098752f17cfe")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
gpl-3.0
KAMI911/loec
examples/Sharpen/binaries-windows-python25/XVThumbImagePlugin.py
1795
# # The Python Imaging Library. # $Id: XVThumbImagePlugin.py 2134 2004-10-06 08:55:20Z fredrik $ # # XV Thumbnail file handler by Charles E. "Gene" Cash # (gcash@magicnet.net) # # see xvcolor.c and xvbrowse.c in the sources to John Bradley's XV, # available from ftp://ftp.cis.upenn.edu/pub/xv/ # # history: # 98-08-15 cec created (b/w only) # 98-12-09 cec added color palette # 98-12-28 fl added to PIL (with only a few very minor modifications) # # To do: # FIXME: make save work (this requires quantization support) # __version__ = "0.1" import string import Image, ImageFile, ImagePalette # standard color palette for thumbnails (RGB332) PALETTE = "" for r in range(8): for g in range(8): for b in range(4): PALETTE = PALETTE + (chr((r*255)/7)+chr((g*255)/7)+chr((b*255)/3)) ## # Image plugin for XV thumbnail images. class XVThumbImageFile(ImageFile.ImageFile): format = "XVThumb" format_description = "XV thumbnail image" def _open(self): # check magic s = self.fp.read(6) if s != "P7 332": raise SyntaxError, "not an XV thumbnail file" # skip info comments while 1: s = string.strip(self.fp.readline()) if s == "#END_OF_COMMENTS": break # read header line s = string.split(self.fp.readline()) self.mode = "P" self.size = int(s[0]), int(s[1]) self.palette = ImagePalette.raw("RGB", PALETTE) self.tile = [ ("raw", (0, 0)+self.size, self.fp.tell(), (self.mode, 0, 1) )] # -------------------------------------------------------------------- Image.register_open("XVThumb", XVThumbImageFile)
gpl-3.0
Venisir/Twilight-Whispers
Assets/RainMaker/Prefab/BaseRainScript.cs
13322
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace DigitalRuby.RainMaker { public class BaseRainScript : MonoBehaviour { [Tooltip("Camera the rain should hover over, defaults to main camera")] public Camera Camera; [Tooltip("Whether rain should follow the camera. If false, rain must be moved manually and will not follow the camera.")] public bool FollowCamera = true; [Tooltip("Light rain looping clip")] public AudioClip RainSoundLight; [Tooltip("Medium rain looping clip")] public AudioClip RainSoundMedium; [Tooltip("Heavy rain looping clip")] public AudioClip RainSoundHeavy; [Tooltip("Intensity of rain (0-1)")] [Range(0.0f, 1.0f)] public float RainIntensity; [Tooltip("Rain particle system")] public ParticleSystem RainFallParticleSystem; [Tooltip("Particles system for when rain hits something")] public ParticleSystem RainExplosionParticleSystem; [Tooltip("Particle system to use for rain mist")] public ParticleSystem RainMistParticleSystem; [Tooltip("The threshold for intensity (0 - 1) at which mist starts to appear")] [Range(0.0f, 1.0f)] public float RainMistThreshold = 0.5f; [Tooltip("Wind looping clip")] public AudioClip WindSound; [Tooltip("Wind sound volume modifier, use this to lower your sound if it's too loud.")] public float WindSoundVolumeModifier = 0.5f; [Tooltip("Wind zone that will affect and follow the rain")] public WindZone WindZone; [Tooltip("X = minimum wind speed. Y = maximum wind speed. Z = sound multiplier. Wind speed is divided by Z to get sound multiplier value. Set Z to lower than Y to increase wind sound volume, or higher to decrease wind sound volume.")] public Vector3 WindSpeedRange = new Vector3(50.0f, 500.0f, 500.0f); [Tooltip("How often the wind speed and direction changes (minimum and maximum change interval in seconds)")] public Vector2 WindChangeInterval = new Vector2(5.0f, 30.0f); [Tooltip("Whether wind should be enabled.")] public bool EnableWind = true; protected LoopingAudioSource audioSourceRainLight; protected LoopingAudioSource audioSourceRainMedium; protected LoopingAudioSource audioSourceRainHeavy; protected LoopingAudioSource audioSourceRainCurrent; protected LoopingAudioSource audioSourceWind; protected Material rainMaterial; protected Material rainExplosionMaterial; protected Material rainMistMaterial; private float lastRainIntensityValue = -1.0f; private float nextWindTime; private void UpdateWind() { if (EnableWind && WindZone != null && WindSpeedRange.y > 1.0f) { WindZone.gameObject.SetActive(true); if (FollowCamera) { WindZone.transform.position = Camera.transform.position; } if (!Camera.orthographic) { WindZone.transform.Translate(0.0f, WindZone.radius, 0.0f); } if (nextWindTime < Time.time) { WindZone.windMain = UnityEngine.Random.Range(WindSpeedRange.x, WindSpeedRange.y); WindZone.windTurbulence = UnityEngine.Random.Range(WindSpeedRange.x, WindSpeedRange.y); if (Camera.orthographic) { int val = UnityEngine.Random.Range(0, 2); WindZone.transform.rotation = Quaternion.Euler(0.0f, (val == 0 ? 90.0f : -90.0f), 0.0f); } else { WindZone.transform.rotation = Quaternion.Euler(UnityEngine.Random.Range(-30.0f, 30.0f), UnityEngine.Random.Range(0.0f, 360.0f), 0.0f); } nextWindTime = Time.time + UnityEngine.Random.Range(WindChangeInterval.x, WindChangeInterval.y); audioSourceWind.Play((WindZone.windMain / WindSpeedRange.z) * WindSoundVolumeModifier); } } else { if (WindZone != null) { WindZone.gameObject.SetActive(false); } audioSourceWind.Stop(); } audioSourceWind.Update(); } private void CheckForRainChange() { if (lastRainIntensityValue != RainIntensity) { lastRainIntensityValue = RainIntensity; if (RainIntensity <= 0.01f) { if (audioSourceRainCurrent != null) { audioSourceRainCurrent.Stop(); audioSourceRainCurrent = null; } if (RainFallParticleSystem != null) { ParticleSystem.EmissionModule e = RainFallParticleSystem.emission; e.enabled = false; RainFallParticleSystem.Stop(); } if (RainMistParticleSystem != null) { ParticleSystem.EmissionModule e = RainMistParticleSystem.emission; e.enabled = false; RainMistParticleSystem.Stop(); } } else { LoopingAudioSource newSource; if (RainIntensity >= 0.67f) { newSource = audioSourceRainHeavy; } else if (RainIntensity >= 0.33f) { newSource = audioSourceRainMedium; } else { newSource = audioSourceRainLight; } if (audioSourceRainCurrent != newSource) { if (audioSourceRainCurrent != null) { audioSourceRainCurrent.Stop(); } audioSourceRainCurrent = newSource; audioSourceRainCurrent.Play(1.0f); } if (RainFallParticleSystem != null) { ParticleSystem.EmissionModule e = RainFallParticleSystem.emission; e.enabled = RainFallParticleSystem.GetComponent<Renderer>().enabled = true; if (!RainFallParticleSystem.isPlaying) { RainFallParticleSystem.Play(); } ParticleSystem.MinMaxCurve rate = e.rateOverTime; rate.mode = ParticleSystemCurveMode.Constant; rate.constantMin = rate.constantMax = RainFallEmissionRate(); e.rateOverTime = rate; } if (RainMistParticleSystem != null) { ParticleSystem.EmissionModule e = RainMistParticleSystem.emission; e.enabled = RainMistParticleSystem.GetComponent<Renderer>().enabled = true; if (!RainMistParticleSystem.isPlaying) { RainMistParticleSystem.Play(); } float emissionRate; if (RainIntensity < RainMistThreshold) { emissionRate = 0.0f; } else { // must have RainMistThreshold or higher rain intensity to start seeing mist emissionRate = MistEmissionRate(); } ParticleSystem.MinMaxCurve rate = e.rateOverTime; rate.mode = ParticleSystemCurveMode.Constant; rate.constantMin = rate.constantMax = emissionRate; e.rateOverTime = rate; } } } } protected virtual void Start() { #if DEBUG if (RainFallParticleSystem == null) { Debug.LogError("Rain fall particle system must be set to a particle system"); return; } #endif if (Camera == null) { Camera = Camera.main; } audioSourceRainLight = new LoopingAudioSource(this, RainSoundLight); audioSourceRainMedium = new LoopingAudioSource(this, RainSoundMedium); audioSourceRainHeavy = new LoopingAudioSource(this, RainSoundHeavy); audioSourceWind = new LoopingAudioSource(this, WindSound); if (RainFallParticleSystem != null) { ParticleSystem.EmissionModule e = RainFallParticleSystem.emission; e.enabled = false; Renderer rainRenderer = RainFallParticleSystem.GetComponent<Renderer>(); rainRenderer.enabled = false; rainMaterial = new Material(rainRenderer.material); rainMaterial.EnableKeyword("SOFTPARTICLES_OFF"); rainRenderer.material = rainMaterial; } if (RainExplosionParticleSystem != null) { ParticleSystem.EmissionModule e = RainExplosionParticleSystem.emission; e.enabled = false; Renderer rainRenderer = RainExplosionParticleSystem.GetComponent<Renderer>(); rainExplosionMaterial = new Material(rainRenderer.material); rainExplosionMaterial.EnableKeyword("SOFTPARTICLES_OFF"); rainRenderer.material = rainExplosionMaterial; } if (RainMistParticleSystem != null) { ParticleSystem.EmissionModule e = RainMistParticleSystem.emission; e.enabled = false; Renderer rainRenderer = RainMistParticleSystem.GetComponent<Renderer>(); rainRenderer.enabled = false; rainMistMaterial = new Material(rainRenderer.material); if (UseRainMistSoftParticles) { rainMistMaterial.EnableKeyword("SOFTPARTICLES_ON"); } else { rainMistMaterial.EnableKeyword("SOFTPARTICLES_OFF"); } rainRenderer.material = rainMistMaterial; } } protected virtual void Update() { #if DEBUG if (RainFallParticleSystem == null) { Debug.LogError("Rain fall particle system must be set to a particle system"); return; } #endif CheckForRainChange(); UpdateWind(); audioSourceRainLight.Update(); audioSourceRainMedium.Update(); audioSourceRainHeavy.Update(); } protected virtual float RainFallEmissionRate() { return (RainFallParticleSystem.main.maxParticles / RainFallParticleSystem.main.startLifetime.constant) * RainIntensity; } protected virtual float MistEmissionRate() { return (RainMistParticleSystem.main.maxParticles / RainMistParticleSystem.main.startLifetime.constant) * RainIntensity * RainIntensity; } protected virtual bool UseRainMistSoftParticles { get { return true; } } } /// <summary> /// Provides an easy wrapper to looping audio sources with nice transitions for volume when starting and stopping /// </summary> public class LoopingAudioSource { public AudioSource AudioSource { get; private set; } public float TargetVolume { get; private set; } public LoopingAudioSource(MonoBehaviour script, AudioClip clip) { AudioSource = script.gameObject.AddComponent<AudioSource>(); AudioSource.loop = true; AudioSource.clip = clip; AudioSource.playOnAwake = false; AudioSource.volume = 0.0f; AudioSource.Stop(); TargetVolume = 1.0f; } public void Play(float targetVolume) { if (!AudioSource.isPlaying) { AudioSource.volume = 0.0f; AudioSource.Play(); } TargetVolume = targetVolume; } public void Stop() { TargetVolume = 0.0f; } public void Update() { if (AudioSource.isPlaying && (AudioSource.volume = Mathf.Lerp(AudioSource.volume, TargetVolume, Time.deltaTime)) == 0.0f) { AudioSource.Stop(); } } } }
gpl-3.0
MartyParty21/AwakenDreamsClient
mcp/temp/src/minecraft/net/minecraft/client/gui/GuiScreenDemo.java
3824
package net.minecraft.client.gui; import java.io.IOException; import java.net.URI; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.resources.I18n; import net.minecraft.client.settings.GameSettings; import net.minecraft.util.ResourceLocation; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class GuiScreenDemo extends GuiScreen { private static final Logger field_146349_a = LogManager.getLogger(); private static final ResourceLocation field_146348_f = new ResourceLocation("textures/gui/demo_background.png"); public void func_73866_w_() { this.field_146292_n.clear(); int i = -16; this.field_146292_n.add(new GuiButton(1, this.field_146294_l / 2 - 116, this.field_146295_m / 2 + 62 + -16, 114, 20, I18n.func_135052_a("demo.help.buy", new Object[0]))); this.field_146292_n.add(new GuiButton(2, this.field_146294_l / 2 + 2, this.field_146295_m / 2 + 62 + -16, 114, 20, I18n.func_135052_a("demo.help.later", new Object[0]))); } protected void func_146284_a(GuiButton p_146284_1_) throws IOException { switch(p_146284_1_.field_146127_k) { case 1: p_146284_1_.field_146124_l = false; try { Class<?> oclass = Class.forName("java.awt.Desktop"); Object object = oclass.getMethod("getDesktop", new Class[0]).invoke((Object)null, new Object[0]); oclass.getMethod("browse", new Class[]{URI.class}).invoke(object, new Object[]{new URI("http://www.minecraft.net/store?source=demo")}); } catch (Throwable throwable) { field_146349_a.error("Couldn\'t open link", throwable); } break; case 2: this.field_146297_k.func_147108_a((GuiScreen)null); this.field_146297_k.func_71381_h(); } } public void func_73876_c() { super.func_73876_c(); } public void func_146276_q_() { super.func_146276_q_(); GlStateManager.func_179131_c(1.0F, 1.0F, 1.0F, 1.0F); this.field_146297_k.func_110434_K().func_110577_a(field_146348_f); int i = (this.field_146294_l - 248) / 2; int j = (this.field_146295_m - 166) / 2; this.func_73729_b(i, j, 0, 0, 248, 166); } public void func_73863_a(int p_73863_1_, int p_73863_2_, float p_73863_3_) { this.func_146276_q_(); int i = (this.field_146294_l - 248) / 2 + 10; int j = (this.field_146295_m - 166) / 2 + 8; this.field_146289_q.func_78276_b(I18n.func_135052_a("demo.help.title", new Object[0]), i, j, 2039583); j = j + 12; GameSettings gamesettings = this.field_146297_k.field_71474_y; this.field_146289_q.func_78276_b(I18n.func_135052_a("demo.help.movementShort", new Object[]{GameSettings.func_74298_c(gamesettings.field_74351_w.func_151463_i()), GameSettings.func_74298_c(gamesettings.field_74370_x.func_151463_i()), GameSettings.func_74298_c(gamesettings.field_74368_y.func_151463_i()), GameSettings.func_74298_c(gamesettings.field_74366_z.func_151463_i())}), i, j, 5197647); this.field_146289_q.func_78276_b(I18n.func_135052_a("demo.help.movementMouse", new Object[0]), i, j + 12, 5197647); this.field_146289_q.func_78276_b(I18n.func_135052_a("demo.help.jump", new Object[]{GameSettings.func_74298_c(gamesettings.field_74314_A.func_151463_i())}), i, j + 24, 5197647); this.field_146289_q.func_78276_b(I18n.func_135052_a("demo.help.inventory", new Object[]{GameSettings.func_74298_c(gamesettings.field_151445_Q.func_151463_i())}), i, j + 36, 5197647); this.field_146289_q.func_78279_b(I18n.func_135052_a("demo.help.fullWrapped", new Object[0]), i, j + 68, 218, 2039583); super.func_73863_a(p_73863_1_, p_73863_2_, p_73863_3_); } }
gpl-3.0
srnsw/xena
xena/ext/src/xalan-j_2_7_1/src/org/apache/xml/utils/DOMOrder.java
1518
/* * 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. */ /* * $Id$ */ package org.apache.xml.utils; /** * @deprecated Since the introduction of the DTM, this class will be removed. * Nodes that implement this index can return a document order index. * Eventually, this will be replaced by DOM 3 methods. * (compareDocumentOrder and/or compareTreePosition.) */ public interface DOMOrder { /** * Get the UID (document order index). * * @return integer whose relative value corresponds to document order * -- that is, if node1.getUid()<node2.getUid(), node1 comes before * node2, and if they're equal node1 and node2 are the same node. No * promises are made beyond that. */ public int getUid(); }
gpl-3.0
nado/stk-code
src/karts/kart_rewinder.hpp
2282
// // SuperTuxKart - a fun racing game with go-kart // Copyright (C) 2013 Joerg Henrichs // // 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, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef HEADER_KART_REWINDER_HPP #define HEADER_KART_REWINDER_HPP #include "graphics/render_info.hpp" #include "karts/kart.hpp" #include "network/rewinder.hpp" #include "utils/cpp2011.hpp" class AbstractKart; class BareNetworkString; class KartRewinder : public Rewinder, public Kart { private: // Flags to indicate the different event types enum { EVENT_CONTROL = 0x01, EVENT_ATTACH = 0x02 }; public: KartRewinder(const std::string& ident, unsigned int world_kart_id, int position, const btTransform& init_transform, PerPlayerDifficulty difficulty, KartRenderType krt = KRT_DEFAULT); virtual ~KartRewinder() {}; virtual BareNetworkString* saveState() const; void reset(); virtual void rewindToState(BareNetworkString *p) OVERRIDE; virtual void rewindToEvent(BareNetworkString *p) OVERRIDE; virtual void update(float dt); // ------------------------------------------------------------------------- virtual void undoState(BareNetworkString *p) OVERRIDE { }; // undoState // ------------------------------------------------------------------------- virtual void undoEvent(BareNetworkString *p) OVERRIDE { }; // undoEvent // ------------------------------------------------------------------------- }; // Rewinder #endif
gpl-3.0
bbreck3/CMSC451
src/etherlog.cpp
1728
#include "etherlog.h" #include <QDebug> #include <QSettings> #include <QApplication> #include <QClipboard> namespace Etherwall { static EtherLog* sLog = NULL; EtherLog::EtherLog() : QAbstractListModel(0), fList() { sLog = this; const QSettings settings; fLogLevel = (LogSeverity)settings.value("log/level", LS_Info).toInt(); } QHash<int, QByteArray> EtherLog::roleNames() const { QHash<int, QByteArray> roles; roles[MsgRole] = "msg"; roles[DateRole] = "date"; roles[SeverityRole] = "severity"; return roles; } int EtherLog::rowCount(const QModelIndex & parent __attribute__ ((unused))) const { return fList.length(); } QVariant EtherLog::data(const QModelIndex & index, int role) const { return fList.at(index.row()).value(role); } void EtherLog::saveToClipboard() const { QString text; foreach ( const LogInfo info, fList ) { text += (info.value(MsgRole).toString() + QString("\n")); } QApplication::clipboard()->setText(text); } void EtherLog::logMsg(const QString &msg, LogSeverity sev) { sLog->log(msg, sev); } void EtherLog::log(QString msg, LogSeverity sev) { if ( sev < fLogLevel ) { return; // skip due to severity setting } beginInsertRows(QModelIndex(), 0, 0); fList.insert(0, LogInfo(msg, sev)); endInsertRows(); } int EtherLog::getLogLevel() const { return fLogLevel; } void EtherLog::setLogLevel(int ll) { fLogLevel = (LogSeverity)ll; QSettings settings; settings.setValue("log/level", ll); } }
gpl-3.0
sapo/kyoto
kyototycoon/ktserver.cc
116444
/************************************************************************************************* * A handy cache/storage server * Copyright (C) 2009-2012 FAL Labs * This file is part of Kyoto Tycoon. * 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 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/>. *************************************************************************************************/ #include "cmdcommon.h" enum { // enumeration for operation counting CNTSET, // setting operations CNTSETMISS, // misses of setting operations CNTREMOVE, // removing operations CNTREMOVEMISS, // misses of removing operations CNTGET, // getting operations CNTGETMISS, // misses of getting operations CNTSCRIPT, // scripting operations CNTMISC // miscellaneous operations }; typedef uint64_t OpCount[CNTMISC+1]; // counters per thread // global variables const char* g_progname; // program name int32_t g_procid; // process ID number double g_starttime; // start time bool g_daemon; // daemon flag kt::RPCServer* g_serv; // running RPC server bool g_restart; // restart flag // function prototypes int main(int argc, char** argv); static void usage(); static void killserver(int signum); static int32_t run(int argc, char** argv); static int32_t proc(const std::vector<std::string>& dbpaths, const char* host, int32_t port, double tout, int32_t thnum, const char* logpath, uint32_t logkinds, const char* ulogpath, int64_t ulim, double uasi, int32_t sid, int32_t omode, double asi, bool ash, const char* bgspath, double bgsi, kc::Compressor* bgscomp, bool dmn, const char* pidpath, const char* cmdpath, const char* scrpath, const char* mhost, int32_t mport, const char* rtspath, double riv, const char* plsvpath, const char* plsvex, const char* pldbpath); static bool dosnapshot(const char* bgspath, kc::Compressor* bgscomp, kt::TimedDB* dbs, int32_t dbnum, kt::RPCServer* serv); // logger implementation class Logger : public kt::RPCServer::Logger { public: // constructor explicit Logger() : strm_(NULL), lock_() {} // destructor ~Logger() { if (strm_) close(); } // open the stream bool open(const char* path) { if (strm_) return false; if (path && *path != '\0' && std::strcmp(path, "-")) { std::ofstream* strm = new std::ofstream; strm->open(path, std::ios_base::out | std::ios_base::binary | std::ios_base::app); if (!*strm) { delete strm; return false; } strm_ = strm; } else { strm_ = &std::cout; } return true; } // close the stream void close() { if (!strm_) return; if (strm_ != &std::cout) delete strm_; strm_ = NULL; } // process a log message. void log(Kind kind, const char* message) { if (!strm_) return; char date[48]; kt::datestrwww(kc::nan(), kc::INT32MAX, 6, date); const char* kstr = "MISC"; switch (kind) { case kt::RPCServer::Logger::DEBUG: kstr = "DEBUG"; break; case kt::RPCServer::Logger::INFO: kstr = "INFO"; break; case kt::RPCServer::Logger::SYSTEM: kstr = "SYSTEM"; break; case kt::RPCServer::Logger::ERROR: kstr = "ERROR"; break; } lock_.lock(); *strm_ << date << ": [" << kstr << "]: " << message << "\n"; strm_->flush(); lock_.unlock(); } private: std::ostream* strm_; kc::Mutex lock_; }; // database logger implementation class DBLogger : public kc::BasicDB::Logger { public: // constructor explicit DBLogger(::Logger* logger, uint32_t kinds) : logger_(logger), kinds_(kinds) {} // process a log message. void log(const char* file, int32_t line, const char* func, kc::BasicDB::Logger::Kind kind, const char* message) { kt::RPCServer::Logger::Kind rkind; switch (kind) { default: rkind = kt::RPCServer::Logger::DEBUG; break; case kc::BasicDB::Logger::INFO: rkind = kt::RPCServer::Logger::INFO; break; case kc::BasicDB::Logger::WARN: rkind = kt::RPCServer::Logger::SYSTEM; break; case kc::BasicDB::Logger::ERROR: rkind = kt::RPCServer::Logger::ERROR; break; } if (!(rkind & kinds_)) return; std::string lmsg; kc::strprintf(&lmsg, "[DB]: %s", message); logger_->log(rkind, lmsg.c_str()); } private: ::Logger* logger_; uint32_t kinds_; }; // replication slave implemantation class Slave : public kc::Thread { friend class Worker; public: // constructor explicit Slave(uint16_t sid, const char* rtspath, const char* host, int32_t port, double riv, kt::RPCServer* serv, kt::TimedDB* dbs, int32_t dbnum, kt::UpdateLogger* ulog, DBUpdateLogger* ulogdbs) : lock_(), sid_(sid), rtspath_(rtspath), host_(""), port_(port), riv_(riv), serv_(serv), dbs_(dbs), dbnum_(dbnum), ulog_(ulog), ulogdbs_(ulogdbs), wrts_(kc::UINT64MAX), rts_(0), alive_(true), hup_(false) { if (host) host_ = host; } // stop the slave void stop() { alive_ = false; } // restart the slave void restart() { hup_ = true; } // set the configuration of the master void set_master(const std::string& host, int32_t port, uint64_t ts, double iv) { kc::ScopedSpinLock lock(&lock_); host_ = host; port_ = port; wrts_ = ts; if (iv >= 0) riv_ = iv; } // get the host name of the master std::string host() { kc::ScopedSpinLock lock(&lock_); return host_; } // get the port number name of the master int32_t port() { kc::ScopedSpinLock lock(&lock_); return port_; } // get the replication time stamp uint64_t rts() { return rts_; } // get the replication interval double riv() { return riv_; } private: static const int32_t DUMMYFREQ = 256; static const size_t RTSFILESIZ = 21; // perform replication void run(void) { if (!rtspath_) return; kc::File rtsfile; if (!rtsfile.open(rtspath_, kc::File::OWRITER | kc::File::OCREATE, kc::NUMBUFSIZ) || !rtsfile.truncate(RTSFILESIZ)) { serv_->log(Logger::ERROR, "opening the RTS file failed: path=%s", rtspath_); return; } rts_ = read_rts(&rtsfile); write_rts(&rtsfile, rts_); kc::Thread::sleep(0.2); bool deferred = false; while (true) { lock_.lock(); std::string host = host_; int32_t port = port_; uint64_t wrts = wrts_; lock_.unlock(); if (!host.empty()) { if (wrts != kc::UINT64MAX) { lock_.lock(); wrts_ = kc::UINT64MAX; rts_ = wrts; write_rts(&rtsfile, rts_); lock_.unlock(); } kt::ReplicationClient rc; if (rc.open(host, port, 60, rts_, sid_)) { serv_->log(Logger::SYSTEM, "replication started: host=%s port=%d rts=%llu", host.c_str(), port, (unsigned long long)rts_); hup_ = false; double rivsum = 0; while (alive_ && !hup_ && rc.alive()) { size_t msiz; uint64_t mts; char* mbuf = rc.read(&msiz, &mts); if (mbuf) { if (msiz > 0) { size_t rsiz; uint16_t rsid, rdbid; const char* rbuf = DBUpdateLogger::parse(mbuf, msiz, &rsiz, &rsid, &rdbid); if (rbuf && rsid != sid_ && rdbid < dbnum_) { kt::TimedDB* db = dbs_ + rdbid; DBUpdateLogger* ulogdb = ulogdbs_ ? ulogdbs_ + rdbid : NULL; if (ulogdb) ulogdb->set_rsid(rsid); if (!db->recover(rbuf, rsiz)) { const kc::BasicDB::Error& e = db->error(); serv_->log(Logger::ERROR, "recovering a database failed: %s: %s", e.name(), e.message()); } if (ulogdb) ulogdb->clear_rsid(); } rivsum += riv_; } else { rivsum += riv_ * DUMMYFREQ / 4; } delete[] mbuf; while (rivsum > 100 && alive_ && !hup_ && rc.alive()) { kc::Thread::sleep(0.1); rivsum -= 100; } } if (mts > rts_) rts_ = mts; } rc.close(); serv_->log(Logger::SYSTEM, "replication finished: host=%s port=%d", host.c_str(), port); write_rts(&rtsfile, rts_); deferred = false; } else { if (!deferred) serv_->log(Logger::SYSTEM, "replication was deferred: host=%s port=%d", host.c_str(), port); deferred = true; } } if (alive_) { kc::Thread::sleep(1); } else { break; } } if (!rtsfile.close()) serv_->log(Logger::ERROR, "closing the RTS file failed"); } // read the replication time stamp uint64_t read_rts(kc::File* file) { char buf[RTSFILESIZ]; file->read_fast(0, buf, RTSFILESIZ); buf[sizeof(buf)-1] = '\0'; return kc::atoi(buf); } // write the replication time stamp void write_rts(kc::File* file, uint64_t rts) { char buf[kc::NUMBUFSIZ]; std::sprintf(buf, "%020llu\n", (unsigned long long)rts); if (!file->write_fast(0, buf, RTSFILESIZ)) serv_->log(Logger::SYSTEM, "writing the time stamp failed"); } kc::SpinLock lock_; const uint16_t sid_; const char* const rtspath_; std::string host_; int32_t port_; double riv_; kt::RPCServer* const serv_; kt::TimedDB* const dbs_; const int32_t dbnum_; kt::UpdateLogger* const ulog_; DBUpdateLogger* const ulogdbs_; uint64_t wrts_; uint64_t rts_; bool alive_; bool hup_; }; // plug-in server driver class PlugInDriver : public kc::Thread { public: // constructor explicit PlugInDriver(kt::PluggableServer* serv) : serv_(serv), error_(false) {} // get the error flag bool error() { return error_; } private: // perform service void run(void) { kc::Thread::sleep(0.4); if (serv_->start()) { if (!serv_->finish()) error_ = true; } else { error_ = true; } } kt::PluggableServer* serv_; bool error_; }; // worker implementation class Worker : public kt::RPCServer::Worker { private: class SLS; typedef kt::RPCClient::ReturnValue RV; public: // constructor explicit Worker(int32_t thnum, kc::CondMap* condmap, kt::TimedDB* dbs, int32_t dbnum, const std::map<std::string, int32_t>& dbmap, int32_t omode, double asi, bool ash, const char* bgspath, double bgsi, kc::Compressor* bgscomp, kt::UpdateLogger* ulog, DBUpdateLogger* ulogdbs, const char* cmdpath, ScriptProcessor* scrprocs, OpCount* opcounts) : thnum_(thnum), condmap_(condmap), dbs_(dbs), dbnum_(dbnum), dbmap_(dbmap), omode_(omode), asi_(asi), ash_(ash), bgspath_(bgspath), bgsi_(bgsi), bgscomp_(bgscomp), ulog_(ulog), ulogdbs_(ulogdbs), cmdpath_(cmdpath), scrprocs_(scrprocs), opcounts_(opcounts), idlecnt_(0), asnext_(0), bgsnext_(0), slave_(NULL) { asnext_ = kc::time() + asi_; bgsnext_ = kc::time() + bgsi_; } // set miscellaneous configuration void set_misc_conf(Slave* slave) { slave_ = slave; } private: // process each request of RPC. RV process(kt::RPCServer* serv, kt::RPCServer::Session* sess, const std::string& name, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { size_t rsiz; const char* rp = kt::strmapget(inmap, "WAIT", &rsiz); if (rp) { std::string condname(rp, rsiz); rp = kt::strmapget(inmap, "WAITTIME"); double wsec = rp ? kc::atof(rp) : 0.0; if (wsec <= 0) wsec = DEFTOUT; kt::ThreadedServer* thserv = serv->reveal_core()->reveal_core(); if (!condmap_->wait(condname, wsec) || thserv->aborted()) { set_message(outmap, "ERROR", "the condition timed out"); return kt::RPCClient::RVETIMEOUT; } } int32_t dbidx = 0; rp = kt::strmapget(inmap, "DB"); if (rp && *rp != '\0') { dbidx = -1; if (*rp >= '0' && *rp <= '9') { dbidx = kc::atoi(rp); } else { std::map<std::string, int32_t>::const_iterator it = dbmap_.find(rp); if (it != dbmap_.end()) dbidx = it->second; } } kt::TimedDB* db = dbidx >= 0 && dbidx < dbnum_ ? dbs_ + dbidx : NULL; int64_t curid = -1; rp = kt::strmapget(inmap, "CUR"); if (rp && *rp >= '0' && *rp <= '9') curid = kc::atoi(rp); kt::TimedDB::Cursor* cur = NULL; if (curid >= 0) { SLS* sls = SLS::create(sess); std::map<int64_t, kt::TimedDB::Cursor*>::iterator it = sls->curs_.find(curid); if (it == sls->curs_.end()) { if (db) { cur = db->cursor(); sls->curs_[curid] = cur; } } else { cur = it->second; if (name == "cur_delete") { sls->curs_.erase(curid); delete cur; return kt::RPCClient::RVSUCCESS; } } } RV rv; if (name == "void") { rv = do_void(serv, sess, inmap, outmap); } else if (name == "echo") { rv = do_echo(serv, sess, inmap, outmap); } else if (name == "report") { rv = do_report(serv, sess, inmap, outmap); } else if (name == "play_script") { rv = do_play_script(serv, sess, inmap, outmap); } else if (name == "tune_replication") { rv = do_tune_replication(serv, sess, inmap, outmap); } else if (name == "ulog_list") { rv = do_ulog_list(serv, sess, inmap, outmap); } else if (name == "ulog_remove") { rv = do_ulog_remove(serv, sess, inmap, outmap); } else if (name == "status") { rv = do_status(serv, sess, db, inmap, outmap); } else if (name == "clear") { rv = do_clear(serv, sess, db, inmap, outmap); } else if (name == "synchronize") { rv = do_synchronize(serv, sess, db, inmap, outmap); } else if (name == "set") { rv = do_set(serv, sess, db, inmap, outmap); } else if (name == "add") { rv = do_add(serv, sess, db, inmap, outmap); } else if (name == "replace") { rv = do_replace(serv, sess, db, inmap, outmap); } else if (name == "append") { rv = do_append(serv, sess, db, inmap, outmap); } else if (name == "increment") { rv = do_increment(serv, sess, db, inmap, outmap); } else if (name == "increment_double") { rv = do_increment_double(serv, sess, db, inmap, outmap); } else if (name == "cas") { rv = do_cas(serv, sess, db, inmap, outmap); } else if (name == "remove") { rv = do_remove(serv, sess, db, inmap, outmap); } else if (name == "get") { rv = do_get(serv, sess, db, inmap, outmap); } else if (name == "check") { rv = do_check(serv, sess, db, inmap, outmap); } else if (name == "seize") { rv = do_seize(serv, sess, db, inmap, outmap); } else if (name == "set_bulk") { rv = do_set_bulk(serv, sess, db, inmap, outmap); } else if (name == "remove_bulk") { rv = do_remove_bulk(serv, sess, db, inmap, outmap); } else if (name == "get_bulk") { rv = do_get_bulk(serv, sess, db, inmap, outmap); } else if (name == "vacuum") { rv = do_vacuum(serv, sess, db, inmap, outmap); } else if (name == "match_prefix") { rv = do_match_prefix(serv, sess, db, inmap, outmap); } else if (name == "match_regex") { rv = do_match_regex(serv, sess, db, inmap, outmap); } else if (name == "match_similar") { rv = do_match_similar(serv, sess, db, inmap, outmap); } else if (name == "cur_jump") { rv = do_cur_jump(serv, sess, cur, inmap, outmap); } else if (name == "cur_jump_back") { rv = do_cur_jump_back(serv, sess, cur, inmap, outmap); } else if (name == "cur_step") { rv = do_cur_step(serv, sess, cur, inmap, outmap); } else if (name == "cur_step_back") { rv = do_cur_step_back(serv, sess, cur, inmap, outmap); } else if (name == "cur_set_value") { rv = do_cur_set_value(serv, sess, cur, inmap, outmap); } else if (name == "cur_remove") { rv = do_cur_remove(serv, sess, cur, inmap, outmap); } else if (name == "cur_get_key") { rv = do_cur_get_key(serv, sess, cur, inmap, outmap); } else if (name == "cur_get_value") { rv = do_cur_get_value(serv, sess, cur, inmap, outmap); } else if (name == "cur_get") { rv = do_cur_get(serv, sess, cur, inmap, outmap); } else if (name == "cur_seize") { rv = do_cur_seize(serv, sess, cur, inmap, outmap); } else { set_message(outmap, "ERROR", "not implemented: %s", name.c_str()); rv = kt::RPCClient::RVENOIMPL; } rp = kt::strmapget(inmap, "SIGNAL", &rsiz); if (rp) { std::string condname(rp, rsiz); rp = kt::strmapget(inmap, "SIGNALBROAD"); bool broad = rp ? true : false; size_t wnum = broad ? condmap_->broadcast(condname) : condmap_->signal(condname); set_message(outmap, "SIGNALED", "%lld", (long long)wnum); } return rv; } // process each request of the others. int32_t process(kt::HTTPServer* serv, kt::HTTPServer::Session* sess, const std::string& path, kt::HTTPClient::Method method, const std::map<std::string, std::string>& reqheads, const std::string& reqbody, std::map<std::string, std::string>& resheads, std::string& resbody, const std::map<std::string, std::string>& misc) { const char* pstr = path.c_str(); if (*pstr == '/') pstr++; int32_t dbidx = 0; const char* rp = std::strchr(pstr, '/'); if (rp) { std::string dbexpr(pstr, rp - pstr); pstr = rp + 1; if (*pstr == '/') pstr++; size_t desiz; char* destr = kc::urldecode(dbexpr.c_str(), &desiz); if (*destr != '\0') { dbidx = -1; if (*destr >= '0' && *destr <= '9') { dbidx = kc::atoi(destr); } else { std::map<std::string, int32_t>::const_iterator it = dbmap_.find(destr); if (it != dbmap_.end()) dbidx = it->second; } } delete[] destr; } if (dbidx < 0 || dbidx >= dbnum_) { resbody.append("no such database\n"); return 400; } kt::TimedDB* db = dbs_ + dbidx; size_t ksiz; char* kbuf = kc::urldecode(pstr, &ksiz); int32_t code; switch (method) { case kt::HTTPClient::MGET: { code = do_rest_get(serv, sess, db, kbuf, ksiz, reqheads, reqbody, resheads, resbody, misc); break; } case kt::HTTPClient::MHEAD: { code = do_rest_head(serv, sess, db, kbuf, ksiz, reqheads, reqbody, resheads, resbody, misc); break; } case kt::HTTPClient::MPUT: { code = do_rest_put(serv, sess, db, kbuf, ksiz, reqheads, reqbody, resheads, resbody, misc); break; } case kt::HTTPClient::MDELETE: { code = do_rest_delete(serv, sess, db, kbuf, ksiz, reqheads, reqbody, resheads, resbody, misc); break; } default: { code = 501; break; } } delete[] kbuf; return code; } // process each binary request bool process_binary(kt::ThreadedServer* serv, kt::ThreadedServer::Session* sess) { int32_t magic = sess->receive_byte(); const char* cmd; bool rv; switch (magic) { case kt::RemoteDB::BMREPLICATION: { cmd = "bin_replication"; rv = do_bin_replication(serv, sess); break; } case kt::RemoteDB::BMPLAYSCRIPT: { cmd = "bin_play_script"; rv = do_bin_play_script(serv, sess); break; } case kt::RemoteDB::BMSETBULK: { cmd = "bin_set_bulk"; rv = do_bin_set_bulk(serv, sess); break; } case kt::RemoteDB::BMREMOVEBULK: { cmd = "bin_remove_bulk"; rv = do_bin_remove_bulk(serv, sess); break; } case kt::RemoteDB::BMGETBULK: { cmd = "bin_get_bulk"; rv = do_bin_get_bulk(serv, sess); break; } default: { cmd = "bin_unknown"; rv = false; break; } } std::string expr = sess->expression(); serv->log(kt::ThreadedServer::Logger::INFO, "(%s): %s: %d", expr.c_str(), cmd, rv); return rv; } // process each idle event void process_idle(kt::RPCServer* serv) { if (omode_ & kc::BasicDB::OWRITER) { int32_t dbidx = idlecnt_++ % dbnum_; kt::TimedDB* db = dbs_ + dbidx; kt::ThreadedServer* thserv = serv->reveal_core()->reveal_core(); for (int32_t i = 0; i < 4; i++) { if (thserv->task_count() > 0) break; if (!db->vacuum(2)) { const kc::BasicDB::Error& e = db->error(); log_db_error(serv, e); break; } kc::Thread::yield(); } } } // process each timer event void process_timer(kt::RPCServer* serv) { if (asi_ > 0 && (omode_ & kc::BasicDB::OWRITER) && kc::time() >= asnext_) { serv->log(Logger::INFO, "synchronizing databases"); for (int32_t i = 0; i < dbnum_; i++) { kt::TimedDB* db = dbs_ + i; if (!db->synchronize(ash_)) { const kc::BasicDB::Error& e = db->error(); log_db_error(serv, e); break; } kc::Thread::yield(); } asnext_ = kc::time() + asi_; } if (bgspath_ && bgsi_ > 0 && kc::time() >= bgsnext_) { serv->log(Logger::INFO, "snapshotting databases"); dosnapshot(bgspath_, bgscomp_, dbs_, dbnum_, serv); bgsnext_ = kc::time() + bgsi_; } } // process the starting event void process_start(kt::RPCServer* serv) { kt::maskthreadsignal(); } // set the error message void set_message(std::map<std::string, std::string>& outmap, const char* key, const char* format, ...) { std::string message; va_list ap; va_start(ap, format); kc::vstrprintf(&message, format, ap); va_end(ap); outmap[key] = message; } // set the database error message void set_db_error(std::map<std::string, std::string>& outmap, const kc::BasicDB::Error& e) { set_message(outmap, "ERROR", "DB: %d: %s: %s", e.code(), e.name(), e.message()); } // log the database error message void log_db_error(kt::RPCServer* serv, const kc::BasicDB::Error& e) { log_db_error(serv->reveal_core(), e); } // log the database error message void log_db_error(kt::HTTPServer* serv, const kc::BasicDB::Error& e) { serv->log(Logger::ERROR, "database error: %d: %s: %s", e.code(), e.name(), e.message()); } // process the void procedure RV do_void(kt::RPCServer* serv, kt::RPCServer::Session* sess, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { return kt::RPCClient::RVSUCCESS; } // process the echo procedure RV do_echo(kt::RPCServer* serv, kt::RPCServer::Session* sess, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { outmap.insert(inmap.begin(), inmap.end()); return kt::RPCClient::RVSUCCESS; } // process the report procedure RV do_report(kt::RPCServer* serv, kt::RPCServer::Session* sess, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { int64_t totalcount = 0; int64_t totalsize = 0; for (int32_t i = 0; i < dbnum_; i++) { int64_t count = dbs_[i].count(); int64_t size = dbs_[i].size(); std::string key; kc::strprintf(&key, "db_%d", i); set_message(outmap, key.c_str(), "count=%lld size=%lld path=%s", (long long)count, (long long)size, dbs_[i].path().c_str()); totalcount += count; totalsize += size; } set_message(outmap, "db_total_count", "%lld", (long long)totalcount); set_message(outmap, "db_total_size", "%lld", (long long)totalsize); kt::ThreadedServer* thserv = serv->reveal_core()->reveal_core(); set_message(outmap, "serv_conn_count", "%lld", (long long)thserv->connection_count()); set_message(outmap, "serv_task_count", "%lld", (long long)thserv->task_count()); set_message(outmap, "serv_thread_count", "%lld", (long long)thnum_); double ctime = kc::time(); set_message(outmap, "serv_current_time", "%.6f", ctime); set_message(outmap, "serv_running_term", "%.6f", ctime - g_starttime); set_message(outmap, "serv_proc_id", "%d", g_procid); std::map<std::string, std::string> sysinfo; kc::getsysinfo(&sysinfo); std::map<std::string, std::string>::iterator it = sysinfo.begin(); std::map<std::string, std::string>::iterator itend = sysinfo.end(); while (it != itend) { std::string key; kc::strprintf(&key, "sys_%s", it->first.c_str()); set_message(outmap, key.c_str(), it->second.c_str()); ++it; } const std::string& mhost = slave_->host(); if (!mhost.empty()) { set_message(outmap, "repl_master_host", "%s", mhost.c_str()); set_message(outmap, "repl_master_port", "%d", slave_->port()); uint64_t rts = slave_->rts(); set_message(outmap, "repl_timestamp", "%llu", (unsigned long long)rts); set_message(outmap, "repl_interval", "%.6f", slave_->riv()); uint64_t cc = kt::UpdateLogger::clock_pure(); uint64_t delay = cc > rts ? cc - rts : 0; set_message(outmap, "repl_delay", "%.6f", delay / 1000000000.0); } OpCount ocsum; for (int32_t i = 0; i <= CNTMISC; i++) { ocsum[i] = 0; } for (int32_t i = 0; i < thnum_; i++) { for (int32_t j = 0; j <= CNTMISC; j++) { ocsum[j] += opcounts_[i][j]; } } set_message(outmap, "cnt_set", "%llu", (unsigned long long)ocsum[CNTSET]); set_message(outmap, "cnt_set_misses", "%llu", (unsigned long long)ocsum[CNTSETMISS]); set_message(outmap, "cnt_remove", "%llu", (unsigned long long)ocsum[CNTREMOVE]); set_message(outmap, "cnt_remove_misses", "%llu", (unsigned long long)ocsum[CNTREMOVEMISS]); set_message(outmap, "cnt_get", "%llu", (unsigned long long)ocsum[CNTGET]); set_message(outmap, "cnt_get_misses", "%llu", (unsigned long long)ocsum[CNTGETMISS]); set_message(outmap, "cnt_script", "%llu", (unsigned long long)ocsum[CNTSCRIPT]); set_message(outmap, "cnt_misc", "%llu", (unsigned long long)ocsum[CNTMISC]); set_message(outmap, "conf_kt_version", "%s (%d.%d)", kt::VERSION, kt::LIBVER, kt::LIBREV); set_message(outmap, "conf_kt_features", "%s", kt::FEATURES); set_message(outmap, "conf_kc_version", "%s (%d.%d)", kc::VERSION, kc::LIBVER, kc::LIBREV); set_message(outmap, "conf_kc_features", "%s", kc::FEATURES); set_message(outmap, "conf_os_name", "%s", kc::OSNAME); return kt::RPCClient::RVSUCCESS; } // process the play_script procedure RV do_play_script(kt::RPCServer* serv, kt::RPCServer::Session* sess, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!scrprocs_) { set_message(outmap, "ERROR", "the scripting extention is disabled"); return kt::RPCClient::RVENOIMPL; } ScriptProcessor* scrproc = scrprocs_ + thid; const char* nstr = kt::strmapget(inmap, "name"); if (!nstr || *nstr == '\0' || !kt::strisalnum(nstr)) { set_message(outmap, "ERROR", "invalid parameters"); return kt::RPCClient::RVEINVALID; } std::map<std::string, std::string> scrinmap; std::map<std::string, std::string>::const_iterator it = inmap.begin(); std::map<std::string, std::string>::const_iterator itend = inmap.end(); while (it != itend) { const char* kbuf = it->first.data(); size_t ksiz = it->first.size(); if (ksiz > 0 && *kbuf == '_') { std::string key(kbuf + 1, ksiz - 1); scrinmap[key] = it->second; } ++it; } opcounts_[thid][CNTSCRIPT]++; std::map<std::string, std::string> scroutmap; RV rv = scrproc->call(nstr, scrinmap, scroutmap); if (rv == kt::RPCClient::RVSUCCESS) { it = scroutmap.begin(); itend = scroutmap.end(); while (it != itend) { std::string key = "_"; key.append(it->first); outmap[key] = it->second; ++it; } } else if (rv == kt::RPCClient::RVENOIMPL) { set_message(outmap, "ERROR", "no such scripting procedure"); } else { set_message(outmap, "ERROR", "the scripting procedure failed"); } return rv; } // process the tune_replication procedure RV do_tune_replication(kt::RPCServer* serv, kt::RPCServer::Session* sess, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { if (!slave_->rtspath_) { set_message(outmap, "ERROR", "the RTS file is not set"); return kt::RPCClient::RVENOIMPL; } const char* host = kt::strmapget(inmap, "host"); if (!host) host = ""; const char* rp = kt::strmapget(inmap, "port"); int32_t port = rp ? kc::atoi(rp) : 0; if (port < 1) port = kt::DEFPORT; rp = kt::strmapget(inmap, "ts"); uint64_t ts = kc::UINT64MAX; if (rp) { if (!std::strcmp(rp, "now")) { ts = kt::UpdateLogger::clock_pure(); } else { ts = kc::atoi(rp); } } rp = kt::strmapget(inmap, "iv"); double iv = rp ? kc::atof(rp) : -1; char tsstr[kc::NUMBUFSIZ]; if (ts == kc::UINT64MAX) { std::sprintf(tsstr, "*"); } else { std::sprintf(tsstr, "%llu", (unsigned long long)ts); } char ivstr[kc::NUMBUFSIZ]; if (iv < 0) { std::sprintf(ivstr, "*"); } else { std::sprintf(ivstr, "%.6f", iv); } serv->log(Logger::SYSTEM, "replication setting was modified: host=%s port=%d ts=%s iv=%s", host, port, tsstr, ivstr); slave_->set_master(host, port, ts, iv); slave_->restart(); return kt::RPCClient::RVSUCCESS; } // process the ulog_list procedure RV do_ulog_list(kt::RPCServer* serv, kt::RPCServer::Session* sess, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { if (!ulog_) { set_message(outmap, "ERROR", "no update log allows no replication"); return kt::RPCClient::RVEINVALID; } std::vector<kt::UpdateLogger::FileStatus> files; ulog_->list_files(&files); std::vector<kt::UpdateLogger::FileStatus>::iterator it = files.begin(); std::vector<kt::UpdateLogger::FileStatus>::iterator itend = files.end(); while (it != itend) { set_message(outmap, it->path.c_str(), "%llu:%llu", (unsigned long long)it->size, (unsigned long long)it->ts); ++it; } return kt::RPCClient::RVSUCCESS; } // process the ulog_remove procedure RV do_ulog_remove(kt::RPCServer* serv, kt::RPCServer::Session* sess, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { if (!ulog_) { set_message(outmap, "ERROR", "no update log allows no replication"); return kt::RPCClient::RVEINVALID; } const char* rp = kt::strmapget(inmap, "ts"); uint64_t ts = kc::UINT64MAX; if (rp) { if (!std::strcmp(rp, "now")) { ts = kt::UpdateLogger::clock_pure(); } else { ts = kc::atoi(rp); } } bool err = false; std::vector<kt::UpdateLogger::FileStatus> files; ulog_->list_files(&files); std::vector<kt::UpdateLogger::FileStatus>::iterator it = files.begin(); std::vector<kt::UpdateLogger::FileStatus>::iterator itend = files.end(); if (it != itend) itend--; while (it != itend) { if (it->ts <= ts && !kc::File::remove(it->path)) { set_message(outmap, "ERROR", "removing a file failed: %s", it->path.c_str()); serv->log(Logger::ERROR, "removing a file failed: %s", it->path.c_str()); err = true; } ++it; } return err ? kt::RPCClient::RVEINTERNAL : kt::RPCClient::RVSUCCESS; } // process the status procedure RV do_status(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } RV rv; opcounts_[thid][CNTMISC]++; std::map<std::string, std::string> status; if (db->status(&status)) { rv = kt::RPCClient::RVSUCCESS; outmap.insert(status.begin(), status.end()); } else { const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } return rv; } // process the clear procedure RV do_clear(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } RV rv; opcounts_[thid][CNTMISC]++; if (db->clear()) { rv = kt::RPCClient::RVSUCCESS; } else { const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } return rv; } // process the synchronize procedure RV do_synchronize(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } const char* rp = kt::strmapget(inmap, "hard"); bool hard = rp ? true : false; rp = kt::strmapget(inmap, "command"); std::string command = rp ? rp : ""; class Visitor : public kc::BasicDB::FileProcessor { public: Visitor(kt::RPCServer* serv, Worker* worker, const std::string& command) : serv_(serv), worker_(worker), command_(command) {} private: bool process(const std::string& path, int64_t count, int64_t size) { if (command_.size() < 1) return true; const char* cmd = command_.c_str(); if (std::strchr(cmd, kc::File::PATHCHR) || !std::strcmp(cmd, kc::File::CDIRSTR) || !std::strcmp(cmd, kc::File::PDIRSTR)) { serv_->log(Logger::INFO, "invalid command name: %s", cmd); return false; } std::string cmdpath; kc::strprintf(&cmdpath, "%s%c%s", worker_->cmdpath_, kc::File::PATHCHR, cmd); std::vector<std::string> args; args.push_back(cmdpath); args.push_back(path); std::string tsstr; uint64_t cc = worker_->ulog_ ? worker_->ulog_->clock() : kt::UpdateLogger::clock_pure(); if (!worker_->slave_->host().empty()) { uint64_t rts = worker_->slave_->rts(); if (rts < cc) cc = rts; } kc::strprintf(&tsstr, "%020llu", (unsigned long long)cc); args.push_back(tsstr); serv_->log(Logger::SYSTEM, "executing: %s \"%s\"", cmd, path.c_str()); if (kt::executecommand(args) != 0) { serv_->log(Logger::ERROR, "execution failed: %s \"%s\"", cmd, path.c_str()); return false; } return true; } kt::RPCServer* serv_; Worker* worker_; std::string command_; }; Visitor visitor(serv, this, command); RV rv; opcounts_[thid][CNTMISC]++; if (db->synchronize(hard, &visitor)) { rv = kt::RPCClient::RVSUCCESS; } else { const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } return rv; } // process the set procedure RV do_set(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } size_t ksiz; const char* kbuf = kt::strmapget(inmap, "key", &ksiz); size_t vsiz; const char* vbuf = kt::strmapget(inmap, "value", &vsiz); if (!kbuf || !vbuf) { set_message(outmap, "ERROR", "invalid parameters"); return kt::RPCClient::RVEINVALID; } const char* rp = kt::strmapget(inmap, "xt"); int64_t xt = rp ? kc::atoi(rp) : kc::INT64MAX; RV rv; opcounts_[thid][CNTSET]++; if (db->set(kbuf, ksiz, vbuf, vsiz, xt)) { rv = kt::RPCClient::RVSUCCESS; } else { opcounts_[thid][CNTSETMISS]++; const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } return rv; } // process the add procedure RV do_add(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } size_t ksiz; const char* kbuf = kt::strmapget(inmap, "key", &ksiz); size_t vsiz; const char* vbuf = kt::strmapget(inmap, "value", &vsiz); if (!kbuf || !vbuf) { set_message(outmap, "ERROR", "invalid parameters"); return kt::RPCClient::RVEINVALID; } const char* rp = kt::strmapget(inmap, "xt"); int64_t xt = rp ? kc::atoi(rp) : kc::INT64MAX; RV rv; opcounts_[thid][CNTSET]++; if (db->add(kbuf, ksiz, vbuf, vsiz, xt)) { rv = kt::RPCClient::RVSUCCESS; } else { opcounts_[thid][CNTSETMISS]++; const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::DUPREC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } return rv; } // process the replace procedure RV do_replace(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } size_t ksiz; const char* kbuf = kt::strmapget(inmap, "key", &ksiz); size_t vsiz; const char* vbuf = kt::strmapget(inmap, "value", &vsiz); if (!kbuf || !vbuf) { set_message(outmap, "ERROR", "invalid parameters"); return kt::RPCClient::RVEINVALID; } const char* rp = kt::strmapget(inmap, "xt"); int64_t xt = rp ? kc::atoi(rp) : kc::INT64MAX; RV rv; opcounts_[thid][CNTSET]++; if (db->replace(kbuf, ksiz, vbuf, vsiz, xt)) { rv = kt::RPCClient::RVSUCCESS; } else { opcounts_[thid][CNTSETMISS]++; const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::NOREC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } return rv; } // process the append procedure RV do_append(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } size_t ksiz; const char* kbuf = kt::strmapget(inmap, "key", &ksiz); size_t vsiz; const char* vbuf = kt::strmapget(inmap, "value", &vsiz); if (!kbuf || !vbuf) { set_message(outmap, "ERROR", "invalid parameters"); return kt::RPCClient::RVEINVALID; } const char* rp = kt::strmapget(inmap, "xt"); int64_t xt = rp ? kc::atoi(rp) : kc::INT64MAX; RV rv; opcounts_[thid][CNTSET]++; if (db->append(kbuf, ksiz, vbuf, vsiz, xt)) { rv = kt::RPCClient::RVSUCCESS; } else { opcounts_[thid][CNTSETMISS]++; const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } return rv; } // process the increment procedure RV do_increment(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } size_t ksiz; const char* kbuf = kt::strmapget(inmap, "key", &ksiz); const char* nstr = kt::strmapget(inmap, "num"); if (!kbuf || !nstr) { set_message(outmap, "ERROR", "invalid parameters"); return kt::RPCClient::RVEINVALID; } int64_t num = kc::atoi(nstr); const char* rp = kt::strmapget(inmap, "orig"); int64_t orig; if (rp) { if (!std::strcmp(rp, "try")) { orig = kc::INT64MIN; } else if (!std::strcmp(rp, "set")) { orig = kc::INT64MAX; } else { orig = kc::atoi(rp); } } else { orig = 0; } rp = kt::strmapget(inmap, "xt"); int64_t xt = rp ? kc::atoi(rp) : kc::INT64MAX; RV rv; opcounts_[thid][CNTSET]++; num = db->increment(kbuf, ksiz, num, orig, xt); if (num != kc::INT64MIN) { rv = kt::RPCClient::RVSUCCESS; set_message(outmap, "num", "%lld", (long long)num); } else { opcounts_[thid][CNTSETMISS]++; const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::LOGIC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } return rv; } // process the increment_double procedure RV do_increment_double(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } size_t ksiz; const char* kbuf = kt::strmapget(inmap, "key", &ksiz); const char* nstr = kt::strmapget(inmap, "num"); if (!kbuf || !nstr) { set_message(outmap, "ERROR", "invalid parameters"); return kt::RPCClient::RVEINVALID; } double num = kc::atof(nstr); const char* rp = kt::strmapget(inmap, "orig"); double orig; if (rp) { if (!std::strcmp(rp, "try")) { orig = -kc::inf(); } else if (!std::strcmp(rp, "set")) { orig = kc::inf(); } else { orig = kc::atof(rp); } } else { orig = 0; } rp = kt::strmapget(inmap, "xt"); int64_t xt = rp ? kc::atoi(rp) : kc::INT64MAX; RV rv; opcounts_[thid][CNTSET]++; num = db->increment_double(kbuf, ksiz, num, orig, xt); if (!kc::chknan(num)) { rv = kt::RPCClient::RVSUCCESS; set_message(outmap, "num", "%f", num); } else { opcounts_[thid][CNTSETMISS]++; const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::LOGIC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } return rv; } // process the cas procedure RV do_cas(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } size_t ksiz; const char* kbuf = kt::strmapget(inmap, "key", &ksiz); if (!kbuf) { set_message(outmap, "ERROR", "invalid parameters"); return kt::RPCClient::RVEINVALID; } size_t ovsiz; const char* ovbuf = kt::strmapget(inmap, "oval", &ovsiz); size_t nvsiz; const char* nvbuf = kt::strmapget(inmap, "nval", &nvsiz); const char* rp = kt::strmapget(inmap, "xt"); int64_t xt = rp ? kc::atoi(rp) : kc::INT64MAX; RV rv; opcounts_[thid][CNTSET]++; if (db->cas(kbuf, ksiz, ovbuf, ovsiz, nvbuf, nvsiz, xt)) { rv = kt::RPCClient::RVSUCCESS; } else { opcounts_[thid][CNTSETMISS]++; const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::LOGIC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } return rv; } // process the remove procedure RV do_remove(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } size_t ksiz; const char* kbuf = kt::strmapget(inmap, "key", &ksiz); if (!kbuf) { set_message(outmap, "ERROR", "invalid parameters"); return kt::RPCClient::RVEINVALID; } RV rv; opcounts_[thid][CNTREMOVE]++; if (db->remove(kbuf, ksiz)) { rv = kt::RPCClient::RVSUCCESS; } else { opcounts_[thid][CNTREMOVEMISS]++; const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::NOREC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } return rv; } // process the get procedure RV do_get(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } size_t ksiz; const char* kbuf = kt::strmapget(inmap, "key", &ksiz); if (!kbuf) { set_message(outmap, "ERROR", "invalid parameters"); return kt::RPCClient::RVEINVALID; } RV rv; opcounts_[thid][CNTGET]++; size_t vsiz; int64_t xt; const char* vbuf = db->get(kbuf, ksiz, &vsiz, &xt); if (vbuf) { outmap["value"] = std::string(vbuf, vsiz); if (xt < kt::TimedDB::XTMAX) set_message(outmap, "xt", "%lld", (long long)xt); delete[] vbuf; rv = kt::RPCClient::RVSUCCESS; } else { opcounts_[thid][CNTGETMISS]++; const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::NOREC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } return rv; } // process the check procedure RV do_check(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } size_t ksiz; const char* kbuf = kt::strmapget(inmap, "key", &ksiz); if (!kbuf) { set_message(outmap, "ERROR", "invalid parameters"); return kt::RPCClient::RVEINVALID; } RV rv; opcounts_[thid][CNTGET]++; int64_t xt; int32_t vsiz = db->check(kbuf, ksiz, &xt); if (vsiz >= 0) { set_message(outmap, "vsiz", "%lld", (long long)vsiz); if (xt < kt::TimedDB::XTMAX) set_message(outmap, "xt", "%lld", (long long)xt); rv = kt::RPCClient::RVSUCCESS; } else { opcounts_[thid][CNTGETMISS]++; const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::NOREC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } return rv; } // process the seize procedure RV do_seize(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } size_t ksiz; const char* kbuf = kt::strmapget(inmap, "key", &ksiz); if (!kbuf) { set_message(outmap, "ERROR", "invalid parameters"); return kt::RPCClient::RVEINVALID; } RV rv; opcounts_[thid][CNTREMOVE]++; opcounts_[thid][CNTGET]++; size_t vsiz; int64_t xt; const char* vbuf = db->seize(kbuf, ksiz, &vsiz, &xt); if (vbuf) { outmap["value"] = std::string(vbuf, vsiz); if (xt < kt::TimedDB::XTMAX) set_message(outmap, "xt", "%lld", (long long)xt); delete[] vbuf; rv = kt::RPCClient::RVSUCCESS; } else { opcounts_[thid][CNTREMOVEMISS]++; opcounts_[thid][CNTGETMISS]++; const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::NOREC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } return rv; } // process the set_bulk procedure RV do_set_bulk(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } const char* rp = kt::strmapget(inmap, "xt"); int64_t xt = rp ? kc::atoi(rp) : kc::INT64MAX; rp = kt::strmapget(inmap, "atomic"); bool atomic = rp ? true : false; std::map<std::string, std::string> recs; std::map<std::string, std::string>::const_iterator it = inmap.begin(); std::map<std::string, std::string>::const_iterator itend = inmap.end(); while (it != itend) { const char* kbuf = it->first.data(); size_t ksiz = it->first.size(); if (ksiz > 0 && *kbuf == '_') { std::string key(kbuf + 1, ksiz - 1); std::string value(it->second.data(), it->second.size()); recs[key] = value; } ++it; } RV rv; opcounts_[thid][CNTSET] += recs.size(); int64_t num = db->set_bulk(recs, xt, atomic); if (num >= 0) { opcounts_[thid][CNTSETMISS] += recs.size() - (size_t)num; rv = kt::RPCClient::RVSUCCESS; set_message(outmap, "num", "%lld", (long long)num); } else { opcounts_[thid][CNTSETMISS] += recs.size(); const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } return rv; } // process the remove_bulk procedure RV do_remove_bulk(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } const char* rp = kt::strmapget(inmap, "atomic"); bool atomic = rp ? true : false; std::vector<std::string> keys; keys.reserve(inmap.size()); std::map<std::string, std::string>::const_iterator it = inmap.begin(); std::map<std::string, std::string>::const_iterator itend = inmap.end(); while (it != itend) { const char* kbuf = it->first.data(); size_t ksiz = it->first.size(); if (ksiz > 0 && *kbuf == '_') { std::string key(kbuf + 1, ksiz - 1); keys.push_back(key); } ++it; } RV rv; opcounts_[thid][CNTREMOVE] += keys.size(); int64_t num = db->remove_bulk(keys, atomic); if (num >= 0) { opcounts_[thid][CNTREMOVEMISS] += keys.size() - (size_t)num; rv = kt::RPCClient::RVSUCCESS; set_message(outmap, "num", "%lld", (long long)num); } else { opcounts_[thid][CNTREMOVEMISS] += keys.size(); const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } return rv; } // process the get_bulk procedure RV do_get_bulk(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } const char* rp = kt::strmapget(inmap, "atomic"); bool atomic = rp ? true : false; std::vector<std::string> keys; keys.reserve(inmap.size()); std::map<std::string, std::string>::const_iterator it = inmap.begin(); std::map<std::string, std::string>::const_iterator itend = inmap.end(); while (it != itend) { const char* kbuf = it->first.data(); size_t ksiz = it->first.size(); if (ksiz > 0 && *kbuf == '_') { std::string key(kbuf + 1, ksiz - 1); keys.push_back(key); } ++it; } RV rv; opcounts_[thid][CNTGET] += keys.size(); std::map<std::string, std::string> recs; int64_t num = db->get_bulk(keys, &recs, atomic); if (num >= 0) { opcounts_[thid][CNTGETMISS] += keys.size() - (size_t)num; rv = kt::RPCClient::RVSUCCESS; std::map<std::string, std::string>::iterator it = recs.begin(); std::map<std::string, std::string>::iterator itend = recs.end(); while (it != itend) { std::string key("_"); key.append(it->first); outmap[key] = it->second; ++it; } set_message(outmap, "num", "%lld", (long long)num); } else { opcounts_[thid][CNTGETMISS] += keys.size(); const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } return rv; } // process the vacuum procedure RV do_vacuum(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } const char* rp = kt::strmapget(inmap, "step"); int64_t step = rp ? kc::atoi(rp) : 0; RV rv; opcounts_[thid][CNTMISC]++; if (db->vacuum(step)) { rv = kt::RPCClient::RVSUCCESS; } else { const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } return rv; } // process the match_prefix procedure RV do_match_prefix(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } size_t psiz; const char* pbuf = kt::strmapget(inmap, "prefix", &psiz); if (!pbuf) { set_message(outmap, "ERROR", "invalid parameters"); return kt::RPCClient::RVEINVALID; } const char* rp = kt::strmapget(inmap, "max"); int64_t max = rp ? kc::atoi(rp) : -1; std::vector<std::string> keys; RV rv; opcounts_[thid][CNTMISC]++; int64_t num = db->match_prefix(std::string(pbuf, psiz), &keys, max); if (num >= 0) { std::vector<std::string>::iterator it = keys.begin(); std::vector<std::string>::iterator itend = keys.end(); int64_t cnt = 0; while (it != itend) { std::string key = "_"; key.append(*it); outmap[key] = kc::strprintf("%lld", (long long)cnt); ++cnt; ++it; } set_message(outmap, "num", "%lld", (long long)num); rv = kt::RPCClient::RVSUCCESS; } else { const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } return rv; } // process the match_regex procedure RV do_match_regex(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } size_t psiz; const char* pbuf = kt::strmapget(inmap, "regex", &psiz); if (!pbuf) { set_message(outmap, "ERROR", "invalid parameters"); return kt::RPCClient::RVEINVALID; } const char* rp = kt::strmapget(inmap, "max"); int64_t max = rp ? kc::atoi(rp) : -1; std::vector<std::string> keys; RV rv; opcounts_[thid][CNTMISC]++; int64_t num = db->match_regex(std::string(pbuf, psiz), &keys, max); if (num >= 0) { std::vector<std::string>::iterator it = keys.begin(); std::vector<std::string>::iterator itend = keys.end(); int64_t cnt = 0; while (it != itend) { std::string key = "_"; key.append(*it); outmap[key] = kc::strprintf("%lld", (long long)cnt); ++cnt; ++it; } set_message(outmap, "num", "%lld", (long long)num); rv = kt::RPCClient::RVSUCCESS; } else { const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::LOGIC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } return rv; } // process the match_similar procedure RV do_match_similar(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB* db, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!db) { set_message(outmap, "ERROR", "no such database"); return kt::RPCClient::RVEINVALID; } size_t osiz; const char* obuf = kt::strmapget(inmap, "origin", &osiz); if (!obuf) { set_message(outmap, "ERROR", "invalid parameters"); return kt::RPCClient::RVEINVALID; } const char* rp = kt::strmapget(inmap, "range"); int64_t range = rp ? kc::atoi(rp) : 1; if (range < 0) range = 1; rp = kt::strmapget(inmap, "utf"); bool utf = rp ? true : false; rp = kt::strmapget(inmap, "max"); int64_t max = rp ? kc::atoi(rp) : -1; std::vector<std::string> keys; RV rv; opcounts_[thid][CNTMISC]++; int64_t num = db->match_similar(std::string(obuf, osiz), range, utf, &keys, max); if (num >= 0) { std::vector<std::string>::iterator it = keys.begin(); std::vector<std::string>::iterator itend = keys.end(); int64_t cnt = 0; while (it != itend) { std::string key = "_"; key.append(*it); outmap[key] = kc::strprintf("%lld", (long long)cnt); ++cnt; ++it; } set_message(outmap, "num", "%lld", (long long)num); rv = kt::RPCClient::RVSUCCESS; } else { const kc::BasicDB::Error& e = db->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::LOGIC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } return rv; } // process the cur_jump procedure RV do_cur_jump(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB::Cursor* cur, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!cur) { set_message(outmap, "ERROR", "no such cursor"); return kt::RPCClient::RVEINVALID; } size_t ksiz; const char* kbuf = kt::strmapget(inmap, "key", &ksiz); RV rv; opcounts_[thid][CNTMISC]++; if (kbuf) { if (cur->jump(kbuf, ksiz)) { rv = kt::RPCClient::RVSUCCESS; } else { const kc::BasicDB::Error& e = cur->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::NOREC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } } else { if (cur->jump()) { rv = kt::RPCClient::RVSUCCESS; } else { const kc::BasicDB::Error& e = cur->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::NOREC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } } return rv; } // process the cur_jump_back procedure RV do_cur_jump_back(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB::Cursor* cur, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!cur) { set_message(outmap, "ERROR", "no such cursor"); return kt::RPCClient::RVEINVALID; } size_t ksiz; const char* kbuf = kt::strmapget(inmap, "key", &ksiz); RV rv; opcounts_[thid][CNTMISC]++; if (kbuf) { if (cur->jump_back(kbuf, ksiz)) { rv = kt::RPCClient::RVSUCCESS; } else { const kc::BasicDB::Error& e = cur->error(); set_db_error(outmap, e); switch (e.code()) { case kc::BasicDB::Error::NOIMPL: { rv = kt::RPCClient::RVENOIMPL; break; } case kc::BasicDB::Error::NOREC: { rv = kt::RPCClient::RVELOGIC; break; } default: { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; break; } } } } else { if (cur->jump_back()) { rv = kt::RPCClient::RVSUCCESS; } else { const kc::BasicDB::Error& e = cur->error(); set_db_error(outmap, e); switch (e.code()) { case kc::BasicDB::Error::NOIMPL: { rv = kt::RPCClient::RVENOIMPL; break; } case kc::BasicDB::Error::NOREC: { rv = kt::RPCClient::RVELOGIC; break; } default: { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; break; } } } } return rv; } // process the cur_step procedure RV do_cur_step(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB::Cursor* cur, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!cur) { set_message(outmap, "ERROR", "no such cursor"); return kt::RPCClient::RVEINVALID; } RV rv; opcounts_[thid][CNTMISC]++; if (cur->step()) { rv = kt::RPCClient::RVSUCCESS; } else { const kc::BasicDB::Error& e = cur->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::NOREC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } return rv; } // process the cur_step_back procedure RV do_cur_step_back(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB::Cursor* cur, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!cur) { set_message(outmap, "ERROR", "no such cursor"); return kt::RPCClient::RVEINVALID; } RV rv; opcounts_[thid][CNTMISC]++; if (cur->step_back()) { rv = kt::RPCClient::RVSUCCESS; } else { const kc::BasicDB::Error& e = cur->error(); set_db_error(outmap, e); switch (e.code()) { case kc::BasicDB::Error::NOIMPL: { rv = kt::RPCClient::RVENOIMPL; break; } case kc::BasicDB::Error::NOREC: { rv = kt::RPCClient::RVELOGIC; break; } default: { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; break; } } } return rv; } // process the cur_set_value procedure RV do_cur_set_value(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB::Cursor* cur, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!cur) { set_message(outmap, "ERROR", "no such cursor"); return kt::RPCClient::RVEINVALID; } size_t vsiz; const char* vbuf = kt::strmapget(inmap, "value", &vsiz); if (!vbuf) { set_message(outmap, "ERROR", "invalid parameters"); return kt::RPCClient::RVEINVALID; } const char* rp = kt::strmapget(inmap, "step"); bool step = rp ? true : false; rp = kt::strmapget(inmap, "xt"); int64_t xt = rp ? kc::atoi(rp) : kc::INT64MAX; RV rv; opcounts_[thid][CNTSET]++; if (cur->set_value(vbuf, vsiz, xt, step)) { rv = kt::RPCClient::RVSUCCESS; } else { opcounts_[thid][CNTSETMISS]++; const kc::BasicDB::Error& e = cur->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::NOREC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } return rv; } // process the remove procedure RV do_cur_remove(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB::Cursor* cur, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!cur) { set_message(outmap, "ERROR", "no such cursor"); return kt::RPCClient::RVEINVALID; } RV rv; opcounts_[thid][CNTREMOVE]++; if (cur->remove()) { rv = kt::RPCClient::RVSUCCESS; } else { opcounts_[thid][CNTREMOVEMISS]++; const kc::BasicDB::Error& e = cur->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::NOREC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } return rv; } // process the cur_get_key procedure RV do_cur_get_key(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB::Cursor* cur, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!cur) { set_message(outmap, "ERROR", "no such cursor"); return kt::RPCClient::RVEINVALID; } const char* rp = kt::strmapget(inmap, "step"); bool step = rp ? true : false; RV rv; opcounts_[thid][CNTGET]++; size_t ksiz; char* kbuf = cur->get_key(&ksiz, step); if (kbuf) { outmap["key"] = std::string(kbuf, ksiz); delete[] kbuf; rv = kt::RPCClient::RVSUCCESS; } else { opcounts_[thid][CNTGETMISS]++; const kc::BasicDB::Error& e = cur->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::NOREC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } return rv; } // process the cur_get_value procedure RV do_cur_get_value(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB::Cursor* cur, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!cur) { set_message(outmap, "ERROR", "no such cursor"); return kt::RPCClient::RVEINVALID; } const char* rp = kt::strmapget(inmap, "step"); bool step = rp ? true : false; RV rv; opcounts_[thid][CNTGET]++; size_t vsiz; char* vbuf = cur->get_value(&vsiz, step); if (vbuf) { outmap["value"] = std::string(vbuf, vsiz); delete[] vbuf; rv = kt::RPCClient::RVSUCCESS; } else { opcounts_[thid][CNTGETMISS]++; const kc::BasicDB::Error& e = cur->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::NOREC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } return rv; } // process the cur_get procedure RV do_cur_get(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB::Cursor* cur, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!cur) { set_message(outmap, "ERROR", "no such cursor"); return kt::RPCClient::RVEINVALID; } const char* rp = kt::strmapget(inmap, "step"); bool step = rp ? true : false; RV rv; opcounts_[thid][CNTGET]++; size_t ksiz, vsiz; const char* vbuf; int64_t xt; char* kbuf = cur->get(&ksiz, &vbuf, &vsiz, &xt, step); if (kbuf) { outmap["key"] = std::string(kbuf, ksiz); outmap["value"] = std::string(vbuf, vsiz); if (xt < kt::TimedDB::XTMAX) set_message(outmap, "xt", "%lld", (long long)xt); delete[] kbuf; rv = kt::RPCClient::RVSUCCESS; } else { opcounts_[thid][CNTGETMISS]++; const kc::BasicDB::Error& e = cur->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::NOREC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } return rv; } // process the cur_seize procedure RV do_cur_seize(kt::RPCServer* serv, kt::RPCServer::Session* sess, kt::TimedDB::Cursor* cur, const std::map<std::string, std::string>& inmap, std::map<std::string, std::string>& outmap) { uint32_t thid = sess->thread_id(); if (!cur) { set_message(outmap, "ERROR", "no such cursor"); return kt::RPCClient::RVEINVALID; } RV rv; opcounts_[thid][CNTGET]++; size_t ksiz, vsiz; const char* vbuf; int64_t xt; char* kbuf = cur->seize(&ksiz, &vbuf, &vsiz, &xt); if (kbuf) { outmap["key"] = std::string(kbuf, ksiz); outmap["value"] = std::string(vbuf, vsiz); if (xt < kt::TimedDB::XTMAX) set_message(outmap, "xt", "%lld", (long long)xt); delete[] kbuf; rv = kt::RPCClient::RVSUCCESS; } else { opcounts_[thid][CNTGETMISS]++; const kc::BasicDB::Error& e = cur->error(); set_db_error(outmap, e); if (e == kc::BasicDB::Error::NOREC) { rv = kt::RPCClient::RVELOGIC; } else { log_db_error(serv, e); rv = kt::RPCClient::RVEINTERNAL; } } return rv; } // process the restful get command int32_t do_rest_get(kt::HTTPServer* serv, kt::HTTPServer::Session* sess, kt::TimedDB* db, const char* kbuf, size_t ksiz, const std::map<std::string, std::string>& reqheads, const std::string& reqbody, std::map<std::string, std::string>& resheads, std::string& resbody, const std::map<std::string, std::string>& misc) { uint32_t thid = sess->thread_id(); int32_t code; opcounts_[thid][CNTGET]++; size_t vsiz; int64_t xt; const char* vbuf = db->get(kbuf, ksiz, &vsiz, &xt); if (vbuf) { resbody.append(vbuf, vsiz); if (xt < kt::TimedDB::XTMAX) { char buf[48]; kt::datestrhttp(xt, 0, buf); resheads["x-kt-xt"] = buf; } delete[] vbuf; code = 200; } else { opcounts_[thid][CNTGETMISS]++; const kc::BasicDB::Error& e = db->error(); kc::strprintf(&resheads["x-kt-error"], "DB: %d: %s: %s", e.code(), e.name(), e.message()); if (e == kc::BasicDB::Error::NOREC) { code = 404; } else { log_db_error(serv, e); code = 500; } } return code; } // process the restful head command int32_t do_rest_head(kt::HTTPServer* serv, kt::HTTPServer::Session* sess, kt::TimedDB* db, const char* kbuf, size_t ksiz, const std::map<std::string, std::string>& reqheads, const std::string& reqbody, std::map<std::string, std::string>& resheads, std::string& resbody, const std::map<std::string, std::string>& misc) { uint32_t thid = sess->thread_id(); int32_t code; opcounts_[thid][CNTGET]++; size_t vsiz; int64_t xt; const char* vbuf = db->get(kbuf, ksiz, &vsiz, &xt); if (vbuf) { if (xt < kt::TimedDB::XTMAX) { char buf[48]; kt::datestrhttp(xt, 0, buf); resheads["x-kt-xt"] = buf; } kc::strprintf(&resheads["content-length"], "%lld", (long long)vsiz); delete[] vbuf; code = 200; } else { opcounts_[thid][CNTGETMISS]++; const kc::BasicDB::Error& e = db->error(); kc::strprintf(&resheads["x-kt-error"], "DB: %d: %s: %s", e.code(), e.name(), e.message()); resheads["content-length"] = "0"; if (e == kc::BasicDB::Error::NOREC) { code = 404; } else { log_db_error(serv, e); code = 500; } } return code; } // process the restful put command int32_t do_rest_put(kt::HTTPServer* serv, kt::HTTPServer::Session* sess, kt::TimedDB* db, const char* kbuf, size_t ksiz, const std::map<std::string, std::string>& reqheads, const std::string& reqbody, std::map<std::string, std::string>& resheads, std::string& resbody, const std::map<std::string, std::string>& misc) { uint32_t thid = sess->thread_id(); int32_t mode = 0; const char* rp = kt::strmapget(reqheads, "x-kt-mode"); if (rp) { if (!kc::stricmp(rp, "add")) { mode = 1; } else if (!kc::stricmp(rp, "replace")) { mode = 2; } } rp = kt::strmapget(reqheads, "x-kt-xt"); int64_t xt = rp ? kt::strmktime(rp) : -1; xt = xt > 0 && xt < kt::TimedDB::XTMAX ? -xt : kc::INT64MAX; int32_t code; opcounts_[thid][CNTSET]++; bool rv; switch (mode) { default: { rv = db->set(kbuf, ksiz, reqbody.data(), reqbody.size(), xt); break; } case 1: { rv = db->add(kbuf, ksiz, reqbody.data(), reqbody.size(), xt); break; } case 2: { rv = db->replace(kbuf, ksiz, reqbody.data(), reqbody.size(), xt); break; } } if (rv) { const char* url = kt::strmapget(misc, "url"); if (url) resheads["location"] = url; code = 201; } else { opcounts_[thid][CNTSETMISS]++; const kc::BasicDB::Error& e = db->error(); kc::strprintf(&resheads["x-kt-error"], "DB: %d: %s: %s", e.code(), e.name(), e.message()); if (e == kc::BasicDB::Error::DUPREC || e == kc::BasicDB::Error::NOREC) { code = 450; } else { log_db_error(serv, e); code = 500; } } return code; } // process the restful delete command int32_t do_rest_delete(kt::HTTPServer* serv, kt::HTTPServer::Session* sess, kt::TimedDB* db, const char* kbuf, size_t ksiz, const std::map<std::string, std::string>& reqheads, const std::string& reqbody, std::map<std::string, std::string>& resheads, std::string& resbody, const std::map<std::string, std::string>& misc) { uint32_t thid = sess->thread_id(); int32_t code; opcounts_[thid][CNTREMOVE]++; if (db->remove(kbuf, ksiz)) { code = 204; } else { opcounts_[thid][CNTREMOVEMISS]++; const kc::BasicDB::Error& e = db->error(); kc::strprintf(&resheads["x-kt-error"], "DB: %d: %s: %s", e.code(), e.name(), e.message()); if (e == kc::BasicDB::Error::NOREC) { code = 404; } else { log_db_error(serv, e); code = 500; } } return code; } // process the binary replication command bool do_bin_replication(kt::ThreadedServer* serv, kt::ThreadedServer::Session* sess) { char tbuf[sizeof(uint32_t)+sizeof(uint64_t)+sizeof(uint16_t)]; if (!sess->receive(tbuf, sizeof(tbuf))) return false; const char* rp = tbuf; uint32_t flags = kc::readfixnum(rp, sizeof(flags)); rp += sizeof(flags); uint64_t ts = kc::readfixnum(rp, sizeof(ts)); rp += sizeof(ts); uint16_t sid = kc::readfixnum(rp, sizeof(sid)); bool white = flags & kt::ReplicationClient::WHITESID; bool err = false; if (ulog_) { kt::UpdateLogger::Reader ulrd; if (ulrd.open(ulog_, ts)) { char c = kt::RemoteDB::BMREPLICATION; if (sess->send(&c, 1)) { serv->log(kt::ThreadedServer::Logger::SYSTEM, "a slave was connected: ts=%llu sid=%u", (unsigned long long)ts, sid); char stack[kc::NUMBUFSIZ+RECBUFSIZ*4]; uint64_t rts = 0; int32_t miss = 0; while (!err && !serv->aborted()) { size_t msiz; uint64_t mts; char* mbuf = ulrd.read(&msiz, &mts); if (mbuf) { size_t rsiz; uint16_t rsid = 0; uint16_t rdbid = 0; const char* rbuf = DBUpdateLogger::parse(mbuf, msiz, &rsiz, &rsid, &rdbid); if (white) { if (rsid != sid) rbuf = NULL; } else { if (rsid == sid) rbuf = NULL; } if (rbuf) { miss = 0; size_t nsiz = 1 + sizeof(uint64_t) + sizeof(uint32_t) + msiz; char* nbuf = nsiz > sizeof(stack) ? new char[nsiz] : stack; char* wp = nbuf; *(wp++) = kt::RemoteDB::BMREPLICATION; kc::writefixnum(wp, mts, sizeof(uint64_t)); wp += sizeof(uint64_t); kc::writefixnum(wp, msiz, sizeof(uint32_t)); wp += sizeof(uint32_t); std::memcpy(wp, mbuf, msiz); if (!sess->send(nbuf, nsiz)) err = true; if (nbuf != stack) delete[] nbuf; } else { miss++; if (miss >= Slave::DUMMYFREQ) { char hbuf[1+sizeof(uint64_t)+sizeof(uint32_t)]; char* wp = hbuf; *(wp++) = kt::RemoteDB::BMREPLICATION; kc::writefixnum(wp, mts, sizeof(uint64_t)); wp += sizeof(uint64_t); kc::writefixnum(wp, 0, sizeof(uint32_t)); if (!sess->send(hbuf, sizeof(hbuf))) err = true; miss = 0; } } if (mts > rts) rts = mts; delete[] mbuf; } else { uint64_t cc = kt::UpdateLogger::clock_pure(); if (cc > 1000000000) cc -= 1000000000; if (cc < rts) cc = rts; char hbuf[1+sizeof(uint64_t)]; char* wp = hbuf; *(wp++) = kt::RemoteDB::BMNOP; kc::writefixnum(wp, cc, sizeof(uint64_t)); if (!sess->send(hbuf, sizeof(hbuf)) || sess->receive_byte() != kt::RemoteDB::BMREPLICATION) err = true; kc::Thread::sleep(0.1); } } serv->log(kt::ThreadedServer::Logger::SYSTEM, "a slave was disconnected: sid=%u", sid); if (!ulrd.close()) { serv->log(kt::ThreadedServer::Logger::ERROR, "closing an update log reader failed"); err = true; } } else { err = true; } } else { serv->log(kt::ThreadedServer::Logger::ERROR, "opening an update log reader failed"); char c = kt::RemoteDB::BMERROR; sess->send(&c, 1); err = true; } } else { char c = kt::RemoteDB::BMERROR; sess->send(&c, 1); serv->log(kt::ThreadedServer::Logger::INFO, "no update log allows no replication"); err = true; } return !err; } // process the binary play_script command bool do_bin_play_script(kt::ThreadedServer* serv, kt::ThreadedServer::Session* sess) { uint32_t thid = sess->thread_id(); char tbuf[sizeof(uint32_t)+sizeof(uint32_t)+sizeof(uint32_t)]; if (!sess->receive(tbuf, sizeof(tbuf))) return false; const char* rp = tbuf; uint32_t flags = kc::readfixnum(rp, sizeof(flags)); rp += sizeof(flags); uint32_t nsiz = kc::readfixnum(rp, sizeof(nsiz)); rp += sizeof(nsiz); uint32_t rnum = kc::readfixnum(rp, sizeof(rnum)); rp += sizeof(rnum); if (nsiz > kt::RemoteDB::DATAMAXSIZ) return false; bool norep = flags & kt::RemoteDB::BONOREPLY; bool err = false; char nstack[kc::NUMBUFSIZ+RECBUFSIZ]; char* nbuf = nsiz + 1 > sizeof(nstack) ? new char[nsiz+1] : nstack; if (sess->receive(nbuf, nsiz)) { nbuf[nsiz] = '\0'; char stack[kc::NUMBUFSIZ+RECBUFSIZ*4]; std::map<std::string, std::string> scrinmap; for (uint32_t i = 0; !err && i < rnum; i++) { char hbuf[sizeof(uint32_t)+sizeof(uint32_t)]; if (sess->receive(hbuf, sizeof(hbuf))) { rp = hbuf; uint32_t ksiz = kc::readfixnum(rp, sizeof(ksiz)); rp += sizeof(ksiz); uint32_t vsiz = kc::readfixnum(rp, sizeof(vsiz)); rp += sizeof(vsiz); if (ksiz <= kt::RemoteDB::DATAMAXSIZ && vsiz <= kt::RemoteDB::DATAMAXSIZ) { size_t rsiz = ksiz + vsiz; char* rbuf = rsiz > sizeof(stack) ? new char[rsiz] : stack; if (sess->receive(rbuf, rsiz)) { std::string key(rbuf, ksiz); std::string value(rbuf + ksiz, vsiz); scrinmap[key] = value; } else { err = true; } if (rbuf != stack) delete[] rbuf; } else { err = true; } } else { err = true; } } if (!err) { if (scrprocs_) { ScriptProcessor* scrproc = scrprocs_ + thid; opcounts_[thid][CNTSCRIPT]++; std::map<std::string, std::string> scroutmap; RV rv = scrproc->call(nbuf, scrinmap, scroutmap); if (rv == kt::RPCClient::RVSUCCESS) { size_t osiz = 1 + sizeof(uint32_t); std::map<std::string, std::string>::iterator it = scroutmap.begin(); std::map<std::string, std::string>::iterator itend = scroutmap.end(); while (it != itend) { osiz += sizeof(uint32_t) + sizeof(uint32_t) + it->first.size() + it->second.size(); ++it; } char* obuf = new char[osiz]; char* wp = obuf; *(wp++) = kt::RemoteDB::BMPLAYSCRIPT; kc::writefixnum(wp, scroutmap.size(), sizeof(uint32_t)); wp += sizeof(uint32_t); it = scroutmap.begin(); itend = scroutmap.end(); while (it != itend) { kc::writefixnum(wp, it->first.size(), sizeof(uint32_t)); wp += sizeof(uint32_t); kc::writefixnum(wp, it->second.size(), sizeof(uint32_t)); wp += sizeof(uint32_t); std::memcpy(wp, it->first.data(), it->first.size()); wp += it->first.size(); std::memcpy(wp, it->second.data(), it->second.size()); wp += it->second.size(); ++it; } if (!norep && !sess->send(obuf, osiz)) err = true; delete[] obuf; } else { char c = kt::RemoteDB::BMERROR; if (!norep) sess->send(&c, 1); } } else { char c = kt::RemoteDB::BMERROR; if (!norep) sess->send(&c, 1); } } } if (nbuf != nstack) delete[] nbuf; return !err; } // process the binary set_bulk command bool do_bin_set_bulk(kt::ThreadedServer* serv, kt::ThreadedServer::Session* sess) { uint32_t thid = sess->thread_id(); char tbuf[sizeof(uint32_t)+sizeof(uint32_t)]; if (!sess->receive(tbuf, sizeof(tbuf))) return false; const char* rp = tbuf; uint32_t flags = kc::readfixnum(rp, sizeof(flags)); rp += sizeof(flags); uint32_t rnum = kc::readfixnum(rp, sizeof(rnum)); rp += sizeof(rnum); bool norep = flags & kt::RemoteDB::BONOREPLY; bool err = false; uint32_t hits = 0; char stack[kc::NUMBUFSIZ+RECBUFSIZ*4]; for (uint32_t i = 0; !err && i < rnum; i++) { char hbuf[sizeof(uint16_t)+sizeof(uint32_t)+sizeof(uint32_t)+sizeof(int64_t)]; if (sess->receive(hbuf, sizeof(hbuf))) { rp = hbuf; uint16_t dbidx = kc::readfixnum(rp, sizeof(dbidx)); rp += sizeof(dbidx); uint32_t ksiz = kc::readfixnum(rp, sizeof(ksiz)); rp += sizeof(ksiz); uint32_t vsiz = kc::readfixnum(rp, sizeof(vsiz)); rp += sizeof(vsiz); int64_t xt = kc::readfixnum(rp, sizeof(xt)); rp += sizeof(xt); if (ksiz <= kt::RemoteDB::DATAMAXSIZ && vsiz <= kt::RemoteDB::DATAMAXSIZ) { size_t rsiz = ksiz + vsiz; char* rbuf = rsiz > sizeof(stack) ? new char[rsiz] : stack; if (sess->receive(rbuf, rsiz)) { if (dbidx < dbnum_) { kt::TimedDB* db = dbs_ + dbidx; opcounts_[thid][CNTSET]++; if (db->set(rbuf, ksiz, rbuf + ksiz, vsiz, xt)) { hits++; } else { opcounts_[thid][CNTSETMISS]++; err = true; } } } else { err = true; } if (rbuf != stack) delete[] rbuf; } else { err = true; } } else { err = true; } } if (err) { char c = kt::RemoteDB::BMERROR; if (!norep) sess->send(&c, 1); } else { char hbuf[1+sizeof(hits)]; char* wp = hbuf; *(wp++) = kt::RemoteDB::BMSETBULK; kc::writefixnum(wp, hits, sizeof(hits)); if (!norep && !sess->send(hbuf, sizeof(hbuf))) err = true; } return !err; } // process the binary remove_bulk command bool do_bin_remove_bulk(kt::ThreadedServer* serv, kt::ThreadedServer::Session* sess) { uint32_t thid = sess->thread_id(); char tbuf[sizeof(uint32_t)+sizeof(uint32_t)]; if (!sess->receive(tbuf, sizeof(tbuf))) return false; const char* rp = tbuf; uint32_t flags = kc::readfixnum(rp, sizeof(flags)); rp += sizeof(flags); uint32_t rnum = kc::readfixnum(rp, sizeof(rnum)); rp += sizeof(rnum); bool norep = flags & kt::RemoteDB::BONOREPLY; bool err = false; uint32_t hits = 0; char stack[kc::NUMBUFSIZ+RECBUFSIZ*2]; for (uint32_t i = 0; !err && i < rnum; i++) { char hbuf[sizeof(uint16_t)+sizeof(uint32_t)]; if (sess->receive(hbuf, sizeof(hbuf))) { rp = hbuf; uint16_t dbidx = kc::readfixnum(rp, sizeof(dbidx)); rp += sizeof(dbidx); uint32_t ksiz = kc::readfixnum(rp, sizeof(ksiz)); rp += sizeof(ksiz); if (ksiz <= kt::RemoteDB::DATAMAXSIZ) { char* kbuf = ksiz > sizeof(stack) ? new char[ksiz] : stack; if (sess->receive(kbuf, ksiz)) { if (dbidx < dbnum_) { kt::TimedDB* db = dbs_ + dbidx; opcounts_[thid][CNTREMOVE]++; if (db->remove(kbuf, ksiz)) { hits++; } else { opcounts_[thid][CNTREMOVEMISS]++; if (db->error() != kc::BasicDB::Error::NOREC) err = true; } } } else { err = true; } if (kbuf != stack) delete[] kbuf; } else { err = true; } } else { err = true; } } if (err) { char c = kt::RemoteDB::BMERROR; if (!norep) sess->send(&c, 1); } else { char hbuf[1+sizeof(hits)]; char* wp = hbuf; *(wp++) = kt::RemoteDB::BMREMOVEBULK; kc::writefixnum(wp, hits, sizeof(hits)); if (!norep && !sess->send(hbuf, sizeof(hbuf))) err = true; } return !err; } // process the binary get_bulk command bool do_bin_get_bulk(kt::ThreadedServer* serv, kt::ThreadedServer::Session* sess) { uint32_t thid = sess->thread_id(); char tbuf[sizeof(uint32_t)+sizeof(uint32_t)]; if (!sess->receive(tbuf, sizeof(tbuf))) return false; const char* rp = tbuf; uint32_t flags = kc::readfixnum(rp, sizeof(flags)); rp += sizeof(flags); uint32_t rnum = kc::readfixnum(rp, sizeof(rnum)); rp += sizeof(rnum); bool err = false; uint32_t hits = 0; char stack[kc::NUMBUFSIZ+RECBUFSIZ*2]; size_t oasiz = kc::NUMBUFSIZ + RECBUFSIZ * 2; char* obuf = (char*)kc::xmalloc(oasiz); size_t osiz = 1 + sizeof(uint32_t); std::memset(obuf, 0, osiz); for (uint32_t i = 0; !err && i < rnum; i++) { char hbuf[sizeof(uint16_t)+sizeof(uint32_t)]; if (sess->receive(hbuf, sizeof(hbuf))) { rp = hbuf; uint16_t dbidx = kc::readfixnum(rp, sizeof(dbidx)); rp += sizeof(dbidx); uint32_t ksiz = kc::readfixnum(rp, sizeof(ksiz)); rp += sizeof(ksiz); if (ksiz <= kt::RemoteDB::DATAMAXSIZ) { char* kbuf = ksiz > sizeof(stack) ? new char[ksiz] : stack; if (sess->receive(kbuf, ksiz)) { if (dbidx < dbnum_) { kt::TimedDB* db = dbs_ + dbidx; opcounts_[thid][CNTGET]++; size_t vsiz; int64_t xt; char* vbuf = db->get(kbuf, ksiz, &vsiz, &xt); if (vbuf) { hits++; size_t usiz = sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint32_t) + sizeof(int64_t) + ksiz + vsiz; if (osiz + usiz > oasiz) { oasiz = oasiz * 2 + usiz; obuf = (char*)kc::xrealloc(obuf, oasiz); } kc::writefixnum(obuf + osiz, dbidx, sizeof(uint16_t)); osiz += sizeof(uint16_t); kc::writefixnum(obuf + osiz, ksiz, sizeof(uint32_t)); osiz += sizeof(uint32_t); kc::writefixnum(obuf + osiz, vsiz, sizeof(uint32_t)); osiz += sizeof(uint32_t); kc::writefixnum(obuf + osiz, xt, sizeof(int64_t)); osiz += sizeof(int64_t); std::memcpy(obuf + osiz, kbuf, ksiz); osiz += ksiz; std::memcpy(obuf + osiz, vbuf, vsiz); osiz += vsiz; delete[] vbuf; } else { opcounts_[thid][CNTGETMISS]++; if (db->error() != kc::BasicDB::Error::NOREC) err = true; } } } else { err = true; } if (kbuf != stack) delete[] kbuf; } else { err = true; } } else { err = true; } } if (err) { char c = kt::RemoteDB::BMERROR; sess->send(&c, 1); } else { *obuf = kt::RemoteDB::BMGETBULK; kc::writefixnum(obuf + 1, hits, sizeof(hits)); if (!sess->send(obuf, osiz)) err = true; } kc::xfree(obuf); return !err; } // session local storage class SLS : public kt::RPCServer::Session::Data { friend class Worker; private: SLS() : curs_() {} ~SLS() { std::map<int64_t, kt::TimedDB::Cursor*>::iterator it = curs_.begin(); std::map<int64_t, kt::TimedDB::Cursor*>::iterator itend = curs_.end(); while (it != itend) { kt::TimedDB::Cursor* cur = it->second; delete cur; ++it; } } static SLS* create(kt::RPCServer::Session* sess) { SLS* sls = (SLS*)sess->data(); if (!sls) { sls = new SLS; sess->set_data(sls); } return sls; } std::map<int64_t, kt::TimedDB::Cursor*> curs_; }; int32_t thnum_; kc::CondMap* const condmap_; kt::TimedDB* const dbs_; const int32_t dbnum_; const std::map<std::string, int32_t>& dbmap_; const int32_t omode_; const double asi_; const bool ash_; const char* const bgspath_; const double bgsi_; kc::Compressor* const bgscomp_; kt::UpdateLogger* const ulog_; DBUpdateLogger* const ulogdbs_; const char* const cmdpath_; ScriptProcessor* const scrprocs_; OpCount* const opcounts_; uint64_t idlecnt_; double asnext_; double bgsnext_; Slave* slave_; }; // main routine int main(int argc, char** argv) { g_progname = argv[0]; g_procid = kc::getpid(); g_starttime = kc::time(); kc::setstdiobin(); kt::setkillsignalhandler(killserver); if (argc > 1 && !std::strcmp(argv[1], "--version")) { printversion(); return 0; } int32_t rv = run(argc, argv); return rv; } // print the usage and exit static void usage() { eprintf("%s: Kyoto Tycoon: a handy cache/storage server\n", g_progname); eprintf("\n"); eprintf("usage:\n"); eprintf(" %s [-host str] [-port num] [-tout num] [-th num] [-log file] [-li|-ls|-le|-lz]" " [-ulog dir] [-ulim num] [-uasi num] [-sid num] [-ord] [-oat|-oas|-onl|-otl|-onr]" " [-asi num] [-ash] [-bgs dir] [-bgsi num] [-bgsc str]" " [-dmn] [-pid file] [-cmd dir] [-scr file]" " [-mhost str] [-mport num] [-rts file] [-riv num]" " [-plsv file] [-plex str] [-pldb file] [db...]\n", g_progname); eprintf("\n"); std::exit(1); } // kill the running server static void killserver(int signum) { if (g_serv) { g_serv->stop(); g_serv = NULL; if (g_daemon && signum == SIGHUP) g_restart = true; if (signum == SIGUSR1) g_restart = true; } } // parse arguments of the command static int32_t run(int argc, char** argv) { bool argbrk = false; std::vector<std::string> dbpaths; const char* host = NULL; int32_t port = kt::DEFPORT; double tout = DEFTOUT; int32_t thnum = DEFTHNUM; const char* logpath = NULL; uint32_t logkinds = kc::UINT32MAX; const char* ulogpath = NULL; int64_t ulim = DEFULIM; double uasi = 0; int32_t sid = -1; int32_t omode = kc::BasicDB::OWRITER | kc::BasicDB::OCREATE; double asi = 0; bool ash = false; const char* bgspath = NULL; double bgsi = DEFBGSI; kc::Compressor* bgscomp = NULL; bool dmn = false; const char* pidpath = NULL; const char* cmdpath = NULL; const char* scrpath = NULL; const char* mhost = NULL; int32_t mport = kt::DEFPORT; const char* rtspath = NULL; double riv = DEFRIV; const char* plsvpath = NULL; const char* plsvex = ""; const char* pldbpath = NULL; for (int32_t i = 1; i < argc; i++) { if (!argbrk && argv[i][0] == '-') { if (!std::strcmp(argv[i], "--")) { argbrk = true; } else if (!std::strcmp(argv[i], "-host")) { if (++i >= argc) usage(); host = argv[i]; } else if (!std::strcmp(argv[i], "-port")) { if (++i >= argc) usage(); port = kc::atoix(argv[i]); } else if (!std::strcmp(argv[i], "-tout")) { if (++i >= argc) usage(); tout = kc::atof(argv[i]); } else if (!std::strcmp(argv[i], "-th")) { if (++i >= argc) usage(); thnum = kc::atof(argv[i]); } else if (!std::strcmp(argv[i], "-log")) { if (++i >= argc) usage(); logpath = argv[i]; } else if (!std::strcmp(argv[i], "-li")) { logkinds = Logger::INFO | Logger::SYSTEM | Logger::ERROR; } else if (!std::strcmp(argv[i], "-ls")) { logkinds = Logger::SYSTEM | Logger::ERROR; } else if (!std::strcmp(argv[i], "-le")) { logkinds = Logger::ERROR; } else if (!std::strcmp(argv[i], "-lz")) { logkinds = 0; } else if (!std::strcmp(argv[i], "-ulog")) { if (++i >= argc) usage(); ulogpath = argv[i]; } else if (!std::strcmp(argv[i], "-ulim")) { if (++i >= argc) usage(); ulim = kc::atoix(argv[i]); } else if (!std::strcmp(argv[i], "-uasi")) { if (++i >= argc) usage(); uasi = kc::atof(argv[i]); } else if (!std::strcmp(argv[i], "-sid")) { if (++i >= argc) usage(); sid = kc::atoix(argv[i]); } else if (!std::strcmp(argv[i], "-ord")) { omode &= ~kc::BasicDB::OWRITER; omode |= kc::BasicDB::OREADER; } else if (!std::strcmp(argv[i], "-oat")) { omode |= kc::BasicDB::OAUTOTRAN; } else if (!std::strcmp(argv[i], "-oas")) { omode |= kc::BasicDB::OAUTOSYNC; } else if (!std::strcmp(argv[i], "-onl")) { omode |= kc::BasicDB::ONOLOCK; } else if (!std::strcmp(argv[i], "-otl")) { omode |= kc::BasicDB::OTRYLOCK; } else if (!std::strcmp(argv[i], "-onr")) { omode |= kc::BasicDB::ONOREPAIR; } else if (!std::strcmp(argv[i], "-asi")) { if (++i >= argc) usage(); asi = kc::atof(argv[i]); } else if (!std::strcmp(argv[i], "-ash")) { ash = true; } else if (!std::strcmp(argv[i], "-bgs")) { if (++i >= argc) usage(); bgspath = argv[i]; } else if (!std::strcmp(argv[i], "-bgsi")) { if (++i >= argc) usage(); bgsi = kc::atof(argv[i]); } else if (!std::strcmp(argv[i], "-bgsc")) { if (++i >= argc) usage(); const char* cn = argv[i]; if (!kc::stricmp(cn, "zlib") || !kc::stricmp(cn, "gz")) { bgscomp = new kc::ZLIBCompressor<kc::ZLIB::RAW>; } else if (!kc::stricmp(cn, "lzo") || !kc::stricmp(cn, "oz")) { bgscomp = new kc::LZOCompressor<kc::LZO::RAW>; } else if (!kc::stricmp(cn, "lzma") || !kc::stricmp(cn, "xz")) { bgscomp = new kc::LZMACompressor<kc::LZMA::RAW>; } } else if (!std::strcmp(argv[i], "-dmn")) { dmn = true; } else if (!std::strcmp(argv[i], "-pid")) { if (++i >= argc) usage(); pidpath = argv[i]; } else if (!std::strcmp(argv[i], "-cmd")) { if (++i >= argc) usage(); cmdpath = argv[i]; } else if (!std::strcmp(argv[i], "-scr")) { if (++i >= argc) usage(); scrpath = argv[i]; } else if (!std::strcmp(argv[i], "-mhost")) { if (++i >= argc) usage(); mhost = argv[i]; } else if (!std::strcmp(argv[i], "-mport")) { if (++i >= argc) usage(); mport = kc::atoix(argv[i]); } else if (!std::strcmp(argv[i], "-rts")) { if (++i >= argc) usage(); rtspath = argv[i]; } else if (!std::strcmp(argv[i], "-riv")) { if (++i >= argc) usage(); riv = kc::atof(argv[i]); } else if (!std::strcmp(argv[i], "-plsv")) { if (++i >= argc) usage(); plsvpath = argv[i]; } else if (!std::strcmp(argv[i], "-plex")) { if (++i >= argc) usage(); plsvex = argv[i]; } else if (!std::strcmp(argv[i], "-pldb")) { if (++i >= argc) usage(); pldbpath = argv[i]; } else { usage(); } } else { argbrk = true; dbpaths.push_back(argv[i]); } } if (port < 1 || thnum < 1 || mport < 1) usage(); if (thnum > THREADMAX) thnum = THREADMAX; if (dbpaths.empty()) { if (pldbpath) usage(); dbpaths.push_back(":"); } int32_t rv = proc(dbpaths, host, port, tout, thnum, logpath, logkinds, ulogpath, ulim, uasi, sid, omode, asi, ash, bgspath, bgsi, bgscomp, dmn, pidpath, cmdpath, scrpath, mhost, mport, rtspath, riv, plsvpath, plsvex, pldbpath); delete bgscomp; return rv; } // drive the server process static int32_t proc(const std::vector<std::string>& dbpaths, const char* host, int32_t port, double tout, int32_t thnum, const char* logpath, uint32_t logkinds, const char* ulogpath, int64_t ulim, double uasi, int32_t sid, int32_t omode, double asi, bool ash, const char* bgspath, double bgsi, kc::Compressor* bgscomp, bool dmn, const char* pidpath, const char* cmdpath, const char* scrpath, const char* mhost, int32_t mport, const char* rtspath, double riv, const char* plsvpath, const char* plsvex, const char* pldbpath) { g_daemon = false; if (dmn) { if (kc::File::PATHCHR == '/') { if (logpath && *logpath != kc::File::PATHCHR) { eprintf("%s: %s: a daemon can accept absolute path only\n", g_progname, logpath); return 1; } if (ulogpath && *ulogpath != kc::File::PATHCHR) { eprintf("%s: %s: a daemon can accept absolute path only\n", g_progname, ulogpath); return 1; } if (bgspath && *bgspath != kc::File::PATHCHR) { eprintf("%s: %s: a daemon can accept absolute path only\n", g_progname, bgspath); return 1; } if (pidpath && *pidpath != kc::File::PATHCHR) { eprintf("%s: %s: a daemon can accept absolute path only\n", g_progname, pidpath); return 1; } if (cmdpath && *cmdpath != kc::File::PATHCHR) { eprintf("%s: %s: a daemon can accept absolute path only\n", g_progname, cmdpath); return 1; } if (scrpath && *scrpath != kc::File::PATHCHR) { eprintf("%s: %s: a daemon can accept absolute path only\n", g_progname, scrpath); return 1; } if (rtspath && *rtspath != kc::File::PATHCHR) { eprintf("%s: %s: a daemon can accept absolute path only\n", g_progname, rtspath); return 1; } if (plsvpath && *plsvpath != kc::File::PATHCHR) { eprintf("%s: %s: a daemon can accept absolute path only\n", g_progname, plsvpath); return 1; } if (pldbpath && *pldbpath != kc::File::PATHCHR) { eprintf("%s: %s: a daemon can accept absolute path only\n", g_progname, pldbpath); return 1; } } if (!kt::daemonize()) { eprintf("%s: switching to a daemon failed\n", g_progname); return 1; } g_procid = kc::getpid(); g_daemon = true; } if (ulogpath && sid < 0) { eprintf("%s: update log requires the server ID\n", g_progname); return 1; } if (!cmdpath) cmdpath = kc::File::CDIRSTR; if (mhost) { if (sid < 0) { eprintf("%s: replication requires the server ID\n", g_progname); return 1; } if (!rtspath) { eprintf("%s: replication requires the replication time stamp file\n", g_progname); return 1; } } if (sid < 0) sid = 0; kc::File::Status sbuf; if (bgspath && !kc::File::status(bgspath, &sbuf) && !kc::File::make_directory(bgspath)) { eprintf("%s: %s: could not open the directory\n", g_progname, bgspath); return 1; } if (!kc::File::status(cmdpath, &sbuf) || !sbuf.isdir) { eprintf("%s: %s: no such directory\n", g_progname, cmdpath); return 1; } if (scrpath && !kc::File::status(scrpath)) { eprintf("%s: %s: no such file\n", g_progname, scrpath); return 1; } if (dbpaths.size() > (size_t)OPENDBMAX) { eprintf("%s: too much databases\n", g_progname); return 1; } kt::RPCServer serv; Logger logger; if (!logger.open(logpath)) { eprintf("%s: %s: could not open the log file\n", g_progname, logpath ? logpath : "-"); return 1; } serv.set_logger(&logger, logkinds); serv.log(Logger::SYSTEM, "================ [START]: pid=%d", g_procid); std::string addr = ""; if (host) { addr = kt::Socket::get_host_address(host); if (addr.empty()) { serv.log(Logger::ERROR, "unknown host: %s", host); return 1; } } kt::SharedLibrary pldblib; kt::KTDBINIT pldbinit = NULL; if (pldbpath) { serv.log(Logger::SYSTEM, "loading a plug-in database file: path=%s", pldbpath); if (!pldblib.open(pldbpath)) { serv.log(Logger::ERROR, "could not load a plug-in database file: %s", pldbpath); return 1; } pldbinit = (kt::KTDBINIT)pldblib.symbol(kt::KTDBINITNAME); if (!pldbinit) { serv.log(Logger::ERROR, "could not find the initializer: %s: %s", pldbpath, kt::KTDBINITNAME); return 1; } } std::string expr = kc::strprintf("%s:%d", addr.c_str(), port); serv.set_network(expr, tout); int32_t dbnum = dbpaths.size(); kt::UpdateLogger* ulog = NULL; DBUpdateLogger* ulogdbs = NULL; if (ulogpath) { ulog = new kt::UpdateLogger; serv.log(Logger::SYSTEM, "opening the update log: path=%s sid=%u", ulogpath, sid); if (!ulog->open(ulogpath, ulim, uasi)) { serv.log(Logger::ERROR, "could not open the update log: %s", ulogpath); delete ulog; return 1; } ulogdbs = new DBUpdateLogger[dbnum]; } kt::TimedDB* dbs = new kt::TimedDB[dbnum]; DBLogger dblogger(&logger, logkinds); std::map<std::string, int32_t> dbmap; for (int32_t i = 0; i < dbnum; i++) { const std::string& dbpath = dbpaths[i]; serv.log(Logger::SYSTEM, "opening a database: path=%s", dbpath.c_str()); if (logkinds != 0) dbs[i].tune_logger(&dblogger, kc::BasicDB::Logger::WARN | kc::BasicDB::Logger::ERROR); if (ulog) { ulogdbs[i].initialize(ulog, sid, i); dbs[i].tune_update_trigger(ulogdbs + i); } if (pldbinit) dbs[i].set_internal_db(pldbinit()); if (!dbs[i].open(dbpath, omode)) { const kc::BasicDB::Error& e = dbs[i].error(); serv.log(Logger::ERROR, "could not open a database file: %s: %s: %s", dbpath.c_str(), e.name(), e.message()); delete[] dbs; delete[] ulogdbs; delete ulog; return 1; } std::string path = dbs[i].path(); const char* rp = path.c_str(); const char* pv = std::strrchr(rp, kc::File::PATHCHR); if (pv) rp = pv + 1; dbmap[rp] = i; } if (bgspath) { kc::DirStream dir; if (dir.open(bgspath)) { std::string name; while (dir.read(&name)) { const char* nstr = name.c_str(); const char* pv = std::strrchr(nstr, kc::File::EXTCHR); int32_t idx = kc::atoi(nstr); if (*nstr >= '0' && *nstr <= '9' && pv && !kc::stricmp(pv + 1, BGSPATHEXT) && idx >= 0 && idx < dbnum) { std::string path; kc::strprintf(&path, "%s%c%s", bgspath, kc::File::PATHCHR, nstr); uint64_t ssts; int64_t sscount, sssize; if (kt::TimedDB::status_snapshot_atomic(path, &ssts, &sscount, &sssize)) { serv.log(Logger::SYSTEM, "applying a snapshot file: db=%d ts=%llu count=%lld size=%lld", idx, (unsigned long long)ssts, (long long)sscount, (long long)sssize); if (!dbs[idx].load_snapshot_atomic(path, bgscomp)) { const kc::BasicDB::Error& e = dbs[idx].error(); serv.log(Logger::ERROR, "could not apply a snapshot: %s: %s", e.name(), e.message()); } } } } dir.close(); } } ScriptProcessor* scrprocs = NULL; if (scrpath) { serv.log(Logger::SYSTEM, "loading a script file: path=%s", scrpath); scrprocs = new ScriptProcessor[thnum]; for (int32_t i = 0; i < thnum; i++) { if (!scrprocs[i].set_resources(i, &serv, dbs, dbnum, &dbmap)) { serv.log(Logger::ERROR, "could not initialize the scripting processor"); delete[] scrprocs; delete[] dbs; delete[] ulogdbs; delete ulog; return 1; } if (!scrprocs[i].load(scrpath)) serv.log(Logger::ERROR, "could not load a script file: %s", scrpath); } } kt::SharedLibrary plsvlib; kt::PluggableServer* plsv = NULL; if (plsvpath) { serv.log(Logger::SYSTEM, "loading a plug-in server file: path=%s", plsvpath); if (!plsvlib.open(plsvpath)) { serv.log(Logger::ERROR, "could not load a plug-in server file: %s", plsvpath); delete[] scrprocs; delete[] dbs; delete[] ulogdbs; delete ulog; return 1; } kt::KTSERVINIT init = (kt::KTSERVINIT)plsvlib.symbol(kt::KTSERVINITNAME); if (!init) { serv.log(Logger::ERROR, "could not find the initializer: %s: %s", plsvpath, kt::KTSERVINITNAME); delete[] scrprocs; delete[] dbs; delete[] ulogdbs; delete ulog; return 1; } plsv = init(); plsv->configure(dbs, dbnum, &logger, logkinds, plsvex); } OpCount* opcounts = new OpCount[thnum]; for (int32_t i = 0; i < thnum; i++) { for (int32_t j = 0; j <= CNTMISC; j++) { opcounts[i][j] = 0; } } kc::CondMap condmap; Worker worker(thnum, &condmap, dbs, dbnum, dbmap, omode, asi, ash, bgspath, bgsi, bgscomp, ulog, ulogdbs, cmdpath, scrprocs, opcounts); serv.set_worker(&worker, thnum); if (pidpath) { char numbuf[kc::NUMBUFSIZ]; size_t nsiz = std::sprintf(numbuf, "%d\n", g_procid); kc::File::write_file(pidpath, numbuf, nsiz); } bool err = false; while (true) { g_restart = false; g_serv = &serv; Slave slave(sid, rtspath, mhost, mport, riv, &serv, dbs, dbnum, ulog, ulogdbs); slave.start(); worker.set_misc_conf(&slave); PlugInDriver pldriver(plsv); if (plsv) pldriver.start(); if (serv.start()) { condmap.broadcast_all(); if (!serv.finish()) err = true; } else { err = true; } kc::Thread::sleep(0.5); if (plsv) { plsv->stop(); pldriver.join(); if (pldriver.error()) err = true; kc::Thread::sleep(0.1); } slave.stop(); slave.join(); if (!g_restart || err) break; logger.close(); if (!logger.open(logpath)) { eprintf("%s: %s: could not open the log file\n", g_progname, logpath ? logpath : "-"); err = true; break; } if (scrprocs) { serv.log(Logger::SYSTEM, "reloading a script file: path=%s", scrpath); for (int32_t i = 0; i < thnum; i++) { scrprocs[i].clear(); if (!scrprocs[i].set_resources(i, &serv, dbs, dbnum, &dbmap)) { serv.log(Logger::ERROR, "could not initialize the scripting processor"); err = true; break; } if (!scrprocs[i].load(scrpath)) serv.log(Logger::ERROR, "could not load a script file: %s", scrpath); } } if (err) break; } if (pidpath) kc::File::remove(pidpath); delete[] opcounts; if (plsv) { delete plsv; if (!plsvlib.close()) { eprintf("%s: closing a shared library failed\n", g_progname); err = true; } } if (bgspath) { serv.log(Logger::SYSTEM, "snapshotting databases"); if (!dosnapshot(bgspath, bgscomp, dbs, dbnum, &serv)) err = true; } delete[] scrprocs; for (int32_t i = 0; i < dbnum; i++) { const std::string& dbpath = dbpaths[i]; serv.log(Logger::SYSTEM, "closing a database: path=%s", dbpath.c_str()); if (!dbs[i].close()) { const kc::BasicDB::Error& e = dbs[i].error(); serv.log(Logger::ERROR, "could not close a database file: %s: %s: %s", dbpath.c_str(), e.name(), e.message()); err = true; } } delete[] dbs; if (ulog) { delete[] ulogdbs; if (!ulog->close()) { eprintf("%s: closing the update log faild\n", g_progname); err = true; } delete ulog; } if (pldbinit && !pldblib.close()) { eprintf("%s: closing a shared library failed\n", g_progname); err = true; } serv.log(Logger::SYSTEM, "================ [FINISH]: pid=%d", g_procid); return err ? 1 : 0; } // snapshot all databases static bool dosnapshot(const char* bgspath, kc::Compressor* bgscomp, kt::TimedDB* dbs, int32_t dbnum, kt::RPCServer* serv) { bool err = false; for (int32_t i = 0; i < dbnum; i++) { kt::TimedDB* db = dbs + i; std::string destpath; kc::strprintf(&destpath, "%s%c%08d%c%s", bgspath, kc::File::PATHCHR, i, kc::File::EXTCHR, BGSPATHEXT); std::string tmppath; kc::strprintf(&tmppath, "%s%ctmp", destpath.c_str(), kc::File::EXTCHR); int32_t cnt = 0; while (true) { if (db->dump_snapshot_atomic(tmppath, bgscomp)) { if (!kc::File::rename(tmppath, destpath)) { serv->log(Logger::ERROR, "renaming a file failed: %s: %s", tmppath.c_str(), destpath.c_str()); } kc::File::remove(tmppath); break; } kc::File::remove(tmppath); const kc::BasicDB::Error& e = db->error(); if (e != kc::BasicDB::Error::LOGIC) { serv->log(Logger::ERROR, "database error: %d: %s: %s", e.code(), e.name(), e.message()); break; } if (++cnt >= 3) { serv->log(Logger::SYSTEM, "snapshotting was abandoned"); err = true; break; } serv->log(Logger::INFO, "retrying snapshot: %d", cnt); } kc::Thread::yield(); } return !err; } // END OF FILE
gpl-3.0
ofenerci/Pocket-Science-Lab
Piezoelectrie-Transducer/piezoelectric-transducer.py
5006
''' GUI Program for Piezo-electric Transducer- Can be used as a impact/force sensor ExpEYES program developed as a part of GSoC-2015 project Project Tilte: Sensor Plug-ins, Add-on devices and GUI Improvements for ExpEYES Mentor Organization:FOSSASIA Mentors: Hong Phuc, Mario Behling, Rebentisch Author: Praveen Patil License : GNU GPL version 3 ''' import gettext gettext.bindtextdomain("expeyes") gettext.textdomain('expeyes') _ = gettext.gettext from Tkinter import * import time, math, sys if sys.version_info.major==3: from tkinter import * else: from Tkinter import * sys.path=[".."] + sys.path import expeyes.eyesj as eyes import expeyes.eyeplot as eyeplot import expeyes.eyemath as eyemath WIDTH = 600 # width of drawing canvas HEIGHT = 400 # height class piezo: tv = [ [], [] ] # Lists for Readings TIMER = 10 # Time interval between reads MINY = 0 MAXY = 5 running = False def xmgrace(self): if self.running == True: return p.grace([self.tv]) def start(self): self.running = True self.index = 0 self.tv = [ [], [] ] try: self.MAXTIME = int(DURATION.get()) self.MINY = int(TMIN.get()) self.MAXY = int(TMAX.get()) g.setWorld(0, self.MINY, self.MAXTIME, self.MAXY,_(''),_('')) self.TIMER = int(TGAP.get()) Total.config(state=DISABLED) Dur.config(state=DISABLED) self.msg(_('Starting the Measurements')) root.after(self.TIMER, self.update) except: self.msg(_('Failed to Start')) def stop(self): self.running = False Total.config(state=NORMAL) Dur.config(state=NORMAL) self.msg(_('User Stopped the measurements')) def update(self): if self.running == False: return t,v = p.get_voltage_time(1) # Read A1 if len(self.tv[0]) == 0: self.start_time = t elapsed = 0 else: elapsed = t - self.start_time self.tv[0].append(elapsed) self.tv[1].append(v) if len(self.tv[0]) >= 2: g.delete_lines() g.line(self.tv[0], self.tv[1],1) if elapsed > self.MAXTIME: self.running = False Total.config(state=NORMAL) Dur.config(state=NORMAL) self.msg(_('Completed the Measurements')) return root.after(self.TIMER, self.update) def save(self): try: fn = filename.get() except: fn = 'pizzo.dat' p.save([self.tv],fn) self.msg(_('Data saved to %s')%fn) def clear(self): if self.running == True: return self.nt = [ [], [] ] g.delete_lines() self.msg(_('Cleared Data and Trace')) def msg(self,s, col = 'blue'): msgwin.config(text=s, fg=col) def quit(self): p.set_state(10,0) sys.exit() p = eyes.open() p.disable_actions() root = Tk() Canvas(root, width = WIDTH, height = 5).pack(side=TOP) g = eyeplot.graph(root, width=WIDTH, height=HEIGHT, bip=False) pt = piezo() cf = Frame(root, width = WIDTH, height = 10) cf.pack(side=TOP, fill = BOTH, expand = 1) b3 = Label(cf, text = _('Read Every')) b3.pack(side = LEFT, anchor = SW) TGAP = StringVar() Dur =Entry(cf, width=5, bg = 'white', textvariable = TGAP) TGAP.set('10') Dur.pack(side = LEFT, anchor = SW) b3 = Label(cf, text = _('mS,')) b3.pack(side = LEFT, anchor = SW) b3 = Label(cf, text = _('for total')) b3.pack(side = LEFT, anchor = SW) DURATION = StringVar() Total =Entry(cf, width=5, bg = 'white', textvariable = DURATION) DURATION.set('100') Total.pack(side = LEFT, anchor = SW) b3 = Label(cf, text = _('Seconds.')) b3.pack(side = LEFT, anchor = SW) b3 = Label(cf, text = _('Range')) b3.pack(side = LEFT, anchor = SW) TMIN = StringVar() TMIN.set('0') Tmin =Entry(cf, width=5, bg = 'white', textvariable = TMIN) Tmin.pack(side = LEFT, anchor = SW) b3 = Label(cf, text = _('to,')) b3.pack(side = LEFT, anchor = SW) TMAX = StringVar() TMAX.set('5') Tmax =Entry(cf, width=5, bg = 'white', textvariable = TMAX) Tmax.pack(side = LEFT, anchor = SW) b3 = Label(cf, text = _('C. ')) b3 = Button(cf, text = _('SAVE to'), command = pt.save) b3.pack(side = LEFT, anchor = SW) b3.pack(side = LEFT, anchor = SW) filename = StringVar() e1 =Entry(cf, width=15, bg = 'white', textvariable = filename) filename.set('piezo.dat') e1.pack(side = LEFT, anchor = SW) cf = Frame(root, width = WIDTH, height = 10) cf.pack(side=TOP, fill = BOTH, expand = 1) b1 = Button(cf, text = _('Xmgrace'), command = pt.xmgrace) b1.pack(side = LEFT, anchor = SW) cf = Frame(root, width = WIDTH, height = 10) cf.pack(side=TOP, fill = BOTH, expand = 1) e1.pack(side = LEFT) b5 = Button(cf, text = _('QUIT'), command = pt.quit) b5.pack(side = RIGHT, anchor = N) b4 = Button(cf, text = _('CLEAR'), command = pt.clear) b4.pack(side = RIGHT, anchor = N) b1 = Button(cf, text = _('STOP'), command = pt.stop) b1.pack(side = RIGHT, anchor = N) b1 = Button(cf, text = _('START'), command = pt.start) b1.pack(side = RIGHT, anchor = N) mf = Frame(root, width = WIDTH, height = 10) mf.pack(side=TOP) msgwin = Label(mf,text=_('Message'), fg = 'blue') msgwin.pack(side=LEFT, anchor = S, fill=BOTH, expand=1) root.title(_('Piezo-electric Transducer')) root.mainloop()
gpl-3.0
Fatalerror66/ffxi-a
scripts/zones/Zeruhn_Mines/npcs/Vorzill.lua
861
----------------------------------- -- Area: Zeruhn Mines -- NPC: Vorzill -- Standard Info NPC ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0066); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
parksandwildlife/learning
moodle/mod/dataform/field/entrytime/version.php
1001
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * @package dataformfield * @subpackage entrytime * @copyright 2014 Itamar Tzadok {@link http://substantialmethods.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ $plugin->component = 'dataformfield_entrytime'; $plugin->version = 2015111604; $plugin->requires = 2015111600;
gpl-3.0
bentearadu/Diagnostics
Sources/UDS_Protocol/stdafx.cpp
299
// stdafx.cpp : source file that includes just the standard includes // UDS_Protocol.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
gpl-3.0
jpm88/Practica3-IV
periodicoII/economia/ibex-35_20130430.php
7105
<!doctype html> <html lang="es"> <head> <meta charset="utf­8"> <title>MONDO DIFFICILE</title> <link rel="stylesheet" type="text/css" href="../estilo.css" /> </head> <body> <section id="bannersuperior"><a href="http://www.amazon.com"> <img src = "../img/amazon.jpg" alt = "Amazon"/> </a></section> <section id="bannerizquierdo"><a href="http://www.amarillasinternet.com"> <img src = "../img/banner.jpg" alt = "Amarillas"/> </a></section> <section id="bannerderecho"><a href="http://www.amarillasinternet.com"> <img src = "../img/banner.jpg" alt = "Amarillas"/> </a></section> <header> <h1 id="titulo">MONDO DIFFICILE</h1> <nav id="menu"> <ul> <li><a href="../index.php" id="color1">Portada</a></li> <li><a href="../nacional.php" id="color2">Nacional</a></li> <li><a href="../internacional.php" id="color3">Internacional</a></li> <li><a href="../economia.php" id="color4">Econom&iacute;a</a></li> <li><a href="../deportes.php" id="color5">Deportes</a></li> <li><a href="../tecnologia.php" id="color6">Tecnolog&iacute;a</a></li> </ul> </nav> </header> <table id="tabla"> <tbody> <tr> <td colspan="3" id="nombreseccion"><h2 id="color4">ECONOM&Iacute;A</h2> </td> </tr> <tr> <td colspan="3" id="noticia1"><h2 id="color4">EL IBEX-35 CIERRA ABRIL CON UN REPUNTE DEL 6,3%, EL MAYOR DESDE AGOSTO DE 2012</h2> <article> <p>01/05/2013 por Juan.</p> <p>El selectivo iniciar&aacute; mayo en los 8.419 puntos, cerca de sus m&aacute;ximos anuales. La prima de riesgo se estabiliz&oacute; en los 292 puntos, en niveles de octubre de 2011.</p> <img id="imagen" src = "../img/ibex-35_20130430.jpg" alt = "Portada"/> <footer id="pie">Monitor de la Bolsa mostrando el Ibex-35.</footer> <p>Un solo gol le falt&oacute; al Real Madrid m&aacute;s heroico para clasificarse para la final de la Champions. Su fe inquebrantable le llev&oacute; a quedarse a las puertas de la clasificaci&oacute;n ante el Borussia Dortmund despu&eacute;s de un principio ilusionante sin premio, un nudo en el que todo pareci&oacute; perdido y un desenlace que casi acaba en org&iacute;a colectiva en el Bernab&eacute;u. Sin embargo, el tanto final no lleg&oacute; y el madridismo debe esperar un a&ntilde;o m&aacute;s para poder saborear la anhelada D&eacute;cima.</p> <p>Los madridistas hicieron en la primera parte todo lo que hab&iacute;a que hacer para poner los cimientos de la gesta... menos marcar el gol. Presi&oacute;n asfixiante arriba, dominio absoluto y ocasiones claras, muy claras.</p> <p>El planteamiento de Mourinho funcion&oacute; a la perfecci&oacute;n y la apuesta ofensiva -con Xabi Alonso y Modric llevando la manija del equipo- dio resultados sobre el campo. Solo cuatro minutos tard&oacute; el Madrid en asustar a los alemanes, pero Higua&iacute;n, solo ante Weidenfeller, marr&oacute; el mano a mano ante el portero.</p> <p>El f&uacute;tbol excelso de los blancos desbord&oacute; al equipo alem&aacute;n y solo un milagro hizo que el gol no llegara. La tuvo Cristiano en un remate a bocajarro y despu&eacute;s &Ouml;zil solo ante el cancerbero alem&aacute;n. No entr&oacute; ninguna, pero era el camino. Adem&aacute;s, G&ouml;tze se tuvo que retirar lesionado. El milagro parec&iacute;a entonces m&aacute;s cerca que nunca.</p> <p>Sin embargo, poco a poco el Dortmund fue dejando atr&aacute;s los nervios iniciales y destapando su calidad. Reus y Gundogan empezaron a aparecer y Lewandowski -qu&eacute; clase tiene- daba salida y aguantaba el bal&oacute;n con maestr&iacute;a. El partido pas&oacute; de ser de pleno dominio blanco a volverse una aut&eacute;ntica batalla campal, malo para el Madrid. El mensaje de Mourinho acusando a sus jugadores de ser demasiado blandos en la ida cal&oacute; hondo en sus jugadores y la 'estopa' repartida por muchos de ellos (Ramos y Coentrao especialmente). Los minutos pasaban pero las ocasiones cesaron despu&eacute;s de que los alemanes empezaran a mostrar las armas que le hab&iacute;an llevado tan lejos.</p> <p>Sin goles en la primera parte, el objetivo de la remontada parec&iacute;a lejos, pero era el buen f&uacute;tbol del Dortmund el que lo hac&iacute;a a&uacute;n m&aacute;s dif&iacute;cil. El cansancio hac&iacute;a pesadas las piernas de los centrocampistas blancos y el gol rondaba la porter&iacute;a blanca. Lewandowski, en su &eacute;pica batalla con Ramos, marr&oacute; dos clar&iacute;simas (una de ellas se estrell&oacute; en el larguero) y Gundogan la tuvo casi a puerta vac&iacute;a, pero se encontr&oacute; con un Diego L&oacute;pez disfrazado de Casillas, que vol&oacute; para sacarle un bal&oacute;n que era gol.</p> <p>Los minutos pasaban y el des&aacute;nimo empez&oacute; a cundir entre el p&uacute;blico, que estaba dejando de creer. Pero a ocho minutos del final lleg&oacute; el ansiado gol, tras una combinaci&oacute;n entre Kak&aacute; y &Ouml;zil que empuj&oacute; a la red Benzema. Como por arte de magia, el convencimiento se apoder&oacute; de todos y cada uno de los jugadores. Cada ataque era peligroso y cada c&oacute;rner parec&iacute;a casi un penalti. Y el segundo lleg&oacute; del pundonor del que m&aacute;s lo merec&iacute;a, Sergio Ramos, que aprovech&oacute; una sucesi&oacute;n de rechaces para empalar el bal&oacute;n al fondo de la red.</p> <p>Quedaban cuatro minutos m&aacute;s el descuento y un solo gol obraba el milagro. Los balones colgados y los ataques deslabazados se sucedieron en busca de un tanto que provocara el orgamo en un Bernab&eacute;u enloquecido. Pero no lleg&oacute;. Un a&ntilde;o m&aacute;s, la D&eacute;cima debe esperar.</p> </article> </td> </tr> <tr> <td rowspan="2"> <fieldset id= "comentario"> <p>Escrito por juanito ayer a las 14:05:</p></br> <p>Prueba de comentario</p> </fieldset> <fieldset id= "comentario"> <p>Escrito por TipicoAmericano hoy a las 19:05:</p></br> <p>Yiiiiah madafacka</p> </fieldset></br> <fieldset id= "comentario"> <legend>Escribir comentarios:</legend> <form name= "comentar" method="post" onsubmit="if(document.forms[0].texto.value.length >= 100){alert('El comentario es demasiado largo'); document.forms[0].texto.select(); return false}"> <textarea name="texto" rows="5" cols="100" placeholder = "Escribe aquí tu opinión sobre la noticia"></textarea></br> <input type = "submit" id = "button1" value = "Enviar comentario"/> </form> </fieldset> </td> <td rowspan="2" id="publi"><a href="http://www.skype.com"> <img src = "../img/skype.jpg" alt = "Skype"/></a> <a href="http://www.casadellibro.com"> <img src = "../img/casadellibro.gif" alt = "Casa del libro"/></a> </td> </tr> </tbody> </table> <footer> <p>Juan Antonio P&eacute;rez Maldonado </br> 618042606 <address>Circunvalaci&oacute;n Encina 23, 18015</address></br> <a href="mailto:jpm88@correo.ugr.es">Correo de contacto</a> <a href="../formulario.php">&iexcl;Suscr&iacute;bete!</a> <a href="../documentacion.pdf">C&oacute;mo se hizo</a></p> </footer> </body> </html>
gpl-3.0
MartyParty21/AwakenDreamsClient
mcp/temp/src/minecraft/net/minecraft/block/BlockSnowBlock.java
1226
package net.minecraft.block; import java.util.Random; import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.util.math.BlockPos; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.World; public class BlockSnowBlock extends Block { protected BlockSnowBlock() { super(Material.field_151596_z); this.func_149675_a(true); this.func_149647_a(CreativeTabs.field_78030_b); } @Nullable public Item func_180660_a(IBlockState p_180660_1_, Random p_180660_2_, int p_180660_3_) { return Items.field_151126_ay; } public int func_149745_a(Random p_149745_1_) { return 4; } public void func_180650_b(World p_180650_1_, BlockPos p_180650_2_, IBlockState p_180650_3_, Random p_180650_4_) { if(p_180650_1_.func_175642_b(EnumSkyBlock.BLOCK, p_180650_2_) > 11) { this.func_176226_b(p_180650_1_, p_180650_2_, p_180650_1_.func_180495_p(p_180650_2_), 0); p_180650_1_.func_175698_g(p_180650_2_); } } }
gpl-3.0
Delitex/test2
admin/controllers/Categories.php
9074
<?php if ( ! defined('BASEPATH')) exit('No direct access allowed'); class Categories extends Admin_Controller { public function __construct() { parent::__construct(); // calls the constructor $this->user->restrict('Admin.Categories'); $this->load->model('Categories_model'); // load the menus model $this->load->model('Image_tool_model'); $this->load->library('permalink'); $this->load->library('pagination'); $this->lang->load('categories'); } public function index() { $url = '?'; $filter = array(); if ($this->input->get('page')) { $filter['page'] = (int) $this->input->get('page'); } else { $filter['page'] = ''; } if ($this->config->item('page_limit')) { $filter['limit'] = $this->config->item('page_limit'); } if ($this->input->get('filter_search')) { $filter['filter_search'] = $data['filter_search'] = $this->input->get('filter_search'); $url .= 'filter_search='.$filter['filter_search'].'&'; } else { $data['filter_search'] = ''; } if (is_numeric($this->input->get('filter_status'))) { $filter['filter_status'] = $data['filter_status'] = $this->input->get('filter_status'); $url .= 'filter_status='.$filter['filter_status'].'&'; } else { $filter['filter_status'] = $data['filter_status'] = ''; } if ($this->input->get('sort_by')) { $filter['sort_by'] = $data['sort_by'] = $this->input->get('sort_by'); } else { $filter['sort_by'] = $data['sort_by'] = 'category_id'; } if ($this->input->get('order_by')) { $filter['order_by'] = $data['order_by'] = $this->input->get('order_by'); $data['order_by_active'] = $this->input->get('order_by') .' active'; } else { $filter['order_by'] = $data['order_by'] = 'ASC'; $data['order_by_active'] = 'ASC'; } $this->template->setTitle($this->lang->line('text_title')); $this->template->setHeading($this->lang->line('text_heading')); $this->template->setButton($this->lang->line('button_new'), array('class' => 'btn btn-primary', 'href' => page_url() .'/edit')); $this->template->setButton($this->lang->line('button_delete'), array('class' => 'btn btn-danger', 'onclick' => 'confirmDelete();'));; if ($this->input->post('delete') AND $this->_deleteCategory() === TRUE) { redirect('categories'); } $order_by = (isset($filter['order_by']) AND $filter['order_by'] == 'ASC') ? 'DESC' : 'ASC'; $data['sort_name'] = site_url('categories'.$url.'sort_by=name&order_by='.$order_by); $data['sort_priority'] = site_url('categories'.$url.'sort_by=priority&order_by='.$order_by); $data['sort_id'] = site_url('categories'.$url.'sort_by=category_id&order_by='.$order_by); $results = $this->Categories_model->getList($filter); $data['categories'] = array(); foreach ($results as $result) { //load categories data into array $data['categories'][] = array( 'category_id' => $result['category_id'], 'name' => $result['name'], 'parent_id' => $result['parent_id'], 'priority' => $result['priority'], 'description' => substr(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8')), 0, 100) . '..', 'status' => ($result['status'] === '1') ? $this->lang->line('text_enabled') : $this->lang->line('text_disabled'), 'edit' => site_url('categories/edit?id=' . $result['category_id']) ); } if ($this->input->get('sort_by') AND $this->input->get('order_by')) { $url .= 'sort_by='.$filter['sort_by'].'&'; $url .= 'order_by='.$filter['order_by'].'&'; } $config['base_url'] = site_url('categories'.$url); $config['total_rows'] = $this->Categories_model->getCount($filter); $config['per_page'] = $filter['limit']; $this->pagination->initialize($config); $data['pagination'] = array( 'info' => $this->pagination->create_infos(), 'links' => $this->pagination->create_links() ); $this->template->render('categories', $data); } public function edit() { $category_info = $this->Categories_model->getCategory((int) $this->input->get('id')); if ($category_info) { $category_id = $category_info['category_id']; $data['_action'] = site_url('categories/edit?id='. $category_id); } else { $category_id = 0; $data['_action'] = site_url('categories/edit'); } $title = (isset($category_info['name'])) ? $category_info['name'] : $this->lang->line('text_new'); $this->template->setTitle(sprintf($this->lang->line('text_edit_heading'), $title)); $this->template->setHeading(sprintf($this->lang->line('text_edit_heading'), $title)); $this->template->setButton($this->lang->line('button_save'), array('class' => 'btn btn-primary', 'onclick' => '$(\'#edit-form\').submit();')); $this->template->setButton($this->lang->line('button_save_close'), array('class' => 'btn btn-default', 'onclick' => 'saveClose();')); $this->template->setButton($this->lang->line('button_icon_back'), array('class' => 'btn btn-default', 'href' => site_url('categories'))); if ($this->input->post() AND $category_id = $this->_saveCategory()) { if ($this->input->post('save_close') === '1') { redirect('categories'); } redirect('categories/edit?id='. $category_id); } $data['category_id'] = $category_info['category_id']; $data['name'] = $category_info['name']; $data['parent_id'] = $category_info['parent_id']; $data['description'] = $category_info['description']; $data['priority'] = $category_info['priority']; $data['status'] = $category_info['status']; $data['no_image'] = $this->Image_tool_model->resize('data/no_photo.png'); $data['permalink'] = $this->permalink->getPermalink('category_id='.$category_info['category_id']); if ($this->input->post('image')) { $data['image'] = $this->input->post('image'); $data['image_name'] = basename($this->input->post('image')); $data['image_url'] = $this->Image_tool_model->resize($this->input->post('image')); } else if (!empty($category_info['image'])) { $data['image'] = $category_info['image']; $data['image_name'] = basename($category_info['image']); $data['image_url'] = $this->Image_tool_model->resize($category_info['image']); } else { $data['image'] = ''; $data['image_name'] = ''; $data['image_url'] = $data['no_image']; } $data['categories'] = array(); $results = $this->Categories_model->getCategories(); foreach ($results as $result) { $data['categories'][] = array( 'category_id' => $result['category_id'], 'category_name' => $result['name'] ); } $this->template->render('categories_edit', $data); } private function _saveCategory() { if ($this->validateForm() === TRUE) { $save_type = (! is_numeric($this->input->get('id'))) ? $this->lang->line('text_added') : $this->lang->line('text_updated'); if ($category_id = $this->Categories_model->saveCategory($this->input->get('id'), $this->input->post())) { $this->alert->set('success', sprintf($this->lang->line('alert_success'), 'Category '.$save_type)); } else { $this->alert->set('warning', sprintf($this->lang->line('alert_error_nothing'), $save_type)); } return $category_id; } } private function _deleteCategory() { if ($this->input->post('delete')) { $deleted_rows = $this->Categories_model->deleteCategory($this->input->post('delete')); if ($deleted_rows > 0) { $prefix = ($deleted_rows > 1) ? '['.$deleted_rows.'] Categories': 'Category'; $this->alert->set('success', sprintf($this->lang->line('alert_success'), $prefix.' '.$this->lang->line('text_deleted'))); } else { $this->alert->set('warning', sprintf($this->lang->line('alert_error_nothing'), $this->lang->line('text_deleted'))); } return TRUE; } } private function validateForm() { $this->form_validation->set_rules('name', 'lang:label_name', 'xss_clean|trim|required|min_length[2]|max_length[32]'); $this->form_validation->set_rules('description', 'lang:label_description', 'xss_clean|trim|min_length[2]|max_length[1028]'); $this->form_validation->set_rules('permalink[permalink_id]', 'lang:label_permalink_id', 'xss_clean|trim|integer'); $this->form_validation->set_rules('permalink[slug]', 'lang:label_permalink_slug', 'xss_clean|trim|alpha_dash|max_length[255]'); $this->form_validation->set_rules('parent_id', 'lang:label_parent', 'xss_clean|trim|integer'); $this->form_validation->set_rules('image', 'lang:label_image', 'xss_clean|trim'); $this->form_validation->set_rules('priority', 'lang:label_priority', 'xss_clean|trim|required|integer'); $this->form_validation->set_rules('status', 'lang:label_status', 'xss_clean|trim|required|integer'); if ($this->form_validation->run() === TRUE) { return TRUE; } else { return FALSE; } } } /* End of file categories.php */ /* Location: ./admin/controllers/categories.php */
gpl-3.0
OldSnapo/gisclient-3
tests/lib/HttpUtils.php
1875
<?php class HttpUtils { static public function post($url, $postParams, $cookieFile = NULL) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postParams); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // curl_setopt($ch, CURLOPT_HEADER, true); if (!is_null($cookieFile)) { curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); } $result = curl_exec($ch); $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return array($httpStatus, $result); } static public function get($url, $cookieFile = NULL) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if (!is_null($cookieFile)) { curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); } $result = curl_exec($ch); $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return array($httpStatus, $result); } static public function put($url, $data, $cookieFile = NULL) { $fh = fopen('php://memory', 'rw'); fwrite($fh, $data); rewind($fh); $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if (!is_null($cookieFile)) { echo "get: CF\n"; curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); } curl_setopt($ch, CURLOPT_PUT, 1); curl_setopt($ch, CURLOPT_INFILE, $fh); curl_setopt($ch, CURLOPT_INFILESIZE, strlen($data)); $result = curl_exec($ch); $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return array($httpStatus, $result); } }
gpl-3.0
cosmo-team/cosmo
quantize.py
1406
import numpy as np from bisect import bisect_right import argparse, os # TODO: try frequency analysis quantization # e.g. k-means? from http://scikit-learn.org/stable/auto_examples/cluster/plot_lena_compress.html # These need to both be numpy arrays def quantize(data, levels): indices = levels.searchsorted(data, side="right") levels = np.append([0], levels) return levels[indices] parser = argparse.ArgumentParser(description='Quantize LCS vector to compress better.') parser.add_argument('filename') mode = parser.add_mutually_exclusive_group(required=True) mode.add_argument('-q', dest='levels', metavar='N', nargs='+', help='a quantization level.', type=int) mode.add_argument('-t', dest='threshold', metavar='<threshold>', help='remove all below this minimum value.', type=int) args = parser.parse_args() filename, levels, threshold = args.filename, args.levels, args.threshold # Add check for file if not os.path.exists(filename): print "Error: file %s does not exist" % (filename) lcs = np.fromfile(filename, dtype=np.uint8) #max_val = lcs.max() if threshold: print "Removing values below %s." % (threshold) lcs[lcs < threshold] = 0 output = lcs if levels: # if 0 not in levels: levels = [0]+sorted(levels) print "Quantizing into these buckets: %s" % (levels) levels = np.array(levels) output = quantize(lcs, levels) output.tofile(filename+".qzd")
gpl-3.0
tranSMART-N/tranSMART-N_app
web-app/js/JS.Class/src/comparable.js
705
JS.Comparable = new JS.Module('Comparable', { extend: { ClassMethods: new JS.Module({ compare: function(one, another) { return one.compareTo(another); } }), included: function(base) { base.extend(this.ClassMethods); } }, lt: function(other) { return this.compareTo(other) < 0; }, lte: function(other) { return this.compareTo(other) < 1; }, gt: function(other) { return this.compareTo(other) > 0; }, gte: function(other) { return this.compareTo(other) > -1; }, eq: function(other) { return this.compareTo(other) === 0; }, between: function(a, b) { return this.gte(a) && this.lte(b); } });
gpl-3.0
quait/madcow
madcow/modules/summon.py
1271
"""Summon people""" import re from learn import Main as Learn from madcow.util import Module from smtplib import SMTP from madcow.conf import settings from madcow.util.text import * class Main(Module): pattern = re.compile(r'^\s*summons?\s+(\S+)(?:\s+(.*?))?\s*$') require_addressing = True help = u'summon <nick> [reason] - summon user' error = u"I couldn't make that summon" def init(self): self.learn = Learn(self.madcow) def response(self, nick, args, kwargs): sendto, reason = args email = self.learn.lookup('email', sendto) if email is None: return u"%s: I don't know the email for %s" % (nick, sendto) body = u'\n'.join((u'To: %s <%s>' % (sendto, email), u'From: ' + settings.SMTP_FROM, u'Subject: Summon from ' + nick, u'', u'You were summoned by %s. Reason: %s' % (nick, reason))) smtp = SMTP(settings.SMTP_SERVER) if settings.SMTP_USER and settings.SMTP_PASS: smtp.login(settings.SMTP_USER, settings.SMTP_PASS) smtp.sendmail(settings.SMTP_FROM, [encode(email, 'ascii')], encode(body)) return u"%s: summoned %s" % (nick, sendto)
gpl-3.0
kevleyski/fluxcomp
src/fluxcomp.cpp
104866
/* (c) Copyright 2012-2013 DirectFB integrated media GmbH (c) Copyright 2001-2013 The world wide DirectFB Open Source Community (directfb.org) (c) Copyright 2000-2004 Convergence (integrated media) GmbH All rights reserved. Written by Denis Oliver Kropp <dok@directfb.org>, Andreas Shimokawa <andi@directfb.org>, Marek Pikarski <mass@directfb.org>, Sven Neumann <neo@directfb.org>, Ville Syrjälä <syrjala@sci.fi> and Claudio Ciccani <klan@users.sf.net>. This file is subject to the terms and conditions of the MIT License: 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. */ //#define DIRECT_ENABLE_DEBUG #include <list> #include <map> #include <string> #include <vector> #include <config.h> extern "C" { #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #ifdef USE_LIBDIRECT #include <direct/debug.h> #include <direct/direct.h> #include <direct/list.h> #include <direct/mem.h> #include <direct/memcpy.h> #include <direct/messages.h> #include <direct/util.h> #endif } #ifdef USE_LIBDIRECT D_DEBUG_DOMAIN( fluxcomp, "fluxcomp", "Flux Compression Tool" ); #define FLUX_D_DEBUG_AT(x...) D_DEBUG_AT(x); #else /* fake macros */ #define FLUX_D_DEBUG_AT(x...) #define D_ASSERT(x...) #define D_PERROR(x...) #define D_WARN(x...) \ do { \ printf( x ); \ printf( "\n" ); \ sleep(5); \ } while (0) #define D_UNIMPLEMENTED(x...) #define DR_OK 0 #define DR_FAILURE 1 /* fake types */ typedef int DirectResult; /* fake functions */ DirectResult errno2result( int erno ) { if (!errno) return DR_OK; return DR_FAILURE; } void direct_initialize() {}; void direct_shutdown() {}; void direct_print_memleaks() {}; #define direct_log_printf(x...) #endif /**********************************************************************************************************************/ static const char *license = "/*\n" " (c) Copyright 2012-2013 DirectFB integrated media GmbH\n" " (c) Copyright 2001-2013 The world wide DirectFB Open Source Community (directfb.org)\n" " (c) Copyright 2000-2004 Convergence (integrated media) GmbH\n" "\n" " All rights reserved.\n" "\n" " Written by Denis Oliver Kropp <dok@directfb.org>,\n" " Andreas Shimokawa <andi@directfb.org>,\n" " Marek Pikarski <mass@directfb.org>,\n" " Sven Neumann <neo@directfb.org>,\n" " Ville Syrjälä <syrjala@sci.fi> and\n" " Claudio Ciccani <klan@users.sf.net>.\n" "\n" " This library is free software; you can redistribute it and/or\n" " modify it under the terms of the GNU Lesser General Public\n" " License as published by the Free Software Foundation; either\n" " version 2 of the License, or (at your option) any later version.\n" "\n" " This library is distributed in the hope that it will be useful,\n" " but WITHOUT ANY WARRANTY; without even the implied warranty of\n" " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" " Lesser General Public License for more details.\n" "\n" " You should have received a copy of the GNU Lesser General Public\n" " License along with this library; if not, write to the\n" " Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n" " Boston, MA 02111-1307, USA.\n" "*/\n"; static const char *filename; /**********************************************************************************************************************/ class FluxConfig { public: bool c_mode; bool identity; std::string include_prefix; bool no_direct; bool call_mode; bool object_ptrs; std::string static_args_bytes; bool dispatch_error_abort; public: FluxConfig() : c_mode( false ), identity( false ), no_direct( false ), call_mode( false ), object_ptrs( false ), static_args_bytes( "1000" ), dispatch_error_abort( false ) { } bool parse_command_line( int argc, char *argv[] ) { int n; for (n = 1; n < argc; n++) { const char *arg = argv[n]; if (strcmp (arg, "-h") == 0 || strcmp (arg, "--help") == 0) { print_usage( argv[0] ); return false; } if (strcmp (arg, "-v") == 0 || strcmp (arg, "--version") == 0) { fprintf( stderr, "fluxcomp version %s\n", FLUXCOMP_VERSION ); return false; } if (strcmp (arg, "-V") == 0 || strcmp (arg, "--version-code") == 0) { fprintf( stdout, "%d", FLUXCOMP_MAJOR_VERSION*1000000 + FLUXCOMP_MINOR_VERSION*1000 + FLUXCOMP_MICRO_VERSION ); return false; } if (strcmp (arg, "-c") == 0 || strcmp (arg, "--generate-c") == 0) { c_mode = true; continue; } if (strcmp (arg, "-i") == 0 || strcmp (arg, "--identity") == 0) { identity = true; continue; } if (strcmp (arg, "--object-ptrs") == 0) { object_ptrs = true; continue; } if (strcmp (arg, "--no-direct") == 0) { no_direct = true; continue; } if (strcmp (arg, "--call-mode") == 0) { call_mode = true; continue; } if (strncmp (arg, "-p=",3) == 0) { include_prefix = std::string(&arg[3]); continue; } if (strncmp (arg, "--include-prefix=", 17) == 0) { include_prefix = std::string(&arg[17]); continue; } if (strncmp (arg, "--static-args-bytes=", 20) == 0) { static_args_bytes = &arg[20]; continue; } if (strcmp (arg, "--dispatch-error-abort") == 0) { dispatch_error_abort = true; continue; } if (filename || access( arg, R_OK )) { print_usage( argv[0] ); return false; } filename = arg; } if (!filename) { print_usage (argv[0]); return false; } return true; } void print_usage( const char *prg_name ) { fprintf( stderr, "\nFlux Compiler Tool (version %s)\n\n", FLUXCOMP_VERSION ); fprintf( stderr, "Usage: %s [options] <filename>\n\n", prg_name ); fprintf( stderr, "Options:\n" ); fprintf( stderr, " -h, --help Show this help message\n" ); fprintf( stderr, " -v, --version Print version information\n" ); fprintf( stderr, " -V, --version-code Output version code to stdout\n" ); fprintf( stderr, " -c, --generate-c Generate C instead of C++ code\n" ); fprintf( stderr, " -i, --identity Generate caller identity tracking code\n" ); fprintf( stderr, " --object-ptrs Return object pointers rather than IDs\n" ); fprintf( stderr, " --call-mode Use call mode function to determine call mode\n" ); fprintf( stderr, " -p=, --include-prefix= Override standard include prefix for includes\n" ); fprintf( stderr, " --static-args-bytes= Override standard limit (1000) for stack based arguments\n" ); fprintf( stderr, " --dispatch-error-abort Abort execution when object lookups etc fail\n" ); fprintf( stderr, "\n" ); } }; /**********************************************************************************************************************/ class Entity { public: Entity( Entity *parent ) : parent( parent ) { } typedef std::list<Entity*> list; typedef std::vector<Entity*> vector; typedef enum { ENTITY_NONE, ENTITY_INTERFACE, ENTITY_METHOD, ENTITY_ARG } Type; virtual Type GetType() const = 0; virtual void Dump() const; virtual void SetProperty( const std::string &name, const std::string &value ); private: const char *buf; size_t length; public: Entity::vector entities; Entity *parent; void Open( const char *buf ) { this->buf = buf; } void Close( size_t length ) { this->length = length; GetEntities( buf, length, entities, this ); } static void GetEntities( const char *buf, size_t length, Entity::vector &out_vector, Entity *parent ); static DirectResult GetEntities( const char *filename, Entity::vector &out_vector ); }; class Interface : public Entity { public: Interface( Entity *parent ) : Entity( parent ), buffered( false ), core( "CoreDFB" ) { } virtual Type GetType() const { return ENTITY_INTERFACE; } virtual void Dump() const; virtual void SetProperty( const std::string &name, const std::string &value ); std::string name; std::string version; std::string object; std::string dispatch; bool buffered; std::string core; }; class Method : public Entity { public: Method( Entity *parent ) : Entity( parent ), async( false ), queue( false ), buffer( false ) { } virtual Type GetType() const { return ENTITY_METHOD; } virtual void Dump() const; virtual void SetProperty( const std::string &name, const std::string &value ); std::string name; bool async; bool queue; bool buffer; public: static std::string PrintParam( std::string string_buffer, std::string type, std::string ptr, std::string name, bool first ) { char buf[1000]; snprintf( buf, sizeof(buf), "%s %-40s %2s%s", first ? "" : ",\n", type.c_str(), ptr.c_str(), name.c_str() ); return string_buffer + buf; } static std::string PrintMember( std::string string_buffer, std::string type, std::string ptr, std::string name ) { char buf[1000]; snprintf( buf, sizeof(buf), " %-40s %2s%s;\n", type.c_str(), ptr.c_str(), name.c_str() ); return string_buffer + buf; } std::string ArgumentsAsParamDecl() const; std::string ArgumentsAsMemberDecl() const; std::string ArgumentsOutputAsMemberDecl( const FluxConfig &config ) const; std::string ArgumentsAsMemberParams() const; std::string ArgumentsInputAssignments() const; std::string ArgumentsOutputAssignments() const; std::string ArgumentsAssertions() const; std::string ArgumentsOutputObjectDecl() const; std::string ArgumentsOutputTmpDecl() const; std::string ArgumentsInputObjectDecl() const; std::string ArgumentsOutputObjectCatch( const FluxConfig &config ) const; std::string ArgumentsOutputObjectThrow( const FluxConfig &config ) const; std::string ArgumentsInoutReturn() const; std::string ArgumentsOutputTmpReturn() const; std::string ArgumentsInputObjectLookup( const FluxConfig &config ) const; std::string ArgumentsInputObjectUnref() const; std::string ArgumentsInputDebug( const FluxConfig &config, const Interface *face ) const; std::string ArgumentsNames() const; std::string ArgumentsSize( const Interface *face, bool output ) const; std::string ArgumentsSizeReturn( const Interface *face ) const; std::string OpenSplitArgumentsIfRequired() const; std::string CloseSplitArgumentsIfRequired() const; }; class Arg : public Entity { public: Arg( Entity *parent ) : Entity( parent ), optional( false ), array( false ), split( false ) { } virtual Type GetType() const { return ENTITY_ARG; } virtual void Dump() const; virtual void SetProperty( const std::string &name, const std::string &value ); std::string name; std::string direction; std::string type; std::string type_name; bool optional; bool array; std::string count; std::string max; bool split; public: std::string param_name() const { if (direction == "output") return std::string("ret_") + name; return name; } std::string formatCharacter() const { if (type == "int") { if (type_name == "u8" || type_name == "u16" || type_name == "u32") return "u"; if (type_name == "s8" || type_name == "s16" || type_name == "s32") return "d"; if (type_name == "u64") return "llu"; if (type_name == "s64") return "lld"; if (type_name == "void*") return "p"; D_WARN( "unrecognized integer type '%s'", type_name.c_str() ); return "lu"; } if (type == "enum") return "x"; D_WARN( "unsupported type '%s'", type.c_str() ); D_UNIMPLEMENTED(); return "x"; } std::string size( bool use_args ) const { if (array) { if (use_args) return std::string("args->") + count + " * sizeof(" + type_name + ")"; else return (split ? std::string( "num_records" ) : count) + " * sizeof(" + type_name + ")"; } return std::string("sizeof(") + type_name + ")"; } std::string sizeReturn( const Method *method ) const { if (array) { /* Lookup 'count' argument */ for (Entity::vector::const_iterator iter = method->entities.begin(); iter != method->entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); if (arg->name == count) { if (arg->direction == "input") return std::string("args->") + count + " * sizeof(" + type_name + ")"; return std::string("return_args->") + count + " * sizeof(" + type_name + ")"; } } } return std::string("sizeof(") + type_name + ")"; } std::string sizeMax( bool use_args ) const { if (array) { if (use_args) return std::string("args->") + max + " * sizeof(" + type_name + ")"; else return max + " * sizeof(" + type_name + ")"; } return std::string("sizeof(") + type_name + ")"; } std::string offset( const Method *method, bool use_args, bool output ) const { D_ASSERT( array == true ); std::string result; for (Entity::vector::const_iterator iter = method->entities.begin(); iter != method->entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); if (!arg->array) continue; FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg == this) break; if (output) { if (arg->direction == "output" || arg->direction == "inout") result += std::string(" + return_args->") + arg->size( false ); } else { if (arg->direction == "input") result += std::string(" + ") + arg->size( use_args ); } } return result; } }; /**********************************************************************************************************************/ void Entity::Dump() const { direct_log_printf( NULL, "\n" ); direct_log_printf( NULL, "Entity (TYPE %d)\n", GetType() ); direct_log_printf( NULL, " Buffer at %p [%zu]\n", buf, length ); } void Interface::Dump() const { Entity::Dump(); direct_log_printf( NULL, " Name %s\n", name.c_str() ); direct_log_printf( NULL, " Version %s\n", version.c_str() ); direct_log_printf( NULL, " Object %s\n", object.c_str() ); direct_log_printf( NULL, " Dispatch %s\n", dispatch.c_str() ); } void Method::Dump() const { Entity::Dump(); direct_log_printf( NULL, " Name %s\n", name.c_str() ); } void Arg::Dump() const { Entity::Dump(); direct_log_printf( NULL, " Name %s\n", name.c_str() ); direct_log_printf( NULL, " Direction %s\n", direction.c_str() ); direct_log_printf( NULL, " Type %s\n", type.c_str() ); direct_log_printf( NULL, " Typename %s\n", type_name.c_str() ); } /**********************************************************************************************************************/ void Entity::SetProperty( const std::string &name, const std::string &value ) { } void Interface::SetProperty( const std::string &name, const std::string &value ) { if (name == "name") { this->name = value; return; } if (name == "version") { version = value; return; } if (name == "object") { object = value; dispatch = value; return; } if (name == "dispatch") { dispatch = value; return; } if (name == "core") { core = value; return; } } void Method::SetProperty( const std::string &name, const std::string &value ) { if (name == "name") { this->name = value; return; } if (name == "async") { async = value == "yes"; return; } if (name == "queue") { queue = value == "yes"; return; } if (name == "buffer") { buffer = value == "yes"; return; } } void Arg::SetProperty( const std::string &name, const std::string &value ) { if (name == "name") { this->name = value; return; } if (name == "direction") { direction = value; return; } if (name == "type") { type = value; return; } if (name == "typename") { type_name = value; return; } if (name == "optional") { optional = value == "yes"; return; } if (name == "count") { array = true; count = value; return; } if (name == "max") { max = value; return; } if (name == "split" && value == "yes") { split = true; return; } } /**********************************************************************************************************************/ void Entity::GetEntities( const char *buf, size_t length, Entity::vector &out_vector, Entity *parent ) { size_t i; unsigned int level = 0; bool quote = false; bool comment = false; std::string name; std::map<unsigned int,std::string> names; Entity *entity = NULL; FLUX_D_DEBUG_AT( fluxcomp, "%s( buf %p, length %zu )\n", __func__, buf, length ); for (i=0; i<length; i++) { FLUX_D_DEBUG_AT( fluxcomp, "%*s[%u] -> '%c' <-\n", level*2, "", level, buf[i] ); if (comment) { switch (buf[i]) { case '\n': comment = false; break; default: break; } } else if (quote) { switch (buf[i]) { // TODO: implement escaped quotes in strings case '"': quote = false; break; default: name += buf[i]; } } else { switch (buf[i]) { case '"': quote = true; break; case '#': comment = true; break; case '.': case '-': case '_': case 'a' ... 'z': case 'A' ... 'Z': case '0' ... '9': name += buf[i]; break; default: if (!name.empty()) { FLUX_D_DEBUG_AT( fluxcomp, "%*s=-> name = '%s'\n", level*2, "", name.c_str() ); if (!names[level].empty()) { switch (level) { case 1: FLUX_D_DEBUG_AT( fluxcomp, "%*s#### setting property '%s' = '%s'\n", level*2, "", names[level].c_str(), name.c_str() ); D_ASSERT( entity != NULL ); entity->SetProperty( names[level], name ); break; default: break; } name = ""; } names[level] = name; name = ""; } switch (buf[i]) { case '{': case '}': switch (buf[i]) { case '{': switch (level) { case 0: if (names[level] == "interface") { D_ASSERT( entity == NULL ); entity = new Interface( parent ); entity->Open( &buf[i + 1] ); FLUX_D_DEBUG_AT( fluxcomp, "%*s#### open entity %p (Interface)\n", level*2, "", entity ); } if (names[level] == "method") { D_ASSERT( entity == NULL ); entity = new Method( parent ); entity->Open( &buf[i + 1] ); FLUX_D_DEBUG_AT( fluxcomp, "%*s#### open entity %p (Method)\n", level*2, "", entity ); } if (names[level] == "arg") { D_ASSERT( entity == NULL ); entity = new Arg( parent ); entity->Open( &buf[i + 1] ); FLUX_D_DEBUG_AT( fluxcomp, "%*s#### open entity %p (Arg)\n", level*2, "", entity ); } break; default: break; } names[level] = ""; level++; break; case '}': D_ASSERT( names[level].empty() ); level--; switch (level) { case 0: FLUX_D_DEBUG_AT( fluxcomp, "%*s#### close entity %p\n", level*2, "", entity ); D_ASSERT( entity != NULL ); entity->Close( &buf[i-1] - entity->buf ); out_vector.push_back( entity ); entity = NULL; break; case 1: break; default: break; } break; } FLUX_D_DEBUG_AT( fluxcomp, "%*s=-> level => %u\n", level*2, "", level ); break; case ' ': case '\t': case '\n': case '\r': break; default: break; } break; } } } } DirectResult Entity::GetEntities( const char *filename, Entity::vector &out_vector ) { int ret = DR_OK; int fd; struct stat stat; void *ptr = MAP_FAILED; /* Open the file. */ fd = open( filename, O_RDONLY ); if (fd < 0) { ret = errno2result( errno ); D_PERROR( "GetEntities: Failure during open() of '%s'!\n", filename ); return (DirectResult) ret; } /* Query file size etc. */ if (fstat( fd, &stat ) < 0) { ret = errno2result( errno ); D_PERROR( "GetEntities: Failure during fstat() of '%s'!\n", filename ); goto out; } /* Memory map the file. */ ptr = mmap( NULL, stat.st_size, PROT_READ, MAP_SHARED, fd, 0 ); if (ptr == MAP_FAILED) { ret = errno2result( errno ); D_PERROR( "GetEntities: Failure during mmap() of '%s'!\n", filename ); goto out; } Entity::GetEntities( (const char*) ptr, stat.st_size, out_vector, NULL ); out: if (ptr != MAP_FAILED) munmap( ptr, stat.st_size ); close( fd ); return (DirectResult) ret; } /**********************************************************************************************************************/ std::string Method::ArgumentsAsParamDecl() const { std::string result; bool first = true; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->type == "struct") { if (arg->direction == "input") result = PrintParam( result, std::string("const ") + arg->type_name, "*", arg->param_name(), first ); else result = PrintParam( result, arg->type_name, "*", arg->param_name(), first ); } else if (arg->type == "enum" || arg->type == "int") { if (arg->direction == "input") { if (arg->array) result = PrintParam( result, std::string("const ") + arg->type_name, "*", arg->param_name(), first ); else result = PrintParam( result, arg->type_name, "", arg->param_name(), first ); } else result = PrintParam( result, arg->type_name, "*", arg->param_name(), first ); } else if (arg->type == "object") { if (arg->direction == "input") result = PrintParam( result, arg->type_name, "*", arg->param_name(), first ); else result = PrintParam( result, arg->type_name, "**", arg->param_name(), first ); } if (first) first = false; } return result; } std::string Method::ArgumentsAsMemberDecl() const { std::string result; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); if (arg->array) continue; FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->direction == "input" || arg->direction == "inout") { if (arg->optional) result = PrintMember( result, "bool", "", arg->name + "_set" ); if (arg->type == "struct") result = PrintMember( result, arg->type_name, "", arg->name ); else if (arg->type == "enum") result = PrintMember( result, arg->type_name, "", arg->name ); else if (arg->type == "int") result = PrintMember( result, arg->type_name, "", arg->name ); else if (arg->type == "object") result = PrintMember( result, "u32", "", arg->name + "_id" ); } } for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { char buf[300]; const Arg *arg = dynamic_cast<const Arg*>( *iter ); if (!arg->array) continue; FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->direction == "input" || arg->direction == "inout") { if (arg->optional) result = PrintMember( result, "bool", "", arg->name + "_set" ); snprintf( buf, sizeof(buf), " /* '%s' %s follow (%s) */\n", arg->count.c_str(), arg->type_name.c_str(), arg->name.c_str() ); result += buf; } } return result; } std::string Method::ArgumentsOutputAsMemberDecl( const FluxConfig &config ) const { std::string result; result = PrintMember( result, "DFBResult", "", "result" ); for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); if (arg->array) continue; FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->direction == "output" || arg->direction == "inout") { if (arg->type == "struct") result = PrintMember( result, arg->type_name, "", arg->name ); else if (arg->type == "enum") result = PrintMember( result, arg->type_name, "", arg->name ); else if (arg->type == "int") result = PrintMember( result, arg->type_name, "", arg->name ); else if (arg->type == "object") { result = PrintMember( result, "u32", "", arg->name + "_id" ); if (config.object_ptrs) result = PrintMember( result, "void*", "", arg->name + "_ptr" ); } } } for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { char buf[300]; const Arg *arg = dynamic_cast<const Arg*>( *iter ); if (!arg->array) continue; FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->direction == "output" || arg->direction == "inout") { if (arg->optional) result = PrintMember( result, "bool", "", arg->name + "_set" ); snprintf( buf, sizeof(buf), " /* '%s' %s follow (%s) */\n", arg->count.c_str(), arg->type_name.c_str(), arg->name.c_str() ); result += buf; } } return result; } std::string Method::ArgumentsAsMemberParams() const { std::string result; bool first = true; bool second_output_array = false; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (first) first = false; else result += ", "; if (arg->direction == "input" || arg->direction == "inout") { if (arg->optional) result += std::string("args->") + arg->name + "_set ? "; if (arg->array) { if (arg->type == "struct" || arg->type == "enum" || arg->type == "int") result += std::string("(") + arg->type_name + "*) ((char*)(args + 1)" + arg->offset( this, true, false ) + ")"; else if (arg->type == "object") D_UNIMPLEMENTED(); } else { if (arg->type == "struct") result += std::string("&args->") + arg->name; else if (arg->type == "enum") result += std::string("args->") + arg->name; else if (arg->type == "int") result += std::string("args->") + arg->name; else if (arg->type == "object") result += arg->name; } if (arg->optional) result += std::string(" : NULL"); } if (arg->direction == "output") { if (arg->optional) D_UNIMPLEMENTED(); if (arg->array) { if (second_output_array) { result += "tmp_" + arg->name; } else { if (arg->type == "struct" || arg->type == "enum" || arg->type == "int") result += std::string("(") + arg->type_name + "*) ((char*)(return_args + 1)" + arg->offset( this, true, true ) + ")"; else if (arg->type == "object") D_UNIMPLEMENTED(); second_output_array = true; } } else { if (arg->type == "struct") result += std::string("&return_args->") + arg->name; else if (arg->type == "enum") result += std::string("&return_args->") + arg->name; else if (arg->type == "int") result += std::string("&return_args->") + arg->name; else if (arg->type == "object") result += std::string("&") + arg->name; } } } return result; } std::string Method::ArgumentsInputAssignments() const { std::string result; bool split = false; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); if (arg->split) { split = true; break; } } for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); if (arg->array) continue; FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->direction == "input" || arg->direction == "inout") { if (arg->optional) result += std::string(" if (") + arg->name + ") {\n"; if (arg->type == "struct") result += std::string(" args->") + arg->name + " = *" + arg->name + ";\n"; else if (arg->type == "enum") result += std::string(" args->") + arg->name + " = " + arg->name + ";\n"; else if (arg->type == "int") result += std::string(" args->") + arg->name + " = " + (split ? (arg->name == "num" ? std::string( "num_records" ) : arg->name) : arg->name) + ";\n"; else if (arg->type == "object") result += std::string(" args->") + arg->name + "_id = " + arg->type_name + "_GetID( " + arg->name + " );\n"; if (arg->optional) { result += std::string(" args->") + arg->name + "_set = true;\n"; result += std::string(" }\n"); result += std::string(" else\n"); result += std::string(" args->") + arg->name + "_set = false;\n"; } } } for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); if (!arg->array) continue; FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->direction == "input" || arg->direction == "inout") { if (arg->optional) result += std::string(" if (") + arg->name + ") {\n"; if (arg->type == "struct" || arg->type == "enum" || arg->type == "int") result += std::string(" direct_memcpy( (char*) (args + 1)") + arg->offset( this, false, false ) + ", " + arg->name + ", " + arg->size( false ) + " );\n"; else if (arg->type == "object") D_UNIMPLEMENTED(); if (arg->optional) { result += std::string(" args->") + arg->name + "_set = true;\n"; result += std::string(" }\n"); result += std::string(" else {\n"); result += std::string(" args->") + arg->name + "_set = false;\n"; result += std::string(" ") + arg->name + " = 0;\n"; // FIXME: this sets num to 0 to avoid dispatch errors, but what if num is before this? result += std::string(" }\n"); } } } return result; } std::string Method::ArgumentsOutputAssignments() const { std::string result; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); if (arg->array) continue; FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->direction == "output" || arg->direction == "inout") { if (arg->type == "struct" || arg->type == "enum" || arg->type == "int") { if (arg->optional) result += std::string(" if (") + arg->param_name() + ")\n"; result += std::string( arg->optional ? " *" : " *") + arg->param_name() + " = return_args->" + arg->name + ";\n"; } } } for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); if (!arg->array) continue; FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->direction == "output" || arg->direction == "inout") { if (arg->optional) D_UNIMPLEMENTED(); if (arg->type == "struct" || arg->type == "enum" || arg->type == "int") result += std::string(" direct_memcpy( ret_") + arg->name + ", (char*) (return_args + 1)" + arg->offset( this, false, true ) + ", " + arg->sizeReturn( this ) + " );\n"; else if (arg->type == "object") D_UNIMPLEMENTED(); } } return result; } std::string Method::OpenSplitArgumentsIfRequired() const { std::string result; std::string record_sizes; int split = 0; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); if (arg->split) { if (split) record_sizes += std::string( " + " ); record_sizes += std::string( "sizeof(" ) + arg->type_name + std::string( ")" ); split++; } } if (!split) return result; result += std::string( "const u32 record_size = " ) + record_sizes + std::string( ";\n" ); result += std::string( "const u32 max_records = " ) + std::string( "CALLBUFFER_FUSION_MESSAGE_SIZE / record_size;\n" ); result += std::string( "for (u32 i = 0; i < num; i+= max_records) {\n" ); result += std::string( " const u32 num_records = num > max_records ? max_records : num;\n" ); return result; } std::string Method::CloseSplitArgumentsIfRequired() const { std::string result; bool split = false; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); if (arg->split) { split = true; break; } } if (split) result += "}"; return result; } std::string Method::ArgumentsAssertions() const { std::string result; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if ((arg->type == "struct" || arg->type == "object") && !arg->optional) result += std::string(" D_ASSERT( ") + arg->param_name() + " != NULL );\n"; } return result; } std::string Method::ArgumentsOutputObjectDecl() const { std::string result; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->type == "object" && arg->direction == "output") result += std::string(" ") + arg->type_name + " *" + arg->name + " = NULL;\n"; } return result; } std::string Method::ArgumentsOutputTmpDecl() const { std::string result; bool second = false; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->direction == "output" && arg->array) { if (second) result += std::string(" ") + arg->type_name + " tmp_" + arg->name + "[" + arg->max + "];\n"; else second = true; } } return result; } std::string Method::ArgumentsInputObjectDecl() const { std::string result; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->type == "object" && arg->direction == "input") result += std::string(" ") + arg->type_name + " *" + arg->name + " = NULL;\n"; } return result; } std::string Method::ArgumentsOutputObjectCatch( const FluxConfig &config ) const { std::string result; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->type == "object" && arg->direction == "output") { char buf[1000]; snprintf( buf, sizeof(buf), " ret = (DFBResult) %s_Catch( %s, return_args->%s%s, &%s );\n" " if (ret) {\n" " D_DERROR( ret, \"%%s: Catching %s by ID %%u failed!\\n\", __FUNCTION__, return_args->%s_id );\n" " goto out;\n" " }\n" "\n" " *%s = %s;\n" "\n", arg->type_name.c_str(), config.c_mode ? "core_dfb" : "core", arg->name.c_str(), config.object_ptrs ? "_ptr" : "_id", arg->name.c_str(), arg->name.c_str(), arg->name.c_str(), arg->param_name().c_str(), arg->name.c_str() ); result += buf; } } return result; } std::string Method::ArgumentsOutputObjectThrow( const FluxConfig &config ) const { std::string result; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->type == "object" && arg->direction == "output") { char buf[1000]; snprintf( buf, sizeof(buf), " %s_Throw( %s, caller, &return_args->%s_id );\n", arg->type_name.c_str(), arg->name.c_str(), arg->name.c_str() ); result += buf; if (config.object_ptrs) { snprintf( buf, sizeof(buf), " return_args->%s_ptr = (void*) %s;\n", arg->name.c_str(), arg->name.c_str() ); result += buf; } } } return result; } std::string Method::ArgumentsInoutReturn() const { std::string result; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->direction == "inout") { char buf[1000]; snprintf( buf, sizeof(buf), " return_args->%s = args->%s;\n", arg->name.c_str(), arg->name.c_str() ); result += buf; } } return result; } std::string Method::ArgumentsOutputTmpReturn() const { std::string result; bool second_output_array = false; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->direction == "output" && arg->array) { if (second_output_array) { char buf[1000]; std::string dst = std::string("(char*) ((char*)(return_args + 1)") + arg->offset( this, true, true ) + ")"; snprintf( buf, sizeof(buf), " direct_memcpy( %s, tmp_%s, return_args->%s_size );\n", dst.c_str(), arg->name.c_str(), arg->name.c_str() ); result += buf; } else second_output_array = true; } } return result; } std::string Method::ArgumentsInputObjectLookup( const FluxConfig &config ) const { std::string result; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->type == "object" && arg->direction == "input") { char buf[1000]; if (arg->optional) { snprintf( buf, sizeof(buf), " if (args->%s_set) {\n" " ret = (DFBResult) %s_Lookup( core_dfb, args->%s_id, caller, &%s );\n" " if (ret) {\n" " D_DERROR( ret, \"%%s(%s): Looking up %s by ID %%u failed!\\n\", __FUNCTION__, args->%s_id );\n" "%s" "%s" " return ret;\n" " }\n" " }\n" "\n", arg->name.c_str(), arg->type_name.c_str(), arg->name.c_str(), arg->name.c_str(), name.c_str(), arg->name.c_str(), arg->name.c_str(), async ? "" : " return_args->result = ret;\n", config.dispatch_error_abort ? " D_BREAK( \"could not lookup object\" );\n" : "" ); } else { snprintf( buf, sizeof(buf), " ret = (DFBResult) %s_Lookup( core_dfb, args->%s_id, caller, &%s );\n" " if (ret) {\n" " D_DERROR( ret, \"%%s(%s): Looking up %s by ID %%u failed!\\n\", __FUNCTION__, args->%s_id );\n" "%s" "%s" " return ret;\n" " }\n" "\n", arg->type_name.c_str(), arg->name.c_str(), arg->name.c_str(), name.c_str(), arg->name.c_str(), arg->name.c_str(), async ? "" : " return_args->result = ret;\n", config.dispatch_error_abort ? " D_BREAK( \"could not lookup object\" );\n" : "" ); } result += buf; } } return result; } std::string Method::ArgumentsInputDebug( const FluxConfig &config, const Interface *face ) const { std::string result; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); if (arg->array) continue; FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->direction == "input" || arg->direction == "inout") { if (arg->optional) result += std::string(" if (args->") + arg->name + "_set)\n"; if (arg->type == "struct") result += std::string(" ; // TODO: ") + arg->type_name + "_debug args->" + arg->name + ";\n"; else if (arg->type == "object") { char buf[1000]; snprintf( buf, sizeof(buf), " D_DEBUG_AT( DirectFB_%s, \" -> %s = %%d\\n\", args->%s_id );\n", face->object.c_str(), arg->name.c_str(), arg->name.c_str() ); result += buf; } else if (arg->type == "enum" || arg->type == "int") { char buf[1000]; snprintf( buf, sizeof(buf), " D_DEBUG_AT( DirectFB_%s, \" -> %s = %%%s\\n\", args->%s );\n", face->object.c_str(), arg->name.c_str(), arg->formatCharacter().c_str(), arg->name.c_str() ); result += buf; } else result += std::string(" ; // TODO: ") + arg->type + " debug\n"; } } return result; } std::string Method::ArgumentsInputObjectUnref() const { std::string result; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->type == "object" && arg->direction == "input") { char buf[1000]; snprintf( buf, sizeof(buf), " if (%s)\n" " %s_Unref( %s );\n" "\n", arg->name.c_str(), arg->type_name.c_str(), arg->name.c_str() ); result += buf; } } return result; } std::string Method::ArgumentsNames() const { std::string result; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); bool last = arg == entities[entities.size()-1]; FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); result += arg->param_name(); if (!last) result += ", "; } return result; } std::string Method::ArgumentsSize( const Interface *face, bool output ) const { std::string result = "sizeof("; bool split = false; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); if (arg->split) { split = true; break; } } if (output) result += face->object + name + "Return)"; else result += face->object + name + ")"; if (split) return result += std::string( " + record_size * num_records" ); for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); if (!arg->array) continue; FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (output) { if (arg->direction == "output" || arg->direction == "inout") result += " + " + arg->sizeMax( false ); } else { if (arg->direction == "input" || arg->direction == "inout") result += " + " + arg->size( false ); } } return result; } std::string Method::ArgumentsSizeReturn( const Interface *face ) const { std::string result = "sizeof("; result += face->object + name + "Return)"; for (Entity::vector::const_iterator iter = entities.begin(); iter != entities.end(); iter++) { const Arg *arg = dynamic_cast<const Arg*>( *iter ); if (!arg->array) continue; FLUX_D_DEBUG_AT( fluxcomp, "%s( %p )\n", __FUNCTION__, arg ); if (arg->direction == "output" || arg->direction == "inout") result += " + " + arg->sizeReturn( this ); } return result; } /**********************************************************************************************************************/ /**********************************************************************************************************************/ class FluxComp { public: void GenerateHeader( const Interface *face, const FluxConfig &config ); void GenerateSource( const Interface *face, const FluxConfig &config ); void PrintInterface( FILE *file, const Interface *face, const std::string &name, const std::string &super, bool abstract ); }; /**********************************************************************************************************************/ void FluxComp::GenerateHeader( const Interface *face, const FluxConfig &config ) { FILE *file; std::string filename = face->object + ".h"; file = fopen( filename.c_str(), "w" ); if (!file) { D_PERROR( "FluxComp: fopen( '%s' ) failed!\n", filename.c_str() ); return; } fprintf( file, "/*\n" " * This file was automatically generated by fluxcomp; DO NOT EDIT!\n" " */\n" "%s\n" "#ifndef ___%s__H___\n" "#define ___%s__H___\n" "\n" "#include %s%s%s%s_includes.h%s\n" "\n" "/**********************************************************************************************************************\n" " * %s\n" " */\n" "\n" "#ifdef __cplusplus\n" "#include <core/Interface.h>\n" "\n" "extern \"C\" {\n" "#endif\n" "\n" "\n", license, face->object.c_str(), face->object.c_str(), config.include_prefix.empty() ? "\"" : "<", config.include_prefix.c_str(), config.include_prefix.empty() ? "" : "/", face->object.c_str(), config.include_prefix.empty() ? "\"" : ">", face->object.c_str() ); /* C Wrappers */ for (Entity::vector::const_iterator iter = face->entities.begin(); iter != face->entities.end(); iter++) { const Method *method = dynamic_cast<const Method*>( *iter ); fprintf( file, "DFBResult %s_%s(\n" " %-40s *obj%s\n" "%s" ");\n" "\n", face->object.c_str(), method->name.c_str(), face->object.c_str(), method->entities.empty() ? "" : ",", method->ArgumentsAsParamDecl().c_str() ); } fprintf( file, "\n" "void %s_Init_Dispatch(\n" " %-20s *core,\n" " %-20s *obj,\n" " FusionCall *call\n" ");\n" "\n", face->object.c_str(), face->core.c_str(), face->dispatch.c_str() ); fprintf( file, "void %s_Deinit_Dispatch(\n" " FusionCall *call\n" ");\n" "\n", face->object.c_str() ); fprintf( file, "\n" "#ifdef __cplusplus\n" "}\n" "%s" "\n" "\n" "%s" "\n" "\n" "/*\n" " * %s Calls\n" " */\n" "typedef enum {\n", config.c_mode ? "#endif\n" : "", !config.c_mode ? "namespace DirectFB {\n" : "", face->object.c_str() ); /* Method IDs */ int index = 1; for (Entity::vector::const_iterator iter = face->entities.begin(); iter != face->entities.end(); iter++) { const Method *method = dynamic_cast<const Method*>( *iter ); fprintf( file, " %s%s_%s = %d,\n", config.c_mode ? "_" : "", face->object.c_str(), method->name.c_str(), index++ ); } fprintf( file, "} %sCall;\n" "\n", face->object.c_str() ); /* Method Argument Structures */ for (Entity::vector::const_iterator iter = face->entities.begin(); iter != face->entities.end(); iter++) { const Method *method = dynamic_cast<const Method*>( *iter ); fprintf( file, "/*\n" " * %s_%s\n" " */\n" "typedef struct {\n" "%s" "} %s%s;\n" "\n" "typedef struct {\n" "%s" "} %s%sReturn;\n" "\n" "\n", face->object.c_str(), method->name.c_str(), method->ArgumentsAsMemberDecl().c_str(), face->object.c_str(), method->name.c_str(), method->ArgumentsOutputAsMemberDecl( config ).c_str(), face->object.c_str(), method->name.c_str() ); } /* Abstract Interface */ if (!config.c_mode) { PrintInterface( file, face, face->name, "Interface", true ); /* Real Interface */ fprintf( file, "\n" "\n" "\n" "class %s_Real : public %s\n" "{\n" "private:\n" " %s *obj;\n" "\n" "public:\n" " %s_Real( %s *core, %s *obj )\n" " :\n" " %s( core ),\n" " obj( obj )\n" " {\n" " }\n" "\n", face->name.c_str(), face->name.c_str(), face->dispatch.c_str(), face->name.c_str(), face->core.c_str(), face->dispatch.c_str(), face->name.c_str() ); } for (Entity::vector::const_iterator iter = face->entities.begin(); iter != face->entities.end(); iter++) { const Method *method = dynamic_cast<const Method*>( *iter ); if (!config.c_mode) { fprintf( file, " virtual DFBResult %s(\n" "%s\n" " );\n" "\n", method->name.c_str(), method->ArgumentsAsParamDecl().c_str() ); } else { fprintf( file, "DFBResult %s_Real__%s( %s *obj%s\n" "%s );\n" "\n", face->name.c_str(), method->name.c_str(), face->dispatch.c_str(), method->ArgumentsAsParamDecl().empty() ? "" : ",", method->ArgumentsAsParamDecl().c_str() ); } } if (!config.c_mode) { fprintf( file, "};\n" ); /* Requestor Interface */ fprintf( file, "\n" "\n" "\n" "class %s_Requestor : public %s%s\n" "{\n" "private:\n" " %s *obj;\n" "\n" "public:\n" " %s_Requestor( %s *core, %s *obj )\n" " :\n" " %s( core ),\n" "%s" " obj( obj )\n" " {\n" " }\n" "\n", face->name.c_str(), face->name.c_str(), face->buffered ? ", public CallBuffer" : "", face->object.c_str(), face->name.c_str(), face->core.c_str(), face->object.c_str(), face->name.c_str(), face->buffered ? " CallBuffer( 16000 ),\n" : "" ); } if (face->buffered) fprintf( file, "protected:\n" " virtual DFBResult flushCalls();\n" "\n" ); if (!config.c_mode) fprintf( file, "public:\n" ); for (Entity::vector::const_iterator iter = face->entities.begin(); iter != face->entities.end(); iter++) { const Method *method = dynamic_cast<const Method*>( *iter ); if (!config.c_mode) { fprintf( file, " virtual DFBResult %s(\n" "%s\n" " );\n" "\n", method->name.c_str(), method->ArgumentsAsParamDecl().c_str() ); } else { fprintf( file, "DFBResult %s_Requestor__%s( %s *obj%s\n" "%s );\n" "\n", face->name.c_str(), method->name.c_str(), face->object.c_str(), method->ArgumentsAsParamDecl().empty() ? "" : ",", method->ArgumentsAsParamDecl().c_str() ); } } if (!config.c_mode) fprintf( file, "};\n" "\n" ); fprintf( file, "\n" "DFBResult %sDispatch__Dispatch( %s *obj,\n" " FusionID caller,\n" " int method,\n" " void *ptr,\n" " unsigned int length,\n" " void *ret_ptr,\n" " unsigned int ret_size,\n" " unsigned int *ret_length );\n", face->object.c_str(), face->dispatch.c_str() ); if (!config.c_mode) fprintf( file, "\n" "}\n" ); fprintf( file, "\n" "\n" "#endif\n" ); if (!config.c_mode) fprintf( file, "\n" "#endif\n" ); fclose( file ); } void FluxComp::GenerateSource( const Interface *face, const FluxConfig &config ) { FILE *file; std::string filename = face->object; bool direct = true; if (!config.c_mode) filename += ".cpp"; else filename += ".c"; if (config.no_direct || face->object != face->dispatch) direct = false; file = fopen( filename.c_str(), "w" ); if (!file) { D_PERROR( "FluxComp: fopen( '%s' ) failed!\n", filename.c_str() ); return; } fprintf( file, "/*\n" " * This file was automatically generated by fluxcomp; DO NOT EDIT!\n" " */\n" "%s\n" "#include <config.h>\n" "\n" "#include \"%s.h\"\n" "\n", license, face->object.c_str() ); if (!config.c_mode) fprintf( file, "extern \"C\" {\n" ); fprintf( file, "#include <directfb_util.h>\n" "\n" "#include <direct/debug.h>\n" "#include <direct/mem.h>\n" "#include <direct/memcpy.h>\n" "#include <direct/messages.h>\n" "\n" "#include <fusion/conf.h>\n" "\n" "#include <core/core.h>\n" ); if (config.call_mode) fprintf( file, "\n" "#include <core/CoreDFB_CallMode.h>\n" ); if (!config.c_mode) fprintf( file, "}\n" ); fprintf( file, "\n" "D_DEBUG_DOMAIN( DirectFB_%s, \"DirectFB/%s\", \"DirectFB %s\" );\n" "\n" "/*********************************************************************************************************************/\n" "\n", face->object.c_str(), face->object.c_str(), face->object.c_str() ); /* C Wrappers */ for (Entity::vector::const_iterator iter = face->entities.begin(); iter != face->entities.end(); iter++) { const Method *method = dynamic_cast<const Method*>( *iter ); if (!config.c_mode) { fprintf( file, "DFBResult\n" "%s_%s(\n" " %-40s *obj%s\n" "%s\n" ")\n" "{\n", face->object.c_str(), method->name.c_str(), face->object.c_str(), method->entities.empty() ? "" : ",", method->ArgumentsAsParamDecl().c_str() ); if (config.call_mode) { fprintf( file, " DFBResult ret;\n" "\n" " switch (CoreDFB_CallMode( core_dfb )) {\n" " case COREDFB_CALL_DIRECT:" ); if (direct) fprintf( file, "{\n" " DirectFB::%s_Real real( core_dfb, obj );\n" "\n" " Core_PushCalling();\n" " ret = real.%s( %s );\n" " Core_PopCalling();\n" "\n" " return ret;\n" " }", face->name.c_str(), method->name.c_str(), method->ArgumentsNames().c_str() ); fprintf( file, "\n case COREDFB_CALL_INDIRECT: {\n" " DirectFB::%s_Requestor requestor( core_dfb, obj );\n" "\n" " Core_PushCalling();\n" " ret = requestor.%s( %s );\n" " Core_PopCalling();\n" "\n" " return ret;\n" " }\n" " case COREDFB_CALL_DENY:\n" " return DFB_DEAD;\n" " }\n" "\n" " return DFB_UNIMPLEMENTED;\n" "}\n" "\n", face->name.c_str(), method->name.c_str(), method->ArgumentsNames().c_str() ); } else { if (direct) fprintf( file, " if (!fusion_config->secure_fusion || dfb_core_is_master( core_dfb )) {\n" " DirectFB::%s_Real real( core_dfb, obj );\n" "\n" " return real.%s( %s );\n" " }\n" "\n", face->name.c_str(), method->name.c_str(), method->ArgumentsNames().c_str() ); fprintf( file, " DirectFB::%s_Requestor requestor( core_dfb, obj );\n" "\n" " return requestor.%s( %s );\n" "}\n" "\n", face->name.c_str(), method->name.c_str(), method->ArgumentsNames().c_str() ); } } else { fprintf( file, "DFBResult\n" "%s_%s(\n" " %-40s *obj%s\n" "%s\n" ")\n" "{\n", face->object.c_str(), method->name.c_str(), face->object.c_str(), method->entities.empty() ? "" : ",", method->ArgumentsAsParamDecl().c_str() ); if (config.call_mode) { fprintf( file, " DFBResult ret;\n" "\n" " switch (CoreDFB_CallMode( core_dfb )) {\n" " case COREDFB_CALL_DIRECT:" ); if (direct) fprintf( file, "{\n" " Core_PushCalling();\n" " ret = %s_Real__%s( obj%s%s );\n" " Core_PopCalling();\n" "\n" " return ret;\n" " }\n", face->name.c_str(), method->name.c_str(), method->ArgumentsAsParamDecl().empty() ? "" : ", ", method->ArgumentsNames().c_str() ); fprintf( file, "\n case COREDFB_CALL_INDIRECT: {\n" " Core_PushCalling();\n" " ret = %s_Requestor__%s( obj%s%s );\n" " Core_PopCalling();\n" "\n" " return ret;\n" " }\n" " case COREDFB_CALL_DENY:\n" " return DFB_DEAD;\n" " }\n" "\n" " return DFB_UNIMPLEMENTED;\n" "}\n" "\n", face->name.c_str(), method->name.c_str(), method->ArgumentsAsParamDecl().empty() ? "" : ", ", method->ArgumentsNames().c_str() ); } else { if (direct) fprintf( file, " if (!fusion_config->secure_fusion || dfb_core_is_master( core_dfb )) {\n" " return %s_Real__%s( obj%s%s );\n" " }\n" "\n", face->name.c_str(), method->name.c_str(), method->ArgumentsAsParamDecl().empty() ? "" : ", ", method->ArgumentsNames().c_str() ); fprintf( file, " return %s_Requestor__%s( obj%s%s );\n" "}\n" "\n", face->name.c_str(), method->name.c_str(), method->ArgumentsAsParamDecl().empty() ? "" : ", ", method->ArgumentsNames().c_str() ); } } } fprintf( file, "/*********************************************************************************************************************/\n" "\n" "static FusionCallHandlerResult\n" "%s_Dispatch( int caller, /* fusion id of the caller */\n" " int call_arg, /* optional call parameter */\n" " void *ptr, /* optional call parameter */\n" " unsigned int length,\n" " void *ctx, /* optional handler context */\n" " unsigned int serial,\n" " void *ret_ptr,\n" " unsigned int ret_size,\n" " unsigned int *ret_length )\n" "{\n", face->object.c_str() ); fprintf( file, " %s *obj = (%s*) ctx;" "\n" " %s%sDispatch__Dispatch( obj, caller, call_arg, ptr, length, ret_ptr, ret_size, ret_length );\n" "\n" " return FCHR_RETURN;\n" "}\n" "\n", face->dispatch.c_str(), face->dispatch.c_str(), config.c_mode ? "" : "DirectFB::", face->object.c_str() ); fprintf( file, "void %s_Init_Dispatch(\n" " %-20s *core,\n" " %-20s *obj,\n" " FusionCall *call\n" ")\n" "{\n", face->object.c_str(), face->core.c_str(), face->dispatch.c_str() ); fprintf( file, " fusion_call_init3( call, %s_Dispatch, obj, core->world );\n" "}\n" "\n", face->object.c_str() ); fprintf( file, "void %s_Deinit_Dispatch(\n" " FusionCall *call\n" ")\n" "{\n" " fusion_call_destroy( call );\n" "}\n" "\n", face->object.c_str() ); fprintf( file, "/*********************************************************************************************************************/\n" "\n" ); if (!config.c_mode) { fprintf( file, "namespace DirectFB {\n" "\n" "\n" ); } /* Requestor Methods */ fprintf( file, "static __inline__ void *args_alloc( void *static_buffer, size_t size )\n" "{\n" " void *buffer = static_buffer;\n" "\n" " if (size > %s) {\n" " buffer = D_MALLOC( size );\n" " if (!buffer)\n" " return NULL;\n" " }\n" "\n" " return buffer;\n" "}\n" "\n", config.static_args_bytes.c_str() ); fprintf( file, "static __inline__ void args_free( void *static_buffer, void *buffer )\n" "{\n" " if (buffer != static_buffer)\n" " D_FREE( buffer );\n" "}\n" "\n" ); if (face->buffered) { fprintf( file, "\n" "DFBResult\n" "%s_Requestor::flushCalls()\n" "{\n" " DFBResult ret;\n" "\n" " ret = (DFBResult) %s_Call( obj, (FusionCallExecFlags)(FCEF_ONEWAY | FCEF_QUEUE), -1, buffer, buffer_len, NULL, 0, NULL );\n" " if (ret) {\n" " D_DERROR( ret, \"%%s: %s_Call( -1 ) failed!\\n\", __FUNCTION__ );\n" " return ret;\n" " }\n" "\n" " return DFB_OK;\n" "}\n", face->name.c_str(), face->object.c_str(), face->object.c_str() ); } for (Entity::vector::const_iterator iter = face->entities.begin(); iter != face->entities.end(); iter++) { const Method *method = dynamic_cast<const Method*>( *iter ); if (!config.c_mode) { fprintf( file, "\n" "DFBResult\n" "%s_Requestor::%s(\n" "%s\n" ")\n", face->name.c_str(), method->name.c_str(), method->ArgumentsAsParamDecl().c_str() ); } else { fprintf( file, "\n" "DFBResult\n" "%s_Requestor__%s( %s *obj%s\n" "%s\n" ")\n", face->name.c_str(), method->name.c_str(), face->object.c_str(), method->ArgumentsAsParamDecl().empty() ? "" : ",", method->ArgumentsAsParamDecl().c_str() ); } if (method->buffer && face->buffered) { fprintf( file, "{\n" "%s" " %s%s *args = (%s%s*) prepare( %s%s_%s, %s );\n" "\n" " if (!args)\n" " return (DFBResult) D_OOM();\n" "\n" " D_DEBUG_AT( DirectFB_%s, \"%s_Requestor::%%s()\\n\", __FUNCTION__ );\n" "\n" "%s" "\n" "%s" "\n" " commit();\n" "\n" "%s" "\n" "%s" "%s" "\n" " return DFB_OK;\n" "}\n" "\n", method->OpenSplitArgumentsIfRequired().c_str(), face->object.c_str(), method->name.c_str(), face->object.c_str(), method->name.c_str(), config.c_mode ? "_" : "", face->object.c_str(), method->name.c_str(), method->ArgumentsSize( face, false ).c_str(), face->object.c_str(), face->name.c_str(), method->ArgumentsAssertions().c_str(), method->ArgumentsInputAssignments().c_str(), method->ArgumentsOutputAssignments().c_str(), method->ArgumentsOutputObjectCatch( config ).c_str(), method->CloseSplitArgumentsIfRequired().c_str() ); } else if (method->async) { fprintf( file, "{\n" " DFBResult ret = DFB_OK;\n" "%s" " char args_static[%s];\n" " %s%s *args = (%s%s*) args_alloc( args_static, %s );\n" "\n" " if (!args)\n" " return (DFBResult) D_OOM();\n" "\n" " D_DEBUG_AT( DirectFB_%s, \"%s_Requestor::%%s()\\n\", __FUNCTION__ );\n" "\n" "%s" "\n" "%s" "\n" "%s" " ret = (DFBResult) %s_Call( obj, (FusionCallExecFlags)(FCEF_ONEWAY%s), %s%s_%s, args, %s, NULL, 0, NULL );\n" " if (ret) {\n" " D_DERROR( ret, \"%%s: %s_Call( %s_%s ) failed!\\n\", __FUNCTION__ );\n" " goto out;\n" " }\n" "\n" "%s" "\n" "%s" "\n" "out:\n" " args_free( args_static, args );\n" " return ret;\n" "}\n" "\n", method->ArgumentsOutputObjectDecl().c_str(), config.static_args_bytes.c_str(), face->object.c_str(), method->name.c_str(), face->object.c_str(), method->name.c_str(), method->ArgumentsSize( face, false ).c_str(), face->object.c_str(), face->name.c_str(), method->ArgumentsAssertions().c_str(), method->ArgumentsInputAssignments().c_str(), face->buffered ? " flush();\n\n" : "", face->object.c_str(), method->queue ? " | FCEF_QUEUE" : "", config.c_mode ? "_" : "", face->object.c_str(), method->name.c_str(), method->ArgumentsSize( face, false ).c_str(), face->object.c_str(), face->object.c_str(), method->name.c_str(), method->ArgumentsOutputAssignments().c_str(), method->ArgumentsOutputObjectCatch( config ).c_str() ); } else { fprintf( file, "{\n" " DFBResult ret = DFB_OK;\n" "%s" " char args_static[%s];\n" " char return_args_static[%s];\n" " %s%s *args = (%s%s*) args_alloc( args_static, %s );\n" " %s%sReturn *return_args;\n" "\n" " if (!args)\n" " return (DFBResult) D_OOM();\n" "\n" " return_args = (%s%sReturn*) args_alloc( return_args_static, %s );\n" "\n" " if (!return_args) {\n" " args_free( args_static, args );\n" " return (DFBResult) D_OOM();\n" " }\n" "\n" " D_DEBUG_AT( DirectFB_%s, \"%s_Requestor::%%s()\\n\", __FUNCTION__ );\n" "\n" "%s" "\n" "%s" "\n" "%s" " ret = (DFBResult) %s_Call( obj, FCEF_NONE, %s%s_%s, args, %s, return_args, %s, NULL );\n" " if (ret) {\n" " D_DERROR( ret, \"%%s: %s_Call( %s_%s ) failed!\\n\", __FUNCTION__ );\n" " goto out;\n" " }\n" "\n" " if (return_args->result) {\n" " /*D_DERROR( return_args->result, \"%%s: %s_%s failed!\\n\", __FUNCTION__ );*/\n" " ret = return_args->result;\n" " goto out;\n" " }\n" "\n" "%s" "\n" "%s" "\n" "out:\n" " args_free( return_args_static, return_args );\n" " args_free( args_static, args );\n" " return ret;\n" "}\n" "\n", method->ArgumentsOutputObjectDecl().c_str(), config.static_args_bytes.c_str(), config.static_args_bytes.c_str(), face->object.c_str(), method->name.c_str(), face->object.c_str(), method->name.c_str(), method->ArgumentsSize( face, false ).c_str(), face->object.c_str(), method->name.c_str(), face->object.c_str(), method->name.c_str(), method->ArgumentsSize( face, true ).c_str(), face->object.c_str(), face->name.c_str(), method->ArgumentsAssertions().c_str(), method->ArgumentsInputAssignments().c_str(), face->buffered ? " flush();\n\n" : "", face->object.c_str(), config.c_mode ? "_" : "", face->object.c_str(), method->name.c_str(), method->ArgumentsSize( face, false ).c_str(), method->ArgumentsSize( face, true ).c_str(), face->object.c_str(), face->object.c_str(), method->name.c_str(), face->object.c_str(), method->name.c_str(), method->ArgumentsOutputAssignments().c_str(), method->ArgumentsOutputObjectCatch( config ).c_str() ); } } /* Dispatch Object */ fprintf( file, "/*********************************************************************************************************************/\n" "\n" "static DFBResult\n" "__%sDispatch__Dispatch( %s *obj,\n" " FusionID caller,\n" " int method,\n" " void *ptr,\n" " unsigned int length,\n" " void *ret_ptr,\n" " unsigned int ret_size,\n" " unsigned int *ret_length )\n" "{\n" " D_UNUSED\n" " DFBResult ret;\n" "\n", face->object.c_str(), face->dispatch.c_str() ); if (!config.c_mode) fprintf( file, "\n" " DirectFB::%s_Real real( core_dfb, obj );\n" "\n", face->name.c_str() ); fprintf( file, "\n" " switch (method) {\n" ); /* Dispatch Methods */ for (Entity::vector::const_iterator iter = face->entities.begin(); iter != face->entities.end(); iter++) { const Method *method = dynamic_cast<const Method*>( *iter ); if (!config.c_mode) fprintf( file, " case %s_%s: {\n", face->object.c_str(), method->name.c_str() ); else fprintf( file, " case _%s_%s: {\n", face->object.c_str(), method->name.c_str() ); if (method->async) { fprintf( file, "%s" "%s" " D_UNUSED\n" " %s%s *args = (%s%s *) ptr;\n" "\n" " D_DEBUG_AT( DirectFB_%s, \"=-> %s_%s\\n\" );\n" "\n" "%s" "\n" "%s", method->ArgumentsInputObjectDecl().c_str(), method->ArgumentsOutputObjectDecl().c_str(), face->object.c_str(), method->name.c_str(), face->object.c_str(), method->name.c_str(), face->object.c_str(), face->object.c_str(), method->name.c_str(), method->ArgumentsInputDebug( config, face ).c_str(), method->ArgumentsInputObjectLookup( config ).c_str() ); if (!config.c_mode) fprintf( file, " real.%s( %s );\n", method->name.c_str(), method->ArgumentsAsMemberParams().c_str() ); else fprintf( file, " %s_Real__%s( obj%s%s );\n", face->name.c_str(), method->name.c_str(), method->ArgumentsAsParamDecl().empty() ? "" : ", ", method->ArgumentsAsMemberParams().c_str() ); fprintf( file, "\n" "%s" " return DFB_OK;\n" " }\n" "\n", method->ArgumentsInputObjectUnref().c_str() ); } else { fprintf( file, "%s" "%s" "%s" " D_UNUSED\n" " %s%s *args = (%s%s *) ptr;\n" " %s%sReturn *return_args = (%s%sReturn *) ret_ptr;\n" "\n" " D_DEBUG_AT( DirectFB_%s, \"=-> %s_%s\\n\" );\n" "\n" "%s", method->ArgumentsInputObjectDecl().c_str(), method->ArgumentsOutputObjectDecl().c_str(), method->ArgumentsOutputTmpDecl().c_str(), face->object.c_str(), method->name.c_str(), face->object.c_str(), method->name.c_str(), face->object.c_str(), method->name.c_str(), face->object.c_str(), method->name.c_str(), face->object.c_str(), face->object.c_str(), method->name.c_str(), method->ArgumentsInputObjectLookup( config ).c_str() ); if (!config.c_mode) fprintf( file, " return_args->result = real.%s( %s );\n", method->name.c_str(), method->ArgumentsAsMemberParams().c_str() ); else fprintf( file, " return_args->result = %s_Real__%s( obj%s%s );\n", face->name.c_str(), method->name.c_str(), method->ArgumentsAsParamDecl().empty() ? "" : ", ", method->ArgumentsAsMemberParams().c_str() ); fprintf( file, " if (return_args->result == DFB_OK) {\n" "%s" "%s" "%s" " }\n" "\n" " *ret_length = %s;\n" "\n" "%s" " return DFB_OK;\n" " }\n" "\n", method->ArgumentsOutputObjectThrow( config ).c_str(), method->ArgumentsInoutReturn().c_str(), method->ArgumentsOutputTmpReturn().c_str(), method->ArgumentsSizeReturn( face ).c_str(), method->ArgumentsInputObjectUnref().c_str() ); } } fprintf( file, " }\n" "\n" " return DFB_NOSUCHMETHOD;\n" "}\n" ); fprintf( file, "/*********************************************************************************************************************/\n" "\n" "DFBResult\n" "%sDispatch__Dispatch( %s *obj,\n" " FusionID caller,\n" " int method,\n" " void *ptr,\n" " unsigned int length,\n" " void *ret_ptr,\n" " unsigned int ret_size,\n" " unsigned int *ret_length )\n" "{\n" " DFBResult ret = DFB_OK;\n" "\n" " D_DEBUG_AT( DirectFB_%s, \"%sDispatch::%%s( %%p )\\n\", __FUNCTION__, obj );\n", face->object.c_str(), face->dispatch.c_str(), face->object.c_str(), face->object.c_str()); if (config.identity) fprintf( file, "\n" " Core_PushIdentity( caller );\n" ); if (face->buffered) { fprintf( file, "\n" " if (method == -1) {\n" " unsigned int consumed = 0;\n" "\n" " while (consumed < length) {\n" " u32 *p = (u32*)( (u8*) ptr + consumed );\n" "\n" " if ((p[0] > length - consumed) || (consumed + p[0] > length)) {\n" " D_WARN( \"invalid data from caller %%lu\", caller );\n" " break;\n" " }\n" "\n" " consumed += p[0];\n" "\n" " ret = __%sDispatch__Dispatch( obj, caller, p[1], p + 2, p[0] - sizeof(int) * 2, NULL, 0, NULL );\n" " if (ret)\n" " break;\n" " }\n" " }\n" " else\n", face->object.c_str() ); } fprintf( file, "\n" " ret = __%sDispatch__Dispatch( obj, caller, method, ptr, length, ret_ptr, ret_size, ret_length );\n", face->object.c_str() ); if (config.identity) fprintf( file, "\n" " Core_PopIdentity();\n" ); fprintf( file, "\n" " return ret;\n" "}\n" ); if (!config.c_mode) fprintf( file, "\n" "}\n" ); fclose( file ); } void FluxComp::PrintInterface( FILE *file, const Interface *face, const std::string &name, const std::string &super, bool abstract ) { fprintf( file, "\n" "\n" "\n" "class %s : public %s\n" "{\n" "public:\n" " %s( %s *core )\n" " :\n" " %s( core )\n" " {\n" " }\n" "\n" "public:\n", name.c_str(), super.c_str(), name.c_str(), face->core.c_str(), super.c_str() ); for (Entity::vector::const_iterator iter = face->entities.begin(); iter != face->entities.end(); iter++) { const Method *method = dynamic_cast<const Method*>( *iter ); fprintf( file, " virtual DFBResult %s(\n" "%s\n" " )%s;\n" "\n", method->name.c_str(), method->ArgumentsAsParamDecl().c_str(), abstract ? " = 0" : "" ); } fprintf( file, "};\n" ); } /**********************************************************************************************************************/ /**********************************************************************************************************************/ int main( int argc, char *argv[] ) { DirectResult ret; Entity::vector faces; FluxConfig config; direct_initialize(); // direct_debug_config_domain( "fluxcomp", true ); // direct_config->debug = true; // direct_config->debugmem = true; /* Parse the command line. */ if (!config.parse_command_line( argc, argv )) return -1; ret = Entity::GetEntities( filename, faces ); if (ret == DR_OK) { FluxComp fc; for (Entity::vector::const_iterator iter = faces.begin(); iter != faces.end(); iter++) { Interface *face = dynamic_cast<Interface*>( *iter ); for (Entity::vector::const_iterator iter = face->entities.begin(); iter != face->entities.end(); iter++) { Method *method = dynamic_cast<Method*>( *iter ); if (!method->async || !method->queue) method->buffer = false; if (method->buffer) { face->buffered = true; break; } } fc.GenerateHeader( face, config ); fc.GenerateSource( face, config ); } } direct_print_memleaks(); direct_shutdown(); return ret; }
gpl-3.0
Zlash65/erpnext
erpnext/selling/page/point_of_sale/point_of_sale.py
4834
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe, json from frappe.utils.nestedset import get_root_of from frappe.utils import cint from erpnext.accounts.doctype.pos_profile.pos_profile import get_item_groups from six import string_types @frappe.whitelist() def get_items(start, page_length, price_list, item_group, search_value="", pos_profile=None): data = dict() warehouse = "" display_items_in_stock = 0 if pos_profile: warehouse, display_items_in_stock = frappe.db.get_value('POS Profile', pos_profile, ['warehouse', 'display_items_in_stock']) if not frappe.db.exists('Item Group', item_group): item_group = get_root_of('Item Group') if search_value: data = search_serial_or_batch_or_barcode_number(search_value) item_code = data.get("item_code") if data.get("item_code") else search_value serial_no = data.get("serial_no") if data.get("serial_no") else "" batch_no = data.get("batch_no") if data.get("batch_no") else "" barcode = data.get("barcode") if data.get("barcode") else "" condition = get_conditions(item_code, serial_no, batch_no, barcode) if pos_profile: condition += get_item_group_condition(pos_profile) lft, rgt = frappe.db.get_value('Item Group', item_group, ['lft', 'rgt']) # locate function is used to sort by closest match from the beginning of the value result = [] items_data = frappe.db.sql(""" SELECT name as item_code, item_name, image as item_image, idx as idx,is_stock_item FROM `tabItem` WHERE disabled = 0 and has_variants = 0 and is_sales_item = 1 and item_group in (select name from `tabItem Group` where lft >= {lft} and rgt <= {rgt}) and {condition} order by idx desc limit {start}, {page_length}""" .format( start=start, page_length=page_length, lft=lft, rgt=rgt, condition=condition ), as_dict=1) if items_data: items = [d.item_code for d in items_data] item_prices_data = frappe.get_all("Item Price", fields = ["item_code", "price_list_rate", "currency"], filters = {'price_list': price_list, 'item_code': ['in', items]}) item_prices, bin_data = {}, {} for d in item_prices_data: item_prices[d.item_code] = d if display_items_in_stock: filters = {'actual_qty': [">", 0], 'item_code': ['in', items]} if warehouse: filters['warehouse'] = warehouse bin_data = frappe._dict( frappe.get_all("Bin", fields = ["item_code", "sum(actual_qty) as actual_qty"], filters = filters, group_by = "item_code") ) for item in items_data: row = {} row.update(item) item_price = item_prices.get(item.item_code) or {} row.update({ 'price_list_rate': item_price.get('price_list_rate'), 'currency': item_price.get('currency'), 'actual_qty': bin_data.get('actual_qty') }) result.append(row) res = { 'items': result } if serial_no: res.update({ 'serial_no': serial_no }) if batch_no: res.update({ 'batch_no': batch_no }) if barcode: res.update({ 'barcode': barcode }) return res @frappe.whitelist() def search_serial_or_batch_or_barcode_number(search_value): # search barcode no barcode_data = frappe.db.get_value('Item Barcode', {'barcode': search_value}, ['barcode', 'parent as item_code'], as_dict=True) if barcode_data: return barcode_data # search serial no serial_no_data = frappe.db.get_value('Serial No', search_value, ['name as serial_no', 'item_code'], as_dict=True) if serial_no_data: return serial_no_data # search batch no batch_no_data = frappe.db.get_value('Batch', search_value, ['name as batch_no', 'item as item_code'], as_dict=True) if batch_no_data: return batch_no_data return {} def get_conditions(item_code, serial_no, batch_no, barcode): if serial_no or batch_no or barcode: return "name = {0}".format(frappe.db.escape(item_code)) return """(name like {item_code} or item_name like {item_code})""".format(item_code = frappe.db.escape('%' + item_code + '%')) def get_item_group_condition(pos_profile): cond = "and 1=1" item_groups = get_item_groups(pos_profile) if item_groups: cond = "and item_group in (%s)"%(', '.join(['%s']*len(item_groups))) return cond % tuple(item_groups) def item_group_query(doctype, txt, searchfield, start, page_len, filters): item_groups = [] cond = "1=1" pos_profile= filters.get('pos_profile') if pos_profile: item_groups = get_item_groups(pos_profile) if item_groups: cond = "name in (%s)"%(', '.join(['%s']*len(item_groups))) cond = cond % tuple(item_groups) return frappe.db.sql(""" select distinct name from `tabItem Group` where {condition} and (name like %(txt)s) limit {start}, {page_len}""" .format(condition = cond, start=start, page_len= page_len), {'txt': '%%%s%%' % txt})
gpl-3.0
oltur/seeyourtravel.com
lib/leaflet-0.6/spec/suites/core/UtilSpec.js
4607
describe('Util', function() { describe('#extend', function() { var a; beforeEach(function() { a = { foo: 5, bar: 'asd' }; }); it('extends the first argument with the properties of the second', function() { L.Util.extend(a, { bar: 7, baz: 3 }); expect(a).to.eql({ foo: 5, bar: 7, baz: 3 }); }); it('accepts more than 2 arguments', function() { L.Util.extend(a, {bar: 7}, {baz: 3}); expect(a).to.eql({ foo: 5, bar: 7, baz: 3 }); }); }); describe('#bind', function() { it('returns the given function with the given context', function() { var fn = function() { return this; }; var fn2 = L.Util.bind(fn, { foo: 'bar' }); expect(fn2()).to.eql({ foo: 'bar' }); }); it('passes additional arguments to the bound function', function () { var fn = sinon.spy(), foo = {}, a = {}, b = {}; var fn2 = L.Util.bind(fn, foo, a, b); fn2(); expect(fn.calledWith(a, b)).to.be.ok(); }); }); describe('#stamp', function() { it('sets a unique id on the given object and returns it', function() { var a = {}, id = L.Util.stamp(a); expect(typeof id).to.eql('number'); expect(L.Util.stamp(a)).to.eql(id); var b = {}, id2 = L.Util.stamp(b); expect(id2).not.to.eql(id); }); }); describe('#invokeEach', function () { it('calls the given method/context with each key/value and additional arguments', function () { var spy = sinon.spy(), ctx = {}; var result = L.Util.invokeEach({ foo: 'bar', yo: 'hey' }, spy, ctx, 1, 2, 3); expect(spy.firstCall.calledWith('foo', 'bar', 1, 2, 3)).to.be.ok(); expect(spy.secondCall.calledWith('yo', 'hey', 1, 2, 3)).to.be.ok(); expect(spy.firstCall.calledOn(ctx)).to.be.ok(); expect(spy.secondCall.calledOn(ctx)).to.be.ok(); expect(result).to.be(true); }); it('returns false if the given agument is not object', function () { var spy = sinon.spy(); expect(L.Util.invokeEach('foo', spy)).to.be(false); expect(spy.called).to.be(false); }); }); describe('#falseFn', function () { it('returns false', function () { expect(L.Util.falseFn()).to.be(false); }); }); describe('#formatNum', function () { it('formats numbers with a given precision', function () { expect(L.Util.formatNum(13.12325555, 3)).to.eql(13.123); expect(L.Util.formatNum(13.12325555)).to.eql(13.12326); }); }); describe('#getParamString', function() { it('creates a valid query string for appending depending on url input', function() { var a = { url: "http://example.com/get", obj: {bar: 7, baz: 3}, result: "?bar=7&baz=3" }; expect(L.Util.getParamString(a.obj,a.url)).to.eql(a.result); var b = { url: "http://example.com/get?justone=qs", obj: {bar: 7, baz: 3}, result: "&bar=7&baz=3" }; expect(L.Util.getParamString(b.obj,b.url)).to.eql(b.result); var c = { url: undefined, obj: {bar: 7, baz: 3}, result: "?bar=7&baz=3" }; expect(L.Util.getParamString(c.obj,c.url)).to.eql(c.result); }); }); describe('#requestAnimFrame', function () { it('calles a function on next frame, unless canceled', function (done) { var spy = sinon.spy(), spy2 = sinon.spy(), foo = {}; L.Util.requestAnimFrame(spy); L.Util.requestAnimFrame(function () { expect(this).to.eql(foo); done(); }, foo); L.Util.cancelAnimFrame(spy); }); }); describe('#limitExecByInterval', function() { it('limits execution to not more often than specified time interval', function (done) { var spy = sinon.spy(); var fn = L.Util.limitExecByInterval(spy, 20); fn(); fn(); fn(); expect(spy.callCount).to.eql(1); setTimeout(function () { expect(spy.callCount).to.eql(2); done(); }, 30); }); }); describe('#splitWords', function () { it('splits words into an array', function () { expect(L.Util.splitWords('foo bar baz')).to.eql(['foo', 'bar', 'baz']); }); }); // TODO setOptions describe('#template', function () { it('evaluates templates with a given data object', function () { var tpl = 'Hello {foo} and {bar}!'; var str = L.Util.template(tpl, { foo: 'Vlad', bar: 'Dave' }); expect(str).to.eql('Hello Vlad and Dave!'); }); it('does not modify text without a token variable', function () { expect(L.Util.template('foo', {})).to.eql('foo'); }); it('throws when a template token is not given', function () { expect(function () { L.Util.template(tpl, {foo: 'bar'}); }).to.throwError(); }); }); });
gpl-3.0
guaix-ucm/numina
numina/instrument/simulation/optics.py
702
# # Copyright 2016-2018 Universidad Complutense de Madrid # # This file is part of Numina # # SPDX-License-Identifier: GPL-3.0+ # License-Filename: LICENSE.txt # import numpy class Stop(object): def __init__(self, name): self.name = name def transmission(self, wl): return numpy.zeros_like(wl) class Open(object): def __init__(self, name): self.name = name def transmission(self, wl): return numpy.ones_like(wl) class Filter(object): def __init__(self, name, transmission=None): self.name = name def transmission(self, wl): # FIXME: implement this with a proper # transmission return numpy.ones_like(wl)
gpl-3.0
monash-merc/karaage
karaage/legacy/usage/south_migrations/0006_auto__chg_field_cpujob_jobname.py
19377
# encoding: utf-8 from south.db import db from south.v2 import SchemaMigration class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'CPUJob.jobname' db.alter_column('cpu_job', 'jobname', self.gf('django.db.models.fields.CharField')(max_length=256, null=True)) def backwards(self, orm): # Changing field 'CPUJob.jobname' db.alter_column('cpu_job', 'jobname', self.gf('django.db.models.fields.CharField')(max_length=100, null=True)) models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'machines.machine': { 'Meta': {'object_name': 'Machine', 'db_table': "'machine'"}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['machines.MachineCategory']"}), 'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'mem_per_core': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'no_cpus': ('django.db.models.fields.IntegerField', [], {}), 'no_nodes': ('django.db.models.fields.IntegerField', [], {}), 'pbs_server_host': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'scaling_factor': ('django.db.models.fields.IntegerField', [], {'default': '1'}), 'start_date': ('django.db.models.fields.DateField', [], {}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'machines.machinecategory': { 'Meta': {'object_name': 'MachineCategory', 'db_table': "'machine_category'"}, 'datastore': ('django.db.models.fields.CharField', [], {'default': "'karaage.datastores.openldap_datastore'", 'max_length': '255'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'machines.useraccount': { 'Meta': {'ordering': "['user']", 'object_name': 'UserAccount', 'db_table': "'user_account'"}, 'date_created': ('django.db.models.fields.DateField', [], {}), 'date_deleted': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'default_project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['projects.Project']", 'null': 'True', 'blank': 'True'}), 'disk_quota': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'machine_category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['machines.MachineCategory']"}), 'previous_shell': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Person']"}), 'username': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'people.institute': { 'Meta': {'ordering': "['name']", 'object_name': 'Institute', 'db_table': "'institute'"}, 'delegates': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'delegate'", 'to': "orm['people.Person']", 'through': "orm['people.InstituteDelegate']", 'blank': 'True', 'symmetrical': 'False', 'null': 'True'}), 'gid': ('django.db.models.fields.IntegerField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}), 'saml_entityid': ('django.db.models.fields.CharField', [], {'max_length': '200', 'unique': 'True', 'null': 'True', 'blank': 'True'}) }, 'people.institutedelegate': { 'Meta': {'object_name': 'InstituteDelegate'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Institute']"}), 'person': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Person']"}), 'send_email': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) }, 'people.person': { 'Meta': {'ordering': "['first_name', 'last_name']", 'object_name': 'Person', 'db_table': "'person'"}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'approved_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'user_approver'", 'null': 'True', 'to': "orm['people.Person']"}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'comment': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'country': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}), 'date_approved': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'date_deleted': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'user_deletor'", 'null': 'True', 'to': "orm['people.Person']"}), 'department': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'expires': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'fax': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Institute']"}), 'is_systemuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_usage': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'mobile': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'position': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'postcode': ('django.db.models.fields.CharField', [], {'max_length': '8', 'null': 'True', 'blank': 'True'}), 'saml_id': ('django.db.models.fields.CharField', [], {'max_length': '200', 'unique': 'True', 'null': 'True', 'blank': 'True'}), 'state': ('django.db.models.fields.CharField', [], {'max_length': '4', 'null': 'True', 'blank': 'True'}), 'supervisor': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'telephone': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, 'projects.project': { 'Meta': {'ordering': "['pid']", 'object_name': 'Project', 'db_table': "'project'"}, 'additional_req': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'approved_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'project_approver'", 'null': 'True', 'to': "orm['people.Person']"}), 'date_approved': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'date_deleted': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'project_deletor'", 'null': 'True', 'to': "orm['people.Person']"}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Institute']"}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_approved': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_usage': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'leaders': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'leaders'", 'symmetrical': 'False', 'to': "orm['people.Person']"}), 'machine_categories': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'projects'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['machines.MachineCategory']"}), 'machine_category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['machines.MachineCategory']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'pid': ('django.db.models.fields.CharField', [], {'max_length': '50', 'primary_key': 'True'}), 'start_date': ('django.db.models.fields.DateField', [], {}), 'users': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['people.Person']", 'null': 'True', 'blank': 'True'}) }, 'software.softwarecategory': { 'Meta': {'ordering': "['name']", 'object_name': 'SoftwareCategory', 'db_table': "'software_category'"}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'software.software': { 'Meta': {'ordering': "['name']", 'object_name': 'SoftwarePackage', 'db_table': "'software_package'"}, 'academic_only': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['software.SoftwareCategory']", 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'gid': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'homepage': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200'}), 'restricted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'tutorial_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, 'software.softwareversion': { 'Meta': {'ordering': "['-version']", 'object_name': 'SoftwareVersion', 'db_table': "'software_version'"}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_used': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'machines': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['machines.Machine']", 'symmetrical': 'False'}), 'module': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'package': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['software.SoftwarePackage']"}), 'version': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'usage.cpujob': { 'Meta': {'ordering': "['-date']", 'object_name': 'CPUJob', 'db_table': "'cpu_job'"}, 'act_wall_time': ('django.db.models.fields.BigIntegerField', [], {'null': 'True', 'blank': 'True'}), 'cores': ('django.db.models.fields.BigIntegerField', [], {'null': 'True', 'blank': 'True'}), 'cpu_usage': ('django.db.models.fields.BigIntegerField', [], {'null': 'True', 'blank': 'True'}), 'ctime': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'date': ('django.db.models.fields.DateField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}), 'est_wall_time': ('django.db.models.fields.BigIntegerField', [], {'null': 'True', 'blank': 'True'}), 'etime': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'exit_status': ('django.db.models.fields.BigIntegerField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'jobid': ('django.db.models.fields.CharField', [], {'max_length': '50', 'unique': 'True', 'null': 'True', 'blank': 'True'}), 'jobname': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}), 'list_mem': ('django.db.models.fields.BigIntegerField', [], {'null': 'True', 'blank': 'True'}), 'list_pmem': ('django.db.models.fields.BigIntegerField', [], {'null': 'True', 'blank': 'True'}), 'list_pvmem': ('django.db.models.fields.BigIntegerField', [], {'null': 'True', 'blank': 'True'}), 'list_vmem': ('django.db.models.fields.BigIntegerField', [], {'null': 'True', 'blank': 'True'}), 'machine': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['machines.Machine']", 'null': 'True', 'blank': 'True'}), 'mem': ('django.db.models.fields.BigIntegerField', [], {'null': 'True', 'blank': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['projects.Project']", 'null': 'True', 'blank': 'True'}), 'qtime': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'queue': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['usage.Queue']", 'null': 'True', 'blank': 'True'}), 'software': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['software.SoftwareVersion']", 'null': 'True', 'blank': 'True'}), 'start': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['machines.UserAccount']", 'null': 'True', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'vmem': ('django.db.models.fields.BigIntegerField', [], {'null': 'True', 'blank': 'True'}) }, 'usage.queue': { 'Meta': {'object_name': 'Queue', 'db_table': "'queue'"}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50', 'primary_key': 'True'}) }, 'usage.usedmodules': { 'Meta': {'object_name': 'UsedModules'}, 'date_added': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'jobid': ('django.db.models.fields.CharField', [], {'max_length': '100', 'primary_key': 'True'}), 'modules': ('django.db.models.fields.TextField', [], {}) } } complete_apps = ['usage']
gpl-3.0
SKuipers/core
modules/Reports/src/Contexts/NullContext.php
1116
<?php /* Gibbon, Flexible & Open School System Copyright (C) 2010, Ross Parker 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/>. */ namespace Gibbon\Module\Reports\Contexts; use Gibbon\Contracts\Database\Connection; use Gibbon\Module\Reports\DataContext; class NullContext implements DataContext { public function getFormatter() { return function () { return ''; }; } public function getIdentifiers(Connection $db, string $gibbonSchoolYearID, string $gibbonReportID, string $gibbonYearGroupID) { return []; } }
gpl-3.0
BotBallARDroneAPI/CBCJVM
cbc/CBCJVM/examples/SensorEvents/bin/Main.java
1771
//package cbccore.tests; import cbccore.Device; import cbccore.events.Event; import cbccore.events.EventManager; import cbccore.events.EventListenerAdapter; import cbccore.events.IEventListener; public class Main { // Dummy events public static Event DRIVE_BEGAN_EVENT = EventManager.get().getUniqueEvent(); public static Event DESTINATION_REACHED_EVENT = EventManager.get().getUniqueEvent(); // Dummy emitter public class Driver { public void drive() { System.out.println("about to emit events"); DRIVE_BEGAN_EVENT.emit(); // ... DESTINATION_REACHED_EVENT.emit(); System.out.println("Done emitting events"); } } // Beeps protected class Beeper implements IEventListener { private String examplePassedVariable; public Beeper(String examplePassedVariable) { this.examplePassedVariable = examplePassedVariable; } @Override public void event(Event e) { System.out.println(examplePassedVariable); } } public Main() { EventManager manager = EventManager.get(); Driver driver = new Driver(); //two different ways of making event listeners manager.connect( DESTINATION_REACHED_EVENT.getType(), new Beeper("BEEP!") ); //this way is more reusable manager.connect( DESTINATION_REACHED_EVENT.getType(), new Beeper("Another BEEP!er object") ); // Inline class ftw! This way is easier for a unique event listener EventListenerAdapter adapter = new EventListenerAdapter() { @Override public void event(Event type) { System.out.println("DRIVE BEGAN!"); } }; manager.connect(DRIVE_BEGAN_EVENT.getType(), adapter); driver.drive(); } public static void main(String[] args) { cbccore.Device.init(); new Main(); } }
gpl-3.0
dataxu/ansible
lib/ansible/modules/cloud/vmware/vsphere_copy.py
6182
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C): 2015, Dag Wieers <dag@wieers.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: vsphere_copy short_description: Copy a file to a vCenter datastore description: - Upload files to a vCenter datastore version_added: 2.0 author: Dag Wieers (@dagwieers) <dag@wieers.com> options: host: description: - The vCenter server on which the datastore is available. required: true aliases: ['hostname'] login: description: - The login name to authenticate on the vCenter server. required: true aliases: ['username'] password: description: - The password to authenticate on the vCenter server. required: true src: description: - The file to push to vCenter required: true datacenter: description: - The datacenter on the vCenter server that holds the datastore. required: true datastore: description: - The datastore on the vCenter server to push files to. required: true path: description: - The file to push to the datastore on the vCenter server. required: true validate_certs: description: - If C(no), SSL certificates will not be validated. This should only be set to C(no) when no other option exists. default: 'yes' type: bool notes: - "This module ought to be run from a system that can access vCenter directly and has the file to transfer. It can be the normal remote target or you can change it either by using C(transport: local) or using C(delegate_to)." - Tested on vSphere 5.5 ''' EXAMPLES = ''' - vsphere_copy: host: vhost login: vuser password: vpass src: /some/local/file datacenter: DC1 Someplace datastore: datastore1 path: some/remote/file transport: local - vsphere_copy: host: vhost login: vuser password: vpass src: /other/local/file datacenter: DC2 Someplace datastore: datastore2 path: other/remote/file delegate_to: other_system ''' import atexit import errno import mmap import socket import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six.moves.urllib.parse import urlencode from ansible.module_utils._text import to_native from ansible.module_utils.urls import open_url def vmware_path(datastore, datacenter, path): ''' Constructs a URL path that VSphere accepts reliably ''' path = "/folder/%s" % path.lstrip("/") # Due to a software bug in vSphere, it fails to handle ampersand in datacenter names # The solution is to do what vSphere does (when browsing) and double-encode ampersands, maybe others ? datacenter = datacenter.replace('&', '%26') if not path.startswith("/"): path = "/" + path params = dict(dsName=datastore) if datacenter: params["dcPath"] = datacenter params = urlencode(params) return "%s?%s" % (path, params) def main(): module = AnsibleModule( argument_spec=dict( host=dict(required=True, aliases=['hostname']), login=dict(required=True, aliases=['username']), password=dict(required=True, no_log=True), src=dict(required=True, aliases=['name']), datacenter=dict(required=True), datastore=dict(required=True), dest=dict(required=True, aliases=['path']), validate_certs=dict(default=True, type='bool'), ), # Implementing check-mode using HEAD is impossible, since size/date is not 100% reliable supports_check_mode=False, ) host = module.params.get('host') login = module.params.get('login') password = module.params.get('password') src = module.params.get('src') datacenter = module.params.get('datacenter') datastore = module.params.get('datastore') dest = module.params.get('dest') validate_certs = module.params.get('validate_certs') fd = open(src, "rb") atexit.register(fd.close) data = mmap.mmap(fd.fileno(), 0, access=mmap.ACCESS_READ) atexit.register(data.close) remote_path = vmware_path(datastore, datacenter, dest) url = 'https://%s%s' % (host, remote_path) headers = { "Content-Type": "application/octet-stream", "Content-Length": str(len(data)), } try: r = open_url(url, data=data, headers=headers, method='PUT', url_username=login, url_password=password, validate_certs=validate_certs, force_basic_auth=True) except socket.error as e: if isinstance(e.args, tuple) and e[0] == errno.ECONNRESET: # VSphere resets connection if the file is in use and cannot be replaced module.fail_json(msg='Failed to upload, image probably in use', status=None, errno=e[0], reason=to_native(e), url=url) else: module.fail_json(msg=str(e), status=None, errno=e[0], reason=str(e), url=url, exception=traceback.format_exc()) except Exception as e: error_code = -1 try: if isinstance(e[0], int): error_code = e[0] except KeyError: pass module.fail_json(msg=to_native(e), status=None, errno=error_code, reason=to_native(e), url=url, exception=traceback.format_exc()) status = r.getcode() if 200 <= status < 300: module.exit_json(changed=True, status=status, reason=r.msg, url=url) else: length = r.headers.get('content-length', None) if r.headers.get('transfer-encoding', '').lower() == 'chunked': chunked = 1 else: chunked = 0 module.fail_json(msg='Failed to upload', errno=None, status=status, reason=r.msg, length=length, headers=dict(r.headers), chunked=chunked, url=url) if __name__ == '__main__': main()
gpl-3.0
kevoree-modeling/framework
microframework/src/main/java/org/kevoree/modeling/format/json/JsonType.java
200
package org.kevoree.modeling.format.json; /** * @ignore ts */ public enum JsonType { VALUE, LEFT_BRACE, RIGHT_BRACE, LEFT_BRACKET, RIGHT_BRACKET, COMMA, COLON, EOF }
gpl-3.0
obiba/onyx
onyx-core/src/main/java/org/obiba/onyx/core/identifier/impl/randomincrement/RandomIncrementIdentifierSequence.java
3246
/******************************************************************************* * Copyright 2008(c) The OBiBa Consortium. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.obiba.onyx.core.identifier.impl.randomincrement; import java.security.SecureRandom; import java.util.Date; import java.util.List; import org.obiba.core.service.PersistenceManager; import org.obiba.onyx.core.domain.identifier.IdentifierSequenceState; import org.obiba.onyx.core.identifier.IdentifierSequence; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.Assert; /** * An implementation of IdentifierSequence that uses a randomly generated value between 1..maxIncrement to increment the * state's lastIdentifier value. */ public class RandomIncrementIdentifierSequence implements IdentifierSequence { // // Instance Variables // @Autowired private PersistenceManager persistenceManager; private SecureRandom random; private int maxIncrement; // // Constructors // public RandomIncrementIdentifierSequence() { random = new SecureRandom(); byte bytes[] = new byte[20]; random.nextBytes(bytes); } // // IdentifierSequence Methods // public void startSequence(String prefix, long lastIdentifier) { Assert.isTrue(!sequenceStateExists(), "called startSequence with existing IdentifierSequenceState"); createSequenceState(prefix, lastIdentifier); } public synchronized String nextIdentifier() { int increment = random.nextInt(maxIncrement) + 1; IdentifierSequenceState state = loadSequenceState(); state.setLastIdentifier(state.getLastIdentifier() + increment); persistenceManager.save(state); return state.getPrefix() + state.getLastIdentifier(); } // // Methods // public void setPersistenceManager(PersistenceManager persistenceManager) { this.persistenceManager = persistenceManager; } public int getMaxIncrement() { return maxIncrement; } public void setMaxIncrement(int maxIncrement) { this.maxIncrement = maxIncrement; } private boolean sequenceStateExists() { return persistenceManager.count(IdentifierSequenceState.class) != 0; } private void createSequenceState(String prefix, long lastIdentifier) { IdentifierSequenceState state = new IdentifierSequenceState(); state.setPrefix(prefix); state.setLastIdentifier(lastIdentifier); state.setLastUpdate(new Date()); persistenceManager.save(state); } private IdentifierSequenceState loadSequenceState() { List<IdentifierSequenceState> result = persistenceManager.list(IdentifierSequenceState.class); Assert.notEmpty(result, "IdentifierSequenceState does not exist (was the startSequence method called?)"); Assert.isTrue(result.size() == 1, "Unexpected number of IdentifierSequenceState entities: " + result.size() + " (expected 1)"); return result.get(0); } }
gpl-3.0
tk8226/YamiPortAIO-v2
Core/Champion Ports/Rumble/ElRumble/Program.cs
368
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LeagueSharp; using LeagueSharp.Common; using SharpDX; using EloBuddy; using LeagueSharp.Common; namespace ElRumble { internal class Program { public static void Main() { Rumble.OnLoad(); } } }
gpl-3.0
Jacob-Kroeze/mdl4biz
admin/tool/generator/version.php
997
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Version details. * * @package tool_generator * @copyright 2013 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $plugin->version = 2013090200; $plugin->requires = 2013090200; $plugin->component = 'tool_generator';
gpl-3.0
andnovar/SmartSensorMobility
Common/src/edu/sharif/ce/dml/common/util/io/output/StreamTextWriter.java
4073
/* * Copyright (c) 2005-2008 by Masoud Moshref Javadi <moshref@ce.sharif.edu>, http://ce.sharif.edu/~moshref * The license.txt file describes the conditions under which this software may be distributed. * * 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/> */ package edu.sharif.ce.dml.common.util.io.output; import java.io.File; // Referenced classes of package edu.sharif.ce.dml.common.util.io.output: // BufferWriter, WritingHandler, OutputLogger public class StreamTextWriter implements WritingHandler { private BufferWriter bufferWriter; private String outputFileName; public StreamTextWriter() { } public void write(String s) { bufferWriter.getBuffer()[bufferWriter.full.getIndex()] = s; try { synchronized (bufferWriter.empty) { if ((bufferWriter.full.getIndex() + 1) % bufferWriter.getBufferSize() == bufferWriter.empty.getIndex()) { bufferWriter.empty.wait(); } } synchronized (bufferWriter.mutex) { bufferWriter.full.setIndex((bufferWriter.full.getIndex() + 1) % bufferWriter.getBufferSize()); } synchronized (bufferWriter.full) { if (bufferWriter.full.getIndex() - bufferWriter.empty.getIndex() > bufferWriter.getBufferSize() / 3 || bufferWriter.empty.getIndex() - bufferWriter.full.getIndex() < (2 * bufferWriter.getBufferSize()) / 3 && bufferWriter.empty.getIndex() > bufferWriter.full.getIndex()) { bufferWriter.full.notify(); } } } catch (InterruptedException e) { e.printStackTrace(); } } public void flush() { synchronized (bufferWriter.full) { if (bufferWriter.full.getIndex() != bufferWriter.empty.getIndex()) { bufferWriter.full.notify(); bufferWriter.flush = true; } } } public void flushAndClose() { if (bufferWriter != null) { bufferWriter.stop = true; synchronized (bufferWriter.full) { bufferWriter.full.notify(); } synchronized (bufferWriter.end) { if (bufferWriter.end.getIndex() == 0) { bufferWriter.end.setIndex(1); try { bufferWriter.end.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } else { System.err.println("No file Selected to write"); } } public void setOutputString(String outputFileName) { if (outputFileName == null) { this.outputFileName = OutputLogger.generateOutputFileName(this.outputFileName); } else { this.outputFileName = outputFileName; } File f = new File(this.outputFileName); if (f.exists()) { f.delete(); } //create necessary directories { File dir = new File(f.getPath().substring(0,f.getPath().indexOf(f.getName()))); dir.mkdirs(); } if (bufferWriter != null) { flushAndClose(); } bufferWriter = new BufferWriter(f); bufferWriter.start(); } public String getOutputString() { return outputFileName; } }
gpl-3.0
NightscoutFoundation/xDrip
app/src/main/java/com/eveningoutpost/dexdrip/insulin/inpen/InPenScanMeister.java
2677
package com.eveningoutpost.dexdrip.insulin.inpen; import android.os.ParcelUuid; import com.eveningoutpost.dexdrip.Models.JoH; import com.eveningoutpost.dexdrip.Models.UserError; import com.eveningoutpost.dexdrip.UtilityModels.Constants; import com.eveningoutpost.dexdrip.UtilityModels.Inevitable; import com.eveningoutpost.dexdrip.UtilityModels.PersistentStore; import com.eveningoutpost.dexdrip.utils.bt.ScanMeister; import com.eveningoutpost.dexdrip.utils.bt.Subscription; import com.polidea.rxandroidble2.scan.ScanFilter; import com.polidea.rxandroidble2.scan.ScanResult; import com.polidea.rxandroidble2.scan.ScanSettings; import java.util.concurrent.TimeUnit; import io.reactivex.schedulers.Schedulers; import static com.eveningoutpost.dexdrip.insulin.inpen.Constants.SCAN_SERVICE_UUID; import static com.eveningoutpost.dexdrip.insulin.inpen.InPen.STORE_INPEN_ADVERT; // jamorham public class InPenScanMeister extends ScanMeister { private static final String TAG = "InPenScanMeister"; private static final boolean D = false; @Override public synchronized void scan() { extendWakeLock((scanSeconds + 1) * Constants.SECOND_IN_MS); stopScan("Scan start"); UserError.Log.d(TAG, "startScan called: hunting: " + address + " " + name); scanSubscription = new Subscription(rxBleClient.scanBleDevices( new ScanSettings.Builder() .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) .build(), new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(SCAN_SERVICE_UUID)).build()) .timeout(scanSeconds, TimeUnit.SECONDS) // is unreliable .subscribeOn(Schedulers.io()) .subscribe(this::onScanResult, this::onScanFailure)); Inevitable.task(STOP_SCAN_TASK_ID, scanSeconds * Constants.SECOND_IN_MS, this::stopScanWithTimeoutCallback); } @Override protected synchronized void onScanResult(ScanResult bleScanResult) { final String this_address = bleScanResult.getBleDevice().getMacAddress(); final byte[] scanRecordBytes = bleScanResult.getScanRecord().getBytes(); if (D) UserError.Log.d(TAG, JoH.bytesToHex(bleScanResult.getScanRecord().getBytes())); if (scanRecordBytes != null && scanRecordBytes.length > 0) { PersistentStore.setBytes(STORE_INPEN_ADVERT + this_address, scanRecordBytes); } stopScan("Got match"); JoH.threadSleep(500); processCallBacks(this_address, "SCAN_FOUND"); releaseWakeLock(); } }
gpl-3.0
mhalagan-nmdp/ngs
hml/src/test/java/org/nmdp/ngs/hml/HmlUtilsTest.java
5130
/* ngs-hml Mapping for HML XSDs. Copyright (c) 2014-2015 National Marrow Donor Program (NMDP) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; with out even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. > http://www.gnu.org/licenses/lgpl.html */ package org.nmdp.ngs.hml; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.nmdp.ngs.hml.HmlUtils.createSequence; import static org.nmdp.ngs.hml.HmlUtils.createSequences; import static org.nmdp.ngs.hml.HmlUtils.getHmlid; import static org.nmdp.ngs.hml.HmlUtils.toDnaSymbolList; import java.net.URL; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.StringReader; import org.biojava.bio.seq.DNATools; import org.biojava.bio.seq.ProteinTools; import org.biojava.bio.seq.RNATools; import org.biojava.bio.symbol.IllegalSymbolException; import org.junit.Test; import org.nmdp.ngs.hml.jaxb.Hml; import org.nmdp.ngs.hml.jaxb.Hmlid; import org.nmdp.ngs.hml.jaxb.Sequence; /** * Unit test for HmlUtils. */ public final class HmlUtilsTest { @Test(expected=NullPointerException.class) public void testCreateSequenceNullBiojavaSequence() throws Exception { createSequence((org.biojava.bio.seq.Sequence) null); } @Test(expected=IllegalArgumentException.class) public void testCreateSequenceInvalidBiojavaAlphabet() throws Exception { createSequence(ProteinTools.createProteinSequence("adef", "foo")); } @Test public void testCreateSequenceBiojavaDna() throws Exception { Sequence dna = createSequence(DNATools.createDNASequence("actg", "foo")); assertEquals("actg", dna.getValue()); } @Test(expected=IllegalArgumentException.class) public void testCreateSequenceBiojavaRna() throws Exception { createSequence(RNATools.createRNASequence("acug", "foo")); } @Test(expected=NullPointerException.class) public void testCreateSequencesNullReader() throws Exception { createSequences((BufferedReader) null); } @Test public void testCreateSequences() throws Exception { StringBuilder sb = new StringBuilder(); sb.append(">foo\n"); sb.append("actg\n"); sb.append(">bar\n"); sb.append("gtca\n"); int count = 0; for (Sequence sequence : createSequences(new BufferedReader(new StringReader(sb.toString())))) { assertTrue("actg".equals(sequence.getValue()) || "gtca".equals(sequence.getValue())); count++; } assertEquals(2, count); } @Test(expected=NullPointerException.class) public void testCreateSequencesNullFile() throws Exception { createSequences((File) null); } @Test(expected=NullPointerException.class) public void testCreateSequencesNullURL() throws Exception { createSequences((URL) null); } @Test(expected=NullPointerException.class) public void testCreateSequencesNullInputStream() throws Exception { createSequences((InputStream) null); } @Test public void testGetHmlid() throws Exception { Hmlid hmlid = getHmlid(read("hmlid.xml")); assertEquals("1234", hmlid.getRoot()); assertEquals("abcd", hmlid.getExtension()); } @Test public void testGetHmlidMissing() throws Exception { assertNull(getHmlid(read("missing-hmlid.xml"))); } @Test(expected=NullPointerException.class) public void testToDnaSymbolListNullSequence() throws Exception { toDnaSymbolList(null); } @Test(expected=IllegalSymbolException.class) public void testToDnaSymbolListIllegalSymbol() throws Exception { Sequence sequence = new Sequence(); sequence.setValue("1234"); toDnaSymbolList(sequence); } @Test public void testToDnaSymbolList() throws Exception { Sequence sequence = new Sequence(); sequence.setValue("actg"); assertEquals("actg", toDnaSymbolList(sequence).seqString()); } @Test public void testToDnaSymbolListWhitespace() throws Exception { Sequence sequence = new Sequence(); sequence.setValue("\t\n a c\t\nt g\t\n"); assertEquals("actg", toDnaSymbolList(sequence).seqString()); } private static Hml read(final String name) throws Exception { return HmlReader.read(HmlUtilsTest.class.getResourceAsStream(name)); } }
gpl-3.0
labscoop/xortify
releases/Standalone/PHP/4.11/providers/xortify/post.loader.php
8877
<?php /* * Prevents Spam, Harvesting, Human Rights Abuse, Captcha Abuse etc. * basic statistic of them in XOOPS Copyright (C) 2012 Simon Roberts * Contact: wishcraft - simon@chronolabs.com.au * * 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/>. * See /docs/license.pdf for full license. * * Shouts:- Mamba (www.xoops.org), flipse (www.nlxoops.nl) * Many thanks for your additional work with version 1.01 * * Version: 3.10 Final (Stable) * Published: Chronolabs * Download: http://code.google.com/p/chronolabs * This File: post.loader.php * Description: Xortify Post Loader provider for client * Date: 09/09/2012 19:34 AEST * License: GNU3 * */ $checkfields = array('uname', 'email', 'ip4', 'ip6', 'network-addy'); require_once( _RUN_XORTIFY_ROOT_PATH . '/class/'._RUN_XORTIFY_PROTOCOL.'.php' ); $func = strtoupper(_RUN_XORTIFY_PROTOCOL).'XortifyExchange'; $apiExchange = new $func; $bans = $apiExchange->getBans(); if (isset($_SESSION['xortify']['uname']) && isset($_SESSION['xortify']['uid']) && isset($_SESSION['xortify']['email'])) { $uid = $_SESSION['xortify']['uid']; $uname = $_SESSION['xortify']['uname']; $email = $_SESSION['xortify']['email']; } else { $uid = 0; $uname = (isset($_REQUEST['uname'])?$_REQUEST['uname']:''); $email = (isset($_REQUEST['email'])?$_REQUEST['email']:''); } include_once _RUN_XORTIFY_ROOT_PATH.'/class/cache/cache.php'; if (!$ipdata = Cache::read('xortify_php_'.sha1(xortify_getIP(true).$uid.$uname.$email))) { $ipdata = xortify_getIPData(); Cache::write('xortify_php_'.sha1(xortify_getIP(true).$uid.$uname.$email), $ipdata, _RUN_XORTIFY_IPCACHE); } if (isset($ipdata['ip4'])) if ($ipdata['ip4']==_RUN_XORTIFY_MYIPv4_ADDRESS) return false; if (isset($ipdata['ip6'])) if ($ipdata['ip6']==_RUN_XORTIFY_MYIPv6_ADDRESS) return false; if (is_array($bans['data'])&&count($bans['data'])>0) { foreach ($bans['data'] as $id => $ban) { foreach($ipdata as $key => $ip) { if (isset($ban[$key])&&!empty($ban[$key])&&!empty($ip)) { if (in_array($key, $checkfields)) { if ($ban[$key] == $ip) { Cache::write('xortify_core_include_common_end', array('time'=>microtime(true)), _RUN_XORTIFY_FAULTDELAY); setcookie('xortify', array('lid' => $lid), time()+3600*24*7*4*3); header('Location: '._RUN_XORTIFY_URL.'/banned.php'); exit(0); } } } } } unlinkOldCachefiles('xortify_',_RUN_XORTIFY_IPCACHE); $_SESSION['xortify']['_pass'] = true; } if (!$checked = Cache::read('xortify_xrt_'.sha1($ipdata['uname'].$ipdata['email'].(isset($ipdata['ip4'])?$ipdata['ip4']:"").(isset($ipdata['ip6'])?$ipdata['ip6']:"").(isset($ipdata['proxy-ip4'])?$ipdata['proxy-ip4']:"").(isset($ipdata['proxy-ip4'])?$ipdata['proxy-ip6']:"").$ipdata['network-addy']))) { $checked = $apiExchange->checkBanned($ipdata); Cache::write('xortify_xrt_'.sha1($ipdata['uname'].$ipdata['email'].(isset($ipdata['ip4'])?$ipdata['ip4']:"").(isset($ipdata['ip6'])?$ipdata['ip6']:"").(isset($ipdata['proxy-ip4'])?$ipdata['proxy-ip4']:"").(isset($ipdata['proxy-ip4'])?$ipdata['proxy-ip6']:"").$ipdata['network-addy']), array_merge($checked, array('ipdata' => $ipdata)), _RUN_XORTIFY_IPCACHE); } if (isset($checked['count'])) { if ($checked['count']>0) { foreach ($checked['bans'] as $id => $ban) foreach($ipdata as $key => $ip) if (in_array($key, $checkfields)) if (isset($ban[$key])&&!empty($ban[$key])&&!empty($ip)) if ($ban[$key] == $ip) { include_once XOOPS_ROOT_PATH."/include/common.php"; Cache::write('xortify_core_include_common_end', array('time'=>microtime(true)), $_SESSION['xortify'][XORTIFY_INSTANCE_KEY][_MI_XOR_VERSION]['moduleConfig']['fault_delay']); setcookie('xortify', array('banned' => true), time()+3600*24*7*4*3); header('Location: '._RUN_XORTIFY_URL.'/banned.php'); exit(0); } } unlinkOldCachefiles('xortify_',_RUN_XORTIFY_IPCACHE); $_SESSION['xortify']['_pass'] = true; } if (isset($_REQUEST['xortify_check'])) { foreach ($_REQUEST['xortify_check'] as $id => $field) { $field = str_replace('[]', '', $field); if (is_array($_REQUEST[$field])) { foreach ($_REQUEST[$field] as $id => $data) { $result = $apiExchange->checkForSpam($data); if ($result['spam']==true) { setcookie('xortify', array_merge($_COOKIE['xortify'],array('spams' => 1)), time()+3600*24*7*4*3); if (_RUN_XORTIFY_SPAMS_ALLOWED<=$_COOKIE['xortify']['spams']) { $results[] = $apiExchange->sendBan(array('comment'=>_XOR_SPAM . ' :: [' . $data . '] len('.strlen($data).')'), 2, xortify_getIPData()); $_SESSION['xortify']['xoops_pagetitle'] = (_RUN_XORITIFY_SPAM_PAGETITLE); $_SESSION['xortify']['description'] = (_RUN_XORITIFY_SPAM_DESCRIPTION); $_SESSION['xortify']['version'] = (_RUN_XORTIFY_VERSION); $_SESSION['xortify']['provider'] = (basename(dirname(__FILE__))); $_SESSION['xortify']['spam'] = (htmlspecialchars($_REQUEST[$field])); $_SESSION['xortify']['agent'] = ($_SERVER['HTTP_USER_AGENT']); $_SESSION['xortify']['left'] = _RUN_XORTIFY_SPAMS_ALLOWED - $_COOKIE['xortify']['spams']; Cache::write('xortify_core_include_common_end', array('time'=>microtime(true)), $_SESSION['xortify'][XORTIFY_INSTANCE_KEY][_MI_XOR_VERSION]['moduleConfig']['fault_delay']); setcookie('xortify', array('banned' => true), time()+3600*24*7*4*3); header('Location: '._RUN_XORTIFY_URL.'/banned.php'); exit(0); } else { $_SESSION['xortify']['xoops_pagetitle'] = (_RUN_XORITIFY_SPAM_PAGETITLE); $_SESSION['xortify']['description'] = (_RUN_XORITIFY_SPAM_DESCRIPTION); $_SESSION['xortify']['version'] = (_RUN_XORTIFY_VERSION); $_SESSION['xortify']['provider'] = (basename(dirname(__FILE__))); $_SESSION['xortify']['spam'] = (htmlspecialchars($_REQUEST[$field])); $_SESSION['xortify']['agent'] = ($_SERVER['HTTP_USER_AGENT']); $_SESSION['xortify']['left'] = _RUN_XORTIFY_SPAMS_ALLOWED - $_COOKIE['xortify']['spams']; include_once XOOPS_ROOT_PATH.'/spam.php'; } exit(0); } } } else { $result = $apiExchange->checkForSpam($_REQUEST[$field], 1, _RUN_XORTIFY_SPAMS_ALLOWADULT); if ($result['spam']==true) { setcookie('xortify', array('spams' => $_COOKIE['xortify']['spams']+1), time()+3600*24*7*4*3); if (_RUN_XORTIFY_SPAMS_ALLOWED<=$_COOKIE['xortify']['spams']) { $results[] = $apiExchange->sendBan(array('comment'=>__RUN_XORITFY_SPAM . ' :: [' . $_REQUEST[$field] . '] len('.strlen($_REQUEST[$field]).')'), 2, xortify_getIPData(true)); $_SESSION['xortify']['xoops_pagetitle'] = (_RUN_XORITIFY_SPAM_PAGETITLE); $_SESSION['xortify']['description'] = (_RUN_XORITIFY_SPAM_DESCRIPTION); $_SESSION['xortify']['version'] = (_RUN_XORTIFY_VERSION); $_SESSION['xortify']['provider'] = (basename(dirname(__FILE__))); $_SESSION['xortify']['spam'] = (htmlspecialchars($_REQUEST[$field])); $_SESSION['xortify']['agent'] = ($_SERVER['HTTP_USER_AGENT']); $_SESSION['xortify']['left'] = _RUN_XORTIFY_SPAMS_ALLOWED - $_COOKIE['xortify']['spams']; Cache::write('xortify_core_include_common_end', array('time'=>microtime(true)), $_SESSION['xortify'][XORTIFY_INSTANCE_KEY][_MI_XOR_VERSION]['moduleConfig']['fault_delay']); setcookie('xortify', array('banned' => true), time()+3600*24*7*4*3); header('Location: '._RUN_XORTIFY_URL.'/banned.php'); exit(0); } else { $_SESSION['xortify']['xoops_pagetitle'] = (_RUN_XORITIFY_SPAM_PAGETITLE); $_SESSION['xortify']['description'] = (_RUN_XORITIFY_SPAM_DESCRIPTION); $_SESSION['xortify']['version'] = (_RUN_XORTIFY_VERSION); $_SESSION['xortify']['provider'] = (basename(dirname(__FILE__))); $_SESSION['xortify']['spam'] = (htmlspecialchars($_REQUEST[$field])); $_SESSION['xortify']['agent'] = ($_SERVER['HTTP_USER_AGENT']); $_SESSION['xortify']['left'] = _RUN_XORTIFY_SPAMS_ALLOWED - $_COOKIE['xortify']['spams']; header('Location: '._RUN_XORTIFY_URL.'/spam.php'); } exit(0); } } } } ?>
gpl-3.0
reaperrr/OpenRA
OpenRA.Mods.Common/FileFormats/Blast.cs
8201
#region Copyright & License Information /* * Copyright 2007-2019 The OpenRA Developers (see AUTHORS) * This file is part of OpenRA, which is free software. It is made * available to you 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. For more * information, see COPYING. */ #endregion #region Additional Copyright & License Information /* * This file is based on the blast routines (version 1.1 by Mark Adler) * included in zlib/contrib */ #endregion using System; using System.IO; namespace OpenRA.Mods.Common.FileFormats { public static class Blast { public static readonly int MAXBITS = 13; // maximum code length public static readonly int MAXWIN = 4096; // maximum window size static byte[] litlen = { 11, 124, 8, 7, 28, 7, 188, 13, 76, 4, 10, 8, 12, 10, 12, 10, 8, 23, 8, 9, 7, 6, 7, 8, 7, 6, 55, 8, 23, 24, 12, 11, 7, 9, 11, 12, 6, 7, 22, 5, 7, 24, 6, 11, 9, 6, 7, 22, 7, 11, 38, 7, 9, 8, 25, 11, 8, 11, 9, 12, 8, 12, 5, 38, 5, 38, 5, 11, 7, 5, 6, 21, 6, 10, 53, 8, 7, 24, 10, 27, 44, 253, 253, 253, 252, 252, 252, 13, 12, 45, 12, 45, 12, 61, 12, 45, 44, 173 }; // bit lengths of length codes 0..15 static byte[] lenlen = { 2, 35, 36, 53, 38, 23 }; // bit lengths of distance codes 0..63 static byte[] distlen = { 2, 20, 53, 230, 247, 151, 248 }; // base for length codes static short[] lengthbase = { 3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24, 40, 72, 136, 264 }; // extra bits for length codes static byte[] extra = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8 }; static Huffman litcode = new Huffman(litlen, litlen.Length, 256); static Huffman lencode = new Huffman(lenlen, lenlen.Length, 16); static Huffman distcode = new Huffman(distlen, distlen.Length, 64); /// <summary>PKWare Compression Library stream.</summary> /// <param name="input">Compressed input stream.</param> /// <param name="output">Stream to write the decompressed output.</param> /// <param name="onProgress">Progress callback, invoked with (read bytes, written bytes).</param> public static void Decompress(Stream input, Stream output, Action<long, long> onProgress = null) { var br = new BitReader(input); // Are literals coded? var coded = br.ReadBits(8); if (coded < 0 || coded > 1) throw new NotImplementedException("Invalid data stream"); var encodedLiterals = coded == 1; // log2(dictionary size) - 6 var dict = br.ReadBits(8); if (dict < 4 || dict > 6) throw new InvalidDataException("Invalid dictionary size"); // output state ushort next = 0; // index of next write location in out[] var first = true; // true to check distances (for first 4K) var outBuffer = new byte[MAXWIN]; // output buffer and sliding window var inputStart = input.Position; var outputStart = output.Position; // decode literals and length/distance pairs do { // length/distance pair if (br.ReadBits(1) == 1) { // Length var symbol = Decode(lencode, br); var len = lengthbase[symbol] + br.ReadBits(extra[symbol]); // Magic number for "done" if (len == 519) { for (var i = 0; i < next; i++) output.WriteByte(outBuffer[i]); if (onProgress != null) onProgress(input.Position - inputStart, output.Position - outputStart); break; } // Distance symbol = len == 2 ? 2 : dict; var dist = Decode(distcode, br) << symbol; dist += br.ReadBits(symbol); dist++; if (first && dist > next) throw new InvalidDataException("Attempt to jump before data"); // copy length bytes from distance bytes back do { var dest = next; var source = dest - dist; var copy = MAXWIN; if (next < dist) { source += copy; copy = dist; } copy -= next; if (copy > len) copy = len; len -= copy; next += (ushort)copy; // copy with old-fashioned memcpy semantics // in case of overlapping ranges. this is NOT // the same as Array.Copy() while (copy-- > 0) outBuffer[dest++] = outBuffer[source++]; // Flush window to outstream if (next == MAXWIN) { for (var i = 0; i < next; i++) output.WriteByte(outBuffer[i]); next = 0; first = false; if (onProgress != null) onProgress(input.Position - inputStart, output.Position - outputStart); } } while (len != 0); } else { // literal value var symbol = encodedLiterals ? Decode(litcode, br) : br.ReadBits(8); outBuffer[next++] = (byte)symbol; if (next == MAXWIN) { for (var i = 0; i < next; i++) output.WriteByte(outBuffer[i]); next = 0; first = false; if (onProgress != null) onProgress(input.Position - inputStart, output.Position - outputStart); } } } while (true); } // Decode a code using Huffman table h. static int Decode(Huffman h, BitReader br) { var code = 0; // len bits being decoded var first = 0; // first code of length len var index = 0; // index of first code of length len in symbol table short next = 1; while (true) { code |= br.ReadBits(1) ^ 1; // invert code int count = h.Count[next++]; if (code < first + count) return h.Symbol[index + (code - first)]; index += count; first += count; first <<= 1; code <<= 1; } } } class BitReader { readonly Stream stream; byte bitBuffer = 0; int bitCount = 0; public BitReader(Stream stream) { this.stream = stream; } public int ReadBits(int count) { var ret = 0; var filled = 0; while (filled < count) { if (bitCount == 0) { bitBuffer = stream.ReadUInt8(); bitCount = 8; } ret |= (bitBuffer & 1) << filled; bitBuffer >>= 1; bitCount--; filled++; } return ret; } } /* * Given a list of repeated code lengths rep[0..n-1], where each byte is a * count (high four bits + 1) and a code length (low four bits), generate the * list of code lengths. This compaction reduces the size of the object code. * Then given the list of code lengths length[0..n-1] representing a canonical * Huffman code for n symbols, construct the tables required to decode those * codes. Those tables are the number of codes of each length, and the symbols * sorted by length, retaining their original order within each length. */ class Huffman { public short[] Count; // number of symbols of each length public short[] Symbol; // canonically ordered symbols public Huffman(byte[] rep, int n, short symbolCount) { var length = new short[256]; // code lengths var s = 0; // current symbol // convert compact repeat counts into symbol bit length list foreach (var code in rep) { var num = (code >> 4) + 1; // Number of codes (top four bits plus 1) var len = (byte)(code & 15); // Code length (low four bits) do length[s++] = len; while (--num > 0); } n = s; // count number of codes of each length Count = new short[Blast.MAXBITS + 1]; for (var i = 0; i < n; i++) Count[length[i]]++; // no codes! if (Count[0] == n) return; // check for an over-subscribed or incomplete set of lengths var left = 1; // one possible code of zero length for (var len = 1; len <= Blast.MAXBITS; len++) { left <<= 1; // one more bit, double codes left left -= Count[len]; // deduct count from possible codes if (left < 0) throw new InvalidDataException("over subscribed code set"); } // generate offsets into symbol table for each length for sorting var offs = new short[Blast.MAXBITS + 1]; for (var len = 1; len < Blast.MAXBITS; len++) offs[len + 1] = (short)(offs[len] + Count[len]); // put symbols in table sorted by length, by symbol order within each length Symbol = new short[symbolCount]; for (short i = 0; i < n; i++) if (length[i] != 0) Symbol[offs[length[i]]++] = i; } } }
gpl-3.0
dmlond/duke-data-service
app/api/dds/v1/trashbin_api.rb
9183
module DDS module V1 class TrashbinAPI < Grape::API helpers PaginationParams desc 'List Projects with Items in Trashbin' do detail 'List Projects with Items in Trashbin.' named 'list trashbin children' failure [ {code: 200, message: 'Success'}, {code: 401, message: 'Unauthorized'} ] end params do use :pagination end get '/trashbin/projects', adapter: :json, root: 'results' do authenticate! paginate(policy_scope(Project).joins(:containers).where(containers: {parent_id: nil, is_deleted:true, is_purged: false}).distinct) end desc 'View Trashbin Item details' do detail 'Show Details of a Trashbin Item.' named 'show trashbin item' failure [ {code: 200, message: 'Success'}, {code: 401, message: 'Unauthorized'}, {code: 403, message: 'Forbidden'}, {code: 404, message: 'Item Does not Exist'}, {code: 404, message: 'Object kind not supported'} ] end params do requires :object_kind, type: String, desc: 'Object Kind' requires :object_id, type: String, desc: 'Object UUID' end get '/trashbin/:object_kind/:object_id', root: false do authenticate! object_kind = KindnessFactory.by_kind(params[:object_kind]) trashed_object = object_kind.find_by!(id: params[:object_id], is_deleted: true, is_purged: false) authorize trashed_object, :show? trashed_object end desc 'Restore a Trashbin Item' do detail 'Restores the item, and any children, to an undeleted status to the specified parent folder or project.' named 'restore trashbin item' failure [ {code: 200, message: 'Success'}, {code: 404, message: 'Parent object does not exist or is itself in the trashbin'}, {code: 401, message: 'Unauthorized'}, {code: 403, message: 'Forbidden'}, {code: 404, message: 'Object or Parent kind not supported'}, {code: 404, message: 'Object not found in trash bin'}, {code: 404, message: 'Parent object does not exist or is itself in the trashbin'} ] end params do requires :object_kind, type: String, desc: 'Object Kind' requires :object_id, type: String, desc: 'Object UUID' optional :parent, desc: "Parent. Required unless restoring a FileVersion", type: Hash do optional :kind, type: String, desc: 'Parent Kind' optional :id, type: String, desc: 'Parent UUID' end end rescue_from TrashbinParentException do |e| message, suggestion = e.message.split('::') error_json = { "error" => "404", "code" => "not_provided", "reason" => message, "suggestion" => suggestion } error!(error_json, 404) end rescue_from IncompatibleParentException do |e| message, suggestion = e.message.split('::') error_json = { "error" => "404", "code" => "not_provided", "reason" => message, "suggestion" => suggestion } error!(error_json, 404) end rescue_from UnRestorableException do |e| error_json = { "error" => "404", "code" => "not_provided", "reason" => "#{e.message} Not Restorable", "suggestion" => "#{e.message} is not Restorable" } error!(error_json, 404) end put '/trashbin/:object_kind/:object_id/restore', root: false do authenticate! parent_params = declared(params, {include_missing: false}, [:parent]) object_kind = KindnessFactory.by_kind(params[:object_kind]) purge_object = object_kind.find_by!(id: params[:object_id], is_deleted: true) authorize purge_object, :destroy? raise UnRestorableException.new(purge_object.kind) unless purge_object.class.include? Restorable if purge_object.is_purged? purge_object else target_parent = purge_object.deleted_from_parent || purge_object.project if params[:parent] parent_kind = KindnessFactory.by_kind(parent_params[:parent][:kind]) target_parent = parent_kind.find(parent_params[:parent][:id]) end target_parent.restore purge_object authorize purge_object, :restore? if purge_object.save purge_object else validation_error!(purge_object) end end end desc 'Purge Trashbin Item' do detail 'Purges the item and any children, and permenantly removes any stored files from the storage_provider. If a FileVersion is restored, the parent is optional, otherwise it is required.' named 'purge trashbin item' failure [ {code: 204, message: 'Successfully Purged'}, {code: 401, message: 'Unauthorized'}, {code: 403, message: 'Forbidden'}, {code: 404, message: 'Item Does not Exist'}, {code: 404, message: 'Object kind not supported'} ] end params do requires :object_kind, type: String, desc: 'Object Kind' requires :object_id, type: String, desc: 'Object UUID' end rescue_from UnPurgableException do |e| error_json = { "error" => "404", "code" => "not_provided", "reason" => "#{e.message} Not Purgable", "suggestion" => "#{e.message} is not Purgable" } error!(error_json, 404) end put '/trashbin/:object_kind/:object_id/purge', root: false do authenticate! object_kind = KindnessFactory.by_kind(params[:object_kind]) purge_object = object_kind.find_by!(id: params[:object_id], is_deleted: true) raise UnPurgableException.new(purge_object.kind) unless purge_object.class.include? Purgable unless purge_object.is_purged? purge_object.purge authorize purge_object, :destroy? purge_object.save end body false end desc 'List folder children in trashbin' do detail 'Returns the trashed children of the folder.' named 'list folder children in the trashbin' failure [ {code: 200, message: "Valid API Token in 'Authorization' Header"}, {code: 401, message: "Missing, Expired, or Invalid API Token in 'Authorization' Header"}, {code: 404, message: 'Folder does not exist or is purged'} ] end params do optional :name_contains, type: String, desc: 'list children whose name contains this string' optional :recurse, type: Boolean, desc: 'If true, searches recursively into subfolders' use :pagination end get '/trashbin/folders/:id/children', adapter: :json, root: 'results' do authenticate! folder = Folder.find_by!(id: params[:id], is_purged: false) authorize folder, :index? name_contains = params[:name_contains] descendants = params[:recurse] ? policy_scope(folder.descendants) : policy_scope(folder.children) descendants = descendants.unscope(:order).where(is_deleted: true, is_purged: false) if name_contains if name_contains.empty? descendants = descendants.none else descendants = descendants.where(Container.arel_table[:name].matches("%#{name_contains}%")) end end paginate(descendants.includes(:parent, :project, :audits).order('updated_at ASC')) end desc 'List project children in the trashbin' do detail 'Returns the trashed children of the project.' named 'list project children in the trashbin' failure [ {code: 200, message: "Valid API Token in 'Authorization' Header"}, {code: 401, message: "Missing, Expired, or Invalid API Token in 'Authorization' Header"}, {code: 404, message: 'Project does not exist or has been deleted'} ] end params do optional :name_contains, type: String, desc: 'list children whose name contains this string' optional :recurse, type: Boolean, desc: 'If true, searches recursively into subfolders' use :pagination end get '/trashbin/projects/:id/children', adapter: :json, root: 'results' do authenticate! project = hide_logically_deleted Project.find(params[:id]) authorize DataFile.new(project: project), :index? name_contains = params[:name_contains] descendants = params[:recurse] ? project.containers : project.children descendants = descendants.unscope(:order).where(is_deleted: true, is_purged: false) if name_contains if name_contains.empty? descendants = descendants.none else descendants = descendants.where(Container.arel_table[:name].matches("%#{name_contains}%")) end end paginate(policy_scope(descendants.includes(:parent, :project, :audits).order('updated_at ASC'))) end end end end
gpl-3.0
nupic-community/nostradamIQ
nostradamIQ-landingpage/webapp/lib/cesium/1.16/Specs/DataSources/DataSourceCollectionSpec.js
5373
/*global defineSuite*/ defineSuite([ 'DataSources/DataSourceCollection', 'Specs/MockDataSource', 'ThirdParty/when' ], function( DataSourceCollection, MockDataSource, when) { "use strict"; it('contains, get, getLength, and indexOf work', function() { var collection = new DataSourceCollection(); var source = new MockDataSource(); expect(collection.length).toEqual(0); expect(collection.contains(source)).toEqual(false); collection.add(new MockDataSource()); collection.add(source); collection.add(new MockDataSource()); expect(collection.length).toEqual(3); expect(collection.get(1)).toBe(source); expect(collection.indexOf(source)).toEqual(1); expect(collection.contains(source)).toEqual(true); collection.remove(collection.get(0)); expect(collection.indexOf(source)).toEqual(0); expect(collection.remove(source)).toEqual(true); expect(collection.contains(source)).toEqual(false); }); it('add and remove events work', function() { var source = new MockDataSource(); var collection = new DataSourceCollection(); var addSpy = jasmine.createSpy('dataSourceAdded'); collection.dataSourceAdded.addEventListener(addSpy); var removeSpy = jasmine.createSpy('dataSourceRemoved'); collection.dataSourceRemoved.addEventListener(removeSpy); collection.add(source); expect(addSpy).toHaveBeenCalledWith(collection, source); expect(removeSpy).not.toHaveBeenCalled(); addSpy.calls.reset(); removeSpy.calls.reset(); expect(collection.remove(source)).toEqual(true); expect(addSpy).not.toHaveBeenCalled(); expect(removeSpy).toHaveBeenCalledWith(collection, source); }); it('add works with promise', function() { var promise = when.defer(); var source = new MockDataSource(); var collection = new DataSourceCollection(); var addSpy = jasmine.createSpy('dataSourceAdded'); collection.dataSourceAdded.addEventListener(addSpy); collection.add(promise); expect(collection.length).toEqual(0); expect(addSpy).not.toHaveBeenCalled(); promise.resolve(source); expect(addSpy).toHaveBeenCalledWith(collection, source); expect(collection.length).toEqual(1); }); it('promise does not get added if not resolved before removeAll', function() { var promise = when.defer(); var source = new MockDataSource(); var collection = new DataSourceCollection(); var addSpy = jasmine.createSpy('dataSourceAdded'); collection.dataSourceAdded.addEventListener(addSpy); collection.add(promise); expect(collection.length).toEqual(0); expect(addSpy).not.toHaveBeenCalled(); collection.removeAll(); promise.resolve(source); expect(addSpy).not.toHaveBeenCalled(); expect(collection.length).toEqual(0); }); it('removeAll triggers events', function() { var sources = [new MockDataSource(), new MockDataSource(), new MockDataSource()]; var collection = new DataSourceCollection(); var removeCalled = 0; collection.dataSourceRemoved.addEventListener(function(sender, dataSource) { expect(sender).toBe(collection); expect(sources.indexOf(dataSource)).not.toEqual(-1); removeCalled++; }); collection.add(sources[0]); collection.add(sources[1]); collection.add(sources[2]); collection.removeAll(); expect(collection.length).toEqual(0); expect(removeCalled).toEqual(sources.length); }); it('destroy triggers remove events and calls destroy', function() { var sources = [new MockDataSource(), new MockDataSource(), new MockDataSource()]; var collection = new DataSourceCollection(); var removeCalled = 0; collection.dataSourceRemoved.addEventListener(function(sender, dataSource) { expect(sender).toBe(collection); expect(sources.indexOf(dataSource)).not.toEqual(-1); removeCalled++; }); collection.add(sources[0]); collection.add(sources[1]); collection.add(sources[2]); expect(collection.isDestroyed()).toEqual(false); collection.destroy(); expect(collection.isDestroyed()).toEqual(true); expect(removeCalled).toEqual(sources.length); expect(sources[0].destroyed).toEqual(true); expect(sources[1].destroyed).toEqual(true); expect(sources[2].destroyed).toEqual(true); }); it('remove returns fals for non-member', function() { var collection = new DataSourceCollection(); expect(collection.remove(new MockDataSource())).toEqual(false); }); it('get throws if passed undefined', function() { var collection = new DataSourceCollection(); expect(function(){ collection.get(undefined); }).toThrowDeveloperError(); }); it('add throws if passed undefined', function() { var collection = new DataSourceCollection(); expect(function(){ collection.add(undefined); }).toThrowDeveloperError(); }); });
gpl-3.0
shguolei/train-graph
ETRCTools/src/org/paradise/etrc/test/PrintTest.java
3067
package org.paradise.etrc.test; import java.awt.*; import java.awt.print.*; public class PrintTest implements Printable { public int iResMul = 4; // 1 = 72 dpi; 4 = 288 dpi public int print(Graphics g, PageFormat pf, int iPage) throws PrinterException { final int FONTSIZE = 12; final double PNT_MM = 25.4 / 72.; if (0 != iPage) return NO_SUCH_PAGE; try { int iPosX = 1; int iPosY = 1; int iAddY = FONTSIZE * 3 / 2 * iResMul; int iWdth = (int) Math.round(pf.getImageableWidth() * iResMul) - 3; int iHght = (int) Math.round(pf.getImageableHeight() * iResMul) - 3; int iCrcl = Math.min(iWdth, iHght) - 4 * iResMul; Graphics2D g2 = (Graphics2D) g; PrinterJob prjob = ((PrinterGraphics) g2).getPrinterJob(); g2.translate(pf.getImageableX(), pf.getImageableY()); g2.scale(1.0 / iResMul, 1.0 / iResMul); g2.setFont(new Font("SansSerif", Font.PLAIN, FONTSIZE * iResMul)); g2.setColor(Color.black); g2.drawRect(iPosX, iPosY, iWdth, iHght); g2.drawLine(iPosX, iHght / 2 + iWdth / 50, iPosX + iWdth, iHght / 2 - iWdth / 50); g2.drawLine(iPosX, iHght / 2 - iWdth / 50, iPosX + iWdth, iHght / 2 + iWdth / 50); g2.drawOval(iPosX + 2 * iResMul, iHght - iCrcl - 2 * iResMul, iCrcl, iCrcl); iPosX += iAddY; iPosY += iAddY / 2; g2.drawString("PrinterJob-UserName: " + prjob.getUserName(), iPosX, iPosY += iAddY); g2.drawString("Betriebssystem: " + System.getProperty("os.name") + " " + System.getProperty("os.version"), iPosX, iPosY += iAddY); g2.drawString("Java-Version: JDK " + System.getProperty("java.version"), iPosX, iPosY += iAddY); g2.drawString("Width/Height: " + dbldgt(pf.getWidth()) + " / " + dbldgt(pf.getHeight()) + " points = " + dbldgt(pf.getWidth() * PNT_MM) + " / " + dbldgt(pf.getHeight() * PNT_MM) + " mm", iPosX, iPosY += iAddY); g2.drawString("Imageable Width/Height: " + dbldgt(pf.getImageableWidth()) + " / " + dbldgt(pf.getImageableHeight()) + " points = " + dbldgt(pf.getImageableWidth() * PNT_MM) + " / " + dbldgt(pf.getImageableHeight() * PNT_MM) + " mm", iPosX, iPosY += iAddY); g2.drawString("Imageable X/Y: " + dbldgt(pf.getImageableX()) + " / " + dbldgt(pf.getImageableY()) + " points = " + dbldgt(pf.getImageableX() * PNT_MM) + " / " + dbldgt(pf.getImageableY() * PNT_MM) + " mm", iPosX, iPosY += iAddY); g2.drawString("versuchte Druckaufl sung: " + 72 * iResMul + " dpi", iPosX, iPosY += iAddY); } catch (Exception ex) { throw new PrinterException(ex.getMessage()); } return PAGE_EXISTS; } private static double dbldgt(double d) { return Math.round(d * 10.) / 10.; // show one digit after point } public static void main(String[] args) { PrinterJob pj = PrinterJob.getPrinterJob(); pj.setPrintable(new PrintTest()); if (pj.printDialog()) { try { pj.print(); } catch (PrinterException e) { System.out.println(e); } } } }
gpl-3.0
freemanmax/stats
upload/themes/default/js/loggedin.js
319
$(document).ready(function(){ width = $(window).width(); pop = $('#ps-loggedin-popup'); pop.css({ top: parseInt(75) + 'px', left: parseInt(width / 2 - pop.width() / 2) + 'px' }); // pop.fadeIn('fast'); setTimeout(function(){pop.fadeIn('fast');}, 250); setTimeout(function(){pop.fadeOut('slow');}, 4000); });
gpl-3.0
pallas1/ccminer-lyra-pallas
stats.cpp
3564
/** * Stats place holder * * Note: this source is C++ (requires std::map) * * tpruvot@github 2014 */ #include <stdlib.h> #include <memory.h> #include <map> #include "miner.h" static std::map<uint64_t, stats_data> tlastscans; static uint64_t uid = 0; //#define STATS_AVG_SAMPLES 60 #define STATS_PURGE_TIMEOUT 240*30 /* 60 mn */ extern uint64_t global_hashrate; extern uint32_t opt_statsavg; /** * Store speed per thread */ void stats_remember_speed(int thr_id, uint32_t hashcount, double hashrate, uint8_t found, uint32_t height) { uint8_t gpu = thr_id;// (uint8_t) device_map[thr_id]; const uint64_t key = ((uid++ % UINT32_MAX) << 32) + gpu; stats_data data; // to enough hashes to give right stats if (hashcount < 1000 || hashrate < 0.01) return; // first hash rates are often erroneous if (uid < opt_n_threads * opt_n_gputhreads) return; memset(&data, 0, sizeof(data)); data.uid = (uint32_t) uid; data.gpu_id = gpu; data.thr_id = (uint8_t)thr_id; data.tm_stat = (uint32_t) time(NULL); data.height = height; data.hashcount = hashcount; data.hashfound = found; data.hashrate = hashrate; data.difficulty = global_diff; if (opt_n_threads == 1 && global_hashrate && uid > 10) { // prevent stats on too high vardiff (erroneous rates) double ratio = (hashrate / (1.0 * global_hashrate)); if (ratio < 0.4 || ratio > 1.6) data.ignored = 1; } tlastscans[key] = data; } /** * Get the computed average speed * @param thr_id int (-1 for all threads) */ double stats_get_speed(int thr_id, double def_speed) { uint64_t gpu = thr_id;//device_map[thr_id]; const uint64_t keymsk = 0xffULL; // last u8 is the gpu double speed = 0.0; int records = 0; std::map<uint64_t, stats_data>::reverse_iterator i = tlastscans.rbegin(); while (i != tlastscans.rend() && records < opt_statsavg) { if (!i->second.ignored) if (thr_id == -1 || (keymsk & i->first) == gpu) { if (i->second.hashcount > 1000) { speed += i->second.hashrate; records++; // applog(LOG_BLUE, "%d %x %.1f", thr_id, i->second.thr_id, i->second.hashrate); } } ++i; } if (records) speed /= (double)(records); else speed = def_speed; if (thr_id == -1) speed *= (double)(opt_n_threads); return speed; } /** * Export data for api calls */ int stats_get_history(int thr_id, struct stats_data *data, int max_records) { const uint64_t gpu = device_map[thr_id]; const uint64_t keymsk = 0xffULL; // last u8 is the gpu int records = 0; std::map<uint64_t, stats_data>::reverse_iterator i = tlastscans.rbegin(); while (i != tlastscans.rend() && records < max_records) { if (!i->second.ignored) if (thr_id == -1 || (keymsk & i->first) == gpu) { memcpy(&data[records], &(i->second), sizeof(struct stats_data)); records++; } ++i; } return records; } /** * Remove old entries to reduce memory usage */ void stats_purge_old(void) { int deleted = 0; uint32_t now = (uint32_t) time(NULL); uint32_t sz = tlastscans.size(); std::map<uint64_t, stats_data>::iterator i = tlastscans.begin(); while (i != tlastscans.end()) { if (i->second.ignored || (now - i->second.tm_stat) > STATS_PURGE_TIMEOUT) { deleted++; tlastscans.erase(i++); } else ++i; } if (opt_debug && deleted) { applog(LOG_DEBUG, "stats: %d/%d records purged", deleted, sz); } } /** * Reset the cache */ void stats_purge_all(void) { tlastscans.clear(); } /** * API meminfo */ void stats_getmeminfo(uint64_t *mem, uint32_t *records) { (*records) = tlastscans.size(); (*mem) = (*records) * sizeof(stats_data); }
gpl-3.0
ZSMingNB/react-news
node_modules/antd/es/anchor/index.js
5611
import _defineProperty from 'babel-runtime/helpers/defineProperty'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import addEventListener from 'rc-util/es/Dom/addEventListener'; import AnchorLink from './AnchorLink'; import Affix from '../affix'; import AnchorHelper, { getDefaultTarget } from './anchorHelper'; var Anchor = function (_React$Component) { _inherits(Anchor, _React$Component); function Anchor(props) { _classCallCheck(this, Anchor); var _this = _possibleConstructorReturn(this, (Anchor.__proto__ || Object.getPrototypeOf(Anchor)).call(this, props)); _this.handleScroll = function () { _this.setState({ activeAnchor: _this.anchorHelper.getCurrentAnchor(_this.props.offsetTop, _this.props.bounds) }); }; _this.updateInk = function () { var activeAnchor = _this.anchorHelper.getCurrentActiveAnchor(); if (activeAnchor) { _this.refs.ink.style.top = activeAnchor.offsetTop + activeAnchor.clientHeight / 2 - 4.5 + 'px'; } }; _this.clickAnchorLink = function (href, component) { _this._avoidInk = true; _this.refs.ink.style.top = component.offsetTop + component.clientHeight / 2 - 4.5 + 'px'; _this.anchorHelper.scrollTo(href, _this.props.offsetTop, getDefaultTarget, function () { _this._avoidInk = false; }); }; _this.renderAnchorLink = function (child) { var href = child.props.href; var type = child.type; if (type.__ANT_ANCHOR_LINK && href) { _this.anchorHelper.addLink(href); return React.cloneElement(child, { onClick: _this.clickAnchorLink, prefixCls: _this.props.prefixCls, bounds: _this.props.bounds, affix: _this.props.affix || _this.props.showInkInFixed, offsetTop: _this.props.offsetTop }); } return child; }; _this.state = { activeAnchor: null, animated: true }; _this.anchorHelper = new AnchorHelper(); return _this; } _createClass(Anchor, [{ key: 'getChildContext', value: function getChildContext() { return { anchorHelper: this.anchorHelper }; } }, { key: 'componentDidMount', value: function componentDidMount() { this.handleScroll(); this.updateInk(); this.scrollEvent = addEventListener((this.props.target || getDefaultTarget)(), 'scroll', this.handleScroll); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { if (this.scrollEvent) { this.scrollEvent.remove(); } } }, { key: 'componentDidUpdate', value: function componentDidUpdate() { if (!this._avoidInk) { this.updateInk(); } } }, { key: 'render', value: function render() { var _classNames; var _props = this.props, prefixCls = _props.prefixCls, offsetTop = _props.offsetTop, style = _props.style, _props$className = _props.className, className = _props$className === undefined ? '' : _props$className, affix = _props.affix, showInkInFixed = _props.showInkInFixed; var _state = this.state, activeAnchor = _state.activeAnchor, animated = _state.animated; var inkClass = classNames((_classNames = {}, _defineProperty(_classNames, prefixCls + '-ink-ball', true), _defineProperty(_classNames, 'animated', animated), _defineProperty(_classNames, 'visible', !!activeAnchor), _classNames)); var wrapperClass = classNames(_defineProperty({}, prefixCls + '-wrapper', true), className); var anchorClass = classNames(prefixCls, { 'fixed': !affix && !showInkInFixed }); var anchorContent = React.createElement( 'div', { className: wrapperClass, style: style }, React.createElement( 'div', { className: anchorClass }, React.createElement( 'div', { className: prefixCls + '-ink' }, React.createElement('span', { className: inkClass, ref: 'ink' }) ), React.Children.toArray(this.props.children).map(this.renderAnchorLink) ) ); return !affix ? anchorContent : React.createElement( Affix, { offsetTop: offsetTop }, anchorContent ); } }]); return Anchor; }(React.Component); export default Anchor; Anchor.Link = AnchorLink; Anchor.defaultProps = { prefixCls: 'ant-anchor', affix: true, showInkInFixed: false }; Anchor.childContextTypes = { anchorHelper: PropTypes.any };
gpl-3.0
tolarteh/moodle20
lib/pear/PHP/CodeSniffer/CommentParser/CommentElement.php
7280
<?php /** * A class to represent Comments of a doc comment. * * PHP version 5 * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <gsherwood@squiz.net> * @author Marc McIntyre <mmcintyre@squiz.net> * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600) * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence * @version CVS: $Id: CommentElement.php,v 1.2 2010/12/14 17:35:22 moodlerobot Exp $ * @link http://pear.php.net/package/PHP_CodeSniffer */ if (class_exists('PHP_CodeSniffer_CommentParser_SingleElement', true) === false) { $error = 'Class PHP_CodeSniffer_CommentParser_SingleElement not found'; throw new PHP_CodeSniffer_Exception($error); } /** * A class to represent Comments of a doc comment. * * Comments are in the following format. * <code> * /** <--this is the start of the comment. * * This is a short comment description * * * * This is a long comment description * * <-- this is the end of the comment * * @return something * {@/} * </code> * * Note that the sentence before two newlines is assumed * the short comment description. * * @category PHP * @package PHP_CodeSniffer * @author Greg Sherwood <gsherwood@squiz.net> * @author Marc McIntyre <mmcintyre@squiz.net> * @copyright 2006 Squiz Pty Ltd (ABN 77 084 670 600) * @license http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence * @version Release: 1.1.0 * @link http://pear.php.net/package/PHP_CodeSniffer */ class PHP_CodeSniffer_CommentParser_CommentElement extends PHP_CodeSniffer_CommentParser_SingleElement { /** * Constructs a PHP_CodeSniffer_CommentParser_CommentElement. * * @param PHP_CodeSniffer_CommentParser_DocElemement $previousElement The element * that * appears * before this * element. * @param array $tokens The tokens * that make * up this * element. * @param PHP_CodeSniffer_File $phpcsFile The file * that this * element is * in. */ public function __construct($previousElement, $tokens, PHP_CodeSniffer_File $phpcsFile) { parent::__construct($previousElement, $tokens, 'comment', $phpcsFile); }//end __construct() /** * Returns the short comment description. * * @return string * @see getLongComment() */ public function getShortComment() { $pos = $this->_getShortCommentEndPos(); if ($pos === -1) { return ''; } return implode('', array_slice($this->tokens, 0, ($pos + 1))); }//end getShortComment() /** * Returns the last token position of the short comment description. * * @return int The last token position of the short comment description * @see _getLongCommentStartPos() */ private function _getShortCommentEndPos() { $found = false; $whiteSpace = array( ' ', "\t", ); foreach ($this->tokens as $pos => $token) { $token = str_replace($whiteSpace, '', $token); if ($token === $this->phpcsFile->eolChar) { if ($found === false) { // Include newlines before short description. continue; } else { if (isset($this->tokens[($pos + 1)]) === true) { if ($this->tokens[($pos + 1)] === $this->phpcsFile->eolChar) { return ($pos - 1); } } else { return $pos; } } } else { $found = true; } }//end foreach return (count($this->tokens) - 1); }//end _getShortCommentEndPos() /** * Returns the long comment description. * * @return string * @see getShortComment */ public function getLongComment() { $start = $this->_getLongCommentStartPos(); if ($start === -1) { return ''; } return implode('', array_slice($this->tokens, $start)); }//end getLongComment() /** * Returns the start position of the long comment description. * * Returns -1 if there is no long comment. * * @return int The start position of the long comment description. * @see _getShortCommentEndPos() */ private function _getLongCommentStartPos() { $pos = ($this->_getShortCommentEndPos() + 1); if ($pos === (count($this->tokens) - 1)) { return -1; } $count = count($this->tokens); for ($i = $pos; $i < $count; $i++) { $content = trim($this->tokens[$i]); if ($content !== '') { if ($content{0} === '@') { return -1; } return $i; } } return -1; }//end _getLongCommentStartPos() /** * Returns the whitespace that exists between * the short and the long comment description. * * @return string */ public function getWhiteSpaceBetween() { $endShort = ($this->_getShortCommentEndPos() + 1); $startLong = ($this->_getLongCommentStartPos() - 1); if ($startLong === -1) { return ''; } return implode('', array_slice($this->tokens, $endShort, ($startLong - $endShort))); }//end getWhiteSpaceBetween() /** * Returns the number of newlines that exist before the tags. * * @return int */ public function getNewlineAfter() { $long = $this->getLongComment(); if ($long !== '') { $long = rtrim($long, ' '); $long = strrev($long); $newlines = strspn($long, $this->phpcsFile->eolChar); } else { $endShort = ($this->_getShortCommentEndPos() + 1); $after = implode('', array_slice($this->tokens, $endShort)); $after = trim($after, ' '); $newlines = strspn($after, $this->phpcsFile->eolChar); } return ($newlines / strlen($this->phpcsFile->eolChar)); }//end getNewlineAfter() /** * Returns true if there is no comment. * * @return boolean */ public function isEmpty() { return (trim($this->getContent()) === ''); }//end isEmpty() }//end class ?>
gpl-3.0
naseef-07/gloox_lib_with_vs2013_project_file
src/mucmessagesession.cpp
1383
/* Copyright (c) 2006-2015 by Jakob Schröter <js@camaya.net> This file is part of the gloox library. http://camaya.net/gloox This software is distributed under a license. The full license agreement can be found in the file LICENSE in this distribution. This software may not be copied, modified, sold or distributed other than expressed in the named license agreement. This software is distributed without any warranty. */ #include "mucmessagesession.h" #include "clientbase.h" #include "message.h" #include "messagehandler.h" namespace gloox { MUCMessageSession::MUCMessageSession( ClientBase* parent, const JID& jid ) : MessageSession( parent, jid, false, Message::Groupchat | Message::Chat | Message::Normal | Message::Error, false ) { } MUCMessageSession::~MUCMessageSession() { } void MUCMessageSession::handleMessage( Message& msg ) { if( m_messageHandler ) m_messageHandler->handleMessage( msg ); } void MUCMessageSession::send( const std::string& message ) { Message m( Message::Groupchat, m_target, message ); // decorate( m ); m_parent->send( m ); } void MUCMessageSession::setSubject( const std::string& subject ) { Message m( Message::Groupchat, m_target.bareJID(), EmptyString, subject ); m_parent->send( m ); } }
gpl-3.0
GRIS-UdeM/ZirkOSC2
JuceLibraryCode/modules/juce_audio_basics/mpe/juce_MPEZone.cpp
11372
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2015 - ROLI Ltd. Permission is granted to use this software under the terms of either: a) the GPL v2 (or any later version) b) the Affero GPL v3 Details of these licenses can be found at: www.gnu.org/licenses JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ namespace { void checkAndLimitZoneParameters (int minValue, int maxValue, int& valueToCheckAndLimit) noexcept { if (valueToCheckAndLimit < minValue || valueToCheckAndLimit > maxValue) { // if you hit this, one of the parameters you supplied for MPEZone // was not within the allowed range! // we fit this back into the allowed range here to maintain a valid // state for the zone, but probably the resulting zone is not what you //wanted it to be! jassertfalse; valueToCheckAndLimit = jlimit (minValue, maxValue, valueToCheckAndLimit); } } } //============================================================================== MPEZone::MPEZone (int masterChannel_, int numNoteChannels_, int perNotePitchbendRange_, int masterPitchbendRange_) noexcept : masterChannel (masterChannel_), numNoteChannels (numNoteChannels_), perNotePitchbendRange (perNotePitchbendRange_), masterPitchbendRange (masterPitchbendRange_) { checkAndLimitZoneParameters (1, 15, masterChannel); checkAndLimitZoneParameters (1, 16 - masterChannel, numNoteChannels); checkAndLimitZoneParameters (0, 96, perNotePitchbendRange); checkAndLimitZoneParameters (0, 96, masterPitchbendRange); } //============================================================================== int MPEZone::getMasterChannel() const noexcept { return masterChannel; } int MPEZone::getNumNoteChannels() const noexcept { return numNoteChannels; } int MPEZone::getFirstNoteChannel() const noexcept { return masterChannel + 1; } int MPEZone::getLastNoteChannel() const noexcept { return masterChannel + numNoteChannels; } Range<int> MPEZone::getNoteChannelRange() const noexcept { return Range<int>::withStartAndLength (getFirstNoteChannel(), getNumNoteChannels()); } bool MPEZone::isUsingChannel (int channel) const noexcept { jassert (channel > 0 && channel <= 16); return channel >= masterChannel && channel <= masterChannel + numNoteChannels; } bool MPEZone::isUsingChannelAsNoteChannel (int channel) const noexcept { jassert (channel > 0 && channel <= 16); return channel > masterChannel && channel <= masterChannel + numNoteChannels; } int MPEZone::getPerNotePitchbendRange() const noexcept { return perNotePitchbendRange; } int MPEZone::getMasterPitchbendRange() const noexcept { return masterPitchbendRange; } void MPEZone::setPerNotePitchbendRange (int rangeInSemitones) noexcept { checkAndLimitZoneParameters (0, 96, rangeInSemitones); perNotePitchbendRange = rangeInSemitones; } void MPEZone::setMasterPitchbendRange (int rangeInSemitones) noexcept { checkAndLimitZoneParameters (0, 96, rangeInSemitones); masterPitchbendRange = rangeInSemitones; } //============================================================================== bool MPEZone::overlapsWith (MPEZone other) const noexcept { if (masterChannel == other.masterChannel) return true; if (masterChannel > other.masterChannel) return other.overlapsWith (*this); return masterChannel + numNoteChannels >= other.masterChannel; } //============================================================================== bool MPEZone::truncateToFit (MPEZone other) noexcept { const int masterChannelDiff = other.masterChannel - masterChannel; // we need at least 2 channels to be left after truncation: // 1 master channel and 1 note channel. otherwise we can't truncate. if (masterChannelDiff < 2) return false; numNoteChannels = jmin (numNoteChannels, masterChannelDiff - 1); return true; } //============================================================================== //============================================================================== #if JUCE_UNIT_TESTS class MPEZoneTests : public UnitTest { public: MPEZoneTests() : UnitTest ("MPEZone class") {} void runTest() override { beginTest ("initialisation"); { { MPEZone zone (1, 10); expectEquals (zone.getMasterChannel(), 1); expectEquals (zone.getNumNoteChannels(), 10); expectEquals (zone.getFirstNoteChannel(), 2); expectEquals (zone.getLastNoteChannel(), 11); expectEquals (zone.getPerNotePitchbendRange(), 48); expectEquals (zone.getMasterPitchbendRange(), 2); expect (zone.isUsingChannel (1)); expect (zone.isUsingChannel (2)); expect (zone.isUsingChannel (10)); expect (zone.isUsingChannel (11)); expect (! zone.isUsingChannel (12)); expect (! zone.isUsingChannel (16)); expect (! zone.isUsingChannelAsNoteChannel (1)); expect (zone.isUsingChannelAsNoteChannel (2)); expect (zone.isUsingChannelAsNoteChannel (10)); expect (zone.isUsingChannelAsNoteChannel (11)); expect (! zone.isUsingChannelAsNoteChannel (12)); expect (! zone.isUsingChannelAsNoteChannel (16)); } { MPEZone zone (5, 4); expectEquals (zone.getMasterChannel(), 5); expectEquals (zone.getNumNoteChannels(), 4); expectEquals (zone.getFirstNoteChannel(), 6); expectEquals (zone.getLastNoteChannel(), 9); expectEquals (zone.getPerNotePitchbendRange(), 48); expectEquals (zone.getMasterPitchbendRange(), 2); expect (! zone.isUsingChannel (1)); expect (! zone.isUsingChannel (4)); expect (zone.isUsingChannel (5)); expect (zone.isUsingChannel (6)); expect (zone.isUsingChannel (8)); expect (zone.isUsingChannel (9)); expect (! zone.isUsingChannel (10)); expect (! zone.isUsingChannel (16)); expect (! zone.isUsingChannelAsNoteChannel (5)); expect (zone.isUsingChannelAsNoteChannel (6)); expect (zone.isUsingChannelAsNoteChannel (8)); expect (zone.isUsingChannelAsNoteChannel (9)); expect (! zone.isUsingChannelAsNoteChannel (10)); } } beginTest ("getNoteChannelRange"); { MPEZone zone (2, 10); Range<int> noteChannelRange = zone.getNoteChannelRange(); expectEquals (noteChannelRange.getStart(), 3); expectEquals (noteChannelRange.getEnd(), 13); } beginTest ("setting master pitchbend range"); { MPEZone zone (1, 10); zone.setMasterPitchbendRange (96); expectEquals (zone.getMasterPitchbendRange(), 96); zone.setMasterPitchbendRange (0); expectEquals (zone.getMasterPitchbendRange(), 0); expectEquals (zone.getPerNotePitchbendRange(), 48); } beginTest ("setting per-note pitchbend range"); { MPEZone zone (1, 10); zone.setPerNotePitchbendRange (96); expectEquals (zone.getPerNotePitchbendRange(), 96); zone.setPerNotePitchbendRange (0); expectEquals (zone.getPerNotePitchbendRange(), 0); expectEquals (zone.getMasterPitchbendRange(), 2); } beginTest ("checking overlap"); { testOverlapsWith (1, 10, 1, 10, true); testOverlapsWith (1, 4, 6, 3, false); testOverlapsWith (1, 4, 8, 3, false); testOverlapsWith (2, 10, 2, 8, true); testOverlapsWith (1, 10, 3, 2, true); testOverlapsWith (3, 10, 5, 9, true); } beginTest ("truncating"); { testTruncateToFit (1, 10, 3, 10, true, 1, 1); testTruncateToFit (3, 10, 1, 10, false, 3, 10); testTruncateToFit (1, 10, 5, 8, true, 1, 3); testTruncateToFit (5, 8, 1, 10, false, 5, 8); testTruncateToFit (1, 10, 4, 3, true, 1, 2); testTruncateToFit (4, 3, 1, 10, false, 4, 3); testTruncateToFit (1, 3, 5, 3, true, 1, 3); testTruncateToFit (5, 3, 1, 3, false, 5, 3); testTruncateToFit (1, 3, 7, 3, true, 1, 3); testTruncateToFit (7, 3, 1, 3, false, 7, 3); testTruncateToFit (1, 10, 2, 10, false, 1, 10); testTruncateToFit (2, 10, 1, 10, false, 2, 10); } } private: //========================================================================== void testOverlapsWith (int masterChannelFirst, int numNoteChannelsFirst, int masterChannelSecond, int numNoteChannelsSecond, bool expectedRetVal) { MPEZone first (masterChannelFirst, numNoteChannelsFirst); MPEZone second (masterChannelSecond, numNoteChannelsSecond); expect (first.overlapsWith (second) == expectedRetVal); expect (second.overlapsWith (first) == expectedRetVal); } //========================================================================== void testTruncateToFit (int masterChannelFirst, int numNoteChannelsFirst, int masterChannelSecond, int numNoteChannelsSecond, bool expectedRetVal, int masterChannelFirstAfter, int numNoteChannelsFirstAfter) { MPEZone first (masterChannelFirst, numNoteChannelsFirst); MPEZone second (masterChannelSecond, numNoteChannelsSecond); expect (first.truncateToFit (second) == expectedRetVal); expectEquals (first.getMasterChannel(), masterChannelFirstAfter); expectEquals (first.getNumNoteChannels(), numNoteChannelsFirstAfter); } }; static MPEZoneTests MPEZoneUnitTests; #endif // JUCE_UNIT_TESTS
gpl-3.0
benzzdan/greeenpeach4
application/controllers/admin/module_main.php
4566
<?php /** * This file is part of OXID eShop Community Edition. * * OXID eShop Community Edition 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. * * OXID eShop Community Edition 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 OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>. * * @link http://www.oxid-esales.com * @copyright (C) OXID eSales AG 2003-2017 * @version OXID eShop CE */ /** * Admin article main deliveryset manager. * There is possibility to change deliveryset name, article, user * and etc. * Admin Menu: Shop settings -> Shipping & Handling -> Main Sets. */ class Module_Main extends oxAdminDetails { /** * Executes parent method parent::render(), creates deliveryset category tree, * passes data to Smarty engine and returns name of template file "deliveryset_main.tpl". * * @return string */ public function render() { if (oxRegistry::getConfig()->getRequestParameter("moduleId")) { $sModuleId = oxRegistry::getConfig()->getRequestParameter("moduleId"); } else { $sModuleId = $this->getEditObjectId(); } $oModule = oxNew('oxModule'); if ($sModuleId) { if ($oModule->load($sModuleId)) { $iLang = oxRegistry::getLang()->getTplLanguage(); $this->_aViewData["oModule"] = $oModule; $this->_aViewData["sModuleName"] = basename($oModule->getInfo("title", $iLang)); $this->_aViewData["sModuleId"] = str_replace("/", "_", $oModule->getModulePath()); } else { oxRegistry::get("oxUtilsView")->addErrorToDisplay(new oxException('EXCEPTION_MODULE_NOT_LOADED')); } } parent::render(); return 'module_main.tpl'; } /** * Activate module * * @return null */ public function activateModule() { if ($this->getConfig()->isDemoShop()) { oxRegistry::get("oxUtilsView")->addErrorToDisplay('MODULE_ACTIVATION_NOT_POSSIBLE_IN_DEMOMODE'); return; } $sModule = $this->getEditObjectId(); /** @var oxModule $oModule */ $oModule = oxNew('oxModule'); if (!$oModule->load($sModule)) { oxRegistry::get("oxUtilsView")->addErrorToDisplay(new oxException('EXCEPTION_MODULE_NOT_LOADED')); return; } try { /** @var oxModuleCache $oModuleCache */ $oModuleCache = oxNew('oxModuleCache', $oModule); /** @var oxModuleInstaller $oModuleInstaller */ $oModuleInstaller = oxNew('oxModuleInstaller', $oModuleCache); if ($oModuleInstaller->activate($oModule)) { $this->_aViewData["updatenav"] = "1"; } } catch (oxException $oEx) { oxRegistry::get("oxUtilsView")->addErrorToDisplay($oEx); $oEx->debugOut(); } } /** * Deactivate module * * @return null */ public function deactivateModule() { if ($this->getConfig()->isDemoShop()) { oxRegistry::get("oxUtilsView")->addErrorToDisplay('MODULE_ACTIVATION_NOT_POSSIBLE_IN_DEMOMODE'); return; } $sModule = $this->getEditObjectId(); /** @var oxModule $oModule */ $oModule = oxNew('oxModule'); if (!$oModule->load($sModule)) { oxRegistry::get("oxUtilsView")->addErrorToDisplay(new oxException('EXCEPTION_MODULE_NOT_LOADED')); return; } try { /** @var oxModuleCache $oModuleCache */ $oModuleCache = oxNew('oxModuleCache', $oModule); /** @var oxModuleInstaller $oModuleInstaller */ $oModuleInstaller = oxNew('oxModuleInstaller', $oModuleCache); if ($oModuleInstaller->deactivate($oModule)) { $this->_aViewData["updatenav"] = "1"; } } catch (oxException $oEx) { oxRegistry::get("oxUtilsView")->addErrorToDisplay($oEx); $oEx->debugOut(); } } }
gpl-3.0
1bigmac/OA
src/com/oa/model/EventCalender.java
1596
package com.oa.model; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="oa_eventCalender") public class EventCalender { private Integer id; private String title; private Boolean allDay; private Date start; private Date end; private String location; private Users users; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Boolean getAllDay() { return allDay; } public void setAllDay(Boolean allDay) { this.allDay = allDay; } public Date getStart() { return start; } public void setStart(Date start) { this.start = start; } public Date getEnd() { return end; } public void setEnd(Date end) { this.end = end; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } @ManyToOne(cascade={CascadeType.ALL}) @JoinColumn(name="userId",referencedColumnName="id") public Users getUsers() { return users; } public void setUsers(Users users) { this.users = users; } @Override public String toString() { return "EventCalender [id=" + id + ", title=" + title + ", allDay=" + allDay + ", start=" + start + ", end=" + end + ", location=" + location + "]"; } }
gpl-3.0
stevenengelen/internet-platform
application/admin/component/news/view/articles/templates/default_scopebar.html.php
1020
<? /** * Belgian Police Web Platform - News Component * * @copyright Copyright (C) 2012 - 2013 Timble CVBA. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link https://github.com/belgianpolice/internet-platform */ ?> <div class="scopebar"> <div class="scopebar__group"> <a class="<?= is_null($state->search) && is_null($state->published) ? 'active' : ''; ?>" href="<?= route('search=&published=' ) ?>"> <?= translate('All') ?> </a> </div> <div class="scopebar__group"> <a class="<?= $state->published === 1 ? 'active' : ''; ?>" href="<?= route($state->published === 1 ? 'published=' : 'published=1' ) ?>"> <?= 'Published' ?> </a> <a class="<?= $state->published === 0 ? 'active' : ''; ?>" href="<?= route($state->published === 0 ? 'published=' : 'published=0' ) ?>"> <?= 'Unpublished' ?> </a> </div> <div class="scopebar__search"> <?= helper('grid.search') ?> </div> </div>
gpl-3.0
saophaisau/port
Core/Champion Ports/Ahri/AhriSharp/Program.cs
322
using System; using LeagueSharp; using LeagueSharp.Common; using EloBuddy; using LeagueSharp.Common; namespace AhriSharp { class Program { public static Helper Helper; public static void Game_OnGameLoad() { Helper = new Helper(); new Ahri(); } } }
gpl-3.0
saophaisau/port
Core/SDK Ports/ArcaneRyze/Modes/Lane.cs
1779
using Arcane_Ryze.Handler; using Arcane_Ryze.Main; using LeagueSharp; using LeagueSharp.SDK; using LeagueSharp.SDK.Enumerations; using System; using System.Linq; using static Arcane_Ryze.Core; using EloBuddy; using LeagueSharp.SDK; namespace Arcane_Ryze.Modes { class Lane { private static AIHeroClient Player = ObjectManager.Player; public static void LaneLogic() { var minions = GameObjects.EnemyMinions.Where(m => m.IsMinion && m.IsEnemy && m.Team != GameObjectTeam.Neutral && m.IsValidTarget(Player.AttackRange)).ToList(); if (PassiveStack > 4) { return; } if (!(Player.ManaPercent >= MenuConfig.LaneMana.Value)) return; { foreach (var m in minions) { if (!m.IsValidTarget() || m.IsZombie || m.IsDead) continue; if (m.Health < Spells.Q.GetDamage(m) && !Player.Spellbook.IsAutoAttacking) { Spells.Q.Cast(m); } if (Spells.Q.IsReady() && m.Health > Spells.Q.GetDamage(m) && Player.GetAutoAttackDamage(m) > m.Health) { Spells.Q.Cast(m); } if (Spells.E.IsReady()) { Spells.E.Cast(m); } if (Spells.W.IsReady() && m.Health < Spells.W.GetDamage(m)) { Spells.W.Cast(m); } if (Spells.R.IsReady() && MenuConfig.LaneR) { Spells.R.Cast(); } } } } } }
gpl-3.0
b3lst/Zeus-Android-Client
app/src/main/java/com/prey/activities/LoginActivity.java
4357
/******************************************************************************* * Created by Carlos Yaconi * Copyright 2012 Fork Ltd. All rights reserved. * License: GPLv3 * Full license at "/LICENSE" ******************************************************************************/ package com.prey.activities; import android.app.NotificationManager; import com.prey.PreyStatus; import com.prey.PreyVerify; import com.prey.R; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.prey.PreyConfig; import com.prey.backwardcompatibility.FroyoSupport; import com.prey.services.PreyDisablePowerOptionsService; public class LoginActivity extends PasswordActivity { @Override public void onConfigurationChanged(Configuration newConfig) { // ignore orientation change super.onConfigurationChanged(newConfig); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // Delete notifications (in case Activity was started by one of them) NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.cancel(R.string.preyForAndroid_name); startup(); boolean disablePowerOptions = PreyConfig.getPreyConfig(getApplicationContext()).isDisablePowerOptions(); if (disablePowerOptions) { startService(new Intent(getApplicationContext(), PreyDisablePowerOptionsService.class)); } else { stopService(new Intent(getApplicationContext(), PreyDisablePowerOptionsService.class)); } } @Override protected void onStart() { super.onStart(); startup(); } private void startup() { if (!isThisDeviceAlreadyRegisteredWithPrey()) { Intent intent = null; if (!isThereBatchInstallationKey()) { intent = new Intent(LoginActivity.this, WelcomeActivity.class); } else { intent = new Intent(LoginActivity.this, WelcomeBatchActivity.class); } startActivity(intent); finish(); } else { PreyVerify.getInstance(this); if (getPreyConfig().showFeedback()) { showFeedback(getApplicationContext()); } else { showLogin(); } } } private void showLogin() { setContentView(R.layout.login); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); updateLoginScreen(); Button gotoSettings = (Button) findViewById(R.id.login_btn_settings); if (!FroyoSupport.getInstance(this).isAdminActive()) { String h1 = getString(R.string.device_not_ready_h1); String h2 = getString(R.string.device_not_ready_h2); TextView textH1 = (TextView) findViewById(R.id.device_ready_h1_text); TextView textH2 = (TextView) findViewById(R.id.device_ready_h2_text); textH1.setText(h1); textH2.setText(h2); } try { Button gotoCP = (Button) findViewById(R.id.login_btn_cp); gotoCP.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { try { String url = PreyConfig.getPreyConfig(getApplicationContext()).getPreyPanelUrl(); Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse(url)); startActivity(browserIntent); } catch (Exception e) { } } }); } catch (Exception e) { } gotoSettings.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if (!PreyStatus.getInstance().isPreyConfigurationActivityResume()) { Intent intent = new Intent(LoginActivity.this, CheckPasswordActivity.class); startActivity(intent); } else { Intent intent = new Intent(LoginActivity.this, PreyConfigurationActivity.class); startActivity(intent); } } }); } private boolean isThisDeviceAlreadyRegisteredWithPrey() { return getPreyConfig().isThisDeviceAlreadyRegisteredWithPrey(false); } private void showFeedback(Context ctx) { Intent popup = new Intent(ctx, FeedbackActivity.class); popup.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); ctx.startActivity(popup); } private boolean isThereBatchInstallationKey() { String apiKeyBatch = getPreyConfig().getApiKeyBatch(); return (apiKeyBatch != null && !"".equals(apiKeyBatch)); } }
gpl-3.0
KlapZaZa/overture
core/codegen/platform/src/main/java/org/overture/codegen/analysis/vdm/VdmAnalysis.java
712
package org.overture.codegen.analysis.vdm; import java.util.HashSet; import java.util.Set; import org.overture.ast.analysis.DepthFirstAnalysisAdaptor; import org.overture.ast.node.INode; public abstract class VdmAnalysis extends DepthFirstAnalysisAdaptor { protected INode topNode; public VdmAnalysis(INode topNode) { this.topNode = topNode; } protected boolean proceed(INode node) { if (node == topNode) { return true; } INode parent = node.parent(); Set<INode> visited = new HashSet<INode>(); while (parent != null && !visited.contains(parent) && this.topNode != parent) { visited.add(parent); parent = parent.parent(); } return this.topNode == parent; } }
gpl-3.0
FreePBX/contactmanager
vendor/giggsey/libphonenumber-for-php/src/data/ShortNumberMetadata_EH.php
2056
<?php /** * This file has been @generated by a phing task by {@link BuildMetadataPHPFromXml}. * See [README.md](README.md#generating-data) for more information. * * Pull requests changing data in these files will not be accepted. See the * [FAQ in the README](README.md#problems-with-invalid-numbers] on how to make * metadata changes. * * Do not modify this file directly! */ return array ( 'generalDesc' => array ( 'NationalNumberPattern' => '1\\d{1,2}', 'PossibleLength' => array ( 0 => 2, 1 => 3, ), 'PossibleLengthLocalOnly' => array ( ), ), 'tollFree' => array ( 'PossibleLength' => array ( 0 => -1, ), 'PossibleLengthLocalOnly' => array ( ), ), 'premiumRate' => array ( 'PossibleLength' => array ( 0 => -1, ), 'PossibleLengthLocalOnly' => array ( ), ), 'emergency' => array ( 'NationalNumberPattern' => '1(?:[59]|77)', 'ExampleNumber' => '15', 'PossibleLength' => array ( ), 'PossibleLengthLocalOnly' => array ( ), ), 'shortCode' => array ( 'NationalNumberPattern' => '1(?:[59]|77)', 'ExampleNumber' => '15', 'PossibleLength' => array ( ), 'PossibleLengthLocalOnly' => array ( ), ), 'standardRate' => array ( 'PossibleLength' => array ( 0 => -1, ), 'PossibleLengthLocalOnly' => array ( ), ), 'carrierSpecific' => array ( 'PossibleLength' => array ( 0 => -1, ), 'PossibleLengthLocalOnly' => array ( ), ), 'smsServices' => array ( 'PossibleLength' => array ( 0 => -1, ), 'PossibleLengthLocalOnly' => array ( ), ), 'id' => 'EH', 'countryCode' => 0, 'internationalPrefix' => '', 'sameMobileAndFixedLinePattern' => false, 'numberFormat' => array ( ), 'intlNumberFormat' => array ( ), 'mainCountryForCode' => false, 'leadingZeroPossible' => false, 'mobileNumberPortableRegion' => false, );
gpl-3.0
sebardo/admin
AdminBundle/Resources/public/plugins/jquery-typeahead/src/jquery.typeahead.js
84585
/*! * jQuery Typeahead * Copyright (C) 2015 RunningCoder.org * Licensed under the MIT license * * @author Tom Bertrand * @version 2.0.0 (2015-07-19) * @link http://www.runningcoder.org/jquerytypeahead/ */ ; (function (window, document, $, undefined) { window.Typeahead = { version: '2.0.0' }; "use strict"; /** * @private * Default options * * @link http://www.runningcoder.org/jquerytypeahead/documentation/ */ var _options = { input: null, minLength: 2, // Modified feature, now accepts 0 to search on focus maxItem: 8, // Modified feature, now accepts 0 as "Infinity" meaning all the results will be displayed dynamic: false, delay: 300, order: null, // ONLY sorts the first "display" key offset: false, hint: false, // -> Improved feature, Added support for excessive "space" characters accent: false, highlight: true, group: false, // -> Improved feature, Array second index is a custom group title (html allowed) maxItemPerGroup: null, // -> Renamed option dropdownFilter: false, // -> Renamed option, true will take group options string will filter on object key dynamicFilter: null, // -> New feature, filter the typeahead results based on dynamic value, Ex: Players based on TeamID backdrop: false, cache: false, ttl: 3600000, compression: false, // -> Requires LZString library suggestion: false, // -> *Coming soon* New feature, save last searches and display suggestion on matched characters searchOnFocus: false, // -> New feature, display search results on input focus resultContainer: null, // -> New feature, list the results inside any container string or jQuery object generateOnLoad: null, // -> New feature, forces the source to be generated on page load even if the input is not focused! mustSelectItem: false, // -> New option, the submit function only gets called if an item is selected href: null, // -> New feature, String or Function to format the url for right-click & open in new tab on link results display: ["display"], // -> Improved feature, allows search in multiple item keys ["display1", "display2"] template: null, emptyTemplate: false, // -> New feature, display an empty template if no result source: null, // -> Modified feature, source.ignore is now a regex; item.group is a reserved word; Ajax callbacks: done, fail, complete, always callback: { onInit: null, onReady: null, // -> New callback, when the Typeahead initial preparation is completed onSearch: null, // -> New callback, when data is being fetched & analyzed to give search results onResult: null, onLayoutBuiltBefore: null, // -> New callback, when the result HTML is build, modify it before it get showed onLayoutBuiltAfter: null, // -> New callback, modify the dom right after the results gets inserted in the result container onNavigate: null, // -> New callback, when a key is pressed to navigate the results onMouseEnter: null, onMouseLeave: null, onClickBefore: null,// -> Improved feature, possibility to e.preventDefault() to prevent the Typeahead behaviors onClickAfter: null, // -> New feature, happens after the default clicked behaviors has been executed onSendRequest: null,// -> New callback, gets called when the Ajax request(s) are sent onReceiveRequest: null, // -> New callback, gets called when the Ajax request(s) are all received onSubmit: null }, selector: { container: "typeahead-container", group: "typeahead-group", result: "typeahead-result", list: "typeahead-list", display: "typeahead-display", query: "typeahead-query", filter: "typeahead-filter", filterButton: "typeahead-filter-button", filterValue: "typeahead-filter-value", dropdown: "typeahead-dropdown", dropdownCarret: "typeahead-caret", button: "typeahead-button", backdrop: "typeahead-backdrop", hint: "typeahead-hint" }, debug: false }; /** * @private * Event namespace */ var _namespace = ".typeahead"; /** * @private * Accent equivalents */ var _accent = { from: "ãàáäâẽèéëêìíïîõòóöôùúüûñç", to: "aaaaaeeeeeiiiiooooouuuunc" }; // SOURCE ITEMS RESERVED KEYS: group, display, data, matchedKey, , href /** * @constructor * Typeahead Class * * @param {object} node jQuery input object * @param {object} options User defined options */ var Typeahead = function (node, options) { this.rawQuery = ''; // Unmodified input query this.query = ''; // Input query this.source = {}; // The generated source kept in memory this.isGenerated = null; // Generated results -> null: not generated, false: generating, true generated this.generatedGroupCount = 0; // Number of groups generated, if limit reached the search can be done this.groupCount = 0; // Number of groups, this value gets counted on the initial source unification this.groupBy = "group"; // This option will change according to filtering or custom grouping this.result = []; // Results based on Source-query match (only contains the displayed elements) this.resultCount = 0; // Total results based on Source-query match this.options = options; // Typeahead options (Merged default & user defined) this.node = node; // jQuery object of the Typeahead <input> this.container = null; // Typeahead container, usually right after <form> this.resultContainer = null; // Typeahead result container (html) this.item = null; // The selected item this.xhr = {}; // Ajax request(s) stack this.hintIndex = null; // Numeric value of the hint index in the result list this.filters = { // Filter list for searching, dropdown and dynamic(s) dropdown: {}, // Dropdown menu if options.dropdownFilter is set dynamic: {} // Checkbox / Radio / Select to filter the source data }; this.requests = {}; // Store the group:request instead of generating them every time this.backdrop = {}; // The backdrop object this.hint = {}; // The hint object this.__construct(); }; Typeahead.prototype = { extendOptions: function () { // If the Typeahead is dynamic, force no cache & no compression if (this.options.dynamic) { this.options.cache = false; this.options.compression = false; } // Ensure Localstorage is available if (this.options.cache) { this.options.cache = (function () { var supported = typeof window.localStorage !== "undefined"; if (supported) { try { window.localStorage.setItem("typeahead", "typeahead"); window.localStorage.removeItem("typeahead"); } catch (e) { supported = false; } } return supported; })(); } if (this.options.compression) { if (typeof LZString !== 'object' || !this.options.cache) { // {debug} _debug.log({ 'node': this.node.selector, 'function': 'extendOptions()', 'message': 'Missing LZString Library or options.cache, no compression will occur.' }); _debug.print(); // {/debug} this.options.compression = false; } } if (typeof this.options.maxItem !== "undefined" && (!/^\d+$/.test(this.options.maxItem) || this.options.maxItem === 0)) { this.options.maxItem = Infinity; } if (this.options.maxItemPerGroup && !/^\d+$/.test(this.options.maxItemPerGroup)) { this.options.maxItemPerGroup = null; } if (this.options.display && !(this.options.display instanceof Array)) { this.options.display = [this.options.display]; } if (this.options.group && !(this.options.group instanceof Array)) { this.options.group = [this.options.group]; } if (this.options.dynamicFilter && !(this.options.dynamicFilter instanceof Array)) { this.options.dynamicFilter = [this.options.dynamicFilter] } if (this.options.resultContainer) { if (typeof this.options.resultContainer === "string") { this.options.resultContainer = $(this.options.resultContainer); } if (!(this.options.resultContainer instanceof jQuery) || !this.options.resultContainer[0]) { // {debug} _debug.log({ 'node': this.node.selector, 'function': 'extendOptions()', 'message': 'Invalid jQuery selector or jQuery Object for "options.resultContainer".' }); _debug.print(); // {/debug} } else { this.resultContainer = this.options.resultContainer; } } if (this.options.group && typeof this.options.group[0] === "string" && this.options.maxItemPerGroup) { this.groupBy = this.options.group[0]; } // Compatibility onClick callback if (this.options.callback && this.options.callback.onClick) { this.options.callback.onClickBefore = this.options.callback.onClick; delete this.options.callback.onClick; } this.options = $.extend( true, {}, _options, this.options ); }, unifySourceFormat: function () { if (this.options.source instanceof Array) { this.options.source = { group: { data: this.options.source } }; this.groupCount += 1; return true; } if (typeof this.options.source.data !== 'undefined' || typeof this.options.source.url !== 'undefined') { this.options.source = { group: this.options.source }; } for (var group in this.options.source) { if (!this.options.source.hasOwnProperty(group)) continue; // Backward compatibility for source.url declaration if (typeof this.options.source[group] === "string" || this.options.source[group] instanceof Array) { this.options.source[group] = { url: this.options.source[group] }; } if (!this.options.source[group].data && !this.options.source[group].url) { // {debug} _debug.log({ 'node': this.node.selector, 'function': 'unifySourceFormat()', 'arguments': JSON.stringify(this.options.source), 'message': 'Undefined "options.source.' + group + '.[data|url]" is Missing - Typeahead dropped' }); _debug.print(); // {/debug} return false; } if (this.options.source[group].display && !(this.options.source[group].display instanceof Array)) { this.options.source[group].display = [this.options.source[group].display]; } if (this.options.source[group].ignore) { if (!(this.options.source[group].ignore instanceof RegExp)) { // {debug} _debug.log({ 'node': this.node.selector, 'function': 'unifySourceFormat()', 'arguments': JSON.stringify(this.options.source[group].ignore), 'message': 'Invalid ignore RegExp.' }); _debug.print(); // {/debug} delete this.options.source[group].ignore; } } this.groupCount += 1; } return true; }, init: function () { this.helper.executeCallback(this.options.callback.onInit, [this.node]); this.container = this.node.closest('.' + this.options.selector.container); // {debug} _debug.log({ 'node': this.node.selector, 'function': 'init()', //'arguments': JSON.stringify(this.options), 'message': 'OK - Typeahead activated on ' + this.node.selector }); _debug.print(); // {/debug} }, delegateEvents: function () { var scope = this, events = [ 'focus' + _namespace, 'input' + _namespace, 'propertychange' + _namespace, 'keydown' + _namespace, 'dynamic' + _namespace, 'generateOnLoad' + _namespace ]; this.container.off(_namespace).on("click" + _namespace + ' touchstart' + _namespace, function (e) { e.stopPropagation(); if (scope.options.dropdownFilter) { scope.container .find('.' + scope.options.selector.dropdown.replace(" ", ".")) .hide(); } }); this.node.closest('form').on("submit", function (e) { if (scope.options.mustSelectItem && scope.helper.isEmpty(scope.item)) { e.preventDefault(); return; } scope.hideLayout(); scope.rawQuery = ''; scope.query = ''; if (scope.helper.executeCallback(scope.options.callback.onSubmit, [scope.node, this, scope.item, e])) { return false; } }); // IE8 fix var preventNextEvent = false; this.node.off(_namespace).on(events.join(' '), function (e) { switch (e.type) { case "generateOnLoad": case "focus": if (scope.isGenerated && scope.options.searchOnFocus && scope.query.length >= scope.options.minLength) { scope.showLayout(); } if (scope.isGenerated === null && !scope.options.dynamic) { scope.generateSource(); } break; case "keydown": if (scope.isGenerated && scope.result.length) { if (e.keyCode && ~[13, 27, 38, 39, 40].indexOf(e.keyCode)) { preventNextEvent = true; scope.navigate(e); } } break; case "propertychange": if (preventNextEvent) { preventNextEvent = false; break; } case "input": scope.rawQuery = scope.node[0].value.toString(); scope.query = scope.node[0].value.replace(/^\s+/, '').toString(); if (scope.options.hint && scope.hint.container && scope.hint.container.val() !== '') { if (scope.hint.container.val().indexOf(scope.rawQuery) !== 0) { scope.hint.container.val('') } } if (scope.options.dynamic) { scope.isGenerated = null; scope.helper.typeWatch(function () { if (scope.query.length >= scope.options.minLength) { scope.generateSource(); } else { scope.hideLayout(); } }, scope.options.delay); return; } case "dynamic": if (!scope.isGenerated) { break; } if (scope.query.length < scope.options.minLength) { scope.hideLayout(); break; } scope.searchResult(); scope.buildLayout(); if (scope.result.length > 0 || scope.options.emptyTemplate) { scope.showLayout(); } else { scope.hideLayout(); } break; } }); if (this.options.generateOnLoad) { this.node.trigger('generateOnLoad' + _namespace); } }, generateSource: function () { if (this.isGenerated && !this.options.dynamic) { return; } this.generatedGroupCount = 0; this.isGenerated = false; if (!this.helper.isEmpty(this.xhr)) { for (var i in this.xhr) { if (!this.xhr.hasOwnProperty(i)) continue; this.xhr[i].abort(); } this.xhr = {}; } var group, dataInLocalstorage, isValidStorage; for (group in this.options.source) { if (!this.options.source.hasOwnProperty(group)) continue; // Get group source from Localstorage if (this.options.cache) { dataInLocalstorage = window.localStorage.getItem(this.node.selector + ":" + group); if (dataInLocalstorage) { if (this.options.compression) { dataInLocalstorage = LZString.decompressFromUTF16(dataInLocalstorage); } // In case the storage key:value are not readable anymore isValidStorage = false; try { dataInLocalstorage = JSON.parse(dataInLocalstorage + ""); if (dataInLocalstorage.data && dataInLocalstorage.ttl > new Date().getTime()) { this.populateSource(dataInLocalstorage.data, group); isValidStorage = true; // {debug} _debug.log({ 'node': this.node.selector, 'function': 'generateSource()', 'message': 'Source for group "' + group + '" found in localStorage.' }); _debug.print(); // {/debug} } else { window.localStorage.removeItem(this.node.selector + ":" + group); } } catch (error) { } if (isValidStorage) continue; } } // Get group source from data if (this.options.source[group].data && !this.options.source[group].url) { this.populateSource( typeof this.options.source[group].data === "function" && this.options.source[group].data() || this.options.source[group].data, group ); continue; } // Get group source from Ajax / JsonP if (this.options.source[group].url) { if (!this.requests[group]) { this.requests[group] = this.generateRequestObject(group); } } } this.handleRequests(); }, generateRequestObject: function (group) { var xhrObject = { request: { url: null, dataType: 'json' }, extra: { path: null, group: group, callback: { done: null, fail: null, complete: null, always: null } }, validForGroup: [group] }; if (!(this.options.source[group].url instanceof Array) && this.options.source[group].url instanceof Object) { this.options.source[group].url = [this.options.source[group].url]; } if (this.options.source[group].url instanceof Array) { if (this.options.source[group].url[0] instanceof Object) { if (this.options.source[group].url[0].callback) { xhrObject.extra.callback = this.options.source[group].url[0].callback; delete this.options.source[group].url[0].callback; } xhrObject.request = $.extend(true, xhrObject.request, this.options.source[group].url[0]); } else if (typeof this.options.source[group].url[0] === "string") { xhrObject.request.url = this.options.source[group].url[0]; } if (this.options.source[group].url[1] && typeof this.options.source[group].url[1] === "string") { xhrObject.extra.path = this.options.source[group].url[1]; } } else if (typeof this.options.source[group].url === "string") { xhrObject.request.url = this.options.source[group].url; } if (xhrObject.request.dataType.toLowerCase() === 'jsonp') { // JSONP needs unique jsonpCallback name to run concurrently xhrObject.request.jsonpCallback = 'callback_' + group; } var stringRequest; for (var _group in this.requests) { if (!this.requests.hasOwnProperty(_group)) continue; stringRequest = JSON.stringify(this.requests[_group].request); if (stringRequest === JSON.stringify(xhrObject.request)) { this.requests[_group].validForGroup.push(group); xhrObject.isDuplicated = true; delete xhrObject.validForGroup; break; } } return xhrObject; }, handleRequests: function () { var scope = this, requestsCount = Object.keys(this.requests).length; if (requestsCount) { this.helper.executeCallback(this.options.callback.onSendRequest, [this.node, this.query]); } for (var group in this.requests) { if (!this.requests.hasOwnProperty(group)) continue; if (this.requests[group].isDuplicated) continue; (function (group, xhrObject) { var _request; if (xhrObject.request.data) { for (var i in xhrObject.request.data) { if (!xhrObject.request.data.hasOwnProperty(i)) continue; if (~String(xhrObject.request.data[i]).indexOf('{{query}}')) { // Prevent the main request from being changed xhrObject = $.extend(true, {}, xhrObject); xhrObject.request.data[i] = xhrObject.request.data[i].replace('{{query}}', scope.query); break; } } } scope.xhr[group] = $.ajax(xhrObject.request).done(function (data, textStatus, jqXHR) { var tmpData; for (var i = 0; i < xhrObject.validForGroup.length; i++) { _request = scope.requests[xhrObject.validForGroup[i]]; if (_request.extra.callback.done instanceof Function) { tmpData = _request.extra.callback.done(data, textStatus, jqXHR); data = tmpData instanceof Array && tmpData || data; // {debug} if (!(tmpData instanceof Array)) { _debug.log({ 'node': scope.node.selector, 'function': 'Ajax.callback.done()', 'message': 'Invalid returned data has to be an Array' }); _debug.print(); } // {/debug} } scope.populateSource(data, _request.extra.group, _request.extra.path); requestsCount -= 1; if (requestsCount === 0) { scope.helper.executeCallback(scope.options.callback.onReceiveRequest, [scope.node, scope.query]); } } }).fail(function (jqXHR, textStatus, errorThrown) { for (var i = 0; i < xhrObject.validForGroup.length; i++) { _request = scope.requests[xhrObject.validForGroup[i]]; _request.extra.callback.fail instanceof Function && _request.extra.callback.fail(jqXHR, textStatus, errorThrown); } // {debug} _debug.log({ 'node': scope.node.selector, 'function': 'Ajax.callback.fail()', 'message': 'Request failed' }); _debug.print(); // {/debug} }).complete(function (jqXHR, textStatus) { for (var i = 0; i < xhrObject.validForGroup.length; i++) { _request = scope.requests[xhrObject.validForGroup[i]]; _request.extra.callback.complete instanceof Function && _request.extra.callback.complete(jqXHR, textStatus); } }).always(function (data, textStatus, jqXHR) { for (var i = 0; i < xhrObject.validForGroup.length; i++) { _request = scope.requests[xhrObject.validForGroup[i]]; _request.extra.callback.always instanceof Function && _request.extra.callback.always(data, textStatus, jqXHR); } }); }(group, this.requests[group])); } }, /** * Build the source groups to be cycled for matched results * * @param {Array} data Array of Strings or Array of Objects * @param {String} group * @param {String} [path] * @return {*} */ populateSource: function (data, group, path) { var extraData, tmpData; if (data && typeof path === "string") { var exploded = path.split('.'), splitIndex = 0; while (splitIndex < exploded.length) { tmpData = data[exploded[splitIndex++]]; if (typeof tmpData !== 'undefined') { data = tmpData; } else { // {debug} _debug.log({ 'node': this.node.selector, 'function': 'populateSource()', 'arguments': path, 'message': 'Invalid data path.' }); _debug.print(); // {/debug} break; } } } if (!(data instanceof Array)) { // {debug} _debug.log({ 'node': this.node.selector, 'function': 'populateSource()', 'arguments': JSON.stringify({group: group}), 'message': 'Invalid data type, must be Array type.' }); _debug.print(); // {/debug} data = []; } extraData = this.options.source[group].url && this.options.source[group].data; if (extraData) { if (typeof extraData === "function") { extraData = extraData(); } if (extraData instanceof Array) { data = data.concat(extraData); } // {debug} else { _debug.log({ 'node': this.node.selector, 'function': 'populateSource()', 'arguments': JSON.stringify(extraData), 'message': 'WARNING - this.options.source.' + group + '.data Must be an Array or a function that returns an Array.' }); _debug.print(); } // {/debug} } var tmpObj, display; if (this.options.source[group].display) { display = this.options.source[group].display[0]; } else { display = this.options.display[0]; } // @TODO: possibly optimize this? for (var i = 0; i < data.length; i++) { if (typeof data[i] === "string") { tmpObj = {}; tmpObj[display] = data[i]; data[i] = tmpObj; } } // @TODO: find a way to save the order from options.source so it appears correctly? this.source[group] = data; if (this.options.cache && !localStorage.getItem(this.node.selector + ":" + group)) { var storage = JSON.stringify({ data: data, ttl: new Date().getTime() + this.options.ttl }); if (this.options.compression) { storage = LZString.compressToUTF16(storage); } localStorage.setItem( this.node.selector + ":" + group, storage ); } this.incrementGeneratedGroup(); }, incrementGeneratedGroup: function () { this.generatedGroupCount += 1; if (this.groupCount !== this.generatedGroupCount) { return; } this.isGenerated = true; this.node.trigger('dynamic' + _namespace); }, /** * Key Navigation * Up 38: select previous item, skip "group" item * Down 40: select next item, skip "group" item * Right 39: change charAt, if last char fill hint (if options is true) * Esc 27: hideLayout * Enter 13: Select item + submit search * * @param {Object} e Event object * @returns {*} */ navigate: function (e) { this.helper.executeCallback(this.options.callback.onNavigate, [this.node, this.query, e]); var itemList = this.resultContainer.find('> ul > li:not([data-search-group])'), activeItem = itemList.filter('.active'), activeItemIndex = activeItem[0] && itemList.index(activeItem) || null; if (e.keyCode === 27) { e.preventDefault(); this.hideLayout(); return; } if (e.keyCode === 13) { if (activeItem.length > 0) { e.preventDefault(); e.stopPropagation(); activeItem.find('a:first').trigger('click'); return; } else { if (this.options.mustSelectItem && this.helper.isEmpty(this.item)) { return; } this.hideLayout(); return; } } if (e.keyCode === 39) { if (activeItemIndex) { itemList.eq(activeItemIndex).find('a:first').trigger('click'); } else if (this.options.hint && this.hint.container.val() !== "" && this.helper.getCaret(this.node[0]) >= this.query.length) { itemList.find('a[data-index="' + this.hintIndex + '"]').trigger('click'); } return; } if (itemList.length > 0) { activeItem.removeClass('active'); } if (e.keyCode === 38) { e.preventDefault(); if (activeItem.length > 0) { if (activeItemIndex - 1 >= 0) { itemList.eq(activeItemIndex - 1).addClass('active'); } } else { itemList.last().addClass('active'); } } else if (e.keyCode === 40) { e.preventDefault(); if (activeItem.length > 0) { if (activeItemIndex + 1 < itemList.length) { itemList.eq(activeItemIndex + 1).addClass('active'); } } else { itemList.first().addClass('active'); } } activeItem = itemList.filter('.active'); if (this.options.hint && this.hint.container) { if (activeItem.length > 0) { this.hint.container.css('color', this.hint.container.css('background-color') || 'fff'); } else { this.hint.container.css('color', this.hint.css.color) } } if (activeItem.length > 0) { var itemIndex = activeItem.find('a:first').attr('data-index'); itemIndex && this.node.val(this.result[itemIndex][this.result[itemIndex].matchedKey]); } else { this.node.val(this.rawQuery); } }, searchResult: function () { this.item = {}; this.helper.executeCallback(this.options.callback.onSearch, [this.node, this.query]); this.result = []; this.resultCount = 0; var scope = this, group, item, match, comparedDisplay, comparedQuery = this.query, itemPerGroup = {}, groupBy = this.filters.dropdown && this.filters.dropdown.key || this.groupBy, hasDynamicFilters = this.filters.dynamic && !this.helper.isEmpty(this.filters.dynamic), displayKeys, missingDisplayKey = {}, filter; if (this.options.accent) { comparedQuery = this.helper.removeAccent(comparedQuery); } for (group in this.source) { if (!this.source.hasOwnProperty(group)) continue; if (this.filters.dropdown && this.filters.dropdown.key === "group" && this.filters.dropdown.value !== group) continue; // @TODO, verify this if (this.options.maxItemPerGroup && groupBy === "group") { if (!itemPerGroup[group]) { itemPerGroup[group] = 0; } else if (itemPerGroup[group] >= this.options.maxItemPerGroup && !this.options.callback.onResult) { break; } } filter = typeof this.options.source[group].filter === "undefined" || this.options.source[group].filter === true; for (var k = 0; k < this.source[group].length; k++) { if (this.result.length >= this.options.maxItem && !this.options.callback.onResult) break; if (hasDynamicFilters && !this.dynamicFilter.validate.apply(this, [this.source[group][k]])) continue; item = this.source[group][k]; item.group = group; if (this.options.maxItemPerGroup && groupBy !== "group") { if (!itemPerGroup[item[groupBy]]) { itemPerGroup[item[groupBy]] = 0; } else if (itemPerGroup[item[groupBy]] >= this.options.maxItemPerGroup && !this.options.callback.onResult) { continue; } } displayKeys = this.options.source[group].display || this.options.display; for (var i = 0; i < displayKeys.length; i++) { if (filter) { comparedDisplay = item[displayKeys[i]]; if (!comparedDisplay) { // {debug} missingDisplayKey[i] = { display: displayKeys[i], data: item }; // {/debug} continue; } comparedDisplay = comparedDisplay.toString(); if (this.options.accent) { comparedDisplay = this.helper.removeAccent(comparedDisplay); } match = comparedDisplay.toLowerCase().indexOf(comparedQuery.toLowerCase()) + 1; if (!match) continue; if (match && this.options.offset && match !== 1) continue; if (this.options.source[group].ignore && this.options.source[group].ignore.test(comparedDisplay)) continue; } if (this.filters.dropdown) { if (this.filters.dropdown.value != item[this.filters.dropdown.key]) continue; } this.resultCount += 1; if ((this.options.callback.onResult && this.result.length >= this.options.maxItem) || this.options.maxItemPerGroup && itemPerGroup[item[groupBy]] >= this.options.maxItemPerGroup ) { break; } item.matchedKey = displayKeys[i]; this.result.push(item); if (this.options.maxItemPerGroup) { itemPerGroup[item[groupBy]] += 1; } break; } } } // {debug} if (!this.helper.isEmpty(missingDisplayKey)) { _debug.log({ 'node': this.node.selector, 'function': 'searchResult()', 'arguments': JSON.stringify(missingDisplayKey), 'message': 'Missing keys for display, make sure options.display is set properly.' }); _debug.print(); } // {/debug} if (this.options.order) { var displayKeys = [], displayKey; for (var i = 0; i < this.result.length; i++) { displayKey = this.options.source[this.result[i].group].display || this.options.display; if (!~displayKeys.indexOf(displayKey[0])) { displayKeys.push(displayKey[0]); } } this.result.sort( scope.helper.sort( displayKeys, scope.options.order === "asc", function (a) { return a.toString().toUpperCase() } ) ); } this.helper.executeCallback(this.options.callback.onResult, [this.node, this.query, this.result, this.resultCount]); }, buildLayout: function () { if (!this.resultContainer) { this.resultContainer = $("<div/>", { "class": this.options.selector.result }); this.container.append(this.resultContainer); } // Reused.. var _query = this.query.toLowerCase(); if (this.options.accent) { _query = this.helper.removeAccent(_query); } var scope = this, resultHtmlList = $("<ul/>", { "class": this.options.selector.list + (scope.helper.isEmpty(scope.result) ? ' empty' : ''), "html": function () { if (scope.options.emptyTemplate && scope.helper.isEmpty(scope.result)) { return $("<li/>", { "html": $("<a/>", { "href": "javascript:;", "html": typeof scope.options.emptyTemplate === "function" && scope.options.emptyTemplate(scope.query) || scope.options.emptyTemplate.replace(/\{\{query}}/gi, scope.query) }) }); } for (var i in scope.result) { if (!scope.result.hasOwnProperty(i)) continue; (function (index, item, ulScope) { var _group = item.group, _liHtml, _aHtml, _display = {}, _displayKeys = scope.options.source[item.group].display || scope.options.display, _href = scope.options.source[item.group].href || scope.options.href, _displayKey, _handle, _template; if (scope.options.group) { if (typeof scope.options.group[0] !== "boolean" && item[scope.options.group[0]]) { _group = item[scope.options.group[0]]; } if (!$(ulScope).find('li[data-search-group="' + _group + '"]')[0]) { $(ulScope).append( $("<li/>", { "class": scope.options.selector.group, "html": $("<a/>", { "href": "javascript:;", "html": scope.options.group[1] && scope.options.group[1].replace(/(\{\{group}})/gi, item[scope.options.group[0]] || _group) || _group }), "data-search-group": _group }) ); } } for (var i = 0; i < _displayKeys.length; i++) { _displayKey = _displayKeys[i]; _display[_displayKey] = item[_displayKey]; if (scope.options.highlight) { if (_display[_displayKey]) { _display[_displayKey] = scope.helper.highlight(_display[_displayKey], _query, scope.options.accent); } // {debug} else { _debug.log({ 'node': scope.node.selector, 'function': 'buildLayout()', 'arguments': JSON.stringify(item), 'message': 'WARNING - Missing display key: "' + _displayKey + '"' }); _debug.print(); } // {/debug} } } _liHtml = $("<li/>", { "html": $("<a/>", { "href": function () { if (_href) { if (typeof _href === "string") { _href = _href.replace(/\{\{([a-z0-9_\-\.]+)\|?(\w+)?}}/gi, function (match, index, option) { var value = scope.helper.namespace(index, item, 'get') || match; if (option && option === "raw") { return value; } return value !== match && scope.helper.slugify(value) || value; }); } else if (typeof _href === "function") { _href = _href(item); } item['href'] = _href; } return _href || "javascript:;"; }, "data-group": _group, "data-index": index, "html": function () { _template = (item.group && scope.options.source[item.group].template) || scope.options.template; if (_template) { _aHtml = _template.replace(/\{\{([a-z0-9_\-\.]+)\|?(\w+)?}}/gi, function (match, index, option) { var value = scope.helper.namespace(index, item, 'get') || match; if (option && option === "raw") { return value; } return scope.helper.namespace(index, _display, 'get') || value; }); } else { _aHtml = '<span class="' + scope.options.selector.display + '">' + scope.helper.joinObject(_display, " ") + '</span>'; } $(this).append(_aHtml); }, "click": ({"item": item}, function (e) { if (scope.options.mustSelectItem && scope.helper.isEmpty(item)) { e.preventDefault(); return; } scope.helper.executeCallback(scope.options.callback.onClickBefore, [scope.node, this, item, e]); if (e.isDefaultPrevented()) { return; } e.preventDefault(); scope.query = scope.rawQuery = item[item.matchedKey].toString(); scope.node.val(scope.query).focus(); scope.searchResult(); scope.buildLayout(); scope.hideLayout(); scope.item = item; scope.helper.executeCallback(scope.options.callback.onClickAfter, [scope.node, this, item, e]); }), "mouseenter": function (e) { $(this).closest('ul').find('li.active').removeClass('active'); $(this).closest('li').addClass('active'); scope.helper.executeCallback(scope.options.callback.onMouseEnter, [scope.node, this, item, e]); }, "mouseleave": function (e) { $(this).closest('li').removeClass('active'); scope.helper.executeCallback(scope.options.callback.onMouseLeave, [scope.node, this, item, e]); } }) }); if (scope.options.group) { _handle = $(ulScope).find('a[data-group="' + _group + '"]:last').closest('li'); if (!_handle[0]) { _handle = $(ulScope).find('li[data-search-group="' + _group + '"]'); } $(_liHtml).insertAfter(_handle); } else { $(ulScope).append(_liHtml); } }(i, scope.result[i], this)); } } }); if (this.options.callback.onLayoutBuiltBefore) { var tmpResultHtmlList = this.helper.executeCallback(this.options.callback.onLayoutBuiltBefore, [this.node, this.query, this.result, resultHtmlList]); if (tmpResultHtmlList instanceof jQuery) { resultHtmlList = tmpResultHtmlList; } // {debug} else { _debug.log({ 'node': this.node.selector, 'function': 'callback.onLayoutBuiltBefore()', 'message': 'Invalid returned value - You must return resultHtmlList jQuery Object' }); _debug.print(); } // {/debug} } this.container.addClass('result'); this.resultContainer .html(resultHtmlList); if (this.options.callback.onLayoutBuiltAfter) { this.helper.executeCallback(this.options.callback.onLayoutBuiltAfter, [this.node, this.query, this.result]); } if (this.options.backdrop) { if (this.backdrop.container) { this.backdrop.container.show(); } else { this.backdrop.css = $.extend( { "opacity": 0.6, "filter": 'alpha(opacity=60)', "position": 'fixed', "top": 0, "right": 0, "bottom": 0, "left": 0, "z-index": 1040, "background-color": "#000" }, this.options.backdrop ); this.backdrop.container = $("<div/>", { "class": this.options.selector.backdrop, "css": this.backdrop.css, "click": function () { scope.hideLayout(); } }).insertAfter(this.container); } this.container .addClass('backdrop') .css({ "z-index": this.backdrop.css["z-index"] + 1, "position": "relative" }); } if (this.options.hint) { var _hint = ""; if (this.result.length > 0 && this.query.length > 0) { if (!this.hint.container) { this.hint.css = $.extend({ "border-color": "transparent", "position": "absolute", "top": 0, "display": "inline", "z-index": -1, "float": "none", "color": "silver", "box-shadow": "none", "cursor": "default", "-webkit-user-select": "none", "-moz-user-select": "none", "-ms-user-select": "none", "user-select": "none" }, this.options.hint ); this.hint.container = $('<input/>', { 'type': this.node.attr('type'), 'class': this.node.attr('class'), 'readonly': true, 'unselectable': 'on', 'tabindex': -1, 'click': function () { // IE8 Fix scope.node.focus(); } }).addClass(_options.selector.hint) .css(this.hint.css) .insertAfter(this.node) this.node.parent().css({ "position": "relative" }); } this.hint.container.css('color', this.hint.css.color) var _displayKeys, _group, _comparedValue; this.hintIndex = null; for (var i = 0; i < this.result.length; i++) { _group = this.result[i].group; _displayKeys = scope.options.source[_group].display || scope.options.display; for (var k = 0; k < _displayKeys.length; k++) { _comparedValue = String(this.result[i][_displayKeys[k]]).toLowerCase(); if (this.options.accent) { _comparedValue = this.helper.removeAccent(_comparedValue); } if (_comparedValue.indexOf(_query) === 0) { _hint = String(this.result[i][_displayKeys[k]]); this.hintIndex = i; break; } } if (this.hintIndex !== null) { break; } } } if (this.hint.container) { this.hint.container .val(_hint.length > 0 && this.rawQuery + _hint.substring(this.query.length) || "") .show(); } } }, buildDropdownLayout: function () { if (!this.options.dropdownFilter) { return; } var scope = this, defaultText; if (typeof this.options.dropdownFilter === "boolean") { defaultText = "all"; } else if (typeof this.options.dropdownFilter === "string") { defaultText = this.options.dropdownFilter } else if (this.options.dropdownFilter instanceof Array) { for (var i = 0; i < this.options.dropdownFilter.length; i++) { if (this.options.dropdownFilter[i].value === "*" && this.options.dropdownFilter[i].display) { defaultText = this.options.dropdownFilter[i].display; break; } } } $('<span/>', { "class": this.options.selector.filter, "html": function () { $(this).append( $('<button/>', { "type": "button", "class": scope.options.selector.filterButton, "html": "<span class='" + scope.options.selector.filterValue + "'>" + defaultText + "</span> <span class='" + scope.options.selector.dropdownCarret + "'></span>", "click": function (e) { e.stopPropagation(); var filterContainer = scope.container.find('.' + scope.options.selector.dropdown.replace(" ", ".")); if (!filterContainer.is(':visible')) { scope.container.addClass('filter'); filterContainer.show(); $('html').off(_namespace + ".dropdownFilter") .on("click" + _namespace + ".dropdownFilter" + ' touchstart' + _namespace + ".dropdownFilter", function () { scope.container.removeClass('filter'); filterContainer.hide(); $(this).off(_namespace + ".dropdownFilter"); }); } else { scope.container.removeClass('filter'); filterContainer.hide(); $('html').off(_namespace + ".dropdownFilter"); } } }) ); $(this).append( $('<ul/>', { "class": scope.options.selector.dropdown, "html": function () { var items = scope.options.dropdownFilter; if (~['string', 'boolean'].indexOf(typeof scope.options.dropdownFilter)) { items = []; for (var group in scope.options.source) { if (!scope.options.source.hasOwnProperty(group)) continue; items.push({ key: 'group', value: group }); } items.push({ key: 'group', value: '*', display: typeof scope.options.dropdownFilter === "string" && scope.options.dropdownFilter || 'All' }); } for (var i = 0; i < items.length; i++) { (function (i, item, ulScope) { if ((!item.key && item.value !== "*") || !item.value) { // {debug} _debug.log({ 'node': scope.node.selector, 'function': 'buildDropdownLayout()', 'arguments': JSON.stringify(item), 'message': 'WARNING - Missing key or value, skipping dropdown filter."' }); _debug.print(); // {/debug} return; } if (item.value === '*') { $(ulScope).append( $("<li/>", { "class": "divider" }) ); } $(ulScope).append( $("<li/>", { "html": $("<a/>", { "href": "javascript:;", "html": item.display || item.value, "click": ({"item": item}, function (e) { e.preventDefault(); _selectFilter.apply(scope, [item]); }) }) }) ); }(i, items[i], this)); } } }) ); } }).insertAfter(scope.container.find('.' + scope.options.selector.query)); /** * @private * Select the filter and rebuild the result group * * @param {string} item */ function _selectFilter(item) { if (item.value === "*") { delete this.filters.dropdown; } else { this.filters.dropdown = item; } this.container .removeClass('filter') .find('.' + this.options.selector.filterValue) .html(item.display || item.value); this.node.trigger('dynamic' + _namespace); this.node.focus(); } }, dynamicFilter: { validate: function (item) { var isValid, softValid = null, hardValid = null, itemValue; for (var key in this.filters.dynamic) { if (!this.filters.dynamic.hasOwnProperty(key)) continue; if (!!~key.indexOf('.')) { itemValue = this.helper.namespace(key, item, 'get'); } else { itemValue = item[key]; } if (this.filters.dynamic[key].modifier === '|' && !softValid) { softValid = itemValue == this.filters.dynamic[key].value || false; } if (this.filters.dynamic[key].modifier === '&') { // Leaving "==" in case of comparing number with string if (itemValue == this.filters.dynamic[key].value) { hardValid = true; } else { hardValid = false; break; } } } isValid = softValid; if (hardValid !== null) { isValid = hardValid; if (hardValid === true && softValid !== null) { isValid = softValid; } } return !!isValid; }, set: function (key, value) { var matches = key.match(/^([|&])?(.+)/); if (!value) { delete this.filters.dynamic[matches[2]]; } else { this.filters.dynamic[matches[2]] = { modifier: matches[1] || '|', value: value }; } this.searchResult(); this.buildLayout(); }, bind: function () { if (!this.options.dynamicFilter) { return; } var scope = this; var filter; for (var i = 0; i < this.options.dynamicFilter.length; i++) { filter = this.options.dynamicFilter[i]; if (typeof filter.selector === "string") { filter.selector = $(filter.selector); } if (!(filter.selector instanceof jQuery) || !filter.selector[0] || !filter.key) { // {debug} _debug.log({ 'node': this.node.selector, 'function': 'buildDynamicLayout()', 'message': 'Invalid jQuery selector or jQuery Object for "filter.selector" or missing filter.key' }); _debug.print(); // {/debug} continue; } (function (filter) { filter.selector.off(_namespace).on('change' + _namespace, function () { scope.dynamicFilter.set.apply(scope, [filter.key, scope.dynamicFilter.getValue(this)]); }).trigger('change' + _namespace); }(filter)); } }, getValue: function (tag) { var value; if (tag.tagName === "SELECT") { value = tag.value; } else if (tag.tagName === "INPUT") { if (tag.type === "checkbox") { value = tag.checked || null; } else if (tag.type === "radio" && tag.checked) { value = tag.value; } } return value; } }, showLayout: function () { var scope = this; $('html').off(_namespace).on("click" + _namespace + " touchstart" + _namespace, function () { scope.hideLayout(); $(this).off(_namespace); }); // Do not add display classes if there are no results if (!this.result.length && !this.options.emptyTemplate) { return; } this.container.addClass('result hint backdrop'); }, hideLayout: function () { this.container.removeClass('result hint backdrop filter'); }, __construct: function () { this.extendOptions(); if (!this.unifySourceFormat()) { return; } this.init(); this.delegateEvents(); this.buildDropdownLayout(); this.dynamicFilter.bind.apply(this); this.helper.executeCallback(this.options.callback.onReady, [this.node]); }, helper: { isEmpty: function (obj) { for (var prop in obj) { if (obj.hasOwnProperty(prop)) return false; } return true; }, /** * Remove every accent(s) from a string * * @param {String} string * @returns {*} */ removeAccent: function (string) { if (typeof string !== "string") { return; } string = string.toLowerCase().replace(new RegExp('[' + _accent.from + ']', 'g'), function (match) { return _accent.to[_accent.from.indexOf(match)]; }); return string; }, /** * Creates a valid url from string * * @param {String} string * @returns {string} */ slugify: function (string) { string = this.removeAccent(string); string = string.replace(/[^-a-z0-9]+/g, '-').replace(/-+/g, '-').trim('-'); return string; }, /** * Sort list of object by key * * @param {String|Array} field * @param {Boolean} reverse * @param {Function} primer * @returns {Function} */ sort: function (field, reverse, primer) { var key = function (x) { for (var i = 0; i < field.length; i++) { if (typeof x[field[i]] !== 'undefined') { return primer(x[field[i]]) } } }; reverse = [-1, 1][+!!reverse]; return function (a, b) { return a = key(a), b = key(b), reverse * ((a > b) - (b > a)); } }, /** * Replace a string from-to index * * @param {String} string The complete string to replace into * @param {Number} offset The cursor position to start replacing from * @param {Number} length The length of the replacing string * @param {String} replace The replacing string * @returns {String} */ replaceAt: function (string, offset, length, replace) { return string.substring(0, offset) + replace + string.substring(offset + length); }, /** * Adds <strong> html around a matched string * * @param {String} string The complete string to match from * @param {String} key * @param {Boolean} [accents] * @returns {*} */ highlight: function (string, key, accents) { string = String(string); var offset = string.toLowerCase().indexOf(key.toLowerCase()); if (accents) { offset = this.removeAccent(string).indexOf(this.removeAccent(key)); } if (offset === -1 || key.length === 0) { return string; } return this.replaceAt( string, offset, key.length, "<strong>" + string.substr(offset, key.length) + "</strong>" ); }, joinObject: function (object, join) { var string = "", iteration = 0; for (var i in object) { if (!object.hasOwnProperty(i)) continue; if (iteration !== 0) { string += join; } string += object[i]; iteration++; } return string; }, /** * Get carret position, mainly used for right arrow navigation * @param element * @returns {*} */ getCaret: function (element) { if (element.selectionStart) { return element.selectionStart; } else if (document.selection) { element.focus(); var r = document.selection.createRange(); if (r == null) { return 0; } var re = element.createTextRange(), rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart', re); return rc.text.length; } return 0; }, /** * Executes an anonymous function or a string reached from the window scope. * * @example * Note: These examples works with every configuration callbacks * * // An anonymous function inside the "onInit" option * onInit: function() { console.log(':D'); }; * * // myFunction() located on window.coucou scope * onInit: 'window.coucou.myFunction' * * // myFunction(a,b) located on window.coucou scope passing 2 parameters * onInit: ['window.coucou.myFunction', [':D', ':)']]; * * // Anonymous function to execute a local function * onInit: function () { myFunction(':D'); } * * @param {String|Array} callback The function to be called * @param {Array} [extraParams] In some cases the function can be called with Extra parameters (onError) * @returns {Boolean} */ executeCallback: function (callback, extraParams) { if (!callback) { return false; } var _callback, _node = extraParams[0]; if (typeof callback === "function") { _callback = callback; } else if (typeof callback === "string" || callback instanceof Array) { if (typeof callback === "string") { callback = [callback, []]; } //_callback = this.helper.getObjectRecursionProperty(window, callback[0]); _callback = this.helper.namespace(callback[0], window, 'get'); if (typeof _callback !== "function") { // {debug} _debug.log({ 'node': _node.selector, 'function': 'executeCallback()', 'arguments': JSON.stringify(callback), 'message': 'WARNING - Invalid callback function"' }); _debug.print(); // {/debug} return false; } } return _callback.apply(this, $.merge(callback[1] || [], (extraParams) ? extraParams : [])) || true; }, namespace: function (namespaceString, objectReference, method, objectValue) { if (typeof namespaceString !== "string" || namespaceString === "") { window.debug('window.namespace.' + method + ' - Missing namespaceString.'); return false; } var parts = namespaceString.split('.'), parent = objectReference || window, value = objectValue || {}, currentPart = ''; for (var i = 0, length = parts.length; i < length; i++) { currentPart = parts[i]; if (!parent[currentPart]) { if (~['get', 'delete'].indexOf(method)) { return false; } parent[currentPart] = {}; } if (~['set', 'create', 'delete'].indexOf(method)) { if (i === length - 1) { if (method === 'set' || method === 'create') { parent[currentPart] = value; } else { delete parent[currentPart]; return true; } } } parent = parent[currentPart]; } return parent; }, typeWatch: (function () { var timer = 0; return function (callback, ms) { clearTimeout(timer); timer = setTimeout(callback, ms); } })() } }; /** * @public * Implement Typeahead on the selected input node. * * @param {Object} options * @return {Object} Modified DOM element */ $.fn.typeahead = $.typeahead = function (options) { return _api.typeahead(this, options); }; /** * @private * API to handles Typeahead methods via jQuery. */ var _api = { /** * Enable Typeahead * * @param {Object} node * @param {Object} options * @returns {*} */ typeahead: function (node, options) { if (!options || !options.source || typeof options.source !== 'object') { // {debug} _debug.log({ 'node': node.selector || options && options.input, 'function': '$.typeahead()', 'arguments': JSON.stringify(options && options.source || ''), 'message': 'Undefined "options" or "options.source" or invalid source type - Typeahead dropped' }); _debug.print(); // {/debug} return; } if (typeof node === "function") { if (!options.input) { // {debug} _debug.log({ 'node': node.selector, 'function': '$.typeahead()', //'arguments': JSON.stringify(options), 'message': 'Undefined "options.input" - Typeahead dropped' }); _debug.print(); // {/debug} return; } node = $(options.input); } if (node.length !== 1) { // {debug} _debug.log({ 'node': node.selector, 'function': '$.typeahead()', 'arguments': JSON.stringify(options.input), 'message': 'Unable to find jQuery input element OR more than 1 input is found - Typeahead dropped' }); _debug.print(); // {/debug} return; } return window.Typeahead[node.selector] = new Typeahead(node, options); } }; // {debug} var _debug = { table: {}, log: function (debugObject) { if (!debugObject.message || typeof debugObject.message !== "string") { return; } this.table[debugObject.message] = $.extend({ 'node': '', 'function': '', 'arguments': '' }, debugObject) }, print: function () { if (Typeahead.prototype.helper.isEmpty(this.table) || !console || !console.table) { return; } if (console.group !== undefined || console.table !== undefined) { console.groupCollapsed('--- jQuery Typeahead Debug ---'); console.table(this.table); console.groupEnd(); } this.table = {}; } }; // {/debug} // IE8 Shims window.console = window.console || { log: function () { } }; if (!('trim' in String.prototype)) { String.prototype.trim = function () { return this.replace(/^\s+/, '').replace(/\s+$/, ''); }; } if (!('indexOf' in Array.prototype)) { Array.prototype.indexOf = function (find, i /*opt*/) { if (i === undefined) i = 0; if (i < 0) i += this.length; if (i < 0) i = 0; for (var n = this.length; i < n; i++) if (i in this && this[i] === find) return i; return -1; }; } if (!Object.keys) { Object.keys = function (obj) { var keys = [], k; for (k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) { keys.push(k); } } return keys; }; } }(window, document, window.jQuery));
gpl-3.0
pymelibre/age-of-companies
client/www/lib/auth0-lock/src/index.js
1019
import Auth0 from 'auth0-js'; import Core from './core'; import classic from './engine/classic'; import css from '../css/index.css'; const styleId = "auth0-lock-style"; let style = document.getElementById(styleId); if (!style) { const head = document.getElementsByTagName("head")[0]; style = document.createElement("style"); style.type = "text/css"; style.setAttribute("id", styleId); head.appendChild(style); } if (style.styleSheet) { style.styleSheet.cssText = css; } else { style.innerHTML = css; } export default class Auth0Lock extends Core { constructor(clientID, domain, options) { super(clientID, domain, options, classic); } } // telemetry Auth0Lock.version = __VERSION__; Auth0.clientInfo.lib_version = Auth0.clientInfo.version; Auth0.clientInfo.name = "lock.js"; Auth0.clientInfo.version = Auth0Lock.version; // TODO: should we have different telemetry for classic/passwordless? // TODO: should we set telemetry info before each request? // TODO: should we inject styles here?
gpl-3.0
nipunn1313/parity
rpc/src/v1/helpers/poll_manager.rs
3153
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Indexes all rpc poll requests. use transient_hashmap::{TransientHashMap, Timer, StandardTimer}; /// Lifetime of poll (in seconds). const POLL_LIFETIME: u32 = 60; pub type PollId = usize; /// Indexes all poll requests. /// /// Lazily garbage collects unused polls info. pub struct PollManager<F, T = StandardTimer> where T: Timer { polls: TransientHashMap<PollId, F, T>, next_available_id: PollId, } impl<F> PollManager<F, StandardTimer> { /// Creates new instance of indexer. pub fn new() -> Self { PollManager::new_with_timer(Default::default()) } } impl<F, T> PollManager<F, T> where T: Timer { pub fn new_with_timer(timer: T) -> Self { PollManager { polls: TransientHashMap::new_with_timer(POLL_LIFETIME, timer), next_available_id: 0, } } /// Returns id which can be used for new poll. /// /// Stores information when last poll happend. pub fn create_poll(&mut self, filter: F) -> PollId { self.polls.prune(); let id = self.next_available_id; self.polls.insert(id, filter); self.next_available_id += 1; id } // Implementation is always using `poll_mut` /// Get a reference to stored poll filter pub fn poll(&mut self, id: &PollId) -> Option<&F> { self.polls.prune(); self.polls.get(id) } /// Get a mutable reference to stored poll filter pub fn poll_mut(&mut self, id: &PollId) -> Option<&mut F> { self.polls.prune(); self.polls.get_mut(id) } /// Removes poll info. pub fn remove_poll(&mut self, id: &PollId) { self.polls.remove(id); } } #[cfg(test)] mod tests { use std::cell::Cell; use transient_hashmap::Timer; use v1::helpers::PollManager; struct TestTimer<'a> { time: &'a Cell<i64>, } impl<'a> Timer for TestTimer<'a> { fn get_time(&self) -> i64 { self.time.get() } } #[test] fn test_poll_indexer() { let time = Cell::new(0); let timer = TestTimer { time: &time, }; let mut indexer = PollManager::new_with_timer(timer); assert_eq!(indexer.create_poll(20), 0); assert_eq!(indexer.create_poll(20), 1); time.set(10); *indexer.poll_mut(&0).unwrap() = 21; assert_eq!(*indexer.poll(&0).unwrap(), 21); assert_eq!(*indexer.poll(&1).unwrap(), 20); time.set(30); *indexer.poll_mut(&1).unwrap() = 23; assert_eq!(*indexer.poll(&1).unwrap(), 23); time.set(75); assert!(indexer.poll(&0).is_none()); assert_eq!(*indexer.poll(&1).unwrap(), 23); indexer.remove_poll(&1); assert!(indexer.poll(&1).is_none()); } }
gpl-3.0
Pike/elmo
apps/elmo_commons/tests/__init__.py
26
# deliberately left empty
mpl-2.0
monkeylittleinc/packer
builder/qemu/step_type_boot_command.go
10431
package qemu import ( "fmt" "log" "net" "regexp" "strings" "time" "unicode" "unicode/utf8" "github.com/mitchellh/go-vnc" "github.com/mitchellh/multistep" "github.com/mitchellh/packer/packer" "github.com/mitchellh/packer/template/interpolate" ) const KeyLeftShift uint32 = 0xFFE1 type bootCommandTemplateData struct { HTTPIP string HTTPPort uint Name string } // This step "types" the boot command into the VM over VNC. // // Uses: // config *config // http_port int // ui packer.Ui // vnc_port uint // // Produces: // <nothing> type stepTypeBootCommand struct{} func (s *stepTypeBootCommand) Run(state multistep.StateBag) multistep.StepAction { config := state.Get("config").(*Config) debug := state.Get("debug").(bool) httpPort := state.Get("http_port").(uint) ui := state.Get("ui").(packer.Ui) vncPort := state.Get("vnc_port").(uint) var pauseFn multistep.DebugPauseFn if debug { pauseFn = state.Get("pauseFn").(multistep.DebugPauseFn) } // Connect to VNC ui.Say("Connecting to VM via VNC") nc, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", vncPort)) if err != nil { err := fmt.Errorf("Error connecting to VNC: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } defer nc.Close() c, err := vnc.Client(nc, &vnc.ClientConfig{Exclusive: false}) if err != nil { err := fmt.Errorf("Error handshaking with VNC: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } defer c.Close() log.Printf("Connected to VNC desktop: %s", c.DesktopName) ctx := config.ctx ctx.Data = &bootCommandTemplateData{ "10.0.2.2", httpPort, config.VMName, } ui.Say("Typing the boot command over VNC...") for i, command := range config.BootCommand { command, err := interpolate.Render(command, &ctx) if err != nil { err := fmt.Errorf("Error preparing boot command: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } // Check for interrupts between typing things so we can cancel // since this isn't the fastest thing. if _, ok := state.GetOk(multistep.StateCancelled); ok { return multistep.ActionHalt } if pauseFn != nil { pauseFn(multistep.DebugLocationAfterRun, fmt.Sprintf("boot_command[%d]: %s", i, command), state) } vncSendString(c, command) } return multistep.ActionContinue } func (*stepTypeBootCommand) Cleanup(multistep.StateBag) {} func vncSendString(c *vnc.ClientConn, original string) { // Scancodes reference: https://github.com/qemu/qemu/blob/master/ui/vnc_keysym.h special := make(map[string]uint32) special["<bs>"] = 0xFF08 special["<del>"] = 0xFFFF special["<enter>"] = 0xFF0D special["<esc>"] = 0xFF1B special["<f1>"] = 0xFFBE special["<f2>"] = 0xFFBF special["<f3>"] = 0xFFC0 special["<f4>"] = 0xFFC1 special["<f5>"] = 0xFFC2 special["<f6>"] = 0xFFC3 special["<f7>"] = 0xFFC4 special["<f8>"] = 0xFFC5 special["<f9>"] = 0xFFC6 special["<f10>"] = 0xFFC7 special["<f11>"] = 0xFFC8 special["<f12>"] = 0xFFC9 special["<return>"] = 0xFF0D special["<tab>"] = 0xFF09 special["<up>"] = 0xFF52 special["<down>"] = 0xFF54 special["<left>"] = 0xFF51 special["<right>"] = 0xFF53 special["<spacebar>"] = 0x020 special["<insert>"] = 0xFF63 special["<home>"] = 0xFF50 special["<end>"] = 0xFF57 special["<pageUp>"] = 0xFF55 special["<pageDown>"] = 0xFF56 special["<leftAlt>"] = 0xFFE9 special["<leftCtrl>"] = 0xFFE3 special["<leftShift>"] = 0xFFE1 special["<rightAlt>"] = 0xFFEA special["<rightCtrl>"] = 0xFFE4 special["<rightShift>"] = 0xFFE2 shiftedChars := "~!@#$%^&*()_+{}|:\"<>?" // TODO(mitchellh): Ripe for optimizations of some point, perhaps. for len(original) > 0 { var keyCode uint32 keyShift := false if strings.HasPrefix(original, "<leftAltOn>") { keyCode = special["<leftAlt>"] original = original[len("<leftAltOn>"):] log.Printf("Special code '<leftAltOn>' found, replacing with: %d", keyCode) c.KeyEvent(keyCode, true) time.Sleep(time.Second / 10) // qemu is picky, so no matter what, wait a small period time.Sleep(100 * time.Millisecond) continue } if strings.HasPrefix(original, "<leftCtrlOn>") { keyCode = special["<leftCtrlOn>"] original = original[len("<leftCtrlOn>"):] log.Printf("Special code '<leftCtrlOn>' found, replacing with: %d", keyCode) c.KeyEvent(keyCode, true) time.Sleep(time.Second / 10) // qemu is picky, so no matter what, wait a small period time.Sleep(100 * time.Millisecond) continue } if strings.HasPrefix(original, "<leftShiftOn>") { keyCode = special["<leftShiftOn>"] original = original[len("<leftShiftOn>"):] log.Printf("Special code '<leftShiftOn>' found, replacing with: %d", keyCode) c.KeyEvent(keyCode, true) time.Sleep(time.Second / 10) // qemu is picky, so no matter what, wait a small period time.Sleep(100 * time.Millisecond) continue } if strings.HasPrefix(original, "<leftAltOff>") { keyCode = special["<leftAltOff>"] original = original[len("<leftAltOff>"):] log.Printf("Special code '<leftAltOff>' found, replacing with: %d", keyCode) c.KeyEvent(keyCode, false) time.Sleep(time.Second / 10) // qemu is picky, so no matter what, wait a small period time.Sleep(100 * time.Millisecond) continue } if strings.HasPrefix(original, "<leftCtrlOff>") { keyCode = special["<leftCtrlOff>"] original = original[len("<leftCtrlOff>"):] log.Printf("Special code '<leftCtrlOff>' found, replacing with: %d", keyCode) c.KeyEvent(keyCode, false) time.Sleep(time.Second / 10) // qemu is picky, so no matter what, wait a small period time.Sleep(100 * time.Millisecond) continue } if strings.HasPrefix(original, "<leftShiftOff>") { keyCode = special["<leftShiftOff>"] original = original[len("<leftShiftOff>"):] log.Printf("Special code '<leftShiftOff>' found, replacing with: %d", keyCode) c.KeyEvent(keyCode, false) time.Sleep(time.Second / 10) // qemu is picky, so no matter what, wait a small period time.Sleep(100 * time.Millisecond) continue } if strings.HasPrefix(original, "<rightAltOn>") { keyCode = special["<rightAltOn>"] original = original[len("<rightAltOn>"):] log.Printf("Special code '<rightAltOn>' found, replacing with: %d", keyCode) c.KeyEvent(keyCode, true) time.Sleep(time.Second / 10) // qemu is picky, so no matter what, wait a small period time.Sleep(100 * time.Millisecond) continue } if strings.HasPrefix(original, "<rightCtrlOn>") { keyCode = special["<rightCtrlOn>"] original = original[len("<rightCtrlOn>"):] log.Printf("Special code '<rightCtrlOn>' found, replacing with: %d", keyCode) c.KeyEvent(keyCode, true) time.Sleep(time.Second / 10) // qemu is picky, so no matter what, wait a small period time.Sleep(100 * time.Millisecond) continue } if strings.HasPrefix(original, "<rightShiftOn>") { keyCode = special["<rightShiftOn>"] original = original[len("<rightShiftOn>"):] log.Printf("Special code '<rightShiftOn>' found, replacing with: %d", keyCode) c.KeyEvent(keyCode, true) time.Sleep(time.Second / 10) // qemu is picky, so no matter what, wait a small period time.Sleep(100 * time.Millisecond) continue } if strings.HasPrefix(original, "<rightAltOff>") { keyCode = special["<rightAltOff>"] original = original[len("<rightAltOff>"):] log.Printf("Special code '<rightAltOff>' found, replacing with: %d", keyCode) c.KeyEvent(keyCode, false) time.Sleep(time.Second / 10) // qemu is picky, so no matter what, wait a small period time.Sleep(100 * time.Millisecond) continue } if strings.HasPrefix(original, "<rightCtrlOff>") { keyCode = special["<rightCtrlOff>"] original = original[len("<rightCtrlOff>"):] log.Printf("Special code '<rightCtrlOff>' found, replacing with: %d", keyCode) c.KeyEvent(keyCode, false) time.Sleep(time.Second / 10) // qemu is picky, so no matter what, wait a small period time.Sleep(100 * time.Millisecond) continue } if strings.HasPrefix(original, "<rightShiftOff>") { keyCode = special["<rightShiftOff>"] original = original[len("<rightShiftOff>"):] log.Printf("Special code '<rightShiftOff>' found, replacing with: %d", keyCode) c.KeyEvent(keyCode, false) time.Sleep(time.Second / 10) // qemu is picky, so no matter what, wait a small period time.Sleep(100 * time.Millisecond) continue } if strings.HasPrefix(original, "<wait>") { log.Printf("Special code '<wait>' found, sleeping one second") time.Sleep(1 * time.Second) original = original[len("<wait>"):] continue } if strings.HasPrefix(original, "<wait5>") { log.Printf("Special code '<wait5>' found, sleeping 5 seconds") time.Sleep(5 * time.Second) original = original[len("<wait5>"):] continue } if strings.HasPrefix(original, "<wait10>") { log.Printf("Special code '<wait10>' found, sleeping 10 seconds") time.Sleep(10 * time.Second) original = original[len("<wait10>"):] continue } if strings.HasPrefix(original, "<wait") && strings.HasSuffix(original, ">") { re := regexp.MustCompile(`<wait([0-9hms]+)>$`) dstr := re.FindStringSubmatch(original) if len(dstr) > 1 { log.Printf("Special code %s found, sleeping", dstr[0]) if dt, err := time.ParseDuration(dstr[1]); err == nil { time.Sleep(dt) original = original[len(dstr[0]):] continue } } } for specialCode, specialValue := range special { if strings.HasPrefix(original, specialCode) { log.Printf("Special code '%s' found, replacing with: %d", specialCode, specialValue) keyCode = specialValue original = original[len(specialCode):] break } } if keyCode == 0 { r, size := utf8.DecodeRuneInString(original) original = original[size:] keyCode = uint32(r) keyShift = unicode.IsUpper(r) || strings.ContainsRune(shiftedChars, r) log.Printf("Sending char '%c', code %d, shift %v", r, keyCode, keyShift) } if keyShift { c.KeyEvent(KeyLeftShift, true) } c.KeyEvent(keyCode, true) time.Sleep(time.Second / 10) c.KeyEvent(keyCode, false) time.Sleep(time.Second / 10) if keyShift { c.KeyEvent(KeyLeftShift, false) } // qemu is picky, so no matter what, wait a small period time.Sleep(100 * time.Millisecond) } }
mpl-2.0
SlateScience/MozillaJS
js/src/python/mozboot/mozboot/osx.py
11714
# 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/. from __future__ import print_function, unicode_literals import os import re import subprocess import sys import tempfile try: from urllib2 import urlopen except ImportError: from urllib.request import urlopen from distutils.version import StrictVersion from mozboot.base import BaseBootstrapper HOMEBREW_BOOTSTRAP = 'http://raw.github.com/mxcl/homebrew/go' XCODE_APP_STORE = 'macappstore://itunes.apple.com/app/id497799835?mt=12' XCODE_LEGACY = 'https://developer.apple.com/downloads/download.action?path=Developer_Tools/xcode_3.2.6_and_ios_sdk_4.3__final/xcode_3.2.6_and_ios_sdk_4.3.dmg' HOMEBREW_AUTOCONF213 = 'https://raw.github.com/Homebrew/homebrew-versions/master/autoconf213.rb' MACPORTS_URL = {'8': 'https://distfiles.macports.org/MacPorts/MacPorts-2.1.3-10.8-MountainLion.pkg', '7': 'https://distfiles.macports.org/MacPorts/MacPorts-2.1.3-10.7-Lion.pkg', '6': 'https://distfiles.macports.org/MacPorts/MacPorts-2.1.3-10.6-SnowLeopard.pkg',} MACPORTS_CLANG_PACKAGE = 'clang-3.2' RE_CLANG_VERSION = re.compile('Apple (?:clang|LLVM) version (\d+\.\d+)') APPLE_CLANG_MINIMUM_VERSION = StrictVersion('4.0') XCODE_REQUIRED = ''' Xcode is required to build Firefox. Please complete the install of Xcode through the App Store. ''' XCODE_REQUIRED_LEGACY = ''' You will need to download and install Xcode to build Firefox. Please complete the Xcode download and then relaunch this script. ''' XCODE_COMMAND_LINE_TOOLS_MISSING = ''' The Xcode command line tools are required to build Firefox. ''' INSTALL_XCODE_COMMAND_LINE_TOOLS_STEPS = ''' Perform the following steps to install the Xcode command line tools: 1) Open Xcode.app 2) Click through any first-run prompts 3) From the main Xcode menu, select Preferences (Command ,) 4) Go to the Download tab (near the right) 5) Install the "Command Line Tools" When that has finished installing, please relaunch this script. ''' UPGRADE_XCODE_COMMAND_LINE_TOOLS = ''' An old version of the Xcode command line tools is installed. You will need to install a newer version in order to compile Firefox. ''' PACKAGE_MANAGER_INSTALL = ''' We will install the %s package manager to install required packages. You will be prompted to install %s with its default settings. If you would prefer to do this manually, hit CTRL+c, install %s yourself, ensure "%s" is in your $PATH, and relaunch bootstrap. ''' PACKAGE_MANAGER_PACKAGES = ''' We are now installing all required packages via %s. You will see a lot of output as packages are built. ''' PACKAGE_MANAGER_OLD_CLANG = ''' We require a newer compiler than what is provided by your version of Xcode. We will install a modern version of Clang through %s. ''' PACKAGE_MANAGER_CHOICE = ''' Please choose a package manager you'd like: 1. Homebrew 2. MacPorts Your choice: ''' NO_PACKAGE_MANAGER_WARNING = ''' It seems you don't have any supported package manager installed. ''' PACKAGE_MANAGER_EXISTS = ''' Looks like you have %s installed. We will install all required packages via %s. ''' MULTI_PACKAGE_MANAGER_EXISTS = ''' It looks like you have multiple package managers installed. ''' # May add support for other package manager on os x. PACKAGE_MANAGER = {'Homebrew': 'brew', 'MacPorts': 'port'} PACKAGE_MANAGER_CHOICES = ['Homebrew', 'MacPorts'] MACPORTS_POSTINSTALL_RESTART_REQUIRED = ''' MacPorts was installed successfully. However, you'll need to start a new shell to pick up the environment changes so MacPorts can be found by your tools. Please start a new shell or terminal window and run this bootstrapper again. ''' class OSXBootstrapper(BaseBootstrapper): def __init__(self, version): BaseBootstrapper.__init__(self) self.os_version = StrictVersion(version) if self.os_version < StrictVersion('10.6'): raise Exception('OS X 10.6 or above is required.') self.minor_version = version.split('.')[1] def install_system_packages(self): self.ensure_xcode() choice = self.ensure_package_manager() self.package_manager = choice getattr(self, 'ensure_%s_packages' % choice)() def ensure_xcode(self): if self.os_version < StrictVersion('10.7'): if not os.path.exists('/Developer/Applications/Xcode.app'): print(XCODE_REQUIRED_LEGACY) subprocess.check_call(['open', XCODE_LEGACY]) sys.exit(1) elif self.os_version >= StrictVersion('10.7'): if not os.path.exists('/Applications/Xcode.app'): print(XCODE_REQUIRED) subprocess.check_call(['open', XCODE_APP_STORE]) print('Once the install has finished, please relaunch this script.') sys.exit(1) # Once Xcode is installed, you need to agree to the license before you can # use it. try: output = self.check_output(['/usr/bin/xcrun', 'clang'], stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: if 'license' in e.output: xcodebuild = self.which('xcodebuild') subprocess.check_call([xcodebuild, '-license']) # Even then we're not done! We need to install the Xcode command line tools. # As of Mountain Lion, apparently the only way to do this is to go through a # menu dialog inside Xcode itself. We're not making this up. if self.os_version >= StrictVersion('10.7'): if not os.path.exists('/usr/bin/clang'): print(XCODE_COMMAND_LINE_TOOLS_MISSING) print(INSTALL_XCODE_COMMAND_LINE_TOOLS_STEPS) sys.exit(1) output = self.check_output(['/usr/bin/clang', '--version']) match = RE_CLANG_VERSION.search(output) if match is None: raise Exception('Could not determine Clang version.') version = StrictVersion(match.group(1)) if version < APPLE_CLANG_MINIMUM_VERSION: print(UPGRADE_XCODE_COMMAND_LINE_TOOLS) print(INSTALL_XCODE_COMMAND_LINE_TOOLS_STEPS) sys.exit(1) def ensure_homebrew_packages(self): self.brew = self.which('brew') assert self.brew is not None installed = self.check_output([self.brew, 'list']).split() packages = [ # We need to install Python because Mercurial requires the Python # development headers which are missing from OS X (at least on # 10.8). ('python', 'python'), ('mercurial', 'mercurial'), ('git', 'git'), ('yasm', 'yasm'), ('autoconf213', HOMEBREW_AUTOCONF213), ] printed = False for name, package in packages: if name in installed: continue if not printed: print(PACKAGE_MANAGER_PACKAGES % ('Homebrew',)) printed = True subprocess.check_call([self.brew, '-v', 'install', package]) if self.os_version < StrictVersion('10.7') and 'llvm' not in installed: print(PACKAGE_MANAGER_OLD_CLANG % ('Homebrew',)) subprocess.check_call([self.brew, '-v', 'install', 'llvm', '--with-clang', '--all-targets']) def ensure_macports_packages(self): self.port = self.which('port') assert self.port is not None installed = set(self.check_output([self.port, 'installed']).split()) packages = ['python27', 'mercurial', 'yasm', 'libidl', 'autoconf213'] missing = [package for package in packages if package not in installed] if missing: print(PACKAGE_MANAGER_PACKAGES % ('MacPorts',)) self.run_as_root([self.port, '-v', 'install'] + missing) if self.os_version < StrictVersion('10.7') and MACPORTS_CLANG_PACKAGE not in installed: print(PACKAGE_MANAGER_OLD_CLANG % ('MacPorts',)) self.run_as_root([self.port, '-v', 'install', MACPORTS_CLANG_PACKAGE]) self.run_as_root([self.port, 'select', '--set', 'python', 'python27']) self.run_as_root([self.port, 'select', '--set', 'clang', 'mp-' + MACPORTS_CLANG_PACKAGE]) def ensure_package_manager(self): ''' Search package mgr in sys.path, if none is found, prompt the user to install one. If only one is found, use that one. If both are found, prompt the user to choose one. ''' installed = [] for name, cmd in PACKAGE_MANAGER.iteritems(): if self.which(cmd) is not None: installed.append(name) if not installed: print(NO_PACKAGE_MANAGER_WARNING) choice = self.prompt_int(prompt=PACKAGE_MANAGER_CHOICE, low=1, high=2) getattr(self, 'install_%s' % PACKAGE_MANAGER_CHOICES[choice - 1].lower())() return PACKAGE_MANAGER_CHOICES[choice - 1].lower() elif len(installed) == 1: print(PACKAGE_MANAGER_EXISTS % (installed[0], installed[0])) return installed[0].lower() else: print(MULTI_PACKAGE_MANAGER_EXISTS) choice = self.prompt_int(prompt=PACKAGE_MANAGER_CHOICE, low=1, high=2) return PACKAGE_MANAGER_CHOICES[choice - 1].lower() def install_homebrew(self): print(PACKAGE_MANAGER_INSTALL % ('Homebrew', 'Homebrew', 'Homebrew', 'brew')) bootstrap = urlopen(url=HOMEBREW_BOOTSTRAP, timeout=20).read() with tempfile.NamedTemporaryFile() as tf: tf.write(bootstrap) tf.flush() subprocess.check_call(['ruby', tf.name]) def install_macports(self): url = MACPORTS_URL.get(self.minor_version, None) if not url: raise Exception('We do not have a MacPorts install URL for your ' 'OS X version. You will need to install MacPorts manually.') print(PACKAGE_MANAGER_INSTALL % ('MacPorts', 'MacPorts', 'MacPorts', 'port')) pkg = urlopen(url=url, timeout=300).read() with tempfile.NamedTemporaryFile(suffix='.pkg') as tf: tf.write(pkg) tf.flush() self.run_as_root(['installer', '-pkg', tf.name, '-target', '/']) # MacPorts installs itself into a location likely not on the PATH. If # we can't find it, prompt to restart. if self.which('port') is None: print(MACPORTS_POSTINSTALL_RESTART_REQUIRED) sys.exit(1) def _update_package_manager(self): if self.package_manager == 'homebrew': subprocess.check_call([self.brew, '-v', 'update']) else: assert self.package_manager == 'macports' self.run_as_root([self.port, 'selfupdate']) def _upgrade_package(self, package): self._ensure_package_manager_updated() if self.package_manager == 'homebrew': subprocess.check_call([self.brew, '-v', 'upgrade', package]) else: assert self.package_manager == 'macports' self.run_as_root([self.port, 'upgrade', package]) def upgrade_mercurial(self, current): self._upgrade_package('mercurial') def upgrade_python(self, current): if self.package_manager == 'homebrew': self._upgrade_package('python') else: self._upgrade_package('python27')
mpl-2.0
michath/ConMonkey
js/src/jit-test/tests/jaeger/bug563000/trap-self.js
220
// |jit-test| debug setDebug(true); x = "notset"; function main() { /* The JSOP_STOP in main. */ trap(main, 38, "success()"); x = "failure"; } function success() { x = "success"; } main(); assertEq(x, "success");
mpl-2.0
michaelforfxhelp/master
third_party/MediaInfoLib/Source/RegressionTest/RegressionTest_Events.cpp
21278
// RegressionTest.cpp : Defines the entry point for the console application. // #include <iostream> #include <stdio.h> #include <map> #include "tchar.h" #include "MediaInfoDLL\MediaInfoDLL.h" #include "MediaInfo\MediaInfo_Events.h" #include "ZenLib\ZtringListListF.h" #include "ZenLib\Dir.h" #include "ZenLib\File.h" #include "ZenLib\FileName.h" #include "RegressionTest/RegressionTest.h" using namespace MediaInfoDLL; using namespace ZenLib; using namespace std; const char* F_FileName; #define echoF(_format) UserHandle_struct::perevent &PerEvent=UserHandle->PerEvent[Event->EventCode]; if (!PerEvent.F_MoreThanOnce) {fprintf(PerEvent.F, _format); PerEvent.F_MoreThanOnce=true; } fprintf(PerEvent.F, "\n"); #define echo0(_format) fprintf(PerEvent.F, _format) #define echo1(_format, Arg1) fprintf(PerEvent.F, _format, Arg1) #define echo2(_format, Arg1, Arg2) fprintf(PerEvent.F, _format, Arg1, Arg2) #define echo4(_format, Arg1, Arg2, Arg3, Arg4) fprintf(PerEvent.F, _format, Arg1, Arg2, Arg3, Arg4) struct UserHandle_struct { FileName Name; Ztring Files; Ztring DataBaseDirectory; struct perevent { FILE* F; bool F_MoreThanOnce; bool Custom_MoreThanOnce; }; map<int32u, perevent> PerEvent; int32u Scenario; bool Custom; bool ParseSpeed; bool NextPacket; bool DemuxContainerOnly; bool Seek; UserHandle_struct() { Custom=false; ParseSpeed=false; NextPacket=false; DemuxContainerOnly=false; Seek=false; } void Clear() { for (map<int32u, perevent>::iterator Item=PerEvent.begin(); Item!=PerEvent.end(); Item++) fclose (Item->second.F); PerEvent.clear(); } }; void General_Start_0 (struct MediaInfo_Event_General_Start_0* Event, struct UserHandle_struct* UserHandle) { echoF("MediaInfo starts\n"); echo1("Stream_Size=%i\n", Event->Stream_Size); } void General_End_0 (struct MediaInfo_Event_General_End_0* Event, struct UserHandle_struct* UserHandle) { echoF("MediaInfo ends\n"); echo1("Stream_Bytes_Analyzed=%i\n", Event->Stream_Bytes_Analyzed); } void General_Parser_Selected_0 (struct MediaInfo_Event_General_Parser_Selected_0* Event, struct UserHandle_struct* UserHandle) { echoF("MediaInfo has selected the parser\n"); echo1("Name=%s\n", Event->Name); } void General_Move_Request_0 (struct MediaInfo_Event_General_Move_Request_0* Event, struct UserHandle_struct* UserHandle) { echoF("MediaInfo has requested to seek\n"); echo1("Stream_Offset=%08x\n", Event->Stream_Offset); } void General_Move_Done_0 (struct MediaInfo_Event_General_Move_Done_0* Event, struct UserHandle_struct* UserHandle) { echoF("MediaInfo has seek\n"); echo1("Stream_Offset=%08x\n", Event->Stream_Offset); } void General_SubFile_Start_0 (struct MediaInfo_Event_General_SubFile_Start_0* Event, struct UserHandle_struct* UserHandle) { echoF("MediaInfo is parsing a new file from the source file\n"); echo1("FileName_Relative=%s\n", Event->FileName_Relative); echo1("FileName_Absolute=%s\n", Event->FileName_Absolute); } void General_SubFile_End_0 (struct MediaInfo_Event_General_SubFile_End_0* Event, struct UserHandle_struct* UserHandle) { echoF("MediaInfo has finished the parsing a new file from the source file\n"); } void Global_Demux_3(struct MediaInfo_Event_Global_Demux_3 *Event, struct UserHandle_struct* UserHandle) { if (!UserHandle->DemuxContainerOnly) return; echoF("MediaInfo Demux\n"); echo1("Stream_Offset=%08x,", Event->Stream_Offset); echo1(" Frame_Number=%u\n", Event->FrameNumber); echo0("IDs="); for (size_t Pos=0; Pos<Event->StreamIDs_Size; Pos++) switch (Event->StreamIDs_Width[Pos]) { case 2: echo1("%02x, ", Event->StreamIDs[Pos]); break; case 4: echo1("%04x, ", Event->StreamIDs[Pos]); break; case 8: echo1("%08x, ", Event->StreamIDs[Pos]); break; default: echo1("%08x, ", Event->StreamIDs[Pos]); break; } echo0("\n"); if (Event->PCR!=(int64u)-1) echo1("PCR=%s, ", Ztring().Duration_From_Milliseconds(Event->PCR/1000000).To_Local().c_str()); if (Event->PTS!=(int64u)-1) echo1("PTS=%s, ", Ztring().Duration_From_Milliseconds(Event->PTS/1000000).To_Local().c_str()); if (Event->DTS!=(int64u)-1) echo1("DTS=%s, ", Ztring().Duration_From_Milliseconds(Event->DTS/1000000).To_Local().c_str()); if (Event->DUR!=(int64u)-1) echo1("DUR=%s, ", Ztring().Duration_From_Milliseconds(Event->DUR/1000000).To_Local().c_str()); if (Event->PCR!=(int64u)-1 || Event->PTS!=(int64u)-1 || Event->DTS!=(int64u)-1 || Event->DUR!=(int64u)-1) echo0("\n"); echo1("Content_Type=%i,", Event->Content_Type); echo1(" Content_Size=%i,", Event->Content_Size); echo1(" Flags=%08x\n", Event->Flags); } void Video_SliceInfo_0(struct MediaInfo_Event_Video_SliceInfo_0 *Event, struct UserHandle_struct* UserHandle) { if (!UserHandle->DemuxContainerOnly) return; echoF("MediaInfo Demux\n"); echo1("Stream_Offset=%08x,", Event->Stream_Offset); echo1(" FramePosition=%u,", Event->FramePosition); echo1(" FieldPosition=%u,", Event->FramePosition); echo1(" SlicePosition=%u,", Event->FramePosition); echo0("IDs="); for (size_t Pos=0; Pos<Event->StreamIDs_Size; Pos++) switch (Event->StreamIDs_Width[Pos]) { case 2: echo1("%02x, ", Event->StreamIDs[Pos]); break; case 4: echo1("%04x, ", Event->StreamIDs[Pos]); break; case 8: echo1("%08x, ", Event->StreamIDs[Pos]); break; default: echo1("%08x, ", Event->StreamIDs[Pos]); break; } echo0("\n"); if (Event->PCR!=(int64u)-1) echo1("PCR=%s, ", Ztring().Duration_From_Milliseconds(Event->PCR/1000000).To_Local().c_str()); if (Event->PTS!=(int64u)-1) echo1("PTS=%s, ", Ztring().Duration_From_Milliseconds(Event->PTS/1000000).To_Local().c_str()); if (Event->DTS!=(int64u)-1) echo1("DTS=%s, ", Ztring().Duration_From_Milliseconds(Event->DTS/1000000).To_Local().c_str()); if (Event->DUR!=(int64u)-1) echo1("DUR=%s, ", Ztring().Duration_From_Milliseconds(Event->DUR/1000000).To_Local().c_str()); if (Event->PCR!=(int64u)-1 || Event->PTS!=(int64u)-1 || Event->DTS!=(int64u)-1 || Event->DUR!=(int64u)-1) echo0("\n"); echo1("SliceType=%i,", Event->SliceType); echo1(" Flags=%08x\n", Event->Flags); } /***************************************************************************/ /* The callback function */ /***************************************************************************/ #define CASE(_PARSER,_EVENT,_VERSION) \ case MediaInfo_Event_##_PARSER##_##_EVENT : if (EventVersion==_VERSION && Data_Size>=sizeof(struct MediaInfo_Event_##_PARSER##_##_EVENT##_##_VERSION)) _PARSER##_##_EVENT##_##_VERSION((struct MediaInfo_Event_##_PARSER##_##_EVENT##_##_VERSION*)Data_Content, UserHandle); break; void __stdcall Event_CallBackFunction(unsigned char* Data_Content, size_t Data_Size, void* UserHandle_Void) { /*Retrieving UserHandle*/ struct UserHandle_struct* UserHandle=(struct UserHandle_struct*)UserHandle_Void; struct MediaInfo_Event_Generic* Event_Generic=(struct MediaInfo_Event_Generic*) Data_Content; unsigned char ParserID; unsigned short EventID; unsigned char EventVersion; /*integrity tests*/ if (Data_Size<4) return; //There is a problem if (UserHandle->PerEvent[Event_Generic->EventCode].F==NULL) { Ztring Number; Number.From_Number(Event_Generic->EventCode, 16); while (Number.size()<8) Number.insert(0, 1, _T('0')); Ztring Name=Ztring(UserHandle->DataBaseDirectory+_T("\\Events\\New\\")+FileName(UserHandle->Files).Name_Get()+_T("\\")+Ztring::ToZtring(UserHandle->Scenario)+_T("\\")+Number+_T("\\")+UserHandle->Name.Name_Get()+_T(".txt")); if (!Dir::Exists(UserHandle->DataBaseDirectory+_T("\\Events\\New"))) Dir::Create(UserHandle->DataBaseDirectory+_T("\\Events\\New")); if (!Dir::Exists(UserHandle->DataBaseDirectory+_T("\\Events\\New\\")+FileName(UserHandle->Files).Name_Get())) Dir::Create(UserHandle->DataBaseDirectory+_T("\\Events\\New\\")+FileName(UserHandle->Files).Name_Get()); if (!Dir::Exists(UserHandle->DataBaseDirectory+_T("\\Events\\New\\")+FileName(UserHandle->Files).Name_Get()+_T("\\")+Ztring::ToZtring(UserHandle->Scenario))) Dir::Create(UserHandle->DataBaseDirectory+_T("\\Events\\New\\")+FileName(UserHandle->Files).Name_Get()+_T("\\")+Ztring::ToZtring(UserHandle->Scenario)); if (!Dir::Exists(FileName(Name).Path_Get())) Dir::Create(FileName(Name).Path_Get()); UserHandle->PerEvent[Event_Generic->EventCode].F=fopen(Name.To_Local().c_str(), "w"); } /*Retrieving EventID*/ ParserID =(unsigned char) ((Event_Generic->EventCode&0xFF000000)>>24); EventID =(unsigned short)((Event_Generic->EventCode&0x00FFFF00)>>8 ); EventVersion=(unsigned char) ( Event_Generic->EventCode&0x000000FF ); //*Global to all parsers switch (EventID) { CASE (Global, Demux, 3) CASE (Video, SliceInfo, 0) default : ; } switch (ParserID) { case MediaInfo_Parser_None : switch (EventID) { case MediaInfo_Event_General_Start : if (EventVersion==0 && Data_Size==sizeof(struct MediaInfo_Event_General_Start_0)) General_Start_0((struct MediaInfo_Event_General_Start_0*)Data_Content, UserHandle); break; case MediaInfo_Event_General_End : if (EventVersion==0 && Data_Size==sizeof(struct MediaInfo_Event_General_End_0)) General_End_0((struct MediaInfo_Event_General_End_0*)Data_Content, UserHandle); break; case MediaInfo_Event_General_Parser_Selected : if (EventVersion==0 && Data_Size==sizeof(struct MediaInfo_Event_General_Parser_Selected_0)) General_Parser_Selected_0((struct MediaInfo_Event_General_Parser_Selected_0*)Data_Content, UserHandle); break; case MediaInfo_Event_General_Move_Request : if (EventVersion==0 && Data_Size==sizeof(struct MediaInfo_Event_General_Move_Request_0)) General_Move_Request_0((struct MediaInfo_Event_General_Move_Request_0*)Data_Content, UserHandle); break; case MediaInfo_Event_General_Move_Done : if (EventVersion==0 && Data_Size==sizeof(struct MediaInfo_Event_General_Move_Done_0)) General_Move_Done_0((struct MediaInfo_Event_General_Move_Done_0*)Data_Content, UserHandle); break; case MediaInfo_Event_General_SubFile_Start : if (EventVersion==0 && Data_Size==sizeof(struct MediaInfo_Event_General_SubFile_Start_0)) General_SubFile_Start_0((struct MediaInfo_Event_General_SubFile_Start_0*)Data_Content, UserHandle); break; case MediaInfo_Event_General_SubFile_End : if (EventVersion==0 && Data_Size==sizeof(struct MediaInfo_Event_General_SubFile_End_0)) General_SubFile_End_0((struct MediaInfo_Event_General_SubFile_End_0*)Data_Content, UserHandle); break; default : ; } break; default : ; //ParserID is unknown } } void RegressionTest_Events(Ztring Files, Ztring DataBaseDirectory, int32u Scenario) { // Scenarios: // bit 0 : quick parsing / full parsing // bit 1 : next packet interface // bit 2 : demux (by container only) // bit 3 : do some seeks cout<<" Analyzing"<<endl; ZtringListListF FilesList_Source; if (FileName(Files).Extension_Get()==_T("csv")) FilesList_Source.Load(DataBaseDirectory+_T("\\Events\\FilesList.csv")); else { FilesList_Source.push_back(ZtringList()); //if (File::Exists(Files)) FilesList_Source.push_back(Files); //else // FilesList_Source.push_back(Files+_T("\\*.*")); } vector<UserHandle_struct> FilesList; for (size_t FilesList_Source_Pos=1; FilesList_Source_Pos<FilesList_Source.size(); FilesList_Source_Pos++) { ZtringList Temp=Dir::GetAllFileNames(FilesList_Source[FilesList_Source_Pos](0)); for (size_t Temp_Pos=0; Temp_Pos<Temp.size(); Temp_Pos++) { UserHandle_struct ToAdd; ToAdd.Name=Temp[Temp_Pos]; ToAdd.DataBaseDirectory=DataBaseDirectory; ToAdd.Files=Files; ToAdd.Scenario=Scenario; if (Scenario&(1<<0)) ToAdd.ParseSpeed=true; if (Scenario&(1<<1)) ToAdd.NextPacket=true; if (Scenario&(1<<2)) ToAdd.DemuxContainerOnly=true; if (Scenario&(1<<3)) ToAdd.Seek=true; FilesList.push_back(ToAdd); } } for (size_t FilesList_Pos=0; FilesList_Pos<FilesList.size(); FilesList_Pos++) { cout<<" "<<FilesList_Pos+1<<"/"<<FilesList.size()<<" "<<FilesList[FilesList_Pos].Name.To_Local()<<endl; MediaInfo MI; Ztring MI_Result; //********************************************************************** // Configuring //********************************************************************** // CallBack configuration // MediaInfo need pointer as text (for compatibility with older version) + 64-bit OS handling // form is "CallBack=memory://handlerInDecimal;UserHandler=memory://handlerInDecimal" // UserHandler is a unique value wich will be provided to the callback function, in order to know which MediaInfo instance send the event wostringstream Event_CallBackFunction_Text; Event_CallBackFunction_Text<<_T("CallBack=memory://")<<(MediaInfo_int64u)Event_CallBackFunction<<_T(";UserHandler=memory://")<<(MediaInfo_int64u)&FilesList[FilesList_Pos]; MI_Result=MI.Option(_T("File_Event_CallBackFunction"), Event_CallBackFunction_Text.str()); if (!MI_Result.empty()) { wcout<<_T("MediaInfo error: ")<<MI_Result<<endl; return; } //Retrieiving basic data MI.Open(FilesList[FilesList_Pos].Name); Ztring Delay_10s=Ztring().Duration_From_Milliseconds(Ztring(MI.Get(Stream_Video, 0, _T("Delay"))).To_int64u()+10000); if (FilesList[FilesList_Pos].ParseSpeed) { MI_Result=MI.Option(_T("ParseSpeed"), _T("1.0")); if (!MI_Result.empty()) { wcout<<_T("MediaInfo error: ")<<MI_Result<<endl; return; } } if (FilesList[FilesList_Pos].DemuxContainerOnly) { MI_Result=MI.Option(_T("Demux"), _T("container")); if (!MI_Result.empty()) { wcout<<_T("MediaInfo error: ")<<MI_Result<<endl; return; } MI_Result=MI.Option(_T("File_Demux_Unpacketize"), _T("1")); if (!MI_Result.empty()) { wcout<<_T("MediaInfo error: ")<<MI_Result<<endl; return; } MI_Result=MI.Option(_T("File_Demux_PCM_20bitTo16bit"), _T("1")); if (!MI_Result.empty()) { wcout<<_T("MediaInfo error: ")<<MI_Result<<endl; return; } } if (FilesList[FilesList_Pos].NextPacket) { MI_Result=MI.Option(_T("File_NextPacket"), _T("1")); if (!MI_Result.empty()) { wcout<<_T("MediaInfo error: ")<<MI_Result<<endl; return; } } MI.Open(FilesList[FilesList_Pos].Name); if (FilesList[FilesList_Pos].NextPacket) { int Counter=0; while (MI.Open_NextPacket()&0x100) { if (FilesList[FilesList_Pos].Seek) { Counter++; if (Counter==0) MI.Option(_T("File_Seek"), _T("0")); if (Counter==100) MI.Option(_T("File_Seek"), Delay_10s); if (Counter==200) MI.Option(_T("File_Seek"), _T("Frame=100")); if (Counter==300) MI.Option(_T("File_Seek"), _T("95%")); } } } FilesList[FilesList_Pos].Clear(); } cout<<" Diff"<<endl; ZtringList Ref=Dir::GetAllFileNames(DataBaseDirectory+_T("\\Events\\Ref\\")+FileName(Files).Name_Get()+_T("\\")+Ztring::ToZtring(Scenario)+_T("*.*")); ZtringList New=Dir::GetAllFileNames(DataBaseDirectory+_T("\\Events\\New\\")+FileName(Files).Name_Get()+_T("\\")+Ztring::ToZtring(Scenario)+_T("*.*")); for (size_t Ref_Pos=0; Ref_Pos<Ref.size(); Ref_Pos++) { Ztring Ref_ToFind=Ref[Ref_Pos]; Ref_ToFind.FindAndReplace(_T("\\Events\\Ref\\"), _T("\\Events\\New\\")); size_t New_RefPos=New.Find(Ref_ToFind); bool IsDiff=false; if (New_RefPos!=(size_t)-1) { File F_Ref; F_Ref.Open(Ref[Ref_Pos]); File F_New; F_New.Open(New[New_RefPos]); if (F_Ref.Size_Get()==F_New.Size_Get()) { int64u Size=F_Ref.Size_Get(); if (Size>100000000) Size=100000000; int8u* F_Ref_Buffer=new int8u[(size_t)Size]; F_Ref.Read(F_Ref_Buffer, (size_t)Size); int8u* F_New_Buffer=new int8u[(size_t)Size]; F_New.Read(F_New_Buffer, (size_t)Size); if (memcmp(F_Ref_Buffer, F_New_Buffer, (size_t)Size)) IsDiff=true; delete[] F_Ref_Buffer; delete[] F_New_Buffer; } else IsDiff=true; } if (New_RefPos==(size_t)-1 || IsDiff) { //Not in new or is different Ztring Diff_Name=Ref[Ref_Pos]; Diff_Name.FindAndReplace(_T("\\Events\\Ref\\"), _T("\\Events\\Diff\\")); if (!Dir::Exists(DataBaseDirectory+_T("\\Events\\Diff"))) Dir::Create(DataBaseDirectory+_T("\\Events\\Diff")); if (!Dir::Exists(DataBaseDirectory+_T("\\Events\\Diff\\")+FileName(Files).Name_Get())) Dir::Create(DataBaseDirectory+_T("\\Events\\Diff\\")+FileName(Files).Name_Get()); if (!Dir::Exists(DataBaseDirectory+_T("\\Events\\Diff\\")+FileName(Files).Name_Get()+_T("\\")+Ztring::ToZtring(Scenario))) Dir::Create(DataBaseDirectory+_T("\\Events\\Diff\\")+FileName(Files).Name_Get()+_T("\\")+Ztring::ToZtring(Scenario)); if (!Dir::Exists(FileName(Diff_Name).Path_Get())) Dir::Create(FileName(Diff_Name).Path_Get()); if (!IsDiff) File::Copy(Ref[Ref_Pos], Diff_Name+_T(".RefAlone.txt")); //Not in new else { File::Copy(Ref[Ref_Pos], Diff_Name+_T(".Ref.txt")); //Diff File::Copy(New[New_RefPos], Diff_Name+_T(".New.txt")); } } if (New_RefPos!=(size_t)-1) New.erase(New.begin()+New_RefPos); } for (size_t New_Pos=0; New_Pos<New.size(); New_Pos++) { //Not in ref Ztring Diff_Name=New[New_Pos]; Diff_Name.FindAndReplace(_T("\\Events\\New\\"), _T("\\Events\\Diff\\")); if (!Dir::Exists(DataBaseDirectory+_T("\\Events\\Diff"))) Dir::Create(DataBaseDirectory+_T("\\Events\\Diff")); if (!Dir::Exists(DataBaseDirectory+_T("\\Events\\Diff\\")+FileName(Files).Name_Get())) Dir::Create(DataBaseDirectory+_T("\\Events\\Diff\\")+FileName(Files).Name_Get()); if (!Dir::Exists(DataBaseDirectory+_T("\\Events\\Diff\\")+FileName(Files).Name_Get()+_T("\\")+Ztring::ToZtring(Scenario))) Dir::Create(DataBaseDirectory+_T("\\Events\\Diff\\")+FileName(Files).Name_Get()+_T("\\")+Ztring::ToZtring(Scenario)); if (!Dir::Exists(FileName(Diff_Name).Path_Get())) Dir::Create(FileName(Diff_Name).Path_Get()); File::Copy(New[New_Pos], Diff_Name+_T(".NewAlone.txt")); //Not in new } }
mpl-2.0
opsidian/terraform
builtin/providers/google/resource_compute_image_test.go
2815
package google import ( "fmt" "testing" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" "google.golang.org/api/compute/v1" ) func TestAccComputeImage_basic(t *testing.T) { var image compute.Image resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckComputeImageDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: testAccComputeImage_basic, Check: resource.ComposeTestCheckFunc( testAccCheckComputeImageExists( "google_compute_image.foobar", &image), ), }, }, }) } func TestAccComputeImage_basedondisk(t *testing.T) { var image compute.Image resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckComputeImageDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: testAccComputeImage_basedondisk, Check: resource.ComposeTestCheckFunc( testAccCheckComputeImageExists( "google_compute_image.foobar", &image), ), }, }, }) } func testAccCheckComputeImageDestroy(s *terraform.State) error { config := testAccProvider.Meta().(*Config) for _, rs := range s.RootModule().Resources { if rs.Type != "google_compute_image" { continue } _, err := config.clientCompute.Images.Get( config.Project, rs.Primary.ID).Do() if err == nil { return fmt.Errorf("Image still exists") } } return nil } func testAccCheckComputeImageExists(n string, image *compute.Image) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if rs.Primary.ID == "" { return fmt.Errorf("No ID is set") } config := testAccProvider.Meta().(*Config) found, err := config.clientCompute.Images.Get( config.Project, rs.Primary.ID).Do() if err != nil { return err } if found.Name != rs.Primary.ID { return fmt.Errorf("Image not found") } *image = *found return nil } } var testAccComputeImage_basic = fmt.Sprintf(` resource "google_compute_image" "foobar" { name = "image-test-%s" raw_disk { source = "https://storage.googleapis.com/bosh-cpi-artifacts/bosh-stemcell-3262.4-google-kvm-ubuntu-trusty-go_agent-raw.tar.gz" } }`, acctest.RandString(10)) var testAccComputeImage_basedondisk = fmt.Sprintf(` resource "google_compute_disk" "foobar" { name = "disk-test-%s" zone = "us-central1-a" image = "debian-8-jessie-v20160803" } resource "google_compute_image" "foobar" { name = "image-test-%s" source_disk = "${google_compute_disk.foobar.self_link}" }`, acctest.RandString(10), acctest.RandString(10))
mpl-2.0
craigcook/bedrock
tests/redirects/base.py
7208
# 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 https://mozilla.org/MPL/2.0/. import re from urllib.parse import parse_qs, urlparse import requests from braceexpand import braceexpand def get_abs_url(url, base_url): try: if url.pattern.startswith("/"): # url is a compiled regular expression pattern return re.compile("".join([re.escape(base_url), url.pattern])) except AttributeError: if url.startswith("/"): # urljoin messes with query strings too much return "".join([base_url, url]) return url def url_test( url, location=None, status_code=requests.codes.moved_permanently, req_headers=None, req_kwargs=None, resp_headers=None, query=None, follow_redirects=False, final_status_code=requests.codes.ok, ): r""" Function for producing a config dict for the redirect test. You can use simple bash style brace expansion in the `url` and `location` values. If you need the `location` to change with the `url` changes you must use the same number of expansions or the `location` will be treated as non-expandable. If you use brace expansion this function will return a list of dicts instead of a dict. You must use the `flatten` function provided to prepare your test fixture if you do this. If you combine brace expansion with a compiled regular expression pattern you must escape any backslashes as this is the escape character for brace expansion. example: url_test('/about/drivers{/,.html}', 'https://wiki.mozilla.org/Firefox/Drivers'), url_test('/projects/index.{de,fr,hr,sq}.html', '/{de,fr,hr,sq}/firefox/'), url_test('/firefox/notes/', re.compile(r'\/firefox\/[\d\.]+\/releasenotes\/'), url_test('/firefox/android/{,beta/}notes/', re.compile(r'\\/firefox\\/android\\/[\\d\\.]+{,beta}\\/releasenotes\\/' :param url: The URL in question (absolute or relative). :param location: If a redirect, either the expected value or a compiled regular expression to match the "Location" header. :param status_code: Expected status code from the request. :param req_headers: Extra headers to send with the request. :param req_kwargs: Extra arguments to pass to requests.get() :param resp_headers: Dict of headers expected in the response. :param query: Dict of expected query params in `location` URL. :param follow_redirects: Boolean indicating whether redirects should be followed. :param final_status_code: Expected status code after following any redirects. :return: dict or list of dicts """ test_data = { "url": url, "location": location, "status_code": status_code, "req_headers": req_headers, "req_kwargs": req_kwargs, "resp_headers": resp_headers, "query": query, "follow_redirects": follow_redirects, "final_status_code": final_status_code, } expanded_urls = list(braceexpand(url)) num_urls = len(expanded_urls) if num_urls == 1: return test_data try: # location is a compiled regular expression pattern location_pattern = location.pattern test_data["location"] = location_pattern except AttributeError: location_pattern = None new_urls = [] if location: expanded_locations = list(braceexpand(test_data["location"])) num_locations = len(expanded_locations) for i, url in enumerate(expanded_urls): data = test_data.copy() data["url"] = url if location and num_urls == num_locations: if location_pattern is not None: # recompile the pattern after expansion data["location"] = re.compile(expanded_locations[i]) else: data["location"] = expanded_locations[i] new_urls.append(data) return new_urls def assert_valid_url( url, location=None, status_code=requests.codes.moved_permanently, req_headers=None, req_kwargs=None, resp_headers=None, query=None, base_url=None, follow_redirects=False, final_status_code=requests.codes.ok, ): """ Define a test of a URL's response. :param url: The URL in question (absolute or relative). :param location: If a redirect, either the expected value or a compiled regular expression to match the "Location" header. :param status_code: Expected status code from the request. :param req_headers: Extra headers to send with the request. :param req_kwargs: Extra arguments to pass to requests.get() :param resp_headers: Dict of headers expected in the response. :param base_url: Base URL for the site to test. :param query: Dict of expected query params in `location` URL. :param follow_redirects: Boolean indicating whether redirects should be followed. :param final_status_code: Expected status code after following any redirects. """ kwargs = {"allow_redirects": follow_redirects} if req_headers: kwargs["headers"] = req_headers if req_kwargs: kwargs.update(req_kwargs) abs_url = get_abs_url(url, base_url) resp = requests.get(abs_url, **kwargs) # so that the value will appear in locals in test output resp_location = resp.headers.get("location") if follow_redirects: assert resp.status_code == final_status_code else: assert resp.status_code == status_code if location and not follow_redirects: if not query and "?" in location: query = parse_qs(urlparse(location).query) location = location.split("?")[0] if query: # all query values must be lists for k, v in query.items(): if isinstance(v, str): query[k] = [v] # parse the QS from resp location header and compare to query arg # since order doesn't matter. resp_parsed = urlparse(resp_location) assert query == parse_qs(resp_parsed.query) # strip off query for further comparison resp_location = resp_location.split("?")[0] if hasattr(location, "match"): # location is a compiled regular expression pattern assert location.match(resp_location) is not None else: assert location == resp_location if resp_headers and not follow_redirects: for name, value in resp_headers.items(): print(name, value) assert name in resp.headers assert resp.headers[name].lower() == value.lower() def flatten(urls_list): """Take a list of dicts which may itself contain some lists of dicts, and return a generator that will return just the dicts in sequence. Example: list(flatten([{'dude': 'jeff'}, [{'walter': 'walter'}, {'donny': 'dead'}]])) > [{'dude': 'jeff'}, {'walter': 'walter'}, {'donny': 'dead'}] """ for url in urls_list: if isinstance(url, dict): yield url else: yield from url
mpl-2.0
burdandrei/nomad
client/alloc_endpoint_test.go
36210
package client import ( "encoding/json" "fmt" "io" "net" "runtime" "strings" "testing" "time" "github.com/hashicorp/go-msgpack/codec" "github.com/hashicorp/nomad/acl" "github.com/hashicorp/nomad/client/config" cstructs "github.com/hashicorp/nomad/client/structs" "github.com/hashicorp/nomad/helper/pluginutils/catalog" "github.com/hashicorp/nomad/helper/uuid" "github.com/hashicorp/nomad/nomad" "github.com/hashicorp/nomad/nomad/mock" nstructs "github.com/hashicorp/nomad/nomad/structs" nconfig "github.com/hashicorp/nomad/nomad/structs/config" "github.com/hashicorp/nomad/plugins/drivers" "github.com/hashicorp/nomad/testutil" "github.com/stretchr/testify/require" "golang.org/x/sys/unix" ) func TestAllocations_Restart(t *testing.T) { t.Parallel() require := require.New(t) client, cleanup := TestClient(t, nil) defer cleanup() a := mock.Alloc() a.Job.TaskGroups[0].Tasks[0].Driver = "mock_driver" a.Job.TaskGroups[0].RestartPolicy = &nstructs.RestartPolicy{ Attempts: 0, Mode: nstructs.RestartPolicyModeFail, } a.Job.TaskGroups[0].Tasks[0].Config = map[string]interface{}{ "run_for": "10s", } require.Nil(client.addAlloc(a, "")) // Try with bad alloc req := &nstructs.AllocRestartRequest{} var resp nstructs.GenericResponse err := client.ClientRPC("Allocations.Restart", &req, &resp) require.Error(err) // Try with good alloc req.AllocID = a.ID testutil.WaitForResult(func() (bool, error) { var resp2 nstructs.GenericResponse err := client.ClientRPC("Allocations.Restart", &req, &resp2) if err != nil && strings.Contains(err.Error(), "not running") { return false, err } return true, nil }, func(err error) { t.Fatalf("err: %v", err) }) } func TestAllocations_Restart_ACL(t *testing.T) { t.Parallel() require := require.New(t) server, addr, root, cleanupS := testACLServer(t, nil) defer cleanupS() client, cleanupC := TestClient(t, func(c *config.Config) { c.Servers = []string{addr} c.ACLEnabled = true }) defer cleanupC() job := mock.BatchJob() job.TaskGroups[0].Count = 1 job.TaskGroups[0].Tasks[0].Config = map[string]interface{}{ "run_for": "20s", } // Wait for client to be running job alloc := testutil.WaitForRunningWithToken(t, server.RPC, job, root.SecretID)[0] // Try request without a token and expect failure { req := &nstructs.AllocRestartRequest{} req.AllocID = alloc.ID var resp nstructs.GenericResponse err := client.ClientRPC("Allocations.Restart", &req, &resp) require.NotNil(err) require.EqualError(err, nstructs.ErrPermissionDenied.Error()) } // Try request with an invalid token and expect failure { token := mock.CreatePolicyAndToken(t, server.State(), 1005, "invalid", mock.NamespacePolicy(nstructs.DefaultNamespace, "", []string{})) req := &nstructs.AllocRestartRequest{} req.AllocID = alloc.ID req.AuthToken = token.SecretID var resp nstructs.GenericResponse err := client.ClientRPC("Allocations.Restart", &req, &resp) require.NotNil(err) require.EqualError(err, nstructs.ErrPermissionDenied.Error()) } // Try request with a valid token { policyHCL := mock.NamespacePolicy(nstructs.DefaultNamespace, "", []string{acl.NamespaceCapabilityAllocLifecycle}) token := mock.CreatePolicyAndToken(t, server.State(), 1007, "valid", policyHCL) require.NotNil(token) req := &nstructs.AllocRestartRequest{} req.AllocID = alloc.ID req.AuthToken = token.SecretID req.Namespace = nstructs.DefaultNamespace var resp nstructs.GenericResponse err := client.ClientRPC("Allocations.Restart", &req, &resp) require.NoError(err) //require.True(nstructs.IsErrUnknownAllocation(err), "Expected unknown alloc, found: %v", err) } // Try request with a management token { req := &nstructs.AllocRestartRequest{} req.AllocID = alloc.ID req.AuthToken = root.SecretID var resp nstructs.GenericResponse err := client.ClientRPC("Allocations.Restart", &req, &resp) // Depending on how quickly the alloc restarts there may be no // error *or* a task not running error; either is fine. if err != nil { require.Contains(err.Error(), "Task not running", err) } } } func TestAllocations_GarbageCollectAll(t *testing.T) { t.Parallel() require := require.New(t) client, cleanup := TestClient(t, nil) defer cleanup() req := &nstructs.NodeSpecificRequest{} var resp nstructs.GenericResponse require.Nil(client.ClientRPC("Allocations.GarbageCollectAll", &req, &resp)) } func TestAllocations_GarbageCollectAll_ACL(t *testing.T) { t.Parallel() require := require.New(t) server, addr, root, cleanupS := testACLServer(t, nil) defer cleanupS() client, cleanupC := TestClient(t, func(c *config.Config) { c.Servers = []string{addr} c.ACLEnabled = true }) defer cleanupC() // Try request without a token and expect failure { req := &nstructs.NodeSpecificRequest{} var resp nstructs.GenericResponse err := client.ClientRPC("Allocations.GarbageCollectAll", &req, &resp) require.NotNil(err) require.EqualError(err, nstructs.ErrPermissionDenied.Error()) } // Try request with an invalid token and expect failure { token := mock.CreatePolicyAndToken(t, server.State(), 1005, "invalid", mock.NodePolicy(acl.PolicyDeny)) req := &nstructs.NodeSpecificRequest{} req.AuthToken = token.SecretID var resp nstructs.GenericResponse err := client.ClientRPC("Allocations.GarbageCollectAll", &req, &resp) require.NotNil(err) require.EqualError(err, nstructs.ErrPermissionDenied.Error()) } // Try request with a valid token { token := mock.CreatePolicyAndToken(t, server.State(), 1007, "valid", mock.NodePolicy(acl.PolicyWrite)) req := &nstructs.NodeSpecificRequest{} req.AuthToken = token.SecretID var resp nstructs.GenericResponse require.Nil(client.ClientRPC("Allocations.GarbageCollectAll", &req, &resp)) } // Try request with a management token { req := &nstructs.NodeSpecificRequest{} req.AuthToken = root.SecretID var resp nstructs.GenericResponse require.Nil(client.ClientRPC("Allocations.GarbageCollectAll", &req, &resp)) } } func TestAllocations_GarbageCollect(t *testing.T) { t.Parallel() require := require.New(t) client, cleanup := TestClient(t, func(c *config.Config) { c.GCDiskUsageThreshold = 100.0 }) defer cleanup() a := mock.Alloc() a.Job.TaskGroups[0].Tasks[0].Driver = "mock_driver" rp := &nstructs.RestartPolicy{ Attempts: 0, Mode: nstructs.RestartPolicyModeFail, } a.Job.TaskGroups[0].RestartPolicy = rp a.Job.TaskGroups[0].Tasks[0].RestartPolicy = rp a.Job.TaskGroups[0].Tasks[0].Config = map[string]interface{}{ "run_for": "10ms", } require.Nil(client.addAlloc(a, "")) // Try with bad alloc req := &nstructs.AllocSpecificRequest{} var resp nstructs.GenericResponse err := client.ClientRPC("Allocations.GarbageCollect", &req, &resp) require.NotNil(err) // Try with good alloc req.AllocID = a.ID testutil.WaitForResult(func() (bool, error) { // Check if has been removed first if ar, ok := client.allocs[a.ID]; !ok || ar.IsDestroyed() { return true, nil } var resp2 nstructs.GenericResponse err := client.ClientRPC("Allocations.GarbageCollect", &req, &resp2) return err == nil, err }, func(err error) { t.Fatalf("err: %v", err) }) } func TestAllocations_GarbageCollect_ACL(t *testing.T) { t.Parallel() require := require.New(t) server, addr, root, cleanupS := testACLServer(t, nil) defer cleanupS() client, cleanupC := TestClient(t, func(c *config.Config) { c.Servers = []string{addr} c.ACLEnabled = true }) defer cleanupC() job := mock.BatchJob() job.TaskGroups[0].Count = 1 job.TaskGroups[0].Tasks[0].Config = map[string]interface{}{ "run_for": "20s", } noSuchAllocErr := fmt.Errorf("No such allocation on client or allocation not eligible for GC") // Wait for client to be running job alloc := testutil.WaitForRunningWithToken(t, server.RPC, job, root.SecretID)[0] // Try request without a token and expect failure { req := &nstructs.AllocSpecificRequest{} req.AllocID = alloc.ID var resp nstructs.GenericResponse err := client.ClientRPC("Allocations.GarbageCollect", &req, &resp) require.NotNil(err) require.EqualError(err, nstructs.ErrPermissionDenied.Error()) } // Try request with an invalid token and expect failure { token := mock.CreatePolicyAndToken(t, server.State(), 1005, "invalid", mock.NodePolicy(acl.PolicyDeny)) req := &nstructs.AllocSpecificRequest{} req.AllocID = alloc.ID req.AuthToken = token.SecretID var resp nstructs.GenericResponse err := client.ClientRPC("Allocations.GarbageCollect", &req, &resp) require.NotNil(err) require.EqualError(err, nstructs.ErrPermissionDenied.Error()) } // Try request with a valid token { token := mock.CreatePolicyAndToken(t, server.State(), 1005, "test-valid", mock.NamespacePolicy(nstructs.DefaultNamespace, "", []string{acl.NamespaceCapabilitySubmitJob})) req := &nstructs.AllocSpecificRequest{} req.AllocID = alloc.ID req.AuthToken = token.SecretID req.Namespace = nstructs.DefaultNamespace var resp nstructs.GenericResponse err := client.ClientRPC("Allocations.GarbageCollect", &req, &resp) require.Error(err, noSuchAllocErr) } // Try request with a management token { req := &nstructs.AllocSpecificRequest{} req.AuthToken = root.SecretID var resp nstructs.GenericResponse err := client.ClientRPC("Allocations.GarbageCollect", &req, &resp) require.Error(err, noSuchAllocErr) } } func TestAllocations_Signal(t *testing.T) { t.Parallel() client, cleanup := TestClient(t, nil) defer cleanup() a := mock.Alloc() require.Nil(t, client.addAlloc(a, "")) // Try with bad alloc req := &nstructs.AllocSignalRequest{} var resp nstructs.GenericResponse err := client.ClientRPC("Allocations.Signal", &req, &resp) require.NotNil(t, err) require.True(t, nstructs.IsErrUnknownAllocation(err)) // Try with good alloc req.AllocID = a.ID var resp2 nstructs.GenericResponse err = client.ClientRPC("Allocations.Signal", &req, &resp2) require.Error(t, err, "Expected error, got: %s, resp: %#+v", err, resp2) require.Contains(t, err.Error(), "Failed to signal task: web, err: Task not running") } func TestAllocations_Signal_ACL(t *testing.T) { t.Parallel() require := require.New(t) server, addr, root, cleanupS := testACLServer(t, nil) defer cleanupS() client, cleanupC := TestClient(t, func(c *config.Config) { c.Servers = []string{addr} c.ACLEnabled = true }) defer cleanupC() job := mock.BatchJob() job.TaskGroups[0].Count = 1 job.TaskGroups[0].Tasks[0].Config = map[string]interface{}{ "run_for": "20s", } // Wait for client to be running job alloc := testutil.WaitForRunningWithToken(t, server.RPC, job, root.SecretID)[0] // Try request without a token and expect failure { req := &nstructs.AllocSignalRequest{} req.AllocID = alloc.ID var resp nstructs.GenericResponse err := client.ClientRPC("Allocations.Signal", &req, &resp) require.NotNil(err) require.EqualError(err, nstructs.ErrPermissionDenied.Error()) } // Try request with an invalid token and expect failure { token := mock.CreatePolicyAndToken(t, server.State(), 1005, "invalid", mock.NodePolicy(acl.PolicyDeny)) req := &nstructs.AllocSignalRequest{} req.AllocID = alloc.ID req.AuthToken = token.SecretID var resp nstructs.GenericResponse err := client.ClientRPC("Allocations.Signal", &req, &resp) require.NotNil(err) require.EqualError(err, nstructs.ErrPermissionDenied.Error()) } // Try request with a valid token { token := mock.CreatePolicyAndToken(t, server.State(), 1005, "test-valid", mock.NamespacePolicy(nstructs.DefaultNamespace, "", []string{acl.NamespaceCapabilityAllocLifecycle})) req := &nstructs.AllocSignalRequest{} req.AllocID = alloc.ID req.AuthToken = token.SecretID req.Namespace = nstructs.DefaultNamespace var resp nstructs.GenericResponse err := client.ClientRPC("Allocations.Signal", &req, &resp) require.NoError(err) } // Try request with a management token { req := &nstructs.AllocSignalRequest{} req.AllocID = alloc.ID req.AuthToken = root.SecretID var resp nstructs.GenericResponse err := client.ClientRPC("Allocations.Signal", &req, &resp) require.NoError(err) } } func TestAllocations_Stats(t *testing.T) { t.Parallel() require := require.New(t) client, cleanup := TestClient(t, nil) defer cleanup() a := mock.Alloc() require.Nil(client.addAlloc(a, "")) // Try with bad alloc req := &cstructs.AllocStatsRequest{} var resp cstructs.AllocStatsResponse err := client.ClientRPC("Allocations.Stats", &req, &resp) require.NotNil(err) // Try with good alloc req.AllocID = a.ID testutil.WaitForResult(func() (bool, error) { var resp2 cstructs.AllocStatsResponse err := client.ClientRPC("Allocations.Stats", &req, &resp2) if err != nil { return false, err } if resp2.Stats == nil { return false, fmt.Errorf("invalid stats object") } return true, nil }, func(err error) { t.Fatalf("err: %v", err) }) } func TestAllocations_Stats_ACL(t *testing.T) { t.Parallel() require := require.New(t) server, addr, root, cleanupS := testACLServer(t, nil) defer cleanupS() client, cleanupC := TestClient(t, func(c *config.Config) { c.Servers = []string{addr} c.ACLEnabled = true }) defer cleanupC() job := mock.BatchJob() job.TaskGroups[0].Count = 1 job.TaskGroups[0].Tasks[0].Config = map[string]interface{}{ "run_for": "20s", } // Wait for client to be running job alloc := testutil.WaitForRunningWithToken(t, server.RPC, job, root.SecretID)[0] // Try request without a token and expect failure { req := &cstructs.AllocStatsRequest{} req.AllocID = alloc.ID var resp cstructs.AllocStatsResponse err := client.ClientRPC("Allocations.Stats", &req, &resp) require.NotNil(err) require.EqualError(err, nstructs.ErrPermissionDenied.Error()) } // Try request with an invalid token and expect failure { token := mock.CreatePolicyAndToken(t, server.State(), 1005, "invalid", mock.NodePolicy(acl.PolicyDeny)) req := &cstructs.AllocStatsRequest{} req.AllocID = alloc.ID req.AuthToken = token.SecretID var resp cstructs.AllocStatsResponse err := client.ClientRPC("Allocations.Stats", &req, &resp) require.NotNil(err) require.EqualError(err, nstructs.ErrPermissionDenied.Error()) } // Try request with a valid token { token := mock.CreatePolicyAndToken(t, server.State(), 1005, "test-valid", mock.NamespacePolicy(nstructs.DefaultNamespace, "", []string{acl.NamespaceCapabilityReadJob})) req := &cstructs.AllocStatsRequest{} req.AllocID = alloc.ID req.AuthToken = token.SecretID req.Namespace = nstructs.DefaultNamespace var resp cstructs.AllocStatsResponse err := client.ClientRPC("Allocations.Stats", &req, &resp) require.NoError(err) } // Try request with a management token { req := &cstructs.AllocStatsRequest{} req.AllocID = alloc.ID req.AuthToken = root.SecretID var resp cstructs.AllocStatsResponse err := client.ClientRPC("Allocations.Stats", &req, &resp) require.NoError(err) } } func TestAlloc_ExecStreaming(t *testing.T) { t.Parallel() require := require.New(t) // Start a server and client s, cleanupS := nomad.TestServer(t, nil) defer cleanupS() testutil.WaitForLeader(t, s.RPC) c, cleanupC := TestClient(t, func(c *config.Config) { c.Servers = []string{s.GetConfig().RPCAddr.String()} }) defer cleanupC() expectedStdout := "Hello from the other side\n" expectedStderr := "Hello from the other side\n" job := mock.BatchJob() job.TaskGroups[0].Count = 1 job.TaskGroups[0].Tasks[0].Config = map[string]interface{}{ "run_for": "20s", "exec_command": map[string]interface{}{ "run_for": "1ms", "stdout_string": expectedStdout, "stderr_string": expectedStderr, "exit_code": 3, }, } // Wait for client to be running job testutil.WaitForRunning(t, s.RPC, job) // Get the allocation ID args := nstructs.AllocListRequest{} args.Region = "global" resp := nstructs.AllocListResponse{} require.NoError(s.RPC("Alloc.List", &args, &resp)) require.Len(resp.Allocations, 1) allocID := resp.Allocations[0].ID // Make the request req := &cstructs.AllocExecRequest{ AllocID: allocID, Task: job.TaskGroups[0].Tasks[0].Name, Tty: true, Cmd: []string{"placeholder command"}, QueryOptions: nstructs.QueryOptions{Region: "global"}, } // Get the handler handler, err := c.StreamingRpcHandler("Allocations.Exec") require.Nil(err) // Create a pipe p1, p2 := net.Pipe() defer p1.Close() defer p2.Close() errCh := make(chan error) frames := make(chan *drivers.ExecTaskStreamingResponseMsg) // Start the handler go handler(p2) go decodeFrames(t, p1, frames, errCh) // Send the request encoder := codec.NewEncoder(p1, nstructs.MsgpackHandle) require.Nil(encoder.Encode(req)) timeout := time.After(3 * time.Second) exitCode := -1 receivedStdout := "" receivedStderr := "" OUTER: for { select { case <-timeout: // time out report require.Equal(expectedStdout, receivedStderr, "didn't receive expected stdout") require.Equal(expectedStderr, receivedStderr, "didn't receive expected stderr") require.Equal(3, exitCode, "failed to get exit code") require.FailNow("timed out") case err := <-errCh: require.NoError(err) case f := <-frames: switch { case f.Stdout != nil && len(f.Stdout.Data) != 0: receivedStdout += string(f.Stdout.Data) case f.Stderr != nil && len(f.Stderr.Data) != 0: receivedStderr += string(f.Stderr.Data) case f.Exited && f.Result != nil: exitCode = int(f.Result.ExitCode) default: t.Logf("received unrelevant frame: %v", f) } if expectedStdout == receivedStdout && expectedStderr == receivedStderr && exitCode == 3 { break OUTER } } } } func TestAlloc_ExecStreaming_NoAllocation(t *testing.T) { t.Parallel() require := require.New(t) // Start a server and client s, cleanupS := nomad.TestServer(t, nil) defer cleanupS() testutil.WaitForLeader(t, s.RPC) c, cleanupC := TestClient(t, func(c *config.Config) { c.Servers = []string{s.GetConfig().RPCAddr.String()} }) defer cleanupC() // Make the request req := &cstructs.AllocExecRequest{ AllocID: uuid.Generate(), Task: "testtask", Tty: true, Cmd: []string{"placeholder command"}, QueryOptions: nstructs.QueryOptions{Region: "global"}, } // Get the handler handler, err := c.StreamingRpcHandler("Allocations.Exec") require.Nil(err) // Create a pipe p1, p2 := net.Pipe() defer p1.Close() defer p2.Close() errCh := make(chan error) frames := make(chan *drivers.ExecTaskStreamingResponseMsg) // Start the handler go handler(p2) go decodeFrames(t, p1, frames, errCh) // Send the request encoder := codec.NewEncoder(p1, nstructs.MsgpackHandle) require.Nil(encoder.Encode(req)) timeout := time.After(3 * time.Second) select { case <-timeout: require.FailNow("timed out") case err := <-errCh: require.True(nstructs.IsErrUnknownAllocation(err), "expected no allocation error but found: %v", err) case f := <-frames: require.Fail("received unexpected frame", "frame: %#v", f) } } func TestAlloc_ExecStreaming_DisableRemoteExec(t *testing.T) { t.Parallel() require := require.New(t) // Start a server and client s, cleanupS := nomad.TestServer(t, nil) defer cleanupS() testutil.WaitForLeader(t, s.RPC) c, cleanupC := TestClient(t, func(c *config.Config) { c.Servers = []string{s.GetConfig().RPCAddr.String()} c.DisableRemoteExec = true }) defer cleanupC() // Make the request req := &cstructs.AllocExecRequest{ AllocID: uuid.Generate(), Task: "testtask", Tty: true, Cmd: []string{"placeholder command"}, QueryOptions: nstructs.QueryOptions{Region: "global"}, } // Get the handler handler, err := c.StreamingRpcHandler("Allocations.Exec") require.Nil(err) // Create a pipe p1, p2 := net.Pipe() defer p1.Close() defer p2.Close() errCh := make(chan error) frames := make(chan *drivers.ExecTaskStreamingResponseMsg) // Start the handler go handler(p2) go decodeFrames(t, p1, frames, errCh) // Send the request encoder := codec.NewEncoder(p1, nstructs.MsgpackHandle) require.Nil(encoder.Encode(req)) timeout := time.After(3 * time.Second) select { case <-timeout: require.FailNow("timed out") case err := <-errCh: require.True(nstructs.IsErrPermissionDenied(err), "expected permission denied error but found: %v", err) case f := <-frames: require.Fail("received unexpected frame", "frame: %#v", f) } } func TestAlloc_ExecStreaming_ACL_Basic(t *testing.T) { t.Parallel() // Start a server and client s, root, cleanupS := nomad.TestACLServer(t, nil) defer cleanupS() testutil.WaitForLeader(t, s.RPC) client, cleanupC := TestClient(t, func(c *config.Config) { c.ACLEnabled = true c.Servers = []string{s.GetConfig().RPCAddr.String()} }) defer cleanupC() // Create a bad token policyBad := mock.NamespacePolicy("other", "", []string{acl.NamespaceCapabilityDeny}) tokenBad := mock.CreatePolicyAndToken(t, s.State(), 1005, "invalid", policyBad) policyGood := mock.NamespacePolicy(nstructs.DefaultNamespace, "", []string{acl.NamespaceCapabilityAllocExec, acl.NamespaceCapabilityReadFS}) tokenGood := mock.CreatePolicyAndToken(t, s.State(), 1009, "valid2", policyGood) job := mock.BatchJob() job.TaskGroups[0].Count = 1 job.TaskGroups[0].Tasks[0].Config = map[string]interface{}{ "run_for": "20s", } // Wait for client to be running job alloc := testutil.WaitForRunningWithToken(t, s.RPC, job, root.SecretID)[0] cases := []struct { Name string Token string ExpectedError string }{ { Name: "bad token", Token: tokenBad.SecretID, ExpectedError: nstructs.ErrPermissionDenied.Error(), }, { Name: "good token", Token: tokenGood.SecretID, ExpectedError: "task not found", }, { Name: "root token", Token: root.SecretID, ExpectedError: "task not found", }, } for _, c := range cases { t.Run(c.Name, func(t *testing.T) { // Make the request req := &cstructs.AllocExecRequest{ AllocID: alloc.ID, Task: "testtask", Tty: true, Cmd: []string{"placeholder command"}, QueryOptions: nstructs.QueryOptions{ Region: "global", AuthToken: c.Token, Namespace: nstructs.DefaultNamespace, }, } // Get the handler handler, err := client.StreamingRpcHandler("Allocations.Exec") require.Nil(t, err) // Create a pipe p1, p2 := net.Pipe() defer p1.Close() defer p2.Close() errCh := make(chan error) frames := make(chan *drivers.ExecTaskStreamingResponseMsg) // Start the handler go handler(p2) go decodeFrames(t, p1, frames, errCh) // Send the request encoder := codec.NewEncoder(p1, nstructs.MsgpackHandle) require.Nil(t, encoder.Encode(req)) select { case <-time.After(3 * time.Second): require.FailNow(t, "timed out") case err := <-errCh: require.Contains(t, err.Error(), c.ExpectedError) case f := <-frames: require.Fail(t, "received unexpected frame", "frame: %#v", f) } }) } } // TestAlloc_ExecStreaming_ACL_WithIsolation_Image asserts that token only needs // alloc-exec acl policy when image isolation is used func TestAlloc_ExecStreaming_ACL_WithIsolation_Image(t *testing.T) { t.Parallel() isolation := drivers.FSIsolationImage // Start a server and client s, root, cleanupS := nomad.TestACLServer(t, nil) defer cleanupS() testutil.WaitForLeader(t, s.RPC) client, cleanupC := TestClient(t, func(c *config.Config) { c.ACLEnabled = true c.Servers = []string{s.GetConfig().RPCAddr.String()} pluginConfig := []*nconfig.PluginConfig{ { Name: "mock_driver", Config: map[string]interface{}{ "fs_isolation": string(isolation), }, }, } c.PluginLoader = catalog.TestPluginLoaderWithOptions(t, "", map[string]string{}, pluginConfig) }) defer cleanupC() // Create a bad token policyBad := mock.NamespacePolicy("other", "", []string{acl.NamespaceCapabilityDeny}) tokenBad := mock.CreatePolicyAndToken(t, s.State(), 1005, "invalid", policyBad) policyAllocExec := mock.NamespacePolicy(nstructs.DefaultNamespace, "", []string{acl.NamespaceCapabilityAllocExec}) tokenAllocExec := mock.CreatePolicyAndToken(t, s.State(), 1009, "valid2", policyAllocExec) policyAllocNodeExec := mock.NamespacePolicy(nstructs.DefaultNamespace, "", []string{acl.NamespaceCapabilityAllocExec, acl.NamespaceCapabilityAllocNodeExec}) tokenAllocNodeExec := mock.CreatePolicyAndToken(t, s.State(), 1009, "valid2", policyAllocNodeExec) job := mock.BatchJob() job.TaskGroups[0].Count = 1 job.TaskGroups[0].Tasks[0].Config = map[string]interface{}{ "run_for": "20s", "exec_command": map[string]interface{}{ "run_for": "1ms", "stdout_string": "some output", }, } // Wait for client to be running job testutil.WaitForRunningWithToken(t, s.RPC, job, root.SecretID) // Get the allocation ID args := nstructs.AllocListRequest{} args.Region = "global" args.AuthToken = root.SecretID args.Namespace = nstructs.DefaultNamespace resp := nstructs.AllocListResponse{} require.NoError(t, s.RPC("Alloc.List", &args, &resp)) require.Len(t, resp.Allocations, 1) allocID := resp.Allocations[0].ID cases := []struct { Name string Token string ExpectedError string }{ { Name: "bad token", Token: tokenBad.SecretID, ExpectedError: nstructs.ErrPermissionDenied.Error(), }, { Name: "alloc-exec token", Token: tokenAllocExec.SecretID, ExpectedError: "", }, { Name: "alloc-node-exec token", Token: tokenAllocNodeExec.SecretID, ExpectedError: "", }, { Name: "root token", Token: root.SecretID, ExpectedError: "", }, } for _, c := range cases { t.Run(c.Name, func(t *testing.T) { // Make the request req := &cstructs.AllocExecRequest{ AllocID: allocID, Task: job.TaskGroups[0].Tasks[0].Name, Tty: true, Cmd: []string{"placeholder command"}, QueryOptions: nstructs.QueryOptions{ Region: "global", AuthToken: c.Token, Namespace: nstructs.DefaultNamespace, }, } // Get the handler handler, err := client.StreamingRpcHandler("Allocations.Exec") require.Nil(t, err) // Create a pipe p1, p2 := net.Pipe() defer p1.Close() defer p2.Close() errCh := make(chan error) frames := make(chan *drivers.ExecTaskStreamingResponseMsg) // Start the handler go handler(p2) go decodeFrames(t, p1, frames, errCh) // Send the request encoder := codec.NewEncoder(p1, nstructs.MsgpackHandle) require.Nil(t, encoder.Encode(req)) select { case <-time.After(3 * time.Second): case err := <-errCh: if c.ExpectedError == "" { require.NoError(t, err) } else { require.Contains(t, err.Error(), c.ExpectedError) } case f := <-frames: // we are good if we don't expect an error if c.ExpectedError != "" { require.Fail(t, "unexpected frame", "frame: %#v", f) } } }) } } // TestAlloc_ExecStreaming_ACL_WithIsolation_Chroot asserts that token only needs // alloc-exec acl policy when chroot isolation is used func TestAlloc_ExecStreaming_ACL_WithIsolation_Chroot(t *testing.T) { t.Parallel() if runtime.GOOS != "linux" || unix.Geteuid() != 0 { t.Skip("chroot isolation requires linux root") } isolation := drivers.FSIsolationChroot // Start a server and client s, root, cleanupS := nomad.TestACLServer(t, nil) defer cleanupS() testutil.WaitForLeader(t, s.RPC) client, cleanup := TestClient(t, func(c *config.Config) { c.ACLEnabled = true c.Servers = []string{s.GetConfig().RPCAddr.String()} pluginConfig := []*nconfig.PluginConfig{ { Name: "mock_driver", Config: map[string]interface{}{ "fs_isolation": string(isolation), }, }, } c.PluginLoader = catalog.TestPluginLoaderWithOptions(t, "", map[string]string{}, pluginConfig) }) defer cleanup() // Create a bad token policyBad := mock.NamespacePolicy("other", "", []string{acl.NamespaceCapabilityDeny}) tokenBad := mock.CreatePolicyAndToken(t, s.State(), 1005, "invalid", policyBad) policyAllocExec := mock.NamespacePolicy(nstructs.DefaultNamespace, "", []string{acl.NamespaceCapabilityAllocExec}) tokenAllocExec := mock.CreatePolicyAndToken(t, s.State(), 1009, "alloc-exec", policyAllocExec) policyAllocNodeExec := mock.NamespacePolicy(nstructs.DefaultNamespace, "", []string{acl.NamespaceCapabilityAllocExec, acl.NamespaceCapabilityAllocNodeExec}) tokenAllocNodeExec := mock.CreatePolicyAndToken(t, s.State(), 1009, "alloc-node-exec", policyAllocNodeExec) job := mock.BatchJob() job.TaskGroups[0].Count = 1 job.TaskGroups[0].Tasks[0].Config = map[string]interface{}{ "run_for": "20s", "exec_command": map[string]interface{}{ "run_for": "1ms", "stdout_string": "some output", }, } // Wait for client to be running job testutil.WaitForRunningWithToken(t, s.RPC, job, root.SecretID) // Get the allocation ID args := nstructs.AllocListRequest{} args.Region = "global" args.AuthToken = root.SecretID args.Namespace = nstructs.DefaultNamespace resp := nstructs.AllocListResponse{} require.NoError(t, s.RPC("Alloc.List", &args, &resp)) require.Len(t, resp.Allocations, 1) allocID := resp.Allocations[0].ID cases := []struct { Name string Token string ExpectedError string }{ { Name: "bad token", Token: tokenBad.SecretID, ExpectedError: nstructs.ErrPermissionDenied.Error(), }, { Name: "alloc-exec token", Token: tokenAllocExec.SecretID, ExpectedError: "", }, { Name: "alloc-node-exec token", Token: tokenAllocNodeExec.SecretID, ExpectedError: "", }, { Name: "root token", Token: root.SecretID, ExpectedError: "", }, } for _, c := range cases { t.Run(c.Name, func(t *testing.T) { // Make the request req := &cstructs.AllocExecRequest{ AllocID: allocID, Task: job.TaskGroups[0].Tasks[0].Name, Tty: true, Cmd: []string{"placeholder command"}, QueryOptions: nstructs.QueryOptions{ Region: "global", AuthToken: c.Token, Namespace: nstructs.DefaultNamespace, }, } // Get the handler handler, err := client.StreamingRpcHandler("Allocations.Exec") require.Nil(t, err) // Create a pipe p1, p2 := net.Pipe() defer p1.Close() defer p2.Close() errCh := make(chan error) frames := make(chan *drivers.ExecTaskStreamingResponseMsg) // Start the handler go handler(p2) go decodeFrames(t, p1, frames, errCh) // Send the request encoder := codec.NewEncoder(p1, nstructs.MsgpackHandle) require.Nil(t, encoder.Encode(req)) select { case <-time.After(3 * time.Second): case err := <-errCh: if c.ExpectedError == "" { require.NoError(t, err) } else { require.Contains(t, err.Error(), c.ExpectedError) } case f := <-frames: // we are good if we don't expect an error if c.ExpectedError != "" { require.Fail(t, "unexpected frame", "frame: %#v", f) } } }) } } // TestAlloc_ExecStreaming_ACL_WithIsolation_None asserts that token needs // alloc-node-exec acl policy as well when no isolation is used func TestAlloc_ExecStreaming_ACL_WithIsolation_None(t *testing.T) { t.Parallel() isolation := drivers.FSIsolationNone // Start a server and client s, root, cleanupS := nomad.TestACLServer(t, nil) defer cleanupS() testutil.WaitForLeader(t, s.RPC) client, cleanup := TestClient(t, func(c *config.Config) { c.ACLEnabled = true c.Servers = []string{s.GetConfig().RPCAddr.String()} pluginConfig := []*nconfig.PluginConfig{ { Name: "mock_driver", Config: map[string]interface{}{ "fs_isolation": string(isolation), }, }, } c.PluginLoader = catalog.TestPluginLoaderWithOptions(t, "", map[string]string{}, pluginConfig) }) defer cleanup() // Create a bad token policyBad := mock.NamespacePolicy("other", "", []string{acl.NamespaceCapabilityDeny}) tokenBad := mock.CreatePolicyAndToken(t, s.State(), 1005, "invalid", policyBad) policyAllocExec := mock.NamespacePolicy(nstructs.DefaultNamespace, "", []string{acl.NamespaceCapabilityAllocExec}) tokenAllocExec := mock.CreatePolicyAndToken(t, s.State(), 1009, "alloc-exec", policyAllocExec) policyAllocNodeExec := mock.NamespacePolicy(nstructs.DefaultNamespace, "", []string{acl.NamespaceCapabilityAllocExec, acl.NamespaceCapabilityAllocNodeExec}) tokenAllocNodeExec := mock.CreatePolicyAndToken(t, s.State(), 1009, "alloc-node-exec", policyAllocNodeExec) job := mock.BatchJob() job.TaskGroups[0].Count = 1 job.TaskGroups[0].Tasks[0].Config = map[string]interface{}{ "run_for": "20s", "exec_command": map[string]interface{}{ "run_for": "1ms", "stdout_string": "some output", }, } // Wait for client to be running job testutil.WaitForRunningWithToken(t, s.RPC, job, root.SecretID) // Get the allocation ID args := nstructs.AllocListRequest{} args.Region = "global" args.AuthToken = root.SecretID args.Namespace = nstructs.DefaultNamespace resp := nstructs.AllocListResponse{} require.NoError(t, s.RPC("Alloc.List", &args, &resp)) require.Len(t, resp.Allocations, 1) allocID := resp.Allocations[0].ID cases := []struct { Name string Token string ExpectedError string }{ { Name: "bad token", Token: tokenBad.SecretID, ExpectedError: nstructs.ErrPermissionDenied.Error(), }, { Name: "alloc-exec token", Token: tokenAllocExec.SecretID, ExpectedError: nstructs.ErrPermissionDenied.Error(), }, { Name: "alloc-node-exec token", Token: tokenAllocNodeExec.SecretID, ExpectedError: "", }, { Name: "root token", Token: root.SecretID, ExpectedError: "", }, } for _, c := range cases { t.Run(c.Name, func(t *testing.T) { // Make the request req := &cstructs.AllocExecRequest{ AllocID: allocID, Task: job.TaskGroups[0].Tasks[0].Name, Tty: true, Cmd: []string{"placeholder command"}, QueryOptions: nstructs.QueryOptions{ Region: "global", AuthToken: c.Token, Namespace: nstructs.DefaultNamespace, }, } // Get the handler handler, err := client.StreamingRpcHandler("Allocations.Exec") require.Nil(t, err) // Create a pipe p1, p2 := net.Pipe() defer p1.Close() defer p2.Close() errCh := make(chan error) frames := make(chan *drivers.ExecTaskStreamingResponseMsg) // Start the handler go handler(p2) go decodeFrames(t, p1, frames, errCh) // Send the request encoder := codec.NewEncoder(p1, nstructs.MsgpackHandle) require.Nil(t, encoder.Encode(req)) select { case <-time.After(3 * time.Second): case err := <-errCh: if c.ExpectedError == "" { require.NoError(t, err) } else { require.Contains(t, err.Error(), c.ExpectedError) } case f := <-frames: // we are good if we don't expect an error if c.ExpectedError != "" { require.Fail(t, "unexpected frame", "frame: %#v", f) } } }) } } func decodeFrames(t *testing.T, p1 net.Conn, frames chan<- *drivers.ExecTaskStreamingResponseMsg, errCh chan<- error) { // Start the decoder decoder := codec.NewDecoder(p1, nstructs.MsgpackHandle) for { var msg cstructs.StreamErrWrapper if err := decoder.Decode(&msg); err != nil { if err == io.EOF || strings.Contains(err.Error(), "closed") { return } t.Logf("received error decoding: %#v", err) errCh <- fmt.Errorf("error decoding: %v", err) return } if msg.Error != nil { errCh <- msg.Error continue } var frame drivers.ExecTaskStreamingResponseMsg if err := json.Unmarshal(msg.Payload, &frame); err != nil { errCh <- err return } t.Logf("received message: %#v", msg) frames <- &frame } }
mpl-2.0
jpetto/bedrock
bin/update/deploy_base.py
7934
""" Deployment for Bedrock in production. Requires commander (https://github.com/oremj/commander) which is installed on the systems that need it. """ import random import re import time import urllib import urllib2 from commander.deploy import commands, task, hostgroups import commander_settings as settings PYTHON = settings.PYTHON_PATH NEW_RELIC_API_KEY = getattr(settings, 'NEW_RELIC_API_KEY', None) NEW_RELIC_APP_ID = getattr(settings, 'NEW_RELIC_APP_ID', None) NEW_RELIC_URL = 'https://rpm.newrelic.com/deployments.xml' GITHUB_URL = 'https://github.com/mozilla/bedrock/compare/{oldrev}...{newrev}' CRON_LOG_DIR = '/var/log/bedrock' # ########## Commands run by chief ############## # the following 3 tasks are run directly by chief, in order. @task def pre_update(ctx, ref=settings.UPDATE_REF): commands['update_code'](ref) commands['check_locale']() commands['update_info']() @task def update(ctx): commands['peep_install']() commands['update_revision_file']() commands['update_assets']() # moves files from SRC_DIR to WWW_DIR commands['checkin_changes']() commands['database']() if 'update_cron' in commands: commands['update_cron']() commands['reload_crond']() @task def deploy(ctx): commands['deploy_app']() commands['ping_newrelic']() # ########## End Commands run by chief ############## def management_cmd(ctx, cmd, use_src_dir=False): """Run a Django management command correctly.""" run_dir = settings.SRC_DIR if use_src_dir else settings.WWW_DIR with ctx.lcd(run_dir): ctx.local('LANG=en_US.UTF-8 {0} manage.py {1}'.format(PYTHON, cmd)) def peep_install_cmd(req_file): """Return the command for installing a requirements file.""" return ('{0} bin/peep.py install -r requirements/{1}.txt ' '--no-use-wheel'.format(PYTHON, req_file)) @task def reload_crond(ctx): """Restart cron daemon.""" ctx.local("killall -SIGHUP crond") @task def update_code(ctx, tag): """Update the code via git.""" with ctx.lcd(settings.SRC_DIR): ctx.local("git fetch --all") ctx.local("git checkout -f %s" % tag) # keeping submodule handling for now because legal-docs # TODO delete next two lines when all submodules are gone ctx.local("git submodule sync") ctx.local("git submodule update --init --recursive") ctx.local("find . -name '*.pyc' -delete") @task def check_locale(ctx): """Ensure locales are from the git repo.""" with ctx.lcd(settings.SRC_DIR): ctx.local('if [ ! -d locale/.git ]; then ' 'rm -rf locale && ' 'git clone https://github.com/mozilla-l10n/bedrock-l10n.git locale;' 'fi') @task def update_assets(ctx): """Compile/compress static assets and fetch external data.""" management_cmd(ctx, 'collectstatic --noinput', use_src_dir=True) @task def update_revision_file(ctx): """Add a file containing the current git hash to media.""" with ctx.lcd(settings.SRC_DIR): ctx.local("if [ -f media/revision.txt ]; then " "mv media/revision.txt media/prev-revision.txt; " "fi") ctx.local("git rev-parse HEAD > media/revision.txt") @task def database(ctx): """Update the database.""" management_cmd(ctx, 'migrate --noinput') @task def checkin_changes(ctx): """Sync files from SRC_DIR to WWW_DIR ignoring .git""" ctx.local(settings.DEPLOY_SCRIPT) @hostgroups(settings.WEB_HOSTGROUP, remote_kwargs={'ssh_key': settings.SSH_KEY}, remote_limit=1) def deploy_app(ctx): """Push code to the webheads""" print 'pushing code to {0}'.format(ctx.env['host']) ctx.remote(settings.REMOTE_UPDATE_SCRIPT) ctx.remote("service httpd graceful") time.sleep(5) @task def update_info(ctx): """Add a bunch of info to the deploy log.""" with ctx.lcd(settings.SRC_DIR): ctx.local("date") ctx.local("git branch") ctx.local("git log -3") ctx.local("git status") ctx.local("git submodule status") with ctx.lcd("locale"): ctx.local("git rev-parse HEAD") ctx.local("git status") @task def peep_install(ctx): """Install things using peep.""" with ctx.lcd(settings.SRC_DIR): # keep pip updated and do it separately # so that the subsequent call uses the new one ctx.local(peep_install_cmd('pip')) ctx.local(peep_install_cmd('prod')) # update any newly installed libs to be relocatable # this call is idempotent ctx.local('virtualenv-2.7 --relocatable ../venv') @task def ping_newrelic(ctx): if NEW_RELIC_API_KEY and NEW_RELIC_APP_ID: with ctx.lcd(settings.SRC_DIR): oldrev = ctx.local('if [ -f media/prev-revision.txt ]; then ' 'cat media/prev-revision.txt; ' 'fi').out.strip() newrev = ctx.local('if [ -f media/revision.txt ]; then ' 'cat media/revision.txt; ' 'fi').out.strip() if oldrev and newrev: log_cmd = 'git log --oneline {0}..{1}'.format(oldrev, newrev) changelog = ctx.local(log_cmd).out.strip() else: changelog = None print 'Post deployment to New Relic' desc = generate_desc(oldrev, newrev, changelog) if changelog: github_url = GITHUB_URL.format(oldrev=oldrev, newrev=newrev) changelog = '{0}\n\n{1}'.format(changelog, github_url) data = { 'deployment[description]': desc, 'deployment[revision]': newrev, 'deployment[app_id]': NEW_RELIC_APP_ID, } if changelog: data['deployment[changelog]'] = changelog data = urllib.urlencode(data) headers = {'x-api-key': NEW_RELIC_API_KEY} try: request = urllib2.Request(NEW_RELIC_URL, data, headers) urllib2.urlopen(request) except urllib2.URLError as exp: print 'Error notifying New Relic: {0}'.format(exp) @task def update_bedrock(ctx, tag): """Do typical bedrock update""" commands['pre_update'](tag) commands['update']() # utility functions # # shamelessly stolen from https://github.com/mythmon/chief-james/ def get_random_desc(): return random.choice([ 'No bugfixes--must be adding infinite loops.', 'No bugfixes--must be rot13ing function names for code security.', 'No bugfixes--must be demonstrating our elite push technology.', 'No bugfixes--must be testing james.', ]) def extract_bugs(changelog): """Takes output from git log --oneline and extracts bug numbers""" bug_regexp = re.compile(r'\bbug (\d+)\b', re.I) bugs = set() for line in changelog: for bug in bug_regexp.findall(line): bugs.add(bug) return sorted(list(bugs)) def generate_desc(from_commit, to_commit, changelog): """Figures out a good description based on what we're pushing out.""" if from_commit.startswith(to_commit): desc = 'Pushing {0} again'.format(to_commit) else: bugs = extract_bugs(changelog.split('\n')) if bugs: bugs = ['bug #{0}'.format(bug) for bug in bugs] desc = 'Fixing: {0}'.format(', '.join(bugs)) else: desc = get_random_desc() return desc def generate_cron_file(ctx, tmpl_name): with ctx.lcd(settings.WWW_DIR): ctx.local("{python} bin/gen-crons.py -p {python} -s {src_dir} " "-w {www_dir} -l {log_dir} -t {template}".format( python=PYTHON, src_dir=settings.SRC_DIR, www_dir=settings.WWW_DIR, log_dir=CRON_LOG_DIR, template=tmpl_name))
mpl-2.0
andrewmoko/openmrs-module-openhmis.cashier
omod_1.x/src/main/java/org/openmrs/module/openhmis/cashier/extension/html/AdminList.java
2556
/* * The contents of this file are subject to the OpenMRS Public 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://license.openmrs.org * * 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. * * Copyright (C) OpenHMIS. All Rights Reserved. */ package org.openmrs.module.openhmis.cashier.extension.html; import java.util.LinkedHashMap; import java.util.Map; import org.openmrs.User; import org.openmrs.api.context.Context; import org.openmrs.module.Extension; import org.openmrs.module.openhmis.cashier.api.util.PrivilegeConstants; import org.openmrs.module.openhmis.cashier.web.CashierWebConstants; import org.openmrs.module.openhmis.cashier.web.PrivilegeWebConstants; import org.openmrs.module.web.extension.AdministrationSectionExt; /** * This class defines the links that will appear on the administration page under the "openhmis.cashier.title" heading. */ public class AdminList extends AdministrationSectionExt { /** * @see AdministrationSectionExt#getMediaType() */ public Extension.MEDIA_TYPE getMediaType() { return Extension.MEDIA_TYPE.html; } /** * @see AdministrationSectionExt#getTitle() */ public String getTitle() { return "openhmis.cashier.title"; } @Override public String getRequiredPrivilege() { return PrivilegeConstants.MANAGE_BILLS; } /** * @see AdministrationSectionExt#getLinks() */ public Map<String, String> getLinks() { User authenticatedUser = Context.getAuthenticatedUser(); LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(); if (authenticatedUser.hasPrivilege(PrivilegeConstants.MANAGE_METADATA)) { map.put(CashierWebConstants.CASHIER_ROLE_PAGE, "openhmis.cashier.admin.role"); map.put(CashierWebConstants.CASH_POINTS_PAGE, "openhmis.cashier.admin.cashPoints"); map.put(CashierWebConstants.PAYMENT_MODES_PAGE, "openhmis.cashier.admin.paymentModes"); } if (authenticatedUser.hasPrivilege(PrivilegeConstants.MANAGE_BILLS)) { map.put(CashierWebConstants.RECEIPT_NUMBER_GENERATOR_PAGE, "openhmis.cashier.admin.receiptNumberGenerator"); } if (authenticatedUser.hasPrivilege(PrivilegeWebConstants.SETTING_PAGE_PRIVILEGE)) { map.put(CashierWebConstants.CASHIER_SETTINGS_PAGE, "openhmis.cashier.admin.cashierSettings"); } return map; } }
mpl-2.0
asm-products/mock-json-api-com-npm
test/specs/testUnauthorized.spec.js
1864
var express = require('express'), mock = require('../../mock.js'), port = 3001, request = require('request'), baseUrl = 'http://localhost', app = express(), server = null, routeName = null, routePath = null, statusCode = null, testScope = null; require('rootpath')(); describe("Test Mock Unauthorized Scenarios", function() { beforeEach(function () { routeName = 'fooUnauthorized'; routePath = '/api/fooUnauthorized'; statusCode = 401; testScope = 'unauthorized'; server = app.listen(port); }); afterEach(function () { server.close(); }); it("Test unauthorized response (401) NOT using queryString parameters", function(done){ var route = mock({ jsonStore: 'test/data/data.json', mockRoutes: [ { name: routeName, mockRoute: routePath, testScope: testScope } ] }); app.use(route.registerRoutes); var url = baseUrl+':'+port+routePath; request(url, function(error, response, body){ expect(response.statusCode).toEqual(statusCode); done(); }); }); it("Test unauthorized response (401) using queryString parameters", function(done){ var route = mock({ jsonStore: 'test/data/data.json', mockRoutes: [ { name: routeName, mockRoute: routePath } ] }); app.use(route.registerRoutes); var url = baseUrl+':'+port+routePath+'?scope='+testScope; request(url, function(error, response, body){ expect(response.statusCode).toEqual(statusCode); done(); }); }); });
agpl-3.0
aldridged/gtg-sugar
include/generic/SugarWidgets/SugarWidgetFieldfloat.php
3755
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * 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 Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ class SugarWidgetFieldFloat extends SugarWidgetFieldInt { function displayList($layout_def) { $vardef = $this->getVardef($layout_def); if ( isset($vardef['precision']) ) { $precision = $vardef['precision']; } else { $precision = null; } return format_number(parent::displayListPlain($layout_def), $precision, $precision); } function displayListPlain($layout_def) { return $this->displayList($layout_def); } function queryFilterEquals(&$layout_def) { return $this->_get_column_select($layout_def)."= ".$GLOBALS['db']->quote(unformat_number($layout_def['input_name0']))."\n"; } function queryFilterNot_Equals(&$layout_def) { return $this->_get_column_select($layout_def)."!=".$GLOBALS['db']->quote(unformat_number($layout_def['input_name0']))."\n"; } function queryFilterGreater(&$layout_def) { return $this->_get_column_select($layout_def)." > ".$GLOBALS['db']->quote(unformat_number($layout_def['input_name0']))."\n"; } function queryFilterLess(&$layout_def) { return $this->_get_column_select($layout_def)." < ".$GLOBALS['db']->quote(unformat_number($layout_def['input_name0']))."\n"; } function queryFilterBetween(&$layout_def) { return $this->_get_column_select($layout_def)." BETWEEN ".$GLOBALS['db']->quote(unformat_number($layout_def['input_name0'])). " AND " . $GLOBALS['db']->quote(unformat_number($layout_def['input_name1'])) . "\n"; } } ?>
agpl-3.0
nmgeek/emoncms
Modules/vis/visualisations/editrealtime.php
8308
<!-- All Emoncms code is released under the GNU Affero General Public License. See COPYRIGHT.txt and LICENSE.txt. --------------------------------------------------------------------- Emoncms - open source energy visualisation Part of the OpenEnergyMonitor project: http://openenergymonitor.org --> <?php global $path, $embed; $type = 1; ?> <!--[if IE]><script language="javascript" type="text/javascript" src="<?php echo $path;?>Lib/flot/excanvas.min.js"></script><![endif]--> <script language="javascript" type="text/javascript" src="<?php echo $path;?>Lib/flot/jquery.flot.min.js"></script> <script language="javascript" type="text/javascript" src="<?php echo $path; ?>Lib/flot/jquery.flot.selection.min.js"></script> <script language="javascript" type="text/javascript" src="<?php echo $path;?>Lib/flot/jquery.flot.time.min.js"></script> <script language="javascript" type="text/javascript" src="<?php echo $path; ?>Modules/vis/visualisations/common/api.js"></script> <script language="javascript" type="text/javascript" src="<?php echo $path; ?>Modules/vis/visualisations/common/inst.js"></script> <script language="javascript" type="text/javascript" src="<?php echo $path; ?>Modules/vis/visualisations/common/proc.js"></script> <?php if (!$embed) { ?> <h2><?php echo _("Datapoint editor:"); ?> <?php echo $feedidname; ?></h2> <p><?php echo _("Click on a datapoint to select, then in the edit box below the graph enter in the new value. You can also add another datapoint by changing the time to a point in time that does not yet have a datapoint."); ?></p> <?php } ?> <div id="graph_bound" style="height:350px; width:100%; position:relative; "> <div id="graph"></div> <div style="position:absolute; top:20px; right:20px;"> <input class="time" type="button" value="D" time="1"/> <input class="time" type="button" value="W" time="7"/> <input class="time" type="button" value="M" time="30"/> <input class="time" type="button" value="Y" time="365"/> | <input id="zoomin" type="button" value="+"/> <input id="zoomout" type="button" value="-"/> <input id="left" type="button" value="<"/> <input id="right" type="button" value=">"/> </div> <h3 style="position:absolute; top:00px; left:50px;"><span id="stats"></span></h3> </div> <div style="width:100% height:50px; background-color:#ddd; padding:10px; margin:10px;"> <?php echo _("Edit feed_"); ?><?php echo $feedid; ?> <?php echo _("@ time:"); ?> <input type="text" id="time" style="width:150px;" value="" /> <?php echo _("new value:"); ?> <input type="text" id="newvalue" style="width:150px;" value="" /> <button id="okb" class="btn btn-info"><?php echo _('Save'); ?></button> <button id="delete-button" class="btn btn-danger"><i class="icon-trash"></i><?php echo _('Delete data in window'); ?></button> </div> <div style="width:100% height:50px; background-color:#ddd; padding:10px; margin:10px;"> <?php echo _("Multiply data in window by:"); ?> <input type="text" id="multiplyvalue" style="width:150px;" value="" /> <button id="multiply-submit" class="btn btn-info"><?php echo _('Save'); ?></button> </div> <div id="myModal" class="modal hide" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="false"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel"><?php echo _('WARNING deleting feed data is permanent'); ?></h3> </div> <div class="modal-body"> <p><?php echo _('Are you sure you want to delete the data in this window?'); ?></p> </div> <div class="modal-footer"> <button class="btn" data-dismiss="modal" aria-hidden="true"><?php echo _('Cancel'); ?></button> <button id="confirmdelete" class="btn btn-primary"><?php echo _('Delete permanently'); ?></button> </div> </div> <script id="source" language="javascript" type="text/javascript"> $('#graph').width($('#graph_bound').width()); $('#graph').height($('#graph_bound').height()); var feedid = "<?php echo $feedid; ?>"; var feedname = "<?php echo $feedidname; ?>"; var type = "<?php echo $type; ?>"; var path = "<?php echo $path; ?>"; var apikey = "<?php echo $write_apikey; ?>"; var timeWindow = (3600000*24.0*7); //Initial time window var start = ((new Date()).getTime())-timeWindow; //Get start time var end = (new Date()).getTime(); //Get end time vis_feed_data(); function vis_feed_data() { var graph_data = []; var npoints = 800; interval = Math.round(((end - start)/npoints)/1000); $.ajax({ url: path+'feed/data.json', data: "id="+feedid+"&start="+start+"&end="+end+"&interval="+interval, dataType: 'json', async: false, success: function(data_in) { graph_data = data_in; } }); var stats = power_stats(graph_data); //$("#stats").html("Average: "+stats['average'].toFixed(0)+"W | "+stats['kwh'].toFixed(2)+" kWh"); var plotdata = {data: graph_data, lines: { show: true, fill: true }}; if (type == 2) plotdata = {data: graph_data, bars: { show: true, align: "center", barWidth: 3600*18*1000, fill: true}}; var plot = $.plot($("#graph"), [plotdata], { grid: { show: true, clickable: true}, xaxis: { mode: "time", timezone: "browser", min: start, max: end }, selection: { mode: "x" } }); } $("#graph").bind("plotclick", function (event, pos, item) { $("#time").val(item.datapoint[0]/1000); $("#newvalue").val(item.datapoint[1]); //$("#stats").html("Value: "+item.datapoint[1]); }); //-------------------------------------------------------------------------------------- // Graph zooming //-------------------------------------------------------------------------------------- $("#graph").bind("plotselected", function (event, ranges) { start = ranges.xaxis.from; end = ranges.xaxis.to; vis_feed_data(); }); //---------------------------------------------------------------------------------------------- // Operate buttons //---------------------------------------------------------------------------------------------- $("#zoomout").click(function () {inst_zoomout(); vis_feed_data();}); $("#zoomin").click(function () {inst_zoomin(); vis_feed_data();}); $('#right').click(function () {inst_panright(); vis_feed_data();}); $('#left').click(function () {inst_panleft(); vis_feed_data();}); $('.time').click(function () {inst_timewindow($(this).attr("time")); vis_feed_data();}); //----------------------------------------------------------------------------------------------- $('#okb').click(function () { var time = $("#time").val(); var newvalue = $("#newvalue").val(); $.ajax({ url: path+'feed/update.json', data: "&apikey="+apikey+"&id="+feedid+"&time="+time+"&value="+newvalue, dataType: 'json', async: false, success: function() {} }); vis_feed_data(); }); $('#multiply-submit').click(function () { var multiplyvalue = $("#multiplyvalue").val(); $.ajax({ url: path+'feed/scalerange.json', data: "&apikey="+apikey+"&id="+feedid+"&start="+start+"&end="+end+"&value="+multiplyvalue, dataType: 'json', async: false, success: function() {} }); vis_feed_data(); }); $('#delete-button').click(function () { $('#myModal').modal('show'); }); $("#confirmdelete").click(function() { $.ajax({ url: path+'feed/deletedatarange.json', data: "&apikey="+apikey+"&id="+feedid+"&start="+start+"&end="+end, dataType: 'json', async: false, success: function() {} }); vis_feed_data(); $('#myModal').modal('hide'); }); </script>
agpl-3.0
pombredanne/Gitorious
app/models/finders/ldap_group_finder.rb
1517
# encoding: utf-8 #-- # Copyright (C) 2012 Gitorious AS # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #++ class LdapGroupFinder def paginate_all(current_page = nil) LdapGroup.paginate(:all, :page => current_page) end def find_by_name!(name) includes = [:projects, :repositories] LdapGroup.find_by_name!(name,:include => includes) end def new_group(params={}) LdapGroup.new(params) end def create_group(params, user) group = new_group(params) begin group.transaction do group.creator = user group.save! end rescue ActiveRecord::RecordInvalid end return group end def by_admin(user) LdapGroup.find_all_by_user_id(user.id) end def find(id) LdapGroup.find(id) end def find_fuzzy(q) LdapGroup.find_fuzzy(q) end def for_user(user) LdapGroup.groups_for_user(user) end end
agpl-3.0
decidim/decidim
decidim-elections/spec/system/preview_elections_with_share_token_spec.rb
253
# frozen_string_literal: true require "spec_helper" describe "Preview elections with share token", type: :system do let(:manifest_name) { "elections" } include_context "with a component" it_behaves_like "preview component with share_token" end
agpl-3.0
osgcc/ryzom
ryzom/common/data_common/r2/r2_actions.lua
1078
-- if not r2.Actions then r2.Actions={} end -- obsolete r2._obsolete_Actions_createActionWithCondition = function(name, conditions, actions) assert(name) assert(type(conditions) == "table") assert(actions) local first = nil local previous = nil local k, condition = next(conditions, nil) while condition do local condition_if = r2.newComponent("RtNpcEventHandlerAction") condition_if.Action = "condition_if" condition_if.Parameters = condition if (previous) then table.insert(previous, condition_if) end if (first == nil) then first = condition_if end previous = condition_if.Children k, condition = next(conditions, k) end do local multi_actions = r2.newComponent("RtNpcEventHandlerAction") multi_actions.Action = "multi_actions" multi_actions.Parameters = "" multi_actions.Children = actions assert(multi_actions) if (previous) then table.insert(previous, multi_actions) end if (first == nil) then first = multi_actions end end -- table.insert(multi_actions.Children, actions) return first end --debugInfo("actions ok!!")
agpl-3.0
CourtneyJWhite/xibo-cms
lib/Controller/Resolution.php
9542
<?php /* * Xibo - Digital Signage - http://www.xibo.org.uk * Copyright (C) 2009-2014 Daniel Garner * * This file is part of Xibo. * * Xibo is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Xibo 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Xibo. If not, see <http://www.gnu.org/licenses/>. */ namespace Xibo\Controller; use baseDAO; use Kit; use Xibo\Exception\AccessDeniedException; use Xibo\Factory\ResolutionFactory; use Xibo\Helper\Form; use Xibo\Helper\Help; use Xibo\Helper\Sanitize; class Resolution extends Base { /** * Display the Resolution Page */ function displayPage() { if ($this->getSession()->get('resolution', 'Filter') == 1) { $pinned = 1; $enabled = $this->getSession()->get('resolution', 'filterEnabled'); } else { $enabled = 1; $pinned = 0; } $data = [ 'defaults' => [ 'enabled' => $enabled, 'filterPinned' => $pinned ] ]; $this->getState()->template = 'resolution-page'; $this->getState()->setData($data); } /** * Resolution Grid * * @SWG\Get( * path="/resolution", * operationId="resolutionSearch", * tags={"resolution"}, * summary="Resolution Search", * description="Search Resolutions this user has access to", * @SWG\Response( * response=200, * description="successful operation", * @SWG\Schema( * type="array", * @SWG\Items(ref="#/definitions/Resolution") * ) * ) * ) */ function grid() { $this->getSession()->set('resolution', 'ResolutionFilter', Sanitize::getCheckbox('XiboFilterPinned')); // Show enabled $filter = [ 'enabled' => $this->getSession()->set('resolution', 'filterEnabled', Sanitize::getInt('filterEnabled', -1)), 'resolutionId' => Sanitize::getInt('resolutionId') ]; $resolutions = ResolutionFactory::query($this->gridRenderSort(), $this->gridRenderFilter($filter)); foreach ($resolutions as $resolution) { /* @var \Xibo\Entity\Resolution $resolution */ if ($this->isApi()) break; $resolution->includeProperty('buttons'); // Edit Button $resolution->buttons[] = array( 'id' => 'resolution_button_edit', 'url' => $this->urlFor('resolution.edit.form', ['id' => $resolution->resolutionId]), 'text' => __('Edit') ); // Delete Button $resolution->buttons[] = array( 'id' => 'resolution_button_delete', 'url' => $this->urlFor('resolution.delete.form', ['id' => $resolution->resolutionId]), 'text' => __('Delete') ); } $this->getState()->template = 'grid'; $this->getState()->setData($resolutions); $this->getState()->recordsTotal = ResolutionFactory::countLast(); } /** * Resolution Add */ function addForm() { $this->getState()->template = 'resolution-form-add'; $this->getState()->setData([ 'help' => Help::Link('Resolution', 'Add') ]); } /** * Resolution Edit Form * @param int $resolutionId */ function editForm($resolutionId) { $resolution = ResolutionFactory::getById($resolutionId); if (!$this->getUser()->checkEditable($resolution)) throw new AccessDeniedException(); $this->getState()->template = 'resolution-form-edit'; $this->getState()->setData([ 'resolution' => $resolution, 'help' => Help::Link('Resolution', 'Edit') ]); } /** * Resolution Delete Form * @param int $resolutionId */ function deleteForm($resolutionId) { $resolution = ResolutionFactory::getById($resolutionId); if (!$this->getUser()->checkEditable($resolution)) throw new AccessDeniedException(); $this->getState()->template = 'resolution-form-delete'; $this->getState()->setData([ 'resolution' => $resolution, 'help' => Help::Link('Resolution', 'Delete') ]); } /** * Add Resolution * * @SWG\Post( * path="/resolution", * operationId="resolutionAdd", * tags={"resolution"}, * summary="Add Resolution", * description="Add new Resolution", * @SWG\Parameter( * name="resolution", * in="formData", * description="A name for the Resolution", * type="string", * required=true * ), * @SWG\Parameter( * name="width", * in="formData", * description="The Display Width of the Resolution", * type="integer", * required=true * ), * @SWG\Parameter( * name="height", * in="formData", * description="The Display Height of the Resolution", * type="integer", * required=true * ), * @SWG\Response( * response=201, * description="successful operation", * @SWG\Schema(ref="#/definitions/Resolution"), * @SWG\Header( * header="Location", * description="Location of the new record", * type="string" * ) * ) * ) */ function add() { $resolution = new \Xibo\Entity\Resolution(); $resolution->resolution = Sanitize::getString('resolution'); $resolution->width = Sanitize::getInt('width'); $resolution->height = Sanitize::getInt('height'); $resolution->save(); // Return $this->getState()->hydrate([ 'httpStatus' => 201, 'message' => sprintf(__('Added %s'), $resolution->resolution), 'id' => $resolution->resolutionId, 'data' => $resolution ]); } /** * Edit Resolution * @param int $resolutionId * * @SWG\Put( * path="/resolution/{resolutionId}", * operationId="resolutionEdit", * tags={"resolution"}, * summary="Edit Resolution", * description="Edit new Resolution", * @SWG\Parameter( * name="resolutionId", * in="path", * description="The Resolution ID to Edit", * type="integer", * required=true * ), * @SWG\Parameter( * name="resolution", * in="formData", * description="A name for the Resolution", * type="string", * required=true * ), * @SWG\Parameter( * name="width", * in="formData", * description="The Display Width of the Resolution", * type="integer", * required=true * ), * @SWG\Parameter( * name="height", * in="formData", * description="The Display Height of the Resolution", * type="integer", * required=true * ), * @SWG\Response( * response=200, * description="successful operation", * @SWG\Schema(ref="#/definitions/Resolution") * ) * ) */ function edit($resolutionId) { $resolution = ResolutionFactory::getById($resolutionId); if (!$this->getUser()->checkEditable($resolution)) throw new AccessDeniedException(); $resolution->resolution = Sanitize::getString('resolution'); $resolution->width = Sanitize::getInt('width'); $resolution->height = Sanitize::getInt('height'); $resolution->enabled = Sanitize::getCheckbox('enabled'); $resolution->save(); // Return $this->getState()->hydrate([ 'message' => sprintf(__('Edited %s'), $resolution->resolution), 'id' => $resolution->resolutionId, 'data' => $resolution ]); } /** * Delete Resolution * @param int $resolutionId * * @SWG\Delete( * path="/resolution/{resolutionId}", * operationId="resolutionDelete", * tags={"resolution"}, * summary="Delete Resolution", * description="Delete Resolution", * @SWG\Parameter( * name="resolutionId", * in="path", * description="The Resolution ID to Delete", * type="integer", * required=true * ), * @SWG\Response( * response=204, * description="successful operation" * ) * ) */ function delete($resolutionId) { $resolution = ResolutionFactory::getById($resolutionId); if (!$this->getUser()->checkDeleteable($resolution)) throw new AccessDeniedException(); $resolution->delete(); // Return $this->getState()->hydrate([ 'message' => sprintf(__('Deleted %s'), $resolution->resolution), ]); } }
agpl-3.0
vtellez/BringBack
app/libraries/libopensso-php/packs/prod_1013/config.php
738
<?php define('OPENSSO_BASE_URL', 'https://opensso.us.es/opensso/'); define('OPENSSO_COOKIE_NAME', 'iPlanetDirectoryPro'); define('OPENSSO_LOGIN_URL', OPENSSO_BASE_URL . 'UI/Login'); define('OPENSSO_LOGOUT_URL', OPENSSO_BASE_URL . 'UI/Logout'); define('OPENSSO_LOGOUT_SERVICE', OPENSSO_BASE_URL . 'identity/logout'); define('OPENSSO_IS_TOKEN_VALID', OPENSSO_BASE_URL . 'identity/isTokenValid'); define('OPENSSO_ATTRIBUTES', OPENSSO_BASE_URL . 'identity/attributes'); define('OPENSSO_COOKIE_NAME_FETCH', OPENSSO_BASE_URL . 'identity/getCookieNameForToken'); define('OPENSSO_DOMAIN', ".us.es"); // Certificados define('VALIDATE_CERT', TRUE); define('CRT_SERIALNUMBER', '210592524451737690364240169455244055745');
agpl-3.0
markaspot/Mark-a-Spot-1.6-CakePHP
plugins/media/tests/groups/model.group.php
259
<?php class AllModelGroupTest extends GroupTest { var $label = 'All model and behavior related test cases'; function AllModelGroupTest() { TestManager::addTestCasesFromDirectory($this,dirname(__FILE__) . DS . '..' . DS . 'cases' . DS . 'models'); } } ?>
agpl-3.0
dalmendras/rapidminer
src/main/java/com/rapidminer/tools/config/AbstractConfigurable.java
9340
/** * Copyright (C) 2001-2015 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.tools.config; import java.io.IOException; import java.security.Key; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import com.rapidminer.parameter.ParameterType; import com.rapidminer.repository.internal.remote.RemoteRepository; import com.rapidminer.tools.LogService; import com.rapidminer.tools.cipher.KeyGeneratorTool; import com.rapidminer.tools.config.actions.ConfigurableAction; /** * Abstract standard implementation of the {@link Configurable} class. * <p> * Contains additional methods which are not part of the {@link Configurable} interface for * compatiblity reasons, e.g {@link #getActions()} and {@link #getTestAction()}. * </p> * * @author Simon Fischer, Dominik Halfkann, Marco Boeck * */ public abstract class AbstractConfigurable implements Configurable { private int id = -1; private String name = "name undefined"; private Map<String, String> parameters = new HashMap<>(); private RemoteRepository source; @Override public int getId() { return id; } @Override public void setId(int id) { this.id = id; } /** * Returns the parameter value for the given key. The value has gone through the * {@link ParameterType#transformNewValue(String)} method. * * @param key * @return */ @Override public String getParameter(String key) { // we only have a map of key - value Strings here, but we need to apply special handling, // e.g. for ParameterTypePassword // iterate over ParameterTypes in Configurator, find the one matching the key and return the // value returned from the transformNewValue method AbstractConfigurator<? extends Configurable> configurator = ConfigurationManager.getInstance() .getAbstractConfigurator(getTypeId()); List<ParameterType> parameterTypes = configurator.getParameterTypes(configurator.getParameterHandler(this)); for (ParameterType type : parameterTypes) { if (type.getKey().equals(key)) { return type.transformNewValue(parameters.get(key)); } } return parameters.get(key); } /** * Returns the xml representation of this parameter value. * * @param key * @return */ public String getParameterAsXMLString(String key) { return parameters.get(key); } /** * Returns the xml representation of this parameter value. If the {@link ParameterType} uses * encryption, will decrypt the value with the given old key and encrypt it again with the * specified new key. * * @param key * key of the parameter * @param decryptKey * used to decrypt the parameter values * @param encryptKey * used to encrypt the parameter values again * @return */ public String getParameterAndChangeEncryption(String key, Key decryptKey, Key encryptKey) { String value = parameters.get(key); // we only have a map of key - value Strings here, but we need to apply special handling, // e.g. for ParameterTypePassword // iterate over ParameterTypes in Configurator, find the one matching the key and return the // decrypted and encrypted again value AbstractConfigurator<? extends Configurable> configurator = ConfigurationManager.getInstance() .getAbstractConfigurator(getTypeId()); for (ParameterType type : configurator.getParameterTypes(configurator.getParameterHandler(this))) { if (type.getKey().equals(key)) { // store current key (will most likely be identical to the decrypt key) Key currentKey = null; try { currentKey = KeyGeneratorTool.getUserKey(); } catch (IOException e) { // should not happen, if it does we simply cannot restore the original key LogService.getRoot().log(Level.WARNING, "com.rapidminer.tools.config.AbstractConfigurable.cannot_backup_key"); } // configurables are stored encrypted, so set the decryption key KeyGeneratorTool.setUserKey(decryptKey); // decrypt it with decryption key value = type.transformNewValue(parameters.get(key)); // set encryption key KeyGeneratorTool.setUserKey(encryptKey); // encrypt it again with encryption key value = type.toString(value); // restore key which was used before this call if (currentKey != null) { KeyGeneratorTool.setUserKey(currentKey); } break; } } return value; } @Override public void setParameter(String key, String value) { parameters.put(key, value); } @Override public void configure(Map<String, String> parameters) { this.parameters.clear(); this.parameters.putAll(parameters); } @Override public Map<String, String> getParameters() { return parameters; } @Override public String getName() { return this.name; } @Override public void setName(String name) { this.name = name; } @Override public void setSource(RemoteRepository source) { this.source = source; } @Override public RemoteRepository getSource() { return source; } @Override public String getShortInfo() { return null; } @Override public boolean hasSameValues(Configurable comparedConfigurable) { if (!name.equals(comparedConfigurable.getName())) { return false; } if (this.parameters.size() != comparedConfigurable.getParameters().size()) { return false; } for (Map.Entry<String, String> parameterEntry : this.parameters.entrySet()) { if (!parameterEntry.getValue().toString() .equals(comparedConfigurable.getParameter(parameterEntry.getKey()).toString())) { // If the string comparison of the 2 objects with equals() returns false return false; } } return true; } /** * @deprecated Use {@link AbstractConfigurable#isEmptyOrDefault(AbstractConfigurator)} instead. */ @Deprecated @Override public boolean isEmptyOrDefault(Configurator<? extends Configurable> configurator) { return isEmptyOrDefault((AbstractConfigurator<? extends Configurable>) configurator); } /** * Checks if the Configurable is empty (has no values/only empty values/default values) * * @param configurator * The configurator to resolve the default values from **/ public boolean isEmptyOrDefault(AbstractConfigurator<? extends Configurable> configurator) { if (this.getName() != null && !this.getName().equals("")) { return false; } else if (this.getParameters() != null && this.getParameters().size() > 0) { for (String key : this.getParameters().keySet()) { // find default value String defaultValue = ""; List<ParameterType> parameterTypes = configurator.getParameterTypes(configurator.getParameterHandler(this)); for (ParameterType type : parameterTypes) { if (type.getKey().equals(key)) { defaultValue = type.getDefaultValueAsString(); } } if (this.getParameters().get(key) != null && !this.getParameters().get(key).equals("") && !this.getParameters().get(key).equals(defaultValue)) { return false; } } return true; } return true; } /** * Returns a list of {@link ConfigurableAction}s. They can be used to perform various tasks * associated with this configuration type, e.g. clearing a cache. * <p> * If no actions are required for this configuration type, returns <code>null</code>. * </p> * These actions can be defined per {@link Configurable} instance, so two {@link Configurable}s * of the same {@link Configurator} type can have different actions. </p> * <p> * Also the actions can be changed dynamically, as they are retrieved each time they are * required. * </p> * * @return */ public Collection<ConfigurableAction> getActions() { return null; } /** * Returns a {@link TestConfigurableAction} which tests the settings for the * {@link Configurable}, e.g. a connection. * <p> * If no test action is required, returns <code>null</code>. * </p> * These actions can be defined per {@link Configurable} instance, so two {@link Configurable}s * of the same {@link Configurator} type can have different actions. </p> * <p> * Also the actions can be changed dynamically, as they are retrieved each time they are * required. * </p> * * @return */ public TestConfigurableAction getTestAction() { return null; } }
agpl-3.0
kat-co/juju
state/workers/restart_test.go
7942
// Copyright 2016 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package workers_test import ( "time" "github.com/juju/errors" "github.com/juju/loggo" "github.com/juju/testing" jc "github.com/juju/testing/checkers" "github.com/juju/utils/clock" gc "gopkg.in/check.v1" "github.com/juju/juju/state/workers" "github.com/juju/juju/worker" "github.com/juju/juju/worker/workertest" ) type RestartWorkersSuite struct { testing.IsolationSuite } var _ = gc.Suite(&RestartWorkersSuite{}) func (*RestartWorkersSuite) TestValidateSuccess(c *gc.C) { config := workers.RestartConfig{ Factory: struct{ workers.Factory }{}, Logger: loggo.GetLogger("test"), Clock: struct{ clock.Clock }{}, Delay: time.Nanosecond, } err := config.Validate() c.Check(err, jc.ErrorIsNil) } func (*RestartWorkersSuite) TestValidateMissingFactory(c *gc.C) { config := validRestartConfig() config.Factory = nil checkInvalidRestartConfig(c, config, "nil Factory not valid") } func (*RestartWorkersSuite) TestValidateUninitializedLogger(c *gc.C) { config := validRestartConfig() config.Logger = loggo.Logger{} checkInvalidRestartConfig(c, config, "uninitialized Logger not valid") } func (*RestartWorkersSuite) TestValidateMissingClock(c *gc.C) { config := validRestartConfig() config.Clock = nil checkInvalidRestartConfig(c, config, "nil Clock not valid") } func (*RestartWorkersSuite) TestValidateMissingDelay(c *gc.C) { config := validRestartConfig() config.Delay = 0 checkInvalidRestartConfig(c, config, "non-positive Delay not valid") } func (*RestartWorkersSuite) TestValidateNegativeDelay(c *gc.C) { config := validRestartConfig() config.Delay = -time.Second checkInvalidRestartConfig(c, config, "non-positive Delay not valid") } func (*RestartWorkersSuite) TestNewLeadershipManagerError(c *gc.C) { fix := Fixture{ LW_errors: []error{ErrFailStart}, } fix.FailRestart(c, "cannot create leadership lease manager: bad start") } func (*RestartWorkersSuite) TestNewSingularManagerError(c *gc.C) { fix := Fixture{ LW_errors: []error{nil}, SW_errors: []error{ErrFailStart}, } fix.FailRestart(c, "cannot create singular lease manager: bad start") } func (*RestartWorkersSuite) TestNewTxnLogWatcherError(c *gc.C) { fix := Fixture{ LW_errors: []error{nil}, SW_errors: []error{nil}, TLW_errors: []error{ErrFailStart}, } fix.FailRestart(c, "cannot create transaction log watcher: bad start") } func (*RestartWorkersSuite) TestNewPresenceWatcherError(c *gc.C) { fix := BasicFixture() fix.PW_errors = []error{ErrFailStart} fix.FailRestart(c, "cannot create presence watcher: bad start") } func (*RestartWorkersSuite) TestLeadershipManagerDelay(c *gc.C) { fix := BasicFixture() fix.LW_errors = []error{errors.New("oof")} fix.RunRestart(c, func(ctx Context, rw *workers.RestartWorkers) { w := NextWorker(c, ctx.LWs()) c.Assert(w, gc.NotNil) AssertWorker(c, rw.LeadershipManager(), w) w.Kill() clock := ctx.Clock() WaitAlarms(c, clock, 1) clock.Advance(almostFiveSeconds) AssertWorker(c, rw.LeadershipManager(), w) err := workertest.CheckKill(c, rw) c.Check(err, gc.ErrorMatches, "error stopping leadership lease manager: oof") }) } func (*RestartWorkersSuite) TestSingularManagerDelay(c *gc.C) { fix := BasicFixture() fix.SW_errors = []error{errors.New("oof")} fix.RunRestart(c, func(ctx Context, rw *workers.RestartWorkers) { w := NextWorker(c, ctx.SWs()) c.Assert(w, gc.NotNil) AssertWorker(c, rw.SingularManager(), w) w.Kill() clock := ctx.Clock() WaitAlarms(c, clock, 1) clock.Advance(almostFiveSeconds) AssertWorker(c, rw.SingularManager(), w) err := workertest.CheckKill(c, rw) c.Check(err, gc.ErrorMatches, "error stopping singular lease manager: oof") }) } func (*RestartWorkersSuite) TestTxnLogWatcherDelay(c *gc.C) { fix := BasicFixture() fix.TLW_errors = []error{errors.New("oof")} fix.RunRestart(c, func(ctx Context, rw *workers.RestartWorkers) { w := NextWorker(c, ctx.TLWs()) c.Assert(w, gc.NotNil) AssertWorker(c, rw.TxnLogWatcher(), w) w.Kill() clock := ctx.Clock() WaitAlarms(c, clock, 1) clock.Advance(almostFiveSeconds) AssertWorker(c, rw.TxnLogWatcher(), w) err := workertest.CheckKill(c, rw) c.Check(err, gc.ErrorMatches, "error stopping transaction log watcher: oof") }) } func (*RestartWorkersSuite) TestPresenceWatcherDelay(c *gc.C) { fix := BasicFixture() fix.PW_errors = []error{errors.New("oof")} fix.RunRestart(c, func(ctx Context, rw *workers.RestartWorkers) { w := NextWorker(c, ctx.PWs()) c.Assert(w, gc.NotNil) AssertWorker(c, rw.PresenceWatcher(), w) w.Kill() clock := ctx.Clock() WaitAlarms(c, clock, 1) clock.Advance(almostFiveSeconds) AssertWorker(c, rw.PresenceWatcher(), w) err := workertest.CheckKill(c, rw) c.Check(err, gc.ErrorMatches, "error stopping presence watcher: oof") }) } func (*RestartWorkersSuite) TestLeadershipManagerRestart(c *gc.C) { fix := BasicFixture() fix.LW_errors = []error{errors.New("oof"), nil} fix.RunRestart(c, func(ctx Context, rw *workers.RestartWorkers) { w := NextWorker(c, ctx.LWs()) c.Assert(w, gc.NotNil) AssertWorker(c, rw.LeadershipManager(), w) w.Kill() clock := ctx.Clock() WaitAlarms(c, clock, 1) clock.Advance(fiveSeconds) w2 := NextWorker(c, ctx.LWs()) c.Assert(w, gc.NotNil) WaitWorker(c, LM_getter(rw), w2) workertest.CleanKill(c, rw) }) } func (*RestartWorkersSuite) TestSingularManagerRestart(c *gc.C) { fix := BasicFixture() fix.SW_errors = []error{errors.New("oof"), nil} fix.RunRestart(c, func(ctx Context, rw *workers.RestartWorkers) { w := NextWorker(c, ctx.SWs()) c.Assert(w, gc.NotNil) AssertWorker(c, rw.SingularManager(), w) w.Kill() clock := ctx.Clock() WaitAlarms(c, clock, 1) clock.Advance(fiveSeconds) w2 := NextWorker(c, ctx.SWs()) c.Assert(w, gc.NotNil) WaitWorker(c, SM_getter(rw), w2) workertest.CleanKill(c, rw) }) } func (*RestartWorkersSuite) TestTxnLogWatcherRestart(c *gc.C) { fix := BasicFixture() fix.TLW_errors = []error{errors.New("oof"), nil} fix.RunRestart(c, func(ctx Context, rw *workers.RestartWorkers) { w := NextWorker(c, ctx.TLWs()) c.Assert(w, gc.NotNil) AssertWorker(c, rw.TxnLogWatcher(), w) w.Kill() clock := ctx.Clock() WaitAlarms(c, clock, 1) clock.Advance(fiveSeconds) w2 := NextWorker(c, ctx.TLWs()) c.Assert(w, gc.NotNil) WaitWorker(c, TLW_getter(rw), w2) workertest.CleanKill(c, rw) }) } func (*RestartWorkersSuite) TestPresenceWatcherRestart(c *gc.C) { fix := BasicFixture() fix.PW_errors = []error{errors.New("oof"), nil} fix.RunRestart(c, func(ctx Context, rw *workers.RestartWorkers) { w := NextWorker(c, ctx.PWs()) c.Assert(w, gc.NotNil) AssertWorker(c, rw.PresenceWatcher(), w) w.Kill() clock := ctx.Clock() WaitAlarms(c, clock, 1) clock.Advance(fiveSeconds) w2 := NextWorker(c, ctx.PWs()) c.Assert(w, gc.NotNil) WaitWorker(c, PW_getter(rw), w2) workertest.CleanKill(c, rw) }) } func (*RestartWorkersSuite) TestStopsAllWorkers(c *gc.C) { fix := BasicFixture() fix.RunRestart(c, func(ctx Context, rw *workers.RestartWorkers) { workertest.CleanKill(c, rw) for _, ch := range []<-chan worker.Worker{ ctx.LWs(), ctx.SWs(), ctx.TLWs(), ctx.PWs(), } { w := NextWorker(c, ch) workertest.CheckKilled(c, w) } }) } func validRestartConfig() workers.RestartConfig { return workers.RestartConfig{ Factory: struct{ workers.Factory }{}, Logger: loggo.GetLogger("test"), Clock: struct{ clock.Clock }{}, Delay: time.Nanosecond, } } func checkInvalidRestartConfig(c *gc.C, config workers.RestartConfig, match string) { check := func(err error) { c.Check(err, jc.Satisfies, errors.IsNotValid) c.Check(err, gc.ErrorMatches, match) } err := config.Validate() check(err) rw, err := workers.NewRestartWorkers(config) if !c.Check(rw, gc.IsNil) { workertest.DirtyKill(c, rw) } check(err) }
agpl-3.0