repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
GobiernoFacil/agentes-v2
resources/views/aspirant/notices/notices-apply-proof.blade.php
995
@extends('layouts.admin.fellow_master') @section('title', 'Aplicar a convocatoria '.$notice->title ) @section('description', 'Aplicar a convocatoria '.$notice->title) @section('body_class', 'aspirante convocatoria') @section('breadcrumb_type', 'notice apply comprobante') @section('breadcrumb', 'layouts.aspirant.breadcrumb.b_notices') @section('content') <!-- title --> @include('aspirant.title_layout') <div class="row"> <div class="col-sm-12"> @include('aspirant.notices.forms.apply-4') </div> </div> @endsection @section('js-content') <script> // Set the date we're counting down to var countDownDate = new Date("{{ date('M j, Y',strtotime($notice->end)) }} 23:59:59").getTime(); </script> <script src="{{url('js/countdown.js')}}"></script> <script> var update_b = document.getElementById('update_b'); update_b.addEventListener('click',function(e){ e.preventDefault(); $('#updateBoxB').hide(); $('#inputFile').show(); console.log("click"); }); </script> @endsection
gpl-3.0
s20121035/rk3288_android5.1_repo
hardware/rockchip/sensor/mid/SensorBase.cpp
4703
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <fcntl.h> #include <errno.h> #include <math.h> #include <poll.h> #include <unistd.h> #include <dirent.h> #include <sys/select.h> #include <cutils/log.h> #include <linux/input.h> #include "SensorBase.h" /*****************************************************************************/ SensorBase::SensorBase( const char* dev_name, const char* data_name) : dev_name(dev_name), data_name(data_name), dev_fd(-1), data_fd(-1) { data_fd = openInput(data_name); } SensorBase::~SensorBase() { if (data_fd >= 0) { close(data_fd); } if (dev_fd >= 0) { close(dev_fd); } } int SensorBase::open_device() { if (dev_fd<0 && dev_name) { dev_fd = open(dev_name, O_RDONLY); LOGE_IF(dev_fd<0, "Couldn't open %s (%s)", dev_name, strerror(errno)); } return 0; } int SensorBase::close_device() { if (dev_fd >= 0) { close(dev_fd); dev_fd = -1; } return 0; } int SensorBase::getFd() const { return data_fd; } int SensorBase::setDelay(int32_t handle, int64_t ns) { return 0; } bool SensorBase::hasPendingEvents() const { return false; } int64_t SensorBase::getTimestamp() { struct timespec t; t.tv_sec = t.tv_nsec = 0; clock_gettime(CLOCK_MONOTONIC, &t); return int64_t(t.tv_sec)*1000000000LL + t.tv_nsec; } struct input_dev { int fd; char name[80]; }; static int getInput(const char *inputName) { int fd = -1; unsigned i; static bool first = true; static struct input_dev dev[255]; if (first) { int fd = -1; const char *dirname = "/dev/input"; char devname[PATH_MAX]; char *filename; DIR *dir; struct dirent *de; first = false; for (i = 0; i < sizeof(dev)/sizeof(dev[0]); i++) { dev[i].fd = -1; dev[i].name[0] = '\0'; } i = 0; dir = opendir(dirname); if (dir == NULL) return -1; strcpy(devname, dirname); filename = devname + strlen(devname); *filename++ = '/'; while ((de = readdir(dir))) { if (de->d_name[0] == '.' && (de->d_name[1] == '\0' || (de->d_name[1] == '.' && de->d_name[2] == '\0'))) continue; strcpy(filename, de->d_name); fd = open(devname, O_RDONLY); if (fd >= 0) { char name[80]; if (ioctl(fd, EVIOCGNAME(sizeof(name) - 1), &name) >= 1) { dev[i].fd = fd; strncpy(dev[i].name, name, sizeof(dev[i].name)); } } i++; } closedir(dir); } for (i = 0; i < sizeof(dev)/sizeof(dev[0]); i++) { if (!strncmp(inputName, dev[i].name, sizeof(dev[i].name))) { fd = dev[i].fd; break; } } LOGE_IF(fd < 0, "couldn't find '%s' input device", inputName); return fd; } int SensorBase::openInput(const char* inputName) { int fd = -1; const char *dirname = "/dev/input"; char devname[PATH_MAX]; char *filename; DIR *dir; struct dirent *de; return getInput(inputName); dir = opendir(dirname); if(dir == NULL) return -1; strcpy(devname, dirname); filename = devname + strlen(devname); *filename++ = '/'; while((de = readdir(dir))) { if(de->d_name[0] == '.' && (de->d_name[1] == '\0' || (de->d_name[1] == '.' && de->d_name[2] == '\0'))) continue; strcpy(filename, de->d_name); fd = open(devname, O_RDONLY); if (fd>=0) { char name[80]; if (ioctl(fd, EVIOCGNAME(sizeof(name) - 1), &name) < 1) { name[0] = '\0'; } if (!strcmp(name, inputName)) { break; } else { close(fd); fd = -1; } } } closedir(dir); LOGE_IF(fd<0, "couldn't find '%s' input device", inputName); return fd; }
gpl-3.0
gavinfernandes2012/NotACellSim
src/test_chromosome.cpp
174
#include "chromosome.hpp" int main(){ std::string FilePath = "dna/Arabidopsis_thaliana.TAIR10.dna.chromosome.1.fa"; Chromosome TestChoromosome(FilePath, 1); return 0; }
gpl-3.0
Valansch/RedMew
map_gen/maps/tetris/scenario.lua
12062
local Event = require 'utils.event' local Token = require 'utils.token' local Task = require 'utils.task' local Global = require 'utils.global' local Debug = require 'utils.debug' local Map = require 'map_gen.maps.tetris.shape' local Tetrimino = require 'map_gen.maps.tetris.tetrimino'(Map) local View = require 'map_gen.maps.tetris.view' local InfinityChest = require 'features.infinite_storage_chest' local states = require 'map_gen.maps.tetris.states' local StateMachine = require 'utils.state_machine' local RS = require 'map_gen.shared.redmew_surface' local MGSP = require 'resources.map_gen_settings' local tetriminos = {} local primitives = { tetri_spawn_y_position = -160, winner_option_index = 0, state = states.voting, next_vote_finished = 305, points = 0, down_substate = 0 } local player_votes = {} local options = { { button = View.button_enum.ccw_button, action_func_name = 'rotate', args = {false}, transition = states.moving }, { button = View.button_enum.noop_button, action_func_name = 'noop', args = {}, transition = states.moving }, { button = View.button_enum.cw_button, action_func_name = 'rotate', args = {true}, transition = states.moving }, { button = View.button_enum.left_button, action_func_name = 'move', args = {-1, 0}, transition = states.moving }, { button = View.button_enum.down_button, transition = states.down }, { button = View.button_enum.right_button, action_func_name = 'move', args = {1, 0}, transition = states.moving }, { button = View.button_enum.pause_button, action_func_name = 'noop', args = {}, transition = states.pause } } local machine = StateMachine.new(states.voting) local player_zoom = {} local player_force = nil local play_surface = nil Global.register( { tetriminos = tetriminos, primitives = primitives, player_votes = player_votes, player_zoom = player_zoom, machine = machine }, function(tbl) tetriminos = tbl.tetriminos primitives = tbl.primitives player_votes = tbl.player_votes player_zoom = tbl.player_zoom machine = tbl.machine end ) local point_table = {1, 3, 5, 9} local tetris_tick_duration = 61 global.vote_delay = 10 -- Use redmew_surface to give us a waterworld and a spawn location RS.set_spawn_position({x = 8, y = 8}) RS.set_map_gen_settings({MGSP.waterworld}) local function calculate_winner() if StateMachine.in_state(machine, states.down) then --TODO: Fix return --Halt vote if in down mode end Debug.print('calculating winner') local vote_sum = {0, 0, 0, 0, 0, 0, 0} for _, vote in pairs(player_votes) do vote_sum[vote] = vote_sum[vote] + 1 end local winners = {} local max = math.max(vote_sum[1], vote_sum[2], vote_sum[3], vote_sum[4], vote_sum[5], vote_sum[6], vote_sum[7]) for candidate, n_votes in pairs(vote_sum) do if max == n_votes then table.insert(winners, candidate) end View.set_vote_number(options[candidate].button, n_votes) end local winner_option_index = 0 if max > 0 then winner_option_index = winners[math.random(#winners)] end primitives.winner_option_index = winner_option_index if _DEBUG and (winner_option_index > 0) then Debug.print('Calculated winner: ' .. View.pretty_names[options[winner_option_index].button]) end end local function player_vote(player, option_index) local old_vote = player_votes[player.index] if old_vote == option_index then return end local vote_button = nil local old_vote_button = nil if option_index then vote_button = options[option_index].button end if old_vote then old_vote_button = options[old_vote].button end player_votes[player.index] = option_index if _DEBUG then Debug.print(string.format('%s voted for %s', player.name, View.pretty_names[vote_button])) end StateMachine.transition(machine, states.voting) calculate_winner() View.set_player_vote(player, vote_button, old_vote_button) end for option_index, option in pairs(options) do View.bind_button( option.button, function(player) player_vote(player, option_index) end ) end local function spawn_new_tetrimino() table.insert(tetriminos, Tetrimino.new(play_surface, {x = 0, y = primitives.tetri_spawn_y_position})) end local function collect_full_row_resources(tetri) local active_qchunks = Tetrimino.active_qchunks(tetri) local storage = {} local full_rows = {} local rows = {} local position = tetri.position local tetri_y = position.y local surface = tetri.surface local get_tile = surface.get_tile local find_entities_filtered = surface.find_entities_filtered for _, qchunk in pairs(active_qchunks) do local q_y = qchunk.y if not rows[q_y] then rows[q_y] = true local y = tetri_y + 16 * q_y - 14 local row_full = true for x = -178, 178, 16 do local tile = get_tile(x, y) if tile.valid and tile.name == 'water' then row_full = false break end end if row_full then table.insert(full_rows, q_y) for _, patch in pairs(find_entities_filtered {type = 'resource', area = {{-178, y}, {162, y + 12}}}) do local subtotal = storage[patch.name] or 0 storage[patch.name] = subtotal + patch.amount patch.destroy() end end end end if #full_rows > 0 then local points = point_table[#full_rows] for resource, amount in pairs(storage) do storage[resource] = amount * points if resource == 'crude-oil' then storage[resource] = nil if #full_rows == 1 then return end end end local x = position.x + active_qchunks[1].x * 16 - 9 local y = tetri_y + active_qchunks[1].y * 16 - 9 local chest = InfinityChest.create_chest(tetri.surface, {x, y}, storage) chest.minable = false chest.destructible = false primitives.points = primitives.points + points * 100 View.set_points(primitives.points) end end local function tetrimino_finished(tetri) local final_y_position = tetri.position.y if final_y_position < (primitives.tetri_spawn_y_position + 352) then primitives.tetri_spawn_y_position = final_y_position - 256 player_force.chart(tetri.surface, {{-192, final_y_position - 352}, {160, final_y_position - 176}}) end StateMachine.transition(machine, states.voting) collect_full_row_resources(tetri) spawn_new_tetrimino() end local chart_area = Token.register( function(data) data.force.chart(data.surface, data.area) end ) local switch_state = Token.register( function(data) StateMachine.transition(machine, data.state) end ) local move_down = Token.register( function() for key, tetri in pairs(tetriminos) do if not Tetrimino.move(tetri, 0, 1) then tetrimino_finished(tetri) --If collided with ground fire finished event tetriminos[key] = nil end local pos = tetri.position Task.set_timeout_in_ticks( 10, chart_area, { force = player_force, surface = play_surface, area = { {pos.x - 32, pos.y - 32}, {pos.x + 64, pos.y + 64} } } ) end end ) local function execute_vote_tick() if game.tick < primitives.next_vote_finished then return end local winner = options[primitives.winner_option_index] if winner then StateMachine.transition(machine, winner.transition) View.set_last_move(winner.button) else View.set_last_move(nil) StateMachine.transition(machine, states.moving) end primitives.winner_option_index = 0 for player_index, _ in pairs(player_votes) do -- reset poll player_votes[player_index] = nil end View.reset_poll_buttons() end local function execute_winner_action() for key, tetri in pairs(tetriminos) do --Execute voted action local winner = options[primitives.winner_option_index] --Execute voted action if winner then local action = Tetrimino[winner.action_func_name] if action then action(tetri, winner.args[1], winner.args[2]) end end end Task.set_timeout_in_ticks(16, move_down) Task.set_timeout_in_ticks(26, switch_state, {state = states.voting}) end local spawn_new_tetrimino_token = Token.register(spawn_new_tetrimino) Event.on_init( function() player_force = game.forces.player play_surface = RS.get_surface() player_force.chart(play_surface, {{-192, -432}, {160, 0}}) Task.set_timeout_in_ticks(30 * tetris_tick_duration - 15, spawn_new_tetrimino_token) View.enable_vote_buttons(true) end ) Event.add( defines.events.on_tick, function() if StateMachine.in_state(machine, states.voting) then local progress = (primitives.next_vote_finished - game.tick + 1) / global.vote_delay / tetris_tick_duration if progress >= 0 and progress <= 1 then View.set_progress(progress) end end end ) local function execute_down_tick() local down_state = primitives.down_substate if down_state > 3 then primitives.down_substate = 0 StateMachine.transition(machine, states.voting) return end primitives.down_substate = down_state + 1 Task.set_timeout_in_ticks(16, move_down) end StateMachine.register_state_tick_callback(machine, states.voting, execute_vote_tick) StateMachine.register_state_tick_callback(machine, states.down, execute_down_tick) StateMachine.register_transition_callback( machine, states.voting, states.pause, function() View.enable_vote_buttons(true) game.print('Pausing...') end ) StateMachine.register_transition_callback( machine, states.pause, states.voting, function() primitives.next_vote_finished = global.vote_delay * tetris_tick_duration + game.tick game.print('Resuming...') end ) StateMachine.register_transition_callback( machine, states.moving, states.voting, function() View.enable_vote_buttons(true) end ) StateMachine.register_transition_callback( machine, states.down, states.voting, function() View.enable_vote_buttons(true) end ) StateMachine.register_transition_callback( machine, states.voting, states.down, function() primitives.next_vote_finished = (3 + global.vote_delay) * tetris_tick_duration + game.tick View.enable_vote_buttons(false) end ) StateMachine.register_transition_callback( machine, states.voting, states.moving, function() View.enable_vote_buttons(false) primitives.next_vote_finished = global.vote_delay * tetris_tick_duration + game.tick execute_winner_action() end ) Event.on_nth_tick( tetris_tick_duration, function() StateMachine.machine_tick(machine) end ) Event.add( defines.events.on_player_left_game, function(event) player_votes[event.player_index] = nil end ) return Map.get_map()
gpl-3.0
Commercial-Group/CG-Theme
wp-content/plugins/divi-booster/core/fixes/095-secondary-nav-hover-color/wp_head_style.php
388
<?php if (!defined('ABSPATH')) { exit(); } // No direct access list($name, $option) = $this->get_setting_bases(__FILE__); ?> #top-header #et-info-phone a:hover, #top-header #et-info a:hover span#et-info-phone, #top-header #et-info a:hover span#et-info-email, #top-header .et-social-icon a:hover { color: <?php echo htmlentities(@$option['hovercol']); ?> !important; }
gpl-3.0
51zhaoshi/myyyyshop
Microsoft.Practices.ObjectBuilder_Source/Microsoft.Practices.ObjectBuilder/PropertySetterStrategy.cs
2328
namespace Microsoft.Practices.ObjectBuilder { using Microsoft.Practices.ObjectBuilder.Properties; using System; using System.Globalization; using System.Reflection; public class PropertySetterStrategy : BuilderStrategy { public override object BuildUp(IBuilderContext context, Type typeToBuild, object existing, string idToBuild) { if (existing != null) { this.InjectProperties(context, existing, idToBuild); } return base.BuildUp(context, typeToBuild, existing, idToBuild); } private void InjectProperties(IBuilderContext context, object obj, string id) { if (obj != null) { Type typePolicyAppliesTo = obj.GetType(); IPropertySetterPolicy policy = context.Policies.Get<IPropertySetterPolicy>(typePolicyAppliesTo, id); if (policy != null) { foreach (IPropertySetterInfo info in policy.Properties.Values) { PropertyInfo propInfo = info.SelectProperty(context, typePolicyAppliesTo, id); if (propInfo != null) { if (!propInfo.CanWrite) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.CannotInjectReadOnlyProperty, new object[] { typePolicyAppliesTo, propInfo.Name })); } object obj2 = info.GetValue(context, typePolicyAppliesTo, id, propInfo); if (obj2 != null) { Guard.TypeIsAssignableFromType(propInfo.PropertyType, obj2.GetType(), obj.GetType()); } if (base.TraceEnabled(context)) { base.TraceBuildUp(context, typePolicyAppliesTo, id, Resources.CallingProperty, new object[] { propInfo.Name, propInfo.PropertyType.Name }); } propInfo.SetValue(obj, obj2, null); } } } } } } }
gpl-3.0
henkelis/sonospy
web2py/applications/admin/languages/zh-cn.py
18109
# coding: utf8 { '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '(something like "it-it")': '(\xe5\xb0\xb1\xe5\x83\x8f\xe8\xbf\x99\xe6\xa0\xb7 "it-it")', 'A new version of web2py is available': '\xe6\x96\xb0\xe7\x89\x88\xe6\x9c\xacweb2py\xe5\xb7\xb2\xe7\xbb\x8f\xe5\x8f\xaf\xe7\x94\xa8', 'A new version of web2py is available: %s': '\xe6\x96\xb0\xe7\x89\x88\xe6\x9c\xac\xe7\x9a\x84web2py\xe5\xb7\xb2\xe7\xbb\x8f\xe5\x8f\xaf\xe7\x94\xa8: %s', 'A new version of web2py is available: Version 1.75.4 (2010-02-18 20:57:56)\n': 'A new version of web2py is available: Version 1.75.4 (2010-02-18 20:57:56)\r\n', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': '\xe6\xb3\xa8\xe6\x84\x8f\xef\xbc\x9a\xe7\x99\xbb\xe5\xbd\x95\xe7\xae\xa1\xe7\x90\x86\xe7\x95\x8c\xe9\x9d\xa2\xe5\xbf\x85\xe9\xa1\xbb\xe9\x80\x9a\xe8\xbf\x87\xe5\xae\x89\xe5\x85\xa8(HTTPS)\xe8\xbf\x9e\xe6\x8e\xa5\xef\xbc\x8c\xe6\x88\x96\xe8\x80\x85\xe6\x9d\xa5\xe8\x87\xaa\xe4\xba\x8e\xe6\x9c\xac\xe6\x9c\xba\xe3\x80\x82', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': '\xe6\xb3\xa8\xe6\x84\x8f\xef\xbc\x9a\xe6\xb5\x8b\xe8\xaf\x95\xe4\xb8\x8d\xe6\x98\xaf\xe5\xa4\x9a\xe7\xba\xbf\xe7\xa8\x8b\xe5\xae\x89\xe5\x85\xa8\xe7\x9a\x84\xef\xbc\x8c\xe6\x89\x80\xe4\xbb\xa5\xe8\xaf\xb7\xe5\x8b\xbf\xe5\x90\x8c\xe6\x97\xb6\xe5\x90\xaf\xe5\x8a\xa8\xe5\xa4\x9a\xe4\xb8\xaa\xe6\xb5\x8b\xe8\xaf\x95\xe4\xbb\xbb\xe5\x8a\xa1\xe3\x80\x82', 'ATTENTION: you cannot edit the running application!': '\xe6\xb3\xa8\xe6\x84\x8f: \xe4\xb8\x8d\xe8\x83\xbd\xe4\xbf\xae\xe6\x94\xb9\xe6\xad\xa3\xe5\x9c\xa8\xe8\xbf\x90\xe8\xa1\x8c\xe4\xb8\xad\xe7\x9a\x84\xe5\xba\x94\xe7\x94\xa8!', 'About': '\xe5\x85\xb3\xe4\xba\x8e', 'About application': '\xe5\x85\xb3\xe4\xba\x8e\xe8\xbf\x99\xe4\xb8\xaa\xe5\xba\x94\xe7\x94\xa8', 'Administrator Password:': '\xe7\xae\xa1\xe7\x90\x86\xe5\x91\x98\xe5\xaf\x86\xe7\xa0\x81:', 'Are you sure you want to delete file "%s"?': '\xe7\x9c\x9f\xe7\x9a\x84\xe8\xa6\x81\xe6\x8a\x8a\xe6\x96\x87\xe4\xbb\xb6"%s"\xe5\x88\xa0\xe9\x99\xa4?', 'Are you sure you want to uninstall application "%s"': '\xe7\x9c\x9f\xe7\x9a\x84\xe7\xa1\xae\xe5\xae\x9a\xe8\xa6\x81\xe6\x8a\x8a\xe5\xba\x94\xe7\x94\xa8"%s"\xe5\x8d\xb8\xe8\xbd\xbd', 'Are you sure you want to uninstall application "%s"?': '\xe7\x9c\x9f\xe7\x9a\x84\xe7\xa1\xae\xe5\xae\x9a\xe8\xa6\x81\xe6\x8a\x8a\xe5\xba\x94\xe7\x94\xa8 "%s"\xe5\x8d\xb8\xe8\xbd\xbd?', 'Cannot be empty': '\xe4\xb8\x8d\xe8\x83\xbd\xe7\x95\x99\xe7\xa9\xba\xe7\x99\xbd\xe7\x9a\x84', 'Change Password': '\xe4\xbf\xae\xe6\x94\xb9\xe5\xaf\x86\xe7\xa0\x81', 'Checking for upgrades...': '\xe6\xa3\x80\xe6\x9f\xa5\xe6\x98\xaf\xe5\x90\xa6\xe6\x9c\x89\xe5\x8d\x87\xe7\xba\xa7\xe7\x89\x88\xe6\x9c\xac\xe4\xb8\xad...', 'Client IP': '\xe5\xae\xa2\xe6\x88\xb7\xe7\xab\xafIP', 'Controllers': '\xe6\x8e\xa7\xe5\x88\xb6\xe5\x99\xa8(Controllers)', 'Create new application': '\xe5\x88\x9b\xe5\xbb\xba\xe4\xb8\x80\xe4\xb8\xaa\xe6\x96\xb0\xe5\xba\x94\xe7\x94\xa8', 'Current request': '\xe5\xbd\x93\xe5\x89\x8d\xe8\xaf\xb7\xe6\xb1\x82', 'Date and Time': '\xe6\x97\xa5\xe6\x9c\x9f\xe4\xb8\x8e\xe6\x97\xb6\xe9\x97\xb4', 'Delete': '\xe5\x88\xa0\xe9\x99\xa4', 'Description': '\xe6\x8f\x8f\xe8\xbf\xb0', 'EDIT': '\xe4\xbf\xae\xe6\x94\xb9', 'Edit application': '\xe4\xbf\xae\xe6\x94\xb9\xe5\xba\x94\xe7\x94\xa8', 'Editing Language file': '\xe5\x9c\xa8\xe6\xad\xa4\xe4\xbf\xae\xe6\x94\xb9\xe8\xaf\xad\xe8\xa8\x80\xe8\xb5\x84\xe6\xba\x90\xe6\x96\x87\xe4\xbb\xb6\xef\xbc\x88\xe8\xaf\x91\xe8\x80\x85Iceberg at qq dot com\xe6\xb3\xa8\xef\xbc\x9a\xe6\xaf\x8f\xe6\xac\xa1\xe4\xbf\xae\xe6\x94\xb9\xe5\x89\x8d\xe6\xb3\xa8\xe6\x84\x8f\xe9\x9a\x8f\xe6\x97\xb6\xe6\x89\x8b\xe5\x8a\xa8\xe5\xa4\x87\xe4\xbb\xbd\xe5\xa5\xbd\xe5\x8e\x9f\xe6\x96\x87\xe4\xbb\xb6\xef\xbc\x8c\xe5\x9b\xa0\xe4\xb8\xba\xe6\x9c\x89\xe6\x97\xb6\xe5\x9b\xa0\xe4\xb8\xba\xe7\xa7\x8d\xe7\xa7\x8d\xe5\x8e\x9f\xe5\x9b\xa0\xe8\xaf\xad\xe8\xa8\x80\xe6\xac\xa1\xe5\xba\x8f\xe4\xbc\x9a\xe8\xa2\xab\xe6\x89\x93\xe4\xb9\xb1\xef\xbc\x8c\xe5\xb0\xb1\xe5\x8f\xaa\xe8\x83\xbd\xe4\xbb\x8e\xe5\xa4\x87\xe4\xbb\xbd\xe6\x96\x87\xe4\xbb\xb6\xe4\xb8\xad\xe6\x81\xa2\xe5\xa4\x8d\xef\xbc\x89', 'Enterprise Web Framework': '\xe4\xbc\x81\xe4\xb8\x9a\xe7\xba\xa7\xe7\x9a\x84\xe7\xbd\x91\xe7\xab\x99\xe5\xbc\x80\xe5\x8f\x91\xe6\xa1\x86\xe6\x9e\xb6', 'Error logs for "%(app)s"': '"%(app)s"\xe7\x9a\x84\xe9\x94\x99\xe8\xaf\xaf\xe6\x97\xa5\xe5\xbf\x97', 'Hello World': '\xe5\xa4\xa7\xe5\xae\xb6\xe5\xa5\xbd', 'Import/Export': '\xe5\xaf\xbc\xe5\x85\xa5/\xe5\xaf\xbc\xe5\x87\xba', 'Installed applications': '\xe5\xb7\xb2\xe5\xae\x89\xe8\xa3\x85\xe7\x9a\x84\xe5\xba\x94\xe7\x94\xa8', 'Invalid Query': '\xe6\x97\xa0\xe6\x95\x88\xe6\x9f\xa5\xe8\xaf\xa2', 'Invalid email': '\xe6\x97\xa0\xe6\x95\x88\xe7\x9a\x84email', 'Language files (static strings) updated': '\xe8\xaf\xad\xe8\xa8\x80\xe8\xb5\x84\xe6\xba\x90\xe6\x96\x87\xe4\xbb\xb6\xe4\xb8\xad\xe7\x9a\x84\xe6\xba\x90\xe5\xad\x97\xe4\xb8\xb2\xe5\xb7\xb2\xe8\xa2\xab\xe6\x9b\xb4\xe6\x96\xb0', 'Languages': '\xe8\xaf\xad\xe8\xa8\x80', 'Last saved on:': '\xe6\x9c\x80\xe5\x90\x8e\xe4\xbf\x9d\xe5\xad\x98\xe4\xba\x8e:', 'Login': '\xe7\x99\xbb\xe5\xbd\x95', 'Login to the Administrative Interface': '\xe7\x99\xbb\xe5\xbd\x95\xe5\x88\xb0\xe7\xae\xa1\xe7\x90\x86\xe5\x91\x98\xe7\x95\x8c\xe9\x9d\xa2', 'Logout': '\xe6\xb3\xa8\xe9\x94\x80', 'Lost Password': '\xe5\xbf\x98\xe8\xae\xb0\xe5\xaf\x86\xe7\xa0\x81', 'Models': '\xe6\xa8\xa1\xe5\x9e\x8b(Models)', 'Modules': '\xe6\xa8\xa1\xe5\x9d\x97', 'No databases in this application': '\xe8\xbf\x99\xe5\xba\x94\xe7\x94\xa8\xe6\xb2\xa1\xe6\x9c\x89\xe6\x95\xb0\xe6\x8d\xae\xe5\xba\x93', 'Original/Translation': '\xe5\x8e\x9f\xe5\xa7\x8b\xe6\x96\x87\xe4\xbb\xb6/\xe7\xbf\xbb\xe8\xaf\x91\xe6\x96\x87\xe4\xbb\xb6', 'Password': '\xe5\xaf\x86\xe7\xa0\x81', 'Plugins': '\xe6\x8f\x92\xe4\xbb\xb6', 'Powered by': '\xe5\x9f\xba\xe4\xba\x8e', 'Register': '\xe6\xb3\xa8\xe5\x86\x8c', 'Saved file hash:': '\xe5\xb7\xb2\xe5\xad\x98\xe6\x96\x87\xe4\xbb\xb6\xe7\x9a\x84Hash:', 'Static files': '\xe9\x9d\x99\xe6\x80\x81\xe6\x96\x87\xe4\xbb\xb6', 'Sure you want to delete this object?': '\xe7\x9c\x9f\xe7\x9a\x84\xe8\xa6\x81\xe5\x88\xa0\xe9\x99\xa4\xe8\xbf\x99\xe4\xb8\xaaobject?', 'TM': '\xe6\xb3\xa8\xe5\x86\x8c\xe5\x95\x86\xe6\xa0\x87', 'Table name': '\xe8\xa1\xa8\xe5\x90\x8d\xe7\xa7\xb0', 'There are no static files': '\xe6\xb2\xa1\xe6\x9c\x89\xe9\x9d\x99\xe6\x80\x81\xe6\x96\x87\xe4\xbb\xb6', 'There are no translators, only default language is supported': '\xe6\xb2\xa1\xe6\x9c\x89\xe6\x89\xbe\xe5\x88\xb0\xe7\x9b\xb8\xe5\xba\x94\xe7\xbf\xbb\xe8\xaf\x91\xef\xbc\x8c\xe5\x8f\xaa\xe8\x83\xbd\xe4\xbd\xbf\xe7\x94\xa8\xe9\xbb\x98\xe8\xae\xa4\xe8\xaf\xad\xe8\xa8\x80', 'Ticket': '\xe7\xa5\xa8\xe6\x8d\xae\xef\xbc\x88\xe9\x94\x99\xe8\xaf\xaf\xe8\xae\xb0\xe5\xbd\x95\xef\xbc\x89', 'To create a plugin, name a file/folder plugin_[name]': '\xe8\xa6\x81\xe5\x88\x9b\xe5\xbb\xba\xe4\xb8\x80\xe4\xb8\xaa\xe6\x8f\x92\xe4\xbb\xb6\xef\xbc\x8c\xe5\x8f\xaa\xe9\x9c\x80\xe6\x8a\x8a\xe4\xb8\x80\xe4\xb8\xaa\xe6\x96\x87\xe4\xbb\xb6\xe6\x88\x96\xe7\x9b\xae\xe5\xbd\x95\xe5\x91\xbd\xe5\x90\x8d\xe4\xb8\xba\xe8\xbf\x99\xe4\xb8\xaa\xe6\xa0\xb7\xe5\xbc\x8f\xef\xbc\x9aplugin_[name]', 'Unable to check for upgrades': '\xe6\x97\xa0\xe6\xb3\x95\xe6\xa3\x80\xe6\x9f\xa5\xe6\x98\xaf\xe5\x90\xa6\xe9\x9c\x80\xe8\xa6\x81\xe5\x8d\x87\xe7\xba\xa7', 'Unable to download': '\xe6\x97\xa0\xe6\xb3\x95\xe4\xb8\x8b\xe8\xbd\xbd', 'Unable to download app': '\xe6\x97\xa0\xe6\xb3\x95\xe4\xb8\x8b\xe8\xbd\xbd\xe5\xba\x94\xe7\x94\xa8', 'Unable to download because': '\xe6\x97\xa0\xe6\xb3\x95\xe4\xb8\x8b\xe8\xbd\xbd\xef\xbc\x8c\xe5\x8e\x9f\xe5\x9b\xa0\xe6\x98\xaf', 'Update:': '\xe6\x9b\xb4\xe6\x96\xb0:', 'Upload & install packed application': '\xe4\xb8\x8a\xe4\xbc\xa0\xe5\xb9\xb6\xe5\xae\x89\xe8\xa3\x85\xe4\xb8\x80\xe4\xb8\xaa\xe5\xba\x94\xe7\x94\xa8\xe7\xa8\x8b\xe5\xba\x8f\xe5\x8c\x85', 'Upload existing application': '\xe4\xb8\x8a\xe4\xbc\xa0\xe5\xb7\xb2\xe6\x9c\x89\xe5\xba\x94\xe7\x94\xa8', 'User ID': '\xe7\x94\xa8\xe6\x88\xb7 ID', 'Version': '\xe7\x89\x88\xe6\x9c\xac', 'Views': '\xe8\xa7\x86\xe5\x9b\xbe(Views)', 'Welcome to web2py': '\xe6\xac\xa2\xe8\xbf\x8e\xe4\xbd\xbf\xe7\x94\xa8web2py', 'about': '\xe5\x85\xb3\xe4\xba\x8e', 'additional code for your application': '\xe6\x9c\xac\xe5\xba\x94\xe7\x94\xa8\xe7\xa8\x8b\xe5\xba\x8f\xe7\x9a\x84\xe4\xbb\xa3\xe7\xa0\x81\xe6\xa8\xa1\xe5\x9d\x97\xe5\xba\x93', 'admin disabled because no admin password': '\xe7\xae\xa1\xe7\x90\x86\xe5\x91\x98\xe9\x9c\x80\xe8\xa6\x81\xe8\xae\xbe\xe5\xae\x9a\xe5\xaf\x86\xe7\xa0\x81\xef\xbc\x8c\xe5\x90\xa6\xe5\x88\x99\xe6\x97\xa0\xe6\xb3\x95\xe7\xae\xa1\xe7\x90\x86', 'admin disabled because not supported on google apps engine': '\xe7\xae\xa1\xe7\x90\x86\xe7\x95\x8c\xe9\x9d\xa2\xe4\xb8\x8d\xe6\x94\xaf\xe6\x8c\x81\xe5\x9c\xa8google apps engine\xe4\xb8\x8a\xe8\xbf\x90\xe8\xa1\x8c', 'admin disabled because unable to access password file': '\xe9\x9c\x80\xe8\xa6\x81\xe5\x8f\xaf\xe4\xbb\xa5\xe6\x93\x8d\xe4\xbd\x9c\xe5\xaf\x86\xe7\xa0\x81\xe6\x96\x87\xe4\xbb\xb6\xef\xbc\x8c\xe5\x90\xa6\xe5\x88\x99\xe6\x97\xa0\xe6\xb3\x95\xe8\xbf\x9b\xe8\xa1\x8c\xe7\xae\xa1\xe7\x90\x86', 'and rename it (required):': '\xe9\x87\x8d\xe5\x91\xbd\xe5\x90\x8d\xe4\xb8\xba (\xe5\xbf\x85\xe9\xa1\xbb):', 'and rename it:': '\xe9\x87\x8d\xe5\x91\xbd\xe5\x90\x8d\xe4\xb8\xba:', 'application "%s" uninstalled': '\xe5\xba\x94\xe7\x94\xa8"%s" \xe5\xb7\xb2\xe8\xa2\xab\xe5\x8d\xb8\xe8\xbd\xbd', 'cache, errors and sessions cleaned': '\xe7\xbc\x93\xe5\xad\x98\xe3\x80\x81\xe9\x94\x99\xe8\xaf\xaf\xe3\x80\x81\xe4\xbc\x9a\xe8\xaf\x9d(sesiones)\xe5\xb7\xb2\xe8\xa2\xab\xe6\xb8\x85\xe7\xa9\xba', 'cannot create file': '\xe6\x97\xa0\xe6\xb3\x95\xe5\x88\x9b\xe5\xbb\xba\xe6\x96\x87\xe4\xbb\xb6', 'cannot upload file "%(filename)s"': '\xe6\x97\xa0\xe6\xb3\x95\xe4\xb8\x8a\xe4\xbc\xa0\xe6\x96\x87\xe4\xbb\xb6 "%(filename)s"', 'check all': '\xe9\x80\x89\xe6\x8b\xa9\xe5\x85\xa8\xe9\x83\xa8', 'clean': '\xe6\xb8\x85\xe9\x99\xa4', 'click here for online examples': '\xe7\x82\xb9\xe5\x87\xbb\xe6\xad\xa4\xe5\xa4\x84\xef\xbc\x8c\xe6\x9f\xa5\xe7\x9c\x8b\xe5\x9c\xa8\xe7\xba\xbf\xe5\xae\x9e\xe4\xbe\x8b', 'click here for the administrative interface': '\xe7\x82\xb9\xe5\x87\xbb\xe6\xad\xa4\xe5\xa4\x84\xef\xbc\x8c\xe8\xbf\x9b\xe5\x85\xa5\xe7\xae\xa1\xe7\x90\x86\xe7\x95\x8c\xe9\x9d\xa2', 'click to check for upgrades': '\xe7\x82\xb9\xe5\x87\xbb\xe6\xad\xa4\xe5\xa4\x84\xef\xbc\x8c\xe6\x9f\xa5\xe7\x9c\x8b\xe6\x98\xaf\xe5\x90\xa6\xe6\x9c\x89\xe5\x8d\x87\xe7\xba\xa7\xe7\x89\x88\xe6\x9c\xac', 'compile': '\xe7\xbc\x96\xe8\xaf\x91', 'controllers': '\xe6\x8e\xa7\xe5\x88\xb6\xe5\x99\xa8(controllers)', 'create': '\xe5\x88\x9b\xe5\xbb\xba', 'create file with filename:': '\xe5\x88\x9b\xe5\xbb\xba\xe4\xb8\x80\xe4\xb8\xaa\xe6\x96\x87\xe4\xbb\xb6\xef\xbc\x8c\xe5\x90\x8d\xe7\xa7\xb0\xe4\xb8\xba:', 'create new application:': '\xe5\x88\x9b\xe5\xbb\xba\xe6\x96\xb0\xe5\xba\x94\xe7\x94\xa8:', 'created by': '\xe5\x88\x9b\xe5\xbb\xba\xe8\x80\x85', 'crontab': '\xe4\xbf\xae\xe6\x94\xb9\xe5\xae\x9a\xe6\x97\xb6\xe9\x85\x8d\xe7\xbd\xae\xe6\x96\x87\xe4\xbb\xb6crontab', 'customize me!': '\xe4\xbf\xae\xe6\x94\xb9\xe6\x88\x91\xe5\x90\xa7!', 'data uploaded': '\xe6\x95\xb0\xe6\x8d\xae\xe5\xb7\xb2\xe8\xa2\xab\xe4\xb8\x8a\xe4\xbc\xa0', 'database': '\xe6\x95\xb0\xe6\x8d\xae\xe5\xba\x93', 'database administration': '\xe6\x95\xb0\xe6\x8d\xae\xe5\xba\x93\xe7\xae\xa1\xe7\x90\x86', 'defines tables': '\xe5\xae\x9a\xe4\xb9\x89\xe4\xba\x86\xe6\x95\xb0\xe6\x8d\xae\xe8\xa1\xa8', 'delete': '\xe5\x88\xa0\xe9\x99\xa4', 'delete all checked': '\xe5\x88\xa0\xe9\x99\xa4\xe6\x89\x80\xe6\x9c\x89\xe9\x80\x89\xe4\xb8\xad\xe7\x9a\x84\xe5\x86\x85\xe5\xae\xb9', 'done!': '\xe6\x90\x9e\xe5\xae\x9a!', 'edit': '\xe4\xbf\xae\xe6\x94\xb9', 'errors': '\xe9\x94\x99\xe8\xaf\xaf', 'export as csv file': '\xe5\xaf\xbc\xe5\x87\xba\xe4\xb8\xbaCSV\xe6\x96\x87\xe4\xbb\xb6', 'exposes': '\xe6\x8a\xab\xe9\x9c\xb2(\xe5\xae\x9a\xe4\xb9\x89)\xe4\xba\x86', 'extends': '\xe6\x89\xa9\xe5\xb1\x95\xe8\x87\xaa', 'file "%(filename)s" created': '\xe6\x96\x87\xe4\xbb\xb6 "%(filename)s" \xe8\xa2\xab\xe5\x88\x9b\xe5\xbb\xba', 'file "%(filename)s" deleted': '\xe6\x96\x87\xe4\xbb\xb6 "%(filename)s" \xe8\xa2\xab\xe5\x88\xa0\xe9\x99\xa4', 'file "%(filename)s" uploaded': '\xe6\x96\x87\xe4\xbb\xb6 "%(filename)s" \xe8\xa2\xab\xe4\xb8\x8a\xe4\xbc\xa0', 'file "%(filename)s" was not deleted': '\xe6\x96\x87\xe4\xbb\xb6 "%(filename)s" \xe6\xb2\xa1\xe8\xa2\xab\xe5\x88\xa0\xe9\x99\xa4', 'file changed on disk': '\xe7\xa1\xac\xe7\x9b\x98\xe4\xb8\x8a\xe7\x9a\x84\xe6\x96\x87\xe4\xbb\xb6\xe5\xb7\xb2\xe7\xbb\x8f\xe4\xbf\xae\xe6\x94\xb9', 'file does not exist': '\xe6\x96\x87\xe4\xbb\xb6\xe5\xb9\xb6\xe4\xb8\x8d\xe5\xad\x98\xe5\x9c\xa8', 'file saved on %(time)s': '\xe6\x96\x87\xe4\xbb\xb6\xe4\xbf\x9d\xe5\xad\x98\xe4\xba\x8e %(time)s', 'help': '\xe5\xb8\xae\xe5\x8a\xa9', 'htmledit': 'html\xe7\xbc\x96\xe8\xbe\x91', 'includes': '\xe5\x8c\x85\xe5\x90\xab\xe4\xba\x86', 'insert new': '\xe6\x8f\x92\xe5\x85\xa5\xe6\x96\xb0\xe7\x9a\x84', 'install': '\xe5\xae\x89\xe8\xa3\x85', 'invalid password': '\xe6\x97\xa0\xe6\x95\x88\xe5\xaf\x86\xe7\xa0\x81', 'invalid request': '\xe6\x97\xa0\xe6\x95\x88\xe8\xaf\xb7\xe6\xb1\x82', 'language file "%(filename)s" created/updated': '\xe8\xaf\xad\xe8\xa8\x80\xe6\x96\x87\xe4\xbb\xb6 "%(filename)s"\xe8\xa2\xab\xe5\x88\x9b\xe5\xbb\xba/\xe6\x9b\xb4\xe6\x96\xb0', 'languages': '\xe8\xaf\xad\xe8\xa8\x80', 'languages updated': '\xe8\xaf\xad\xe8\xa8\x80\xe5\xb7\xb2\xe8\xa2\xab\xe5\x88\xb7\xe6\x96\xb0', 'loading...': '\xe8\xbd\xbd\xe5\x85\xa5\xe4\xb8\xad...', 'login': '\xe7\x99\xbb\xe5\xbd\x95', 'logout': '\xe6\xb3\xa8\xe9\x94\x80', 'merge': '\xe5\x90\x88\xe5\xb9\xb6', 'models': '\xe6\xa8\xa1\xe5\x9e\x8b(models)', 'modules': '\xe6\xa8\xa1\xe5\x9d\x97', 'new application "%s" created': '\xe6\x96\xb0\xe5\xba\x94\xe7\x94\xa8 "%s"\xe5\xb7\xb2\xe8\xa2\xab\xe5\x88\x9b\xe5\xbb\xba', 'new record inserted': '\xe6\x96\xb0\xe8\xae\xb0\xe5\xbd\x95\xe8\xa2\xab\xe6\x8f\x92\xe5\x85\xa5', 'or import from csv file': '\xe6\x88\x96\xe8\x80\x85\xef\xbc\x8c\xe4\xbb\x8ecsv\xe6\x96\x87\xe4\xbb\xb6\xe5\xaf\xbc\xe5\x85\xa5', 'or provide app url:': '\xe6\x88\x96\xe8\x80\x85\xe6\x8f\x90\xe4\xbe\x9b\xe5\xba\x94\xe7\x94\xa8\xe7\xa8\x8b\xe5\xba\x8f\xe6\x89\x80\xe5\x9c\xa8\xe7\x9a\x84\xe7\xbd\x91\xe5\x9d\x80:', 'or provide application url:': '\xe6\x88\x96\xe8\x80\x85\xef\xbc\x8c\xe6\x8f\x90\xe4\xbe\x9b\xe5\xba\x94\xe7\x94\xa8\xe6\x89\x80\xe5\x9c\xa8\xe5\x9c\xb0\xe5\x9d\x80\xe9\x93\xbe\xe6\x8e\xa5:', 'overwrite installed app': '\xe8\xa6\x86\xe7\x9b\x96\xe5\xb7\xb2\xe7\xbb\x8f\xe5\xad\x98\xe5\x9c\xa8\xe7\x9a\x84\xe5\xba\x94\xe7\x94\xa8', 'pack all': '\xe5\x85\xa8\xe9\x83\xa8\xe6\x89\x93\xe5\x8c\x85', 'record does not exist': '\xe8\xae\xb0\xe5\xbd\x95\xe5\xb9\xb6\xe4\xb8\x8d\xe5\xad\x98\xe5\x9c\xa8', 'restore': '\xe6\x81\xa2\xe5\xa4\x8d', 'save': '\xe4\xbf\x9d\xe5\xad\x98', 'shell': '\xe5\x9c\xa8\xe5\x91\xbd\xe4\xbb\xa4\xe8\xa1\x8c\xe7\x95\x8c\xe9\x9d\xa2(shell)\xe4\xb8\xad\xe7\xbc\x96\xe8\xbe\x91', 'site': '\xe6\x80\xbb\xe7\xab\x99', 'some files could not be removed': '\xe6\x9c\x89\xe4\xba\x9b\xe6\x96\x87\xe4\xbb\xb6\xe6\x97\xa0\xe6\xb3\x95\xe8\xa2\xab\xe7\xa7\xbb\xe9\x99\xa4', 'static': '\xe9\x9d\x99\xe6\x80\x81\xe6\x96\x87\xe4\xbb\xb6', 'submit': '\xe6\x8f\x90\xe4\xba\xa4', 'test': '\xe6\xb5\x8b\xe8\xaf\x95', 'the application logic, each URL path is mapped in one exposed function in the controller': '\xe6\x8e\xa7\xe5\x88\xb6\xe5\x99\xa8\xe5\xb1\x82\xef\xbc\x8c\xe5\xae\x9e\xe7\x8e\xb0\xe4\xba\x86\xe4\xb8\x9a\xe5\x8a\xa1\xe9\x80\xbb\xe8\xbe\x91\xef\xbc\x8c\xe6\xaf\x8f\xe4\xb8\xaa\xe7\xbd\x91\xe5\x9d\x80\xe9\x83\xbd\xe8\xa2\xab\xe6\x98\xa0\xe5\xb0\x84\xe5\x88\xb0\xe6\x8e\xa7\xe5\x88\xb6\xe5\x99\xa8\xe5\x86\x85\xe9\x83\xa8\xe7\x9a\x84\xe4\xb8\x80\xe4\xb8\xaa\xe5\x87\xbd\xe6\x95\xb0', 'the data representation, define database tables and sets': '\xe6\x95\xb0\xe6\x8d\xae\xe5\xb1\x82\xef\xbc\x8c\xe5\xae\x9a\xe4\xb9\x89\xe4\xba\x86\xe6\x95\xb0\xe6\x8d\xae\xe5\xba\x93\xe7\x9a\x84\xe8\xa1\xa8\xe7\xbb\x93\xe6\x9e\x84\xe5\x92\x8c\xe6\x95\xb0\xe6\x8d\xae\xe9\x9b\x86', 'the presentations layer, views are also known as templates': '\xe8\xa1\xa8\xe7\x8e\xb0\xe5\xb1\x82\xef\xbc\x8c\xe8\xa7\x86\xe5\x9b\xbe(views)\xe6\x9c\x89\xe6\x97\xb6\xe4\xb9\x9f\xe8\xa2\xab\xe7\xa7\xb0\xe4\xbd\x9c\xe6\xa8\xa1\xe6\x9d\xbf(templates)', 'these files are served without processing, your images go here': '\xe8\xbf\x99\xe4\xba\x9b\xe6\x96\x87\xe4\xbb\xb6\xe5\xb0\x86\xe8\xa2\xab\xe5\x8e\x9f\xe6\xa0\xb7\xe5\x91\x88\xe7\x8e\xb0\xe3\x80\x82\xe4\xbe\x8b\xe5\xa6\x82\xe4\xbd\xa0\xe7\x9a\x84\xe5\x9b\xbe\xe7\x89\x87\xe8\xb5\x84\xe6\xba\x90\xe5\xb0\xb1\xe5\xba\x94\xe8\xaf\xa5\xe6\x94\xbe\xe5\x9c\xa8\xe6\xad\xa4\xe5\xa4\x84\xe3\x80\x82', 'translation strings for the application': '\xe5\xaf\xb9\xe5\xbd\x93\xe5\x89\x8d\xe5\xba\x94\xe7\x94\xa8\xe7\x9a\x84\xe8\xaf\xad\xe8\xa8\x80\xe6\x96\x87\xe5\xad\x97\xe8\xbf\x9b\xe8\xa1\x8c\xe7\xbf\xbb\xe8\xaf\x91', 'unable to create application "%s"': '\xe6\x97\xa0\xe6\xb3\x95\xe5\x88\x9b\xe5\xbb\xba\xe5\xba\x94\xe7\x94\xa8 "%s"', 'unable to delete file "%(filename)s"': '\xe6\x97\xa0\xe6\xb3\x95\xe5\x88\xa0\xe9\x99\xa4\xe6\x96\x87\xe4\xbb\xb6 "%(filename)s"', 'unable to uninstall "%s"': '\xe6\x97\xa0\xe6\xb3\x95\xe5\x8d\xb8\xe8\xbd\xbd "%s"', 'uncheck all': '\xe5\x85\xa8\xe9\x83\xa8\xe4\xb8\x8d\xe9\x80\x89', 'uninstall': '\xe5\x8d\xb8\xe8\xbd\xbd', 'update': '\xe6\x9b\xb4\xe6\x96\xb0', 'update all languages': '\xe6\x9b\xb4\xe6\x96\xb0\xe6\x89\x80\xe6\x9c\x89\xe8\xaf\xad\xe8\xa8\x80', 'upload application:': '\xe6\x8f\x90\xe4\xba\xa4\xe5\xb7\xb2\xe6\x9c\x89\xe7\x9a\x84\xe5\xba\x94\xe7\x94\xa8:', 'upload file:': '\xe6\x8f\x90\xe4\xba\xa4\xe6\x96\x87\xe4\xbb\xb6:', 'upload plugin file:': '\xe4\xb8\x8a\xe4\xbc\xa0\xe6\x8f\x92\xe4\xbb\xb6\xe6\x96\x87\xe4\xbb\xb6:', 'views': '\xe8\xa7\x86\xe5\x9b\xbe(views)', 'web2py Recent Tweets': 'twitter\xe4\xb8\x8a\xe7\x9a\x84web2py\xe8\xbf\x9b\xe5\xb1\x95\xe5\xae\x9e\xe6\x92\xad', 'web2py is up to date': 'web2py\xe7\x8e\xb0\xe5\x9c\xa8\xe5\xb7\xb2\xe7\xbb\x8f\xe6\x98\xaf\xe6\x9c\x80\xe6\x96\xb0\xe7\x9a\x84\xe7\x89\x88\xe6\x9c\xac\xe4\xba\x86', }
gpl-3.0
idega/com.idega.block.ldap
src/java/com/idega/core/ldap/client/jndi/ConnectionData.java
7524
package com.idega.core.ldap.client.jndi; /** * The ConnectionData inner class is used to pass * connection data around. Not all fields are * guaranteed to be valid values. */ public class ConnectionData { /** * The base to start browsing from, e.g.'o=Democorp,c=au'. * (This is often reset to what the directory says the base * is in practice). */ public String baseDN = ""; /** * The LDAP Version (2 or 3) being used. */ public int version = 3; // default to 3... /** * Which protocol to use (currently "ldap", "dsml") */ public static final String LDAP = "ldap"; public static final String DSML = "dsml"; public String protocol = LDAP; // default is always to use LDAP /** * A URL of the form ldap://hostname:portnumber. */ public String url; /** * The Manager User's distinguished name (optionally null if not used). */ public String userDN; /** * The Manager User's password - (is null if user is not manager). */ public char[] pwd; /** * The jndi ldap referral type: [follow:ignore:throw] (may be null - defaults to 'follow'). */ public String referralType = "follow"; /** * How aliases should be handled in searches ('always'|'never'|'find'|'search'). */ public String aliasType = "searching"; /** * Whether to use SSL (either simple or client-authenticated). */ public boolean useSSL; /** * The file containing the trusted server certificates (no keys). * */ // XXX we may want to expand this later to 'SSL type' public String cacerts; /** * The file containing client certificates and private key(s). */ public String clientcerts; /** * The password to the ca's keystore (may be null for non-client authenticated ssl). */ public char[] caKeystorePwd; /** * The password to the client's keystore (may be null for non-client authenticated ssl). */ public char[] clientKeystorePwd; /** * The type of ca keystore file; e.g. 'JKS', or 'PKCS12'. */ public String caKeystoreType; /** * The type of client keystore file; e.g. 'JKS', or 'PKCS12'. */ public String clientKeystoreType; /** * Whether to set BER tracing on or not. (This is a very verbose * dump of all the raw ldap data as it streams past). */ public boolean tracing; /** * Empty constructor - data fields are intended * to be set directly. */ public ConnectionData() {} public void setProtocol(String newProtocol) { if (newProtocol.equalsIgnoreCase(LDAP)) protocol = LDAP; else if (newProtocol.equalsIgnoreCase(DSML)) protocol = DSML; else System.err.println("Unknown Protocol " + newProtocol); } /** * This should be used to clear all the passwords * saved in this data object when they have been * used and are no longer needed... make sure however * that no references to the passwords remain to be * used by other parts of the program first :-)! */ public void clearPasswords() { if (pwd!=null) for (int i=0; i<pwd.length; i++) pwd[i] = ' '; //TE: null is incompatible. if (caKeystorePwd!=null) for (int i=0; i<caKeystorePwd.length; i++) caKeystorePwd[i] = ' '; if (clientKeystorePwd!=null) for (int i=0; i<clientKeystorePwd.length; i++) clientKeystorePwd[i] = ' '; } /** * Sets the url from the host & port, e.g. "ldap://" + host + ":" + port". * (NB: If the protocol is <i>NOT</i> LDAP, (e.g. DSML) this must be set first. * @param host the host name to connect to, e.g. echidna or 168.10.5.122. * @param port the host port to connect to, e.g. 19389. */ public void setURL(String host, int port) { if (protocol == LDAP) url = "ldap://" + host + ":" + port; else if (protocol == DSML) url = "http://" + host + ":" + port; } /** * Sets the url from the host & port, e.g. "ldap://" + host + ":" + port". * (NB: If the protocol is <i>NOT</i> LDAP, (e.g. DSML) this must be set first. * @param URL The full URL to connect to */ public void setURL(String URL) { if (protocol==LDAP) { if (URL.toLowerCase().startsWith("ldap://")) url = URL; else url = "ldap://" + URL; } else if (protocol == DSML) { if (URL.toLowerCase().startsWith("http://")) url = URL; else if (URL.toLowerCase().startsWith("dsml://")) url = "http://" + URL.substring(7); else url = "http://" + URL; } else // not sure if this is necessary... { if (URL.toLowerCase().startsWith("ldap:")) { protocol = LDAP; url = URL; } else if (URL.toLowerCase().startsWith("http:")) { protocol = DSML; url = URL; } else if (URL.toLowerCase().startsWith("dsml:")) { protocol = DSML; url = "http:" + URL.substring(5); } } } public String getURL() { return url; } /** * Gets the host name from the url string. * @return the host name for example: DEMOCORP. */ // parse rules; the url is always of the form <protocol>://<hostname>:<port>[/server stuff (for dsml only)] public String getHost() { if(url==null) return null; int protocolSeparator = url.indexOf("://") + 3; int portSeparator = url.indexOf(":", protocolSeparator); return url.substring(protocolSeparator, portSeparator); } /** * Gets the port number from the url string. * @return the port number for example: 19389. */ public int getPort() { if(url==null) return -1; try { int protocolSeparator = url.indexOf("://") + 3; int portSeparator = url.indexOf(":", protocolSeparator)+1; int serverDetails = url.indexOf("/", portSeparator); String port = (serverDetails == -1)? url.substring(portSeparator):url.substring(portSeparator, serverDetails); int portNumber = Integer.parseInt(port); if (portNumber > 65536 || portNumber <= 0) return -1; return portNumber; } catch (NumberFormatException nfe) { return -1; } } /** * Returns this data object as a string (doesn't include passwords).. * @return the data object as a string. */ @Override public String toString() { return new String("baseDN: " + baseDN + "\nversion: " + Integer.toString(version) + "\nurl: " + url + "\nuserDN: " + userDN + "\nreferralType: " + referralType + "\naliasType: " + aliasType + "\nuseSSL: " + String.valueOf(useSSL) + "\ncacerts: " + cacerts + "\nclientcerts: " + clientcerts + "\nclientKeystoreType: " + clientKeystoreType + "\ncaKeystoreType: " + caKeystoreType + "\ntracing: " + String.valueOf(tracing) + "\nprotocol: " + protocol ); } }
gpl-3.0
luv/avis_zmqprx
server/src/main/org/avis/subscription/ast/nodes/Const.java
3395
/* * Avis event router. * * Copyright (C) 2008 Matthew Phillips <avis@mattp.name> * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 org.avis.subscription.ast.nodes; import java.util.Map; import org.avis.subscription.ast.Node; import static org.avis.util.Util.valuesEqual; public class Const extends Node { public static final Const CONST_FALSE = new Const (FALSE); public static final Const CONST_TRUE = new Const (TRUE); public static final Const CONST_BOTTOM = new Const (BOTTOM); public static final Const CONST_ZERO = new Const (0); private Object value; public static Const bool (Boolean value) { if (value == TRUE) return CONST_TRUE; else if (value == FALSE) return CONST_FALSE; else throw new IllegalArgumentException ("Invalid value: " + value); } public static Const string (String string) { return new Const (string); } public static Const int32 (int value) { if (value == 0) return CONST_ZERO; else return new Const (value); } public static Node int64 (long value) { return new Const (value); } public static Node real64 (double value) { return new Const (value); } public Const (Object value) { this.value = value; } @Override public boolean equals (Object obj) { return obj.getClass () == Const.class && valuesEqual (((Const)obj).value, value); } @Override public int hashCode () { return value == null ? 0 : value.hashCode (); } public Object value () { return value; } @Override public Class<?> evalType () { if (value == BOTTOM) return Boolean.class; else return value.getClass (); } @Override public Node inlineConstants () { return this; } @Override public Object evaluate (Map<String, Object> attrs) { return value; } @Override public String expr () { if (value instanceof String) return "'" + value + "'"; else if (value instanceof Number) return numExpr (); else return value.toString (); } @Override public String presentation () { if (value instanceof String) return "Str: \"" + value + '\"'; else if (value instanceof Number) return numPresentation (); else return "Const: " + value; } private String numPresentation () { StringBuilder str = new StringBuilder ("Num: "); str.append (value); if (value instanceof Long) str.append ('L'); else if (value instanceof Double) str.append (" (double)"); return str.toString (); } private String numExpr () { StringBuilder str = new StringBuilder (); str.append (value); if (value instanceof Long) str.append ('L'); return str.toString (); } }
gpl-3.0
shekharcs1-/Test
service/src/main/java/com/drdolittle/petclinic/petclinic/repository/jdbc/JdbcPetVisitExtractor.java
1762
/* * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.drdolittle.petclinic.petclinic.repository.jdbc; import org.springframework.data.jdbc.core.OneToManyResultSetExtractor; import org.springframework.jdbc.core.ResultSetExtractor; import com.drdolittle.petclinic.petclinic.model.Visit; import java.sql.ResultSet; import java.sql.SQLException; /** * {@link ResultSetExtractor} implementation by using the * {@link OneToManyResultSetExtractor} of Spring Data Core JDBC Extensions. */ public class JdbcPetVisitExtractor extends OneToManyResultSetExtractor<JdbcPet, Visit, Integer> { public JdbcPetVisitExtractor() { super(new JdbcPetRowMapper(), new JdbcVisitRowMapper()); } @Override protected Integer mapPrimaryKey(ResultSet rs) throws SQLException { return rs.getInt("pets.id"); } @Override protected Integer mapForeignKey(ResultSet rs) throws SQLException { if (rs.getObject("visits.pet_id") == null) { return null; } else { return rs.getInt("visits.pet_id"); } } @Override protected void addChild(JdbcPet root, Visit child) { root.addVisit(child); } }
gpl-3.0
dciabrin/ra-tester
ra/rabbitmq/tests.py
6491
#!/usr/bin/env python '''Resource Agents Tester Tests for the RabbitMQ resource agent. ''' __copyright__ = ''' Copyright (C) 2018 Damien Ciabrini <dciabrin@redhat.com> Licensed under the GNU GPL. ''' # # 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. import sys, signal, time, os, re, string, subprocess, tempfile from stat import * from cts import CTS from cts.CTS import CtsLab from cts.CTStests import CTSTest from cts.CTSscenarios import * from cts.CTSaudits import * from cts.CTSvars import * from cts.patterns import PatternSelector from cts.logging import LogFactory from cts.remote import RemoteFactory from cts.watcher import LogWatcher from cts.environment import EnvFactory from racts.ratest import ResourceAgentTest tests = [] class RabbitMQCommonTest(ResourceAgentTest): def bundle_command(self, cluster_nodes, config): engine = self.Env["container_engine"] name = config["name"] image = config["container_image"] return "pcs resource bundle create %s"\ " container %s image=%s network=host options=\"--user=root --log-driver=journald\""\ " replicas=3 run-command=\"/usr/sbin/pacemaker_remoted\" network control-port=3123"\ " storage-map id=map0 source-dir=/dev/log target-dir=/dev/log"\ " storage-map id=map1 source-dir=/dev/zero target-dir=/etc/libqb/force-filesystem-sockets options=ro"\ " storage-map id=map2 source-dir=/etc/hosts target-dir=/etc/hosts options=ro"\ " storage-map id=map3 source-dir=/etc/localtime target-dir=/etc/localtime options=ro"\ " storage-map id=map4 source-dir=/etc/rabbitmq target-dir=/etc/rabbitmq options=ro"\ " storage-map id=map5 source-dir=/var/lib/rabbitmq target-dir=/var/lib/rabbitmq options=rw"\ " storage-map id=map6 source-dir=/var/log/rabbitmq target-dir=/var/log/rabbitmq options=rw"\ " storage-map id=map7 source-dir=/usr/lib/ocf target-dir=/usr/lib/ocf options=rw"%\ (name, engine, image) def resource_command(self, cluster_nodes, config): name = config["ocf_name"] return """pcs resource create %s ocf:heartbeat:rabbitmq-cluster set_policy='ha-all ^(?!amq\\.).* {"ha-mode":"all"}' op stop interval=0s timeout=200s"""%name def setup_test(self, node): self.setup_inactive_resource(self.Env["nodes"]) def teardown_test(self, node): self.delete_resource(self.Env["nodes"]) def errorstoignore(self): return ResourceAgentTest.errorstoignore(self) + [ "ERROR: Failed to forget node rabbit@.* via rabbit@.*" ] class ClusterStart(RabbitMQCommonTest): '''Start a rabbitmq cluster''' def __init__(self, cm): RabbitMQCommonTest.__init__(self,cm) self.name = "ClusterStart" def test(self, target): # setup_test has created the inactive resource config = self.config name = config["name"] ocf_name = config["ocf_name"] # force a probe to ensure pacemaker knows that the resource # is in disabled state patterns = [self.ratemplates.build("Pat:RscRemoteOp", "probe", self.resource_probe_pattern(config, n), n, 'not running') \ for n in self.Env["nodes"]] watch = self.make_watch(patterns) self.rsh_check(target, "pcs resource refresh %s"%name) watch.lookforall() assert not watch.unmatched, watch.unmatched # bundles run OCF resources on bundle nodes, not host nodes target_nodes = self.resource_target_nodes(config, self.Env["nodes"]) patterns = [self.ratemplates.build("Pat:RscRemoteOp", "start", ocf_name, n, 'ok') \ for n in target_nodes] watch = self.make_watch(patterns) self.rsh_check(target, "pcs resource enable %s"%name) watch.lookforall() assert not watch.unmatched, watch.unmatched # teardown_test will delete the resource tests.append(ClusterStart) class ClusterRebootAllNodes(ClusterStart): '''Restart the rabbitmq cluster after all hosts have been rebooted''' def __init__(self, cm): RabbitMQCommonTest.__init__(self,cm) self.name = "ClusterRebootAllNodes" def test(self, target): # ClusterStart starts all the rabbitmq clones ClusterStart.test(self, target) # restart all the nodes forcibly config = self.config name = config["name"] target_nodes = self.resource_target_nodes(config, self.Env["nodes"]) patterns = [self.ratemplates.build("Pat:RscRemoteOp", "start", name, n, 'ok') \ for n in target_nodes] watch = self.make_watch(patterns) self.log("Force-reset nodes "%self.Env["nodes"]) for n in self.Env["nodes"]: self.rsh(n, "echo b > /proc/sysrq-trigger") self.log("Wait until all nodes are restarted and reachable over ssh") for n in self.Env["nodes"]: self.wait_until_restarted(n) # wait until pacemaker restart all the rabbitmq clones watch.lookforall() assert not watch.unmatched, watch.unmatched # teardown_test will delete the resource def errorstoignore(self): return ResourceAgentTest.errorstoignore(self) + [ # libvirt seems to log warnings when triggering the b sysreq "libvirtd.*error : virPCIGetDeviceAddressFromSysfsLink:.*internal error: Failed to parse PCI config address", # pengine is not happy if stonith is disabled "pengine.*error: ENABLE STONITH TO KEEP YOUR RESOURCES SAFE", "pengine.*error: Calculated transition .*(with errors), saving inputs" ] tests.append(ClusterRebootAllNodes)
gpl-3.0
leafsoftinfo/pyramus
framework/src/main/java/fi/pyramus/security/impl/IdentityImpl.java
698
package fi.pyramus.security.impl; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import fi.otavanopisto.security.ContextReference; import fi.otavanopisto.security.Identity; @ApplicationScoped public class IdentityImpl implements Identity { @Inject private SessionController sessionController; @Override public boolean isLoggedIn() { return sessionController.isLoggedIn(); } @Override public boolean isAdmin() { return sessionController.isSuperuser(); } @Override public boolean hasPermission(String permission, ContextReference contextReference) { return sessionController.hasPermission(permission, contextReference); } }
gpl-3.0
SiLeBAT/FSK-Lab
de.bund.bfr.knime.foodprocess.tests/src/de/bund/bfr/knime/util/NameAndDbIdTest.java
1865
package de.bund.bfr.knime.util; import static org.junit.Assert.*; import static org.junit.Assert.assertTrue; import org.junit.Test; @SuppressWarnings("static-method") public class NameAndDbIdTest { @Test public void testNameConstructor() { NameAndDbId identifier = new NameAndDbId("name"); assertEquals(-1, identifier.getId()); assertEquals("name", identifier.getName()); } @Test public void testFullConstructor() throws Exception { NameAndDbId identifier = new NameAndDbId("name", 0); assertEquals(0, identifier.getId()); assertEquals("name", identifier.getName()); } @SuppressWarnings("unlikely-arg-type") @Test public void testEquals() throws Exception { // Compare with same object NameAndDbId identifier = new NameAndDbId("name"); assertTrue(identifier.equals(identifier)); // Compare with null assertFalse(identifier.equals(null)); // Compare with other class assertFalse(identifier.equals("a string")); // Compare with identifier with different id assertFalse(identifier.equals(new NameAndDbId("name", 2))); // Compare with identifier with same id assertTrue(identifier.equals(new NameAndDbId("name", identifier.getId()))); // Compare null name with non-null name (same id) assertFalse(new NameAndDbId(null, identifier.getId()).equals(identifier)); // Compare null name with null name (same id) assertTrue(new NameAndDbId(null, identifier.getId()).equals(new NameAndDbId(null, identifier.getId()))); // Compare non-null name with different name (same id) assertFalse(identifier.equals(new NameAndDbId("other", identifier.getId()))); } @Test public void testHashCode() throws Exception { NameAndDbId oneIdentifier = new NameAndDbId("name", 0); NameAndDbId anotherIdentifier = new NameAndDbId("name", 0); assertEquals(oneIdentifier.hashCode(), anotherIdentifier.hashCode()); } }
gpl-3.0
Bashka/D
library/patterns/entity/dataType/special/network/IPAddress.php
240
<?php namespace D\library\patterns\entity\dataType\special\network; /** * Представления IP адресов различных версий в системе. * @author Artur Sh. Mamedbekov */ interface IPAddress{ }
gpl-3.0
Russell-Jones/django-wiki
django_notify/migrations/0004_auto__chg_field_notification_url.py
7017
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models try: from django.contrib.auth import get_user_model except ImportError: # django < 1.5 from django.contrib.auth.models import User else: User = get_user_model() user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name) user_model_label = '%s.%s' % (User._meta.app_label, User._meta.module_name) class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'Notification.url' db.alter_column('notify_notification', 'url', self.gf('django.db.models.fields.CharField')(max_length=200, null=True)) def backwards(self, orm): # Changing field 'Notification.url' db.alter_column('notify_notification', 'url', self.gf('django.db.models.fields.URLField')(max_length=200, 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'}) }, user_model_label: { 'Meta': {'object_name': User.__name__, 'db_table': "'%s'" % User._meta.db_table}, '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'}) }, 'django_notify.notification': { 'Meta': {'ordering': "('-id',)", 'object_name': 'Notification', 'db_table': "'notify_notification'"}, 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_emailed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_viewed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'message': ('django.db.models.fields.TextField', [], {}), 'occurrences': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}), 'subscription': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['django_notify.Subscription']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'url': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, 'django_notify.notificationtype': { 'Meta': {'object_name': 'NotificationType', 'db_table': "'notify_notificationtype'"}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']", 'null': 'True', 'blank': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128', 'primary_key': 'True'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}) }, 'django_notify.settings': { 'Meta': {'object_name': 'Settings', 'db_table': "'notify_settings'"}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'interval': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s']" % user_orm_label}) }, 'django_notify.subscription': { 'Meta': {'object_name': 'Subscription', 'db_table': "'notify_subscription'"}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'latest': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'latest_for'", 'null': 'True', 'to': "orm['django_notify.Notification']"}), 'notification_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['django_notify.NotificationType']"}), 'object_id': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}), 'send_emails': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'settings': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['django_notify.Settings']"}) } } complete_apps = ['django_notify']
gpl-3.0
dumischbaenger/ews-example
src/main/java/de/dumischbaenger/ws/DeleteMeetingInstanceResponseMessageType.java
954
package de.dumischbaenger.ws; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java-Klasse für DeleteMeetingInstanceResponseMessageType complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType name="DeleteMeetingInstanceResponseMessageType"&gt; * &lt;complexContent&gt; * &lt;extension base="{http://schemas.microsoft.com/exchange/services/2006/messages}ResponseMessageType"&gt; * &lt;/extension&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DeleteMeetingInstanceResponseMessageType", namespace = "http://schemas.microsoft.com/exchange/services/2006/messages") public class DeleteMeetingInstanceResponseMessageType extends ResponseMessageType { }
gpl-3.0
MunchkinGeorge/Evil-Science
munchkingeorge/evil_science/proxy/CommonProxy.java
264
package munchkingeorge.evil_science.proxy; import cpw.mods.fml.common.network.IGuiHandler; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; public class CommonProxy { public void registerRenderers() { } }
gpl-3.0
barbanet/magento-dc-regions
app/code/community/Dc/Regions/Block/Adminhtml/Installer.php
1889
<?php /** * Dc_Regions * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * * @category Dc * @package Dc_Regions * @copyright Copyright (c) 2014-2015 Damián Culotta. (http://www.damianculotta.com.ar/) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ class Dc_Regions_Block_Adminhtml_Installer extends Mage_Adminhtml_Block_Widget { public function __construct() { parent::__construct(); $this->setTemplate('dc/regions/installer.phtml'); } /** * @return string */ public function getHeaderText() { return Mage::helper('regions')->__('Regions Installer'); } /** * @return Mage_Core_Block_Abstract */ protected function _prepareLayout() { parent::_prepareLayout(); $this->getLayout()->getBlock('head')->addCss('dc/regions/css/style.css'); $this->setChild('backButton', $this->getLayout()->createBlock('adminhtml/widget_button') ->setData(array( 'label' => Mage::helper('regions')->__('Back'), 'onclick' => 'setLocation(\'' . $this->getUrl('*/*/index') .'\')', 'class' => 'back' )) ); } /** * @return string */ public function getSaveUrl() { return $this->getUrl('*/*/install'); } /** * @return string */ public function getBackButtonHtml() { return $this->getChildHtml('backButton'); } public function getCountries() { return Mage::getModel('regions/installer')->getOptionArray(); } }
gpl-3.0
dumischbaenger/ews-example
src/main/java/de/dumischbaenger/ws/GetHoldOnMailboxesType.java
1710
package de.dumischbaenger.ws; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * * Request type for the GetHoldOnMailboxes web method. * * * <p>Java-Klasse für GetHoldOnMailboxesType complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType name="GetHoldOnMailboxesType"&gt; * &lt;complexContent&gt; * &lt;extension base="{http://schemas.microsoft.com/exchange/services/2006/messages}BaseRequestType"&gt; * &lt;sequence&gt; * &lt;element name="HoldId" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;/sequence&gt; * &lt;/extension&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "GetHoldOnMailboxesType", namespace = "http://schemas.microsoft.com/exchange/services/2006/messages", propOrder = { "holdId" }) public class GetHoldOnMailboxesType extends BaseRequestType { @XmlElement(name = "HoldId", required = true) protected String holdId; /** * Ruft den Wert der holdId-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getHoldId() { return holdId; } /** * Legt den Wert der holdId-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setHoldId(String value) { this.holdId = value; } }
gpl-3.0
dtromb/gocairo
line.go
444
package cairo /* #cgo LDFLAGS: -lcairo #include <cairo/cairo.h> */ import "C" type LineCap uint32 const ( LineCapButt LineCap = C.CAIRO_LINE_CAP_BUTT LineCapRound = C.CAIRO_LINE_CAP_ROUND LineCapSquare = C.CAIRO_LINE_CAP_SQUARE ) type LineJoin uint32 const ( LineJoinMiter LineJoin = C.CAIRO_LINE_JOIN_MITER LineJoinRound = C.CAIRO_LINE_JOIN_ROUND LineJoinBevel = C.CAIRO_LINE_JOIN_BEVEL )
gpl-3.0
will-bainbridge/OpenFOAM-dev
src/lagrangian/parcel/submodels/MPPIC/PackingModels/Explicit/Explicit.H
4096
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Copyright (C) 2013-2020 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::PackingModels::Explicit Description Explicit model for applying an inter-particle stress to the particles. The inter-particle stress is calculated using current particle locations. This force is then applied only to the particles that are moving towards regions of close pack. The resulting velocity change is limited using an abstracted correction velocity limiter. Reference: \verbatim "An Incompressible Three-Dimensional Multiphase Particle-in-Cell Model for Dense Particle Flows" D Snider Journal of Computational Physics Volume 170, Issue 2, Pages 523-549, July 2001 \endverbatim SourceFiles Explicit.C \*---------------------------------------------------------------------------*/ #ifndef Explicit_H #define Explicit_H #include "PackingModel.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { namespace PackingModels { /*---------------------------------------------------------------------------*\ Class Explicit Declaration \*---------------------------------------------------------------------------*/ template<class CloudType> class Explicit : public PackingModel<CloudType> { // Private Data //- Volume fraction average const AveragingMethod<scalar>* volumeAverage_; //- Velocity average const AveragingMethod<vector>* uAverage_; //- Stress average field autoPtr<AveragingMethod<scalar>> stressAverage_; //- Correction limiter autoPtr<CorrectionLimitingMethod> correctionLimiting_; public: //- Runtime type information TypeName("explicit"); // Constructors //- Construct from components Explicit(const dictionary& dict, CloudType& owner); //- Construct copy Explicit(const Explicit<CloudType>& cm); //- Construct and return a clone virtual autoPtr<PackingModel<CloudType>> clone() const { return autoPtr<PackingModel<CloudType>> ( new Explicit<CloudType>(*this) ); } //- Destructor virtual ~Explicit(); // Member Functions //- Calculate the inter particles stresses virtual void cacheFields(const bool store); //- Calculate the velocity correction virtual vector velocityCorrection ( typename CloudType::parcelType& p, const scalar deltaT ) const; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace PackingModels } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #ifdef NoRepository #include "Explicit.C" #endif // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
gpl-3.0
marpet/seadas
seadas-ocsswrest/src/main/java/gov/nasa/gsfc/seadas/ocsswrest/utilities/ProcessRunner.java
3955
package gov.nasa.gsfc.seadas.ocsswrest.utilities; import gov.nasa.gsfc.seadas.ocsswrest.database.SQLiteJDBC; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Created by IntelliJ IDEA. * User: Aynur Abdurazik (aabduraz) * Date: 6/24/13 * Time: 2:03 PM * To change this template use File | Settings | File Templates. */ public class ProcessRunner { public static Process execute(String[] cmdArray) { ProcessBuilder processBuilder = new ProcessBuilder(cmdArray); Map<String, String> env = processBuilder.environment(); HashMap environment = new HashMap(); environment.put("OCSSWROOT", OCSSWServerModel.OCSSW_INSTALL_DIR); env.putAll(environment); processBuilder.directory(new File(ServerSideFileUtilities.FILE_UPLOAD_PATH)); Process process = null; try { process = processBuilder.start(); } catch (IOException ioe) { } return process; } public static Process executeInstaller(String[] cmdArray) { executeTest(); ProcessBuilder processBuilder = new ProcessBuilder(cmdArray); processBuilder.directory(new File(OCSSWServerModel.OCSSW_INSTALL_DIR)); Process process = null; try { System.out.println("starting execution 1 ..."); process = processBuilder.start(); System.out.println("starting execution 2 ..."); process.wait(); System.out.println("starting execution 3 ..."); } catch (IOException ioe) { System.out.println("installer execution exception!"); System.out.println(ioe.getMessage()); } catch (InterruptedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. System.out.println(e.getMessage()); } System.out.println("completed installer execution!"); return process; } public static Process executeCmdArray(String[] cmdArray) { executeTest(); int exitValue = 1; ProcessBuilder processBuilder = new ProcessBuilder(cmdArray); Process process = null; try { System.out.println("starting execution 1 ..."); process = processBuilder.start(); if (process != null) { exitValue = process.waitFor(); } } catch (IOException ioe) { System.out.println("installer execution IO exception!"); System.out.println(ioe.getMessage()); }catch (InterruptedException ie) { System.out.println("installer execution Interrupted exception!"); System.out.println(ie.getMessage()); } return process; } public static Process executeTest(){ ArrayList<String> cmdList = new ArrayList<String>(); cmdList.add("mkdir"); cmdList.add("/home/aabduraz/Public/test"); System.out.println("starting test execution ..."); String[] cmdArray = new String[3]; cmdArray[0] = "ls"; cmdArray[1] = ">"; cmdArray[2] = "test"; ProcessBuilder processBuilder = new ProcessBuilder(cmdArray); processBuilder.directory(new File("/home/aabduraz")); Process process = null; try { process = processBuilder.start(); System.out.println("test executed!" ); processBuilder = new ProcessBuilder(cmdList); process = processBuilder.start(); System.out.println("test2 executed!"); } catch (IOException ioe) { System.out.println("Exception in execution!"); System.out.println(ioe.getMessage()); } //int i = process.exitValue(); System.out.println("completed " ) ; //System.out.println(process.exitValue()); return process; } }
gpl-3.0
fearless359/simpleinvoices
include/class/MyCrypt.php
4665
<?php class MyCrypt { const HEXCHRS = "0123456789abcdef"; /** * Static function to encrypt a string using a specified key. * @param string $encrypt String to encrypt * @param string $key String to use as the encryption key. * @return string Encrypted string. */ public static function encrypt($encrypt, $key) { throw new PdoDbException("Mcrypt::encrypt - method deprecated"); // $encrypt = serialize($encrypt); // $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_DEV_URANDOM); // $key = pack('H*', $key); // $mac = hash_hmac('sha256', $encrypt, substr(bin2hex($key), -32)); // $passcrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $encrypt . $mac, MCRYPT_MODE_CBC, $iv); // $encoded = base64_encode($passcrypt) . '|' . base64_encode($iv); // return $encoded; } /** * Static function to decrypt a string using a specified key. * @param string $decrypt String to decrypt. * @param string $key String to use as the encryption key. * @return string Decrypted string. * @throws PdoDbException if the string cannot be decrypted. */ public static function decrypt($decrypt, $key) { throw new PdoDbException("Mcrypt::decrypt - method deprecated"); // $decrypt = explode('|', $decrypt . '|'); // $decoded = base64_decode($decrypt[0]); // $iv = base64_decode($decrypt[1]); // if (strlen($iv) !== mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC)) { // throw new PdoDbException("MyCrypt decrypt(): Invalid size of decode string."); // } // $key = pack('H*', $key); // $decrypted = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $decoded, MCRYPT_MODE_CBC, $iv)); // $mac = substr($decrypted, -64); // $decrypted = substr($decrypted, 0, -64); // $calcmac = hash_hmac('sha256', $decrypted, substr(bin2hex($key), -32)); // if ($calcmac !== $mac) { // throw new PdoDbException("MyCrypt decrypt(): Calculated mac is not equal to store mac."); // } // $decrypted = unserialize($decrypted); // return $decrypted; } /** * Join the two parts of the line together separated by an equal sign. * @param string $itemname Name of this item. * @param string $encrypt Encrypted value associated with the <b>$itemname</b>. * @return string Line formed by joining <b>$itemname = $encrypt</b>. */ public static function join($itemname, $encrypt) { throw new PdoDbException("Mcrypt::join - method deprecated"); // $line = $itemname . " = " . $encrypt; // return $line; } /** * Unjoin line parts separated by an equal sign. * @param string $line Line to be broken apart. * @param string $prefix Value that is at the first part of the field separated from the * rest of the parameter name by a period. Ex: <i>database.adapter</i> is the <i>adapter</i> * field with a prefix of <i>database</i>. * @return array $pieces The two parts of the line previously joined by the equal sign. */ public static function unjoin($line, $prefix) { $line = preg_replace('/^(.*);.*$/', '$1', $line); $pieces = explode("=", $line, 2); if (count($pieces) != 2) return array("",""); $parts = explode(".", $pieces[0]); $ndx = count($parts) - 1; if (!empty($prefix) && ($ndx < 1 || trim($parts[0] != $prefix))) return array("",""); $pieces[0] = trim($parts[$ndx]); $pieces[1] = trim($pieces[1]); return $pieces; } /** * Static function to generate a 64 character key based on a specified value. * @param String $id Character string to base key on. * @return String Generated hex key. * @throws PdoDbException if no <b>$id</b> is specified. */ public static function keygen($id=null) { if (!isset($id)) { throw new PdoDbException("MyCrypt keygen(): Required parameter not provided."); } $len = strlen($id); $key = ''; for($i=0; $i<$len; $i++) { $chr = substr($id,$i,1); $val = ord(substr($id,$i,1)); $lft = 0; do { $ndx = $val % 16; $chr = substr(self::HEXCHRS, $ndx, 1); $key = ($lft++ % 2 == 0 ? $chr . $key : $key . $chr); $val = ($val - $ndx) / 16; } while($val > 0); } while (strlen($key) < 64) $key .= $key; $key = substr($key, 0, 64); return $key; } }
gpl-3.0
iomad/iomad
blocks/iomad_company_admin/classes/output/renderer.php
15316
<?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 block_iomad_company_admin * @copyright 2021 Derick Turner * @author Derick Turner * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace block_iomad_company_admin\output; defined('MOODLE_INTERNAL') || die(); use plugin_renderer_base; use html_writer; class renderer extends plugin_renderer_base { /** * Display role templates. */ public function role_templates($templates, $backlink) { global $DB; // get heading $out = '<h3>' . get_string('roletemplates', 'block_iomad_company_admin') . '</h3>'; $out .= '<a class="btn btn-primary" href="'.$backlink.'">' . get_string('back') . '</a>'; $table = new \html_table(); foreach ($templates as $template) { $deletelink = new \moodle_url('/blocks/iomad_company_admin/company_capabilities.php', array('templateid' => $template->id, 'action' => 'delete', 'sesskey' => sesskey())); $editlink = new \moodle_url('/blocks/iomad_company_admin/company_capabilities.php', array('templateid' => $template->id, 'action' => 'edit')); $row = array($template->name, '<a class="btn btn-primary" href="'.$deletelink.'">' . get_string('deleteroletemplate', 'block_iomad_company_admin') . '</a> ' . '<a class="btn btn-primary" href="'.$editlink.'">' . get_string('editroletemplate', 'block_iomad_company_admin') . '</a>'); $table->data[] = $row; } $out .= \html_writer::table($table); return $out; } /** * Is the supplied id in the leaf somewhere? * @param array $leaf * @param int $id * @return boolean */ private function id_in_tree($leaf, $id) { if ($leaf->id == $id) { return true; } if (!empty($leaf->children)) { foreach ($leaf->children as $child) { if (self::id_in_tree($child, $id)) { return true; } } } return false; } /** * Render one leaf of department select * @param array $leaf * @param int $depth - how far down the tree * @param int $selected - which node is selected (if any) * @return html */ private function department_leaf($leaf, $depth, $selected) { $haschildren = !empty($leaf->children); $expand = self::id_in_tree($leaf, $selected); if ($depth == 1 && $leaf->id == $selected) { $expand = false; } $style = 'style="margin-left: ' . $depth * 5 . 'px;"'; $class = 'tree_item'; $aria = ''; if ($haschildren) { $class .= ' haschildren'; if ($expand) { $aria = 'aria-expanded="true"'; } else { $aria = 'aria-expanded="false"'; } } else { $class .= ' nochildren'; } if ($leaf->id == $selected) { $aria_selected = 'aria-selected="true"'; $name = '<b>' . $leaf->name . ' ' . $leaf->id . ' ' . $selected . '</b>'; } else { $aria_selected = 'aria-selected="false"'; $name = $leaf->name . ' ' . $leaf->id . ' ' . $selected; } $data = 'data-id="' . $leaf->id . '"'; $html = '<div role="treeitem" ' . $aria . ' ' . $aria_selected . ' class="' . $class .'" ' . $style . '>'; $html .= '<span class="tree_dept_name" ' . $data . '>' . $leaf->name . '</span>'; if ($haschildren) { $html .= '<div role="group">'; foreach($leaf->children as $child) { $html .= $this->department_leaf($child, $depth+1, $selected); } $html .= '</div>'; } $html .= '</div>'; return $html; } /** * Create list markup for tree.js department select * @param array $tree structure * @param int $selected selected id (if any) * @return string HTML markup */ public function department_tree($trees, $selected) { $html = ''; $html .= '<div class="dep_tree">'; $html .= '<div role="tree" id="department_tree">'; foreach ($trees as $tree) { $html .= $this->department_leaf($tree, 1, $selected); } $html .= '</div></div>'; return $html; } /** * Render admin block * @param adminblock $adminblock */ public function render_adminblock(adminblock $adminblock) { return $this->render_from_template('block_iomad_company_admin/adminblock', $adminblock->export_for_template($this)); } /** * Render editcompanies page * @param editcompanies $editcompanies */ public function render_editcompanies(editcompanies $editcompanies) { return $this->render_from_template('block_iomad_company_admin/editcompanies', $editcompanies->export_for_template($this)); } /** * Render company capabilities roles page * @param capabilitiesroles $capabilitiesroles */ public function render_capabilitiesroles(capabilitiesroles $capabilitiesroles) { return $this->render_from_template('block_iomad_company_admin/capabilitiesroles', $capabilitiesroles->export_for_template($this)); } /** * Render capabilties page * @param capabilitiesroles $capabilities */ public function render_capabilities(capabilities $capabilities) { return $this->render_from_template('block_iomad_company_admin/capabilities', $capabilities->export_for_template($this)); } /** * Render role templates page * @param roletemplates $roletemplates */ public function render_roletemplates(roletemplates $roletemplates) { return $this->render_from_template('block_iomad_company_admin/roletemplates', $roletemplates->export_for_template($this)); } public function render_datetime_element($name, $id, $timestamp) { // Get the calendar type used - see MDL-18375. $calendartype = \core_calendar\type_factory::get_calendar_instance(); $this->_elements = array(); $dateformat = $calendartype->get_date_order(); // Reverse date element (Day, Month, Year), in RTL mode. if (right_to_left()) { $dateformat = array_reverse($dateformat); } if (!empty($timestamp)) { $dayvalue = date('d', $timestamp); $monvalue = date('n', $timestamp); $yearvalue = date('Y', $timestamp); $selectarray = array('class' => 'customselect', 'onchange' => "this.form.submit()"); $checkboxarray = array('type' => 'checkbox', 'name' => $name."[enabled]", 'value' => 1, 'checked' => 'checked', 'class' => 'form-check-input datecontrolswitch checkbox', 'id' => 'id_' . $id . '_calender_enabled'); } else { $dayvalue = date('d', time()); $monvalue = date('n', time()); $yearvalue = date('Y', time()); $selectarray = array('class' => 'customselect', 'disabled' => 'disabled', 'onchange' => "this.form.submit()"); $checkboxarray = array('type' => 'checkbox', 'name' => $name."[enabled]", 'class' => 'form-check-input datecontrolswitch checkbox', 'id' => 'id_' . $id . '_calender_enabled'); } $html = html_writer::start_tag('span', array('class' => 'fdate_selector d-flex')); $html .= html_writer::start_tag('span', array('data-fieldtype' => 'select')); $html .= html_writer::start_tag('select', $selectarray + array('name' => $name."[day]", 'id' => $id."_day")); foreach ($dateformat['day'] as $key => $value) if ($dayvalue == $key) { $html .= html_writer::tag('option', $value, array('value' => $key, 'selected' => true)); } else { $html .= html_writer::tag('option', $value, array('value' => $key)); } $html .= html_writer::end_tag('select'); $html .= html_writer::end_tag('span') . " "; $html .= html_writer::start_tag('span', array('data-fieldtype' => 'select')); $html .= html_writer::start_tag('select', $selectarray + array('name' => $name."[month]", 'id' => $id."_month")); foreach ($dateformat['month'] as $key => $value) if ($monvalue == $key) { $html .= html_writer::tag('option', $value, array('value' => $key, 'selected' => true)); } else { $html .= html_writer::tag('option', $value, array('value' => $key)); } $html .= html_writer::end_tag('select'); $html .= html_writer::end_tag('span') . " "; $html .= html_writer::start_tag('span', array('data-fieldtype' => 'select')); $html .= html_writer::start_tag('select', $selectarray + array('name' => $name."[year]", 'id' => $id."_year")); foreach ($dateformat['year'] as $key => $value) if ($yearvalue == $key) { $html .= html_writer::tag('option', $value, array('value' => $key, 'selected' => true)); } else { $html .= html_writer::tag('option', $value, array('value' => $key)); } $html .= html_writer::end_tag('select'); $html .= html_writer::end_tag('span') . " "; $html .= html_writer::start_tag('a', array('class' => "visibleifjs", 'name' => $name."[calendar]", 'href'=>"#", 'id'=>"id_" . $id ."_calendar")); $html .= html_writer::tag('i', '', array('class'=>"icon fa fa-calendar fa-fw ", 'title'=>"Calendar", 'aria-label'=>"Calendar")); $html .= html_writer::end_tag('a'); $html .= html_writer::end_tag('span'); if (empty($timestamp)) { $html .= html_writer::start_tag('label', array('class' => 'form-check fitem')); $html .= html_writer::tag('input', '', $checkboxarray); $html .= get_string('enable'); $html .= html_writer::end_tag('label'); } $html .= html_writer::tag('input', '', array('name' => 'orig' . $name, 'type' => 'hidden', 'value' => $timestamp, 'id' => 'orig' . $id)); return $html; } public function display_tree_selector($company, $parentlevel, $linkurl, $urlparams, $departmentid = 0) { global $USER; if (\iomad::has_capability('block/iomad_company_admin:edit_all_departments', \context_system::instance())) { $userlevels = array($parentlevel->id => $parentlevel->id); } else { $userlevels = $company->get_userlevel($USER); } $subhierarchieslist = array(); $departmenttree = array(); foreach ($userlevels as $userlevelid => $userlevel) { $subhierarchieslist = $subhierarchieslist + \company::get_all_subdepartments($userlevelid); $departmenttree[] = \company::get_all_subdepartments_raw($userlevelid); } if (empty($departmentid)) { $departmentid = key($userlevels); } $treehtml = $this->department_tree($departmenttree, optional_param('deptid', 0, PARAM_INT)); $departmentselect = new \single_select(new \moodle_url($linkurl, $urlparams), 'deptid', $subhierarchieslist, $departmentid); $departmentselect->label = get_string('department', 'block_iomad_company_admin') . $this->help_icon('department', 'block_iomad_company_admin') . '&nbsp'; $returnhtml = html_writer::tag('h4', get_string('department', 'block_iomad_company_admin')); $returnhtml .= \html_writer::start_tag('div', array('class' => 'iomadclear')); $returnhtml .= \html_writer::start_tag('div', array('class' => 'fitem')); $returnhtml .= $treehtml; $returnhtml .= \html_writer::start_tag('div', array('style' => 'display:none')); $returnhtml .= $this->render($departmentselect); $returnhtml .= \html_writer::end_tag('div'); $returnhtml .= \html_writer::end_tag('div'); $returnhtml .= \html_writer::end_tag('div'); return $returnhtml; } public function display_tree_selector_form($company, &$mform, $parentid = 0, $before = '') { global $USER; // Get the available departments. $parentlevel = \company::get_company_parentnode($company->id); if (\iomad::has_capability('block/iomad_company_admin:edit_all_departments', \context_system::instance())) { $userlevels = array($parentlevel->id => $parentlevel->id); } else { $userlevels = $company->get_userlevel($USER); } // Put them into a big list. $subhierarchieslist = array(); $departmenttree = array(); foreach ($userlevels as $userlevelid => $userlevel) { $subhierarchieslist = $subhierarchieslist + \company::get_all_subdepartments($userlevelid); $departmenttree[] = \company::get_all_subdepartments_raw($userlevelid); } // Set up the tree HTML. if (empty($parentid)) { $initialdepartment = optional_param('deptid', 0, PARAM_INT); } else { $initialdepartment = $parentid; } $treehtml = $this->department_tree($departmenttree, $initialdepartment); // Add it to the form. if (empty($before)) { $mform->addElement('html', "<h4>" . get_string('department', 'block_iomad_company_admin') . "</h4>"); $mform->addElement('html', $treehtml); } else { $mform->insertElementBefore($mform->addElement('html', "<h4>" . get_string('department', 'block_iomad_company_admin') . "</h4>"), $before); $mform->insertElementBefore($mform->addElement('html', $treehtml), $before); } // This is getting hidden anyway, so no need for label $mform->addElement('html', '<div class="display:none;">'); $mform->addElement('select', 'deptid', ' ', $subhierarchieslist, array('class' => 'iomad_department_select', 'onchange' => 'this.form.submit()')); $mform->disabledIf('deptid', 'action', 'eq', 1); $mform->addElement('html', '</div>'); } }
gpl-3.0
chris-klinger/Goat
results/intermediate.py
4244
""" This module contains helper functions/classes for dealing with intermediate search results, including creating new or reverse searches from them. """ import re from Bio import SeqIO from bin.initialize_goat import configs from searches import search_util from queries import query_objects class Search2Queries: def __init__(self, search_obj, mode='reverse'): self.sobj = search_obj self.mode = mode # get dbs from global variables self.sqdb = configs['search_queries'] self.udb = configs['result_db'] self.qdb = configs['query_db'] self.rdb = configs['record_db'] def get_result_objs(self): """Goes through and fetches the robj for each rid""" for rid in self.sobj.list_results(): #print(rid) robj = self.udb[rid] yield robj def populate_search_queries(self): """Populates queries for each result""" for robj in self.get_result_objs(): r2q = Result2Queries(self.sobj, robj, self.mode) r2q.add_queries() # adds queries to search queries db class Result2Queries: def __init__(self, search_obj, result_obj, mode='reverse'): self.sobj = search_obj self.uobj = result_obj self.mode = mode # dbs are global self.qdb = configs['query_db'] self.rdb = configs['record_db'] self.sqdb = configs['search_queries'] def get_titles(self): """Return a list of hit names""" desired_seqs = [] seq_records = [] if self.sobj.algorithm == 'blast': desired_seqs.extend([search_util.remove_blast_header(hit.title) for hit in self.uobj.parsed_result.descriptions]) elif self.sobj.algorithm == 'hmmer': #desired_seqs.extend([(hit.target_name + ' ' + hit.desc) # should recapitulate description # for hit in self.uobj.parsed_result.descriptions]) desired_seqs.extend([hit.title for hit in self.uobj.parsed_result.descriptions]) #tterfile = open('/Users/cklinger/tthermophila.txt','w') #for seq in desired_seqs: #print(seq) #print() #tterfile.write(str(seq) + '\n') #tterfile.write('\n') #print() for record in SeqIO.parse(self.get_record_file(), "fasta"): #print(str(record.description).strip()) #tterfile.write(str(record.description) + '\n') if (record.description in desired_seqs or\ re.sub('\t',' ',record.description) in desired_seqs): # BLAST turns tabs into three spaces seq_records.append(record) return seq_records def get_record_file(self): """Return the full handle to the db record file""" robj = self.rdb[self.uobj.database] # fetch record object for v in robj.files.values(): # should maybe encapsulate better if v.filetype == self.uobj.db_type: return v.filepath def add_queries(self): """ Adds new query objects; these are present both as a list of qids in the result_obj and as query objects in the search_queries DB """ o_qid = None # original query tdb = None # target db if self.mode == 'reverse': if self.sobj.algorithm == 'blast': o_qid = self.uobj.query qobj = self.qdb[self.uobj.query] tdb = qobj.record # target defined if reverse search elif self.sobj.algorithm == 'hmmer': if self.uobj.spec_qid: o_qid = self.uobj.spec_qid if self.uobj.spec_record: tdb = self.uobj.spec_record for record in self.get_titles(): qobj = query_objects.SeqQuery( identity=record.id, name=record.name, description=record.description, sequence=record.seq, record=self.uobj.database, target_db=tdb, original_query=o_qid) self.uobj.add_int_query(record.id) self.sqdb.add_entry(record.id, qobj) # adds the qobj to the int database
gpl-3.0
eduardgamiao/Mepedia
target/scala-2.10/src_managed/main/views/html/Ho.template.scala
5639
package views.html import play.templates._ import play.templates.TemplateMagic._ import play.api.templates._ import play.api.templates.PlayMagic._ import models._ import controllers._ import java.lang._ import java.util._ import scala.collection.JavaConversions._ import scala.collection.JavaConverters._ import play.api.i18n._ import play.core.j.PlayMagicForJava._ import play.mvc._ import play.data._ import play.api.data.Field import play.mvc.Http.Context.Implicit._ import views.html._ /**/ object Ho extends BaseScalaTemplate[play.api.templates.HtmlFormat.Appendable,Format[play.api.templates.HtmlFormat.Appendable]](play.api.templates.HtmlFormat) with play.api.templates.Template0[play.api.templates.HtmlFormat.Appendable] { /**/ def apply():play.api.templates.HtmlFormat.Appendable = { _display_ { Seq[Any](_display_(Seq[Any](/*1.2*/Main("Michael Ho")/*1.20*/ {_display_(Seq[Any](format.raw/*1.22*/(""" <div class="container"> <div class="row"> <div class="col-md-4"> <div class="well"> <div class="ho"></div> </div> </div> <div class="col-md-8"> <div class="well"> <h3>Michael Ho</h3> <p>The most consistent performer of the past three decades on the heaviest stretch of surf in the world happens to be one of the smallest. At a mere 5'5" and 135 pounds, Michael Ho personally proved size to be of little importance when it comes to bravery on the North Shore. His expertise was not limited to big surf, as he became a highly successful and feared competitor in all conditions, finishing in the ASP Top 16 for 10 consecutive seasons.</p> <p>Edmund "Chico" Ho was stationed in Cuba, serving in the U.S. Army, when his wife was expecting their first child. They wanted desperately to make it back to Hawaii for the blessed event, but came up short as their son Michael entered the world in San Mateo, California. Chico was an original Waikiki beach boys, carving tikis, shaping boards and fishing to support his growing family (three girls and another boy, 1993 ASP World Champion Derek Ho followed). He hoisted Michael onto his shoulders and introduced him to surfing at age three. A few years later, the youngster was competing in local amateur events with peers Kainoa and Keone Downing, Clinton Blears and Kenny Morrow, soon finding success as the U.S. Boys' amateur champion.</p> <p>Inspired by Jeff Hakman, Larry Bertlemann and Reno Abellira, Ho put equal time into developing his big-wave riding and hotdog surfing. By age 10, he was surfing Haleiwa on the North Shore. At 15, he represented Hawaii at the World Amateur Championships in Ocean Beach and surfed into the finals. After graduation from Kailua High School, he set his sights on professional surfing. At the time, he knew of no one getting paid to go surfing, but he was ready to test the waters. "Rabbit [Bartholomew] and I were talking about getting money from sponsors on a plane ride from somewhere. I got a couple hundred from some wetsuit company, and I was, like, 'whoa.'"</p> <p>As the IPS world tour first wandered the globe in 1976, Ho led a formidable Hawaiian assault, rising to third in 1978 and establishing himself as a barnacle in the Top 16. He twice won the Hawaiian Triple Crown, the Duke Classic and the World Cup, as well as claiming the 1982 Pipe Masters while surfing with a cast on his broken wrist. At any venue, his keen sense of positioning and wave knowledge made him an unwelcome draw for any competitor. Three-time world champion Tom Curren called Ho the person he least liked to compete against.</p> <p>For all his international achievements, nowhere was Ho more dominant than the North Shore of Oahu -- his home since age 17. At Sunset Beach, a spot he first surfed at 15, his knowledge of the complex conditions remains unparalleled. Older than most of the lineup, he shows few signs of slowing, still an avid competitor and finalist in the 1997 Pipe Masters. Married since 1988, he has two children -- Mason and Coco. Both have made their own names in professional surfing-- Mason for his air game and barrel riding, and Coco on the women's World Tour.</p> <p>Surfing has been, and will remain, Ho's only profession. A competitor in each World Masters Championship since its inception in 1997, he came through with a victory in the Over 40 Division in Lafiteria, France, in the 2000 event. "I never beat Rabbit or MR man-on-man before, so that in itself was a feat." Known as "Uncle Mike" across the North Shore, he remains childlike at heart, and his passion for surfing is as strong as ever.</p> </div> </div> </div> </div> """)))})),format.raw/*55.2*/(""" """))} } def render(): play.api.templates.HtmlFormat.Appendable = apply() def f:(() => play.api.templates.HtmlFormat.Appendable) = () => apply() def ref: this.type = this } /* -- GENERATED -- DATE: Fri Jan 10 22:31:23 HST 2014 SOURCE: /Users/eduardgamiao/Desktop/ICS414/Mepedia/app/views/Ho.scala.html HASH: e6f98e21e38ce2f0e0a24c3d1d9caa476b48de73 MATRIX: 861->1|887->19|926->21|4976->4040 LINES: 29->1|29->1|29->1|83->55 -- GENERATED -- */
gpl-3.0
JuantAldea/LUT-2013-Tuister-OOP
Tuister/src/pdus/UnlikePDU.java
805
package pdus; import javax.xml.bind.JAXBException; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlAccessType; @XmlRootElement(name = "unlike") @XmlAccessorType(XmlAccessType.NONE) public class UnlikePDU extends PDU { @XmlAttribute(name = "postid") protected Integer postid; @SuppressWarnings("unused") private UnlikePDU() { } public UnlikePDU(Integer postid) { this.postid = postid; } public String toXML() throws JAXBException { return super.toXML(this.getClass()); } public static UnlikePDU XMLParse(String xml) throws JAXBException { return (UnlikePDU) PDU.XMLParse(xml, UnlikePDU.class); } }
gpl-3.0
INSAlgo/codingbattle-2017
pre-concours/a_dis_papa/sol/sol-php.php
36
<?php echo substr(fgets(STDIN), 4);
gpl-3.0
siefkenj/JSCalc
bignum.js
20464
// Generated by CoffeeScript 1.3.1 /* * Bignumber support for javascript. * * Copyright (C) 2012 Jason Siefken * * 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/>. */ var BigInt, BigNatural, CHUNK_DIGITS, CHUNK_SIZE, COMPLEX_PERCISION, Complex, ComplexMath, LOG10, trimZeros; LOG10 = Math.log(10); CHUNK_SIZE = 10; CHUNK_DIGITS = Math.round(Math.log(CHUNK_SIZE) / LOG10); trimZeros = function(array) { while (array.length > 0 && array[array.length - 1] === 0) { array.pop(); } return array; }; BigNatural = (function() { BigNatural.name = 'BigNatural'; function BigNatural(num) { var arr, chunk, i; this.nums = []; if (typeof num === "number") { while (num >= 1) { chunk = num % CHUNK_SIZE; this.nums.push(chunk); num = (num - chunk) / CHUNK_SIZE; } } else if (typeof num === "string") { i = num.length; while (i > 0) { this.nums.push(parseInt(num.slice(Math.max(i - CHUNK_DIGITS, 0), i), 10)); i -= CHUNK_DIGITS; } } else if (num instanceof Array || num instanceof BigNatural) { arr = void 0; if (num instanceof Array) { arr = num; } else { arr = num.nums; } this.nums = trimZeros(arr.slice()); } else { throw { name: "Initialization Error" }; ({ message: "Unknown initialization type " + num }); } } BigNatural.prototype._constructor = BigNatural; BigNatural.prototype.toString = function() { var formatChunk; formatChunk = function(n) { var leading, ret; ret = "" + n; leading = Array(Math.max(0, CHUNK_DIGITS - ret.length) + 1).join("0"); return leading + ret; }; if (this.nums.length === 0) { return "0"; } return this.nums[this.nums.length - 1] + this.nums.slice(0, this.nums.length - 1).reverse().map(formatChunk).join(""); }; BigNatural.prototype._compareArrays = function(a, b) { var i; if ((a.length === 0 && b.length === 1 && b[0] === 0) || (b.length === 0 && a.length === 1 && a[0] === 0) || (a.length === 0 && b.length === 0)) { return 0; } if (a.length > b.length) { return 1; } else { if (a.length < b.length) { return -1; } } i = a.length; while (i >= 0) { if (a[i] > b[i]) { return 1; } else { if (a[i] < b[i]) { return -1; } } i--; } return 0; }; BigNatural.prototype._sumArraysWithCarry = function(a, b) { var carry, chunk, chunkSum, getElm, i, ret; getElm = function(array, elm) { return (typeof array[elm] === "undefined" ? 0 : array[elm]); }; ret = []; carry = 0; i = 0; while (i < Math.max(a.length, b.length)) { chunkSum = getElm(a, i) + getElm(b, i) + carry; chunk = chunkSum % CHUNK_SIZE; carry = (chunkSum - chunk) / CHUNK_SIZE; ret.push(chunk); i++; } if (carry > 0) { ret.push(carry); } return ret; }; BigNatural.prototype._subtractArrays = function(a, b) { var complement, sum; complement = this._arrayPAdicCompliment; sum = this._sumArraysWithCarry; return complement(sum(complement(a), b)); }; BigNatural.prototype._arrayPAdicCompliment = function(array) { return array.map(function(d) { return CHUNK_SIZE - d - 1; }); }; BigNatural.prototype._arrayDivideWithRemainder = function(a, b) { var cmp, divChunk, dividand, remainder, _ref; if (b.length === 0 || (b.length === 1 && b[0] === 0)) { throw { name: "Division By Zero Error" }; ({ message: "Division by zero" }); } dividand = []; remainder = []; cmp = this._compareArrays(a.slice(1), b); if (cmp === 0 || cmp === 1) { _ref = this._arrayDivideWithRemainder(a.slice(1), b), dividand = _ref[0], remainder = _ref[1]; remainder.unshift(a[0]); a = remainder; } divChunk = 0; cmp = this._compareArrays(a, b); while (cmp === 0 || cmp === 1) { a = trimZeros(this._subtractArrays(a, b)); divChunk++; cmp = this._compareArrays(a, b); } dividand.unshift(divChunk); return [trimZeros(dividand), a]; }; BigNatural.prototype.shift = function(n) { var i, ret; ret = Array(n); i = n - 1; while (i >= 0) { ret[i] = 0; i--; } return new this._constructor(ret.concat(this.nums)); }; BigNatural.prototype.add = function(other) { return new this._constructor(this._sumArraysWithCarry(this.nums, other.nums)); }; BigNatural.prototype.sub = function(other) { var complement, sum; complement = this._arrayPAdicCompliment; sum = this._sumArraysWithCarry; return new this._constructor(complement(sum(complement(this.nums), other.nums))); }; BigNatural.prototype.mul = function(other) { var carry, chunk, chunkProduct, currArray, digit, getElm, pos, ret; getElm = function(array, elm) { if (typeof array[elm] === "undefined") { return 0; } else { return array[elm]; } }; ret = new this._constructor(0); digit = 0; while (digit < other.nums.length) { currArray = []; carry = 0; pos = 0; while (pos < this.nums.length) { chunkProduct = other.nums[digit] * this.nums[pos] + carry; chunk = chunkProduct % CHUNK_SIZE; carry = (chunkProduct - chunk) / CHUNK_SIZE; currArray.push(chunk); pos++; } currArray.push(carry); ret = ret.add((new this._constructor(currArray)).shift(digit)); digit++; } return ret; }; BigNatural.prototype.mod = function(other) { var ret; if (other.eq(new this._constructor(0))) { return new this._constructor(0); } ret = new this._constructor(this); if (this.nums.length >= other.nums.length + 2) { ret = ret.mod(other.shift(1)); } while (ret.gte(other)) { ret = new this._constructor(ret.sub(other)); } return ret; }; BigNatural.prototype.gcd = function(other) { var a, b, _ref; a = this; b = other; while (!(b.isZero())) { _ref = [b, a.mod(b)], a = _ref[0], b = _ref[1]; } return a; }; BigNatural.prototype.div = function(other) { return this.divideWithRemainder(other)[0]; }; BigNatural.prototype.divideWithRemainder = function(other) { var dividand, remainder, _ref; _ref = this._arrayDivideWithRemainder(this.nums, other.nums), dividand = _ref[0], remainder = _ref[1]; return [new this._constructor(dividand), new this._constructor(remainder)]; }; BigNatural.prototype.cmp = function(other) { return this._compareArrays(this.nums, other.nums); }; BigNatural.prototype.isZero = function() { return this.nums.length === 0 || (this.nums.length === 1 && this.nums[0] === 0); }; BigNatural.prototype.isOne = function() { return this.nums.length === 1 && this.nums[0] === 1; }; BigNatural.prototype.eq = function(other) { return this.cmp(other) === 0; }; BigNatural.prototype.gt = function(other) { return this.cmp(other) === 1; }; BigNatural.prototype.lt = function(other) { return this.cmp(other) === -1; }; BigNatural.prototype.gte = function(other) { var cmp; cmp = this.cmp(other); return cmp === 1 || cmp === 0; }; BigNatural.prototype.lte = function(other) { var cmp; cmp = this.cmp(other); return cmp === -1 || cmp === 0; }; return BigNatural; })(); BigInt = (function() { BigInt.name = 'BigInt'; function BigInt(num, sign) { this.num; this.sign = 1; if (typeof num === "number") { if (num < 0) { this.sign = -1; num = -num; } } else if (typeof num === "string") { if (num.charAt(0) === "-") { this.sign = -1; num = num.slice(1); } } else if (num instanceof BigNatural) { if (sign === -1) { this.sign = -1; } num = num.nums; } else { if (num instanceof Array ? sign === -1 : void 0) { this.sign = -1; } } this.num = new BigNatural(num); } BigInt.prototype._constructor = BigInt; BigInt.prototype.toString = function() { var sign; sign = (this.sign === 1 ? "" : "-"); return sign + this.num; }; BigInt.prototype.negate = function() { return new this._constructor(this.num, -this.sign); }; BigInt.prototype.abs = function() { return new this._constructor(this.num, 1); }; BigInt.prototype.add = function(other) { var bigger, sign, smaller, sum; sign = void 0; if (this.sign === other.sign) { sign = this.sign; return new this._constructor(this.num.add(other.num), sign); } else { bigger = void 0; smaller = void 0; if (this.num.cmp(other.num) === 1) { bigger = this.num; smaller = other.num; sign = this.sign; } else { bigger = other.num; smaller = this.num; sign = other.sign; } sum = bigger.sub(smaller); return new this._constructor(sum, sign); } }; BigInt.prototype.mul = function(other) { var sign; sign = this.sign * other.sign; return new this._constructor(this.num.mul(other.num), sign); }; BigInt.prototype.div = function(other) { return this.divideWithRemainder(other)[0]; }; BigInt.prototype.divideWithRemainder = function(other) { var dividand, dividandSign, remainder, remainderSign, _ref; dividandSign = 1; remainderSign = 1; if (this.sign === -1 && other.sign === 1) { dividandSign = -1; remainderSign = -1; } else if (this.sign === 1 && other.sign === -1) { dividandSign = -1; remainderSign = 1; } else if (this.sign === -1 && other.sign === -1) { dividandSign = 1; remainderSign = -1; } this.sign * other.sign; _ref = this.num.divideWithRemainder(other.num), dividand = _ref[0], remainder = _ref[1]; return [new this._constructor(dividand, dividandSign), new this._constructor(remainder, remainderSign)]; }; BigInt.prototype.gcd = function(other) { return this.num.gcd(other.num); }; BigInt.prototype.cmp = function(other) { if (this.sign > other.sign) { return 1; } else { if (this.sign < other.sign) { return -1; } } if (this.sign === 1) { return this.num.cmp(other.num); } else { return -this.num.cmp(other.num); } }; BigInt.prototype.isZero = function() { return this.nums.length === 0 || (this.nums.length === 1 && this.nums[0] === 0); }; BigInt.prototype.isOne = function() { return this.nums.length === 1 && this.nums[0] === 1 && this.sign === 1; }; return BigInt; })(); COMPLEX_PERCISION = 10e10; Complex = (function() { Complex.name = 'Complex'; function Complex(re, im) { this.re = re; this.im = im; } Complex.prototype._constructor = Complex; Complex.prototype.toString = function() { var im, imToString, re; imToString = function(x) { if (x === 1) { return "i"; } else { if (x === -1) { return "-i"; } } return x + "i"; }; if (isNaN(this.re) && isNaN(this.im)) { return "NaN"; } re = Math.round(this.re * COMPLEX_PERCISION) / COMPLEX_PERCISION; im = Math.round(this.im * COMPLEX_PERCISION) / COMPLEX_PERCISION; if (re === 0 && im === 0) { return "0"; } else if (im === 0) { return "" + re; } else { if (re === 0) { return imToString(im); } } if (im < 0) { return re + " - " + imToString(Math.abs(im)); } else { return re + " + " + imToString(im); } }; Complex.prototype.isReal = function(a) { a = a || this; if (Math.abs(a.im) < 1 / COMPLEX_PERCISION) { return true; } return false; }; Complex.prototype.isImaginary = function(a) { a = a || this; if (Math.abs(a.re) < 1 / COMPLEX_PERCISION) { return true; } return false; }; Complex.prototype.eq = function(other) { var im, otherIm, otherRe, re; re = Math.round(this.re * COMPLEX_PERCISION) / COMPLEX_PERCISION; im = Math.round(this.im * COMPLEX_PERCISION) / COMPLEX_PERCISION; otherRe = Math.round(other.re * COMPLEX_PERCISION) / COMPLEX_PERCISION; otherIm = Math.round(other.im * COMPLEX_PERCISION) / COMPLEX_PERCISION; return re === otherRe && im === otherIm; }; Complex.prototype.add = function(other) { return new Complex(this.re + other.re, this.im + other.im); }; Complex.prototype.sub = function(other) { return new Complex(this.re - other.re, this.im - other.im); }; Complex.prototype.mul = function(other) { var a, b, c, d; a = this.re; b = this.im; c = other.re; d = other.im; return new Complex(a * c - b * d, a * d + b * c); }; Complex.prototype.div = function(other) { var a, abs, b, c, d, denom; a = this.re; b = this.im; c = other.re; d = other.im; abs = Math.abs; if (abs(c) >= abs(d)) { denom = c + d * (d / c); return new Complex((a + b * (d / c)) / denom, (b - a * (d / c)) / denom); } else { denom = d + c * (c / d); return new Complex((a * (c / d) + b) / denom, (b * (c / d) - a) / denom); } }; Complex.prototype.conj = function() { return new Complex(this.re, -this.im); }; Complex.prototype.norm = function() { var abs, im, re; re = this.re; im = this.im; if (re === 0 && im === 0) { return 0; } abs = Math.abs; if (abs(re) >= abs(im)) { return abs(re) * Math.sqrt(1 + (im / re) * (im / re)); } if (abs(re) < abs(im)) { return abs(im) * Math.sqrt(1 + (re / im) * (re / im)); } }; Complex.prototype.arg = function() { var ret; ret = Math.atan2(this.im, this.re); return (ret === -Math.PI ? Math.PI : ret); }; return Complex; })(); ComplexMath = { i: new Complex(0, 1), minusI: new Complex(0, -1), iOverTwo: new Complex(0, 1 / 2), one: new Complex(1, 0), minusOne: new Complex(-1, 0), pi: new Complex(Math.PI, 0), equal: function(a, b) { return a.eq(b); }, gt: function(a, b) { return (a.norm() - b.norm()) > 1 / COMPLEX_PERCISION; }, lt: function(a, b) { return (a.norm() - b.norm()) < -1 / COMPLEX_PERCISION; }, gte: function(a, b) { return ComplexMath.equal(a, b) || ComplexMath.gt(a, b); }, lte: function(a, b) { return ComplexMath.equal(a, b) || ComplexMath.lt(a, b); }, re: function(z) { return new Complex(z.re, 0); }, im: function(z) { return new Complex(z.im, 0); }, arg: function(z) { return new Complex(z.arg(), 0); }, norm: function(z) { return new Complex(z.norm(), 0); }, fromPolar: function(mag, arg) { var a, b; a = mag * Math.cos(arg); b = mag * Math.sin(arg); return new Complex(a, b); }, floor: function(z) { return new Complex(Math.floor(z.re), Math.floor(z.im)); }, ceil: function(z) { return new Complex(Math.ceil(z.re), Math.ceil(z.im)); }, round: function(z) { return new Complex(Math.round(z.re), Math.round(z.im)); }, mod: function(a, b) { var im, re; if (a instanceof Array) { b = a[1]; a = a[0]; } re = ((a.re % b.re) + b.re) % b.re; im = ((a.im % b.im) + b.im) % b.im; if (isNaN(re) && isNaN(im)) { return new Complex(NaN, NaN); } else if (isNaN(re)) { return new Complex(0, im); } else { if (isNaN(im)) { return new Complex(re, 0); } } return new Complex(re, im); }, conj: function(z) { return z.conj(); }, negate: function(z) { return new Complex(-z.re, -z.im); }, sqrt: function(z) { var arg, mag; mag = z.norm(); arg = z.arg(); return ComplexMath.fromPolar(Math.sqrt(mag), arg / 2); }, add: function(a, b) { return a.add(b); }, sub: function(a, b) { return a.sub(b); }, mul: function(a, b) { return a.mul(b); }, div: function(a, b) { return a.div(b); }, log: function(z) { var arg, mag; mag = z.norm(); arg = z.arg(); return new Complex(Math.log(mag), arg); }, exp: function(z) { var arg, cos, mag, sin; mag = z.norm(); arg = z.arg(); cos = Math.cos(arg); sin = Math.sin(arg); return ComplexMath.fromPolar(Math.exp(mag * cos), mag * sin); }, pow: function(a, b) { var binaryDigits, buffer, currentPower, exponent, i, _i; if (b.isReal() && Math.round(b.re) === b.re && b.re < 10000) { exponent = b.re; currentPower = a; buffer = new Complex(1, 0); binaryDigits = Math.floor(Math.log(exponent) / Math.log(2)); for (i = _i = 0; 0 <= binaryDigits ? _i <= binaryDigits : _i >= binaryDigits; i = 0 <= binaryDigits ? ++_i : --_i) { if ((exponent >> i) % 2 === 1) { buffer = ComplexMath.mul(buffer, currentPower); } currentPower = ComplexMath.mul(currentPower, currentPower); } return buffer; } return ComplexMath.exp(ComplexMath.mul(ComplexMath.log(a), b)); }, factorial: function(z) { var accum, x; if (!z.isReal() || z.re < -1 / COMPLEX_PERCISION) { return new Complex(NaN, NaN); } x = z.re; if (x > 170) { return new Complex(Infinity, 0); } accum = 1; while (x > 1) { accum = accum * x; x = x - 1; } return new Complex(accum, 0); }, sin: function(z) { var twoI; twoI = new Complex(0, 2); return ComplexMath.div(ComplexMath.sub(ComplexMath.exp(ComplexMath.mul(ComplexMath.i, z)), ComplexMath.exp(ComplexMath.mul(ComplexMath.minusI, z))), twoI); }, cos: function(z) { var two; two = new Complex(2, 0); return ComplexMath.div(ComplexMath.add(ComplexMath.exp(ComplexMath.mul(ComplexMath.i, z)), ComplexMath.exp(ComplexMath.mul(ComplexMath.minusI, z))), two); }, tan: function(z) { return ComplexMath.sin(z).div(ComplexMath.cos(z)); }, asin: function(z) { return ComplexMath.mul(ComplexMath.log(ComplexMath.add(ComplexMath.mul(ComplexMath.i, z), ComplexMath.sqrt(ComplexMath.sub(ComplexMath.one, z.mul(z))))), ComplexMath.minusI); }, acos: function(z) { var sq; sq = ComplexMath.sqrt(ComplexMath.sub(ComplexMath.one, z.mul(z))); return ComplexMath.mul(ComplexMath.log(ComplexMath.add(z, ComplexMath.mul(z, ComplexMath.i))), ComplexMath.minusI); }, atan: function(z) { var lgm, lgp; lgm = ComplexMath.log(ComplexMath.sub(ComplexMath.one, ComplexMath.mul(ComplexMath.i, z))); lgp = ComplexMath.log(ComplexMath.add(ComplexMath.one, ComplexMath.mul(ComplexMath.i, z))); return ComplexMath.mul(ComplexMath.iOverTwo, ComplexMath.sub(lgm, lgp)); }, atan2: function(a, b) { return new Complex(Math.atan2(a.re, b.re), 0); }, sec: function(z) { return ComplexMath.one.div(ComplexMath.cos(z)); }, csc: function(z) { return ComplexMath.one.div(ComplexMath.sin(z)); }, cot: function(z) { return ComplexMath.one.div(ComplexMath.tan(z)); }, sinh: function(z) { return ComplexMath.minusI.mul(ComplexMath.sin(ComplexMath.i.mul(z))); }, cosh: function(z) { return ComplexMath.cos(ComplexMath.i.mul(z)); }, tanh: function(z) { return ComplexMath.minusI.mul(ComplexMath.tan(ComplexMath.i.mul(z))); }, asinh: function(z) { return ComplexMath.log(z.add(ComplexMath.sqrt(ComplexMath.one.add(z.mul(z))))); }, acosh: function(z) { return ComplexMath.log(z.add(ComplexMath.sqrt(ComplexMath.minusOne.add(z.mul(z))))); }, atanh: function(z) { return ComplexMath.log(ComplexMath.one.add(z)).sub(ComplexMath.log(ComplexMath.one.sub(z))).div(new Complex(2, 0)); } };
gpl-3.0
leopuglia/Evolution.Net
src/util/EvolutionNet.Util/Calendar/Holiday/Country/Us/National.cs
5954
using System; using System.Collections.Generic; namespace EvolutionNet.Util.Calendar.Holiday.Country.Us { public class National : Base { public National(int year) : base(year) { } #region NewYearDay public NationalHoliday NewYearDay { get { return GetNewYearDay(Year); } } public static DateTime GetNewYearDayDate(int year) { return Common.GetNewYearDayDate(year); } public static NationalHoliday GetNewYearDay(int year) { return new NationalHoliday(GetNewYearDayDate(year), "New Year"); } #endregion #region MartinLutherKingBirthday public NationalHoliday MartinLutherKingBirthday { get { return GetMartinLutherKingBirthday(Year); } } public static DateTime GetMartinLutherKingBirthdayDate(int year) { return MonthHelper.DateFromWeekday(year, 1, DayOfWeek.Monday, 3); } public static NationalHoliday GetMartinLutherKingBirthday(int year) { return new NationalHoliday(GetMartinLutherKingBirthdayDate(year), "MartinLutherKingBirthday"); } #endregion #region InaugurationDay public NationalHoliday InaugurationDay { get { return GetInaugurationDay(Year); } } public static DateTime? GetInaugurationDayDate(int year) { DateTime? date = null; if (year%4 == 1) { date = new DateTime(year, 1, 20); if (date.Value.DayOfWeek == DayOfWeek.Sunday) date.Value.AddDays(1); } return date; } public static NationalHoliday GetInaugurationDay(int year) { if (GetInaugurationDayDate(year) != null) return new NationalHoliday(GetInaugurationDayDate(year).Value, "InaugurationDay"); return null; } #endregion #region WashingtonBirthday public NationalHoliday WashingtonBirthday { get { return GetWashingtonBirthday(Year); } } public static DateTime GetWashingtonBirthdayDate(int year) { return MonthHelper.DateFromWeekday(year, 2, DayOfWeek.Monday, 3); } public static NationalHoliday GetWashingtonBirthday(int year) { return new NationalHoliday(GetWashingtonBirthdayDate(year), "WashingtonBirthday"); } #endregion #region MemorialDay // Ultima segunda do mês public NationalHoliday MemorialDay { get { return GetMemorialDay(Year); } } public static DateTime GetMemorialDayDate(int year) { return MonthHelper.DateFromWeekdayByEnd(year, 5, DayOfWeek.Monday, 1); } public static NationalHoliday GetMemorialDay(int year) { return new NationalHoliday(GetMemorialDayDate(year), "MemorialDay"); } #endregion #region IndependenceDay public NationalHoliday IndependenceDay { get { return GetIndependenceDay(Year); } } public static DateTime GetIndependenceDayDate(int year) { return new DateTime(year, 7, 4); } public static NationalHoliday GetIndependenceDay(int year) { return new NationalHoliday(GetIndependenceDayDate(year), "IndependenceDay"); } #endregion #region LaborDay public NationalHoliday LaborDay { get { return GetLaborDay(Year); } } public static DateTime GetLaborDayDate(int year) { return MonthHelper.DateFromWeekday(year, 9, DayOfWeek.Monday, 1); } public static NationalHoliday GetLaborDay(int year) { return new NationalHoliday(GetLaborDayDate(year), "LaborDay"); } #endregion #region ColumbusDay public NationalHoliday ColumbusDay { get { return GetColumbusDay(Year); } } public static DateTime GetColumbusDayDate(int year) { return MonthHelper.DateFromWeekday(year, 10, DayOfWeek.Monday, 2); } public static NationalHoliday GetColumbusDay(int year) { return new NationalHoliday(GetColumbusDayDate(year), "ColumbusDay"); } #endregion #region VeteransDay public NationalHoliday VeteransDay { get { return GetVeteransDay(Year); } } public static DateTime GetVeteransDayDate(int year) { return new DateTime(year, 11, 11); } public static NationalHoliday GetVeteransDay(int year) { return new NationalHoliday(GetVeteransDayDate(year), "VeteransDay"); } #endregion #region ThanksGivingDay public NationalHoliday ThanksGivingDay { get { return GetThanksGivingDay(Year); } } public static DateTime GetThanksGivingDayDate(int year) { return MonthHelper.DateFromWeekday(year, 11, DayOfWeek.Thursday, 4); } public static NationalHoliday GetThanksGivingDay(int year) { return new NationalHoliday(GetThanksGivingDayDate(year), "ThanksGivingDay"); } #endregion #region ChristmasDay public NationalHoliday ChristmasDay { get { return GetChristmasDay(Year); } } public static DateTime GetChristmasDayDate(int year) { return Christian.GetChristmasDayDate(year); } public static NationalHoliday GetChristmasDay(int year) { return new NationalHoliday(GetChristmasDayDate(year), "ChristmasDay"); } #endregion public override IList<NationalHoliday> NationalHolidays { get { // TODO: Aqui eu posso fazer na mão ou via reflection. Seria pegar todas as propriedades que são NationalHoliday. // TODO: Posso fazer um Helper para isso, tipo akele helper pra instanciar objetos. IList<NationalHoliday> list = new List<NationalHoliday>(); list.Add(NewYearDay); list.Add(MartinLutherKingBirthday); if (InaugurationDay != null) list.Add(InaugurationDay); list.Add(WashingtonBirthday); list.Add(MemorialDay); list.Add(IndependenceDay); list.Add(LaborDay); list.Add(ColumbusDay); list.Add(VeteransDay); list.Add(ThanksGivingDay); list.Add(ChristmasDay); return list; } } public override IList<BaseHoliday> Holidays { get { return ConvertListTo<BaseHoliday>(NationalHolidays); } } } }
gpl-3.0
iCarto/siga
libRaster/src/org/gvsig/raster/datastruct/ColorItem.java
4205
/* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana * * Copyright (C) 2005 IVER T.I. and Generalitat Valenciana. * * 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. */ package org.gvsig.raster.datastruct; import java.awt.Color; /** * Valor minimo para un item de una tabla de color. Este tendrá que pixel afecta, * nombre de esa clase, color y como estará interpolado con el siguiente. * * @version 04/07/2007 * @author BorSanZa - Borja Sánchez Zamorano (borja.sanchez@iver.es) */ public class ColorItem implements Cloneable { private double value = 0.0f; private String nameClass = null; private Color color = Color.black; private double interpolated = 50; /** * Devuelve el color * @return */ public Color getColor() { return color; } /** * Definir el color * @param color */ public void setColor(Color color) { this.color = color; } /** * Devuelve el valor de interpolación con el siguiente color. * Límites: 0..100 * @return */ public double getInterpolated() { return interpolated; } /** * Definir el valor de interpolación. Si es mayor a 100 o menor a 0 se pone * entre los valores correctos. * @param interpolated */ public void setInterpolated(double interpolated) { if (interpolated > 100) this.interpolated = 100; else if (interpolated < 0) this.interpolated = 0; else this.interpolated = interpolated; } /** * Obtener en que valor estará dicho color * @return */ public double getValue() { return value; } /** * Definir el valor del ColorItem. * @param value */ public void setValue(double value) { if (Double.isNaN(value)) return; this.value = value; } /** * Devuelve el nombre de la clase * @return */ public String getNameClass() { return nameClass; } /** * Define el nombre de la clase * @param nameClass */ public void setNameClass(String nameClass) { this.nameClass = nameClass; } /* * (non-Javadoc) * @see java.lang.Object#clone() */ public Object clone() { ColorItem clone = null; try { clone = (ColorItem) super.clone(); } catch (CloneNotSupportedException e) { } if (color != null) clone.color = new Color(color.getRGB(), (color.getAlpha() != 255)); if (nameClass != null) clone.nameClass = new String(nameClass); return clone; } /* * (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((color == null) ? 0 : color.hashCode()); result = PRIME * result + (int) interpolated; result = PRIME * result + ((nameClass == null) ? 0 : nameClass.hashCode()); long temp; temp = Double.doubleToLongBits(value); result = PRIME * result + (int) (temp ^ (temp >>> 32)); return result; } /* * (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ColorItem other = (ColorItem) obj; if (color == null) { if (other.color != null) return false; } else if (!color.equals(other.color)) return false; if (interpolated != other.interpolated) return false; if (nameClass == null) { if (other.nameClass != null) return false; } else if (!nameClass.equals(other.nameClass)) return false; if (Double.doubleToLongBits(value) != Double.doubleToLongBits(other.value)) return false; return true; } }
gpl-3.0
atlaser/Tools
SContest/Version1/SContest1/SContest1/SContest1.cpp
857
// SContest1.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "SContest1.h" #include "TestObj.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // The one and only application object CWinApp theApp; using namespace std; int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0; HMODULE hModule = ::GetModuleHandle(NULL); if (hModule != NULL) { // initialize MFC and print and error on failure if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0)) { // TODO: change error code to suit your needs _tprintf(_T("Fatal Error: MFC initialization failed\n")); nRetCode = 1; } else { CTestObj::GetMe().StartTest(); } } else { // TODO: change error code to suit your needs _tprintf(_T("Fatal Error: GetModuleHandle failed\n")); nRetCode = 1; } return nRetCode; }
gpl-3.0
4rg0n/poe_orb_calc
js/ext/app/view/error/Window.js
2143
/** * Window for Errors * * @xtype calc-error-window * * @class Calc.view.error.Window * @extends Ext.window.Window * @mixin Calc.library.mixin.Template * @author Arg0n <argonthechecker@gmail.com> */ Ext.define('Calc.view.error.Window', { extend: 'Ext.window.Window', mixins: [ 'Calc.library.mixin.Template' ], /** * Error type * * @cfg {Number} type */ type: null, iconCls: Calc.cssPrefix + 'icon-error', alias: 'widget.calc-error-window', itemId: 'calc-error-window', autoScroll: true, closable: true, closeAction: 'hide', modal: true, loader: { url: Calc.appFolder + 'template/error/Error.html', renderer: Calc.XTemplateRenderer.loader }, styleHtmlContent: true, bodyPadding: 10, maxHeight: 600, maxWidth: 800, /** * Sets data for template * Oberwrites Calc.library.mixin.Template.setData() * * @param {Object} data * @param {Boolean} load */ setData: function(data, load) { if (Ext.isObject(data)) { this.data = data; Ext.apply(this, data); if (data.title) { this.setTitle(data.title); } else { this.setTitle(Language.translate('Error')); } if (data.type) { this.setType(data.type); } if (load) { this.loadTemplate(); } } }, /** * Sets error type * * @param {Number} type */ setType: function(type) { this.type = type; this.updateLoaderUrl(); }, /** * Initialise loader URL */ updateLoaderUrl: function() { if (this.isUnknown) { this.loader.url = Calc.appFolder + '/template/error/Error.html'; return; } if (this.type) { this.getLoader().url = Calc.appFolder + '/template/error/' + this.type + '.html'; } } });
gpl-3.0
hep-mirrors/rivet
include/Rivet/Tools/RivetMT2.hh
1580
// -*- C++ -*- #ifndef RIVET_MT2_HH #define RIVET_MT2_HH #include "Rivet/Math/Vector4.hh" namespace Rivet { /// @brief Compute asymm mT2**2 using the bisection method /// /// If the second invisible mass is not given, symm mT2**2 will be calculated. /// /// @note Cheng/Han arXiv:0810.5178, Lester arXiv:1411.4312 double mT2Sq(const FourMomentum& a, const FourMomentum& b, const Vector3& ptmiss, double invisiblesMass, double invisiblesMass2=-1); /// Override for mT2Sq with FourMomentum ptmiss inline double mT2Sq(const FourMomentum& a, const FourMomentum& b, const FourMomentum& ptmiss, double invisiblesMass, double invisiblesMass2=-1) { return mT2Sq(a, b, ptmiss.perpVec(), invisiblesMass, invisiblesMass2); } /// @brief Compute asymm mT2 using the bisection method /// /// If the second invisible mass is not given, symm mT2 will be calculated. /// /// @note Cheng/Han arXiv:0810.5178, Lester arXiv:1411.4312 inline double mT2(const FourMomentum& a, const FourMomentum& b, const Vector3& ptmiss, double invisiblesMass, double invisiblesMass2=-1) { const double mt2sq = mT2Sq(a, b, ptmiss, invisiblesMass, invisiblesMass2); return mt2sq >= 0 ? sqrt(mt2sq) : -1; } /// Override for mT2 with FourMomentum ptmiss inline double mT2(const FourMomentum& a, const FourMomentum& b, const FourMomentum& ptmiss, double invisiblesMass, double invisiblesMass2=-1) { return mT2(a, b, ptmiss.perpVec(), invisiblesMass, invisiblesMass2); } } #endif
gpl-3.0
basilfx/BierApp-Android
app/src/main/java/com/basilfx/bierapp/exceptions/UnexpectedStatusCode.java
475
package com.basilfx.bierapp.exceptions; import org.apache.http.HttpException; public class UnexpectedStatusCode extends HttpException{ /** * */ private static final long serialVersionUID = -2261400615322872338L; public UnexpectedStatusCode(int statusCode) { super("Unexpected HTTP status code " + statusCode); } public UnexpectedStatusCode(int statusCode, int expected) { super("Unexpected HTTP status code " + statusCode + ". Expected " + expected); } }
gpl-3.0
richard-roberts/Mocappie
src/scene/coordinates/joint.py
92
from src.scene.coordinates.coordinate import Coordinate class Joint(Coordinate): pass
gpl-3.0
erudit/eruditorg
tests/functional/apps/public/account_actions/test_forms.py
4065
# -*- coding: utf-8 -*- from account_actions.action_base import AccountActionBase from account_actions.action_pool import actions from account_actions.test.factories import AccountActionTokenFactory from django.contrib.auth.models import User from django.test import TestCase from faker import Factory from apps.public.account_actions.forms import AccountActionRegisterForm faker = Factory.create() consumed = False class TestAction(AccountActionBase): name = "test-consumed" def execute(self, method): global consumed consumed = True # noqa class TestAccountActionRegisterForm(TestCase): def tearDown(self): super(TestAccountActionRegisterForm, self).tearDown() actions._registry.pop("test-consumed", None) def test_can_initialize_the_email_address_using_the_token(self): # Setup token = AccountActionTokenFactory.create(email="test@example.com") # Run form = AccountActionRegisterForm(token=token) # Check self.assertEqual(form.fields["email"].initial, "test@example.com") def test_can_initialize_the_first_name_using_the_token(self): # Setup token = AccountActionTokenFactory.create(first_name="foo") # Run form = AccountActionRegisterForm(token=token) # Check self.assertEqual(form.fields["first_name"].initial, "foo") def test_can_initialize_the_last_name_using_the_token(self): # Setup token = AccountActionTokenFactory.create(last_name="bar") # Run form = AccountActionRegisterForm(token=token) # Check self.assertEqual(form.fields["last_name"].initial, "bar") def test_cannot_be_validated_if_a_user_with_the_same_email_address_already_exists(self): # Setup User.objects.create_user( username="test@example.com", password="not_secret", email="test@exampe.com" ) token = AccountActionTokenFactory.create(email="test@exampe.com") form_data = { "username": faker.simple_profile().get("mail"), "email": "test@exampe.com", "first_name": faker.first_name(), "last_name": faker.last_name(), "password1": "not_secret", "password2": "not_secret", } # Run form = AccountActionRegisterForm(form_data, token=token) # Check self.assertFalse(form.is_valid()) self.assertTrue("email" in form.errors) def test_can_properly_create_a_user(self): # Setup token = AccountActionTokenFactory.create() form_data = { "username": faker.simple_profile().get("mail"), "email": faker.email(), "first_name": faker.first_name(), "last_name": faker.last_name(), "password1": "not_secret", "password2": "not_secret", } # Run & check form = AccountActionRegisterForm(form_data, token=token) self.assertTrue(form.is_valid()) form.save() user = User.objects.first() self.assertEqual(user.username, form_data["email"]) self.assertEqual(user.email, form_data["email"]) self.assertEqual(user.first_name, form_data["first_name"]) self.assertEqual(user.last_name, form_data["last_name"]) self.assertTrue(user.check_password("not_secret")) def test_can_properly_consume_the_token(self): # Setup actions.register(TestAction) token = AccountActionTokenFactory.create(action="test-consumed") form_data = { "username": faker.simple_profile().get("mail"), "email": faker.email(), "first_name": faker.first_name(), "last_name": faker.last_name(), "password1": "not_secret", "password2": "not_secret", } # Run & check form = AccountActionRegisterForm(form_data, token=token) self.assertTrue(form.is_valid()) form.save() global consumed self.assertTrue(consumed)
gpl-3.0
open-notify/Open-Notify-API
update.py
1994
import redis import json import urllib2 import datetime from calendar import timegm import time import os import sys REDIS_URL = os.getenv('REDISTOGO_URL', 'redis://localhost:6379') r = redis.StrictRedis.from_url(REDIS_URL) # NASA's station FDO updates this page with very precise data. Only using a # small bit of it for now. url = "http://spaceflight.nasa.gov/realdata/sightings/SSapplications/Post/JavaSSOP/orbit/ISS/SVPOST.html" def update_tle(): # Open a http request req = urllib2.Request(url) response = urllib2.urlopen(req) data = response.read() # parse the HTML data = data.split("<PRE>")[1] data = data.split("</PRE>")[0] data = data.split("Vector Time (GMT): ")[1:] for group in data: # Time the vector is valid for datestr = group[0:17] # parse date string tm = time.strptime(datestr, "%Y/%j/%H:%M:%S") # change into more useful datetime object dt = datetime.datetime(tm[0], tm[1], tm[2], tm[3], tm[4], tm[5]) # Debug #print dt # More parsing tle = group.split("TWO LINE MEAN ELEMENT SET")[1] tle = tle[8:160] lines = tle.split('\n')[0:3] # Most recent TLE now = datetime.datetime.utcnow() if (dt - now).days >= 0: # Debug Printing """ print dt for line in lines: print line.strip() print "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" """ tle = json.dumps([lines[0].strip(), lines[1].strip(), lines[2].strip()]) r.set("iss_tle", tle) r.set("iss_tle_time", timegm(dt.timetuple())) r.set("iss_tle_last_update", timegm(now.timetuple())) break if __name__ == '__main__': print "Updating ISS TLE from JSC..." try: update_tle() except: exctype, value = sys.exc_info()[:2] print "Error:", exctype, value
gpl-3.0
401AR/W17401AR
Assets/Scripts/UI/ListItem.cs
2173
/****************************************************************************** * Author: Michael Morris * Course: CMPUT401 AR * File: SkinToneItem.cs * * Description: Provides access to dynamic item controls for slot items. * * ***************************************************************************/ using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; public class ListItem : MonoBehaviour { public Image Preview; public Text Name; public Toggle Entry; private SyncListFinding data; // Set list item data from SyncListFinding public void setData(SyncListFinding data) { Name.text = data.name; this.data = data; // Processing differs based on texture / color loading. if (data.texturePath != "0") { Preview.sprite = Resources.Load<Sprite>(data.texturePath); } else { Preview.color = data.getColor(); } // Keep logging specific (not agnostic). if (data.texturePath != "0") { Debug.Log("Added finding: Name: " + data.name + " Texture: " + data.texturePath); } else { Debug.Log("Added finding: Name: " + data.name + " Color: " + data.colorJson); } } // Highlight this button public void select() { Entry.isOn = true; } // Remove highlight on this button. public void deselect() { Entry.isOn = false; } // Use this for initialization void Start() { Toggle btn = Entry.GetComponent<Toggle>(); btn.onValueChanged.AddListener((value) => { TaskOnValueChanged(value); } ); } // On click event handler public void TaskOnValueChanged(bool newState) { if (newState == true) { FindingClickHandler.Instance.setCurrentFinding(this.data); Entry.isOn = !Entry.isOn; //parentList.highlight(data.id); Debug.Log("You clicked me!"); } } // Clear selection before destroying. private void OnDestroy() { deselect(); } }
gpl-3.0
billrive/billrive
billrive-app/src/main/java/com/uhsarp/billrive/services/PaymentService.java
666
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.uhsarp.billrive.services; //import com.uhsarp.billrive.dao.GenericDao; import com.uhsarp.billrive.domain.Payment; import javax.annotation.Resource; import org.springframework.stereotype.Service; /** * * @author Sravan */ @Service("PaymentService") public class PaymentService { // @Resource(name= "neo4jDAO") // GenericDao genericDAO; public Payment createPayment(int userId, Payment paymentObj) { Payment payment = null; // payment=genericDAO.createPayment(userId, paymentObj); return payment; } }
gpl-3.0
alephcero/adsProject
make_dummy.py
533
def make_dummy(data): data['male_14to24'] = ((data.female == 0) & ((data.age >= 14) & (data.age <= 24))).astype(int) data['male_25to34'] = ((data.female == 0) & ((data.age >= 25 ) & ( data.age <= 34))).astype(int) data['female_14to24'] = ((data.female == 1) & ((data.age >= 14 ) & ( data.age <= 24))).astype(int) data['female_25to34'] = ((data.female == 1) & ((data.age >= 25 ) & ( data.age <= 34))).astype(int) data['female_35more'] = ((data.female == 1) & ((data.age >= 35 ))).astype(int) return data
gpl-3.0
diphda/grupoagrupo
lib/filter/doctrine/ConsumerGroupStateFormFilter.class.php
355
<?php /** * ConsumerGroupState filter form. * * @package grupos_consumo * @subpackage filter * @author Your name here * @version SVN: $Id: sfDoctrineFormFilterTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $ */ class ConsumerGroupStateFormFilter extends BaseConsumerGroupStateFormFilter { public function configure() { } }
gpl-3.0
Webdeskme/Webdesk-me
Apps/Admin/uploadCSV.php
3893
<?php $i = 0; $tier = test_input($_POST['tier']); $pass = f_enc(test_input($_POST['pass'])); if(!file_exists('Temp/')){ mkdir('Temp/'); } $target_dir = "Temp/"; $target_file = $target_dir . 'temp.csv'; $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); // Allow certain file formats if($imageFileType != "csv") { echo "Sorry, only csv files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.<br>"; } else { echo "Sorry, there was an error uploading your file."; } } $file = fopen($target_file,"r"); while(! feof($file)) { //print_r(fgetcsv($file)); $user[$i] = fgetcsv($file); $i = $i + 1; } fclose($file); unlink($target_file); $z = 1; while($z < $i){ //echo $z . ': ' . $user[$z][2] . '<br>'; $user[$z][2] = f_enc(strtolower($user[$z][2])); if(!file_exists($wd_root . '/User/' . $user[$z][2] . '/')){ mkdir($wd_root . '/User/' . $user[$z][2] . '/'); mkdir($wd_root . '/User/' . $user[$z][2] . '/Admin/'); mkdir($wd_root . '/User/' . $user[$z][2] . '/Sec/'); mkdir($wd_root . '/User/' . $user[$z][2] . '/Doc/'); mkdir($wd_root . '/User/' . $user[$z][2] . '/Web/'); mkdir($wd_root . '/User/' . $user[$z][2] . '/App/'); mkdir($wd_root . '/User/' . $user[$z][2] . '/Book/'); mkdir($wd_root . '/User/' . $user[$z][2] . '/Ext/'); $rand = file_get_contents($wd_root . '/User/' . $_SESSION['user'] . '/Admin/oid.txt'); $vrand = rand(10000000000000000000, 99999999999999999999); $vrand = $vrand . 'abcdefghijklmnopqrstuvwxyz'; $vrand = str_shuffle($vrand); //$vrand = file_get_contents($wd_root . 'User/' . $_SESSION['user'] . '/Admin/val.txt'); //$url = file_get_contents($wd_root . 'User/' . $_SESSION['user'] . '/Admin/url.txt'); file_put_contents($wd_root . '/User/' . $user[$z][2] .'/Admin/pass.txt', $pass); file_put_contents($wd_root . '/User/' . $user[$z][2] .'/Admin/oid.txt', $rand); file_put_contents($wd_root . '/User/' . $user[$z][2] .'/Admin/val.txt', $vrand); file_put_contents($wd_root . '/User/' . $user[$z][2] .'/Admin/back.txt', 'back.jpg'); file_put_contents($wd_root . '/User/' . $user[$z][2] .'/Admin/tier.txt', $tier); file_put_contents($wd_root . '/User/' . $user[$z][2] .'/Admin/color.txt', '#ffffff'); file_put_contents($wd_root . '/User/' . $user[$z][2] .'/Admin/Pcolor.txt', '#ffffff'); //file_put_contents($wd_root . '/User/' . $user[$z][2] .'/Admin/url.txt', $url); if(file_exists($wd_root . '/User/' . $user[$z][2] . '/Admin/info.json')){ //$obj = file_get_contents($wd_root . 'User/' . $user[$z][2] . '/Admin/info.json'); $obj = file_get_contents($wd_root . '/User/' . $user[$z][2] . '/Admin/info.json'); $obj = json_decode($obj); } else{ $obj = new stdClass; } $obj->fn = $user[$z][0]; $obj->ln = $user[$z][1]; $obj->email = $user[$z][3]; $obj->contact = $user[$z][4]; $nObj = json_encode($obj); file_put_contents($wd_root . '/User/' . $user[$z][2] . '/Admin/info.json', $nObj); } $z = $z + 1; } wd_head($wd_type, $wd_app, 'ManageUsers.php', ''); ?>
gpl-3.0
DRE2N/DungeonsXL
core/src/main/java/de/erethon/dungeonsxl/DXLModule.java
4700
/* * Copyright (C) 2012-2022 Frank Baumann * * 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 de.erethon.dungeonsxl; import de.erethon.dungeonsxl.api.DungeonModule; import de.erethon.dungeonsxl.api.Requirement; import de.erethon.dungeonsxl.api.Reward; import de.erethon.dungeonsxl.api.dungeon.GameRule; import de.erethon.dungeonsxl.api.sign.DungeonSign; import de.erethon.dungeonsxl.requirement.*; import de.erethon.dungeonsxl.reward.*; import de.erethon.dungeonsxl.sign.button.*; import de.erethon.dungeonsxl.sign.passive.*; import de.erethon.dungeonsxl.sign.rocker.*; import de.erethon.dungeonsxl.sign.windup.*; import de.erethon.dungeonsxl.util.commons.misc.Registry; /** * @author Daniel Saukel */ public class DXLModule implements DungeonModule { @Override public void initRequirements(Registry<String, Class<? extends Requirement>> requirementRegistry) { requirementRegistry.add("feeLevel", FeeLevelRequirement.class); requirementRegistry.add("feeMoney", FeeMoneyRequirement.class); requirementRegistry.add("finishedDungeons", FinishedDungeonsRequirement.class); requirementRegistry.add("forbiddenItems", ForbiddenItemsRequirement.class); requirementRegistry.add("groupSize", GroupSizeRequirement.class); requirementRegistry.add("keyItems", KeyItemsRequirement.class); requirementRegistry.add("permission", PermissionRequirement.class); requirementRegistry.add("timeSinceFinish", TimeSinceFinishRequirement.class); requirementRegistry.add("timeSinceStart", TimeSinceStartRequirement.class); requirementRegistry.add("timeframe", TimeframeRequirement.class); } @Override public void initRewards(Registry<String, Class<? extends Reward>> rewardRegistry) { rewardRegistry.add("item", ItemReward.class); rewardRegistry.add("money", MoneyReward.class); rewardRegistry.add("level", LevelReward.class); } @Override public void initSigns(Registry<String, Class<? extends DungeonSign>> signRegistry) { signRegistry.add("ACTIONBAR", ActionBarSign.class); signRegistry.add("BED", BedSign.class); signRegistry.add("BLOCK", BlockSign.class); signRegistry.add("BOSSSHOP", BossShopSign.class); signRegistry.add("CHECKPOINT", CheckpointSign.class); signRegistry.add("CLASSES", ClassesSign.class); signRegistry.add("CMD", CommandSign.class); signRegistry.add("DROP", DropSign.class); signRegistry.add("DUNGEONCHEST", DungeonChestSign.class); signRegistry.add("END", EndSign.class); signRegistry.add("FLAG", FlagSign.class); signRegistry.add("HOLOGRAM", HologramSign.class); signRegistry.add("INTERACT", InteractSign.class); signRegistry.add("LEAVE", LeaveSign.class); signRegistry.add("LIVES", LivesModifierSign.class); signRegistry.add("LOBBY", LobbySign.class); signRegistry.add("MOB", MobSign.class); signRegistry.add("MSG", ChatMessageSign.class); signRegistry.add("NOTE", NoteSign.class); signRegistry.add("DOOR", OpenDoorSign.class); signRegistry.add("PLACE", PlaceSign.class); signRegistry.add("PROTECTION", ProtectionSign.class); signRegistry.add("READY", ReadySign.class); signRegistry.add("REDSTONE", RedstoneSign.class); signRegistry.add("RESOURCEPACK", ResourcePackSign.class); signRegistry.add("REWARDCHEST", RewardChestSign.class); signRegistry.add("SCRIPT", ScriptSign.class); signRegistry.add("SOUNDMSG", SoundMessageSign.class); signRegistry.add("START", StartSign.class); signRegistry.add("TELEPORT", TeleportSign.class); signRegistry.add("TITLE", TitleSign.class); signRegistry.add("TRIGGER", TriggerSign.class); signRegistry.add("WAVE", WaveSign.class); } @Override public void initGameRules(Registry<String, GameRule> gameRuleRegistry) { for (GameRule rule : GameRule.VALUES) { gameRuleRegistry.add(rule.getKey(), rule); } } }
gpl-3.0
NyxStudios/Orion
src/Orion.Core/Packets/Players/PlayerPvp.cs
1870
// Copyright (c) 2020 Pryaxis & Orion Contributors // // This file is part of Orion. // // Orion 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. // // Orion 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 Orion. If not, see <https://www.gnu.org/licenses/>. using System; using System.Runtime.InteropServices; using Orion.Core.Utils; namespace Orion.Core.Packets.Players { /// <summary> /// A packet sent to set a player's PvP status. /// </summary> [StructLayout(LayoutKind.Explicit, Size = 2)] public struct PlayerPvp : IPacket { [FieldOffset(0)] private byte _bytes; // Used to obtain an interior reference. /// <summary> /// Gets or sets the player index. /// </summary> /// <value>The player index.</value> [field: FieldOffset(0)] public byte PlayerIndex { get; set; } /// <summary> /// Gets or sets a value indicating whether the player is in PvP. /// </summary> /// <value><see langword="true"/> if the player is in PvP; otherwise, <see langword="false"/>.</value> [field: FieldOffset(1)] public bool IsInPvp { get; set; } PacketId IPacket.Id => PacketId.PlayerPvp; int IPacket.ReadBody(Span<byte> span, PacketContext context) => span.Read(ref _bytes, 2); int IPacket.WriteBody(Span<byte> span, PacketContext context) => span.Write(ref _bytes, 2); } }
gpl-3.0
d0m3nik/pycimg
docs/conf.py
5544
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # pycimg documentation build configuration file, created by # sphinx-quickstart on Tue Dec 12 11:21:29 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath('../')) from unittest.mock import MagicMock class Mock(MagicMock): @classmethod def __getattr__(cls, name): return MagicMock() MOCK_MODULES = ['numpy', 'pycimg.cimg_bindings'] sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon', 'sphinx.ext.githubpages'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_parsers = { '.md': 'recommonmark.parser.CommonMarkParser' } source_suffix = ['.rst', '.md'] #source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = 'pycimg' copyright = '2020, Dominik Brugger' author = 'Dominik Brugger' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.0.0' # The full version, including alpha/beta/rc tags. release = '1.0.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # # html_theme = 'alabaster' html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # This is required for the alabaster theme # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars html_sidebars = { '**': [ 'relations.html', # needs 'show_related': True theme option to display 'searchbox.html', ] } # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'pycimgdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'pycimg.tex', 'pycimg Documentation', 'Dominik Brugger', 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'pycimg', 'pycimg Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'pycimg', 'pycimg Documentation', author, 'pycimg', 'One line description of project.', 'Miscellaneous'), ]
gpl-3.0
malalanayake/design-patterns
src/main/java/sample/design/Interface/segregation/bad/Human.java
504
package sample.design.Interface.segregation.bad; /** * * Distibution under GNU GENERAL PUBLIC LICENSE Version 2, June 1991 * * @author dmalalan * @created Apr 12, 2016 1:25:34 PM * * @blog https://malalanayake.wordpress.com/ */ public class Human implements Worker { public void startWork() { System.out.println("[START:Working Human]"); } public void stopWork() { System.out.println("[STOP:Working Human]"); } public void eat() { System.out.println("[EAT:Lunch Human]"); } }
gpl-3.0
phiratio/Pluralsight-materials
Paths/HTML5/04.Meeting-Web-Accessibility-Guidelines/2-web-accessibility-meeting-guidelines-m2-exercise-files/Acme/js/navigation.js
168
var menu = document.querySelector('#main-nav'); document.querySelector('#menu-trigger').addEventListener('click', function (e) { menu.classList.toggle('active'); });
gpl-3.0
wuts/xiaodoudian
application/modules/galleries/language/english/galleries_lang.php
3549
<?php // labels $lang['gal_upload_label'] = 'Upload'; $lang['gal_page_content_label'] = 'Page content'; $lang['gal_photo_label'] = 'Photo'; $lang['gal_photo_title_label'] = 'Title'; $lang['gal_photo_description_label'] = 'Description'; $lang['gal_photos_list_label'] = 'Photos List'; $lang['gal_photo_show_in_homepage_label'] = 'Show In Homepage'; $lang['gal_photo_publish_label'] = 'Publish'; $lang['gal_photo_posted_label_alt_label'] = 'Posted Date'; $lang['gal_photo_yes_label'] = 'Yes'; $lang['gal_photo_no_label'] = 'No'; $lang['gal_edit_photo_label'] = 'Edit A Photo'; $lang['gal_desc_label'] = 'Description'; $lang['gal_required_label'] = 'Required'; $lang['gal_album_label'] = 'Album'; $lang['gal_number_of_photo_label'] = 'Number of photos'; $lang['gal_updated_label'] = 'Updated'; $lang['gal_actions_label'] = 'Actions'; $lang['gal_view_label'] = 'View'; $lang['gal_manage_label'] = 'Manage'; $lang['gal_edit_label'] = 'Edit'; $lang['gal_delete_label'] = 'Delete'; $lang['gal_title_label'] = 'Title'; $lang['gal_parent_gallery_label'] = 'Parent gallery'; $lang['gal_no_parent_select_label'] = '-- None --'; $lang['gal_other_comments_label'] = 'They said...'; $lang['gal_your_comments_label'] = 'You say...?'; $lang['gal_catagories_label'] = 'Gallery Catagories'; $lang['gal_more_label'] = 'More...'; // titles $lang['gal_manage_title'] = 'Photos in this Gallery'; $lang['gal_add_photo_title'] = 'Add a Photo'; $lang['gal_edit_photo_title'] = 'Edit a Photo'; $lang['gal_create_title'] = 'Create gallery'; $lang['gal_edit_title'] = 'Edit gallery "%s"'; $lang['gal_comments_title'] = 'Comments'; $lang['gal_photo_galleries_title'] = 'Photo Galleries'; // messages $lang['gal_no_galleries_error'] = 'There are no galleries.'; $lang['gal_no_photos_in_gallery_error'] = 'There are no photos in this gallery.'; $lang['gal_currently_no_photos_error'] = 'There are no photos at the moment. Please come back another time.'; $lang['gal_already_exist_error'] = 'The gallery you tried to view, does not exist.'; $lang['gal_add_success'] = 'The gallery "%s" was saved.'; $lang['gal_add_error'] = 'An error occurred.'; $lang['gal_edit_success'] = 'The gallery "%s" was saved.'; $lang['gal_edit_error'] = 'An error occurred.'; $lang['gal_delete_no_select_error'] = 'You need to select one or more galleries to delete.'; $lang['gal_delete_error'] = 'Error occurred while trying to delete gallery %s'; $lang['gal_delete_dir_error'] = 'Unable to delete directory "%s"'; $lang['gal_mass_delete_success'] = '%s galleries out of %s successfully deleted.'; $lang['gal_upload_success'] = 'Image "%s" uploaded successfully.'; $lang['gal_upload_error'] = 'An error occurred uploading the image "%s".'; $lang['gal_photo_delete_no_select_error'] = 'You need to select one or more photos to delete.'; $lang['gal_photo_delete_success'] = 'Deleted %s image(s) successfully.'; $lang['gal_photo_delete_error'] = 'No images were deleted.'; $lang['gal_name_already_exist_error'] = 'A gallery with this name already exists.'; $lang['gal_photo_update_success'] = 'Update photo successfully.'; $lang['gal_photo_update_error'] = 'An error occurred.'; ?>
gpl-3.0
dansteen/controlled-compose
logger/tail_logger.go
1409
// TailLogger is an implementation of logger that will tail provide a log stream // as well as, optionally, print logs to the console package logger import ( cli_logger "github.com/docker/libcompose/cli/logger" "github.com/docker/libcompose/logger" ) // TailLoggerFactory Implements the logger.Factory interface for TailLogger type TailLoggerFactory struct { loggerFactory logger.Factory } // TailLogger implements logger.Logger interface with output to a stream type TailLogger struct { loggerLogger logger.Logger name string factory *TailLoggerFactory } // Create implements logger.Factory.Create. func (c *TailLoggerFactory) Create(name string) logger.Logger { c.loggerFactory = cli_logger.NewColorLoggerFactory() colorLogger := c.loggerFactory.Create(name) return &TailLogger{ loggerLogger: colorLogger, name: name, factory: c, } } // Out implements logger.Logger.Out. func (c *TailLogger) Out(bytes []byte) { c.loggerLogger.Out(bytes) } // Err implements logger.Logger.Err. func (c *TailLogger) Err(bytes []byte) { c.loggerLogger.Err(bytes) } // StreamOut will return an ioReader to StdOut back to the caller which can // be streamed from. func (c *TailLogger) OutLines(bytes []byte) *Line { } // StreamErr will return an ioReader to StdErr object back to the caller which can // be streamed from. func (c *TailLogger) ErrLines(bytes []byte) *Line { }
gpl-3.0
yaha-soft/yaha
src/Yaha/UserBundle/UserBundle.php
120
<?php namespace Yaha\UserBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class UserBundle extends Bundle { }
gpl-3.0
Sendarox/HiveJumpPads
older_versions/v2_X/eu/Sendarox/HiveJumpPads/Listener/JumpPadListener.java
8611
/* */ package eu.Sendarox.HiveJumpPads.Listener; /* */ /* */ import eu.Sendarox.HiveJumpPads.HiveJumpPads; /* */ import eu.Sendarox.HiveJumpPads.TransanslateAlternateColors; /* */ import java.io.File; /* */ import java.util.HashMap; /* */ import java.util.List; /* */ import org.bukkit.Bukkit; /* */ import org.bukkit.Location; /* */ import org.bukkit.Sound; /* */ import org.bukkit.World; /* */ import org.bukkit.block.Block; /* */ import org.bukkit.configuration.file.FileConfiguration; /* */ import org.bukkit.entity.Player; /* */ import org.bukkit.event.player.PlayerMoveEvent; /* */ import org.bukkit.util.Vector; /* */ /* */ public class JumpPadListener implements org.bukkit.event.Listener /* */ { /* */ private HiveJumpPads hjp; /* */ /* */ public JumpPadListener(HiveJumpPads hjp) /* */ { /* 24 */ this.hjp = hjp; /* */ } /* */ /* */ /* */ @org.bukkit.event.EventHandler /* */ private void onJump(PlayerMoveEvent e) /* */ { /* 31 */ File file = new File("plugins/Hive JumpPads/JumpPads/", "JumpPad-Config.yml"); /* 32 */ FileConfiguration cfg = org.bukkit.configuration.file.YamlConfiguration.loadConfiguration(file); /* */ /* 34 */ File f = new File("plugins/Hive JumpPads/", "config.yml"); /* 35 */ FileConfiguration cfg1 = org.bukkit.configuration.file.YamlConfiguration.loadConfiguration(f); /* 36 */ this.hjp.getDataFolder(); /* 37 */ Player p = e.getPlayer(); /* */ /* 39 */ World location = p.getWorld(); /* 40 */ Location playerLoc = p.getLocation(); /* 41 */ if (cfg.getBoolean("HiveJumpPads.JumpPad.Enable JumpPads") == Boolean.FALSE.booleanValue()) { /* 42 */ return; /* */ } /* 44 */ if (cfg1.getStringList("HiveJumpPads.Disabed_Worlds_for_both_JumpPads").contains(location.getName())) { /* 45 */ return; /* */ } /* 47 */ if (cfg.getStringList("HiveJumpPads.JumpPads.DisabledWorlds").contains(location.getName())) { /* 48 */ return; /* */ } /* */ /* 51 */ if (cfg.getBoolean("HiveJumpPads.JumpPad.3x3 Field") == Boolean.FALSE.booleanValue()) { /* 52 */ int PressurePlate_ID = playerLoc.getWorld().getBlockAt(playerLoc).getRelative(0, 0, 0).getTypeId(); /* 53 */ int ID = playerLoc.getWorld().getBlockAt(playerLoc).getRelative(0, -1, 0).getTypeId(); /* 54 */ if ((p.hasPermission("HiveJumpPads.use.JumpPad")) && /* 55 */ (PressurePlate_ID == cfg.getInt("HiveJumpPads.JumpPad.PressurePlateID")) && (ID == cfg.getInt("HiveJumpPads.JumpPad.BlockID"))) { /* 56 */ Long time = Long.valueOf(System.currentTimeMillis()); /* 57 */ if (HiveJumpPads.cooldown.containsKey(p.getName())) { /* 58 */ Long lastUsage = (Long)HiveJumpPads.cooldown.get(p.getName()); /* 59 */ if (lastUsage.longValue() + 1000L > time.longValue()) { /* 60 */ return; /* */ } /* */ } /* 63 */ double Height = cfg.getDouble("HiveJumpPads.Lenght & Height.JumpHeight"); /* 64 */ double Width = cfg.getDouble("HiveJumpPads.Lenght & Height.JumpLenght"); /* */ /* 66 */ double BlockHeight = Height / 19.5D; /* 67 */ double BlockWidth = Width / 5.0D; /* 68 */ p.setVelocity(p.getLocation().getDirection().setY(BlockHeight).multiply(BlockWidth)); /* */ /* 70 */ if (cfg.getBoolean("HiveJumpPads.Sound & Effects.Enable Sounds") == Boolean.TRUE.booleanValue()) { /* 71 */ p.playSound(p.getLocation(), Sound.valueOf(cfg.getString("HiveJumpPads.Sound & Effects.Sound").toUpperCase()), 100.0F, 100.0F); /* */ } /* */ /* 74 */ if (cfg.getBoolean("HiveJumpPads.Sound & Effects.Enable Effects") != Boolean.FALSE.booleanValue()) { /* 75 */ for (Player all : Bukkit.getOnlinePlayers()) { /* 76 */ all.playEffect(p.getLocation(), org.bukkit.Effect.valueOf(cfg.getString("HiveJumpPads.Sound & Effects.Effect").toUpperCase()), 4); /* */ } /* */ } /* */ /* 80 */ if (cfg.getBoolean("HiveJumpPads.Sound & Effects.Enable message") == Boolean.TRUE.booleanValue()) { /* 81 */ p.sendMessage(TransanslateAlternateColors.colMsg(cfg.getString("HiveJumpPads.Sound & Effects.message"))); /* */ } /* */ /* */ /* 85 */ HiveJumpPads.Jumped.put(p.getName(), Boolean.valueOf(true)); /* 86 */ HiveJumpPads.cooldown.put(p.getName(), time); /* */ } /* */ } /* 89 */ else if ((cfg.getBoolean("HiveJumpPads.JumpPad.3x3 Field") == Boolean.TRUE.booleanValue()) && /* 90 */ (p.hasPermission("HiveJumpPads.use.JumpPad"))) { /* 91 */ int ID = playerLoc.getWorld().getBlockAt(playerLoc).getRelative(0, 0, 0).getTypeId(); /* 92 */ int ID2 = playerLoc.getWorld().getBlockAt(playerLoc).getRelative(0, -1, 0).getTypeId(); /* 93 */ int ID3 = playerLoc.getWorld().getBlockAt(playerLoc).getRelative(1, -1, 0).getTypeId(); /* 94 */ int ID4 = playerLoc.getWorld().getBlockAt(playerLoc).getRelative(-1, -1, 0).getTypeId(); /* 95 */ int ID5 = playerLoc.getWorld().getBlockAt(playerLoc).getRelative(0, -1, 1).getTypeId(); /* 96 */ int ID6 = playerLoc.getWorld().getBlockAt(playerLoc).getRelative(0, -1, -1).getTypeId(); /* 97 */ int ID7 = playerLoc.getWorld().getBlockAt(playerLoc).getRelative(-1, -1, -1).getTypeId(); /* 98 */ int ID8 = playerLoc.getWorld().getBlockAt(playerLoc).getRelative(1, -1, 1).getTypeId(); /* 99 */ if ((ID == cfg.getInt("HiveJumpPads.JumpPad.PressurePlateID")) && /* 100 */ (ID2 == cfg.getInt("HiveJumpPads.JumpPad.BlockID")) && /* 101 */ (ID3 == cfg.getInt("HiveJumpPads.JumpPad.BlockID")) && /* 102 */ (ID4 == cfg.getInt("HiveJumpPads.JumpPad.BlockID")) && /* 103 */ (ID5 == cfg.getInt("HiveJumpPads.JumpPad.BlockID")) && /* 104 */ (ID6 == cfg.getInt("HiveJumpPads.JumpPad.BlockID")) && /* 105 */ (ID7 == cfg.getInt("HiveJumpPads.JumpPad.BlockID")) && /* 106 */ (ID8 == cfg.getInt("HiveJumpPads.JumpPad.BlockID"))) { /* 107 */ Long time = Long.valueOf(System.currentTimeMillis()); /* 108 */ if (HiveJumpPads.cooldown.containsKey(p.getName())) { /* 109 */ Long lastUsage = (Long)HiveJumpPads.cooldown.get(p.getName()); /* 110 */ if (lastUsage.longValue() + 1000L > time.longValue()) { /* 111 */ return; /* */ } /* */ } /* 114 */ double Height = cfg.getDouble("HiveJumpPads.Lenght & Height.JumpHeight"); /* 115 */ double Width = cfg.getDouble("HiveJumpPads.Lenght & Height.JumpLenght"); /* */ /* 117 */ double BlockHeight = Height / 19.5D; /* 118 */ double BlockWidth = Width / 5.0D; /* 119 */ p.setVelocity(p.getLocation().getDirection().setY(BlockHeight).multiply(BlockWidth)); /* */ /* 121 */ if (cfg.getBoolean("HiveJumpPads.Sound & Effects.Enable Sounds") == Boolean.TRUE.booleanValue()) { /* 122 */ p.playSound(p.getLocation(), Sound.valueOf(cfg.getString("HiveJumpPads.Sound & Effects.Sound").toUpperCase()), 100.0F, 100.0F); /* */ } /* */ /* 125 */ if (cfg.getBoolean("HiveJumpPads.Sound & Effects.Enable Effects") == Boolean.TRUE.booleanValue()) { /* 126 */ for (Player all : Bukkit.getOnlinePlayers()) { /* 127 */ all.playEffect(p.getLocation(), org.bukkit.Effect.valueOf(cfg.getString("HiveJumpPads.Sound & Effects.Effect").toUpperCase()), 4); /* */ } /* */ } /* */ /* 131 */ if (cfg.getBoolean("HiveJumpPads.Sound & Effects.Enable message") == Boolean.TRUE.booleanValue()) { /* 132 */ p.sendMessage(TransanslateAlternateColors.colMsg(cfg.getString("HiveJumpPads.Sound & Effects.message"))); /* */ } /* */ /* 135 */ HiveJumpPads.Jumped.put(p.getName(), Boolean.valueOf(true)); /* 136 */ HiveJumpPads.cooldown.put(p.getName(), time); /* */ } /* */ } /* */ } /* */ } /* Location: M:\BENUTZER\Downloads\Hive_JumpPads_v.2.16.jar!\eu\Sendarox\HiveJumpPads\Listener\JumpPadListener.class * Java compiler version: 7 (51.0) * JD-Core Version: 0.7.1 */
gpl-3.0
grnydawn/fasin
fasin/utils.py
1454
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import os, sys, time, datetime here = os.path.dirname(os.path.realpath(__file__)) fixedform_extensions = ['.f', '.for', '.fpp', '.ftn', '.F', '.FOR', '.FPP', '.FTN'] freeform_extensions = ['.f90', '.f95', '.f03', '.f08', '.F90', '.F95', '.F03', '.F08'] SMAPSTR = '@S%d@' CMAPSTR = '@C%d@' FMAPSTR = '@F%d@' def R2C(rulename): splitted = [r if r else '_' for r in rulename.split('_')] replaced = [c[0].upper()+c[1:] for c in splitted] return ''.join(replaced) def N2R(obj): clsname = obj.__class__.__name__ rulename = ''.join(['_'+c.lower() if c.isupper() else c for c in clsname]) return rulename[1:] if rulename[0] == '_' else rulename def to_bytes(s, encoding='utf-8'): try: return s.encode(encoding) except: return s def to_unicodes(s, encoding=None): try: if encoding is None: encoding = sys.stdin.encoding return s.decode(encoding) except: return s def datetimestr(): ts = time.time() utc = datetime.datetime.utcfromtimestamp(ts) now = datetime.datetime.fromtimestamp(ts) tzdiff = now - utc secdiff = int(tzdiff.days*24*3600 + tzdiff.seconds) tzstr = '{0}{1}'.format('+' if secdiff>=0 else '-', time.strftime('%H:%M:%S', time.gmtime(abs(secdiff)))) return '{0} {1}'.format(str(now), tzstr)
gpl-3.0
infphilo/hisat2
hisat2_inspect.cpp
28374
/* * Copyright 2015, Daehwan Kim <infphilo@gmail.com> * * This file is part of HISAT 2. * * HISAT 2 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. * * HISAT 2 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 HISAT 2. If not, see <http://www.gnu.org/licenses/>. */ #include <string> #include <iostream> #include <getopt.h> #include <stdexcept> #include "assert_helpers.h" #include "endian_swap.h" #include "hgfm.h" #include "reference.h" #include "ds.h" #include "alt.h" using namespace std; MemoryTally gMemTally; static bool showVersion = false; // just print version and quit? int verbose = 0; // be talkative static int names_only = 0; // just print the sequence names in the index static int snp_only = 0; static int splicesite_only = 0; static int splicesite_all_only = 0; static int exon_only = 0; static int summarize_only = 0; // just print summary of index and quit static int across = 60; // number of characters across in FASTA output static bool refFromGFM = false; // true -> when printing reference, decode it from Gbwt instead of reading it from BitPairReference static string wrapper; static const char *short_options = "vhnsea:"; enum { ARG_VERSION = 256, ARG_WRAPPER, ARG_USAGE, ARG_SNP, ARG_SPLICESITE, ARG_SPLICESITE_ALL, ARG_EXON, }; static struct option long_options[] = { {(char*)"verbose", no_argument, 0, 'v'}, {(char*)"version", no_argument, 0, ARG_VERSION}, {(char*)"usage", no_argument, 0, ARG_USAGE}, {(char*)"names", no_argument, 0, 'n'}, {(char*)"snp", no_argument, 0, ARG_SNP}, {(char*)"ss", no_argument, 0, ARG_SPLICESITE}, {(char*)"ss-all", no_argument, 0, ARG_SPLICESITE_ALL}, {(char*)"exon", no_argument, 0, ARG_EXON}, {(char*)"summary", no_argument, 0, 's'}, {(char*)"help", no_argument, 0, 'h'}, {(char*)"across", required_argument, 0, 'a'}, {(char*)"gbwt-ref", no_argument, 0, 'g'}, {(char*)"wrapper", required_argument, 0, ARG_WRAPPER}, {(char*)0, 0, 0, 0} // terminator }; /** * Print a summary usage message to the provided output stream. */ static void printUsage(ostream& out) { out << "HISAT2 version " << string(HISAT2_VERSION).c_str() << " by Daehwan Kim (infphilo@gmail.com, http://www.ccb.jhu.edu/people/infphilo)" << endl; out << "Usage: hisat2-inspect [options]* <ht2_base>" << endl << " <ht2_base> ht2 filename minus trailing .1." << gfm_ext << "/.2." << gfm_ext << endl << endl << " By default, prints FASTA records of the indexed nucleotide sequences to" << endl << " standard out. With -n, just prints names. With -s, just prints a summary of" << endl << " the index parameters and sequences. With -e, preserves colors if applicable." << endl << endl << "Options:" << endl; if(wrapper == "basic-0") { out << " --large-index force inspection of the 'large' index, even if a" << endl << " 'small' one is present." << endl; } out << " -a/--across <int> Number of characters across in FASTA output (default: 60)" << endl << " -s/--summary Print summary incl. ref names, lengths, index properties" << endl << " -n/--names Print reference sequence names only" << endl << " --snp Print SNPs" << endl << " --ss Print splice sites" << endl << " --ss-all Print splice sites including those not in the global index" << endl << " --exon Print exons" << endl << " -e/--ht2-ref Reconstruct reference from ." << gfm_ext << " (slow, preserves colors)" << endl << " -v/--verbose Verbose output (for debugging)" << endl << " -h/--help print detailed description of tool and its options" << endl << " --usage print this usage message" << endl ; if(wrapper.empty()) { cerr << endl << "*** Warning ***" << endl << "'hisat-inspect' was run directly. It is recommended " << "to use the wrapper script instead." << endl << endl; } } /** * Parse an int out of optarg and enforce that it be at least 'lower'; * if it is less than 'lower', than output the given error message and * exit with an error and a usage message. */ static int parseInt(int lower, const char *errmsg) { long l; char *endPtr= NULL; l = strtol(optarg, &endPtr, 10); if (endPtr != NULL) { if (l < lower) { cerr << errmsg << endl; printUsage(cerr); throw 1; } return (int32_t)l; } cerr << errmsg << endl; printUsage(cerr); throw 1; return -1; } /** * Read command-line arguments */ static void parseOptions(int argc, char **argv) { int option_index = 0; int next_option; do { next_option = getopt_long(argc, argv, short_options, long_options, &option_index); switch (next_option) { case ARG_WRAPPER: wrapper = optarg; break; case ARG_USAGE: case 'h': printUsage(cout); throw 0; break; case 'v': verbose = true; break; case ARG_VERSION: showVersion = true; break; case 'g': refFromGFM = true; break; case 'n': names_only = true; break; case ARG_SNP: snp_only = true; break; case ARG_SPLICESITE: splicesite_only = true; break; case ARG_SPLICESITE_ALL: splicesite_all_only = true; break; case ARG_EXON: exon_only = true; break; case 's': summarize_only = true; break; case 'a': across = parseInt(-1, "-a/--across arg must be at least 1"); break; case -1: break; /* Done with options. */ case 0: if (long_options[option_index].flag != 0) break; default: printUsage(cerr); throw 1; } } while(next_option != -1); } static void print_fasta_record( ostream& fout, const string& defline, const string& seq) { fout << ">"; fout << defline.c_str() << endl; if(across > 0) { size_t i = 0; while (i + across < seq.length()) { fout << seq.substr(i, across).c_str() << endl; i += across; } if (i < seq.length()) fout << seq.substr(i).c_str() << endl; } else { fout << seq.c_str() << endl; } } /** * Given output stream, BitPairReference, reference index, name and * length, print the whole nucleotide reference with the appropriate * number of columns. */ static void print_ref_sequence( ostream& fout, BitPairReference& ref, const string& name, size_t refi, size_t len) { bool newlines = across > 0; int myacross = across > 0 ? across : 60; size_t incr = myacross * 1000; uint32_t *buf = new uint32_t[(incr + 128)/4]; fout << ">" << name.c_str() << "\n"; ASSERT_ONLY(SStringExpandable<uint32_t> destU32); for(size_t i = 0; i < len; i += incr) { size_t amt = min(incr, len-i); assert_leq(amt, incr); int off = ref.getStretch(buf, refi, i, amt ASSERT_ONLY(, destU32)); uint8_t *cb = ((uint8_t*)buf) + off; for(size_t j = 0; j < amt; j++) { if(newlines && j > 0 && (j % myacross) == 0) fout << "\n"; assert_range(0, 4, (int)cb[j]); fout << "ACGTN"[(int)cb[j]]; } fout << "\n"; } delete []buf; } /** * Create a BitPairReference encapsulating the reference portion of the * index at the given basename. Iterate through the reference * sequences, sending each one to print_ref_sequence to print. */ static void print_ref_sequences( ostream& fout, const EList<string>& refnames, const TIndexOffU* plen, const string& adjustedGFMFileBase) { BitPairReference ref( adjustedGFMFileBase, // input basename false, // true -> expect colorspace reference false, // sanity-check reference NULL, // infiles NULL, // originals false, // infiles are sequences false, // memory-map false, // use shared memory false, // sweep mm-mapped ref verbose, // be talkative verbose); // be talkative at startup assert_eq(ref.numRefs(), refnames.size()); for(size_t i = 0; i < ref.numRefs(); i++) { print_ref_sequence( fout, ref, refnames[i], i, plen[i]); } } /** * Given an index, reconstruct the reference by LF mapping through the * entire thing. */ template<typename index_t, typename TStr> static void print_index_sequences(ostream& fout, GFM<index_t>& gfm) { EList<string>* refnames = &(gfm.refnames()); TStr cat_ref; gfm.restore(cat_ref); TIndexOffU curr_ref = OFF_MASK; string curr_ref_seq = ""; TIndexOffU curr_ref_len = OFF_MASK; TIndexOffU last_text_off = 0; size_t orig_len = cat_ref.length(); TIndexOffU tlen = OFF_MASK; bool first = true; for(size_t i = 0; i < orig_len; i++) { TIndexOffU tidx = OFF_MASK; TIndexOffU textoff = OFF_MASK; tlen = OFF_MASK; bool straddled = false; gfm.joinedToTextOff(1 /* qlen */, (TIndexOffU)i, tidx, textoff, tlen, true, straddled); if (tidx != OFF_MASK && textoff < tlen) { if (curr_ref != tidx) { if (curr_ref != OFF_MASK) { // Add trailing gaps, if any exist if(curr_ref_seq.length() < curr_ref_len) { curr_ref_seq += string(curr_ref_len - curr_ref_seq.length(), 'N'); } print_fasta_record(fout, (*refnames)[curr_ref], curr_ref_seq); } curr_ref = tidx; curr_ref_seq = ""; curr_ref_len = tlen; last_text_off = 0; first = true; } TIndexOffU textoff_adj = textoff; if(first && textoff > 0) textoff_adj++; if (textoff_adj - last_text_off > 1) curr_ref_seq += string(textoff_adj - last_text_off - 1, 'N'); curr_ref_seq.push_back("ACGT"[int(cat_ref[i])]); last_text_off = textoff; first = false; } } if (curr_ref < refnames->size()) { // Add trailing gaps, if any exist if(curr_ref_seq.length() < curr_ref_len) { curr_ref_seq += string(curr_ref_len - curr_ref_seq.length(), 'N'); } print_fasta_record(fout, (*refnames)[curr_ref], curr_ref_seq); } } static char *argv0 = NULL; template <typename index_t> static void print_index_sequence_names(const string& fname, ostream& fout) { EList<string> p_refnames; readEbwtRefnames<index_t>(fname, p_refnames); for(size_t i = 0; i < p_refnames.size(); i++) { cout << p_refnames[i].c_str() << endl; } } /** * Print a short summary of what's in the index and its flags. */ template <typename index_t> static void print_snps( const string& fname, ostream& fout) { ALTDB<index_t> altdb; GFM<index_t> gfm( fname, &altdb, -1, // don't require entire reverse true, // index is for the forward direction -1, // offrate (-1 = index default) 0, // offrate-plus (0 = index default) false, // use memory-mapped IO false, // use shared memory false, // sweep memory-mapped memory true, // load names? false, // load SA sample? false, // load ftab? false, // load rstarts? true, // load splice sites? verbose, // be talkative? verbose, // be talkative at startup? false, // pass up memory exceptions? false, // sanity check? false); // use haplotypes? gfm.loadIntoMemory( -1, // need entire reverse true, // load SA sample true, // load ftab true, // load rstarts true, // load names verbose); // verbose EList<string> p_refnames; readEbwtRefnames<index_t>(fname, p_refnames); const EList<ALT<index_t> >& alts = altdb.alts(); const EList<string>& altnames = altdb.altnames(); assert_eq(alts.size(), altnames.size()); for(size_t i = 0; i < alts.size(); i++) { const ALT<index_t>& alt = alts[i]; if(!alt.snp()) continue; if(alt.deletion() && alt.reversed) continue; string type = "single"; if(alt.type == ALT_SNP_DEL) { type = "deletion"; } else if(alt.type == ALT_SNP_INS) { type = "insertion"; } index_t tidx = 0, toff = 0, tlen = 0; bool straddled2 = false; gfm.joinedToTextOff( 1, alt.pos, tidx, toff, tlen, true, // reject straddlers? straddled2); // straddled? cout << altnames[i] << "\t" << type << "\t"; assert_lt(tidx, p_refnames.size()); cout << p_refnames[tidx] << "\t" << toff << "\t"; if(alt.type == ALT_SNP_SGL) { cout << "ACGT"[alt.seq & 0x3]; } else if(alt.type == ALT_SNP_DEL) { cout << alt.len; } else if(alt.type == ALT_SNP_INS) { for(index_t i = 0; i < alt.len; i++) { int nt = (alt.seq >> ((alt.len - i - 1) << 1)) & 0x3; cout << "ACGT"[nt]; } } cout << endl; } } /** * Print a short summary of what's in the index and its flags. */ template <typename index_t> static void print_splicesites( const string& fname, ostream& fout) { ALTDB<index_t> altdb; GFM<index_t> gfm( fname, &altdb, -1, // don't require entire reverse true, // index is for the forward direction -1, // offrate (-1 = index default) 0, // offrate-plus (0 = index default) false, // use memory-mapped IO false, // use shared memory false, // sweep memory-mapped memory true, // load names? false, // load SA sample? false, // load ftab? false, // load rstarts? true, // load splice sites? verbose, // be talkative? verbose, // be talkative at startup? false, // pass up memory exceptions? false, // sanity check? false); // use haplotypes? gfm.loadIntoMemory( -1, // need entire reverse true, // load SA sample true, // load ftab true, // load rstarts true, // load names verbose); // verbose EList<string> p_refnames; readEbwtRefnames<index_t>(fname, p_refnames); const EList<ALT<index_t> >& alts = altdb.alts(); for(size_t i = 0; i < alts.size(); i++) { const ALT<index_t>& alt = alts[i]; if(!alt.splicesite()) continue; if(alt.left >= alt.right) continue; if(!splicesite_all_only && alt.excluded) continue; index_t tidx = 0, toff = 0, tlen = 0; bool straddled2 = false; gfm.joinedToTextOff( 1, alt.left, tidx, toff, tlen, true, // reject straddlers? straddled2); // straddled? index_t tidx2 = 0, toff2 = 0, tlen2 = 0; gfm.joinedToTextOff( 1, alt.right, tidx2, toff2, tlen2, true, // reject straddlers? straddled2); // straddled? assert_eq(tidx, tidx2); assert_lt(tidx, p_refnames.size()); cout << p_refnames[tidx] << "\t" << toff - 1 << "\t" << toff2 + 1 << "\t" << (alt.fw > 0 ? "+" : "-") << endl; } } /** * Print a short summary of what's in the index and its flags. */ template <typename index_t> static void print_exons( const string& fname, ostream& fout) { ALTDB<index_t> altdb; GFM<index_t> gfm( fname, &altdb, -1, // don't require entire reverse true, // index is for the forward direction -1, // offrate (-1 = index default) 0, // offrate-plus (0 = index default) false, // use memory-mapped IO false, // use shared memory false, // sweep memory-mapped memory true, // load names? false, // load SA sample? false, // load ftab? false, // load rstarts? true, // load splice sites? verbose, // be talkative? verbose, // be talkative at startup? false, // pass up memory exceptions? false, // sanity check? false); // use haplotypes? gfm.loadIntoMemory( -1, // need entire reverse true, // load SA sample true, // load ftab true, // load rstarts true, // load names verbose); // verbose EList<string> p_refnames; readEbwtRefnames<index_t>(fname, p_refnames); const EList<ALT<index_t> >& alts = altdb.alts(); for(size_t i = 0; i < alts.size(); i++) { const ALT<index_t>& alt = alts[i]; if(!alt.exon()) continue; index_t tidx = 0, toff = 0, tlen = 0; bool straddled2 = false; gfm.joinedToTextOff( 1, alt.left, tidx, toff, tlen, true, // reject straddlers? straddled2); // straddled? index_t tidx2 = 0, toff2 = 0, tlen2 = 0; gfm.joinedToTextOff( 1, alt.right, tidx2, toff2, tlen2, true, // reject straddlers? straddled2); // straddled? assert_eq(tidx, tidx2); assert_lt(tidx, p_refnames.size()); cout << p_refnames[tidx] << "\t" << toff - 1 << "\t" << toff2 + 1 << "\t" << (alt.fw > 0 ? "+" : "-") << endl; } } /** * Print a short summary of what's in the index and its flags. */ template <typename index_t> static void print_index_summary( const string& fname, ostream& fout) { int major, minor; string extra_version; int32_t flags = GFM<index_t>::readVersionFlags(fname, major, minor, extra_version); bool entireReverse = false; ALTDB<index_t> altdb; GFM<index_t> gfm( fname, &altdb, -1, // don't require entire reverse true, // index is for the forward direction -1, // offrate (-1 = index default) 0, // offrate-plus (0 = index default) false, // use memory-mapped IO false, // use shared memory false, // sweep memory-mapped memory true, // load names? false, // load SA sample? false, // load ftab? false, // load rstarts? true, // load splice sites? verbose, // be talkative? verbose, // be talkative at startup? false, // pass up memory exceptions? false, // sanity check? false); // use haplotypes? EList<string> p_refnames; readEbwtRefnames<index_t>(fname, p_refnames); cout << "Index version" << "\t2." << major << '.' << minor; if(extra_version != "") { cout << "-" << extra_version; } cout << endl; cout << "Flags" << '\t' << (-flags) << endl; cout << "2.0-compatible" << '\t' << (entireReverse ? "1" : "0") << endl; cout << "SA-Sample" << "\t1 in " << (1 << gfm.gh().offRate()) << endl; cout << "FTab-Chars" << '\t' << gfm.gh().ftabChars() << endl; assert_eq(gfm.nPat(), p_refnames.size()); for(size_t i = 0; i < p_refnames.size(); i++) { cout << "Sequence-" << (i+1) << '\t' << p_refnames[i].c_str() << '\t' << gfm.plen()[i] << endl; } index_t numSnps = 0, numSpliceSites = 0, numExons = 0; const EList<ALT<index_t> >& alts = altdb.alts(); for(size_t i = 0; i < alts.size(); i++) { const ALT<index_t>& alt = alts[i]; if(alt.snp()) { numSnps++; } else if(alt.splicesite()) { if(alt.left < alt.right) { numSpliceSites++; } } else if(alt.exon()) { numExons++; } } cout << "Num. SNPs: " << numSnps << endl; cout << "Num. Splice Sites: " << numSpliceSites << endl; cout << "Num. Exons: " << numExons << endl; } extern void initializeCntLut(); extern void initializeCntBit(); static void driver( const string& ebwtFileBase, const string& query) { initializeCntLut(); initializeCntBit(); // Adjust string adjustedEbwtFileBase = adjustEbwtBase(argv0, ebwtFileBase, verbose); if (names_only) { print_index_sequence_names<TIndexOffU>(adjustedEbwtFileBase, cout); } else if(summarize_only) { print_index_summary<TIndexOffU>(adjustedEbwtFileBase, cout); } else if(snp_only) { print_snps<TIndexOffU>(adjustedEbwtFileBase, cout); } else if(splicesite_only || splicesite_all_only) { print_splicesites<TIndexOffU>(adjustedEbwtFileBase, cout); } else if(exon_only) { print_exons<TIndexOffU>(adjustedEbwtFileBase, cout); } else { // Initialize Ebwt object ALTDB<TIndexOffU> altdb; HGFM<TIndexOffU, uint16_t> gfm( adjustedEbwtFileBase, &altdb, -1, // don't care about entire-reverse true, // index is for the forward direction -1, // offrate (-1 = index default) 0, // offrate-plus (0 = index default) false, // use memory-mapped IO false, // use shared memory false, // sweep memory-mapped memory true, // load names? true, // load SA sample? true, // load ftab? true, // load rstarts? true, // load splice sites? false, // be talkative? false, // be talkative at startup? false, // pass up memory exceptions? false, // sanity check? false); // use haplotypes? gfm.loadIntoMemory( -1, // need entire reverse true, // load SA sample true, // load ftab true, // load rstarts true, // load names verbose); // verbose // Load whole index into memory if(refFromGFM) { print_index_sequences<TIndexOffU, SString<char> >(cout, gfm); } else { EList<string> refnames; readEbwtRefnames<TIndexOffU>(adjustedEbwtFileBase, refnames); print_ref_sequences( cout, refnames, gfm.plen(), adjustedEbwtFileBase); } // Evict any loaded indexes from memory if(gfm.isInMemory()) { gfm.evictFromMemory(); } } } /** * main function. Parses command-line arguments. */ int main(int argc, char **argv) { try { string ebwtFile; // read serialized Ebwt from this file string query; // read query string(s) from this file EList<string> queries; string outfile; // write query results to this file argv0 = argv[0]; parseOptions(argc, argv); if(showVersion) { cout << argv0 << " version " << HISAT2_VERSION << endl; if(sizeof(void*) == 4) { cout << "32-bit" << endl; } else if(sizeof(void*) == 8) { cout << "64-bit" << endl; } else { cout << "Neither 32- nor 64-bit: sizeof(void*) = " << sizeof(void*) << endl; } cout << "Built on " << BUILD_HOST << endl; cout << BUILD_TIME << endl; cout << "Compiler: " << COMPILER_VERSION << endl; cout << "Options: " << COMPILER_OPTIONS << endl; cout << "Sizeof {int, long, long long, void*, size_t, off_t}: {" << sizeof(int) << ", " << sizeof(long) << ", " << sizeof(long long) << ", " << sizeof(void *) << ", " << sizeof(size_t) << ", " << sizeof(off_t) << "}" << endl; return 0; } // Get input filename if(optind >= argc) { cerr << "No index name given!" << endl; printUsage(cerr); return 1; } ebwtFile = argv[optind++]; // Optionally summarize if(verbose) { cout << "Input ht2 file: \"" << ebwtFile.c_str() << "\"" << endl; cout << "Output file: \"" << outfile.c_str() << "\"" << endl; cout << "Local endianness: " << (currentlyBigEndian()? "big":"little") << endl; #ifdef NDEBUG cout << "Assertions: disabled" << endl; #else cout << "Assertions: enabled" << endl; #endif } driver(ebwtFile, query); return 0; } catch(std::exception& e) { cerr << "Error: Encountered exception: '" << e.what() << "'" << endl; cerr << "Command: "; for(int i = 0; i < argc; i++) cerr << argv[i] << " "; cerr << endl; return 1; } catch(int e) { if(e != 0) { cerr << "Error: Encountered internal HISAT2 exception (#" << e << ")" << endl; cerr << "Command: "; for(int i = 0; i < argc; i++) cerr << argv[i] << " "; cerr << endl; } return e; } }
gpl-3.0
kuiwang/my-dev
src/main/java/com/taobao/top/link/embedded/websocket/util/StringUtil.java
10111
/* * The MIT License * * Copyright (c) 2011 Takahiro Hashimoto * * 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. */ package com.taobao.top.link.embedded.websocket.util; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * The Class StringUtil. * * @author Takahiro Hashimoto */ public class StringUtil { /** * The Enum State. * * @author Takahiro Hashimoto */ enum State { /** The DELIM. */ DELIM, /** The KEY. */ KEY, /** The KE y_ start. */ KEY_START, /** The VALUE. */ VALUE, /** The VALU e_ start. */ VALUE_START; } /** The hex table. */ private static char[] hexTable = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /** The log. */ private static Logger log = Logger.getLogger(StringUtil.class.getName()); /** * Adds the header. * * @param sb the sb * @param key the key * @param value the value */ public static void addHeader(StringBuilder sb, String key, String value) { // TODO need folding? sb.append(key + ": " + value + "\r\n"); } /** * Adds the param. * * @param sb the sb * @param key the key * @param param the param * @return the string builder */ public static StringBuilder addParam(StringBuilder sb, String key, String param) { sb.append(key).append("=").append(param); return sb; } /** * Adds the quoted param. * * @param sb the sb * @param key the key * @param param the param * @return the string builder */ public static StringBuilder addQuotedParam(StringBuilder sb, String key, String param) { sb.append(key).append("=\"").append(param).append("\""); return sb; } /** * Join. * * @param delim the delim * @param collections the collections * @return the string */ public static String join(String delim, Collection<String> collections) { String[] values = new String[collections.size()]; collections.toArray(values); return join(delim, 0, collections.size(), values); } /** * Join. * * @param delim the delim * @param start the start * @param end the end * @param strings the strings * @return the string */ public static String join(String delim, int start, int end, String... strings) { if (strings.length == 1) { return strings[0]; } StringBuilder sb = new StringBuilder(strings[start]); for (int i = start + 1; i < end; i++) { sb.append(delim).append(strings[i]); } return sb.toString(); } /** * Join. * * @param delim the delim * @param strings the strings * @return the string */ public static String join(String delim, String... strings) { return join(delim, 0, strings.length, strings); } /** * Lpad. * * @param str the str * @param len the len * @param padding the padding * @return the string */ public static String lpad(Object str, int len, String padding) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < (len - str.toString().length()); i++) { sb.append(padding); } sb.append(str); return sb.toString(); } /** * ex. realm="testrealm@host.com", qop="auth,auth-int" * * @param str the str * @param delim the delim * @return the map */ public static Map<String, String> parseKeyValues(String str, char delim) { State state = State.KEY; char[] chars = str.toCharArray(); String key = null; String value = null; StringBuilder sb = new StringBuilder(); Map<String, String> map = new HashMap<String, String>(); boolean isQuoted = false; for (char c : chars) { switch (state) { case KEY_START: if (c == ' ') { continue; } else { sb.append(c); state = State.KEY; } break; case KEY: if (c == '=') { key = sb.toString().trim(); sb = new StringBuilder(); state = State.VALUE_START; } else { sb.append(c); } break; case VALUE_START: if (c == ' ') { continue; } else if (c == '"') { state = State.VALUE; isQuoted = true; } else { sb.append(c); state = State.VALUE; isQuoted = false; } break; case VALUE: if (isQuoted && (c == '"')) { state = State.DELIM; value = sb.toString(); map.put(key, value); sb = new StringBuilder(); } else if (!isQuoted && (c == delim)) { state = State.KEY_START; value = sb.toString(); map.put(key, value); sb = new StringBuilder(); } else { sb.append(c); } break; case DELIM: if (c == ' ') { continue; } else if (c == ',') { state = State.KEY_START; } else { break; } break; } } return map; } /** * Read line. * * @param buf the buf * @return the string */ public static String readLine(ByteBuffer buf) { boolean completed = false; buf.mark(); while (buf.hasRemaining() && !completed) { byte b = buf.get(); if (b == '\r') { if (buf.hasRemaining() && (buf.get() == '\n')) { completed = true; } } } if (!completed) { return null; } int limit = buf.position(); buf.reset(); int length = limit - buf.position(); byte[] tmp = new byte[length]; buf.get(tmp, 0, length); try { String line = new String(tmp, "US-ASCII"); if (log.isLoggable(Level.FINEST)) { log.finest(line.trim()); } return line; } catch (UnsupportedEncodingException e) { ; } return null; } /** * Rpad. * * @param str the str * @param len the len * @param padding the padding * @return the string */ public static String rpad(Object str, int len, String padding) { StringBuilder sb = new StringBuilder(); sb.append(str); for (int i = 0; i < (len - str.toString().length()); i++) { sb.append(padding); } return sb.toString(); } /** * toHexString. * * @param b the b * @return the string */ public static String toHexString(byte b) { char[] chars = new char[2]; int d = (b & 0xF0) >> 4; int m = b & 0x0F; chars[0] = hexTable[d]; chars[1] = hexTable[m]; return new String(chars); } /** * toHexString. * * @param bytes the bytes * @return the string */ public static String toHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { char[] chars = new char[2]; int d = (b & 0xF0) >> 4; int m = b & 0x0F; chars[0] = hexTable[d]; chars[1] = hexTable[m]; sb.append(chars); } return sb.toString(); } /** * To m d5 hex string. * * @param str the str * @return the string */ public static String toMD5HexString(String str) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes("US-ASCII")); return toHexString(md.digest()); } catch (UnsupportedEncodingException e) { ; } catch (NoSuchAlgorithmException e) { ; } return null; } }
gpl-3.0
CCAFS/MARLO
marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/mysql/AuditLogMySQLDao.java
10722
/***************************************************************** * This file is part of Managing Agricultural Research for Learning & * Outcomes Platform (MARLO). * MARLO 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. * MARLO 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 MARLO. If not, see <http://www.gnu.org/licenses/>. *****************************************************************/ package org.cgiar.ccafs.marlo.data.dao.mysql; import org.cgiar.ccafs.marlo.data.IAuditLog; import org.cgiar.ccafs.marlo.data.dao.AuditLogDao; import org.cgiar.ccafs.marlo.data.dao.UserDAO; import org.cgiar.ccafs.marlo.data.model.Auditlog; import org.cgiar.ccafs.marlo.utils.BigDecimalTypeAdapter; import org.cgiar.ccafs.marlo.utils.DateTypeAdapter; import org.cgiar.ccafs.marlo.utils.DoubleTypeAdapter; import org.cgiar.ccafs.marlo.utils.FloatTypeAdapter; import org.cgiar.ccafs.marlo.utils.IntegerTypeAdapter; import org.cgiar.ccafs.marlo.utils.LongTypeAdapter; import org.cgiar.ccafs.marlo.utils.StringTypeAdapter; import java.lang.reflect.Field; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.inject.Inject; import javax.inject.Named; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.metadata.ClassMetadata; import org.hibernate.type.OneToOneType; import org.hibernate.type.OrderedSetType; import org.hibernate.type.SetType; import org.hibernate.type.Type; /** * @author Christian Garcia */ @Named public class AuditLogMySQLDao extends AbstractMarloDAO<Auditlog, Long> implements AuditLogDao { public String baseModelPakcage = "org.cgiar.ccafs.marlo.data.model"; public UserDAO userDao; @Inject public AuditLogMySQLDao(SessionFactory sessionFactory, UserDAO userDao) { super(sessionFactory); this.userDao = userDao; } @Override public List<Auditlog> findAllWithClassNameAndIdAndActionName(Class<?> classAudit, long id, String actionName) { String queryString = "from " + Auditlog.class.getName() + " where ENTITY_NAME='class " + classAudit.getName() + "' and ENTITY_ID=" + id + " and main=1 and DETAIL like 'Action: " + actionName + "%' order by CREATED_DATE desc"; Query query = this.getSessionFactory().getCurrentSession().createQuery(queryString); query.setMaxResults(11); List<Auditlog> auditLogs = super.findAll(query); return auditLogs; } @Override public Auditlog getAuditlog(String transactionID) { List<Auditlog> auditLogs = super.findAll("from " + Auditlog.class.getName() + " where transaction_id='" + transactionID + "' and main=1"); if (!auditLogs.isEmpty()) { Auditlog log = auditLogs.get(0); return log; } return null; } @Override public Auditlog getAuditlog(String transactionID, IAuditLog auditLog) { List<Auditlog> auditLogs = super.findAll("from " + Auditlog.class.getName() + " where transaction_id='" + transactionID + "' and ENTITY_ID=" + auditLog.getId() + " and ENTITY_NAME='" + auditLog.getClass().toString() + "'"); if (!auditLogs.isEmpty()) { Auditlog log = auditLogs.get(0); return log; } return null; } @Override public List<Auditlog> getCompleteHistory(String transactionID) { List<Auditlog> auditLogs = super.findAll("from " + Auditlog.class.getName() + " where transaction_id='" + transactionID + "'"); return auditLogs; } @Override public IAuditLog getHistory(String transactionID) { List<Auditlog> auditLogs = super.findAll("from " + Auditlog.class.getName() + " where transaction_id='" + transactionID + "' and main=1"); if (!auditLogs.isEmpty()) { Auditlog log = auditLogs.get(0); IAuditLog iAuditLog = this.loadFromAuditLog(log); try { this.loadRelationsForIAuditLog(iAuditLog, transactionID); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } return iAuditLog; } return null; } @Override public List<Auditlog> getHistoryBefore(String transactionID) { List<Auditlog> logs = new ArrayList<Auditlog>(); Auditlog principal = this.getAuditlog(transactionID); String sql = " select transaction_id from auditlog where transaction_id !='" + transactionID + "' and ENTITY_ID='" + principal.getEntityId() + "'" + " and ENTITY_NAME='" + principal.getEntityName() + "' and DETAIL = '" + principal.getDetail() + "' and CREATED_DATE< '" + principal.getCreatedDate() + "' ORDER BY CREATED_DATE desc"; List<Map<String, Object>> auditLogs = super.findCustomQuery(sql); if (!auditLogs.isEmpty()) { logs.addAll(this.getCompleteHistory(auditLogs.get(0).get("transaction_id").toString())); } return logs; } @Override public List<Auditlog> getHistoryBeforeList(String transactionID, String className, String entityID) { List<Auditlog> logs = new ArrayList<Auditlog>(); Auditlog principal = this.getAuditlog(transactionID); String sql = " select transaction_id from auditlog where transaction_id !='" + transactionID + "' and ENTITY_ID='" + entityID + "'" + " and ENTITY_NAME='" + className + "' and CREATED_DATE< '" + principal.getCreatedDate() + "' ORDER BY CREATED_DATE desc"; List<Map<String, Object>> auditLogs = super.findCustomQuery(sql); if (!auditLogs.isEmpty()) { logs.addAll(this.getCompleteHistory(auditLogs.get(0).get("transaction_id").toString())); } return logs; } @Override public List<Auditlog> listLogs(Class<?> classAudit, long id, String actionName, Long phaseId) { List<Auditlog> auditLogs = super.findAll("from " + Auditlog.class.getName() + " where ENTITY_NAME='class " + classAudit.getName() + "' and ENTITY_ID=" + id + " and main=1 and id_phase=" + phaseId + " and DETAIL like 'Action: " + actionName + "%' order by CREATED_DATE desc "); // " and principal=1 order by CREATED_DATE desc LIMIT 10"); for (Auditlog auditlog : auditLogs) { auditlog.setUser(userDao.getUser(auditlog.getUserId())); } if (auditLogs.size() > 11) { return auditLogs.subList(0, 11); } return auditLogs; } public IAuditLog loadFromAuditLog(Auditlog auditlog) { try { Gson gson = new GsonBuilder().registerTypeAdapter(Integer.class, new IntegerTypeAdapter()) .registerTypeAdapter(Long.class, new LongTypeAdapter()) .registerTypeAdapter(Double.class, new DoubleTypeAdapter()) .registerTypeAdapter(Float.class, new FloatTypeAdapter()) .registerTypeAdapter(BigDecimal.class, new BigDecimalTypeAdapter()) .registerTypeAdapter(String.class, new StringTypeAdapter()) .registerTypeAdapter(Date.class, new DateTypeAdapter()).create(); Class<?> classToCast = Class.forName(auditlog.getEntityName().replace("class ", "")); IAuditLog iAuditLog = (IAuditLog) gson.fromJson(auditlog.getEntityJson(), classToCast); if (iAuditLog.getModifiedBy() != null && iAuditLog.getModifiedBy().getId() != null) { iAuditLog.setModifiedBy(userDao.getUser(iAuditLog.getModifiedBy().getId())); } else { iAuditLog.setModifiedBy(userDao.getUser(new Long(3))); } return iAuditLog; } catch (JsonSyntaxException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } public void loadRelationsForIAuditLog(IAuditLog iAuditLog, String transactionID) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { try { Session session = super.getSessionFactory().getCurrentSession(); ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(iAuditLog.getClass()); String[] propertyNames = classMetadata.getPropertyNames(); for (String name : propertyNames) { try { Type propertyType = classMetadata.getPropertyType(name); Field privateField = iAuditLog.getClass().getDeclaredField(name); privateField.setAccessible(true); if (propertyType instanceof OneToOneType) { Object obj = privateField.get(iAuditLog); if (obj != null && obj instanceof IAuditLog) { this.loadRelationsForIAuditLog((IAuditLog) obj, transactionID); } } if (propertyType instanceof OrderedSetType || propertyType instanceof SetType) { String classNameRelation = propertyType.getName(); String sql = "from " + Auditlog.class.getName() + " where transaction_id='" + transactionID + "' and main=3 and relation_name='" + classNameRelation + ":" + iAuditLog.getId() + "'order by ABS(ENTITY_ID) asc"; List<Auditlog> auditLogsRelations = super.findAll(sql); Set<IAuditLog> relation = new HashSet<IAuditLog>(); for (Auditlog auditlog : auditLogsRelations) { IAuditLog relationObject = this.loadFromAuditLog(auditlog); this.loadRelationsForIAuditLog(relationObject, transactionID); relation.add(relationObject); } classMetadata.setPropertyValue(iAuditLog, name, relation); } } catch (Exception e) { } } } catch (JsonSyntaxException e) { e.printStackTrace(); } } }
gpl-3.0
clbonner/cragbook
views/crag.php
1753
<script> $(document).ready( function () { getCrag(<?= $_GET["cragid"] ?>); }); </script> <div id="backlink"> <a href="<?= SITEURL ?>/area.php?areaid=<?= $data["area"]["areaid"] ?>"><i class="fa fa-angle-left">&nbsp<?= $data["area"]["name"] ?></i></a> </div> <div class="content panel"> <?php if (isset($_SESSION["userid"])): ?> <div class="right"> <button class="btn-edit fa fa-edit" onclick="window.location.assign('<?= SITEURL ?>/admin/crag.php?action=edit&cragid=<?= $_GET["cragid"] ?>')"></button> <button class="btn-edit fa fa-trash" onclick="window.location.assign('<?= SITEURL ?>/admin/crag.php?action=delete&cragid=<?= $_GET["cragid"] ?>')"></button> </div> <?php endif ?> <div id="name" class="title"></div> <div id="viewpicker"> <button id="infoview" class="fa fa-info btn-picker" onclick="viewCragInfo()"></button> <button id="mapview" class="fa fa-map-o btn-picker" onclick="viewCragMap('crag')"></button> <button id="printview" class="fa fa-print btn-picker" onclick="printRoutes('crag')"></button> </div> <div id="view"></div> </div> <div class="content panel"> <?php if (isset($_SESSION["userid"])): ?> <div class="right"> <button class="btn-edit fa fa-plus" onclick="window.location.assign('<?= SITEURL ?>/admin/route.php?action=add&cragid=<?= $_GET["cragid"] ?>')"></button> <button class="btn-edit fa fa-sort" onclick="window.location.assign('<?= SITEURL ?>/admin/route_sort.php?cragid=<?= $_GET["cragid"] ?>')"></button> </div> <?php endif ?> <div class="heading">Routes</div> <div id="gradefilter"></div> <div id="routes"></div> <div id="modal" class="modal"></div> </div>
gpl-3.0
lvk/Unitale
Assets/Scripts/Debug/UserDebugger.cs
1435
using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; /// <summary> /// Behaviour you can use to print lines into a UnityEngine.UI.Text component for debugging, keeping only a set amount of lines in memory. /// </summary> public class UserDebugger : MonoBehaviour { public static UserDebugger instance; public Text text; public int maxLines; public Queue<string> dbgContent = new Queue<string>(); private bool firstActive = false; private string originalText; void Awake(){ instance = this; originalText = text.text; gameObject.SetActive(false); } public static void warn(string line){ instance.writeLine("[Warn] " + line); } public void userWriteLine(string line) { // activation of the debug window if you're printing to it for the first time if (!firstActive) { gameObject.SetActive(true); firstActive = true; } writeLine(line); } private void writeLine(string line) { // enqueue the new line and keep queue at capacity dbgContent.Enqueue(line); if (dbgContent.Count > maxLines) { dbgContent.Dequeue(); } // print to debug console text.text = originalText; foreach(string dbgLine in dbgContent){ text.text += "\n" + dbgLine; } } }
gpl-3.0
MECTsrl/ATCMcontrol_Engineering
src/Target/Templates/AddOnHandler/AAddOnObject.cpp
7417
/* $Header: /4CReleased/V2.20.00/Target/TEMPLATES/AddOnHandler/AAddOnObject.cpp 1 28.02.07 18:54 Ln $ * ------------------------------------------------------------------------------ * * =FILENAME $Workfile: AAddOnObject.cpp $ * $Logfile: /4CReleased/V2.20.00/Target/TEMPLATES/AddOnHandler/AAddOnObject.cpp $ * * =PROJECT ATCMControl V2.x * * =SWKE Target * * =COMPONENT AddOnHandler * * =CURRENT $Date: 28.02.07 18:54 $ * $Revision: 1 $ * * ------------------------------------------------------------------------------ * * All Rights Reserved. * * ------------------------------------------------------------------------------ */ /* ---- Includes: ---------------------------------------------------------- */ #include "StdAfx.h" #include "AddOnHandler.h" #include "AAddOnObject.h" #include "ProjectWizardDialog.h" #include "ATargetData.h" #include "AProjectData.h" #include "PouProtectionDlg.h" #include "GHFile.h" #include "EnterPasswordDlg.h" /* ---- Target Specific Includes: ----------------------------------------- */ /* ---- Local Defines: ----------------------------------------------------- */ #define DISP_POUPROTECTION _T("PouProtection") /* ---- Global Variables: -------------------------------------------------- */ /* ---- Local Functions: --------------------------------------------------- */ /* ---- Implementations: --------------------------------------------------- */ /* ---------------------------------------------------------------------------- */ /** * CAAddOnObject * */ CAAddOnObject::CAAddOnObject() : CBaseTargetObject(_T("[*PR]\\[*PR]_Addon.kad")) { } /* ---------------------------------------------------------------------------- */ /** * ~CAAddOnObject * */ CAAddOnObject::~CAAddOnObject() { } /* ---------------------------------------------------------------------------- */ /** * InterfaceSupportsErrorInfo * */ STDMETHODIMP CAAddOnObject::InterfaceSupportsErrorInfo(REFIID riid) { if (CAAddOnObject::InterfaceSupportsErrorInfo(riid) == S_OK) return S_OK; return S_FALSE; } /* ---------------------------------------------------------------------------- */ /** * ShowProjectWizardDialog * */ HRESULT CAAddOnObject::ShowProjectWizardDialog(CBaseProjectData* pProjectData) { HRESULT hr; CProjectWizardDialog tDlg(pProjectData); if (tDlg.DoModal () != ID_WIZFINISH) { return (S_FALSE); } hr = pProjectData->CreateProjectFiles (); if (FAILED (hr)) { delete pProjectData; } return (hr); } /* ---------------------------------------------------------------------------- */ /** * CreateTargetData * */ CBaseTargetData* CAAddOnObject::CreateTargetData(ICEProjInfo* pICEProjInfo) { CBaseTargetData* ptTargetData = new CATargetData( this, pICEProjInfo, m_strKADFileName); ptTargetData->Init(); if(!ptTargetData) { ::AfxThrowMemoryException(); } return ptTargetData; } /* ---------------------------------------------------------------------------- */ /** * CreateProjectData * */ CBaseProjectData* CAAddOnObject::CreateProjectData() { CBaseProjectData* pProjectData = (CBaseProjectData*) new CAProjectData; if(!pProjectData) { ::AfxThrowMemoryException(); } return pProjectData; } /* ---------------------------------------------------------------------------- */ /** * ActionDispatcher * */ HRESULT CAAddOnObject::ActionDispatcher(CBaseTargetData* ptBaseTargetData, const CString& crstrMethodName, const CString& crstrSourceFile, const CString& crstrSourceId, const CString& crstrAddInfo, BOOL& bHandled) { HRESULT hr = S_FALSE; bHandled = FALSE; CATargetData* pData = dynamic_cast<CATargetData*>(ptBaseTargetData); if(!pData) { return E_FAIL; } ICEProjInfo* pICEProjectInfo = ptBaseTargetData->GetProjInfo(); if(!pICEProjectInfo) { return E_FAIL; } // these methods do not need the target file to be loaded if (crstrMethodName.CompareNoCase(DISP_POUPROTECTION)==0) { hr = OnPouProtection(pData, crstrSourceFile, crstrSourceId, pICEProjectInfo, crstrAddInfo); bHandled = TRUE; } return hr; } /* ---------------------------------------------------------------------------- */ /** * OnPouProtection * */ HRESULT CAAddOnObject::OnPouProtection(CATargetData* pTargetData, const CString& crstrFileName, const CString& crstrIdPath, ICEProjInfo* pICEProjInfo, const CString& crstrAddInfo) { HRESULT hr = S_OK; ASSERT(pICEProjInfo); // first load file CComBSTR sProjectPath; hr = pICEProjInfo->getProjectPath(&sProjectPath); if (hr != S_OK) { CString strMessage; strMessage.LoadString(IDS_INTERNAL_ERROR); strMessage += _T(": OnPouProtection1"); ::AfxMessageBox(strMessage, MB_OK|MB_ICONERROR); return hr; } // open 4gh file CGHFile tGHFile; CString strGHFileName; strGHFileName.Format("%s\\Project.4gh", (CString)sProjectPath); tGHFile.SetFileName(strGHFileName); if(!tGHFile.Read()) { ::AfxMessageBox(IDS_4GHFILE_READ_ERR); return E_FAIL; } // password dialog CString strGHPassword = tGHFile.GetPassword(); CEnterPasswordDlg tEnterPWDlg(strGHPassword); if(tEnterPWDlg.DoModal() != IDOK) { tGHFile.SetPassword(tEnterPWDlg.m_strPassword); if(tEnterPWDlg.m_bPasswdChanged) { tGHFile.Write(); } return E_FAIL; } tGHFile.SetPassword(tEnterPWDlg.m_strPassword); if(tEnterPWDlg.m_bPasswdChanged) { tGHFile.Write(); } // check project guid CComBSTR sSection(_T("ATTRIBUTES")); CComBSTR sKey(_T("GUID")); CComBSTR sValue; pICEProjInfo->CPGetValueForKeyFromSection(sSection, sKey, &sValue); CString strProjectGuid(sValue); // remove "" strProjectGuid = strProjectGuid.Mid(1); strProjectGuid = strProjectGuid.Left(strProjectGuid.GetLength()-1); if(strProjectGuid.Compare(tGHFile.GetProjectGuid()) != 0) { ::AfxMessageBox(IDS_4GHFILE_PROJCONFILCT); return E_FAIL; } // user is authorized to get pou protection dialog CPouProtectionDlg tDlg(&tGHFile, pICEProjInfo); if(tDlg.DoModal() != IDOK) { return S_FALSE; } return hr; } /* ============================================================================ * T A R G E T S P E C I F I C * ============================================================================ * */ /* ---------------------------------------------------------------------------- */
gpl-3.0
timgrube/DNA
src/dna/depr/metrics/apsp/IntWeightedAllPairsShortestPathsR.java
6391
package dna.depr.metrics.apsp; import java.util.Comparator; import java.util.PriorityQueue; import dna.graph.IElement; import dna.graph.edges.DirectedEdge; import dna.graph.edges.UndirectedEdge; import dna.graph.nodes.DirectedNode; import dna.graph.nodes.Node; import dna.graph.nodes.UndirectedNode; import dna.graph.weights.IWeighted; import dna.graph.weights.IntWeight; import dna.updates.batch.Batch; import dna.updates.update.Update; public class IntWeightedAllPairsShortestPathsR extends IntWeightedAllPairsShortestPaths { public IntWeightedAllPairsShortestPathsR() { super("IntWeightedAllPairsShortestPathsR", ApplicationType.Recomputation); } @Override public boolean applyBeforeBatch(Batch b) { return false; } @Override public boolean applyAfterBatch(Batch b) { return false; } @Override public boolean applyBeforeUpdate(Update u) { return false; } @Override public boolean applyAfterUpdate(Update u) { return false; } @Override public boolean compute() { for (IElement source_ : this.g.getNodes()) { Node source = (Node) source_; int[] dist = this.getInitialDist(this.g.getMaxNodeIndex() + 1); Node[] previous = new Node[this.g.getMaxNodeIndex() + 1]; boolean[] visited = new boolean[g.getMaxNodeIndex() + 1]; PriorityQueue<Node> Q = new PriorityQueue<Node>(g.getNodeCount(), new DistComparator(dist)); dist[source.getIndex()] = 0; Q.add(source); while (!Q.isEmpty()) { Node current = (Node) Q.remove(); if (visited[current.getIndex()]) { continue; } visited[current.getIndex()] = true; if (current instanceof DirectedNode) { for (IElement e : ((DirectedNode) current) .getOutgoingEdges()) { Node n = ((DirectedEdge) e).getDst(); IntWeight w = (IntWeight) ((IWeighted) e).getWeight(); this.process(source, current, n, (int) w.getWeight(), dist, previous, visited, Q); } } else if (current instanceof UndirectedNode) { for (IElement e : ((UndirectedNode) current).getEdges()) { Node n = ((UndirectedEdge) e).getDifferingNode(current); IntWeight w = (IntWeight) ((IWeighted) e).getWeight(); this.process(source, current, n, (int) w.getWeight(), dist, previous, visited, Q); } } } for (int d : dist) { if (d > 0 && d != Integer.MAX_VALUE) { this.apsp.incr(d); } } } return true; } protected class DistComparator implements Comparator<Node> { private int[] dist; public DistComparator(int[] dist) { this.dist = dist; } @Override public int compare(Node o1, Node o2) { return this.dist[o1.getIndex()] - this.dist[o2.getIndex()]; } } protected void process(Node source, Node current, Node n, int weight, int[] dist, Node[] previous, boolean[] visited, PriorityQueue<Node> Q) { if (n.getIndex() == source.getIndex()) { return; } int newDist = dist[current.getIndex()] + weight; if (previous[n.getIndex()] == null || newDist < dist[n.getIndex()]) { dist[n.getIndex()] = newDist; previous[n.getIndex()] = current; Q.add(n); } } protected int[] getInitialDist(int size) { int[] dist = new int[size]; for (int i = 0; i < dist.length; i++) { dist[i] = Integer.MAX_VALUE; } return dist; } // protected HashMap<Node, HashMap<Node, Node>> parents; // // protected HashMap<Node, HashMap<Node, Integer>> heights; // // @Override // public void init_() { // super.init_(); // this.parents = new HashMap<Node, HashMap<Node, Node>>(); // this.heights = new HashMap<Node, HashMap<Node, Integer>>(); // } // // @Override // public void reset_() { // super.reset_(); // this.parents = new HashMap<Node, HashMap<Node, Node>>(); // this.heights = new HashMap<Node, HashMap<Node, Integer>>(); // } // // @Override // public boolean compute() { // // for (IElement ie : g.getNodes()) { // Node s = (Node) ie; // // HashMap<Node, Node> parent = new HashMap<Node, Node>(); // HashMap<Node, Integer> height = new HashMap<Node, Integer>(); // // for (IElement iNode : g.getNodes()) { // Node t = (Node) iNode; // if (t.equals(s)) { // height.put(s, 0); // } else { // height.put(t, Integer.MAX_VALUE); // } // } // if (DirectedNode.class.isAssignableFrom(this.g // .getGraphDatastructures().getNodeType())) { // PriorityQueue<QueueElement<DirectedNode>> q = new // PriorityQueue<QueueElement<DirectedNode>>(); // q.add(new QueueElement((DirectedNode) s, height.get(s))); // while (!q.isEmpty()) { // QueueElement<DirectedNode> c = q.poll(); // DirectedNode current = c.e; // if (height.get(current) == Integer.MAX_VALUE) { // break; // } // // for (IElement iEdge : current.getOutgoingEdges()) { // DirectedIntWeightedEdge d = (DirectedIntWeightedEdge) iEdge; // // DirectedNode neighbor = d.getDst(); // // int alt = height.get(current) + d.getWeight(); // if (alt < 0) { // continue; // } // if (alt < height.get(neighbor)) { // height.put(neighbor, alt); // parent.put(neighbor, current); // QueueElement<DirectedNode> temp = new QueueElement<DirectedNode>( // neighbor, height.get(neighbor)); // if (q.contains(temp)) { // q.remove(temp); // } // q.add(temp); // } // } // } // } else { // PriorityQueue<QueueElement<UndirectedNode>> q = new // PriorityQueue<QueueElement<UndirectedNode>>(); // q.add(new QueueElement((UndirectedNode) s, height.get(s))); // while (!q.isEmpty()) { // QueueElement<UndirectedNode> c = q.poll(); // UndirectedNode current = c.e; // // if (height.get(current) == Integer.MAX_VALUE) { // break; // } // // for (IElement iEdge : current.getEdges()) { // UndirectedIntWeightedEdge d = (UndirectedIntWeightedEdge) iEdge; // // UndirectedNode neighbor = d.getDifferingNode(current); // // int alt = height.get(current) + d.getWeight(); // if (alt < 0) { // continue; // } // if (alt < height.get(neighbor)) { // height.put(neighbor, alt); // parent.put(neighbor, current); // QueueElement<UndirectedNode> temp = new QueueElement<UndirectedNode>( // neighbor, height.get(neighbor)); // if (q.contains(temp)) { // q.remove(temp); // } // q.add(temp); // } // } // } // } // for (int i : height.values()) { // if (i != Integer.MAX_VALUE && i != 0) { // apsp.incr(i); // } // } // apsp.truncate(); // parents.put(s, parent); // heights.put(s, height); // } // // return true; // } }
gpl-3.0
sharebookproject/AndroidPQCrypto
MCElieceProject/Flexiprovider/src/main/java/de/flexiprovider/pqc/ecc/mceliece/McElieceCCA2KeyPairGenerator.java
7427
package de.flexiprovider.pqc.ecc.mceliece; import de.flexiprovider.api.Registry; import de.flexiprovider.api.SecureRandom; import de.flexiprovider.api.exceptions.InvalidAlgorithmParameterException; import de.flexiprovider.api.exceptions.InvalidParameterException; import de.flexiprovider.api.keys.KeyPair; import de.flexiprovider.api.keys.KeyPairGenerator; import de.flexiprovider.api.parameters.AlgorithmParameterSpec; import de.flexiprovider.common.math.codingtheory.GF2mField; import de.flexiprovider.common.math.codingtheory.GoppaCode; import de.flexiprovider.common.math.codingtheory.PolynomialGF2mSmallM; import de.flexiprovider.common.math.codingtheory.PolynomialRingGF2m; import de.flexiprovider.common.math.codingtheory.GoppaCode.MaMaPe; import de.flexiprovider.common.math.linearalgebra.GF2Matrix; import de.flexiprovider.common.math.linearalgebra.Permutation; import de.flexiprovider.pqc.ecc.ECCKeyGenParameterSpec; /** * This class implements key pair generation of the McEliece Public Key * Cryptosystem (McEliecePKC). The class extends the <a * href="java.security.spec.KeyPairGeneratorSpi">KeyPairGeneratorSpi</a> class. * <p> * The algorithm is given the parameters m and t or the key size n as input. * Then, the following matrices are generated: * <ul> * <li>G' is a k x n generator matrix of a binary irreducible (n,k) Goppa code * GC which can correct up to t errors where n = 2^m and k is chosen maximal, * i.e. k <= n - mt</li> * <li>H is an mt x n check matrix of the Goppa code GC</li> * <li>S is a k x k random binary non-singular matrix</li> * <li>P is an n x n random permutation matrix.</li> * </ul> * Then, the algorithm computes the k x n matrix G = SG'P.<br/> The public key * is (n, t, G). The private key is (m, k, field polynomial, Goppa polynomial, * H, S, P, setJ);<br/> A key pair consists of a McEliecePublicKey and a * McEliecePrivatKey. * <p> * The default parameters are m = 10 and t = 50. * <p> * The McElieceKeyPairGenerator can be used as follows: * <ol> * <li>get instance of McEliecePKC key pair generator:<br/> * <tt>KeyPairGenerator kpg = * KeyPairGenerator.getInstance("McEliece","FlexiPQC");</tt></li> * <li>initialize the KPG with key size n:<br/> <tt>kpg.initialize(n);</tt><br/> * or with parameters m and t via a <a * href="de.flexiprovider.pqc.ecc.mceliece.McElieceParameterSpec">McElieceParameterSpec</a>:<br/> * <tt>McElieceParameterSpec paramSpec = new McElieceParameterSpec(m, t);<br/> * kpg.initialize(paramSpec, Registry.getSecureRandom());</tt></li> * <li>create McEliecePKC key pair:<br/> * <tt>KeyPair keyPair = kpg.generateKeyPair();</tt></li> * <li>get the encoded private and public keys from the key pair:<br/> * <tt>encodedPublicKey = keyPair.getPublic().getEncoded();<br/> * encodedPrivateKey = keyPair.getPrivate().getEncoded();</tt></li> * </ol> * * @see de.flexiprovider.pqc.ecc.ECCKeyGenParameterSpec * @author Elena Klintsevich * @author Martin D_ring */ public class McElieceCCA2KeyPairGenerator extends KeyPairGenerator { // the extension degree of the finite field GF(2^m) private int m; // the length of the code private int n; // the error correction capability private int t; // the field polynomial private int fieldPoly; // the source of randomness private SecureRandom random; // flag indicating whether the key pair generator has been initialized private boolean initialized = false; /** * Initialize the key pair generator with the given parameters and source of * randomness. The parameters have to be an instance of * {@link de.flexiprovider.pqc.ecc.ECCKeyGenParameterSpec}. If the parameters are <tt>null</tt>, the * default parameters are used (see {@link de.flexiprovider.pqc.ecc.ECCKeyGenParameterSpec}). * * @param params * the parameters * @param random * the source of randomness * @throws de.flexiprovider.api.exceptions.InvalidAlgorithmParameterException * if the parameters are not an instance of * {@link de.flexiprovider.pqc.ecc.ECCKeyGenParameterSpec}. */ public void initialize(AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { this.random = (random != null) ? random : Registry.getSecureRandom(); if (params == null) { initializeDefault(); return; } if (!(params instanceof ECCKeyGenParameterSpec)) { throw new InvalidAlgorithmParameterException("unsupported type"); } ECCKeyGenParameterSpec mParams = (ECCKeyGenParameterSpec) params; m = mParams.getM(); n = mParams.getN(); t = mParams.getT(); fieldPoly = mParams.getFieldPoly(); initialized = true; } /** * Initialize the key pair generator with the given key size and source of * randomness. * * @param keySize * the length of the code * @param random * the source of randomness */ public void initialize(int keySize, SecureRandom random) { try { ECCKeyGenParameterSpec paramSpec = new ECCKeyGenParameterSpec(keySize); initialize(paramSpec, random); } catch (InvalidParameterException e) { throw new RuntimeException("invalid key size"); } catch (InvalidAlgorithmParameterException e) { // the parameters are correct and must be accepted throw new RuntimeException("internal error"); } } /** * Default initialization of the key pair generator. */ private void initializeDefault() { try { ECCKeyGenParameterSpec paramSpec = new ECCKeyGenParameterSpec(); initialize(paramSpec, Registry.getSecureRandom()); } catch (InvalidAlgorithmParameterException e) { // the parameters are correct and must be accepted throw new RuntimeException("internal error"); } } /** * Generate a McEliece key pair. The public key is an instance of * {@link McEliecePublicKey}, the private key is an instance of * {@link McEliecePrivateKey}. * * @return the McEliece key pair * @see McEliecePublicKey * @see McEliecePrivateKey */ public KeyPair genKeyPair() { if (!initialized) { initializeDefault(); } // finite field GF(2^m) GF2mField field = new GF2mField(m, fieldPoly); // irreducible Goppa polynomial PolynomialGF2mSmallM gp = new PolynomialGF2mSmallM(field, t, PolynomialGF2mSmallM.RANDOM_IRREDUCIBLE_POLYNOMIAL, random); PolynomialRingGF2m ring = new PolynomialRingGF2m(field, gp); // matrix for computing square roots in (GF(2^m))^t PolynomialGF2mSmallM[] qInv = ring.getSquareRootMatrix(); // generate canonical check matrix GF2Matrix h = GoppaCode.createCanonicalCheckMatrix(field, gp); // compute short systematic form of check matrix MaMaPe mmp = GoppaCode.computeSystematicForm(h, random); GF2Matrix shortH = mmp.getSecondMatrix(); Permutation p = mmp.getPermutation(); // compute short systematic form of generator matrix GF2Matrix shortG = (GF2Matrix) shortH.computeTranspose(); // obtain number of rows of G (= dimension of the code) int k = shortG.getNumRows(); // generate keys McElieceCCA2PublicKey pubKey = new McElieceCCA2PublicKey(n, t, shortG); McElieceCCA2PrivateKey privKey = new McElieceCCA2PrivateKey(n, k, field, gp, p, h, qInv); // return key pair return new KeyPair(pubKey, privKey); } }
gpl-3.0
jcespinosa/EcoGlasses
gui.py
11927
#!/usr/bin/python ######################################################################## # 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/>. # ######################################################################## import cv2 as cv import numpy as np from cPickle import dumps, loads from time import sleep from Tkinter import * from traceback import print_exc from threading import Thread from PIL import Image, ImageTk from sys import argv from Queue import Queue from MySocket import ClientSocket CAM_ID = 0 # ====================================================================== # App Class # # Builds and draws all the GUI # Load each processed frame # # ====================================================================== class App(Frame): def __init__(self, parent, width, height): Frame.__init__(self, parent) parent.wm_protocol('WM_DELETE_WINDOW', self.onClose) self.windowSize = {'width': width, 'height': height} self.parent = parent self.buildUI() self.queue = Queue() self.processQueue() return def onClose(self): print '[!] Terminating App thread, destroying GUI.' detect.stop = True capture.stop = True self.parent.destroy() self.parent.quit() def buildUI(self): print '[>] Creating UI ...' if(debug): print '[!] Debug mode.' self.parent.title('EcoGlasses debug window') self.menubar = Menu(self.parent) self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label='Reset', command=detect.reset) self.filemenu.add_command(label='Close', command=self.onClose) self.menubar.add_cascade(label='Menu 1', menu=self.filemenu) self.parent.config(menu=self.menubar) self.outlineColor, self.canvasTextColor, self.backgroundColor = 'black', 'black', 'white' self.message = 'Esperando conexion con servidor ...' self.canvasText = '' self.text = 'Waiting for server data ...' if(debug): self.canvasFrame = Frame(self.parent)#.grid(row=0, column=0) self.canvasContainer = LabelFrame(self.canvasFrame, text="Capture", width=self.windowSize['width'], height=self.windowSize['height']) self.videoCanvas = Canvas(self.canvasContainer, width=self.windowSize['width'], height=self.windowSize['height'], bg=self.backgroundColor) self.videoCanvas.pack() self.canvasFrame.pack(side=LEFT) self.canvasContainer.pack(expand="yes", padx=5, pady=5) self.infoFrame = Frame(self.parent)#.grid(row=0, column=1) self.infoContainer = LabelFrame(self.infoFrame, text="Product information", padx=5, pady=5, width=self.windowSize['width']/2, height=self.windowSize['height']) self.infoText = Text(self.infoContainer, width=50, height=29, background='white') self.resetButton = Button(self.infoFrame, text="Reset detection", command=detect.reset) self.infoFrame.pack(side=LEFT) self.infoContainer.pack(expand="yes", padx=5, pady=5) self.infoText.pack() self.resetButton.pack() self.infoText.insert(INSERT, self.text) self.canvasFontSize = 20 else: self.canvasFrame = Frame(self.parent)#.grid(row=0, column=0) self.videoCanvas = Canvas(self.canvasFrame, width=self.windowSize['width'], height=self.windowSize['height'], bg=self.backgroundColor) self.videoCanvas.pack(expand="yes") self.canvasFrame.pack(side=LEFT) self.canvasFontSize = 45 print '[O] UI ready.' return def updateWidgets(self): if(debug): self.infoText.delete('1.0', END) self.infoText.insert(INSERT, self.text) else: if(feedback): pass else: self.videoCanvas.delete('all') pass x1, y1, h, w = calculateROI((self.windowSize['height'], self.windowSize['width'], None)) x2, y2 = x1 + w, y1 + h self.videoCanvas.create_rectangle(x1, y1, x2, y2, width=8.0, dash=(10,15), outline=self.outlineColor) self.videoCanvas.create_text(self.windowSize['width']/2, (self.windowSize['height']/2)+250, font=("Ubuntu", self.canvasFontSize), fill=self.canvasTextColor, text=self.message) self.videoCanvas.create_text(self.windowSize['width']/2, (self.windowSize['height']/2), font=("Ubuntu", self.canvasFontSize), fill=self.canvasTextColor, text=self.canvasText) self.videoCanvas.configure(bg=self.backgroundColor) return def loadFrame(self, frame): w, h = self.windowSize['width'], self.windowSize['height'] try: self.frame = ImageTk.PhotoImage(frame) self.videoCanvas.delete('all') self.videoCanvas.configure(width=w, height=h) self.videoCanvas.create_image(w/2, h/2, image=self.frame) except Exception, e: print e return def processTask(self, task): t = task['task'] if(t == 0): self.loadFrame(task['frame']); elif(t == 1): self.outlineColor = task['color1'] self.backgroundColor = task['color2'] elif(t == 2): self.message = task['message'] self.text = task['text'] self.canvasText = task['text'] else: pass self.updateWidgets() return def processQueue(self): if(self.queue.qsize() > 0): task = self.queue.get(0) self.processTask(task) #print self.queue.qsize() self.parent.after(50, self.processQueue) return # ====================================================================== # Client # # # ====================================================================== class Client(): def __init__(self): self.socket = ClientSocket() self.socket.connect() def encode(self, message): message = dumps(message, 2) return message def decode(self, message): try: message = loads(message) except Exception, e: message = None print "[X] Error decoding the message from the server %s." % (e) return message def send(self, message): message = self.encode(message) self.socket.send(message) return def receive(self): message = self.socket.receive() if(message): message = self.decode(message) else: message = None return message def close(self): print '\n[O] Closing connection with the server.\n' message = self.encode('CLOSE') self.socket.send(message) self.socket.close() return # ====================================================================== # Detection # # # ====================================================================== class Detection(Thread): def __init__(self): Thread.__init__(self) self.frame = None self.state = None self.stop = False def reset(self): self.state = 'idle' #print "Reset" return def setFrame(self, frame): if(self.state == 'idle'): self.frame = frame self.state = 'busy' return def processResult(self, res): if(res): state = int(res['state']) if(state == 0): app.queue.put({'task': 1, 'color1': 'black', 'color2': 'white'}) app.queue.put({'task': 2, 'message': 'Nada se ha detectado.', 'text': ''}) self.reset() elif(state == 1): text = "Marca: %s\nProducto: %s\nHecho en: %s\nCodigo: %s\n"%(res['data']['name'],res['data']['product'],res['data']['madein'],res['data']['barcode']) message = "Se detecto %s"%(res['data']['name']) app.queue.put({'task': 1, 'color1': 'green', 'color2': 'green'}) app.queue.put({'task': 2, 'message': message, 'text': text}) else: app.queue.put({'task': 1, 'color1': 'red', 'color2': 'red'}) app.queue.put({'task': 2, 'message': 'Ocurrio un error en la deteccion.', 'text': 'Error'}) self.reset() return def sendFrame(self, s): if(self.frame is not None): print '[>] Sending frame to detection server ...' s.send(self.frame) self.frame = None result = s.receive() self.processResult(result) return def run(self): self.state = 'idle' s = Client() while(not self.stop): self.sendFrame(s) sleep(1.5) s.close() print '[!] Terminating Detection thread.' return # ====================================================================== # Capture Class # # Reads a frame from webcam # Convert the frames from OpenCV to PIL images # # ====================================================================== class Capture(Thread): def __init__(self): Thread.__init__(self) self.capture = None self.frame = None self.cvFrame = None self.roi = None self.stop = False return def getFrame(self): cameraIndex = CAM_ID c = cv.waitKey(100) if(c == 'n'): cameraIndex += 1 self.capture = cv.VideoCapture(cameraIndex) frame = None if not self.capture: cameraIndex = 0 self.capture = cv.VideoCapture(cameraIndex) frame = None dump, self.cvFrame = self.capture.read() #self.cvFrame = cv.flip(self.cvFrame, 0) # Uncomment to flip the frame vertically #self.cvFrame = cv.flip(self.cvFrame, 1) # Uncomment to flip the frame horizonally self.frame = cv2pil(self.cvFrame) self.roi = getROI(self.cvFrame) return def run(self): self.capture = cv.VideoCapture(CAM_ID) while(not self.stop): self.getFrame() if(self.frame): detect.setFrame(self.roi) app.queue.put({'task': 0, 'frame': self.frame}) sleep(0.1) print '[!] Terminating Capture thread.' return # ====================================================================== # cv2pil # # Convert the frames from OpenCV to PIL images # # ====================================================================== def cv2pil(frame): h, w, d = frame.shape frame = Image.fromstring('RGB', (w,h), frame.tostring(), 'raw', 'BGR') return frame # ====================================================================== # calculateROI # # TODO # # ====================================================================== def calculateROI(im): fh, fw, fd = im.shape if(isinstance(im, np.ndarray)) else im bh, bw = (350, 350) x = (fw - bw)/2 y = (fh - bh)/2 return x, y, bh, bw # ====================================================================== # getROI # # TODO # # ====================================================================== def getROI(im): x, y, bh, bw = calculateROI(im) roi = im[y:y+bh, x:x+bw] return roi # ====================================================================== # Main # ====================================================================== if(__name__ == '__main__'): debug, feedback = False, False if(len(argv) > 1): debug = True if(argv[1] == '-d') else False feedback = True if(argv[1] == '-f') else False root = Tk() w, h = (640, 480) if(not debug): w, h = root.winfo_screenwidth(), root.winfo_screenheight() root.overrideredirect(1) root.geometry("%dx%d+0+0" % (w, h)) root.focus_set() # <-- move focus to this widget root.bind("<Key>", lambda e: e.widget.quit()) detect = Detection() detect.start() app = App(root, w, h) capture = Capture() capture.start() root.mainloop()
gpl-3.0
pklaus/avrnetio
example.readOutTemperatures.py
2448
#!/usr/bin/env python # -*- encoding: UTF8 -*- # Author: Philipp Klaus, philipp.l.klaus AT web.de # This file is part of avrnetio. # # avrnetio 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. # # avrnetio 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 avrnetio. If not, see <http://www.gnu.org/licenses/>. # example how to use the avrnetio class ## import the avrnetio class: import avrnetio ## for debugging (set debug mark with pdb.set_trace() ) import pdb ## for sys.exit(1) import sys ## for NTC calculations import electronics ## for ConfigParser.RawConfigParser() import ConfigParser CONFIGURATION_FILE = "connection.cfg" def main(): config = ConfigParser.ConfigParser() try: if config.read(CONFIGURATION_FILE) == []: raise Exception() except: print "error: please make sure you adopted the configuration file:", CONFIGURATION_FILE sys.exit(2) try: host = config.get('avrnetio1', 'host') refVoltage = float(config.get('avrnetio1', 'reference_voltage')) except: print "error: please make sure your configuration file", CONFIGURATION_FILE, "contains the section", '"avrnetio1"', 'with the entry', '"host" and "reference_voltage" (a floating point value).' sys.exit(2) try: netio = avrnetio.Avrnetio(host) netio.set_ref_ep(refVoltage) except StandardError: print("could not connect") sys.exit(1) ntc_voltage = netio.get_adcs_as_volts()[4] netio = None temperature = electronics.Ntc(4700.0,25.0+273,3580.0) temperature.Uvcc = refVoltage # print response print "\n--------- successfully queried the AVR-NET-IO with ethersex commands ---------" print "NTC voltage: %.3f V" % (ntc_voltage) print "temperature: %.1f °C" % (temperature.ntc_potential_to_temp(ntc_voltage)-273) print "---------------------------------------------------------------- \n" if __name__ == '__main__': main()
gpl-3.0
xGamers665/tera-emu
com.tera.gapi.npc/src/main/java/com/tera/gapi/npc/intercept/NpcLoadPoint.java
1073
/** * This file is part of tera-api. * * tera-api 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. * tera-api 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 tera-api. If not, see <http://www.gnu.org/licenses/>. */ package com.tera.gapi.npc.intercept; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marks point at which Npc object will be created * * @author ATracer * @since 0.1.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface NpcLoadPoint { }
gpl-3.0
alessandrolanghi/mit
src/providers/impianto.ts
4553
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { IImpianto } from '../models/impianto'; import { IAnagrafica, Anagrafica } from '../models/anagrafica'; import { BackendService } from './backend'; import { AuthService } from './auth'; @Injectable() export class ImpiantoService { constructor(private backSrv: BackendService, private auth: AuthService) { } private creaAnagraficaVuota(): IAnagrafica { let anagrafica = new Anagrafica(); anagrafica.id = '0'; anagrafica.cognome = '(non definito)'; return anagrafica; } getDettagliImpianto(id): Observable<IImpianto> { return new Observable<IImpianto> ( observer => { this.backSrv.object('impianti/' + this.auth.utente.azienda + '/' + id, { preserveSnapshot: true }).subscribe( risposta => { let impianto: IImpianto; impianto = risposta.val(); impianto.id = risposta.key; impianto.anagrafiche = []; if(risposta.val().anagrafiche) { for(let anagrafica in risposta.val().anagrafiche) { this.backSrv.object('anagrafiche/' + this.auth.utente.azienda, { preserveSnapshot: true }).$ref.child(anagrafica).once( 'value', successo => { let anagrafica: IAnagrafica; anagrafica = successo.val(); anagrafica.id = successo.key; impianto.anagrafiche.push(anagrafica); }, errore => { impianto.anagrafiche.push(this.creaAnagraficaVuota()); } ); } } else { impianto.anagrafiche.push(this.creaAnagraficaVuota()); } return observer.next(impianto); }); } ); } getElencoImpianti(query: string = ''): Observable<Array<IImpianto>> { return new Observable<Array<IImpianto>>( observer => { let impiantiArray: Array<IImpianto> = [] this.backSrv.list('impianti/' + this.auth.utente.azienda, { preserveSnapshot: true }).$ref.on("child_added", (child) => { let tmp = child.val(); let impianto: IImpianto; impianto = child.val(); impianto.id = child.key; impianto.anagrafiche = []; if(tmp.anagrafiche) { for(let anagrafica in tmp.anagrafiche) { this.backSrv.object('anagrafiche/' + this.auth.utente.azienda, { preserveSnapshot: true }).$ref.child(anagrafica).once( 'value', successo => { let anagrafica: IAnagrafica; anagrafica = successo.val(); anagrafica.id = successo.key; impianto.anagrafiche.push(anagrafica); impiantiArray.push(impianto); impiantiArray = this.ordinaElenco(impiantiArray); }, errore => { impianto.anagrafiche.push(this.creaAnagraficaVuota()); impiantiArray.push(impianto); impiantiArray = this.ordinaElenco(impiantiArray); } ); } } else { impianto.anagrafiche.push(this.creaAnagraficaVuota()); impiantiArray.push(impianto); impiantiArray = this.ordinaElenco(impiantiArray); } }); return observer.next(impiantiArray); } ); } private ordinaElenco(impianti: Array<IImpianto>) { return impianti.sort((a: IImpianto, b: IImpianto) => { return +(a.anagrafiche[0].cognome > b.anagrafiche[0].cognome); }); } }
gpl-3.0
robwarm/gpaw-symm
gpaw/factory.py
3562
import optparse from ase.units import Bohr, Hartree from ase.tasks.calcfactory import CalculatorFactory, str2dict from gpaw.utilities.gpts import get_number_of_grid_points from gpaw.wavefunctions.pw import PW class GPAWFactory(CalculatorFactory): def __init__(self, show_text_output=False, write_gpw_file=None, **kwargs): self.show_text_output = show_text_output # this is used as write(mode=write_gpw_file) # so it should be called rather write_gpw_mode? if write_gpw_file is not None: assert isinstance(write_gpw_file, str) self.write_gpw_file = write_gpw_file CalculatorFactory.__init__(self, None, 'GPAW', **kwargs) def __call__(self, name, atoms): kpts = self.calculate_kpts(atoms) kwargs = self.kwargs.copy() # modify a copy if (not atoms.pbc.any() and len(atoms) == 1 and atoms.get_initial_magnetic_moments().any() and 'hund' not in kwargs): kwargs['hund'] = True if atoms.pbc.any() and 'gpts' not in kwargs: # Use fixed number of gpts: h = kwargs.get('h') if h is not None: h /= Bohr cell_cv = atoms.cell / Bohr mode = kwargs.get('mode') if mode == 'pw': mode = PW() gpts = get_number_of_grid_points(cell_cv, h, mode, kwargs.get('realspace')) kwargs['h'] = None kwargs['gpts'] = gpts if isinstance(mode, PW): kwargs['mode'] = PW(mode.ecut * Hartree, mode.fftwflags, atoms.cell) if self.show_text_output: txt = '-' else: txt = name + '.txt' if self.write_gpw_file is not None: from gpaw.hooks import hooks hooks['converged'] = ( lambda calc, name=name + '.gpw', mode=self.write_gpw_file: calc.write(name, mode)) from gpaw import GPAW return GPAW(txt=txt, kpts=kpts, **kwargs) def add_options(self, parser): CalculatorFactory.add_options(self, parser) calc = optparse.OptionGroup(parser, 'GPAW') calc.add_option('--parameter-file', metavar='FILE', help='Read GPAW parameters from file.') calc.add_option('-S', '--show-text-output', action='store_true', help='Send text output from calculation to ' + 'standard out.') calc.add_option('-W', '--write-gpw-file', metavar='MODE', help='Write gpw file.') parser.add_option_group(calc) def parse(self, opts, args): if opts.parameters: # Import stuff that eval() may need to know: from gpaw.wavefunctions.pw import PW from gpaw.occupations import FermiDirac, MethfesselPaxton from gpaw.mixer import Mixer, MixerSum from gpaw.poisson import PoissonSolver from gpaw.eigensolvers import RMM_DIIS self.kwargs.update(str2dict(opts.parameters, locals())) opts.parameters = None CalculatorFactory.parse(self, opts, args) self.show_text_output = opts.show_text_output self.write_gpw_file = opts.write_gpw_file if opts.parameter_file: self.kwargs.update(eval(open(opts.parameter_file).read()))
gpl-3.0
xingh/bsn-goldparser
bsn.GoldParser.Test/Semantic/TestUnicode.cs
1572
using System; using System.IO; using System.Text; using Xunit; using bsn.GoldParser.Grammar; namespace bsn.GoldParser.Semantic { public class TestUnicode { public sealed class TestParser { public static bool Parse(string filePath) { using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { return Parse(stream); } } public static bool Parse(Stream stream) { CompiledGrammar grammar = CompiledGrammar.Load(typeof(TestUnicode), "TestUnicode.egt"); // embedded resource SemanticTypeActions<TestToken> actions = new SemanticTypeActions<TestToken>(grammar); actions.Initialize(true); using (StreamReader reader = new StreamReader(stream)) // defaults to UTF-8 { SemanticProcessor<TestToken> processor = new SemanticProcessor<TestToken>(reader, actions); ParseMessage parseMessage = processor.ParseAll(); return (parseMessage == ParseMessage.Accept); } } } [Terminal("(EOF)")] [Terminal("(Error)")] [Terminal("(Whitespace)")] [Terminal("Identifier")] [Terminal("från")] [Terminal("välj")] [Terminal("Åäö")] public class TestToken: SemanticToken { public TestToken() {} [Rule("<Select> ::= ~välj Åäö från <Källa>")] public TestToken(TestToken t1, TestToken t2, TestToken t3) {} } [Fact] public void TestSemanticMappingWithUnicodeStrings() { string source = "välj ä från dummy"; Assert.True(TestParser.Parse(new MemoryStream(Encoding.UTF8.GetBytes(source)))); } } }
gpl-3.0
igemsoftware2017/USTC-Software-2017
tests/core/plugins/expected/apps.py
238
from biohub.core.plugins import PluginConfig class TestConfig(PluginConfig): name = 'tests.core.plugins.test' title = '' author = '' description = '' js_url = '' # the URL of `plugin.js`, you may leave it to blank
gpl-3.0
TeoV/cgrates
console/resources_allocate.go
1907
/* Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments Copyright (C) ITsysCOM GmbH 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 console import ( "time" "github.com/cgrates/cgrates/utils" ) func init() { c := &CmdResourceAllocate{ name: "resources_allocate", rpcMethod: utils.ResourceSv1AllocateResources, rpcParams: &utils.ArgRSv1ResourceUsage{}, } commands[c.Name()] = c c.CommandExecuter = &CommandExecuter{c} } // Commander implementation type CmdResourceAllocate struct { name string rpcMethod string rpcParams *utils.ArgRSv1ResourceUsage *CommandExecuter } func (self *CmdResourceAllocate) Name() string { return self.name } func (self *CmdResourceAllocate) RpcMethod() string { return self.rpcMethod } func (self *CmdResourceAllocate) RpcParams(reset bool) interface{} { if reset || self.rpcParams == nil { self.rpcParams = &utils.ArgRSv1ResourceUsage{ CGREvent: new(utils.CGREvent), } } return self.rpcParams } func (self *CmdResourceAllocate) PostprocessRpcParams() error { if self.rpcParams != nil && self.rpcParams.CGREvent != nil && self.rpcParams.CGREvent.Time == nil { self.rpcParams.CGREvent.Time = utils.TimePointer(time.Now()) } return nil } func (self *CmdResourceAllocate) RpcResult() interface{} { var atr string return &atr }
gpl-3.0
welldooder64/TheBananaKingdom
bk_common/net/welldooder64/bananakingdom/creativetab/CreativeTabBK.java
664
package net.welldooder64.bananakingdom.creativetab; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.creativetab.CreativeTabs; import net.welldooder64.bananakingdom.lib.ItemIDs; public class CreativeTabBK extends CreativeTabs{ public CreativeTabBK(int tabID) { super(tabID, net.welldooder64.bananakingdom.lib.Reference.MOD_ID); } @Override @SideOnly(Side.CLIENT) public int getTabIconItemIndex() { return ItemIDs.BananaID; } @Override @SideOnly(Side.CLIENT) public String getTranslatedTabLabel() { return "The Banana Kingdom"; } }
gpl-3.0
zuonima/sql-utils
src/main/java/com/alibaba/druid/sql/parser/SQLDDLParser.java
1473
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.sql.parser; import com.alibaba.druid.sql.ast.statement.SQLTableConstraint; public class SQLDDLParser extends SQLStatementParser { public SQLDDLParser(String sql){ super(sql); } public SQLDDLParser(SQLExprParser exprParser){ super(exprParser); } protected SQLTableConstraint parseConstraint() { if (lexer.token == Token.CONSTRAINT) { lexer.nextToken(); } if (lexer.token == Token.IDENTIFIER) { this.exprParser.name(); throw new ParserException("TODO. " + lexer.info()); } if (lexer.token == Token.PRIMARY) { lexer.nextToken(); accept(Token.KEY); throw new ParserException("TODO. " + lexer.info()); } throw new ParserException("TODO " + lexer.info()); } }
gpl-3.0
AndyMoreland/cs-244-project
src/main/java/gameengine/ChineseCheckersStateMachine.java
2452
package gameengine; import com.google.common.base.Optional; import com.google.common.collect.Lists; import common.CryptoUtil; import common.Digest; import common.StateMachineCheckpointListener; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import statemachine.InvalidStateMachineOperationException; import statemachine.Operation; import statemachine.StateMachine; import java.util.List; /** * Created by andrew on 11/30/14. */ public class ChineseCheckersStateMachine implements StateMachine<ChineseCheckersState, Operation<ChineseCheckersState>> { private static Logger LOG = LogManager.getLogger(ChineseCheckersStateMachine.class); private ChineseCheckersState state; private int numOperationsApplied; private static final int CHECKPOINT_INTERVAL = 100; private int lastCheckpointed; private Optional<Digest> checkpointDigest; private List<StateMachineCheckpointListener> listeners; public ChineseCheckersStateMachine(ChineseCheckersState state) { this.state = state; this.numOperationsApplied = 0; this.lastCheckpointed = -1; // never checkpointed this.checkpointDigest = Optional.absent(); this.listeners = Lists.newArrayList(); } @Override synchronized public void applyOperation(Operation<ChineseCheckersState> op) throws InvalidStateMachineOperationException { LOG.info("Applying operation: " + op); if (!op.isValid(this.getState())) { throw new InvalidStateMachineOperationException(); } op.apply(this.getState()); numOperationsApplied++; // checkpointing currently blocks application of moves if ((numOperationsApplied % CHECKPOINT_INTERVAL) == 0) { LOG.info("Checkpointing after operation " + numOperationsApplied); checkpointDigest = Optional.of(CryptoUtil.computeDigest(this)); lastCheckpointed = numOperationsApplied; for (StateMachineCheckpointListener listener : listeners) { listener.notifyOnCheckpointed(lastCheckpointed, checkpointDigest.get()); } } } synchronized public ChineseCheckersState getState() { return state; } synchronized public void setState(ChineseCheckersState newState) { state = newState; } @Override public void addCheckpointListener(StateMachineCheckpointListener listener) { listeners.add(listener); } }
gpl-3.0
a-v-k/astrid
src/main/java/org/tasks/injection/ContentProviderModule.java
100
package org.tasks.injection; import dagger.Module; @Module public class ContentProviderModule { }
gpl-3.0
sofa/angular-sofa-full-page-view
src/sofaFullPageViewDirective.js
2367
angular.module('sofa.fullPageView', ['sofa-full-page-view.tpl.html']) .directive('sofaFullPageView', function () { 'use strict'; return { restrict: 'E', controller: function () { }, link: function ($scope, $element, attrs) { var onOpen = $scope.$eval(attrs.onOpen); var onClose = $scope.$eval(attrs.onClose); $scope.openFullPageView = function (e) { e.preventDefault(); if (angular.isFunction(onOpen)) { onOpen($scope); } $scope.active = true; }; $scope.closeFullPageView = function (e) { e.preventDefault(); if (angular.isFunction(onClose)) { onClose($scope); } $scope.active = false; }; $scope.$on('$destroy', function () { $scope.cloneElement.remove(); }); } }; }) .directive('sofaFullPageViewClone', ['$window', function ($window) { 'use strict'; return { restrict: 'E', require: '^sofaFullPageView', replace: true, transclude: true, templateUrl: 'sofa-full-page-view.tpl.html', compile: function () { return function ($scope, $element) { angular.element($window.document.body).prepend($element); $scope.active = false; $scope.cloneElement = $element; $element.css('height', $window.innerHeight + 'px'); // orientationchange will not work for android, so we use the resize event $window.addEventListener('resize', function () { $element.css('height', $window.innerHeight + 'px'); }); }; } }; }]) .directive('sofaFullPageViewOriginal', function () { 'use strict'; return { restrict: 'E', require: '^sofaFullPageView', link: function ($scope, $element) { $scope.originalElement = $element; } }; });
gpl-3.0
nortikin/sverchok
nodes/field/scalar_field_formula.py
7301
import numpy as np import bpy from bpy.props import EnumProperty, BoolProperty, StringProperty from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import updateNode, zip_long_repeat, match_long_repeat from sverchok.utils.modules.eval_formula import get_variables, sv_compile, safe_eval_compiled from sverchok.utils.script_importhelper import safe_names_np from sverchok.utils.math import ( to_cylindrical, to_spherical, to_cylindrical_np, to_spherical_np, coordinate_modes ) from sverchok.utils.field.scalar import SvScalarFieldLambda class SvScalarFieldFormulaNode(bpy.types.Node, SverchCustomTreeNode): """ Triggers: Scalar Field Formula Tooltip: Generate scalar field by formula """ bl_idname = 'SvExScalarFieldFormulaNode' bl_label = 'Scalar Field Formula' bl_icon = 'OUTLINER_OB_EMPTY' sv_icon = 'SV_SCALAR_FIELD' def on_update(self, context): self.adjust_sockets() updateNode(self, context) formula: StringProperty( name = "Formula", default = "x*x + y*y + z*z", update = on_update) input_mode : EnumProperty( name = "Coordinates", items = coordinate_modes, default = 'XYZ', update = updateNode) use_numpy_function : BoolProperty( name = "Vectorize", description = "Vectorize formula computations; disable this if you have troubles with some functions", default = True, update = updateNode) def sv_init(self, context): self.inputs.new('SvScalarFieldSocket', "Field") self.outputs.new('SvScalarFieldSocket', "Field") def draw_buttons(self, context, layout): layout.label(text="Input:") layout.prop(self, "input_mode", expand=True) layout.prop(self, "formula", text="") def draw_buttons_ext(self, context, layout): self.draw_buttons(context, layout) layout.prop(self, 'use_numpy_function') def make_function(self, variables): compiled = sv_compile(self.formula) def carthesian(x, y, z, V): variables.update(dict(x=x, y=y, z=z, V=V)) r = safe_eval_compiled(compiled, variables) if not isinstance(r, np.ndarray): r = np.full_like(x, r) return r def cylindrical(x, y, z, V): rho, phi, z = to_cylindrical((x, y, z), mode='radians') variables.update(dict(rho=rho, phi=phi, z=z, V=V)) r = safe_eval_compiled(compiled, variables) if not isinstance(r, np.ndarray): r = np.full_like(x, r) return r def spherical(x, y, z, V): rho, phi, theta = to_spherical((x, y, z), mode='radians') variables.update(dict(rho=rho, phi=phi, theta=theta, V=V)) r = safe_eval_compiled(compiled, variables) if not isinstance(r, np.ndarray): r = np.full_like(x, r) return r if self.input_mode == 'XYZ': function = carthesian elif self.input_mode == 'CYL': function = cylindrical else: # SPH function = spherical return function def make_function_vector(self, variables): compiled = sv_compile(self.formula) def carthesian(x, y, z, V): variables.update(dict(x=x, y=y, z=z, V=V)) r = safe_eval_compiled(compiled, variables, allowed_names = safe_names_np) if not isinstance(r, np.ndarray): r = np.full_like(x, r) return r def cylindrical(x, y, z, V): rho, phi, z = to_cylindrical_np((x, y, z), mode='radians') variables.update(dict(rho=rho, phi=phi, z=z, V=V)) r = safe_eval_compiled(compiled, variables, allowed_names = safe_names_np) if not isinstance(r, np.ndarray): r = np.full_like(x, r) return r def spherical(x, y, z, V): rho, phi, theta = to_spherical_np((x, y, z), mode='radians') variables.update(dict(rho=rho, phi=phi, theta=theta, V=V)) r = safe_eval_compiled(compiled, variables, allowed_names = safe_names_np) if not isinstance(r, np.ndarray): r = np.full_like(x, r) return r if self.input_mode == 'XYZ': function = carthesian elif self.input_mode == 'CYL': function = cylindrical else: # SPH function = spherical return function def get_coordinate_variables(self): if self.input_mode == 'XYZ': return {'x', 'y', 'z', 'V'} elif self.input_mode == 'CYL': return {'rho', 'phi', 'z', 'V'} else: # SPH return {'rho', 'phi', 'theta', 'V'} def get_variables(self): variables = get_variables(self.formula) variables.difference_update(self.get_coordinate_variables()) return list(sorted(list(variables))) def adjust_sockets(self): variables = self.get_variables() for key in self.inputs.keys(): if key not in variables and key not in ['Field']: self.debug("Input {} not in variables {}, remove it".format(key, str(variables))) self.inputs.remove(self.inputs[key]) for v in variables: if v not in self.inputs: self.debug("Variable {} not in inputs {}, add it".format(v, str(self.inputs.keys()))) self.inputs.new('SvStringsSocket', v) def sv_update(self): if not self.formula: return self.adjust_sockets() def get_input(self): variables = self.get_variables() inputs = {} for var in variables: if var in self.inputs and self.inputs[var].is_linked: inputs[var] = self.inputs[var].sv_get() return inputs def process(self): if not any(socket.is_linked for socket in self.outputs): return fields_s = self.inputs['Field'].sv_get(default = [None]) var_names = self.get_variables() inputs = self.get_input() input_values = [inputs.get(name, [[0]]) for name in var_names] if var_names: parameters = match_long_repeat([fields_s] + input_values) else: parameters = [fields_s] fields_out = [] for field_in, *objects in zip(*parameters): if var_names: var_values_s = zip_long_repeat(*objects) else: var_values_s = [[]] for var_values in var_values_s: variables = dict(zip(var_names, var_values)) function = self.make_function(variables) if self.use_numpy_function: function_vector = self.make_function_vector(variables) else: function_vector = None new_field = SvScalarFieldLambda(function, variables, field_in, function_vector) fields_out.append(new_field) self.outputs['Field'].sv_set(fields_out) def register(): bpy.utils.register_class(SvScalarFieldFormulaNode) def unregister(): bpy.utils.unregister_class(SvScalarFieldFormulaNode)
gpl-3.0
sethten/MoDesserts
mcp50/src/minecraft/net/minecraft/src/Packet105UpdateProgressbar.java
1802
package net.minecraft.src; import java.io.*; public class Packet105UpdateProgressbar extends Packet { /** The id of the window that the progress bar is in. */ public int windowId; /** * Which of the progress bars that should be updated. (For furnaces, 0 = progress arrow, 1 = fire icon) */ public int progressBar; /** * The value of the progress bar. The maximum values vary depending on the progress bar. Presumably the values are * specified as in-game ticks. Some progress bar values increase, while others decrease. For furnaces, 0 is empty, * full progress arrow = about 180, full fire icon = about 250) */ public int progressBarValue; public Packet105UpdateProgressbar() { } /** * Passes this Packet on to the NetHandler for processing. */ public void processPacket(NetHandler par1NetHandler) { par1NetHandler.handleUpdateProgressbar(this); } /** * Abstract. Reads the raw packet data from the data stream. */ public void readPacketData(DataInputStream par1DataInputStream) throws IOException { windowId = par1DataInputStream.readByte(); progressBar = par1DataInputStream.readShort(); progressBarValue = par1DataInputStream.readShort(); } /** * Abstract. Writes the raw packet data to the data stream. */ public void writePacketData(DataOutputStream par1DataOutputStream) throws IOException { par1DataOutputStream.writeByte(windowId); par1DataOutputStream.writeShort(progressBar); par1DataOutputStream.writeShort(progressBarValue); } /** * Abstract. Return the size of the packet (not counting the header). */ public int getPacketSize() { return 5; } }
gpl-3.0
lordsergioinspa/FreeNOS
lib/libarch/intel/IntelMP.cpp
3336
/* * Copyright (C) 2015 Niek Linnenbank * * 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/>. */ #include <FreeNOS/System.h> #include <Log.h> #include "IntelConstant.h" #include "IntelMP.h" #include "IntelBoot.h" IntelMP::IntelMP(IntelAPIC & apic) : CoreManager() , m_apic(apic) { SystemInformation info; m_bios.map(MPAreaAddr, MPAreaSize); m_lastMemory.map(info.memorySize - MegaByte(1), MegaByte(1)); m_apic.getIO().map(IntelAPIC::IOBase, PAGESIZE); } IntelMP::MPConfig * IntelMP::scanMemory(Address addr) { MPFloat *mpf; // Look for the Multiprocessor configuration for (uint i = 0; i < MPAreaSize - sizeof(Address); i += sizeof(Address)) { mpf = (MPFloat *)(addr + i); if (mpf->signature == MPFloatSignature) return (MPConfig *) (mpf->configAddr - MPAreaAddr + addr); } return ZERO; } IntelMP::Result IntelMP::discover() { MPConfig *mpc = 0; MPEntry *entry; // Clear previous discoveries m_cores.clear(); // Try to find MPTable in the BIOS memory. mpc = scanMemory(m_bios.getBase()); // Retry in the last 1MB of physical memory if not found. if (!mpc) { mpc = scanMemory(m_lastMemory.getBase()); if (!mpc) { ERROR("MP header not found"); return NotFound; } } // Found config DEBUG("MP header found at " << (void *) mpc); DEBUG("Local APIC at " << (void *) mpc->apicAddr); entry = (MPEntry *)(mpc + 1); // Search for multiprocessor entries for (uint i = 0; i < mpc->count; i++) entry = parseEntry(entry); return Success; } IntelMP::Result IntelMP::boot(CoreInfo *info) { DEBUG("booting core" << info->coreId << " at " << (void *) info->memory.phys << " with kernel: " << info->kernelCommand); // Copy 16-bit realmode startup code VMCopy(SELF, API::Write, (Address) bootEntry16, MPEntryAddr, PAGESIZE); // Copy the CoreInfo structure VMCopy(SELF, API::Write, (Address) info, MPInfoAddr, sizeof(*info)); // Send inter-processor-interrupt to wakeup the processor if (m_apic.sendStartupIPI(info->coreId, MPEntryAddr) != IntController::Success) return IOError; // Wait until the core raises the 'booted' flag in CoreInfo while (1) { CoreInfo check; VMCopy(SELF, API::Read, (Address) &check, MPInfoAddr, sizeof(check)); if (check.booted) break; } return Success; } IntelMP::MPEntry * IntelMP::parseEntry(IntelMP::MPEntry *entry) { if (entry->type == MPEntryProc) { m_cores.append(entry->apicId); return entry + 1; } else return (MPEntry *) (((Address)(entry)) + 8); }
gpl-3.0
uprel/gisapp
admin/logindialog/js/Ext.ux.form.LoginDialog.js
17557
/** * Free and simple to use loginDialog for ExtJS 3.x * * @author Albert Varaksin (ExtJS 2.x) * @author Sumit Madan (ExtJS 3.x) * @license LGPLv3 http://www.opensource.org/licenses/lgpl-3.0.html * @version 1.0 beta, 07/12/2008 - ExtJS 2.x * @version 1.0, 05/03/2009 - ExtJS 3.x * @version 1.1, 07/18/2009 - ExtJS 3.x * * Uros : added extraparam, language value parameter, guest access, changelanguage, languagestore */ Ext.namespace('Ext.ux.form'); /** * Login dialog constructor * * @param {Object} config * @extends {Ext.util.Observable} */ Ext.ux.form.LoginDialog = function (config) { Ext.apply(this, config); // The CSS needed to style the dialog. var css = '.ux-auth-header-icon {background: url("' + this.basePath + '/small/locked.png") 0 4px no-repeat !important;}' + '.ux-auth-header {background:transparent url("' + this.basePath + '/large/lock.png") no-repeat center right;padding:10px;padding-right:45px;padding-bottom:1px;font-weight:bold;}' + '.ux-auth-login {background-image: url("' + this.basePath + '/medium/key.png") !important;}' + '.ux-auth-guest {background-image: url("' + this.basePath + '/medium/guest.png") !important;}' + '.ux-auth-close {background-image: url("' + this.basePath + '/medium/close.png") !important;}' + '.ux-auth-warning {background:url("' + this.basePath + '/small/warning.png") no-repeat center left; padding: 2px; padding-left:20px; font-weight:bold;}' + '.ux-auth-header .error {color:red;}' + '.ux-auth-form {padding:10px;}'; Ext.util.CSS.createStyleSheet(css, this._cssId); if (this.forceVirtualKeyboard) { this.enableVirtualKeyboard = true; } // LoginDialog events this.addEvents({ 'show': true, // when dialog is visible and rendered 'cancel': true, // When user cancelled the login 'success': true, // on succesfful login 'failure': true, // on failed login 'submit': true // about to submit the data }); Ext.ux.form.LoginDialog.superclass.constructor.call(this, config); // head info panel this._headPanel = new Ext.Panel({ baseCls: 'x-plain', html: this.message, cls: 'ux-auth-header', region: 'north', height: 60 }); // store username id to focus on window show event this._usernameId = Ext.id(); this._passwordId = Ext.id(); this._loginButtonId = Ext.id(); this._cancelButtonId = Ext.id(); this._rememberMeId = Ext.id(); // form panel this._formPanel = new Ext.form.FormPanel({ region: 'center', border: false, bodyStyle: "padding: 10px;", waitMsgTarget: true, labelWidth: 75, defaults: {width: 250}, items: [{ xtype: 'textfield', id: this._usernameId, name: this.usernameField, fieldLabel: this.usernameLabel, vtype: this.usernameVtype, validateOnBlur: false, allowBlank: false }, { xtype: 'textfield', inputType: 'password', id: this._passwordId, name: this.passwordField, fieldLabel: this.passwordLabel, vtype: this.passwordVtype, width: this.enableVirtualKeyboard == true ? 230 : 250, validateOnBlur: false, allowBlank: false, validationEvent: this.forceVirtualKeyboard == true ? 'blur' : 'keyup', enableKeyEvents: true, keyboardConfig: { showIcon: true, languageSelection: true }, plugins: this.enableVirtualKeyboard == true ? new Ext.ux.plugins.VirtualKeyboard() : null, listeners: { render: function () { this.capsWarningTooltip = new Ext.ToolTip({ target: this.id, anchor: 'top', width: 305, html: '<div class="ux-auth-warning">Caps Lock is On</div><br />' + '<div>Having Caps Lock on may cause you to enter your password incorrectly.</div><br />' + '<div>You should press Caps Lock to turn it off before entering your password.</div>' }); // disable to tooltip from showing on mouseover this.capsWarningTooltip.disable(); // When the password field fires the blur event, // the tootip gets enabled automatically (possibly an ExtJS bug). // Disable the tooltip everytime it gets enabled // The tooltip is shown explicitly by calling show() // and enabling/disabling does not affect the show() function. this.capsWarningTooltip.on('enable', function () { this.disable(); }); }, keypress: { fn: function (field, e) { if (this.forceVirtualKeyboard) { field.plugins.expand(); e.stopEvent(); } else { var charCode = e.getCharCode(); if ((e.shiftKey && charCode >= 97 && charCode <= 122) || (!e.shiftKey && charCode >= 65 && charCode <= 90)) { field.capsWarningTooltip.show(); } else { if (field.capsWarningTooltip.hidden == false) { field.capsWarningTooltip.hide(); } } } }, scope: this }, blur: function (field) { if (this.capsWarningTooltip.hidden == false) { this.capsWarningTooltip.hide(); } } } }, { xtype: 'box', autoEl: { html: '<div style="text-align: right; width: 330px;">' + '<a href="' + this.forgotPasswordLink + '" target="_blank">' + this.forgotPasswordLabel + '</a></div>' } }, { xtype: 'box', autoEl: 'div', height: 10 }, { xtype: 'iconcombo', hiddenName: this.languageField, fieldLabel: this.languageLabel, store: new Ext.data.SimpleStore({ fields: ['languageCode', 'languageName', 'countryFlag'], data: this.languageStore }), valueField: 'languageCode', value: this.language, displayField: 'languageName', iconClsField: 'countryFlag', triggerAction: 'all', editable: false, mode: 'local', listeners: { select: function (combo, record, index) { //TODO fix this, not OK, must be generic look extraparamvalue if (this.value != this.originalValue) { urlParams.lang = this.value; var startParams = Ext.urlEncode(urlParams); window.location.href = map + "?" + startParams; } } } }, // { // xtype: 'checkbox', // id: this._rememberMeId, // name: this.rememberMeField, // boxLabel: '&nbsp;' + this.rememberMeLabel, // width: 200, // listeners: { // render: function () { // Ext.get(Ext.DomQuery.select('#x-form-el-' + this._rememberMeId + ' input')).set({ // qtip: 'This is not recommended for shared computers.' // }); // // }, // scope: this // } // }, { //extraparameter xtype: 'hidden', name: this.extraParamField, value: this.extraParamValue }] }); // Default buttons and keys var buttons = [{ //id : this._guestButtonId, text: this.guestButton, iconCls: 'ux-auth-guest', width: 90, handler: this.guestSubmit, scale: 'medium', scope: this }, { id: this._loginButtonId, text: this.loginButton, iconCls: 'ux-auth-login', width: 90, handler: this.submit, scale: 'medium', scope: this }]; var keys = [{ key: [10, 13], handler: this.submit, scope: this }]; // if cancel button exists if (typeof this.cancelButton == 'string') { buttons.push({ id: this._cancelButtonId, text: this.cancelButton, iconCls: 'ux-auth-close', width: 90, handler: this.cancel, scale: 'medium', scope: this }); keys.push({ key: [27], handler: this.cancel, scope: this }); } // create the window this._window = new Ext.Window({ width: 370, height: 280, closable: false, resizable: false, draggable: true, modal: this.modal, iconCls: 'ux-auth-header-icon', title: this.title, layout: 'border', bodyStyle: 'padding:5px;', buttons: buttons, keys: keys, items: [this._headPanel, this._formPanel], shadow: false }); // when window is visible set focus to the username field // and fire "show" event this._window.on('show', function () { Ext.getCmp(this._usernameId).focus(true, 500); Ext.getCmp(this._passwordId).setRawValue(''); this.fireEvent('show', this); }, this); }; // Extend the Observable class Ext.extend(Ext.ux.form.LoginDialog, Ext.util.Observable, { /** * LoginDialog window title * * @type {String} */ title: 'Login', /** * The message on the LoginDialog * * @type {String} */ message: 'Access to this location is restricted to authorized users only.' + '<br />Please type your username and password.', /** * When login failed and no server message sent * * @type {String} */ failMessage: 'Unable to log in', /** * When submitting the login details * * @type {String} */ waitMessage: 'Please wait...', /** * The login button text * * @type {String} */ loginButton: 'Login', guestButton: 'Guest', /** * Cancel button * * @type {String} */ cancelButton: null, /** * Username field label * * @type {String} */ usernameLabel: 'Username', /** * Username field name * * @type {String} */ usernameField: 'username', /** * Username validation * * @type {String} */ usernameVtype: 'alphanum', /** * Password field label * * @type {String} */ passwordLabel: 'Password', /** * Password field name * * @type {String} */ passwordField: 'password', /** * Password field validation * * @type {String} */ passwordVtype: 'alphanum', /** * Language field label * * @type {String} */ languageLabel: 'Language', /** * Language field name * * @type {String} */ languageField: 'lang', /** * Selected language (2 letter code) * * @type {String} */ language: 'en', /** * Available languages * */ languageStore: [ ['en', 'English', 'ux-flag-en'] ], /** * RememberMe field label * * @type {String} */ rememberMeLabel: 'Remember me on this computer', /** * RememberMe field name * * @type {String} */ rememberMeField: 'rememberme', /** * ExtraParam field name * * @type {String} */ extraParamField: 'extra', /** * ExtraParam field value * * @type {String} */ extraParamValue: 'extravalue', /** * Forgot Password field label * * @type {String} */ forgotPasswordLabel: 'Forgot Password?', /** * Enable Virtual Keyboard for password * * @type {Bool} */ enableVirtualKeyboard: false, /** * Force Virtual Keyboard for password entry * If true, also sets enableVirtualKeyboard property to true * * @type {Bool} */ forceVirtualKeyboard: false, /** * encrypt password using SHA1 * * @type {Bool} */ encrypt: false, /** * Salt prepended to password, before encryption * If encrypt property is false, salt is not used * * @type {String} */ salt: '', /** * Forgot Password hyperlink * * @type {String} */ forgotPasswordLink: 'about:blank', /** * Request url * * @type {String} */ url: '/auth/login', /** * Path to images * * @type {String} */ basePath: '/', /** * Form submit method * * @type {String} */ method: 'post', /** * Open modal window * * @type {Bool} */ modal: false, /** * CSS identifier * * @type {String} */ _cssId: 'ux-LoginDialog-css', /** * Head info panel * * @type {Ext.Panel} */ _headPanel: null, /** * Form panel * * @type {Ext.form.FormPanel} */ _formPanel: null, /** * The window object * * @type {Ext.Window} */ _window: null, /** * Set the LoginDialog message * * @param {String} msg */ setMessage: function (msg) { this._headPanel.body.update(msg); }, /** * Show the LoginDialog * * @param {Ext.Element} el */ show: function (el) { this._window.show(el); }, /** * Hide the LoginDialog */ hide: function () { this._window.hide() }, /** * Hide and cleanup the LoginDialog */ destroy: function () { this._window.hide(); this.purgeListeners(); Ext.util.CSS.removeStyleSheet(this._cssId); var self = this; delete self; }, /** * Cancel the login (closes the dialog window) */ cancel: function () { if (this.fireEvent('cancel', this)) { this.hide(); } }, guestSubmit: function () { var form = this._formPanel.getForm(); form.setValues({ user_name: "guest", user_password: "guest" }); this.submit(); }, /** * Submit login details to the server */ submit: function () { var form = this._formPanel.getForm(); if (form.isValid()) { Ext.getCmp(this._loginButtonId).disable(); if (Ext.getCmp(this._cancelButtonId)) { Ext.getCmp(this._cancelButtonId).disable(); } if (this.encrypt) { Ext.getCmp(this._passwordId).setRawValue( Ext.ux.Crypto.SHA1.hash(this.salt + Ext.getCmp(this._passwordId).getValue()) ); } if (this.fireEvent('submit', this, form.getValues())) { this.setMessage(this.message); form.submit({ url: this.url, method: this.method, waitMsg: this.waitMessage, success: this.onSuccess, failure: this.onFailure, scope: this }); } } }, /** * On success * * @param {Ext.form.BasicForm} form * @param {Ext.form.Action} action */ onSuccess: function (form, action) { if (this.fireEvent('success', this, action)) { // enable buttons Ext.getCmp(this._loginButtonId).enable(); if (Ext.getCmp(this._cancelButtonId)) { Ext.getCmp(this._cancelButtonId).enable(); } this.hide(); } }, /** * On failures * * @param {Ext.form.BasicForm} form * @param {Ext.form.Action} action */ onFailure: function (form, action) { // enable buttons Ext.getCmp(this._loginButtonId).enable(); if (Ext.getCmp(this._cancelButtonId)) { Ext.getCmp(this._cancelButtonId).enable(); } if (this.encrypt) { Ext.getCmp(this._passwordId).setRawValue(''); } Ext.getCmp(this._passwordId).focus(true); var msg = ''; if (action.result && action.result.message) msg = action.result.message || this.failMessage; else msg = this.failMessage; try { msg = new String(eval(msg)); } catch (e) { // } this.setMessage(this.message + '<br /><span class="error">' + msg + '</span>'); this.fireEvent('failure', this, action, msg); } });
gpl-3.0
Dennis-Z/OpenRCT2
src/openrct2/object/ObjectManager.cpp
22325
#pragma region Copyright (c) 2014-2017 OpenRCT2 Developers /***************************************************************************** * OpenRCT2, an open source clone of Roller Coaster Tycoon 2. * * OpenRCT2 is the work of many authors, a full list can be found in contributors.md * For more information, visit https://github.com/OpenRCT2/OpenRCT2 * * OpenRCT2 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. * * A full copy of the GNU General Public License can be found in licence.txt *****************************************************************************/ #pragma endregion #include <array> #include <memory> #include <unordered_set> #include "../core/Console.hpp" #include "../core/Memory.hpp" #include "../localisation/string_ids.h" #include "FootpathItemObject.h" #include "LargeSceneryObject.h" #include "Object.h" #include "ObjectManager.h" #include "ObjectRepository.h" #include "SceneryGroupObject.h" #include "SmallSceneryObject.h" #include "WallObject.h" extern "C" { #include "../object_list.h" } class ObjectManager final : public IObjectManager { private: IObjectRepository * _objectRepository; Object * * _loadedObjects = nullptr; public: explicit ObjectManager(IObjectRepository * objectRepository) { Guard::ArgumentNotNull(objectRepository); _objectRepository = objectRepository; _loadedObjects = Memory::AllocateArray<Object *>(OBJECT_ENTRY_COUNT); for (size_t i = 0; i < OBJECT_ENTRY_COUNT; i++) { _loadedObjects[i] = nullptr; } UpdateLegacyLoadedObjectList(); UpdateSceneryGroupIndexes(); reset_type_to_ride_entry_index_map(); } ~ObjectManager() override { SetNewLoadedObjectList(nullptr); } Object * GetLoadedObject(size_t index) override { if (_loadedObjects == nullptr) { return nullptr; } return _loadedObjects[index]; } Object * GetLoadedObject(const rct_object_entry * entry) override { Object * loadedObject = nullptr; const ObjectRepositoryItem * ori = _objectRepository->FindObject(entry); if (ori != nullptr) { loadedObject = ori->LoadedObject; } return loadedObject; } uint8 GetLoadedObjectEntryIndex(const Object * object) override { uint8 result = UINT8_MAX; size_t index = GetLoadedObjectIndex(object); if (index != SIZE_MAX) { get_type_entry_index(index, nullptr, &result); } return result; } Object * LoadObject(const rct_object_entry * entry) override { Object * loadedObject = nullptr; const ObjectRepositoryItem * ori = _objectRepository->FindObject(entry); if (ori != nullptr) { loadedObject = ori->LoadedObject; if (loadedObject == nullptr) { uint8 objectType = entry->flags & 0x0F; sint32 slot = FindSpareSlot(objectType); if (slot != -1) { loadedObject = GetOrLoadObject(ori); if (loadedObject != nullptr) { _loadedObjects[slot] = loadedObject; UpdateLegacyLoadedObjectList(); UpdateSceneryGroupIndexes(); reset_type_to_ride_entry_index_map(); } } } } return loadedObject; } bool LoadObjects(const rct_object_entry * entries, size_t count) override { // Find all the required objects size_t numRequiredObjects; auto requiredObjects = new const ObjectRepositoryItem *[OBJECT_ENTRY_COUNT]; if (!GetRequiredObjects(entries, requiredObjects, &numRequiredObjects)) { delete[] requiredObjects; return false; } // Create a new list of loaded objects size_t numNewLoadedObjects; Object * * loadedObjects = LoadObjects(requiredObjects, &numNewLoadedObjects); delete[] requiredObjects; if (loadedObjects == nullptr) { UnloadAll(); return false; } else { SetNewLoadedObjectList(loadedObjects); UpdateLegacyLoadedObjectList(); UpdateSceneryGroupIndexes(); reset_type_to_ride_entry_index_map(); log_verbose("%u / %u new objects loaded", numNewLoadedObjects, numRequiredObjects); return true; } } void UnloadObjects(const rct_object_entry * entries, size_t count) override { // TODO there are two performance issues here: // - FindObject for every entry which is a dictionary lookup // - GetLoadedObjectIndex for every entry which enumerates _loadedList size_t numObjectsUnloaded = 0; for (size_t i = 0; i < count; i++) { const rct_object_entry * entry = &entries[i]; const ObjectRepositoryItem * ori = _objectRepository->FindObject(entry); if (ori != nullptr) { Object * loadedObject = ori->LoadedObject; if (loadedObject != nullptr) { UnloadObject(loadedObject); numObjectsUnloaded++; } } } if (numObjectsUnloaded > 0) { UpdateLegacyLoadedObjectList(); UpdateSceneryGroupIndexes(); reset_type_to_ride_entry_index_map(); } } void UnloadAll() override { if (_loadedObjects != nullptr) { for (sint32 i = 0; i < OBJECT_ENTRY_COUNT; i++) { UnloadObject(_loadedObjects[i]); } } UpdateLegacyLoadedObjectList(); UpdateSceneryGroupIndexes(); reset_type_to_ride_entry_index_map(); } void ResetObjects() override { if (_loadedObjects != nullptr) { for (size_t i = 0; i < OBJECT_ENTRY_COUNT; i++) { Object * loadedObject = _loadedObjects[i]; if (loadedObject != nullptr) { loadedObject->Unload(); loadedObject->Load(); } } UpdateLegacyLoadedObjectList(); UpdateSceneryGroupIndexes(); reset_type_to_ride_entry_index_map(); } } std::vector<const ObjectRepositoryItem *> GetPackableObjects() override { std::vector<const ObjectRepositoryItem *> objects; size_t numObjects = _objectRepository->GetNumObjects(); for (size_t i = 0; i < numObjects; i++) { const ObjectRepositoryItem * item = &_objectRepository->GetObjects()[i]; if (item->LoadedObject != nullptr && item->LoadedObject->GetLegacyData() != nullptr && IsObjectCustom(item)) { objects.push_back(item); } } return objects; } static rct_string_id GetObjectSourceGameString(const rct_object_entry * entry) { uint8 source = (entry->flags & 0xF0) >> 4; switch (source) { case OBJECT_SOURCE_RCT2: return STR_ROLLERCOASTER_TYCOON_2_DROPDOWN; case OBJECT_SOURCE_WACKY_WORLDS: return STR_OBJECT_FILTER_WW; case OBJECT_SOURCE_TIME_TWISTER: return STR_OBJECT_FILTER_TT; default: return STR_OBJECT_FILTER_CUSTOM; } } private: sint32 FindSpareSlot(uint8 objectType) { if (_loadedObjects != nullptr) { sint32 firstIndex = GetIndexFromTypeEntry(objectType, 0); sint32 endIndex = firstIndex + object_entry_group_counts[objectType]; for (sint32 i = firstIndex; i < endIndex; i++) { if (_loadedObjects[i] == nullptr) { return i; } } } return -1; } size_t GetLoadedObjectIndex(const Object * object) { Guard::ArgumentNotNull(object, GUARD_LINE); size_t result = SIZE_MAX; if (_loadedObjects != nullptr) { for (size_t i = 0; i < OBJECT_ENTRY_COUNT; i++) { if (_loadedObjects[i] == object) { result = i; break; } } } return result; } void SetNewLoadedObjectList(Object * * newLoadedObjects) { if (newLoadedObjects == nullptr) { UnloadAll(); } else { UnloadObjectsExcept(newLoadedObjects); } Memory::Free(_loadedObjects); _loadedObjects = newLoadedObjects; } void UnloadObject(Object * object) { if (object != nullptr) { // TODO try to prevent doing a repository search const ObjectRepositoryItem * ori = _objectRepository->FindObject(object->GetObjectEntry()); if (ori != nullptr) { _objectRepository->UnregisterLoadedObject(ori, object); } object->Unload(); delete object; // Because it's possible to have the same loaded object for multiple // slots, we have to make sure find and set all of them to nullptr if (_loadedObjects != nullptr) { for (size_t i = 0; i < OBJECT_ENTRY_COUNT; i++) { if (_loadedObjects[i] == object) { _loadedObjects[i] = nullptr; } } } } } void UnloadObjectsExcept(Object * * newLoadedObjects) { if (_loadedObjects == nullptr) { return; } // Build a hash set for quick checking auto exceptSet = std::unordered_set<Object *>(); for (sint32 i = 0; i < OBJECT_ENTRY_COUNT; i++) { Object * object = newLoadedObjects[i]; if (object != nullptr) { exceptSet.insert(object); } } // Unload objects that are not in the hash set size_t totalObjectsLoaded = 0; size_t numObjectsUnloaded = 0; for (sint32 i = 0; i < OBJECT_ENTRY_COUNT; i++) { Object * object = _loadedObjects[i]; if (object != nullptr) { totalObjectsLoaded++; if (exceptSet.find(object) == exceptSet.end()) { UnloadObject(object); numObjectsUnloaded++; } } } log_verbose("%u / %u objects unloaded", numObjectsUnloaded, totalObjectsLoaded); } void UpdateLegacyLoadedObjectList() { for (sint32 i = 0; i < OBJECT_ENTRY_COUNT; i++) { Object * loadedObject = nullptr; if (_loadedObjects != nullptr) { loadedObject = _loadedObjects[i]; } uint8 objectType, entryIndex; get_type_entry_index(i, &objectType, &entryIndex); rct_object_entry_extended * legacyEntry = &object_entry_groups[objectType].entries[entryIndex]; void * * legacyChunk = &object_entry_groups[objectType].chunks[entryIndex]; if (loadedObject == nullptr) { Memory::Set(legacyEntry, 0xFF, sizeof(rct_object_entry_extended)); *legacyChunk = (void *)-1; } else { legacyEntry->entry = *loadedObject->GetObjectEntry(); legacyEntry->chunk_size = 0; *legacyChunk = loadedObject->GetLegacyData(); } } } void UpdateSceneryGroupIndexes() { if (_loadedObjects != nullptr) { for (size_t i = 0; i < OBJECT_ENTRY_COUNT; i++) { Object * loadedObject = _loadedObjects[i]; if (loadedObject != nullptr) { rct_scenery_entry * sceneryEntry; switch (loadedObject->GetObjectType()) { case OBJECT_TYPE_SMALL_SCENERY: sceneryEntry = (rct_scenery_entry *)loadedObject->GetLegacyData(); sceneryEntry->small_scenery.scenery_tab_id = GetPrimarySceneryGroupEntryIndex(loadedObject); break; case OBJECT_TYPE_LARGE_SCENERY: sceneryEntry = (rct_scenery_entry *)loadedObject->GetLegacyData(); sceneryEntry->large_scenery.scenery_tab_id = GetPrimarySceneryGroupEntryIndex(loadedObject); break; case OBJECT_TYPE_WALLS: sceneryEntry = (rct_scenery_entry *)loadedObject->GetLegacyData(); sceneryEntry->wall.scenery_tab_id = GetPrimarySceneryGroupEntryIndex(loadedObject); break; case OBJECT_TYPE_BANNERS: sceneryEntry = (rct_scenery_entry *)loadedObject->GetLegacyData(); sceneryEntry->banner.scenery_tab_id = GetPrimarySceneryGroupEntryIndex(loadedObject); break; case OBJECT_TYPE_PATH_BITS: sceneryEntry = (rct_scenery_entry *)loadedObject->GetLegacyData(); sceneryEntry->path_bit.scenery_tab_id = GetPrimarySceneryGroupEntryIndex(loadedObject); break; case OBJECT_TYPE_SCENERY_SETS: auto sgObject = static_cast<SceneryGroupObject *>(loadedObject); sgObject->UpdateEntryIndexes(); break; } } } // HACK Scenery window will lose its tabs after changing the scenery group indexing // for now just close it, but it will be better to later tell it to invalidate the tabs window_close_by_class(WC_SCENERY); } } uint8 GetPrimarySceneryGroupEntryIndex(Object * loadedObject) { auto sceneryObject = static_cast<SceneryObject *>(loadedObject); const rct_object_entry * primarySGEntry = sceneryObject->GetPrimarySceneryGroup(); Object * sgObject = GetLoadedObject(primarySGEntry); uint8 entryIndex = 255; if (sgObject != nullptr) { entryIndex = GetLoadedObjectEntryIndex(sgObject); } return entryIndex; } rct_object_entry* DuplicateObjectEntry(const rct_object_entry* original) { rct_object_entry * duplicate = Memory::Allocate<rct_object_entry>(sizeof(rct_object_entry)); duplicate->checksum = original->checksum; strncpy(duplicate->name, original->name, 8); duplicate->flags = original->flags; return duplicate; } std::vector<rct_object_entry> GetInvalidObjects(const rct_object_entry * entries) override { std::vector<rct_object_entry> invalidEntries; invalidEntries.reserve(OBJECT_ENTRY_COUNT); for (sint32 i = 0; i < OBJECT_ENTRY_COUNT; i++) { const rct_object_entry * entry = &entries[i]; const ObjectRepositoryItem * ori = nullptr; if (!object_entry_is_empty(entry)) { ori = _objectRepository->FindObject(entry); if (ori == nullptr) { invalidEntries.push_back(*entry); ReportMissingObject(entry); } else { Object * loadedObject = nullptr; loadedObject = ori->LoadedObject; if (loadedObject == nullptr) { loadedObject = _objectRepository->LoadObject(ori); if (loadedObject == nullptr) { invalidEntries.push_back(*entry); ReportObjectLoadProblem(entry); } delete loadedObject; } } } } return invalidEntries; } bool GetRequiredObjects(const rct_object_entry * entries, const ObjectRepositoryItem * * requiredObjects, size_t * outNumRequiredObjects) { bool missingObjects = false; size_t numRequiredObjects = 0; for (sint32 i = 0; i < OBJECT_ENTRY_COUNT; i++) { const rct_object_entry * entry = &entries[i]; const ObjectRepositoryItem * ori = nullptr; if (!object_entry_is_empty(entry)) { ori = _objectRepository->FindObject(entry); if (ori == nullptr) { missingObjects = true; ReportMissingObject(entry); } numRequiredObjects++; } requiredObjects[i] = ori; } if (outNumRequiredObjects != nullptr) { *outNumRequiredObjects = numRequiredObjects; } return !missingObjects; } Object * * LoadObjects(const ObjectRepositoryItem * * requiredObjects, size_t * outNewObjectsLoaded) { size_t newObjectsLoaded = 0; Object * * loadedObjects = Memory::AllocateArray<Object *>(OBJECT_ENTRY_COUNT); for (sint32 i = 0; i < OBJECT_ENTRY_COUNT; i++) { Object * loadedObject = nullptr; const ObjectRepositoryItem * ori = requiredObjects[i]; if (ori != nullptr) { loadedObject = ori->LoadedObject; if (loadedObject == nullptr) { loadedObject = GetOrLoadObject(ori); if (loadedObject == nullptr) { ReportObjectLoadProblem(&ori->ObjectEntry); Memory::Free(loadedObjects); return nullptr; } else { newObjectsLoaded++; } } } loadedObjects[i] = loadedObject; } if (outNewObjectsLoaded != nullptr) { *outNewObjectsLoaded = newObjectsLoaded; } return loadedObjects; } Object * GetOrLoadObject(const ObjectRepositoryItem * ori) { Object * loadedObject = ori->LoadedObject; if (loadedObject == nullptr) { // Try to load object loadedObject = _objectRepository->LoadObject(ori); if (loadedObject != nullptr) { loadedObject->Load(); // Connect the ori to the registered object _objectRepository->RegisterLoadedObject(ori, loadedObject); } } return loadedObject; } static void ReportMissingObject(const rct_object_entry * entry) { utf8 objName[9] = { 0 }; Memory::Copy(objName, entry->name, 8); Console::Error::WriteLine("[%s] Object not found.", objName); } void ReportObjectLoadProblem(const rct_object_entry * entry) { utf8 objName[9] = { 0 }; Memory::Copy(objName, entry->name, 8); Console::Error::WriteLine("[%s] Object could not be loaded.", objName); } static sint32 GetIndexFromTypeEntry(uint8 objectType, uint8 entryIndex) { sint32 result = 0; for (uint8 i = 0; i < objectType; i++) { result += object_entry_group_counts[i]; } result += entryIndex; return result; } }; static ObjectManager * _objectManager = nullptr; IObjectManager * CreateObjectManager(IObjectRepository * objectRepository) { _objectManager = new ObjectManager(objectRepository); return _objectManager; } IObjectManager * GetObjectManager() { return _objectManager; } extern "C" { void * object_manager_get_loaded_object_by_index(size_t index) { IObjectManager * objectManager = GetObjectManager(); Object * loadedObject = objectManager->GetLoadedObject(index); return (void *)loadedObject; } void * object_manager_get_loaded_object(const rct_object_entry * entry) { IObjectManager * objectManager = GetObjectManager(); Object * loadedObject = objectManager->GetLoadedObject(entry); return (void *)loadedObject; } uint8 object_manager_get_loaded_object_entry_index(const void * loadedObject) { IObjectManager * objectManager = GetObjectManager(); const Object * object = static_cast<const Object *>(loadedObject); uint8 entryIndex = objectManager->GetLoadedObjectEntryIndex(object); return entryIndex; } void * object_manager_load_object(const rct_object_entry * entry) { IObjectManager * objectManager = GetObjectManager(); Object * loadedObject = objectManager->LoadObject(entry); return (void *)loadedObject; } void object_manager_unload_objects(const rct_object_entry * entries, size_t count) { IObjectManager * objectManager = GetObjectManager(); objectManager->UnloadObjects(entries, count); } void object_manager_unload_all_objects() { IObjectManager * objectManager = GetObjectManager(); if (objectManager != nullptr) { objectManager->UnloadAll(); } } rct_string_id object_manager_get_source_game_string(const rct_object_entry * entry) { return ObjectManager::GetObjectSourceGameString(entry); } }
gpl-3.0
DanteOnline/free-art
venv/bin/pilprint.py
2627
#!/home/dante/Projects/free-art/venv/bin/python3 # # The Python Imaging Library. # $Id$ # # print image files to postscript printer # # History: # 0.1 1996-04-20 fl Created # 0.2 1996-10-04 fl Use draft mode when converting. # 0.3 2003-05-06 fl Fixed a typo or two. # from __future__ import print_function import getopt import os import sys import subprocess VERSION = "pilprint 0.3/2003-05-05" from PIL import Image from PIL import PSDraw letter = (1.0*72, 1.0*72, 7.5*72, 10.0*72) def description(filepath, image): title = os.path.splitext(os.path.split(filepath)[1])[0] format = " (%dx%d " if image.format: format = " (" + image.format + " %dx%d " return title + format % image.size + image.mode + ")" if len(sys.argv) == 1: print("PIL Print 0.3/2003-05-05 -- print image files") print("Usage: pilprint files...") print("Options:") print(" -c colour printer (default is monochrome)") print(" -d debug (show available drivers)") print(" -p print via lpr (default is stdout)") print(" -P <printer> same as -p but use given printer") sys.exit(1) try: opt, argv = getopt.getopt(sys.argv[1:], "cdpP:") except getopt.error as v: print(v) sys.exit(1) printerArgs = [] # print to stdout monochrome = 1 # reduce file size for most common case for o, a in opt: if o == "-d": # debug: show available drivers Image.init() print(Image.ID) sys.exit(1) elif o == "-c": # colour printer monochrome = 0 elif o == "-p": # default printer channel printerArgs = ["lpr"] elif o == "-P": # printer channel printerArgs = ["lpr", "-P%s" % a] for filepath in argv: try: im = Image.open(filepath) title = description(filepath, im) if monochrome and im.mode not in ["1", "L"]: im.draft("L", im.size) im = im.convert("L") if printerArgs: p = subprocess.Popen(printerArgs, stdin=subprocess.PIPE) fp = p.stdin else: fp = sys.stdout ps = PSDraw.PSDraw(fp) ps.begin_document() ps.setfont("Helvetica-Narrow-Bold", 18) ps.text((letter[0], letter[3]+24), title) ps.setfont("Helvetica-Narrow-Bold", 8) ps.text((letter[0], letter[1]-30), VERSION) ps.image(letter, im) ps.end_document() if printerArgs: fp.close() except: print("cannot print image", end=' ') print("(%s:%s)" % (sys.exc_info()[0], sys.exc_info()[1]))
gpl-3.0
obiba/magma
magma-api/src/test/java/org/obiba/magma/ValueSequenceTest.java
2945
/* * Copyright (c) 2019 OBiBa. 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.magma; import java.util.Comparator; import org.junit.Test; import org.obiba.magma.support.Values; import org.obiba.magma.type.TextType; import com.google.common.collect.ImmutableList; import static org.fest.assertions.api.Assertions.assertThat; public class ValueSequenceTest extends AbstractValueTest { @Test public void test_isSequence() { Value value = testValue(); assertThat(value.isSequence()).isTrue(); } @Test public void test_asSequence() { Value value = testValue(); ValueSequence sequence = value.asSequence(); assertThat(value == sequence).isTrue(); } @Test public void test_sort_sortsElementsInNaturalOrder() { ValueSequence value = testValue(); ValueSequence sorted = value.sort(); assertThat(value == sorted).isFalse(); assertThat(sorted.getValue()).isEqualTo(ImmutableList.copyOf(Values.asValues(TextType.get(), "B", "C", "a"))); } @Test public void test_sort_sortsUsingComparator() { ValueSequence value = testValue(); ValueSequence sorted = value.sort(new Comparator<Value>() { @Override public int compare(Value o1, Value o2) { return String.CASE_INSENSITIVE_ORDER.compare((String) o1.getValue(), (String) o2.getValue()); } }); assertThat(value == sorted).isFalse(); assertThat(sorted.getValue()).isEqualTo(ImmutableList.copyOf(Values.asValues(TextType.get(), "a", "B", "C"))); } @Test public void test_getSize() { ValueSequence value = testValue(); assertThat(value.getSize()).isEqualTo(3); } @Test public void test_get() { ValueSequence value = testValue(); assertThat(value.get(0)).isEqualTo(TextType.get().valueOf("C")); assertThat(value.get(1)).isEqualTo(TextType.get().valueOf("B")); assertThat(value.get(2)).isEqualTo(TextType.get().valueOf("a")); } @Test(expected = RuntimeException.class) public void test_get_throwsWhenOutOfBound() { ValueSequence value = testValue(); value.get(-1); } @Test public void test_contains() { ValueSequence value = testValue(); assertThat(value.contains(TextType.get().valueOf("C"))).isTrue(); assertThat(value.contains(TextType.get().valueOf("B"))).isTrue(); assertThat(value.contains(TextType.get().valueOf("a"))).isTrue(); assertThat(value.contains(TextType.get().valueOf("CBa"))).isFalse(); } @Override protected ValueSequence testValue() { return TextType.get().sequenceOf(testObject()); } @Override protected Iterable<Value> testObject() { return ImmutableList.copyOf(Values.asValues(TextType.get(), "C", "B", "a")); } }
gpl-3.0
sio2project/oioioi
oioioi/ipdnsauth/middleware.py
3656
from django.contrib import auth from django.core.exceptions import ImproperlyConfigured from django.template.response import TemplateResponse from oioioi.su.utils import is_under_su, reset_to_real_user # Code based on django.contrib.auth.middleware.RemoteUserMiddleware class IpDnsAuthMiddleware(object): """Middleware for authentication based on user IP or DNS hostname.""" def __init__(self, get_response): self.get_response = get_response def __call__(self, request): self._process_request(request) return self.get_response(request) def _process_request(self, request): if not hasattr(request, 'user'): raise ImproperlyConfigured( "The IpDns user auth middleware requires the" " authentication middleware to be installed. Edit your" " MIDDLEWARE setting to insert" " 'django.contrib.auth.middleware.AuthenticationMiddleware'" " before the IpDnsAuthMiddleware class." ) ip_addr = request.META.get('REMOTE_ADDR') dns_name = request.META.get('REMOTE_HOST') if dns_name == ip_addr: dns_name = None if not dns_name and not ip_addr: return user = auth.authenticate(request, ip_addr=ip_addr, dns_name=dns_name) if user: auth.login(request, user) # Code based on django.contrib.auth.middleware.RemoteUserMiddleware class ForceDnsIpAuthMiddleware(object): """Middleware which allows only IP/DNS login for participants of on-site contests.""" def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_view(self, request, view_func, view_args, view_kwargs): if not hasattr(request, 'user'): raise ImproperlyConfigured( "The ForceDnsIpAuthMiddleware middleware requires the" " 'django.contrib.auth.middleware.AuthenticationMiddleware'" " earlier in MIDDLEWARE." ) if not request.user.is_anonymous and not hasattr(request.user, 'backend'): raise ImproperlyConfigured( "The ForceDnsIpAuthMiddleware middleware requires the" " 'oioioi.base.middleware.AnnotateUserBackendMiddleware'" " earlier in MIDDLEWARE." ) if not hasattr(request, 'contest'): raise ImproperlyConfigured( "The ForceDnsIpAuthMiddleware middleware requires the" " 'oioioi.contests.middleware.CurrentContestMiddleware'" " earlier in MIDDLEWARE." ) if not request.contest: return if not hasattr(request, 'contest_exclusive'): raise ImproperlyConfigured( "The ForceDnsIpAuthMiddleware middleware requires the" " 'oioioi.contextexcl.middleware.ExclusiveContestsMiddleware'" " earlier in MIDDLEWARE." ) if not request.contest_exclusive: return if not request.contest.controller.is_onsite(): return if not request.user.is_authenticated: return backend_path = request.user.backend if backend_path != 'oioioi.ipdnsauth.backends.IpDnsBackend': if is_under_su(request): reset_to_real_user(request) else: auth.logout(request) return TemplateResponse( request, 'ipdnsauth/access_blocked.html', {'auth_backend': backend_path} )
gpl-3.0
AmosJindao/movie
database-service/src/main/java/db/bean/information_schema/InnodbFtBeingDeleted.java
695
package db.bean.information_schema; /* SELECT DOC_ID AS docId FROM information_schema.INNODB_FT_BEING_DELETED */ /** */ public class InnodbFtBeingDeleted{ /**Column{tableCatalog='def', tableSchema='information_schema', tableName='INNODB_FT_BEING_DELETED', columnName='DOC_ID', ordinalPosition=1, columnDefault='0', isNullable='NO', dataType='bigint', characterMaximumLength=0, characterOctetLength=0, numericPrecision=20, numericScale=0, datetimePrecision=0, characterSetName='null', collationName='null', columnType='bigint(21) unsigned', columnKey='', extra='', privileges='select', columnComment='', generationExpression=''}*/ private Long docId; public Long getDocId(){ return docId; } }
gpl-3.0
lingcarzy/v5cart
admin/controller/module/slideshow.php
2333
<?php class ControllerModuleSlideshow extends Controller { public function index() { $this->language->load('module/slideshow'); $this->document->setTitle(L('module_name')); M('setting/setting'); if ($this->request->isPost() && $this->validate()) { $this->model_setting_setting->editSetting('slideshow', $this->request->post); $this->session->set_flashdata('success', L('text_success')); $this->redirect(UA('extension/module')); } $this->data['breadcrumbs'] = array(); $this->data['breadcrumbs'][] = array( 'text' => L('text_home'), 'href' => UA('common/home'), 'separator' => false ); $this->data['breadcrumbs'][] = array( 'text' => L('text_module'), 'href' => UA('extension/module'), 'separator' => ' :: ' ); $this->data['breadcrumbs'][] = array( 'text' => L('module_name'), 'href' => UA('module/slideshow'), 'separator' => ' :: ' ); $this->data['modules'] = array(); if (isset($this->request->post['slideshow_module'])) { $this->data['modules'] = $this->request->post['slideshow_module']; } elseif (C('slideshow_module')) { $this->data['modules'] = C('slideshow_module'); } $this->data['templates'] = glob(DIR_CATALOG . 'view/theme/' . C('config_template') . '/template/module/slideshow_*.tpl'); foreach ($this->data['templates'] as $i => $tpl) { $this->data['templates'][$i] = basename($tpl); } M('design/layout'); $this->data['layouts'] = $this->model_design_layout->getLayouts(); M('design/banner'); $this->data['banners'] = $this->model_design_banner->getBanners(); $this->children = array( 'common/header', 'common/footer' ); $this->display('module/slideshow.tpl'); } protected function validate() { if (!$this->user->hasPermission('modify', 'module/slideshow')) { $this->setMessage('error_warning', L('error_permission')); return false; } if (isset($this->request->post['slideshow_module'])) { $error = array(); foreach ($this->request->post['slideshow_module'] as $key => $value) { if (!$value['width'] || !$value['height']) { $error[$key] = L('error_dimension'); } } if ($error) { $this->setMessage('error_dimension', $error); return false; } } return true; } } ?>
gpl-3.0
tmunzer/get-a-key
src/public/web-app/help/app.js
868
var gak = angular.module("gak", [ "ngRoute", 'ui.bootstrap', 'ngSanitize', 'ngMaterial', 'ngMessages' ]); gak .config(function ($routeProvider) { $routeProvider .when("/azureAD", { module: "App", controller: "AppCtrl" }) .otherwise({ redirectTo: "/azureAD/" }); }) .config(function ($mdThemingProvider) { $mdThemingProvider.definePalette('ahBlue', colors) .theme('default') .primaryPalette("ahBlue", { 'default': '600' }) .accentPalette('ahBlue', { 'default': '200' // by default use shade 400 from the pink palette for primary intentions }); }); gak.controller("AppCtrl", function ($scope) { console.log('help'); });
gpl-3.0
auto-mat/klub
apps/repolinks/templatetags/repolinks.py
285
from django import template from ..models import Repo register = template.Library() class ReposNode(template.Node): def render(self, context): context["repos"] = Repo.objects.all() return "" @register.tag def load_repos(parser, token): return ReposNode()
gpl-3.0
Caple/OakMagic
src/com/ignoreourgirth/gary/oakmagic/spells/Holy.java
2078
/******************************************************************************* * Copyright (c) 2012 GaryMthrfkinOak (Jesse Caple). * * This 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 software 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 software. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.ignoreourgirth.gary.oakmagic.spells; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Monster; import org.bukkit.entity.Player; import com.ignoreourgirth.gary.oakmagic.spellTypes.Spell; public class Holy extends Spell{ public Holy(int id) { super(id); spellDescription = "Disintegrates zombies and skeletons leaving nothing but ash."; isProjectileSpell = true; } @Override public boolean canCast(Player caster, Entity targetEntity, Location targetLocation, int spellLevel) { if (targetEntity != null) return (targetEntity.getType() == EntityType.ZOMBIE || targetEntity.getType() == EntityType.SKELETON ); return false; } @Override public void execute(Player caster, Entity targetEntity, Location targetLocation, int spellLevel) { Monster mob = (Monster) targetEntity; mob.getLocation().getWorld().playEffect(mob.getLocation(), Effect.ENDER_SIGNAL, 0); mob.getLocation().getWorld().playEffect(mob.getLocation(), Effect.ENDER_SIGNAL, 0); mob.damage(10000, caster); } @Override protected void onCastTick(Player caster, Entity targetEntity, Location targetLocation, int spellLevel) { } }
gpl-3.0
dcnewman/RepRapFirmware
src/Roland.cpp
4778
// This class allows the RepRap firmware to transmit commands to a Roland mill // See: http://www.rolanddg.com/product/3d/3d/mdx-20_15/mdx-20_15.html // http://altlab.org/d/content/m/pangelo/ideas/rml_command_guide_en_v100.pdf #if SUPPORT_ROLAND #include "RepRapFirmware.h" Roland::Roland(Platform* p) { platform = p; } void Roland::Init() { pinMode(ROLAND_RTS_PIN, OUTPUT); pinMode(ROLAND_CTS_PIN, INPUT); digitalWrite(ROLAND_RTS_PIN, HIGH); sBuffer = new StringRef(buffer, ARRAY_SIZE(buffer)); sBuffer->Clear(); bufferPointer = 0; Zero(true); longWait = platform->Time(); active = false; } void Roland::Spin() { if (!Active()) { platform->ClassReport(longWait); return; } // 'U' is 01010101 in binary (nice for an oscilloscope...) //SERIAL_AUX2_DEVICE.write('U'); //SERIAL_AUX2_DEVICE.flush(); //return; // Are we sending something to the Roland? if (Busy()) // Busy means we are sending something { if (digitalRead(ROLAND_CTS_PIN)) { platform->ClassReport(longWait); return; } SERIAL_AUX2_DEVICE.write(buffer[bufferPointer]); SERIAL_AUX2_DEVICE.flush(); bufferPointer++; } else // Not sending. { // Finished talking to the Roland sBuffer->Clear(); bufferPointer = 0; // Anything new to do? EndstopChecks endStopsToCheck; uint8_t moveType; FilePosition filePos; if (reprap.GetGCodes()->ReadMove(move, endStopsToCheck, moveType, filePos)) { move[AXES] = move[DRIVES]; // Roland doesn't have extruders etc. ProcessMove(); } } platform->ClassReport(longWait); } void Roland::Zero(bool feed) { size_t lim = feed ? AXES + 1 : AXES; for(size_t axis = 0; axis < lim; axis++) { move[axis] = 0.0; coordinates[axis] = 0.0; oldCoordinates[axis] = 0.0; offset[axis] = 0.0; } if (reprap.Debug(moduleGcodes)) { platform->Message(HOST_MESSAGE, "Roland zero\n"); } } bool Roland::Busy() { return buffer[bufferPointer] != 0; } bool Roland::ProcessHome() { if (Busy()) { return false; } sBuffer->copy("H;\n"); Zero(false); if (reprap.Debug(moduleGcodes)) { platform->MessageF(HOST_MESSAGE, "Roland home: %s", buffer); } return true; } bool Roland::ProcessDwell(long milliseconds) { if (Busy()) { return false; } sBuffer->printf("W%ld;", milliseconds); sBuffer->catf("Z %.4f,%.4f,%.4f;", oldCoordinates[0], oldCoordinates[1], oldCoordinates[2]); sBuffer->cat("W0;\n"); if (reprap.Debug(moduleGcodes)) { platform->MessageF(HOST_MESSAGE, "Roland dwell: %s", buffer); } return true; } bool Roland::ProcessG92(float v, size_t axis) { if (Busy()) { return false; } move[axis] = v; coordinates[axis] = move[axis]*ROLAND_FACTOR + offset[axis]; offset[axis] = oldCoordinates[axis]; oldCoordinates[axis] = coordinates[axis]; if (reprap.Debug(moduleGcodes)) { platform->Message(HOST_MESSAGE, "Roland G92\n"); } return true; } bool Roland::ProcessSpindle(float rpm) { if (Busy()) { return false; } if (rpm < 0.5) // Stop { sBuffer->printf("!MC 0;\n"); } else // Go { sBuffer->printf("!RC%ld;!MC 1;\n", (long)(rpm + 100.0)); } if (reprap.Debug(moduleGcodes)) { platform->MessageF(HOST_MESSAGE, "Roland spindle: %s", buffer); } return true; } void Roland::GetCurrentRolandPosition(float moveBuffer[]) { for(size_t axis = 0; axis < AXES; axis++) { moveBuffer[axis] = move[axis]; } for(size_t axis = AXES; axis < DRIVES; axis++) { moveBuffer[axis] = 0.0; } moveBuffer[DRIVES] = move[AXES]; } void Roland::ProcessMove() { for(size_t axis = 0; axis < AXES; axis++) { coordinates[axis] = move[axis] * ROLAND_FACTOR + offset[axis]; } coordinates[AXES] = move[AXES]; // Start with feedrate; For some reason the Roland won't accept more than 4 d.p. sBuffer->printf("V %.4f;", coordinates[AXES]); // Now the move sBuffer->catf("Z %.4f,%.4f,%.4f;\n", coordinates[0], coordinates[1], coordinates[2]); for(size_t axis = 0; axis <= AXES; axis++) { oldCoordinates[axis] = coordinates[axis]; } if (reprap.Debug(moduleGcodes)) { platform->MessageF(HOST_MESSAGE, "Roland move: %s", buffer); } } bool Roland::RawWrite(const char* s) { if (Busy()) { return false; } sBuffer->copy(s); sBuffer->cat("\n"); if (reprap.Debug(moduleGcodes)) { platform->MessageF(HOST_MESSAGE, "Roland rawwrite: %s", buffer); } return true; } bool Roland::Active() { return active; } void Roland::Activate() { digitalWrite(ROLAND_RTS_PIN, LOW); active = true; if (reprap.Debug(moduleGcodes)) { platform->Message(HOST_MESSAGE, "Roland started\n"); } } bool Roland::Deactivate() { if (Busy()) { return false; } digitalWrite(ROLAND_RTS_PIN, HIGH); active = false; if (reprap.Debug(moduleGcodes)) { platform->Message(HOST_MESSAGE, "Roland stopped\n"); } return true; } #endif
gpl-3.0
ddperalta/phpFrameworks1
system/database/DB_query_builder.php
63554
<?php /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014 - 2017, British Columbia Institute of Technology * * 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. * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/) * @license http://opensource.org/licenses/MIT MIT License * @link https://codeigniter.com * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); /** * Query Builder Class * * This is the platform-independent base Query Builder implementation class. * * @package CodeIgniter * @subpackage Drivers * @category Database * @author EllisLab Dev Team * @link https://codeigniter.com/user_guide/database/ */ abstract class CI_DB_query_builder extends CI_DB_driver { /** * Return DELETE SQL flag * * @var bool */ protected $return_delete_sql = FALSE; /** * Reset DELETE data flag * * @var bool */ protected $reset_delete_data = FALSE; /** * QB SELECT data * * @var array */ protected $qb_select = array(); /** * QB DISTINCT flag * * @var bool */ protected $qb_distinct = FALSE; /** * QB FROM data * * @var array */ protected $qb_from = array(); /** * QB JOIN data * * @var array */ protected $qb_join = array(); /** * QB WHERE data * * @var array */ protected $qb_where = array(); /** * QB GROUP BY data * * @var array */ protected $qb_groupby = array(); /** * QB HAVING data * * @var array */ protected $qb_having = array(); /** * QB keys * * @var array */ protected $qb_keys = array(); /** * QB LIMIT data * * @var int */ protected $qb_limit = FALSE; /** * QB OFFSET data * * @var int */ protected $qb_offset = FALSE; /** * QB ORDER BY data * * @var array */ protected $qb_orderby = array(); /** * QB data sets * * @var array */ protected $qb_set = array(); /** * QB data set for update_batch() * * @var array */ protected $qb_set_ub = array(); /** * QB aliased tables list * * @var array */ protected $qb_aliased_tables = array(); /** * QB WHERE group started flag * * @var bool */ protected $qb_where_group_started = FALSE; /** * QB WHERE group count * * @var int */ protected $qb_where_group_count = 0; // Query Builder Caching variables /** * QB Caching flag * * @var bool */ protected $qb_caching = FALSE; /** * QB Cache exists list * * @var array */ protected $qb_cache_exists = array(); /** * QB Cache SELECT data * * @var array */ protected $qb_cache_select = array(); /** * QB Cache FROM data * * @var array */ protected $qb_cache_from = array(); /** * QB Cache JOIN data * * @var array */ protected $qb_cache_join = array(); /** * QB Cache WHERE data * * @var array */ protected $qb_cache_where = array(); /** * QB Cache GROUP BY data * * @var array */ protected $qb_cache_groupby = array(); /** * QB Cache HAVING data * * @var array */ protected $qb_cache_having = array(); /** * QB Cache ORDER BY data * * @var array */ protected $qb_cache_orderby = array(); /** * QB Cache data sets * * @var array */ protected $qb_cache_set = array(); /** * QB No Escape data * * @var array */ protected $qb_no_escape = array(); /** * QB Cache No Escape data * * @var array */ protected $qb_cache_no_escape = array(); // -------------------------------------------------------------------- /** * Select * * Generates the SELECT portion of the query * * @param string * @param mixed * @return CI_DB_query_builder */ public function select($select = '*', $escape = NULL) { if (is_string($select)) { $select = explode(',', $select); } // If the escape value was not set, we will base it on the global setting is_bool($escape) OR $escape = $this->_protect_identifiers; foreach ($select as $val) { $val = trim($val); if ($val !== '') { $this->qb_select[] = $val; $this->qb_no_escape[] = $escape; if ($this->qb_caching === TRUE) { $this->qb_cache_select[] = $val; $this->qb_cache_exists[] = 'select'; $this->qb_cache_no_escape[] = $escape; } } } return $this; } // -------------------------------------------------------------------- /** * Select Max * * Generates a SELECT MAX(field) portion of a query * * @param string the field * @param string an alias * @return CI_DB_query_builder */ public function select_max($select = '', $alias = '') { return $this->_max_min_avg_sum($select, $alias, 'MAX'); } // -------------------------------------------------------------------- /** * Select Min * * Generates a SELECT MIN(field) portion of a query * * @param string the field * @param string an alias * @return CI_DB_query_builder */ public function select_min($select = '', $alias = '') { return $this->_max_min_avg_sum($select, $alias, 'MIN'); } // -------------------------------------------------------------------- /** * Select Average * * Generates a SELECT AVG(field) portion of a query * * @param string the field * @param string an alias * @return CI_DB_query_builder */ public function select_avg($select = '', $alias = '') { return $this->_max_min_avg_sum($select, $alias, 'AVG'); } // -------------------------------------------------------------------- /** * Select Sum * * Generates a SELECT SUM(field) portion of a query * * @param string the field * @param string an alias * @return CI_DB_query_builder */ public function select_sum($select = '', $alias = '') { return $this->_max_min_avg_sum($select, $alias, 'SUM'); } // -------------------------------------------------------------------- /** * SELECT [MAX|MIN|AVG|SUM]() * * @used-by select_max() * @used-by select_min() * @used-by select_avg() * @used-by select_sum() * * @param string $select Field name * @param string $alias * @param string $type * @return CI_DB_query_builder */ protected function _max_min_avg_sum($select = '', $alias = '', $type = 'MAX') { if ( ! is_string($select) OR $select === '') { $this->display_error('db_invalid_query'); } $type = strtoupper($type); if ( ! in_array($type, array('MAX', 'MIN', 'AVG', 'SUM'))) { show_error('Invalid function type: '.$type); } if ($alias === '') { $alias = $this->_create_alias_from_table(trim($select)); } $sql = $type.'('.$this->protect_identifiers(trim($select)).') AS '.$this->escape_identifiers(trim($alias)); $this->qb_select[] = $sql; $this->qb_no_escape[] = NULL; if ($this->qb_caching === TRUE) { $this->qb_cache_select[] = $sql; $this->qb_cache_exists[] = 'select'; } return $this; } // -------------------------------------------------------------------- /** * Determines the alias name based on the table * * @param string $item * @return string */ protected function _create_alias_from_table($item) { if (strpos($item, '.') !== FALSE) { $item = explode('.', $item); return end($item); } return $item; } // -------------------------------------------------------------------- /** * DISTINCT * * Sets a flag which tells the query string compiler to add DISTINCT * * @param bool $val * @return CI_DB_query_builder */ public function distinct($val = TRUE) { $this->qb_distinct = is_bool($val) ? $val : TRUE; return $this; } // -------------------------------------------------------------------- /** * From * * Generates the FROM portion of the query * * @param mixed $from can be a string or array * @return CI_DB_query_builder */ public function from($from) { foreach ((array) $from as $val) { if (strpos($val, ',') !== FALSE) { foreach (explode(',', $val) as $v) { $v = trim($v); $this->_track_aliases($v); $this->qb_from[] = $v = $this->protect_identifiers($v, TRUE, NULL, FALSE); if ($this->qb_caching === TRUE) { $this->qb_cache_from[] = $v; $this->qb_cache_exists[] = 'from'; } } } else { $val = trim($val); // Extract any aliases that might exist. We use this information // in the protect_identifiers to know whether to add a table prefix $this->_track_aliases($val); $this->qb_from[] = $val = $this->protect_identifiers($val, TRUE, NULL, FALSE); if ($this->qb_caching === TRUE) { $this->qb_cache_from[] = $val; $this->qb_cache_exists[] = 'from'; } } } return $this; } // -------------------------------------------------------------------- /** * JOIN * * Generates the JOIN portion of the query * * @param string * @param string the join condition * @param string the type of join * @param string whether not to try to escape identifiers * @return CI_DB_query_builder */ public function join($table, $cond, $type = '', $escape = NULL) { if ($type !== '') { $type = strtoupper(trim($type)); if ( ! in_array($type, array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER'), TRUE)) { $type = ''; } else { $type .= ' '; } } // Extract any aliases that might exist. We use this information // in the protect_identifiers to know whether to add a table prefix $this->_track_aliases($table); is_bool($escape) OR $escape = $this->_protect_identifiers; if ( ! $this->_has_operator($cond)) { $cond = ' USING ('.($escape ? $this->escape_identifiers($cond) : $cond).')'; } elseif ($escape === FALSE) { $cond = ' ON '.$cond; } else { // Split multiple conditions if (preg_match_all('/\sAND\s|\sOR\s/i', $cond, $joints, PREG_OFFSET_CAPTURE)) { $conditions = array(); $joints = $joints[0]; array_unshift($joints, array('', 0)); for ($i = count($joints) - 1, $pos = strlen($cond); $i >= 0; $i--) { $joints[$i][1] += strlen($joints[$i][0]); // offset $conditions[$i] = substr($cond, $joints[$i][1], $pos - $joints[$i][1]); $pos = $joints[$i][1] - strlen($joints[$i][0]); $joints[$i] = $joints[$i][0]; } } else { $conditions = array($cond); $joints = array(''); } $cond = ' ON '; for ($i = 0, $c = count($conditions); $i < $c; $i++) { $operator = $this->_get_operator($conditions[$i]); $cond .= $joints[$i]; $cond .= preg_match("/(\(*)?([\[\]\w\.'-]+)".preg_quote($operator)."(.*)/i", $conditions[$i], $match) ? $match[1].$this->protect_identifiers($match[2]).$operator.$this->protect_identifiers($match[3]) : $conditions[$i]; } } // Do we want to escape the table name? if ($escape === TRUE) { $table = $this->protect_identifiers($table, TRUE, NULL, FALSE); } // Assemble the JOIN statement $this->qb_join[] = $join = $type.'JOIN '.$table.$cond; if ($this->qb_caching === TRUE) { $this->qb_cache_join[] = $join; $this->qb_cache_exists[] = 'join'; } return $this; } // -------------------------------------------------------------------- /** * WHERE * * Generates the WHERE portion of the query. * Separates multiple calls with 'AND'. * * @param mixed * @param mixed * @param bool * @return CI_DB_query_builder */ public function where($key, $value = NULL, $escape = NULL) { return $this->_wh('qb_where', $key, $value, 'AND ', $escape); } // -------------------------------------------------------------------- /** * OR WHERE * * Generates the WHERE portion of the query. * Separates multiple calls with 'OR'. * * @param mixed * @param mixed * @param bool * @return CI_DB_query_builder */ public function or_where($key, $value = NULL, $escape = NULL) { return $this->_wh('qb_where', $key, $value, 'OR ', $escape); } // -------------------------------------------------------------------- /** * WHERE, HAVING * * @used-by where() * @used-by or_where() * @used-by having() * @used-by or_having() * * @param string $qb_key 'qb_where' or 'qb_having' * @param mixed $key * @param mixed $value * @param string $type * @param bool $escape * @return CI_DB_query_builder */ protected function _wh($qb_key, $key, $value = NULL, $type = 'AND ', $escape = NULL) { $qb_cache_key = ($qb_key === 'qb_having') ? 'qb_cache_having' : 'qb_cache_where'; if ( ! is_array($key)) { $key = array($key => $value); } // If the escape value was not set will base it on the global setting is_bool($escape) OR $escape = $this->_protect_identifiers; foreach ($key as $k => $v) { $prefix = (count($this->$qb_key) === 0 && count($this->$qb_cache_key) === 0) ? $this->_group_get_type('') : $this->_group_get_type($type); if ($v !== NULL) { if ($escape === TRUE) { $v = ' '.$this->escape($v); } if ( ! $this->_has_operator($k)) { $k .= ' = '; } } elseif ( ! $this->_has_operator($k)) { // value appears not to have been set, assign the test to IS NULL $k .= ' IS NULL'; } elseif (preg_match('/\s*(!?=|<>|\sIS(?:\s+NOT)?\s)\s*$/i', $k, $match, PREG_OFFSET_CAPTURE)) { $k = substr($k, 0, $match[0][1]).($match[1][0] === '=' ? ' IS NULL' : ' IS NOT NULL'); } $this->{$qb_key}[] = array('condition' => $prefix.$k.$v, 'escape' => $escape); if ($this->qb_caching === TRUE) { $this->{$qb_cache_key}[] = array('condition' => $prefix.$k.$v, 'escape' => $escape); $this->qb_cache_exists[] = substr($qb_key, 3); } } return $this; } // -------------------------------------------------------------------- /** * WHERE IN * * Generates a WHERE field IN('item', 'item') SQL query, * joined with 'AND' if appropriate. * * @param string $key The field to search * @param array $values The values searched on * @param bool $escape * @return CI_DB_query_builder */ public function where_in($key = NULL, $values = NULL, $escape = NULL) { return $this->_where_in($key, $values, FALSE, 'AND ', $escape); } // -------------------------------------------------------------------- /** * OR WHERE IN * * Generates a WHERE field IN('item', 'item') SQL query, * joined with 'OR' if appropriate. * * @param string $key The field to search * @param array $values The values searched on * @param bool $escape * @return CI_DB_query_builder */ public function or_where_in($key = NULL, $values = NULL, $escape = NULL) { return $this->_where_in($key, $values, FALSE, 'OR ', $escape); } // -------------------------------------------------------------------- /** * WHERE NOT IN * * Generates a WHERE field NOT IN('item', 'item') SQL query, * joined with 'AND' if appropriate. * * @param string $key The field to search * @param array $values The values searched on * @param bool $escape * @return CI_DB_query_builder */ public function where_not_in($key = NULL, $values = NULL, $escape = NULL) { return $this->_where_in($key, $values, TRUE, 'AND ', $escape); } // -------------------------------------------------------------------- /** * OR WHERE NOT IN * * Generates a WHERE field NOT IN('item', 'item') SQL query, * joined with 'OR' if appropriate. * * @param string $key The field to search * @param array $values The values searched on * @param bool $escape * @return CI_DB_query_builder */ public function or_where_not_in($key = NULL, $values = NULL, $escape = NULL) { return $this->_where_in($key, $values, TRUE, 'OR ', $escape); } // -------------------------------------------------------------------- /** * Internal WHERE IN * * @used-by where_in() * @used-by or_where_in() * @used-by where_not_in() * @used-by or_where_not_in() * * @param string $key The field to search * @param array $values The values searched on * @param bool $not If the statement would be IN or NOT IN * @param string $type * @param bool $escape * @return CI_DB_query_builder */ protected function _where_in($key = NULL, $values = NULL, $not = FALSE, $type = 'AND ', $escape = NULL) { if ($key === NULL OR $values === NULL) { return $this; } if ( ! is_array($values)) { $values = array($values); } is_bool($escape) OR $escape = $this->_protect_identifiers; $not = ($not) ? ' NOT' : ''; if ($escape === TRUE) { $where_in = array(); foreach ($values as $value) { $where_in[] = $this->escape($value); } } else { $where_in = array_values($values); } $prefix = (count($this->qb_where) === 0 && count($this->qb_cache_where) === 0) ? $this->_group_get_type('') : $this->_group_get_type($type); $where_in = array( 'condition' => $prefix.$key.$not.' IN('.implode(', ', $where_in).')', 'escape' => $escape ); $this->qb_where[] = $where_in; if ($this->qb_caching === TRUE) { $this->qb_cache_where[] = $where_in; $this->qb_cache_exists[] = 'where'; } return $this; } // -------------------------------------------------------------------- /** * LIKE * * Generates a %LIKE% portion of the query. * Separates multiple calls with 'AND'. * * @param mixed $field * @param string $match * @param string $side * @param bool $escape * @return CI_DB_query_builder */ public function like($field, $match = '', $side = 'both', $escape = NULL) { return $this->_like($field, $match, 'AND ', $side, '', $escape); } // -------------------------------------------------------------------- /** * NOT LIKE * * Generates a NOT LIKE portion of the query. * Separates multiple calls with 'AND'. * * @param mixed $field * @param string $match * @param string $side * @param bool $escape * @return CI_DB_query_builder */ public function not_like($field, $match = '', $side = 'both', $escape = NULL) { return $this->_like($field, $match, 'AND ', $side, 'NOT', $escape); } // -------------------------------------------------------------------- /** * OR LIKE * * Generates a %LIKE% portion of the query. * Separates multiple calls with 'OR'. * * @param mixed $field * @param string $match * @param string $side * @param bool $escape * @return CI_DB_query_builder */ public function or_like($field, $match = '', $side = 'both', $escape = NULL) { return $this->_like($field, $match, 'OR ', $side, '', $escape); } // -------------------------------------------------------------------- /** * OR NOT LIKE * * Generates a NOT LIKE portion of the query. * Separates multiple calls with 'OR'. * * @param mixed $field * @param string $match * @param string $side * @param bool $escape * @return CI_DB_query_builder */ public function or_not_like($field, $match = '', $side = 'both', $escape = NULL) { return $this->_like($field, $match, 'OR ', $side, 'NOT', $escape); } // -------------------------------------------------------------------- /** * Internal LIKE * * @used-by like() * @used-by or_like() * @used-by not_like() * @used-by or_not_like() * * @param mixed $field * @param string $match * @param string $type * @param string $side * @param string $not * @param bool $escape * @return CI_DB_query_builder */ protected function _like($field, $match = '', $type = 'AND ', $side = 'both', $not = '', $escape = NULL) { if ( ! is_array($field)) { $field = array($field => $match); } is_bool($escape) OR $escape = $this->_protect_identifiers; // lowercase $side in case somebody writes e.g. 'BEFORE' instead of 'before' (doh) $side = strtolower($side); foreach ($field as $k => $v) { $prefix = (count($this->qb_where) === 0 && count($this->qb_cache_where) === 0) ? $this->_group_get_type('') : $this->_group_get_type($type); if ($escape === TRUE) { $v = $this->escape_like_str($v); } if ($side === 'none') { $like_statement = "{$prefix} {$k} {$not} LIKE '{$v}'"; } elseif ($side === 'before') { $like_statement = "{$prefix} {$k} {$not} LIKE '%{$v}'"; } elseif ($side === 'after') { $like_statement = "{$prefix} {$k} {$not} LIKE '{$v}%'"; } else { $like_statement = "{$prefix} {$k} {$not} LIKE '%{$v}%'"; } // some platforms require an escape sequence definition for LIKE wildcards if ($escape === TRUE && $this->_like_escape_str !== '') { $like_statement .= sprintf($this->_like_escape_str, $this->_like_escape_chr); } $this->qb_where[] = array('condition' => $like_statement, 'escape' => $escape); if ($this->qb_caching === TRUE) { $this->qb_cache_where[] = array('condition' => $like_statement, 'escape' => $escape); $this->qb_cache_exists[] = 'where'; } } return $this; } // -------------------------------------------------------------------- /** * Starts a query group. * * @param string $not (Internal use only) * @param string $type (Internal use only) * @return CI_DB_query_builder */ public function group_start($not = '', $type = 'AND ') { $type = $this->_group_get_type($type); $this->qb_where_group_started = TRUE; $prefix = (count($this->qb_where) === 0 && count($this->qb_cache_where) === 0) ? '' : $type; $where = array( 'condition' => $prefix.$not.str_repeat(' ', ++$this->qb_where_group_count).' (', 'escape' => FALSE ); $this->qb_where[] = $where; if ($this->qb_caching) { $this->qb_cache_where[] = $where; } return $this; } // -------------------------------------------------------------------- /** * Starts a query group, but ORs the group * * @return CI_DB_query_builder */ public function or_group_start() { return $this->group_start('', 'OR '); } // -------------------------------------------------------------------- /** * Starts a query group, but NOTs the group * * @return CI_DB_query_builder */ public function not_group_start() { return $this->group_start('NOT ', 'AND '); } // -------------------------------------------------------------------- /** * Starts a query group, but OR NOTs the group * * @return CI_DB_query_builder */ public function or_not_group_start() { return $this->group_start('NOT ', 'OR '); } // -------------------------------------------------------------------- /** * Ends a query group * * @return CI_DB_query_builder */ public function group_end() { $this->qb_where_group_started = FALSE; $where = array( 'condition' => str_repeat(' ', $this->qb_where_group_count--).')', 'escape' => FALSE ); $this->qb_where[] = $where; if ($this->qb_caching) { $this->qb_cache_where[] = $where; } return $this; } // -------------------------------------------------------------------- /** * Group_get_type * * @used-by group_start() * @used-by _like() * @used-by _wh() * @used-by _where_in() * * @param string $type * @return string */ protected function _group_get_type($type) { if ($this->qb_where_group_started) { $type = ''; $this->qb_where_group_started = FALSE; } return $type; } // -------------------------------------------------------------------- /** * GROUP BY * * @param string $by * @param bool $escape * @return CI_DB_query_builder */ public function group_by($by, $escape = NULL) { is_bool($escape) OR $escape = $this->_protect_identifiers; if (is_string($by)) { $by = ($escape === TRUE) ? explode(',', $by) : array($by); } foreach ($by as $val) { $val = trim($val); if ($val !== '') { $val = array('field' => $val, 'escape' => $escape); $this->qb_groupby[] = $val; if ($this->qb_caching === TRUE) { $this->qb_cache_groupby[] = $val; $this->qb_cache_exists[] = 'groupby'; } } } return $this; } // -------------------------------------------------------------------- /** * HAVING * * Separates multiple calls with 'AND'. * * @param string $key * @param string $value * @param bool $escape * @return CI_DB_query_builder */ public function having($key, $value = NULL, $escape = NULL) { return $this->_wh('qb_having', $key, $value, 'AND ', $escape); } // -------------------------------------------------------------------- /** * OR HAVING * * Separates multiple calls with 'OR'. * * @param string $key * @param string $value * @param bool $escape * @return CI_DB_query_builder */ public function or_having($key, $value = NULL, $escape = NULL) { return $this->_wh('qb_having', $key, $value, 'OR ', $escape); } // -------------------------------------------------------------------- /** * ORDER BY * * @param string $orderby * @param string $direction ASC, DESC or RANDOM * @param bool $escape * @return CI_DB_query_builder */ public function order_by($orderby, $direction = '', $escape = NULL) { $direction = strtoupper(trim($direction)); if ($direction === 'RANDOM') { $direction = ''; // Do we have a seed value? $orderby = ctype_digit((string) $orderby) ? sprintf($this->_random_keyword[1], $orderby) : $this->_random_keyword[0]; } elseif (empty($orderby)) { return $this; } elseif ($direction !== '') { $direction = in_array($direction, array('ASC', 'DESC'), TRUE) ? ' '.$direction : ''; } is_bool($escape) OR $escape = $this->_protect_identifiers; if ($escape === FALSE) { $qb_orderby[] = array('field' => $orderby, 'direction' => $direction, 'escape' => FALSE); } else { $qb_orderby = array(); foreach (explode(',', $orderby) as $field) { $qb_orderby[] = ($direction === '' && preg_match('/\s+(ASC|DESC)$/i', rtrim($field), $match, PREG_OFFSET_CAPTURE)) ? array('field' => ltrim(substr($field, 0, $match[0][1])), 'direction' => ' '.$match[1][0], 'escape' => TRUE) : array('field' => trim($field), 'direction' => $direction, 'escape' => TRUE); } } $this->qb_orderby = array_merge($this->qb_orderby, $qb_orderby); if ($this->qb_caching === TRUE) { $this->qb_cache_orderby = array_merge($this->qb_cache_orderby, $qb_orderby); $this->qb_cache_exists[] = 'orderby'; } return $this; } // -------------------------------------------------------------------- /** * LIMIT * * @param int $value LIMIT value * @param int $offset OFFSET value * @return CI_DB_query_builder */ public function limit($value, $offset = 0) { is_null($value) OR $this->qb_limit = (int) $value; empty($offset) OR $this->qb_offset = (int) $offset; return $this; } // -------------------------------------------------------------------- /** * Sets the OFFSET value * * @param int $offset OFFSET value * @return CI_DB_query_builder */ public function offset($offset) { empty($offset) OR $this->qb_offset = (int) $offset; return $this; } // -------------------------------------------------------------------- /** * LIMIT string * * Generates a platform-specific LIMIT clause. * * @param string $sql SQL Query * @return string */ protected function _limit($sql) { return $sql.' LIMIT '.($this->qb_offset ? $this->qb_offset.', ' : '').(int) $this->qb_limit; } // -------------------------------------------------------------------- /** * The "set" function. * * Allows key/value pairs to be set for inserting or updating * * @param mixed * @param string * @param bool * @return CI_DB_query_builder */ public function set($key, $value = '', $escape = NULL) { $key = $this->_object_to_array($key); if ( ! is_array($key)) { $key = array($key => $value); } is_bool($escape) OR $escape = $this->_protect_identifiers; foreach ($key as $k => $v) { $this->qb_set[$this->protect_identifiers($k, FALSE, $escape)] = ($escape) ? $this->escape($v) : $v; } return $this; } // -------------------------------------------------------------------- /** * Get SELECT query string * * Compiles a SELECT query string and returns the sql. * * @param string the table name to select from (optional) * @param bool TRUE: resets QB values; FALSE: leave QB values alone * @return string */ public function get_compiled_select($table = '', $reset = TRUE) { if ($table !== '') { $this->_track_aliases($table); $this->from($table); } $select = $this->_compile_select(); if ($reset === TRUE) { $this->_reset_select(); } return $select; } // -------------------------------------------------------------------- /** * Get * * Compiles the select statement based on the other functions called * and runs the query * * @param string the table * @param string the limit clause * @param string the offset clause * @return CI_DB_result */ public function get($table = '', $limit = NULL, $offset = NULL) { if ($table !== '') { $this->_track_aliases($table); $this->from($table); } if ( ! empty($limit)) { $this->limit($limit, $offset); } $result = $this->query($this->_compile_select()); $this->_reset_select(); return $result; } // -------------------------------------------------------------------- /** * "Count All Results" query * * Generates a platform-specific query string that counts all records * returned by an Query Builder query. * * @param string * @param bool the reset clause * @return int */ public function count_all_results($table = '', $reset = TRUE) { if ($table !== '') { $this->_track_aliases($table); $this->from($table); } // ORDER BY usage is often problematic here (most notably // on Microsoft SQL Server) and ultimately unnecessary // for selecting COUNT(*) ... if ( ! empty($this->qb_orderby)) { $orderby = $this->qb_orderby; $this->qb_orderby = NULL; } $result = ($this->qb_distinct === TRUE OR ! empty($this->qb_groupby) OR ! empty($this->qb_cache_groupby)) ? $this->query($this->_count_string.$this->protect_identifiers('numrows')."\nFROM (\n".$this->_compile_select()."\n) CI_count_all_results") : $this->query($this->_compile_select($this->_count_string.$this->protect_identifiers('numrows'))); if ($reset === TRUE) { $this->_reset_select(); } // If we've previously reset the qb_orderby values, get them back elseif ( ! isset($this->qb_orderby)) { $this->qb_orderby = $orderby; } if ($result->num_rows() === 0) { return 0; } $row = $result->row(); return (int) $row->numrows; } // -------------------------------------------------------------------- /** * Get_Where * * Allows the where clause, limit and offset to be added directly * * @param string $table * @param string $where * @param int $limit * @param int $offset * @return CI_DB_result */ public function get_where($table = '', $where = NULL, $limit = NULL, $offset = NULL) { if ($table !== '') { $this->from($table); } if ($where !== NULL) { $this->where($where); } if ( ! empty($limit)) { $this->limit($limit, $offset); } $result = $this->query($this->_compile_select()); $this->_reset_select(); return $result; } // -------------------------------------------------------------------- /** * Insert_Batch * * Compiles batch insert strings and runs the queries * * @param string $table Table to insert into * @param array $set An associative array of insert values * @param bool $escape Whether to escape values and identifiers * @return int Number of rows inserted or FALSE on failure */ public function insert_batch($table, $set = NULL, $escape = NULL, $batch_size = 100) { if ($set === NULL) { if (empty($this->qb_set)) { return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE; } } else { if (empty($set)) { return ($this->db_debug) ? $this->display_error('insert_batch() called with no data') : FALSE; } $this->set_insert_batch($set, '', $escape); } if (strlen($table) === 0) { if ( ! isset($this->qb_from[0])) { return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE; } $table = $this->qb_from[0]; } // Batch this baby $affected_rows = 0; for ($i = 0, $total = count($this->qb_set); $i < $total; $i += $batch_size) { if ($this->query($this->_insert_batch($this->protect_identifiers($table, TRUE, $escape, FALSE), $this->qb_keys, array_slice($this->qb_set, $i, $batch_size)))) { $affected_rows += $this->affected_rows(); } } $this->_reset_write(); return $affected_rows; } // -------------------------------------------------------------------- /** * Insert batch statement * * Generates a platform-specific insert string from the supplied data. * * @param string $table Table name * @param array $keys INSERT keys * @param array $values INSERT values * @return string */ protected function _insert_batch($table, $keys, $values) { return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES '.implode(', ', $values); } // -------------------------------------------------------------------- /** * The "set_insert_batch" function. Allows key/value pairs to be set for batch inserts * * @param mixed * @param string * @param bool * @return CI_DB_query_builder */ public function set_insert_batch($key, $value = '', $escape = NULL) { $key = $this->_object_to_array_batch($key); if ( ! is_array($key)) { $key = array($key => $value); } is_bool($escape) OR $escape = $this->_protect_identifiers; $keys = array_keys($this->_object_to_array(current($key))); sort($keys); foreach ($key as $row) { $row = $this->_object_to_array($row); if (count(array_diff($keys, array_keys($row))) > 0 OR count(array_diff(array_keys($row), $keys)) > 0) { // batch function above returns an error on an empty array $this->qb_set[] = array(); return; } ksort($row); // puts $row in the same order as our keys if ($escape !== FALSE) { $clean = array(); foreach ($row as $value) { $clean[] = $this->escape($value); } $row = $clean; } $this->qb_set[] = '('.implode(',', $row).')'; } foreach ($keys as $k) { $this->qb_keys[] = $this->protect_identifiers($k, FALSE, $escape); } return $this; } // -------------------------------------------------------------------- /** * Get INSERT query string * * Compiles an insert query and returns the sql * * @param string the table to insert into * @param bool TRUE: reset QB values; FALSE: leave QB values alone * @return string */ public function get_compiled_insert($table = '', $reset = TRUE) { if ($this->_validate_insert($table) === FALSE) { return FALSE; } $sql = $this->_insert( $this->protect_identifiers( $this->qb_from[0], TRUE, NULL, FALSE ), array_keys($this->qb_set), array_values($this->qb_set) ); if ($reset === TRUE) { $this->_reset_write(); } return $sql; } // -------------------------------------------------------------------- /** * Insert * * Compiles an insert string and runs the query * * @param string the table to insert data into * @param array an associative array of insert values * @param bool $escape Whether to escape values and identifiers * @return bool TRUE on success, FALSE on failure */ public function insert($table = '', $set = NULL, $escape = NULL) { if ($set !== NULL) { $this->set($set, '', $escape); } if ($this->_validate_insert($table) === FALSE) { return FALSE; } $sql = $this->_insert( $this->protect_identifiers( $this->qb_from[0], TRUE, $escape, FALSE ), array_keys($this->qb_set), array_values($this->qb_set) ); $this->_reset_write(); return $this->query($sql); } // -------------------------------------------------------------------- /** * Validate Insert * * This method is used by both insert() and get_compiled_insert() to * validate that the there data is actually being set and that table * has been chosen to be inserted into. * * @param string the table to insert data into * @return string */ protected function _validate_insert($table = '') { if (count($this->qb_set) === 0) { return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE; } if ($table !== '') { $this->qb_from[0] = $table; } elseif ( ! isset($this->qb_from[0])) { return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE; } return TRUE; } // -------------------------------------------------------------------- /** * Replace * * Compiles an replace into string and runs the query * * @param string the table to replace data into * @param array an associative array of insert values * @return bool TRUE on success, FALSE on failure */ public function replace($table = '', $set = NULL) { if ($set !== NULL) { $this->set($set); } if (count($this->qb_set) === 0) { return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE; } if ($table === '') { if ( ! isset($this->qb_from[0])) { return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE; } $table = $this->qb_from[0]; } $sql = $this->_replace($this->protect_identifiers($table, TRUE, NULL, FALSE), array_keys($this->qb_set), array_values($this->qb_set)); $this->_reset_write(); return $this->query($sql); } // -------------------------------------------------------------------- /** * Replace statement * * Generates a platform-specific replace string from the supplied data * * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ protected function _replace($table, $keys, $values) { return 'REPLACE INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')'; } // -------------------------------------------------------------------- /** * FROM tables * * Groups tables in FROM clauses if needed, so there is no confusion * about operator precedence. * * Note: This is only used (and overridden) by MySQL and CUBRID. * * @return string */ protected function _from_tables() { return implode(', ', $this->qb_from); } // -------------------------------------------------------------------- /** * Get UPDATE query string * * Compiles an update query and returns the sql * * @param string the table to update * @param bool TRUE: reset QB values; FALSE: leave QB values alone * @return string */ public function get_compiled_update($table = '', $reset = TRUE) { // Combine any cached components with the current statements $this->_merge_cache(); if ($this->_validate_update($table) === FALSE) { return FALSE; } $sql = $this->_update($this->qb_from[0], $this->qb_set); if ($reset === TRUE) { $this->_reset_write(); } return $sql; } // -------------------------------------------------------------------- /** * UPDATE * * Compiles an update string and runs the query. * * @param string $table * @param array $set An associative array of update values * @param mixed $where * @param int $limit * @return bool TRUE on success, FALSE on failure */ public function update($table = '', $set = NULL, $where = NULL, $limit = NULL) { // Combine any cached components with the current statements $this->_merge_cache(); if ($set !== NULL) { $this->set($set); } if ($this->_validate_update($table) === FALSE) { return FALSE; } if ($where !== NULL) { $this->where($where); } if ( ! empty($limit)) { $this->limit($limit); } $sql = $this->_update($this->qb_from[0], $this->qb_set); $this->_reset_write(); return $this->query($sql); } // -------------------------------------------------------------------- /** * Validate Update * * This method is used by both update() and get_compiled_update() to * validate that data is actually being set and that a table has been * chosen to be update. * * @param string the table to update data on * @return bool */ protected function _validate_update($table) { if (count($this->qb_set) === 0) { return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE; } if ($table !== '') { $this->qb_from = array($this->protect_identifiers($table, TRUE, NULL, FALSE)); } elseif ( ! isset($this->qb_from[0])) { return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE; } return TRUE; } // -------------------------------------------------------------------- /** * Update_Batch * * Compiles an update string and runs the query * * @param string the table to retrieve the results from * @param array an associative array of update values * @param string the where key * @return int number of rows affected or FALSE on failure */ public function update_batch($table, $set = NULL, $index = NULL, $batch_size = 100) { // Combine any cached components with the current statements $this->_merge_cache(); if ($index === NULL) { return ($this->db_debug) ? $this->display_error('db_must_use_index') : FALSE; } if ($set === NULL) { if (empty($this->qb_set_ub)) { return ($this->db_debug) ? $this->display_error('db_must_use_set') : FALSE; } } else { if (empty($set)) { return ($this->db_debug) ? $this->display_error('update_batch() called with no data') : FALSE; } $this->set_update_batch($set, $index); } if (strlen($table) === 0) { if ( ! isset($this->qb_from[0])) { return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE; } $table = $this->qb_from[0]; } // Batch this baby $affected_rows = 0; for ($i = 0, $total = count($this->qb_set_ub); $i < $total; $i += $batch_size) { if ($this->query($this->_update_batch($this->protect_identifiers($table, TRUE, NULL, FALSE), array_slice($this->qb_set_ub, $i, $batch_size), $index))) { $affected_rows += $this->affected_rows(); } $this->qb_where = array(); } $this->_reset_write(); return $affected_rows; } // -------------------------------------------------------------------- /** * Update_Batch statement * * Generates a platform-specific batch update string from the supplied data * * @param string $table Table name * @param array $values Update data * @param string $index WHERE key * @return string */ protected function _update_batch($table, $values, $index) { $ids = array(); foreach ($values as $key => $val) { $ids[] = $val[$index]['value']; foreach (array_keys($val) as $field) { if ($field !== $index) { $final[$val[$field]['field']][] = 'WHEN '.$val[$index]['field'].' = '.$val[$index]['value'].' THEN '.$val[$field]['value']; } } } $cases = ''; foreach ($final as $k => $v) { $cases .= $k." = CASE \n" .implode("\n", $v)."\n" .'ELSE '.$k.' END, '; } $this->where($val[$index]['field'].' IN('.implode(',', $ids).')', NULL, FALSE); return 'UPDATE '.$table.' SET '.substr($cases, 0, -2).$this->_compile_wh('qb_where'); } // -------------------------------------------------------------------- /** * The "set_update_batch" function. Allows key/value pairs to be set for batch updating * * @param array * @param string * @param bool * @return CI_DB_query_builder */ public function set_update_batch($key, $index = '', $escape = NULL) { $key = $this->_object_to_array_batch($key); if ( ! is_array($key)) { // @todo error } is_bool($escape) OR $escape = $this->_protect_identifiers; foreach ($key as $k => $v) { $index_set = FALSE; $clean = array(); foreach ($v as $k2 => $v2) { if ($k2 === $index) { $index_set = TRUE; } $clean[$k2] = array( 'field' => $this->protect_identifiers($k2, FALSE, $escape), 'value' => ($escape === FALSE ? $v2 : $this->escape($v2)) ); } if ($index_set === FALSE) { return $this->display_error('db_batch_missing_index'); } $this->qb_set_ub[] = $clean; } return $this; } // -------------------------------------------------------------------- /** * Empty Table * * Compiles a delete string and runs "DELETE FROM table" * * @param string the table to empty * @return bool TRUE on success, FALSE on failure */ public function empty_table($table = '') { if ($table === '') { if ( ! isset($this->qb_from[0])) { return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE; } $table = $this->qb_from[0]; } else { $table = $this->protect_identifiers($table, TRUE, NULL, FALSE); } $sql = $this->_delete($table); $this->_reset_write(); return $this->query($sql); } // -------------------------------------------------------------------- /** * Truncate * * Compiles a truncate string and runs the query * If the database does not support the truncate() command * This function maps to "DELETE FROM table" * * @param string the table to truncate * @return bool TRUE on success, FALSE on failure */ public function truncate($table = '') { if ($table === '') { if ( ! isset($this->qb_from[0])) { return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE; } $table = $this->qb_from[0]; } else { $table = $this->protect_identifiers($table, TRUE, NULL, FALSE); } $sql = $this->_truncate($table); $this->_reset_write(); return $this->query($sql); } // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data * * If the database does not support the truncate() command, * then this method maps to 'DELETE FROM table' * * @param string the table name * @return string */ protected function _truncate($table) { return 'TRUNCATE '.$table; } // -------------------------------------------------------------------- /** * Get DELETE query string * * Compiles a delete query string and returns the sql * * @param string the table to delete from * @param bool TRUE: reset QB values; FALSE: leave QB values alone * @return string */ public function get_compiled_delete($table = '', $reset = TRUE) { $this->return_delete_sql = TRUE; $sql = $this->delete($table, '', NULL, $reset); $this->return_delete_sql = FALSE; return $sql; } // -------------------------------------------------------------------- /** * Delete * * Compiles a delete string and runs the query * * @param mixed the table(s) to delete from. String or array * @param mixed the where clause * @param mixed the limit clause * @param bool * @return mixed */ public function delete($table = '', $where = '', $limit = NULL, $reset_data = TRUE) { // Combine any cached components with the current statements $this->_merge_cache(); if ($table === '') { if ( ! isset($this->qb_from[0])) { return ($this->db_debug) ? $this->display_error('db_must_set_table') : FALSE; } $table = $this->qb_from[0]; } elseif (is_array($table)) { empty($where) && $reset_data = FALSE; foreach ($table as $single_table) { $this->delete($single_table, $where, $limit, $reset_data); } return; } else { $table = $this->protect_identifiers($table, TRUE, NULL, FALSE); } if ($where !== '') { $this->where($where); } if ( ! empty($limit)) { $this->limit($limit); } if (count($this->qb_where) === 0) { return ($this->db_debug) ? $this->display_error('db_del_must_use_where') : FALSE; } $sql = $this->_delete($table); if ($reset_data) { $this->_reset_write(); } return ($this->return_delete_sql === TRUE) ? $sql : $this->query($sql); } // -------------------------------------------------------------------- /** * Delete statement * * Generates a platform-specific delete string from the supplied data * * @param string the table name * @return string */ protected function _delete($table) { return 'DELETE FROM '.$table.$this->_compile_wh('qb_where') .($this->qb_limit ? ' LIMIT '.$this->qb_limit : ''); } // -------------------------------------------------------------------- /** * DB Prefix * * Prepends a database prefix if one exists in configuration * * @param string the table * @return string */ public function dbprefix($table = '') { if ($table === '') { $this->display_error('db_table_name_required'); } return $this->dbprefix.$table; } // -------------------------------------------------------------------- /** * Set DB Prefix * * Set's the DB Prefix to something new without needing to reconnect * * @param string the prefix * @return string */ public function set_dbprefix($prefix = '') { return $this->dbprefix = $prefix; } // -------------------------------------------------------------------- /** * Track Aliases * * Used to track SQL statements written with aliased tables. * * @param string The table to inspect * @return string */ protected function _track_aliases($table) { if (is_array($table)) { foreach ($table as $t) { $this->_track_aliases($t); } return; } // Does the string contain a comma? If so, we need to separate // the string into discreet statements if (strpos($table, ',') !== FALSE) { return $this->_track_aliases(explode(',', $table)); } // if a table alias is used we can recognize it by a space if (strpos($table, ' ') !== FALSE) { // if the alias is written with the AS keyword, remove it $table = preg_replace('/\s+AS\s+/i', ' ', $table); // Grab the alias $table = trim(strrchr($table, ' ')); // Store the alias, if it doesn't already exist if ( ! in_array($table, $this->qb_aliased_tables)) { $this->qb_aliased_tables[] = $table; } } } // -------------------------------------------------------------------- /** * Compile the SELECT statement * * Generates a query string based on which functions were used. * Should not be called directly. * * @param bool $select_override * @return string */ protected function _compile_select($select_override = FALSE) { // Combine any cached components with the current statements $this->_merge_cache(); // Write the "select" portion of the query if ($select_override !== FALSE) { $sql = $select_override; } else { $sql = ( ! $this->qb_distinct) ? 'SELECT ' : 'SELECT DISTINCT '; if (count($this->qb_select) === 0) { $sql .= '*'; } else { // Cycle through the "select" portion of the query and prep each column name. // The reason we protect identifiers here rather than in the select() function // is because until the user calls the from() function we don't know if there are aliases foreach ($this->qb_select as $key => $val) { $no_escape = isset($this->qb_no_escape[$key]) ? $this->qb_no_escape[$key] : NULL; $this->qb_select[$key] = $this->protect_identifiers($val, FALSE, $no_escape); } $sql .= implode(', ', $this->qb_select); } } // Write the "FROM" portion of the query if (count($this->qb_from) > 0) { $sql .= "\nFROM ".$this->_from_tables(); } // Write the "JOIN" portion of the query if (count($this->qb_join) > 0) { $sql .= "\n".implode("\n", $this->qb_join); } $sql .= $this->_compile_wh('qb_where') .$this->_compile_group_by() .$this->_compile_wh('qb_having') .$this->_compile_order_by(); // ORDER BY // LIMIT if ($this->qb_limit OR $this->qb_offset) { return $this->_limit($sql."\n"); } return $sql; } // -------------------------------------------------------------------- /** * Compile WHERE, HAVING statements * * Escapes identifiers in WHERE and HAVING statements at execution time. * * Required so that aliases are tracked properly, regardless of whether * where(), or_where(), having(), or_having are called prior to from(), * join() and dbprefix is added only if needed. * * @param string $qb_key 'qb_where' or 'qb_having' * @return string SQL statement */ protected function _compile_wh($qb_key) { if (count($this->$qb_key) > 0) { for ($i = 0, $c = count($this->$qb_key); $i < $c; $i++) { // Is this condition already compiled? if (is_string($this->{$qb_key}[$i])) { continue; } elseif ($this->{$qb_key}[$i]['escape'] === FALSE) { $this->{$qb_key}[$i] = $this->{$qb_key}[$i]['condition']; continue; } // Split multiple conditions $conditions = preg_split( '/((?:^|\s+)AND\s+|(?:^|\s+)OR\s+)/i', $this->{$qb_key}[$i]['condition'], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY ); for ($ci = 0, $cc = count($conditions); $ci < $cc; $ci++) { if (($op = $this->_get_operator($conditions[$ci])) === FALSE OR ! preg_match('/^(\(?)(.*)('.preg_quote($op, '/').')\s*(.*(?<!\)))?(\)?)$/i', $conditions[$ci], $matches)) { continue; } // $matches = array( // 0 => '(test <= foo)', /* the whole thing */ // 1 => '(', /* optional */ // 2 => 'test', /* the field name */ // 3 => ' <= ', /* $op */ // 4 => 'foo', /* optional, if $op is e.g. 'IS NULL' */ // 5 => ')' /* optional */ // ); if ( ! empty($matches[4])) { $this->_is_literal($matches[4]) OR $matches[4] = $this->protect_identifiers(trim($matches[4])); $matches[4] = ' '.$matches[4]; } $conditions[$ci] = $matches[1].$this->protect_identifiers(trim($matches[2])) .' '.trim($matches[3]).$matches[4].$matches[5]; } $this->{$qb_key}[$i] = implode('', $conditions); } return ($qb_key === 'qb_having' ? "\nHAVING " : "\nWHERE ") .implode("\n", $this->$qb_key); } return ''; } // -------------------------------------------------------------------- /** * Compile GROUP BY * * Escapes identifiers in GROUP BY statements at execution time. * * Required so that aliases are tracked properly, regardless of wether * group_by() is called prior to from(), join() and dbprefix is added * only if needed. * * @return string SQL statement */ protected function _compile_group_by() { if (count($this->qb_groupby) > 0) { for ($i = 0, $c = count($this->qb_groupby); $i < $c; $i++) { // Is it already compiled? if (is_string($this->qb_groupby[$i])) { continue; } $this->qb_groupby[$i] = ($this->qb_groupby[$i]['escape'] === FALSE OR $this->_is_literal($this->qb_groupby[$i]['field'])) ? $this->qb_groupby[$i]['field'] : $this->protect_identifiers($this->qb_groupby[$i]['field']); } return "\nGROUP BY ".implode(', ', $this->qb_groupby); } return ''; } // -------------------------------------------------------------------- /** * Compile ORDER BY * * Escapes identifiers in ORDER BY statements at execution time. * * Required so that aliases are tracked properly, regardless of wether * order_by() is called prior to from(), join() and dbprefix is added * only if needed. * * @return string SQL statement */ protected function _compile_order_by() { if (is_array($this->qb_orderby) && count($this->qb_orderby) > 0) { for ($i = 0, $c = count($this->qb_orderby); $i < $c; $i++) { if ($this->qb_orderby[$i]['escape'] !== FALSE && ! $this->_is_literal($this->qb_orderby[$i]['field'])) { $this->qb_orderby[$i]['field'] = $this->protect_identifiers($this->qb_orderby[$i]['field']); } $this->qb_orderby[$i] = $this->qb_orderby[$i]['field'].$this->qb_orderby[$i]['direction']; } return $this->qb_orderby = "\nORDER BY ".implode(', ', $this->qb_orderby); } elseif (is_string($this->qb_orderby)) { return $this->qb_orderby; } return ''; } // -------------------------------------------------------------------- /** * Object to Array * * Takes an object as input and converts the class variables to array key/vals * * @param object * @return array */ protected function _object_to_array($object) { if ( ! is_object($object)) { return $object; } $array = array(); foreach (get_object_vars($object) as $key => $val) { // There are some built in keys we need to ignore for this conversion if ( ! is_object($val) && ! is_array($val) && $key !== '_parent_name') { $array[$key] = $val; } } return $array; } // -------------------------------------------------------------------- /** * Object to Array * * Takes an object as input and converts the class variables to array key/vals * * @param object * @return array */ protected function _object_to_array_batch($object) { if ( ! is_object($object)) { return $object; } $array = array(); $out = get_object_vars($object); $fields = array_keys($out); foreach ($fields as $val) { // There are some built in keys we need to ignore for this conversion if ($val !== '_parent_name') { $i = 0; foreach ($out[$val] as $data) { $array[$i++][$val] = $data; } } } return $array; } // -------------------------------------------------------------------- /** * Start Cache * * Starts QB caching * * @return CI_DB_query_builder */ public function start_cache() { $this->qb_caching = TRUE; return $this; } // -------------------------------------------------------------------- /** * Stop Cache * * Stops QB caching * * @return CI_DB_query_builder */ public function stop_cache() { $this->qb_caching = FALSE; return $this; } // -------------------------------------------------------------------- /** * Flush Cache * * Empties the QB cache * * @return CI_DB_query_builder */ public function flush_cache() { $this->_reset_run(array( 'qb_cache_select' => array(), 'qb_cache_from' => array(), 'qb_cache_join' => array(), 'qb_cache_where' => array(), 'qb_cache_groupby' => array(), 'qb_cache_having' => array(), 'qb_cache_orderby' => array(), 'qb_cache_set' => array(), 'qb_cache_exists' => array(), 'qb_cache_no_escape' => array() )); return $this; } // -------------------------------------------------------------------- /** * Merge Cache * * When called, this function merges any cached QB arrays with * locally called ones. * * @return void */ protected function _merge_cache() { if (count($this->qb_cache_exists) === 0) { return; } elseif (in_array('select', $this->qb_cache_exists, TRUE)) { $qb_no_escape = $this->qb_cache_no_escape; } foreach (array_unique($this->qb_cache_exists) as $val) // select, from, etc. { $qb_variable = 'qb_'.$val; $qb_cache_var = 'qb_cache_'.$val; $qb_new = $this->$qb_cache_var; for ($i = 0, $c = count($this->$qb_variable); $i < $c; $i++) { if ( ! in_array($this->{$qb_variable}[$i], $qb_new, TRUE)) { $qb_new[] = $this->{$qb_variable}[$i]; if ($val === 'select') { $qb_no_escape[] = $this->qb_no_escape[$i]; } } } $this->$qb_variable = $qb_new; if ($val === 'select') { $this->qb_no_escape = $qb_no_escape; } } // If we are "protecting identifiers" we need to examine the "from" // portion of the query to determine if there are any aliases if ($this->_protect_identifiers === TRUE && count($this->qb_cache_from) > 0) { $this->_track_aliases($this->qb_from); } } // -------------------------------------------------------------------- /** * Is literal * * Determines if a string represents a literal value or a field name * * @param string $str * @return bool */ protected function _is_literal($str) { $str = trim($str); if (empty($str) OR ctype_digit($str) OR (string) (float) $str === $str OR in_array(strtoupper($str), array('TRUE', 'FALSE'), TRUE)) { return TRUE; } static $_str; if (empty($_str)) { $_str = ($this->_escape_char !== '"') ? array('"', "'") : array("'"); } return in_array($str[0], $_str, TRUE); } // -------------------------------------------------------------------- /** * Reset Query Builder values. * * Publicly-visible method to reset the QB values. * * @return CI_DB_query_builder */ public function reset_query() { $this->_reset_select(); $this->_reset_write(); return $this; } // -------------------------------------------------------------------- /** * Resets the query builder values. Called by the get() function * * @param array An array of fields to reset * @return void */ protected function _reset_run($qb_reset_items) { foreach ($qb_reset_items as $item => $default_value) { $this->$item = $default_value; } } // -------------------------------------------------------------------- /** * Resets the query builder values. Called by the get() function * * @return void */ protected function _reset_select() { $this->_reset_run(array( 'qb_select' => array(), 'qb_from' => array(), 'qb_join' => array(), 'qb_where' => array(), 'qb_groupby' => array(), 'qb_having' => array(), 'qb_orderby' => array(), 'qb_aliased_tables' => array(), 'qb_no_escape' => array(), 'qb_distinct' => FALSE, 'qb_limit' => FALSE, 'qb_offset' => FALSE )); } // -------------------------------------------------------------------- /** * Resets the query builder "write" values. * * Called by the insert() update() insert_batch() update_batch() and delete() functions * * @return void */ protected function _reset_write() { $this->_reset_run(array( 'qb_set' => array(), 'qb_set_ub' => array(), 'qb_from' => array(), 'qb_join' => array(), 'qb_where' => array(), 'qb_orderby' => array(), 'qb_keys' => array(), 'qb_limit' => FALSE )); } }
gpl-3.0
Metabolix/PutkaRTS
src/gui/widget/Label.hpp
1575
#ifndef PUTKARTS_GUI_Widget_Label_HPP #define PUTKARTS_GUI_Widget_Label_HPP #include "Widget.hpp" namespace GUI { namespace Widget { class Label; } } /** * Class for the Label widget. */ class GUI::Widget::Label: public Widget { /** Text for the label. */ sf::Text label; /** Is the label centered? */ bool isCentered; public: /** * Create a Label. * * @param text Text to render. * @param x X coordinate of the text. * @param y Y coordinate of the text. * @param height Height of the text. */ Label(const std::string& text = "", float x = 0, float y = 0, float height = 8); /** * Create a Label. * * @param text Text to render. * @param x X coordinate of the text. * @param y Y coordinate of the text. * @param width Maximum width of the text. * @param height Maximum height of the text. */ Label(const std::string& text, float x, float y, float width, float height); /** * Set the text. * * @param text The text. */ virtual void setText(const std::string& text); /** * Set whether the text is centered or aligned to left. * * @param isCentered_ Is the text centered? */ virtual void setCentered(bool isCentered_) { isCentered = isCentered_; } /** * Handle events. * * @param e The event. * @param window The window of the event. * @return Always false. */ virtual bool handleEvent(const sf::Event& e, const sf::RenderWindow& window) { return false; } /** * Draw the Label. * * @param window The render window. */ virtual void draw(sf::RenderWindow& window); }; #endif
gpl-3.0
KineticIsEpic/CadenciiStudio
src/Cadencii/MidiDeviceImp.cs
1683
#if !JAVA /* * MidiDeviceImp.cs * Copyright © 2009-2011 kbinani * * This file is part of cadencii. * * cadencii is free software; you can redistribute it and/or * modify it under the terms of the GPLv3 License. * * cadencii 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. */ using System; using System.Collections.Generic; using cadencii.media; namespace cadencii { using boolean = Boolean; public class MidiDeviceImp { const int CHANNEL = 16; private MidiOutDevice s_device; private int[] s_last_program = new int[CHANNEL]; private boolean s_initialized = false; public boolean Initialized { get { return s_initialized; } } public MidiDeviceImp( uint device_id ){ s_device = new MidiOutDevice( device_id ); s_initialized = true; for ( int i = 0; i < CHANNEL; i++ ) { s_last_program[i] = -1; } } public void Play( byte channel, byte program, byte note, byte velocity ) { if ( CHANNEL < channel ) { return; } if ( s_last_program[channel] != program ) { s_device.ProgramChange( channel, program ); s_last_program[channel] = program; } s_device.Play( channel, note, velocity ); } public void Terminate() { if ( s_initialized && s_device != null ) { s_device.Close(); } } } } #endif
gpl-3.0
SecurityFTW/cs-suite
tools/Scout2/AWSScout2/services/s3.py
14329
# -*- coding: utf-8 -*- """ S3-related classes and functions """ import json from botocore.exceptions import ClientError from opinel.utils.aws import connect_service, handle_truncated_response from opinel.utils.console import printError, printException, printInfo from opinel.utils.globals import manage_dictionary from opinel.services.s3 import get_s3_bucket_location from AWSScout2.configs.base import BaseConfig ######################################## # S3Config ######################################## class S3Config(BaseConfig): """ S3 configuration for all AWS regions :cvar targets: Tuple with all S3 resource names that may be fetched """ targets = ( ('buckets', 'Buckets', 'list_buckets', {}, False), ) def __init__(self, thread_config): self.buckets = {} self.buckets_count = 0 super(S3Config, self).__init__(thread_config) def parse_buckets(self, bucket, params): """ Parse a single S3 bucket TODO """ bucket['name'] = bucket.pop('Name') api_client = params['api_clients'][get_s3_list_region(list(params['api_clients'].keys())[0])] bucket['CreationDate'] = str(bucket['CreationDate']) bucket['region'] = get_s3_bucket_location(api_client, bucket['name']) # h4ck :: fix issue #59, location constraint can be EU or eu-west-1 for Ireland... if bucket['region'] == 'EU': bucket['region'] = 'eu-west-1' # h4ck :: S3 is global but region-aware... if bucket['region'] not in params['api_clients']: printInfo('Skipping bucket %s (region %s outside of scope)' % (bucket['name'], bucket['region'])) self.buckets_count -= 1 return api_client = params['api_clients'][bucket['region']] get_s3_bucket_logging(api_client, bucket['name'], bucket) get_s3_bucket_versioning(api_client, bucket['name'], bucket) get_s3_bucket_webhosting(api_client, bucket['name'], bucket) bucket['grantees'] = get_s3_acls(api_client, bucket['name'], bucket) # TODO: # CORS # Lifecycle # Notification ? # Get bucket's policy get_s3_bucket_policy(api_client, bucket['name'], bucket) # If requested, get key properties #if params['check_encryption'] or params['check_acls']: # get_s3_bucket_keys(api_client, bucket['name'], bucket, params['check_encryption'], # params['check_acls']) bucket['id'] = self.get_non_aws_id(bucket['name']) self.buckets[bucket['id']] = bucket def match_iam_policies_and_buckets(s3_info, iam_info): if 'Action' in iam_info['permissions']: for action in (x for x in iam_info['permissions']['Action'] if ((x.startswith('s3:') and x != 's3:ListAllMyBuckets') or (x == '*'))): for iam_entity in iam_info['permissions']['Action'][action]: if 'Allow' in iam_info['permissions']['Action'][action][iam_entity]: for allowed_iam_entity in iam_info['permissions']['Action'][action][iam_entity]['Allow']: # For resource statements, we can easily rely on the existing permissions structure if 'Resource' in iam_info['permissions']['Action'][action][iam_entity]['Allow'][allowed_iam_entity]: for full_path in (x for x in iam_info['permissions']['Action'][action][iam_entity]['Allow'][allowed_iam_entity]['Resource'] if x.startswith('arn:aws:s3:') or x == '*'): parts = full_path.split('/') bucket_name = parts[0].split(':')[-1] update_iam_permissions(s3_info, bucket_name, iam_entity, allowed_iam_entity, iam_info['permissions']['Action'][action][iam_entity]['Allow'][allowed_iam_entity]['Resource'][full_path]) # For notresource statements, we must fetch the policy document to determine which buckets are not protected if 'NotResource' in iam_info['permissions']['Action'][action][iam_entity]['Allow'][allowed_iam_entity]: for full_path in (x for x in iam_info['permissions']['Action'][action][iam_entity]['Allow'][allowed_iam_entity]['NotResource'] if x.startswith('arn:aws:s3:') or x == '*'): for policy_type in ['InlinePolicies', 'ManagedPolicies']: if policy_type in iam_info['permissions']['Action'][action][iam_entity]['Allow'][allowed_iam_entity]['NotResource'][full_path]: for policy in iam_info['permissions']['Action'][action][iam_entity]['Allow'][allowed_iam_entity]['NotResource'][full_path][policy_type]: update_bucket_permissions(s3_info, iam_info, action, iam_entity, allowed_iam_entity, full_path, policy_type, policy) def update_iam_permissions(s3_info, bucket_name, iam_entity, allowed_iam_entity, policy_info): if bucket_name != '*' and bucket_name in s3_info['buckets']: bucket = s3_info['buckets'][bucket_name] manage_dictionary(bucket, iam_entity, {}) manage_dictionary(bucket, iam_entity + '_count', 0) if not allowed_iam_entity in bucket[iam_entity]: bucket[iam_entity][allowed_iam_entity] = {} bucket[iam_entity + '_count'] = bucket[iam_entity + '_count'] + 1 if 'inline_policies' in policy_info: manage_dictionary(bucket[iam_entity][allowed_iam_entity], 'inline_policies', {}) bucket[iam_entity][allowed_iam_entity]['inline_policies'].update(policy_info['inline_policies']) if 'policies' in policy_info: manage_dictionary(bucket[iam_entity][allowed_iam_entity], 'policies', {}) bucket[iam_entity][allowed_iam_entity]['policies'].update(policy_info['policies']) elif bucket_name == '*': for bucket in s3_info['buckets']: update_iam_permissions(s3_info, bucket, iam_entity, allowed_iam_entity, policy_info) pass else: # Could be an error or cross-account access, ignore... pass def update_bucket_permissions(s3_info, iam_info, action, iam_entity, allowed_iam_entity, full_path, policy_type, policy_name): allowed_buckets = [] # By default, all buckets are allowed for bucket_name in s3_info['buckets']: allowed_buckets.append(bucket_name) if policy_type == 'InlinePolicies': policy = iam_info[iam_entity.title()][allowed_iam_entity]['Policies'][policy_name]['PolicyDocument'] elif policy_type == 'ManagedPolicies': policy = iam_info['ManagedPolicies'][policy_name]['PolicyDocument'] else: printError('Error, found unknown policy type.') for statement in policy['Statement']: for target_path in statement['NotResource']: parts = target_path.split('/') bucket_name = parts[0].split(':')[-1] path = '/' + '/'.join(parts[1:]) if len(parts) > 1 else '/' if (path == '/' or path == '/*') and (bucket_name in allowed_buckets): # Remove bucket from list allowed_buckets.remove(bucket_name) elif bucket_name == '*': allowed_buckets = [] policy_info = {} policy_info[policy_type] = {} policy_info[policy_type][policy_name] = iam_info['permissions']['Action'][action][iam_entity]['Allow'][allowed_iam_entity]['NotResource'][full_path][policy_type][policy_name] for bucket_name in allowed_buckets: update_iam_permissions(s3_info, bucket_name, iam_entity, allowed_iam_entity, policy_info) def init_s3_permissions(): permissions = {} permissions['read'] = False permissions['write'] = False permissions['read_acp'] = False permissions['write_acp'] = False return permissions def set_s3_permissions(permissions, name): if name == 'READ' or name == 'FULL_CONTROL': permissions['read'] = True if name == 'WRITE' or name == 'FULL_CONTROL': permissions['write'] = True if name == 'READ_ACP' or name == 'FULL_CONTROL': permissions['read_acp'] = True if name == 'WRITE_ACP' or name == 'FULL_CONTROL': permissions['write_acp'] = True def s3_group_to_string(uri): if uri == 'http://acs.amazonaws.com/groups/global/AuthenticatedUsers': return 'Authenticated users' elif uri == 'http://acs.amazonaws.com/groups/global/AllUsers': return 'Everyone' elif uri == 'http://acs.amazonaws.com/groups/s3/LogDelivery': return 'Log delivery' else: return uri def get_s3_acls(api_client, bucket_name, bucket, key_name = None): try: grantees = {} if key_name: grants = api_client.get_object_acl(Bucket = bucket_name, Key = key_name) else: grants = api_client.get_bucket_acl(Bucket = bucket_name) for grant in grants['Grants']: if 'ID' in grant['Grantee']: grantee = grant['Grantee']['ID'] display_name = grant['Grantee']['DisplayName'] if 'DisplayName' in grant['Grantee'] else grant['Grantee']['ID'] elif 'URI' in grant['Grantee']: grantee = grant['Grantee']['URI'].split('/')[-1] display_name = s3_group_to_string(grant['Grantee']['URI']) else: grantee = display_name = 'Unknown' permission = grant['Permission'] manage_dictionary(grantees, grantee, {}) grantees[grantee]['DisplayName'] = display_name if 'URI' in grant['Grantee']: grantees[grantee]['URI'] = grant['Grantee']['URI'] manage_dictionary(grantees[grantee], 'permissions', init_s3_permissions()) set_s3_permissions(grantees[grantee]['permissions'], permission) return grantees except Exception as e: printException(e) def get_s3_bucket_policy(api_client, bucket_name, bucket_info): try: bucket_info['policy'] = json.loads(api_client.get_bucket_policy(Bucket = bucket_name)['Policy']) except Exception as e: if type(e) == ClientError and e.response['Error']['Code'] == 'NoSuchBucketPolicy': pass else: printException(e) def get_s3_bucket_versioning(api_client, bucket_name, bucket_info): try: versioning = api_client.get_bucket_versioning(Bucket = bucket_name) bucket_info['versioning_status'] = versioning['Status'] if 'Status' in versioning else 'Disabled' bucket_info['version_mfa_delete'] = versioning['MFADelete'] if 'MFADelete' in versioning else 'Disabled' except Exception as e: bucket_info['versioning_status'] = 'Unknown' bucket_info['version_mfa_delete'] = 'Unknown' def get_s3_bucket_logging(api_client, bucket_name, bucket_info): try: logging = api_client.get_bucket_logging(Bucket = bucket_name) if 'LoggingEnabled' in logging: bucket_info['logging'] = logging['LoggingEnabled']['TargetBucket'] + '/' + logging['LoggingEnabled']['TargetPrefix'] bucket_info['logging_stuff'] = logging else: bucket_info['logging'] = 'Disabled' except Exception as e: printError('Failed to get logging configuration for %s' % bucket_name) printException(e) bucket_info['logging'] = 'Unknown' def get_s3_bucket_webhosting(api_client, bucket_name, bucket_info): try: result = api_client.get_bucket_website(Bucket = bucket_name) bucket_info['web_hosting'] = 'Enabled' if 'IndexDocument' in result else 'Disabled' except Exception as e: # TODO: distinguish permission denied from 'NoSuchWebsiteConfiguration' errors bucket_info['web_hosting'] = 'Disabled' pass # List all available buckets def get_s3_buckets(api_client, s3_info, s3_params): manage_dictionary(s3_info, 'buckets', {}) buckets = api_client[get_s3_list_region(s3_params['selected_regions'])].list_buckets()['Buckets'] targets = [] for b in buckets: # Abort if bucket is not of interest if (b['Name'] in s3_params['skipped_buckets']) or (len(s3_params['checked_buckets']) and b['Name'] not in s3_params['checked_buckets']): continue targets.append(b) s3_info['buckets_count'] = len(targets) s3_params['api_clients'] = api_client s3_params['s3_info'] = s3_info thread_work(targets, get_s3_bucket, params = s3_params, num_threads = 30) show_status(s3_info) s3_info['buckets_count'] = len(s3_info['buckets']) return s3_info # Get key-specific information (server-side encryption, acls, etc...) def get_s3_bucket_keys(api_client, bucket_name, bucket, check_encryption, check_acls): bucket['keys'] = [] keys = handle_truncated_response(api_client.list_objects, {'Bucket': bucket_name}, ['Contents']) bucket['keys_count'] = len(keys['Contents']) key_count = 0 update_status(key_count, bucket['keys_count'], 'keys') for key in keys['Contents']: key_count += 1 key['name'] = key.pop('Key') key['LastModified'] = str(key['LastModified']) if check_encryption: try: # The encryption configuration is only accessible via an HTTP header, only returned when requesting one object at a time... k = api_client.get_object(Bucket = bucket_name, Key = key['name']) key['ServerSideEncryption'] = k['ServerSideEncryption'] if 'ServerSideEncryption' in k else None key['SSEKMSKeyId'] = k['SSEKMSKeyId'] if 'SSEKMSKeyId' in k else None except Exception as e: printException(e) continue if check_acls: try: key['grantees'] = get_s3_acls(api_client, bucket_name, bucket, key_name = key['name']) except Exception as e: continue # Save it bucket['keys'].append(key) update_status(key_count, bucket['keys_count'], 'keys') # # Return region to be used for global calls such as list bucket and get bucket location # def get_s3_list_region(region): if region.startswith('us-gov-'): return 'us-gov-west-1' elif region.startswith('cn-'): return 'cn-north-1' else: return 'us-east-1'
gpl-3.0
Darkpeninsula/Darkcore-Rebase
src/server/scripts/Outland/BlackTemple/boss_warlord_najentus.cpp
8222
/* * Copyright (C) 2011-2012 DarkCore <http://www.darkpeninsula.eu/> * Copyright (C) 2011-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/> * * 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/>. */ /* ScriptData SDName: Boss_Warlord_Najentus SD%Complete: 95 SDComment: SDCategory: Black Temple EndScriptData */ #include "ScriptPCH.h" #include "black_temple.h" enum eEnums { SAY_AGGRO = -1564000, SAY_NEEDLE1 = -1564001, SAY_NEEDLE2 = -1564002, SAY_SLAY1 = -1564003, SAY_SLAY2 = -1564004, SAY_SPECIAL1 = -1564005, SAY_SPECIAL2 = -1564006, SAY_ENRAGE1 = -1564007, //is this text actually in use? SAY_ENRAGE2 = -1564008, SAY_DEATH = -1564009, //Spells SPELL_NEEDLE_SPINE = 39992, SPELL_TIDAL_BURST = 39878, SPELL_TIDAL_SHIELD = 39872, SPELL_IMPALING_SPINE = 39837, SPELL_CREATE_NAJENTUS_SPINE = 39956, SPELL_HURL_SPINE = 39948, SPELL_BERSERK = 26662, GOBJECT_SPINE = 185584, EVENT_BERSERK = 1, EVENT_YELL = 2, EVENT_NEEDLE = 3, EVENT_SPINE = 4, EVENT_SHIELD = 5, GCD_CAST = 1, GCD_YELL = 2 }; class boss_najentus : public CreatureScript { public: boss_najentus() : CreatureScript("boss_najentus") { } CreatureAI* GetAI(Creature* creature) const { return new boss_najentusAI (creature); } struct boss_najentusAI : public ScriptedAI { boss_najentusAI(Creature* c) : ScriptedAI(c) { instance = c->GetInstanceScript(); } InstanceScript* instance; EventMap events; uint64 SpineTargetGUID; void Reset() { events.Reset(); SpineTargetGUID = 0; if (instance) instance->SetData(DATA_HIGHWARLORDNAJENTUSEVENT, NOT_STARTED); } void KilledUnit(Unit* /*victim*/) { DoScriptText(urand(0, 1) ? SAY_SLAY1 : SAY_SLAY2, me); events.DelayEvents(5000, GCD_YELL); } void JustDied(Unit* /*victim*/) { if (instance) instance->SetData(DATA_HIGHWARLORDNAJENTUSEVENT, DONE); DoScriptText(SAY_DEATH, me); } void SpellHit(Unit* /*caster*/, const SpellInfo* spell) { if (spell->Id == SPELL_HURL_SPINE && me->HasAura(SPELL_TIDAL_SHIELD)) { me->RemoveAurasDueToSpell(SPELL_TIDAL_SHIELD); DoCast(me, SPELL_TIDAL_BURST, true); ResetTimer(); } } void EnterCombat(Unit* /*who*/) { if (instance) instance->SetData(DATA_HIGHWARLORDNAJENTUSEVENT, IN_PROGRESS); DoScriptText(SAY_AGGRO, me); DoZoneInCombat(); events.ScheduleEvent(EVENT_BERSERK, 480000, GCD_CAST); events.ScheduleEvent(EVENT_YELL, 45000 + (rand()%76)*1000, GCD_YELL); ResetTimer(); } bool RemoveImpalingSpine() { if (!SpineTargetGUID) return false; Unit* target = Unit::GetUnit(*me, SpineTargetGUID); if (target && target->HasAura(SPELL_IMPALING_SPINE)) target->RemoveAurasDueToSpell(SPELL_IMPALING_SPINE); SpineTargetGUID=0; return true; } void ResetTimer(uint32 inc = 0) { events.RescheduleEvent(EVENT_NEEDLE, 10000 + inc, GCD_CAST); events.RescheduleEvent(EVENT_SPINE, 20000 + inc, GCD_CAST); events.RescheduleEvent(EVENT_SHIELD, 60000 + inc); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_SHIELD: DoCast(me, SPELL_TIDAL_SHIELD, true); ResetTimer(45000); break; case EVENT_BERSERK: DoScriptText(SAY_ENRAGE2, me); DoCast(me, SPELL_BERSERK, true); events.DelayEvents(15000, GCD_YELL); break; case EVENT_SPINE: { Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1); if (!target) target = me->getVictim(); if (target) { DoCast(target, SPELL_IMPALING_SPINE, true); SpineTargetGUID = target->GetGUID(); //must let target summon, otherwise you cannot click the spine target->SummonGameObject(GOBJECT_SPINE, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), me->GetOrientation(), 0, 0, 0, 0, 30); DoScriptText(urand(0, 1) ? SAY_NEEDLE1 : SAY_NEEDLE2, me); events.DelayEvents(1500, GCD_CAST); events.DelayEvents(15000, GCD_YELL); } events.ScheduleEvent(EVENT_SPINE, 21000, GCD_CAST); return; } case EVENT_NEEDLE: { //DoCast(me, SPELL_NEEDLE_SPINE, true); std::list<Unit*> targets; SelectTargetList(targets, 3, SELECT_TARGET_RANDOM, 80, true); for (std::list<Unit*>::const_iterator i = targets.begin(); i != targets.end(); ++i) DoCast(*i, 39835, true); events.ScheduleEvent(EVENT_NEEDLE, urand(15000, 25000), GCD_CAST); events.DelayEvents(1500, GCD_CAST); return; } case EVENT_YELL: DoScriptText(RAND(SAY_SPECIAL1, SAY_SPECIAL2), me); events.ScheduleEvent(EVENT_YELL, urand(25000, 100000), GCD_YELL); events.DelayEvents(15000, GCD_YELL); break; } } DoMeleeAttackIfReady(); } }; }; class go_najentus_spine : public GameObjectScript { public: go_najentus_spine() : GameObjectScript("go_najentus_spine") { } bool OnGossipHello(Player* player, GameObject* go) { if (InstanceScript* instance = go->GetInstanceScript()) if (Creature* Najentus = Unit::GetCreature(*go, instance->GetData64(DATA_HIGHWARLORDNAJENTUS))) if (CAST_AI(boss_najentus::boss_najentusAI, Najentus->AI())->RemoveImpalingSpine()) { player->CastSpell(player, SPELL_CREATE_NAJENTUS_SPINE, true); go->Delete(); } return true; } }; void AddSC_boss_najentus() { new boss_najentus(); new go_najentus_spine(); }
gpl-3.0
stream009/libadblock
src/core/file.cpp
480
#include "file.hpp" #include <cassert> #include <fstream> #include <sstream> namespace adblock { File:: File(Path path) : m_path { std::move(path) } { assert(!m_path.empty()); reload(); } File::~File() = default; void File:: reload() { std::ostringstream buf; std::ifstream input { m_path.c_str() }; if (!input.is_open()) throw std::ifstream::failure("Can't open file"); buf << input.rdbuf(); m_data = buf.str(); } } // namespace adblock
gpl-3.0
LeMaker/LN_Digital_Emulator
LN_Digital_Emulator/gui.py
24519
from PySide import QtGui, QtCore from PySide.QtCore import (Qt, QThread, QObject, Slot, Signal) from PySide.QtGui import ( QMainWindow, QPushButton, QApplication, QPainter, QFont ) from multiprocessing import Queue from threading import Barrier import LNcommon import LNdigitalIO from .LN_Digital_Emulator_ui import Ui_LN_DigitalEmulatorWindow # circle drawing PIN_COLOUR = QtGui.QColor(0, 255, 255) SWITCH_COLOUR = QtCore.Qt.yellow CIRCLE_R = 9 # Following are for LN Digital 1 and 2 INPUT_PIN_CIRCLE_COORD = ( # LN Digital ((5, 179), (17, 179), (29, 179), (41, 179), (53, 179), (65, 179), (77, 179),(89, 179)), # LN Digital 2 ((171, 4), (159, 4), (147, 4), (135, 4), (123, 4), (111, 4), (99, 4), (87, 4))) # output coords are backwards (output port indexed (7 -> 0) OUTPUT_PIN_CIRCLE_COORD = ( # LN Digital ((167, 12), (155, 12), (144, 12), (132, 12), (120, 12), (108, 12), (97, 12), (85, 12)), # LN Digital 2 ((272, 4), (260, 4), (248, 4), (236, 4), (224, 4), (212, 4), (200, 4), (188, 4))) SWITCH_CIRCLE_COORD = ( # LN Digital ((13, 155), (43, 155), (69, 155), (94, 155)), # LN Digital 2 ((160, 30), (134, 30), (108, 30), (82, 30))) RELAY_CIRCLE_COORD = ( # LN Digital ((275, 55), (275, 67), (275, 79), (275, 94), (275, 108), (275, 120)), # LN Digital 2 ((286, 88), (286, 99), (286, 111), (286, 125), (286, 137), (286, 149))) # led locations LED_LABEL_X = ((175, 163, 152, 140, 128, 116, 105, 93), (280, 268, 257, 244, 232, 219, 207, 195)) # boundaries for input presses (index 0: LN Digital 1, 1: LN Digital 2) SWITCH_BOUNDARY_Y_TOP = (148, 29) SWITCH_BOUNDARY_Y_BOTTOM = (161, 44) SWITCH_BOUNDARY_X_LEFT = ((10, 41, 66, 91), (157, 132, 105, 79)) SWITCH_BOUNDARY_X_RIGHT = ((30, 61, 86, 111), (177, 151, 124, 97)) PIN_BOUNDARY_Y_TOP = (180, 4) PIN_BOUNDARY_Y_BOTTOM = (190, 14) PIN_BOUNDARY_X_LEFT = ((5, 19, 31, 44, 53, 68, 79, 91, 104), (171, 159, 147, 135, 123, 111, 99, 87)) PIN_BOUNDARY_X_RIGHT = ((15, 27, 38, 51, 66, 74, 87, 99, 112), (180, 168, 156, 144, 132, 120, 108, 96)) NUM_LN_DIGITALS = 4 class CircleDrawingWidget(QtGui.QWidget): def __init__(self, parent=None, emu_window=None): super(CircleDrawingWidget, self).__init__(parent) # mirror actual state self.emu_window = emu_window # 'hold' for every input self.input_hold = [False for i in self.emu_window.input_state] @property def switch_circles_state(self): return self.emu_window.input_state[:4] @property def relay_circles_state(self): """returns six booleans for the relay pins""" # relays are attached to pins 0 and 1 if self.emu_window.output_state[0]: state0 = [False, True, True] else: state0 = [True, True, False] if self.emu_window.output_state[1]: state1 = [False, True, True] else: state1 = [True, True, False] return state1 + state0 def paintEvent(self, event): painter = QtGui.QPainter(self) painter.setBrush(QtGui.QBrush(PIN_COLOUR)) painter.setPen(QtGui.QPen(PIN_COLOUR)) # draw input circles for i, state in enumerate(self.emu_window.input_state): if state: painter.drawEllipse( INPUT_PIN_CIRCLE_COORD[self.emu_window.LNdig_ver-1][i][0], INPUT_PIN_CIRCLE_COORD[self.emu_window.LNdig_ver-1][i][1], CIRCLE_R, CIRCLE_R) # draw output circles for i, state in enumerate(self.emu_window.output_state): if state: painter.drawEllipse( OUTPUT_PIN_CIRCLE_COORD[self.emu_window.LNdig_ver-1][i][0], OUTPUT_PIN_CIRCLE_COORD[self.emu_window.LNdig_ver-1][i][1], CIRCLE_R, CIRCLE_R) # draw relay circles for i, state in enumerate(self.relay_circles_state): if state: painter.drawEllipse( RELAY_CIRCLE_COORD[self.emu_window.LNdig_ver-1][i][0], RELAY_CIRCLE_COORD[self.emu_window.LNdig_ver-1][i][1], CIRCLE_R, CIRCLE_R) # draw switch circles painter.setBrush(QtGui.QBrush(SWITCH_COLOUR)) painter.setPen(QtGui.QPen(SWITCH_COLOUR)) for i, state in enumerate(self.switch_circles_state): if state: painter.drawEllipse( SWITCH_CIRCLE_COORD[self.emu_window.LNdig_ver-1][i][0], SWITCH_CIRCLE_COORD[self.emu_window.LNdig_ver-1][i][1], CIRCLE_R, CIRCLE_R) painter.end() def mousePressEvent(self, event): self._pressed_pin, self._pressed_switch = switch = \ get_input_index_from_mouse(event.pos(), self.emu_window.LNdig_ver) if self._pressed_pin is None: event.ignore() return # if we are over a switch, turn it on, else toggle if self._pressed_switch: self.emu_window.input_state[self._pressed_pin] = True else: self.emu_window.input_state[self._pressed_pin] = \ not self.emu_window.input_state[self._pressed_pin] # hold it if we're setting it the pin high self.input_hold[self._pressed_pin] = \ self.emu_window.input_state[self._pressed_pin] self.emu_window.update_emulator() def mouseReleaseEvent(self, event): if self._pressed_pin is None: event.ignore() return # if we're releasing a switch, turn off the pin (if it's not held) if self._pressed_switch: if not self.input_hold[self._pressed_pin]: self.emu_window.input_state[self._pressed_pin] = False self._pressed_pin = None self._pressed_switch = False self.emu_window.update_emulator() class LNdigitalEmulatorWindow(QMainWindow, Ui_LN_DigitalEmulatorWindow): def __init__(self, parent=None): super(LNdigitalEmulatorWindow, self).__init__(parent) self.setupUi(self) self.LNdigital = None self.current_LN = 0 self.LNdig_ver = 1 # self._input_states = [[False for state in range(8)] # for p in range(NUM_LN_DIGITALS)] # self._previous_input_states = [list(p) for p in self._input_states] # self._output_states = [[False for state in range(8)] # for p in range(NUM_LN_DIGITALS)] self.input_state = [False for state in range(8)] self.previous_input_state = list(self.input_state) self.output_state = [False for state in range(8)] # add the circle drawing widget self.circleDrawingWidget = \ CircleDrawingWidget(self.centralwidget, self) self.circleDrawingWidget.setGeometry(QtCore.QRect(10, 10, 301, 191)) self.circleDrawingWidget.setObjectName("circleDrawingWidget") self.output_buttons = [ self.output0Button, self.output1Button, self.output2Button, self.output3Button, self.output4Button, self.output5Button, self.output6Button, self.output7Button] self.led_labels = [ self.led0Label, self.led1Label, self.led2Label, self.led3Label, self.led4Label, self.led5Label, self.led6Label, self.led7Label] # hide the leds for led in self.led_labels: led.setVisible(False) # show LN Digital Image and Leds self.LN_DigitalImageLabel.setVisible(True) self.set_led_label_locations() self.address0ActionToggled() # set up signal/slots self.outputControlAction.toggled.connect(self.enable_output_control) self.inputPullupsAction.toggled.connect(self.set_input_pullups) self.board_actions = ( self.board0Action, self.board1Action, self.board2Action, self.board3Action, ) for button in self.output_buttons: button.toggled.connect(self.output_overide) self.allOnButton.clicked.connect(self.all_outputs_on) self.allOffButton.clicked.connect(self.all_outputs_off) self.flipButton.clicked.connect(self.all_outputs_toggle) self.address0Action.toggled.connect(self.address0ActionToggled) self.address1Action.toggled.connect(self.address1ActionToggled) self.address2Action.toggled.connect(self.address2ActionToggled) self.address3Action.toggled.connect(self.address3ActionToggled) self.output_override_enabled = False def address0ActionToggled(self): self._addressActionToggled(0) def address1ActionToggled(self): self._addressActionToggled(1) def address2ActionToggled(self): self._addressActionToggled(2) def address3ActionToggled(self): self._addressActionToggled(3) def _addressActionToggled(self, index): self.current_LN = index if self.LNdigital: self.LNdigital.hardware_addr = index # block the signals self.address0Action.blockSignals(True) self.address1Action.blockSignals(True) self.address2Action.blockSignals(True) self.address3Action.blockSignals(True) # set correct check pattern self.address0Action.setChecked(index == 0) self.address1Action.setChecked(index == 1) self.address2Action.setChecked(index == 2) self.address3Action.setChecked(index == 3) # unblock the signals self.address0Action.blockSignals(False) self.address1Action.blockSignals(False) self.address2Action.blockSignals(False) self.address3Action.blockSignals(False) self.update_emulator() def set_led_label_locations(self): """Sets the location of the LED on image labels.""" led_labels = (self.led0Label, self.led1Label, self.led2Label, self.led3Label, self.led4Label, self.led5Label, self.led6Label, self.led7Label) for i, led_label in enumerate(led_labels): # print("Moving led_label[{}] to {}".format(i, LED_LABEL_X[self.LNdig_ver-1][i])) led_label.move(LED_LABEL_X[self.LNdig_ver-1][i], 40) led_label.raise_() def enable_output_control(self, enable): if enable: self._saved_output_state = list(self.output_state) self.update_all_output_buttons() else: self.output_state = self._saved_output_state self.uncheck_all_output_buttons() self.update_emulator() self.output_override_enabled = enable self.outputControlBox.setEnabled(enable) def set_input_pullups(self, enable): if self.LNdigital is not None: self.LNdigital.gppub.value = 0xff if enable else 0x00 if not enable: for i, s in enumerate(self.input_state): self.set_input(i, False) self.update_emulator() def output_overide(self, enable): """sets the output to mirror the override buttons""" # find out output override buttons state # then write them to the output # don't use set_output since that is locked when override mode is on for i, button in enumerate(self.output_buttons): self.output_state[i] = button.isChecked() self.update_emulator() def set_output(self, index, enable, hardware_addr=None): """Sets the specified output on or off""" if not self.output_override_enabled: self.output_state[index] = enable def set_input(self, index, enable, hardware_addr=None): # don't set the input if it is being held if not self.circleDrawingWidget.input_hold[index]: self.input_state[index] = enable def get_output_as_value(self): output_value = 0 for bit_index, state in enumerate(self.output_state): this_bit = 1 if state else 0 output_value |= (this_bit << bit_index) return output_value def update_LN(self): self.LNdigital.output_port.value = self.get_output_as_value() interrupt_flagger = Signal(int) def update_emulator(self): self.update_circles() if self.input_has_changed(): pin, direction = self.get_changed_pin_and_direction() self.interrupt_flagger.emit( small_nums_to_single_val(pin, direction)) self.previous_input_state = list(self.input_state) self.update_led_images() if self.LNdigital is not None: self.update_LN() def input_has_changed(self): return self.input_state != self.previous_input_state def get_changed_pin_and_direction(self): for i, x in enumerate( zip(self.input_state, self.previous_input_state)): if x[0] != x[1]: pin = i direction = LNdigitalIO.IODIR_ON \ if x[0] else LNdigitalIO.IODIR_OFF return pin, direction def update_circles(self): self.circleDrawingWidget.input_pin_circles_state = self.input_state self.circleDrawingWidget.output_pin_circles_state = self.output_state self.circleDrawingWidget.repaint() def update_led_images(self): for index, state in enumerate(self.output_state): self.led_labels[index].setVisible(state) def all_outputs_on(self): self.output_state = [True for s in range(8)] self.update_all_output_buttons() self.update_emulator() def all_outputs_off(self): self.output_state = [False for s in range(8)] self.update_all_output_buttons() self.update_emulator() def all_outputs_toggle(self): self.output_state = [not s for s in self.output_state] self.update_all_output_buttons() self.update_emulator() def uncheck_all_output_buttons(self): for button in self.output_buttons: button.toggled.disconnect(self.output_overide) button.setChecked(False) button.toggled.connect(self.output_overide) def update_all_output_buttons(self): for i, button in enumerate(self.output_buttons): button.toggled.disconnect(self.output_overide) button.setChecked(self.output_state[i]) button.toggled.connect(self.output_overide) @Slot(int) def set_input_enable(self, value): pin_num, hardware_addr = single_val_to_small_nums(value) self.set_input(pin_num, True, hardware_addr) self.update_emulator() @Slot(int) def set_input_disable(self, value): pin_num, hardware_addr = single_val_to_small_nums(value) self.set_input(pin_num, False, hardware_addr) self.update_emulator() @Slot(int) def set_output_enable(self, value): pin_num, hardware_addr = single_val_to_small_nums(value) self.set_output(pin_num, True, hardware_addr) self.update_emulator() @Slot(int) def set_output_disable(self, value): pin_num, hardware_addr = single_val_to_small_nums(value) self.set_output(pin_num, False, hardware_addr) self.update_emulator() send_input = Signal(int) @Slot(int) def get_input(self, value): pin_num, hardware_addr = single_val_to_small_nums(value) input_on = 1 if self.input_state[pin_num] else 0 send_val = small_nums_to_single_val(input_on, hardware_addr) self.send_input.emit(send_val) send_output = Signal(int) @Slot(int) def get_output(self, value): pin_num, hardware_addr = single_val_to_small_nums(value) pin_on = 1 if self.output_state[pin_num] else 0 send_val = small_nums_to_single_val(pin_on, hardware_addr) self.send_output.emit(send_val) class QueueWatcher(QObject): """Handles the queue which talks to the main process""" set_out_enable = Signal(int) set_out_disable = Signal(int) get_in = Signal(int) get_out = Signal(int) def __init__(self, app, emu_window, q_to_em, q_from_em): super().__init__() self.main_app = app self.emu_window = emu_window self.q_to_em = q_to_em self.q_from_em = q_from_em self.perform = { 'set_out': self.set_out_pin, 'get_in': self.get_in_pin, 'get_out': self.get_out_pin, 'register_interrupt': self.register_interrupt, 'activate_interrupt': self.activate_interrupt, 'deactivate_interrupt': self.deactivate_interrupt, 'quit': self.quit_main_app, } self.pin_function_maps = list() self.interrupts_activated = False def check_queue(self): while True: action = self.q_to_em.get(block=True) task = action[0] self.perform[task](action[1:]) def set_out_pin(self, data): pin, enable, hardware_addr = data if enable: self.set_out_enable.emit( small_nums_to_single_val(pin, hardware_addr)) else: self.set_out_disable.emit( small_nums_to_single_val(pin, hardware_addr)) def get_in_pin(self, data): pin, hardware_addr = data[0], data[1] self.get_in.emit(small_nums_to_single_val(pin, hardware_addr)) # now we have to rely on the emulator getting back to us @Slot(int) def send_get_in_pin_result(self, value): value, hardware_addr = single_val_to_small_nums(value) self.q_from_em.put(value) def get_out_pin(self, data): pin, hardware_addr = data[0], data[1] self.get_out.emit(small_nums_to_single_val(pin, hardware_addr)) @Slot(int) def send_get_out_pin_result(self, value): value, hardware_addr = single_val_to_small_nums(value) self.q_from_em.put(value) def register_interrupt(self, data): pin_num, direction, callback = data self.pin_function_maps.append(LNcommon.interrupts.PinFunctionMap( pin_num, direction, callback)) def activate_interrupt(self, data): self.interrupts_activated = True def deactivate_interrupt(self, data): self.interrupts_activated = False @Slot(int) def handle_interrupt(self, data): pin, direction = single_val_to_small_nums(data) func = self.get_registered_interrupt_func(pin, direction) if func is not None: flag = 0xff ^ LNcommon.get_bit_mask(pin) capture = self.emu_window.get_output_as_value() func(LNcommon.InterruptEvent(flag, capture)) def get_registered_interrupt_func(self, pin, direction): for funcmap in self.pin_function_maps: if funcmap.pin_num == pin and funcmap.direction == direction: return funcmap.callback else: return None def quit_main_app(self, data): self.main_app.quit() class InputWatcher(QObject): """Handles inputs and changes the emulator accordingly""" set_in_enable = Signal(int) set_in_disable = Signal(int) def __init__(self, emu_window): super().__init__() self.emu_window = emu_window cap = emu_window.LNdigital.intcapb.value # clear interrupt self.event_listeners = list() for i in range(NUM_LN_DIGITALS): listener = LNdigitalIO.InputEventListener( emu_window.LNdigital) for i in range(8): listener.register( i, LNdigitalIO.IODIR_BOTH, self.set_input) self.event_listeners.append(listener) def check_inputs(self): for listener in self.event_listeners: listener.activate() def stop_checking_inputs(self): for listener in self.event_listeners: listener.deactivate() def set_input(self, event): if event.direction == LNdigitalIO.IODIR_OFF: self.set_in_disable.emit( small_nums_to_single_val(event.pin_num, event.chip.hardware_addr)) else: self.set_in_enable.emit( small_nums_to_single_val(event.pin_num, event.chip.hardware_addr)) def get_input_index_from_mouse(point, LNdig_ver): """returns the pin number based on the point clicked, also returns a boolean specifying if the press occured on a switch Returns: (pin, switch?) """ x = point.x() y = point.y() # check for a switch press if (SWITCH_BOUNDARY_Y_TOP[LNdig_ver-1] < y and y < SWITCH_BOUNDARY_Y_BOTTOM[LNdig_ver-1]): for i in range(4): if (SWITCH_BOUNDARY_X_LEFT[LNdig_ver-1][i] < x and x < SWITCH_BOUNDARY_X_RIGHT[LNdig_ver-1][i]): return (i, True) elif (PIN_BOUNDARY_Y_TOP[LNdig_ver-1] < y and y < PIN_BOUNDARY_Y_BOTTOM[LNdig_ver-1]): # check for a pin press for i in range(8): if (PIN_BOUNDARY_X_LEFT[LNdig_ver-1][i] < x and x < PIN_BOUNDARY_X_RIGHT[LNdig_ver-1][i]): return (i, False) return (None, False) # no pin found, press did not occur on switch def start_q_watcher(app, emu_window, proc_comms_q_to_em, proc_comms_q_from_em): # need to spawn a worker thread that watches the proc_comms_q # need to seperate queue function from queue thread # http://stackoverflow.com/questions/4323678/threading-and-signals-problem # -in-pyqt q_watcher = QueueWatcher( app, emu_window, proc_comms_q_to_em, proc_comms_q_from_em) q_watcher_thread = QThread() q_watcher.moveToThread(q_watcher_thread) q_watcher_thread.started.connect(q_watcher.check_queue) # now that we've set up the thread, let's set up rest of signals/slots q_watcher.set_out_enable.connect(emu_window.set_output_enable) q_watcher.set_out_disable.connect(emu_window.set_output_disable) q_watcher.get_in.connect(emu_window.get_input) q_watcher.get_out.connect(emu_window.get_output) emu_window.send_output.connect(q_watcher.send_get_out_pin_result) emu_window.send_input.connect(q_watcher.send_get_in_pin_result) emu_window.interrupt_flagger.connect(q_watcher.handle_interrupt) # not sure why this doesn't work by connecting to q_watcher_thread.quit def about_to_quit(): q_watcher_thread.quit() app.aboutToQuit.connect(about_to_quit) q_watcher_thread.start() def start_input_watcher(app, emu_window): input_watcher = InputWatcher(emu_window) input_watcher_thread = QThread() input_watcher.moveToThread(input_watcher_thread) input_watcher_thread.started.connect(input_watcher.check_inputs) # signal / slots input_watcher.set_in_enable.connect(emu_window.set_input_enable) input_watcher.set_in_disable.connect(emu_window.set_input_disable) # quit setup def about_to_quit(): input_watcher.stop_checking_inputs() input_watcher_thread.quit() app.aboutToQuit.connect(about_to_quit) input_watcher_thread.start() def run_emulator( sysargv, use_LNdigital, init_board, emulated_LN): app = QApplication(sysargv) emu_window = LNdigitalEmulatorWindow() if use_LNdigital: emu_window.LNdigital = LNdigitalIO.LNdigitals( hardware_addr=emulated_LN.hardware_addr, bus=emulated_LN.bus, chip_select=emulated_LN.chip_select, init_board=init_board) emu_window.current_LN = emulated_LN.hardware_addr start_q_watcher(app, emu_window, emulated_LN.proc_comms_q_to_em, emulated_LN.proc_comms_q_from_em) # only watch inputs if there is actually a LN digital if emu_window.LNdigital is not None: start_input_watcher(app, emu_window) emu_window.show() app.exec_() def small_nums_to_single_val(val1, val2): return (val1 << 4) ^ val2 def single_val_to_small_nums(singleval): val2 = singleval & 0xf val1 = singleval >> 4 return val1, val2
gpl-3.0
bencebeky/etudes
square1/shape.py
4293
#/usr/bin/env python3 # coding=utf8 # Generate figures for solving the Square 1 puzzle into a cube shape. """ Copyright 2015 Bence Béky 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/>. """ import numpy from matplotlib import lines from matplotlib import gridspec from matplotlib import patches from matplotlib import pyplot from matplotlib.backends.backend_pdf import PdfPages from sys import argv pyplot.interactive(False) # Transform a line segment from the coordinate system of a single side to the # coordinate system of the subplot. def drawline(ax, voffset, data): data = numpy.array(data).T data[:,1] += 2 * voffset ax.lines.extend([patches.Polygon(0.5 + 0.5 * data, transform=ax.transAxes, facecolor="grey", edgecolor="black", linewidth=1.5)]) # Draw a single side at given vertical offset. def drawshape(ax, side, voffset): angle = 0.0 short = numpy.sqrt(0.5) / numpy.cos(numpy.pi/12) while (side > 0): assert(side % 3 != 0); angle1 = angle + numpy.pi / 6; angle2 = angle + numpy.pi / 3; if (side % 3 == 1): drawline(ax, voffset, [[0.0, short * numpy.sin(angle), short * numpy.sin(angle1)], [0.0, + short * numpy.cos(angle), short * numpy.cos(angle1)]]) angle = angle1 else: drawline(ax, voffset, [[0.0, short * numpy.sin(angle), numpy.sin(angle1), short * numpy.sin(angle2)], [0.0, short * numpy.cos(angle), numpy.cos(angle1), short * numpy.cos(angle2)]]) angle = angle2 side //= 3; # Draw two sides in given subplot. def drawshapes(ax, shapes): ax.set_axis_off() ax.set_aspect(1.0) drawshape(ax, shapes[0], 0.0) drawshape(ax, shapes[1], 1.0) ax.lines.extend([lines.Line2D([0.5, 0.5], [0.0, 2.0], transform=ax.transAxes, linewidth=1.5)]) # Read solution file and generate |firststep|. For each shape, |firststep| # contains the first step to take on one of the shortest paths to the root. def read_firststep(): firststep = {} with open("solution.dat") as f: for line in f: words = line.split(); assert(len(words) == 6) firststep[(int(words[0]), int(words[1]))] = [ (int(words[2]), int(words[3])), (int(words[4]), int(words[5]))] return firststep # Generate maximal list of suffix-free paths. def generate_suffixfree(firststep): # |paths| is the list of all paths from all shapes to one step before the root. paths = [] for shape in firststep.keys(): if (shape == (4100, 4100)): continue path = [] while shape != (4100, 4100): rotated, shape = firststep[shape] path.append(rotated) paths.append(path) # |suffixfree| is the suffix-free union of |paths| suffixfree = [] for path in paths: is_a_suffix = False for otherpath in paths: if (len(otherpath) <= len(path)): continue if (otherpath[-len(path):] == path): is_a_suffix = True break if (not is_a_suffix): suffixfree.append(path) # Sort in place. suffixfree.sort(key=len) return suffixfree def plot(suffixfree): rows = 6 columns = max([len(path) for path in suffixfree]) pdf = PdfPages("solution.pdf") for pagenumber in range(int(numpy.ceil(len(suffixfree)/rows))): fig = pyplot.figure(figsize=(8.27,11.69)) gs = gridspec.GridSpec(rows, columns, top=0.95, bottom=0.0, wspace=0.2, hspace=0.0) for row in range(min(rows, len(suffixfree) - rows*pagenumber)): path = suffixfree[rows*pagenumber + row] for column in range(len(path)): ax = fig.add_subplot(gs[row, column]) drawshapes(ax, path[column]) pdf.savefig() pyplot.close(fig) pdf.close() firststep = read_firststep() suffixfree = generate_suffixfree(firststep) plot(suffixfree)
gpl-3.0
Niky4000/UsefulUtils
projects/ibs/SshTest/src/main/java/ru/ibs/tomcatrestart/SshTest.java
5448
package ru.ibs.tomcatrestart; import java.io.File; import java.io.FileInputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; /** * * @author NAnishhenko */ public class SshTest { private static final String CONFIG_FILE_NAME = "properties.txt"; private static final String CONFIG_REMOTE_FILE_NAME = "properties_remote.txt"; private String s = File.separator; private boolean targetSystemIsLinux = false; private static final int TIME_TO_WAIT = 10000; final Integer port; final String host; final String user; final String password; final String zipArchPath; final String targetUnpackDir; final String tomcatModulesDir; final String modules; final String pmpClientPath; final String sshPmpClientPath; final String[] deleteDirPath; final String[] deleteFilesPath; final String[] deleteDirsPath; final Properties properties; boolean forceCopy = false; public SshTest(String configFileName) throws Exception { properties = new Properties(); properties.load(new FileInputStream(new File(configFileName))); host = properties.getProperty("host"); user = properties.getProperty("user"); password = properties.getProperty("password"); zipArchPath = properties.getProperty("zipArchPath"); targetUnpackDir = properties.getProperty("targetUnpackDir"); tomcatModulesDir = properties.getProperty("tomcatModulesDir"); modules = properties.getProperty("modules"); pmpClientPath = properties.getProperty("pmpClientPath"); sshPmpClientPath = properties.getProperty("sshPmpClientPath"); deleteDirPath = splitString(properties.getProperty("deleteDirPath")); deleteFilesPath = splitString(properties.getProperty("deleteFilesPath")); deleteDirsPath = splitString(properties.getProperty("deleteDirsPath")); port = Integer.valueOf(getProperties().getProperty("port")); } public static void main(String[] args) throws Exception { new SshTest("D:\\GIT\\UsefulUtils\\projects\\ibs\\SshTest\\properties2.txt").testSsh(); System.exit(0); } public void testSsh() throws Exception { System.out.println("Before SshClient! " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); System.out.println("------------------------------"); System.out.println("------------------------------"); System.out.println("------------------------------"); System.out.println("------------------------------"); SshClient sshClient = new SshClient(getHost(), getUser(), getPassword(), port); sshClient.scpTo("D:\\tmp\\zzzz\\debug_stage1CompositeObject_5288_2017-12.bin", "D:\\tmp\\debug_stage1CompositeObject_5288_2017-12"); sshClient.execCommand(new String[]{"java -Xmx8G -Dpmp.config.path=D:\\GIT\\rmis\\etc\\recreate_111_test\\runtime.properties -jar D:\\tmp\\recreate\\module-pmp-bill-recreate.jar -mf 4889 2017-11"}); // Scp.createSshClient(getHost(), getUser(), getPassword(), port, new String[]{"java -Xmx4G -Dpmp.config.path=/home/mls/tomcat/modules/conf/module-pmp-bill-recreate-executor-war/runtime-recreate.properties -jar /home/mls/tomcat/webapps/module-pmp-bill-recreate.jar -mf 1863 2017-12"}); System.out.println("------------------------------"); System.out.println("------------------------------"); System.out.println("------------------------------"); System.out.println("------------------------------"); System.out.println("After SshClient! " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); } protected String[] splitString(String str) { if (str != null) { if (str.contains(",")) { return str.split(","); } else { return new String[]{str}; } } else { return new String[0]; } } public String getHost() { return host; } public String getUser() { return user; } public String getPassword() { return password; } public String getZipArchPath() { return zipArchPath; } public String getTargetUnpackDir() { return targetUnpackDir; } public String getTomcatModulesDir() { return tomcatModulesDir; } public String getModules() { return modules; } public String getPmpClientPath() { return pmpClientPath; } public String getSshPmpClientPath() { return sshPmpClientPath; } public String[] getDeleteDirPath() { return deleteDirPath; } public String[] getDeleteFilesPath() { return deleteFilesPath; } public String[] getDeleteDirsPath() { return deleteDirsPath; } public String getS() { return s; } public void setS(String s) { this.s = s; } public boolean isTargetSystemIsLinux() { return targetSystemIsLinux; } public void setTargetSystemIsLinux(boolean targetSystemIsLinux) { this.targetSystemIsLinux = targetSystemIsLinux; } public boolean isForceCopy() { return forceCopy; } public void setForceCopy(boolean forceCopy) { this.forceCopy = forceCopy; } public Properties getProperties() { return properties; } }
gpl-3.0
kleberkruger/Estagio
estagio-backend_backup/target/generated-sources/apt/br/ufms/estagio/entity/QDiscente.java
3458
package br.ufms.estagio.entity; import static com.mysema.query.types.PathMetadataFactory.*; import com.mysema.query.types.path.*; import com.mysema.query.types.PathMetadata; import javax.annotation.Generated; import com.mysema.query.types.Path; import com.mysema.query.types.path.PathInits; /** * QDiscente is a Querydsl query type for Discente */ @Generated("com.mysema.query.codegen.EntitySerializer") public class QDiscente extends EntityPathBase<Discente> { private static final long serialVersionUID = -2062237179L; private static final PathInits INITS = PathInits.DIRECT2; public static final QDiscente discente = new QDiscente("discente"); public final QUsuario _super; //inherited public final BooleanPath ativo; //inherited public final StringPath cpfCnpj; public final QCurso curso; //inherited public final DateTimePath<java.util.Date> dataAtualizacao; //inherited public final DateTimePath<java.util.Date> dataCriacao; public final DatePath<java.time.LocalDate> dataIngresso = createDate("dataIngresso", java.time.LocalDate.class); // inherited public final QEndereco endereco; //inherited public final CollectionPath<EnderecoEletronico, QEnderecoEletronico> enderecosEletronicos; //inherited public final NumberPath<Long> id; //inherited public final StringPath nacionalidade; //inherited public final StringPath nome; public final StringPath rga = createString("rga"); //inherited public final NumberPath<Integer> rgNumero; //inherited public final StringPath rgOrgaoExpedidor; //inherited public final StringPath senha; //inherited public final CollectionPath<Telefone, QTelefone> telefones; //inherited public final EnumPath<br.ufms.estagio.enumerate.TipoPessoa> tipoPessoa; //inherited public final EnumPath<br.ufms.estagio.enumerate.TipoUsuario> tipoUsuario; public QDiscente(String variable) { this(Discente.class, forVariable(variable), INITS); } public QDiscente(Path<? extends Discente> path) { this(path.getType(), path.getMetadata(), path.getMetadata().isRoot() ? INITS : PathInits.DEFAULT); } public QDiscente(PathMetadata<?> metadata) { this(metadata, metadata.isRoot() ? INITS : PathInits.DEFAULT); } public QDiscente(PathMetadata<?> metadata, PathInits inits) { this(Discente.class, metadata, inits); } public QDiscente(Class<? extends Discente> type, PathMetadata<?> metadata, PathInits inits) { super(type, metadata, inits); this._super = new QUsuario(type, metadata, inits); this.ativo = _super.ativo; this.cpfCnpj = _super.cpfCnpj; this.curso = inits.isInitialized("curso") ? new QCurso(forProperty("curso"), inits.get("curso")) : null; this.dataAtualizacao = _super.dataAtualizacao; this.dataCriacao = _super.dataCriacao; this.endereco = _super.endereco; this.enderecosEletronicos = _super.enderecosEletronicos; this.id = _super.id; this.nacionalidade = _super.nacionalidade; this.nome = _super.nome; this.rgNumero = _super.rgNumero; this.rgOrgaoExpedidor = _super.rgOrgaoExpedidor; this.senha = _super.senha; this.telefones = _super.telefones; this.tipoPessoa = _super.tipoPessoa; this.tipoUsuario = _super.tipoUsuario; } }
gpl-3.0
sgdc3/AuthMeReloaded
src/main/java/fr/xephi/authme/command/executable/authme/SpawnCommand.java
1398
package fr.xephi.authme.command.executable.authme; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.command.CommandParts; import fr.xephi.authme.command.ExecutableCommand; import fr.xephi.authme.settings.Spawn; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; /** */ public class SpawnCommand extends ExecutableCommand { /** * Execute the command. * * @param sender The command sender. * @param commandReference The command reference. * @param commandArguments The command arguments. * * @return True if the command was executed successfully, false otherwise. */ @Override public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) { // Make sure the command executor is a player try { if (sender instanceof Player) { if (Spawn.getInstance().getSpawn() != null) ((Player) sender).teleport(Spawn.getInstance().getSpawn()); else sender.sendMessage("[AuthMe] Spawn has failed, please try to define the spawn"); } else { sender.sendMessage("[AuthMe] Please use that command in game"); } } catch (NullPointerException ex) { ConsoleLogger.showError(ex.getMessage()); } return true; } }
gpl-3.0
NurselGokce/roundtrap
plugins/help/help.php
2568
<?php /** * Help Plugin * * @author Aleksander 'A.L.E.C' Machniak * @license GNU GPLv3+ * * Configuration (see config.inc.php.dist) * **/ class help extends rcube_plugin { // all task excluding 'login' and 'logout' public $task = '?(?!login|logout).*'; // we've got no ajax handlers public $noajax = true; // skip frames public $noframe = true; function init() { $this->add_texts('localization/', false); // register task $this->register_task('help'); // register actions $this->register_action('index', array($this, 'action')); $this->register_action('about', array($this, 'action')); $this->register_action('license', array($this, 'action')); // add taskbar button $this->add_button(array( 'command' => 'help', 'class' => 'button-help', 'classsel' => 'button-help button-selected', 'innerclass' => 'button-inner', 'label' => 'help.help', ), 'taskbar'); // add style for taskbar button (must be here) and Help UI $skin_path = $this->local_skin_path(); if (is_file($this->home . "/$skin_path/help.css")) { $this->include_stylesheet("$skin_path/help.css"); } } function action() { $rcmail = rcmail::get_instance(); $this->load_config(); // register UI objects $rcmail->output->add_handlers(array( 'helpcontent' => array($this, 'content'), )); if ($rcmail->action == 'about') $rcmail->output->set_pagetitle($this->gettext('about')); else if ($rcmail->action == 'license') $rcmail->output->set_pagetitle($this->gettext('license')); else $rcmail->output->set_pagetitle($this->gettext('help')); $rcmail->output->send('help.help'); } function content($attrib) { $rcmail = rcmail::get_instance(); if ($rcmail->action == 'about') { return @file_get_contents($this->home.'/content/about.html'); } else if ($rcmail->action == 'license') { return @file_get_contents($this->home.'/content/license.html'); } // default content: iframe if ($src = $rcmail->config->get('help_source')) $attrib['src'] = $src; if (empty($attrib['id'])) $attrib['id'] = 'rcmailhelpcontent'; $attrib['name'] = $attrib['id']; return $rcmail->output->frame($attrib); } }
gpl-3.0