code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
#include <epoxy/gl.h>
#include "../asset_manager.h"
#include "../common.h"
#include "../ship_space.h"
#include "../mesh.h"
#include "../player.h"
#include "tools.h"
extern GLuint overlay_shader;
extern GLuint simple_shader;
extern ship_space *ship;
extern asset_manager asset_man;
extern mesh_data const * mesh_for_block_type(block_type t);
extern glm::mat4 get_corner_matrix(block_type type, glm::ivec3 pos);
struct remove_block_tool : tool
{
raycast_info_block rc;
void pre_use(player *pl) override {
ship->raycast_block(pl->eye, pl->dir, MAX_REACH_DISTANCE, enter_exit_framing, &rc);
}
bool can_use() {
return rc.hit && !rc.inside;
}
void use() override
{
if (!can_use())
return;
ship->remove_block(rc.bl);
}
void preview(frame_data *frame) override
{
if (!can_use())
return;
block *bl = rc.block;
if (bl->type != block_empty && bl->type != block_untouched) {
auto mesh = mesh_for_block_type(bl->type);
auto mat = frame->alloc_aligned<mesh_instance>(1);
if (bl->type == block_frame) {
mat.ptr->world_matrix = mat_position(glm::vec3(rc.bl));
}
else {
mat.ptr->world_matrix = get_corner_matrix(bl->type, rc.bl);
}
mat.ptr->color = glm::vec4(1.f, 0.f, 0.f, 1.f);
mat.bind(1, frame);
glUseProgram(overlay_shader);
glEnable(GL_BLEND);
glEnable(GL_POLYGON_OFFSET_FILL);
draw_mesh(mesh->hw);
glDisable(GL_POLYGON_OFFSET_FILL);
glDisable(GL_BLEND);
glUseProgram(simple_shader);
}
}
void get_description(char *str) override
{
strcpy(str, "Remove Framing");
}
};
tool *tool::create_remove_block_tool() { return new remove_block_tool(); }
| engineers-nightmare/engineers-nightmare | src/tools/remove_block.cc | C++ | gpl-3.0 | 1,912 |
@extends('main')
@section('title', 'My Requests')
@section('stylesheets')
<link rel="stylesheet" href="/css/author.css">
@stop
@section('content')
<!-- Wrapper -->
<div id="wrapper">
<!-- Main -->
<div id="main">
<!-- Show All Advice -->
<section id="answer" class="main special">
<header class="major">
<h2>My Requests</h2>
</header>
@if (! json_decode($advice_requests, true))
<section class="box">
<div class="blog-summary">
<p>No request up yet! Why not write one now? (: Ask <a href="{{ url('ask') }}">here</a>.</p>
</div>
</section>
@else
@foreach(json_decode($advice_requests, true) as $post)
<section class="box">
<div class="blog-header">
<div class="blog-author--no-cover">
<h3>Me</h3>
</div>
</div>
<div class="blog-body">
<div class="blog-summary">
<p>{{ $post['message'] }}</p>
</div>
<div class="blog-tags">
<ul>
<li class="label">{{ $post['label'] }}</li>
<li>{{ $post['created_time'] }}</li>
<li>{{ $post['comment_count'] }} advice</li>
</ul>
</div>
</div>
<div class="blog-footer">
@foreach($post['comments'] as $comment)
<p class="comments">
<span style="color:gray;">
@if (! $comment['fb_user_id'])
Addvise:
@else
<span class="fb-user-id">{{ $comment['fb_user_id'] }}</span>:
@endif
</span>
<b> {{ $comment['message'] }}</b>
</p>
@endforeach
<ul>
<li class="give-advice"><a href="{{ url('https://facebook.com/' . $post['fb_post_id']) }}" target="_blank">View on Facebook</a></li>
</ul>
</div>
</section>
@endforeach
@endif
</section>
</div>
</div>
<script src="/js/translate.js"></script>
@stop
| jia1/addvise | resources/views/needAddvise_me.blade.php | PHP | gpl-3.0 | 2,064 |
class LogisticRegression():
def __init__(self, input_size, output_size):
self.W = np.random.uniform(size=(input_size, output_size),
high=0.1, low=-0.1)
self.b = np.random.uniform(size=output_size,
high=0.1, low=-0.1)
self.output_size = output_size
def forward(self, X):
Z = np.dot(X, self.W) + self.b
sZ = softmax(Z)
return sZ
def predict(self, X):
if len(X.shape) == 1:
return np.argmax(self.forward(X))
else:
return np.argmax(self.forward(X), axis=1)
def grad_loss(self, x, y_true):
y_pred = self.forward(x)
dnll_output = y_pred - one_hot(self.output_size, y_true)
grad_W = np.outer(x, dnll_output)
grad_b = dnll_output
grads = {"W": grad_W, "b": grad_b}
return grads
def train(self, x, y, learning_rate):
# Traditional SGD update without momentum
grads = self.grad_loss(x, y)
self.W = self.W - learning_rate * grads["W"]
self.b = self.b - learning_rate * grads["b"]
def loss(self, x, y):
nll = NegLogLike(one_hot(self.output_size, y), self.forward(x))
return nll
def accuracy(self, X, y):
y_preds = np.argmax(self.forward(X), axis=1)
acc = np.mean(y_preds == y)
return acc | wikistat/Apprentissage | BackPropagation/solutions/lr_class.py | Python | gpl-3.0 | 1,424 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-14 14:30
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('barbadosdb', '0007_club_users'),
]
operations = [
migrations.RenameField(
model_name='club',
old_name='user',
new_name='users',
),
]
| codento/barbados | barbados/barbadosdb/migrations/0008_club_users2.py | Python | gpl-3.0 | 415 |
<?php
/**
* Created by PhpStorm.
* User: sizov
* Date: 7/23/14
* Time: 7:49 PM
*/
include 'install/checkconf.php';
$ldap_server = $LdapIp;
$domain = $DomainPrefix;
function ldapAuth($ldap_server, $login, $password)
{
$ldapConn = ldap_connect( $ldap_server ) or die("can't connect to ldap server ".$ldap_server);
ldap_set_option( $ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3 );
ldap_set_option($ldapConn, LDAP_OPT_REFERRALS, 0);
if ( $ldapConn )
{
$ldapBind = ldap_bind( $ldapConn, $login, $password ) or die("can't auth with: ".$ldapConn." ".$login." ".$password);
if ( $ldapBind )
{
ldap_close($ldapConn);
return true;
}
}
return false;
}
//Работа с БД
//Данные для подключения к БД
$mysqlServer = $MysqlIp;
$mysqlUsername = $MysqlLogin;
$mysqlPassword = $MysqlPassword;
$mysqlDatabase = $MysqlDatabase;
$mysqli = new mysqli( $mysqlServer, $mysqlUsername, $mysqlPassword, $mysqlDatabase ); //Устанавливаем соединение в базой мускула
if ( $mysqli->connect_errno )
{
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; //Не удалось установить соединение с базой мускула.
}
else
{
$mysqli->set_charset("utf8"); //Устанавливаем принудительно кодировку в UTF-8!
}
if ( !empty( $_POST["login"] ) && !empty( $_POST["password"] ) )
{
$login = trim( $_POST["login"] );
$password = trim( $_POST["password"] );
$ip = trim($_POST["ip"], "/");
if ( ldapAuth($ldap_server, $login.$domain, $password) )
{
$query = "UPDATE `users` SET `ip` = INET_ATON('".$ip."') WHERE `login`='".$login."'";
$result = $mysqli->query( $query ) or die("insert ip error");
header('Location: /sldap/error_page.php?message=Теперь вы можете пользоваться интернетом.');
}
else
{
header('Location: /sldap/error_page.php?status=auth&ip='.$ip.'&message=Вы не верно ввели логин или пароль.');
}
}
else
{
header('Location: /sldap/error_page.php?status=auth&ip='.$ip.'&message=Вы не верно ввели логин или пароль.');
}
?> | SpecialForce3331/sldap | web/views/auth.php | PHP | gpl-3.0 | 2,551 |
package br.net.fabiozumbi12.pixelvip.bukkit;
import br.net.fabiozumbi12.pixelvip.bukkit.bungee.SpigotText;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class PVUtil {
private final PixelVip plugin;
public PVUtil(PixelVip plugin) {
this.plugin = plugin;
}
public String toColor(String str) {
return str.replaceAll("(&([Aa-fFkK-oOrR0-9]))", "\u00A7$2");
}
public String removeColor(String str) {
return str.replaceAll("(&([Aa-fFkK-oOrR0-9]))", "");
}
public long getNowMillis() {
Calendar cal = Calendar.getInstance();
return cal.getTimeInMillis();
}
public long dayToMillis(Long days) {
return TimeUnit.DAYS.toMillis(days);
}
public long millisToDay(String millis) {
return TimeUnit.MILLISECONDS.toDays(Long.parseLong(millis));
}
public long millisToDay(Long millis) {
return TimeUnit.MILLISECONDS.toDays(millis);
}
public void sendHoverKey(CommandSender sender, String key) {
try {
if (plugin.getPVConfig().getBoolean(true, "configs.spigot.clickKeySuggest") && sender instanceof Player) {
SpigotText text = new SpigotText();
text.setText(plugin.getUtil().toColor(plugin.getPVConfig().getLang("timeKey") + key + " " + plugin.getPVConfig().getLang("hoverKey")));
text.setHover(plugin.getUtil().toColor(plugin.getPVConfig().getLang("hoverKey")));
text.setClick(plugin.getPVConfig().getString("/usekey ", "configs.spigot.clickSuggest").replace("{key}", key));
text.sendMessage(sender);
} else {
sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang("timeKey") + key));
}
} catch (NoSuchMethodError e) {
sender.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang("timeKey") + key));
}
}
public String genKey(int length) {
char[] chartset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
Random random = new SecureRandom();
char[] result = new char[length];
for (int i = 0; i < result.length; i++) {
int randomCharIndex = random.nextInt(chartset.length);
result[i] = chartset[randomCharIndex];
}
return new String(result);
}
public void sendVipTime(CommandSender src, String UUID, String name) {
List<String[]> vips = plugin.getPVConfig().getVipInfo(UUID);
if (vips.size() > 0) {
src.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang("_pluginTag", "vipInfoFor") + name + ":"));
src.sendMessage(plugin.getUtil().toColor("&b---------------------------------------------"));
vips.stream().filter(v -> v.length == 5).forEach((vipInfo) -> {
String time = plugin.getUtil().millisToMessage(Long.parseLong(vipInfo[0]));
if (plugin.getPVConfig().isVipActive(vipInfo[1], UUID)) {
time = plugin.getUtil().millisToMessage(Long.parseLong(vipInfo[0]) - plugin.getUtil().getNowMillis());
}
src.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang("timeLeft") + time));
src.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang("timeGroup") + plugin.getPVConfig().getVipTitle(vipInfo[1])));
src.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang("timeActive") + plugin.getPVConfig().getLang(vipInfo[3])));
src.sendMessage(plugin.getUtil().toColor("&b---------------------------------------------"));
});
} else {
src.sendMessage(plugin.getUtil().toColor(plugin.getPVConfig().getLang("_pluginTag", "playerNotVip")));
}
}
public String millisToMessage(long millis) {
long days = TimeUnit.MILLISECONDS.toDays(millis);
long hour = TimeUnit.MILLISECONDS.toHours(millis - TimeUnit.DAYS.toMillis(days));
long min = TimeUnit.MILLISECONDS.toMinutes((millis - TimeUnit.DAYS.toMillis(days)) - TimeUnit.HOURS.toMillis(hour));
StringBuilder msg = new StringBuilder();
if (days > 0) {
msg.append("&6").append(days).append(plugin.getPVConfig().getLang("days")).append(", ");
}
if (hour > 0) {
msg.append("&6").append(hour).append(plugin.getPVConfig().getLang("hours")).append(", ");
}
if (min > 0) {
msg.append("&6").append(min).append(plugin.getPVConfig().getLang("minutes")).append(", ");
}
try {
msg.replace(msg.lastIndexOf(","), msg.lastIndexOf(",") + 1, ".").replace(msg.lastIndexOf(","), msg.lastIndexOf(",") + 1, plugin.getPVConfig().getLang("and"));
} catch (StringIndexOutOfBoundsException ex) {
return plugin.getPVConfig().getLang("lessThan");
}
return msg.toString();
}
public String expiresOn(Long millis) {
Date date = new Date(millis);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
return sdf.format(date);
}
public void ExecuteCmd(String cmd, Player player) {
if (cmd == null || cmd.isEmpty()) return;
if (player != null) cmd = cmd.replace("{p}", player.getName());
plugin.addLog("Running Command - \"" + cmd + "\"");
String finalCmd = cmd;
Bukkit.getScheduler().runTask(plugin, () -> plugin.serv.dispatchCommand(plugin.serv.getConsoleSender(), finalCmd));
}
public boolean paymentItems(HashMap<String, Integer> items, Player player, String payment, String transCode) {
int log = 0;
for (Map.Entry<String, Integer> item : items.entrySet()) {
int multipl = item.getValue();
String key = item.getKey();
for (int i = 0; i < multipl; i++) {
String cmd = "givepackage " + player.getName() + " " + key;
ExecuteCmd(cmd, null);
plugin.addLog("API:" + payment + " | " + player.getName() + " | Item Cmd:" + cmd + " | Transaction Code: " + transCode);
log++;
}
}
return log != 0;
}
}
| FabioZumbi12/PixelVip | PixelVip-Spigot/src/main/java/br/net/fabiozumbi12/pixelvip/bukkit/PVUtil.java | Java | gpl-3.0 | 6,402 |
// This library re-implements setTimeout, setInterval, clearTimeout, clearInterval for iOS6.
// iOS6 suffers from a bug that kills timers that are created while a page is scrolling.
// This library fixes that problem by recreating timers after scrolling finishes (with interval correction).
// This code is free to use by anyone (MIT, blabla).
// Original Author: rkorving@wizcorp.jp
(function (window) {
var timeouts = {};
var intervals = {};
var orgSetTimeout = window.setTimeout;
var orgSetInterval = window.setInterval;
var orgClearTimeout = window.clearTimeout;
var orgClearInterval = window.clearInterval;
// To prevent errors if loaded on older IE.
if (!window.addEventListener) return false;
function axZmCreateTimer(set, map, args) {
var id, cb = args[0],
repeat = (set === orgSetInterval);
function callback() {
if (cb) {
cb.apply(window, arguments);
if (!repeat) {
delete map[id];
cb = null;
}
}
}
args[0] = callback;
id = set.apply(window, args);
map[id] = {
args: args,
created: Date.now(),
cb: cb,
id: id
};
return id;
}
function axZmResetTimer(set, clear, map, virtualId, correctInterval) {
var timer = map[virtualId];
if (!timer) {
return;
}
var repeat = (set === orgSetInterval);
// cleanup
clear(timer.id);
// reduce the interval (arg 1 in the args array)
if (!repeat) {
var interval = timer.args[1];
var reduction = Date.now() - timer.created;
if (reduction < 0) {
reduction = 0;
}
interval -= reduction;
if (interval < 0) {
interval = 0;
}
timer.args[1] = interval;
}
// recreate
function callback() {
if (timer.cb) {
timer.cb.apply(window, arguments);
if (!repeat) {
delete map[virtualId];
timer.cb = null;
}
}
}
timer.args[0] = callback;
timer.created = Date.now();
timer.id = set.apply(window, timer.args);
}
window.setTimeout = function () {
return axZmCreateTimer(orgSetTimeout, timeouts, arguments);
};
window.setInterval = function () {
return axZmCreateTimer(orgSetInterval, intervals, arguments);
};
window.clearTimeout = function (id) {
var timer = timeouts[id];
if (timer) {
delete timeouts[id];
orgClearTimeout(timer.id);
}
};
window.clearInterval = function (id) {
var timer = intervals[id];
if (timer) {
delete intervals[id];
orgClearInterval(timer.id);
}
};
//check and add listener on the top window if loaded on frameset/iframe
var win = window;
while (win.location != win.parent.location) {
win = win.parent;
}
win.addEventListener('scroll', function () {
// recreate the timers using adjusted intervals
// we cannot know how long the scroll-freeze lasted, so we cannot take that into account
var virtualId;
for (virtualId in timeouts) {
axZmResetTimer(orgSetTimeout, orgClearTimeout, timeouts, virtualId);
}
for (virtualId in intervals) {
axZmResetTimer(orgSetInterval, orgClearInterval, intervals, virtualId);
}
});
}(window)); | Karplyak/avtomag.url.ph | axZm/plugins/ios6TimersFix.js | JavaScript | gpl-3.0 | 2,999 |
<?php
/**
* Qhebunel
* User profile (settings) page
* This page should be used instead of the WP admin dashboard for readers
* to change their settings.
*
* This page is displayed when a handler runs into an error.
*/
if (!defined('QHEBUNEL_REQUEST') || QHEBUNEL_REQUEST !== true) die;
global $section_params;
$user_id = (int)$section_params;
//Show message to users who aren't logged in
if (!is_user_logged_in()) {
echo('<div class="qheb-error-message">'.__('You must log in to edit your profile.', 'qhebunel').'</div>');
return;//stop page rendering, but create footer
}
if (!empty($user_id) && !QhebunelUser::is_moderator()) {
echo('<div class="qheb-error-message">'.__('You can only edit your own profile.', 'qhebunel').'</div>');
return;//stop page rendering, but create footer
}
//Select user
if (empty($user_id)) {
$user_id = $current_user->ID;
}
//Load data to display
$user_data = get_userdata($user_id);
$user_login = $user_data->user_login;
$first_name = get_user_meta($user_id, 'first_name', true);
$last_name = get_user_meta($user_id, 'last_name', true);
$nick_name = $user_data->display_name;
$email = $user_data->user_email;
$ext_data = $wpdb->get_row(
$wpdb->prepare(
'select * from `qheb_user_ext` where `uid`=%d',
$user_id
),
ARRAY_A
);
?>
<form method="post" action="<?=site_url('forum/')?>" enctype="multipart/form-data" onsubmit="return validate_profile_form();" id="profile_form">
<input type="hidden" name="action" value="profile" />
<input type="hidden" name="MAX_FILE_SIZE" value="<?=QHEBUNEL_AVATAR_MAX_FILESIZE?>" />
<input type="hidden" name="user-id" value="<?=$user_id?>" />
<h2><?php _e('Basic information', 'qhebunel'); ?></h2>
<table class="profile_settings">
<tfoot>
<tr><td colspan="2"><input name="update" type="submit" value="<?php _e('Save', 'qhebunel'); ?>" /></td></tr>
</tfoot>
<tbody>
<tr title="<?php _e('This is the name you use to log in. You cannot change it.', 'qhebunel'); ?>">
<th><label for="username"><?php _e('Login name', 'qhebunel'); ?></label></th>
<td><input name="username" id="username" type="text" readonly="readonly" value="<?=$user_login?>" /><span class="icon">🔒</span></td>
</tr>
<tr>
<th><label for="firstname"><?php _e('First name', 'qhebunel'); ?></label></th>
<td><input name="firstname" id="firstname" type="text" value="<?=$first_name?>" /></td>
</tr>
<tr>
<th><label for="lastname"><?php _e('Last name', 'qhebunel'); ?></label></th>
<td><input name="lastname" id="lastname" type="text" value="<?=$last_name?>" /></td>
</tr>
<tr title="<?php _e('This is the name visible next to your comments and forum posts.', 'qhebunel'); ?>">
<th><label for="nickname"><?php _e('Nickname', 'qhebunel'); ?></label></th>
<td><input name="nickname" id="nickname" type="text" required="required" value="<?=$nick_name?>" /></td>
</tr>
<tr title="<?php _e('Your email address is used to send you notifications you request and it\'s used in case you forgot your password.', 'qhebunel'); ?>">
<th><label for="email"><?php _e('Email', 'qhebunel'); ?></label></th>
<td><input name="email" id="email" type="email" required="required" value="<?=$email?>" /><span class="icon">✓</span></td>
</tr>
<?php if ($user_id == $current_user->ID) {?>
<tr title="<?php _e('Leave the password fields blank if you don\'t want to change your current password.', 'qhebunel'); ?>">
<th><label for="old-pass"><?php _e('Old password', 'qhebunel'); ?></label></th>
<td><input name="old-pass" id="old-pass" type="password" value="" /><span class="icon"></span></td>
</tr>
<?php } ?>
<tr title="<?php _e('Leave the password fields blank if you don\'t want to change your current password.', 'qhebunel'); ?>">
<th><label for="pass1"><?php _e('New password', 'qhebunel'); ?></label></th>
<td><input name="pass1" id="pass1" type="password" value="" /><span class="icon"></span></td>
</tr>
<tr title="<?php _e('Leave the password fields blank if you don\'t want to change your current password.', 'qhebunel'); ?>">
<th><label for="pass2"><?php _e('New password', 'qhebunel'); ?></label></th>
<td><input name="pass2" id="pass2" type="password" value="" /><span class="icon"></span></td>
</tr>
</tbody>
</table>
<h2><?php _e('Avatar and signature', 'qhebunel'); ?></h2>
<table class="profile_settings">
<tfoot>
<tr><td colspan="2"><input name="update" type="submit" value="<?php _e('Save', 'qhebunel'); ?>" /></td></tr>
</tfoot>
<tbody>
<tr>
<th><?php _e('Current avatar', 'qhebunel'); ?></th>
<td>
<?php
if (!empty($ext_data['avatar'])) {
echo('<img src="'.WP_CONTENT_URL.'/forum/avatars/'.$ext_data['avatar'].'" alt="" />');
echo('<br/><input name="delete_avatar" type="submit" value="'.__('Delete avatar', 'qhebunel').'" />');
} else {
_e('You don\'t have an avatar.', 'qhebunel');
}
?>
</td>
</tr>
<tr>
<th><?php _e('Upload new avatar', 'qhebunel'); ?></th>
<td>
<input type="file" name="avatar" accept="image/jpeg,image/png,image/gif" />
</td>
</tr>
<tr>
<th><?php _e('Current signature', 'qhebunel'); ?></th>
<td>
<?php
if (!empty($ext_data['signature'])) {
echo('<div class="user-signature">'.QhebunelUI::format_post($ext_data['signature']).'</div>');
} else {
_e('You don\'t have a signature.', 'qhebunel');
}
?>
</td>
</tr>
<tr>
<th><?php _e('Edit signature', 'qhebunel'); ?></th>
<td>
<textarea name="signature"><?=(empty($ext_data['signature']) ? '' : $ext_data['signature'])?></textarea>
</td>
</tr>
</tbody>
</table>
</form> | attilawagner/qhebunel | pages/profileedit.php | PHP | gpl-3.0 | 5,850 |
<?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/>.
/**
* Strings for component 'qtype_ddimageortext', language 'es', branch 'MOODLE_26_STABLE'
*
* @package qtype_ddimageortext
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['pluginname'] = 'Arrastrar y soltar sobre una imagen';
$string['pluginnameadding'] = 'Añadir arrastrar y soltar sobre una imagen';
$string['pluginnameediting'] = 'Editar arrastrar y soltar sobre una imagen';
| dixidix/simulacion | extras/moodledata/lang/es/qtype_ddimageortext.php | PHP | gpl-3.0 | 1,223 |
from argparse import ArgumentParser, ArgumentTypeError
from locale import getdefaultlocale
from multiprocessing import Pool
from contextlib import redirect_stdout
from io import StringIO
from zdict import constants, utils, easter_eggs
from zdict.api import dump
from zdict.completer import DictCompleter
from zdict.loader import get_dictionary_map
from zdict.utils import readline, check_zdict_dir_and_db
def user_set_encoding_and_is_utf8():
# Check user's encoding settings
try:
(lang, enc) = getdefaultlocale()
except ValueError:
print("Didn't detect your LC_ALL environment variable.")
print("Please export LC_ALL with some UTF-8 encoding.")
print("For example: `export LC_ALL=en_US.UTF-8`")
return False
else:
if enc != "UTF-8":
print("zdict only works with encoding=UTF-8, ")
print("but your encoding is: {} {}".format(lang, enc))
print("Please export LC_ALL with some UTF-8 encoding.")
print("For example: `export LC_ALL=en_US.UTF-8`")
return False
return True
def get_args():
# parse args
parser = ArgumentParser(prog='zdict')
parser.add_argument(
'words',
metavar='word',
type=str,
nargs='*',
help='Words for searching its translation'
)
parser.add_argument(
"-v", "--version",
action="version",
version='%(prog)s-' + constants.VERSION
)
parser.add_argument(
"-d", "--disable-db-cache",
default=False,
action="store_true",
help="Temporarily not using the result from db cache.\
(still save the result into db)"
)
parser.add_argument(
"-t", "--query-timeout",
type=float,
default=5.0,
action="store",
help="Set timeout for every query. default is 5 seconds."
)
def positive_int_only(value):
ivalue = int(value)
if ivalue <= 0:
raise ArgumentTypeError(
"%s is an invalid positive int value" % value
)
return ivalue
parser.add_argument(
"-j", "--jobs",
type=positive_int_only,
nargs="?",
default=0, # 0: not using, None: auto, N (1, 2, ...): N jobs
action="store",
help="""
Allow N jobs at once.
Do not pass any argument to use the number of CPUs in the system.
"""
)
parser.add_argument(
"-sp", "--show-provider",
default=False,
action="store_true",
help="Show the dictionary provider of the queried word"
)
parser.add_argument(
"-su", "--show-url",
default=False,
action="store_true",
help="Show the url of the queried word"
)
available_dictionaries = list(dictionary_map.keys())
available_dictionaries.append('all')
parser.add_argument(
"-dt", "--dict",
default="yahoo",
action="store",
choices=available_dictionaries,
metavar=','.join(available_dictionaries),
help="""
Must be seperated by comma and no spaces after each comma.
Choose the dictionary you want. (default: yahoo)
Use 'all' for qureying all dictionaries.
If 'all' or more than 1 dictionaries been chosen,
--show-provider will be set to True in order to
provide more understandable output.
"""
)
parser.add_argument(
"-ld", "--list-dicts",
default=False,
action="store_true",
help="Show currently supported dictionaries."
)
parser.add_argument(
"-V", "--verbose",
default=False,
action="store_true",
help="Show more information for the queried word.\
(If the chosen dictionary have implemented verbose related functions)"
)
parser.add_argument(
"-c", "--force-color",
default=False,
action="store_true",
help="Force color printing (zdict automatically disable color printing \
when output is not a tty, use this option to force color printing)"
)
parser.add_argument(
'--dump', dest='pattern',
nargs='?',
default=None, const=r'^.*$',
help='Dump the querying history, can be filtered with regex'
)
parser.add_argument(
"-D", "--debug",
default=False,
action="store_true",
help="Print raw html prettified by BeautifulSoup for debugging."
)
return parser.parse_args()
def set_args(args):
if args.force_color:
utils.Color.set_force_color()
args.dict = args.dict.split(',')
if 'all' in args.dict:
args.dict = tuple(dictionary_map.keys())
else:
# Uniq and Filter the dict not in supported dictionary list then sort.
args.dict = sorted(set(d for d in args.dict if d in dictionary_map))
if len(args.dict) > 1:
args.show_provider = True
return args
def lookup_string_wrapper(dict_class, word, args):
import sys
if args.force_color:
utils.Color.set_force_color()
else:
utils.Color.set_force_color(sys.stdout.isatty())
dictionary = dict_class(args)
f = StringIO()
with redirect_stdout(f):
dictionary.lookup(word)
return f.getvalue()
def init_worker():
# When -j been used, make subprocesses ignore KeyboardInterrupt
# for not showing KeyboardInterrupt traceback error message.
import signal
signal.signal(signal.SIGINT, signal.SIG_IGN)
def normal_mode(args):
if args.jobs == 0:
# user didn't use `-j`
for word in args.words:
for d in args.dict:
zdict = dictionary_map[d](args)
zdict.lookup(word)
else:
# user did use `-j`
# If processes is None, os.cpu_count() is used.
pool = Pool(args.jobs, init_worker)
for word in args.words:
futures = [
pool.apply_async(lookup_string_wrapper,
(dictionary_map[d], word, args))
for d in args.dict
]
results = [i.get() for i in futures]
print(''.join(results))
easter_eggs.lookup_pyjokes(word)
class MetaInteractivePrompt():
def __init__(self, args):
self.args = args
self.dicts = tuple(
dictionary_map[d](self.args) for d in self.args.dict
)
self.dict_classes = tuple(dictionary_map[d] for d in self.args.dict)
if self.args.jobs == 0:
# user didn't use `-j`
self.pool = None
else:
# user did use `-j`
# If processes is None, os.cpu_count() is used.
self.pool = Pool(self.args.jobs, init_worker)
def __del__(self):
del self.dicts
def prompt(self):
user_input = input('[zDict]: ').strip()
if user_input:
if self.pool:
futures = [
self.pool.apply_async(lookup_string_wrapper,
(d, user_input, self.args))
for d in self.dict_classes
]
results = [i.get() for i in futures]
print(''.join(results))
else:
for dictionary_instance in self.dicts:
dictionary_instance.lookup(user_input)
else:
return
def loop_prompt(self):
while True:
self.prompt()
def interactive_mode(args):
# configure readline and completer
readline.parse_and_bind("tab: complete")
readline.set_completer(DictCompleter().complete)
zdict = MetaInteractivePrompt(args)
zdict.loop_prompt()
def execute_zdict(args):
if args.list_dicts:
for provider in sorted(dictionary_map):
print(
'{}: {}\n{}\n'.format(
provider,
dictionary_map[provider](args).title,
dictionary_map[provider](args).HOMEPAGE_URL,
)
)
exit()
if args.pattern:
for word in dump(pattern=args.pattern):
print(word)
exit()
try:
if args.words:
normal_mode(args)
else:
interactive_mode(args)
except (KeyboardInterrupt, EOFError):
print()
return
def main():
if user_set_encoding_and_is_utf8():
check_zdict_dir_and_db()
global dictionary_map
dictionary_map = get_dictionary_map()
args = get_args()
args = set_args(args)
execute_zdict(args)
else:
exit()
| zdict/zdict | zdict/zdict.py | Python | gpl-3.0 | 8,711 |
package edu.uiuc.zenvisage.zqlcomplete.executor;
import java.util.ArrayList;
import java.util.List;
public class ZColumn {
private String variable;
private String attribute; //put z here
private List<String> values;
private String expression;
private boolean aggregate;
// after executing expression, implement after set operation is implemented
// private List<String> parsedValues;
public ZColumn(String attribute) {
this.attribute = attribute;
}
public ZColumn() {
variable = "";
attribute = "";
values = new ArrayList<String>();
expression = "";
aggregate = false;
// parsedValues = new ArrayList<String>();
}
public String getVariable() {
return variable;
}
public void setVariable(String source) {
variable = source;
}
public String getExpression() {
return expression;
}
public void setExpression(String source) {
expression = source;
}
public String getAttribute() {
return attribute;
}
public void setAttribute(String source) {
attribute = source;
}
public List<String> getValues() {
return values;
}
public void setValues(List<String> source) {
values = source;
}
public boolean isAggregate() {
return aggregate;
}
public void setAggregate(boolean aggregate) {
this.aggregate = aggregate;
}
}
| zenvisage/zenvisage | src/main/java/edu/uiuc/zenvisage/zqlcomplete/executor/ZColumn.java | Java | gpl-3.0 | 1,296 |
/**=========================================================
* Module: SupportService.js
* Checks for features supports on browser
=========================================================*/
/*jshint -W069*/
(function() {
'use strict';
angular
.module('naut')
.service('support', service);
service.$inject = ['$document', '$window'];
function service($document, $window) {
/*jshint validthis:true*/
var support = this;
var doc = $document[0];
// Check for transition support
// -----------------------------------
support.transition = (function() {
function transitionEnd() {
var el = document.createElement('bootstrap');
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
};
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] };
}
}
return false;
}
return transitionEnd();
})();
// Check for animation support
// -----------------------------------
support.animation = (function() {
var animationEnd = (function() {
var element = doc.body || doc.documentElement,
animEndEventNames = {
WebkitAnimation: 'webkitAnimationEnd',
MozAnimation: 'animationend',
OAnimation: 'oAnimationEnd oanimationend',
animation: 'animationend'
}, name;
for (name in animEndEventNames) {
if (element.style[name] !== undefined) return animEndEventNames[name];
}
}());
return animationEnd && { end: animationEnd };
})();
// Check touch device
// -----------------------------------
support.touch = (
('ontouchstart' in window && navigator.userAgent.toLowerCase().match(/mobile|tablet/)) ||
($window.DocumentTouch && document instanceof $window.DocumentTouch) ||
($window.navigator['msPointerEnabled'] && $window.navigator['msMaxTouchPoints'] > 0) || //IE 10
($window.navigator['pointerEnabled'] && $window.navigator['maxTouchPoints'] > 0) || //IE >=11
false
);
return support;
}
})();
| rdemorais/ecar-spa | pe-spa/src/js/modules/common/services/support.service.js | JavaScript | gpl-3.0 | 2,683 |
# Generated by Django 2.0.9 on 2019-01-25 03:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('base', '0009_auto_20170824_0722'),
]
operations = [
migrations.AlterField(
model_name='alphagramtag',
name='tag',
field=models.CharField(choices=[('D5', 'Very Easy'), ('D4', 'Easy'), ('D3', 'Average'), ('D2', 'Hard'), ('D1', 'Very Hard')], max_length=2),
),
]
| domino14/Webolith | djAerolith/base/migrations/0010_auto_20190124_1902.py | Python | gpl-3.0 | 488 |
# Authors:
# Jason Gerard DeRose <jderose@redhat.com>
#
# Copyright (C) 2008 Red Hat
# see file 'COPYING' for use and warranty information
#
# 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/>.
"""
Test the `ipalib.crud` module.
"""
from ipatests.util import read_only, raises, get_api, ClassChecker
from ipalib import crud, frontend, plugable, config
from ipalib.parameters import Str
class CrudChecker(ClassChecker):
"""
Class for testing base classes in `ipalib.crud`.
"""
def get_api(self, args=tuple(), options=tuple()):
"""
Return a finalized `ipalib.plugable.API` instance.
"""
(api, home) = get_api()
class user(frontend.Object):
takes_params = (
'givenname',
Str('sn', flags='no_update'),
Str('uid', primary_key=True),
'initials',
Str('uidnumber', flags=['no_create', 'no_search'])
)
class user_verb(self.cls):
takes_args = args
takes_options = options
api.register(user)
api.register(user_verb)
api.finalize()
return api
class test_Create(CrudChecker):
"""
Test the `ipalib.crud.Create` class.
"""
_cls = crud.Create
def test_get_args(self):
"""
Test the `ipalib.crud.Create.get_args` method.
"""
api = self.get_api()
assert list(api.Method.user_verb.args) == ['uid']
assert api.Method.user_verb.args.uid.required is True
def test_get_options(self):
"""
Test the `ipalib.crud.Create.get_options` method.
"""
api = self.get_api()
assert list(api.Method.user_verb.options) == \
['givenname', 'sn', 'initials', 'all', 'raw', 'version']
for param in api.Method.user_verb.options():
if param.name != 'version':
assert param.required is True
api = self.get_api(options=(Str('extra?'),))
assert list(api.Method.user_verb.options) == \
['givenname', 'sn', 'initials', 'extra', 'all', 'raw', 'version']
assert api.Method.user_verb.options.extra.required is False
class test_Update(CrudChecker):
"""
Test the `ipalib.crud.Update` class.
"""
_cls = crud.Update
def test_get_args(self):
"""
Test the `ipalib.crud.Update.get_args` method.
"""
api = self.get_api()
assert list(api.Method.user_verb.args) == ['uid']
assert api.Method.user_verb.args.uid.required is True
def test_get_options(self):
"""
Test the `ipalib.crud.Update.get_options` method.
"""
api = self.get_api()
assert list(api.Method.user_verb.options) == \
['givenname', 'initials', 'uidnumber', 'all', 'raw', 'version']
for param in api.Method.user_verb.options():
if param.name in ['all', 'raw']:
assert param.required is True
else:
assert param.required is False
class test_Retrieve(CrudChecker):
"""
Test the `ipalib.crud.Retrieve` class.
"""
_cls = crud.Retrieve
def test_get_args(self):
"""
Test the `ipalib.crud.Retrieve.get_args` method.
"""
api = self.get_api()
assert list(api.Method.user_verb.args) == ['uid']
assert api.Method.user_verb.args.uid.required is True
def test_get_options(self):
"""
Test the `ipalib.crud.Retrieve.get_options` method.
"""
api = self.get_api()
assert list(api.Method.user_verb.options) == ['all', 'raw', 'version']
class test_Delete(CrudChecker):
"""
Test the `ipalib.crud.Delete` class.
"""
_cls = crud.Delete
def test_get_args(self):
"""
Test the `ipalib.crud.Delete.get_args` method.
"""
api = self.get_api()
assert list(api.Method.user_verb.args) == ['uid']
assert api.Method.user_verb.args.uid.required is True
def test_get_options(self):
"""
Test the `ipalib.crud.Delete.get_options` method.
"""
api = self.get_api()
assert list(api.Method.user_verb.options) == ['version']
assert len(api.Method.user_verb.options) == 1
class test_Search(CrudChecker):
"""
Test the `ipalib.crud.Search` class.
"""
_cls = crud.Search
def test_get_args(self):
"""
Test the `ipalib.crud.Search.get_args` method.
"""
api = self.get_api()
assert list(api.Method.user_verb.args) == ['criteria']
assert api.Method.user_verb.args.criteria.required is False
def test_get_options(self):
"""
Test the `ipalib.crud.Search.get_options` method.
"""
api = self.get_api()
assert list(api.Method.user_verb.options) == \
['givenname', 'sn', 'uid', 'initials', 'all', 'raw', 'version']
for param in api.Method.user_verb.options():
if param.name in ['all', 'raw']:
assert param.required is True
else:
assert param.required is False
class test_CrudBackend(ClassChecker):
"""
Test the `ipalib.crud.CrudBackend` class.
"""
_cls = crud.CrudBackend
def get_subcls(self):
class ldap(self.cls):
pass
return ldap
def check_method(self, name, *args):
o = self.cls()
e = raises(NotImplementedError, getattr(o, name), *args)
assert str(e) == 'CrudBackend.%s()' % name
sub = self.subcls()
e = raises(NotImplementedError, getattr(sub, name), *args)
assert str(e) == 'ldap.%s()' % name
def test_create(self):
"""
Test the `ipalib.crud.CrudBackend.create` method.
"""
self.check_method('create')
def test_retrieve(self):
"""
Test the `ipalib.crud.CrudBackend.retrieve` method.
"""
self.check_method('retrieve', 'primary key', 'attribute')
def test_update(self):
"""
Test the `ipalib.crud.CrudBackend.update` method.
"""
self.check_method('update', 'primary key')
def test_delete(self):
"""
Test the `ipalib.crud.CrudBackend.delete` method.
"""
self.check_method('delete', 'primary key')
def test_search(self):
"""
Test the `ipalib.crud.CrudBackend.search` method.
"""
self.check_method('search')
| cluck/freeipa | ipatests/test_ipalib/test_crud.py | Python | gpl-3.0 | 7,084 |
<?php
/*
* GraPHPizer source code analytics engine (cli component)
* Copyright (C) 2015 Martin Helmich <kontakt@martin-helmich.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Helmich\Graphizer\Persistence\Op;
use Helmich\Graphizer\Persistence\Op\Builder\EdgeBuilder;
use Helmich\Graphizer\Persistence\Op\Builder\UpdateBuilder;
/**
* Creates a new node.
*
* @package Helmich\Graphizer
* @subpackage Persistence\Op
*/
class MergeNode extends AbstractOperation implements NodeMatcher {
use EdgeBuilder;
use UpdateBuilder;
use PropertyTrait;
private $id;
private $labels;
/**
* @param string $label
* @param array $properties
*/
public function __construct($label, array $properties = []) {
$this->id = 'node' . sha1(json_encode($properties));
$this->labels = [$label];
$this->properties = $this->filterProperties($properties);
}
/**
* @return string
*/
public function getId() {
return $this->id;
}
/**
* @return string
*/
public function getLabel() {
return $this->labels[0];
}
/**
* @param string $label
* @return void
*/
public function addLabel($label) {
$this->labels[] = $label;
}
/**
* @return string
*/
public function toCypher() {
$propValues = [];
foreach ($this->properties as $key => $value) {
$propValues[] = sprintf('%s: {prop_%s}.%s', $key, $this->id, $key);
}
return sprintf(
'CREATE (%s:%s {%s})',
$this->id,
implode(':', $this->labels),
implode(', ', $propValues)
);
}
/**
* @return array
*/
public function toJson() {
$properties = $this->properties;
$properties['__node_id'] = $this->id;
return [
'nodes' => [
[
'labels' => $this->labels,
'properties' => $properties,
'merge' => TRUE
]
]
];
}
/**
* @return string
*/
public function getArguments() {
$properties = $this->properties;
$properties['__node_id'] = $this->id;
return ['prop_' . $this->id => $properties];
}
/**
* @return NodeMatcher
*/
public function getMatcher() {
return new MatchNodeByIdProperty($this->id);
}
} | martin-helmich/graphpizer-cli | src/Persistence/Op/MergeNode.php | PHP | gpl-3.0 | 2,735 |
<a href="?page=<?=$page?>&cate=<?=$cate?>">
<button type="button" class="btn btn-default" ><i class="fa fa-arrow-left"></i> Back to Testimonial List</button>
</a>
<br><br>
<header class="widget-header">
<a href="?page=<?=$page?>&cate=<?=$cate?>">
<button type="button" class="close">×</button>
</a>
<h4 class="widget-title">Edit Testimonial</h4>
</header><!-- .widget-header -->
<hr class="widget-separator">
<div class="widget-body">
<form action="#" class="form-horizontal" method="post" data-parsley-validate>
<input type="hidden" name="form" value="pages-about-us-editTestimonial">
<input type="hidden" name="token" value="<?=$Token?>">
<div class="form-group">
<label for="control-demo-1" class="col-sm-2">Name</label>
<div class="col-sm-10">
<input type="text" name="txtTitle" id="txtTitle" class="form-control" value="<?=getDataTable("db_testimonial", "testimonial_id", $id, "testimonial_name")?>" required="required">
</div>
</div><!-- .form-group -->
<div class="form-group">
<label for="control-demo-1" class="col-sm-2">Sub Name</label>
<div class="col-sm-10">
<input type="text" name="txtSubName" id="control-demo-1" class="form-control" value="<?=getDataTable("db_testimonial", "testimonial_id", $id, "testimonial_sub_name")?>" required="required">
</div>
</div><!-- .form-group -->
<div class="form-group">
<label for="control-demo-1" class="col-sm-2">Content</label>
<div class="col-sm-10">
<textarea name="txtContent" id="txtContent" class="form-control" cols="30" rows="5" required="required"><?=getDataTable("db_testimonial", "testimonial_id", $id, "testimonial_content")?></textarea>
</div>
</div><!-- .form-group -->
<div class="form-group">
<label for="control-demo-1" class="col-sm-3"><button type="submit" class="btn mw-md btn-primary">Save</button></label>
<div class="col-sm-4">
</div>
</div><!-- .form-group -->
</form>
</div><!-- .widget-body -->
</form> | brandonccy/SmartNano | admincp/modules/pages/about-us/includes/action/editTestimonial.php | PHP | gpl-3.0 | 1,979 |
/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 5.0 */
/* JavaCCOptions:KEEP_LINE_COL=null */
package de.fuberlin.csw.aspectowl.parser;
/**
* This exception is thrown when parse errors are encountered.
* You can explicitly create objects of this exception type by
* calling the method generateParseException in the generated
* parser.
*
* You can modify this class to customize your error reporting
* mechanisms so long as you retain the public fields.
*/
public class ParseException extends Exception {
/**
* The version identifier for this Serializable class.
* Increment only if the <i>serialized</i> form of the
* class changes.
*/
private static final long serialVersionUID = 1L;
/**
* This constructor is used by the method "generateParseException"
* in the generated parser. Calling this constructor generates
* a new object of this type with the fields "currentToken",
* "expectedTokenSequences", and "tokenImage" set.
*/
public ParseException(Token currentTokenVal,
int[][] expectedTokenSequencesVal,
String[] tokenImageVal
)
{
super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal));
currentToken = currentTokenVal;
expectedTokenSequences = expectedTokenSequencesVal;
tokenImage = tokenImageVal;
}
/**
* The following constructors are for use by you for whatever
* purpose you can think of. Constructing the exception in this
* manner makes the exception behave in the normal way - i.e., as
* documented in the class "Throwable". The fields "errorToken",
* "expectedTokenSequences", and "tokenImage" do not contain
* relevant information. The JavaCC generated code does not use
* these constructors.
*/
public ParseException() {
super();
}
/** Constructor with message. */
public ParseException(String message) {
super(message);
}
/**
* This is the last token that has been consumed successfully. If
* this object has been created due to a parse error, the token
* followng this token will (therefore) be the first error token.
*/
public Token currentToken;
/**
* Each entry in this array is an array of integers. Each array
* of integers represents a sequence of tokens (by their ordinal
* values) that is expected at this point of the parse.
*/
public int[][] expectedTokenSequences;
/**
* This is a reference to the "tokenImage" array of the generated
* parser within which the parse error occurred. This array is
* defined in the generated ...Constants interface.
*/
public String[] tokenImage;
/**
* It uses "currentToken" and "expectedTokenSequences" to generate a parse
* error message and returns it. If this object has been created
* due to a parse error, and you do not catch it (it gets thrown
* from the parser) the correct error message
* gets displayed.
*/
private static String initialise(Token currentToken,
int[][] expectedTokenSequences,
String[] tokenImage) {
String eol = System.getProperty("line.separator", "\n");
StringBuffer expected = new StringBuffer();
int maxSize = 0;
for (int i = 0; i < expectedTokenSequences.length; i++) {
if (maxSize < expectedTokenSequences[i].length) {
maxSize = expectedTokenSequences[i].length;
}
for (int j = 0; j < expectedTokenSequences[i].length; j++) {
expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');
}
if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
expected.append("...");
}
expected.append(eol).append(" ");
}
String retval = "Encountered \"";
Token tok = currentToken.next;
for (int i = 0; i < maxSize; i++) {
if (i != 0) retval += " ";
if (tok.kind == 0) {
retval += tokenImage[0];
break;
}
retval += " " + tokenImage[tok.kind];
retval += " \"";
retval += add_escapes(tok.image);
retval += " \"";
tok = tok.next;
}
retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
retval += "." + eol;
if (expectedTokenSequences.length == 1) {
retval += "Was expecting:" + eol + " ";
} else {
retval += "Was expecting one of:" + eol + " ";
}
retval += expected.toString();
return retval;
}
/**
* The end of line string for this machine.
*/
protected String eol = System.getProperty("line.separator", "\n");
/**
* Used to convert raw characters to their escaped version
* when these raw version cannot be used as part of an ASCII
* string literal.
*/
static String add_escapes(String str) {
StringBuffer retval = new StringBuffer();
char ch;
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i))
{
case 0 :
continue;
case '\b':
retval.append("\\b");
continue;
case '\t':
retval.append("\\t");
continue;
case '\n':
retval.append("\\n");
continue;
case '\f':
retval.append("\\f");
continue;
case '\r':
retval.append("\\r");
continue;
case '\"':
retval.append("\\\"");
continue;
case '\'':
retval.append("\\\'");
continue;
case '\\':
retval.append("\\\\");
continue;
default:
if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + s.substring(s.length() - 4, s.length()));
} else {
retval.append(ch);
}
continue;
}
}
return retval.toString();
}
}
/* JavaCC - OriginalChecksum=6aec7c540a7de5b09f956eda7a0c9656 (do not edit this line) */
| ag-csw/aspect-owl-protege | src/main/java/de/fuberlin/csw/aspectowl/parser/ParseException.java | Java | gpl-3.0 | 6,190 |
/**
* Copyright (C) 2001-2016 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.execution;
import com.rapidminer.operator.ExecutionUnit;
import com.rapidminer.operator.OperatorException;
/**
* Executes an {@link ExecutionUnit}.
*
* @author Simon Fischer
* */
public interface UnitExecutor {
public boolean isRemote(ExecutionUnit unit);
public void execute(ExecutionUnit unit) throws OperatorException;
public boolean validate(ExecutionUnit unit, String mode) throws OperatorException;
}
| transwarpio/rapidminer | rapidMiner/rapidminer-studio-core/src/main/java/com/rapidminer/operator/execution/UnitExecutor.java | Java | gpl-3.0 | 1,306 |
package com.fuav.android.view.checklist.row;
import com.fuav.android.R;
import com.fuav.android.view.checklist.CheckListItem;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.EditText;
public class ListRow_Note extends ListRow implements OnFocusChangeListener {
public ListRow_Note(LayoutInflater inflater, final CheckListItem checkListItem) {
super(inflater, checkListItem);
}
@Override
public View getView(View convertView) {
View view;
if (convertView == null) {
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.list_note_item, null);
holder = new ViewHolder(viewGroup, checkListItem);
viewGroup.setTag(holder);
view = viewGroup;
} else {
view = convertView;
holder = (ViewHolder) convertView.getTag();
}
updateDisplay((ViewHolder) holder);
return view;
}
private void updateDisplay(ViewHolder holder) {
holder.editTextView.setOnFocusChangeListener(this);
holder.editTextView.setText(checkListItem.getValue());
updateCheckBox(checkListItem.isVerified());
}
@Override
public int getViewType() {
return ListRow_Type.NOTE_ROW.ordinal();
}
private static class ViewHolder extends BaseViewHolder {
private EditText editTextView;
private ViewHolder(ViewGroup viewGroup, CheckListItem checkListItem) {
super(viewGroup, checkListItem);
}
@Override
protected void setupViewItems(ViewGroup viewGroup, CheckListItem checkListItem) {
this.editTextView = (EditText) viewGroup.findViewById(R.id.lst_note);
}
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!v.isFocused() && this.listener != null) {
checkListItem.setValue(((ViewHolder) this.holder).editTextView.getText().toString());
updateRowChanged();
}
}
}
| forgodsake/TowerPlus | Android/src/com/fuav/android/view/checklist/row/ListRow_Note.java | Java | gpl-3.0 | 1,912 |
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/gen0cide/laforge/ent/ginfilemiddleware"
"github.com/gen0cide/laforge/ent/provisionedhost"
"github.com/gen0cide/laforge/ent/provisioningstep"
"github.com/google/uuid"
)
// GinFileMiddlewareCreate is the builder for creating a GinFileMiddleware entity.
type GinFileMiddlewareCreate struct {
config
mutation *GinFileMiddlewareMutation
hooks []Hook
}
// SetURLID sets the "url_id" field.
func (gfmc *GinFileMiddlewareCreate) SetURLID(s string) *GinFileMiddlewareCreate {
gfmc.mutation.SetURLID(s)
return gfmc
}
// SetFilePath sets the "file_path" field.
func (gfmc *GinFileMiddlewareCreate) SetFilePath(s string) *GinFileMiddlewareCreate {
gfmc.mutation.SetFilePath(s)
return gfmc
}
// SetAccessed sets the "accessed" field.
func (gfmc *GinFileMiddlewareCreate) SetAccessed(b bool) *GinFileMiddlewareCreate {
gfmc.mutation.SetAccessed(b)
return gfmc
}
// SetNillableAccessed sets the "accessed" field if the given value is not nil.
func (gfmc *GinFileMiddlewareCreate) SetNillableAccessed(b *bool) *GinFileMiddlewareCreate {
if b != nil {
gfmc.SetAccessed(*b)
}
return gfmc
}
// SetID sets the "id" field.
func (gfmc *GinFileMiddlewareCreate) SetID(u uuid.UUID) *GinFileMiddlewareCreate {
gfmc.mutation.SetID(u)
return gfmc
}
// SetGinFileMiddlewareToProvisionedHostID sets the "GinFileMiddlewareToProvisionedHost" edge to the ProvisionedHost entity by ID.
func (gfmc *GinFileMiddlewareCreate) SetGinFileMiddlewareToProvisionedHostID(id uuid.UUID) *GinFileMiddlewareCreate {
gfmc.mutation.SetGinFileMiddlewareToProvisionedHostID(id)
return gfmc
}
// SetNillableGinFileMiddlewareToProvisionedHostID sets the "GinFileMiddlewareToProvisionedHost" edge to the ProvisionedHost entity by ID if the given value is not nil.
func (gfmc *GinFileMiddlewareCreate) SetNillableGinFileMiddlewareToProvisionedHostID(id *uuid.UUID) *GinFileMiddlewareCreate {
if id != nil {
gfmc = gfmc.SetGinFileMiddlewareToProvisionedHostID(*id)
}
return gfmc
}
// SetGinFileMiddlewareToProvisionedHost sets the "GinFileMiddlewareToProvisionedHost" edge to the ProvisionedHost entity.
func (gfmc *GinFileMiddlewareCreate) SetGinFileMiddlewareToProvisionedHost(p *ProvisionedHost) *GinFileMiddlewareCreate {
return gfmc.SetGinFileMiddlewareToProvisionedHostID(p.ID)
}
// SetGinFileMiddlewareToProvisioningStepID sets the "GinFileMiddlewareToProvisioningStep" edge to the ProvisioningStep entity by ID.
func (gfmc *GinFileMiddlewareCreate) SetGinFileMiddlewareToProvisioningStepID(id uuid.UUID) *GinFileMiddlewareCreate {
gfmc.mutation.SetGinFileMiddlewareToProvisioningStepID(id)
return gfmc
}
// SetNillableGinFileMiddlewareToProvisioningStepID sets the "GinFileMiddlewareToProvisioningStep" edge to the ProvisioningStep entity by ID if the given value is not nil.
func (gfmc *GinFileMiddlewareCreate) SetNillableGinFileMiddlewareToProvisioningStepID(id *uuid.UUID) *GinFileMiddlewareCreate {
if id != nil {
gfmc = gfmc.SetGinFileMiddlewareToProvisioningStepID(*id)
}
return gfmc
}
// SetGinFileMiddlewareToProvisioningStep sets the "GinFileMiddlewareToProvisioningStep" edge to the ProvisioningStep entity.
func (gfmc *GinFileMiddlewareCreate) SetGinFileMiddlewareToProvisioningStep(p *ProvisioningStep) *GinFileMiddlewareCreate {
return gfmc.SetGinFileMiddlewareToProvisioningStepID(p.ID)
}
// Mutation returns the GinFileMiddlewareMutation object of the builder.
func (gfmc *GinFileMiddlewareCreate) Mutation() *GinFileMiddlewareMutation {
return gfmc.mutation
}
// Save creates the GinFileMiddleware in the database.
func (gfmc *GinFileMiddlewareCreate) Save(ctx context.Context) (*GinFileMiddleware, error) {
var (
err error
node *GinFileMiddleware
)
gfmc.defaults()
if len(gfmc.hooks) == 0 {
if err = gfmc.check(); err != nil {
return nil, err
}
node, err = gfmc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GinFileMiddlewareMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = gfmc.check(); err != nil {
return nil, err
}
gfmc.mutation = mutation
if node, err = gfmc.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(gfmc.hooks) - 1; i >= 0; i-- {
if gfmc.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = gfmc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, gfmc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (gfmc *GinFileMiddlewareCreate) SaveX(ctx context.Context) *GinFileMiddleware {
v, err := gfmc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (gfmc *GinFileMiddlewareCreate) Exec(ctx context.Context) error {
_, err := gfmc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (gfmc *GinFileMiddlewareCreate) ExecX(ctx context.Context) {
if err := gfmc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (gfmc *GinFileMiddlewareCreate) defaults() {
if _, ok := gfmc.mutation.Accessed(); !ok {
v := ginfilemiddleware.DefaultAccessed
gfmc.mutation.SetAccessed(v)
}
if _, ok := gfmc.mutation.ID(); !ok {
v := ginfilemiddleware.DefaultID()
gfmc.mutation.SetID(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (gfmc *GinFileMiddlewareCreate) check() error {
if _, ok := gfmc.mutation.URLID(); !ok {
return &ValidationError{Name: "url_id", err: errors.New(`ent: missing required field "url_id"`)}
}
if _, ok := gfmc.mutation.FilePath(); !ok {
return &ValidationError{Name: "file_path", err: errors.New(`ent: missing required field "file_path"`)}
}
if _, ok := gfmc.mutation.Accessed(); !ok {
return &ValidationError{Name: "accessed", err: errors.New(`ent: missing required field "accessed"`)}
}
return nil
}
func (gfmc *GinFileMiddlewareCreate) sqlSave(ctx context.Context) (*GinFileMiddleware, error) {
_node, _spec := gfmc.createSpec()
if err := sqlgraph.CreateNode(ctx, gfmc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err}
}
return nil, err
}
if _spec.ID.Value != nil {
_node.ID = _spec.ID.Value.(uuid.UUID)
}
return _node, nil
}
func (gfmc *GinFileMiddlewareCreate) createSpec() (*GinFileMiddleware, *sqlgraph.CreateSpec) {
var (
_node = &GinFileMiddleware{config: gfmc.config}
_spec = &sqlgraph.CreateSpec{
Table: ginfilemiddleware.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: ginfilemiddleware.FieldID,
},
}
)
if id, ok := gfmc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = id
}
if value, ok := gfmc.mutation.URLID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: ginfilemiddleware.FieldURLID,
})
_node.URLID = value
}
if value, ok := gfmc.mutation.FilePath(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: ginfilemiddleware.FieldFilePath,
})
_node.FilePath = value
}
if value, ok := gfmc.mutation.Accessed(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: ginfilemiddleware.FieldAccessed,
})
_node.Accessed = value
}
if nodes := gfmc.mutation.GinFileMiddlewareToProvisionedHostIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Inverse: false,
Table: ginfilemiddleware.GinFileMiddlewareToProvisionedHostTable,
Columns: []string{ginfilemiddleware.GinFileMiddlewareToProvisionedHostColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: provisionedhost.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := gfmc.mutation.GinFileMiddlewareToProvisioningStepIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Inverse: false,
Table: ginfilemiddleware.GinFileMiddlewareToProvisioningStepTable,
Columns: []string{ginfilemiddleware.GinFileMiddlewareToProvisioningStepColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: provisioningstep.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// GinFileMiddlewareCreateBulk is the builder for creating many GinFileMiddleware entities in bulk.
type GinFileMiddlewareCreateBulk struct {
config
builders []*GinFileMiddlewareCreate
}
// Save creates the GinFileMiddleware entities in the database.
func (gfmcb *GinFileMiddlewareCreateBulk) Save(ctx context.Context) ([]*GinFileMiddleware, error) {
specs := make([]*sqlgraph.CreateSpec, len(gfmcb.builders))
nodes := make([]*GinFileMiddleware, len(gfmcb.builders))
mutators := make([]Mutator, len(gfmcb.builders))
for i := range gfmcb.builders {
func(i int, root context.Context) {
builder := gfmcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GinFileMiddlewareMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, gfmcb.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, gfmcb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, gfmcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (gfmcb *GinFileMiddlewareCreateBulk) SaveX(ctx context.Context) []*GinFileMiddleware {
v, err := gfmcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (gfmcb *GinFileMiddlewareCreateBulk) Exec(ctx context.Context) error {
_, err := gfmcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (gfmcb *GinFileMiddlewareCreateBulk) ExecX(ctx context.Context) {
if err := gfmcb.Exec(ctx); err != nil {
panic(err)
}
}
| gen0cide/laforge | ent/ginfilemiddleware_create.go | GO | gpl-3.0 | 11,377 |
/**
* junit-remote
*
* 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/.
*
* @author Tradeshift - http://www.tradeshift.com
*/
package com.tradeshift.test.remote.internal;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
public class RedirectingStream extends OutputStream {
private final PrintStream delegate;
private OutputStream redirector;
public RedirectingStream(PrintStream delegate) {
this.delegate = delegate;
}
@Override
public void write(int b) throws IOException {
delegate.write(b);
if (redirector != null) {
redirector.write(b);
}
}
public void setRedirector(OutputStream redirector) {
this.redirector = redirector;
}
}
| Tradeshift/junit-remote | src/main/java/com/tradeshift/test/remote/internal/RedirectingStream.java | Java | gpl-3.0 | 1,372 |
/* This file is part of the db4o object database http://www.db4o.com
Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com
db4o is free software; you can redistribute it and/or modify it under
the terms of version 3 of the GNU General Public License as published
by the Free Software Foundation.
db4o 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 com.db4o.db4ounit.common.assorted;
import java.util.*;
import com.db4o.ext.*;
import db4ounit.*;
import db4ounit.extensions.*;
@decaf.Remove(decaf.Platform.JDK11)
public class TransientCloneTestCase extends AbstractDb4oTestCase {
public static class Item {
public List list;
public Hashtable ht;
public String str;
public int myInt;
public Molecule[] molecules;
}
@Override
protected void store() throws Exception {
Item item = new Item();
item.list = new ArrayList();
item.list.add(new Atom("listAtom"));
item.list.add(item);
item.ht = new Hashtable();
item.ht.put("htc", new Molecule("htAtom"));
item.ht.put("recurse", item);
item.str = "str";
item.myInt = 100;
item.molecules = new Molecule[3];
for (int i = 0; i < item.molecules.length; i++) {
item.molecules[i] = new Molecule("arr" + i);
item.molecules[i].child = new Atom("arr" + i);
item.molecules[i].child.child = new Atom("arrc" + i);
}
store(item);
}
public void test() {
final Item item = retrieveOnlyInstance(Item.class);
db().activate(item, Integer.MAX_VALUE);
Item originalValues = peekPersisted(false);
cmp(item, originalValues);
db().deactivate(item, Integer.MAX_VALUE);
Item modified = peekPersisted(false);
cmp(originalValues, modified);
db().activate(item, Integer.MAX_VALUE);
modified.str = "changed";
modified.molecules[0].name = "changed";
item.str = "changed";
item.molecules[0].name = "changed";
db().store(item.molecules[0]);
db().store(item);
Item tc = peekPersisted(true);
cmp(originalValues, tc);
tc = peekPersisted(false);
cmp(modified, tc);
db().commit();
tc = peekPersisted(true);
cmp(modified, tc);
}
private void cmp(Item to, Item tc) {
Assert.isTrue(tc != to);
Assert.isTrue(tc.list != to);
Assert.isTrue(tc.list.size() == to.list.size());
Iterator i = tc.list.iterator();
Atom tca = next(i);
Iterator j = to.list.iterator();
Atom tct = next(j);
Assert.isTrue(tca != tct);
Assert.isTrue(tca.name.equals(tct.name));
Assert.areSame(next(i), tc);
Assert.areSame(next(j), to);
Assert.isTrue(tc.ht != to.ht);
Molecule tcm = (Molecule) tc.ht.get("htc");
Molecule tom = (Molecule) to.ht.get("htc");
Assert.isTrue(tcm != tom);
Assert.isTrue(tcm.name.equals(tom.name));
Assert.areSame(tc.ht.get("recurse"), tc);
Assert.areSame(to.ht.get("recurse"), to);
Assert.areEqual(to.str, tc.str);
Assert.isTrue(tc.str.equals(to.str));
Assert.isTrue(tc.myInt == to.myInt);
Assert.isTrue(tc.molecules.length == to.molecules.length);
Assert.isTrue(tc.molecules.length == to.molecules.length);
tcm = tc.molecules[0];
tom = to.molecules[0];
Assert.isTrue(tcm != tom);
Assert.isTrue(tcm.name.equals(tom.name));
Assert.isTrue(tcm.child != tom.child);
Assert.isTrue(tcm.child.name.equals(tom.child.name));
}
private <T> T next (Iterator i) {
Assert.isTrue(i.hasNext());
return (T)i.next();
}
private Item peekPersisted(boolean committed) {
ExtObjectContainer oc = db();
return oc.peekPersisted(retrieveOnlyInstance(Item.class), Integer.MAX_VALUE, committed);
}
}
| potty-dzmeia/db4o | src/db4oj.tests/src/com/db4o/db4ounit/common/assorted/TransientCloneTestCase.java | Java | gpl-3.0 | 3,796 |
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2015, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.server.subcommands;
import net.minecraft.command.ICommandSender;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.ChunkEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import appeng.core.AEConfig;
import appeng.core.AELog;
import appeng.core.features.AEFeature;
import appeng.server.ISubCommand;
public class ChunkLogger implements ISubCommand
{
private boolean enabled = false;
@SubscribeEvent
public void onChunkLoadEvent( final ChunkEvent.Load event )
{
if( !event.world.isRemote )
{
AELog.info( "Chunk Loaded: " + event.getChunk().xPosition + ", " + event.getChunk().zPosition );
this.displayStack();
}
}
private void displayStack()
{
if( AEConfig.instance.isFeatureEnabled( AEFeature.ChunkLoggerTrace ) )
{
boolean output = false;
for( final StackTraceElement e : Thread.currentThread().getStackTrace() )
{
if( output )
{
AELog.info( " " + e.getClassName() + '.' + e.getMethodName() + " (" + e.getLineNumber() + ')' );
}
else
{
output = e.getClassName().contains( "EventBus" ) && e.getMethodName().contains( "post" );
}
}
}
}
@SubscribeEvent
public void onChunkUnloadEvent( final ChunkEvent.Unload unload )
{
if( !unload.world.isRemote )
{
AELog.info( "Chunk Unloaded: " + unload.getChunk().xPosition + ", " + unload.getChunk().zPosition );
this.displayStack();
}
}
@Override
public String getHelp( final MinecraftServer srv )
{
return "commands.ae2.ChunkLogger";
}
@Override
public void call( final MinecraftServer srv, final String[] data, final ICommandSender sender )
{
this.enabled = !this.enabled;
if( this.enabled )
{
MinecraftForge.EVENT_BUS.register( this );
sender.addChatMessage( new ChatComponentTranslation( "commands.ae2.ChunkLoggerOn" ) );
}
else
{
MinecraftForge.EVENT_BUS.unregister( this );
sender.addChatMessage( new ChatComponentTranslation( "commands.ae2.ChunkLoggerOff" ) );
}
}
}
| itachi1706/Applied-Energistics-2 | src/main/java/appeng/server/subcommands/ChunkLogger.java | Java | gpl-3.0 | 2,932 |
#include "code_generator_widget.h"
#include <iostream>
#include <fstream>
#include <map>
#include <string>
CodeGeneratorWidget::CodeGeneratorWidget(QWidget *parent, Qt::WindowFlags f) : QDialog(parent,f)
{
setupUi(this);
code_hl=new SyntaxHighlighter(code_txt);
code_hl->loadConfiguration(GlobalAttributes::XML_HIGHLIGHT_CONF_PATH);
connect(close_btn, SIGNAL(clicked(void)), this, SLOT(close(void)));
connect(clear_btn, SIGNAL(clicked(void)), this, SLOT(doClearCode(void)));
connect(generate_btn, SIGNAL(clicked(void)), this, SLOT(doGenerateCode(void)));
this->generator = 0;
}
void CodeGeneratorWidget::setGenerator(BaseCodeGenerator *generator)
{
this->generator = generator;
}
void CodeGeneratorWidget::show(DatabaseModel *model, OperationList *op_list)
{
doClearCode();
this->setEnabled(model!=nullptr && op_list!=nullptr);
this->op_list = op_list;
this->model = model;
QDialog::show();
}
void CodeGeneratorWidget::doClearCode(void)
{
code_txt->setPlainText(QString("Ready.."));
}
void CodeGeneratorWidget::doGenerateCode(void)
{
std::map< std::string, std::string > files_to_generate;
std::map< std::string, std::string >::iterator it;
try
{
if(!op_list->isOperationChainStarted())
op_list->startOperationChain();
this->generator->generateCode(*model, *this, files_to_generate);
for(it = files_to_generate.begin(); it != files_to_generate.end(); ++it)
{
std::ofstream out_file("/tmp/" + it->first);
out_file << it->second;
out_file.close();
}
op_list->finishOperationChain();
}
catch(Exception &e)
{
if(op_list->isOperationChainStarted())
op_list->finishOperationChain();
op_list->undoOperation();
op_list->removeLastOperation();
throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
}
}
void CodeGeneratorWidget::log(std::string text)
{
code_txt->setPlainText(QString::fromStdString(text));
}
| campisano/pgmodeler | plugins/code_generator/src/code_generator_widget.cpp | C++ | gpl-3.0 | 2,090 |
/**
* -----------------------------------------------------------------------------
* @package smartVISU
* @author Martin Gleiß
* @copyright 2012 - 2015
* @license GPL [http://www.gnu.de]
* -----------------------------------------------------------------------------
*/
/**
* Class for controlling all communication with a connected system. There are
* simple I/O functions, and complex functions for real-time values.
*/
var io = {
// the adress
adress: '',
// the port
port: '',
// -----------------------------------------------------------------------------
// P U B L I C F U N C T I O N S
// -----------------------------------------------------------------------------
/**
* Does a read-request and adds the result to the buffer
*
* @param the item
*/
read: function (item) {
},
/**
* Does a write-request with a value
*
* @param the item
* @param the value
*/
write: function (item, val) {
io.send({'cmd': 'item', 'id': item, 'val': val});
widget.update(item, val);
},
/**
* Trigger a logic
*
* @param the logic
* @param the value
*/
trigger: function (name, val) {
io.send({'cmd': 'logic', 'name': name, 'val': val});
},
/**
* Initializion of the driver
*
* @param the ip or url to the system (optional)
* @param the port on which the connection should be made (optional)
*/
init: function (address, port) {
io.address = address;
io.port = port;
io.open();
},
/**
* Lets the driver work
*/
run: function (realtime) {
// old items
widget.refresh();
// new items
io.monitor();
},
// -----------------------------------------------------------------------------
// C O M M U N I C A T I O N F U N C T I O N S
// -----------------------------------------------------------------------------
// The functions in this paragraph may be changed. They are all private and are
// only be called from the public functions above. You may add or delete some
// to fit your requirements and your connected system.
/**
* This driver version
*/
version: 3,
/**
* This driver uses a websocket
*/
socket: false,
/**
* Opens the connection and add some handlers
*/
open: function () {
io.socket = new WebSocket('ws://' + io.address + ':' + io.port + '/');
io.socket.onopen = function () {
io.send({'cmd': 'proto', 'ver': io.version});
io.monitor();
};
io.socket.onmessage = function (event) {
var item, val;
var data = JSON.parse(event.data);
// DEBUG:
console.log("[io.smarthome.py] receiving data: ", event.data);
switch (data.cmd) {
case 'item':
for (var i = 0; i < data.items.length; i++) {
item = data.items[i][0];
val = data.items[i][1];
/* not supported:
if (data.items[i].length > 2) {
data.p[i][2] options for visu
};
*/
// convert binary
if (val === false) {
val = 0;
}
if (val === true) {
val = 1;
}
widget.update(item, val);
}
break;
case 'series':
data.sid = data.sid.substr(0, data.sid.length);
widget.update(data.sid.replace(/\|/g, '\.'), data.series);
break;
case 'dialog':
notify.info(data.header, data.content);
break;
case 'log':
if (data.init) {
widget.update(data.name, data.log);
}
else {
var log = widget.get(data.name); // only a reference
for (var i = 0; i < data.log.length; i++) {
log.unshift(data.log[i]);
if (log.length >= 50) {
log.pop();
}
}
widget.update(data.name);
}
break;
case 'proto':
var proto = parseInt(data.ver);
if (proto != io.version) {
notify.warning('Driver: smarthome.py', 'Protocol mismatch<br />smartVISU driver is: v' + io.version + '<br />SmartHome.py is: v' + proto + '<br /><br /> Update the system!');
}
break;
case 'url':
$.mobile.changePage(data.url);
break;
}
};
io.socket.onerror = function (error) {
notify.error('Driver: smarthome.py', 'Could not connect to smarthome.py server!<br /> Websocket error ' + error.data + '.');
};
io.socket.onclose = function () {
notify.debug('Driver: smarthome.py', 'Connection closed to smarthome.py server!');
};
},
/**
* Sends data to the connected system
*/
send: function (data) {
if (io.socket.readyState == 1) {
io.socket.send(unescape(encodeURIComponent(JSON.stringify(data))));
// DEBUG:
console.log('[io.smarthome.py] sending data: ', JSON.stringify(data));
}
},
/**
* Monitors the items
*/
monitor: function () {
if (widget.listeners().length) {
// items
io.send({'cmd': 'monitor', 'items': widget.listeners()});
}
// plot (avg, min, max, on)
var unique = Array();
widget.plot().each(function (idx) {
var items = widget.explode($(this).attr('data-item'));
for (var i = 0; i < items.length; i++) {
var pt = items[i].split('.');
if (!unique[items[i]] && !widget.get(items[i]) && (pt instanceof Array) && widget.checkseries(items[i])) {
var item = items[i].substr(0, items[i].length - 4 - pt[pt.length - 4].length - pt[pt.length - 3].length - pt[pt.length - 2].length - pt[pt.length - 1].length);
io.send({'cmd': 'series', 'item': item, 'series': pt[pt.length - 4], 'start': pt[pt.length - 3], 'count': pt[pt.length - 1]});
unique[items[i]] = 1;
}
}
});
// log
widget.log().each(function (idx) {
io.send({'cmd': 'log', 'name': $(this).attr('data-item'), 'max': $(this).attr('data-count')});
});
},
/**
* Closes the connection
*/
close: function () {
console.log("[io.smarthome.py] close connection");
if (io.socket.readyState > 0) {
io.socket.close();
}
io.socket = null;
}
};
| lbernau/smartVISU-deprecated | driver/io_smarthome.py.js | JavaScript | gpl-3.0 | 5,820 |
/*
Copyright 2012 James Edwards
This file is part of Jhrome.
Jhrome is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Jhrome is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Jhrome. If not, see <http://www.gnu.org/licenses/>.
*/
package com.newgroup.tabs.event;
import com.newgroup.tabs.Tab;
import javax.swing.JTabbedPane;
public class TabAddedEvent extends TabbedPaneEvent
{
public TabAddedEvent( JTabbedPane tabbedPane , long timestamp , Tab addedTab , int insertIndex )
{
super( tabbedPane , timestamp );
this.addedTab = addedTab;
this.insertIndex = insertIndex;
}
public final Tab addedTab;
public final int insertIndex;
public Tab getAddedTab( )
{
return addedTab;
}
public int getInsertIndex( )
{
return insertIndex;
}
@Override
public String toString( )
{
return String.format( "%s[tabbedPane: %s, timestamp: %d, addedTab: %s, insertIndex: %d]" , getClass( ).getName( ) , tabbedPane , timestamp , addedTab , insertIndex );
}
}
| DJVUpp/Desktop | djuvpp-djvureader-_linux-f9cd57d25c2f/DjVuReader++/src/com/newgroup/tabs/event/TabAddedEvent.java | Java | gpl-3.0 | 1,427 |
# -*- coding: utf-8 -*-
#
# 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.
import json
import os
import re
import sys
THIS_DIR = os.path.abspath('.')
BASE_DIR = os.path.abspath('..')
# 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.
sys.path.insert(0, BASE_DIR)
bower_metadata = json.load(open(os.path.join(BASE_DIR, 'bower.json')))
npm_metadata = json.load(open(os.path.join(BASE_DIR, 'package.json')))
def setup(app):
app.add_config_value('readthedocs', False, True)
readthedocs = os.environ.get('READTHEDOCS') == 'True'
if readthedocs:
os.environ['GMUSICPROCURATOR_SETTINGS'] = 'default_settings.py'
# -- General configuration ----------------------------------------------------
AUTHORS = u', '.join(bower_metadata['authors'])
TITLE = u'GMusicProcurator'
LONG_TITLE = u'{0} Documentation'.format(TITLE)
SUMMARY = bower_metadata['description']
SHORT_COPYRIGHT = u'2014, {0}. Some Rights Reserved.'.format(AUTHORS)
COPYRIGHT = u'''{0}
This work is licensed under a
Creative Commons Attribution-ShareAlike 4.0
International License'''.format(SHORT_COPYRIGHT)
# 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.coverage',
'sphinx.ext.ifconfig',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode',
'sphinxcontrib.autohttp.flask',
]
if not readthedocs:
extensions += [
'sphinxcontrib.coffeedomain',
]
try:
import rst2pdf
except ImportError:
rst2pdf = None
if rst2pdf:
extensions.append('rst2pdf.pdfbuilder')
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = TITLE
copyright = COPYRIGHT
# 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 = re.match(r'\d+\.\d+', npm_metadata['version']).group(0)
# The full version, including alpha/beta/rc tags.
release = npm_metadata['version']
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
if readthedocs:
exclude_patterns += [
'coffeescript.rst',
]
# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = False
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
show_authors = True
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# intersphinx extension
intersphinx_mapping = {
'py': ('http://docs.python.org/2.7/', None)
}
mdn_inv = os.path.join(THIS_DIR, 'mdn-js-objects.inv')
bb_inv = os.path.join(THIS_DIR, 'backbone.inv')
if not readthedocs:
if os.path.exists(mdn_inv):
mdn = 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/'
intersphinx_mapping['js'] = (mdn, mdn_inv)
if os.path.exists(bb_inv):
intersphinx_mapping['backbone'] = ('http://backbonejs.org/', bb_inv)
# coffeedomain extension
coffee_src_dir = os.path.join(BASE_DIR, 'gmusicprocurator', 'static', 'cs')
# -- 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 = 'default'
# 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 themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# 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']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
'**': [
'localtoc.html',
'relations.html',
'sourcelink.html',
'searchbox.html',
'copyright_sidebar.html',
],
}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'GMusicProcuratordoc'
# -- 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': '',
}
# 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 = [
('index', 'GMusicProcurator.tex', LONG_TITLE, AUTHORS, 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'gmusicprocurator', LONG_TITLE, [AUTHORS], 1)
]
# If true, show URL addresses after external links.
# man_show_urls = False
# -- 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 = [
('index', 'GMusicProcurator', LONG_TITLE, AUTHORS,
'GMusicProcurator', SUMMARY, 'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False
# -- Options for Epub output ----------------------------------------------
# Bibliographic Dublin Core info.
epub_title = TITLE
epub_author = AUTHORS
epub_publisher = AUTHORS
epub_copyright = COPYRIGHT
# The basename for the epub file. It defaults to the project name.
# epub_basename = TITLE
# The HTML theme for the epub output. Since the default themes are not
# optimized for small screen space, using the same theme for HTML and epub
# output is usually not wise. This defaults to 'epub', a theme designed to
# save visual space.
# epub_theme = 'epub'
# The language of the text. It defaults to the language option
# or en if the language is not set.
# epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
# epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
# epub_identifier = ''
# A unique identification for the text.
# epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
# epub_cover = ()
# A sequence of (type, uri, title) tuples for the guide element of content.opf.
# epub_guide = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
# epub_pre_files = []
# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
# epub_post_files = []
# A list of files that should not be packed into the epub file.
# epub_exclude_files = []
# The depth of the table of contents in toc.ncx.
# epub_tocdepth = 3
# Allow duplicate toc entries.
# epub_tocdup = True
# Choose between 'default' and 'includehidden'.
# epub_tocscope = 'default'
# Fix unsupported image types using the PIL.
# epub_fix_images = False
# Scale large images.
# epub_max_image_width = 0
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# epub_show_urls = 'inline'
# If false, no index is generated.
# epub_use_index = True
# -- Options for PDF output --------------------------------------------------
pdf_documents = [
('index', u'gmusicprocurator', TITLE, AUTHORS),
]
| malept/gmusicprocurator | docs/conf.py | Python | gpl-3.0 | 12,282 |
#!python3
import os
import sys
import fnmatch
import re
import shutil
import subprocess
PYTEST = "pytest"
FLAKE8 = "flake8"
BLACK = "black"
BLACK_FLAGS = ["-l", "79"]
PYGETTEXT = os.path.join(sys.base_prefix, "tools", "i18n", "pygettext.py")
INCLUDE_PATTERNS = {"*.py"}
EXCLUDE_PATTERNS = {
"build/*",
"docs/*",
"mu/contrib/*",
"mu/modes/api/*",
"utils/*",
}
_exported = {}
def _walk(
start_from=".", include_patterns=None, exclude_patterns=None, recurse=True
):
if include_patterns:
_include_patterns = set(os.path.normpath(p) for p in include_patterns)
else:
_include_patterns = set()
if exclude_patterns:
_exclude_patterns = set(os.path.normpath(p) for p in exclude_patterns)
else:
_exclude_patterns = set()
for dirpath, dirnames, filenames in os.walk(start_from):
for filename in filenames:
filepath = os.path.normpath(os.path.join(dirpath, filename))
if not any(
fnmatch.fnmatch(filepath, pattern)
for pattern in _include_patterns
):
continue
if any(
fnmatch.fnmatch(filepath, pattern)
for pattern in _exclude_patterns
):
continue
yield filepath
if not recurse:
break
def _rmtree(dirpath, cascade_errors=False):
try:
shutil.rmtree(dirpath)
except OSError:
if cascade_errors:
raise
def _rmfiles(start_from, pattern):
"""Remove files from a directory and its descendants
Starting from `start_from` directory and working downwards,
remove all files which match `pattern`, eg *.pyc
"""
for filepath in _walk(start_from, {pattern}):
os.remove(filepath)
def export(function):
"""Decorator to tag certain functions as exported, meaning
that they show up as a command, with arguments, when this
file is run.
"""
_exported[function.__name__] = function
return function
@export
def test(*pytest_args):
"""Run the test suite
Call py.test to run the test suite with additional args.
The subprocess runner will raise an exception if py.test exits
with a failure value. This forces things to stop if tests fail.
"""
print("\ntest")
os.environ["LANG"] = "en_GB.utf8"
return subprocess.run(
[sys.executable, "-m", PYTEST] + list(pytest_args)
).returncode
@export
def coverage():
"""View a report on test coverage
Call py.test with coverage turned on
"""
print("\ncoverage")
os.environ["LANG"] = "en_GB.utf8"
return subprocess.run(
[
sys.executable,
"-m",
PYTEST,
"-v",
"--cov-config",
".coveragerc",
"--cov-report",
"term-missing",
"--cov=mu",
"tests/",
]
).returncode
@export
def flake8(*flake8_args):
"""Run the flake8 code checker
Call flake8 on all files as specified by setup.cfg
"""
print("\nflake8")
os.environ["PYFLAKES_BUILTINS"] = "_"
return subprocess.run([sys.executable, "-m", FLAKE8]).returncode
@export
def tidy():
"""Tidy code with the 'black' formatter."""
clean()
print("\nTidy")
for target in [
"setup.py",
"make.py",
"mu",
"package",
"tests",
"utils",
]:
return_code = subprocess.run(
[sys.executable, "-m", BLACK, target] + BLACK_FLAGS
).returncode
if return_code != 0:
return return_code
return 0
@export
def black():
"""Check code with the 'black' formatter."""
clean()
print("\nblack")
# Black is no available in Python 3.5, in that case let the tests continue
try:
import black as black_ # noqa: F401
except ImportError as e:
python_version = sys.version_info
if python_version.major == 3 and python_version.minor == 5:
print("Black checks are not available in Python 3.5.")
return 0
else:
print(e)
return 1
for target in [
"setup.py",
"make.py",
"mu",
"package",
"tests",
"utils",
]:
return_code = subprocess.run(
[sys.executable, "-m", BLACK, target, "--check"] + BLACK_FLAGS
).returncode
if return_code != 0:
return return_code
return 0
@export
def check():
"""Run all the checkers and tests"""
print("\nCheck")
funcs = [clean, black, flake8, coverage]
for func in funcs:
return_code = func()
if return_code != 0:
return return_code
return 0
@export
def clean():
"""Reset the project and remove auto-generated assets"""
print("\nClean")
_rmtree("build")
_rmtree("dist")
_rmtree(".eggs")
_rmtree("docs/_build")
_rmtree(".pytest_cache")
_rmtree("lib")
_rmtree(".git/avatar/") # Created with `make video`
_rmtree("venv-pup") # Created wth `make macos/win64`
# TODO: recursive __pycache__ directories
_rmfiles(".", ".coverage")
_rmfiles(".", "*.egg-info")
_rmfiles(".", "*.mp4") # Created with `make video`
_rmfiles(".", "*.pyc")
_rmfiles("mu/locale", "*.pot")
_rmfiles("mu/wheels", "*.zip")
return 0
def _translate_lang(lang):
"""Returns `value` from `lang` expected to be like 'LANG=value'."""
match = re.search(r"^LANG=(.*)$", lang)
if not match:
raise RuntimeError("Need LANG=xx_XX argument.")
value = match.group(1)
if not value:
raise RuntimeError("Need LANG=xx_XX argument.")
return value
_MU_LOCALE_DIRNAME = os.path.join("mu", "locale")
_MESSAGES_POT_FILENAME = os.path.join(_MU_LOCALE_DIRNAME, "messages.pot")
@export
def translate_begin(lang=""):
"""Create/update a mu.po file for translation."""
lang = _translate_lang(lang)
result = _translate_extract()
if result != 0:
raise RuntimeError("Failed creating the messages catalog file.")
mu_po_filename = os.path.join(
_MU_LOCALE_DIRNAME,
lang,
"LC_MESSAGES",
"mu.po",
)
update = os.path.exists(mu_po_filename)
cmd = [
"pybabel",
"update" if update else "init",
"-i",
_MESSAGES_POT_FILENAME,
"-o",
mu_po_filename,
"--locale={locale}".format(locale=lang),
]
result = subprocess.run(cmd).returncode
print(
"{action} {mu_po_filename}.".format(
action="Updated" if update else "Created",
mu_po_filename=repr(mu_po_filename),
)
)
print(
"Review its translation strings "
"and finalize with 'make translate_done'."
)
return result
_TRANSLATE_IGNORE_DIRNAMES = {
os.path.join("mu", "modes", "api"),
os.path.join("mu", "contrib"),
}
def _translate_ignore(dirname):
"""Return True if `dirname` files should be excluded from translation."""
return any(dirname.startswith(dn) for dn in _TRANSLATE_IGNORE_DIRNAMES)
def _translate_filenames():
"""Returns a sorted list of filenames with translatable strings."""
py_filenames = []
for dirname, _, filenames in os.walk("mu"):
if _translate_ignore(dirname):
continue
py_filenames.extend(
os.path.join(dirname, fn) for fn in filenames if fn.endswith(".py")
)
return sorted(py_filenames)
def _translate_extract():
"""Creates the message catalog template messages.pot file."""
cmd = [
"pybabel",
"extract",
"-o",
_MESSAGES_POT_FILENAME,
*_translate_filenames(),
]
return subprocess.run(cmd).returncode
@export
def translate_done(lang=""):
"""Compile translation strings in mu.po to mu.mo file."""
lang = _translate_lang(lang)
lc_messages_dirname = os.path.join(
_MU_LOCALE_DIRNAME,
lang,
"LC_MESSAGES",
)
mu_po_filename = os.path.join(lc_messages_dirname, "mu.po")
mu_mo_filename = os.path.join(lc_messages_dirname, "mu.mo")
cmd = [
"pybabel",
"compile",
"-i",
mu_po_filename,
"-o",
mu_mo_filename,
"--locale={locale}".format(locale=lang),
]
return subprocess.run(cmd).returncode
@export
def translate_test(lang=""):
"""Run translate_done and lauch Mu in the given LANG."""
result = translate_done(lang)
if result != 0:
raise RuntimeError("Failed compiling the mu.po file.")
local_env = dict(os.environ)
local_env["LANG"] = _translate_lang(lang)
return subprocess.run(
[sys.executable, "-m", "mu"], env=local_env
).returncode
@export
def run():
"""Run Mu from within a virtual environment"""
clean()
if not os.environ.get("VIRTUAL_ENV"):
raise RuntimeError(
"Cannot run Mu;" "your Python virtualenv is not activated"
)
return subprocess.run([sys.executable, "-m", "mu"]).returncode
@export
def dist():
"""Generate a source distribution and a binary wheel"""
if check() != 0:
raise RuntimeError("Check failed")
print("Checks pass; good to package")
return subprocess.run(
[sys.executable, "setup.py", "sdist", "bdist_wheel"]
).returncode
@export
def publish_test():
"""Upload to a test PyPI"""
dist()
print("Packaging complete; upload to PyPI")
return subprocess.run(
[
sys.executable,
"-m",
"twine",
"upload",
"-r",
"test",
"--sign",
"dist/*",
]
).returncode
@export
def publish_live():
"""Upload to PyPI"""
dist()
print("Packaging complete; upload to PyPI")
return subprocess.run(
[sys.executable, "-m", "twine", "upload", "--sign", "dist/*"]
).returncode
_PUP_PBS_URLs = {
32: "https://github.com/indygreg/python-build-standalone/releases/download/20200822/cpython-3.7.9-i686-pc-windows-msvc-shared-pgo-20200823T0159.tar.zst", # noqa: E501
64: None,
}
def _build_windows_msi(bitness=64):
"""Build Windows MSI installer"""
try:
pup_pbs_url = _PUP_PBS_URLs[bitness]
except KeyError:
raise ValueError("bitness") from None
if check() != 0:
raise RuntimeError("Check failed")
print("Fetching wheels")
subprocess.check_call([sys.executable, "-m", "mu.wheels"])
print("Building {}-bit Windows installer".format(bitness))
if pup_pbs_url:
os.environ["PUP_PBS_URL"] = pup_pbs_url
cmd_sequence = (
[sys.executable, "-m", "virtualenv", "venv-pup"],
["./venv-pup/Scripts/pip.exe", "install", "pup"],
[
"./venv-pup/Scripts/pup.exe",
"package",
"--launch-module=mu",
"--nice-name=Mu Editor",
"--icon-path=./package/icons/win_icon.ico",
"--license-path=./LICENSE",
".",
],
["cmd.exe", "/c", "dir", r".\dist"],
)
try:
for cmd in cmd_sequence:
print("Running:", " ".join(cmd))
subprocess.check_call(cmd)
finally:
shutil.rmtree("./venv-pup", ignore_errors=True)
@export
def win32():
"""Build 32-bit Windows installer"""
_build_windows_msi(bitness=32)
@export
def win64():
"""Build 64-bit Windows installer"""
_build_windows_msi(bitness=64)
@export
def docs():
"""Build the docs"""
cwd = os.getcwd()
os.chdir("docs")
if os.name == "nt":
cmds = ["cmd", "/c", "make.bat", "html"]
else:
cmds = ["make", "html"]
try:
return subprocess.run(cmds).returncode
except Exception:
return 1
finally:
os.chdir(cwd)
@export
def help():
"""Display all commands with their description in alphabetical order"""
module_doc = sys.modules["__main__"].__doc__ or "check"
print(module_doc + "\n" + "=" * len(module_doc) + "\n")
for command, function in sorted(_exported.items()):
doc = function.__doc__
if doc:
first_line = doc.splitlines()[0]
else:
first_line = ""
print("make {} - {}".format(command, first_line))
def main(command="help", *args):
"""Dispatch on command name, passing all remaining parameters to the
module-level function.
"""
try:
function = _exported[command]
except KeyError:
raise RuntimeError("No such command: %s" % command)
else:
return function(*args)
if __name__ == "__main__":
sys.exit(main(*sys.argv[1:]))
| mu-editor/mu | make.py | Python | gpl-3.0 | 12,681 |
<?php
// declare(encoding='UTF-8');
/**
* Classe Registre, qui permet un accès à différentes variables et paramètres à travers les autres classes.
* C'est un remplaçant à la variable magique $_GLOBALS de Php.
* C'est un singleton.
* Si vous voulez paramètré votre application via un fichier de configuration, utilisez plutôt la classe @see Config.
*
* @category php 5.2
* @package Framework
* @author Jean-Pascal MILCENT <jmp@tela-botanica.org>
* @copyright Copyright (c) 2009, Tela Botanica (accueil@tela-botanica.org)
* @license http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt Licence CECILL
* @license http://www.gnu.org/licenses/gpl.html Licence GNU-GPL
* @version $Id: Registre.php 301 2011-01-18 14:23:52Z jpm $
* @link /doc/framework/
*
*/
class Registre {
/** Tableau associatif stockant les variables. */
private static $stockage = array();
/**
* Ajoute un objet au tableau selon un intitulé donné.
* @param string l'intitulé sous lequel l'objet sera conservé
* @param mixed l'objet à conserver
*/
public static function set($intitule, $objet) {
if (is_array($objet) && isset(self::$stockage[$intitule])) {
self::$stockage[$intitule] = array_merge((array) self::$stockage[$intitule], (array) $objet);
$message = "Le tableau $intitule présent dans le registre a été fusionné avec un nouveau tableau de même intitulé !";
trigger_error($message, E_USER_WARNING);
} else {
self::$stockage[$intitule] = $objet;
}
}
/**
* Renvoie le contenu associé à l'intitulé donné en paramètre.
* @return mixed l'objet associé à l'intitulé ou null s'il n'est pas présent
*/
public static function get($intitule) {
$retour = (isset(self::$stockage[$intitule])) ? self::$stockage[$intitule] : null;
return $retour;
}
/**
* Détruit l'objet associé à l'intitulé, n'a pas d'effet si il n'y a pas d'objet associé.
* @param string l'intitulé de l'entrée du registre à détruire.
*/
public static function detruire($intitule) {
if (isset(self::$stockage[$intitule])) {
unset(self::$stockage[$intitule]);
}
}
/**
* Teste si le registre contient une donnée pour un intitulé d'entrée donné.
* @param string l'intitulé de l'entrée du registre à tester.
* @return boolean true si un objet associé à cet intitulé est présent, false sinon
*/
public static function existe($intitule) {
$retour = (isset(self::$stockage[$intitule])) ? true : false;
return $retour;
}
}
?> | jpmilcent/depim | server/framework/Registre.php | PHP | gpl-3.0 | 2,499 |
{
aboutMessage: "Über ProjecQtOr …",
aboutMessageLocale: "Lokal",
aboutMessageWebsite: "Webseite",
AccessProfile: "Zugriffsprofile",
accessProfileGlobalCreator: "Ersteller+",
accessProfileGlobalManager: "Manager+",
accessProfileGlobalReader: "Leser+",
accessProfileGlobalUpdater: "Änderer+",
accessProfileNoAccess: "Kein Zugriff",
accessProfileRestrictedCreator: "Ersteller",
accessProfileRestrictedManager: "Manager",
accessProfileRestrictedReader: "Leser",
accessProfileRestrictedUpdater: "Änderer",
accessReadOwnOnly: "Leser eigene",
accessScopeAll: "Alle Elemente aller Projekte",
accessScopeNo: "Kein Elemente",
accessScopeOwn: "Eigene Elemente",
accessScopeProject: "Elemente eigener Projekte",
accessScopeResp: "Elemente für die er verantwortlich ist",
Action: "Aktion",
ActionType: "Aktionstyp",
activeConnections: "Aktiver Status",
Activity: "Aktivität",
ActivityPrice: "Preis der Aktivität",
ActivityType: "Aktivitätstyp",
actualDueDate: "Berücksichtige anfängliches Endedatum",
actualDueDateTime: "Berücksichtige anfängliches Endedatum/-zeit",
addAffectation: "neue Zuordnung hinzufügen",
addApprover: "Genehmiger hinzufügen",
addAssignment: "Zuordnung hinzufügen",
addAttachement: "Anhang hinzufügen",
addDependency: "Abhängigkeit hinzufügen",
addDependencyPredecessor: "Vorgänger hinzufügen",
addDependencySuccessor: "Nachfolger hinzufügen",
addDocumentVersion: "neue Version hinzufügen",
addExpenseDetail: "Aufwandsdetail hinzufügen",
addFilterClause: "Filterkriterium hinzufügen",
addFilterClauseTitle: "Filterregel hinzufügen",
addHyperlink: "Hyperlink für Datei oder Web-Seite hinzufügen",
addLine: "Zeile hinzufügen",
addLink: "Elementverknüpfung hinzufügen",
addNote: "Notiz hinzufügen",
addOrigin: "Ursprung hinzufügen",
addPhoto: "Foto hinzufügen",
addResourceCost: "Ressourcekosten hinzufügen",
addTestCaseRun: "Testfall zu Testplan hinzufügen",
addVersionProject: "Verbindung zwischen Version und Projekt",
adminCronCheckDates: "Verzögerung für die Erzeugung von Alarmen = ${1} Sekunden",
adminCronCheckEmails: "Emails Eingang Verzögerung = ${1} Sekunden",
adminCronCheckImport: "Verzögerungen von automatischen Importen = ${1} Sekunden",
adminCronSleepTime: "Generelle Cron Ruhezeit = ${1} Sekunden",
advancedFilter: "Erweiterer Filter",
Affectation: "Ressourcenzuordnung",
affectTeamMembers: "Team zuweisen auf Projekt ",
after: "dahinter",
Alert: "Alarm",
ALERT: "Alarm",
alertChooseOneAtLeast: "Mindestens ein Element wählen",
alertCronStatus: "Alarm Erstellung",
alertInvalidForm: "Einige Felder enthalten ungültige Daten. <br/>Bitte erst korrigieren.",
alertNoNewAssignment: "Keine Zuordnung auf ungenutztes Element möglich.",
alertOngoingChange: "Aktuelle Änderungen nicht gesichert.<br/>Bitte vorher sichern oder abbrechen.",
alertOngoingQuery: "Abfrage läuft<br/>Bitte warten",
alertQuitOngoingChange: "Aktuelle Änderungen nicht gesichert.\nWollen Sie wirklich ProjecQtOr beenden?",
alertValue: "Alarm Wert",
all: "Alle",
allProjects: "Alle Projekte",
allUsers: "Alle Nutzer",
alsoDeleteAttachement: "ACHTUNG, diese Aktion wird auch die ${1} verbundene(n) Anhangdatei(en) löschen.",
always: "immer",
amongst: "über",
Anomaly: "Störung",
anyChange: "beliebige Änderung",
applicationStatus: "Status der Applikation ",
applicationStatusClosed: "geschlossen",
applicationStatusOpen: "offen",
applicationTitle: "ProjeQtOr",
approved: "genehmigt",
approveNow: "jetzt genehmigen",
approver: "Genehmiger",
Approver: "Genehmiger",
April: "April",
Assignment: "Zuordnung",
assignmentAdd: "Zuordnung hinzufügt",
assignmentChange: "Zuordnung geändert",
assignmentEditRight: "Zuweisungen bearbeiten",
assignmentViewRight: "Zuweisungen anzeigen",
Attachement: "Anhang",
attachmentAdd: "Anhänge hinzufügen",
attributeNotSelected: "Werte nicht gewählt",
Audit: "Verbindung",
August: "August",
before: "davor",
bigExportQuestion: "Der Export hat ${1} Zeilen. Weitermachen?",
Bill: "Rechnung",
billingTypeE: "gemäß Konditionen",
billingTypeM: "manuelle Rechnungsstellung",
billingTypeN: "nicht abgerechnet",
billingTypeP: "nach gedeckelter Produktionszeit",
billingTypeR: "nach erstellter Arbeit",
BillLine: "Rechnungszeilen",
BillType: "Rechnungstyp",
blocked: "gesperrt",
blockedTestCaseRun: "Testfall als gesperrt markieren",
Browser: "Navigator",
buttonBrowse: "Suchen …",
buttonCancel: "Abbruch",
buttonChangePassword: "Passwort ändern",
buttonClear: "Löschen",
buttonCollapse: "Zuklappen aller Gruppen",
buttonCopy: "Kopiere den aktuellen ${1}",
buttonDefault: "Standardwert",
buttonDelete: "Lösche den aktuellen ${1}",
buttonDeleteMultiple: "Lösche alle gewählten Elemente",
buttonExpand: "Aufklappen aller Gruppen",
buttonHideList: "Liste ausblenden",
buttonHideMenu: "Menü ausblenden",
buttonImportData: "Datenimport",
buttonMail: "Email Details von ${1}",
buttonMultiUpdate: "Mehrfachaktualisierung",
buttonNew: "Erstelle neu ${1}",
buttonNo: "Nein",
buttonOK: "OK",
buttonPlan: "Berechne geplante Aktivitäten",
buttonPrint: "Drucke den aktuellen ${1}",
buttonQuitMultiple: "Mehrfachaktualisierung verlassen",
buttonRedoItem: "Gehe vorwärts",
buttonRefresh: "Anzeige des aktuellen ${1} erneuern",
buttonRefreshList: "Liste aktualisieren",
buttonReset: "Rücksetzen",
buttonSave: "Sichern der Änderung des aktuellen ${1} ([CTRL]+S)",
buttonSaveImputation: "Sichern der Arbeitsauftrag ${1}",
buttonSaveMultiple: "Mehrfachaktualisierung sichern",
buttonSaveParameter: "Sichern der Parameter",
buttonSaveParameters: "Sichern Parameter",
buttonSelectAll: "Alle Elemente auswahlen",
buttonSelectFiles: "Wähle Dateien …",
buttonShowList: "Liste anzeigen",
buttonShowMenu: "Menü anzeigen",
buttonStandardMode: "Modus Standardanzeige",
buttonSwitchedMode: "Modus Umschaltanzeige",
buttonUndo: "Änderung rückgängig machen für aktuellen ${1}",
buttonUndoImputation: "Änderung rückgängig machen für Arbeitsauftrag ${1}",
buttonUndoItem: "Gehe zurück",
buttonUnselectAll: "Alle Auswahlen aufheben",
buttonYes: "Ja",
byte: "Byte",
byteLetter: "B",
Calendar: "Kalender",
CalendarDefinition: "Kalender",
cancelled: "abgebrochen",
cannotDeleteBilledTerm: "abgerechnete B",
cannotGoto: "Kann nicht zu diesem Element gehen<br/>Bitte wählen Sie erst aus der ersten Liste auswählen.",
changeActualDueDate: "Ändere geplantes Endedatum zu",
changeActualDueDateTime: "Ändere aktuelles Endedatum/ -zeit zu",
changeActualEndDate: "Ändere aktuelles Endedatum zu",
changeInitialDueDate: "Ändere ursprüngl. Endedatum zu",
changeInitialDueDateTime: "Ändere ursprüngl. Endedatum/ -zeit zu",
changeInitialEndDate: "Ändere ursprüngl. Endedatum zu",
changePlanningMode: "Ändere Planungsmodus zu",
changeValidatedEndDate: "Ändere bestätigtes Endedatum zu",
changeValidatedStartDate: "Ändere bestätigtes Startdatum zu",
checkAsList: "Wähle Spalten für Anzeige",
Checklist: "Checkliste",
checklistAccess: "Zugriff auf Checklisten",
ChecklistDefinition: "Checkliste",
ChecklistDefinitionLine: "Checklistenzeilen",
checkUncheckAll: "wählen / abwählen",
chooseColumnExport: "Wähle Spalten für Export",
chronological: "zeitlich",
Client: "Kunde",
ClientType: "Kundentyp",
close: "Schließen",
closeAlerts: "Schließe Alarme",
closed: "abgeschlossen",
closedMessage: "Meldung wenn Applikation im Wartungsmodus / Offline.",
closedSinceMore: "schließe bei mehr als",
closeEmails: "Schließe Mails",
codDesignation: "Bezeichnung",
colAccountable: "abrechenbar",
colActionnee: "Akteur",
colActualDueDate: "Zieldatum geplant",
colActualDueDateTime: "Zieldatum aktuell",
colActualEndDate: "Endedatum geplant",
colAdd: "Änderung",
colAddAmount: "Änderung Betrag",
colAdditionalInfo: "zusätzl. Info",
colAddNote: "(öffentliche) Notiz hinzufügen",
colAddPricePerDayAmount: "Änderung Preis/Tag",
colAddress: "Adresse",
colAddToDescription: "Beschreibung hinzufügen",
colAddToResult: "Ergebnis hinzufügen",
colAddWork: "Änderung Arbeit",
colAlert: "Alarm",
colAlertDateTime: "Erinnerungsdatum",
colAlertInitialDateTime: "Erstelle Datum",
colAlertReadDateTime: "Lesedatum",
colAlertReceiver: "Empfänger des Alarms",
colAllowDuplicate: "erlaube Duplikat",
colAllowDuplicateTestInSession: "erlaube Testfall Duplikat in Testplan",
colAmount: "Betrag",
colApiKey: "API Schlüssel",
colAssigned: "zugewiesen",
colAssignedCost: "zugewiesene Kosten",
colAssignedWork: "zugewiesene Arbeit",
colAttendees: "Anwesende",
colBank: "Bank",
colBillable: "abrechenbar",
colBillContact: "Rechnung Vertrag",
colBillId: "Rechnungsnummer",
colBillingType: "Rechnungstyp",
colBrowser: "Browser",
colBrowserVersion: "Browserversion",
colCancelled: "abgebrochen",
colCapacity: "Kapazität",
colCategory: "Kategorie",
colCause: "Ursache",
colChangeIssuer: "Ändere ${1} zu",
colChangeProject: "Ändere ${1} zu",
colChangeRequestor: "Ändere ${1} zu",
colChangeResponsible: "Ändere ${1} zu",
colChangeStatus: "Ändere Status zu",
colChangeTargetVersion: "Ändere Zielversion zu",
colChangeType: "Ändere Type zu",
colChoice: "Auswahlmöglichkeit",
colChoices: "Auswahlmöglichkeiten",
colCity: "Stadt",
colClient: "Kunde",
colClientCode: "Kundencode",
colClientName: "Kundenname",
colClosureDate: "Abschlussdatum",
colClosureDateTime: "Abschlussdatum/-zeit",
colCode: "Code",
colColor: "Farbe",
colColumn: "Daten",
colComment: "Kommentare",
colCommissionCost: "Auftrag",
colCompanyNumber: "Firmennummer",
colComplement: "Zubehör",
colConnection: "Erster Zugriff",
colContactName: "Kontaktname",
colContractCode: "Vertragscode",
colContractor: "Hauptlieferant",
colCost: "Kosten",
colCountBlocked: "gesperrt",
colCountFailed: "fehlgeschlagen",
colCountIssues: "Problem",
colCountLinked: "verbunden",
colCountPassed: "erfolgreich",
colCountPlanned: "geplant",
colCountry: "Land ",
colCountTests: "Anzahl Testfälle",
colCountTotal: "gesamt",
colCreationDate: "Erstellungsdatum",
colCreationDateTime: "Erstellungsdatum/-zeit",
colCriticality: "Kritikalität",
colCriticalityShort: "Krit.",
colCurrentDocumentVersion: "letzte Version",
colDate: "Datum",
colDecisionAccountable: "verantwortlich",
colDecisionDate: "Entscheidungsdatum",
colDefaultType: "Standardtyp",
colDependencyDelay: "Verzug (zu spät)",
colDependencyDelayComment: "Tage zwischen Start Vorgänger und Nachfolger",
colDescription: "Beschreibung",
colDesignation: "Bezeichnung",
colDetail: "Detail",
colDisplayName: "Name anzeigen",
colDocumentReference: "Dokumentenreferenz",
colDone: "erledigt",
colDoneDate: "Erledigungsdatum",
colDoneDateTime: "Erledigungsdatum/-zeit",
colDontReceiveTeamMails: "Kein Empfang von Team Mails",
colDueDate: "Zieldatum",
colDuplicateTicket: "Doppeltes Ticket",
colDuration: "Dauer",
colEisDate: "geplanter Produktivbetrieb",
colElement: "Element",
colEmail: "Mail-Adresse",
colEnd: "Ende",
colEndDate: "Endedatum",
colEndTime: "Endezeit",
colEstimatedEffort: "geschätzer Aufwand",
colEstimatedWork: "Arbeit geschätzt",
colExclusive: "nur Einzelauswahl zulassen",
colExclusiveShort: "Einzel.",
colExpected: "erwarteter Fortschritt",
colExpectedProgress: "erwarteter Fortschritt",
colExpectedResult: "erwartetes Ergebnis",
colExpense: "Aufwand",
colExpenseAssignedAmount: "Aufwände zuweisen",
colExpenseLeftAmount: "verbleibende Aufwände",
colExpensePlannedAmount: "Plan-Aufwände",
colExpenseRealAmount: "Ist-Aufwände",
colExpenseValidatedAmount: "genehmigte Aufwände",
colExternalReference: "Externe Referenz",
colFax: "FAX",
colFile: "Datei",
colFilter: "Filter",
colFirstDay: "Erster Tag",
colFixPlanning: "Feste Planung",
colFormat: "Skala",
colFullAmount: "Gesamtbetrag",
colHandled: "bearbeitet",
colHandledDate: "bearbeitet am",
colHandledDateTime: "bearbeitet um",
colHyperlink: "Hyperlink",
colIbanBban: "Kontonummer (BBAN)",
colIbanCountry: "Land (IBAN)",
colIbanKey: "Schlüssel (IBAN)",
colIcon: "Icon",
colId: "ID",
colIdAccessScopeCreate: "Berechtigung 'Erstellen'",
colIdAccessScopeDelete: "Berechtigung 'Löschen'",
colIdAccessScopeRead: "Berechtigung 'Lesen'",
colIdAccessScopeUpdate: "Berechtigung 'Ändern'",
colIdActionType: "Aktionstyp",
colIdActivityPlanningMode: "Planungstyp",
colIdActivityPrice: "Aktivitätspreis",
colIdActivityType: "Aktivitätstyp",
colIdAuthor: "Author",
colIdBill: "Rechnung",
colIdBillType: "Rechnungstyp",
colIdCalendarDefinition: "Kalender",
colIdClient: "Kunde",
colIdClientType: "Kundentyp",
colIdCommandType: "Auftragstyp",
colIdContact: "Kontakt",
colIdContext: "Kontext",
colIdContext1: "Umfeld",
colIdContext2: "Betriebssystem",
colIdContext3: "Navigator",
colIdContextType: "Kontexttyp",
colIdCriticality: "Kritikalität",
colIdDecisionType: "Entscheidungstyp",
colIdDocumentDirectory: "Verzeichnis",
colIdEfficiency: "Effizienz",
colIdFeasibility: "Machbarkeit",
colIdHealth: "Projektstatus",
colIdIndicator: "Indikator",
colIdle: "abgeschlossen",
colIdleDate: "geschlossen am",
colIdleDateTime: "geschlossen um",
colIdLikelihood: "Wahrscheinlichkeit",
colIdLocker: "gesperrt durch",
colIdMailable: "Element geändert",
colIdMeetingType: "Besprechungstyp",
colIdMessageType: "Meldungstyp",
colIdMilestonePlanningMode: "Planungstyp",
colIdMilestoneType: "Meilensteintyp",
colIdOverallProgress: "Gesamtfortschritt",
colIdPeriodicity: "Häufigkeit",
colIdPlanningMode: "Planungsmodus",
colIdPriority: "Priorität",
colIdPrivacy: "Datenschutz",
colIdProduct: "Produkt",
colIdProfile: "Profile",
colIdProject: "Projekt",
colIdQuality: "Qualitätslevel",
colIdQuestionType: "Fragentyp",
colIdQuotationType: "Angebotstyp",
colIdRecipient: "Empfänger",
colIdReferencable: "Element",
colIdRequirement: "Übergeordnete Anforderung",
colIdRequirementType: "Typ",
colIdResource: "Ressource",
colIdRole: "Funktion",
colIdSeverity: "Auswirkung",
colIdSponsor: "Sponsor",
colIdStatus: "Status",
colIdTeam: "Team",
colIdTerm: "Bedingung",
colIdTestCase: "Übergeordneter Testfall",
colIdTestCaseType: "Typ",
colIdTestSession: "Testlauf",
colIdTestSessionPlanningMode: "Planungsmodus",
colIdTestSessionType: "Typ",
colIdTicketType: "Tickettyp",
colIdTrend: "Trend",
colIdUrgency: "Dringlichkeit",
colIdUser: "Benutzer",
colIdVersion: "Version",
colIdVersioningType: "Versionstyp",
colIdWorkflow: "Workflow",
colImpact: "Auswirkung",
colImportElementType: "Elementtyp für Import",
colImportFileType: "Dateiformat für Import",
colInitial: "anfänglich",
colInitialAmount: "Initial Betrag",
colInitialDueDate: "Zieldatum anfängl.",
colInitialDueDateTime: "Zieldatum anfängl.",
colInitialDuration: "Dauer anfängl.",
colInitialEisDate: "Start des Produktivbetriebs",
colInitialEndDate: "Enddatum anfängl.",
colInitialPricePerDayAmount: "Initial Preis/Tag",
colInitials: "Initialen",
colInitialStartDate: "Startdatum anfängl.",
colInitialWork: "Arbeit anfängl.",
colIsBilled: "angekündigt",
colIsContact: "ist ein Kontakt",
colIsEis: "ist im Produktivbetrieb",
colIsLdap: "kommt von LDAP",
colIsOffDay: "Abwesenheitstag",
colIsPeriodic: "periodisch",
colIsRef: "Referenz",
colIsResource: "ist eine Ressource",
colIsSubProductOf: "Unterprojekt von",
colIsSubProject: "Teilprojekt von",
colIssuer: "Aussteller",
colIssuerShort: "Ausst.",
colIsUser: "ist ein Benutzer",
colLastAccess: "Letzter Zugriff",
colLate: "zu spät",
colLatitude: "Breitengrad",
colLeft: "verbleibend",
colLeftCost: "verbleibende Kosten",
colLeftWork: "verbleibende Arbeit",
colLikelihood: "Wahrscheinlichkeit",
colLikelihoodShort: "%",
colLineCount: "Anzahl Zeilen",
colLineNumber: "Position",
colLink: "Link",
colLinkActivity: "verbundene Aktivität",
colListShowMilestone: "Meilensteine anzeigen",
colLocation: "Standort",
colLockCancelled: "Sperre abgebrochen",
colLockDone: "Sperre 'erledigt'",
colLocked: "gesperrt",
colLockedDate: "gesperrt seit",
colLockHandled: "Sperre 'bearbeitet'",
colLockIdle: "Sperre 'abgeschlossen'",
colLockTags: "Sperre 'Prüfungen'",
colLongitude: "Längengrad",
colMailBody: "Text des Mails",
colMailDateTime: "gesendet am",
colMailMessage: "Nachricht",
colMailStatus: "Sendestatus",
colMailTitle: "Titel des Mails",
colMailTo: "Empfänger",
colMailToAssigned: "Zugewiesene Ressource",
colMailToContact: "Antragsteller",
colMailToLeader: "Projektleiter",
colMailToManager: "Projektmanager",
colMailToOther: "andere",
colMailToProject: "Projektteam",
colMailToResource: "Verantwortlich",
colMailToUser: "Aussteller",
colMainRole: "Hauptfunktion",
colManager: "Manager",
colMandatoryDescription: "Beschreibung",
colMandatoryResourceOnHandled: "verantwortlich",
colMandatoryResultOnDone: "Ergebnis",
colMeetingDate: "Besprechungsdatum",
colMeetingEndTime: "Endezeit",
colMeetingStartTime: "Startzeit",
colMessage: "Meldung",
colMinutes: "Protokoll",
colMobile: "Handy",
colName: "Name",
colNameClient: "Kunde",
colNewStatus: "neuer Status",
colNextDocumentVersion: "neue Version",
colNote: "Notiz",
colNotPlannedWork: "[not planned work]",
colNoWork: "Keine Arbeit",
colNumBank: "Bankleitzahl",
colNumCompte: "Kontonummer",
colNumOffice: "Postfachnummer",
colNumTax: "Steuernummer",
colOfferValidityEndDate: "Gültigkeit des Angebots",
colOperation: "Vorgang",
colOpportunityImprovement: "Verbesserung erwartet",
colOpportunityImprovementShort: "Verbessg.",
colOpportunitySource: "Chancenquelle",
colOrContact: "oder Kontakt",
colOrigin: "Ursprung",
colOriginalVersion: "Ursprungsversion",
colOriginId: "Ursprungs-ID",
colOriginType: "Ursprungstyp",
colOrLink: "oder Link",
colOrNotSet: "oder nicht gesetzt",
colOrOtherEvent: "oder anderes Ereignis",
colOrProduct: "oder Product",
colOrUser: "oder Benutzer",
colOtherAttendees: "Weitere Anwesende",
colOtherVersions: "Andere Versionen",
colParameters: "Parameter",
colParentActivity: "übergeordnete Aktivität",
colParentDirectory: "Oberverzeichnis",
colParentTestSession: "Ursprungs-Session",
colPassword: "Passwort",
colPaymentDelay: "Zahlungsziel (in Tagen)",
colPct: "%",
colPeriod: "Zyklus",
colPeriodicityEndDate: "Endedatum",
colPeriodicityOpenDays: "Nur offene Tage",
colPeriodicityStartDate: "Startdatum",
colPeriodicityTimes: "Wiederholungen",
colPeriodicOccurence: "Wiederholung",
colPhone: "Telefon",
colPhoto: "Foto",
colPlanned: "geplant",
colPlannedAmount: "Plan-Betrag",
colPlannedAmount2: "Plan-Betrag",
colPlannedCost: "Plan-Kosten",
colPlannedDate: "Plan-Datum",
colPlannedDate2: "Plan-Datum",
colPlannedDueDate: "Plan-Zieldatum",
colPlannedDuration: "Plan-Dauer",
colPlannedEis: "Plan-Datum für Produktivbetrieb",
colPlannedEisDate: "Plan-Datum für Produktivbetrieb",
colPlannedEnd: "Plan-Endedatum",
colPlannedEndDate: "Plan-Endedatum",
colPlannedStartDate: "Plan-Startdatum",
colPlannedWork: "Plan-Arbeit",
colPlanning: "Planung",
colPlanningActivity: "Zugewiesene Aktivität",
colPlatform: "Plattform",
colPredefinedNote: "vordefinierte Notiz",
colPrerequisite: "Voraussetzung",
colPreviousStartDate: "Vorheriges Startdatum",
colPrice: "Preis",
colPriceCost: "Preis der Aktivität",
colPricePerDay: "Preis/Tag",
colPriority: "Priorität",
colPriorityShort: "Prio",
colProductName: "Produktname",
colProductVersion: "Version",
colProfileCode: "Profilcode",
colProgress: "Fortschritt",
colProjectCode: "Projektcode",
colProjectName: "Projektname",
colProjectType: "Projekttyp",
colQuantity: "Menge",
colRate: "Anteil in %",
colReadFlag: "lesen",
colReal: "ist",
colRealAmount: "Ist-Betrag",
colRealCost: "Ist-Kosten",
colRealDate: "Ist-Datum",
colRealDuration: "Ist-Dauer",
colRealEis: "Ist-Datum für Produktivbetrieb",
colRealEisDate: "Ist-Datum für Produktivbetrieb",
colRealEnd: "Ist-Endedatum",
colRealEndDate: "Ist-Endedatum",
colRealName: "Tatsächl. Name",
colRealStartDate: "Ist-Startdatum",
colRealWork: "Ist-Arbeit",
colReceptionDateTime: "Übermittlungsdatum",
colRecipient: "Empfänger",
colReference: "Referenz",
colReferenceDocumentVersion: "Referenz Version",
colReffType: "Elementtyp",
colRefId: "Element ID",
colRefType: "Elementtyp",
colReplier: "Antwortender",
colReport: "Bericht",
colRequestDisconnection: "Abmeldung erbeten",
colRequested: "gefordert",
colRequestor: "Antragsteller",
colResource: "Ressourcen",
colResourceCost: "Resourcekosten",
colResourceName: "Ressourcenname",
colResponse: "Antwort",
colResponsible: "verantwortlich",
colResponsibleShort: "verantw.",
colResult: "Ergebnis",
colResultImport: "Importergebnis",
colRib: "Bank ID",
colSendDate: "Sendedatum",
colSender: "Sender",
colSendMail: "sende Mail an",
colSessionId: "Sitzungs ID",
colSetCancelledStatus: "abgebrochen Status",
colSetDoneStatus: "Status 'erledigt'",
colSetHandledStatus: "Status 'bearbeitet'",
colSetIdleStatus: "Status 'abgeschlossen'",
colSeverity: "Auswirkung",
colSeverityShort: "Schw.",
colShowDetail: "Zeige Detail",
colShowInFlash: "im Blitzbericht anzeigen",
colSize: "Größe",
colSortOrder: "Sortierung",
colSortOrderShort: "Sortierung",
colStart: "Start",
colStartDate: "Startdatum",
colStartTime: "Startzeit",
colState: "Land",
colStatusDateTime: "Datum",
colStreet: "Straße",
colSubcontractor: "outgesourced",
colSubcontractorCost: "Outsource Kosten",
colSubDirectory: "Verzeichnis",
colTargetVersion: "Zielversion",
colTask: "Aufgabe",
colTax: "Steuersatz (%)",
colTaxFree: "steuerfrei",
colTeam: "Team",
colTechnicalRisk: "Technisches Risko",
colTestCase: "Testfall",
colTestCases: "Testfälle",
colTestSession: "Testplan",
colTestSummary: "Teststatus",
colText: "Text",
colTicket: "Ticket",
colTicketWork: "Zusammenfassung Ticketaufwand",
colTime: "Zeit",
colTitle: "Titel",
colTotalAssignedCost: "Zugewiesene Gesamtkosten",
colTotalCost: "Gesamtkosten",
colTotalLeftCost: "verbleibende Gesamtkosten",
colTotalPlannedCost: "geplante Gesamtkosten",
colTotalRealCost: "Ist-Gesamtkosten",
colTotalValidatedCost: "genehmigte Gesamtkosten",
colType: "Typ",
columnSelector: "wähle Spalten für Anzeige",
colUnit: "Einheit",
colUntaxedAmount: "Nettobetrag",
colUrgency: "Dringlichkeit",
colUser: "Benutzer",
colUserAgent: "Benutzer Agent",
colUserName: "Benutzername",
colValidated: "bestätigt",
colValidatedAmount: "Gesamtbetrag",
colValidatedAmount2: "Betrag",
colValidatedAmount3: "Gesamtbetrag",
colValidatedCost: "bestätigte Kosten",
colValidatedDate: "bestätigtes Datum",
colValidatedDueDate: "Zieldatum bestätigt",
colValidatedDuration: "Dauer bestätigt",
colValidatedEnd: "Endedatum bestätigt",
colValidatedEndDate: "Endedatum bestätigt",
colValidatedPricePerDayAmount: "bestätigter Gesamtpreis/Tag",
colValidatedPricePerDayAmount2: "Preis/Tag",
colValidatedStartDate: "Startdatum bestätigt",
colValidatedWork: "Arbeit bestätigt",
colValidatedWork2: "Arbeit",
colValue: "Wert",
colValueAfter: "Wert neu",
colValueBefore: "Wert alt",
colValueCost: "Wert",
colValueUnit: "Wert / Einheit",
colVersion: "Version",
colVersionName: "Versionsname",
colWarning: "Erinnerung",
colWbs: "PSP",
colWbsSortable: "PSP sortierbarer",
colWeekday1: "Mo",
colWeekday2: "Di",
colWeekday3: "Mi",
colWeekday4: "Do",
colWeekday5: "Fr",
colWeekday6: "Sa",
colWeekday7: "So",
colWork: "Arbeit",
colWorkElementCount: "Nummer",
colWorkElementEstimatedWork: "geschätzer Aufwand für Tickets",
colWorkElementLeftWork: "verbleibender Aufwand für Tickets",
colWorkElementRealWork: "Ist-Aufwand für Tickets",
colWorkflowUpdate: "Workflow",
colZip: "Postleitzahl",
comboCloseButton: "Schließen",
comboDetailAccess: "Schalter anzeigen 'Detail-Kombinationen'",
comboNewButton: "Erstelle neues Element",
comboSaveButton: "Sichere Element",
comboSearchButton: "Suche ein Element",
comboSelectButton: "Wähle dieses Element",
Command: "Auftrag",
CommandType: "Auftragstyp",
commentDueDates: "Anf | Pln | Ist",
confirmChangeLoosing: "Aktuelle Änderung nicht gespeichert.<br/>Die Änderungen gehen verloren.<br/>Wollen Sie weitermachen?",
confirmControlDelete: "Folgende Abhängigkeiten werden gelöscht",
confirmControlSave: "Folgende Abhängigkeiten werden geschlossen",
confirmCopy: "Kopiere den ${1} #${2} ?",
confirmDelete: "Lösche den ${1} #${2} ?",
confirmDeleteAffectation: "Löschen der Zuordnung #${1} ?",
confirmDeleteApprover: "Lösche Genehmiger '${1}' ?",
confirmDeleteAssignment: "Zuordnung Ressource ${1} löschen?",
confirmDeleteDocumentVersion: "Lösche Version '${1}' ?",
confirmDeleteExpenseDetail: "Sollen Detailaufwand '${1}' gelöscht werden?",
confirmDeleteLink: "Verbindung mit Element ${1} #${2} löschen?",
confirmDeleteOrigin: "Lösche Ursprung ${1} #${2}?",
confirmDeleteOtherVersion: "Lösche ${2} '${1}' ?",
confirmDeleteResourceCost: "Ressourcekosten für Funktion ${1} löschen?",
confirmDeleteTestCaseRun: "Lösche Testfall #${1} von Testplan?",
confirmDeleteVersionProject: "Lösche Verbindung zwischen Version und Projekt?",
confirmDisconnectAll: "Bestätigung 'Abmelden aller Nutzer' (außer Ihres eigenen Nutzers)",
confirmDisconnection: "Wollen Sie sich abmelden?",
confirmLocaleChange: "Sie haben die Sprache geändert.<br/>Möchten Sie die Seite aktualisieren, um die Änderung zu sehen?",
confirmRemoveFilter: "Lösche Filter '${1}' ?",
confirmResetList: "Setzt die Anzeige auf Standardwert zurück - weitermachen?",
connectionsDurationPerDay: "Connections duration per day",
connectionsNumberPerDay: "Verbindungen pro Tag",
Console: "Konsolemeldungen",
consolidateAlways: "immer",
consolidateIfSet: "nur wenn gewählt (löscht nicht übergeordnete Aktivität)",
consolidateNever: "nie",
Contact: "Kontakt",
contactAdministrator: "Kontaktieren Sie Ihren Administrator.",
contacts: "Kontakte",
contains: "enthält",
Context: "Kontext",
ContextType: "Kontexttyp",
copiedFrom: "kopiert von",
copyAssignments: "Kopiere Zuweisungen zu Aktivitäten (incl. Arbeit)",
copyFromCalendar: "Importiere dieses Jahr zum Kalender",
copyProjectAffectations: "Kopiere Zuweisungen zum Projekt (incl. Unterprojekte)",
copyProjectStructure: "Kopieren der Projektstruktur (Aktivitäten & Meilensteine)",
copySubProjects: "Kopiere Unterprojekt",
copyToClass: "Kopiere als neu",
copyToLinkOrigin: "Verbinde aktuelles Element zur Kopie",
copyToName: "Kopiere Name",
copyToOrigin: "Aktuelles Element als Original des kopierten Elements hinzufügen",
copyToType: "Typ kopiertes Element",
copyToWithAttachments: "Anhänge mitkopieren",
copyToWithLinks: "Verknüpfungen mitkopieren",
copyToWithNotes: "Notizen mitkopieren",
copyWithStructure: "Kopieren gesamte Struktur (Unteraktivitäten & -Meilensteine)",
costAccess: "Kosten anzeigen",
count: "zähle",
created: "erstellt",
criteria: "Filter oder Sortierkriterien",
Criticality: "Kritikalität",
cronLogAsFile: "Protokollieren als Datei",
cronLogAsMail: "Protokollieren als Datei und Mail",
cronLogAsMailWithFile: "Protokollieren als Datei und Mail mit Protokoll",
cronStatus: "Cron Status",
cronTasks: "Hintergrundverarbeitung",
csvFile: "CSV Datei (Comma Separated Value)",
cumulated: "kumuliert",
day: "Tag",
days: "Tage",
dbMaintenance: "Wartung von Daten",
debugLevel0: "Keine Fehlerverfolgung",
debugLevel1: "Fehlerverfolgung",
debugLevel2: "Standard Fehlerverfolgung",
debugLevel3: "Fehler/Debug Stufe",
debugLevel4: "Funktionsverfolgung",
December: "Dezember",
Decision: "Entscheidung",
DecisionType: "Entscheidungstyp",
defaultFilterCleared: "Standard-Filter gelöscht",
defaultFilterError: "Standard-Filter kann nicht auf '$ {1}' gesetzt werden.",
defaultFilterSet: "Standard-Filter auf '$ {1}' gesetzt.",
defaultValue: "Standardwert",
deleteAlerts: "Lösche Alarme",
deleteAudit: "Lösche Verbindungs Logbuch",
deleteButton: "Löschen",
deleteEmails: "Lösche Mails",
Dependency: "Abhängigkeit",
descriptionChange: "Beschreibung geändert",
dialogAffectation: "Ressourcenzuordnung",
dialogAlert: "Alarm",
dialogApprover: "Wähle Genehmiger",
dialogAssignment: "Zuordnung",
dialogAttachement: "Anhang",
dialogBillLine: "Rechnungszeile",
dialogChecklist: "Checkliste",
dialogChecklistDefinitionLine: "Auswahlmöglichkeiten für die Checklistenzeile",
dialogConfirm: "Bestätigung",
dialogCopy: "Kopiere Element",
dialogCopyProject: "Kopiere Projekt",
dialogDependency: "Abhängigkeit hinzufügen",
dialogDependencyActivity: "Abhängigkeit zu Aktivität hinzufügen",
dialogDependencyEdit: "Abhängigkeit ändern",
dialogDependencyExtended: "Abhängigkeit zu Element ${1} #${2} hinzufügen",
dialogDependencyProject: "Verbindung zu Projekt hinzufügen ",
dialogDependencyRestricted: "Füge ${3} zu Element ${1} #${2} hinzu",
dialogDetailCombo: "Details Listenelement",
dialogDocumentVersion: "Dokumentversion",
dialogError: "Fehler",
dialogExpenseDetail: "Details Aufwand",
dialogExport: "Export",
dialogFilter: "Erweiterte Filterfunktion",
dialogInformation: "Information",
dialogLink: "Verbindung hinzufügen ",
dialogLinkAction: "Verbindung zu Aktion hinzufügen",
dialogLinkExtended: "Verbindung zu Element ${1} #${2} hinzufügen",
dialogLinkIssue: "Verbindung zu eine Problem hinzufügen",
dialogLinkRestricted: "Füge Verbindung zwischen Element ${1} #${2} und Element ${3} hinzu.",
dialogLinkRisk: "Verbindung zu Risiko hinzufügen",
dialogNote: "Notiz",
dialogOrigin: "Ursprungselement hinzufügen",
dialogOtherVersion: "Andere Versionen hinzufügen",
dialogPlan: "Kalkuliere Planung für Projekt",
dialogPlanSaveDates: "Speichere geplantes Datum in gefordertes und bestätigtes Datum",
dialogPrint: "Druckvoransicht",
dialogProjectSelectorParameters: "Projektauswahl Parameter",
dialogQuestion: "Frage",
dialogResourceCost: "Ressourcekosten",
dialogTestCaseRun: "Testfall-Durchlauf",
dialogTodayParameters: "Heute Parameter",
dialogVersionProject: "Verbindung Projekt zu Version",
dialogWorkflowParameter: "Wähle Status anzeigen / ausblenden",
Diary: "Terminkalender",
diaryAccess: "Zugriff auf Terminkalender",
disconnect: "Abmeldung",
disconnectAll: "Abmelden aller Nutzer",
disconnected: "Ihre Sitzung wurde vom Administrator beendet<br/>Bitte neu (später) anmelden.",
disconnectMessage: "Ende aktuelle Sitzung",
disconnectSession: "Erzwinge Abmeldung dieser Sitzung",
displayAlert: "Interner Alarm",
displayAlertAndMail: "Interner Alarm & Mail",
displayEndDate: "Anzeige bis",
displayMail: "Mail",
displayModeSelect: "Filterauswahl (mit Autovervollständigung)",
displayModeStandard: "Standard (entspricht WBS Struktur)",
displayNo: "Nein",
displayStartDate: "Anzeige von",
displayYes: "Ja",
displayYesClosed: "Ja (kompakte Ansicht)",
displayYesOpened: "Ja (ausführliche Ansicht)",
displayYesShowOnClick: "Ja (Anzeige bei Mouseclick)",
displayYesShowOnMouse: "Ja (Anzeige bei Mousebewegung)",
document: "Dokumente",
Document: "Dokument",
DocumentDirectory: "Dokumentverzeichnis",
documents: "Dokumente",
DocumentType: "Dokumenttyp",
documentUnlockRight: "Entsperre alle Dokumente",
DocumentVersion: "Dokumentversion",
documentVersionIsRef: "Diese Version ist die letzte Referenz für das Dokument (zuletzt geprüft)",
documentVersionUpdate: "Aktualisiere",
done: "erledigt",
doneoperationclose: "geschlossen",
doneoperationdelete: "gelöscht",
dragAndDrop: "Dateien hierher Ziehen und Ablegen",
duplicateAlreadyLinked: "Duplikat bereits verbunden mit anderem Duplikat",
duplicateIsSame: "Duplikat von sich selbst nicht möglich",
editAffectation: "Ressourcenzuordnung ändern",
editAssignment: "Zuordnung ändern",
editDependencyPredecessor: "Vorgänger ändern",
editDependencySuccessor: "Nachfolger ändern",
editDocumentVersion: "Bearbeite diese Version",
editExpenseDetail: "Aufwandsdetails ändern",
editLine: "Bearbeite diese Zeile",
editNote: "Notiz ändern",
editResourceCost: "Ressourcekosten ändern",
editTestCaseRun: "Testfall-Durchlauf ändern",
editVersionProject: "Verbindung Projekt und Version ändern",
Efficiency: "Effizienz",
elementHistoty: "Historie",
emailMandatory: "Mail muss erfasst sein",
end: "Ende",
Environment: "Stammdaten",
eolDefault: "Standard Format (\r\n)",
eolPostfix: "Spezifisches Format für Postfix < 2.1 (\n)",
ERROR: "Fehler",
errorAck: "Fehler bei Bestätigung",
errorConnection: "Verbindung abgebrochen. Bitte neu anmelden.",
errorConnectionCNX: "SQL FEHLER<BR//>Verbindungsproblem bei '${1}' Für Nutzer '${2}'.<BR/>Überprüfe 'Parameter' Datei.",
errorConnectionDB: "SQL FEHLER<BR/>Verbindungsproblem 'unbekannte Datenbank' '${1}'.<BR/>Überprüfe 'Parameter' Datei.",
errorControlClose: "Element kann nicht geschlossen werden - es bestehen noch nicht geschlossene, aber abhängige Elemente",
errorControlDelete: "Element kann nicht gelöscht werden, da es bestehende Abhängigkeiten gibt.",
errorCreateRights: "Sie haben nicht das Recht zum Erstellen",
errorDeleteCostStartDate: "Neuer Kostensatz kann nicht vor dem alten wirksam werden",
errorDeleteDefaultCalendar: "Standard Kalender kann nicht gelöscht werden.",
errorDeleteDoneBill: "Erledigte Rechnung kann nicht gelöscht werden.",
errorDeleteRights: "Sie haben nicht das Recht zum Löschen",
errorDependencyHierarchy: "Kann keine Abhängigkeit mit übergeordneten Element erstellen",
errorDependencyLoop: "Kann keine gegenseitigen Abhängigkeiten erstellen.",
errorDuplicateActivityPrice: "Ein Aktivitätspreis für das selbe Projekt und Typ bereits vorhanden",
errorDuplicateAffectation: "Dupliziere Zuordnung",
errorDuplicateApprover: "Genehmiger existiert bereits",
errorDuplicateChecklistDefinition: "Checklisten Definition bereits vorhanden (gleiches Element, gleicher Typ)",
errorDuplicateDependency: "Abhängigkeit besteht bereits",
errorDuplicateDocumentVersion: "Version '${1}' gibt es bereits für dieses Dokument",
errorDuplicateIndicator: "Doppelter Indikator",
errorDuplicateLink: "Diese Verbindung besteht bereits",
errorDuplicateStatusMail: "'Mail nach Statusänderung' für dieses Element in diesem Satus bereits definiert",
errorDuplicateTestCase: "Testfall bereits zu Testplan verbunden - 'erlaube Duplikat' ist nicht aktiviert",
errorDuplicateTicketDelay: "Definition 'Verzögerung' für diesen Type in dieser Dringlichkeit gibt es bereits",
errorDuplicateUser: "Mit diesem Namen gibt es schon einen Nutzer",
errorDuplicateVersionProject: "Zuordnung Projekt zu Version kann nur einmal erfolgen",
errorEmptyBill: "Die Rechnung darf nicht leer sein",
errorFinalizeMessage: "Fehler bei finalizeMessageDisplay('${1}') : <br/>Ziel ist kein Knoten und kein Steuerelement<br/>oder lastOperation oder lastOperationStatus ist kein Knoten<br/><br/>${2}",
errorHierarchicLoop: "Kann keine Hierarchie-Abhängigkeiten erstellen.",
errorIdleWithLeftWork: "Element mit offener Arbeit kann nicht geschlossen werden.",
errorImportFormat: "<b>FEHLER - Feldtyp und gewähltes Dateiformat stimmen nicht überein</b><br/>Import abgebrochen",
errorLoadContent: "Fehler bei loadContent('${1}', '${2}', '${3}', '${4}')<br/>Ziel '${5}' ist kein Knoten und kein Steuerelement",
errorLockedBill: "Rechnung gesperrt",
errorMagicQuotesGpc: "'magic_quotes_gpc' muss abgeschalten werden (Wert = false). <br/>Ändern Sie die Datei 'Php.ini'.",
errorMandatoryValidatedDuration: "Gültige Dauer erforderlich.",
errorMandatoryValidatedEndDate: "Gültiges Endedatum erforderlich.",
errorMandatoryValidatedStartDate: "Gültiges Startdatum erforderlich.",
errorMessage: "Fehler aufgetreten bei ${1} mit ${2}",
errorMessageCopy: "${1} Fehler während des Kopierens",
errorNoFile: "Keine Datei zum Hochladen vorhanden",
errorNotFoundFile: "Importdatei nicht gefunden",
errorObjectId: "Fehler mit Schalter NEU : objectId ist kein Knoten",
errorRegisterGlobals: "'register_globals' muss abgeschalten werden (Wert = false). <br/>Ändern Sie die Datei 'Php.ini'.",
errorStartEndDates: "${1}' darf nicht spätester als '${2}' sein.",
errorSubmitForm: "Fehler bei 'submitForm('${1}', '${2}', '${3}')' : <br/> Form '${3}' ist kein Steuerelement.",
errorTooBigFile: "Dateigröße übersteigt maximales Limit von ${1} Bytes (${2})",
errorUpdateRights: "Sie haben nicht das Recht zum Ändern",
errorUploadFile: "Fehler beim Hochladen der Datei. Fehler Kode = ${1}",
errorValueWithoutUnit: "Einheit erforderlich, wenn ein Wert vorhanden ist",
errorWorflow: "Dieser Status ist laut Workflow nicht zugelassen",
errorXhrPost: "Fehler xhrPost return für loadContent('${1}', '${2}', '${3}', '${4}') : <br/> ${5}",
estimated: "Arbeit geschätzt",
evolutive: "Entwicklung",
exceptionMessage: "Ein Ausnahmefall von ${1} bei ${2} ist aufgetreten",
existingDirectoryName: "Dieses Verzeichnis existiert bereits",
ExpenseDetail: "Aufwandsdetail",
ExpenseDetailType: "Aufwandsdetailtyp",
exportReferencesAs: "ID oder Name für Referenzen",
external: "benutzerdefiniert",
ExternalShortcuts: "Externe Abkürzungen",
failed: "nicht erfolgreich",
failedTestCaseRun: "Testfall als 'fehlgeschlagen' markieren",
Feasibility: "Machbarkeit",
February: "Februar",
filterName: "Filtername",
filterOnId: "Filter nach ID",
filterOnName: "Filter nach Name",
filterOnType: "Filter nach Typ",
flashReport: "Blitzbericht",
Friday: "Freitag",
from: "von",
Health: "Projektstatus",
help: "Online Handbuch",
helpAlertCheckTime: "Verzögerung in Sekunden vor neuer Prüfung, ob neuer Alarm vorhanden.",
helpBillNumSize: "Zahl der Stellen für Rechnungsnummer",
helpBillNumStart: "Startnummer für Rechnungen",
helpBillPrefix: "Präfix für Rechnungsnummern",
helpBillSuffix: "Anhang für Rechnungsnummern",
helpBrowserLocaleDateFormat: "Format zur Darstellung des Datums - DD für Tag - MM für Monat - YYYY für Jahr",
helpChangeReferenceOnTypeChange: "Ändere Referenz nach Typänderung",
helpConsolidateValidated: "konsolidiere bestätigte Arbeit & Kosten bei Top-Aktivitäten und -Projekten",
helpCronCheckDates: "Verzögerung für Erzeugung Alarme in Sekunden",
helpCronCheckEmails: "Verzögerung (in Sek.) für Prüfung Maileingang, Speichern von Antworten als Notizen",
helpCronCheckEmailsHost: "IMAP host Verbindungdaten zur Prüfung auf Maileingang, z. B. : {imap.gmail.com:993/imap/ssl}INBOX",
helpCronCheckEmailsPassword: "IMAP password Maileingang",
helpCronCheckEmailsUser: "IMAP Name Maileingang",
helpCronCheckImport: "Verzögerungen autom. Importe in Sek.",
helpCronDirectory: "Arbeitsverzeichnis für CRON Kennzeichen",
helpCronImportDirectory: "Verzeichnis Integration von neuen Dateien",
helpCronImportLogDestination: "Ort Ergebnisprotokoll der automatischen Integration",
helpCronImportMailList: "Mail-Verteiler Ergebnisprotokoll autom. Integration",
helpCronSleepTime: "Standard Cron Wartezeit in Sekunden",
helpCsvSeparator: "Zeichentrennung je Feld im CSV Format für Im-/Export",
helpCurrency: "Währungskennzeichen für Kostensicht",
helpCurrencyPosition: "Position Währungskennzeichen",
helpDayTime: "Anzahl Stunden für Arbeit pro Tag",
helpDefaultProfile: "Standardprofil für neue Nutzer",
helpDefaultProject: "Wähle das Standardprojekt für jede neue Anmeldung.",
helpDefaultTheme: "Standard Benutzeroberfläche, wenn Nutzer keine individuelle Einstellung wählt",
helpDisplayAttachement: "Anzeigemodus für Abschnitt Anhang",
helpDisplayHistory: "Zeige die Änderungshistorie je Element an.",
helpDisplayNote: "Anzeigemodus für Abschnitt Notiz",
helpDisplayOnlyHandled: "Nur Aufgaben 'in Bearbeitung' im 'Ist-Arbeit-Report' anzeigen",
helpDisplayResourcePlan: "Formatierungsoptionen für Ressourcen in Ganttplanung",
helpDocumentReferenceFormat: "Format Dokumentenreferenz",
helpDocumentRoot: "Wurzelverzeichnis für Dokumente",
helpDontReceiveTeamMails: "keine Mails, wenn Empfänger ist aus 'Team' (Resourcen, die dem Projekt zugeordnet sind)",
helpDownload: "Lade diese Datei herunter.",
helpDraftSeparator: "Trennzeichen für ENTWURF im Versionsnamen",
helpEndAM: "Endzeit der Standardarbeitszeit am Vormittag",
helpEndPM: "Endzeit der Standardarbeitszeit am Nachmittag",
helpFilenameCharset: "Zeichensatz für Dateien auf dem Server, um Nicht-ASCII-Zeichen zu berücksichtigen (z. B. ISO-8859-15)",
helpGanttPlanningPrintOldStyle: "Drucke Gantt im alten Format - sofern Fehler beim Druck auftraten - Sie verlieren zwar Besonderheiten im Layout, gewinnen aber Stabilität",
helpGetVersion: "Aktivitätstypen",
helpHideMenu: "Verdecke oder zeige linkes 'Baum'-Menü",
helpImport: "Anzeige der Feldnamen",
helpImputationUnit: "Einheit für Ist-Arbeit: Tage oder Stunden",
helpLang: "Wählen Sie ihre bevorzugte Sprache.",
helpLdapDefaultProfile: "Standard Profil für neue Nutzer, die durch LDAP hinzugefügt werden.",
helpLdapMsgOnUserCreation: "Nachrichtentyp oder Alarm an Adminstrator, bei neuen LDAP Nutzern",
helpLogFile: "Log Dateiname (kann den Parameter ${date} enhalten, um 1 Datei pro Tage zu haben)",
helpLogLevel: "Log Stufe",
helpMaxDaysToBookWork: "Erfassung von IST-Arbeit in die Zukunft über die festgelegte Anzahl von Tagen hinaus, führt zur Sicherheitsmeldung",
helpMaxProjectsToDisplay: "Maximale Anzahl von Projekten in der Datenbank ab der Projekte in der Planungssicht begrenzt werden",
helpnitializePassword: "Automatische Passwort-Initialisierung bei neuen Nutzern",
helpOtherEmail: "manuelle Eingabe Mail-Adresse",
helpParamAdminMail: "E-Mail des Administrators",
helpParamAttachementDirectory: "Verzeichnis für Anhänge",
helpParamAttachementMaxSize: "Maximale Größe für Anhänge in byte - muss kleiner oder gleich zum PHP Parameter : upload_max_filesize sein",
helpParamConfirmQuit: "Anzeige Abmelden-Bestätigung bei 'Schließen d. Tabs' oder 'Rücktaste'",
helpParamDbDisplayName: "Datenbankname der in der Fußleiste angezeigt wird",
helpParamDefaultLocale: "Standardsprache, wenn Nutzer keine individuelle Einstellung wählt",
helpParamDefaultPassword: "Standard Password bei Nutzeranlage",
helpParamDefaultTimezone: "Standard Zeitzone - liste siehe entsprechende Webseite",
helpParamFadeLoadingMode: "Neue Bildschirme in Überblendemodus anzeigen",
helpParamIconSize: "Größe der Icons in der Menübaumanzeige",
helpParamLdap_allow_login: "Erlaube Verbindung mit LDAP Nutzer",
helpParamLdap_base_dn: "LDAP Basis DN für ProjecQtOr Nutzer",
helpParamLdap_host: "LDAP Hostadresse oder IP",
helpParamLdap_port: "LDAP port - Standard ist 389",
helpParamLdap_search_pass: "LDAP Password für Hauptnutzer",
helpParamLdap_search_user: "LDAP Hauptnutzer für Verbindung und Suche in LDAP",
helpParamLdap_user_filter: "LDAP Filter zur Suche nach Nutzernamen - Ergebnis %USERNAME% gefunden",
helpParamLdap_version: "LDAP Protokollversion, um Kompatibilitätsprobleme zu lösen",
helpParamLockAfterWrongTries: "lock user after a given number of wrong connexions",
helpParamMailBodyApprover: "Text für Mails 'Genehmigung von Anforderungen'",
helpParamMailBodyUser: "Text für Login Informations Mails",
helpParamMailEol: "Zeilenende Format für Mails zur Problemlösung von Postfix < 2.1",
helpParamMailReplyTo: "Antworten an' Mail-Adresse",
helpParamMailReplyToName: "Name des Mail-Senders - auch für Antworten",
helpParamMailSender: "Absender' Mail-Adresse",
helpParamMailSendmailPath: "Pfad für 'sendmail' wenn nicht automatisch durch PHP identifiziert (im Zweifel leer lassen)",
helpParamMailSmtpPassword: "SMTP login password",
helpParamMailSmtpPort: "Port für email (smtp) server [Standardwert = 25]",
helpParamMailSmtpServer: "Smtp server [Standard = 'localhost']",
helpParamMailSmtpUsername: "SMTP login Name - notwendig für die Authentifizierung am Verbindungsserver",
helpParamMailTitleAnyChange: "Mailtitel bei Änderungen",
helpParamMailTitleApprover: "Titel für Mails 'Genehmigung von Anforderungen'",
helpParamMailTitleAssignment: "Mailtitel für hinzugefügte Zuweisung",
helpParamMailTitleAssignmentChange: "Mailtitel für geänderte Zuweisung",
helpParamMailTitleAttachment: "Mailtitel für hinzugefügte Anhänge",
helpParamMailTitleDescription: "Mailtitel für geänderte Beschreibungen",
helpParamMailTitleDirect: "Mailtitel, die manuell (Mail Schalter) versandt werden",
helpParamMailTitleNew: "Mailtitel für hinzugefügte Elemente",
helpParamMailTitleNote: "Mailtitel für hinzugefügte Notizen",
helpParamMailTitleNoteChange: "Mailtitel für geänderte Notizen",
helpParamMailTitleResponsible: "Mailtitel für geänderte Verantwortliche",
helpParamMailTitleResult: "Mailtitel für geänderte Ergebnisse",
helpParamMailTitleStatus: "Mailtitel für Statusänderungen",
helpParamMailTitleUser: "Titel für Login Informations Mail",
helpParamMemoryLimitForPDF: "Speicherlimit in MB für PDF-Erstellung - zu wenig Speicher führt zu PDF Problemen und zu viel Speicher bringt den Server zum Absturz",
helpParamPasswordMinLength: "Mindestzahl von Zeichen für das Password",
helpParamReportTempDirectory: "Temporäres Verzeichnis für Berichte - muss im Web Dokumentenstamm sein, um Images zu bekommen ",
helpParamTopIconSize: "Größe der Icons in der Top-Menü-Anzeige",
helpPasswordValidityDays: "Passwort Gültigkeit (in Tage) bis zur Änderung-Aufforderung - 0 für dauerhafte Gültigkeit",
helpPdfInNewWindow: "PDF Exporte in neuem Fenster (oder Tabulator) oder aktuellem Fenster voranzeigen",
helpPreserveUploadedFileName: "Soll die Datei nach Download mit dem Ursprungs-Dateinamen (Ja) oder gemäß Formatierung (Nein) benannt werden.",
helpPrintInNewWindow: "Voranzeige Druckausgabe in neuem Fenster (oder Tabulator) oder aktuellem Fenster",
helpRealWorkOnlyForResponsible: "Nur Verantwortlicher kann IST-Aufwände im Ticket erfassen",
helpReferenceFormatNumber: "Anzahl Stellen für Referenznummernzähler",
helpReferenceFormatPrefix: "Präfix Format für Referenznummer",
helpRefreshUpdates: "Aktualisiere Anzeige nach Änderungen.",
helpRememberMe: "Erinnerung' Funktion für Autoverbindung erlauben",
helpResetColor: "Farbe zurücksetzen - wird transparent",
helpResetPassword: "Passwort zurücksetzen - Bitte sichern nach dieser Aktion.",
helpSelectFile: "Wähle die Datei zum Hochladen.",
helpSetHandledOnRealWork: "Aufgabe erst auf 'begonnen' setzen, wenn Ist-Arbeit erfaßt wurde",
helpSetResponsibleIfNeeded: "Weise automatisch Verantwortlichen als Ressource zu, wenn eine Resource erforderlich ist.",
helpSetResponsibleIfSingle: "Weise automatisch Verantwortlichen als Ressource zu, wenn nur eine Resource dem Projekt zugewiesen ist.",
helpStartAM: "Start Standardarbeitszeit am Vormittag",
helpStartPage: "Anzeige nach Logon",
helpStartPM: "Start Standardarbeitszeit am Nachmittag",
helpSwitchedMode: "Legt Anzeige zwischen Listen- und Detailanzeige fest",
helpTheme: "Farbe für die Anzeige ändern",
helpTitle: "Titel für Tooltip",
helpVersionReferenceSuffix: "Anhang für Versions-Referenz",
helpWorkUnit: "Einheit für Arbeit",
hour: "Stunde",
hours: "Stunden",
iconSizeBig: "groß (32px)",
iconSizeMedium: "mittel (22px)",
iconSizeSmall: "klein (16px)",
ifEmpty: "wenn leer",
imputationAccess: "Zugriff auf Ressourcenzuordnung ",
indentDecreaseButton: "Einrückung verringern",
indentIncreaseButton: "Element unter Vorgänger einrücken",
IndicatorDefinition: "Indikator",
IndividualExpense: "Individueller Aufwand",
IndividualExpenseType: "Individueller Aufwandstyp",
INFO: "Information",
infoLocaleChange: "Sie änderten die bevorzugte Sprache.<br/>Bis zur nächsten Neuanmeldung werden nicht alle Informationen korrekt angezeigt.<br/>Deshalb bitte speichern Sie die Parameter und melden sich neu an.",
infoLocaleChangeShort: "Sie änderten die bevorzugte Sprache.",
infoMessage: "Besuchen Sie die 'ProjecQtOr web Site'.",
initialDueDate: "Berücksichtige anfängliches Startdatum",
initialDueDateTime: "Berücksichtige anfängliches Startdatum/-zeit",
initialEndDate: "Berücksichtige gewünschtes Endedatum",
initialStartDate: "Berücksichtige gewünschtes Startdatum",
invalidAccessAttempt: "Unzulässiger Zugriffsversuch",
invalidDirectoryName: "Ungültiger Verzeichnisname",
invalidGpsData: "Ungültige GPS Daten",
invalidLogDir: "Log-Buch-Verzeichnis '${1}' ist ungültig. Überprüfen Sie die 'Parameter' Datei.",
invalidLogin: "Ungültige Anmeldedaten.",
invalidPasswordChange: "Ungültiges neues Passwort<br> - es muss mindestens ${1} Zeichen lang sein.<br/> - es muss unterschiedlich vom Standard-/Start-Wert sein.",
Invoice: "Rechnung",
InvoiceType: "Rechnungtyp",
isEmpty: "ist leer",
isIssuerOf: "ist Ersteller von",
isNotEmpty: "ist nicht leer",
isResponsibleOf: "ist verantwortlich für",
Issue: "Probleme",
IssueType: "Problemtyp",
January: "Januar",
July: "Juli",
June: "Juni",
labelDisplayOnlyCurrentWeekMeetings: "Zeige nur Besprechungen der aktuellen Woche",
labelHideDone: "'nicht bearbeitete' Elemente ausblenden",
labelHideNotHandled: "'erledigte' Elemente ausblenden",
labelMultipleMode: "Mehrfach-Modus",
labelShowIdle: "Zeige abgeschlossene Elemente",
labelShowLeftWork: "Zeige verbleibende Arbeit",
labelShowMilestone: "Meilensteine anzeigen",
labelShowPlannedWork: "Zeige geplante Arbeit",
labelShowProjectLevel: "Zeige Projektebene",
labelShowResource: "Zeige Ressourcen",
labelShowWbs: "Zeige PSP",
langDe: "Deutsch",
langEl: "Griechisch",
langEn: "Englisch - English",
langEs: "Spanisch - Español",
langFa: "Farsi (Persian) - فارسی",
langFr: "Französisch - Français",
langJa: "Japanisch",
langNl: "Holländisch - Nederlands",
langPt: "Portugisisch - Português",
langPtBr: "Portuguese (Brazil) - Português (Brazil)",
langRu: "Russisch - Pусский",
langZh: "Chinese - 简体中文",
ldapError: "LDAP Fehler",
left: "Arbeit verbleibend",
Likelihood: "Wahrscheinlichkeit",
limitedDisplay: "Liste ist gekürzt auf die ${1} ersten Positionen",
Link: "Verbindung",
linkElement: "verbundenes Element",
linkType: "verbundener Elementtyp",
listTodayItems: "Anzuzeigende Elemente",
lockDocument: "Sperre dieses Dokument",
lockedLogDir: "Logbuch-Verzeichnis '${1}' ist gesperrt. Logbuch-Funktion nicht verfügbar.",
lockedUser: "Dieser Nutzer ist gesperrt.<br/>Bitte Kontakt mit Administrator aufnehmen.",
lockRequirement: "Sperre Anforderung",
login: "Anmeldung",
loginOK: "Anmeldung war erfolgreich",
Mail: "Mailausgang",
mailSent: "Mail versandt",
mailSentTo: "Mail versandt an '${1}'",
mainProject: "Hauptprojekt",
maintenanceDone: "${1} '${2}' ${3}",
manageConnections: "Verwalte Verbindungen",
mandatoryField: "erforderlich",
mandatoryOnDoneStatus: "erforderlich bei 'erledigt'-Status",
mandatoryOnHandledStatus: "erforderlich bei 'bearbeitet'-Status",
March: "März",
markAsRead: "Als gelesen markieren",
max: "max",
May: "Mai",
mean: "mean",
Meeting: "Besprechung",
MeetingType: "Besprechungstyp",
members: "Mitglieder",
menu: "Menü",
menuAccessProfile: "Zugriffsmodus",
menuAccessRight: "Zugriff auf Daten",
menuAction: "Aktionen",
menuActionType: "Aktionstypen",
menuActivity: "Aktivitäten",
menuActivityPrice: "Aktivitätenpreis",
menuActivityType: "Aktivitätstypen",
menuAdmin: "Verwaltung",
menuAffectation: "Ressourcenzuordnungen",
menuAlert: "Alarme",
menuAllAction: "Alle Aktionen",
menuAllActivity: "Alle Aktivitäten",
menuAllComponent: "Alle Komponenten",
menuAllIssue: "Alle Probleme",
menuAllMeeting: "Alle Besprechungen",
menuAllRisk: "Alle Risiken",
menuAnomaly: "Unregelmäßigkeiten",
menuAudit: "Prüfe Verbindungen",
menuAutomation: "Steuerung & Automatisierung",
menuBarMoveLeft: "Balken nach links verschieben",
menuBarMoveRight: "Balken nach rechts verschieben",
menuBill: "Rechnungen",
menuBillType: "Rechnungstypen",
menuCalendar: "Kalender",
menuCalendarDefinition: "Kalender",
menuChecklistDefinition: "Checklisten",
menuClient: "Kunden",
menuClientType: "Kundentypen",
menuCommand: "Aufträge",
menuCommandType: "Auftragstypen",
menuComponent: "Komponenten",
menuContact: "Kontakte",
menuContext: "Kontext",
menuContextType: "Kontextypen",
menuCriticality: "Kritikalitäten",
menuDecision: "Entscheidungen",
menuDecisionType: "Entscheidungstypen",
menuDiary: "Terminkalender",
menuDocument: "Dokumente",
menuDocumentDirectory: "Dokumentenverzeichnis",
menuDocumentType: "Dokumenttypen",
menuEfficiency: "Effizienzen",
menuEnvironment: "Stammdaten",
menuEnvironmentalParameter: "Stammdaten",
menuExpenseDetailType: "Aufwandsdetailtypen",
menuFeasibility: "Machbarkeiten",
menuFinancial: "Finanzen",
menuFollowup: "Planung & Berichte",
menuGlobalParameter: "Globale Parameter",
menuHabilitation: "Zugriff auf Formulare",
menuHabilitationOther: "Spezielle Zugriffe",
menuHabilitationParameter: "Zugriffsrechte",
menuHabilitationReport: "Zugriff auf Berichte",
menuHealth: "Projektstatus",
menuImportData: "Daten importieren",
menuImputation: "Ist-Arbeit-Report ",
menuIndicatorDefinition: "Indikatoren",
menuIndividualExpense: "Individuelle Aufwände",
menuIndividualExpenseType: "Individuelle Aufwandtypen",
menuInvoice: "Rechnung",
menuInvoiceType: "Rechnungstypen",
menuIssue: "Probleme",
menuIssueType: "Problemtypen",
menuLikelihood: "Wahrscheinlichkeit",
menuListOfValues: "Werte & Ausprägungen",
menuMail: "Mailausgang",
menuMeeting: "Besprechungen",
menuMeetingType: "Besprechungstypen",
menuMessage: "Meldungen",
menuMessageType: "Meldungstypen",
menuMilestone: "Meilensteine",
menuMilestoneType: "Meilensteintypen",
menuOpportunity: "Chancen",
menuOpportunityType: "Chancentypen",
menuOverallProgress: "Gesamt Fortschritt",
menuParameter: "Parameter",
menuPayment: "Zahlungen",
menuPaymentType: "Zahlungstypen",
menuPeriodicMeeting: "Regelmäßige Besprechungen",
menuPlanning: "Planung",
menuPortfolioPlanning: "Projekt Portfolio",
menuPredefinedNote: "vordefinierte Notizen",
menuPriority: "Prioritäten",
menuProduct: "Produkte",
menuProfile: "Profile",
menuProject: "Projekte",
menuProjectExpense: "Projektaufwände",
menuProjectExpenseType: "Projektaufwandstypen",
menuProjectLife: "Produkt-Lebenzyklus",
menuProjectParameter: "Projekt Parameter",
menuProjectType: "Projekttypen",
menuQuality: "Qualitätslevel",
menuQuestion: "Fragen",
menuQuestionType: "Fragentypen",
menuQuotation: "Angebote",
menuQuotationType: "Angebotstypen",
menuRecipient: "Empfänger",
menuReports: "Berichte",
menuRequestor: "Abfragegenerator",
menuRequirement: "Anforderungen",
menuRequirementTest: "Anforderungen & Tests",
menuRequirementType: "Anforderungstypen",
menuResource: "Ressourcen",
menuResourcePlanning: "Ressourcenplanung",
menuReview: "Protokolle / Logbücher",
menuRisk: "Risiken",
menuRiskLevel: "Risikoebenen",
menuRiskManagementPlan: "Risiko & Problem Management",
menuRiskType: "Risikotypen",
menuRole: "Funktionen",
menuSeverity: "Auswirkung",
menuStatus: "Status",
menuStatusMail: "Mails nach Statusänderungen",
menuTeam: "Teams",
menuTerm: "Konditionen",
menuTestCase: "Testfälle",
menuTestCaseType: "Testfalltypen",
menuTestSession: "Testpläne",
menuTestSessionType: "Testplantypen",
menuTicket: "Tickets",
menuTicketDelay: "Verzögerungen für Tickets",
menuTicketSimple: "Tickets (einfach)",
menuTicketType: "Tickettypen",
menuToday: "Heute",
menuTool: "Werkzeuge",
menuTrend: "Trends",
menuType: "Liste der Typen",
menuUrgency: "Dringlichkeiten",
menuUser: "Nutzer",
menuUserParameter: "Nutzerparameter",
menuVersion: "Versionen",
menuWork: "Arbeit",
menuWorkflow: "Workflow",
Message: "Meldung",
messageConfirmationNeeded: "Aktion erfordert Bestätigung",
messageDateMandatoryWithTime: "Das Feld '${1}' muss Datum mit Zeit enthalten",
messageError: "FEHLER",
messageImputationSaved: "Ist-Aufwände gesichert",
messageInvalidControls: "Ungültiges Steuerelement",
messageInvalidDate: "Das Datum muss einen gültigen Wert haben.",
messageInvalidDateNamed: "Das Feld '${1}' muss ein gültiges Datum haben.",
messageInvalidNumeric: "Wert von ${1} ist nicht numerisch",
messageInvalidTime: "Die Zeit muss einen gültigen Wert haben.",
messageInvalidTimeNamed: "Das Feld '${1}' muss einen gültigen Wert haben.",
messageItemDelete: "Element ${1} # ${2} wurde nicht in der Datenbank gefunden.",
messageMandatory: "Feld '${1}' ist erforderlich",
messageNoAccess: "Sie haben nicht die Zugriffsberechtigung für ${1}.",
messageNoChange: "Keine Änderung vorhanden.",
messageNoData: "Nr. ${1} ist ausgewählt.",
messageNoImputationChange: "Keine Änderung bei Ist-Arbeit vorhanden.",
messageParametersNoChangeSaved: "Keine Änderung bei Parametern vorhanden.",
messageParametersSaved: "Parameter sind gesichert.",
messagePreview: "Bereite Druckvorschau vor …",
messageSelectedNotAvailable: "Sie wählten '${1}'.<br/>Die Funktionalität ist nicht verfügbar in dieser Version von ProjecQtOr.<br/>Tut uns leid …",
messageTextTooLong: "Länge für ${1} überschreitet ${2} Zeichen",
MessageType: "Meldungstyp",
Milestone: "Meilenstein",
MilestoneType: "Meilensteintyp",
min: "min",
minute: "Minuten",
Monday: "Montag",
month: "Monat",
moveCancelled: "Verschiebung nicht möglich.",
moveDone: "Element erfolgreich verschoben",
msgCannotDeleteContact: "Kontakt kann nicht gelöscht werden, denn er ist auch ein Benutzer.",
msgCannotDeleteProfile: "Dieses Profil kann nicht gelöscht werden",
msgCannotDeleteProjectType: "Dieser Typ von Projekten kann nicht gelöscht werden",
msgCannotDeleteResource: "Ressource kann nicht gelöscht werden, denn sie ist auch ein Benutzer.",
msgCannotDeleteStatus: "Dieser Standardstatus kann nicht gelöscht werden",
msgEnterPlannedDA: "Geplantes Datum und Betrag müssen beide erfaßt werden.",
msgEnterRealDA: "Ist-Datum und -Betrag müssen beide erfaßt werden.",
msgEnterRPAmount: "Betrag (geplant oder ist) muss erfaßt werden.",
msgEnterRPDate: "Datum (geplant oder ist) muss erfaßt werden.",
msgIncorrectReceiver: "Empfänger kann für dieses Element nicht ausgewählt werden.",
msgNotGranted: "Sie haben nicht das Recht für diese Operation",
msgParentActivityInSameProject: "Übergeordnete Aktivität muss im selben Projekt vorhanden sein.",
msgParentRequirementInSameProjectProduct: "Übergeordnete Anforderung muss im selben Projekt vorhanden sein.",
msgParentTestCaseInSameProjectProduct: "Übergeordneter Testfall muss im selben Projekt vorhanden sein.",
msgPdfDosabled: "PDF export ist deaktiviert.",
msgPlanningActivityInSameProject: "Planungstyp muss im selben Projekt vorhanden sein.",
msgRealWorkInTheFuture: "Ihre IST-Aufwand-Meldung liegt über den zugelassenen ${1} Tagen in der Zukunft - Wollen Sie das?",
msgTranslatable: "Achtung - dieses Feld wird gemäß lokalen Einstellungen übersetzt.",
msgTranslation: "Übersetzung",
msgUnableToDeleteRealWork: "Kann nicht gelöscht werden, da Ist-Arbeit gebucht ist.",
never: "nie",
newLine: "<br/><br/>",
newParameters: "${1} neue Paramenter in Version ${2}",
newPassword: "Neues Passwort",
newUser: "Neuer Nutzer",
newUserMessage: "Nutzer '${1}' von LDAP erstellt",
newVersion: "Neue Version ${1} auf ProjecQtOr Webseite verfügbar",
nextDays: "Nächste Tage",
noChecklistDefined: "Keine Checkliste für dieses Element",
noDataToDisplay: "Keine Daten zur Anzeige verfügbar",
noFilterClause: "Keine Filterklausel",
noItemSelected: "Kein Element ausgewählt",
noMailSent: "Kann Mail nicht an '${1}'. ${2} senden.",
noStoredFilter: "Keine gespeicherten Filter",
notAbleToStopCron: "Cron Prozess kann nicht gestoppt werden. Bitte nochmals versuchen oder löschen Sie '/file/cron/RUNNING file'",
notAmongst: "nicht über",
notApproved: "nicht genehmigt",
notAssignedWork: "nicht zugewiesene Arbeit",
notContains: "enthält nicht",
Note: "Notiz",
noteAdd: "Notiz hinzugefügt",
noteChange: "Notiz geändert",
noteFromEmail: "Notiz als Mail erhalten",
notPlanned: "nicht geplant",
November: "November",
October: "Oktober",
openDays: "offene Tage",
openHours: "offene Stunden",
OperatingSystem: "OS",
operationDelete: "gelöscht",
operationInsert: "eingefügt",
operationUpdate: "aktualisiert",
operatorNotSelected: "Operator ist verpflichtend",
Opportunity: "Chance",
OpportunityType: "Chancentype",
Origin: "Ursprung",
originElement: "Ursprungselement",
originType: "Urspungstyp",
OtherVersion: "Andere Version",
otherVersionAdd: "Andere Version hinzufügen",
otherVersionDelete: "Andere Version löschen",
otherVersionSetMain: "Setze diese Version als Hauptversion",
OverallProgress: "Gesamt Fortschritt",
paramAlertCheckTime: "Verzögerung um Alarme prüfen in Sek.",
paramBillNumSize: "Zahl der Stellen für Rechnungsnummer",
paramBillNumStart: "Startnummer für Rechnungen",
paramBillPrefix: "Vorspann für Rechnungsnummern",
paramBillSuffix: "Anhang für Rechnungsnummern",
paramBrowserLocaleDateFormat: "Format zur Darstellung des Datums",
paramChangeReferenceOnTypeChange: "Ändere Referenz nach Typänderung",
paramConsolidateValidated: "konsolidiere bestätigte Arbeit & Kosten",
paramCronCheckDates: "Verzögerung Erzeugung Alarme in Sek.",
paramCronCheckEmails: "Verzögerung Maileingangprüfung in Sek.",
paramCronCheckEmailsHost: "IMAP host zur Prüfung auf Maileingang",
paramCronCheckEmailsPassword: "IMAP password Maileingang",
paramCronCheckEmailsUser: "IMAP Name Maileingang",
paramCronCheckImport: "Verzögerungen autom. Importe in Sek.",
paramCronDirectory: "CRON Arbeitsverzeichnis",
paramCronImportDirectory: "Verzeichnis automatisch integrierter Dateien",
paramCronImportLogDestination: "Ort für Protokolle",
paramCronImportMailList: "Mailverteiler für Protokolle",
paramCronSleepTime: "Generelle Cron Wartezeit in Sekunden",
paramCsvSeparator: "Trenner für CSV Dateien",
paramCurrency: "Währung",
paramCurrencyPosition: "Position Währungskennzeichens in Kostensicht",
paramDayTime: "Anzahl Stunden pro Tag",
paramDefaultProfile: "Standarprofil bei neuen Nutzern",
paramDefaultProject: "Standard Projekt",
paramDefaultTheme: "Standard Benutzeroberfläche",
paramDisplayAttachement: "Zeige Anhänge",
paramDisplayHistory: "Zeige Historie",
paramDisplayNote: "Zeige Notizen",
paramDisplayOnlyHandled: "Nur 'begonnen' Aufgaben anzeigen",
paramDisplayResourcePlan: "Anzeige Ressourcen im Gantt",
paramDocumentReferenceFormat: "Format Dokumentenreferenz",
paramDocumentRoot: "Wurzelverzeichnis für Dokumente",
paramDontReceiveTeamMails: "Kein Empfang von Team Mails",
paramDraftSeparator: "Trennzeichen für DRAFT im Versionsnamen",
paramEndAM: "Endezeit Vormittag",
paramEndPM: "Endezeit Nachmittag",
paramFilenameCharset: "Zeichensatz für Dateien auf dem Server",
paramGanttPlanningPrintOldStyle: "Drucke Gantt im alten Format",
paramGetVersion: "Prüfung, auf neue Version",
paramHideMenu: "Menü ausblenden",
paramImputationUnit: "Einheit für Ist-Arbeit",
paramInitializePassword: "Passwort-Initialisierung bei neuen Nutzern",
paramLang: "Sprache",
paramLdapDefaultProfile: "Standard-Profil für LDAP Nutzer",
paramLdapMsgOnUserCreation: "Nachricht bei neuen Nutzer durch LDAP",
paramLogFile: "Log Dateiname",
paramLogLevel: "Log Stufe",
paramMaxDaysToBookWork: "Max. Tage um IST-Aufwände zu buchen",
paramMaxItemsInTodayLists: "Maximale Positionen in 'Heute' Ansicht",
paramMaxProjectsToDisplay: "Maximal anzuzeigende Projekte",
paramNone: "keine",
paramParamAdminMail: "E-Mail des Administrators",
paramParamAttachementDirectory: "Verzeichnis für Anhänge",
paramParamAttachementMaxSize: "Maximale Größe für Anhänge",
paramParamConfirmQuit: "Bitte bestätigen Sie die Abmeldung",
paramParamDbDisplayName: "Name der Datenbank",
paramParamDefaultLocale: "Standardsprache",
paramParamDefaultPassword: "Standard Password",
paramParamDefaultTimezone: "Zeitzone",
paramParamFadeLoadingMode: "Anzeige im Überblendmodus",
paramParamIconSize: "Icon Größe im Menü",
paramParamLdap_allow_login: "Verbindung mit LDAP Nutzer",
paramParamLdap_base_dn: "LDAP Basis DN",
paramParamLdap_host: "LDAP Host",
paramParamLdap_port: "LDAP Port",
paramParamLdap_search_pass: "LDAP Password",
paramParamLdap_search_user: "LDAP Nutzer",
paramParamLdap_user_filter: "LDAP Nutzerfilter",
paramParamLdap_version: "LDAP Version",
paramParamLockAfterWrongTries: "lock user after wrong tries",
paramParamMailBodyApprover: "Text für Mails 'Genehmigung von Anforderungen'",
paramParamMailBodyUser: "Text für Mails an Nutzer",
paramParamMailEol: "Zeilenende Format für Mails",
paramParamMailReplyTo: "Antworten an' Mail-Adresse",
paramParamMailReplyToName: "Name Mail-Sender - auch für Antworten",
paramParamMailSender: "Absender' Mail-Adresse",
paramParamMailSendmailPath: "Pfad für 'sendmail'",
paramParamMailSmtpPassword: "SMTP login password",
paramParamMailSmtpPort: "smtp Port",
paramParamMailSmtpServer: "smtp Server",
paramParamMailSmtpUsername: "SMTP login Name",
paramParamMailTitleAnyChange: "Mailtitel für geänderte Zuweisung",
paramParamMailTitleApprover: "Titel für Mails 'Genehmigung von Anforderungen'",
paramParamMailTitleAssignment: "Mailtitel für geänderte Zuweisung",
paramParamMailTitleAssignmentChange: "Mailtitel für geänderte Zuweisung",
paramParamMailTitleAttachment: "Mailtitel für 'hinzugefügte Anhänge'",
paramParamMailTitleDescription: "Mailtitel für geänderte Beschreibungen",
paramParamMailTitleDirect: "Mailtitel, die manuell (Mail Schalter) versandt werden",
paramParamMailTitleNew: "Mailtitel für 'hinzugefügte Elemente'",
paramParamMailTitleNote: "Mailtitel für 'hinzugefügte Notizen'",
paramParamMailTitleNoteChange: "Mailtitel für geänderte Notizen",
paramParamMailTitleResponsible: "Mailtitel für 'geänderte Verantwortliche'",
paramParamMailTitleResult: "Mailtitel für geänderte Ergebnisse",
paramParamMailTitleStatus: "Mailtitel für 'Statusänderungen'",
paramParamMailTitleUser: "Mailtitel an Nutzer",
paramParamMemoryLimitForPDF: "Speicherlimit in MB für PDF-Erstellung",
paramParamPasswordMinLength: "Mindestzahl von Zeichen für das Password",
paramParamReportTempDirectory: "Temporäres Verzeichnis für Berichte",
paramParamTopIconSize: "Größe der Icons in der Top-Menü-Anzeige",
paramPasswordValidityDays: "Passwort Gültigkeit (in Tage)",
paramPdfInNewWindow: "PDF export in neuem Fenster",
paramPreserveUploadedFileName: "Original Dateinamen zusätzlich speichern",
paramPrintHistory: "Druck Historie",
paramPrintInNewWindow: "Druck in neuem Fenster",
paramProjectIndentChar: "Zeichen für Einrückung bei Projekten",
paramRealWorkOnlyForResponsible: "Nur Verantwortlicher arbeitet an Ticket",
paramReferenceFormatNumber: "Anzahl Stellen für Referenznummernzähler",
paramReferenceFormatPrefix: "Präfix Format für Referenz",
paramRefreshUpdates: "Wiederhole Aktualisierung",
paramRememberMe: "Erinnerung' Funktion erlauben",
paramSetHandledOnRealWork: "Aufgabe auf 'begonnen' setzen, wenn Ist-Arbeit erfaßt",
paramSetResponsibleIfNeeded: "Verantwortlichen automatisch setzen, wenn erforderlich",
paramSetResponsibleIfSingle: "Verantwortlichen automatisch setzen, wenn einzige Ressource",
paramStartAM: "Startzeit Vormittag",
paramStartPage: "erste Seite",
paramStartPM: "Startzeit Nachmittag",
paramSwitchedMode: "Umschaltmodus",
paramTheme: "Thema",
paramVersionReferenceSuffix: "Anhang für Versions-Referenz",
paramWorkUnit: "Einheit für Arbeit",
passed: "erfolgreich",
passedTestCaseRun: "Testfall als 'erfolgreich' markieren",
password: "Passwort",
passwordChanged: "Passwort geändert.",
passwordReset: "Passwort zurückgesetzt auf '${1}'.<br/>Bitte sichern, damit die Änderung wirksam wird.",
passwordResetMessage: "Passwort zurückgesetzt auf '${1}'.<br>Sie müssen es bei der ersten Anmeldung ändern.",
Payment: "Zahlung",
PaymentType: "Zahlungstyp",
percent: "%",
periodForTasks: "Zeitraum für Aufgabenauswahl",
periodicEvery: "alle",
periodicFor: "für",
periodicityDaily: "täglich",
periodicityMonthlyDay: "gleicher Tag in jeden Monat",
periodicityMonthlyWeek: "gleiche Woche in jeden Monat",
periodicityWeekly: "gleicher Tag in jeder Woche",
periodicityYearly: "gleicher Tag in jedem Jahr",
PeriodicMeeting: "Regelmäßige Besprechungen",
periodicMonths: "Monate",
periodicOn: "an",
periodicTh: "ste",
periodicTimes: "Wiederholungen",
periodicTo: "bis",
periodicUntil: "bis",
periodicWeeks: "Wochen",
periodScale: "Skala",
planDatesNotSaved: "kein geplantes Datum gespeichert",
planDatesSaved: "geplantes Datum gespeichert",
planDone: "Planung wird kalkuliert in ${1} Sekunden.",
planDoneWithLimits: "Folgende Aufgaben konnten nicht geplant werden, da die Resoucenzuordnung endet :",
planned: "geplant",
PlannedCostOverAssignedCost: "Vergleich geplante Kosten mit zugewiesenen Kosten",
PlannedCostOverValidatedCost: "Vergleich geplante Kosten mit bestätigten Kosten",
plannedEndDate: "Berücksichtige geplantes Endedatum",
plannedStartDate: "Berücksichtige geplantes Startdatum",
PlannedWorkOverAssignedWork: "Geplante Arbeit verglichen mit zugewiesener Arbeit",
PlannedWorkOverValidatedWork: "Geplante Arbeit verglichen mit bestätigter Arbeit",
PlanningModeALAP: "so spät wie möglich",
PlanningModeASAP: "so früh wie möglich",
PlanningModeFDUR: "Feste Dauer",
PlanningModeFIXED: "fester Meilenstein",
PlanningModeFLOAT: "flexibler Meilenstein",
PlanningModeFULL: "normal in ganzen Tagen",
PlanningModeGROUP: "zusammenarbeiten",
PlanningModeHALF: "normal in halben Tagen",
PlanningModeREGUL: "normal zwischen Datum",
planningRight: "Planung kalkulieren",
Predecessor: "Vorgänger",
PredefinedNote: "vordefinierte Notizen",
print: "Druck",
printList: "drucke die Liste",
printPlanning: "drucke die Planung",
Priority: "Priorität",
private: "privat",
Product: "Produkt",
Profile: "Profile",
profileAdministrator: "Administrator",
profileExternalProjectLeader: "Externer Projektleiter",
profileExternalTeamMember: "Externes Projektteammitglied",
profileGuest: "Gastzugang",
profileProjectLeader: "Projektleiter",
profileSupervisor: "Vorgesetzter",
profileTeamMember: "Projektteam",
progress: "Fortschritt",
Project: "Projekt",
ProjectExpense: "Projektaufwand",
ProjectExpenseType: "Projektaufwandstyp",
projectListDisplayMode: "Projektlisten Anzeigemodus",
projects: "Projekte",
projectSelector: "Projekt",
ProjectType: "Projekttyp",
public: "öffentlich",
Quality: "Qualitätslevel",
quarter: "Quartal",
Question: "Frage",
QuestionType: "Fragentyp",
quickSearch: "Suche",
Quotation: "Angebot",
QuotationType: "Angebotstyp",
real: "Ist-Arbeit",
RealWorkOverAssignedWork: "Vergleich Ist-Arbeit mit zugewiesener Arbeit",
RealWorkOverValidatedWork: "Vergleich Ist-Arbeit mit bestätigter Arbeit",
Recipient: "Empfänger",
refreshUpdatesNo: "Nein (nur manuelle Aktualisierung)",
refreshUpdatesYes: "Ja (automatische Aktualisierung)",
rememberMe: "Erinnerung",
rememberMETitle: "Erinnerungsfunktion nicht auf öffentlichen oder unsicheren Computern nutzen",
remind: "erinnern",
remindMeIn: "erinnere mich in",
removeAffectation: "lösche diese Ressourcenzuordnung",
removeAllFilters: "lösche alle Filterkriterien",
removeApprover: "Lösche Genehmiger",
removeAssignment: "lösche diese Zuordnung",
removeAttachement: "lösche Anhang",
removeDependency: "lösche diese Abhängigkeit",
removeDependencyPredecessor: "lösche diesen Vorgänger",
removeDependencySuccessor: "lösche diesen Nachfolger",
removeDocumentVersion: "Lösche diese Version",
removeExpenseDetail: "lösche Aufwandsdetail",
removeFilter: "lösche diese Filterkriterien",
removeLine: "Lösche diese Zeile",
removeLink: "lösche dieses verbundenene Element",
removeNote: "lösche diese Notiz",
removeOrigin: "lösche Ursprung",
removePhoto: "Foto löschen",
removeResourceCost: "lösche diese Ressourcekosten",
removeStoredFilter: "lösche diesen gespeicherten Filter",
removeTestCaseRun: "Testfall löschen",
removeVersionProject: "lösche Verbindung zwischen Version und Projekt",
reportAudit: "Verbindungsprüfung",
reportAvailabilityPlan: "Ressourcenverfügbarkeit - monatlich",
reportAvailabilitySynthesis: "verfügbare Übersichten",
reportBill: "Rechnungen",
reportCategoryBill: "Fakturierung",
reportCategoryCost: "Kosten",
reportCategoryHistory: "Historie",
reportCategoryMisc: "Verschiedenes",
reportCategoryPlan: "Planung",
reportCategoryRequirementTest: "Anforderungen & Tests",
reportCategoryStatus: "Aktueller Status",
reportCategoryTicket: "Tickets",
reportCategoryWork: "Arbeit",
reportCostDetail: "Kostenübersicht je Aktivität",
reportCostMonthly: "Monatliche Kosten",
reportExpenseCostTotal: "Gesamtaufwand und -kosten - monatlich",
reportExpenseProject: "Projektaufwand - monatlich",
reportExpenseResource: "Individueller Aufwand - monatlich",
reportExpenseTotal: "Gesamtaufwand - monatlich",
reportExportMSProject: "Export MS-Project XML Format",
reportFacture: "Rechnungen",
reportGlobalWorkPlanningMonthly: "Arbeitsplan - monatlich",
reportGlobalWorkPlanningWeekly: "Arbeitsplan - wöchentlich",
reportHistoryDetail: "Historie für ein Element",
reportHistoryDeteled: "Gelöschte Positionen",
reportNoData: "Keine Daten zur Anzeige verfügbar",
reportOpportunityPlan: "Chancen Plan",
reportPlanActivityMonthly: "Planung Projekten/Aktivitäten/Ressourcen - monatlich",
reportPlanColoredMonthly: "Ressourcenplanung - in Farbe - monatlich",
reportPlanDetail: "Aktivitätenplanung - detailliert - monatlich",
reportPlanGantt: "Gantt",
reportPlannedDates: "Sichere geplantes Datum in",
reportPlanProjectMonthly: "Projektplanung - detailliert - monatlich",
reportPlanResourceMonthly: "Ressourcenplanung - detailliert - monatlich",
reportPortfolioGantt: "Portfolio Ganttplanung",
reportPrint: "Drucke Bericht",
reportPrintCsv: "Export im CSV Format",
reportPrintPdf: "Export im PDF Format",
reportProductTest: "Test Produktabdeckung",
reportProductTestDetail: "Testfall Details",
reportProject: "Projekt Dashboard",
reportRequirementTest: "Test Anforderungsabdeckung",
reportRiskManagementPlan: "Risiko Management Plan",
Reports: "Berichte",
reportShow: "Bericht anzeigen",
reportStatusAll: "Status der gesamten Arbeit",
reportStatusOngoing: "Status der laufenden Arbeit",
reportTermMonthly: "Monatliche Konditionen",
reportTermTitle: "Setze Stichtage für Periode",
reportTermWeekly: "Wöchentliche Konditionen",
reportTestSession: "Testplan Zusammenfassung",
reportTicketGlobalCrossReport: "Tickets - je Qualifikation - gesamt",
reportTicketGlobalSynthesis: "Tickets - offen - gesamt",
reportTicketMonthlyCrossReport: "Tickets - je Qualifikation - monatlich",
reportTicketMonthlySynthesis: "Tickets - offen - monatlich",
reportTicketWeeklyCrossReport: "Tickets - je Qualifikation - wöchentlich",
reportTicketWeeklySynthesis: "Tickets - offen - wöchentlich",
reportTicketYearly: "Tickets - jährlich",
reportTicketYearlyByType: "Tickets - je Typ - jährlich",
reportTicketYearlyCrossReport: "Tickets - je Qualifikation - jährlich",
reportTicketYearlySynthesis: "Tickets - offen - jährlich",
reportVersionDetail: "Versionsdetails",
reportVersionStatus: "Versionsstatus",
reportWorkDetailMonthly: "Arbeit - detailliert - je Ressource - monatlich",
reportWorkDetailWeekly: "Arbeit - detailliert - je Ressource - wöchentlich",
reportWorkDetailYearly: "Arbeit - detailliert - je Ressource - jährlich",
reportWorkMonthly: "Arbeit - monatlich",
reportWorkPerActivity: "Arbeitsübersicht je Aktivität",
reportWorkPlan: "Arbeitsübersicht je Aktivität",
reportWorkWeekly: "Arbeit - wöchentlich",
reportWorkYearly: "Arbeit - jährlich",
Requirement: "Anforderung",
RequirementType: "Anforderungstyp",
requirementUnlockRight: "Entsperre alle Anforderungen",
resetColor: "zurücksetzen",
resetPassword: "Passwort zurücksetzen",
Resource: "Ressource",
ResourceCost: "Ressourcekosten",
resourcePlanningRight: "Zugriff auf Ressourcenplanung für andere",
resources: "Ressourcen",
responsibleChange: "Änderung des Verantwortlichen",
resultChange: "Ergebnis geändert",
resultClosed: "geschlossen",
resultCopied: "kopiert als",
resultDeleted: "gelöscht",
resultError: "Elemente mit Fehler",
resultInserted: "eingefügt",
resultOk: "Elemente geändert",
resultSave: "gesichert",
resultUpdated: "geändert",
resultWarning: "Elemente nicht geändert",
rightClickToCopy: "Rechts click und Kopierlink wählen oder click and [CTRL]+C um den Direktlink dieses Objektes zu kopieren",
Risk: "Risiko",
RiskLevel: "Risiko Ebene",
RiskType: "Risikotyp",
Role: "Funktion",
run: "Start",
running: "läuft",
Saturday: "Samstag",
saveDates: "sichere die Daten",
saveFilter: "Sichere diesen Filter",
savePlannedDates: "speichere geplantes Datum in gefordertes und bestätigtes Datum",
second: "Sekunde",
sectionAbacus: "Rechenhilfe",
sectionActiveFilter: "Aktiver Filter",
sectionAddress: "Adresses",
sectionAffectations: "Ressourcenzuordnungen",
sectionAlerts: "Alarm Verwaltung",
sectionAnswer: "Antwort",
sectionApprovers: "Genehmiger",
sectionAssignment: "Zuordnung",
sectionAssignmentManagement: "Zuweisungsmanagement",
sectionAttachements: "Anhänge",
sectionBehavior: "Verhalten",
sectionBilling: "Rechnungsstellung",
sectionBillLines: "Rechnungspositionen",
sectionButtons: "Schalter anzeigen",
sectionCalendar: "Kalendertage",
sectionChecklistLines: "Checklistenzeilen",
sectionComboDetail: "Schalter anzeigen 'Detail-Kombinationen'",
sectionConnectionStatus: "Verbindungsstatus",
sectionContacts: "Kontakte",
sectionCron: "Steuerung automatisierte Services (CRON)",
sectionDailyHours: "Tägliche Arbeitszeit",
sectionDates: "Datum",
sectionDebug: "Fehlersuche",
sectionDescription: "Beschreibung",
sectionDetail: "Detail",
sectionDisplay: "Anzeige",
sectionDisplayParameter: "Anzeige-Parameter",
sectionDocument: "Dokument",
sectionDocumentUnlock: "Dokument entsperren",
sectionFiles: "Dateien und Verzeichnisse",
sectionFunctionCost: "Funktion & Kosten",
sectionIBAN: "Internationale Bank-Konto-Nummer (IBAN)",
sectionIHM: "Standard-Bildschirmanzeige",
sectionImputation: "Ist-Arbeit-Buchung",
sectionImputationDiary: "Ist-Arbeit-Buchung und Terminkalender",
sectionInternalAlert: "Empfänger interner Alarme",
sectionLdap: "LDAP Verwaltung der Parameter",
sectionLink: "verbundenes Element",
sectionLinkAction: "verbundene Aktion",
sectionLinkDecision: "gefällte Entscheidungen",
sectionLinkIssue: "verbundene Probleme",
sectionLinkMeeting: "diskutiert in Besprechung",
sectionLinkQuestion: "neue oder gelöste Fragen",
sectionLinkRisk: "verbundene Risiken",
sectionLocalization: "Lokale Einstellung",
sectionLock: "Sperre",
sectionMail: "E-Mail-Versand",
sectionMailDescription: "Mailbeschreibung",
sectionMailItem: "betroffener Punkt",
sectionMailText: "Text des Mails",
sectionMailTitle: "Haupttitel",
sectionMembers: "Teammitglieder",
sectionMessage: "Meldung",
sectionMiscellaneous: "Verschiedenes",
sectionNotes: "Notizen",
sectionObjectDetail: "Details der Elemente",
sectionPassword: "Password",
sectionPeriodicity: "Wiederholung",
sectionPlanning: "Planung",
sectionPlanningRight: "Planungskalkulation",
sectionPredecessor: "Vorgänger Element",
sectionPrice: "Festpreis",
sectionPrintExport: "Druck & Export Parameter",
sectionProgress: "Fortschritt",
sectionProjects: "Projekte",
sectionReferenceFormat: "Format für Referenznummerierung",
sectionResponsible: "Verantwortliche",
sectionSendMail: "Mailadresse",
sectionStoredFilters: "Gespeicherte Filter",
sectionSubprojects: "Teilprojekte",
sectionSuccessor: "Nachfolger Element",
sectionTestCaseRun: "Testfall-Durchläufe",
sectionTreatment: "Behandlung",
sectionTrigger: "Auslöserelement für diese Kondition",
sectionUnlock: "Entsperre Positionen",
sectionUserAndPassword: "Nutzer und Passwort",
sectionValidation: "Überprüfung",
sectionVersion: "Versionen",
sectionVersionproject_projects: "verbundene Projekte",
sectionVersionproject_versions: "verbundenene Versionen",
sectionVersions: "Produkt Versionen",
sectionWorkCost: "Arbeit und Kosten anzeigen",
sectionWorkflowDiagram: "Workflow Diagramm",
sectionWorkflowStatus: "Vorgaben für Änderungen von einem zum anderen Status",
sectionWorkUnit: "Einheit für Arbeit",
sectionYear: "Jahr",
selectedItemsCount: "Anzahl gewählter Elemente",
selectProjectToPlan: "Sie müssen ein Projekt wählen",
selectStoredFilter: "Wähle diesen gespeicherten Filter",
send: "Senden",
sendAlert: "Sende einen internen Alarm",
sendInfoToApprovers: "Erinnerungs-Mail an Genehmiger schicken",
sendInfoToUser: "Sende Informationen zum Nutzer",
sendMailToAttendees: "E-Mail-Einladung",
sendToPrinter: "Sende Dokument zum Drucker",
sentAlertTo: "Alarm versandt an ${1} Nutzer",
sentSinceMore: "versandt vor mehr als",
September: "September",
sequential: "sequenziell",
setApplicationToClosed: "Schließe Applikation",
setApplicationToOpen: "Starte Applikation",
Severity: "Auswirkung",
shortDay: "T",
shortHour: "S",
shortMinute: "Mn",
shortMonth: "M",
shortQuarter: "Q",
shortSecond: "S",
shortWeek: "W",
shortYear: "J",
showDetail: "Suche / Anzeige",
showDirectAccess: "Gehe zu diesem Element",
showIdleElements: "Zeige inaktive Elemente",
showInToday: "Füge Report zu Heute-Übersicht",
showLeftWork: "Zeige offene Arbeit rechts des Ganttbalkens",
showPlannedWork: "Zeige geplante Arbeit",
showProjectLevel: "Zeige Projektebene über Aktivitäten",
showResources: "Zeige Ressourcen rechts vom Ganttbalken",
showWbs: "Zeige PSP mit Namen",
Software: "Software",
sortAsc: "aufsteigend",
sortDesc: "absteigend",
sortFilter: "sortieren",
sqlError: "SQL Fehler",
startWork: "Starte Arbeit",
Status: "Status",
StatusMail: "Mail nach Statusänderung",
statusMustChangeCancelled: "'abgebrochen' muss durch Statusänderung erfolgen",
statusMustChangeDone: "'erledigt' muss durch Statusänderung erfolgen",
statusMustChangeHandled: "'bearbeitet' muss durch Statusänderung erfolgen",
statusMustChangeIdle: "'abgeschlossen' muss durch Statusänderung erfolgen",
stop: "Stopp",
stopped: "gestoppt",
stopWork: "Stoppe Arbeit",
storedFilters: "Gespeicherte Filter",
submittedWorkPeriod: "abgegeben am <br/>${1}",
submitWorkPeriod: "Ist-Arbeit melden",
subProjects: "Teilprojekte",
Successor: "Nachfolger",
sum: "Summe",
Sunday: "Sonntag",
targetValue: "Zielwert",
Team: "Team",
team: "Team",
Term: "Kondition",
TestCase: "Testfall",
TestCaseRun: "Testfall-Durchlauf",
TestCaseType: "Testfalltyp",
TestSession: "Testplan",
TestSessionType: "Testplantyp",
themeBlue: "dunkelblau",
themeBlueContrast: "kontrastierendes blau",
themeBlueLight: "hellblau",
themeGreen: "dunkelgrün",
themeGreenContrast: "kontrastierendes grün",
themeGreenLight: "hellgrün",
themeGrey: "dunkelgrau",
themeGreyContrast: "kontrastierendes grau",
themeGreyLight: "hellgrau",
themeOrange: "dunkelorange",
themeOrangeContrast: "kontrastierendes orange",
themeOrangeLight: "hellorange",
themeProjectom: "Projectom",
themeProjectOrRIA: "ProjecQtOr",
themeProjectOrRIAContrasted: "ProjecQtOr kontrastierend",
themeProjectOrRIALight: "ProjecQtOr hell",
themeProjeQtOr: "ProjeQtOr",
themeProjeQtOrDark: "ProjeQtOr Dark",
themeProjeQtOrEarth: "ProjeQtOr Earth",
themeProjeQtOrFire: "ProjeQtOr Fire",
themeProjeQtOrForest: "ProjeQtOr Forest",
themeProjeQtOrLight: "ProjeQtOr Light",
themeProjeQtOrWater: "ProjeQtOr Water",
themeProjeQtOrWine: "ProjeQtOr Wine",
themeRandom: "zufällig",
themeRed: "dunkelrot",
themeRedContrast: "kontrastierendes rot",
themeRedLight: "hellrot",
themeWhite: "schwarz & weiß",
Thursday: "Donnerstag",
Ticket: "Ticket",
TicketDelay: "Verspätung für Tickets",
TicketSimple: "Ticket",
TicketType: "Tickettyp",
titleCountAll: "alle",
titleCountNotClosed: "nicht geschlossen",
titleCountScope: "Bereich gezählte Elemente:",
titleCountTodo: "zu erledigen",
titleNbAll: "gesamt",
titleNbClosed: "geschlossen",
titleNbDone: "erledigt",
titleNbTodo: "zu erledigen",
titleResetList: "Setze Anzeige auf Standard zurück",
to: "an",
today: "Heute",
Today: "Element von Heute-Übersicht",
todayAssignedTasks: "Aufgabe zugewiesen an",
todayIs: "Heute ist",
todayIssuerRequestorTasks: "Aussteller oder Anforderer der Arbeit",
todayProjects: "Projekte",
todayProjectsTasks: "Alle Projekt-Arbeiten zugewiesen an",
todayResponsibleTasks: "Verantwortlicher d. Arbeit",
Trend: "Trend",
Tuesday: "Dienstag",
undefinedValue: "nicht definiert",
unlockDocument: "Entsperre Dokument",
unlockRequirement: "Entsperre Anforderung",
unSubmitWorkPeriod: "Ist-Arbeit zurückziehen",
unValidateWorkPeriod: "Ist-Arbeit ablehnen",
updatedReference: "Referenz für Element '${1}' geändert",
updateInitialDates: "gefordertes Datum",
updateReference: "Ändere Referenz für",
updateValidatedDates: "bestätigtes Datum",
Urgency: "Dringlichkeit",
User: "Nutzer",
userMailMessage: "Ihre Anmeldung zu ProjecQtOr ist '${1}'.<br/>${2}<br/>Bei Problemen wenden Sie sich bitte an Ihren Administrator ${3}.",
userMailTitle: "[ProjecQtOr Meldung] Ihre Zugangsdaten",
validatedEndDate: "Berücksichtige bestätigtes Endedatum",
validatedStartDate: "Berücksichtige bestätigtes Startdatum",
validatedWorkPeriod: "geprüft durch ${2} am <br/>${1}",
validatePassword: "Überprüfen Sie Ihr Passwort",
validateWorkPeriod: "Arbeit gutheißen",
valueNotSelected: "Wert kann nicht leer sein",
Version: "Version",
versionDraftUpdate: "Entwurf",
versionMajorUpdate: "wesentlich",
versionMinorUpdate: "geringfügig",
versionNoUpdate: "kein",
VersionProject: "Verbindung Projekt-Version",
versions: "Versionen",
visibilityScopeAll: "Alle sichtbaren",
visibilityScopeNo: "Keine anzeigen",
visibilityScopeValid: "Nur bestätigte anzeigen",
WARNING: "Warnung",
warningValue: "Warnungswert",
Wednesday: "Mittwoch",
week: "Woche",
welcomeMessage: "Willkommen",
Work: "Arbeit",
workAccess: "Arbeit anzeigen",
Workflow: "Workflow",
workflowParameters: "Wähle Status anzeigen / ausblenden",
workStarted: "Arbeit gestartet",
workStartedAt: "gestartet um ${1}",
workStartedBy: "gestartet durch ${1}",
workStartedSince: "gestartet seit ${1} Tag(en)",
workStopped: "Arbeit gestoppt",
workValidate: "Ist-Arbeit gutheißen",
wrongMaintenanceUser: "Upgrade wird gerade durchgeführt.<br/>Nur der Administrator kann sich verbinden.",
xlsxFile: "xlsx Datei (Excel 2010)",
year: "Jahr",
currentLocaleOfFile: "de"
}
| nikochan2k/projeqtor-ja | tool/i18n/nls/de/lang.js | JavaScript | gpl-3.0 | 84,654 |
<?php
/**
*
* @package mahara
* @subpackage dwoo
* @author Catalyst IT Ltd
* @author Jordi Boggiano <j.boggiano@seld.be>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
* @copyright For copyright information on Mahara, please see the README file distributed with this software.
*/
/**
* This class is a Dwoo ITemplate class. It acts as a pass-through to the standard
* Dwoo_Template_File class, which reads template files. What this class does is take
* a template specifier for a Mahara plugin's template file, like
* "blocktype:creativecommons:statement.tpl", and translate that into the relative path
* to the template (statement.tpl) and say which directories to search for this relative
* path in.
*
* The actual code that translates the Dwoo identifier into a relative filesystem path, is in the
* "get_theme_path()" method in the plugin type's class. Most plugin types will not need to customize
* this and can simply inherit the implementation from Plugin. If the plugin can also have template
* files that live outside of the {$plugintype}/{$pluginname} directory, then it will need to provide
* its own implementation of get_theme_path().
*/
namespace Mahara;
require __DIR__ . '/../vendor/autoload.php';
use Dwoo\Template\File as File;
class Dwoo_Template_Mahara extends File {
/**
* Convert a Mahara plugin template file path into a normal template file path with extra search paths.
*
* @param string $pluginfile The plugintype, name, and name of file, e.g. "blocktype:clippy:index.tpl"
* @param int $cacheTime Not used.
* @param int $cacheId Not used.
* @param int $compileId Not used.
* @param array $includePath The paths to look in.
* @throws MaharaException
*/
public function __construct($file, $cacheTime = null, $cacheId = null, $compileId = null, $includePath = null) {
global $THEME;
$parts = explode(':', $file, 3);
if (count($parts) !== 3) {
throw new SystemException("Invalid template path \"{$file}\"");
}
// Keep the original string for logging purposes
$dwooref = $file;
list($plugintype, $pluginname, $file) = $parts;
// Since we use $plugintype as part of a file path, we should whitelist it
$plugintype = strtolower($plugintype);
if (!in_array($plugintype, plugin_types())) {
throw new SystemException("Invalid plugintype in Dwoo template \"{$dwooref}\"");
}
// Get the relative path for this particular plugin
require_once(get_config('docroot') . $plugintype . '/lib.php');
$pluginpath = call_static_method(generate_class_name($plugintype), 'get_theme_path', $pluginname);
// Because this is a plugin template file, we don't want to include any accidental matches against
// core template files with the same name.
$includePath = array();
// First look for a local override.
$includePath[] = get_config('docroot') . "local/theme/plugintype/{$pluginpath}/templates";
// Then look for files in a custom theme
foreach ($THEME->inheritance as $theme) {
$includePath[] = get_config('docroot') . "theme/{$theme}/plugintype/{$pluginpath}/templates";
}
// Lastly look for files in the plugin itself
foreach ($THEME->inheritance as $theme) {
$includePath[] = get_config('docroot') . "{$pluginpath}/theme/{$theme}/templates";
// For legacy purposes also look for the template file loose under the theme directory.
$includePath[] = get_config('docroot') . "{$pluginpath}/theme/{$theme}";
}
// Now, we instantiate this as a standard Dwoo_Template_File class.
// We're passing in $file, which is the relative path to the file, and
// $includePath, which is an array of directories to search for $file in.
// We let Dwoo figure out which one actually has it.
parent::__construct($file, null, null, null, $includePath);
}
}
| MaharaProject/mahara | htdocs/lib/dwoo/mahara/Dwoo_Template_Mahara.php | PHP | gpl-3.0 | 4,089 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration | Version: 3.2
\\ / A nd | Web: http://www.foam-extend.org
\\/ M anipulation | For copyright notice see file Copyright
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend 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.
foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "wedgeFaPatch.H"
#include "wedgeFaPatchField.H"
#include "transformField.H"
#include "symmTransform.H"
#include "diagTensor.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
template<class Type>
wedgeFaPatchField<Type>::wedgeFaPatchField
(
const faPatch& p,
const DimensionedField<Type, areaMesh>& iF
)
:
transformFaPatchField<Type>(p, iF)
{}
template<class Type>
wedgeFaPatchField<Type>::wedgeFaPatchField
(
const wedgeFaPatchField<Type>& ptf,
const faPatch& p,
const DimensionedField<Type, areaMesh>& iF,
const faPatchFieldMapper& mapper
)
:
transformFaPatchField<Type>(ptf, p, iF, mapper)
{
if (!isType<wedgeFaPatch>(this->patch()))
{
FatalErrorIn
(
"wedgeFaPatchField<Type>::wedgeFaPatchField\n"
"(\n"
" const wedgeFaPatchField<Type>& ptf,\n"
" const faPatch& p,\n"
" const Field<Type>& iF,\n"
" const faPatchFieldMapper& mapper\n"
")\n"
) << "Field type does not correspond to patch type for patch "
<< this->patch().index() << "." << endl
<< "Field type: " << typeName << endl
<< "Patch type: " << this->patch().type()
<< exit(FatalError);
}
}
template<class Type>
wedgeFaPatchField<Type>::wedgeFaPatchField
(
const faPatch& p,
const DimensionedField<Type, areaMesh>& iF,
const dictionary& dict
)
:
transformFaPatchField<Type>(p, iF, dict)
{
if (!isType<wedgeFaPatch>(p))
{
FatalIOErrorIn
(
"wedgeFaPatchField<Type>::wedgeFaPatchField\n"
"(\n"
" const faPatch& p,\n"
" const Field<Type>& field,\n"
" dictionary& dict\n"
")\n",
dict
) << "patch " << this->patch().index() << " not wedge type. "
<< "Patch type = " << p.type()
<< exit(FatalIOError);
}
this->evaluate();
}
template<class Type>
wedgeFaPatchField<Type>::wedgeFaPatchField
(
const wedgeFaPatchField<Type>& ptf,
const DimensionedField<Type, areaMesh>& iF
)
:
transformFaPatchField<Type>(ptf, iF)
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
// Return gradient at boundary
template<class Type>
tmp<Field<Type> > wedgeFaPatchField<Type>::snGrad() const
{
Field<Type> pif = this->patchInternalField();
return
(
transform(refCast<const wedgeFaPatch>(this->patch()).faceT(), pif)
- pif
)*(0.5*this->patch().deltaCoeffs());
}
// Evaluate the patch field
template<class Type>
void wedgeFaPatchField<Type>::evaluate(const Pstream::commsTypes)
{
if (!this->updated())
{
this->updateCoeffs();
}
faPatchField<Type>::operator==
(
transform
(
refCast<const wedgeFaPatch>(this->patch()).edgeT(),
this->patchInternalField()
)
);
}
// Return defining fields
template<class Type>
tmp<Field<Type> > wedgeFaPatchField<Type>::snGradTransformDiag() const
{
const diagTensor diagT =
0.5*diag(I - refCast<const wedgeFaPatch>(this->patch()).faceT());
const vector diagV(diagT.xx(), diagT.yy(), diagT.zz());
return tmp<Field<Type> >
(
new Field<Type>
(
this->size(),
transformMask<Type>
(
pow
(
diagV,
pTraits<typename powProduct<vector, pTraits<Type>::rank>
::type>::zero
)
)
)
);
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// ************************************************************************* //
| Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2 | src/finiteArea/fields/faPatchFields/constraint/wedge/wedgeFaPatchField.C | C++ | gpl-3.0 | 5,145 |
package rprogn.callables.stack;
import rprogn.callables.Callable;
import rprogn.functions.Scope;
import rprogn.interpreter.Interpreter;
import rprogn.variable.Var;
import rprogn.variable.VarStack;
public class CallablePush implements Callable {
@Override
public void Call(Interpreter interpreter, Scope scope) {
Var a = interpreter.pop();
Var b = interpreter.pop();
if(!(a instanceof VarStack) && b instanceof VarStack){
Var c = a;
a = b;
b = c;
}
if(a instanceof VarStack){
VarStack stack = (VarStack) a;
stack.push(b);
}
}
@Override
public String describe() {
return "Push a value to a stack.";
}
}
| TehFlaminTaco/RProgN-2 | source/src/rprogn/callables/stack/CallablePush.java | Java | gpl-3.0 | 641 |
/*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2015 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.application.server;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.wandora.application.Wandora;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMapException;
/**
*
* @author akivela
*/
public class WebAppHelper {
public static Topic getRequestTopic(WandoraWebAppServer server, String target, HttpServletRequest request, HttpServletResponse response) throws TopicMapException {
Wandora wandora=server.getWandora();
Topic topic=null;
String si=request.getParameter("topic");
if(si==null || si.length()==0) si=request.getParameter("si");
if(si==null || si.length()==0) {
String sl=request.getParameter("sl");
if(sl==null || sl.length()==0){
topic=wandora.getOpenTopic();
if(topic==null){
server.writeResponse(response,HttpServletResponse.SC_NOT_FOUND,"404 Not Found<br />Wandora application does not have any topic open and no topic is specified in http parameters.");
}
}
else{
topic=wandora.getTopicMap().getTopicBySubjectLocator(sl);
if(topic==null) {
server.writeResponse(response,HttpServletResponse.SC_NOT_FOUND,"404 Not Found<br />Topic with subject locator "+sl+" not found.");
}
}
}
else {
topic=wandora.getTopicMap().getTopic(si);
if(topic==null) {
topic = wandora.getTopicMap().getTopicWithBaseName(si);
}
if(topic==null) {
server.writeResponse(response,HttpServletResponse.SC_NOT_FOUND,"404 Not Found<br />Topic with subject identifier "+si+" not found.");
}
}
return topic;
}
}
| Anisorf/ENCODE | encode/src/org/wandora/application/server/WebAppHelper.java | Java | gpl-3.0 | 2,691 |
package domain.dao;
import java.sql.Timestamp;
import java.util.Date;
import javax.persistence.ParameterMode;
import javax.persistence.Query;
import javax.persistence.StoredProcedureQuery;
import org.hibernate.Session;
import hibernate.HibernateConnection;
/**
* The Class DAOSimulator.
*/
public class DAOSimulator {
/** The Constant STRING_PLANE_ID. */
private static final String STRING_PLANE_ID = "planeId";
/** The Constant STRING_AIRPORT_ID. */
private static final String STRING_AIRPORT_ID = "airportId";
/** The Constant STRING_CORRECT_DATE. */
private static final String STRING_CORRECT_DATE = "correctDate";
/** The Constant SECOND_TO_MIN. */
private static final int SECOND_TO_MIN = 60;
/** The Constant MILIS_TO_SECOND. */
private static final int MILIS_TO_SECOND = 1000;
/** The Constant MIN_TO_HOURS. */
private static final int MIN_TO_HOURS = 60;
/** The Constant HOURS_TO_DAY. */
private static final int HOURS_TO_DAY = 24;
/** The Constant WEEK_MARGIN. */
private static final int WEEK_MARGIN = 7 + 1;
/** The Constant MILIS_TO_DAYS. */
private static final int MILIS_TO_DAYS = MILIS_TO_SECOND * SECOND_TO_MIN * MIN_TO_HOURS * HOURS_TO_DAY;
/** The Constant PARAMETER_AIRPORT_ID. */
private static final String PARAMETER_AIRPORT_ID = STRING_AIRPORT_ID;
/** The Constant PARAMETER_MARGIN_WEEK. */
private static final String PARAMETER_MARGIN_WEEK = "marginWeek";
/** The Constant QUERY_COUNT_FLIGHTS_IN_WEEK. */
private static final String QUERY_COUNT_FLIGHTS_IN_WEEK = "select COUNT(f) from Flight as f "
+ "where (f.expectedDepartureDate BETWEEN current_date and :" + PARAMETER_MARGIN_WEEK
+ " and f.route.departureTerminal.airport.id = :" + PARAMETER_AIRPORT_ID + " ) "
+ "or (f.expectedArrivalDate BETWEEN current_date and :" + PARAMETER_MARGIN_WEEK
+ " and f.route.arrivalTerminal.airport.id = :" + PARAMETER_AIRPORT_ID + " )";
/** The session. */
private static Session session;
/**
* Gets the number of flights in A week from airport.
*
* @param airportId
* the airport id
* @return the number of flights in A week from airport
*/
public static Long getNumberOfFlightsInAWeekFromAirport(int airportId) {
Long numFlights = null;
Date soon = new Date();
try {
session = HibernateConnection.getSession();
Query query = session.createQuery(QUERY_COUNT_FLIGHTS_IN_WEEK);
query.setParameter(PARAMETER_AIRPORT_ID, airportId);
query.setParameter(PARAMETER_MARGIN_WEEK, new Date(soon.getTime() + (MILIS_TO_DAYS * WEEK_MARGIN)));
numFlights = (Long) query.getSingleResult();
} catch (Exception e) {
e.printStackTrace();
} finally {
HibernateConnection.closeSession(session);
}
return numFlights;
}
/**
* Gets the correct date from schedule.
*
* @param planeId
* the plane id
* @param airportId
* the airport id
* @return the correct date from schedule
*/
public static Date getCorrectDateFromSchedule(int planeId, int airportId) {
Date date = null;
try {
session = HibernateConnection.getSession();
StoredProcedureQuery query = session.createStoredProcedureQuery("selectDate")
.registerStoredProcedureParameter(STRING_PLANE_ID, Integer.class, ParameterMode.IN)
.registerStoredProcedureParameter(STRING_AIRPORT_ID, Integer.class, ParameterMode.IN)
.registerStoredProcedureParameter(STRING_CORRECT_DATE, Timestamp.class, ParameterMode.OUT)
.setParameter(STRING_PLANE_ID, planeId).setParameter(STRING_AIRPORT_ID, airportId);
query.execute();
date = (Timestamp) query.getOutputParameterValue(STRING_CORRECT_DATE);
} catch (Exception e) {
e.printStackTrace();
} finally {
HibernateConnection.closeSession(session);
}
return date;
}
}
| Maracars/POPBL5 | src/domain/dao/DAOSimulator.java | Java | gpl-3.0 | 3,764 |
/****************************************************************************
** Copyright (C) 2014-2017 Dream IP
**
** This file is part of GPStudio.
**
** GPStudio is a 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 "pdfviewer.h"
#include <QDebug>
#include <QUrl>
#include <QDesktopServices>
#include <QMessageBox>
#include <QFile>
void PdfViewer::showDocument(const QString &file)
{
if(!QFile::exists(file))
{
QMessageBox::warning(NULL, "Documentation file does not exist.", "Documentation file does not exist.");
return;
}
QUrl pdfUrl(file);
QDesktopServices::openUrl(pdfUrl);
}
| DreamIP/GPStudio | gui-tools/src/gpstudio_gui/viewer/viewerwidgets/pdfviewer.cpp | C++ | gpl-3.0 | 1,292 |
# Generated by Django 2.0 on 2018-02-26 22:11
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('CreateYourLaws', '0012_codeblock_is_cdp'),
]
operations = [
migrations.RenameField(
model_name='codeblock',
old_name='is_cdp',
new_name='is_cbp',
),
]
| denisjul/democratos | democratos/CreateYourLaws/migrations/0013_auto_20180226_2211.py | Python | gpl-3.0 | 369 |
/**
* @file mirror/pre_registered/default.hpp
* @brief Pre-registration of the default set of namespace, types,
* classes, etc. with Mirror
*
* Copyright 2008-2010 Matus Chochlik. Distributed under the Boost
* Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef MIRROR_PRE_REGISTERED_DEFAULT_1012140609_HPP
#define MIRROR_PRE_REGISTERED_DEFAULT_1012140609_HPP
// namespaces
#include <mirror/pre_registered/namespace/std.hpp>
#include <mirror/pre_registered/namespace/boost.hpp>
#include <mirror/pre_registered/namespace/mirror.hpp>
// Native C/C++ types
#include <mirror/pre_registered/type/native.hpp>
// std::basic_string's
#include <mirror/pre_registered/type/std/string.hpp>
// std::pair template
#include <mirror/pre_registered/type/std/pair.hpp>
// std::tuple template
#include <mirror/pre_registered/type/std/tuple.hpp>
//
#include <mirror/pre_registered/type/std/initializer_list.hpp>
#include <mirror/pre_registered/type/std/allocator.hpp>
#include <mirror/pre_registered/type/std/memory.hpp>
#include <mirror/pre_registered/type/std/functional.hpp>
#include <mirror/pre_registered/type/std/vector.hpp>
#include <mirror/pre_registered/type/std/list.hpp>
#include <mirror/pre_registered/type/std/deque.hpp>
#include <mirror/pre_registered/type/std/map.hpp>
#include <mirror/pre_registered/type/std/set.hpp>
//
// std::tm structure
#include <mirror/pre_registered/class/std/tm.hpp>
#endif //include guard
| firestarter/firestarter | redist/mirror-lib/mirror/pre_registered/default.hpp | C++ | gpl-3.0 | 1,508 |
/*
Sqlmake http://code.google.com/p/sqlmake/
Copyright © 2010-2012 Mitja Golouh
This file is part of Sqlmake.
Sqlmake is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Sqlmake is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Sqlmake. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.IO;
using SQLMake;
namespace SQLMakeTest
{
[TestFixture]
class SQLPlusScannerDropStatementsTest
{
[Test]
public void DropClusterTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropCluster"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropCluster");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("CLUSTER", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("PERSONNEL", scanner.currCommand.objectName);
}
[Test]
public void DropContextTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropContext"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropContext");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("CONTEXT", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("HR_CONTEXT", scanner.currCommand.objectName);
}
[Test]
public void DropDatabaseTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropDatabase"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropDatabase");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("DATABASE", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
}
[Test]
public void DropDatabaseLinkTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropDatabaseLink"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropDatabaseLink");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("DATABASE LINK", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("REMOTE", scanner.currCommand.objectName);
}
[Test]
public void DropPublicDatabaseLinkTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropPublicDatabaseLink"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropPublicDatabaseLink");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("PUBLIC DATABASE LINK", scanner.currCommand.cmdName);
Assert.AreEqual("DATABASE LINK", scanner.currCommand.baseCmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("REMOTE", scanner.currCommand.objectName);
}
[Test]
public void DropDimensionTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropDimension"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropDimension");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("DIMENSION", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("CUSTOMERS_DIM", scanner.currCommand.objectName);
}
[Test]
public void DropDirectoryTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropDirectory"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropDirectory");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("DIRECTORY", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("BFILE_DIR", scanner.currCommand.objectName);
}
[Test]
public void DropDiskgroupTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropDiskgroup"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropDiskgroup");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("DISKGROUP", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("DGROUP_01", scanner.currCommand.objectName);
}
[Test]
public void DropEditionTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropEdition"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropEdition");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("EDITION", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("TEST", scanner.currCommand.objectName);
}
[Test]
public void DropFlashbackArchiveTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropFlashbackArchive"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropFlashbackArchive");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("FLASHBACK ARCHIVE", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("TEST", scanner.currCommand.objectName);
}
[Test]
public void DropFunctionTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropFunction"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropFunction");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("FUNCTION", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("OE.SECONDMAX", scanner.currCommand.objectName);
}
[Test]
public void DropIndexTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropIndex"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropIndex");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("INDEX", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("ORD_CUSTOMER_IX_DEMO", scanner.currCommand.objectName);
}
[Test]
public void DropIndextypeTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropIndextype"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropIndextype");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("INDEXTYPE", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("POSITION_INDEXTYPE", scanner.currCommand.objectName);
}
[Test]
public void DropJavaClassTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropJavaClass"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropJavaClass");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("JAVA CLASS", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("\"Agent\"", scanner.currCommand.objectName);
}
[Test]
public void DropJavaSourceTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropJavaSource"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropJavaSource");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("JAVA SOURCE", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("\"Agent\"", scanner.currCommand.objectName);
}
[Test]
public void DropJavaResourceTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropJavaResource"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropJavaResource");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("JAVA RESOURCE", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("\"Agent\"", scanner.currCommand.objectName);
}
[Test]
public void DropLibraryTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropLibrary"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropLibrary");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("LIBRARY", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("EXT_LIB", scanner.currCommand.objectName);
}
[Test]
public void DropMaterializedViewTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropMaterializedView"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropMaterializedView");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("MATERIALIZED VIEW", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("EMP_DATA", scanner.currCommand.objectName);
}
[Test]
public void DropMaterializedViewLogTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropMaterializedViewLog"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropMaterializedViewLog");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("MATERIALIZED VIEW LOG", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("OE.CUSTOMERS", scanner.currCommand.secondaryObjectName);
}
[Test]
public void DropOperatorTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropOperator"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropOperator");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("OPERATOR", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("EQ_OP", scanner.currCommand.objectName);
}
[Test]
public void DropOutlineTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropOutline"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropOutline");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("OUTLINE", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("SALARIES", scanner.currCommand.objectName);
}
[Test]
public void DropPackageTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropPackage"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropPackage");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("PACKAGE", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("EMP_MGMT", scanner.currCommand.objectName);
}
[Test]
public void DropPackageBodyTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropPackageBody"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropPackageBody");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("PACKAGE BODY", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("EMP_MGMT", scanner.currCommand.objectName);
}
[Test]
public void DropProcedureTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropProcedure"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropProcedure");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("PROCEDURE", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("HR.REMOVE_EMP", scanner.currCommand.objectName);
}
[Test]
public void DropProfileTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropProfile"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropProfile");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("PROFILE", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("APP_USER", scanner.currCommand.objectName);
}
[Test]
public void DropRestorePointTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropRestorePoint"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropRestorePoint");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("RESTORE POINT", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("GOOD_DATA", scanner.currCommand.objectName);
}
[Test]
public void DropRoleTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropRole"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropRole");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("ROLE", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("DW_MANAGER", scanner.currCommand.objectName);
}
[Test]
public void DropRollbackSegmentTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropRollbackSegment"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropRollbackSegment");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("ROLLBACK SEGMENT", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("RBS_ONE", scanner.currCommand.objectName);
}
[Test]
public void DropSequenceTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropSequence"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropSequence");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("SEQUENCE", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("OE.CUSTOMERS_SEQ", scanner.currCommand.objectName);
}
[Test]
public void DropPublicSynonymTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropPublicSynonym"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropPublicSynonym");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("PUBLIC SYNONYM", scanner.currCommand.cmdName);
Assert.AreEqual("SYNONYM", scanner.currCommand.baseCmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("CUSTOMERS", scanner.currCommand.objectName);
}
[Test]
public void DropSynonymTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropSynonym"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropSynonym");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("SYNONYM", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("CUSTOMERS", scanner.currCommand.objectName);
}
[Test]
public void DropTableTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropTable"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropTable");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("TABLE", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("LIST_CUSTOMERS", scanner.currCommand.objectName);
}
[Test]
public void DropTablespaceTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropTablespace"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropTablespace");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("TABLESPACE", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("TBS_01", scanner.currCommand.objectName);
}
[Test]
public void DropTriggerTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropTrigger"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropTrigger");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("TRIGGER", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("HR.SALARY_CHECK", scanner.currCommand.objectName);
}
[Test]
public void DropTypeTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropType"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropType");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("TYPE", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("PERSON_T", scanner.currCommand.objectName);
}
[Test]
public void DropTypeBodyTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropTypeBody"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropTypeBody");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("TYPE BODY", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("DATA_TYP1", scanner.currCommand.objectName);
}
[Test]
public void DropUserTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropUser"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropUser");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("USER", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("BEZEL", scanner.currCommand.objectName);
}
[Test]
public void DropViewTest()
{
StringReader sr = new StringReader(ResourceHelper.GetResourceString("DropView"));
SQLMake.Util.Settings.loadSettings();
SQLPlusScanner scanner;
scanner = new SQLPlusScanner(sr, "DropView");
scanner.readNextBlock();
Assert.AreEqual(CommandTypes.Sql, scanner.currCommand.cmdType);
Assert.AreEqual("VIEW", scanner.currCommand.cmdName);
Assert.AreEqual("DROP", scanner.currCommand.action);
Assert.AreEqual("EMP_VIEW", scanner.currCommand.objectName);
}
}
}
| danijelkavcic/sqlmake | src/SQLMakeTest/SQLPlusScannerDropStatementsTest.cs | C# | gpl-3.0 | 26,506 |
/*
* This file is part of evQueue
*
* evQueue 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.
*
* evQueue 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 evQueue. If not, see <http://www.gnu.org/licenses/>.
*
* Author: Thibault Kummer <bob@coldsource.net>
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <syslog.h>
#include <errno.h>
#include <stdio.h>
#include <mysql/mysql.h>
#include <Logger.h>
#include <Queue.h>
#include <QueuePool.h>
#include <Workflows.h>
#include <WorkflowInstance.h>
#include <WorkflowInstances.h>
#include <ConfigurationReader.h>
#include <Exception.h>
#include <Retrier.h>
#include <WorkflowScheduler.h>
#include <WorkflowSchedule.h>
#include <global.h>
#include <ProcessManager.h>
#include <DB.h>
#include <Statistics.h>
#include <Tasks.h>
#include <RetrySchedules.h>
#include <GarbageCollector.h>
#include <SequenceGenerator.h>
#include <handle_connection.h>
#include <tools.h>
#include <xqilla/xqilla-dom3.hpp>
int listen_socket;
void signal_callback_handler(int signum)
{
if(signum==SIGINT || signum==SIGTERM)
{
// Shutdown requested
// Close main listen socket, this will release accept() loop
close(listen_socket);
}
else if(signum==SIGHUP)
{
Logger::Log(LOG_NOTICE,"Got SIGHUP, reloading scheduler configuration");
WorkflowScheduler *scheduler = WorkflowScheduler::GetInstance();
scheduler->Reload();
Tasks *tasks = Tasks::GetInstance();
tasks->Reload();
RetrySchedules *retry_schedules = RetrySchedules::GetInstance();
retry_schedules->Reload();
Workflows *workflows = Workflows::GetInstance();
workflows->Reload();
}
else if(signum==SIGUSR1)
{
Logger::Log(LOG_NOTICE,"Got SIGUSR1, flushing retrier");
Retrier *retrier = Retrier::GetInstance();
retrier->Flush();
}
}
int main(int argc,const char **argv)
{
// Check parameters
const char *config_filename = 0;
bool daemonize = false;
bool daemonized = false;
for(int i=1;i<argc;i++)
{
if(strcmp(argv[i],"--daemon")==0)
daemonize = true;
else if(strcmp(argv[i],"--config")==0 && i+1<argc)
{
config_filename = argv[i+1];
i++;
}
else if(strcmp(argv[i],"--ipcq-remove")==0)
return tools_queue_destroy();
else if(strcmp(argv[i],"--ipcq-stats")==0)
return tools_queue_stats();
else
{
fprintf(stderr,"Unknown option : %s\n",argv[i]);
tools_print_usage();
return -1;
}
}
if(config_filename==0)
{
tools_print_usage();
return -1;
}
// Initialize external libraries
mysql_library_init(0,0,0);
XQillaPlatformUtils::initialize();
openlog("evqueue",0,LOG_DAEMON);
struct sigaction sa;
sigset_t block_mask;
sigemptyset(&block_mask);
sigaddset(&block_mask, SIGINT);
sigaddset(&block_mask, SIGTERM);
sigaddset(&block_mask, SIGHUP);
sigaddset(&block_mask, SIGUSR1);
sa.sa_handler = signal_callback_handler;
sa.sa_mask = block_mask;
sa.sa_flags = 0;
sigaction(SIGHUP,&sa,0);
sigaction(SIGINT,&sa,0);
sigaction(SIGTERM,&sa,0);
sigaction(SIGUSR1,&sa,0);
try
{
// Read configuration
Configuration *config;
config = ConfigurationReader::Read(config_filename);
// Create logger as soon as possible
Logger *logger = new Logger();
// Open pid file before fork to eventually print errors
FILE *pidfile = fopen(config->Get("core.pidfile"),"w");
if(pidfile==0)
throw Exception("core","Unable to open pid file");
int gid = atoi(config->Get("core.gid"));
if(gid!=0 && setgid(gid)!=0)
throw Exception("core","Unable to set requested GID");
// Set uid/gid if requested
int uid = atoi(config->Get("core.uid"));
if(uid!=0 && setuid(uid)!=0)
throw Exception("core","Unable to set requested UID");
// Check database connection
DB db;
db.Ping();
if(daemonize)
{
daemon(1,0);
daemonized = true;
}
// Write pid after daemonization
fprintf(pidfile,"%d\n",getpid());
fclose(pidfile);
// Instanciate sequence generator, used for savepoint level 0 or 1
SequenceGenerator *seq = new SequenceGenerator();
// Create statistics counter
Statistics *stats = new Statistics();
// Start retrier
Retrier *retrier = new Retrier();
// Start scheduler
WorkflowScheduler *scheduler = new WorkflowScheduler();
// Create queue pool
QueuePool *pool = new QueuePool();
// Instanciate workflow instances map
WorkflowInstances *workflow_instances = new WorkflowInstances();
// Instanciate workflows list
Workflows *workflows = new Workflows();
// Instanciate tasks list
Tasks *tasks = new Tasks();
// Instanciate retry schedules list
RetrySchedules *retry_schedules = new RetrySchedules();
// Check if workflows are to resume (we have to resume them before starting ProcessManager)
db.Query("SELECT workflow_instance_id, workflow_schedule_id FROM t_workflow_instance WHERE workflow_instance_status='EXECUTING'");
while(db.FetchRow())
{
Logger::Log(LOG_NOTICE,"[WID %d] Resuming",db.GetFieldInt(0));
WorkflowInstance *workflow_instance = 0;
bool workflow_terminated;
try
{
workflow_instance = new WorkflowInstance(db.GetFieldInt(0));
workflow_instance->Resume(&workflow_terminated);
if(workflow_terminated)
delete workflow_instance;
}
catch(Exception &e)
{
Logger::Log(LOG_NOTICE,"[WID %d] Unexpected exception trying to resume : [ %s ] %s\n",db.GetFieldInt(0),e.context,e.error);
if(workflow_instance)
delete workflow_instance;
}
}
// On level 0 or 1, executing workflows are only stored during engine restart. Purge them since they are resumed
if(Configuration::GetInstance()->GetInt("workflowinstance.savepoint.level")<=1)
db.Query("DELETE FROM t_workflow_instance WHERE workflow_instance_status='EXECUTING'");
// Load workflow schedules
db.Query("SELECT ws.workflow_schedule_id, w.workflow_name, wi.workflow_instance_id FROM t_workflow_schedule ws LEFT JOIN t_workflow_instance wi ON(wi.workflow_schedule_id=ws.workflow_schedule_id AND wi.workflow_instance_status='EXECUTING') INNER JOIN t_workflow w ON(ws.workflow_id=w.workflow_id) WHERE ws.workflow_schedule_active=1");
while(db.FetchRow())
{
WorkflowSchedule *workflow_schedule = 0;
try
{
workflow_schedule = new WorkflowSchedule(db.GetFieldInt(0));
scheduler->ScheduleWorkflow(workflow_schedule, db.GetFieldInt(2));
}
catch(Exception &e)
{
Logger::Log(LOG_NOTICE,"[WSID %d] Unexpected exception trying initialize workflow schedule : [ %s ] %s\n",db.GetFieldInt(0),e.context,e.error);
if(workflow_schedule)
delete workflow_schedule;
}
}
// Start Process Manager (Forker & Gatherer)
ProcessManager *pm = new ProcessManager();
// Start garbage GarbageCollector
GarbageCollector *gc = new GarbageCollector();
Logger::Log(LOG_NOTICE,"evqueue core started");
int re,s,optval;
struct sockaddr_in local_addr,remote_addr;
socklen_t remote_addr_len;
// Create listen socket
listen_socket=socket(PF_INET,SOCK_STREAM,0);
// Configure socket
optval=1;
setsockopt(listen_socket,SOL_SOCKET,SO_REUSEADDR,&optval,sizeof(int));
// Bind socket
memset(&local_addr,0,sizeof(struct sockaddr_in));
local_addr.sin_family=AF_INET;
if(strcmp(config->Get("network.bind.ip"),"*")==0)
local_addr.sin_addr.s_addr=htonl(INADDR_ANY);
else
local_addr.sin_addr.s_addr=inet_addr(config->Get("network.bind.ip"));
local_addr.sin_port = htons(atoi(config->Get("network.bind.port")));
re=bind(listen_socket,(struct sockaddr *)&local_addr,sizeof(struct sockaddr_in));
if(re==-1)
throw Exception("core","Unable to bind listen socket");
// Listen on socket
re=listen(listen_socket,config->GetInt("network.listen.backlog"));
if(re==-1)
throw Exception("core","Unable to listen on socket");
Logger::Log(LOG_NOTICE,"Listen backlog set to %d",config->GetInt("network.listen.backlog"));
char *ptr,*parameters;
Logger::Log(LOG_NOTICE,"Accepting connection on port %s",config->Get("network.bind.port"));
// Loop for incoming connections
int len,*sp;
while(1)
{
remote_addr_len=sizeof(struct sockaddr);
s = accept(listen_socket,(struct sockaddr *)&remote_addr,&remote_addr_len);
if(s<0)
{
if(errno==EINTR)
continue; // Interrupted by signal, continue
// Shutdown requested
Logger::Log(LOG_NOTICE,"Shutting down...");
// Request shutdown on ProcessManager and wait
pm->Shutdown();
pm->WaitForShutdown();
// Request shutdown on scheduler and wait
scheduler->Shutdown();
scheduler->WaitForShutdown();
// Request shutdown on Retrier and wait
retrier->Shutdown();
retrier->WaitForShutdown();
// Save current state in database
workflow_instances->RecordSavepoint();
// Request shutdown on GarbageCollector and wait
gc->Shutdown();
gc->WaitForShutdown();
// All threads have exited, we can cleanly exit
delete stats;
delete retrier;
delete scheduler;
delete pool;
delete workflow_instances;
delete workflows;
delete tasks;
delete retry_schedules;
delete pm;
delete gc;
delete seq;
XQillaPlatformUtils::terminate();
mysql_library_end();
unlink(config->Get("core.pidfile"));
Logger::Log(LOG_NOTICE,"Clean exit");
delete logger;
return 0;
}
sp = new int;
*sp = s;
pthread_t thread;
pthread_attr_t thread_attr;
pthread_attr_init(&thread_attr);
pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
pthread_create(&thread, &thread_attr, handle_connection, sp);
}
}
catch(Exception &e)
{
// We have to use only syslog here because the logger might not be instanciated yet
syslog(LOG_CRIT,"Unexpected exception : [ %s ] %s\n",e.context,e.error);
if(!daemonized)
fprintf(stderr,"Unexpected exception : [ %s ] %s\n",e.context,e.error);
return -1;
}
return 0;
}
| anshumang/evqueue-core | evqueue.cpp | C++ | gpl-3.0 | 10,552 |
/**
* @file Session class.
* @copyright 2014 Shipping Soon
* @license GPLv3
* @see {@link https://github.com/shippingsoon/Synesthesia-Symphony} for sourcecode
* @see {@link https://www.shippingsoon.com/synesthesia-symphony} for online demo
*/
import {IConfig, IGameData, ISession} from '../game/types';
import {injectable, unmanaged} from 'inversify';
/**
* @classdesc Session class. This was originally a singleton class but was refactored to use InversifyJs' singleton scope.
*/
@injectable()
export class Session implements ISession {
//Background music volume level.
private _bgmVolumeLevel: number = 127;
//Sound effects volume level.
private _sfxVolumeLevel: number = 127;
//Read only configuration data. This data is stored in a config.json file. See IConfig for more details.
private _config: IConfig;
//Game data used to initiate entities such as player, projectile, and items. This data is either loaded from a database or a JSON file.
private _data: IGameData;
public constructor() {}
//#region Mutator Region (Note: regions are collapsible with IntelliJ)
/**
* Gets the background music volume level.
* @return {number}
*/
public get bgmVolumeLevel(): number {return this._bgmVolumeLevel;}
/**
* Sets the background music volume level.
* @param bgmVolumeLevel - The background music volume level. Must be between 0-127.
* @throws {Error}
*/
public set bgmVolumeLevel(bgmVolumeLevel: number) {
if (bgmVolumeLevel < 0 || bgmVolumeLevel > 127) {
throw new Error('Background music volume level must be between 0 and 127');
}
this._bgmVolumeLevel = bgmVolumeLevel;
}
/**
* Gets the sound effects volume level.
* @return {number}
*/
public get sfxVolumeLevel(): number {return this._bgmVolumeLevel;}
/**
* Sets the sound effects volume level.
* @param {number} sfxVolumeLevel - The sound effects volume to set. Must be between 0-127.
* @throws {Error}
*/
public set sfxVolumeLevel(sfxVolumeLevel: number) {
if (sfxVolumeLevel < 0 || sfxVolumeLevel > 127) {
throw new Error('Sound effects volume level must be between 0 and 127');
}
this._bgmVolumeLevel = sfxVolumeLevel;
}
/**
* Gets the readonly configuration data. See config.json or IConfig for more details.
* @return {IConfig}
*/
public get config(): IConfig {return this._config;}
/**
* Gets the configuration data.
* @param config - The configuration data.
*/
public set config(config: IConfig) {this._config = config;}
/**
* Gets the game data.
* @return {IGameData}
*/
public get data(): IGameData {return this._data;}
/**
* Sets the game data.
* @param data - The game data.
*/
public set data(data: IGameData) {this._data = data;}
//#endregion
}
| shippingsoon/Synesthesia-Symphony | system/session.ts | TypeScript | gpl-3.0 | 2,736 |
<?
header('Content-Type: application/json; charset=utf-8');
require_once "MysqliDb.php";
$lat = $_GET['latitude']; // latitude of centre of bounding circle in degrees
$lon = $_GET['longitude']; // longitude of centre of bounding circle in degrees
$rad = $_GET['radius']; // radius of bounding circle in kilometers
if (!checkNumeric(array($lat, $lon, $rad))) {
http_response_code(400);
exit();
}
$db = new MysqliDb("host","user","password","database");
$max = intval($_GET['max']);
if($max == 0) {
$max = 20;
}
$R = 6371*1000; // earth's radius, km
// first-cut bounding box (in degrees)
$maxLat = $lat + rad2deg($rad/$R);
$minLat = $lat - rad2deg($rad/$R);
// compensate for degrees longitude getting smaller with increasing latitude
$maxLon = $lon + rad2deg($rad/$R/cos(deg2rad($lat)));
$minLon = $lon - rad2deg($rad/$R/cos(deg2rad($lat)));
// convert origin of filter circle to radians
$lat = deg2rad($lat);
$lon = deg2rad($lon);
$q="Select metadata, latitude, longitude,altitude, type,".
"acos(sin($lat)*sin(radians(latitude)) + cos($lat)*cos(radians(latitude))*cos(radians(longitude)-$lon))*$R As distance".
" From (".
"Select * ".
"From geopoint ".
"Where latitude > $minLat And latitude < $maxLat".
" And longitude > $minLon And longitude < $maxLon".
") As FirstCut ".
"Where acos(sin($lat)*sin(radians(latitude)) + cos($lat)*cos(radians(latitude))*cos(radians(longitude)-$lon))*$R < $rad".
" order by distance ASC limit $max";
$res=$db->rawQuery($q);
function checkNumeric($input) {
foreach($input as $f) {
if ($f == null || !is_numeric($f)) {
return false;
}
}
return true;
}
?>
{"results":<?=json_encode($res)?>}
| fabienric/geoservice-api | search.php | PHP | gpl-3.0 | 1,709 |
import json
import socket
import sys
attackSocket = socket.socket()
attackSocket.connect(('localhost', 8080))
attackSocket.send("{0}\r\n".format(
json.dumps(
{'membership': "full", 'channel': sys.argv[1], 'message': ' '.join(sys.argv[3:]), 'type': "start", 'which': sys.argv[2]}
)).encode('utf-8'))
attackSocket.close()
| randomrandomlol123/fewgewgewgewhg | sender.py | Python | gpl-3.0 | 325 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration | Version: 3.2
\\ / A nd | Web: http://www.foam-extend.org
\\/ M anipulation | For copyright notice see file Copyright
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend 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.
foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::RosinRammler
Description
Rosin-Rammler pdf
@f[
pdf = ( x/d )^n \exp ( -( x/d )^n )
@f]
SourceFiles
RosinRammlerI.H
RosinRammler.C
RosinRammlerIO.C
\*---------------------------------------------------------------------------*/
#ifndef RosinRammler_H
#define RosinRammler_H
#include "pdf.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class RosinRammler Declaration
\*---------------------------------------------------------------------------*/
class RosinRammler
:
public pdf
{
// Private data
dictionary pdfDict_;
//- min and max values of the distribution
scalar minValue_;
scalar maxValue_;
List<scalar> d_;
List<scalar> n_;
List<scalar> ls_;
scalar range_;
public:
//- Runtime type information
TypeName("RosinRammler");
// Constructors
//- Construct from components
RosinRammler
(
const dictionary& dict,
Random& rndGen
);
//- Destructor
virtual ~RosinRammler();
// Member Functions
//- Sample the pdf
virtual scalar sample() const;
//- Return the minimum value
virtual scalar minValue() const;
//- Return the maximum value
virtual scalar maxValue() const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2 | src/thermophysicalModels/pdfs/RosinRammler/RosinRammler.H | C++ | gpl-3.0 | 2,909 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration | Version: 3.2
\\ / A nd | Web: http://www.foam-extend.org
\\/ M anipulation | For copyright notice see file Copyright
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend 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.
foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>.
Class
HormannAgathos
Description
Implements the point in polygon problem using the winding number technique
presented in the paper:
"The point in polygon problem for arbitrary polygons",
Kai Hormann, Alexander Agathos, 2001
Author
Martin Beaudoin, Hydro-Quebec, (2008)
SourceFiles
HormannAgathosI.H
HormannAgathos.C
HormannAgathosIO.C
\*---------------------------------------------------------------------------*/
#ifndef HormannAgathos_H
#define HormannAgathos_H
#include "List.H"
#include "point2D.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class HormannAgathos Declaration
\*---------------------------------------------------------------------------*/
class HormannAgathos
{
// Private data
//- 2D coordinate of polygon vertices
// We keep the same notation as in the paper
List<point2D> P_;
//- 2D distance tolerance factor for in/out tests
scalar distTol_;
//- 2D distance epsilon for in/out tests
scalar epsilon_;
// Private Member Functions
//- Compute 2D distance epsilon based on a tolerance factor
void evaluateEpsilon();
//- Comparison of two scalar within a tolerance
inline bool equalWithTol
(
const scalar& a,
const scalar& b
) const;
inline bool greaterWithTol
(
const scalar& a,
const scalar& b
) const;
inline bool smallerWithTol
(
const scalar& a,
const scalar& b
) const;
inline bool greaterOrEqualWithTol
(
const scalar& a,
const scalar& b
) const;
inline bool smallerOrEqualWithTol
(
const scalar& a,
const scalar& b
) const;
public:
// Public typedefs
enum inOutClassification
{
POINT_OUTSIDE,
POINT_INSIDE,
POINT_ON_VERTEX,
POINT_ON_EDGE
};
// Constructors
//- Construct from components
HormannAgathos
(
const List<point2D>& P,
const scalar& distTol
);
// Destructor - default
// Member Functions
//- Executa classification of points
inOutClassification evaluate(const point2D& R) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#include "HormannAgathosI.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2 | src/foam/algorithms/polygon/pointInPolygon/HormannAgathos.H | C++ | gpl-3.0 | 4,042 |
<?php
function concat_exclamation($str) {
$str .= "!";
print $str;
}
function concat_exclamation_to_each_value($arr) {
foreach ($arr as $key => $value) {
$arr[$key] = $value . "!";
}
print_r($arr);
}
function concat_exclamation_to_name($obj) {
$obj->newname .= "!";
print_r($obj);
}
?>
<!doctype html>
<html>
<head>
<title>Object Oriented Programming - Passing By Copy Vs. Passing By Reference</title>
</head>
<body>
<strong>String passed to function - passed by copy</strong>
<?php
$str = "And on earth peace to all people of good will";
?>
<ul>
<li>Original value: <?= $str ?></li>
<li>Modified value in function: <?php concat_exclamation($str)?></li>
<li>Value after function: <?= $str ?></li>
</ul>
<strong>Array passed to function - passed by copy</strong>
<?php
$arr = array(
"X" => "Andrew",
"Knife" => "Bartholomew",
"Staff" => "James the Younger",
"Shell" => "James the Great",
"Poisned Cup" => "John",
"Noose" => "Judas",
"Medallion" => "Jude",
"Bags of Money" => "Matthew",
"Battle Axe" => "Matthias",
"Sword" => "Paul",
"Keys" => "Peter",
"Loaves of Bread" => "Philip",
"Saw" => "Simon",
"Spear" => "Thomas"
);
?>
<ul>
<li>Original value: <pre><?php print_r($arr); ?></pre></li>
<li>Modified value in function: <pre><?php concat_exclamation_to_each_value($arr); ?></pre></li>
<li>Value after function: <pre><?php print_r($arr)?></pre></li>
</ul>
<strong>Array passed to function - passed by copy</strong>
<?php
class Renamed {
public $oldname;
public $newname;
}
$obj = new Renamed();
$obj->oldname = "Simon";
$obj->newname = "Peter";
?>
<ul>
<li>Original value: <pre><?php print_r($obj); ?></pre></li>
<li>Modified value in function: <pre><?php concat_exclamation_to_name($obj); ?></pre></li>
<li>Value after function: <pre><?php print_r($obj)?></pre></li>
</ul>
</body>
</html>
| themystic/php-demos | object-oriented-programming/passing-by-reference.php | PHP | gpl-3.0 | 2,344 |
<?php
/* Copyright (C) 2015 FH Technikum-Wien
*
* 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.
*
* Authors: Manfred kindl <manfred.kindl@technikum-wien.at>
*/
require_once('../../../config/global.config.inc.php');
require_once('../../../config/cis.config.inc.php');
require_once('../../../include/studiengang.class.php');
require_once('../../../include/mail.class.php');
require_once('../../../include/kontakt.class.php');
require_once('../include/functions.inc.php');
require_once('../bewerbung.config.inc.php');
// Wenn das Script ueber die Kommandozeile aufgerufen wird, erfolgt keine Authentifizierung
if (php_sapi_name() != 'cli')
{
$uid = get_uid();
$rechte = new benutzerberechtigung();
$rechte->getBerechtigungen($uid);
if(!$rechte->isBerechtigt('admin'))
{
exit($rechte->errormsg);
}
}
// An der FHTW werden alle Bachelor-Studiengänge über das Infocenter abgewickelt
$qry = "
SELECT
person_id,
studiengang_kz,
tbl_prestudentstatus.orgform_kurzbz,
tbl_prestudent.insertamum,
vorname,
nachname,
gebdatum,
geschlecht,
studiensemester_kurzbz,
tbl_studienplan.bezeichnung AS studienplan
FROM
public.tbl_prestudent
JOIN
public.tbl_person USING (person_id)
JOIN
public.tbl_prestudentstatus USING (prestudent_id)
JOIN
lehre.tbl_studienplan USING (studienplan_id)
JOIN
public.tbl_studiengang USING (studiengang_kz)
WHERE
tbl_prestudent.insertvon='online'
AND (tbl_prestudent.insertamum >= (SELECT (CURRENT_DATE -1||' '||'03:00:00')::timestamp)
OR tbl_prestudentstatus.insertamum >= (SELECT (CURRENT_DATE -1||' '||'03:00:00')::timestamp))
AND tbl_prestudentstatus.status_kurzbz = 'Interessent'
AND tbl_prestudentstatus.bewerbung_abgeschicktamum IS NULL
AND tbl_studiengang.typ != 'b' AND tbl_studiengang.typ != 'm'
AND get_rolle_prestudent (tbl_prestudent.prestudent_id, studiensemester_kurzbz) != 'Abgewiesener'
ORDER BY studiengang_kz, studiensemester_kurzbz, orgform_kurzbz, nachname, vorname";
$db = new basis_db();
$studiengaenge = array();
$stg_kz = '';
$orgform = '';
$mailcontent = '';
$studiensemester = '';
$mail_alle = '';
// Prueft, ob das Logverzeichnis existiert.
// Wenn nicht, wird versucht, eines anzulegen.
// Falls dies fehl schlaegt, wird kein Logfile erstellt.
$write_log = true;
if(!is_dir(LOG_PATH.'bewerbungstool/neu_registriert/'))
{
if (mkdir(LOG_PATH.'bewerbungstool',0777,true))
{
if(!is_dir(LOG_PATH.'bewerbungstool/neu_registriert/'))
{
if (mkdir(LOG_PATH.'bewerbungstool/neu_registriert',0777,true))
$write_log = true;
else
$write_log = false;
}
}
else
$write_log = false;
}
// Aus Datenschutzgründen werden Logfiles älter als 3 Monate gelöscht
$dateLess3Months = date("Y_m", strtotime("-3 months"));
if (file_exists(LOG_PATH.'bewerbungstool/neu_registriert/'.$dateLess3Months.'_log.html'))
{
unlink(LOG_PATH.'bewerbungstool/neu_registriert/'.$dateLess3Months.'_log.html');
}
$logfile = LOG_PATH.'bewerbungstool/neu_registriert/'.date('Y_m').'_log.html';
$logcontent = '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<h2 style="text-align: center">'.date('Y-m-d').'</h2><hr>';
$empf_array = array();
if(defined('BEWERBERTOOL_BEWERBUNG_EMPFAENGER'))
$empf_array = unserialize(BEWERBERTOOL_BEWERBUNG_EMPFAENGER);
$mailtext = '
<style type="text/css">
.table1
{
font-size: small;
cellpadding: 3px;
}
.table1 th
{
background: #DCE4EF;
border: 1px solid #FFF;
padding: 4px;
text-align: left;
}
.table1 td
{
background-color: #EEEEEE;
padding: 4px;
}
</style>
Folgende Personen haben sich gestern registriert, ihre Bewerbung aber noch nicht abgeschickt:<br><br>';
if($result = $db->db_query($qry))
{
if ($db->db_num_rows($result) > 0)
{
$mailcontent = $mailtext;
$anzahl = $db->db_num_rows($result);
while($row = $db->db_fetch_object($result))
{
if (($stg_kz != '' && $stg_kz != $row->studiengang_kz) || ($orgform != '' && $orgform != $row->orgform_kurzbz))
{
$mailcontent .= '</tbody></table>';
$mailcontent .= '<a href="mailto:?BCC='.$mail_alle.'">Mail an alle</a>';
$studiensemester = '';
$studiengang = new studiengang();
if(!$studiengang->load($stg_kz))
die($p->t('global/fehlerBeimLadenDesDatensatzes'));
$bezeichnung = strtoupper($studiengang->typ.$studiengang->kurzbz);
if(defined('BEWERBERTOOL_MAILEMPFANG') && BEWERBERTOOL_MAILEMPFANG!='')
$empfaenger = BEWERBERTOOL_MAILEMPFANG;
elseif(isset($empf_array[$stg_kz]))
$empfaenger = $empf_array[$stg_kz];
else
$empfaenger = $studiengang->email;
if ($empfaenger == '')
{
if (defined('MAIL_ADMIN') && MAIL_ADMIN != '')
{
$empfaenger = MAIL_ADMIN;
$mailcontentWithWarning = '<p style="color: red; font-weight: bold; padding: 10px 0">Kein Empfänger für diese Mail gefunden</p>';
$mailcontentWithWarning .= $mailcontent;
$mailcontent = $mailcontentWithWarning;
}
else
{
continue;
}
}
$mailcontent = wordwrap($mailcontent,70);
//Pfuschloesung fur BIF Dual
if (CAMPUS_NAME=='FH Technikum Wien' && $stg_kz == 257 && $orgform == 'DUA')
$empfaenger = 'info.bid@technikum-wien.at';
$mail = new mail($empfaenger, 'no-reply', 'Neu registriert '.$bezeichnung.' '.$orgform, 'Bitte sehen Sie sich die Nachricht in HTML Sicht an, um den Inhalt vollständig darzustellen.');
//$mail->setBCCRecievers('kindlm@technikum-wien.at');
$mail->setHTMLContent($mailcontent);
$mail->send();
if ($write_log)
{
$logcontent .= '<h3>Studiengang: '.$stg_kz.'</h3>';
$logcontent .= 'Empfänger: '.$empfaenger.'<br>';
$logcontent .= 'Betreff: Neu registriert '.$bezeichnung.' '.$orgform.'<br><br>';
$logcontent .= $mailcontent;
$logcontent .= '<hr>';
// Schreibt den Inhalt in die Datei
// unter Verwendung des Flags FILE_APPEND, um den Inhalt an das Ende der Datei anzufügen
// und das Flag LOCK_EX, um ein Schreiben in die selbe Datei zur gleichen Zeit zu verhindern
file_put_contents($logfile, $logcontent, FILE_APPEND | LOCK_EX);
$logcontent = '';
}
$mailcontent = $mailtext;
$mail_alle = '';
}
if ($row->studiensemester_kurzbz != '' && $studiensemester != $row->studiensemester_kurzbz)
{
if ($studiensemester != '')
{
$mailcontent .= '</tbody></table>';
$mailcontent .= '<a href="mailto:?BCC='.$mail_alle.'">Mail an alle</a>';
$mail_alle = '';
}
$mailcontent .= '<h3>'.$row->studiensemester_kurzbz.' '.$row->orgform_kurzbz.'</h3>';
$mailcontent .= '<table class="table1"><thead><tr>
<th>Studienplan</th>
<th>Anrede</th>
<th>Nachname</th>
<th>Vorname</th>
<th>Geburtsdatum</th>
<th>Mailadresse</th>
</thead><tbody>';
$studiensemester = $row->studiensemester_kurzbz;
}
$kontakt = new kontakt();
$kontakt->load_persKontakttyp($row->person_id, 'email', 'zustellung DESC, updateamum DESC, insertamum DESC NULLS LAST');
$mailadresse = isset($kontakt->result[0]->kontakt)?$kontakt->result[0]->kontakt:'';
$mailcontent .= '<tr>';
$mailcontent .= '<td>'.($row->studienplan != ''?$row->studienplan:'<span style="color: red">Es konnte kein passender Studienplan ermittelt werden</span>').'</td>';
$mailcontent .= '<td>'.($row->geschlecht=='m'?'Herr ':'Frau ').'</td>';
$mailcontent .= '<td>'.$row->nachname.'</td>';
$mailcontent .= '<td>'.$row->vorname.'</td>';
$mailcontent .= '<td>'.date('d.m.Y', strtotime($row->gebdatum)).'</td>';
$mailcontent .= '<td><a href="mailto:'.$mailadresse.'">'.$mailadresse.'</a></td>';
$mailcontent .= '</tr>';
$mail_alle .= $mailadresse.';';
$stg_kz = $row->studiengang_kz;
$orgform = $row->orgform_kurzbz;
}
$mailcontent .= '</tbody></table>';
$mailcontent .= '<a href="mailto:?BCC='.$mail_alle.'">Mail an alle</a>';
$studiengang = new studiengang();
if(!$studiengang->load($stg_kz))
die($p->t('global/fehlerBeimLadenDesDatensatzes'));
$bezeichnung = strtoupper($studiengang->typ.$studiengang->kurzbz);
if(defined('BEWERBERTOOL_MAILEMPFANG') && BEWERBERTOOL_MAILEMPFANG!='')
$empfaenger = BEWERBERTOOL_MAILEMPFANG;
elseif(isset($empf_array[$stg_kz]))
$empfaenger = $empf_array[$stg_kz];
else
$empfaenger = $studiengang->email;
if ($empfaenger == '')
{
if (defined('MAIL_ADMIN') && MAIL_ADMIN != '')
{
$empfaenger = MAIL_ADMIN;
$mailcontentWithWarning = '<p style="color: red; font-weight: bold; padding: 10px 0">Kein Empfänger für diese Mail gefunden</p>';
$mailcontentWithWarning .= $mailcontent;
$mailcontent = $mailcontentWithWarning;
}
else
{
exit();
}
}
$mailcontent = wordwrap($mailcontent,70);
//Pfuschloesung fur BIF Dual
if (CAMPUS_NAME=='FH Technikum Wien' && $stg_kz == 257 && $orgform == 'DUA')
$empfaenger = 'info.bid@technikum-wien.at';
$mail = new mail($empfaenger, 'no-reply', 'Neu registriert '.$bezeichnung.' '.$orgform, 'Bitte sehen Sie sich die Nachricht in HTML Sicht an, um den Inhalt vollständig darzustellen.');
//$mail->setBCCRecievers('kindlm@technikum-wien.at');
$mail->setHTMLContent($mailcontent);
$mail->send();
if ($write_log)
{
$logcontent .= '<h3>Studiengang: '.$stg_kz.'</h3>';
$logcontent .= 'Empfänger: '.$empfaenger.'<br>';
$logcontent .= 'Betreff: Neu registriert '.$bezeichnung.' '.$orgform.'<br><br>';
$logcontent .= $mailcontent;
$logcontent .= '<hr>';
// Schreibt den Inhalt in die Datei
// unter Verwendung des Flags FILE_APPEND, um den Inhalt an das Ende der Datei anzufügen
// und das Flag LOCK_EX, um ein Schreiben in die selbe Datei zur gleichen Zeit zu verhindern
file_put_contents($logfile, $logcontent, FILE_APPEND | LOCK_EX);
$logcontent = '';
}
}
}
else
{
$mailcontent = '<h3>Fehler in Cronjob "addons/bewerbung/cronjobs/neu_registriert_job.php"</h3><br><br><b>'.$db->errormsg.'</b>';
$mail = new mail(MAIL_ADMIN, 'no-reply', 'Fehler in Cronjob "addons/bewerbung/cronjobs/neu_registriert_job.php"', 'Bitte sehen Sie sich die Nachricht in HTML Sicht an, um den Inhalt vollständig darzustellen.');
$mail->setHTMLContent($mailcontent);
$mail->send();
}
?>
| FH-Complete/FHC-AddOn-Bewerbung | cronjobs/neu_registriert_job.php | PHP | gpl-3.0 | 10,904 |
/*===========================================================================*\
* *
* OpenFlipper *
* Copyright (C) 2001-2014 by Computer Graphics Group, RWTH Aachen *
* www.openflipper.org *
* *
*--------------------------------------------------------------------------- *
* This file is part of OpenFlipper. *
* *
* OpenFlipper is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenFlipper is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU LesserGeneral Public *
* License along with OpenFlipper. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $LastChangedBy$ *
* $Date$ *
* *
\*===========================================================================*/
#ifndef TREEMODEL_H
#define TREEMODEL_H
#include <QAbstractItemModel>
#include <QModelIndex>
#include <QVariant>
#include "TreeItem.hh"
class TreeModel : public QAbstractItemModel
{
Q_OBJECT
signals:
// the connected TreeView changed data
void dataChangedInside(int _id, int _column,const QVariant& _value);
// an object was moved via dragNdrop
void moveBaseObject(int _id, int _newParentId);
public:
/// Constructor
TreeModel(QObject *_parent = 0);
/// Destructor
~TreeModel();
//===========================================================================
/** @name inherited from QAbstractItemModel
* @{ */
//===========================================================================
public:
/// Get the data of the corresponding entry
QVariant data(const QModelIndex &_index,int _role) const;
/// return the types of the corresponding entry
Qt::ItemFlags flags(const QModelIndex &_index) const;
/// return the header data of the model
QVariant headerData(int _section,
Qt::Orientation _orientation,
int _role = Qt::DisplayRole) const;
/// Get the ModelIndex at given row,column
QModelIndex index(int _row, int _column,
const QModelIndex &_parent = QModelIndex()) const;
/// Get the parent ModelIndex
QModelIndex parent(const QModelIndex &_index) const;
/// get the number of rows
int rowCount(const QModelIndex &_parent = QModelIndex()) const;
/** \brief Return the number of columns
*
* @param _parent unused
* @return return always 4
*/
int columnCount(const QModelIndex &_parent = QModelIndex()) const;
/** \brief Set Data at 'index' to 'value'
*
* @param _index a ModelIndex defining the positin in the model
* @param _value the new value
* @param _role unused
* @return return if the data was set successfully
*/
bool setData(const QModelIndex &_index, const QVariant &_value , int _role);
/** @} */
//===========================================================================
/** @name Internal DataStructure (the TreeItem Tree)
* @{ */
//===========================================================================
public:
/// Return the ModelIndex corresponding to a given TreeItem and Column
QModelIndex getModelIndex(TreeItem* _object, int _column );
/// Check if the given item is the root item
bool isRoot(TreeItem* _item);
/// Get the name of a given object
bool getObjectName(TreeItem* _object , QString& _name);
/// Get the TreeItem corresponding to a given ModelIndex
TreeItem *getItem(const QModelIndex &_index) const;
/// Get the TreeItem corresponding to a given OpenFlipper ObjectID
TreeItem *getItem(const int _id) const;
/// Get the name of a TreeItem corresponding to a given ModelIndex
QString itemName(const QModelIndex &_index) const;
/// Get the id of a TreeItem corresponding to a given ModelIndex
int itemId(const QModelIndex &_index) const;
/// The object with the given id has been changed. Check if model also has to be changed
void objectChanged(int _id);
/// The object with the given id has been added. add it to the internal tree
void objectAdded(BaseObject* _object);
/// The object with the given id has been deleted. delete it from the internal tree
void objectDeleted(int _id);
/// move the item to a new parent
void moveItem(TreeItem* _item, TreeItem* _parent );
private:
/// Root item of the tree
TreeItem* rootItem_;
/** @} */
//===========================================================================
/** @name Drag and Drop
* @{ */
//===========================================================================
public:
/// supported drag & Drop actions
Qt::DropActions supportedDropActions() const;
/// stores the mimeType for Drag & Drop
QStringList mimeTypes() const;
/// get the mimeData for a given ModelIndex
QMimeData* mimeData(const QModelIndexList& indexes) const;
/** \brief This is called when mimeData is dropped
*
* @param data The dropped data
* @param action The definition of the dropAction which occurred
* @param row Unused
* @param column Unused
* @param parent Parent under which the drop occurred
* @return returns if the drop was successful
*/
bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent);
/** @} */
};
#endif
| heartvalve/OpenFlipper | Plugin-Datacontrol/TreeModel.hh | C++ | gpl-3.0 | 7,695 |
/*
package de.elxala.zWidgets
Copyright (C) 2005-2017 Alejandro Xalabarder Aulet
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package javaj.widgets;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import de.elxala.langutil.*;
import de.elxala.Eva.*;
import de.elxala.mensaka.*;
import javaj.widgets.kits.dndFileTransHandler;
import javaj.widgets.basics.*;
import javaj.widgets.graphics.*;
/*
//(o) WelcomeGastona_source_javaj_widgets (m) zImage
========================================================================================
================ documentation for javajCatalog.gast ===================================
========================================================================================
#gastonaDoc#
<docType> javaj_widget
<name> zImage
<groupInfo> misc
<javaClass> javaj.widgets.zImage
<importance> 4
<desc> //An image (rapid prefix 'm')
<help>
//
// To show an image of format GIF, JPEG, or PNG from a file (see javax.swing.ImageIcon)
// The file path might be a file, a resource found in the current class path or an Url.
//
<prefix> m
<attributes>
name , in_out, possibleValues , desc
, in , file name , //File name of the image
visible , in , 0 / 1 , //Value 0 to make the widget not visible
enabled , in , 0 / 1 , //Value 0 to disable the widget
droppedFiles , out , (Eva table) , //Eva table (pathFile,fileName,extension,fullPath,date,size) containing all dropped files. Note that this attribute has to exist in order to enable drag & dropping files into this Component.
droppedDirs , out , (Eva table) , //Eva table (pathFile,fileName,extension,fullPath,date,size) containing all dropped directories. Note that this attribute has to exist in order to enable drag & dropping files into this Component.
<messages>
msg, in_out, desc
data! , in , update data
control! , in , update control
, out , Image has been clicked
droppedFiles, out , If files drag & drop enabled this message indicates that the user has dropped files (see attribute 'droppedFiles')
droppedDirs , out , If directories drag & drop is enabled this message indicates that the user has dropped directories (see attribute 'droppedDirs')
<examples>
gastSample
hello Image
image viewer
<hello Image>
//#javaj#
//
// <frames> F, Hello zImage
//
// <layout of F>
// PANEL, X
// mImage
//
//#data#
//
// <mImage> 'javaj/img/miDesto.png
//
<image viewer>
//#javaj#
//
// <frames> F, Sample Image viewer
//
// <layout of F>
// EVA, 10, 10, 6, 6
//
// ---, 300 , X
// , bDir , mImage
// X , aTree , +
//
//#data#
//
// <bDir> 'Image Directory
// <bDir DIALOG> DIR
//
//#listix#
//
// <main0>
// SET VAR, aTree separator, @<:sys file.separator>
//
// <-- bDir>
// SCAN, ADDFILES,, @<bDir chosen>, +, png, +, gif, +, jpeg, +, jpg
// -->, aTree data!, sqlSelect, //SELECT fullPath FROM scan_all;
//
// <-- aTree>
// -->, mImage data!,, @<aTree selectedPath>
//
#**FIN_EVA#
*/
/**
*/
public class zImage extends JPanel implements MouseListener, MensakaTarget
{
protected basicAparato helper = null;
protected dndFileTransHandler dndHandler = null;
protected Color backColor = Color.GRAY; //new JButton().getBackground (); // new JButton().getBackgroundColor ();
// own data
protected Icon theImage = null;
protected float alpha = 0.f;
public zImage ()
{
// default constructor to allow instantiation using <javaClass of...>
}
// ------
public zImage (String map_name)
{
init (map_name);
addMouseListener (this);
}
public void setName (String map_name)
{
init (map_name);
}
public void init (String map_name)
{
super.setName (map_name);
helper = new basicAparato ((MensakaTarget) this, new widgetEBS (map_name, null, null));
// ??
//setLayout (new BorderLayout());
setBackground(new JButton().getBackground ());
}
private void readAlpha ()
{
alpha = (float) stdlib.atof (helper.ebs ().getSimpleDataAttribute ("alpha", "1"));
if (alpha == 1.f)
alpha = (float) stdlib.atof (helper.ebs ().getSimpleDataAttribute ("opacity", "1"));
String backC = helper.ebs ().getSimpleDataAttribute ("backcolor");
if (backC != null)
{
uniColor uco = new uniColor ();
uco.parseColor (backC);
backColor = uco.getNativeColor ();
}
}
public boolean takePacket (int mappedID, EvaUnit euData, String [] pars)
{
switch (mappedID)
{
case widgetConsts.RX_UPDATE_DATA:
helper.ebs ().setDataControlAttributes (euData, null, pars);
theImage = javaLoad.getSomeHowImageIcon (helper.ebs ().getText ());
readAlpha ();
//paintImmediately (new Rectangle (0, 0, getSize().width, getSize().height));
paintImmediately (getVisibleRect());
// repaint ();
break;
case widgetConsts.RX_UPDATE_CONTROL:
helper.ebs ().setDataControlAttributes (null, euData, pars);
setEnabled (helper.ebs ().getEnabled ());
readAlpha ();
//(o) TODO_REVIEW visibility issue
// avoid setVisible (false) when the component is not visible (for the first time ?)
boolean visible = helper.ebs ().getVisible ();
if (visible && isShowing ())
setVisible (visible);
if (dndHandler == null)
{
if (helper.ebs ().isDroppable ())
{
// made it "dropable capable"
// drag & drop ability
//
/**
Make the zWidget to drag'n'drop of files or directories capable
Note that the zWidget is not subscribed to the drag'n'drop message itself ("%name% droppedFiles" or ..droppedDirs")
therefore it will not take any action on this event. It is a task of a controller to
examine, accept, process and insert into the widget the files if desired and convenient
Note that at this point the control for the zWidget (helper.ebs().getControl ())
is null and we have to update it into the handler when it chanhges
*/
dndHandler = new dndFileTransHandler (
helper.ebs().getControl (),
helper.ebs().evaName (""),
dndFileTransHandler.arrALL_FIELDS
);
setTransferHandler (dndHandler);
}
}
else
{
// every time the control changes set it to the drag&drop handler
dndHandler.setCommunicationLine (helper.ebs().getControl ());
}
break;
default:
return false;
}
return true;
}
public Dimension getPreferredSize ()
{
return (theImage != null) ?
new Dimension (theImage.getIconWidth(), theImage.getIconHeight()) :
new Dimension (10, 10);
}
public void mousePressed (MouseEvent e)
{
// helper.signalAction ();
}
public void mouseReleased (MouseEvent e)
{
// helper.signalAction ();
}
public void mouseClicked (MouseEvent e)
{
helper.signalAction ();
}
public void mouseEntered (MouseEvent e)
{
// helper.signalAction ();
}
public void mouseExited (MouseEvent e)
{
// helper.signalAction ();
}
public void paint(Graphics g)
{
Dimension d = getSize();
if (d.width <= 0 || d.height <= 0) return; // >>>> return
if (backColor != null)
{
g.setColor (backColor);
g.fillRect (0, 0, d.width, d.height);
}
else
g.clearRect (0, 0, d.width, d.height);
if (theImage == null) return; // No image yet!
int left = (d.width - theImage.getIconWidth()) / 2;
int right = (d.height - theImage.getIconHeight()) / 2;
if (alpha < 1.f)
{
Graphics2D g2d = (Graphics2D) g;
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
theImage.paintIcon(this, g2d, left, right);
}
else
theImage.paintIcon(this, g, left, right);
}
}
| wakeupthecat/gastona | pc/src/javaj/widgets/zImage.java | Java | gpl-3.0 | 9,717 |
/*
* qZeb3D - calculating 3D-point-clouds from Georawfiles/Georohdaten of german ZEB
* Copyright (C) 2016 Christoph Jung
*
* 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 "track.h"
Track::Track(QObject *parent) : QObject(parent) {
this->zebAdmin = false;
this->parametres = false;
}
void Track::setDataMedium(QString medium) {
this->dataMedium = medium;
}
QString Track::getDataMedium() {
return this->dataMedium;
}
int Track::getYear() {
return year;
}
void Track::setYear(int value) {
year = value;
}
QString Track::getStreetClass() {
return streetClass;
}
void Track::setStreetClass(QString value) {
streetClass = value;
}
QString Track::getCountry() {
return country;
}
void Track::setCountry(QString value) {
country = value;
}
QVector<Camera *> Track::getCameras() {
return cameras;
}
void Track::addCamera(Camera *value) {
cameras.append(value);
}
QString Track::getReason()
{
return reason;
}
void Track::setReason(QString value)
{
reason = value;
}
QString Track::getSystem()
{
return system;
}
void Track::setSystem(QString value)
{
system = value;
}
QString Track::getVersion()
{
return version;
}
void Track::setVersion(QString value)
{
version = value;
}
QString Track::getDesignerCompany()
{
return designerCompany;
}
void Track::setDesignerCompany(QString value)
{
designerCompany = value;
}
QString Track::getOperatorCompany()
{
return operatorCompany;
}
void Track::setOperatorCompany(QString value)
{
operatorCompany = value;
}
QString Track::getPrinciple()
{
return principle;
}
void Track::setPrinciple(QString value)
{
principle = value;
}
QString Track::getDrivingPerson()
{
return drivingPerson;
}
void Track::setDrivingPerson(QString value)
{
drivingPerson = value;
}
QString Track::getOperatingPerson()
{
return operatingPerson;
}
void Track::setOperatingPerson(QString value)
{
operatingPerson = value;
}
QString Track::getPositionSystem()
{
return positionSystem;
}
void Track::setPositionSystem(QString value)
{
positionSystem = value;
}
bool Track::getZebAdmin()
{
return zebAdmin;
}
void Track::setZebAdmin(bool value)
{
zebAdmin = value;
}
bool Track::getParametres()
{
return parametres;
}
void Track::setParametres(bool value)
{
parametres = value;
}
Longitudinal *Track::getLongitudinalMeasurement()
{
return longitudinalMeasurement;
}
void Track::setLongitudinalMeasurement(Longitudinal *value)
{
longitudinalMeasurement = value;
}
Transverse *Track::getTransverseMeasurement()
{
return transverseMeasurement;
}
void Track::setTransverseMeasruement(Transverse *value)
{
transverseMeasurement = value;
}
Damage *Track::getDamageMeasurement()
{
return damageMeasurement;
}
void Track::setDamageMeasurement(Damage *value)
{
damageMeasurement = value;
}
QString Track::getNumberPlate()
{
return numberPlate;
}
void Track::setNumberPlate(QString value)
{
numberPlate = value;
}
| jagodki/qzeb3d | ZebData/Rawdata/track.cpp | C++ | gpl-3.0 | 3,636 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Search_Lucene
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Exception.php,v 1.1.2.3 2011-05-30 08:31:01 root Exp $
*/
/**
* Framework base exception
*/
require_once 'Zend/Search/Lucene/Exception.php';
/**
* @category Zend
* @package Zend_Search_Lucene
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Search_Lucene_Document_Exception extends Zend_Search_Lucene_Exception
{}
| MailCleaner/MailCleaner | www/framework/Zend/Search/Lucene/Document/Exception.php | PHP | gpl-3.0 | 1,162 |
import os
import unittest
from vsg.rules import process
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_035_test_input.vhd'))
lExpected = []
lExpected.append('')
utils.read_file(os.path.join(sTestDir, 'rule_035_test_input.fixed.vhd'), lExpected)
lExpectedCompactAlignmentFalse = []
lExpectedCompactAlignmentFalse.append('')
utils.read_file(os.path.join(sTestDir, 'rule_035_test_input.fixed_compact_alignment_false.vhd'), lExpectedCompactAlignmentFalse)
class test_process_rule(unittest.TestCase):
def setUp(self):
self.oFile = vhdlFile.vhdlFile(lFile)
self.assertIsNone(eError)
def test_rule_035(self):
oRule = process.rule_035()
self.assertTrue(oRule)
self.assertEqual(oRule.name, 'process')
self.assertEqual(oRule.identifier, '035')
lExpected = [30, 31, 35, 38]
oRule.analyze(self.oFile)
self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations))
def test_fix_rule_035(self):
oRule = process.rule_035()
oRule.fix(self.oFile)
lActual = self.oFile.get_lines()
self.assertEqual(lExpected, lActual)
oRule.analyze(self.oFile)
self.assertEqual(oRule.violations, [])
def test_rule_035_compact_alignment_false(self):
oRule = process.rule_035()
oRule.compact_alignment = False
oRule.include_lines_without_comments = False
lExpected = [30, 31, 38]
oRule.analyze(self.oFile)
self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations))
def test_fix_rule_035_compact_alignment_false(self):
oRule = process.rule_035()
oRule.compact_alignment = False
oRule.include_lines_without_comments = False
oRule.fix(self.oFile)
lActual = self.oFile.get_lines()
self.assertEqual(lExpectedCompactAlignmentFalse, lActual)
oRule.analyze(self.oFile)
self.assertEqual(oRule.violations, [])
| jeremiah-c-leary/vhdl-style-guide | vsg/tests/process/test_rule_035.py | Python | gpl-3.0 | 2,131 |
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2021 Evan Debenham
*
* 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 com.shatteredpixel.shatteredpixeldungeon.actors.mobs;
import com.shatteredpixel.shatteredpixeldungeon.Assets;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.items.Generator;
import com.shatteredpixel.shatteredpixeldungeon.items.Item;
import com.shatteredpixel.shatteredpixeldungeon.levels.features.Chasm;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.shatteredpixel.shatteredpixeldungeon.sprites.SkeletonSprite;
import com.shatteredpixel.shatteredpixeldungeon.utils.GLog;
import com.watabou.noosa.audio.Sample;
import com.watabou.utils.PathFinder;
import com.watabou.utils.Random;
public class Skeleton extends Mob {
{
spriteClass = SkeletonSprite.class;
HP = HT = 25;
defenseSkill = 9;
EXP = 5;
maxLvl = 10;
loot = Generator.Category.WEAPON;
lootChance = 0.1667f; //by default, see rollToDropLoot()
properties.add(Property.UNDEAD);
properties.add(Property.INORGANIC);
}
@Override
public int damageRoll() {
return Random.NormalIntRange( 2, 10 );
}
@Override
public void die( Object cause ) {
super.die( cause );
if (cause == Chasm.class) return;
boolean heroKilled = false;
for (int i = 0; i < PathFinder.NEIGHBOURS8.length; i++) {
Char ch = findChar( pos + PathFinder.NEIGHBOURS8[i] );
if (ch != null && ch.isAlive()) {
int damage = Random.NormalIntRange(6, 12);
damage = Math.max( 0, damage - (ch.drRoll() + ch.drRoll()) );
ch.damage( damage, this );
if (ch == Dungeon.hero && !ch.isAlive()) {
heroKilled = true;
}
}
}
if (Dungeon.level.heroFOV[pos]) {
Sample.INSTANCE.play( Assets.Sounds.BONES );
}
if (heroKilled) {
Dungeon.fail( getClass() );
GLog.n( Messages.get(this, "explo_kill") );
}
}
@Override
public void rollToDropLoot() {
//each drop makes future drops 1/2 as likely
// so loot chance looks like: 1/6, 1/12, 1/24, 1/48, etc.
lootChance *= Math.pow(1/2f, Dungeon.LimitedDrops.SKELE_WEP.count);
super.rollToDropLoot();
}
@Override
protected Item createLoot() {
Dungeon.LimitedDrops.SKELE_WEP.count++;
return super.createLoot();
}
@Override
public int attackSkill( Char target ) {
return 12;
}
@Override
public int drRoll() {
return Random.NormalIntRange(0, 5);
}
}
| 00-Evan/shattered-pixel-dungeon | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/mobs/Skeleton.java | Java | gpl-3.0 | 3,174 |
<?php
use Phast\System;
System::$Configuration["Database.ServerName"] = "localhost";
System::$Configuration["Database.UserName"] = "Sydne_Sullen";
System::$Configuration["Database.Password"] = "Hb+z.p)iF/}P.*aoIW6efA2.#";
System::$Configuration["Database.DatabaseName"] = "Sydne_SullenStudio";
System::$Configuration["Database.TablePrefix"] = "";
System::$Configuration["Application.BasePath"] = "http://sydne.sullen-studio.com";
System::$Configuration["WebFramework.StaticPath"] = "http://static.alcehosting.net";
System::$Configuration["Company.Title"] = "Sullen Studio";
?> | alcexhim/Sydne | PrivateWebsite/Include/Configuration.inc.php | PHP | gpl-3.0 | 604 |
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'operaciones',
templateUrl: './operaciones.component.html',
styleUrls: ['./operaciones.component.css']
})
export class OperacionesComponent implements OnInit {
constructor() { }
ngOnInit(): void { }
}
| NetRevolutions/SICOTYC | SICOTYC/UI/src/app/sicotyc/operaciones/operaciones.component.ts | TypeScript | gpl-3.0 | 297 |
"""
Indivo Model for VideoMessage
"""
from fact import Fact
from django.db import models
from django.conf import settings
class VideoMessage(Fact):
file_id=models.CharField(max_length=200)
storage_type=models.CharField(max_length=200)
subject=models.CharField(max_length=200)
from_str=models.CharField(max_length=200)
date_recorded=models.DateTimeField(null=True)
date_sent=models.DateTimeField(null=True)
def __unicode__(self):
return 'VideoMessage %s' % self.id
| newmediamedicine/indivo_server_1_0 | indivo/models/fact_objects/videomessage.py | Python | gpl-3.0 | 489 |
package de.danielluedecke.zettelkasten.database;
public class Result {
Document[] collection = new Document[0];
public Result() {}
public Result(Document[]collection) {
this.collection = collection;
}
public int getCount() {return collection.length;}
public Document getItem(int i) {return collection[i];}
}
| RalfBarkow/Zettelkasten | src/main/java/de/danielluedecke/zettelkasten/database/Result.java | Java | gpl-3.0 | 345 |
class HomeController < ApplicationController
def index
end
def nice
end
end
| tudor3084/percent2 | app/controllers/home_controller.rb | Ruby | gpl-3.0 | 95 |
/**************************************************************************
* Otter Browser: Web browser controlled by the user, not vice-versa.
* Copyright (C) 2015 - 2016 Michal Dutkiewicz aka Emdek <michal@emdek.pl>
*
* 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 "BookmarkWidget.h"
#include "../MainWindow.h"
#include "../Menu.h"
#include "../../core/BookmarksManager.h"
#include "../../core/Utils.h"
#include "../../core/WindowsManager.h"
#include <QtCore/QDateTime>
#include <QtGui/QMouseEvent>
namespace Otter
{
BookmarkWidget::BookmarkWidget(BookmarksItem *bookmark, const ActionsManager::ActionEntryDefinition &definition, QWidget *parent) : ToolButtonWidget(definition, parent),
m_bookmark(bookmark)
{
updateBookmark(m_bookmark);
connect(BookmarksManager::getModel(), SIGNAL(bookmarkRemoved(BookmarksItem*)), this, SLOT(removeBookmark(BookmarksItem*)));
connect(BookmarksManager::getModel(), SIGNAL(bookmarkModified(BookmarksItem*)), this, SLOT(updateBookmark(BookmarksItem*)));
}
BookmarkWidget::BookmarkWidget(const QString &path, const ActionsManager::ActionEntryDefinition &definition, QWidget *parent) : ToolButtonWidget(definition, parent),
m_bookmark(BookmarksManager::getModel()->getItem(path))
{
updateBookmark(m_bookmark);
connect(BookmarksManager::getModel(), SIGNAL(bookmarkRemoved(BookmarksItem*)), this, SLOT(removeBookmark(BookmarksItem*)));
connect(BookmarksManager::getModel(), SIGNAL(bookmarkModified(BookmarksItem*)), this, SLOT(updateBookmark(BookmarksItem*)));
}
void BookmarkWidget::mouseReleaseEvent(QMouseEvent *event)
{
QToolButton::mouseReleaseEvent(event);
if ((event->button() == Qt::LeftButton || event->button() == Qt::MiddleButton) && m_bookmark)
{
MainWindow *mainWindow(MainWindow::findMainWindow(parentWidget()));
if (mainWindow)
{
mainWindow->getWindowsManager()->open(m_bookmark, WindowsManager::calculateOpenHints(WindowsManager::DefaultOpen, event->button(), event->modifiers()));
}
}
}
void BookmarkWidget::removeBookmark(BookmarksItem *bookmark)
{
if (m_bookmark && m_bookmark == bookmark)
{
m_bookmark = NULL;
deleteLater();
}
}
void BookmarkWidget::updateBookmark(BookmarksItem *bookmark)
{
if (bookmark != m_bookmark)
{
return;
}
const QString title(m_bookmark->data(BookmarksModel::TitleRole).toString().isEmpty() ? tr("(Untitled)") : m_bookmark->data(BookmarksModel::TitleRole).toString());
const BookmarksModel::BookmarkType type(static_cast<BookmarksModel::BookmarkType>(m_bookmark->data(BookmarksModel::TypeRole).toInt()));
if (type == BookmarksModel::RootBookmark || type == BookmarksModel::TrashBookmark || type == BookmarksModel::FolderBookmark)
{
Menu *menu(new Menu(Menu::BookmarksMenuRole, this));
menu->menuAction()->setData(m_bookmark->index());
setPopupMode(QToolButton::InstantPopup);
setToolTip(title);
setMenu(menu);
setEnabled(m_bookmark->rowCount() > 0);
}
else
{
QStringList toolTip;
toolTip.append(tr("Title: %1").arg(title));
if (!m_bookmark->data(BookmarksModel::UrlRole).toString().isEmpty())
{
toolTip.append(tr("Address: %1").arg(m_bookmark->data(BookmarksModel::UrlRole).toString()));
}
if (m_bookmark->data(BookmarksModel::DescriptionRole).isValid())
{
toolTip.append(tr("Description: %1").arg(m_bookmark->data(BookmarksModel::DescriptionRole).toString()));
}
if (!m_bookmark->data(BookmarksModel::TimeAddedRole).toDateTime().isNull())
{
toolTip.append(tr("Created: %1").arg(m_bookmark->data(BookmarksModel::TimeAddedRole).toDateTime().toString()));
}
if (!m_bookmark->data(BookmarksModel::TimeVisitedRole).toDateTime().isNull())
{
toolTip.append(tr("Visited: %1").arg(m_bookmark->data(BookmarksModel::TimeVisitedRole).toDateTime().toString()));
}
setToolTip(QLatin1String("<div style=\"white-space:pre;\">") + toolTip.join(QLatin1Char('\n')) + QLatin1String("</div>"));
setMenu(NULL);
}
setText(title);
setStatusTip(m_bookmark->data(BookmarksModel::UrlRole).toString());
setIcon(m_bookmark->data(Qt::DecorationRole).value<QIcon>());
}
}
| elebow/otter | src/ui/toolbars/BookmarkWidget.cpp | C++ | gpl-3.0 | 4,719 |
package com.simplecity.amp_library.ui.modelviews;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.simplecity.amp_library.R;
import com.simplecity.amp_library.model.Genre;
import com.simplecity.amp_library.ui.adapters.ViewType;
import com.simplecity.amp_library.ui.views.NonScrollImageButton;
import com.simplecity.amp_library.utils.StringUtils;
import com.simplecityapps.recycler_adapter.model.BaseViewModel;
import com.simplecityapps.recycler_adapter.recyclerview.BaseViewHolder;
public class GenreView extends BaseViewModel<GenreView.ViewHolder> implements
SectionedView {
public interface ClickListener {
void onItemClick(Genre genre);
void onOverflowClick(View v, Genre genre);
}
public Genre genre;
@Nullable
private ClickListener clickListener;
public GenreView(Genre genre) {
this.genre = genre;
}
public void setClickListener(@Nullable ClickListener clickListener) {
this.clickListener = clickListener;
}
void onClick() {
if (clickListener != null) {
clickListener.onItemClick(genre);
}
}
void onOverflowClick(View v) {
if (clickListener != null) {
clickListener.onOverflowClick(v, genre);
}
}
@Override
public int getViewType() {
return ViewType.GENRE;
}
@Override
public int getLayoutResId() {
return R.layout.list_item_two_lines;
}
@Override
public void bindView(ViewHolder holder) {
super.bindView(holder);
holder.lineOne.setText(genre.name);
String albumAndSongsLabel = StringUtils.makeAlbumAndSongsLabel(holder.itemView.getContext(), -1, genre.numSongs);
if (!TextUtils.isEmpty(albumAndSongsLabel)) {
holder.lineTwo.setText(albumAndSongsLabel);
holder.lineTwo.setVisibility(View.VISIBLE);
} else {
holder.lineTwo.setVisibility(View.GONE);
}
}
@Override
public ViewHolder createViewHolder(ViewGroup parent) {
return new ViewHolder(createView(parent));
}
@Override
public String getSectionName() {
String string = StringUtils.keyFor(genre.name);
if (!TextUtils.isEmpty(string)) {
string = string.substring(0, 1).toUpperCase();
} else {
string = " ";
}
return string;
}
public static class ViewHolder extends BaseViewHolder<GenreView> {
@BindView(R.id.line_one)
public TextView lineOne;
@BindView(R.id.line_two)
public TextView lineTwo;
@BindView(R.id.btn_overflow)
public NonScrollImageButton overflowButton;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(v -> viewModel.onClick());
overflowButton.setOnClickListener(v -> viewModel.onOverflowClick(v));
}
@Override
public String toString() {
return "GenreView.ViewHolder";
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GenreView genreView = (GenreView) o;
return genre != null ? genre.equals(genreView.genre) : genreView.genre == null;
}
@Override
public int hashCode() {
return genre != null ? genre.hashCode() : 0;
}
}
| timusus/Shuttle | app/src/main/java/com/simplecity/amp_library/ui/modelviews/GenreView.java | Java | gpl-3.0 | 3,659 |
package worker
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"sync"
"time"
"github.com/docker/distribution/reference"
dc "github.com/docker/docker/client"
"github.com/ethereum/go-ethereum/common"
log "github.com/noxiouz/zapctx/ctxlog"
"github.com/opencontainers/go-digest"
"github.com/sonm-io/core/insonmnia/auth"
"github.com/sonm-io/core/util"
"github.com/sonm-io/core/util/xdocker"
"go.uber.org/zap"
)
type Whitelist interface {
Allowed(ctx context.Context, ref xdocker.Reference, auth string) (bool, xdocker.Reference, error)
}
func NewWhitelist(ctx context.Context, config *WhitelistConfig) Whitelist {
wl := whitelist{
superusers: make(map[string]struct{}),
}
for _, su := range config.PrivilegedAddresses {
parsed := common.HexToAddress(su)
wl.superusers[parsed.Hex()] = struct{}{}
}
go wl.updateRoutine(ctx, config.Url, config.RefreshPeriod)
return &wl
}
type WhitelistRecord struct {
AllowedHashes []digest.Digest `json:"allowed_hashes"`
}
type whitelist struct {
superusers map[string]struct{}
Records map[string]WhitelistRecord
RecordsMu sync.RWMutex
}
func (w *whitelist) updateRoutine(ctx context.Context, url string, updatePeriod uint) error {
ticker := util.NewImmediateTicker(time.Duration(time.Second * time.Duration(updatePeriod)))
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
err := w.load(ctx, url)
if err != nil {
log.G(ctx).Error("could not load whitelist", zap.Error(err))
}
}
}
}
func (w *whitelist) load(ctx context.Context, url string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
log.G(ctx).Info("fetched whitelist")
if resp.StatusCode != 200 {
return fmt.Errorf("failed to download whitelist - got %s", resp.Status)
}
return w.fillFromJsonReader(ctx, resp.Body)
}
func (w *whitelist) fillFromJsonReader(ctx context.Context, jsonReader io.Reader) error {
decoder := json.NewDecoder(jsonReader)
r := make(map[string]WhitelistRecord)
err := decoder.Decode(&r)
if err != nil {
return fmt.Errorf("could not decode whitelist data: %v", err)
}
w.RecordsMu.Lock()
w.Records = r
w.RecordsMu.Unlock()
return nil
}
func (w *whitelist) digestAllowed(name string, digest digest.Digest) (bool, error) {
ref, err := reference.ParseNormalizedNamed(name)
if err != nil {
return false, err
}
w.RecordsMu.RLock()
defer w.RecordsMu.RUnlock()
record, ok := w.Records[ref.Name()]
if !ok {
return false, nil
}
for _, allowedDigest := range record.AllowedHashes {
if allowedDigest == digest {
return true, nil
}
}
return false, nil
}
func (w *whitelist) Allowed(ctx context.Context, ref xdocker.Reference, authority string) (bool, xdocker.Reference, error) {
wallet, err := auth.ExtractWalletFromContext(ctx)
if err != nil {
log.G(ctx).Warn("could not extract wallet from context", zap.Error(err))
return false, ref, err
}
_, ok := w.superusers[wallet.Hex()]
if ok {
return true, ref, nil
}
if !ref.HasName() {
return false, ref, errors.New("can not check whitelist for unnamed reference")
}
if ref.HasDigest() {
allowed, err := w.digestAllowed(ref.Name(), ref.Digest())
return allowed, ref, err
}
dockerClient, err := dc.NewEnvClient()
if err != nil {
return false, ref, err
}
defer dockerClient.Close()
inspection, err := dockerClient.DistributionInspect(ctx, ref.String(), authority)
if err != nil {
return false, ref, fmt.Errorf("could not perform DistributionInspect for %s: %v", ref.String(), err)
}
ref, err = ref.WithDigest(inspection.Descriptor.Digest)
if err != nil {
return false, ref, fmt.Errorf("could not add digest to reference %s: %v", ref.String(), err)
}
allowed, err := w.digestAllowed(ref.Name(), inspection.Descriptor.Digest)
return allowed, ref, err
}
| sonm-io/core | insonmnia/worker/whitelist.go | GO | gpl-3.0 | 3,863 |
<?php
/**
* flatCore Content Management System
* Installer/Updater
*/
session_start();
error_reporting(E_ALL ^E_NOTICE);
require '../config.php';
$modus = 'install';
define('INSTALLER', TRUE);
if(isset($_GET['l']) && is_dir('../lib/lang/'.basename($_GET['l']).'/')) {
$_SESSION['lang'] = basename($_GET['l']);
}
if(!isset($_SESSION['lang']) || $_SESSION['lang'] == '') {
$l = 'de';
$modus = 'choose_lang';
} else {
$l = $_SESSION['lang'];
}
include 'php/functions.php';
include '../lib/lang/'.$l.'/dict-install.php';
include '../acp/core/icons.php';
if(is_file("$fc_db_content")) {
$modus = "update";
$db_type = 'sqlite';
}
if(is_file("../config_database.php")) {
$modus = "update";
$db_type = 'mysql';
}
if(isset($_POST['check_database'])) {
include 'php/check_connection.php';
}
if($_SESSION['user_class'] == "administrator") {
$modus = "update";
}
if($modus == "update") {
/* updates for admins only */
if($_SESSION['user_class'] != "administrator"){
die("PERMISSION DENIED!");
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><?php echo"$modus"; ?> flatCore | Content Management System</title>
<script src="../styles/default/js/jquery.min.js"></script>
<script src="../styles/default/js/bootstrap.bundle.min.js"></script>
<link media="screen" rel="stylesheet" type="text/css" href="../styles/default/css/styles.min.css" />
<link media="screen" rel="stylesheet" type="text/css" href="css/styles.css" />
<link href="../acp/fontawesome/css/all.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div id="inst-background">
<div id="inst-header">
<div style="float:right;margin-top:-38px;"><span class="badge badge-info p-2"><?php echo"$modus" ?></span></div>
<h1>flatCore <small>Installation & Setup</small></h1>
</div>
<div id="inst-body">
<?php
if($modus == "install") {
include("inc.install.php");
} else if($modus == "update") {
include("inc.update.php");
} else {
echo '<h3 class="text-center">Choose your Language ...</h3><hr>';
echo '<div class="row">';
echo '<div class="col-md-6">';
echo '<p class="text-center"><a href="index.php?l=de"><img src="../lib/lang/de/flag.png" class="img-rounded"><br>DE</a></p>';
echo '</div>';
echo '<div class="col-md-6">';
echo '<p class="text-center"><a href="index.php?l=en"><img src="../lib/lang/en/flag.png" class="img-rounded"><br>EN</a></p>';
echo '</div>';
echo '</div>';
}
?>
</div>
<div id="inst-footer">
<a href="http://www.flatcore.org">
<img src="images/logo.png" alt="flatCore Logo">
<h3>flatCore<br><small>Content Management System</small></h3>
</a>
</div>
</div>
<p class="text-center"><?php echo date("Y/m/d H:i:s",time()); ?></p>
</div>
</body>
</html>
| flatCore/flatCore-CMS | install/index.php | PHP | gpl-3.0 | 2,785 |
using System.Diagnostics;
using System.ComponentModel;
using System.IO;
using System.Text;
namespace System.IO.Ports
{
[MonitoringDescriptionAttribute("SerialPortDesc")]
public class SerialPort : Component
{
public const int InfiniteTimeout = -1;
[MonitoringDescriptionAttribute("SerialErrorReceived")]
public event SerialErrorReceivedEventHandler ErrorReceived;
[MonitoringDescriptionAttribute("SerialPinChanged")]
public event SerialPinChangedEventHandler PinChanged;
[MonitoringDescriptionAttribute("SerialDataReceived")]
public event SerialDataReceivedEventHandler DataReceived;
[BrowsableAttribute(false)]
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
public Stream BaseStream
{
get { throw new NotImplementedException(); }
}
[BrowsableAttribute(true)]
[MonitoringDescriptionAttribute("BaudRate")]
[DefaultValueAttribute(9600)]
public int BaudRate
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[BrowsableAttribute(false)]
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
public bool BreakState
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
[BrowsableAttribute(false)]
public int BytesToWrite
{
get { throw new NotImplementedException(); }
}
[BrowsableAttribute(false)]
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
public int BytesToRead
{
get { throw new NotImplementedException(); }
}
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
[BrowsableAttribute(false)]
public bool CDHolding
{
get { throw new NotImplementedException(); }
}
[BrowsableAttribute(false)]
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
public bool CtsHolding
{
get { throw new NotImplementedException(); }
}
[MonitoringDescriptionAttribute("DataBits")]
[BrowsableAttribute(true)]
[DefaultValueAttribute(8)]
public int DataBits
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[DefaultValueAttribute(false)]
[MonitoringDescriptionAttribute("DiscardNull")]
[BrowsableAttribute(true)]
public bool DiscardNull
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[BrowsableAttribute(false)]
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
public bool DsrHolding
{
get { throw new NotImplementedException(); }
}
[MonitoringDescriptionAttribute("DtrEnable")]
[BrowsableAttribute(true)]
[DefaultValueAttribute(false)]
public bool DtrEnable
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
[MonitoringDescriptionAttribute("Encoding")]
[BrowsableAttribute(false)]
public Encoding Encoding
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[MonitoringDescriptionAttribute("Handshake")]
//[DefaultValueAttribute(Mono.Cecil.CustomAttributeArgument)]
[BrowsableAttribute(true)]
public Handshake Handshake
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[BrowsableAttribute(false)]
public bool IsOpen
{
get { throw new NotImplementedException(); }
}
[DefaultValueAttribute("\n")]
[MonitoringDescriptionAttribute("NewLine")]
[BrowsableAttribute(false)]
public string NewLine
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[MonitoringDescriptionAttribute("Parity")]
[BrowsableAttribute(true)]
//[DefaultValueAttribute(Mono.Cecil.CustomAttributeArgument)]
public Parity Parity
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[DefaultValueAttribute(63)]
[MonitoringDescriptionAttribute("ParityReplace")]
[BrowsableAttribute(true)]
public byte ParityReplace
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[DefaultValueAttribute("COM1")]
[MonitoringDescriptionAttribute("PortName")]
[BrowsableAttribute(true)]
public string PortName
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[BrowsableAttribute(true)]
[DefaultValueAttribute(4096)]
[MonitoringDescriptionAttribute("ReadBufferSize")]
public int ReadBufferSize
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[DefaultValueAttribute(-1)]
[BrowsableAttribute(true)]
[MonitoringDescriptionAttribute("ReadTimeout")]
public int ReadTimeout
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[MonitoringDescriptionAttribute("ReceivedBytesThreshold")]
[BrowsableAttribute(true)]
[DefaultValueAttribute(1)]
public int ReceivedBytesThreshold
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[BrowsableAttribute(true)]
[MonitoringDescriptionAttribute("RtsEnable")]
[DefaultValueAttribute(false)]
public bool RtsEnable
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
//[DefaultValueAttribute(Mono.Cecil.CustomAttributeArgument)]
[MonitoringDescriptionAttribute("StopBits")]
[BrowsableAttribute(true)]
public StopBits StopBits
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[BrowsableAttribute(true)]
[DefaultValueAttribute(2048)]
[MonitoringDescriptionAttribute("WriteBufferSize")]
public int WriteBufferSize
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
[DefaultValueAttribute(-1)]
[MonitoringDescriptionAttribute("WriteTimeout")]
[BrowsableAttribute(true)]
public int WriteTimeout
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public SerialPort(IContainer container)
{
throw new NotImplementedException();
}
public SerialPort()
{
throw new NotImplementedException();
}
public SerialPort(string portName)
{
throw new NotImplementedException();
}
public SerialPort(string portName, int baudRate)
{
throw new NotImplementedException();
}
public SerialPort(string portName, int baudRate, Parity parity)
{
throw new NotImplementedException();
}
public SerialPort(string portName, int baudRate, Parity parity, int dataBits)
{
throw new NotImplementedException();
}
public SerialPort(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
{
throw new NotImplementedException();
}
public void Close()
{
throw new NotImplementedException();
}
protected override void Dispose(bool disposing)
{
throw new NotImplementedException();
}
public void DiscardInBuffer()
{
throw new NotImplementedException();
}
public void DiscardOutBuffer()
{
throw new NotImplementedException();
}
public static string[] GetPortNames()
{
throw new NotImplementedException();
}
public void Open()
{
throw new NotImplementedException();
}
public int Read(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public int ReadChar()
{
throw new NotImplementedException();
}
public int Read(char[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public int ReadByte()
{
throw new NotImplementedException();
}
public string ReadExisting()
{
throw new NotImplementedException();
}
public string ReadLine()
{
throw new NotImplementedException();
}
public string ReadTo(string value)
{
throw new NotImplementedException();
}
public void Write(string text)
{
throw new NotImplementedException();
}
public void Write(char[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public void WriteLine(string text)
{
throw new NotImplementedException();
}
}
}
| zebraxxl/CIL2Java | StdLibs/System/System/IO/Ports/SerialPort.cs | C# | gpl-3.0 | 11,104 |
/*
* Created: 15.04.2012
*
* Copyright (C) 2012 Victor Antonovich (v.antonovich@gmail.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/>.
*/
package su.comp.bk.arch.cpu.opcode;
import su.comp.bk.arch.Computer;
import su.comp.bk.arch.cpu.Cpu;
import su.comp.bk.arch.cpu.addressing.AddressingMode;
import su.comp.bk.arch.cpu.addressing.RegisterAddressingMode;
/**
* Compare operation.
*/
public class CmpOpcode extends DoubleOperandOpcode {
public final static int OPCODE = 020000;
public CmpOpcode(Cpu cpu) {
super(cpu);
}
@Override
public int getOpcode() {
return OPCODE;
}
@Override
public int getExecutionTime() {
int srcAddrCode = getSrcOperandAddressingMode().getCode();
int destAddrCode = getDestOperandAddressingMode().getCode();
return getBaseExecutionTime() + getAddressingTimeA(srcAddrCode) +
((srcAddrCode == RegisterAddressingMode.CODE) ? getAddressingTimeA2(destAddrCode)
: getAddressingTimeA(destAddrCode));
}
@Override
public void execute() {
boolean isByteMode = isByteModeOperation();
AddressingMode srcMode = getSrcOperandAddressingMode();
int srcRegister = getSrcOperandRegister();
// Read source value
srcMode.preAddressingAction(isByteMode, srcRegister);
int srcValue = srcMode.readAddressedValue(isByteMode, srcRegister);
srcMode.postAddressingAction(isByteMode, srcRegister);
if (srcValue != Computer.BUS_ERROR) {
// Read destination value
AddressingMode destMode = getDestOperandAddressingMode();
int destRegister = getDestOperandRegister();
destMode.preAddressingAction(isByteMode, destRegister);
int destValue = destMode.readAddressedValue(isByteMode, destRegister);
destMode.postAddressingAction(isByteMode, destRegister);
if (destValue != Computer.BUS_ERROR) {
int resultValue = srcValue - destValue;
// Set flags
Cpu cpu = getCpu();
cpu.setPswFlagN(isByteMode, resultValue);
cpu.setPswFlagZ(isByteMode, resultValue);
cpu.setPswFlagV((((srcValue ^ destValue) & (~destValue ^ resultValue))
& (isByteMode ? 0200 : 0100000)) != 0);
cpu.setPswFlagC((resultValue & (isByteMode ? ~0377 : ~0177777)) != 0);
}
}
}
}
| 3cky/bkemu-android | app/src/main/java/su/comp/bk/arch/cpu/opcode/CmpOpcode.java | Java | gpl-3.0 | 3,085 |
# -*- coding: utf-8 -*-
# Copyright (C) 2007-2010 Toms Bauģis <toms.baugis at gmail.com>
# This file is part of Project Hamster.
# Project Hamster 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.
# Project Hamster 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 Project Hamster. If not, see <http://www.gnu.org/licenses/>.
import gtk
import gobject
import time
import datetime as dt
from ..lib import stuff, graphics, pytweener
from ..configuration import conf
class Selection(graphics.Sprite):
def __init__(self, start_time = None, end_time = None):
graphics.Sprite.__init__(self, z_order = 100)
self.start_time, self.end_time = None, None
self.width, self.height = None, None
self.fill = None # will be set to proper theme color on render
self.fixed = False
self.start_label = graphics.Label("", 8, "#333", visible = False)
self.end_label = graphics.Label("", 8, "#333", visible = False)
self.duration_label = graphics.Label("", 8, "#FFF", visible = False)
self.add_child(self.start_label, self.end_label, self.duration_label)
self.connect("on-render", self.on_render)
def on_render(self, sprite):
if not self.fill: # not ready yet
return
self.graphics.rectangle(0, 0, self.width, self.height)
self.graphics.fill(self.fill, 0.3)
self.graphics.rectangle(0.5, 0.5, self.width, self.height)
self.graphics.stroke(self.fill)
# adjust labels
self.start_label.visible = self.fixed == False and self.start_time is not None
if self.start_label.visible:
self.start_label.text = self.start_time.strftime("%H:%M")
if self.x - self.start_label.width - 5 > 0:
self.start_label.x = -self.start_label.width - 5
else:
self.start_label.x = 5
self.start_label.y = self.height
self.end_label.visible = self.fixed == False and self.end_time is not None
if self.end_label.visible:
self.end_label.text = self.end_time.strftime("%H:%M")
self.end_label.x = self.width + 5
self.end_label.y = self.height
duration = self.end_time - self.start_time
duration = int(duration.seconds / 60)
self.duration_label.text = "%02d:%02d" % (duration / 60, duration % 60)
self.duration_label.visible = self.duration_label.width < self.width
if self.duration_label.visible:
self.duration_label.y = (self.height - self.duration_label.height) / 2
self.duration_label.x = (self.width - self.duration_label.width) / 2
else:
self.duration_label.visible = False
class DayLine(graphics.Scene):
__gsignals__ = {
"on-time-chosen": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)),
}
def __init__(self, start_time = None):
graphics.Scene.__init__(self)
day_start = conf.get("day_start_minutes")
self.day_start = dt.time(day_start / 60, day_start % 60)
self.view_time = start_time or dt.datetime.combine(dt.date.today(), self.day_start)
self.scope_hours = 24
self.fact_bars = []
self.categories = []
self.connect("on-enter-frame", self.on_enter_frame)
self.connect("on-mouse-move", self.on_mouse_move)
self.connect("on-mouse-down", self.on_mouse_down)
self.connect("on-mouse-up", self.on_mouse_up)
self.connect("on-click", self.on_click)
self.plot_area = graphics.Sprite()
self.selection = Selection()
self.chosen_selection = Selection()
self.plot_area.add_child(self.selection, self.chosen_selection)
self.drag_start = None
self.current_x = None
self.snap_points = []
self.add_child(self.plot_area)
def plot(self, date, facts, select_start, select_end = None):
for bar in self.fact_bars:
self.plot_area.sprites.remove(bar)
self.fact_bars = []
for fact in facts:
fact_bar = graphics.Rectangle(0, 0, fill = "#aaa", stroke="#aaa") # dimensions will depend on screen situation
fact_bar.fact = fact
if fact.category in self.categories:
fact_bar.category = self.categories.index(fact.category)
else:
fact_bar.category = len(self.categories)
self.categories.append(fact.category)
self.plot_area.add_child(fact_bar)
self.fact_bars.append(fact_bar)
self.view_time = dt.datetime.combine((select_start - dt.timedelta(hours=self.day_start.hour, minutes=self.day_start.minute)).date(), self.day_start)
if select_start and select_start > dt.datetime.now():
select_start = dt.datetime.now()
self.chosen_selection.start_time = select_start
if select_end and select_end > dt.datetime.now():
select_end = dt.datetime.now()
self.chosen_selection.end_time = select_end
self.chosen_selection.width = None
self.chosen_selection.fixed = True
self.chosen_selection.visible = True
self.redraw()
def on_mouse_down(self, scene, event):
self.drag_start = self.current_x
self.chosen_selection.visible = False
def on_mouse_up(self, scene, event):
if self.drag_start:
self.drag_start = None
start_time = self.selection.start_time
if start_time > dt.datetime.now():
start_time = dt.datetime.now()
end_time = self.selection.end_time
self.new_selection()
self.emit("on-time-chosen", start_time, end_time)
def on_click(self, scene, event, target):
self.drag_start = None
# If self.selection.start_time is somehow None, just reset the selection.
# This can sometimes happen when dragging left to right in small
# increments. https://bugzilla.gnome.org/show_bug.cgi?id=669478
if self.selection == None or self.selection.start_time == None:
self.new_selection()
return
start_time = self.selection.start_time
if start_time > dt.datetime.now():
start_time = dt.datetime.now()
end_time = None
if self.fact_bars:
times = [bar.fact.start_time for bar in self.fact_bars if bar.fact.start_time - start_time > dt.timedelta(minutes=5)]
times.extend([bar.fact.start_time + bar.fact.delta for bar in self.fact_bars if bar.fact.start_time + bar.fact.delta - start_time > dt.timedelta(minutes=5)])
if times:
end_time = min(times)
self.new_selection()
self.emit("on-time-chosen", start_time, end_time)
def new_selection(self):
self.plot_area.sprites.remove(self.selection)
self.selection = Selection()
self.plot_area.add_child(self.selection)
self.redraw()
def on_mouse_move(self, scene, event):
if self.current_x:
active_bar = None
# find if we are maybe on a bar
for bar in self.fact_bars:
if bar.x < self.current_x < bar.x + bar.width:
active_bar = bar
break
if active_bar:
self.set_tooltip_text("%s - %s" % (active_bar.fact.activity, active_bar.fact.category))
else:
self.set_tooltip_text("")
self.redraw()
def on_enter_frame(self, scene, context):
g = graphics.Graphics(context)
self.plot_area.y = 15.5
self.plot_area.height = self.height - 30
vertical = min(self.plot_area.height / 5 , 7)
minute_pixel = (self.scope_hours * 60.0 - 15) / self.width
snap_points = []
g.set_line_style(width=1)
bottom = self.plot_area.y + self.plot_area.height
for bar in self.fact_bars:
bar.y = vertical * bar.category + 5
bar.height = vertical
bar_start_time = bar.fact.start_time - self.view_time
minutes = bar_start_time.seconds / 60 + bar_start_time.days * self.scope_hours * 60
bar.x = round(minutes / minute_pixel) + 0.5
bar.width = round((bar.fact.delta).seconds / 60 / minute_pixel)
if not snap_points or bar.x - snap_points[-1][0] > 1:
snap_points.append((bar.x, bar.fact.start_time))
if not snap_points or bar.x + bar.width - snap_points[-1][0] > 1:
snap_points.append((bar.x + bar.width, bar.fact.start_time + bar.fact.delta))
self.snap_points = snap_points
if self.chosen_selection.start_time and self.chosen_selection.width is None:
# we have time but no pixels
minutes = round((self.chosen_selection.start_time - self.view_time).seconds / 60 / minute_pixel) + 0.5
self.chosen_selection.x = minutes
if self.chosen_selection.end_time:
self.chosen_selection.width = round((self.chosen_selection.end_time - self.chosen_selection.start_time).seconds / 60 / minute_pixel)
else:
self.chosen_selection.width = 0
self.chosen_selection.height = self.chosen_selection.parent.height
# use the oportunity to set proper colors too
self.chosen_selection.fill = self.get_style().bg[gtk.STATE_SELECTED].to_string()
self.chosen_selection.duration_label.color = self.get_style().fg[gtk.STATE_SELECTED].to_string()
self.selection.visible = self._mouse_in # TODO - think harder about the mouse_out event
self.selection.width = 0
self.selection.height = self.selection.parent.height
if self.mouse_x:
start_x = max(min(self.mouse_x, self.width-1), 0) #mouse, but within screen regions
# check for snap points
start_x = start_x + 0.5
minutes = int(round(start_x * minute_pixel / 15)) * 15
start_time = self.view_time + dt.timedelta(hours = minutes / 60, minutes = minutes % 60)
if snap_points:
delta, closest_snap, time = min((abs(start_x - i), i, time) for i, time in snap_points)
if abs(closest_snap - start_x) < 5 and (not self.drag_start or self.drag_start != closest_snap):
start_x = closest_snap
minutes = (time.hour - self.day_start.hour) * 60 + time.minute - self.day_start.minute
start_time = time
self.current_x = minutes / minute_pixel
end_time, end_x = None, None
if self.drag_start:
minutes = int(self.drag_start * minute_pixel)
end_time = self.view_time + dt.timedelta(hours = minutes / 60, minutes = minutes % 60)
end_x = round(self.drag_start) + 0.5
if end_time and end_time < start_time:
start_time, end_time = end_time, start_time
start_x, end_x = end_x, start_x
self.selection.start_time = start_time
self.selection.end_time = end_time
self.selection.x = start_x
if end_time:
self.selection.width = end_x - start_x
self.selection.y = 0
self.selection.fill = self.get_style().bg[gtk.STATE_SELECTED].to_string()
self.selection.duration_label.color = self.get_style().fg[gtk.STATE_SELECTED].to_string()
#time scale
g.set_color("#000")
background = self.get_style().bg[gtk.STATE_NORMAL].to_string()
text = self.get_style().text[gtk.STATE_NORMAL].to_string()
tick_color = g.colors.contrast(background, 80)
layout = g.create_layout(size = 8)
for i in range(self.scope_hours * 60):
label_time = (self.view_time + dt.timedelta(minutes=i))
g.set_color(tick_color)
if label_time.minute == 0:
g.move_to(round(i / minute_pixel) + 0.5, bottom - 15)
g.line_to(round(i / minute_pixel) + 0.5, bottom)
g.stroke()
elif label_time.minute % 15 == 0:
g.move_to(round(i / minute_pixel) + 0.5, bottom - 5)
g.line_to(round(i / minute_pixel) + 0.5, bottom)
g.stroke()
if label_time.minute == 0 and label_time.hour % 4 == 0:
if label_time.hour == 0:
g.move_to(round(i / minute_pixel) + 0.5, self.plot_area.y)
g.line_to(round(i / minute_pixel) + 0.5, bottom)
label_minutes = label_time.strftime("%b %d")
else:
label_minutes = label_time.strftime("%H<small><sup>%M</sup></small>")
g.set_color(text)
layout.set_markup(label_minutes)
label_w, label_h = layout.get_pixel_size()
g.move_to(round(i / minute_pixel) + 2, 0)
context.show_layout(layout)
#current time
if self.view_time < dt.datetime.now() < self.view_time + dt.timedelta(hours = self.scope_hours):
minutes = round((dt.datetime.now() - self.view_time).seconds / 60 / minute_pixel) + 0.5
g.move_to(minutes, self.plot_area.y)
g.line_to(minutes, bottom)
g.stroke("#f00", 0.4)
snap_points.append(minutes - 0.5)
| landonb/hamster-applet | src/hamster/widgets/dayline.py | Python | gpl-3.0 | 13,958 |
<?php
/*
Template Name: Proyectos
*/
get_header();
the_post();
?>
<div id="primary" class="content-area col-md-9 col-xs-12">
<div id="content" class="site-content col-xs-12">
<article id="post-<?php the_ID() ?>" <?php post_class() ?>>
<header class="entry-header">
<h1 class="entry-title"><?php the_title() ?></h1>
</header>
<div class="entry-content">
<?php the_content() ?>
<?php edit_post_link('Editar', '<span class="edit-link">', '</span>') ?>
<?php $team_posts = get_posts(array( 'post_type' => 'project', 'posts_per_page' => -1, 'orderby' => 'title', 'order' => 'ASC')) ?>
<div class="row projects">
<?php foreach ($team_posts as $post): ?>
<?php setup_postdata($post); ?>
<div class="col-sm-6 project">
<?php if (has_post_thumbnail()) : ?>
<?php the_post_thumbnail('full') ?>
<?php endif ?>
<h3 class="project-title"><?php the_title() ?></h3>
<p>
<a rel="follow" href="http://<?php the_field('sitio_web') ?>.eticagnu.org/">http://<?php the_field('sitio_web') ?>.eticagnu.org/</a>
</p>
<div class="project-content">
<?php the_content(); ?>
</div>
</div>
<?php endforeach ?>
</div>
</div>
</article>
</div>
</div>
<?php
get_sidebar();
get_footer();
| ETICAGNU/eticagnuwptheme | proyectos.php | PHP | gpl-3.0 | 1,313 |
<?
namespace Module\Car\Offer\Admin
{
class Detail extends \System\Module
{
public function run()
{
$rq = $this->request;
$res = $this->response;
$ident = $this->req('ident');
$offer = \Car\Offer::get_first()
->where(array(
'ident' => $ident,
'visible' => true
))
->fetch();
if ($offer) {
$cfg = $rq->fconfig;
$cfg['ui']['data'] = array(
array(
'model' => 'Car.Offer',
'items' => array(
$offer->to_object_with_perms($rq->user)
)
)
);
$rq->fconfig = $cfg;
$res->subtitle = 'úpravy nabídky na sdílení auta';
$this->propagate('offer', $offer);
$this->partial('pages/carshare-detail', array(
"item" => $offer,
"free" => $offer->seats - $offer->requests->where(array('status' => 2))->count(),
"show_form" => false,
"show_rq" => true,
"requests" => $offer->requests->add_filter(array(
'attr' => 'status',
'type' => 'exact',
'exact' => array(1,2)
))->fetch(),
));
$this->partial('pages/carshare-admin-links', array(
"ident" => $ident
));
} else throw new \System\Error\NotFound();
}
}
}
| just-paja/improtresk-2015 | lib/module/car/offer/admin/detail.php | PHP | gpl-3.0 | 1,186 |
/**
* Copyright (C) 2011 Eric Huang
*
* This file is part of rectpack.
*
* rectpack 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.
*
* rectpack 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 rectpack. If not, see <http://www.gnu.org/licenses/>.
*/
#include "BoundingBoxes.h"
#include "Globals.h"
#include "HeapBox.h"
#include "Parameters.h"
#include "ConflictBT.h"
#include "SimpleSums.h"
#include "SpaceFill.h"
ConflictBT::ConflictBT() :
m_pWidths(NULL),
m_pHeights(NULL) {
}
ConflictBT::~ConflictBT() {
}
bool ConflictBT::packX() {
m_nDeepestConflict = 0;
UInt nTrash(0);
m_vSums.clear();
m_vSums.insert(0);
m_vSums.push();
return(nextVariable(m_vRectPtrs.begin(), nTrash));
}
void ConflictBT::initialize(const Parameters* pParams) {
RatPack::initialize(pParams);
m_vDomains.initialize(pParams);
/**
* If the subset sums computed by the bounding boxes is invalid,
* we'll have to compute our own. Otherwise, we can use the
* precomputed sums.
*/
if(m_pBoxes == NULL ||
m_pBoxes->m_bAllIntegralBoxes ||
m_pBoxes->m_Widths.empty() ||
m_pBoxes->m_Heights.empty()) {
m_Widths.initializeW(m_vRects.begin(), m_vRects.end());
m_pWidths = &m_Widths;
m_Heights.initializeH(m_vRects.begin(), m_vRects.end());
m_pHeights = &m_Heights;
}
else {
m_pWidths = &m_pBoxes->m_Widths;
m_pHeights = &m_pBoxes->m_Heights;
}
}
void ConflictBT::initialize(const HeapBox* pBox) {
RatPack::initialize(pBox);
m_vDomains.initialize(this);
m_vDomains.initialize(&pBox->m_Box);
}
void ConflictBT::initialize(const BoundingBoxes* pBoxes) {
RatPack::initialize(pBoxes);
}
bool ConflictBT::packInterval(RectPtrArray::iterator i,
UInt& nDeepest) {
Rectangle* r(*i);
const DomConfig* dc(&m_vDomains.get(r)[0]); // Change 0 to note dominance rules.
for(DomConfig::const_iterator j = dc->begin(); j != dc->end(); ++j) {
if(m_vX.canFit(*j)) {
m_Nodes.tick(XI);
m_vX.pushHinted(*j);
if(m_vX.propagate())
if(nextVariable(i + 1, nDeepest))
return(true);
m_vX.pop();
}
}
return(false);
}
bool ConflictBT::packSingle(const Compulsory* c,
RectPtrArray::iterator i,
UInt& nDeepest) {
/**
* Now process all rectangles that haven't gotten any commitments
* made.
*/
UInt nNext;
{
SimpleSums ss2(m_vSums);
for(RectPtrArray::iterator i2 = i; i2 != m_iFirstUnit; ++i2) {
if((*i2)->rotatable())
ss2.add((*i2)->m_nWidth, c->m_nStart.m_nRight);
else
ss2.add((*i2)->m_nWidth, (*i2)->m_nHeight,
c->m_nStart.m_nRight);
}
for(UInt m = c->m_pRect->m_nID + 1; m < (UInt) (i - m_vRectPtrs.begin()); ++m)
ss2.add(m_vX.values()[m].m_nValue, c->m_nStart.m_nRight);
SimpleSums::const_iterator j(ss2.lower_bound(c->m_nStart.m_nLeft));
if(j == ss2.end())
nNext = c->m_nStart.m_nRight + 1;
else
nNext = *j;
}
nDeepest = std::max(nDeepest, c->m_pRect->m_nID);
while(nNext <= c->m_nStart.m_nRight) {
UInt nLocalDeepest = c->m_pRect->m_nID;
m_Nodes.tick(XF);
m_vSums.push(nNext + c->m_pRect->m_nWidth);
m_vX.push(c->m_pRect, nNext);
if(m_vX.propagate())
if(nextVariable(i, nLocalDeepest))
return(true);
m_vX.pop();
m_vSums.pop();
nDeepest = std::max(nDeepest, nLocalDeepest);
{
SimpleSums ss2(m_vSums);
for(RectPtrArray::iterator i2 = i;
i2 != m_iFirstUnit && (*i2)->m_nID <= nLocalDeepest; ++i2) {
if((*i2)->rotatable())
ss2.add((*i2)->m_nWidth, c->m_nStart.m_nRight);
else
ss2.add((*i2)->m_nWidth, (*i2)->m_nHeight,
c->m_nStart.m_nRight);
}
for(UInt m = c->m_pRect->m_nID + 1; m < (UInt) (i - m_vRectPtrs.begin()); ++m)
ss2.add(m_vX.values()[m].m_nValue, c->m_nStart.m_nRight);
SimpleSums::const_iterator k(ss2.upper_bound(nNext));
if(k == ss2.end())
nNext = c->m_nStart.m_nRight + 1;
else
nNext = *k;
}
}
return(false);
}
bool ConflictBT::orientation(RectPtrArray::iterator i,
UInt& nDeepest) {
if(packInterval(i, nDeepest)) return(true);
if((*i)->rotatable()) {
(*i)->rotate();
if(packInterval(i, nDeepest)) return(true);
}
return(false);
}
bool ConflictBT::nextVariable(RectPtrArray::iterator i, UInt& nDeepest) {
if(bQuit) return(false);
/**
* In the base case we're at the end of our packing sequence.
*/
if(i == m_iFirstUnit) {
m_nDeepestConflict = m_vRectPtrs.size() - 1;
/**
* We're potentially done with everything. Before we pack the
* other dimension, however, we must ensure that we have
* completely finished with packing even the singular values.
*/
const Compulsory* c(NULL);
UInt nLargestArea(0);
m_vX.largestAreaPlacement(nLargestArea, c);
if(c) return(packSingle(c, i, nDeepest));
else return(packY());
}
m_nDeepestConflict = std::max(m_nDeepestConflict, (*i)->m_nID);
const Compulsory* c(NULL);
UInt nLargestArea(0);
m_vX.largestAreaPlacement(nLargestArea, c);
if(c && nLargestArea > m_vDomains.get(*i)[0][0].area())
return(packSingle(c, i, nDeepest));
else return(orientation(i, nDeepest));
}
bool ConflictBT::packY() {
if(m_pParams->m_bScheduling)
return(true);
else
return(m_pSpaceFill->packY(m_vX, m_pHeights));
}
| pupitetris/rectpack | src/ConflictBT.cc | C++ | gpl-3.0 | 5,723 |
import simplejson
import traceback
import logging
import os
import requests
from collections import OrderedDict
from string import ascii_letters, digits
ID = "nem"
permission = 1
nem_logger = logging.getLogger("NEM_Tools")
# Colour Constants for List and Multilist command
COLOURPREFIX = unichr(3)
COLOUREND = COLOURPREFIX
BOLD = unichr(2)
DARKGREEN = COLOURPREFIX + "03"
RED = COLOURPREFIX + "05"
PURPLE = COLOURPREFIX + "06"
ORANGE = COLOURPREFIX + "07"
BLUE = COLOURPREFIX + "12"
PINK = COLOURPREFIX + "13"
GRAY = COLOURPREFIX + "14"
LIGHTGRAY = COLOURPREFIX + "15"
ALLOWED_IN_FILENAME = "-_.() %s%s" % (ascii_letters, digits)
# Colour Constants End
class NotEnoughClasses():
def getLatestVersion(self):
try:
return self.fetch_json("https://bot.notenoughmods.com/?json")
except:
print("Failed to get NEM versions, falling back to hard-coded")
nem_logger.exception("Failed to get NEM versions, falling back to hard-coded.")
#traceb = str(traceback.format_exc())
# print(traceb)
return ["1.4.5", "1.4.6-1.4.7", "1.5.1", "1.5.2", "1.6.1", "1.6.2", "1.6.4",
"1.7.2", "1.7.4", "1.7.5", "1.7.7", "1.7.9", "1.7.10"]
def __init__(self):
self.requests_session = requests.Session()
self.requests_session.headers = {
'User-agent': 'NotEnoughMods:Tools/1.X (+https://github.com/NotEnoughMods/NotEnoughModPolling)'
}
self.requests_session.max_redirects = 5
self.cache_dir = os.path.join("commands", "NEM", "cache")
self.cache_last_modified = {}
self.cache_etag = {}
self.versions = self.getLatestVersion()
self.version = self.versions[len(self.versions) - 1]
def normalize_filename(self, name):
return ''.join(c for c in name if c in ALLOWED_IN_FILENAME)
def fetch_page(self, url, timeout=10, decode_json=False, cache=False):
try:
if cache:
fname = self.normalize_filename(url)
filepath = os.path.join(self.cache_dir, fname)
if os.path.exists(filepath):
# get it (conditionally) and, if necessary, store the new version
headers = {}
# set etag if it exists
etag = self.cache_etag.get(url)
if etag:
headers['If-None-Match'] = etag
# set last-modified if it exists
last_modified = self.cache_last_modified.get(url)
if last_modified:
headers['If-Modified-Since'] = '"{}"'.format(last_modified)
request = self.requests_session.get(url, timeout=timeout, headers=headers)
if request.status_code == 304:
# load from cache
with open(filepath, 'r') as f:
# and return it
if decode_json:
return simplejson.load(f)
else:
return f.read()
else:
# cache the new version
with open(filepath, 'w') as f:
f.write(request.content)
self.cache_etag[url] = request.headers.get('etag')
self.cache_last_modified[url] = request.headers.get('last-modified')
# and return it
if decode_json:
return request.json()
else:
return request.content
else:
# get it and cache it
request = self.requests_session.get(url, timeout=timeout)
with open(filepath, 'w') as f:
f.write(request.content)
self.cache_etag[url] = request.headers.get('etag')
self.cache_last_modified[url] = request.headers.get('last-modified')
if decode_json:
return request.json()
else:
return request.content
else:
# no caching
request = self.requests_session.get(url, timeout=timeout)
if decode_json:
return request.json()
else:
return request.content
except:
traceback.print_exc()
pass
# most likely a timeout
def fetch_json(self, *args, **kwargs):
return self.fetch_page(*args, decode_json=True, **kwargs)
NEM = NotEnoughClasses()
def execute(self, name, params, channel, userdata, rank):
try:
command = commands[params[0]]
command(self, name, params, channel, userdata, rank)
except:
self.sendMessage(channel, "Invalid sub-command!")
self.sendMessage(channel, "See \"=nem help\" for help")
def setlist(self, name, params, channel, userdata, rank):
if len(params) != 2:
self.sendMessage(channel,
"{name}: Insufficient amount of parameters provided.".format(name=name)
)
self.sendMessage(channel,
"{name}: {setlistHelp}".format(name=name,
setlistHelp=help["setlist"][0])
)
else:
NEM.version = str(params[1])
self.sendMessage(channel,
"switched list to: "
"{bold}{blue}{version}{colourEnd}".format(bold=BOLD,
blue=BLUE,
version=params[1],
colourEnd=COLOUREND)
)
def multilist(self, name, params, channel, userdata, rank):
if len(params) != 2:
self.sendMessage(channel,
"{name}: Insufficient amount of parameters provided.".format(name=name))
self.sendMessage(channel,
"{name}: {multilistHelp}".format(name=name,
multilistHelp=help["multilist"][0])
)
else:
try:
jsonres = {}
results = OrderedDict()
modName = params[1]
for version in NEM.versions:
jsonres[version] = NEM.fetch_json("https://bot.notenoughmods.com/" + requests.utils.quote(version) + ".json", cache=True)
for i, mod in enumerate(jsonres[version]):
if modName.lower() == mod["name"].lower():
results[version] = i
break
else:
aliases = [mod_alias.lower() for mod_alias in mod["aliases"]]
if modName.lower() in aliases:
results[version] = i
count = len(results)
if count == 0:
self.sendMessage(channel, name + ": mod not present in NEM.")
return
elif count == 1:
count = str(count) + " MC version"
else:
count = str(count) + " MC versions"
self.sendMessage(channel, "Listing " + count + " for \"" + params[1] + "\":")
for version in results.iterkeys():
alias = ""
modData = jsonres[version][results[version]]
if modData["aliases"]:
alias_joinText = "{colourEnd}, {colour}".format(colourEnd=COLOUREND,
colour=PINK)
alias_text = alias_joinText.join(modData["aliases"])
alias = "({colour}{text}{colourEnd}) ".format(colourEnd=COLOUREND,
colour=PINK,
text=alias_text)
comment = ""
if modData["comment"] != "":
comment = "({colour}{text}{colourEnd}) ".format(colourEnd=COLOUREND,
colour=GRAY,
text=modData["comment"])
dev = ""
try:
if modData["dev"] != "":
dev = ("({colour}dev{colourEnd}: "
"{colour2}{version}{colourEnd}) ".format(colourEnd=COLOUREND,
colour=GRAY,
colour2=RED,
version=modData["dev"])
)
except Exception as error:
print(error)
traceback.print_exc()
self.sendMessage(channel,
"{bold}{blue}{mcversion}{colourEnd}{bold}: "
"{purple}{name}{colourEnd} {aliasString}"
"{darkgreen}{version}{colourEnd} {devString}"
"{comment}{orange}{shorturl}{colourEnd}".format(name=modData["name"],
aliasString=alias,
devString=dev,
comment=comment,
version=modData["version"],
shorturl=modData["shorturl"],
mcversion=version,
bold=BOLD,
blue=BLUE,
purple=PURPLE,
darkgreen=DARKGREEN,
orange=ORANGE,
colourEnd=COLOUREND)
)
except Exception as error:
self.sendMessage(channel, name + ": " + str(error))
traceback.print_exc()
def list(self, name, params, channel, userdata, rank):
if len(params) < 2:
self.sendMessage(channel,
"{name}: Insufficient amount of parameters provided.".format(name=name))
self.sendMessage(channel,
"{name}: {helpEntry}".format(name=name,
helpEntry=help["list"][0])
)
return
if len(params) >= 3:
version = params[2]
else:
version = NEM.version
try:
result = NEM.fetch_page("https://bot.notenoughmods.com/" + requests.utils.quote(version) + ".json", cache=True)
if not result:
self.sendMessage(channel,
"{0}: Could not fetch the list. Are you sure it exists?".format(name)
)
return
jsonres = simplejson.loads(result, strict=False)
results = []
i = -1
for mod in jsonres:
i = i + 1
if str(params[1]).lower() in mod["name"].lower():
results.append(i)
continue
else:
aliases = mod["aliases"]
for alias in aliases:
if params[1].lower() in alias.lower():
results.append(i)
break
count = len(results)
if count == 0:
self.sendMessage(channel, name + ": no results found.")
return
elif count == 1:
count = str(count) + " result"
else:
count = str(count) + " results"
self.sendMessage(channel,
"Listing {count} for \"{term}\" in "
"{bold}{colour}{version}"
"{colourEnd}{bold}".format(count=count,
term=params[1],
version=version,
bold=BOLD,
colourEnd=COLOUREND,
colour=BLUE)
)
for line in results:
alias = COLOURPREFIX
if jsonres[line]["aliases"]:
alias_joinText = "{colourEnd}, {colour}".format(colourEnd=COLOUREND,
colour=PINK)
alias_text = alias_joinText.join(jsonres[line]["aliases"])
alias = "({colour}{text}{colourEnd}) ".format(colourEnd=COLOUREND,
colour=PINK,
text=alias_text)
comment = ""
if jsonres[line]["comment"] != "":
comment = "({colour}{text}{colourEnd}) ".format(colourEnd=COLOUREND,
colour=GRAY,
text=jsonres[line]["comment"])
dev = ""
try:
if jsonres[line]["dev"] != "":
dev = ("({colour}dev{colourEnd}): "
"{colour2}{version}{colourEnd})".format(colourEnd=COLOUREND,
colour=GRAY,
colour2=RED,
version=jsonres[line]["dev"])
)
except Exception as error:
print(error)
traceback.print_exc()
self.sendMessage(channel,
"{purple}{name}{colourEnd} {aliasString}"
"{darkgreen}{version}{colourEnd} {devString}"
"{comment}{orange}{shorturl}{colourEnd}".format(name=jsonres[line]["name"],
aliasString=alias,
devString=dev,
comment=comment,
version=jsonres[line]["version"],
shorturl=jsonres[line]["shorturl"],
purple=PURPLE,
darkgreen=DARKGREEN,
orange=ORANGE,
colourEnd=COLOUREND)
)
except Exception as error:
self.sendMessage(channel, "{0}: {1}".format(name, error))
traceback.print_exc()
def compare(self, name, params, channel, userdata, rank):
try:
oldVersion, newVersion = params[1], params[2]
oldJson = NEM.fetch_json("https://bot.notenoughmods.com/" + requests.utils.quote(oldVersion) + ".json", cache=True)
newJson = NEM.fetch_json("https://bot.notenoughmods.com/" + requests.utils.quote(newVersion) + ".json", cache=True)
newMods = {modInfo["name"].lower(): True for modInfo in newJson}
missingMods = []
for modInfo in oldJson:
old_modName = modInfo["name"].lower()
if old_modName not in newMods:
missingMods.append(modInfo["name"])
path = "commands/modbot.mca.d3s.co/htdocs/compare/{0}...{1}.json".format(oldVersion, newVersion)
with open(path, "w") as f:
f.write(simplejson.dumps(missingMods, sort_keys=True, indent=4 * ' '))
self.sendMessage(channel,
"{0} mods died trying to update to {1}".format(len(missingMods), newVersion)
)
except Exception as error:
self.sendMessage(channel, "{0}: {1}".format(name, error))
traceback.print_exc()
def about(self, name, params, channel, userdata, rank):
self.sendMessage(channel, "Not Enough Mods toolkit for IRC by SinZ & Yoshi2 v4.0")
def help(self, name, params, channel, userdata, rank):
if len(params) == 1:
self.sendMessage(channel,
"{0}: Available commands: {1}".format(name,
", ".join(help))
)
else:
command = params[1]
if command in help:
for line in help[command]:
self.sendMessage(channel, name + ": " + line)
else:
self.sendMessage(channel, name + ": Invalid command provided")
def force_cacheRedownload(self, name, params, channel, userdata, rank):
if self.rankconvert[rank] >= 3:
for version in NEM.versions:
url = "https://bot.notenoughmods.com/" + requests.utils.quote(version) + ".json"
normalized = NEM.normalize_filename(url)
filepath = os.path.join(NEM.cache_dir, normalized)
if os.path.exists(filepath):
NEM.cache_last_modified[normalized] = 0
self.sendMessage(channel, "Cache Timestamps have been reset. Cache will be redownloaded on the next fetching.")
commands = {
"list": list,
"multilist": multilist,
"about": about,
"help": help,
"setlist": setlist,
"compare": compare,
"forceredownload": force_cacheRedownload
}
help = {
"list": ["=nem list <search> <version>",
"Searches the NotEnoughMods database for <search> and returns all results to IRC."],
"about": ["=nem about",
"Shows some info about the NEM plugin."],
"help": ["=nem help [command]",
"Shows the help info about [command] or lists all commands for this plugin."],
"setlist": ["=nem setlist <version>",
"Sets the default version to be used by other commands to <version>."],
"multilist": ["=nem multilist <modName or alias>",
"Searches the NotEnoughMods database for modName or alias in all MC versions."],
"compare": ["=nem compare <oldVersion> <newVersion>",
"Compares the NEMP entries for two different MC versions and says how many mods haven't been updated to the new version."]
}
| NotEnoughMods/NotEnoughModPolling | NotEnoughMods_Tools.py | Python | gpl-3.0 | 19,543 |
def __load():
import imp, os, sys
ext = 'pygame/imageext.so'
for path in sys.path:
if not path.endswith('lib-dynload'):
continue
ext_path = os.path.join(path, ext)
if os.path.exists(ext_path):
mod = imp.load_dynamic(__name__, ext_path)
break
else:
raise ImportError(repr(ext) + " not found")
__load()
del __load
| mokuki082/EggDrop | code/build/bdist.macosx-10.6-intel/python3.4-standalone/app/temp/pygame/imageext.py | Python | gpl-3.0 | 397 |
//
// Copyright (c) 2014 richards-tech
//
// This file is part of VRWidgetLib
//
// VRWidgetLib 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.
//
// VRWidgetLib 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 VRWidgetLib. If not, see <http://www.gnu.org/licenses/>.
//
#include "VRPlaneWidget.h"
#include <qdebug.h>
VRPlaneWidget::VRPlaneWidget(QObject *parent, VRWIDGET_TYPE widgetType)
: VRWidget(parent, widgetType)
{
m_image = NULL;
}
VRPlaneWidget::~VRPlaneWidget()
{
if (m_image != NULL)
delete m_image;
}
void VRPlaneWidget::VRWidgetInit()
{
m_plane.generate(m_width, m_height);
m_plane.setShader(globalShader[QTGLSHADER_TEXTURE]);
m_image = new QImage(QSize(1280, 720), QImage::Format_RGB888);
m_image->fill(QColor(40, 80, 20, 255));
m_font.setFamily("Arial");
m_font.setPixelSize(8);
m_font.setFixedPitch(true);
}
void VRPlaneWidget::VRWidgetRender()
{
startWidgetRender();
startComponentRender();
m_plane.draw();
endComponentRender(m_plane.getBoundMinus(), m_plane.getBoundPlus());
endWidgetRender();
}
void VRPlaneWidget::paintText(const QString& text, int x, int y, int width)
{
if (m_image == NULL)
return;
QPainter painter(m_image);
QFontMetrics metrics = QFontMetrics(m_font);
int border = qMax(4, metrics.leading());
QRect rect;
rect = metrics.boundingRect(text);
painter.setRenderHint(QPainter::TextAntialiasing);
painter.fillRect(QRect(x, y, width + 2 * border, rect.height() + 2 * border),
QColor(0, 0, 0, 128));
painter.setPen(Qt::white);
painter.drawText(x + border, y + border,
width + border, rect.height() + border,
Qt::AlignLeft | Qt::TextWordWrap, text);
painter.end();
m_plane.setTexture(*m_image);
}
void VRPlaneWidget::paintFileImage(const char *fileName)
{
m_image->load(fileName);
m_image->convertToFormat(QImage::Format_RGB888);
m_plane.setTexture(*m_image);
}
void VRPlaneWidget::paintImage(const QImage& image)
{
*m_image = image;
m_plane.setTexture(*m_image);
}
| robotage/SyntroApps | SyntroCommon/GL/VRWidgetLib/VRPlaneWidget.cpp | C++ | gpl-3.0 | 2,597 |
/*****************************************************************
* 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.dao.DeliverableUserPartnershipDAO;
import org.cgiar.ccafs.marlo.data.model.DeliverableUserPartnership;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
@Named
public class DeliverableUserPartnershipMySQLDAO extends AbstractMarloDAO<DeliverableUserPartnership, Long>
implements DeliverableUserPartnershipDAO {
@Inject
public DeliverableUserPartnershipMySQLDAO(SessionFactory sessionFactory) {
super(sessionFactory);
}
@Override
public void deleteDeliverableUserPartnership(long deliverableUserPartnershipId) {
DeliverableUserPartnership deliverableUserPartnership = this.find(deliverableUserPartnershipId);
deliverableUserPartnership.setActive(false);
this.update(deliverableUserPartnership);
}
@Override
public boolean existDeliverableUserPartnership(long deliverableUserPartnershipID) {
DeliverableUserPartnership deliverableUserPartnership = this.find(deliverableUserPartnershipID);
if (deliverableUserPartnership == null) {
return false;
}
return true;
}
@Override
public DeliverableUserPartnership find(long id) {
return super.find(DeliverableUserPartnership.class, id);
}
@Override
public List<DeliverableUserPartnership> findAll() {
String query = "from " + DeliverableUserPartnership.class.getName() + " where is_active=1";
List<DeliverableUserPartnership> list = super.findAll(query);
if (list.size() > 0) {
return list;
}
return null;
}
@Override
public List<DeliverableUserPartnership> findByDeliverableID(long deliverableID) {
String query =
"from " + DeliverableUserPartnership.class.getName() + " where is_active=1 and deliverable_id = " + deliverableID;
List<DeliverableUserPartnership> list = super.findAll(query);
if (list.isEmpty()) {
return list;
}
return null;
}
@Override
public List<DeliverableUserPartnership> findPartnershipsByInstitutionProjectAndPhase(long institutionId,
long projectId, long phaseId) {
String query = "select dup from DeliverableUserPartnership dup where dup.institution.id = :institutionId and "
+ "dup.phase.id = :phaseId and dup.deliverable.project.id = :projectId and dup.deliverable.active = true";
Query createQuery = this.getSessionFactory().getCurrentSession().createQuery(query);
createQuery.setParameter("phaseId", phaseId);
createQuery.setParameter("institutionId", institutionId);
createQuery.setParameter("projectId", projectId);
List<DeliverableUserPartnership> deliverables = super.findAll(createQuery);
return deliverables;
}
@Override
public DeliverableUserPartnership save(DeliverableUserPartnership deliverableUserPartnership) {
if (deliverableUserPartnership.getId() == null) {
super.saveEntity(deliverableUserPartnership);
} else {
deliverableUserPartnership = super.update(deliverableUserPartnership);
}
return deliverableUserPartnership;
}
} | CCAFS/MARLO | marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/mysql/DeliverableUserPartnershipMySQLDAO.java | Java | gpl-3.0 | 4,091 |
package cuina.map;
import cuina.database.KeyReference;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Rasterbasiertes Spielfeld mit Terraininformationen.
* <p>
* Enthält weitere Daten:
* <dl>
* <dt>objects</dt>
* <dd>Liste von Objekten welche Spielobjekte auf der Karte darstellen.</dd>
* </dl>
* <dt>events</dt>
* <dd>Liste von Objekten welche kartenbezogene Events darstellen.</dd>
* </dl>
* </p>
* @author TheWhiteShadow
*/
public class Map implements Serializable
{
private static final long serialVersionUID = 7126463419853704389L;
public static final int LAYERS = 4;
/** Schlüssel der Map. */
private String key;
/** Feldanzahl in horizontaler Richtung. */
public int width;
/** Feldanzahl in vertikaler Richtung. */
public int height;
// transient, da Mapdaten optimiert serialisiert werden.
/** 3D-Array mit den IDs der einzelnen Felder. */
transient public short[][][] data;
/** Spielobjekte auf der Karte. */
public List<Object> objects;
public List<Object> areas;
public List<Object> paths;
// Referenz zur Tileset-Datenbank
@KeyReference(name="Tileset")
public String tilesetKey = "";
public Map(String key, int width, int height)
{
this.key = key;
this.width = width;
this.height = height;
this.data = new short[width][height][LAYERS];
this.objects = new ArrayList<Object>();
this.areas = new ArrayList<Object>();
this.paths = new ArrayList<Object>();
}
public String getKey()
{
return key;
}
private final synchronized void writeObject( ObjectOutputStream s ) throws IOException
{
s.defaultWriteObject();
short[] dataStream = new short[width * height * LAYERS];
for(int x = 0; x < width; x++)
for(int y = 0; y < height; y++)
for(int z = 0; z < LAYERS; z++)
{
dataStream[x*height*LAYERS + y*LAYERS + z] = data[x][y][z];
}
s.writeObject(dataStream);
}
private final synchronized void readObject( ObjectInputStream s ) throws IOException, ClassNotFoundException
{
s.defaultReadObject();
short[] dataStream = (short[])s.readObject();
data = new short[width][height][LAYERS];
for(int x = 0; x < width; x++)
for(int y = 0; y < height; y++)
for(int z = 0; z < LAYERS; z++)
{
data[x][y][z] = dataStream[x*height*LAYERS + y*LAYERS + z];
// if (version < 1 && data[x][y][z] > 0)
// data[x][y][z] += Tileset.AUTOTILES_OFFSET;
}
// version = 1;
}
}
| TheWhiteShadow3/cuina | CuinaEclipse/cuina.editor.map/src/cuina/map/Map.java | Java | gpl-3.0 | 2,507 |
class CreateIssues < ActiveRecord::Migration[4.2]
def change
create_table :issues do |t|
t.references :user, null: false, index: true, foreign_key: true
t.string :barcode, null: false
t.text :message, null: false
t.integer :resolver_id, index: true
t.timestamp :resolved_at
t.timestamps null: false
end
add_foreign_key :issues, :users, column: :resolver_id
end
end
| ndlib/annex-ims | db/migrate/20150428155251_create_issues.rb | Ruby | gpl-3.0 | 418 |
using System;
using EP.SOLID.DIP.Solucao.Interfaces;
namespace EP.SOLID.DIP.Solucao
{
public class Cliente
{
private readonly ICPFServices _cpfServices;
private readonly IEmailServices _emailServices;
public Cliente(
ICPFServices cpfServices,
IEmailServices emailServices)
{
_cpfServices = cpfServices;
_emailServices = emailServices;
}
public int ClienteId { get; set; }
public string Nome { get; set; }
public string Email { get; set; }
public string CPF { get; set; }
public DateTime DataCadastro { get; set; }
public bool IsValid()
{
return _emailServices.IsValid(Email) && _cpfServices.IsValid(CPF);
}
}
} | CARLORION/PrincipiosSOLID | EP.SOLID/5 - DIP/DIP.Solucao/Cliente.cs | C# | gpl-3.0 | 794 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-02-01 20:16
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('djreceive', '0024_auto_20170131_1732'),
]
operations = [
migrations.RemoveField(
model_name='audioabxtrial',
name='result',
),
migrations.AddField(
model_name='audioabxtrial',
name='A',
field=models.CharField(max_length=1024, null=True),
),
migrations.AddField(
model_name='audioabxtrial',
name='B',
field=models.CharField(max_length=1024, null=True),
),
migrations.AddField(
model_name='audioabxtrial',
name='X',
field=models.CharField(max_length=1024, null=True),
),
migrations.AddField(
model_name='audioabxtrial',
name='correct',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='audioabxtrial',
name='key_press',
field=models.IntegerField(null=True),
),
]
| rivasd/djPsych | djreceive/migrations/0025_auto_20170201_1516.py | Python | gpl-3.0 | 1,227 |
// Core functionality inspired by http://www.ghosthorses.co.uk/production-diary/super-simple-responsive-progress-bar/
jQuery(function($) {
moveProgressBar();
$(window).resize(function() {
moveProgressBar();
});
function moveProgressBar() {
$('.rprogress-wrap').each(function(i, e) {
var getPercent = ($(e).data('progress-percent') / 100);
var getProgressWrapWidth = $(e).width();
var progressTotal = getPercent * getProgressWrapWidth;
var animationLength = $(e).data('speed');
$(e).find('.rprogress-bar').stop().animate({
left: progressTotal
}, animationLength);
});
}
});
| wp-plugins/responsive-progress-bar | assets/js/responsive-progressbar.js | JavaScript | gpl-3.0 | 642 |
#include <SFML/Window.hpp>
#include <SFML/OpenGL.hpp>
#include <stdio.h>
#include <math.h>
//CONSTANTS
#define GL_PI (3.141592653f)
//GLOBALS
GLboolean g_vsync = false;
GLboolean g_run = true;
//WIN VARS (Start square)
GLuint win_w = 600;
GLuint win_h = 600;
//LIMITS
GLfloat limit = 100.0f;
GLfloat rot_inc = GL_PI / 36.0f;
GLfloat max_ang = 6.0f * GL_PI;
GLfloat ang_inc = 0.1f;
void draw_axes()
{
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_LINES);
glVertex3f(-100.0f, 0.0f, 0.0f);
glVertex3f(100.0f, 0.0f, 0.0f);
glEnd();
glColor3f(0.0f, 0.0f, 1.0f);
glBegin(GL_LINES);
glVertex3f(0.0f, -100.0f, 0.0f);
glVertex3f(0.0f, 100.0f, 0.0f);
glEnd();
glColor3f(1.0f, 1.0f, 0.0f);
glBegin(GL_LINES);
glVertex3f(0.0f, 0.0f, -100.0f);
glVertex3f(0.0f, 0.0f, 100.0f);
glEnd();
}
void render_scene()
{
GLfloat x;
GLfloat y;
GLfloat z;
GLfloat theta;
GLfloat sizes[2];
GLfloat size_inc;
GLfloat point_size;
glGetFloatv(GL_POINT_SIZE_RANGE, sizes);
glGetFloatv(GL_POINT_SIZE_GRANULARITY, &size_inc);
point_size = sizes[0];
glClear(GL_COLOR_BUFFER_BIT);
draw_axes();
glColor3f(0.0f, 1.0f, 0.0f);
z = -limit / 2.0f;
for (theta = 0.0f; theta <= max_ang; theta += ang_inc) {
x = limit / 2.0f * cos(theta);
y = limit / 2.0f * sin(theta);
glPointSize(point_size);
glBegin(GL_POINTS);
glVertex3f(x, y, z);
glEnd();
z += 5.0f * ang_inc;
point_size += size_inc;
if (point_size > sizes[1])
point_size = sizes[0];
}
}
void win_resized(GLsizei w, GLsizei h)
{
GLfloat ar;
GLfloat max_x;
GLfloat max_y;
GLfloat max_z;
win_w = w;
win_h = h;
if (win_h == 0)
win_h = 1;
glViewport(0, 0, win_w, win_h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
ar = (GLfloat)w / (GLfloat)h;
if (w <= h) {
max_x = limit;
max_y = limit / ar;
} else {
max_x = limit * ar;
max_y = limit;
}
max_z = limit;
glOrtho(-max_x, max_x, -max_y, max_y, -max_z, max_z);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void setup_render_state()
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
win_resized(win_w, win_h);
}
void process_key(sf::Event::KeyEvent e)
{
switch (e.code) {
case (sf::Keyboard::Right):
glRotatef(-rot_inc * 180.0f / GL_PI, 0.0f, 1.0f, 0.0f);
break;
case (sf::Keyboard::Left):
glRotatef(rot_inc * 180.0f / GL_PI, 0.0f, 1.0f, 0.0f);
break;
case (sf::Keyboard::Up):
glRotatef(rot_inc * 180.0f / GL_PI, 1.0f, 0.0f, 0.0f);
break;
case (sf::Keyboard::Down):
glRotatef(-rot_inc * 180.0f / GL_PI, 1.0f, 0.0f, 0.0f);
break;
case (sf::Keyboard::Escape):
g_run = false;
break;
case (sf::Keyboard::Space):
glLoadIdentity();
break;
default:
break;
}
}
void handle_event(sf::Event e)
{
switch (e.type) {
case sf::Event::Closed:
fprintf(stderr,
"OpenGL Version String: %s\n",
glGetString(GL_VERSION));
g_run = false;
break;
case sf::Event::Resized:
win_resized(e.size.width, e.size.height);
break;
case sf::Event::KeyPressed:
process_key(e.key);
break;
default:
break;
}
}
int main(int argc, const char * const argv[])
{
sf::Event e;
sf::Window win;
sf::VideoMode vm;
sf::Clock c;
std::string win_title;
win_title = "Pointsz";
vm.width = win_w;
vm.height = win_h;
vm.bitsPerPixel = 32;
win.create(vm, win_title);
win.setFramerateLimit(60);
win.setVerticalSyncEnabled(g_vsync);
win.setActive();
setup_render_state();
c.restart();
while(g_run) {
while (win.pollEvent(e))
handle_event(e);
render_scene();
win.display();
}
win.close();
return 0;
}
| neptoess/opengl-superbible-fourth | ch03/Pointsz/src/main.cpp | C++ | gpl-3.0 | 3,535 |
import Modal from '../../src/modal'
import EventHandler from '../../src/dom/event-handler'
import ScrollBarHelper from '../../src/util/scrollbar'
/** Test helpers */
import { clearBodyAndDocument, clearFixture, createEvent, getFixture, jQueryMock } from '../helpers/fixture'
describe('Modal', () => {
let fixtureEl
beforeAll(() => {
fixtureEl = getFixture()
})
afterEach(() => {
clearFixture()
clearBodyAndDocument()
document.body.classList.remove('modal-open')
document.querySelectorAll('.modal-backdrop')
.forEach(backdrop => {
backdrop.remove()
})
})
beforeEach(() => {
clearBodyAndDocument()
})
describe('VERSION', () => {
it('should return plugin version', () => {
expect(Modal.VERSION).toEqual(jasmine.any(String))
})
})
describe('Default', () => {
it('should return plugin default config', () => {
expect(Modal.Default).toEqual(jasmine.any(Object))
})
})
describe('DATA_KEY', () => {
it('should return plugin data key', () => {
expect(Modal.DATA_KEY).toEqual('bs.modal')
})
})
describe('constructor', () => {
it('should take care of element either passed as a CSS selector or DOM element', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modalBySelector = new Modal('.modal')
const modalByElement = new Modal(modalEl)
expect(modalBySelector._element).toEqual(modalEl)
expect(modalByElement._element).toEqual(modalEl)
})
})
describe('toggle', () => {
it('should call ScrollBarHelper to handle scrollBar on body', done => {
fixtureEl.innerHTML = [
'<div class="modal"><div class="modal-dialog"></div></div>'
].join('')
spyOn(ScrollBarHelper.prototype, 'hide').and.callThrough()
spyOn(ScrollBarHelper.prototype, 'reset').and.callThrough()
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modalEl.addEventListener('shown.bs.modal', () => {
expect(ScrollBarHelper.prototype.hide).toHaveBeenCalled()
modal.toggle()
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(ScrollBarHelper.prototype.reset).toHaveBeenCalled()
done()
})
modal.toggle()
})
})
describe('show', () => {
it('should show a modal', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modalEl.addEventListener('show.bs.modal', event => {
expect(event).toBeDefined()
})
modalEl.addEventListener('shown.bs.modal', () => {
expect(modalEl.getAttribute('aria-modal')).toEqual('true')
expect(modalEl.getAttribute('role')).toEqual('dialog')
expect(modalEl.getAttribute('aria-hidden')).toBeNull()
expect(modalEl.style.display).toEqual('block')
expect(document.querySelector('.modal-backdrop')).not.toBeNull()
done()
})
modal.show()
})
it('should show a modal without backdrop', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl, {
backdrop: false
})
modalEl.addEventListener('show.bs.modal', event => {
expect(event).toBeDefined()
})
modalEl.addEventListener('shown.bs.modal', () => {
expect(modalEl.getAttribute('aria-modal')).toEqual('true')
expect(modalEl.getAttribute('role')).toEqual('dialog')
expect(modalEl.getAttribute('aria-hidden')).toBeNull()
expect(modalEl.style.display).toEqual('block')
expect(document.querySelector('.modal-backdrop')).toBeNull()
done()
})
modal.show()
})
it('should show a modal and append the element', done => {
const modalEl = document.createElement('div')
const id = 'dynamicModal'
modalEl.setAttribute('id', id)
modalEl.classList.add('modal')
modalEl.innerHTML = '<div class="modal-dialog"></div>'
const modal = new Modal(modalEl)
modalEl.addEventListener('shown.bs.modal', () => {
const dynamicModal = document.getElementById(id)
expect(dynamicModal).not.toBeNull()
dynamicModal.remove()
done()
})
modal.show()
})
it('should do nothing if a modal is shown', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
spyOn(EventHandler, 'trigger')
modal._isShown = true
modal.show()
expect(EventHandler.trigger).not.toHaveBeenCalled()
})
it('should do nothing if a modal is transitioning', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
spyOn(EventHandler, 'trigger')
modal._isTransitioning = true
modal.show()
expect(EventHandler.trigger).not.toHaveBeenCalled()
})
it('should not fire shown event when show is prevented', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modalEl.addEventListener('show.bs.modal', event => {
event.preventDefault()
const expectedDone = () => {
expect().nothing()
done()
}
setTimeout(expectedDone, 10)
})
modalEl.addEventListener('shown.bs.modal', () => {
throw new Error('shown event triggered')
})
modal.show()
})
it('should be shown after the first call to show() has been prevented while fading is enabled ', done => {
fixtureEl.innerHTML = '<div class="modal fade"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
let prevented = false
modalEl.addEventListener('show.bs.modal', event => {
if (!prevented) {
event.preventDefault()
prevented = true
setTimeout(() => {
modal.show()
})
}
})
modalEl.addEventListener('shown.bs.modal', () => {
expect(prevented).toBeTrue()
expect(modal._isAnimated()).toBeTrue()
done()
})
modal.show()
})
it('should set is transitioning if fade class is present', done => {
fixtureEl.innerHTML = '<div class="modal fade"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modalEl.addEventListener('show.bs.modal', () => {
setTimeout(() => {
expect(modal._isTransitioning).toEqual(true)
})
})
modalEl.addEventListener('shown.bs.modal', () => {
expect(modal._isTransitioning).toEqual(false)
done()
})
modal.show()
})
it('should close modal when a click occurred on data-bs-dismiss="modal" inside modal', done => {
fixtureEl.innerHTML = [
'<div class="modal fade">',
' <div class="modal-dialog">',
' <div class="modal-header">',
' <button type="button" data-bs-dismiss="modal"></button>',
' </div>',
' </div>',
'</div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const btnClose = fixtureEl.querySelector('[data-bs-dismiss="modal"]')
const modal = new Modal(modalEl)
spyOn(modal, 'hide').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
btnClose.click()
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(modal.hide).toHaveBeenCalled()
done()
})
modal.show()
})
it('should close modal when a click occurred on a data-bs-dismiss="modal" with "bs-target" outside of modal element', done => {
fixtureEl.innerHTML = [
'<button type="button" data-bs-dismiss="modal" data-bs-target="#modal1"></button>',
'<div id="modal1" class="modal fade">',
' <div class="modal-dialog">',
' </div>',
'</div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const btnClose = fixtureEl.querySelector('[data-bs-dismiss="modal"]')
const modal = new Modal(modalEl)
spyOn(modal, 'hide').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
btnClose.click()
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(modal.hide).toHaveBeenCalled()
done()
})
modal.show()
})
it('should set .modal\'s scroll top to 0', done => {
fixtureEl.innerHTML = [
'<div class="modal fade">',
' <div class="modal-dialog">',
' </div>',
'</div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modalEl.addEventListener('shown.bs.modal', () => {
expect(modalEl.scrollTop).toEqual(0)
done()
})
modal.show()
})
it('should set modal body scroll top to 0 if modal body do not exists', done => {
fixtureEl.innerHTML = [
'<div class="modal fade">',
' <div class="modal-dialog">',
' <div class="modal-body"></div>',
' </div>',
'</div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const modalBody = modalEl.querySelector('.modal-body')
const modal = new Modal(modalEl)
modalEl.addEventListener('shown.bs.modal', () => {
expect(modalBody.scrollTop).toEqual(0)
done()
})
modal.show()
})
it('should not trap focus if focus equal to false', done => {
fixtureEl.innerHTML = '<div class="modal fade"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl, {
focus: false
})
spyOn(modal._focustrap, 'activate').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
expect(modal._focustrap.activate).not.toHaveBeenCalled()
done()
})
modal.show()
})
it('should add listener when escape touch is pressed', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
spyOn(modal, 'hide').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
const keydownEscape = createEvent('keydown')
keydownEscape.key = 'Escape'
modalEl.dispatchEvent(keydownEscape)
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(modal.hide).toHaveBeenCalled()
done()
})
modal.show()
})
it('should do nothing when the pressed key is not escape', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
spyOn(modal, 'hide')
const expectDone = () => {
expect(modal.hide).not.toHaveBeenCalled()
done()
}
modalEl.addEventListener('shown.bs.modal', () => {
const keydownTab = createEvent('keydown')
keydownTab.key = 'Tab'
modalEl.dispatchEvent(keydownTab)
setTimeout(expectDone, 30)
})
modal.show()
})
it('should adjust dialog on resize', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
spyOn(modal, '_adjustDialog').and.callThrough()
const expectDone = () => {
expect(modal._adjustDialog).toHaveBeenCalled()
done()
}
modalEl.addEventListener('shown.bs.modal', () => {
const resizeEvent = createEvent('resize')
window.dispatchEvent(resizeEvent)
setTimeout(expectDone, 10)
})
modal.show()
})
it('should not close modal when clicking outside of modal-content if backdrop = false', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl, {
backdrop: false
})
const shownCallback = () => {
setTimeout(() => {
expect(modal._isShown).toEqual(true)
done()
}, 10)
}
modalEl.addEventListener('shown.bs.modal', () => {
modalEl.click()
shownCallback()
})
modalEl.addEventListener('hidden.bs.modal', () => {
throw new Error('Should not hide a modal')
})
modal.show()
})
it('should not close modal when clicking outside of modal-content if backdrop = static', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl, {
backdrop: 'static'
})
const shownCallback = () => {
setTimeout(() => {
expect(modal._isShown).toEqual(true)
done()
}, 10)
}
modalEl.addEventListener('shown.bs.modal', () => {
modalEl.click()
shownCallback()
})
modalEl.addEventListener('hidden.bs.modal', () => {
throw new Error('Should not hide a modal')
})
modal.show()
})
it('should close modal when escape key is pressed with keyboard = true and backdrop is static', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl, {
backdrop: 'static',
keyboard: true
})
const shownCallback = () => {
setTimeout(() => {
expect(modal._isShown).toEqual(false)
done()
}, 10)
}
modalEl.addEventListener('shown.bs.modal', () => {
const keydownEscape = createEvent('keydown')
keydownEscape.key = 'Escape'
modalEl.dispatchEvent(keydownEscape)
shownCallback()
})
modal.show()
})
it('should not close modal when escape key is pressed with keyboard = false', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl, {
keyboard: false
})
const shownCallback = () => {
setTimeout(() => {
expect(modal._isShown).toEqual(true)
done()
}, 10)
}
modalEl.addEventListener('shown.bs.modal', () => {
const keydownEscape = createEvent('keydown')
keydownEscape.key = 'Escape'
modalEl.dispatchEvent(keydownEscape)
shownCallback()
})
modalEl.addEventListener('hidden.bs.modal', () => {
throw new Error('Should not hide a modal')
})
modal.show()
})
it('should not overflow when clicking outside of modal-content if backdrop = static', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog" style="transition-duration: 20ms;"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl, {
backdrop: 'static'
})
modalEl.addEventListener('shown.bs.modal', () => {
modalEl.click()
setTimeout(() => {
expect(modalEl.clientHeight).toEqual(modalEl.scrollHeight)
done()
}, 20)
})
modal.show()
})
it('should not queue multiple callbacks when clicking outside of modal-content and backdrop = static', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog" style="transition-duration: 50ms;"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl, {
backdrop: 'static'
})
modalEl.addEventListener('shown.bs.modal', () => {
const spy = spyOn(modal, '_queueCallback').and.callThrough()
modalEl.click()
modalEl.click()
setTimeout(() => {
expect(spy).toHaveBeenCalledTimes(1)
done()
}, 20)
})
modal.show()
})
it('should trap focus', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
spyOn(modal._focustrap, 'activate').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
expect(modal._focustrap.activate).toHaveBeenCalled()
done()
})
modal.show()
})
})
describe('hide', () => {
it('should hide a modal', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modalEl.addEventListener('shown.bs.modal', () => {
modal.hide()
})
modalEl.addEventListener('hide.bs.modal', event => {
expect(event).toBeDefined()
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(modalEl.getAttribute('aria-modal')).toBeNull()
expect(modalEl.getAttribute('role')).toBeNull()
expect(modalEl.getAttribute('aria-hidden')).toEqual('true')
expect(modalEl.style.display).toEqual('none')
expect(document.querySelector('.modal-backdrop')).toBeNull()
done()
})
modal.show()
})
it('should close modal when clicking outside of modal-content', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modalEl.addEventListener('shown.bs.modal', () => {
modalEl.click()
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(modalEl.getAttribute('aria-modal')).toBeNull()
expect(modalEl.getAttribute('role')).toBeNull()
expect(modalEl.getAttribute('aria-hidden')).toEqual('true')
expect(modalEl.style.display).toEqual('none')
expect(document.querySelector('.modal-backdrop')).toBeNull()
done()
})
modal.show()
})
it('should do nothing is the modal is not shown', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modal.hide()
expect().nothing()
})
it('should do nothing is the modal is transitioning', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modal._isTransitioning = true
modal.hide()
expect().nothing()
})
it('should not hide a modal if hide is prevented', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
modalEl.addEventListener('shown.bs.modal', () => {
modal.hide()
})
const hideCallback = () => {
setTimeout(() => {
expect(modal._isShown).toEqual(true)
done()
}, 10)
}
modalEl.addEventListener('hide.bs.modal', event => {
event.preventDefault()
hideCallback()
})
modalEl.addEventListener('hidden.bs.modal', () => {
throw new Error('should not trigger hidden')
})
modal.show()
})
it('should release focus trap', done => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
spyOn(modal._focustrap, 'deactivate').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
modal.hide()
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(modal._focustrap.deactivate).toHaveBeenCalled()
done()
})
modal.show()
})
})
describe('dispose', () => {
it('should dispose a modal', () => {
fixtureEl.innerHTML = '<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
const focustrap = modal._focustrap
spyOn(focustrap, 'deactivate').and.callThrough()
expect(Modal.getInstance(modalEl)).toEqual(modal)
spyOn(EventHandler, 'off')
modal.dispose()
expect(Modal.getInstance(modalEl)).toBeNull()
expect(EventHandler.off).toHaveBeenCalledTimes(3)
expect(focustrap.deactivate).toHaveBeenCalled()
})
})
describe('handleUpdate', () => {
it('should call adjust dialog', () => {
fixtureEl.innerHTML = '<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>'
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
spyOn(modal, '_adjustDialog')
modal.handleUpdate()
expect(modal._adjustDialog).toHaveBeenCalled()
})
})
describe('data-api', () => {
it('should toggle modal', done => {
fixtureEl.innerHTML = [
'<button type="button" data-bs-toggle="modal" data-bs-target="#exampleModal"></button>',
'<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]')
modalEl.addEventListener('shown.bs.modal', () => {
expect(modalEl.getAttribute('aria-modal')).toEqual('true')
expect(modalEl.getAttribute('role')).toEqual('dialog')
expect(modalEl.getAttribute('aria-hidden')).toBeNull()
expect(modalEl.style.display).toEqual('block')
expect(document.querySelector('.modal-backdrop')).not.toBeNull()
setTimeout(() => trigger.click(), 10)
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(modalEl.getAttribute('aria-modal')).toBeNull()
expect(modalEl.getAttribute('role')).toBeNull()
expect(modalEl.getAttribute('aria-hidden')).toEqual('true')
expect(modalEl.style.display).toEqual('none')
expect(document.querySelector('.modal-backdrop')).toBeNull()
done()
})
trigger.click()
})
it('should not recreate a new modal', done => {
fixtureEl.innerHTML = [
'<button type="button" data-bs-toggle="modal" data-bs-target="#exampleModal"></button>',
'<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const modal = new Modal(modalEl)
const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]')
spyOn(modal, 'show').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
expect(modal.show).toHaveBeenCalled()
done()
})
trigger.click()
})
it('should prevent default when the trigger is <a> or <area>', done => {
fixtureEl.innerHTML = [
'<a data-bs-toggle="modal" href="#" data-bs-target="#exampleModal"></a>',
'<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]')
spyOn(Event.prototype, 'preventDefault').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
expect(modalEl.getAttribute('aria-modal')).toEqual('true')
expect(modalEl.getAttribute('role')).toEqual('dialog')
expect(modalEl.getAttribute('aria-hidden')).toBeNull()
expect(modalEl.style.display).toEqual('block')
expect(document.querySelector('.modal-backdrop')).not.toBeNull()
expect(Event.prototype.preventDefault).toHaveBeenCalled()
done()
})
trigger.click()
})
it('should focus the trigger on hide', done => {
fixtureEl.innerHTML = [
'<a data-bs-toggle="modal" href="#" data-bs-target="#exampleModal"></a>',
'<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]')
spyOn(trigger, 'focus')
modalEl.addEventListener('shown.bs.modal', () => {
const modal = Modal.getInstance(modalEl)
modal.hide()
})
const hideListener = () => {
setTimeout(() => {
expect(trigger.focus).toHaveBeenCalled()
done()
}, 20)
}
modalEl.addEventListener('hidden.bs.modal', () => {
hideListener()
})
trigger.click()
})
it('should not prevent default when a click occurred on data-bs-dismiss="modal" where tagName is DIFFERENT than <a> or <area>', done => {
fixtureEl.innerHTML = [
'<div class="modal">',
' <div class="modal-dialog">',
' <button type="button" data-bs-dismiss="modal"></button>',
' </div>',
'</div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const btnClose = fixtureEl.querySelector('button[data-bs-dismiss="modal"]')
const modal = new Modal(modalEl)
spyOn(Event.prototype, 'preventDefault').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
btnClose.click()
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(Event.prototype.preventDefault).not.toHaveBeenCalled()
done()
})
modal.show()
})
it('should prevent default when a click occurred on data-bs-dismiss="modal" where tagName is <a> or <area>', done => {
fixtureEl.innerHTML = [
'<div class="modal">',
' <div class="modal-dialog">',
' <a type="button" data-bs-dismiss="modal"></a>',
' </div>',
'</div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const btnClose = fixtureEl.querySelector('a[data-bs-dismiss="modal"]')
const modal = new Modal(modalEl)
spyOn(Event.prototype, 'preventDefault').and.callThrough()
modalEl.addEventListener('shown.bs.modal', () => {
btnClose.click()
})
modalEl.addEventListener('hidden.bs.modal', () => {
expect(Event.prototype.preventDefault).toHaveBeenCalled()
done()
})
modal.show()
})
it('should not focus the trigger if the modal is not visible', done => {
fixtureEl.innerHTML = [
'<a data-bs-toggle="modal" href="#" data-bs-target="#exampleModal" style="display: none;"></a>',
'<div id="exampleModal" class="modal" style="display: none;"><div class="modal-dialog"></div></div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]')
spyOn(trigger, 'focus')
modalEl.addEventListener('shown.bs.modal', () => {
const modal = Modal.getInstance(modalEl)
modal.hide()
})
const hideListener = () => {
setTimeout(() => {
expect(trigger.focus).not.toHaveBeenCalled()
done()
}, 20)
}
modalEl.addEventListener('hidden.bs.modal', () => {
hideListener()
})
trigger.click()
})
it('should not focus the trigger if the modal is not shown', done => {
fixtureEl.innerHTML = [
'<a data-bs-toggle="modal" href="#" data-bs-target="#exampleModal"></a>',
'<div id="exampleModal" class="modal"><div class="modal-dialog"></div></div>'
].join('')
const modalEl = fixtureEl.querySelector('.modal')
const trigger = fixtureEl.querySelector('[data-bs-toggle="modal"]')
spyOn(trigger, 'focus')
const showListener = () => {
setTimeout(() => {
expect(trigger.focus).not.toHaveBeenCalled()
done()
}, 10)
}
modalEl.addEventListener('show.bs.modal', event => {
event.preventDefault()
showListener()
})
trigger.click()
})
it('should call hide first, if another modal is open', done => {
fixtureEl.innerHTML = [
'<button data-bs-toggle="modal" data-bs-target="#modal2"></button>',
'<div id="modal1" class="modal fade"><div class="modal-dialog"></div></div>',
'<div id="modal2" class="modal"><div class="modal-dialog"></div></div>'
].join('')
const trigger2 = fixtureEl.querySelector('button')
const modalEl1 = document.querySelector('#modal1')
const modalEl2 = document.querySelector('#modal2')
const modal1 = new Modal(modalEl1)
modalEl1.addEventListener('shown.bs.modal', () => {
trigger2.click()
})
modalEl1.addEventListener('hidden.bs.modal', () => {
expect(Modal.getInstance(modalEl2)).not.toBeNull()
expect(modalEl2.classList.contains('show')).toBeTrue()
done()
})
modal1.show()
})
})
describe('jQueryInterface', () => {
it('should create a modal', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const div = fixtureEl.querySelector('div')
jQueryMock.fn.modal = Modal.jQueryInterface
jQueryMock.elements = [div]
jQueryMock.fn.modal.call(jQueryMock)
expect(Modal.getInstance(div)).not.toBeNull()
})
it('should create a modal with given config', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const div = fixtureEl.querySelector('div')
jQueryMock.fn.modal = Modal.jQueryInterface
jQueryMock.elements = [div]
jQueryMock.fn.modal.call(jQueryMock, { keyboard: false })
spyOn(Modal.prototype, 'constructor')
expect(Modal.prototype.constructor).not.toHaveBeenCalledWith(div, { keyboard: false })
const modal = Modal.getInstance(div)
expect(modal).not.toBeNull()
expect(modal._config.keyboard).toBe(false)
})
it('should not re create a modal', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const div = fixtureEl.querySelector('div')
const modal = new Modal(div)
jQueryMock.fn.modal = Modal.jQueryInterface
jQueryMock.elements = [div]
jQueryMock.fn.modal.call(jQueryMock)
expect(Modal.getInstance(div)).toEqual(modal)
})
it('should throw error on undefined method', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const div = fixtureEl.querySelector('div')
const action = 'undefinedMethod'
jQueryMock.fn.modal = Modal.jQueryInterface
jQueryMock.elements = [div]
expect(() => {
jQueryMock.fn.modal.call(jQueryMock, action)
}).toThrowError(TypeError, `No method named "${action}"`)
})
it('should call show method', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const div = fixtureEl.querySelector('div')
const modal = new Modal(div)
jQueryMock.fn.modal = Modal.jQueryInterface
jQueryMock.elements = [div]
spyOn(modal, 'show')
jQueryMock.fn.modal.call(jQueryMock, 'show')
expect(modal.show).toHaveBeenCalled()
})
it('should not call show method', () => {
fixtureEl.innerHTML = '<div class="modal" data-bs-show="false"><div class="modal-dialog"></div></div>'
const div = fixtureEl.querySelector('div')
jQueryMock.fn.modal = Modal.jQueryInterface
jQueryMock.elements = [div]
spyOn(Modal.prototype, 'show')
jQueryMock.fn.modal.call(jQueryMock)
expect(Modal.prototype.show).not.toHaveBeenCalled()
})
})
describe('getInstance', () => {
it('should return modal instance', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const div = fixtureEl.querySelector('div')
const modal = new Modal(div)
expect(Modal.getInstance(div)).toEqual(modal)
expect(Modal.getInstance(div)).toBeInstanceOf(Modal)
})
it('should return null when there is no modal instance', () => {
fixtureEl.innerHTML = '<div class="modal"><div class="modal-dialog"></div></div>'
const div = fixtureEl.querySelector('div')
expect(Modal.getInstance(div)).toBeNull()
})
})
describe('getOrCreateInstance', () => {
it('should return modal instance', () => {
fixtureEl.innerHTML = '<div></div>'
const div = fixtureEl.querySelector('div')
const modal = new Modal(div)
expect(Modal.getOrCreateInstance(div)).toEqual(modal)
expect(Modal.getInstance(div)).toEqual(Modal.getOrCreateInstance(div, {}))
expect(Modal.getOrCreateInstance(div)).toBeInstanceOf(Modal)
})
it('should return new instance when there is no modal instance', () => {
fixtureEl.innerHTML = '<div></div>'
const div = fixtureEl.querySelector('div')
expect(Modal.getInstance(div)).toEqual(null)
expect(Modal.getOrCreateInstance(div)).toBeInstanceOf(Modal)
})
it('should return new instance when there is no modal instance with given configuration', () => {
fixtureEl.innerHTML = '<div></div>'
const div = fixtureEl.querySelector('div')
expect(Modal.getInstance(div)).toEqual(null)
const modal = Modal.getOrCreateInstance(div, {
backdrop: true
})
expect(modal).toBeInstanceOf(Modal)
expect(modal._config.backdrop).toEqual(true)
})
it('should return the instance when exists without given configuration', () => {
fixtureEl.innerHTML = '<div></div>'
const div = fixtureEl.querySelector('div')
const modal = new Modal(div, {
backdrop: true
})
expect(Modal.getInstance(div)).toEqual(modal)
const modal2 = Modal.getOrCreateInstance(div, {
backdrop: false
})
expect(modal).toBeInstanceOf(Modal)
expect(modal2).toEqual(modal)
expect(modal2._config.backdrop).toEqual(true)
})
})
})
| kmcurry/3Scape | public/bower_components/bootstrap/js/tests/unit/modal.spec.js | JavaScript | gpl-3.0 | 35,285 |
/**
* Dokuwiki Namespaced template java file
*
* @link https://www.dokuwiki.org/template:namespaced
* @author Simon DELAGE <sdelage@gmail.com>
* @license GPL 2 (https://www.gnu.org/licenses/gpl-2.0.html)
*
* Here comes java magic
*
* We handle several device classes based on browser width.
* - desktop: > __tablet_width__ (as set in style.ini)
* - mobile:
* - tablet <= __tablet_width__
* - phone <= __phone_width__
*/
var device_class = ''; // not yet known
var device_classes = 'desktop mobile tablet phone';
var $docHeight = jQuery(document).height();
var $sitenavH = 0;
if (jQuery('#namespaced__site_nav').hasClass("sticky")) $sitenavH = jQuery('#namespaced__site_nav').outerHeight();
var $pagenavH = 0;
if (jQuery('#namespaced__page_nav').hasClass("sticky")) $pagenavH = jQuery('#namespaced__page_nav').outerHeight();
var $scrollDelta = $sitenavH + $pagenavH;
//// blur when clicked
//jQuery('#dokuwiki__pagetools div.tools>ul>li>a').on('click', function(){
// this.blur();
//});
// RESIZE WATCHER
jQuery(function(){
var resizeTimer;
dw_page.makeToggle('#namespaced__aside h6.toggle','#namespaced__aside div.content');
tpl_dokuwiki_mobile();
jQuery(window).on('resize',
function(){
if (resizeTimer) clearTimeout(resizeTimer);
resizeTimer = setTimeout(tpl_dokuwiki_mobile,200);
}
);
});
function tpl_dokuwiki_mobile(){
// the z-index in mobile.css is (mis-)used purely for detecting the screen mode here
var screen_mode = jQuery('#screen__mode').css('z-index') + '';
// determine our device pattern
// TODO: consider moving into dokuwiki core
switch (screen_mode) {
case '2002':
if (device_class.match(/extract-sidebar/)) return;
device_class = 'desktop extract-sidebar';
break;
case '2001':
if (device_class.match(/extract-toc/)) return;
device_class = 'desktop extract-toc';
break;
case '1001':
if (device_class.match(/phone/)) return;
device_class = 'mobile phone';
break;
default:
if (device_class == 'desktop') return;
device_class = 'desktop';
}
jQuery('html').removeClass(device_classes).addClass(device_class);
// handle some layout changes based on change in device
var $handle = jQuery('#namespaced__aside h6.toggle');
var $toc = jQuery('#dw__toc h3');
if (device_class == 'desktop') {
// reset for desktop mode
if($handle.length) {
$handle[0].setState(1);
//$handle.hide();
}
if($toc.length) {
$toc[0].setState(1);
}
}
if (device_class.match(/mobile/)){
// toc and sidebar hiding
if($handle.length) {
//$handle.show();
$handle[0].setState(-1);
}
if($toc.length) {
$toc[0].setState(-1);
}
}
}
// SCROLL WATCHER
// Watch scroll to show/hide got-to-top/bottom page tools
jQuery(document).scroll(function() {
var $scrollTop = jQuery(document).scrollTop();
if ($scrollTop >= 600) {
// user scrolled 600 pixels or more;
jQuery('#namespaced__pagetools ul li.top').fadeIn(500);
if ($scrollTop >= $docHeight - 1200) {
// user scrolled 600 pixels or more;
jQuery('#namespaced__pagetools ul li.bottom').fadeOut(0);
} else {
jQuery('#namespaced__pagetools ul li.bottom').fadeIn(500);
}
} else {
jQuery('#namespaced__pagetools ul li.top').fadeOut(0);
}
});
// CLICK WATCHER
// Add scroll delta from stickies when clicking a link
//jQuery('a[href*="#"]:not([href="#spacious__main"])').click(function(e) {
jQuery('a[href*="#"]').click(function() {
var $target = jQuery(this.hash);
//if ($target.length == 0) target = jQuery('a[name="' + this.hash.substr(1) + '"]');
if ($target.length == 0) $target = jQuery('html');
// Move to intended target with delta depending on stickies
jQuery('html, body').scrollTop($target.offset().top - $scrollDelta );
return false;
});
//jQuery(document).ready(function() {
// jQuery('#namespaced__updown .up').fadeIn(0);
//});
| geekitude/dokuwiki-template-namespaced | script.js | JavaScript | gpl-3.0 | 4,265 |
const teams = [
{
id: "sln",
full: "St. Louis Cardinals",
location: "St. Louis",
nickname: "Cardinals",
},
{
id: "mil",
full: "Milwaukee Brewers",
location: "Milwaukee",
nickname: "Brewers",
},
{
id: "atl",
full: "Atlanta Braves",
location: "Atlanta",
nickname: "Braves",
},
{
id: "nyn",
full: "New York Mets",
location: "New York",
nickname: "Mets",
},
{
id: "nya",
full: "New York Yankees",
location: "New York",
nickname: "Yankees",
},
{
id: "was",
full: "Washington Nationals",
location: "Washington",
nickname: "Nationals",
},
{
id: "tor",
full: "Toronto Blue Jays",
location: "Toronto",
nickname: "Blue Jays",
},
{
id: "chn",
full: "Chicago Cubs",
location: "Chicago",
nickname: "Cubs",
},
{
id: "cha",
full: "Chicago White Sox",
location: "Chicago",
nickname: "White Sox",
},
{
id: "bos",
full: "Boston Red Sox",
location: "Boston",
nickname: "Red Sox",
},
{
id: "phi",
full: "Philadelphia Phillies",
location: "Philadelphia",
nickname: "Phillies",
},
{
id: "bal",
full: "Baltimore Orioles",
location: "Baltimore",
nickname: "Orioles",
},
{
id: "cin",
full: "Cincinnati Reds",
location: "Cincinnati",
nickname: "Reds",
},
{
id: "cle",
full: "Cleveland Indians",
location: "Cleveland",
nickname: "Indians",
},
{
id: "det",
full: "Detroit Tigers",
location: "Detroit",
nickname: "Tigers",
},
{
id: "min",
full: "Minnesota Twins",
location: "Minnesota",
nickname: "Twins",
},
{
id: "lan",
full: "Los Angeles Dodgers",
location: "Los Angeles",
nickname: "Dodgers",
},
{
id: "ana",
full: "Los Angeles Angels",
location: "Los Angeles",
nickname: "Angels",
},
{
id: "mia",
full: "Miami Marlins",
location: "Miami",
nickname: "Marlins",
},
{
id: "sea",
full: "Seattle Mariners",
location: "Seattle",
nickname: "Mariners",
},
{
id: "pit",
full: "Pittsburgh Pirates",
location: "Pittsburgh",
nickname: "Pirates",
},
{
id: "oak",
full: "Oakland Athletics",
location: "Oakland",
nickname: "Athletics",
},
{
id: "sfn",
full: "San Francisco Giants",
location: "San Francisco",
nickname: "Giants",
},
{
id: "col",
full: "Colorado Rockies",
location: "Colorado",
nickname: "Rockies",
},
{
id: "sdn",
full: "San Diego Padres",
location: "San Diego",
nickname: "Padres",
},
{
id: "hou",
full: "Houston Astros",
location: "Houston",
nickname: "Astros",
},
{
id: "kca",
full: "Kansas City Royals",
location: "Kansas City",
nickname: "Royals",
},
{
id: "tex",
full: "Texas Rangers",
location: "Texas",
nickname: "Rangers",
},
{
id: "tba",
full: "Tampa Bay Rays",
location: "Tampa Bay",
nickname: "Rays",
},
{
id: "ari",
full: "Arizona Diamondbacks",
location: "Arizona",
nickname: "Diamondbacks",
},
];
module.exports = teams; | Conrad2134/pitchfx | src/teams.js | JavaScript | gpl-3.0 | 2,914 |
"use strict";
const { BrowserWindow } = require("electron");
module.exports = (dirname, storage) => {
let win;
let init = () => {
if (win === null || win === undefined) {
createWindow();
}
};
let createWindow = () => {
const { screen } = require("electron");
const { width, height } = screen.getPrimaryDisplay().workAreaSize;
win = new BrowserWindow({
frame: false,
autoHideMenuBar: true,
width: width,
height: height,
transparent: true,
alwaysOnTop: true,
resizable: false,
movable: false,
hasShadow: false,
});
win.loadURL(`file://${dirname}/views/support.html`);
win.on("closed", () => {
win = undefined;
});
};
let getWindow = () => win;
return {
init: init,
getWindow: getWindow,
};
};
| Toinane/colorpicker | src/browsers/support.js | JavaScript | gpl-3.0 | 950 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
* Copyright (C) 2014-2015 University of Arizona.
*
* 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/>.
*
* Author: Jerald Paul Abraham <jeraldabraham@email.arizona.edu>
*/
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <string>
#include <unistd.h>
#include <vector>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem.hpp>
#include <boost/noncopyable.hpp>
#include <ndn-cxx/exclude.hpp>
#include <ndn-cxx/face.hpp>
#include <ndn-cxx/name-component.hpp>
#include <ndn-cxx/util/backports.hpp>
#include "logger.hpp"
namespace ndn {
class NdnTrafficClient : boost::noncopyable
{
public:
explicit
NdnTrafficClient(const char* programName)
: m_programName(programName)
, m_logger("NdnTrafficClient")
, m_instanceId(to_string(std::rand()))
, m_hasError(false)
, m_hasQuietLogging(false)
, m_interestInterval(getDefaultInterestInterval())
, m_nMaximumInterests(-1)
, m_face(m_ioService)
, m_nInterestsSent(0)
, m_nPatternsSent(0)
, m_nInterestsReceived(0)
, m_nContentInconsistencies(0)
, m_minimumInterestRoundTripTime(std::numeric_limits<double>::max())
, m_maximumInterestRoundTripTime(0)
, m_totalInterestRoundTripTime(0)
{
}
class InterestTrafficConfiguration
{
public:
InterestTrafficConfiguration()
: m_trafficPercentage(-1)
, m_nameAppendBytes(-1)
, m_nameAppendSequenceNumber(-1)
, m_minSuffixComponents(-1)
, m_maxSuffixComponents(-1)
, m_excludeBeforeBytes(-1)
, m_excludeAfterBytes(-1)
, m_childSelector(-1)
, m_mustBeFresh(-1)
, m_nonceDuplicationPercentage(-1)
, m_interestLifetime(getDefaultInterestLifetime())
, m_nInterestsSent(0)
, m_nInterestsReceived(0)
, m_minimumInterestRoundTripTime(std::numeric_limits<double>::max())
, m_maximumInterestRoundTripTime(0)
, m_totalInterestRoundTripTime(0)
, m_nContentInconsistencies(0)
{
}
static time::milliseconds
getDefaultInterestLifetime()
{
return time::milliseconds(-1);
}
void
printTrafficConfiguration(Logger& logger)
{
std::string detail;
if (m_trafficPercentage > 0)
detail += "TrafficPercentage=" + to_string(m_trafficPercentage) + ", ";
if (!m_names.empty())
detail += "Name=" + m_names.at(0) + ", ";
if (m_nameAppendBytes > 0)
detail += "NameAppendBytes=" + to_string(m_nameAppendBytes) + ", ";
if (m_nameAppendSequenceNumber > 0)
detail += "NameAppendSequenceNumber=" + to_string(m_nameAppendSequenceNumber) + ", ";
if (m_minSuffixComponents >= 0)
detail += "MinSuffixComponents=" + to_string(m_minSuffixComponents) + ", ";
if (m_maxSuffixComponents >= 0)
detail += "MaxSuffixComponents=" + to_string(m_maxSuffixComponents) + ", ";
if (!m_excludeBefore.empty())
detail += "ExcludeBefore=" + m_excludeBefore + ", ";
if (!m_excludeAfter.empty())
detail += "ExcludeAfter=" + m_excludeAfter + ", ";
if (m_excludeBeforeBytes > 0)
detail += "ExcludeBeforeBytes=" + to_string(m_excludeBeforeBytes) + ", ";
if (m_excludeAfterBytes > 0)
detail += "ExcludeAfterBytes=" + to_string(m_excludeAfterBytes) + ", ";
if (m_childSelector >= 0)
detail += "ChildSelector=" + to_string(m_childSelector) + ", ";
if (m_mustBeFresh >= 0)
detail += "MustBeFresh=" + to_string(m_mustBeFresh) + ", ";
if (m_nonceDuplicationPercentage > 0)
detail += "NonceDuplicationPercentage=" + to_string(m_nonceDuplicationPercentage) + ", ";
if (m_interestLifetime >= time::milliseconds(0))
detail += "InterestLifetime=" + to_string(m_interestLifetime.count()) + ", ";
if (!m_expectedContents.empty())
detail += "ExpectedContent=" + m_expectedContents.at(0) + ", ";
if (detail.length() >= 2)
detail = detail.substr(0, detail.length() - 2); // Removing suffix ", "
logger.log(detail, false, false);
}
bool
extractParameterValue(const std::string& detail, std::string& parameter, std::string& value)
{
std::string allowedCharacters = ":/+._-%";
std::size_t i = 0;
parameter = "";
value = "";
while (detail[i] != '=' && i < detail.length()) {
parameter += detail[i];
i++;
}
if (i == detail.length())
return false;
i++;
while ((std::isalnum(detail[i]) ||
allowedCharacters.find(detail[i]) != std::string::npos) &&
i < detail.length()) {
value += detail[i];
i++;
}
if (parameter.empty() || value.empty())
return false;
else
return true;
}
bool
processConfigurationDetail(const std::string& detail, Logger& logger, int lineNumber)
{
std::string parameter, value;
if (extractParameterValue(detail, parameter, value))
{
if (parameter == "TrafficPercentage")
m_trafficPercentage = std::stoi(value);
else if (parameter == "Name")
{
std::cout << "Reading: "<<value<<"\n";
m_names.push_back(value);
}
else if (parameter == "NameAppendBytes")
m_nameAppendBytes = std::stoi(value);
else if (parameter == "NameAppendSequenceNumber")
m_nameAppendSequenceNumber = std::stoi(value);
else if (parameter == "MinSuffixComponents")
m_minSuffixComponents = std::stoi(value);
else if (parameter == "MaxSuffixComponents")
m_maxSuffixComponents = std::stoi(value);
else if (parameter == "ExcludeBefore")
m_excludeBefore = value;
else if (parameter == "ExcludeAfter")
m_excludeAfter = value;
else if (parameter == "ExcludeBeforeBytes")
m_excludeBeforeBytes = std::stoi(value);
else if (parameter == "ExcludeAfterBytes")
m_excludeAfterBytes = std::stoi(value);
else if (parameter == "ChildSelector")
m_childSelector = std::stoi(value);
else if (parameter == "MustBeFresh")
m_mustBeFresh = std::stoi(value);
else if (parameter == "NonceDuplicationPercentage")
m_nonceDuplicationPercentage = std::stoi(value);
else if (parameter == "InterestLifetime")
m_interestLifetime = time::milliseconds(std::stoi(value));
else if (parameter == "ExpectedContent")
{
m_expectedContents.push_back(value);
std::cout << "Reading content value: "<<value<<"\n";
}
else
logger.log("Line " + to_string(lineNumber) +
" \t- Invalid Parameter='" + parameter + "'", false, true);
}
else
{
logger.log("Line " + to_string(lineNumber) +
" \t- Improper Traffic Configuration Line- " + detail, false, true);
return false;
}
return true;
}
bool
checkTrafficDetailCorrectness()
{
return true;
}
private:
int m_trafficPercentage;
std::vector<std::string> m_names;
int m_nameAppendBytes;
int m_nameAppendSequenceNumber;
int m_minSuffixComponents;
int m_maxSuffixComponents;
std::string m_excludeBefore;
std::string m_excludeAfter;
int m_excludeBeforeBytes;
int m_excludeAfterBytes;
int m_childSelector;
int m_mustBeFresh;
int m_nonceDuplicationPercentage;
time::milliseconds m_interestLifetime;
int m_nInterestsSent;
int m_nInterestsReceived;
//round trip time is stored as milliseconds with fractional
//sub-millisecond precision
double m_minimumInterestRoundTripTime;
double m_maximumInterestRoundTripTime;
double m_totalInterestRoundTripTime;
int m_nContentInconsistencies;
std::vector<std::string> m_expectedContents;
friend class NdnTrafficClient;
}; // class InterestTrafficConfiguration
bool
hasError() const
{
return m_hasError;
}
void
usage() const
{
std::cout << "Usage:\n"
<< " " << m_programName << " [options] <Traffic_Configuration_File>\n"
<< "\n"
<< "Generate Interest traffic as per provided Traffic Configuration File.\n"
<< "Interests are continuously generated unless a total number is specified.\n"
<< "Set environment variable NDN_TRAFFIC_LOGFOLDER to redirect output to a log file.\n"
<< "\n"
<< "Options:\n"
<< " [-i interval] - set interest generation interval in milliseconds (default "
<< getDefaultInterestInterval() << ")\n"
<< " [-c count] - set total number of interests to be generated\n"
<< " [-q] - quiet mode: no interest reception/data generation logging\n"
<< " [-h] - print this help text and exit\n";
exit(EXIT_FAILURE);
}
static time::milliseconds
getDefaultInterestInterval()
{
return time::milliseconds(1000);
}
void
setInterestInterval(int interestInterval)
{
if (interestInterval <= 0)
usage();
m_interestInterval = time::milliseconds(interestInterval);
}
void
setMaximumInterests(int maximumInterests)
{
if (maximumInterests <= 0)
usage();
m_nMaximumInterests = maximumInterests;
}
void
setConfigurationFile(char* configurationFile)
{
m_configurationFile = configurationFile;
}
void
setQuietLogging()
{
m_hasQuietLogging = true;
}
void
signalHandler()
{
logStatistics();
m_logger.shutdownLogger();
m_face.shutdown();
m_ioService.stop();
exit(m_hasError ? EXIT_FAILURE : EXIT_SUCCESS);
}
void
logStatistics()
{
m_logger.log("\n\n== Interest Traffic Report ==\n", false, true);
m_logger.log("Total Traffic Pattern Types = " +
to_string(m_trafficPatterns.size()), false, true);
m_logger.log("Total Interests Sent = " +
to_string(m_nInterestsSent), false, true);
m_logger.log("Total Responses Received = " +
to_string(m_nInterestsReceived), false, true);
double loss = 0;
if (m_nInterestsSent > 0)
loss = (m_nInterestsSent - m_nInterestsReceived) * 100.0 / m_nInterestsSent;
m_logger.log("Total Interest Loss = " + to_string(loss) + "%", false, true);
if (m_nContentInconsistencies != 0 || m_nInterestsSent != m_nInterestsReceived)
m_hasError = true;
double average = 0;
double inconsistency = 0;
if (m_nInterestsReceived > 0)
{
average = m_totalInterestRoundTripTime / m_nInterestsReceived;
inconsistency = m_nContentInconsistencies * 100.0 / m_nInterestsReceived;
}
m_logger.log("Total Data Inconsistency = " +
to_string(inconsistency) + "%", false, true);
m_logger.log("Total Round Trip Time = " +
to_string(m_totalInterestRoundTripTime) + "ms", false, true);
m_logger.log("Average Round Trip Time = " +
to_string(average) + "ms\n", false, true);
for (std::size_t patternId = 0; patternId < m_trafficPatterns.size(); patternId++)
{
m_logger.log("Traffic Pattern Type #" +
to_string(patternId + 1), false, true);
m_trafficPatterns[patternId].printTrafficConfiguration(m_logger);
m_logger.log("Total Interests Sent = " +
to_string(m_trafficPatterns[patternId].m_nInterestsSent), false, true);
m_logger.log("Total Responses Received = " +
to_string(m_trafficPatterns[patternId].m_nInterestsReceived), false, true);
loss = 0;
if (m_trafficPatterns[patternId].m_nInterestsSent > 0)
{
loss = (m_trafficPatterns[patternId].m_nInterestsSent -
m_trafficPatterns[patternId].m_nInterestsReceived);
loss *= 100.0;
loss /= m_trafficPatterns[patternId].m_nInterestsSent;
}
m_logger.log("Total Interest Loss = " + to_string(loss) + "%", false, true);
average = 0;
inconsistency = 0;
if (m_trafficPatterns[patternId].m_nInterestsReceived > 0)
{
average = (m_trafficPatterns[patternId].m_totalInterestRoundTripTime /
m_trafficPatterns[patternId].m_nInterestsReceived);
inconsistency = m_trafficPatterns[patternId].m_nContentInconsistencies;
inconsistency *= 100.0 / m_trafficPatterns[patternId].m_nInterestsReceived;
}
m_logger.log("Total Data Inconsistency = " +
to_string(inconsistency) + "%", false, true);
m_logger.log("Total Round Trip Time = " +
to_string(m_trafficPatterns[patternId].m_totalInterestRoundTripTime) +
"ms", false, true);
m_logger.log("Average Round Trip Time = " +
to_string(average) + "ms\n", false, true);
}
}
bool
checkTrafficPatternCorrectness()
{
return true;
}
void
parseConfigurationFile()
{
std::string patternLine;
std::ifstream patternFile;
m_logger.log("Analyzing Traffic Configuration File: " + m_configurationFile, true, true);
patternFile.open(m_configurationFile.c_str());
if (patternFile.is_open())
{
int lineNumber = 0;
while (getline(patternFile, patternLine))
{
lineNumber++;
if (std::isalpha(patternLine[0]))
{
InterestTrafficConfiguration interestData;
bool shouldSkipLine = false;
if (interestData.processConfigurationDetail(patternLine, m_logger, lineNumber))
{
while (getline(patternFile, patternLine) && std::isalpha(patternLine[0]))
{
lineNumber++;
if (!interestData.processConfigurationDetail(patternLine,
m_logger, lineNumber))
{
shouldSkipLine = true;
break;
}
}
lineNumber++;
}
else
shouldSkipLine = true;
if (!shouldSkipLine)
{
if (interestData.checkTrafficDetailCorrectness())
m_trafficPatterns.push_back(interestData);
}
}
}
patternFile.close();
if (!checkTrafficPatternCorrectness())
{
m_logger.log("ERROR - Traffic Configuration Provided Is Not Proper- " +
m_configurationFile, false, true);
m_logger.shutdownLogger();
exit(EXIT_FAILURE);
}
m_logger.log("Traffic Configuration File Processing Completed\n", true, false);
for (std::size_t patternId = 0; patternId < m_trafficPatterns.size(); patternId++)
{
m_logger.log("Traffic Pattern Type #" +
to_string(patternId + 1), false, false);
m_trafficPatterns[patternId].printTrafficConfiguration(m_logger);
m_logger.log("", false, false);
}
}
else
{
m_logger.log("ERROR - Unable To Open Traffic Configuration File: " +
m_configurationFile, false, true);
m_logger.shutdownLogger();
exit(EXIT_FAILURE);
}
}
void
initializeTrafficConfiguration()
{
if (boost::filesystem::exists(boost::filesystem::path(m_configurationFile)))
{
if (boost::filesystem::is_regular_file(boost::filesystem::path(m_configurationFile)))
{
parseConfigurationFile();
}
else
{
m_logger.log("ERROR - Traffic Configuration File Is Not A Regular File: " +
m_configurationFile, false, true);
m_logger.shutdownLogger();
exit(EXIT_FAILURE);
}
}
else
{
m_logger.log("ERROR - Traffic Configuration File Does Not Exist: " +
m_configurationFile, false, true);
m_logger.shutdownLogger();
exit(EXIT_FAILURE);
}
}
uint32_t
getOldNonce()
{
if (m_nonces.size() == 0)
return getNewNonce();
int randomNonceIndex = std::rand() % m_nonces.size();
return m_nonces[randomNonceIndex];
}
uint32_t
getNewNonce()
{
//Performance Enhancement
if (m_nonces.size() > 1000)
m_nonces.clear();
uint32_t randomNonce = static_cast<uint32_t>(std::rand());
while (std::find(m_nonces.begin(), m_nonces.end(), randomNonce) != m_nonces.end())
randomNonce = static_cast<uint32_t>(std::rand());
m_nonces.push_back(randomNonce);
return randomNonce;
}
static name::Component
generateRandomNameComponent(size_t length)
{
Buffer buffer(length);
for (size_t i = 0; i < length; i++) {
buffer[i] = static_cast<uint8_t>(std::rand() % 256);
}
return name::Component(buffer);
}
void
onData(const ndn::Interest& interest,
ndn::Data& data,
int globalReference,
int localReference,
int patternId,
time::steady_clock::TimePoint sentTime)
{
std::string logLine = "Data Received - PatternType=" + to_string(patternId + 1);
logLine += ", GlobalID=" + to_string(globalReference);
logLine += ", LocalID=" + to_string(localReference);
logLine += ", Name=" + interest.getName().toUri();
unsigned int i;
bool consistent=false;
m_nInterestsReceived++;
m_trafficPatterns[patternId].m_nInterestsReceived++;
if (!m_trafficPatterns[patternId].m_expectedContents.empty())
{
std::string receivedContent = reinterpret_cast<const char*>(data.getContent().value());
int receivedContentLength = data.getContent().value_size();
receivedContent = receivedContent.substr(0, receivedContentLength);
for (i = 0; i < m_trafficPatterns[patternId].m_expectedContents.size(); i++)
{
std::cout <<"Comparing "<<receivedContent<<" with "<<m_trafficPatterns[patternId].m_expectedContents.at(i)<<"\n";
if (receivedContent == m_trafficPatterns[patternId].m_expectedContents.at(i))
{
logLine += ", IsConsistent=Yes";
consistent = true;
break;
}
}
if(!consistent)
{
m_nContentInconsistencies++;
m_trafficPatterns[patternId].m_nContentInconsistencies++;
logLine += ", IsConsistent=No";
}
}
else
logLine += ", IsConsistent=NotChecked";
if (!m_hasQuietLogging)
m_logger.log(logLine, true, false);
double roundTripTime = (time::steady_clock::now() - sentTime).count() / 1000000.0;
if (m_minimumInterestRoundTripTime > roundTripTime)
m_minimumInterestRoundTripTime = roundTripTime;
if (m_maximumInterestRoundTripTime < roundTripTime)
m_maximumInterestRoundTripTime = roundTripTime;
if (m_trafficPatterns[patternId].m_minimumInterestRoundTripTime > roundTripTime)
m_trafficPatterns[patternId].m_minimumInterestRoundTripTime = roundTripTime;
if (m_trafficPatterns[patternId].m_maximumInterestRoundTripTime < roundTripTime)
m_trafficPatterns[patternId].m_maximumInterestRoundTripTime = roundTripTime;
m_totalInterestRoundTripTime += roundTripTime;
m_trafficPatterns[patternId].m_totalInterestRoundTripTime += roundTripTime;
if (m_nMaximumInterests >= 0 && globalReference == m_nMaximumInterests)
{
logStatistics();
m_logger.shutdownLogger();
m_face.shutdown();
m_ioService.stop();
}
}
void
onTimeout(const ndn::Interest& interest,
int globalReference,
int localReference,
int patternId)
{
std::string logLine = "Interest Timed Out - PatternType=" + to_string(patternId + 1);
logLine += ", GlobalID=" + to_string(globalReference);
logLine += ", LocalID=" + to_string(localReference);
logLine += ", Name=" + interest.getName().toUri();
m_logger.log(logLine, true, false);
if (m_nMaximumInterests >= 0 && globalReference == m_nMaximumInterests)
{
logStatistics();
m_logger.shutdownLogger();
m_face.shutdown();
m_ioService.stop();
}
}
void
generateTraffic(boost::asio::deadline_timer* timer)
{
if (m_nMaximumInterests < 0 || m_nPatternsSent < m_nMaximumInterests)
{
int trafficKey = std::rand() % 100;
int cumulativePercentage = 0;
std::size_t patternId;
for (patternId = 0; patternId < m_trafficPatterns.size(); patternId++)
{
cumulativePercentage += m_trafficPatterns[patternId].m_trafficPercentage;
if (trafficKey <= cumulativePercentage)
{
m_nPatternsSent++;
std::cout<<"Size of the m_names is "<<m_trafficPatterns[patternId].m_names.size()<<"\n";
bool timer_scheduled = false;
for(unsigned int i = 0; i < m_trafficPatterns[patternId].m_names.size(); i++)
{
//Name interestName(m_trafficPatterns[patternId].m_name);
Name interestName(m_trafficPatterns[patternId].m_names.at(i));
std::cout <<"Name in interest: "<<interestName<<"\n";
if (m_trafficPatterns[patternId].m_nameAppendBytes > 0)
interestName.append(generateRandomNameComponent(m_trafficPatterns[patternId].m_nameAppendBytes));
if (m_trafficPatterns[patternId].m_nameAppendSequenceNumber >= 0)
{
interestName.append(to_string(m_trafficPatterns[patternId].m_nameAppendSequenceNumber));
m_trafficPatterns[patternId].m_nameAppendSequenceNumber++;
}
Interest interest(interestName);
if (m_trafficPatterns[patternId].m_minSuffixComponents >= 0)
interest.setMinSuffixComponents(
m_trafficPatterns[patternId].m_minSuffixComponents);
if (m_trafficPatterns[patternId].m_maxSuffixComponents >= 0)
interest.setMaxSuffixComponents(
m_trafficPatterns[patternId].m_maxSuffixComponents);
Exclude exclude;
if (!m_trafficPatterns[patternId].m_excludeBefore.empty() &&
!m_trafficPatterns[patternId].m_excludeAfter.empty())
{
exclude.excludeRange(
name::Component(
m_trafficPatterns[patternId].m_excludeAfter),
name::Component(m_trafficPatterns[patternId].m_excludeBefore));
interest.setExclude(exclude);
}
else if (!m_trafficPatterns[patternId].m_excludeBefore.empty())
{
exclude.excludeBefore(
name::Component(m_trafficPatterns[patternId].m_excludeBefore));
interest.setExclude(exclude);
}
else if (!m_trafficPatterns[patternId].m_excludeAfter.empty())
{
exclude.excludeAfter(
name::Component(m_trafficPatterns[patternId].m_excludeAfter));
interest.setExclude(exclude);
}
if (m_trafficPatterns[patternId].m_excludeBeforeBytes > 0 &&
m_trafficPatterns[patternId].m_excludeAfterBytes > 0)
{
exclude.excludeRange(
generateRandomNameComponent(
m_trafficPatterns[patternId].m_excludeAfterBytes),
generateRandomNameComponent(
m_trafficPatterns[patternId].m_excludeBeforeBytes));
interest.setExclude(exclude);
}
else if (m_trafficPatterns[patternId].m_excludeBeforeBytes > 0)
{
exclude.excludeBefore(
generateRandomNameComponent(
m_trafficPatterns[patternId].m_excludeBeforeBytes));
interest.setExclude(exclude);
}
else if (m_trafficPatterns[patternId].m_excludeAfterBytes > 0)
{
exclude.excludeAfter(
generateRandomNameComponent(
m_trafficPatterns[patternId].m_excludeAfterBytes));
interest.setExclude(exclude);
}
if (m_trafficPatterns[patternId].m_childSelector >= 0)
interest.setChildSelector(m_trafficPatterns[patternId].m_childSelector);
if (m_trafficPatterns[patternId].m_mustBeFresh == 0)
interest.setMustBeFresh(false);
else if (m_trafficPatterns[patternId].m_mustBeFresh > 0)
interest.setMustBeFresh(true);
if (m_trafficPatterns[patternId].m_nonceDuplicationPercentage > 0)
{
int duplicationPercentage = std::rand() % 100;
if (m_trafficPatterns[patternId].m_nonceDuplicationPercentage <=
duplicationPercentage)
interest.setNonce(getOldNonce());
else
interest.setNonce(getNewNonce());
}
else
interest.setNonce(getNewNonce());
if (m_trafficPatterns[patternId].m_interestLifetime >= time::milliseconds(0))
interest.setInterestLifetime(m_trafficPatterns[patternId].m_interestLifetime);
try {
m_nInterestsSent++;
m_trafficPatterns[patternId].m_nInterestsSent++;
time::steady_clock::TimePoint sentTime = time::steady_clock::now();
m_face.expressInterest(interest,
bind(&NdnTrafficClient::onData,
this, _1, _2, m_nPatternsSent,
m_trafficPatterns[patternId].m_nInterestsSent,
patternId, sentTime),
bind(&NdnTrafficClient::onTimeout,
this, _1, m_nInterestsSent,
m_trafficPatterns[patternId].m_nInterestsSent,
patternId));
if (!m_hasQuietLogging) {
std::string logLine =
"Sending Interest - PatternType=" + to_string(patternId + 1) +
", GlobalID=" + to_string(m_nInterestsSent) +
", LocalID=" +
to_string(m_trafficPatterns[patternId].m_nInterestsSent) +
", Name=" + interest.getName().toUri();
m_logger.log(logLine, true, false);
}
if(!timer_scheduled)
{
timer->expires_at(timer->expires_at() +
boost::posix_time::millisec(m_interestInterval.count()));
timer->async_wait(bind(&NdnTrafficClient::generateTraffic, this, timer));
timer_scheduled = true;
}
}
catch (const std::exception& e) {
m_logger.log("ERROR: " + std::string(e.what()), true, true);
}
}
break;
}
}
if (patternId == m_trafficPatterns.size())
{
timer->expires_at(timer->expires_at() +
boost::posix_time::millisec(m_interestInterval.count()));
timer->async_wait(bind(&NdnTrafficClient::generateTraffic, this, timer));
}
}
}
void
run()
{
boost::asio::signal_set signalSet(m_ioService, SIGINT, SIGTERM);
signalSet.async_wait(bind(&NdnTrafficClient::signalHandler, this));
m_logger.initializeLog(m_instanceId);
initializeTrafficConfiguration();
if (m_nMaximumInterests == 0)
{
logStatistics();
m_logger.shutdownLogger();
return;
}
boost::asio::deadline_timer deadlineTimer(m_ioService,
boost::posix_time::millisec(m_interestInterval.count()));
deadlineTimer.async_wait(bind(&NdnTrafficClient::generateTraffic, this, &deadlineTimer));
try {
m_face.processEvents();
}
catch (const std::exception& e) {
m_logger.log("ERROR: " + std::string(e.what()), true, true);
m_logger.shutdownLogger();
m_hasError = true;
m_ioService.stop();
}
}
private:
std::string m_programName;
Logger m_logger;
std::string m_instanceId;
bool m_hasError;
bool m_hasQuietLogging;
time::milliseconds m_interestInterval;
int m_nMaximumInterests;
std::string m_configurationFile;
boost::asio::io_service m_ioService;
Face m_face;
std::vector<InterestTrafficConfiguration> m_trafficPatterns;
std::vector<uint32_t> m_nonces;
int m_nInterestsSent;
int m_nPatternsSent;
int m_nInterestsReceived;
int m_nContentInconsistencies;
//round trip time is stored as milliseconds with fractional
//sub-milliseconds precision
double m_minimumInterestRoundTripTime;
double m_maximumInterestRoundTripTime;
double m_totalInterestRoundTripTime;
};
} // namespace ndn
int
main(int argc, char* argv[])
{
std::srand(std::time(nullptr));
ndn::NdnTrafficClient client(argv[0]);
int option;
while ((option = getopt(argc, argv, "hqi:c:")) != -1) {
switch (option) {
case 'h':
client.usage();
break;
case 'i':
client.setInterestInterval(atoi(optarg));
break;
case 'c':
client.setMaximumInterests(atoi(optarg));
break;
case 'q':
client.setQuietLogging();
break;
default:
client.usage();
break;
}
}
argc -= optind;
argv += optind;
if (!argc)
client.usage();
client.setConfigurationFile(argv[0]);
client.run();
return client.hasError() ? EXIT_FAILURE : EXIT_SUCCESS;
}
| oascigil/trafficgen | src/ndn-traffic-client.cpp | C++ | gpl-3.0 | 31,588 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import *
from unittest import TestCase
__author__ = 'nicolas'
import os
class TestTauPyModel(TestCase):
def test_create_taup_model(self):
"""
See if the create model function in the tau interface runs smoothly.
"""
from taupy import tau
try:
os.remove("ak135.taup")
except FileNotFoundError:
pass
ak135 = tau.TauPyModel("ak135", taup_model_path=".")
os.remove("ak135.taup")
| obspy/TauPy | taupy/tests/test_tauPyModel.py | Python | gpl-3.0 | 645 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* View
* @copyright (c) 2017, Davi Menezes (davimenezes.dvi@gmail.com)
*/
?>
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Read Mail <small> https://bitbucket.org/DaviMenezes</small>
</h1>
<ol class="breadcrumb">
<li><a href="<?= base_url() ?>"><i class="fa fa-dashboard"></i> Home </a></li>
<!--'<li class="active"></li>'-->
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-md-3">
<a href="<?= base_url("page/mail_compose") ?>" class="btn btn-primary btn-block margin-bottom">Compose</a>
<div class="box box-solid">
<div class="box-header with-border">
<h3 class="box-title">Folders</h3>
<div class="box-tools">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body no-padding">
<ul class="nav nav-pills nav-stacked">
<li><a href="<?= base_url("page/mailbox") ?>">
<i class = "fa fa-inbox"></i> Inbox
<span class="label label-primary pull-right">12</span>
</a>
</li>
<li><a href="#"><i class="fa fa-envelope-o"></i> Sent</a></li>
<li><a href="#"><i class="fa fa-file-text-o"></i> Drafts</a></li>
<li><a href="#"><i class="fa fa-filter"></i> Junk <span class="label label-warning pull-right">65</span></a>
</li>
<li><a href="#"><i class="fa fa-trash-o"></i> Trash</a></li>
</ul>
</div>
<!-- /.box-body -->
</div>
<!-- /. box -->
<div class="box box-solid">
<div class="box-header with-border">
<h3 class="box-title">Labels</h3>
<div class="box-tools">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
</div>
</div>
<div class="box-body no-padding">
<ul class="nav nav-pills nav-stacked">
<li><a href="#"><i class="fa fa-circle-o text-red"></i> Important</a></li>
<li><a href="#"><i class="fa fa-circle-o text-yellow"></i> Promotions</a></li>
<li><a href="#"><i class="fa fa-circle-o text-light-blue"></i> Social</a></li>
</ul>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
<div class="col-md-9">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Read Mail</h3>
<div class="box-tools pull-right">
<a href="#" class="btn btn-box-tool" data-toggle="tooltip" title="Previous"><i class="fa fa-chevron-left"></i></a>
<a href="#" class="btn btn-box-tool" data-toggle="tooltip" title="Next"><i class="fa fa-chevron-right"></i></a>
</div>
</div>
<!-- /.box-header -->
<div class="box-body no-padding">
<div class="mailbox-read-info">
<h3>Message Subject Is Placed Here</h3>
<h5>From: help@example.com
<span class="mailbox-read-time pull-right">15 Feb. 2016 11:03 PM</span></h5>
</div>
<!-- /.mailbox-read-info -->
<div class="mailbox-controls with-border text-center">
<div class="btn-group">
<button type="button" class="btn btn-default btn-sm" data-toggle="tooltip" data-container="body" title="Delete">
<i class="fa fa-trash-o"></i></button>
<button type="button" class="btn btn-default btn-sm" data-toggle="tooltip" data-container="body" title="Reply">
<i class="fa fa-reply"></i></button>
<button type="button" class="btn btn-default btn-sm" data-toggle="tooltip" data-container="body" title="Forward">
<i class="fa fa-share"></i></button>
</div>
<!-- /.btn-group -->
<button type="button" class="btn btn-default btn-sm" data-toggle="tooltip" title="Print">
<i class="fa fa-print"></i></button>
</div>
<!-- /.mailbox-controls -->
<div class="mailbox-read-message">
<p>Hello John,</p>
<p>Keffiyeh blog actually fashion axe vegan, irony biodiesel. Cold-pressed hoodie chillwave put a bird
on it aesthetic, bitters brunch meggings vegan iPhone. Dreamcatcher vegan scenester mlkshk. Ethical
master cleanse Bushwick, occupy Thundercats banjo cliche ennui farm-to-table mlkshk fanny pack
gluten-free. Marfa butcher vegan quinoa, bicycle rights disrupt tofu scenester chillwave 3 wolf moon
asymmetrical taxidermy pour-over. Quinoa tote bag fashion axe, Godard disrupt migas church-key tofu
blog locavore. Thundercats cronut polaroid Neutra tousled, meh food truck selfies narwhal American
Apparel.</p>
<p>Raw denim McSweeney's bicycle rights, iPhone trust fund quinoa Neutra VHS kale chips vegan PBR&B
literally Thundercats +1. Forage tilde four dollar toast, banjo health goth paleo butcher. Four dollar
toast Brooklyn pour-over American Apparel sustainable, lumbersexual listicle gluten-free health goth
umami hoodie. Synth Echo Park bicycle rights DIY farm-to-table, retro kogi sriracha dreamcatcher PBR&B
flannel hashtag irony Wes Anderson. Lumbersexual Williamsburg Helvetica next level. Cold-pressed
slow-carb pop-up normcore Thundercats Portland, cardigan literally meditation lumbersexual crucifix.
Wayfarers raw denim paleo Bushwick, keytar Helvetica scenester keffiyeh 8-bit irony mumblecore
whatever viral Truffaut.</p>
<p>Post-ironic shabby chic VHS, Marfa keytar flannel lomo try-hard keffiyeh cray. Actually fap fanny
pack yr artisan trust fund. High Life dreamcatcher church-key gentrify. Tumblr stumptown four dollar
toast vinyl, cold-pressed try-hard blog authentic keffiyeh Helvetica lo-fi tilde Intelligentsia. Lomo
locavore salvia bespoke, twee fixie paleo cliche brunch Schlitz blog McSweeney's messenger bag swag
slow-carb. Odd Future photo booth pork belly, you probably haven't heard of them actually tofu ennui
keffiyeh lo-fi Truffaut health goth. Narwhal sustainable retro disrupt.</p>
<p>Skateboard artisan letterpress before they sold out High Life messenger bag. Bitters chambray
leggings listicle, drinking vinegar chillwave synth. Fanny pack hoodie American Apparel twee. American
Apparel PBR listicle, salvia aesthetic occupy sustainable Neutra kogi. Organic synth Tumblr viral
plaid, shabby chic single-origin coffee Etsy 3 wolf moon slow-carb Schlitz roof party tousled squid
vinyl. Readymade next level literally trust fund. Distillery master cleanse migas, Vice sriracha
flannel chambray chia cronut.</p>
<p>Thanks,<br>Jane</p>
</div>
<!-- /.mailbox-read-message -->
</div>
<!-- /.box-body -->
<div class="box-footer">
<ul class="mailbox-attachments clearfix">
<li>
<span class="mailbox-attachment-icon"><i class="fa fa-file-pdf-o"></i></span>
<div class="mailbox-attachment-info">
<a href="#" class="mailbox-attachment-name"><i class="fa fa-paperclip"></i> Sep2014-report.pdf</a>
<span class="mailbox-attachment-size">
1,245 KB
<a href="#" class="btn btn-default btn-xs pull-right"><i class="fa fa-cloud-download"></i></a>
</span>
</div>
</li>
<li>
<span class="mailbox-attachment-icon"><i class="fa fa-file-word-o"></i></span>
<div class="mailbox-attachment-info">
<a href="#" class="mailbox-attachment-name"><i class="fa fa-paperclip"></i> App Description.docx</a>
<span class="mailbox-attachment-size">
1,245 KB
<a href="#" class="btn btn-default btn-xs pull-right"><i class="fa fa-cloud-download"></i></a>
</span>
</div>
</li>
<li>
<span class="mailbox-attachment-icon has-img"><img src="<?= base_url('assets/img/photo1.png') ?>" alt="Attachment"></span>
<div class="mailbox-attachment-info">
<a href="#" class="mailbox-attachment-name"><i class="fa fa-camera"></i> photo1.png</a>
<span class="mailbox-attachment-size">
2.67 MB
<a href="#" class="btn btn-default btn-xs pull-right"><i class="fa fa-cloud-download"></i></a>
</span>
</div>
</li>
<li>
<span class="mailbox-attachment-icon has-img"><img src="<?= base_url('assets/img/photo2.png') ?>" alt="Attachment"></span>
<div class="mailbox-attachment-info">
<a href="#" class="mailbox-attachment-name"><i class="fa fa-camera"></i> photo2.png</a>
<span class="mailbox-attachment-size">
1.9 MB
<a href="#" class="btn btn-default btn-xs pull-right"><i class="fa fa-cloud-download"></i></a>
</span>
</div>
</li>
</ul>
</div>
<!-- /.box-footer -->
<div class="box-footer">
<div class="pull-right">
<button type="button" class="btn btn-default"><i class="fa fa-reply"></i> Reply</button>
<button type="button" class="btn btn-default"><i class="fa fa-share"></i> Forward</button>
</div>
<button type="button" class="btn btn-default"><i class="fa fa-trash-o"></i> Delete</button>
<button type="button" class="btn btn-default"><i class="fa fa-print"></i> Print</button>
</div>
<!-- /.box-footer -->
</div>
<!-- /. box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content --> | DaviMenezes/DviCodeIgniter | application/views/examples/mailbox/read_mail.php | PHP | gpl-3.0 | 12,385 |
package edu.xjtu.wwh.rmi;
import java.io.IOException;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import edu.xjtu.wwh.core.OperHDFS;
import edu.xjtu.wwh.parameter.DefaultParameter;
public class ThirdParty {
public static void main(String[] args) {
// TODO Auto-generated method stub
//First First get unique clientID and attr_str and base path.
String base=getBase();
String clientID=getClientID();
String attr_str=getAttrStr();
//在RMI服务注册表中查找名称为eci的对象,并调用其上的方法
CoreFunc cf=null;
try {
cf=(CoreFunc) Naming.lookup("rmi://localhost:8888/cf");
cf.init(base, clientID);
} catch (MalformedURLException | RemoteException | NotBoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Generate related private keys using attr_str
try {
cf.keyInitial(attr_str);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Call decFun
byte[] cipher=OperHDFS.readFromHDFS("cipher").getBytes();
System.out.println(""+cipher.length);
try {
byte[] rs=cf.decFunc(cipher);
System.out.println("DEC:"+new String(rs));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//upd decFun
byte[] newCipher=OperHDFS.readFromHDFS("newCipher").getBytes();
System.out.println(newCipher.length);
try {
byte[] rs=cf.decFunc(newCipher);
System.out.println("UPD:"+new String(rs));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String getBase() {
// TODO Auto-generated method stub
return DefaultParameter.BASE;
}
public static String getClientID(){
return DefaultParameter.TEST_CLIENT_ID;
}
public static String getAttrStr(){
return DefaultParameter.TEST_ATTR_STR;
}
}
| SteadyStill/rfid | src/edu/xjtu/wwh/rmi/ThirdParty.java | Java | gpl-3.0 | 1,997 |
<?php
/*
* Copyright 2014 Google Inc.
*
* 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.
*/
/**
* Service definition for YouTube (v3).
*
* <p>
* The YouTube Data API v3 is an API that provides access to YouTube data, such
* as videos, playlists, and channels.</p>
*
* <p>
* For more information about this service, see the API
* <a href="https://developers.google.com/youtube/" target="_blank">Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class Google_Service_YouTube extends Google_Service
{
/** Manage your YouTube account. */
const YOUTUBE =
"https://www.googleapis.com/auth/youtube";
/** See a list of your current active channel members, their current level, and when they became a member. */
const YOUTUBE_CHANNEL_MEMBERSHIPS_CREATOR =
"https://www.googleapis.com/auth/youtube.channel-memberships.creator";
/** See, edit, and permanently delete your YouTube videos, ratings, comments and captions. */
const YOUTUBE_FORCE_SSL =
"https://www.googleapis.com/auth/youtube.force-ssl";
/** View your YouTube account. */
const YOUTUBE_READONLY =
"https://www.googleapis.com/auth/youtube.readonly";
/** Manage your YouTube videos. */
const YOUTUBE_UPLOAD =
"https://www.googleapis.com/auth/youtube.upload";
/** View and manage your assets and associated content on YouTube. */
const YOUTUBEPARTNER =
"https://www.googleapis.com/auth/youtubepartner";
/** View private information of your YouTube channel relevant during the audit process with a YouTube partner. */
const YOUTUBEPARTNER_CHANNEL_AUDIT =
"https://www.googleapis.com/auth/youtubepartner-channel-audit";
public $abuseReports;
public $activities;
public $captions;
public $channelBanners;
public $channelSections;
public $channels;
public $commentThreads;
public $comments;
public $i18nLanguages;
public $i18nRegions;
public $liveBroadcasts;
public $liveChatBans;
public $liveChatMessages;
public $liveChatModerators;
public $liveStreams;
public $members;
public $membershipsLevels;
public $playlistItems;
public $playlists;
public $search;
public $sponsors;
public $subscriptions;
public $superChatEvents;
public $tests;
public $thirdPartyLinks;
public $thumbnails;
public $videoAbuseReportReasons;
public $videoCategories;
public $videos;
public $watermarks;
/**
* Constructs the internal representation of the YouTube service.
*
* @param Google_Client $client The client used to deliver requests.
* @param string $rootUrl The root URL used for requests to the service.
*/
public function __construct(Google_Client $client, $rootUrl = null)
{
parent::__construct($client);
$this->rootUrl = $rootUrl ?: 'https://youtube.googleapis.com/';
$this->servicePath = '';
$this->batchPath = 'batch';
$this->version = 'v3';
$this->serviceName = 'youtube';
$this->abuseReports = new Google_Service_YouTube_Resource_AbuseReports(
$this,
$this->serviceName,
'abuseReports',
array(
'methods' => array(
'insert' => array(
'path' => 'youtube/v3/abuseReports',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->activities = new Google_Service_YouTube_Resource_Activities(
$this,
$this->serviceName,
'activities',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/activities',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'home' => array(
'location' => 'query',
'type' => 'boolean',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'publishedBefore' => array(
'location' => 'query',
'type' => 'string',
),
'regionCode' => array(
'location' => 'query',
'type' => 'string',
),
'publishedAfter' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->captions = new Google_Service_YouTube_Resource_Captions(
$this,
$this->serviceName,
'captions',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/captions',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOf' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'download' => array(
'path' => 'youtube/v3/captions/{id}',
'httpMethod' => 'GET',
'parameters' => array(
'id' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'tfmt' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOf' => array(
'location' => 'query',
'type' => 'string',
),
'tlang' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/captions',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOf' => array(
'location' => 'query',
'type' => 'string',
),
'sync' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'list' => array(
'path' => 'youtube/v3/captions',
'httpMethod' => 'GET',
'parameters' => array(
'videoId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'onBehalfOf' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'youtube/v3/captions',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOf' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'sync' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),
)
)
);
$this->channelBanners = new Google_Service_YouTube_Resource_ChannelBanners(
$this,
$this->serviceName,
'channelBanners',
array(
'methods' => array(
'insert' => array(
'path' => 'youtube/v3/channelBanners/insert',
'httpMethod' => 'POST',
'parameters' => array(
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->channelSections = new Google_Service_YouTube_Resource_ChannelSections(
$this,
$this->serviceName,
'channelSections',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/channelSections',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/channelSections',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'youtube/v3/channelSections',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
),
),'update' => array(
'path' => 'youtube/v3/channelSections',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->channels = new Google_Service_YouTube_Resource_Channels(
$this,
$this->serviceName,
'channels',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/channels',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'mySubscribers' => array(
'location' => 'query',
'type' => 'boolean',
),
'forUsername' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'categoryId' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'managedByMe' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'update' => array(
'path' => 'youtube/v3/channels',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->commentThreads = new Google_Service_YouTube_Resource_CommentThreads(
$this,
$this->serviceName,
'commentThreads',
array(
'methods' => array(
'insert' => array(
'path' => 'youtube/v3/commentThreads',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'list' => array(
'path' => 'youtube/v3/commentThreads',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'searchTerms' => array(
'location' => 'query',
'type' => 'string',
),
'videoId' => array(
'location' => 'query',
'type' => 'string',
),
'order' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'moderationStatus' => array(
'location' => 'query',
'type' => 'string',
),
'textFormat' => array(
'location' => 'query',
'type' => 'string',
),
'allThreadsRelatedToChannelId' => array(
'location' => 'query',
'type' => 'string',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
),
),'update' => array(
'path' => 'youtube/v3/commentThreads',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->comments = new Google_Service_YouTube_Resource_Comments(
$this,
$this->serviceName,
'comments',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/comments',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'youtube/v3/comments',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'list' => array(
'path' => 'youtube/v3/comments',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'textFormat' => array(
'location' => 'query',
'type' => 'string',
),
'parentId' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),'markAsSpam' => array(
'path' => 'youtube/v3/comments/markAsSpam',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'setModerationStatus' => array(
'path' => 'youtube/v3/comments/setModerationStatus',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'moderationStatus' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'banAuthor' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'update' => array(
'path' => 'youtube/v3/comments',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->i18nLanguages = new Google_Service_YouTube_Resource_I18nLanguages(
$this,
$this->serviceName,
'i18nLanguages',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/i18nLanguages',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->i18nRegions = new Google_Service_YouTube_Resource_I18nRegions(
$this,
$this->serviceName,
'i18nRegions',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/i18nRegions',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->liveBroadcasts = new Google_Service_YouTube_Resource_LiveBroadcasts(
$this,
$this->serviceName,
'liveBroadcasts',
array(
'methods' => array(
'bind' => array(
'path' => 'youtube/v3/liveBroadcasts/bind',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'streamId' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'control' => array(
'path' => 'youtube/v3/liveBroadcasts/control',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'displaySlate' => array(
'location' => 'query',
'type' => 'boolean',
),
'offsetTimeMs' => array(
'location' => 'query',
'type' => 'string',
),
'walltime' => array(
'location' => 'query',
'type' => 'string',
),
),
),'delete' => array(
'path' => 'youtube/v3/liveBroadcasts',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/liveBroadcasts',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'youtube/v3/liveBroadcasts',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'broadcastStatus' => array(
'location' => 'query',
'type' => 'string',
),
'broadcastType' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
),
),'transition' => array(
'path' => 'youtube/v3/liveBroadcasts/transition',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'broadcastStatus' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'youtube/v3/liveBroadcasts',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->liveChatBans = new Google_Service_YouTube_Resource_LiveChatBans(
$this,
$this->serviceName,
'liveChatBans',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/liveChat/bans',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'youtube/v3/liveChat/bans',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->liveChatMessages = new Google_Service_YouTube_Resource_LiveChatMessages(
$this,
$this->serviceName,
'liveChatMessages',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/liveChat/messages',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'youtube/v3/liveChat/messages',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'list' => array(
'path' => 'youtube/v3/liveChat/messages',
'httpMethod' => 'GET',
'parameters' => array(
'liveChatId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'profileImageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->liveChatModerators = new Google_Service_YouTube_Resource_LiveChatModerators(
$this,
$this->serviceName,
'liveChatModerators',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/liveChat/moderators',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'youtube/v3/liveChat/moderators',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'list' => array(
'path' => 'youtube/v3/liveChat/moderators',
'httpMethod' => 'GET',
'parameters' => array(
'liveChatId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->liveStreams = new Google_Service_YouTube_Resource_LiveStreams(
$this,
$this->serviceName,
'liveStreams',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/liveStreams',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/liveStreams',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'youtube/v3/liveStreams',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'youtube/v3/liveStreams',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->members = new Google_Service_YouTube_Resource_Members(
$this,
$this->serviceName,
'members',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/members',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'mode' => array(
'location' => 'query',
'type' => 'string',
),
'filterByMemberChannelId' => array(
'location' => 'query',
'type' => 'string',
),
'hasAccessToLevel' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->membershipsLevels = new Google_Service_YouTube_Resource_MembershipsLevels(
$this,
$this->serviceName,
'membershipsLevels',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/membershipsLevels',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->playlistItems = new Google_Service_YouTube_Resource_PlaylistItems(
$this,
$this->serviceName,
'playlistItems',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/playlistItems',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/playlistItems',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'youtube/v3/playlistItems',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'videoId' => array(
'location' => 'query',
'type' => 'string',
),
'playlistId' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
),
),'update' => array(
'path' => 'youtube/v3/playlistItems',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->playlists = new Google_Service_YouTube_Resource_Playlists(
$this,
$this->serviceName,
'playlists',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/playlists',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/playlists',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'youtube/v3/playlists',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'youtube/v3/playlists',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->search = new Google_Service_YouTube_Resource_Search(
$this,
$this->serviceName,
'search',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/search',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'location' => array(
'location' => 'query',
'type' => 'string',
),
'regionCode' => array(
'location' => 'query',
'type' => 'string',
),
'publishedAfter' => array(
'location' => 'query',
'type' => 'string',
),
'channelType' => array(
'location' => 'query',
'type' => 'string',
),
'order' => array(
'location' => 'query',
'type' => 'string',
),
'videoDuration' => array(
'location' => 'query',
'type' => 'string',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'locationRadius' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'safeSearch' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'publishedBefore' => array(
'location' => 'query',
'type' => 'string',
),
'relatedToVideoId' => array(
'location' => 'query',
'type' => 'string',
),
'type' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'videoDefinition' => array(
'location' => 'query',
'type' => 'string',
),
'forContentOwner' => array(
'location' => 'query',
'type' => 'boolean',
),
'videoCaption' => array(
'location' => 'query',
'type' => 'string',
),
'relevanceLanguage' => array(
'location' => 'query',
'type' => 'string',
),
'videoSyndicated' => array(
'location' => 'query',
'type' => 'string',
),
'videoLicense' => array(
'location' => 'query',
'type' => 'string',
),
'forDeveloper' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'videoDimension' => array(
'location' => 'query',
'type' => 'string',
),
'eventType' => array(
'location' => 'query',
'type' => 'string',
),
'q' => array(
'location' => 'query',
'type' => 'string',
),
'videoCategoryId' => array(
'location' => 'query',
'type' => 'string',
),
'topicId' => array(
'location' => 'query',
'type' => 'string',
),
'videoEmbeddable' => array(
'location' => 'query',
'type' => 'string',
),
'videoType' => array(
'location' => 'query',
'type' => 'string',
),
'forMine' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),
)
)
);
$this->sponsors = new Google_Service_YouTube_Resource_Sponsors(
$this,
$this->serviceName,
'sponsors',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/sponsors',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'filter' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->subscriptions = new Google_Service_YouTube_Resource_Subscriptions(
$this,
$this->serviceName,
'subscriptions',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/subscriptions',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'youtube/v3/subscriptions',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'list' => array(
'path' => 'youtube/v3/subscriptions',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'order' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'forChannelId' => array(
'location' => 'query',
'type' => 'string',
),
'channelId' => array(
'location' => 'query',
'type' => 'string',
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'mine' => array(
'location' => 'query',
'type' => 'boolean',
),
'mySubscribers' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'myRecentSubscribers' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),
)
)
);
$this->superChatEvents = new Google_Service_YouTube_Resource_SuperChatEvents(
$this,
$this->serviceName,
'superChatEvents',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/superChatEvents',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->tests = new Google_Service_YouTube_Resource_Tests(
$this,
$this->serviceName,
'tests',
array(
'methods' => array(
'insert' => array(
'path' => 'youtube/v3/tests',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->thirdPartyLinks = new Google_Service_YouTube_Resource_ThirdPartyLinks(
$this,
$this->serviceName,
'thirdPartyLinks',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/thirdPartyLinks',
'httpMethod' => 'DELETE',
'parameters' => array(
'linkingToken' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'type' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
),
),'insert' => array(
'path' => 'youtube/v3/thirdPartyLinks',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),'list' => array(
'path' => 'youtube/v3/thirdPartyLinks',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'linkingToken' => array(
'location' => 'query',
'type' => 'string',
),
'type' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'youtube/v3/thirdPartyLinks',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
),
),
)
)
);
$this->thumbnails = new Google_Service_YouTube_Resource_Thumbnails(
$this,
$this->serviceName,
'thumbnails',
array(
'methods' => array(
'set' => array(
'path' => 'youtube/v3/thumbnails/set',
'httpMethod' => 'POST',
'parameters' => array(
'videoId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->videoAbuseReportReasons = new Google_Service_YouTube_Resource_VideoAbuseReportReasons(
$this,
$this->serviceName,
'videoAbuseReportReasons',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/videoAbuseReportReasons',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->videoCategories = new Google_Service_YouTube_Resource_VideoCategories(
$this,
$this->serviceName,
'videoCategories',
array(
'methods' => array(
'list' => array(
'path' => 'youtube/v3/videoCategories',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'regionCode' => array(
'location' => 'query',
'type' => 'string',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->videos = new Google_Service_YouTube_Resource_Videos(
$this,
$this->serviceName,
'videos',
array(
'methods' => array(
'delete' => array(
'path' => 'youtube/v3/videos',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'getRating' => array(
'path' => 'youtube/v3/videos/getRating',
'httpMethod' => 'GET',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'insert' => array(
'path' => 'youtube/v3/videos',
'httpMethod' => 'POST',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'stabilize' => array(
'location' => 'query',
'type' => 'boolean',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwnerChannel' => array(
'location' => 'query',
'type' => 'string',
),
'autoLevels' => array(
'location' => 'query',
'type' => 'boolean',
),
'notifySubscribers' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'list' => array(
'path' => 'youtube/v3/videos',
'httpMethod' => 'GET',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'id' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'locale' => array(
'location' => 'query',
'type' => 'string',
),
'maxHeight' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'videoCategoryId' => array(
'location' => 'query',
'type' => 'string',
),
'hl' => array(
'location' => 'query',
'type' => 'string',
),
'myRating' => array(
'location' => 'query',
'type' => 'string',
),
'chart' => array(
'location' => 'query',
'type' => 'string',
),
'maxWidth' => array(
'location' => 'query',
'type' => 'integer',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'regionCode' => array(
'location' => 'query',
'type' => 'string',
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'rate' => array(
'path' => 'youtube/v3/videos/rate',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'rating' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'reportAbuse' => array(
'path' => 'youtube/v3/videos/reportAbuse',
'httpMethod' => 'POST',
'parameters' => array(
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'youtube/v3/videos',
'httpMethod' => 'PUT',
'parameters' => array(
'part' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->watermarks = new Google_Service_YouTube_Resource_Watermarks(
$this,
$this->serviceName,
'watermarks',
array(
'methods' => array(
'set' => array(
'path' => 'youtube/v3/watermarks/set',
'httpMethod' => 'POST',
'parameters' => array(
'channelId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),'unset' => array(
'path' => 'youtube/v3/watermarks/unset',
'httpMethod' => 'POST',
'parameters' => array(
'channelId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'onBehalfOfContentOwner' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
}
}
| ftisunpar/BlueTape | vendor/google/apiclient-services/src/Google/Service/YouTube.php | PHP | gpl-3.0 | 70,431 |
define(['backbone'], function(Backbone){
var Role = Backbone.Model.extend({
idAttribute: 'UID',
url: '/api/role'
});
var role = new Role();
role.fetch();
return role;
});
| gsmlg/oneblog | app/assets/javascript/app/role.js | JavaScript | gpl-3.0 | 207 |
# GNU Solfege - free ear training software
# Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2011,
# 2013 Tom Cato Amundsen
# Copyright (C) 2013 Jan Baumgart (Folkwang Universitaet der Kuenste)
#
# 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/>.
from __future__ import absolute_import
from __future__ import division
from gi.repository import GObject
from gi.repository import Gtk
from gi.repository import Gdk
from solfege import abstract
from solfege import abstract_solmisation_addon
from solfege import gu
from solfege import lessonfile
from solfege import mpd
from solfege.const import solmisation_syllables, solmisation_notenames
class Teacher(abstract.Teacher, abstract_solmisation_addon.SolmisationAddOnClass):
OK = 0
ERR_PICKY = 1
ERR_NO_ELEMS = 2
def __init__(self, exname):
abstract.Teacher.__init__(self, exname)
self.lessonfileclass = lessonfile.HeaderLessonfile
def play_question(self):
if self.q_status == self.QSTATUS_NO:
return
self.play(self.get_music_string())
def guess_answer(self, a):
assert self.q_status in [self.QSTATUS_NEW, self.QSTATUS_WRONG]
v = []
for idx in range(len(self.m_question)):
v.append(self.m_question[idx] == a[idx])
if not [x for x in v if x == 0]:
self.q_status = self.QSTATUS_SOLVED
self.maybe_auto_new_question()
return 1
else:
self.q_status = self.QSTATUS_WRONG
class RhythmViewer(Gtk.Frame):
def __init__(self, parent):
Gtk.Frame.__init__(self)
self.set_shadow_type(Gtk.ShadowType.IN)
self.g_parent = parent
self.g_box = Gtk.HBox()
self.g_box.show()
self.g_box.set_spacing(gu.PAD_SMALL)
self.g_box.set_border_width(gu.PAD)
self.add(self.g_box)
self.m_data = []
# the number of rhythm elements the viewer is supposed to show
self.m_num_notes = 0
self.g_face = None
self.__timeout = None
def set_num_notes(self, i):
self.m_num_notes = i
def clear(self):
for child in self.g_box.get_children():
child.destroy()
self.m_data = []
def create_holders(self):
"""
create those |__| that represents one beat
"""
if self.__timeout:
GObject.source_remove(self.__timeout)
self.clear()
for x in range(self.m_num_notes):
self.g_box.pack_start(gu.create_png_image('holder'), False, False, 0)
self.m_data = []
def clear_wrong_part(self):
"""When the user have answered the question, this method is used
to clear all but the first correct elements."""
# this assert is always true because if there is no rhythm element,
# then there is a rhythm holder ( |__| )
assert self.m_num_notes == len(self.g_parent.m_t.m_question)
self.g_face.destroy()
self.g_face = None
for n in range(self.m_num_notes):
if self.m_data[n] != self.g_parent.m_t.m_question[n]:
break
for x in range(n, len(self.g_box.get_children())):
self.g_box.get_children()[n].destroy()
self.m_data = self.m_data[:n]
for x in range(n, self.m_num_notes):
self.g_box.pack_start(gu.create_png_image('holder'), False, False, 0)
def add_rhythm_element(self, i):
assert len(self.m_data) <= self.m_num_notes
if len(self.g_box.get_children()) >= self.m_num_notes:
self.g_box.get_children()[self.m_num_notes-1].destroy()
vbox = Gtk.VBox()
vbox.show()
# im = gu.create_rhythm_image(const.RHYTHMS[i])
im = self.g_parent.solbutton(i, False)
vbox.pack_start(im, True, True, 0)
vbox.pack_start(gu.create_png_image('rhythm-wrong'), False, False, 0)
vbox.get_children()[-1].hide()
self.g_box.pack_start(vbox, False, False, 0)
self.g_box.reorder_child(vbox, len(self.m_data))
self.m_data.append(i)
def backspace(self):
if len(self.m_data) > 0:
if self.g_face:
self.g_box.get_children()[-2].destroy()
self.g_face.destroy()
self.g_face = None
self.g_box.get_children()[len(self.m_data)-1].destroy()
self.g_box.pack_start(gu.create_png_image('holder'), False, False, 0)
del self.m_data[-1]
def mark_wrong(self, idx):
"""
Mark the rhythm elements that was wrong by putting the content of
graphics/rhythm-wrong.png (normally a red line) under the element.
"""
self.g_box.get_children()[idx].get_children()[1].show()
def len(self):
"return the number of rhythm elements currently viewed"
return len(self.m_data)
def sad_face(self):
l = gu.HarmonicProgressionLabel(_("Wrong"))
l.show()
self.g_box.pack_start(l, False, False, 0)
self.g_face = Gtk.EventBox()
self.g_face.connect('button_press_event', self.on_sadface_event)
self.g_face.show()
im = Gtk.Image()
im.set_from_stock('solfege-sadface', Gtk.IconSize.LARGE_TOOLBAR)
im.show()
self.g_face.add(im)
self.g_box.pack_start(self.g_face, False, False, 0)
def happy_face(self):
l = gu.HarmonicProgressionLabel(_("Correct"))
l.show()
self.g_box.pack_start(l, False, False, 0)
self.g_face = Gtk.EventBox()
self.g_face.connect('button_press_event', self.on_happyface_event)
self.g_face.show()
im = Gtk.Image()
im.set_from_stock('solfege-happyface', Gtk.IconSize.LARGE_TOOLBAR)
im.show()
self.g_face.add(im)
self.g_box.pack_start(self.g_face, False, False, 0)
def on_happyface_event(self, obj, event):
if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 1:
self.g_parent.new_question()
def on_sadface_event(self, obj, event):
if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 1:
self.clear_wrong_part()
def flash(self, s):
self.clear()
l = Gtk.Label(label=s)
l.set_name("Feedback")
l.set_alignment(0.0, 0.5)
l.show()
self.g_box.pack_start(l, True, True, 0)
self.g_box.set_size_request(
max(l.size_request().width + gu.PAD * 2, self.g_box.size_request().width),
max(l.size_request().height + gu.PAD * 2, self.g_box.size_request().height))
self.__timeout = GObject.timeout_add(2000, self.unflash)
def unflash(self, *v):
self.__timeout = None
self.clear()
class Gui(abstract.Gui, abstract_solmisation_addon.SolmisationAddOnGuiClass):
lesson_heading = _("Solmisation Diktat")
def __init__(self, teacher):
abstract.Gui.__init__(self, teacher)
self.m_key_bindings = {'backspace_ak': self.on_backspace}
self.g_answer_box = Gtk.VBox()
self.answer_buttons = []
self.m_answer_buttons = {}
#-------
hbox = gu.bHBox(self.practise_box)
b = Gtk.Button(_("Play"))
b.show()
b.connect('clicked', self.play_users_answer)
hbox.pack_start(b, False, True, 0)
self.practise_box.pack_start(Gtk.HBox(), False, False,
padding=gu.PAD_SMALL)
self.g_rhythm_viewer = RhythmViewer(self)
self.g_rhythm_viewer.create_holders()
hbox.pack_start(self.g_rhythm_viewer, True, True, 0)
self.practise_box.pack_start(self.g_answer_box, False, False, 0)
# action area
self.std_buttons_add(
('new', self.new_question),
('repeat', self.repeat_question),
#('play_answer', self.play_users_answer),
('give_up', self.give_up),
('backspace', self.on_backspace))
self.practise_box.show_all()
##############
# config_box #
##############
self.add_select_elements_gui()
#--------
self.config_box.pack_start(Gtk.HBox(), False, False,
padding=gu.PAD_SMALL)
self.add_select_num_notes_gui()
#-----
self.config_box.pack_start(Gtk.HBox(), False, False,
padding=gu.PAD_SMALL)
#------
hbox = gu.bHBox(self.config_box, False)
hbox.set_spacing(gu.PAD_SMALL)
hbox.pack_start(Gtk.Label(_("Beats per minute:")), False, False, 0)
spin = gu.nSpinButton(self.m_exname, 'bpm',
Gtk.Adjustment(60, 20, 240, 1, 10))
hbox.pack_start(spin, False, False, 0)
hbox = gu.bHBox(self.config_box, False)
hbox.set_spacing(gu.PAD_SMALL)
hbox.pack_start(gu.nCheckButton(self.m_exname,
"show_first_note",
_("Show the first tone")), False, False, 0)
hbox.pack_start(gu.nCheckButton(self.m_exname,
"play_cadence",
_("Play cadence")), False, False, 0)
self._add_auto_new_question_gui(self.config_box)
self.config_box.show_all()
def solbutton(self, i, connect):
if i > len(solmisation_syllables) or i < 0:
btn = Gtk.Button()
else:
btn = Gtk.Button(solmisation_syllables[i])
btn.show()
if connect:
btn.connect('clicked', self.guess_element, i)
return btn
def select_element_cb(self, button, element_num):
super(Gui, self).select_element_cb(button, element_num)
self.m_answer_buttons[element_num].set_sensitive(button.get_active())
#self.update_answer_buttons()
def on_backspace(self, widget=None):
if self.m_t.q_status == self.QSTATUS_SOLVED:
return
self.g_rhythm_viewer.backspace()
if not self.g_rhythm_viewer.m_data:
self.g_backspace.set_sensitive(False)
def play_users_answer(self, widget):
if self.g_rhythm_viewer.m_data:
melody = ""
p = mpd.MusicalPitch()
for k in self.g_rhythm_viewer.m_data:
melody += " " + mpd.transpose_notename(solmisation_notenames[k], self.m_t.m_transp) + "4"
self.m_t.play(r"\staff{ \time 1000000/4 %s }" % melody)
def guess_element(self, sender, i):
if self.m_t.q_status == self.QSTATUS_NO:
self.g_rhythm_viewer.flash(_("Click 'New' to begin."))
return
if self.m_t.q_status == self.QSTATUS_SOLVED:
return
if self.g_rhythm_viewer.len() == len(self.m_t.m_question):
self.g_rhythm_viewer.clear_wrong_part()
self.g_backspace.set_sensitive(True)
self.g_rhythm_viewer.add_rhythm_element(i)
if self.g_rhythm_viewer.len() == len(self.m_t.m_question):
if self.m_t.guess_answer(self.g_rhythm_viewer.m_data):
self.g_rhythm_viewer.happy_face()
self.std_buttons_answer_correct()
else:
v = []
for idx in range(len(self.m_t.m_question)):
v.append(self.m_t.m_question[idx] == self.g_rhythm_viewer.m_data[idx])
for x in range(len(v)):
if not v[x]:
self.g_rhythm_viewer.mark_wrong(x)
self.g_rhythm_viewer.sad_face()
self.std_buttons_answer_wrong()
def new_question(self, widget=None):
g = self.m_t.new_question()
if g == self.m_t.OK:
self.g_first_rhythm_button.grab_focus()
self.g_rhythm_viewer.set_num_notes(self.get_int('num_notes'))
self.g_rhythm_viewer.create_holders()
self.std_buttons_new_question()
if self.m_t.get_bool('show_first_note'):
self.g_rhythm_viewer.add_rhythm_element(self.m_t.m_question[0])
try:
self.m_t.play_question()
except Exception, e:
if not self.standard_exception_handler(e, self.on_end_practise):
raise
return
elif g == self.m_t.ERR_PICKY:
self.g_rhythm_viewer.flash(_("You have to solve this question first."))
else:
assert g == self.m_t.ERR_NO_ELEMS
self.g_repeat.set_sensitive(False)
self.g_rhythm_viewer.flash(_("You have to configure this exercise properly"))
def repeat_question(self, *w):
self.m_t.play_question()
self.g_first_rhythm_button.grab_focus()
def update_answer_buttons(self):
"""
(Re)create the buttons needed to answer the questions.
We recreate the buttons for each lesson file because the
header may specify a different set of rhythm elements to use.
"""
for but in self.answer_buttons:
but.destroy()
self.answer_buttons = []
self.g_first_rhythm_button = None
gs = Gtk.SizeGroup(Gtk.SizeGroupMode.HORIZONTAL)
for i, v in enumerate((
[1, 4, -1, 8, 11, -1, 15, 18, 21, -1, 25, 28, -1, 32],
[0, 3, 6, 7, 10, 13, 14, 17, 20, 23, 24, 27, 30, 31, 34],
[2, 5, -1, 9, 12, -1, 16, 19, 22, -1, 26, 29, -1, 33])):
hbox = Gtk.HBox(True, 0)
for k in v:
b = self.solbutton(k, True)
gs.add_widget(b)
b.set_sensitive(False)
for n in self.m_t.m_P.header.solmisation_elements:
if k == n:
b.set_sensitive(True)
if not self.g_first_rhythm_button:
self.g_first_rhythm_button = b
hbox.pack_start(b, True, True, 0)
self.answer_buttons.append(b)
if k != -1:
self.m_answer_buttons[k] = b
spacing = Gtk.Alignment()
if i in (0, 2):
spacing.set_property('left-padding', 16)
spacing.set_property('right-padding', 16)
spacing.add(hbox)
self.g_answer_box.pack_start(spacing, True, True, 0)
spacing.show_all()
def on_start_practise(self):
# FIXME for now, we run in custom_mode all the time, so we don't
# have to add lots of lesson files. We can change this later.
#self.m_t.m_custom_mode = self.get_bool('gui/expert_mode')
self.m_t.m_custom_mode = True
super(Gui, self).on_start_practise()
if not self.m_t.m_P.header.solmisation_elements:
self.m_t.m_P.header.solmisation_elements = self.m_t.elements[:]
self.update_answer_buttons()
self.std_buttons_start_practise()
if self.m_t.m_custom_mode:
self.update_select_elements_buttons()
self.g_element_frame.show()
else:
self.g_element_frame.hide()
self.m_t.set_default_header_values()
if 'show_first_note' in self.m_t.m_P.header:
self.m_t.set_bool('show_first_note', self.m_t.m_P.header.show_first_note)
if 'play_cadence' in self.m_t.m_P.header:
self.m_t.set_bool('play_cadence', self.m_t.m_P.header.play_cadence)
self.g_rhythm_viewer.flash(_("Click 'New' to begin."))
def on_end_practise(self):
self.m_t.end_practise()
self.std_buttons_end_practise()
self.g_rhythm_viewer.create_holders()
def give_up(self, widget=None):
if self.m_t.q_status == self.QSTATUS_NO:
return
self.g_rhythm_viewer.clear()
for i in self.m_t.m_question:
self.g_rhythm_viewer.add_rhythm_element(i)
self.m_t.q_status = self.QSTATUS_SOLVED
self.std_buttons_give_up()
| RannyeriDev/Solfege | solfege/exercises/solmisation.py | Python | gpl-3.0 | 16,440 |
package org.cgiar.ccafs.marlo.data.model;
// Generated May 17, 2017 3:36:29 PM by Hibernate Tools 4.3.1.Final
/**
* CustomParameter generated by hbm2java
*/
public class CustomParameter extends MarloAuditableEntity implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 9127311887995427567L;
private GlobalUnit crp;
private Parameter parameter;
private String value;
public CustomParameter() {
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
CustomParameter other = (CustomParameter) obj;
if (this.getId() == null) {
if (other.getId() != null) {
return false;
}
} else if (!this.getId().equals(other.getId())) {
return false;
}
return true;
}
public GlobalUnit getCrp() {
return crp;
}
public Parameter getParameter() {
return parameter;
}
public Long getParameterId() {
return this.getParameter().getId();
}
public String getValue() {
return value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.getId() == null) ? 0 : this.getId().hashCode());
return result;
}
public void setCrp(GlobalUnit crp) {
this.crp = crp;
}
public void setParameter(Parameter parameter) {
this.parameter = parameter;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return "CustomParameter [id=" + this.getId() + ", crp=" + crp + ", parameter=" + parameter + ", value=" + value
+ "]";
}
}
| CCAFS/MARLO | marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/model/CustomParameter.java | Java | gpl-3.0 | 1,703 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-02-15 11:53
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sigad', '0033_auto_20180207_1028'),
]
operations = [
migrations.AddField(
model_name='documento',
name='capa',
field=models.BooleanField(choices=[(True, 'Sim'), (False, 'Não')], default=False, help_text='Só um objeto pode ser capa de sua classe. Caso haja outro já selecionado, ele será desconsiderado.', verbose_name='Capa de sua Classe'),
),
migrations.AlterField(
model_name='classe',
name='template_classe',
field=models.IntegerField(choices=[(1, 'Listagem em Linha'), (2, 'Galeria Albuns'), (3, 'Página dos Parlamentares'), (4, 'Página individual de Parlamentar'), (5, 'Banco de Imagens'), (6, 'Galeria de Áudios'), (7, 'Galeria de Vídeos'), (99, 'Documento Específico')], default=1, verbose_name='Template para a Classe'),
),
]
| cmjatai/cmj | cmj/sigad/migrations/0034_auto_20180215_0953.py | Python | gpl-3.0 | 1,088 |
#region Copyright & License Information
/*
* Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System.Collections.Generic;
using System.Linq;
using OpenRA.Graphics;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Traits
{
public class GameSaveViewportManagerInfo : ITraitInfo
{
public object Create(ActorInitializer init) { return new GameSaveViewportManager(); }
}
public class GameSaveViewportManager : IWorldLoaded, IGameSaveTraitData
{
WorldRenderer worldRenderer;
void IWorldLoaded.WorldLoaded(World w, WorldRenderer wr) { worldRenderer = wr; }
List<MiniYamlNode> IGameSaveTraitData.IssueTraitData(Actor self)
{
// HACK: Store the viewport state for the skirmish observer on the first bot's trait
// TODO: This won't make sense for MP saves
var localPlayer = worldRenderer.World.LocalPlayer;
if ((localPlayer != null && localPlayer.PlayerActor != self) ||
(localPlayer == null && self.Owner != self.World.Players.FirstOrDefault(p => p.IsBot)))
return null;
var nodes = new List<MiniYamlNode>()
{
new MiniYamlNode("Viewport", FieldSaver.FormatValue(worldRenderer.Viewport.CenterPosition))
};
var renderPlayer = worldRenderer.World.RenderPlayer;
if (localPlayer == null && renderPlayer != null)
nodes.Add(new MiniYamlNode("RenderPlayer", FieldSaver.FormatValue(renderPlayer.PlayerActor.ActorID)));
return nodes;
}
void IGameSaveTraitData.ResolveTraitData(Actor self, List<MiniYamlNode> data)
{
var viewportNode = data.FirstOrDefault(n => n.Key == "Viewport");
if (viewportNode != null)
worldRenderer.Viewport.Center(FieldLoader.GetValue<WPos>("Viewport", viewportNode.Value.Value));
var renderPlayerNode = data.FirstOrDefault(n => n.Key == "RenderPlayer");
if (renderPlayerNode != null)
{
var renderPlayerActorID = FieldLoader.GetValue<uint>("RenderPlayer", renderPlayerNode.Value.Value);
worldRenderer.World.RenderPlayer = worldRenderer.World.GetActorById(renderPlayerActorID).Owner;
}
}
}
}
| tysonliddell/OpenRA | OpenRA.Mods.Common/Traits/World/GameSaveViewportManager.cs | C# | gpl-3.0 | 2,338 |
/*
* Copyright (C) 2016 Salvatore D'Angelo
* This file is part of Mr Snake project.
* This file derive from the Mr Nom project developed by Mario Zechner for the Beginning Android
* Games book (chapter 6).
*
* Mr Snake 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.
*
* Mr Snake 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.
*/
package org.androidforfun.mrsnake.model;
import java.util.ArrayList;
import java.util.List;
/*
* This class represents the snake. A snake is composed by several pieces described by the class
* SnakeBody. In particular the first piece is the head represented by SnakeHead class and the last
* piece is the tail represented by SnakeTail class.
*
* @author Salvatore D'Angelo
*/
public class Snake {
// the list of pieces of the snake
private List<SnakeBody> parts = new ArrayList<>();
// the direction of the snake. Possible values are: UP, DOWN, LEFT and RIGHT.
private Direction direction;
// when the head of the snake turn this variable contains the direction of the neck. Its value
// depends on if the snake turned clockwise or anticlockwise. In the former case the possible
// values are: UP_RIGHT, RIGHT_DOWN, DOWN_LEFT, LEFT_UP. In the latter case the possible values
// are: UP_LEFT, LEFT_DOWN, DOWN_RIGHT, RIGHT_UP.
private Direction neckDirection;
public Snake() {
reset();
}
/*
* The snake is turned clockwise. The new direction and neck direction depends on the old
* direction.
* UP -> LEFT - UP_LEFT
* LEFT -> DOWN - LEFT_DOWN
* DOWN -> RIGHT - DOWN_RIGHT
* RIGHT -> UP - RIGHT_UP
*/
public void turnAntiClockwise() {
switch (direction) {
case UP:
neckDirection=Direction.UP_LEFT;
direction=Direction.LEFT;
break;
case LEFT:
neckDirection=Direction.LEFT_DOWN;
direction=Direction.DOWN;
break;
case DOWN:
neckDirection=Direction.DOWN_RIGHT;
direction=Direction.RIGHT;
break;
case RIGHT:
neckDirection=Direction.RIGHT_UP;
direction=Direction.UP;
break;
}
}
/*
* The snake is turned anticlockwise. The new direction and neck direction depends on the old
* direction.
* UP -> RIGHT - UP_RIGHT
* RIGHT -> DOWN - RIGHT_DOWN
* DOWN -> LEFT - DOWN_LEFT
* LEFT -> UP - LEFT_UP
*/
public void turnClockwise() {
switch (direction) {
case UP:
neckDirection=Direction.UP_RIGHT;
direction=Direction.RIGHT;
break;
case RIGHT:
neckDirection=Direction.RIGHT_DOWN;
direction=Direction.DOWN;
break;
case DOWN:
neckDirection=Direction.DOWN_LEFT;
direction=Direction.LEFT;
break;
case LEFT:
neckDirection=Direction.LEFT_UP;
direction=Direction.UP;
break;
}
}
/*
* When the snake eat a fruti its size must be increased by 1 piece. This piece is added in the
* middle so the tail should shift by a position. The direction of this shift depends on the
* current direction of the tail
*/
public void eat() {
// add a new piece to the snake
SnakeTail tail = (SnakeTail) parts.get(parts.size()-1);
parts.add(parts.size()-1, new SnakeBody(tail.getX(), tail.getY(), tail.direction));
// shift the tail by 1 position with a direction that depends on its current position.
switch (tail.direction) {
case UP:
tail.moveDown();
break;
case DOWN:
tail.moveUp();
break;
case LEFT:
tail.moveRight();
break;
case RIGHT:
tail.moveLeft();
break;
}
}
/*
* Advance the snake on the grid by a position that depends on the current snake direction.
*/
public void advance() {
int last = parts.size() - 1;
SnakeHead head = (SnakeHead) parts.get(0);
SnakeBody neck = parts.get(1);
SnakeTail tail = (SnakeTail) parts.get(last);
// move all the snake pieces but head, one step forward
for(int i = last; i > 0; i--) {
SnakeBody before = parts.get(i-1);
SnakeBody part = parts.get(i);
part.setX(before.getX());
part.setY(before.getY());
part.direction=before.direction;
}
// move the head towards the snake direction.
head.direction=direction;
switch (direction) {
case UP:
head.moveUp();
break;
case LEFT:
head.moveLeft();
break;
case DOWN:
head.moveDown();
break;
case RIGHT:
head.moveRight();
break;
}
// determine the neck direction
switch (neckDirection) {
case UP_RIGHT:
case LEFT_UP:
case DOWN_LEFT:
case RIGHT_DOWN:
case LEFT_DOWN:
case UP_LEFT:
case DOWN_RIGHT:
case RIGHT_UP:
neck.direction=neckDirection;
neckDirection=Direction.UP;
break;
}
// determine the tail direction
switch (tail.direction) {
case DOWN_LEFT:
case UP_LEFT:
tail.direction=Direction.LEFT;
break;
case LEFT_UP:
case RIGHT_UP:
tail.direction=Direction.UP;
break;
case RIGHT_DOWN:
case LEFT_DOWN:
tail.direction=Direction.DOWN;
break;
case UP_RIGHT:
case DOWN_RIGHT:
tail.direction=Direction.RIGHT;
break;
}
}
/*
* Initializes the snake with a head, a tail and 2 pieces in the middle.
* Direction is UP.
*/
public void reset() {
direction = Direction.UP;
neckDirection = Direction.UP;
parts.clear();
parts.add(new SnakeHead(5, 6, Direction.UP));
parts.add(new SnakeBody(5, 7, Direction.UP));
parts.add(new SnakeBody(5, 8, Direction.UP));
parts.add(new SnakeTail(5, 9, Direction.UP));
}
/*
* Check if snake eat itself.
*/
public boolean checkBitten() {
int len = parts.size();
SnakeBody head = parts.get(0);
for(int i = 1; i < len; i++) {
SnakeBody part = parts.get(i);
if (head.collide(part))
return true;
}
return false;
}
public SnakeHead getSnakeHead() {
return (SnakeHead) parts.get(0);
}
public SnakeBody getSnakeBody(int i) {
return parts.get(i);
}
public int getLength() {
return parts.size();
}
}
| sasadangelo/MrSnake | app/src/main/java/org/androidforfun/mrsnake/model/Snake.java | Java | gpl-3.0 | 7,705 |
"use strict";
var TransitionHookPhase;
(function (TransitionHookPhase) {
TransitionHookPhase[TransitionHookPhase["CREATE"] = 0] = "CREATE";
TransitionHookPhase[TransitionHookPhase["BEFORE"] = 1] = "BEFORE";
TransitionHookPhase[TransitionHookPhase["RUN"] = 2] = "RUN";
TransitionHookPhase[TransitionHookPhase["SUCCESS"] = 3] = "SUCCESS";
TransitionHookPhase[TransitionHookPhase["ERROR"] = 4] = "ERROR";
})(TransitionHookPhase = exports.TransitionHookPhase || (exports.TransitionHookPhase = {}));
var TransitionHookScope;
(function (TransitionHookScope) {
TransitionHookScope[TransitionHookScope["TRANSITION"] = 0] = "TRANSITION";
TransitionHookScope[TransitionHookScope["STATE"] = 1] = "STATE";
})(TransitionHookScope = exports.TransitionHookScope || (exports.TransitionHookScope = {}));
//# sourceMappingURL=interface.js.map | DigitalCookiesGroup/SWEDesigner | Front-End/node_modules/@uirouter/core/lib/transition/interface.js | JavaScript | gpl-3.0 | 852 |
<?php
namespace Squareup;
class Exception extends \Exception {
const ERR_CODE_ACCESS_TOKEN_REVOKED = 'ACCESS_TOKEN_REVOKED';
const ERR_CODE_ACCESS_TOKEN_EXPIRED = 'ACCESS_TOKEN_EXPIRED';
private $config;
private $log;
private $language;
private $errors;
private $isCurlError;
private $overrideFields = array(
'billing_address.country',
'shipping_address.country',
'email_address',
'phone_number'
);
public function __construct($registry, $errors, $is_curl_error = false) {
$this->errors = $errors;
$this->isCurlError = $is_curl_error;
$this->config = $registry->get('config');
$this->log = $registry->get('log');
$this->language = $registry->get('language');
$message = $this->concatErrors();
if ($this->config->get('config_error_log')) {
$this->log->write($message);
}
parent::__construct($message);
}
public function isCurlError() {
return $this->isCurlError;
}
public function isAccessTokenRevoked() {
return $this->errorCodeExists(self::ERR_CODE_ACCESS_TOKEN_REVOKED);
}
public function isAccessTokenExpired() {
return $this->errorCodeExists(self::ERR_CODE_ACCESS_TOKEN_EXPIRED);
}
protected function errorCodeExists($code) {
if (is_array($this->errors)) {
foreach ($this->errors as $error) {
if ($error['code'] == $code) {
return true;
}
}
}
return false;
}
protected function overrideError($field) {
return $this->language->get('squareup_override_error_' . $field);
}
protected function parseError($error) {
if (!empty($error['field']) && in_array($error['field'], $this->overrideFields)) {
return $this->overrideError($error['field']);
}
$message = $error['detail'];
if (!empty($error['field'])) {
$message .= sprintf($this->language->get('squareup_error_field'), $error['field']);
}
return $message;
}
protected function concatErrors() {
$messages = [];
if (is_array($this->errors)) {
foreach ($this->errors as $error) {
$messages[] = $this->parseError($error);
}
} else {
$messages[] = $this->errors;
}
return implode(' ', $messages);
}
} | lucasjkr/opencommerce | system/library/squareup/exception.php | PHP | gpl-3.0 | 2,480 |
/**
* Copyright Université Lyon 1 / Université Lyon 2 (2009,2010)
*
* <ithaca@liris.cnrs.fr>
*
* This file is part of Visu.
*
* This software is a computer program whose purpose is to provide an
* enriched videoconference application.
*
* Visu is a free software subjected to a double license.
* You can redistribute it and/or modify since you respect the terms of either
* (at least one of the both license) :
* - the GNU Lesser General Public License as published by the Free Software Foundation;
* either version 3 of the License, or any later version.
* - the CeCILL-C as published by CeCILL; either version 2 of the License, or any later version.
*
* -- GNU LGPL license
*
* Visu is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Visu is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Visu. If not, see <http://www.gnu.org/licenses/>.
*
* -- CeCILL-C license
*
* This software is governed by the CeCILL-C license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL-C
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-C license and that you accept its terms.
*
* -- End of licenses
*/
package com.lyon2.utils;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
public class UserAccountHelpers
{
public static String key (int nb)
{
Random rand = new Random();
String password = new String();
String dico = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
int size = dico.length();
for(int i = 0; i < nb ; ++i)
{
password += dico.charAt( rand.nextInt(size) );
}
return password;
}
public static String md5(String str)
{
String hash = new String();
try
{
String s="test";
MessageDigest m=MessageDigest.getInstance("MD5");
m.update(s.getBytes(),0,s.length());
hash = new BigInteger( 1,m.digest()).toString(16);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
return hash;
}
}
| ithaca/visu | VisuServeur/visu/src/com/lyon2/utils/UserAccountHelpers.java | Java | gpl-3.0 | 3,804 |
/*
* Copyright (c) 2019. Bernard Bou <1313ou@gmail.com>
*/
package treebolic.glue.component;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.TypedValue;
import android.view.Display;
import android.view.WindowManager;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.graphics.drawable.DrawableCompat;
/**
* Utilities
*
* @author Bernard Bou
*/
@SuppressWarnings("WeakerAccess")
public class Utils
{
@NonNull
static public int[] fetchColors(@NonNull final Context context, @NonNull int... attrs)
{
final TypedValue typedValue = new TypedValue();
final TypedArray array = context.obtainStyledAttributes(typedValue.data, attrs);
final int[] colors = new int[attrs.length];
for (int i = 0; i < attrs.length; i++)
{
colors[i] = array.getColor(i, 0);
}
array.recycle();
return colors;
}
/*
* Get color from theme
*
* @param context context
* @param styleId style id (ex: R.style.MyTheme)
* @param colorAttrIds attr ids (ex: R.attr.editTextColor)
* @return colors
*/
/*
@SuppressWarnings("WeakerAccess")
@NonNull
static public int[] fetchColorsFromStyle(@NonNull final Context context, @NonNull int styleId, @NonNull int... colorAttrIds)
{
final TypedArray array = context.obtainStyledAttributes(styleId, colorAttrIds);
final int[] colors = new int[colorAttrIds.length];
for (int i = 0; i < colorAttrIds.length; i++)
{
colors[i] = array.getColor(i, 0);
}
array.recycle();
return colors;
}
*/
@NonNull
static public Integer[] fetchColorsNullable(@NonNull final Context context, @NonNull @SuppressWarnings("SameParameterValue") int... attrs)
{
final TypedValue typedValue = new TypedValue();
final TypedArray array = context.obtainStyledAttributes(typedValue.data, attrs);
final Integer[] colors = new Integer[attrs.length];
for (int i = 0; i < attrs.length; i++)
{
colors[i] = array.hasValue(i) ? array.getColor(i, 0) : null;
}
array.recycle();
return colors;
}
/*
static public int fetchColor(final Context context, int attr)
{
final TypedValue typedValue = new TypedValue();
final Resources.Theme theme = context.getTheme();
theme.resolveAttribute(attr, typedValue, true);
return typedValue.data;
}
*/
/*
static public Integer fetchColorNullable(final Context context, int attr)
{
final TypedValue typedValue = new TypedValue();
final Resources.Theme theme = context.getTheme();
theme.resolveAttribute(attr, typedValue, true);
return typedValue.type == TypedValue.TYPE_NULL ? null : typedValue.data;
}
*/
static public int getColor(@NonNull final Context context, @ColorRes @SuppressWarnings("SameParameterValue") int resId)
{
return ContextCompat.getColor(context, resId);
}
/**
* Get drawable
*
* @param context context
* @param resId drawable id
* @return drawable
*/
static public Drawable getDrawable(@NonNull final Context context, @DrawableRes int resId)
{
return ResourcesCompat.getDrawable(context.getResources(), resId, context.getTheme());
}
/**
* Get drawables
*
* @param context context
* @param resIds drawable ids
* @return drawables
*/
@NonNull
static public Drawable[] getDrawables(@NonNull final Context context, @NonNull @SuppressWarnings("SameParameterValue") int... resIds)
{
final Resources resources = context.getResources();
final Resources.Theme theme = context.getTheme();
Drawable[] drawables = new Drawable[resIds.length];
for (int i = 0; i < resIds.length; i++)
{
drawables[i] = ResourcesCompat.getDrawable(resources, resIds[i], theme);
}
return drawables;
}
static public void tint(@NonNull final Drawable drawable, @ColorInt int iconTint)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
drawable.setTint(iconTint);
}
else
{
DrawableCompat.setTint(DrawableCompat.wrap(drawable), iconTint);
}
}
static public int screenWidth(@NonNull final Context context)
{
final WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
assert wm != null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
{
final Rect bounds = wm.getCurrentWindowMetrics().getBounds();
return bounds.width();
}
else
{
final Display display = wm.getDefaultDisplay();
final Point size = new Point();
display.getSize(size);
// int height = size.y;
return size.x;
}
}
static public Point screenSize(@NonNull final Context context)
{
final WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
assert wm != null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
{
final Rect bounds = wm.getCurrentWindowMetrics().getBounds();
return new Point(bounds.width(),bounds.height());
}
else
{
final Display display = wm.getDefaultDisplay();
final Point size = new Point();
display.getSize(size);
return size;
}
}
public static String join(@NonNull final CharSequence delim, @Nullable final CharSequence[] strs)
{
if (strs == null)
{
return "";
}
StringBuilder sb = new StringBuilder();
boolean first = true;
for (CharSequence str : strs)
{
if (str == null || str.length() == 0)
{
continue;
}
if (first)
{
first = false;
}
else
{
sb.append(delim);
}
sb.append(str);
}
return sb.toString();
}
} | 1313ou/TreebolicLib | treebolicGlue/src/main/java/treebolic/glue/component/Utils.java | Java | gpl-3.0 | 5,780 |
class CreatePermissions < ActiveRecord::Migration
def self.up
create_table :permissions do |t|
t.integer :role_id
t.integer :user_id
t.timestamps
end
end
def self.down
drop_table :permissions
end
end
| alfrenovsky/Digesto | db/migrate/20110908115724_create_permissions.rb | Ruby | gpl-3.0 | 240 |
/* -*- mia-c++ -*-
*
* This file is part of MIA - a toolbox for medical image analysis
* Copyright (c) Leipzig, Madrid 1999-2017 Gert Wollny
*
* MIA 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 MIA; if not, see <http://www.gnu.org/licenses/>.
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <mia/core/histogram.hh>
#include <mia/core/cmdlineparser.hh>
#include <mia/core/cmeans.hh>
#include <mia/2d.hh>
#include <memory>
#include <vector>
#include <numeric>
using namespace mia;
using namespace std;
typedef vector<C2DFImage> C2DFImageVec;
const SProgramDescription g_description = {
{pdi_group, "Analysis, filtering, combining, and segmentation of 2D images"},
{pdi_short, "Run a c-means segmentation of a 2D image."},
{
pdi_description, "This program runs the segmentation of a 2D image by applying "
"a localized c-means approach that helps to overcome intensity inhomogeneities "
"in the image. The approach evaluates a global c-means clustering, and then "
"separates the image into overlapping regions where more c-means iterations "
"are run only including the locally present classes, i.e. the classes that "
"relatively contain more pixels than a given threshold. This program implements "
"a 2D prototype of the algorithm described in: "
"[Dunmore CJ, Wollny G, Skinner MM. (2018) MIA-Clustering: a novel method "
"for segmentation of paleontological material. PeerJ 6:e4374.](https://doi.org/10.7717/peerj.4374)"
},
{
pdi_example_descr, "Run the segmentation on image test.png using three classes, "
"local regions of 40 pixels (grid width 20 pixels), and a class ignore threshold of 0.01."
},
{pdi_example_code, "-i test.png -o label.png -n 3 -g 20 -t 0.01"}
};
class FRunHistogram : public TFilter<void>
{
public:
template <typename T>
void operator()(const T2DImage<T>& image);
CSparseHistogram::Compressed get_histogram() const;
private:
CSparseHistogram m_sparse_histogram;
};
class FLocalCMeans: public TFilter<void>
{
public:
typedef map<int, CMeans::DVector> Probmap;
FLocalCMeans(float epsilon, const vector<double>& global_class_centers,
const C2DBounds& start, const C2DBounds& end,
const Probmap& global_probmap,
float rel_cluster_threshold,
const map<int, unsigned>& segmap,
vector<C2DFDatafield>& prob_buffer);
template <typename T>
void operator()(const T2DImage<T>& image);
private:
const float m_epsilon;
const vector<double>& m_global_class_centers;
const C2DBounds m_start;
const C2DBounds m_end;
const Probmap& m_global_probmap;
const float m_rel_cluster_threshold;
const map<int, unsigned>& m_segmap;
vector<C2DFDatafield>& m_prob_buffer;
size_t m_count;
};
class FCrispSeg: public TFilter<P2DImage>
{
public:
FCrispSeg(const map<int, unsigned>& segmap):
m_segmap(segmap)
{
}
template <typename T>
P2DImage operator()(const T2DImage<T>& image) const
{
P2DImage out_image = make_shared<C2DUBImage>(image.get_size());
C2DUBImage *help = static_cast<C2DUBImage *>(out_image.get());
transform(image.begin(), image.end(), help->begin(),
[this](T x) {
return m_segmap.at(x);
});
return out_image;
}
private:
const map<int, unsigned>& m_segmap;
};
int do_main(int argc, char *argv[])
{
string in_filename;
string out_filename;
string out_filename2;
string cls_filename;
string debug_filename;
int blocksize = 15;
double rel_cluster_threshold = 0.02;
float cmeans_epsilon = 0.0001;
CMeans::PInitializer class_center_initializer;
const auto& image2dio = C2DImageIOPluginHandler::instance();
CCmdOptionList opts(g_description);
opts.set_group("File-IO");
opts.add(make_opt( in_filename, "in-file", 'i', "image to be segmented",
CCmdOptionFlags::required_input, &image2dio ));
opts.add(make_opt( out_filename, "out-file", 'o', "class label image based on "
"merging local labels", CCmdOptionFlags::output, &image2dio ));
opts.add(make_opt( out_filename2, "out-global-crisp", 'G', "class label image based on "
"global segmentation", CCmdOptionFlags::output, &image2dio ));
opts.add(make_opt( cls_filename, "class-prob", 'C', "class probability image file, filetype "
"must support floating point multi-frame images", CCmdOptionFlags::output, &image2dio ));
opts.set_group("Parameters");
opts.add(make_opt( blocksize, EParameterBounds::bf_min_closed, {3},
"grid-spacing", 'g', "Spacing of the grid used to modulate "
"the intensity inhomogeneities"));
opts.add(make_opt( class_center_initializer, "kmeans:nc=3",
"cmeans", 'c', "c-means initializer"));
opts.add(make_opt( cmeans_epsilon, EParameterBounds::bf_min_open,
{0.0}, "c-means-epsilon", 'e', "c-means breaking condition for update tolerance"));
opts.add(make_opt( rel_cluster_threshold, EParameterBounds::bf_min_closed | EParameterBounds::bf_max_open,
{0.0, 1.0}, "relative-cluster-threshold", 't', "threshhold to ignore classes when initializing"
" the local cmeans from the global one."));
if (opts.parse(argc, argv) != CCmdOptionList::hr_no)
return EXIT_SUCCESS;
if (out_filename.empty() && out_filename2.empty()) {
throw invalid_argument("You must specify at least one output file");
}
auto in_image = load_image2d(in_filename);
FRunHistogram global_histogram;
mia::accumulate(global_histogram, *in_image);
CMeans globale_cmeans(cmeans_epsilon, class_center_initializer);
auto gh = global_histogram.get_histogram();
CMeans::DVector global_class_centers;
auto global_sparse_probmap = globale_cmeans.run(gh, global_class_centers, false);
cvinfo() << "Histogram range: [" << gh[0].first << ", " << gh[gh.size() - 1].first << "]\n";
cvinfo() << "Global class centers: " << global_class_centers << "\n";
cvinfo() << "Probmap size = " << global_sparse_probmap.size()
<< " weight number " << global_sparse_probmap[0].second.size() << "\n";
auto n_classes = global_class_centers.size();
// need the normalized class centers
map<int, unsigned> segmap;
for_each(global_sparse_probmap.begin(), global_sparse_probmap.end(),
[&segmap](const CMeans::SparseProbmap::value_type & x) {
int c = 0;
float max_prob = 0.0f;
for (unsigned i = 0; i < x.second.size(); ++i) {
auto f = x.second[i];
if (f > max_prob) {
max_prob = f;
c = i;
};
}
segmap[x.first] = c;
});
FLocalCMeans::Probmap global_probmap;
for (auto k : global_sparse_probmap) {
global_probmap[k.first] = k.second;
};
if (!out_filename2.empty()) {
FCrispSeg cs(segmap);
auto crisp_global_seg = mia::filter(cs, *in_image);
if (!save_image (out_filename2, crisp_global_seg)) {
cverr() << "Unable to save to '" << out_filename2 << "'\n";
}
}
int nx = (in_image->get_size().x + blocksize - 1) / blocksize;
int ny = (in_image->get_size().y + blocksize - 1) / blocksize;
int start_x = (nx * blocksize - in_image->get_size().x) / 2;
int start_y = (ny * blocksize - in_image->get_size().y) / 2;
vector<C2DFDatafield> prob_buffer(global_class_centers.size());
for (unsigned i = 0; i < global_class_centers.size(); ++i)
prob_buffer[i] = C2DFDatafield(in_image->get_size());
for (int iy_base = start_y; iy_base < (int)in_image->get_size().y; iy_base += blocksize) {
unsigned iy = iy_base < 0 ? 0 : iy_base;
unsigned iy_end = iy_base + 2 * blocksize;
if (iy_end > in_image->get_size().y)
iy_end = in_image->get_size().y;
for (int ix_base = start_x; ix_base < (int)in_image->get_size().x; ix_base += blocksize) {
unsigned ix = ix_base < 0 ? 0 : ix_base;
unsigned ix_end = ix_base + 2 * blocksize;
if (ix_end > in_image->get_size().x)
ix_end = in_image->get_size().x;
FLocalCMeans lcm(cmeans_epsilon, global_class_centers,
C2DBounds(ix, iy), C2DBounds(ix_end, iy_end),
global_probmap,
rel_cluster_threshold,
segmap,
prob_buffer);
mia::accumulate(lcm, *in_image);
}
}
// save the prob images ?
// normalize probability images
C2DFImage sum(prob_buffer[0]);
for (unsigned c = 1; c < n_classes; ++c) {
transform(sum.begin(), sum.end(), prob_buffer[c].begin(), sum.begin(),
[](float x, float y) {
return x + y;
});
}
for (unsigned c = 0; c < n_classes; ++c) {
transform(sum.begin(), sum.end(), prob_buffer[c].begin(), prob_buffer[c].begin(),
[](float s, float p) {
return p / s;
});
}
if (!cls_filename.empty()) {
C2DImageIOPluginHandler::Instance::Data classes;
for (unsigned c = 0; c < n_classes; ++c)
classes.push_back(make_shared<C2DFImage>(prob_buffer[c]));
if (!C2DImageIOPluginHandler::instance().save(cls_filename, classes))
cverr() << "Error writing class images to '" << cls_filename << "'\n";
}
// now for each pixel we have a probability sume that should take inhomogeinities
// into account
C2DUBImage out_image(in_image->get_size(), *in_image);
fill(out_image.begin(), out_image.end(), 0);
for (unsigned c = 1; c < n_classes; ++c) {
auto iout = out_image.begin();
auto eout = out_image.end();
auto itest = prob_buffer[0].begin();
auto iprob = prob_buffer[c].begin();
while ( iout != eout ) {
if (*itest < *iprob) {
*itest = *iprob;
*iout = c;
}
++iout;
++itest;
++iprob;
}
}
return save_image(out_filename, out_image) ? EXIT_SUCCESS : EXIT_FAILURE;
}
template <typename T>
void FRunHistogram::operator()(const T2DImage<T>& image)
{
m_sparse_histogram(image.begin(), image.end());
}
CSparseHistogram::Compressed FRunHistogram::get_histogram() const
{
return m_sparse_histogram.get_compressed_histogram();
}
FLocalCMeans::FLocalCMeans(float epsilon, const vector<double>& global_class_centers,
const C2DBounds& start, const C2DBounds& end,
const Probmap& global_probmap,
float rel_cluster_threshold,
const map<int, unsigned>& segmap,
vector<C2DFDatafield>& prob_buffer):
m_epsilon(epsilon),
m_global_class_centers(global_class_centers),
m_start(start),
m_end(end),
m_global_probmap(global_probmap),
m_rel_cluster_threshold(rel_cluster_threshold),
m_segmap(segmap),
m_prob_buffer(prob_buffer),
m_count((m_end - m_start).product())
{
}
template <typename T>
void FLocalCMeans::operator()(const T2DImage<T>& image)
{
cvmsg() << "Start subrange [" << m_start << "]-[" << m_end << "]\n";
// obtain the histogram for the current patch
CSparseHistogram histogram;
histogram(image.begin_range(m_start, m_end),
image.end_range(m_start, m_end));
auto ch = histogram.get_compressed_histogram();
// calculate the class avaliability in the patch
vector<double> partition(m_global_class_centers.size());
for (auto idx : ch) {
const double n = idx.second;
auto v = m_global_probmap.at(idx.first);
transform(partition.begin(), partition.end(), v.begin(),
partition.begin(), [n](double p, double value) {
return p + n * value;
});
}
auto part_thresh = std::accumulate(partition.begin(), partition.end(), 0.0) * m_rel_cluster_threshold;
cvinfo() << "Partition = " << partition << "\n";
// select the classes that should be used further on
vector<double> retained_class_centers;
vector<unsigned> used_classed;
for (unsigned i = 0; i < partition.size(); ++i) {
if (partition[i] >= part_thresh) {
retained_class_centers.push_back(m_global_class_centers[i]);
used_classed.push_back(i);
}
}
// prepare linear interpolation summing
auto center = C2DFVector((m_end + m_start)) / 2.0f;
auto max_distance = C2DFVector((m_end - m_start)) / 2.0f;
if (retained_class_centers.size() > 1) {
ostringstream cci_descr;
cci_descr << "predefined:cc=[" << retained_class_centers << "]";
cvinfo() << "Initializing local cmeans with '" << cci_descr.str()
<< " for retained classes " << used_classed << "'\n";
auto cci = CMeansInitializerPluginHandler::instance().produce(cci_descr.str());
// remove data that was globally assigned to now unused class
CSparseHistogram::Compressed cleaned_histogram;
cleaned_histogram.reserve(ch.size());
// copy used intensities
for (auto c : used_classed) {
for (auto ich : ch) {
if ( m_segmap.at(ich.first) == c) {
cleaned_histogram.push_back(ich);
}
}
}
// evluate the local c-means classification
CMeans local_cmeans(m_epsilon, cci);
auto local_map = local_cmeans.run(cleaned_histogram, retained_class_centers);
// create a lookup map intensity -> probability vector
map<unsigned short, CMeans::DVector> mapper;
for (auto i : local_map) {
mapper[i.first] = i.second;
}
// now add the new probabilities to the global maps.
auto ii = image.begin_range(m_start, m_end);
auto ie = image.end_range(m_start, m_end);
while (ii != ie) {
auto probs = mapper.find(*ii);
auto delta = (C2DFVector(ii.pos()) - center) / max_distance;
float lin_scale = (1.0 - std::fabs(delta.x)) * (1.0 - std::fabs(delta.y));
if (probs != mapper.end()) {
for (unsigned c = 0; c < used_classed.size(); ++c) {
m_prob_buffer[used_classed[c]](ii.pos()) += lin_scale * probs->second[c];
}
} else { // not in local map: retain global probabilities
auto v = m_global_probmap.at(*ii);
for (unsigned c = 0; c < v.size(); ++c) {
m_prob_buffer[c](ii.pos()) += lin_scale * v[c];
}
}
++ii;
}
} else { // only one class retained, add 1.0 to probabilities, linearly smoothed
cvdebug() << "Only one class used:" << used_classed[0] << "\n";
auto ii = m_prob_buffer[used_classed[0]].begin_range(m_start, m_end);
auto ie = m_prob_buffer[used_classed[0]].end_range(m_start, m_end);
while (ii != ie) {
auto delta = (C2DFVector(ii.pos()) - center) / max_distance;
*ii += (1.0 - std::fabs(delta.x)) * (1.0 - std::fabs(delta.y)); ;
++ii;
}
}
cvmsg() << "Done subrange [" << m_start << "]-[" << m_end << "]\n";
}
#include <mia/internal/main.hh>
MIA_MAIN(do_main);
| gerddie/mia | src/2dsegment-local-cmeans.cc | C++ | gpl-3.0 | 17,671 |
import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from 'azureexplorer/tests/helpers/start-app';
module('Integration | Notifications', {
afterEach: function() {
Ember.run(this.application, 'destroy');
this.store = null;
}
});
test('Notifications show up for batch download', function (assert) {
this.application = startApp({}, assert);
this.store = this.application.__container__.lookup('store:main');
Ember.run(() => {
this.store.findAll('account').then(accounts => {
accounts.content.forEach(account => {
account.record.deleteRecord();
account.record.save();
});
});
});
andThen(() => {
Ember.run(() => {
let newAccount = this.store.createRecord('account', {
name: 'Testaccount',
key: 'n+ufPpP3UwY+REvC3/zqBmHt2hCDdI06tQI5HFN7XnpUR5VEKMI+8kk/ez7QLQ3Cmojt/c1Ktaug3nK8FC8AeA==',
active: true
});
newAccount.save();
});
visit('/');
});
andThen(function () {
visit('/explorer').then(function () {
// replace file input as text box to avoid native dialog displaying
Ember.$('#nwSaveDirectory').attr('type', 'text');
Ember.$('#nwSaveInput').attr('type', 'text');
// select all blobs
return click('#selectAllCheckbox');
})
.then(function () {
return click('.fa-download');
})
.then(function () {
return triggerEvent('#nwSaveDirectory', 'change');
})
.then(function () {
return click('.handle');
})
.then(function () {
assert.equal(find('.mdi-action-done').length, 4);
});
});
});
| ritazh/xplat | tests/acceptance/notification-test.js | JavaScript | gpl-3.0 | 1,845 |