answer stringlengths 15 1.25M |
|---|
#include <openbeacon.h>
#include <acc.h>
#include <flash.h>
#include <radio.h>
#include <timer.h>
static int8_t g_tag_angle;
int8_t tag_angle(void)
{
return g_tag_angle;
}
void blink(uint8_t times)
{
while(times
{
nrf_gpio_pin_set(CONFIG_LED_PIN);
timer_wait(MILLISECONDS(10));
nrf_gpio_pin_clear(CONFIG_LED_PIN);
timer_wait(MILLISECONDS(490));
}
}
void halt(uint8_t times)
{
while(TRUE)
{
blink(times);
timer_wait(SECONDS(3));
}
}
void main_entry(void)
{
uint32_t tag_id;
/* enabled LED output */
nrf_gpio_cfg_output(CONFIG_LED_PIN);
nrf_gpio_pin_set(CONFIG_LED_PIN);
/* enabled input pin */
nrf_gpio_cfg_input(CONFIG_SWITCH_PIN, NRF_GPIO_PIN_NOPULL);
/* initialize UART */
uart_init();
/* start timer */
timer_init();
/* initialize flash */
if(flash_init())
halt(2);
/* initialize accelerometer */
if(acc_init())
halt(3);
/* calculate tag ID from NRF_FICR->DEVICEID */
tag_id = crc32(&NRF_FICR->DEVICEID, sizeof(NRF_FICR->DEVICEID));
/* start radio */
debug_printf("\n\rInitializing Tag[%08X] v" PROGRAM_VERSION " @24%02iMHz ...\n\r",
tag_id,
<API key>);
radio_init(tag_id);
/* enter main loop */
nrf_gpio_pin_clear(CONFIG_LED_PIN);
while(TRUE)
{
/* get tag angle once per second */
timer_wait(MILLISECONDS(5000));
/* blink every 5 seconds */
nrf_gpio_pin_set(CONFIG_LED_PIN);
timer_wait(MILLISECONDS(0.5));
nrf_gpio_pin_clear(CONFIG_LED_PIN);
}
} |
/** Path: theme pagelayout **/
body {
margin: auto 0px;
width: auto;
}
#page {
width: 100%;
}
#page-header {
float: left;
width: 100%;
}
#page-content {
clear: both;
float: left;
overflow: hidden;
position: relative;
width: 100%;
}
#page-content #region-main-box {
float: left;
right: 28%;
position: relative;
width: 100%;
}
#page-content #region-post-box {
float: left;
right: 72%;
position: relative;
width: 100%;
}
#page-content #region-main {
float: left;
overflow: hidden;
position: relative;
margin-right: 0px;
left: 100%;
width: 72%;
}
#page-content #region-post {
float: left;
overflow: hidden;
position: relative;
left: 100%;
width: 28%;
}
#page-content #region-main .region-content {
overflow: hidden;
padding: 50px 15px 20px 0;
}
#page-content #region-post .region-content {
padding: 0 0 0 10px;
}
#page-footer {
clear: both;
float: left;
width: 100%;
}
/** No blocks whatsoever **/
.content-only #page-content #region-main-box {
right: 0%;
}
.content-only #page-content #region-post-box {
right: 100%;
}
.content-only #page-content #region-main {
left: 100%;
width: 100%;
}
.content-only #page-content #region-pre {
width: 0%;
}
.content-only #page-content #region-post {
width: 0%;
}
.pagelayout-report #page-content #region-main {overflow:auto;}
.pagelayout-report #page-content #region-main .region-content {overflow:visible;}
#<API key> #region-main .region-content #region-header.inside {
margin-bottom: 110px;
} |
<?php
paginaPrivata();
richiediComitato();
?>
<div class="row-fluid">
<div class="span3">
<?php menuVolontario(); ?>
</div>
<div class="span9">
<?php if ( isset($_GET['ok']) ) { ?>
<div class="alert alert-success">
<i class="icon-save"></i> <strong>Richiesta inviata</strong>.
La richiesta è stata inviata con successo.
</div>
<?php }
if ( isset($_GET['ann']) ) { ?>
<div class="alert alert-success">
<i class="icon-save"></i> <strong>Richiesta annullata</strong>.
La richiesta di riserva è stata annullata con successo.
</div>
<?php }
if ( isset($_GET['gia']) ) { ?>
<div class="alert alert-danger">
<i class="icon-save"></i> <strong>Richiesta già presente</strong>.
E' già presente una richiesta di riserva.
</div>
<?php }
if ( isset($_GET['err']) ) { ?>
<div class="alert alert-danger">
<i class="icon-warning-sign"></i> <strong>Date non corrette</strong>.
La date che hai inserito sono incorrette.
</div>
<?php }
$i=0;
foreach ( $me->storico() as $app ) {
if ($app->attuale())
{
if($app->stato == MEMBRO_PENDENTE){
redirect('errore.comitato');
$i=1; }}}
foreach($me->riserve() as $riserva){
$riservafine = $riserva->fine;
if($riserva && $riserva->stato==RISERVA_INCORSO && !$riserva->presaInCarico()){ ?>
<div class="row-fluid">
<h2><i class="icon-warning-sign muted"></i> Richiesta riserva in elaborazione</h2>
<div class="alert alert-block">
<div class="row-fluid">
<span class="span12">
<p>La tua richiesta di transito nel ruolo di riserva è in fase di elaborazione.</p>
<p>La tua richiesta è in attesa di essere protocollata dalla segreteria del tuo Comitato,
potrai chiederne l'annullamento fino a quel momento.</p>
</span>
</div>
</div>
</div>
<div class="row-fluid">
<form class="form-horizontal" action="?p=utente.riserva.sospendi.ok" method="POST">
<input type="hidden" name="elimina" value="true" >
<button type="submit" class="btn btn-block btn-danger">
<i class="icon-remove"></i> Annulla la richiesta di transito nel ruolo di riserva
</button>
</form>
<div>
<?php $i=2; }
if($riserva && $riserva->presaInCarico() && $riserva->stato==RISERVA_INCORSO){ ?>
<div class="row-fluid">
<h2><i class="icon-warning-sign muted"></i> Richiesta riserva presa in carico</h2>
<div class="alert alert-block">
<div class="row-fluid">
<span class="span12">
<p>La tua richiesta di riserva è stata presa in carico il <strong><?php echo date('d-m-Y', $riserva->protData); ?></strong> con numero di protocollo <strong><?php echo $riserva->protNumero; ?></strong>.</p>
<p>La tua richiesta è in attesa di conferma da parte del tuo Presidente di Comitato.</p>
<p>Da questo momento non puoi più annullare la richiesta. Se hai cambiato idea contatta il tuo Presidente.</p>
</span>
</div>
</div>
</div>
<?php $i=3; }
if($riserva && $riserva->stato==RISERVA_OK && $riservafine >= time()){ ?>
<div class="row-fluid">
<h2><i class="icon-ok-sign muted"></i> Richiesta di riserva approvata</h2>
<div class="alert alert-success">
<div class="row-fluid">
<span class="span12">
<p>La tua richiesta di riserva è stata approvata.</p>
<p>Rimarrai nel ruolo di riserva dal <strong> <?php echo date('d-m-Y', $riserva->inizio); ?></strong> fino al <strong> <?php echo date('d-m-Y', $riserva->fine); ?></strong>.</p>
</span>
</div>
</div>
</div>
<?php $i=4; }}
if($i==0){ ?>
<div class="row-fluid">
<h2><i class="icon-pause muted"></i> Richiesta Riserva</h2>
<div class="alert alert-block alert-info ">
<div class="row-fluid">
<span class="span7">
<h4>Vuoi transitare nel ruolo di riserva ?</h4>
<p>Con questo modulo puoi richiedere il transito nel ruolo di riserva</p>
<p>Specifica il motivo di tale scelta</p>
<p>Seleziona il periodo in cui vuoi stare nel ruolo di riserva.</p>
</span>
</div>
</div>
</div>
<div class="row-fluid">
<form class="form-horizontal" action="?p=utente.riserva.ok&id=<?php echo $me->id; ?>" method="POST">
<div class="control-group">
<label class="control-label" for="datainizio">Data inizio </label>
<div class="controls">
<input class="input-medium" type="text" name="datainizio" id="datainizio" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="datafine">Data fine </label>
<div class="controls">
<input class="input-medium" type="text" name="datafine" id="datafine" required>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputMotivo">Motivazione </label>
<div class="controls">
<input class="span8" type="text" name="inputMotivo" id="motivo" placeholder="es.: Motivi di salute" required>
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-large btn-success">
<i class="icon-ok"></i>
Invia richiesta
</button>
</div>
</div>
</div>
<?php } ?>
</div>
</div> |
package cc.blynk.core.http.handlers;
public class StaticFile {
public final String path;
public final boolean doCaching;
public StaticFile(String path) {
this.path = path;
this.doCaching = false;
}
public StaticFile(String path, boolean doCaching) {
this.path = path;
this.doCaching = doCaching;
}
public boolean isStatic(String url) {
return url.startsWith(path);
}
} |
using System;
using System.Diagnostics;
using System.Media;
using System.Windows.Forms;
using JetBrains.Annotations;
namespace AldursLab.WurmAssistant3.Utils
{
public partial class <API key> : Form
{
readonly Exception exception;
public <API key>([NotNull] Exception exception)
{
if (exception == null) throw new <API key>(nameof(exception));
this.exception = exception;
InitializeComponent();
SystemSounds.Exclamation.Play();
}
private void <API key>(object sender, <API key> e)
{
const string link = "https:
try
{
Process.Start(link);
}
catch (Exception ohcrap)
{
MessageBox.Show(
$"I'm sorry, failed to start process for link: {link}. Batman can't help this. Error: {ohcrap}",
"Oops",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(exception.ToString());
}
}
} |
package org.eclim.test.impl;
import java.util.ArrayList;
import java.util.List;
public class TestDelegateVUnit
{
private List<Double> list = new ArrayList<Double>();
} |
#ifndef AD7689_H
#define AD7689_H
#include <Arduino.h>
#include "yspi.h"
#include "yADC.h"
// input configuration: bipolar/unipolar, single ended or differential
#define INCC_BIPOLAR_DIFF (0b000) // 00X
#define INCC_BIPOLAR_COM (0b010)
#define INCC_TEMP (0b011)
#define INCC_UNIPOLAR_DIFF (0b100)// 10X
#define <API key> (0b110)
#define <API key> (0b111)
// reference voltage (note: decoupling caps required on REF/REFIN when using INT_REF!)
#define INT_REF_25 (0b000)
#define INT_REF_4096 (0b001)
#define EXT_REF_TEMP_ON (0b010)
#define EXT_REF_TEMP_BUF (0b011)
#define EXT_REF_TEMP_OFF (0b110)
#define <API key> (0b111)
// sequencer configuration (default: no sequencer)
#define SEQ_OFF (0b00)
#define SEQ_UPDATE (0b01)
#define SEQ_SCAN_INPUT_TEMP (0b10)
#define SEQ_SCAN_INPUT (0b11)
#define MAX_FREQ (38000000) // 26 ns period @ VDD 5V and VIO 3.3 - 5V
#define UNIPOLAR_MODE (0)
#define BIPOLAR_MODE (1)
#define DIFFERENTIAL_MODE (2)
#define REF_INTERNAL (0)
#define REF_EXTERNAL (1)
#define REF_GND (2)
#define REF_COM (3)
// bit shifts needed for config register values, from datasheet p. 27 table 11:
#define CFG (13)
#define INCC (10)
#define INx (7)
#define BW (6)
#define REF (3)
#define SEQ (1)
#define RB (0)
#define TEMP_REF (4.096) // reference voltage to be used for temperature measurement, either 2.5V or 4.096V
#define BASE_TEMP (25)
#define TEMP_BASE_VOLTAGE (0.283)
#define TEMP_RICO (0.001)
#define INTERNAL_25 (2.5)
#define INTERNAL_4096 (4.096)
#define TOTAL_CHANNELS (8)
#define TOTAL_STEPS (65536)
#define TCONV (4)
#define TACQ (2)
#define STARTUP_DELAY (100)
/** Configuration settings of the ADC.
* This should *not* be modified directly by the user.
* Incorrect configuration combinations may lead to unpredictable results and potentially damage the ADC!
*/
struct AD7689_conf {
bool CFG_conf; /*!< True if configuration command should be updated. */
uint8_t INCC_conf; /*!< Input channel configuration */
uint8_t INx_conf; /*!< Number of activated input channels */
uint8_t BW_conf; /*!< Bandwidth filtering */
uint8_t REF_conf; /*!< Reference voltage settings */
uint8_t SEQ_conf; /*!< Sequencer settings */
float REF_voltage; /*!< Reference voltages */
bool RB_conf; /*!< True if readback should be enabled */
};
/**
* Represents the Analog Devices AD7689, an ADC with 8 channels and 16 bit resolution.
*/
class AD7689 : public YADC {
protected:
AD7689_conf conf; /*!< Configuration settings for the ADC. */
const float posref; /*!< Positive voltage reference for unipolar or bipolar mode. */
const float negref; /*!< Negative voltage reference, either COM or ground. */
const uint8_t refsrc; /*!< Positive voltage eference source. */
const uint8_t inputConfig; /*!< Input channel configuration. */
const uint8_t refConfig; /*!< Voltage reference configuration. */
uint32_t timeStamps[TOTAL_CHANNELS]; /*!< Last set of time stamps for each channel. */
uint16_t samples[TOTAL_CHANNELS]; /*!< Last set of samples for each channel. */
uint16_t framePeriod; /*!< Length of a single frame, in microseconds. */
uint16_t curTemp; /*!< Last temperature measurement. */
uint16_t tempTime; /*!< Time stamp for last temperature measurement. */
uint32_t lastSeqEndTime; /*!< Time stamp of the end of the last data acquisition sequence. */
uint8_t inputCount; /*!< Number of input channels. Even for differential mode. */
bool sequencerActive; /*!< True when the sequencer is initialized, false at start-up or during self tests */
bool filterConfig; /*!< Input filter configuration. */
uint16_t shiftTransaction(uint16_t command, bool readback, uint16_t* rb_cmd_ptr) const;
uint16_t toCommand(AD7689_conf cfg) const;
AD7689_conf getADCConfig(bool default_config = false);
float readTemperature(void);
void configureSequencer();
void readChannels(uint8_t channels, uint8_t mode, uint16_t* data, uint16_t* temp);
float calculateVoltage(uint16_t sample) const;
float calculateTemp(uint16_t temp) const;
uint32_t initSampleTiming(void);
void <API key>(void);
// initialisation funcitons
uint8_t getInputConfig(uint8_t polarity, bool differential) const;
float getNegRef(float posR, uint8_t polarity) const;
uint8_t getRefSrc(uint8_t refS, float posR) const;
float getPosRef(uint8_t refS, float posR) const;
public:
AD7689(const YSPI *const y, uint8_t numberChannels = TOTAL_CHANNELS);
void enableFiltering(bool onOff);
float acquireChannel(uint8_t channel, uint32_t* timeStamp);
float acquireChannel(uint8_t channel);
float acquireTemperature();
bool selftest(void);
};
#endif |
"""Askbot template context processor that makes some parameters
from the django settings, all parameters from the askbot livesettings
and the application available for the templates
"""
import sys
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils import simplejson
import askbot
from askbot import api
from askbot import models
from askbot import const
from askbot.conf import settings as askbot_settings
from askbot.search.state_manager import SearchState
from askbot.utils import url_utils
from askbot.utils.slug import slugify
from askbot.utils.html import site_url
from askbot.utils.translation import get_language
def <API key>(request):
"""The context processor function"""
#if not request.path.startswith('/' + settings.ASKBOT_URL):
# #todo: this is a really ugly hack, will only work
# #when askbot is installed not at the home page.
# #this will not work for the
# #heavy modders of askbot, because their custom pages
# #will not receive the askbot settings in the context
# #to solve this properly we should probably explicitly
# #add settings to the context per page
# return {}
my_settings = askbot_settings.as_dict()
my_settings['LANGUAGE_CODE'] = getattr(request, 'LANGUAGE_CODE', settings.LANGUAGE_CODE)
my_settings['MULTILINGUAL'] = getattr(settings, 'ASKBOT_MULTILINGUAL', False)
my_settings['LANGUAGES_DICT'] = dict(getattr(settings, 'LANGUAGES', []))
my_settings['<API key>'] = \
settings.<API key>
my_settings['ASKBOT_URL'] = settings.ASKBOT_URL
my_settings['STATIC_URL'] = settings.STATIC_URL
my_settings['<API key>'] = getattr(settings, '<API key>', False)
my_settings['USE_LOCAL_FONTS'] = getattr(
settings,
'<API key>',
False
)
my_settings['CSRF_COOKIE_NAME'] = settings.CSRF_COOKIE_NAME
my_settings['DEBUG'] = settings.DEBUG
my_settings['USING_RUNSERVER'] = 'runserver' in sys.argv
my_settings['ASKBOT_VERSION'] = askbot.get_version()
my_settings['LOGIN_URL'] = url_utils.get_login_url()
my_settings['LOGOUT_URL'] = url_utils.get_logout_url()
if my_settings['EDITOR_TYPE'] == 'tinymce':
tinymce_plugins = settings.<API key>.get('plugins', '').split(',')
my_settings['TINYMCE_PLUGINS'] = map(lambda v: v.strip(), tinymce_plugins)
else:
my_settings['TINYMCE_PLUGINS'] = [];
my_settings['LOGOUT_REDIRECT_URL'] = url_utils.<API key>()
my_settings['<API key>'] = 'askbot.deps.django_authopenid' \
in settings.INSTALLED_APPS
current_language = get_language()
#for some languages we will start searching for shorter words
if current_language == 'ja':
#we need to open the search box and show info message about
#the japanese lang search
<API key> = 1
else:
<API key> = my_settings['<API key>']
need_scope_links = askbot_settings.ALL_SCOPE_ENABLED or \
askbot_settings.<API key> or \
(request.user.is_authenticated() and askbot_settings.<API key>)
context = {
'base_url': site_url(''),
'empty_search_state': SearchState.get_empty(),
'<API key>': <API key>,
'<API key>': current_language,
'settings': my_settings,
'moderation_items': api.<API key>(request.user),
'need_scope_links': need_scope_links,
'noscript_url': const.DEPENDENCY_URLS['noscript'],
}
if askbot_settings.GROUPS_ENABLED:
#calculate context needed to list all the groups
def _get_group_url(group):
"""calculates url to the group based on its id and name"""
group_slug = slugify(group['name'])
return reverse(
'users_by_group',
kwargs={'group_id': group['id'], 'group_slug': group_slug}
)
#load id's and names of all groups
global_group = models.Group.objects.get_global_group()
groups = models.Group.objects.exclude_personal()
groups = groups.exclude(id=global_group.id)
groups_data = list(groups.values('id', 'name'))
#sort groups_data alphanumerically, but case-insensitive
groups_data = sorted(
groups_data,
lambda x, y: cmp(x['name'].lower(), y['name'].lower())
)
#insert data for the global group at the first position
groups_data.insert(0, {'id': global_group.id, 'name': global_group.name})
#build group_list for the context
group_list = list()
for group in groups_data:
link = _get_group_url(group)
group_list.append({'name': group['name'], 'link': link})
context['group_list'] = simplejson.dumps(group_list)
return context |
/* Lots still TODO here! */
/* General markup styles */
* {
padding: 0;
margin: 0;
}
body {
font: 11pt Verdana, Arial, Helvetica, sans-serif;
color:#000000;
}
a:link { color: #000000; text-decoration: none; }
a:visited { color: #000000; text-decoration: none; }
a:active { color: #000000; text-decoration: none; }
img, .noprint, #sub-header, #sub-footer, .navbar, .box1, .divider, .signature { display: none; }
/* Display smilies (Bug #47265) */
.content img {
display: inline;
}
/* Container for the main body */
#wrap {
margin: 0 2em;
}
p { font-size: 85%; }
.copyright { font-size: 75%; }
.page-number { float:right; width: auto; text-align: right; font-size: 75%; }
h1, h2, h3, h1 a, h2 a, h3 a {
font-family: "Trebuchet MS",georgia,Verdana,Sans-serif;
color: #000000;
background: none;
text-decoration: none;
font-weight: bold;
}
h1 { font-size: 20pt; }
h2 { font-size: 16pt; margin-top: 1em; }
h3 { font-size: 14pt; margin-top: 1em; }
.content {
font-size: 11pt;
line-height: 14pt;
margin-bottom: 1em;
font-family: "Lucida Grande", "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
overflow: hidden;
}
.postbody a:link, .postbody a:visited, .postbody a:hover, .postbody a:active {
text-decoration: underline;
padding: 0.1em 0.2em;
margin: -0.1em -0.2em;
color: #666;
background: none;
font-size: 100%;
}
html>body .postbody a:link:after, html>body .postbody a:visited:after {
content: " (" attr(href) ") ";
font-size: 90%;
text-decoration: none;
}
hr {
height: 1px;
background-color: #999999;
border-width: 0;
}
.author {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 75%;
margin-bottom: 0.6em;
}
.date {
font-family: Verdana, Arial, Helvetica, sans-serif;
float: right;
position: relative;
text-align: right;
font-size: 75%;
}
/* Dont want to print url for names or titles in content area */
.postbody .author a:link, .postbody .author a:visited,
html>body .postbody .author a:link:after,
html>body .postbody .author a:visited:after,
.postquote .quote-by a:link, .postquote .quote-by a:visited,
html>body .postquote .quote-by a:link:after,
html>body .postquote .quote-by a:visited:after,
html>body .postbody h1 a:link:after, html>body .postbody h2 a:link:after {
text-decoration: none;
content: "";
}
/* Poster profile */
.postprofile { display: none; }
.grip-show { display:none; }
/* Quote */
.postquote, blockquote {
font-size: 85%;
margin: 1em 18% 1em 4%;
padding: 0.5em;
position: relative;
line-height: 1.5em;
border: 1px #999999 solid;
}
.postquote img { display: none; }
.postquote span { display: block; }
.postquote span .postquote { font-size: 100%; }
.quote-by, blockquote cite {
color: black;
display : block;
font-weight: bold;
}
/* List */
ol, ul {
margin-left: 15pt
}
/* Misc page elements */
div.spacer { clear: both; }
/* Accessibility tweaks: Mozilla.org */
.skip_link { display: none; }
dl.codebox dt { display: none; } |
// SimulationCraft for Star Wars: The Old Republic
#include "warr_knight.hpp"
namespace warr_knight {
targetdata_t::targetdata_t( class_t& source, player_t& target ) :
::targetdata_t( source, target )
{
}
// Warrior | Knight Character Definitions
::action_t* class_t::create_action( const std::string& name,
const std::string& options_str )
{
//if ( name == m.a_adrenaline_probe ) return new adrenaline_probe_t ( this, name, options_str ) ;
return base_t::create_action( name, options_str );
}
void class_t::init_talents()
{
base_t::init_talents();
// Rage|Focus
talents.ravager = find_talent( "Ravager" );
talents.malice = find_talent( "Malice");
talents.decimate = find_talent( "Decimate" );
talents.payback = find_talent( "Payback" );
talents.overpower = find_talent( "Overpower" );
talents.enraged_scream = find_talent( "Enraged Scream" );
talents.brutality = find_talent( "Brutality" );
talents.saber_strength = find_talent( "Saber Strength" );
talents.obliterate = find_talent( "Obliterate" );
talents.strangulate = find_talent( "Strangulate" );
talents.dominate = find_talent( "Dominate" );
talents.shockwave = find_talent( "Shockwave" );
talents.berserker = find_talent( "Berserker" );
talents.gravity = find_talent( "Gravity" );
talents.interceptor = find_talent( "Interceptor" );
talents.shii_cho_mastery = find_talent( "Shii Cho Mastery" );
talents.dark_resonance = find_talent( "Dark Resonance" );
talents.undying = find_talent( "Undying" );
talents.force_crush = find_talent( "Force Crush" );
}
void class_t::init_benefits()
{
base_t::init_benefits();
}
void class_t::init_buffs()
{
base_t::init_buffs();
}
void class_t::init_procs()
{
base_t::init_procs();
}
void class_t::init_rng()
{
base_t::init_rng();
}
void class_t::init_actions()
{
base_t::init_actions();
}
void class_t::create_mirror()
{
//bool ag = type == IA_SNIPER || type == IA_OPERATIVE;
// ABILITY = ? AGENT LABEL : SMUGGLER LABEL ;
//m.a_adrenaline_probe = ag ? "adrenaline_probe" : "cool_head" ;
// Shared Talents
//m.t_deadly_directive = ag ? "deadly_directive" : "black_market_mods" ;
}
void class_t::create_talents()
{
static const talentinfo_t rage_tree[] = {
{ "Ravager" , 3 }, { "Malice" , 3 }, { "Decimate" , 2 },
{ "Payback" , 2 }, { "Overpower" , 2 }, { "Enraged Scream" , 1 }, { "Brutality" , 2 },
{ "Saber Strength" , 2 }, { "Obliterate" , 1 }, { "Strangulate" , 2 },
{ "Dominate" , 3 }, { "Shockwave" , 2 }, { "Berserker" , 2 },
{ "Gravity" , 1 }, { "Interceptor" , 2 }, { "Shii Cho Mastery" , 2 },
{ "Dark Resonance" , 3 }, { "Undying" , 2 },
{ "Force Crush" , 1 }
};
init_talent_tree( SITH_MARAUDER_RAGE, rage_tree );
}
} |
package janala;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class <API key> {
private static util.IntArrayUtil jarUtil = new util.IntArrayUtil();
private static tests.homework.IntArrayUtil srcUtil = new tests.homework.IntArrayUtil();
@Test
public void <API key>() throws Exception {
int[] arr0 = {0, 0, 0, 0, 0, 0, 0, 0};
int[] arr1 = {0, 0, 0, 0, 0, 0, 0, 0};
assertEquals(jarUtil.findMinViaRecursion(arr0), srcUtil.findMinViaRecursion(arr1));
}
} |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
EXAMPLES = r'''
- name: Get pool facts
bigip_gtm_facts:
server: lb.mydomain.com
user: admin
password: secret
include: pool
filter: my_pool
delegate_to: localhost
'''
RETURN = r'''
wide_ip:
description:
Contains the lb method for the wide ip and the pools that are within the wide ip.
returned: changed
type: list
sample:
wide_ip:
- enabled: True
failure_rcode: noerror
<API key>: disabled
failure_rcode_ttl: 0
full_path: /Common/foo.ok.com
last_resort_pool: ""
minimal_response: enabled
name: foo.ok.com
partition: Common
persist_cidr_ipv4: 32
persist_cidr_ipv6: 128
persistence: disabled
pool_lb_mode: round-robin
pools:
- name: d3qw
order: 0
partition: Common
ratio: 1
ttl_persistence: 3600
type: naptr
pool:
description: Contains the pool object status and enabled status.
returned: changed
type: list
sample:
pool:
- alternate_mode: round-robin
dynamic_ratio: disabled
enabled: True
fallback_mode: return-to-dns
full_path: /Common/d3qw
load_balancing_mode: round-robin
manual_resume: disabled
<API key>: 1
members:
- disabled: True
flags: a
full_path: ok3.com
member_order: 0
name: ok3.com
order: 10
preference: 10
ratio: 1
service: 80
name: d3qw
partition: Common
qos_hit_ratio: 5
qos_hops: 0
<API key>: 3
qos_lcs: 30
qos_packet_rate: 1
qos_rtt: 50
qos_topology: 0
qos_vs_capacity: 0
qos_vs_score: 0
availability_state: offline
enabled_state: disabled
ttl: 30
type: naptr
<API key>: disabled
virtual_server:
description:
Contains the virtual server enabled and availability status, and address.
returned: changed
type: list
sample:
virtual_server:
- addresses:
- device_name: /Common/qweqwe
name: 10.10.10.10
translation: none
datacenter: /Common/xfxgh
enabled: True
<API key>: no
full_path: /Common/qweqwe
iq_allow_path: yes
<API key>: yes
iq_allow_snmp: yes
limit_cpu_usage: 0
<API key>: disabled
limit_max_bps: 0
<API key>: disabled
<API key>: 0
<API key>: disabled
limit_max_pps: 0
<API key>: disabled
limit_mem_avail: 0
<API key>: disabled
link_discovery: disabled
monitor: /Common/bigip
name: qweqwe
partition: Common
product: single-bigip
<API key>: disabled
virtual_servers:
- destination: 10.10.10.10:0
enabled: True
full_path: jsdfhsd
limit_max_bps: 0
<API key>: disabled
<API key>: 0
<API key>: disabled
limit_max_pps: 0
<API key>: disabled
name: jsdfhsd
translation_address: none
translation_port: 0
'''
import re
from ansible.module_utils.basic import AnsibleModule
HAS_DEVEL_IMPORTS = False
try:
# Sideband repository used for dev
from library.module_utils.network.f5.bigip import HAS_F5SDK
from library.module_utils.network.f5.bigip import F5Client
from library.module_utils.network.f5.common import F5ModuleError
from library.module_utils.network.f5.common import AnsibleF5Parameters
from library.module_utils.network.f5.common import cleanup_tokens
from library.module_utils.network.f5.common import fqdn_name
from library.module_utils.network.f5.common import f5_argument_spec
try:
from library.module_utils.network.f5.common import <API key>
except ImportError:
HAS_F5SDK = False
HAS_DEVEL_IMPORTS = True
except ImportError:
# Upstream Ansible
from ansible.module_utils.network.f5.bigip import HAS_F5SDK
from ansible.module_utils.network.f5.bigip import F5Client
from ansible.module_utils.network.f5.common import F5ModuleError
from ansible.module_utils.network.f5.common import AnsibleF5Parameters
from ansible.module_utils.network.f5.common import cleanup_tokens
from ansible.module_utils.network.f5.common import fqdn_name
from ansible.module_utils.network.f5.common import f5_argument_spec
try:
from ansible.module_utils.network.f5.common import <API key>
except ImportError:
HAS_F5SDK = False
try:
import json
except ImportError:
import simplejson as json
from ansible.module_utils.parsing.convert_bool import BOOLEANS_TRUE
from ansible.module_utils.six import iteritems
from distutils.version import LooseVersion
try:
from f5.utils.responses.handlers import Stats
from ansible.module_utils.f5_utils import <API key>
except ImportError:
HAS_F5SDK = False
class BaseManager(object):
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.kwargs = kwargs
self.types = dict(
a_s='a',
aaaas='aaaa',
cnames='cname',
mxs='mx',
naptrs='naptr',
srvs='srv'
)
def exec_module(self):
result = self.<API key>()
return result
def filter_matches_name(self, name):
if self.want.filter is None:
return True
matches = re.match(self.want.filter, str(name))
if matches:
return True
else:
return False
def <API key>(self):
version = self.client.api.tmos_version
if LooseVersion(version) < LooseVersion('12.0.0'):
return True
else:
return False
def <API key>(self, collection, collection_type=None):
results = []
for item in collection:
if not self.filter_matches_name(item.name):
continue
facts = self.format_facts(item, collection_type)
results.append(facts)
return results
def <API key>(self, resource):
stats = Stats(resource.stats.load())
return stats.stat
class UntypedManager(BaseManager):
def exec_module(self):
results = []
facts = self.read_facts()
for item in facts:
filtered = [(k, v) for k, v in iteritems(item) if self.filter_matches_name(k)]
if filtered:
results.append(dict(filtered))
return results
class TypedManager(BaseManager):
def exec_module(self):
results = []
for collection, type in iteritems(self.types):
facts = self.read_facts(collection)
if not facts:
continue
for x in facts:
x.update({'type': type})
for item in facts:
attrs = item.to_return()
filtered = [(k, v) for k, v in iteritems(attrs) if self.filter_matches_name(k)]
if filtered:
results.append(dict(filtered))
return results
class Parameters(AnsibleF5Parameters):
@property
def include(self):
requested = self._values['include']
valid = ['pool', 'wide_ip', 'virtual_server', 'server', 'all']
if any(x for x in requested if x not in valid):
raise F5ModuleError(
"The valid 'include' choices are {0}".format(', '.join(valid))
)
if any(x for x in requested if x == 'virtual_server'):
self._values['__warnings'].append(
dict(
msg="The 'virtual_server' param is deprecated. Use 'server' instead",
version='2.5'
)
)
if 'all' in requested:
return ['all']
else:
return requested
class BaseParameters(Parameters):
@property
def enabled(self):
if self._values['enabled'] is None:
return None
elif self._values['enabled'] in BOOLEANS_TRUE:
return True
else:
return False
@property
def disabled(self):
if self._values['disabled'] is None:
return None
elif self._values['disabled'] in BOOLEANS_TRUE:
return True
else:
return False
def <API key>(self, resource):
del resource['kind']
del resource['generation']
del resource['selfLink']
def to_return(self):
result = {}
for returnable in self.returnables:
result[returnable] = getattr(self, returnable)
result = self._filter_params(result)
return result
class PoolParameters(BaseParameters):
api_map = {
'alternateMode': 'alternate_mode',
'dynamicRatio': 'dynamic_ratio',
'fallbackMode': 'fallback_mode',
'fullPath': 'full_path',
'loadBalancingMode': 'load_balancing_mode',
'manualResume': 'manual_resume',
'maxAnswersReturned': '<API key>',
'qosHitRatio': 'qos_hit_ratio',
'qosHops': 'qos_hops',
'qosKilobytesSecond': '<API key>',
'qosLcs': 'qos_lcs',
'qosPacketRate': 'qos_packet_rate',
'qosRtt': 'qos_rtt',
'qosTopology': 'qos_topology',
'qosVsCapacity': 'qos_vs_capacity',
'qosVsScore': 'qos_vs_score',
'<API key>': '<API key>',
'membersReference': 'members'
}
returnables = [
'alternate_mode', 'dynamic_ratio', 'enabled', 'disabled', 'fallback_mode',
'load_balancing_mode', 'manual_resume', '<API key>', 'members',
'name', 'partition', 'qos_hit_ratio', 'qos_hops', '<API key>',
'qos_lcs', 'qos_packet_rate', 'qos_rtt', 'qos_topology', 'qos_vs_capacity',
'qos_vs_score', 'ttl', 'type', 'full_path', 'availability_state',
'enabled_state', 'availability_status'
]
@property
def <API key>(self):
if self._values['<API key>'] is None:
return None
return int(self._values['<API key>'])
@property
def members(self):
result = []
if self._values['members'] is None or 'items' not in self._values['members']:
return result
for item in self._values['members']['items']:
self.<API key>(item)
if 'disabled' in item:
if item['disabled'] in BOOLEANS_TRUE:
item['disabled'] = True
else:
item['disabled'] = False
if 'enabled' in item:
if item['enabled'] in BOOLEANS_TRUE:
item['enabled'] = True
else:
item['enabled'] = False
if 'fullPath' in item:
item['full_path'] = item.pop('fullPath')
if 'memberOrder' in item:
item['member_order'] = int(item.pop('memberOrder'))
# Cast some attributes to integer
for x in ['order', 'preference', 'ratio', 'service']:
if x in item:
item[x] = int(item[x])
result.append(item)
return result
@property
def qos_hit_ratio(self):
if self._values['qos_hit_ratio'] is None:
return None
return int(self._values['qos_hit_ratio'])
@property
def qos_hops(self):
if self._values['qos_hops'] is None:
return None
return int(self._values['qos_hops'])
@property
def <API key>(self):
if self._values['<API key>'] is None:
return None
return int(self._values['<API key>'])
@property
def qos_lcs(self):
if self._values['qos_lcs'] is None:
return None
return int(self._values['qos_lcs'])
@property
def qos_packet_rate(self):
if self._values['qos_packet_rate'] is None:
return None
return int(self._values['qos_packet_rate'])
@property
def qos_rtt(self):
if self._values['qos_rtt'] is None:
return None
return int(self._values['qos_rtt'])
@property
def qos_topology(self):
if self._values['qos_topology'] is None:
return None
return int(self._values['qos_topology'])
@property
def qos_vs_capacity(self):
if self._values['qos_vs_capacity'] is None:
return None
return int(self._values['qos_vs_capacity'])
@property
def qos_vs_score(self):
if self._values['qos_vs_score'] is None:
return None
return int(self._values['qos_vs_score'])
@property
def availability_state(self):
if self._values['stats'] is None:
return None
try:
result = self._values['stats']['<API key>']
return result['description']
except AttributeError:
return None
@property
def enabled_state(self):
if self._values['stats'] is None:
return None
try:
result = self._values['stats']['status_enabledState']
return result['description']
except AttributeError:
return None
@property
def availability_status(self):
# This fact is a combination of the availability_state and enabled_state
# The purpose of the fact is to give a higher-level view of the availability
# of the pool, that can be used in playbooks. If you need further detail,
# consider using the following facts together.
# - availability_state
# - enabled_state
if self.enabled_state == 'enabled':
if self.availability_state == 'offline':
return 'red'
elif self.availability_state == 'available':
return 'green'
elif self.availability_state == 'unknown':
return 'blue'
else:
return 'none'
else:
# disabled
return 'black'
class WideIpParameters(BaseParameters):
api_map = {
'fullPath': 'full_path',
'failureRcode': 'failure_return_code',
'<API key>': '<API key>',
'failureRcodeTtl': '<API key>',
'lastResortPool': 'last_resort_pool',
'minimalResponse': 'minimal_response',
'persistCidrIpv4': 'persist_cidr_ipv4',
'persistCidrIpv6': 'persist_cidr_ipv6',
'poolLbMode': 'pool_lb_mode',
'ttlPersistence': 'ttl_persistence'
}
returnables = [
'full_path', 'description', 'enabled', 'disabled', 'failure_return_code',
'<API key>', '<API key>', 'last_resort_pool',
'minimal_response', 'persist_cidr_ipv4', 'persist_cidr_ipv6', 'pool_lb_mode',
'ttl_persistence', 'pools'
]
@property
def pools(self):
result = []
if self._values['pools'] is None:
return []
for pool in self._values['pools']:
del pool['nameReference']
for x in ['order', 'ratio']:
if x in pool:
pool[x] = int(pool[x])
result.append(pool)
return result
@property
def <API key>(self):
if self._values['<API key>'] is None:
return None
return int(self._values['<API key>'])
@property
def persist_cidr_ipv4(self):
if self._values['persist_cidr_ipv4'] is None:
return None
return int(self._values['persist_cidr_ipv4'])
@property
def persist_cidr_ipv6(self):
if self._values['persist_cidr_ipv6'] is None:
return None
return int(self._values['persist_cidr_ipv6'])
@property
def ttl_persistence(self):
if self._values['ttl_persistence'] is None:
return None
return int(self._values['ttl_persistence'])
class ServerParameters(BaseParameters):
api_map = {
'fullPath': 'full_path',
'exposeRouteDomains': '<API key>',
'iqAllowPath': 'iq_allow_path',
'iqAllowServiceCheck': '<API key>',
'iqAllowSnmp': 'iq_allow_snmp',
'limitCpuUsage': 'limit_cpu_usage',
'limitCpuUsageStatus': '<API key>',
'limitMaxBps': 'limit_max_bps',
'limitMaxBpsStatus': '<API key>',
'limitMaxConnections': '<API key>',
'<API key>': '<API key>',
'limitMaxPps': 'limit_max_pps',
'limitMaxPpsStatus': '<API key>',
'limitMemAvail': 'limit_mem_available',
'limitMemAvailStatus': '<API key>',
'linkDiscovery': 'link_discovery',
'proberFallback': 'prober_fallback',
'proberPreference': 'prober_preference',
'<API key>': '<API key>',
'devicesReference': 'devices',
'<API key>': 'virtual_servers'
}
returnables = [
'datacenter', 'enabled', 'disabled', '<API key>', 'iq_allow_path',
'full_path', '<API key>', 'iq_allow_snmp', 'limit_cpu_usage',
'<API key>', 'limit_max_bps', '<API key>',
'<API key>', '<API key>', 'limit_max_pps',
'<API key>', 'limit_mem_available', '<API key>',
'link_discovery', 'monitor', 'product', 'prober_fallback', 'prober_preference',
'<API key>', 'addresses', 'devices', 'virtual_servers'
]
@property
def devices(self):
result = []
if self._values['devices'] is None or 'items' not in self._values['devices']:
return result
for item in self._values['devices']['items']:
self.<API key>(item)
if 'fullPath' in item:
item['full_path'] = item.pop('fullPath')
result.append(item)
return result
@property
def virtual_servers(self):
result = []
if self._values['virtual_servers'] is None or 'items' not in self._values['virtual_servers']:
return result
for item in self._values['virtual_servers']['items']:
self.<API key>(item)
if 'disabled' in item:
if item['disabled'] in BOOLEANS_TRUE:
item['disabled'] = True
else:
item['disabled'] = False
if 'enabled' in item:
if item['enabled'] in BOOLEANS_TRUE:
item['enabled'] = True
else:
item['enabled'] = False
if 'fullPath' in item:
item['full_path'] = item.pop('fullPath')
if 'limitMaxBps' in item:
item['limit_max_bps'] = int(item.pop('limitMaxBps'))
if 'limitMaxBpsStatus' in item:
item['<API key>'] = item.pop('limitMaxBpsStatus')
if 'limitMaxConnections' in item:
item['<API key>'] = int(item.pop('limitMaxConnections'))
if '<API key>' in item:
item['<API key>'] = item.pop('<API key>')
if 'limitMaxPps' in item:
item['limit_max_pps'] = int(item.pop('limitMaxPps'))
if 'limitMaxPpsStatus' in item:
item['<API key>'] = item.pop('limitMaxPpsStatus')
if 'translationAddress' in item:
item['translation_address'] = item.pop('translationAddress')
if 'translationPort' in item:
item['translation_port'] = int(item.pop('translation_port'))
result.append(item)
return result
@property
def limit_cpu_usage(self):
if self._values['limit_cpu_usage'] is None:
return None
return int(self._values['limit_cpu_usage'])
@property
def limit_max_bps(self):
if self._values['limit_max_bps'] is None:
return None
return int(self._values['limit_max_bps'])
@property
def <API key>(self):
if self._values['<API key>'] is None:
return None
return int(self._values['<API key>'])
@property
def limit_max_pps(self):
if self._values['limit_max_pps'] is None:
return None
return int(self._values['limit_max_pps'])
@property
def limit_mem_available(self):
if self._values['limit_mem_available'] is None:
return None
return int(self._values['limit_mem_available'])
class PoolFactManager(BaseManager):
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
super(PoolFactManager, self).__init__(**kwargs)
self.kwargs = kwargs
def exec_module(self):
if self.<API key>():
manager = self.get_manager('untyped')
else:
manager = self.get_manager('typed')
facts = manager.exec_module()
result = dict(pool=facts)
return result
def get_manager(self, type):
if type == 'typed':
return <API key>(**self.kwargs)
elif type == 'untyped':
return <API key>(**self.kwargs)
class <API key>(TypedManager):
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
super(<API key>, self).__init__(**kwargs)
self.want = PoolParameters(params=self.module.params)
def read_facts(self, collection):
results = []
collection = self.<API key>(collection)
for resource in collection:
attrs = resource.attrs
attrs['stats'] = self.<API key>(resource)
params = PoolParameters(attrs)
results.append(params)
return results
def <API key>(self, collection_name):
pools = self.client.api.tm.gtm.pools
collection = getattr(pools, collection_name)
result = collection.get_collection(
requests_params=dict(
params='<API key>=true'
)
)
return result
class <API key>(UntypedManager):
def __init__(self, *args, **kwargs):
self.client = kwargs.get('client', None)
self.module = kwargs.get('module', None)
super(<API key>, self).__init__(**kwargs)
self.want = PoolParameters(params=self.module.params)
def read_facts(self):
results = []
collection = self.<API key>()
for resource in collection:
attrs = resource.attrs
attrs['stats'] = self.<API key>(resource)
params = PoolParameters(attrs)
results.append(params)
return results
def <API key>(self):
result = self.client.api.tm.gtm.pools.get_collection(
requests_params=dict(
params='<API key>=true'
)
)
return result
class WideIpFactManager(BaseManager):
def exec_module(self):
if self.<API key>():
manager = self.get_manager('untyped')
else:
manager = self.get_manager('typed')
facts = manager.exec_module()
result = dict(wide_ip=facts)
return result
def get_manager(self, type):
if type == 'typed':
return <API key>(**self.kwargs)
elif type == 'untyped':
return <API key>(**self.kwargs)
class <API key>(TypedManager):
def __init__(self, *args, **kwargs):
self.client = kwargs.get('client', None)
self.module = kwargs.get('module', None)
super(<API key>, self).__init__(**kwargs)
self.want = WideIpParameters(params=self.module.params)
def read_facts(self, collection):
results = []
collection = self.<API key>(collection)
for resource in collection:
attrs = resource.attrs
params = WideIpParameters(attrs)
results.append(params)
return results
def <API key>(self, collection_name):
wideips = self.client.api.tm.gtm.wideips
collection = getattr(wideips, collection_name)
result = collection.get_collection(
requests_params=dict(
params='<API key>=true'
)
)
return result
class <API key>(UntypedManager):
def __init__(self, *args, **kwargs):
self.client = kwargs.get('client', None)
self.module = kwargs.get('module', None)
super(<API key>, self).__init__(**kwargs)
self.want = WideIpParameters(params=self.module.params)
def read_facts(self):
results = []
collection = self.<API key>()
for resource in collection:
attrs = resource.attrs
params = WideIpParameters(attrs)
results.append(params)
return results
def <API key>(self):
result = self.client.api.tm.gtm.wideips.get_collection(
requests_params=dict(
params='<API key>=true'
)
)
return result
class ServerFactManager(UntypedManager):
def __init__(self, *args, **kwargs):
self.client = kwargs.get('client', None)
self.module = kwargs.get('module', None)
super(ServerFactManager, self).__init__(**kwargs)
self.want = ServerParameters(params=self.module.params)
def exec_module(self):
facts = super(ServerFactManager, self).exec_module()
result = dict(server=facts, virtual_server=facts)
return result
def read_facts(self):
results = []
collection = self.<API key>()
for resource in collection:
attrs = resource.attrs
params = WideIpParameters(attrs)
results.append(params)
return results
def <API key>(self):
result = self.client.api.tm.gtm.servers.get_collection(
requests_params=dict(
params='<API key>=true'
)
)
return result
class ModuleManager(object):
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.kwargs = kwargs
self.want = Parameters(params=self.module.params)
def exec_module(self):
if not self.gtm_provisioned():
raise F5ModuleError(
"GTM must be provisioned to use this module."
)
if 'all' in self.want.include:
names = ['pool', 'wide_ip', 'server']
else:
names = self.want.include
# The virtual_server parameter is deprecated
if 'virtual_server' in names:
names.append('server')
names.remove('virtual_server')
managers = [self.get_manager(name) for name in names]
result = self.execute_managers(managers)
if result:
result['changed'] = True
else:
result['changed'] = False
self.<API key>()
return result
def <API key>(self):
warnings = []
if self.want:
warnings += self.want._values.get('__warnings', [])
for warning in warnings:
self.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
def execute_managers(self, managers):
results = dict()
for manager in managers:
result = manager.exec_module()
results.update(result)
return results
def get_manager(self, which):
if 'pool' == which:
return PoolFactManager(**self.kwargs)
if 'wide_ip' == which:
return WideIpFactManager(**self.kwargs)
if 'server' == which:
return ServerFactManager(**self.kwargs)
def gtm_provisioned(self):
resource = self.client.api.tm.sys.dbs.db.load(
name='provisioned.cpu.gtm'
)
if int(resource.value) == 0:
return False
return True
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = False
argument_spec = dict(
include=dict(type='list', required=True),
filter=dict()
)
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
def main():
spec = ArgumentSpec()
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode
)
if not HAS_F5SDK:
module.fail_json(msg="The python f5-sdk module is required")
try:
client = F5Client(**module.params)
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
module.exit_json(**results)
except F5ModuleError as ex:
cleanup_tokens(client)
module.fail_json(msg=str(ex))
if __name__ == '__main__':
main() |
package de.tudarmstadt.ukp.dkpro.wsd.supervised.ims.annotator;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.uima.UimaContext;
import org.apache.uima.fit.descriptor.ExternalResource;
import org.apache.uima.resource.<API key>;
import de.tudarmstadt.ukp.dkpro.wsd.algorithm.<API key>;
import de.tudarmstadt.ukp.dkpro.wsd.annotator.<API key>;
import de.tudarmstadt.ukp.dkpro.wsd.si.<API key>;
import de.tudarmstadt.ukp.dkpro.wsd.type.WSDItem;
/**
* An abstract class for annotators which call a disambiguation algorithm taking
* as a parameter the id of the document.
*
* @author Nicolai Erbs <erbs@ukp.informatik.tu-darmstadt.de>
*
*/
public class ImsWSDAnnotator
extends <API key>
{
public final static String <API key> = "<API key>";
@ExternalResource(key = <API key>)
protected <API key> wsdMethod;
@Override
public void initialize(UimaContext context)
throws <API key>
{
super.initialize(context);
inventory = wsdMethod.getSenseInventory();
}
@Override
protected String <API key>()
throws <API key>
{
if (<API key> != null) {
return <API key>;
}
else {
return wsdMethod.<API key>();
}
}
@Override
protected Map<WSDItem, Map<String, Double>> getDisambiguation(Collection<WSDItem> wsdItems,
String documentText)
throws <API key>
{
String <API key> = wsdMethod.getDisambiguation(documentText);
Map<String,String> mapping = getMapping(documentText, <API key>);
Map<WSDItem, Map<String, Double>> disambiguation = new HashMap<WSDItem, Map<String, Double>>();
Map<String, Double> senses;
for(WSDItem wsdItem : wsdItems){
senses = new HashMap<String, Double>();
if(mapping.containsKey(wsdItem.getCoveredText())){
senses.put(mapping.get(wsdItem.getCoveredText()), 1d);
}
disambiguation.put(wsdItem,senses);
}
return disambiguation;
}
static Map<String, String> getMapping( String documentText, String <API key>) throws <API key>
{
Map<String, String> mapping = new HashMap<String, String>();
//Todo This mapping should be improved
String[] words = documentText.replaceAll("\n", "").replaceAll("\\.", " ").replaceAll(" ", " ").split(" ");
String[] senses = <API key>.replaceAll("\n", "").replaceAll("\\.", " ").replaceAll(" ", " ").split(" ");
// System.out.println(StringUtils.join(words, ","));
// System.out.println(StringUtils.join(senses, ","));
if(words.length != senses.length){
throw new <API key>("Mapping from IMS to WSDItems cannot be performed.");
}
//Lucy is in the sky with diamonds.
//1x05x00xx 2x42x03xx in the 1x17x00xx with 1x21x00xx .
for(int n=0;n<words.length;n++){
if(!words[n].equalsIgnoreCase(senses[n])){
mapping.put(words[n], senses[n]);
}
}
return mapping;
}
} |
#include "ml.h"
#include <stdio.h>
/*
The sample demonstrates how to use different decision trees.
*/
void print_result(float train_err, float test_err, const CvMat* var_imp)
{
printf( "train error %f\n", train_err );
printf( "test error %f\n\n", test_err );
if (var_imp)
{
bool is_flt = false;
if ( CV_MAT_TYPE( var_imp->type ) == CV_32FC1)
is_flt = true;
printf( "variable impotance\n" );
for( int i = 0; i < var_imp->cols; i++)
{
printf( "%d %f\n", i, is_flt ? var_imp->data.fl[i] : var_imp->data.db[i] );
}
}
printf("\n");
}
int main()
{
const int train_sample_count = 300;
//#define LEPIOTA
#ifdef LEPIOTA
const char* filename = "../../../OpenCV/samples/c/agaricus-lepiota.data";
#else
const char* filename = "../../../OpenCV/samples/c/waveform.data";
#endif
CvDTree dtree;
CvBoost boost;
CvRTrees rtrees;
CvERTrees ertrees;
CvMLData data;
CvTrainTestSplit spl( train_sample_count );
if ( data.read_csv( filename ) == 0)
{
#ifdef LEPIOTA
data.set_response_idx( 0 );
#else
data.set_response_idx( 21 );
data.change_var_type( 21, CV_VAR_CATEGORICAL );
#endif
data.<API key>( &spl );
printf("======DTREE=====\n");
dtree.train( &data, CvDTreeParams( 10, 2, 0, false, 16, 0, false, false, 0 ));
print_result( dtree.calc_error( &data, CV_TRAIN_ERROR), dtree.calc_error( &data, CV_TEST_ERROR ), dtree.get_var_importance() );
#ifdef LEPIOTA
printf("======BOOST=====\n");
boost.train( &data, CvBoostParams(CvBoost::DISCRETE, 100, 0.95, 2, false, 0));
print_result( boost.calc_error( &data, CV_TRAIN_ERROR ), boost.calc_error( &data ), 0 );
#endif
printf("======RTREES=====\n");
rtrees.train( &data, CvRTParams( 10, 2, 0, false, 16, 0, true, 0, 100, 0, CV_TERMCRIT_ITER ));
print_result( rtrees.calc_error( &data, CV_TRAIN_ERROR), rtrees.calc_error( &data, CV_TEST_ERROR ), rtrees.get_var_importance() );
printf("======ERTREES=====\n");
ertrees.train( &data, CvRTParams( 10, 2, 0, false, 16, 0, true, 0, 100, 0, CV_TERMCRIT_ITER ));
print_result( ertrees.calc_error( &data, CV_TRAIN_ERROR), ertrees.calc_error( &data, CV_TEST_ERROR ), ertrees.get_var_importance() );
}
else
printf("File can not be read");
return 0;
} |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>gSOAP <API key>: Class Members - Variables</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<!-- Generated by Doxygen 1.7.4 -->
<div id="top">
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">gSOAP <API key> <span id="projectnumber">2.8 Stable</span></div>
</td>
</tr>
</tbody>
</table>
</div>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li class="current"><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<div id="navrow3" class="tabs2">
<ul class="tablist">
<li><a href="functions.html"><span>All</span></a></li>
<li class="current"><a href="functions_vars.html"><span>Variables</span></a></li>
</ul>
</div>
<div id="navrow4" class="tabs3">
<ul class="tablist">
<li><a href="#index__"><span>_</span></a></li>
<li><a href="#index_a"><span>a</span></a></li>
<li><a href="#index_b"><span>b</span></a></li>
<li><a href="#index_d"><span>d</span></a></li>
<li><a href="#index_e"><span>e</span></a></li>
<li><a href="#index_f"><span>f</span></a></li>
<li><a href="#index_h"><span>h</span></a></li>
<li><a href="#index_i"><span>i</span></a></li>
<li><a href="#index_l"><span>l</span></a></li>
<li><a href="#index_m"><span>m</span></a></li>
<li><a href="#index_n"><span>n</span></a></li>
<li><a href="#index_o"><span>o</span></a></li>
<li><a href="#index_r"><span>r</span></a></li>
<li><a href="#index_s"><span>s</span></a></li>
<li><a href="#index_t"><span>t</span></a></li>
<li><a href="#index_u"><span>u</span></a></li>
<li><a href="#index_w"><span>w</span></a></li>
</ul>
</div>
</div>
<div class="contents">
 
<h3><a class="anchor" id="index__"></a>- _ -</h3><ul>
<li>__any
: <a class="el" href="<API key>.html#<API key>"><API key></a>
, <a class="el" href="<API key>.html#<API key>"><API key></a>
, <a class="el" href="<API key>.html#<API key>">wsa5__MetadataType</a>
, <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
<li>__anyAttribute
: <a class="el" href="<API key>.html#<API key>"><API key></a>
, <a class="el" href="<API key>.html#<API key>">wsa5__RelatesToType</a>
, <a class="el" href="<API key>.html#<API key>"><API key></a>
, <a class="el" href="<API key>.html#<API key>"><API key></a>
, <a class="el" href="<API key>.html#<API key>">wsa5__MetadataType</a>
</li>
<li>__item
: <a class="el" href="<API key>.html#<API key>">wsa5__RelatesToType</a>
</li>
<li>__size
: <a class="el" href="<API key>.html#<API key>">wsa5__MetadataType</a>
, <a class="el" href="<API key>.html#<API key>"><API key></a>
, <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
<li><API key>
: <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
<li>__sizeAckRequested
: <a class="el" href="<API key>.html#<API key>">SOAP_ENV__Header</a>
</li>
<li>__sizeNack
: <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
<li><API key>
: <a class="el" href="<API key>.html#<API key>">SOAP_ENV__Header</a>
</li>
</ul>
<h3><a class="anchor" id="index_a"></a>- a -</h3><ul>
<li>Accept
: <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
<li><API key>
: <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
<li>acksid
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_sequence</a>
</li>
<li>acksto
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_sequence</a>
</li>
<li>AcksTo
: <a class="el" href="<API key>.html#<API key>"><API key></a>
, <a class="el" href="<API key>.html#<API key>">wsrm__AcceptType</a>
</li>
<li>Action
: <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
<li>Address
: <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
</ul>
<h3><a class="anchor" id="index_b"></a>- b -</h3><ul>
<li>behavior
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_sequence</a>
</li>
<li>buf
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_content</a>
</li>
</ul>
<h3><a class="anchor" id="index_d"></a>- d -</h3><ul>
<li>Detail
: <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
</ul>
<h3><a class="anchor" id="index_e"></a>- e -</h3><ul>
<li>Endpoint
: <a class="el" href="<API key>.html#<API key>">wsrm__OfferType</a>
</li>
<li>expires
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_sequence</a>
</li>
<li>Expires
: <a class="el" href="<API key>.html#<API key>">wsrm__OfferType</a>
, <a class="el" href="<API key>.html#<API key>"><API key></a>
, <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
</ul>
<h3><a class="anchor" id="index_f"></a>- f -</h3><ul>
<li>fault
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_sequence</a>
</li>
<li>FaultCode
: <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
<li>fdisconnect
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_data</a>
</li>
<li>fheader
: <a class="el" href="<API key>.html#<API key>">soap_wsa_data</a>
</li>
<li>Final
: <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
<li>fpreparefinalrecv
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_data</a>
</li>
<li>fresponse
: <a class="el" href="<API key>.html#<API key>">soap_wsa_data</a>
</li>
<li>fsend
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_data</a>
</li>
<li>fseterror
: <a class="el" href="<API key>.html#<API key>">soap_wsa_data</a>
</li>
</ul>
<h3><a class="anchor" id="index_h"></a>- h -</h3><ul>
<li>handle
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_sequence</a>
</li>
</ul>
<h3><a class="anchor" id="index_i"></a>- i -</h3><ul>
<li>id
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_sequence</a>
</li>
<li>Identifier
: <a class="el" href="<API key>.html#<API key>">wsrm__SequenceType</a>
, <a class="el" href="<API key>.html#<API key>"><API key></a>
, <a class="el" href="<API key>.html#<API key>"><API key></a>
, <a class="el" href="<API key>.html#<API key>"><API key></a>
, <a class="el" href="<API key>.html#<API key>">wsrm__OfferType</a>
, <a class="el" href="<API key>.html#<API key>"><API key></a>
, <a class="el" href="<API key>.html#<API key>"><API key></a>
, <a class="el" href="<API key>.html#<API key>"><API key></a>
, <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
<li><API key>
: <a class="el" href="<API key>.html#<API key>"><API key></a>
, <a class="el" href="<API key>.html#<API key>">wsrm__OfferType</a>
</li>
</ul>
<h3><a class="anchor" id="index_l"></a>- l -</h3><ul>
<li>last
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_message</a>
</li>
<li>LastMsgNumber
: <a class="el" href="<API key>.html#<API key>"><API key></a>
, <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
<li>lastnum
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_sequence</a>
</li>
<li>len
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_content</a>
</li>
<li>list
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_message</a>
</li>
<li>lower
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_range</a>
</li>
<li>Lower
: <a class="el" href="struct__wsrm_____sequence_acknowledgement_1_1__wsrm_____sequence_acknowledgement___acknowledgement_range.html#<API key>"><API key>::<API key></a>
</li>
</ul>
<h3><a class="anchor" id="index_m"></a>- m -</h3><ul>
<li>MessageNumber
: <a class="el" href="<API key>.html#<API key>">wsrm__SequenceType</a>
</li>
<li>messages
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_sequence</a>
</li>
<li>Metadata
: <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
<li>msg
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_data</a>
</li>
</ul>
<h3><a class="anchor" id="index_n"></a>- n -</h3><ul>
<li>Nack
: <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
<li>next
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_message</a>
, <a class="el" href="<API key>.html#<API key>">soap_wsrm_range</a>
, <a class="el" href="<API key>.html#<API key>">soap_wsrm_sequence</a>
, <a class="el" href="<API key>.html#<API key>">soap_wsrm_content</a>
</li>
<li>None
: <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
<li>num
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_message</a>
, <a class="el" href="<API key>.html#<API key>">soap_wsrm_sequence</a>
</li>
</ul>
<h3><a class="anchor" id="index_o"></a>- o -</h3><ul>
<li>Offer
: <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
</ul>
<h3><a class="anchor" id="index_r"></a>- r -</h3><ul>
<li>ranges
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_sequence</a>
</li>
<li>ReferenceParameters
: <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
<li>RelationshipType
: <a class="el" href="<API key>.html#<API key>">wsa5__RelatesToType</a>
</li>
<li>retry
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_sequence</a>
</li>
</ul>
<h3><a class="anchor" id="index_s"></a>- s -</h3><ul>
<li>seq
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_data</a>
</li>
<li>SoapAction
: <a class="el" href="<API key>.html#<API key>"><API key></a>
</li>
<li>state
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_message</a>
, <a class="el" href="<API key>.html#<API key>">soap_wsrm_data</a>
, <a class="el" href="<API key>.html#<API key>">soap_wsrm_sequence</a>
</li>
</ul>
<h3><a class="anchor" id="index_t"></a>- t -</h3><ul>
<li>to
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_sequence</a>
</li>
</ul>
<h3><a class="anchor" id="index_u"></a>- u -</h3><ul>
<li>upper
: <a class="el" href="<API key>.html#<API key>">soap_wsrm_range</a>
</li>
<li>Upper
: <a class="el" href="struct__wsrm_____sequence_acknowledgement_1_1__wsrm_____sequence_acknowledgement___acknowledgement_range.html#<API key>"><API key>::<API key></a>
</li>
</ul>
<h3><a class="anchor" id="index_w"></a>- w -</h3><ul>
<li>wsa5__Action
: <a class="el" href="<API key>.html#<API key>">SOAP_ENV__Header</a>
</li>
<li>wsa5__FaultTo
: <a class="el" href="<API key>.html#<API key>">SOAP_ENV__Header</a>
</li>
<li>wsa5__From
: <a class="el" href="<API key>.html#<API key>">SOAP_ENV__Header</a>
</li>
<li>wsa5__MessageID
: <a class="el" href="<API key>.html#<API key>">SOAP_ENV__Header</a>
</li>
<li>wsa5__RelatesTo
: <a class="el" href="<API key>.html#<API key>">SOAP_ENV__Header</a>
</li>
<li>wsa5__ReplyTo
: <a class="el" href="<API key>.html#<API key>">SOAP_ENV__Header</a>
</li>
<li>wsa5__To
: <a class="el" href="<API key>.html#<API key>">SOAP_ENV__Header</a>
</li>
<li>wsrm__AckRequested
: <a class="el" href="<API key>.html#<API key>">SOAP_ENV__Header</a>
</li>
<li>wsrm__Sequence
: <a class="el" href="<API key>.html#<API key>">SOAP_ENV__Header</a>
</li>
<li><API key>
: <a class="el" href="<API key>.html#<API key>">SOAP_ENV__Header</a>
</li>
<li>wsrm__SequenceFault
: <a class="el" href="<API key>.html#<API key>">SOAP_ENV__Header</a>
</li>
</ul>
</div>
<hr class="footer"/><address class="footer"><small>Generated on Sat Oct 22 2011 15:04:50 for gSOAP <API key> by 
<a href="http:
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.4 </small></address>
</body>
</html> |
//! The generated content assignment phase.
//! done in parallel and is therefore a sequential pass that runs on as little of the flow tree
//! as possible.
use context::LayoutContext;
use flow::<API key>;
use flow::{self, AFFECTS_COUNTERS, Flow, <API key>, ImmutableFlowUtils};
use fragment::{Fragment, <API key>, <API key>, <API key>};
use gfx::display_list::OpaqueNode;
use <API key>::restyle_damage::{<API key>, RestyleDamage};
use <API key>::wrapper_traits::PseudoElementType;
use smallvec::SmallVec;
use std::collections::{HashMap, LinkedList};
use std::sync::Arc;
use style::computed_values::content::ContentItem;
use style::computed_values::{display, list_style_type};
use style::dom::TRestyleDamage;
use style::properties::{ComputedValues, ServoComputedValues};
use text::TextRunScanner;
static DECIMAL: [char; 10] = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ];
// TODO(pcwalton): `<API key>`
static ARABIC_INDIC: [char; 10] = [ '٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩' ];
// TODO(pcwalton): `armenian`, `upper-armenian`, `lower-armenian`
static BENGALI: [char; 10] = [ '০', '১', '২', '৩', '৪', '৫', '৬', '৭', '৮', '৯' ];
static CAMBODIAN: [char; 10] = [ '០', '១', '២', '៣', '៤', '៥', '៦', '៧', '៨', '៩' ];
// TODO(pcwalton): Suffix for CJK decimal.
static CJK_DECIMAL: [char; 10] = [ '', '', '', '', '', '', '', '', '', '' ];
static DEVANAGARI: [char; 10] = [ '०', '१', '२', '३', '४', '५', '६', '७', '८', '९' ];
// TODO(pcwalton): `georgian`
static GUJARATI: [char; 10] = ['૦', '૧', '૨', '૩', '૪', '૫', '૬', '૭', '૮', '૯'];
static GURMUKHI: [char; 10] = ['੦', '੧', '੨', '੩', '੪', '੫', '੬', '੭', '੮', '੯'];
// TODO(pcwalton): `hebrew`
static KANNADA: [char; 10] = ['೦', '೧', '೨', '೩', '೪', '೫', '೬', '೭', '೮', '೯'];
static LAO: [char; 10] = ['໐', '໑', '໒', '໓', '໔', '໕', '໖', '໗', '໘', '໙'];
static MALAYALAM: [char; 10] = ['൦', '൧', '൨', '൩', '൪', '൫', '൬', '൭', '൮', '൯'];
static MONGOLIAN: [char; 10] = ['᠐', '᠑', '᠒', '᠓', '᠔', '᠕', '᠖', '᠗', '᠘', '᠙'];
static MYANMAR: [char; 10] = ['၀', '၁', '၂', '၃', '၄', '၅', '၆', '၇', '၈', '၉'];
static ORIYA: [char; 10] = ['୦', '୧', '୨', '୩', '୪', '୫', '୬', '୭', '୮', '୯'];
static PERSIAN: [char; 10] = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
// TODO(pcwalton): `lower-roman`, `upper-roman`
static TELUGU: [char; 10] = ['౦', '౧', '౨', '౩', '౪', '౫', '౬', '౭', '౮', '౯'];
static THAI: [char; 10] = ['๐', '๑', '๒', '๓', '๔', '๕', '๖', '๗', '๘', '๙'];
static TIBETAN: [char; 10] = ['༠', '༡', '༢', '༣', '༤', '༥', '༦', '༧', '༨', '༩'];
static LOWER_ALPHA: [char; 26] = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z'
];
static UPPER_ALPHA: [char; 26] = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
];
static CJK_EARTHLY_BRANCH: [char; 12] = [
'', '', '', '', '', '', '', '', '', '', '', ''
];
static CJK_HEAVENLY_STEM: [char; 10] = [
'', '', '', '', '', '', '', '', '', ''
];
static LOWER_GREEK: [char; 24] = [
'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'ι', 'κ', 'λ', 'μ', 'ν', 'ξ', 'ο', 'π', 'ρ', 'σ', 'τ',
'υ', 'φ', 'χ', 'ψ', 'ω'
];
static HIRAGANA: [char; 48] = [
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', ''
];
static HIRAGANA_IROHA: [char; 47] = [
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', ''
];
static KATAKANA: [char; 48] = [
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', ''
];
static KATAKANA_IROHA: [char; 47] = [
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', ''
];
The generated content resolution traversal.
pub struct <API key><'a> {
The layout context.
layout_context: &'a LayoutContext<'a>,
The counter representing an ordered list item.
list_item: Counter,
Named CSS counters.
counters: HashMap<String, Counter>,
The level of quote nesting.
quote: u32,
}
impl<'a> <API key><'a> {
Creates a new generated content resolution traversal.
pub fn new(layout_context: &'a LayoutContext<'a>) -> <API key><'a> {
<API key> {
layout_context: layout_context,
list_item: Counter::new(),
counters: HashMap::new(),
quote: 0,
}
}
}
impl<'a> <API key> for <API key><'a> {
#[inline]
fn process(&mut self, flow: &mut Flow, level: u32) {
let mut mutator = <API key> {
traversal: self,
level: level,
is_block: flow.is_block_like(),
incremented: false,
};
flow.mutate_fragments(&mut |fragment| mutator.mutate_fragment(fragment))
}
#[inline]
fn should_process(&mut self, flow: &mut Flow) -> bool {
flow::base(flow).restyle_damage.intersects(<API key>) ||
flow::base(flow).flags.intersects(AFFECTS_COUNTERS | <API key>)
}
}
The object that mutates the generated content fragments.
struct <API key><'a,'b:'a> {
The traversal.
traversal: &'a mut <API key><'b>,
The level we're at in the flow tree.
level: u32,
Whether this flow is a block flow.
is_block: bool,
Whether we've incremented the counter yet.
incremented: bool,
}
impl<'a,'b> <API key><'a,'b> {
fn mutate_fragment(&mut self, fragment: &mut Fragment) {
// We only reset and/or increment counters once per flow. This avoids double-incrementing
// counters on list items (once for the main fragment and once for the marker).
if !self.incremented {
self.<API key>(fragment);
}
let mut list_style_type = fragment.style().get_list().list_style_type;
if fragment.style().get_box().display != display::T::list_item {
list_style_type = list_style_type::T::none
}
let mut new_info = None;
{
let info =
if let <API key>::GeneratedContent(ref mut info) = fragment.specific {
info
} else {
return
};
match **info {
<API key>::ListItem => {
new_info = self.traversal.list_item.render(self.traversal.layout_context,
fragment.node,
fragment.pseudo.clone(),
fragment.style.clone(),
list_style_type,
RenderingMode::Suffix(".\u{00a0}"))
}
<API key>::Empty |
<API key>::ContentItem(ContentItem::String(_)) => {
// Nothing to do here.
}
<API key>::ContentItem(ContentItem::Counter(ref counter_name,
counter_style)) => {
let temporary_counter = Counter::new();
let counter = self.traversal
.counters
.get(&*counter_name)
.unwrap_or(&temporary_counter);
new_info = counter.render(self.traversal.layout_context,
fragment.node,
fragment.pseudo.clone(),
fragment.style.clone(),
counter_style,
RenderingMode::Plain)
}
<API key>::ContentItem(ContentItem::Counters(ref counter_name,
ref separator,
counter_style)) => {
let temporary_counter = Counter::new();
let counter = self.traversal
.counters
.get(&*counter_name)
.unwrap_or(&temporary_counter);
new_info = counter.render(self.traversal.layout_context,
fragment.node,
fragment.pseudo,
fragment.style.clone(),
counter_style,
RenderingMode::All(&separator));
}
<API key>::ContentItem(ContentItem::OpenQuote) => {
new_info = render_text(self.traversal.layout_context,
fragment.node,
fragment.pseudo,
fragment.style.clone(),
self.quote(&*fragment.style, false));
self.traversal.quote += 1
}
<API key>::ContentItem(ContentItem::CloseQuote) => {
if self.traversal.quote >= 1 {
self.traversal.quote -= 1
}
new_info = render_text(self.traversal.layout_context,
fragment.node,
fragment.pseudo,
fragment.style.clone(),
self.quote(&*fragment.style, true));
}
<API key>::ContentItem(ContentItem::NoOpenQuote) => {
self.traversal.quote += 1
}
<API key>::ContentItem(ContentItem::NoCloseQuote) => {
if self.traversal.quote >= 1 {
self.traversal.quote -= 1
}
}
}
};
fragment.specific = match new_info {
Some(new_info) => new_info,
// If the fragment did not generate any content, replace it with a no-op placeholder
// so that it isn't processed again on the next layout. FIXME (mbrubeck): When
// processing an inline flow, this traversal should be allowed to insert or remove
// fragments. Then we can just remove these fragments rather than adding placeholders.
None => <API key>::GeneratedContent(box <API key>::Empty)
};
}
fn <API key>(&mut self, fragment: &mut Fragment) {
let mut list_style_type = fragment.style().get_list().list_style_type;
if !self.is_block || fragment.style().get_box().display != display::T::list_item {
list_style_type = list_style_type::T::none
}
match list_style_type {
list_style_type::T::disc | list_style_type::T::none | list_style_type::T::circle |
list_style_type::T::square | list_style_type::T::disclosure_open |
list_style_type::T::disclosure_closed => {}
_ => self.traversal.list_item.increment(self.level, 1),
}
// Truncate down counters.
for (_, counter) in &mut self.traversal.counters {
counter.truncate_to_level(self.level);
}
self.traversal.list_item.truncate_to_level(self.level);
for &(ref counter_name, value) in &fragment.style().get_counters().counter_reset.0 {
if let Some(ref mut counter) = self.traversal.counters.get_mut(counter_name) {
counter.reset(self.level, value);
continue
}
let mut counter = Counter::new();
counter.reset(self.level, value);
self.traversal.counters.insert((*counter_name).clone(), counter);
}
for &(ref counter_name, value) in &fragment.style().get_counters().counter_increment.0 {
if let Some(ref mut counter) = self.traversal.counters.get_mut(counter_name) {
counter.increment(self.level, value);
continue
}
let mut counter = Counter::new();
counter.increment(self.level, value);
self.traversal.counters.insert((*counter_name).clone(), counter);
}
self.incremented = true
}
fn quote(&self, style: &ServoComputedValues, close: bool) -> String {
let quotes = &style.get_list().quotes;
if quotes.0.is_empty() {
return String::new()
}
let &(ref open_quote, ref close_quote) =
if self.traversal.quote as usize >= quotes.0.len() {
quotes.0.last().unwrap()
} else {
"es.0[self.traversal.quote as usize]
};
if close {
close_quote.clone()
} else {
open_quote.clone()
}
}
}
A counter per CSS 2.1 § 12.4.
struct Counter {
The values at each level.
values: Vec<CounterValue>,
}
impl Counter {
fn new() -> Counter {
Counter {
values: Vec::new(),
}
}
fn reset(&mut self, level: u32, value: i32) {
// Do we have an instance of the counter at this level? If so, just mutate it.
if let Some(ref mut existing_value) = self.values.last_mut() {
if level == existing_value.level {
existing_value.value = value;
return
}
}
// Otherwise, push a new instance of the counter.
self.values.push(CounterValue {
level: level,
value: value,
})
}
fn truncate_to_level(&mut self, level: u32) {
if let Some(position) = self.values.iter().position(|value| value.level > level) {
self.values.truncate(position)
}
}
fn increment(&mut self, level: u32, amount: i32) {
if let Some(ref mut value) = self.values.last_mut() {
value.value += amount;
return
}
self.values.push(CounterValue {
level: level,
value: amount,
})
}
fn render(&self,
layout_context: &LayoutContext,
node: OpaqueNode,
pseudo: PseudoElementType<()>,
style: Arc<ServoComputedValues>,
list_style_type: list_style_type::T,
mode: RenderingMode)
-> Option<<API key>> {
let mut string = String::new();
match mode {
RenderingMode::Plain => {
let value = match self.values.last() {
Some(ref value) => value.value,
None => 0,
};
push_representation(value, list_style_type, &mut string)
}
RenderingMode::Suffix(suffix) => {
let value = match self.values.last() {
Some(ref value) => value.value,
None => 0,
};
push_representation(value, list_style_type, &mut string);
string.push_str(suffix)
}
RenderingMode::All(separator) => {
let mut first = true;
for value in &self.values {
if !first {
string.push_str(separator)
}
first = false;
push_representation(value.value, list_style_type, &mut string)
}
}
}
if string.is_empty() {
None
} else {
render_text(layout_context, node, pseudo, style, string)
}
}
}
How a counter value is to be rendered.
enum RenderingMode<'a> {
The innermost counter value is rendered with no extra decoration.
Plain,
The innermost counter value is rendered with the given string suffix.
Suffix(&'a str),
All values of the counter are rendered with the given separator string between them.
All(&'a str),
}
The value of a counter at a given level.
struct CounterValue {
The level of the flow tree that this corresponds to.
level: u32,
The value of the counter at this level.
value: i32,
}
Creates fragment info for a literal string.
fn render_text(layout_context: &LayoutContext,
node: OpaqueNode,
pseudo: PseudoElementType<()>,
style: Arc<ServoComputedValues>,
string: String)
-> Option<<API key>> {
let mut fragments = LinkedList::new();
let info = <API key>::UnscannedText(
box <API key>::new(string, None));
fragments.push_back(Fragment::<API key>(node,
pseudo,
style.clone(),
style,
RestyleDamage::rebuild_and_reflow(),
info));
// FIXME(pcwalton): This should properly handle multiple marker fragments. This could happen
// due to text run splitting.
let fragments = TextRunScanner::new().scan_for_runs(&mut layout_context.font_context(),
fragments);
if fragments.is_empty() {
None
} else {
Some(fragments.fragments.into_iter().next().unwrap().specific)
}
}
Appends string that represents the value rendered using the system appropriate for the given
`list-style-type` onto the given string.
fn push_representation(value: i32, list_style_type: list_style_type::T, accumulator: &mut String) {
match list_style_type {
list_style_type::T::none => {}
list_style_type::T::disc |
list_style_type::T::circle |
list_style_type::T::square |
list_style_type::T::disclosure_open |
list_style_type::T::disclosure_closed => {
accumulator.push(<API key>(list_style_type))
}
list_style_type::T::decimal => <API key>(value, &DECIMAL, accumulator),
list_style_type::T::arabic_indic => {
<API key>(value, &ARABIC_INDIC, accumulator)
}
list_style_type::T::bengali => <API key>(value, &BENGALI, accumulator),
list_style_type::T::cambodian | list_style_type::T::khmer => {
<API key>(value, &CAMBODIAN, accumulator)
}
list_style_type::T::cjk_decimal => {
<API key>(value, &CJK_DECIMAL, accumulator)
}
list_style_type::T::devanagari => {
<API key>(value, &DEVANAGARI, accumulator)
}
list_style_type::T::gujarati => <API key>(value, &GUJARATI, accumulator),
list_style_type::T::gurmukhi => <API key>(value, &GURMUKHI, accumulator),
list_style_type::T::kannada => <API key>(value, &KANNADA, accumulator),
list_style_type::T::lao => <API key>(value, &LAO, accumulator),
list_style_type::T::malayalam => {
<API key>(value, &MALAYALAM, accumulator)
}
list_style_type::T::mongolian => {
<API key>(value, &MONGOLIAN, accumulator)
}
list_style_type::T::myanmar => <API key>(value, &MYANMAR, accumulator),
list_style_type::T::oriya => <API key>(value, &ORIYA, accumulator),
list_style_type::T::persian => <API key>(value, &PERSIAN, accumulator),
list_style_type::T::telugu => <API key>(value, &TELUGU, accumulator),
list_style_type::T::thai => <API key>(value, &THAI, accumulator),
list_style_type::T::tibetan => <API key>(value, &TIBETAN, accumulator),
list_style_type::T::lower_alpha => {
<API key>(value, &LOWER_ALPHA, accumulator)
}
list_style_type::T::upper_alpha => {
<API key>(value, &UPPER_ALPHA, accumulator)
}
list_style_type::T::cjk_earthly_branch => {
<API key>(value, &CJK_EARTHLY_BRANCH, accumulator)
}
list_style_type::T::cjk_heavenly_stem => {
<API key>(value, &CJK_HEAVENLY_STEM, accumulator)
}
list_style_type::T::lower_greek => {
<API key>(value, &LOWER_GREEK, accumulator)
}
list_style_type::T::hiragana => {
<API key>(value, &HIRAGANA, accumulator)
}
list_style_type::T::hiragana_iroha => {
<API key>(value, &HIRAGANA_IROHA, accumulator)
}
list_style_type::T::katakana => {
<API key>(value, &KATAKANA, accumulator)
}
list_style_type::T::katakana_iroha => {
<API key>(value, &KATAKANA_IROHA, accumulator)
}
}
}
Returns the static character that represents the value rendered using the given list-style, if
possible.
pub fn <API key>(list_style_type: list_style_type::T) -> char {
match list_style_type {
list_style_type::T::disc => '•',
list_style_type::T::circle => '',
list_style_type::T::square => '',
list_style_type::T::disclosure_open => '',
list_style_type::T::disclosure_closed => '‣',
_ => panic!("No static representation for this list-style-type!"),
}
}
Pushes the string that represents the value rendered using the given *alphabetic system* onto
the accumulator per CSS-COUNTER-STYLES § 3.1.4.
fn <API key>(value: i32, system: &[char], accumulator: &mut String) {
let mut abs_value = <API key>(value, accumulator);
let mut string: SmallVec<[char; 8]> = SmallVec::new();
while abs_value != 0 {
// Step 1.
abs_value = abs_value - 1;
// Step 2.
string.push(system[abs_value % system.len()]);
// Step 3.
abs_value = abs_value / system.len();
}
accumulator.extend(string.iter().cloned().rev())
}
Pushes the string that represents the value rendered using the given *numeric system* onto the
accumulator per CSS-COUNTER-STYLES § 3.1.5.
fn <API key>(value: i32, system: &[char], accumulator: &mut String) {
let mut abs_value = <API key>(value, accumulator);
// Step 1.
if abs_value == 0 {
accumulator.push(system[0]);
return
}
// Step 2.
let mut string: SmallVec<[char; 8]> = SmallVec::new();
while abs_value != 0 {
// Step 2.1.
string.push(system[abs_value % system.len()]);
// Step 2.2.
abs_value = abs_value / system.len();
}
// Step 3.
accumulator.extend(string.iter().cloned().rev())
}
If the system uses a negative sign, handle negative values per CSS-COUNTER-STYLES § 2.
Returns the absolute value of the counter.
fn <API key>(value: i32, accumulator: &mut String) -> usize {
// 3. If the counter value is negative and the counter style uses a negative sign, instead
// generate an initial representation using the absolute value of the counter value.
if value < 0 {
// TODO: Support different negative signs using the 'negative' descriptor.
// https://drafts.csswg.org/date/2015-07-16/css-counter-styles/#<API key>
accumulator.push('-');
value.abs() as usize
} else {
value as usize
}
} |
// This file is part of libigl, a simple c++ geometry processing library.
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
#ifndef IGL_BBW_H
#define IGL_BBW_H
#include "igl_inline.h"
#include <Eigen/Dense>
#include <igl/active_set.h>
namespace igl
{
// Container for BBW computation related data and flags
class BBWData
{
public:
// Enforce partition of unity during optimization (optimize all weight
// simultaneously)
bool partition_unity;
// Initial guess
Eigen::MatrixXd W0;
igl::active_set_params active_set_params;
// Verbosity level
// 0: quiet
// 1: loud
// 2: louder
int verbosity;
public:
IGL_INLINE BBWData();
// Print current state of object
IGL_INLINE void print();
};
// Compute Bounded Biharmonic Weights on a given domain (V,Ele) with a given
// set of boundary conditions
// Templates
// DerivedV derived type of eigen matrix for V (e.g. MatrixXd)
// DerivedF derived type of eigen matrix for F (e.g. MatrixXi)
// Derivedb derived type of eigen matrix for b (e.g. VectorXi)
// Derivedbc derived type of eigen matrix for bc (e.g. MatrixXd)
// DerivedW derived type of eigen matrix for W (e.g. MatrixXd)
// Inputs:
// V #V by dim vertex positions
// Ele #Elements by simplex-size list of element indices
// b #b boundary indices into V
// bc #b by #W list of boundary values
// data object containing options, intial guess --> solution and results
// Outputs:
// W #V by #W list of *unnormalized* weights to normalize use
// igl::normalize_row_sums(W,W);
// Returns true on success, false on failure
template <
typename DerivedV,
typename DerivedEle,
typename Derivedb,
typename Derivedbc,
typename DerivedW>
IGL_INLINE bool bbw(
const Eigen::PlainObjectBase<DerivedV> & V,
const Eigen::PlainObjectBase<DerivedEle> & Ele,
const Eigen::PlainObjectBase<Derivedb> & b,
const Eigen::PlainObjectBase<Derivedbc> & bc,
BBWData & data,
Eigen::PlainObjectBase<DerivedW> & W);
}
#ifndef IGL_STATIC_LIBRARY
# include "bbw.cpp"
#endif
#endif |
<!DOCTYPE html>
<!-- DO NOT EDIT! This test has been generated by tools/gentest.py. -->
<title>Canvas test: 2d.path.rect.zero.1</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/2dcontext/resources/canvas-tests.js"></script>
<link rel="stylesheet" href="/2dcontext/resources/canvas-tests.css">
<body class="show_output">
<h1>2d.path.rect.zero.1</h1>
<p class="desc"></p>
<p class="output">Actual output:</p>
<canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas>
<p class="output expectedtext">Expected output:<p><img src="/images/green-100x50.png" class="output expected" id="expected" alt="">
<ul id="d"></ul>
<script>
var t = async_test("");
_addTest(function(canvas, ctx) {
ctx.fillStyle = '#f00';
ctx.fillRect(0, 0, 100, 50);
ctx.strokeStyle = '#0f0';
ctx.lineWidth = 100;
ctx.beginPath();
ctx.rect(0, 50, 100, 0);
ctx.stroke();
_assertPixel(canvas, 50,25, 0,255,0,255, "50,25", "0,255,0,255");
});
</script> |
# This Source Code Form is subject to the terms of the Mozilla Public
import pytest
from pages.firefox.desktop.desktop import DesktopPage
@pytest.mark.skip_if_firefox(reason='Download button is not shown for up-to-date Firefox browsers.')
@pytest.mark.smoke
@pytest.mark.nondestructive
def <API key>(base_url, selenium):
page = DesktopPage(selenium, base_url).open()
page.<API key>()
assert page.<API key>.is_displayed |
<!DOCTYPE HTML>
<html>
<!
https://bugzilla.mozilla.org/show_bug.cgi?id=691215
<head>
<title>Test for Bug 691215</title>
<script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
</head>
<body>
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=691215">Mozilla Bug 691215</a>
<p id="display"></p>
<div id="content" style="display: none">
</div>
<pre id="test">
<script type="application/javascript">
/** Test for Bug 691215 **/
SimpleTest.<API key>();
var url = "data:text/xml,<root/>";
var w;
addLoadEvent(function() {
// Need a separate window because we do not prettyprint in iframes. This is
// why this test can't be a crashtest.
w = window.open(url);
// Need to poll for load completion, sadly
setTimeout(checker, 0);
});
function checker() {
if (w.location.href != url ||
w.document.readyState != "complete") {
setTimeout(checker, 0);
return;
}
var doc = w.document;
var n = doc.createElement("span");
doc.replaceChild(n, doc.documentElement);
w.close();
ok(1, "Hey, we got here, that's good");
SimpleTest.finish();
}
</script>
</pre>
</body>
</html> |
assertEq(Math.cbrt(1), 1);
assertEq(Math.cbrt(-1), -1);
var sloppy_tolerance = 200; // FIXME
assertNear(Math.cbrt(1e-300), 1e-100, sloppy_tolerance);
assertNear(Math.cbrt(-1e-300), -1e-100, sloppy_tolerance);
var cbrt_data = [
[ Math.E, 1.3956124250860895 ],
[ Math.PI, 1.4645918875615231 ],
[ Math.LN2, 0.8849970445005177 ],
[ Math.SQRT2, 1.1224620483093728 ]
];
for (var [x, y] of cbrt_data)
assertNear(Math.cbrt(x), y, sloppy_tolerance);
reportCompare(0, 0, "ok"); |
package vault
import (
"bytes"
"testing"
"github.com/hashicorp/vault/physical"
)
// mockBarrier returns a physical backend, security barrier, and master key
func mockBarrier(t *testing.T) (physical.Backend, SecurityBarrier, []byte) {
inm := physical.NewInmem()
b, err := NewAESGCMBarrier(inm)
if err != nil {
t.Fatalf("err: %v", err)
}
// Initialize and unseal
key, _ := b.GenerateKey()
b.Initialize(key)
b.Unseal(key)
return inm, b, key
}
func <API key>(t *testing.T) {
inm := physical.NewInmem()
b, err := NewAESGCMBarrier(inm)
if err != nil {
t.Fatalf("err: %v", err)
}
testBarrier(t, b)
}
// Verify data sent through is encrypted
func <API key>(t *testing.T) {
inm := physical.NewInmem()
b, err := NewAESGCMBarrier(inm)
if err != nil {
t.Fatalf("err: %v", err)
}
// Initialize and unseal
key, _ := b.GenerateKey()
b.Initialize(key)
b.Unseal(key)
// Put a logical entry
entry := &Entry{Key: "test", Value: []byte("test")}
err = b.Put(entry)
if err != nil {
t.Fatalf("err: %v", err)
}
// Check the physcial entry
pe, err := inm.Get("test")
if err != nil {
t.Fatalf("err: %v", err)
}
if pe == nil {
t.Fatalf("missing physical entry")
}
if pe.Key != "test" {
t.Fatalf("bad: %#v", pe)
}
if bytes.Equal(pe.Value, entry.Value) {
t.Fatalf("bad: %#v", pe)
}
}
// Verify data sent through is cannot be tampered
func <API key>(t *testing.T) {
inm := physical.NewInmem()
b, err := NewAESGCMBarrier(inm)
if err != nil {
t.Fatalf("err: %v", err)
}
// Initialize and unseal
key, _ := b.GenerateKey()
b.Initialize(key)
b.Unseal(key)
// Put a logical entry
entry := &Entry{Key: "test", Value: []byte("test")}
err = b.Put(entry)
if err != nil {
t.Fatalf("err: %v", err)
}
// Change a byte in the underlying physical entry
pe, _ := inm.Get("test")
pe.Value[15]++
err = inm.Put(pe)
if err != nil {
t.Fatalf("err: %v", err)
}
// Read from the barrier
_, err = b.Get("test")
if err == nil {
t.Fatalf("should fail!")
}
} |
# Contexts
You may have noticed that there are several different types of "context" classes
in JeroMQ.
## tl;dr: Which one do I use?
Use ZContext. It is the current state of the art for JeroMQ.
## zmq.Ctx
[Ctx][ctx], part of the zmq package, contains low-level implementation details
of a ZeroMQ context.
It should not be used directly in code that uses the JeroMQ library.
## org.zeromq.ZMQ.Context
[ZMQ.Context][zmq-context] was the first cut at a higher-level API for a ZeroMQ
context.
Before destroying a ZMQ.Context, care must be taken to close any
[sockets](sockets.md) and [pollers](pollers.md) that may have been created via
the context. ZContext, by comparison, does this for you.
## org.zeromq.ZContext
[ZContext][zcontext] is an improvement over ZMQ.Context, lending itself to more
concise, convenient, and safe usage.
ZContext implements the [java.io.Closable][closable] interface, which makes it
convenient to use in a [try-with-resources statement][try-with-resources]. When
a ZContext is closed, resources such as sockets and pollers are cleaned up
automatically.
## See also
* [zguide: Getting the Context Right][zguide-contexts]: general information
about contexts in ZeroMQ
* [ZSocket][zsocket]: The next evolution of contexts (or lack thereof) in
ZeroMQ?
[ctx]: http://static.javadoc.io/org.zeromq/jeromq/0.4.3/zmq/Ctx.html
[zmq-context]: http://static.javadoc.io/org.zeromq/jeromq/0.4.3/org/zeromq/ZMQ.Context.html
[zcontext]: http://static.javadoc.io/org.zeromq/jeromq/0.4.3/org/zeromq/ZContext.html
[closable]: https://docs.oracle.com/javase/7/docs/api/java/io/Closeable.html
[try-with-resources]: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
[zguide-contexts]: http://zguide.zeromq.org/page:all#<API key>
[zsocket]: http://static.javadoc.io/org.zeromq/jeromq/0.4.3/org/zeromq/ZSocket.html |
<!DOCTYPE HTML PUBLIC "-
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>http:
<link href="activity-home.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css">
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<script type="text/javascript" src="DOMTestCase.js"></script>
<script type="text/javascript" src="exclusions.js"></script>
<script type="text/javascript">
// expose test function names
function <API key>()
{
return ['hc_nodevalue05'];
}
var docsLoaded = -1000000;
var builder = null;
// This function is called by the testing framework before
// running the test suite.
// If there are no configuration exceptions, asynchronous
// document loading is started. Otherwise, the status
// is set to complete and the exception is immediately
// raised when entering the body of the test.
function setUpPage() {
setUpPageStatus = 'running';
try {
// creates test document builder, may throw exception
builder = <API key>();
docsLoaded = 0;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
docsLoaded += preload(docRef, "doc", "hc_staff");
if (docsLoaded == 1) {
setUpPage = 'complete';
}
} catch(ex) {
<API key>(builder, ex);
setUpPage = 'complete';
}
}
// This method is called on the completion of
// each asychronous load started in setUpTests.
// When every synchronous loaded document has completed,
// the page status is changed which allows the
// body of the test to be executed.
function loadComplete() {
if (++docsLoaded == 1) {
setUpPageStatus = 'complete';
runJSUnitTests();
markTodos();
SimpleTest.finish();
}
}
var docName = 'hc_nodevalue05';
window.doc = window;
SimpleTest.<API key>();
addLoadEvent(setUpPage);
function hc_nodevalue05() {
var success;
if(checkInitialization(builder, "hc_nodevalue05") != null) return;
var doc;
var newNode;
var newValue;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
doc = load(docRef, "doc", "hc_staff");
newNode = doc.<API key>();
newValue = newNode.nodeValue;
assertNull("initiallyNull",newValue);
newNode.nodeValue = "This should have no effect";
newValue = newNode.nodeValue;
assertNull("<API key>",newValue);
}
</script>
</head>
<body>
<h2>Test http:
<p></p>
<p>
Copyright (c) 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the <a href="http:
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</p>
<iframe name="doc" src="files/hc_staff.html"></iframe>
<br>
</body>
</html> |
<!DOCTYPE html>
<!-- DO NOT EDIT! This test has been generated by tools/gentest.py. -->
<title>Canvas test: 2d.composite.solid.source-out</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/2dcontext/resources/canvas-tests.js"></script>
<link rel="stylesheet" href="/2dcontext/resources/canvas-tests.css">
<body class="show_output">
<h1>2d.composite.solid.source-out</h1>
<p class="desc"></p>
<p class="output">Actual output:</p>
<canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas>
<p class="output expectedtext">Expected output:<p><img src="2d.composite.solid.source-out.png" class="output expected" id="expected" alt="">
<ul id="d"></ul>
<script>
var t = async_test("");
_addTest(function(canvas, ctx) {
ctx.fillStyle = 'rgba(0, 255, 255, 1.0)';
ctx.fillRect(0, 0, 100, 50);
ctx.<API key> = 'source-out';
ctx.fillStyle = 'rgba(255, 255, 0, 1.0)';
ctx.fillRect(0, 0, 100, 50);
_assertPixelApprox(canvas, 50,25, 0,0,0,0, "50,25", "0,0,0,0", 5);
});
</script> |
<!DOCTYPE html>
<!-- DO NOT EDIT! Generated by <API key>/generic/tools/generate.py using common/security-features/tools/template/test.release.html.template. -->
<html>
<head>
<title><API key>: No <API key></title>
<meta charset='utf-8'>
<meta name="description" content="No <API key>">
<link rel="author" title="Kristijan Burnik" href="burnik@chromium.org">
<link rel="help" href="https://w3c.github.io/<API key>/">
<meta name="assert" content="<API key>: Expects blocked for iframe-tag to <API key> origin and no-redirect redirection from https context.">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/security-features/resources/common.sub.js"></script>
<script src="/<API key>/generic/test-case.sub.js"></script>
</head>
<body>
<script>
TestCase(
{
"expectation": "blocked",
"origin": "<API key>",
"redirection": "no-redirect",
"source_context_list": [],
"source_scheme": "https",
"subresource": "iframe-tag",
"<API key>": []
},
document.querySelector("meta[name=assert]").content,
new SanityChecker()
).start();
</script>
<div id="log"></div>
</body>
</html> |
import Helper from '@ember/component/helper';
import { formatHertz } from 'nomad-ui/utils/units';
/**
* Hertz Formatter
*
* Usage: {{format-hertz hertz}}
*
* Outputs the frequency reduced to the largest supported unit size for which
* the resulting number is larger than one.
*/
function formatHertzHelper([hertz], { start }) {
return formatHertz(hertz, start || 'MHz');
}
export default Helper.helper(formatHertzHelper); |
// Code generated by "<API key> -type MachineImageFilter"; DO NOT EDIT.
package triton
import (
"github.com/hashicorp/hcl/v2/hcldec"
"github.com/zclconf/go-cty/cty"
)
// <API key> is an auto-generated flat version of MachineImageFilter.
// Where the contents of a field with a `mapstructure:,squash` tag are bubbled up.
type <API key> struct {
MostRecent *bool `mapstructure:"most_recent" cty:"most_recent"`
Name *string `cty:"name"`
OS *string `cty:"os"`
Version *string `cty:"version"`
Public *bool `cty:"public"`
State *string `cty:"state"`
Owner *string `cty:"owner"`
Type *string `cty:"type"`
}
// FlatMapstructure returns a new <API key>.
// <API key> is an auto-generated flat version of MachineImageFilter.
// Where the contents a fields with a `mapstructure:,squash` tag are bubbled up.
func (*MachineImageFilter) FlatMapstructure() interface{ HCL2Spec() map[string]hcldec.Spec } {
return new(<API key>)
}
// HCL2Spec returns the hcl spec of a MachineImageFilter.
// This spec is used by HCL to read the fields of MachineImageFilter.
// The decoded values from this spec will then be applied to a <API key>.
func (*<API key>) HCL2Spec() map[string]hcldec.Spec {
s := map[string]hcldec.Spec{
"most_recent": &hcldec.AttrSpec{Name: "most_recent", Type: cty.Bool, Required: false},
"name": &hcldec.AttrSpec{Name: "name", Type: cty.String, Required: false},
"os": &hcldec.AttrSpec{Name: "os", Type: cty.String, Required: false},
"version": &hcldec.AttrSpec{Name: "version", Type: cty.String, Required: false},
"public": &hcldec.AttrSpec{Name: "public", Type: cty.Bool, Required: false},
"state": &hcldec.AttrSpec{Name: "state", Type: cty.String, Required: false},
"owner": &hcldec.AttrSpec{Name: "owner", Type: cty.String, Required: false},
"type": &hcldec.AttrSpec{Name: "type", Type: cty.String, Required: false},
}
return s
} |
package virtualbox
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/mitchellh/multistep"
"github.com/mitchellh/packer/builder/common"
"github.com/mitchellh/packer/packer"
"io"
"io/ioutil"
"log"
"os"
"strings"
"time"
)
var additionsVersionMap = map[string]string{
"4.2.1": "4.2.0",
"4.1.23": "4.1.22",
}
// This step uploads a file containing the VirtualBox version, which
// can be useful for various provisioning reasons.
// Produces:
// <API key> string - Path to the guest additions.
type <API key> struct{}
func (s *<API key>) Run(state map[string]interface{}) multistep.StepAction {
var action multistep.StepAction
cache := state["cache"].(packer.Cache)
driver := state["driver"].(Driver)
ui := state["ui"].(packer.Ui)
config := state["config"].(*config)
// Get VBox version
version, err := driver.Version()
if err != nil {
state["error"] = fmt.Errorf("Error reading version for guest additions download: %s", err)
return multistep.ActionHalt
}
if newVersion, ok := additionsVersionMap[version]; ok {
log.Printf("Rewriting guest additions version: %s to %s", version, newVersion)
version = newVersion
}
additionsName := fmt.Sprintf("VBoxGuestAdditions_%s.iso", version)
// Use provided version or get it from virtualbox.org
var checksum string
if config.<API key> != "" {
checksum = config.<API key>
} else {
checksum, action = s.<API key>(state, version, additionsName)
if action != multistep.ActionContinue {
return action
}
}
checksumBytes, err := hex.DecodeString(checksum)
if err != nil {
state["error"] = fmt.Errorf("Couldn't decode checksum into bytes: %s", checksum)
return multistep.ActionHalt
}
// Use the provided source (URL or file path) or generate it
url := config.GuestAdditionsURL
if url == "" {
url = fmt.Sprintf(
"http://download.virtualbox.org/virtualbox/%s/%s",
version,
additionsName)
}
log.Printf("Guest additions URL: %s", url)
log.Printf("Acquiring lock to download the guest additions ISO.")
cachePath := cache.Lock(url)
defer cache.Unlock(url)
downloadConfig := &common.DownloadConfig{
Url: url,
TargetPath: cachePath,
Hash: sha256.New(),
Checksum: checksumBytes,
}
download := common.NewDownloadClient(downloadConfig)
ui.Say("Downloading VirtualBox guest additions. Progress will be shown periodically.")
state["<API key>"], action = s.progressDownload(download, state)
return action
}
func (s *<API key>) Cleanup(state map[string]interface{}) {}
func (s *<API key>) progressDownload(c *common.DownloadClient, state map[string]interface{}) (string, multistep.StepAction) {
ui := state["ui"].(packer.Ui)
var result string
downloadCompleteCh := make(chan error, 1)
// Start a goroutine to actually do the download...
go func() {
var err error
result, err = c.Get()
downloadCompleteCh <- err
}()
progressTicker := time.NewTicker(5 * time.Second)
defer progressTicker.Stop()
// A loop that handles showing progress as well as timing out and handling
// interrupts and all that.
DownloadWaitLoop:
for {
select {
case err := <-downloadCompleteCh:
if err != nil {
state["error"] = fmt.Errorf("Error downloading: %s", err)
return "", multistep.ActionHalt
}
break DownloadWaitLoop
case <-progressTicker.C:
ui.Message(fmt.Sprintf("Download progress: %d%%", c.PercentProgress()))
case <-time.After(1 * time.Second):
if _, ok := state[multistep.StateCancelled]; ok {
ui.Say("Interrupt received. Cancelling download...")
return "", multistep.ActionHalt
}
}
}
return result, multistep.ActionContinue
}
func (s *<API key>) <API key>(state map[string]interface{}, additionsVersion string, additionsName string) (string, multistep.StepAction) {
// First things first, we get the list of checksums for the files available
// for this version.
checksumsUrl := fmt.Sprintf("http://download.virtualbox.org/virtualbox/%s/SHA256SUMS", additionsVersion)
checksumsFile, err := ioutil.TempFile("", "packer")
if err != nil {
state["error"] = fmt.Errorf(
"Failed creating temporary file to store guest addition checksums: %s",
err)
return "", multistep.ActionHalt
}
defer os.Remove(checksumsFile.Name())
checksumsFile.Close()
downloadConfig := &common.DownloadConfig{
Url: checksumsUrl,
TargetPath: checksumsFile.Name(),
Hash: nil,
}
log.Printf("Downloading guest addition checksums: %s", checksumsUrl)
download := common.NewDownloadClient(downloadConfig)
checksumsPath, action := s.progressDownload(download, state)
if action != multistep.ActionContinue {
return "", action
}
// Next, we find the checksum for the file we're looking to download.
// It is an error if the checksum cannot be found.
checksumsF, err := os.Open(checksumsPath)
if err != nil {
state["error"] = fmt.Errorf("Error opening guest addition checksums: %s", err)
return "", multistep.ActionHalt
}
defer checksumsF.Close()
// We copy the contents of the file into memory. In general this file
// is quite small so that is okay. In the future, we probably want to
// use bufio and iterate line by line.
var contents bytes.Buffer
io.Copy(&contents, checksumsF)
checksum := ""
for _, line := range strings.Split(contents.String(), "\n") {
parts := strings.Fields(line)
log.Printf("Checksum file parts: %#v", parts)
if len(parts) != 2 {
// Bogus line
continue
}
if strings.HasSuffix(parts[1], additionsName) {
checksum = parts[0]
log.Printf("Guest additions checksum: %s", checksum)
break
}
}
if checksum == "" {
state["error"] = fmt.Errorf("The checksum for the file '%s' could not be found.", additionsName)
return "", multistep.ActionHalt
}
return checksum, multistep.ActionContinue
} |
package google
import (
"errors"
"fmt"
"strconv"
"testing"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func <API key>(t *testing.T) {
t.Parallel()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: <API key>,
Check: resource.<API key>(
<API key>("data.<API key>.available"),
),
},
},
})
}
func <API key>(n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Can't find zones data source: %s", n)
}
if rs.Primary.ID == "" {
return errors.New("zones data source ID not set.")
}
count, ok := rs.Primary.Attributes["names.
if !ok {
return errors.New("can't find 'names' attribute")
}
noOfNames, err := strconv.Atoi(count)
if err != nil {
return errors.New("failed to read number of zones")
}
if noOfNames < 2 {
return fmt.Errorf("expected at least 2 zones, received %d, this is most likely a bug",
noOfNames)
}
for i := 0; i < noOfNames; i++ {
idx := "names." + strconv.Itoa(i)
v, ok := rs.Primary.Attributes[idx]
if !ok {
return fmt.Errorf("zone list is corrupt (%q not found), this is definitely a bug", idx)
}
if len(v) < 1 {
return fmt.Errorf("Empty zone name (%q), this is definitely a bug", idx)
}
}
return nil
}
}
var <API key> = `
data "<API key>" "available" {}
` |
Release v1.6.9 (2016-12-30)
Service Client Updates
* `service/codedeploy`: Updates service API and documentation
* CodeDeploy will support Iam Session Arns in addition to Iam User Arns for on premise host authentication.
* `service/ecs`: Updates service API and documentation
* Amazon EC2 Container Service (ECS) now supports the ability to customize the placement of tasks on container instances.
* `aws/endpoints`: Updated Regions and Endpoints metadata.
Release v1.6.8 (2016-12-22)
Service Client Updates
* `service/apigateway`: Updates service API and documentation
* Amazon API Gateway is adding support for generating SDKs in more languages. This update introduces two new operations used to dynamically discover these SDK types and what configuration each type accepts.
* `service/directoryservice`: Updates service documentation
* Added code snippets for the DS SDKs
* `service/elasticbeanstalk`: Updates service API and documentation
* `service/iam`: Updates service API and documentation
* Adds service-specific credentials to IAM service to make it easier to onboard CodeCommit customers. These are username/password credentials that work with a single service.
* `service/kms`: Updates service API, documentation, and examples
* Update docs and add SDK examples
Release v1.6.7 (2016-12-22)
Service Client Updates
* `service/ecr`: Updates service API and documentation
* `aws/endpoints`: Updated Regions and Endpoints metadata.
* `service/rds`: Updates service API and documentation
* Cross Region Encrypted Snapshot Copying (CopyDBSnapshot)
Release v1.6.6 (2016-12-20)
Service Client Updates
* `aws/endpoints`: Updated Regions and Endpoints metadata.
* `service/firehose`: Updates service API, documentation, and examples
* Processing feature enables users to process and modify records before Amazon Firehose delivers them to destinations.
* `service/route53`: Updates service API and documentation
* Enum updates for eu-west-2 and ca-central-1
* `service/storagegateway`: Updates service API, documentation, and examples
* File gateway is a new mode in the AWS Storage Gateway that support a file interface into S3, alongside the current block-based volume and VTL storage. File gateway combines a service and virtual software appliance, enabling you to store and retrieve objects in Amazon S3 using industry standard file protocols such as NFS. The software appliance, or gateway, is deployed into your on-premises environment as a virtual machine (VM) running on VMware ESXi. The gateway provides access to objects in S3 as files on a Network File System (NFS) mount point.
Release v1.6.5 (2016-12-19)
Service Client Updates
* `service/cloudformation`: Updates service documentation
* Minor doc update for CloudFormation.
* `service/cloudtrail`: Updates service paginators
* `service/cognitoidentity`: Updates service API and documentation
* We are adding Groups to Cognito user pools. Developers can perform CRUD operations on groups, add and remove users from groups, list users in groups, etc. We are adding fine-grained role-based access control for Cognito identity pools. Developers can configure an identity pool to get the IAM role from an authenticated user's token, or they can configure rules that will map a user to a different role
* `service/<API key>`: Updates service API and documentation
* Adds new APIs to group discovered servers into Applications with get summary and neighbors. Includes additional filters for ListConfigurations and DescribeAgents API.
* `service/inspector`: Updates service API, documentation, and examples
* Doc-only Update for Inspector: Adding SDK code snippets for Inspector
* `service/sqs`: Updates service documentation
SDK Bug Fixes
* `aws/request`: Add <API key> to throttle retry codes (#1011)
* Fixes: Not retrying when <API key> #1009
SDK Feature
* `private/model/api`: Adds crosslinking to service documentation (#1010)
Release v1.6.4 (2016-12-15)
Service Client Updates
* `service/<API key>`: Updates service API and documentation
* `aws/endpoints`: Updated Regions and Endpoints metadata.
* `service/ssm`: Updates service API and documentation
* This will provide customers with access to the Patch Baseline and Patch Compliance APIs.
SDK Bug Fixes
* `service/route53`: Fix URL path cleaning for Route53 API requests (#1006)
* Fixes: SerializationError when using Route53 <API key> #1005
* `aws/request`: Add <API key> to throttle retry codes (#1002)
* Fixes: Not retrying when <API key> #1001
Release v1.6.3 (2016-12-14)
Service Client Updates
* `service/batch`: Adds new service
* AWS Batch is a batch computing service that lets customers define queues and compute environments and then submit work as batch jobs.
* `service/<API key>`: Updates service API and documentation
* Adds support for SSL enabled Oracle endpoints and task modification.
* `service/elasticbeanstalk`: Updates service documentation
* `aws/endpoints`: Updated Regions and Endpoints metadata.
* `service/cloudwatchlogs`: Updates service API and documentation
* Add support for associating LogGroups with AWSTagris tags
* `service/<API key>`: Updates service API and documentation
* Add new enum to DataSetType: <API key>
* `service/rds`: Updates service documentation
* Doc-only Update for RDS: New versions available in CreateDBInstance
* `service/sts`: Updates service documentation
* Adding Code Snippet Examples for SDKs for STS
SDK Bug Fixes
* `aws/request`: Fix retrying timeout requests (#981)
* Fixes: Requests Retrying is broken if the error was caused due to a client timeout #947
* `aws/request`: Fix for Go 1.8 request incorrectly sent with body (#991)
* Fixes: service/route53: ListHostedZones hangs and then fails with go1.8 #984
* private/protocol/rest: Use RawPath instead of Opaque (#993)
* Fixes: HTTP2 request failing with REST protocol services, e.g AWS X-Ray
* private/model/api: Generate REST-JSON JSONVersion correctly (#998)
* Fixes: REST-JSON protocol service code missing JSONVersion metadata.
Release v1.6.2 (2016-12-08)
Service Client Updates
* `service/cloudfront`: Add lambda function associations to cache behaviors
* `service/codepipeline`: This is a doc-only update request to incorporate some recent minor revisions to the doc content.
* `service/rds`: Updates service API and documentation
* `service/wafregional`: With this new feature, customers can use AWS WAF directly on Application Load Balancers in a VPC within available regions to protect their websites and web services from malicious attacks such as SQL injection, Cross Site Scripting, bad bots, etc.
Release v1.6.1 (2016-12-07)
Service Client Updates
* `service/config`: Updates service API
* `service/s3`: Updates service API
* `service/sqs`: Updates service API and documentation
Release v1.6.0 (2016-12-06)
Service Client Updates
* `service/config`: Updates service API and documentation
* `service/ec2`: Updates service API
* `service/sts`: Updates service API, documentation, and examples
SDK Bug Fixes
* private/protocol/xml/xmlutil: Fix SDK XML unmarshaler #975
* Fixes GetBucketACL Grantee required type always nil. #916
SDK Feature
* aws/endpoints: Add endpoint metadata to SDK #961
* Adds Region and Endpoint metadata to the SDK. This allows you to enumerate regions and endpoint metadata based on a defined model embedded in the SDK.
Release v1.5.13 (2016-12-01)
Service Client Updates
* `service/apigateway`: Updates service API and documentation
* `service/appstream`: Adds new service
* `service/codebuild`: Adds new service
* `service/directconnect`: Updates service API and documentation
* `service/ec2`: Adds new service
* `service/elasticbeanstalk`: Updates service API and documentation
* `service/health`: Adds new service
* `service/lambda`: Updates service API and documentation
* `service/opsworkscm`: Adds new service
* `service/pinpoint`: Adds new service
* `service/shield`: Adds new service
* `service/ssm`: Updates service API and documentation
* `service/states`: Adds new service
* `service/xray`: Adds new service
Release v1.5.12 (2016-11-30)
Service Client Updates
* `service/lightsail`: Adds new service
* `service/polly`: Adds new service
* `service/rekognition`: Adds new service
* `service/snowball`: Updates service API and documentation
Release v1.5.11 (2016-11-29)
Service Client Updates
`service/s3`: Updates service API and documentation
Release v1.5.10 (2016-11-22)
Service Client Updates
* `service/cloudformation`: Updates service API and documentation
* `service/glacier`: Updates service API, documentation, and examples
* `service/route53`: Updates service API and documentation
* `service/s3`: Updates service API and documentation
SDK Bug Fixes
* `private/protocol/xml/xmlutil`: Fixes xml marshaler to unmarshal properly
into tagged fields
[
Release v1.5.9 (2016-11-22)
Service Client Updates
* `service/cloudtrail`: Updates service API and documentation
* `service/ecs`: Updates service API and documentation
Release v1.5.8 (2016-11-18)
Service Client Updates
* `service/<API key>`: Updates service API and documentation
* `service/elasticmapreduce`: Updates service API and documentation
* `service/elastictranscoder`: Updates service API, documentation, and examples
* `service/gamelift`: Updates service API and documentation
* `service/lambda`: Updates service API and documentation
Release v1.5.7 (2016-11-18)
Service Client Updates
* `service/apigateway`: Updates service API and documentation
* `service/meteringmarketplace`: Updates service API and documentation
* `service/monitoring`: Updates service API and documentation
* `service/sqs`: Updates service API, documentation, and examples
Release v1.5.6 (2016-11-16)
Service Client Updates
`service/route53`: Updates service API and documentation
`service/servicecatalog`: Updates service API and documentation
Release v1.5.5 (2016-11-15)
Service Client Updates
* `service/ds`: Updates service API and documentation
* `service/elasticache`: Updates service API and documentation
* `service/kinesis`: Updates service API and documentation
Release v1.5.4 (2016-11-15)
Service Client Updates
* `service/cognito-idp`: Updates service API and documentation
Release v1.5.3 (2016-11-11)
Service Client Updates
* `service/cloudformation`: Updates service documentation and examples
* `service/logs`: Updates service API and documentation
Release v1.5.2 (2016-11-03)
Service Client Updates
* `service/directconnect`: Updates service API and documentation
Release v1.5.1 (2016-11-02)
Service Client Updates
* `service/email`: Updates service API and documentation
Release v1.5.0 (2016-11-01)
Service Client Updates
* `service/cloudformation`: Updates service API and documentation
* `service/ecr`: Updates service paginators
SDK Feature Updates
* `private/model/api`: Add generated setters for API parameters (#918)
* Adds setters to the SDK's API parameter types, and are a convenience method that reduce the need to use `aws.String` and like utility.
Release v1.4.22 (2016-10-25)
Service Client Updates
* `service/<API key>`: Updates service documentation.
* `service/autoscaling`: Updates service documentation.
Release v1.4.21 (2016-10-24)
Service Client Updates
* `service/sms`: AWS Server Migration Service (SMS) is an agentless service which makes it easier and faster for you to migrate thousands of on-premises workloads to AWS. AWS SMS allows you to automate, schedule, and track incremental replications of live server volumes, making it easier for you to coordinate large-scale server migrations.
* `service/ecs`: Updates documentation.
SDK Feature Updates
* `private/models/api`: Improve code generation of documentation.
Release v1.4.20 (2016-10-20)
Service Client Updates
* `service/budgets`: Adds new service, AWS Budgets.
* `service/waf`: Updates service documentation.
Release v1.4.19 (2016-10-18)
Service Client Updates
* `service/cloudfront`: Updates service API and documentation.
* Ability to use Amazon CloudFront to deliver your content both via IPv6 and IPv4 using HTTP/HTTPS.
* `service/configservice`: Update service API and documentation.
* `service/iot`: Updates service API and documentation.
* `service/kinesisanalytics`: Updates service API and documentation.
* Whenever Amazon Kinesis Analytics is not able to detect schema for the given streaming source on DiscoverInputSchema API, we would return the raw records that was sampled to detect the schema.
* `service/rds`: Updates service API and documentation.
* Amazon Aurora integrates with other AWS services to allow you to extend your Aurora DB cluster to utilize other capabilities in the AWS cloud. Permission to access other AWS services is granted by creating an IAM role with the necessary permissions, and then associating the role with your DB cluster.
SDK Feature Updates
* `service/dynamodb/dynamodbattribute`: Add UnmarshalListOfMaps #897
* Adds support for unmarshaling a list of maps. This is useful for unmarshaling the DynamoDB AttributeValue list of maps returned by APIs like Query and Scan.
Release v1.4.18 (2016-10-17)
Service Model Updates
* `service/route53`: Updates service API and documentation.
Release v1.4.17
Service Model Updates
* `service/acm`: Update service API, and documentation.
* This change allows users to import third-party SSL/TLS certificates into ACM.
* `service/elasticbeanstalk`: Update service API, documentation, and pagination.
* Elastic Beanstalk <API key> API is being updated to support pagination.
* `service/gamelift`: Update service API, and documentation.
* New APIs to protect game developer resource (builds, alias, fleets, instances, game sessions and player sessions) against abuse.
SDK Features
* `service/s3`: Add support for accelerate with dualstack [
Release v1.4.16 (2016-10-13)
Service Model Updates
* `service/ecr`: Update Amazon EC2 Container Registry service model
* DescribeImages is a new api used to expose image metadata which today includes image size and image creation timestamp.
* `service/elasticache`: Update Amazon ElastiCache service model
* Elasticache is launching a new major engine release of Redis, 3.2 (providing stability updates and new command sets over 2.8), as well as ElasticSupport for enabling Redis Cluster in 3.2, which provides support for multiple node groups to horizontally scale data, as well as superior engine failover capabilities
SDK Bug Fixes
* `aws/session`: Skip shared config on read errors [
* `aws/signer/v4`: Add support for URL.EscapedPath to signer [
SDK Features
* `private/model/api`: Add docs for errors to API operations [
* `private/model/api`: Improve field and waiter doc strings [
* `service/dynamodb/dynamodbattribute`: Allow multiple struct tag elements [
* Add build tags to internal SDK tools [
Release v1.4.15 (2016-10-06)
Service Model Updates
* `service/<API key>`: Update Amazon Cognito Identity Provider service model
* `service/devicefarm`: Update AWS Device Farm documentation
* `service/opsworks`: Update AWS OpsWorks service model
* `service/s3`: Update Amazon Simple Storage Service model
* `service/waf`: Update AWS WAF service model
SDK Bug Fixes
* `aws/request`: Fix HTTP Request Body race condition [
SDK Feature Updates
* `aws/ec2metadata`: Add support for EC2 User Data [
* `aws/signer/v4`: Remove logic determining if request needs to be resigned [
Release v1.4.14 (2016-09-29)
* `service/ec2`: api, documentation, and paginators updates.
* `service/s3`: api and documentation updates.
Release v1.4.13 (2016-09-27)
* `service/codepipeline`: documentation updates.
* `service/cloudformation`: api and documentation updates.
* `service/kms`: documentation updates.
* `service/elasticfilesystem`: documentation updates.
* `service/snowball`: documentation updates. |
import { compose } from 'redux';
import * as React from 'react';
import { <API key> } from 'core/utils/errors';
import Button from 'ui/components/Button';
import './styles.scss';
export class <API key> extends React.Component {
constructor(props) {
super(props);
this.state = {
buttonClicked: false,
throwRenderError: false,
};
}
onClick = () => {
this.setState({ buttonClicked: true });
setTimeout(() => this.setState({ buttonClicked: false }), 3000);
throw new Error('This is a simulated client error');
};
throwRenderError = () => {
this.setState({ throwRenderError: true });
};
render() {
const prompt = this.state.buttonClicked
? 'Nice! Check Sentry'
: ' Go ahead, trigger an error';
if (this.state.throwRenderError) {
throw new Error('This is a simulated client render error');
}
return (
<div className="SimulateClientError">
<div>
<p>
This page allows you to simulate client errors, mainly to test our
integration with Sentry. If Sentry is enabled (by configuring a
DSN), the errors produced by clicking the buttons should appear in
the interface.
</p>
<p>There are two available behaviors:</p>
<ul>
<li>
The grey button allows to throw an error in the button handler (
<code>onClick()</code>) and can be used multiple times. It throws
unhandled errors, which should be automatically logged by Sentry.
</li>
<li>
The red button allows to throw an error in the{' '}
<code>render()</code> method and is not recoverable because the
error will be handled in the <code>ErrorPage</code> component,
which should log the error with <code>log.error()</code>. On the
client, <code>log.error</code> is bound to{' '}
<code>console.error</code>, which should automatically send errors
to Sentry.
</li>
</ul>
</div>
<div>
<Button
buttonType="neutral"
className="<API key>"
onClick={this.onClick}
>
{prompt}
</Button>
<Button
buttonType="alert"
className="<API key>"
onClick={this.throwRenderError}
>
Trigger a render error
</Button>
</div>
</div>
);
}
}
export default compose(<API key>('<API key>'))(
<API key>,
); |
package com.temenos.interaction.media.odata.xml.atom;
import org.odata4j.format.xml.XmlFormatWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.temenos.interaction.core.hypermedia.<API key>;
import com.temenos.interaction.core.hypermedia.Link;
import com.temenos.interaction.core.hypermedia.ResourceState;
import com.temenos.interaction.core.hypermedia.Transition;
import com.temenos.interaction.core.resource.RESTResource;
public class <API key> implements LinkInterceptor {
private final Logger logger = LoggerFactory.getLogger(<API key>.class);
// this class uses AtomXMLProvider as a helper
private AtomXMLProvider providerHelper;
public <API key>(AtomXMLProvider providerHelper) {
this.providerHelper = providerHelper;
}
@Override
public Link addingLink(RESTResource resource, Link linkToAdd) {
if(resource == null) {
return null;
}
Link result = null;
String rel = "";
if(linkToAdd != null) {
logger.debug("Link rel["+linkToAdd.getRel()+"] title["+linkToAdd.getTitle()+"] href["+linkToAdd.getHref()+"]");
result = linkToAdd;
rel = <API key>(result, providerHelper.getEntitySet(result.getTransition().getTarget()));
} else {
logger.warn("Link to add was null for " + resource.getEntityName());
}
/*
* Identify 'self' link
*/
Link selfLink = null;
for (Link link : resource.getLinks()) {
if(link == null) {
logger.warn("Found null link for " + resource.getEntityName());
} else {
// prefer edit
if ((selfLink == null && ("self".equals(link.getRel()) || "edit".equals(link.getRel())))
|| (selfLink != null && !"edit".equals(selfLink.getRel()) && "edit".equals(link.getRel()))) {
selfLink = link;
}
}
}
if (selfLink != null && linkToAdd != null && !selfLink.equals(linkToAdd)
&& (linkToAdd.getRel().equals("item") || linkToAdd.getRel().equals("collection")
|| linkToAdd.getRel().equals("self") || linkToAdd.getRel().equals("edit"))
&& linkToAdd.getHref().equals(selfLink.getHref())) {
result = null;
}
/*
* Remove duplicate links (mainly for the 'edit' case)
*/
if (result != null) {
Link firstInstance = null;
for (Link link : resource.getLinks()) {
if(link != null) {
// is this the first instance of this rel/href combination
if (firstInstance != null
&& !firstInstance.equals(result)
&& rel.equals(link.getRel())
&& result.getHref().equals(link.getHref())) {
result = null;
break;
}
if (result.getRel().equals(link.getRel())
&& result.getHref().equals(link.getHref())) {
firstInstance = link;
}
}
}
}
if (result != null) {
result = new Link(result.getTransition(),
result.getTitle(),
rel,
result.getHref(),
result.getConsumes(),
result.getProduces(),
result.getMethod(),
result.getExtensions());
}
return result;
}
/**
* Return the OData link relation from the specified link.
* @param link link
* @return odata link rel
*/
public String <API key>(Link link, String entitySetName) {
String rel = link.getRel();
Transition transition = link.getTransition();
if(transition == null) {
return rel;
}
// hack, just until we fix this up
rel = rel.replace("item", "");
rel = rel.replace("collection", "");
// don't change the link relations if they have been specified in the RIM
if (rel.length() > 0)
return rel;
if (transition.<API key>() || (rel.equals("self") || rel.equals("edit"))) {
if (rel.length() == 0) {
//Links from collection to entity resource of an entity are considered 'self' links within an odata feed
rel = "self";
}
} else if (transition.getTarget() instanceof <API key>) {
rel = XmlFormatWriter.related + entitySetName + (rel != null && rel.length() > 0 ? " " : "") + rel;
} else if (transition.getTarget() instanceof ResourceState) {
//entry type relations should use the entityType name
rel = XmlFormatWriter.related + transition.getTarget().getEntityName() + (rel != null && rel.length() > 0 ? " " : "") + rel;
}
return rel;
}
} |
package scrum.client.files;
import scrum.client.common.ABlockWidget;
import scrum.client.common.AScrumAction;
import scrum.client.common.BlockHeaderWidget;
import scrum.client.common.BlockWidgetFactory;
import scrum.client.dnd.TrashSupport;
import com.google.gwt.user.client.ui.Widget;
public class FileBlock extends ABlockWidget<File> implements TrashSupport {
@Override
protected void <API key>(BlockHeaderWidget header) {
File file = getObject();
header.addText(file.getLabelModel());
header.addText(file.getUploadTimeModel(), true);
header.addMenuAction(new DeleteFileAction(file));
}
@Override
protected void onUpdateHeader(BlockHeaderWidget header) {
File file = getObject();
header.setDragHandle(file.getReference());
}
@Override
protected Widget <API key>() {
return new FileWidget(getObject());
}
@Override
public AScrumAction getTrashAction() {
return new DeleteFileAction(getObject());
}
public static final BlockWidgetFactory<File> FACTORY = new BlockWidgetFactory<File>() {
@Override
public FileBlock createBlock() {
return new FileBlock();
}
};
} |
# <API key>: false
module Spree
module Admin
module NavigationHelper
# Make an admin tab that coveres one or more resources supplied by symbols
# Option hash may follow. Valid options are
# * :label to override link text, otherwise based on the first resource name (translated)
# * :route to override automatically determining the default route
# * :match_path as an alternative way to control when the tab is active,
# /products would match /admin/products, /admin/products/5/variants etc.
# * :except_paths to reject subpaths that have their own menu,
# e.g. match_path = '/admin/orders', except_paths = ['/admin/orders/bulk_management']
def tab(*args)
options = { label: args.first.to_s }
if args.last.is_a?(Hash)
options = options.merge(args.last)
end
# Return if resource is found and user is not allowed to :admin
klass = klass_for(options[:label])
return '' if klass && cannot?(:admin, klass)
options[:route] ||= "admin_#{args.first}"
destination_url = options[:url] || spree.public_send("#{options[:route]}_path")
titleized_label = Spree.t(options[:label],
default: options[:label],
scope: [:admin, :tab]).titleize
css_classes = []
if options[:icon]
link = link_to_with_icon(options[:icon], titleized_label, destination_url)
css_classes << 'tab-with-icon'
else
link = link_to(titleized_label, destination_url)
end
selected = if options[:match_path]
PathChecker
.new(request.fullpath, self)
.active_path?(options[:match_path], options[:except_paths])
else
args.include?(controller.controller_name.to_sym)
end
css_classes << 'selected' if selected
if options[:css_class]
css_classes << options[:css_class]
end
content_tag('li', link, class: css_classes.join(' '))
end
# finds class for a given symbol / string
# Example :
# :products returns Spree::Product
# :my_products returns MyProduct if MyProduct is defined
# :my_products returns My::Product if My::Product is defined
# If it cannot constantize, it tries a collection of custom translations
# This allows us to use cancan abilities on tab
def klass_for(name)
model_name = name.to_s
klass = ["Spree::#{model_name.classify}",
model_name.classify,
model_name.tr('_', '/').classify].
find(&:safe_constantize).
try(:safe_constantize)
klass ||= name.singularize.to_sym
klass = :overview if klass == :dashboard
klass = Spree::Order if klass == :<API key>
klass = EnterpriseGroup if klass == :group
klass = VariantOverride if klass == :Inventory
klass = ProductImport::ProductImporter if klass == :import
klass = Spree::Admin::ReportsController if klass == :report
klass
end
def link_to_edit(resource, options = {})
options[:data] = { action: 'edit' }
link_to_with_icon('icon-edit', Spree.t(:edit), edit_object_url(resource), options)
end
def link_to_delete(resource, options = {})
url = options[:url] || object_url(resource)
name = options[:name] || I18n.t(:delete)
options[:class] = "delete-resource"
options[:data] = { confirm: I18n.t(:are_you_sure), action: 'remove' }
link_to_with_icon 'icon-trash', name, url, options
end
def link_to_with_icon(icon_name, text, url, options = {})
options[:class] = (options[:class].to_s + " icon_link with-tip #{icon_name}").strip
options[:class] += ' no-text' if options[:no_text]
options[:title] = text if options[:no_text]
text = options[:no_text] ? '' : raw("<span class='text'>#{text}</span>")
options.delete(:no_text)
link_to(text, url, options)
end
def icon(icon_name)
icon_name ? content_tag(:i, '', class: icon_name) : ''
end
def button(text, icon_name = nil, button_type = 'submit', options = {})
button_tag(text, options.merge(type: button_type, class: "#{icon_name} button"))
end
def button_link_to(text, url, html_options = {})
if html_options[:method] &&
html_options[:method].to_s.downcase != 'get' &&
!html_options[:remote]
form_tag(url, method: html_options.delete(:method)) do
button(text, html_options.delete(:icon), nil, html_options)
end
else
if html_options['data-update'].nil? && html_options[:remote]
object_name, action = url.split('/')[-2..-1]
html_options['data-update'] = [action, object_name.singularize].join('_')
end
html_options.delete('data-update') unless html_options['data-update']
html_options[:class] = 'button'
if html_options[:icon]
html_options[:class] += " #{html_options[:icon]}"
end
link_to(<API key>(text, html_options), url, html_options)
end
end
def <API key>(text, _html_options)
s = ''
s << text
raw(s)
end
def <API key>(link_text, url, options = {})
is_active = url.ends_with?(controller.controller_name) ||
url.ends_with?( "#{controller.controller_name}/edit")
options.merge!(class: is_active ? 'active' : nil)
content_tag(:li, options) do
link_to(link_text, url)
end
end
end
end
end |
package org.geomajas.plugin.printing.client.template;
import java.util.ArrayList;
import java.util.List;
import org.geomajas.configuration.FontStyleInfo;
import org.geomajas.configuration.client.ClientLayerInfo;
import org.geomajas.configuration.client.<API key>;
import org.geomajas.configuration.client.<API key>;
import org.geomajas.geometry.Coordinate;
import org.geomajas.gwt.client.map.MapModel;
import org.geomajas.gwt.client.map.MapView;
import org.geomajas.gwt.client.map.layer.Layer;
import org.geomajas.gwt.client.map.layer.RasterLayer;
import org.geomajas.gwt.client.map.layer.VectorLayer;
import org.geomajas.plugin.printing.client.util.PrintingLayout;
import org.geomajas.plugin.printing.command.dto.PrintTemplateInfo;
import org.geomajas.plugin.printing.component.dto.ImageComponentInfo;
import org.geomajas.plugin.printing.component.dto.LabelComponentInfo;
import org.geomajas.plugin.printing.component.dto.<API key>;
import org.geomajas.plugin.printing.component.dto.LegendComponentInfo;
import org.geomajas.plugin.printing.component.dto.<API key>;
import org.geomajas.plugin.printing.component.dto.<API key>;
import org.geomajas.plugin.printing.component.dto.<API key>;
import org.geomajas.plugin.printing.component.dto.MapComponentInfo;
import org.geomajas.plugin.printing.component.dto.PageComponentInfo;
import org.geomajas.plugin.printing.component.dto.PrintComponentInfo;
import org.geomajas.plugin.printing.component.dto.<API key>;
import org.geomajas.plugin.printing.component.dto.<API key>;
import org.geomajas.plugin.printing.component.dto.<API key>;
import org.geomajas.plugin.rasterizing.command.dto.<API key>;
import org.geomajas.sld.<API key>;
import org.geomajas.sld.RuleInfo;
/**
* Default print template builder, parameters include title, size, raster DPI, orientation, etc...
*
* @author Jan De Moerloose
*/
public class <API key> extends <API key> {
protected double pageWidth;
protected double pageHeight;
protected int marginX;
protected int marginY;
protected String titleText;
protected int rasterDpi;
protected boolean withScaleBar;
protected boolean withArrow;
protected MapModel mapModel;
protected String applicationId;
@Override
public PrintTemplateInfo buildTemplate() {
PrintTemplateInfo template = super.buildTemplate();
template.setId(1L);
template.setName("default");
return template;
}
@Override
protected PageComponentInfo buildPage() {
PageComponentInfo page = super.buildPage();
page.getLayoutConstraint().setWidth((float) pageWidth);
page.getLayoutConstraint().setHeight((float) pageHeight);
return page;
}
@Override
protected MapComponentInfo buildMap() {
MapComponentInfo map = super.buildMap();
map.getLayoutConstraint().setMarginX(marginX);
map.getLayoutConstraint().setMarginY(marginY);
MapView view = mapModel.getMapView();
double mapWidth = getPageWidth() - 2 * marginX;
double mapHeight = getPageHeight() - 2 * marginY;
Coordinate origin = view.getBounds().createFittingBox(mapWidth, mapHeight).getOrigin();
map.setLocation(new org.geomajas.geometry.Coordinate(origin.getX(), origin.getY()));
map.setPpUnit((float) (mapWidth / view.getBounds().createFittingBox(mapWidth, mapHeight).getWidth()));
map.setTag("map");
map.setMapId(mapModel.getMapInfo().getId());
map.setApplicationId(applicationId);
map.setRasterResolution(rasterDpi);
List<PrintComponentInfo> layers = new ArrayList<PrintComponentInfo>();
// use the normal way for raster layers (TODO: add support for dpi to rasterized part)
for (Layer layer : mapModel.getLayers()) {
if (layer instanceof RasterLayer && layer.isShowing()) {
<API key> info = new <API key>();
RasterLayer rasterLayer = (RasterLayer) layer;
info.setLayerId(rasterLayer.getServerLayerId());
info.setStyle(rasterLayer.getLayerInfo().getStyle());
layers.add(info);
}
}
// use the rasterized layers way for vector layers
for (ClientLayerInfo layerInfo : mapModel.getMapInfo().getLayers()) {
// we must skip the raster layers or we have them twice !
if (layerInfo instanceof <API key>) {
<API key> rInfo = (<API key>) layerInfo
.getWidgetInfo(<API key>.WIDGET_KEY);
rInfo.setShowing(false);
}
}
<API key> <API key> = new <API key>();
<API key>.setMapInfo(mapModel.getMapInfo());
layers.add(<API key>);
map.getChildren().addAll(0, layers);
return map;
}
@Override
protected ImageComponentInfo buildArrow() {
if (isWithArrow()) {
ImageComponentInfo northarrow = super.buildArrow();
northarrow.setImagePath("/images/northarrow.gif");
northarrow.getLayoutConstraint().setAlignmentX(<API key>.RIGHT);
northarrow.getLayoutConstraint().setAlignmentY(<API key>.TOP);
northarrow.getLayoutConstraint().setMarginX((float) PrintingLayout.templateMarginX);
northarrow.getLayoutConstraint().setMarginY((float) PrintingLayout.templateMarginY);
northarrow.getLayoutConstraint().setWidth((float) PrintingLayout.<API key>);
northarrow.setTag("arrow");
return northarrow;
} else {
return null;
}
}
@Override
protected LegendComponentInfo buildLegend() {
LegendComponentInfo legend = super.buildLegend();
FontStyleInfo style = new FontStyleInfo();
style.setFamily(PrintingLayout.<API key>);
style.setStyle(PrintingLayout.<API key>);
style.setSize((int) PrintingLayout.<API key>);
legend.setFont(style);
legend.setMapId(mapModel.getMapInfo().getId());
legend.setTag("legend");
for (Layer layer : mapModel.getLayers()) {
if (layer instanceof VectorLayer && layer.isShowing()) {
VectorLayer vectorLayer = (VectorLayer) layer;
<API key> layerInfo = vectorLayer.getLayerInfo();
String label = layerInfo.getLabel();
<API key> fts = layerInfo.getNamedStyleInfo().getUserStyle().
<API key>().get(0);
for (RuleInfo rule : fts.getRuleList()) {
// use title if present, name if not
String title = (rule.getTitle() != null ? rule.getTitle() : rule.getName());
// fall back to style name
if (title == null) {
title = layerInfo.getNamedStyleInfo().getName();
}
<API key> item = new <API key>();
<API key> graphic = new <API key>();
graphic.setLabel(title);
graphic.setRuleInfo(rule);
graphic.setLayerId(layerInfo.getServerLayerId());
item.addChild(graphic);
item.addChild(getLegendLabel(legend, title));
legend.addChild(item);
}
} else if (layer instanceof RasterLayer && layer.isShowing()) {
RasterLayer rasterLayer = (RasterLayer) layer;
<API key> layerInfo = rasterLayer.getLayerInfo();
<API key> item = new <API key>();
<API key> icon = new <API key>();
icon.setLabel(layerInfo.getLabel());
icon.setLayerType(layerInfo.getLayerType());
item.addChild(icon);
item.addChild(getLegendLabel(legend, layerInfo.getLabel()));
legend.addChild(item);
}
}
return legend;
}
private LabelComponentInfo getLegendLabel(LegendComponentInfo legend, String text) {
LabelComponentInfo legendLabel = new LabelComponentInfo();
legendLabel.setBackgroundColor(PrintingLayout.<API key>);
legendLabel.setBorderColor(PrintingLayout.<API key>);
legendLabel.setFontColor(PrintingLayout.<API key>);
legendLabel.setFont(legend.getFont());
legendLabel.setText(text);
legendLabel.setTextOnly(true);
return legendLabel;
}
@Override
protected <API key> buildScaleBar() {
if (isWithScaleBar()) {
<API key> bar = super.buildScaleBar();
bar.setTicNumber(3);
bar.setTag("scalebar");
return bar;
} else {
return null;
}
}
@Override
protected LabelComponentInfo buildTitle() {
if (titleText != null) {
LabelComponentInfo title = super.buildTitle();
title.setText(titleText);
title.getLayoutConstraint().setMarginY(2 * marginY);
return title;
} else {
return null;
}
}
public double getPageWidth() {
return pageWidth;
}
public void setPageWidth(double pageWidth) {
this.pageWidth = pageWidth;
}
public double getPageHeight() {
return pageHeight;
}
public void setPageHeight(double pageHeight) {
this.pageHeight = pageHeight;
}
public String getTitleText() {
return titleText;
}
public void setTitleText(String titleText) {
this.titleText = titleText;
}
public int getRasterDpi() {
return rasterDpi;
}
public void setRasterDpi(int rasterDpi) {
this.rasterDpi = rasterDpi;
}
public boolean isWithScaleBar() {
return withScaleBar;
}
public void setWithScaleBar(boolean withScaleBar) {
this.withScaleBar = withScaleBar;
}
public boolean isWithArrow() {
return withArrow;
}
public void setWithArrow(boolean withArrow) {
this.withArrow = withArrow;
}
public int getMarginX() {
return marginX;
}
public void setMarginX(int marginX) {
this.marginX = marginX;
}
public int getMarginY() {
return marginY;
}
public void setMarginY(int marginY) {
this.marginY = marginY;
}
public MapModel getMapModel() {
return mapModel;
}
public void setMapModel(MapModel mapModel) {
this.mapModel = mapModel;
}
public String getApplicationId() {
return applicationId;
}
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
} |
#ifndef <API key>
#define <API key>
#include <Fabric/Core/AST/FunctionBase.h>
#include <Fabric/Core/CG/ExprType.h>
namespace llvm
{
class Module;
class FunctionPassManager;
};
namespace Fabric
{
namespace AST
{
class MethodOpImpl : public FunctionBase
{
<API key>( MethodOpImpl );
public:
REPORT_RC_LEAKS
static RC::ConstHandle<MethodOpImpl> Create(
CG::Location const &location,
std::string const &returnTypeName,
std::string const &thisTypeName,
std::string const &methodName,
CG::Usage thisUsage,
RC::ConstHandle<ParamVector> const ¶ms,
std::string const *symbolName,
RC::ConstHandle<CompoundStatement> const &body
);
virtual std::string getPencilKey( RC::Handle<CG::Manager> const &cgManager ) const;
virtual std::string <API key>( RC::Handle<CG::Manager> const &cgManager ) const;
virtual std::string getDesc( RC::Handle<CG::Manager> const &cgManager ) const;
virtual RC::ConstHandle<ParamVector> getParams( RC::Handle<CG::Manager> const &cgManager ) const;
protected:
MethodOpImpl(
CG::Location const &location,
std::string const &returnTypeName,
std::string const &thisTypeName,
std::string const &methodName,
CG::Usage thisUsage,
RC::ConstHandle<ParamVector> const ¶ms,
std::string const *symbolName,
RC::ConstHandle<CompoundStatement> const &body
);
virtual void appendJSONMembers( JSON::ObjectEncoder const &jsonObjectEncoder, bool includeLocation ) const;
private:
std::string m_thisTypeName;
CG::Usage m_thisUsage;
std::string m_methodName;
RC::ConstHandle<ParamVector> m_params;
};
}
}
#endif //<API key> |
<?php
/**
* @var IndexController $this
* @var string $current_url
*/
?>
<section class="col-md-4 col-md-offset-4">
<div class="well">
<script>
$(function () {
var $form = $(".form-signin");
$("#create_account").on("click change", function () {
if ($(this).prop("checked")) {
$form.removeClass("login").addClass("anlegen");
} else {
$form.removeClass("anlegen").addClass("login");
}
}).trigger("change");
})
</script>
<form class="form-horizontal form-signin" method="POST" action="<?= CHtml::encode($current_url) ?>">
<fieldset>
<legend class="form_row">Einloggen</legend>
<?php
foreach ($_POST as $key => $val) if (!in_array($key, array("email", "bestaetigungscode", "password", "password2", AntiXSS::createToken("login"), AntiXSS::createToken("anlegen")))) {
echo "<input type='hidden' name='" . CHtml::encode($key) . "' value='" . CHtml::encode($val) . "'>";
}
?>
<div class="checkbox form_row">
<label>
<input type="checkbox" name="register" id="create_account"> Neuen Zugang anlegen
</label>
</div>
<div class="form_row">
<label for="email" class="control-label sr-only">E-Mail-Adresse</label>
<input id="email" type="email" name="email" class="form-control" placeholder="Email-Adresse" autofocus required>
</div>
<div class="form_row">
<label for="password" class="control-label sr-only">Passwort</label>
<input id="password" name="password" type="password" class="form-control" placeholder="Passwort" required>
</div>
<div class="form_row">
<label for="password2" class="control-label sr-only">Passwort bestätigen</label>
<input id="password2" name="password2" type="password" class="form-control" placeholder="Passwort bestätigen">
</div>
<div id="<API key>" style="display: none;">
Es wurde bereits eine E-Mail mit dem Bestätigungscode an diese Adresse geschickt.<br>
<label for="bestaetigungscode"><strong>Bitte gib den Bestätigungscode an:</strong></label>
<div>
<input type="text" name="bestaetigungscode" id="bestaetigungscode" value="" style="width: 280px;">
</div>
<br><br><br>
</div>
<div style="text-align: right; font-style: italic; margin-top: -5px; font-size: 11px; margin-bottom: 7px;">
<?php echo CHtml::link("Passwort vergessen?", $this->createUrl("benachrichtigungen/<API key>")) ?>
</div>
<button class="btn btn-lg btn-primary btn-block" id="login" type="submit" name="<?php echo AntiXSS::createToken("login_anlegen"); ?>"><span class="login">Login</span><span
class="anlegen">Anlegen</span></button>
</fieldset>
</form>
</div>
</section> |
#include "config.h"
#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#include "monit.h"
#include "socket.h"
#include "event.h"
#include "MMonit.h"
/**
* Connect to a data collector servlet and send the event or status message.
*
* @file
*/
/**
* Send message to the server
* @param C An mmonit object
* @param D Data to send
* @return true if the message sending succeeded otherwise false
*/
static boolean_t _send(Socket_T socket, Mmonit_T C, const char *D) {
char *<API key>(C->url->user, C->url->password);
int rv = Socket_print(socket,
"POST %s HTTP/1.1\r\n"
"Host: %s:%d\r\n"
"Content-Type: text/xml\r\n"
"Content-Length: %lu\r\n"
"Pragma: no-cache\r\n"
"Accept: */*\r\n"
"User-Agent: Monit/%s\r\n"
"%s"
"\r\n"
"%s",
C->url->path,
C->url->hostname, C->url->port,
(unsigned long)strlen(D),
VERSION,
auth ? auth : "",
D);
FREE(auth);
if (rv <0) {
LogError("M/Monit: error sending data to %s -- %s\n", C->url->url, STRERROR);
return false;
}
return true;
}
/**
* Check that the server returns a valid HTTP response
* @param C An mmonit object
* @return true if the response is valid otherwise false
*/
static boolean_t _receive(Socket_T socket, Mmonit_T C) {
int status;
char buf[STRLEN];
if (! Socket_readLine(socket, buf, sizeof(buf))) {
LogError("M/Monit: error receiving data from %s -- %s\n", C->url->url, STRERROR);
return false;
}
Str_chomp(buf);
int n = sscanf(buf, "%*s %d", &status);
if (n != 1 || (status >= 400)) {
LogError("M/Monit: message sending failed to %s -- %s\n", C->url->url, buf);
return false;
}
return true;
}
Handler_Type MMonit_send(Event_T E) {
Handler_Type rv = Handler_Mmonit;
/* The event is sent to mmonit just once - only in the case that the state changed */
if (! Run.mmonits || (E && ! E->state_changed))
return Handler_Succeeded;
StringBuffer_T sb = StringBuffer_create(256);
for (Mmonit_T C = Run.mmonits; C; C = C->next) {
Socket_T socket = Socket_create(C->url->hostname, C->url->port, Socket_Tcp, Socket_Ip, C->ssl, C->timeout);
if (! socket) {
LogError("M/Monit: cannot open a connection to %s\n", C->url->url);
goto error;
}
char buf[STRLEN];
status_xml(sb, E, 2, Socket_getLocalHost(socket, buf, sizeof(buf)));
if (! _send(socket, C, <API key>(sb))) {
LogError("M/Monit: cannot send %s message to %s\n", E ? "event" : "status", C->url->url);
goto error;
}
StringBuffer_clear(sb);
if (! _receive(socket, C)) {
LogError("M/Monit: %s message to %s failed\n", E ? "event" : "status", C->url->url);
goto error;
}
rv = Handler_Succeeded; // Return success if at least one M/Monit succeeded
DEBUG("M/Monit: %s message sent to %s\n", E ? "event" : "status", C->url->url);
error:
if (socket)
Socket_free(&socket);
}
StringBuffer_free(&sb);
return rv;
} |
package com.jaspersoft.ireport.designer;
import com.jaspersoft.ireport.designer.data.ReportQueryDialog;
import java.util.Map;
import net.sf.jasperreports.engine.JRDataset;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;
/**
*
* @author gtoffoli
*/
public interface FieldsProvider {
/**
* Returns true if the provider supports the {@link #getFields(IReportConnection,JRDataset,Map) getFields}
* operation. By returning true in this method the data source provider indicates
* that it is able to introspect the data source and discover the available fields.
*
* @return true if the getFields() operation is supported.
*/
public boolean <API key>();
public JRField[] getFields(IReportConnection con, JRDataset reportDataset, Map parameters ) throws JRException, <API key>;
/**
* Returns true if the getFields can be run in a backgroiund thread each time the user changes the query.
* This approach can not be valid for fieldsProviders that require much time to return the list of fields.
*/
public boolean <API key>();
/**
* Returns true if the FieldsProvider can run an own query designer
*/
public boolean hasQueryDesigner();
/**
* Returns true if the FieldsProvider can run an own editor
*/
public boolean hasEditorComponent();
/**
* This method is used to run a query designer for the specific language.
*
* @param con the IReportConnection active in iReport.
* @param query the query to modify
* @param reportQueryDialog the parent reportQueryDialog. It can be used to get all (sub)dataset informations
* with reportQueryDialog.getSubDataset();
*
*/
public String designQuery(IReportConnection con, String query, ReportQueryDialog reportQueryDialog ) throws JRException, <API key>;
/**
* The component that will stay on the right of the query panel. To listen for query changes, the component must implement
* the interface <API key>. The component will be visible only when a queryCahnged is successfully executed.
* The component can store the reference to the report query dialog in which it will appear.
*
* The editor can
*/
public <API key> getEditorComponent( ReportQueryDialog reportQueryDialog );
} |
class <API key> < ActiveRecord::Migration
def change
change_table(:dependencies) { |t| t.timestamps }
end
end |
require_dependency 'importers'
module Importers
class AssignmentImporter < Importer
self.item_class = Assignment
def self.process_migration(data, migration)
assignments = data['assignments'] ? data['assignments']: []
to_import = migration.to_import 'assignments'
assignments.each do |assign|
if migration.import_object?("assignments", assign['migration_id'])
begin
<API key>(assign, migration.context, migration)
rescue
migration.add_import_warning(t('#migration.assignment_type', "Assignment"), assign[:title], $!)
end
end
end
migration_ids = assignments.map{|m| m['assignment_id'] }.compact
conn = Assignment.connection
cases = []
max = migration.context.assignments.map(&:position).compact.max || 0
migration.context.assignments
assignments.each_with_index{|m, idx| cases << " WHEN migration_id=#{conn.quote(m['assignment_id'])} THEN #{max + idx + 1} " if m['assignment_id'] }
unless cases.empty?
conn.execute("UPDATE assignments SET position=CASE #{cases.join(' ')} ELSE NULL END WHERE context_id=#{migration.context.id} AND context_type=#{conn.quote(migration.context.class.to_s)} AND migration_id IN (#{migration_ids.map{|id| conn.quote(id)}.join(',')})")
end
end
def self.<API key>(hash, context, migration, item=nil, quiz=nil)
hash = hash.<API key>
return nil if hash[:migration_id] && hash[:<API key>] && !hash[:<API key>][hash[:migration_id]]
item ||= Assignment.where(context_type: context.class.to_s, context_id: context, id: hash[:id]).first
item ||= Assignment.where(context_type: context.class.to_s, context_id: context, migration_id: hash[:migration_id]).first if hash[:migration_id]
item ||= context.assignments.new #new(:context => context)
item.title = hash[:title]
item.title = I18n.t('untitled assignment') if item.title.blank?
item.migration_id = hash[:migration_id]
if item.new_record? || item.deleted?
if item.can_unpublish?
item.workflow_state = (hash[:workflow_state] || 'published')
else
item.workflow_state = 'published'
end
end
if hash[:<API key>] == false
self.extend TextHelper
end
description = ""
if hash[:<API key>] == false
description += migration.convert_text(hash[:description] || "")
description += migration.convert_text(hash[:instructions] || "")
else
description += migration.convert_html(hash[:description] || "", :assignment, hash[:migration_id], :description)
description += migration.convert_html(hash[:instructions] || "", :assignment, hash[:migration_id], :description)
end
description += Attachment.<API key>(context, hash[:attachment_ids])
item.description = description
if hash[:freeze_on_copy]
item.freeze_on_copy = true
item.copied = true
item.copying = true
end
if !hash[:submission_types].blank?
item.submission_types = hash[:submission_types]
elsif ['discussion_topic'].include?(hash[:submission_format])
item.submission_types = "discussion_topic"
elsif ['online_upload','textwithattachments'].include?(hash[:submission_format])
item.submission_types = "online_upload,online_text_entry"
elsif ['online_text_entry'].include?(hash[:submission_format])
item.submission_types = "online_text_entry"
elsif ['webpage'].include?(hash[:submission_format])
item.submission_types = "online_upload"
elsif ['online_quiz'].include?(hash[:submission_format])
item.submission_types = "online_quiz"
elsif ['external_tool'].include?(hash[:submission_format])
item.submission_types = "external_tool"
end
if item.submission_types == "online_quiz"
item.saved_by = :quiz
end
if item.submission_types == "discussion_topic"
item.saved_by = :discussion_topic
end
if hash[:grading_type]
item.grading_type = hash[:grading_type]
item.points_possible = hash[:points_possible]
elsif grading = hash[:grading]
hash[:due_at] ||= grading[:due_at] || grading[:due_date]
hash[:<API key>] ||= grading[:<API key>]
if grading[:grade_type] =~ /numeric|points/i
item.points_possible = grading[:points_possible] ? grading[:points_possible].to_f : 10
elsif grading[:grade_type] =~ /alphanumeric|letter_grade/i
item.grading_type = "letter_grade"
item.points_possible = grading[:points_possible] ? grading[:points_possible].to_f : 100
elsif grading[:grade_type] == 'rubric'
hash[:rubric_migration_id] ||= grading[:rubric_id]
elsif grading[:grade_type] == 'not_graded'
item.submission_types = 'not_graded'
end
end
if hash[:<API key>]
item.assignment_group = context.assignment_groups.where(migration_id: hash[:<API key>]).first
end
item.assignment_group ||= context.assignment_groups.where(name: t(:<API key>, "Imported Assignments")).first_or_create
item.<API key>!
rubric = nil
rubric = context.rubrics.where(migration_id: hash[:rubric_migration_id]).first if hash[:rubric_migration_id]
rubric ||= context.available_rubric(hash[:rubric_id]) if hash[:rubric_id]
if rubric
assoc = rubric.associate_with(item, context, :purpose => 'grading')
assoc.use_for_grading = !!hash[:<API key>] if hash.has_key?(:<API key>)
assoc.hide_score_total = !!hash[:<API key>] if hash.has_key?(:<API key>)
if hash[:<API key>]
assoc.summary_data ||= {}
assoc.summary_data[:saved_comments] ||= {}
assoc.summary_data[:saved_comments] = hash[:<API key>]
end
assoc.save
item.points_possible ||= rubric.points_possible if item.infer_grading_type == "points"
end
if hash[:<API key>]
gs = context.grading_standards.where(migration_id: hash[:<API key>]).first
item.grading_standard = gs if gs
elsif hash[:grading_standard_id] && migration
gs = GradingStandard.for(context).where(id: hash[:grading_standard_id]).first unless migration.cross_institution?
if gs
item.grading_standard = gs if gs
else
migration.add_warning(t('errors.import.<API key>', %{The assignment "%{title}" referenced a grading scheme that was not found in the target course's account chain.}, :title => hash[:title]))
end
end
if quiz
item.quiz = quiz
elsif hash[:quiz_migration_id]
if q = context.quizzes.where(migration_id: hash[:quiz_migration_id]).first
if !item.quiz || item.quiz.id == q.id
# the quiz is published because it has an assignment
q.assignment = item
q.generate_quiz_data
q.published_at = Time.now
q.workflow_state = 'available'
q.save
end
end
item.submission_types = 'online_quiz'
item.saved_by = :quiz
end
hash[:due_at] ||= hash[:due_date]
[:due_at, :lock_at, :unlock_at, :peer_reviews_due_at].each do |key|
item.send"#{key}=", Canvas::Migration::MigratorHelper.<API key>(hash[key]) unless hash[key].nil?
end
if hash[:has_group_category]
item.group_category ||= context.group_categories.active.where(:name => t("Project Groups")).first_or_create
end
[:turnitin_enabled, :peer_reviews,
:<API key>, :<API key>,
:<API key>, :allowed_extensions,
:position, :peer_review_count, :muted
].each do |prop|
item.send("#{prop}=", hash[prop]) unless hash[prop].nil?
end
# ^ merge into prop list above once this feature flag is retired
if hash[:moderated_grading] && context.feature_enabled?(:moderated_grading)
item.moderated_grading = true
end
migration.add_imported_item(item)
if migration.date_shift_options
# Unfortunately, we save the assignment here, and then shift dates and
# save the assignment again later in the course migration. Saving here
# would normally schedule the auto peer reviews job with the
# pre-shifted due date, which is probably in the past. After shifting
# dates, it is saved again, but because the job is stranded, and
# because the new date is probably later than the old date, the new job
# is not scheduled, even though that's the date we want.
item.<API key> = true
end
item.<API key>!
item.<API key> = nil
if item.submission_types == 'external_tool'
tag = item.<API key>(:url => hash[:external_tool_url], :new_tab => hash[:<API key>])
if hash[:external_tool_id] && migration && !migration.cross_institution?
tool_id = hash[:external_tool_id].to_i
tag.content_id = tool_id if ContextExternalTool.all_tools_for(context).where(id: tool_id).exists?
elsif hash[:<API key>]
tool = context.<API key>.where(migration_id: hash[:<API key>]).first
tag.content_id = tool.id if tool
end
tag.content_type = 'ContextExternalTool'
if !tag.save
if tag.errors["url"]
migration.add_warning(t('errors.import.external_tool_url',
"The url for the external tool assignment \"%{assignment_name}\" wasn't valid.",
:assignment_name => item.title))
end
item.association(:external_tool_tag).target = nil # otherwise it will trigger destroy on the tag
end
end
if context.respond_to?(:<API key>) && context.<API key>
if group = context.<API key>[item.migration_id]
AssignmentGroup.<API key>(group, item)
end
end
item
end
end
end |
class CmsController < MyProfileController
protect 'edit_profile', :profile, :only => [:set_home_page]
include ArticleHelper
def search_tags
arg = params[:term].downcase
result = ActsAsTaggableOn::Tag.where('name ILIKE ?', "%#{arg}%").limit(10)
render :text => <API key>(result).to_json, :content_type => 'application/json'
end
def self.protect_if(*args)
before_filter(*args) do |c|
user, profile = c.send(:user), c.send(:profile)
if yield(c, user, profile)
true
else
<API key>(c)
false
end
end
end
before_filter :login_required, :except => [:suggest_an_article]
before_filter :load_recent_files, :only => [:new, :edit]
helper_method :file_types
protect_if :only => :upload_files do |c, user, profile|
article_id = c.params[:parent_id]
(!article_id.blank? && profile.articles.find(article_id).allow_create?(user)) ||
(user && (user.has_permission?('post_content', profile) || user.has_permission?('publish_content', profile)))
end
protect_if :except => [:suggest_an_article, :set_home_page, :edit, :destroy, :publish, :<API key>, :<API key>, :<API key>, :upload_files, :new] do |c, user, profile|
user && (user.has_permission?('post_content', profile) || user.has_permission?('publish_content', profile))
end
protect_if :only => :new do |c, user, profile|
article = profile.articles.find_by_id(c.params[:parent_id])
(!article.nil? && (article.allow_create?(user) || article.parent.allow_create?(user))) ||
(user && (user.has_permission?('post_content', profile) || user.has_permission?('publish_content', profile)))
end
protect_if :only => :destroy do |c, user, profile|
profile.articles.find(c.params[:id]).allow_post_content?(user)
end
protect_if :only => :edit do |c,user,profile|
profile.articles.find(c.params[:id]).allow_edit?(user)
end
def boxes_holder
profile
end
def view
@article = profile.articles.find(params[:id])
conditions = []
if @article.has_posts?
conditions = ['type != ?', 'RssFeed']
end
@articles = @article.children.reorder("case when type = 'Folder' then 0 when type ='Blog' then 1 else 2 end, updated_at DESC, name").paginate(
:conditions => conditions,
:per_page => per_page,
:page => params[:npage]
)
end
def index
@article = nil
@articles = profile.top_level_articles.paginate(
:order => "case when type = 'Folder' then 0 when type ='Blog' then 1 else 2 end, updated_at DESC",
:per_page => per_page,
:page => params[:npage]
)
render :action => 'view'
end
def edit
@success_back_to = params[:success_back_to]
@article = profile.articles.find(params[:id])
version = params[:version]
@article.revert_to(version) if version
@parent_id = params[:parent_id]
@type = params[:type] || @article.class.to_s
translations if @article.translatable?
continue = params[:continue]
@article.<API key> = params[:q].split(/,/).map{|n| environment.people.find n.to_i} unless params[:q].nil?
@tokenized_children = <API key>(
profile.members.includes(:<API key>).find_all{ |m|
m.<API key>.include?(@article)
}
)
refuse_blocks
record_coming
if request.post?
@article.image = nil if params[:remove_image] == 'true'
if @article.image.present? && params[:article][:image_builder] &&
params[:article][:image_builder][:label]
@article.image.label = params[:article][:image_builder][:label]
@article.image.save!
end
@article.last_changed_by = user
if @article.update_attributes(params[:article])
if !continue
if @article.content_type.nil? || @article.image?
success_redirect
else
redirect_to :action => (@article.parent ? 'view' : 'index'), :id => @article.parent
end
end
end
end
unless @article.kind_of?(RssFeed)
@escaped_body = CGI::escapeHTML(@article.body || '')
@escaped_abstract = CGI::escapeHTML(@article.abstract || '')
end
end
def new
# FIXME this method should share some logic wirh edit !!!
@success_back_to = params[:success_back_to]
# user must choose an article type first
@parent = profile.articles.find(params[:parent_id]) if params && params[:parent_id].present?
record_coming
@type = params[:type]
if @type.blank?
@article_types = []
<API key>.each do |type|
@article_types.push({
:class => type,
:short_description => type.short_description,
:description => type.description
})
end
@parent_id = params[:parent_id]
render :action => 'select_article_type', :layout => false, :back_to => @back_to
return
else
refuse_blocks
end
raise "Invalid article type #{@type}" unless valid_article_type?(@type)
klass = @type.constantize
article_data = environment.enabled?('<API key>') ? { :accept_comments => false } : {}
article_data.merge!(params[:article]) if params[:article]
article_data.merge!(:profile => profile) if profile
@article = if params[:clone]
current_article = profile.articles.find(params[:id])
current_article.copy_without_save
else
klass.new(article_data)
end
parent = check_parent(params[:parent_id])
if parent
@article.parent = parent
@parent_id = parent.id
end
@article.profile = profile
@article.author = user
@article.last_changed_by = user
@article.created_by = user
translations if @article.translatable?
continue = params[:continue]
if request.post?
@article.<API key> = params[:q].split(/,/).map{|n| environment.people.find n.to_i} unless params[:q].nil?
if @article.save
if continue
redirect_to :action => 'edit', :id => @article
else
respond_to do |format|
format.html { success_redirect }
format.json { render :text => {:id => @article.id, :full_name => profile.identifier + '/' + @article.full_name}.to_json }
end
end
return
end
end
render :action => 'edit'
end
post_only :set_home_page
def set_home_page
return <API key> unless user.can_change_homepage?
article = params[:id].nil? ? nil : profile.articles.find(params[:id])
profile.update_attribute(:home_page, article)
if article.nil?
session[:notice] = _('Homepage reseted.')
else
session[:notice] = _('"%s" configured as homepage.') % article.name
end
redirect_to (request.referer || profile.url)
end
def upload_files
@uploaded_files = []
@article = @parent = check_parent(params[:parent_id])
@target = @parent ? ('/%s/%s' % [profile.identifier, @parent.full_name]) : '/%s' % profile.identifier
if @article
record_coming
end
if request.post? && params[:uploaded_files]
params[:uploaded_files].each do |file|
unless file == ''
@uploaded_files << UploadedFile.create(
{
:uploaded_data => file,
:profile => profile,
:parent => @parent,
:last_changed_by => user,
:author => user,
},
:without_protection => true
)
end
end
@errors = @uploaded_files.select { |f| f.errors.any? }
if @errors.any?
render :action => 'upload_files', :parent_id => @parent_id
else
session[:notice] = _('File(s) successfully uploaded')
if @back_to
redirect_to @back_to
elsif @parent
redirect_to :action => 'view', :id => @parent.id
else
redirect_to :action => 'index'
end
end
end
end
def destroy
@article = profile.articles.find(params[:id])
if request.post?
@article.destroy
session[:notice] = _("\"%s\" was removed." % @article.name)
referer = Rails.application.routes.recognize_path URI.parse(request.referer).path rescue nil
if referer and referer[:controller] == 'cms' and referer[:action] != 'edit'
redirect_to referer
elsif @article.parent
redirect_to @article.parent.url
else
redirect_to profile.url
end
end
end
def why_categorize
render :action => params[:action], :layout => false
end
def update_categories
@object = params[:id] ? @profile.articles.find(params[:id]) : Article.new
@categories = @toplevel_categories = environment.<API key>
if params[:category_id]
@current_category = Category.find(params[:category_id])
@categories = @current_category.children
end
render :template => 'shared/update_categories', :locals => { :category => @current_category, :object_name => 'article' }
end
def <API key>
render :text => find_by_contents(:profiles, environment, user.memberships, params['q'], {:page => 1}, {:fields => ['name']})[:results].map {|community| {:id => community.id, :name => community.name} }.to_json
end
def publish
@article = profile.articles.find(params[:id])
record_coming
@failed = {}
if request.post?
article_name = params[:name]
task = ApproveArticle.create!(:article => @article, :name => article_name, :target => user, :requestor => user)
begin
task.finish
rescue Exception => ex
@failed[ex.message] ? @failed[ex.message] << @article.name : @failed[ex.message] = [@article.name]
task.cancel
end
if @failed.blank?
session[:notice] = _("Your publish request was sent successfully")
if @back_to
redirect_to @back_to
else
redirect_to @article.view_url
end
end
end
end
def <API key>
if request.post?
@back_to = params[:back_to]
@article = profile.articles.find(params[:id])
@failed = {}
article_name = params[:name]
params_marked = (params['q'] || '').split(',').select { |marked| user.memberships.map(&:id).include? marked.to_i }
@marked_groups = Profile.find(params_marked)
if @marked_groups.empty?
redirect_to @back_to
return session[:notice] = _("Select some group to publish your article")
end
@marked_groups.each do |item|
task = ApproveArticle.create!(:article => @article, :name => article_name, :target => item, :requestor => user)
begin
task.finish unless item.moderated_articles?
rescue Exception => ex
@failed[ex.message] ? @failed[ex.message] << item.name : @failed[ex.message] = [item.name]
task.cancel
end
end
if @failed.blank?
session[:notice] = _("Your publish request was sent successfully")
if @back_to
redirect_to @back_to
else
redirect_to @article.view_url
end
else
session[:notice] = _("Some of your publish requests couldn't be sent.")
render :action => 'publish'
end
end
end
def <API key>
if request.post?
@article = profile.articles.find(params[:id])
if environment.portal_enabled
task = ApproveArticle.create!(:article => @article, :name => params[:name], :target => environment.portal_community, :requestor => user)
begin
task.finish unless environment.portal_community.moderated_articles?
session[:notice] = _("Your publish request was sent successfully")
rescue
session[:notice] = _("Your publish request couldn't be sent.")
task.cancel
end
else
session[:notice] = _("There is no portal community to publish your article.")
end
if @back_to
redirect_to @back_to
else
redirect_to @article.view_url
end
end
end
def suggest_an_article
@back_to = params[:back_to] || request.referer || url_for(profile.public_profile_url)
@task = SuggestArticle.new(params[:task])
if request.post?
@task.target = profile
@task.ip_address = request.remote_ip
@task.user_agent = request.user_agent
@task.referrer = request.referrer
@task.requestor = current_person if logged_in?
if (logged_in? || verify_recaptcha(:model => @task, :message => _('Please type the words correctly'))) && @task.save
session[:notice] = _('Thanks for your suggestion. The community administrators were notified.')
redirect_to @back_to
end
end
end
def search
query = params[:q]
results = find_by_contents(:uploaded_files, profile, profile.files.published, query)[:results]
render :text => <API key>(results), :content_type => 'application/json'
end
def <API key>
arg = params[:q].downcase
result = profile.members.find(:all, :conditions => ['LOWER(name) LIKE ?', "%#{arg}%"])
render :text => <API key>(result).to_json
end
def media_upload
parent = check_parent(params[:parent_id])
if request.post?
begin
@file = UploadedFile.create!(:uploaded_data => params[:file], :profile => profile, :parent => parent) unless params[:file] == ''
@file = FilePresenter.for(@file)
rescue Exception => exception
render :text => exception.to_s, :status => :bad_request
end
end
end
def <API key>
load_recent_files(params[:parent_id], params[:q])
render :partial => '<API key>'
end
def view_all_media
paginate_options = {:page => params[:page].blank? ? 1 : params[:page] }
@key = params[:key].to_sym
load_recent_files(params[:parent_id], params[:q], paginate_options)
end
protected
include CmsHelper
def <API key>
articles = [
TinyMceArticle,
TextileArticle,
Event
]
articles += <API key> if params && params[:cms]
parent_id = params ? params[:parent_id] : nil
if profile.enterprise?
articles << EnterpriseHomepage
end
if @parent && @parent.blog?
articles -= Article.folder_types.map(&:constantize)
end
if user.is_admin?(profile.environment)
articles << RawHTMLArticle
end
articles
end
def <API key>
[Folder, Blog, UploadedFile, Forum, Gallery, RssFeed] + @plugins.dispatch(:content_types)
end
def record_coming
if request.post?
@back_to = params[:back_to]
else
@back_to = params[:back_to] || request.referer
end
end
def valid_article_type?(type)
(<API key> + <API key>).map {|item| item.name}.include?(type)
end
def check_parent(id)
if !id.blank?
parent = profile.articles.find(id)
if ! parent.allow_children?
raise ArgumentError.new("cannot create child of article which does not accept children")
end
parent
else
nil
end
end
def refuse_blocks
if ['TinyMceArticle', 'TextileArticle', 'Event', 'EnterpriseHomepage'].include?(@type)
@no_design_blocks = true
end
end
def per_page
10
end
def translations
@locales = environment.locales.invert.reject { |name, lang| !@article.<API key>.include?(lang) }
@selected_locale = @article.language || FastGettext.locale
end
def <API key>(list)
list.map do |item|
{
'title' => item.title,
'url' => item.image? ? item.public_filename(:uploaded) : url_for(item.url),
:icon => icon_for_article(item),
:content_type => item.mime_type,
:error => item.errors.any? ? _('%s could not be uploaded') % item.title : nil,
}
end.to_json
end
def content_editor?
true
end
def success_redirect
if !@success_back_to.blank?
redirect_to @success_back_to
else
redirect_to @article.view_url
end
end
def file_types
{:images => _('Images'), :generics => _('Files')}
end
def load_recent_files(parent_id = nil, q = nil, paginate_options = {:page => 1, :per_page => 6})
#TODO Since we only have special support for images, I'm limiting myself to
# consider generic files as non-images. In the future, with more supported
# file types we'll need to have a smart way to fetch from the database
# scopes of each supported type as well as the non-supported types as a
# whole.
@recent_files = {}
parent = parent_id.present? ? profile.articles.find(parent_id) : nil
if parent.present?
files = parent.children.files
else
files = profile.files
end
files = files.reorder('created_at DESC')
images = files.images
generics = files.no_images
if q.present?
@recent_files[:images] = find_by_contents(:images, profile, images, q, paginate_options)[:results]
@recent_files[:generics] = find_by_contents(:generics, profile, generics, q, paginate_options)[:results]
else
@recent_files[:images] = images.paginate(paginate_options)
@recent_files[:generics] = generics.paginate(paginate_options)
end
end
end |
<?php
namespace Shopware\Bundle\SearchBundle\Condition;
use Shopware\Bundle\SearchBundle\ConditionInterface;
class ProductIdCondition implements ConditionInterface, \JsonSerializable
{
/**
* @var int[]
*/
protected $productIds;
/**
* @param int[] $productIds
*/
public function __construct(array $productIds)
{
$this->productIds = $productIds;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'productids';
}
/**
* @return int[]
*/
public function getProductIds()
{
return $this->productIds;
}
/**
* {@inheritdoc}
*/
public function jsonSerialize()
{
return get_object_vars($this);
}
} |
OC.L10N.register(
"lib",
{
"See %s" : "%s kucken",
"Sample configuration detected" : "<API key> erkannt",
"PHP %s or higher is required." : "PHP %s oder méi nei ass néideg.",
"PHP with a version lower than %s is required." : "PHP mat enger Versioun %s oder méi kleng ass néideg.",
"Following databases are supported: %s" : "Dës Datebanke ginn ënnerstëtzt: %s",
"Unknown filetype" : "Onbekannten Fichier Typ",
"Invalid image" : "Ongülteg d'Bild",
"today" : "haut",
"yesterday" : "gëschter",
"_%n day ago_::_%n days ago_" : ["%n Dag hier","%n Deeg hier"],
"last month" : "Läschte Mount",
"_%n month ago_::_%n months ago_" : ["%n Mount hier","%n Méint hier"],
"last year" : "Läscht Joer",
"_%n year ago_::_%n years ago_" : ["%n Joer hier","%n Joer hier"],
"_%n hour ago_::_%n hours ago_" : ["%n Stonn hier","%n Stonnen hier"],
"seconds ago" : "Sekonnen hir",
"File name contains at least one invalid character" : "Den Numm vum Fichier entält min. een ongültegz Zeechen",
"%s shared »%s« with you" : "Den/D' %s huet »%s« mat dir gedeelt",
"Apps" : "Applikatiounen",
"A valid username must be provided" : "Et muss e gültegen Benotzernumm ugi ginn",
"A valid password must be provided" : "Et muss e gültegt Passwuert ugi ginn",
"Help" : "Hëllef",
"Personal" : "Perséinlech",
"Users" : "Benotzer",
"Admin" : "Admin",
"web services under your control" : "Web-Servicer ënnert denger Kontroll",
"Authentication error" : "Authentifikatioun's Fehler",
"Data directory (%s) is invalid" : "Daten-Dossier (%s) ass ongëlteg"
},
"nplurals=2; plural=(n != 1);"); |
# -*- coding: utf-8 -*-
# Releasing children from poverty in Jesus' name
# The licence is in the file __manifest__.py
from odoo import api, exceptions, fields, models, _
from datetime import datetime
from odoo.tools import <API key> as DF
from odoo.tools import <API key> as DTF
class <API key>(models.Model):
''' Add possibility to create request to modify the planning
- Move a planning day
- Create a new planning day
Requests needed to be approved.
Request can be created or approved in this cases only:
- An employee does not work twice a day
- An employee move a working day only
- An employee cannot add a working day during his/her holiday
'''
_name = "hr.planning.day.move.request"
# FIELDS #
name = fields.Char(
required=True, states={'validate': [('readonly', True)]})
old_date = fields.Date(
states={'validate': [('readonly', True)]})
new_date = fields.Date(
required=True, states={'validate': [('readonly', True)]})
hour_from = fields.Float(
'From', default=8, states={'validate': [('readonly', True)]})
hour_to = fields.Float(
'To', default=17, states={'validate': [('readonly', True)]})
employee_id = fields.Many2one(
'hr.employee', 'Employee', default=lambda self: self._employee_get(),
required=True, states={'validate': [('readonly', True)]})
state = fields.Selection(
[('to_approve', 'To Approve'), ('validate', 'Approved')],
'Status', default='to_approve', track_visibility="onchange",
readonly=True)
type = fields.Selection(
[('add', 'Add'), ('move', 'Move')], 'Type', required=True,
states={'validate': [('readonly', True)]})
# FIELDS METHODS #
def _employee_get(self):
return self.env.user.id
# ORM METHODS #
@api.model
def create(self, vals):
# Move request
if vals['type'] == 'move':
# Check if this employee is working this day
if (self._check_is_working(
vals['employee_id'], vals['old_date'])):
return super(<API key>,
self).create(vals)
# Check if the move will have no effect
elif vals['old_date'] == vals['new_date']:
raise exceptions.UserError(_(u'You chose the same date'))
else:
employee_name = self.env['hr.employee'].browse(
vals['employee_id']).name
raise exceptions.UserError(
_(u'{} does not work this day : {}').format(
employee_name, vals['old_date'])
)
# Add request
else:
vals['old_date'] = False
return super(<API key>, self).create(vals)
@api.multi
def write(self, vals):
if 'type' in vals:
if vals['type'] == 'add':
vals['old_date'] = False
return super(<API key>, self).write(vals)
# Delete a request
@api.multi
def unlink(self):
employee_ids = self.mapped('employee_id.id')
res = super(<API key>, self).unlink()
self.env['hr.planning.wizard'].generate(employee_ids)
return res
# WORKFLOW METHODS #
# Approve a request
@api.multi
def approve(self):
self.write({'state': 'validate'})
employee_ids = list()
for move_request in self:
employee_ids.append(move_request.employee_id.id)
# Avoid to approve a request if the employee is already working
if(move_request._check_is_working(
move_request.employee_id.id,
move_request.new_date)):
raise exceptions.UserError(
_(u'{} already works this day : {}').format(
move_request.employee_id.name,
move_request.new_date)
)
self.env['hr.planning.wizard'].generate(employee_ids)
return True
# Refuse a request
@api.multi
def refuse(self):
self.write({'state': 'to_approve'})
employee_ids = self.mapped('employee_id.id')
self.env['hr.planning.wizard'].generate(employee_ids)
return True
# PRIVATE METHODS #
def _check_is_working(self, employee_id, date):
planning_day_obj = self.env['hr.planning.day']
planning_days = planning_day_obj.search(
[('employee_id', '=', employee_id)])
# Find in the planning day
for planning_day in planning_days:
if (datetime.strptime(
planning_day.start_date, DTF).date() ==
datetime.strptime(date, DF).date()):
return True
return False |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../../../dep/bootstrap/css/bootstrap.css">
<link rel="stylesheet" href="../../mvelo.css">
<link rel="stylesheet" href="keyGenDialog.css">
<script src="../../../dep/jquery.min.js"></script>
<script src="../../../dep/jquery.ext.js"></script>
<script src="../../mvelo.js"></script>
<script src="keyGenDialog.js"></script>
</head>
<body>
</body>
</html> |
module.exports = function(grunt, options){
grunt.registerTask('compilelibsimple', 'Process lib through babel, browserify and uglify', function(n){
grunt.task.run('babel:lib');
grunt.task.run(['env:build', 'browserify:lib', 'env:dev']);
});
const fs = require('fs');
const dirs = p => fs.readdirSync(p).filter(f => fs.statSync(p+"/"+f).isDirectory());
dirs('res/js/ui').map((d) => {
grunt.registerTask('watchgalvanize:' + d, 'Process all libs through babel, browserify and uglify', function(n){
grunt.option('galvanizeConfig', [
{configs:{libName:d}}
]);
grunt.task.run('galvanize:compilelibsimple');
});
});
} |
import * as <API key> from "./src/<API key>";
import * as locationModules from "./src/locationModules";
export {printRecording,
<API key>}
from "./src/singleLayer2D";
export {<API key>};
export {locationModules}; |
package anzsoft.xmpp4gwt.client.xmpp.xeps.vcard;
import anzsoft.xmpp4gwt.client.JID;
import anzsoft.xmpp4gwt.client.ResponseHandler;
import anzsoft.xmpp4gwt.client.packet.Packet;
import anzsoft.xmpp4gwt.client.stanzas.IQ;
public abstract class <API key> implements ResponseHandler {
public final void onResult(IQ iq) {
JID jid = JID.fromString(iq.getAtribute("from"));
Packet vcard = iq.getFirstChild("vCard");
if (vcard == null)
return;
VCard result = new VCard();
result.setJid(jid);
Packet fn = vcard.getFirstChild("FN");
Packet n = vcard.getFirstChild("N");
Packet nickname = vcard.getFirstChild("NICKNAME");
Packet adr = vcard.getFirstChild("ADR");
Packet title = vcard.getFirstChild("TITLE");
Packet photo = vcard.getFirstChild("PHOTO");
result.setName(fn == null ? null : fn.getCData());
result.setNickname(nickname == null ? null : nickname.getCData());
result.setTitle(title == null ? null : title.getCData());
if (adr != null) {
Packet ctry = adr.getFirstChild("CTRY");
Packet locality = adr.getFirstChild("LOCALITY");
result.setCountry(ctry == null ? null : ctry.getCData());
result.setLocality(locality == null ? null : locality.getCData());
}
if (n != null) {
Packet family = n.getFirstChild("FAMILY");
Packet given = n.getFirstChild("GIVEN");
Packet middle = n.getFirstChild("MIDDLE");
result.setNameFamily(family == null ? null : family.getCData());
result.setNameGiven(given == null ? null : given.getCData());
result.setNameMiddle(middle == null ? null : middle.getCData());
}
if (photo != null) {
Packet filename = photo.getFirstChild("FILENAME");
result.setPhotoFileName(filename == null ? null : filename
.getCData());
}
onSuccess(result);
}
public abstract void onSuccess(final VCard vcard);
} |
function preinit() {
// Initialize
tinyMCE.setWindowArg('mce_windowresize', false);
}
function init() {
tinyMCEPopup.resizeToInnerSize();
SXE.initElementDialog('ins');
if (SXE.currentAction == "update") {
setFormValue('datetime', tinyMCE.getAttrib(SXE.updateElement, 'datetime'));
setFormValue('cite', tinyMCE.getAttrib(SXE.updateElement, 'cite'));
SXE.showRemoveButton();
}
}
function setElementAttribs(elm) {
setAllCommonAttribs(elm);
setAttrib(elm, 'datetime');
setAttrib(elm, 'cite');
}
function insertIns() {
var elm = tinyMCE.getParentElement(SXE.focusElement, 'ins');
tinyMCEPopup.execCommand('mceBeginUndoLevel');
if (elm == null) {
var s = SXE.inst.selection.getSelectedHTML();
if(s.length > 0) {
tinyMCEPopup.execCommand('mceInsertContent', false, '<ins id="#sxe_temp_ins#">' + s + '</ins>');
var elementArray = tinyMCE.<API key>(SXE.inst.getBody(), 'ins', 'id', '#sxe_temp_ins#');
for (var i=0; i<elementArray.length; i++) {
var elm = elementArray[i];
setElementAttribs(elm);
}
}
} else {
setElementAttribs(elm);
}
tinyMCE.triggerNodeChange();
tinyMCEPopup.execCommand('mceEndUndoLevel');
tinyMCEPopup.close();
}
function removeIns() {
SXE.removeElement('ins');
tinyMCEPopup.close();
} |
#Datamanager for OS
forked from [ngBoilerplate](http://joshdmiller.github.com/ng-boilerplate)
## Quick Start
Install Node.js and then:
sh
$ cd path/to/openspending/static/
$ git clone git://github.com/nathanhilbert/datamanger_OS
$ cd datamanager_OS
$ sudo npm -g install grunt-cli karma bower
$ npm install
$ bower install
$ grunt watch --force
Finally, run the OS server and open `http://localhost:5000/static/datamanager_OS/build/index.html` in your browser. |
.nav-side-menu {
overflow: auto;
font-family: verdana;
font-size: 12px;
font-weight: 200;
background-color: #2e353d;
position: fixed;
top: 0px;
width: 300px;
height: 100%;
color: #e1ffff;
}
.nav-side-menu .brand {
background-color: #23282e;
line-height: 50px;
display: block;
text-align: center;
font-size: 14px;
}
.nav-side-menu .toggle-btn {
display: none;
}
.nav-side-menu ul,
.nav-side-menu li {
list-style: none;
padding: 0px;
margin: 0px;
line-height: 35px;
cursor: pointer;
/*
.collapsed{
.arrow:before{
font-family: FontAwesome;
content: "\f053";
display: inline-block;
padding-left:10px;
padding-right: 10px;
vertical-align: middle;
float:right;
}
}
*/
}
.nav-side-menu ul :not(collapsed) .arrow:before,
.nav-side-menu li :not(collapsed) .arrow:before {
font-family: FontAwesome;
content: "\f078";
display: inline-block;
padding-left: 10px;
padding-right: 10px;
vertical-align: middle;
float: right;
}
.nav-side-menu ul .active,
.nav-side-menu li .active {
border-left: 3px solid #d19b3d;
background-color: #4f5b69;
}
.nav-side-menu ul .sub-menu li.active,
.nav-side-menu li .sub-menu li.active {
color: #d19b3d;
}
.nav-side-menu ul .sub-menu li.active a,
.nav-side-menu li .sub-menu li.active a {
color: #d19b3d;
}
.nav-side-menu ul .sub-menu li,
.nav-side-menu li .sub-menu li {
background-color: #181c20;
border: none;
line-height: 28px;
border-bottom: 1px solid #23282e;
margin-left: 0px;
}
.nav-side-menu ul .sub-menu li:hover,
.nav-side-menu li .sub-menu li:hover {
background-color: #020203;
}
.nav-side-menu ul .sub-menu li:before,
.nav-side-menu li .sub-menu li:before {
font-family: FontAwesome;
content: "\f105";
display: inline-block;
padding-left: 10px;
padding-right: 10px;
vertical-align: middle;
}
.nav-side-menu li {
padding-left: 0px;
border-left: 3px solid #2e353d;
border-bottom: 1px solid #23282e;
}
.nav-side-menu li a {
text-decoration: none;
color: #e1ffff;
}
.nav-side-menu li a i {
padding-left: 10px;
width: 20px;
padding-right: 20px;
}
.nav-side-menu li:hover {
border-left: 3px solid #d19b3d;
background-color: #4f5b69;
-webkit-transition: all 1s ease;
-moz-transition: all 1s ease;
-o-transition: all 1s ease;
-ms-transition: all 1s ease;
transition: all 1s ease;
}
@media (max-width: 767px) {
.nav-side-menu {
position: relative;
width: 100%;
margin-bottom: 10px;
}
.nav-side-menu .toggle-btn {
display: block;
cursor: pointer;
position: absolute;
right: 10px;
top: 10px;
z-index: 10 !important;
padding: 3px;
background-color: #ffffff;
color: #000;
width: 40px;
text-align: center;
}
.brand {
text-align: left !important;
font-size: 22px;
padding-left: 20px;
line-height: 50px !important;
}
}
@media (min-width: 767px) {
.nav-side-menu .menu-list .menu-content {
display: block;
}
}
body {
margin: 0px;
padding: 0px;
} |
package org.phenotips.studies.family;
import org.xwiki.component.annotation.Role;
import java.util.List;
import org.json.JSONObject;
/**
* Converts the JSON generated by the pedigree into the default format accepted by PhenoTips.
*
* @version $Id$
* @since 1.4
*/
@Role
public interface PedigreeProcessor
{
/**
* Takes a JSON object from a pedigree and converts it into a list of patient JSON objects, in the format consumable
* by the internal PhenoTips patient data model. This is a static method, but cannot be declared as such, given the
* necessity of injections.
*
* @param pedigree a valid pedigree object.
* @return list of JSON objects, each containing patient data of a single patient. Returns an empty list if pedigree
* is null.
*/
List<JSONObject> convert(Pedigree pedigree);
} |
(function($)
{
'use strict';
$.fn.ModMorris = function(options)
{
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
hideHover: 'always',
resize: true,
grid: false,
goals: [100],
gridTextSize: 10,
postUnits: '%',
parseTime: false,
lineWidth: 1,
goalStrokeWidth: 1,
goalLineColors: ['green'],
lineColors: ['#559a9b'],
// ID of the element in which to draw the chart.
element: this.attr('id'),
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: [
{try: '#1', value: 10},
{try: '#2', value: 35},
{try: '#3', value: 85},
{try: '#4', value: 75},
{try: '#5', value: 95},
{try: '#6', value: 100},
],
// The name of the data record attribute that contains x-values.
xkey: 'try',
// A list of names of data record attributes that contain y-values.
ykeys: ['value'],
// Labels for the ykeys -- will be displayed when you hover over the
// chart.
labels: ['Value']
}, options);
var Chart = new Morris.Line(settings);
window.setTimeout(function(){
Chart.raphael.setSize('100%','100%');
Chart.redraw();
},500);
return this;
};
}(jQuery)); |
<?php
$mess=array(
"iOS" => "iOS",
"Template for redirecting to iPhone application" => "Template for redirecting to iPhone application",
"iOS Application URL" => "iOS Application URL",
"iOS Application" => "iOS Application",
"Android Application URL" => "Android Application URL",
"Android App" => "Android App",
); |
class <API key> < <API key>
include <API key>
end |
#ifndef <API key>
#define <API key>
#include <string>
#include <vector>
#include "rest/ConnectionInfo.h"
#include "ngsi/ParseData.h"
extern std::string getEntityAttribute
(
ConnectionInfo* ciP,
int components,
std::vector<std::string>& compV,
ParseData* parseDataP
);
#endif // <API key> |
# Kernel/Output/HTML/PreferencesLanguage.pm
# $Id: PreferencesLanguage.pm,v 1.13 2010/05/04 01:22:10 martin Exp $
package Kernel::Output::HTML::PreferencesLanguage;
use strict;
use warnings;
use vars qw($VERSION);
$VERSION = qw($Revision: 1.13 $) [1];
sub new {
my ( $Type, %Param ) = @_;
# allocate new hash for object
my $Self = {%Param};
bless( $Self, $Type );
# get needed objects
for (qw(ConfigObject LogObject DBObject LayoutObject UserID ParamObject ConfigItem)) {
$Self->{$_} = $Param{$_} || die "Got no $_!";
}
return $Self;
}
sub Param {
my ( $Self, %Param ) = @_;
my @Params;
push(
@Params,
{
%Param,
Name => $Self->{ConfigItem}->{PrefKey},
Data => $Self->{ConfigObject}->Get('<API key>'),
HTMLQuote => 0,
SelectedID => $Self->{ParamObject}->GetParam( Param => 'UserLanguage' )
|| $Param{UserData}->{UserLanguage}
|| $Self->{LayoutObject}->{UserLanguage}
|| $Self->{ConfigObject}->Get('DefaultLanguage'),
Block => 'Option',
Max => 100,
},
);
return @Params;
}
sub Run {
my ( $Self, %Param ) = @_;
for my $Key ( keys %{ $Param{GetParam} } ) {
my @Array = @{ $Param{GetParam}->{$Key} };
for (@Array) {
# pref update db
if ( !$Self->{ConfigObject}->Get('DemoSystem') ) {
$Self->{UserObject}->SetPreferences(
UserID => $Param{UserData}->{UserID},
Key => $Key,
Value => $_,
);
}
# update SessionID
if ( $Param{UserData}->{UserID} eq $Self->{UserID} ) {
$Self->{SessionObject}->UpdateSessionID(
SessionID => $Self->{SessionID},
Key => $Key,
Value => $_,
);
}
}
}
$Self->{Message} = 'Preferences updated successfully!';
return 1;
}
sub Error {
my ( $Self, %Param ) = @_;
return $Self->{Error} || '';
}
sub Message {
my ( $Self, %Param ) = @_;
return $Self->{Message} || '';
}
1; |
import Conversation from 'compiled/models/Conversation'
QUnit.module('Conversation', {
setup() {
this.conversation = new Conversation()
}
})
test('#validate validates body length', function() {
ok(this.conversation.validate({body: ''}))
ok(this.conversation.validate({body: null}).body)
ok(
this.conversation.validate({
body: 'body',
recipients: [{}]
}) === undefined
)
})
test('#validate validates there must be at least one recipient object', function() {
const testData = {
body: 'i love testing javascript',
recipients: [{}]
}
ok(this.conversation.validate(testData) === undefined)
testData.recipients = []
ok(this.conversation.validate(testData).recipients)
delete testData.recipients
ok(this.conversation.validate(testData).recipients)
})
test('#url is the correct API url', function() {
equal(this.conversation.url, '/api/v1/conversations')
}) |
package system
import (
"github.com/juju/cmd"
"github.com/juju/errors"
"launchpad.net/gnuflag"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/cmd/envcmd"
)
func <API key>() cmd.Command {
return envcmd.WrapSystem(&listBlocksCommand{})
}
// listBlocksCommand lists all blocks for environments within the system.
type listBlocksCommand struct {
envcmd.SysCommandBase
out cmd.Output
api listBlocksAPI
apierr error
}
var listBlocksDoc = `List all blocks for environments within the specified system`
// listBlocksAPI defines the methods on the system manager API endpoint
// that the list-blocks command calls.
type listBlocksAPI interface {
Close() error
<API key>() ([]params.<API key>, error)
}
// Info implements Command.Info.
func (c *listBlocksCommand) Info() *cmd.Info {
return &cmd.Info{
Name: "list-blocks",
Purpose: "list all blocks within the system",
Doc: listBlocksDoc,
}
}
// SetFlags implements Command.SetFlags.
func (c *listBlocksCommand) SetFlags(f *gnuflag.FlagSet) {
c.out.AddFlags(f, "tabular", map[string]cmd.Formatter{
"yaml": cmd.FormatYaml,
"json": cmd.FormatJson,
"tabular": <API key>,
})
}
func (c *listBlocksCommand) getAPI() (listBlocksAPI, error) {
if c.api != nil {
return c.api, c.apierr
}
return c.<API key>()
}
// Run implements Command.Run
func (c *listBlocksCommand) Run(ctx *cmd.Context) error {
api, err := c.getAPI()
if err != nil {
return errors.Annotate(err, "cannot connect to the API")
}
defer api.Close()
envs, err := api.<API key>()
if err != nil {
logger.Errorf("Unable to list blocked environments: %s", err)
return err
}
return c.out.Write(ctx, envs)
} |
import random
import math
import numpy as np
def generate(data):
canvas_width = 300
canvas_height = 300
data["params"]["canvas_width"] = canvas_width
data["params"]["canvas_height"] = canvas_height
# Creating all variables, even knowing that just a few would be used in this Example
# Could improve later
# point
x0 = 40
y0 = 40
interval = np.linspace(100,200,11)
xP = random.choice(interval)
data["params"]["xP"] = xP
yP = random.choice(interval)
data["params"]["xP"] = xP
data["params"]["yP"] = yP
data["params"]["x0"] = x0
data["params"]["y0"] = canvas_height - y0
xA = 40
xD = 260
xB = random.randint(xA+20,xD/2)
xC = random.randint(xB + 30,xD-20)
y = 160
w = xC-xB
xE = xB + w/2
data["params"]["xA"] = xA
data["params"]["xB"] = xB
data["params"]["xC"] = xC
data["params"]["xD"] = xD
data["params"]["xE"] = xE
data["params"]["y"] = y
data["params"]["w"] = w
# vector
allangles = [0,30,45,60,90]
alpha = random.choice(allangles) if random.choice([0,1]) else -random.choice(allangles)
data["params"]["alpha"] = alpha
alphas = -alpha
# arc vector
if random.choice([0,1]):
data["params"]["arc_orientation"] = "true"
<API key> = "clockwise"
else:
data["params"]["arc_orientation"] = "false"
<API key> = "counter-clockwise"
# distributed load
wmin = 20
wmax = 60
angle = random.choice([0,180])
if random.choice([0,1]):
comp = "larger "
if angle == 0:
data["params"]["w1"] = wmax
data["params"]["w2"] = wmin
else:
data["params"]["w1"] = wmin
data["params"]["w2"] = wmax
else:
comp = "smaller "
if angle == 0:
data["params"]["w1"] = wmin
data["params"]["w2"] = wmax
else:
data["params"]["w1"] = wmax
data["params"]["w2"] = wmin
data["params"]["theta"] = angle
orientation = "downwards" if angle == 0 else "upwards"
# torque
if random.choice([0,1]):
torque_sign = "positive"
data["params"]["gamma"] = 0
else:
torque_sign = "negative"
data["params"]["gamma"] = 180
for i in range(0,7):
data["params"]["visible" + str(i)] = "false"
question = random.choice([1,2,3,4,5,6])
text = ""
if (question == 1):
text = "Add a point to position $(" + str(xP - x0) + "," + str(canvas_height - yP - y0) + ")$"
text += " w.r.t. the origin $O$. Each square side has length 20."
data["params"]["visible1"] = 'true'
elif (question == 2):
text = "Add a vector at $B$ with orientation $\\theta = $" + str(alphas)
data["params"]["visible2"] = 'true'
data["params"]["visible0"] = 'true'
elif (question == 3):
text = "Add a " + str(<API key>) + " moment at $C$."
data["params"]["visible3"] = 'true'
data["params"]["visible0"] = 'true'
elif (question == 4):
text = "Apply an uniform distributed load to the beam below, on the interval from $B$ to $C$."
text += " The load should point " + str(orientation) + "."
data["params"]["visible4"] = 'true'
data["params"]["visible0"] = 'true'
elif (question == 5):
text = "Apply a triangular distributed load to the beam below, on the interval from $B$ to $C$."
text += " The load should point " + str(orientation) + "."
text += " The magnitude (in absolute value) in $B$ is " + str(comp) + "than in $C$."
data["params"]["visible5"] = 'true'
data["params"]["visible0"] = 'true'
elif (question == 6):
text = "Apply a " + str(torque_sign) + " torque at $C$."
data["params"]["visible6"] = 'true'
data["params"]["visible0"] = 'true'
data["params"]["text"] = text
return data |
from __future__ import absolute_import
# Some utilities for speaking s3g
import struct
import array
import time
import serial
import makerbot_driver
import uuid
class s3g(object):
""" Represents an interface to a s3g driven bot. Contains methods and functions to
read and write data to the bot. No data is cached by this driver, all data is requested
over the USB bus when queried.
"""
POINT_LENGTH = 3
<API key> = 5
@classmethod
def from_filename(cls, port, condition, baudrate=115200, timeout=.2):
"""Constructs and returns an s3g object connected to the
passed file endpoint passed as a string @port (ie 'COM0' or '/dev/tty9')
@param port target Serial port name
@param baurdate baudrace 115200 assumed
@param timeout, time allowance before timeout error. 0.2 assummed
@return s3g object, equipped with a StreamWrtier directed at port.
"""
s = serial.Serial(port, baudrate=baudrate, timeout=timeout)
# begin baud rate hack
# There is an interaction between the 8U2 firmware and PySerial where
# PySerial thinks the 8U2 is already running at the specified baud rate and
# it doesn't actually issue the ioctl calls to set the baud rate. We work
# around it by setting the baud rate twice, to two different values. This
# forces PySerial to issue the correct ioctl calls.
s.baudrate = 9600
s.baudrate = baudrate
# end baud rate hack
mb_streamWriter = makerbot_driver.Writer.StreamWriter(s, condition)
return s3g(mb_streamWriter)
def __init__(self, mb_stream_writer=None):
self.writer = mb_stream_writer
self._eeprom_reader = None
self.print_to_file_type = 's3g'
self.tool_query_code = 'Bbb'
def <API key>(self, print_to_file_type):
self.print_to_file_type = print_to_file_type
def init_eeprom_reader(self, firmware_version=None):
self._eeprom_reader = makerbot_driver.EEPROM.EepromReader.factory(
self, firmware_version)
@property
def eeprom_reader(self):
if self._eeprom_reader is None:
self._eeprom_reader = makerbot_driver.EEPROM.EepromReader.factory(
self)
return self._eeprom_reader
def close(self):
""" If any ports are open for this s3g bot, it closes those ports """
if self.writer:
self.writer.close()
def is_open(self):
"""@returns true if we have a writer and it is open. False otherwise."""
if self.writer:
return self.writer.is_open()
return False
def open(self):
""" If a writer with data exists in this bot, attempts to open that writer."""
if self.writer:
self.writer.open()
def get_version(self):
"""
Get the firmware version number of the connected machine
@return Version number
"""
payload = struct.pack(
'<BH',
makerbot_driver.<API key>['GET_VERSION'],
makerbot_driver.s3g_version,
)
response = self.writer.send_query_payload(payload)
[response_code, version] = makerbot_driver.Encoder.unpack_response(
'<BH', response)
# TODO: check response_code
return version
def get_name(self):
"""
Get stored Bot Name
@return a string for the name
TODO: merge this function with future eeprom read/write module
"""
name = self.eeprom_reader.read_data('MACHINE_NAME')
return name[0]
def get_toolhead_count(self):
"""
@return the toolhead count of this bot. -1 on error
"""
data = self.eeprom_reader.read_data('TOOL_COUNT')
return data[0]
def get_vid_pid(self):
"""
Due to a production issue with a vendor, we do not
trust the VID/PID in all EEPROMS, and the generic
get_vid_pid most used should return the interface VID/PID,
not the eeprom vid_pid. """
return self.get_vid_pid_iface()
def get_vid_pid_eeprom(self):
"""
@returns tuple of vid,pid. tuple from EEPROM (None,None) on error
"""
reader = self.create_reader()
data = reader.read_data('VID_PID_INFO')
return data[0], data[1]
def get_vid_pid_iface(self):
"""
Reads VID/PID values from the serial port object associated
with this device.
@return USB vid/pid tuple from the usb chip on the machine,
"""
vid = None
pid = None
if self.writer is not None:
if isinstance(self.writer, makerbot_driver.Writer.StreamWriter):
portname = self.writer.file.port
detector = makerbot_driver.<API key>()
vid, pid = detector.<API key>(portname)
return vid, pid
def get_verified_status(self, verified_pid=makerbot_driver.vid_pid[1]):
"""
@returns true if this firmware is marked as verified
"""
vid_pid = self.get_vid_pid()
return vid_pid[1] is verified_pid
def <API key>(self):
"""
Get the firmware version number of the connected machine
@return Version number
"""
payload = struct.pack(
'<BH',
makerbot_driver.<API key>['<API key>'],
makerbot_driver.s3g_version,
)
response = self.writer.send_query_payload(payload)
[response_code,
version,
internal_version,
software_variant,
reserved_a,
reserved_b] = makerbot_driver.Encoder.unpack_response('<BHHBBH', response)
# TODO: check response_code
version_info = {
'Version': version,
'InternalVersion': internal_version,
'SoftwareVariant': software_variant,
'ReservedA': reserved_a,
'ReservedB': reserved_b,
}
return version_info
def capture_to_file(self, filename):
"""
Capture all subsequent commands up to the 'end capture' command to a file with the given filename on an SD card.
@param str filename: The name of the file to write to on the SD card
"""
payload = struct.pack(
'<B',
makerbot_driver.<API key>['CAPTURE_TO_FILE'],
)
payload += filename
payload += '\x00'
response = self.writer.send_query_payload(payload)
[response_code, sd_response_code] = makerbot_driver.Encoder.unpack_response('<BB', response)
# TODO: check response_code
if sd_response_code != makerbot_driver.sd_error_dict['SUCCESS']:
raise makerbot_driver.SDCardError(sd_response_code)
def end_capture_to_file(self):
"""
Send the end capture signal to the bot, so it stops capturing data and writes all commands out to a file on the SD card
@return The number of bytes written to file
"""
payload = struct.pack(
'<B',
makerbot_driver.<API key>['END_CAPTURE'],
)
response = self.writer.send_query_payload(payload)
[response_code, sdResponse] = makerbot_driver.Encoder.unpack_response(
'<BI', response)
# TODO: check response_code
return sdResponse
def reset(self):
"""
reset the bot, unless the bot is waiting to tell us a build is cancelled.
"""
payload = struct.pack(
'<B',
makerbot_driver.<API key>['RESET'],
)
# TODO: mismatch here.
self.writer.send_action_payload(payload)
def is_finished(self):
"""
Checks if the steppers are still executing a command
"""
payload = struct.pack(
'<B',
makerbot_driver.<API key>['IS_FINISHED'],
)
response = self.writer.send_query_payload(payload)
[response_code, isFinished] = makerbot_driver.Encoder.unpack_response(
'<B?', response)
# TODO: check response_code
return isFinished
def clear_buffer(self):
"""
Clears the buffer of all commands
"""
payload = struct.pack(
'<B',
makerbot_driver.<API key>['CLEAR_BUFFER'],
)
# TODO: mismatch here.
self.writer.send_action_payload(payload)
def pause(self):
"""
pause the machine
"""
payload = struct.pack(
'<B',
makerbot_driver.<API key>['PAUSE'],
)
# TODO: mismatch here.
self.writer.send_action_payload(payload)
def get_build_stats(self):
"""
Get some statistics about the print currently running, or the last print if no print is active
"""
payload = struct.pack(
'<B',
makerbot_driver.<API key>['GET_BUILD_STATS'],
)
response = self.writer.send_query_payload(payload)
[response_code,
build_state,
build_hours,
build_minutes,
line_number,
reserved] = makerbot_driver.Encoder.unpack_response('<BBBBLL', response)
# TODO: check response_code
info = {
'BuildState': build_state,
'BuildHours': build_hours,
'BuildMinutes': build_minutes,
'LineNumber': line_number,
'Reserved': reserved
}
return info
def <API key>(self):
"""
Get some communication statistics about traffic on the tool network from the Host.
@return a dictionary of communication stats, keyed by stat name
"""
payload = struct.pack(
'<B',
makerbot_driver.<API key>['<API key>'],
)
response = self.writer.send_query_payload(payload)
[response_code,
packetsReceived,
packetsSent,
<API key>,
packetRetries,
noiseBytes] = makerbot_driver.Encoder.unpack_response('<BLLLLL', response)
# TODO: check response_code
info = {
'PacketsReceived': packetsReceived,
'PacketsSent': packetsSent,
'<API key>': <API key>,
'PacketRetries': packetRetries,
'NoiseBytes': noiseBytes,
}
return info
def <API key>(self):
"""
Retrieve bits of information about the motherboard
POWER_ERROR : An error was detected with the system power.
HEAT_SHUTDOWN : The heaters were shutdown because the bot was inactive for over 20 minutes
@return: A python dictionary of various flags and whether they were set or not at reset
"""
payload = struct.pack(
'<B',
makerbot_driver.<API key>['<API key>'],
)
response = self.writer.send_query_payload(payload)
[response_code, bitfield] = makerbot_driver.Encoder.unpack_response(
'<BB', response)
# TODO: check response_code
bitfield = makerbot_driver.Encoder.decode_bitfield(bitfield)
flags = {
'preheat': bitfield[0],
'manual_mode': bitfield[1],
'onboard_script': bitfield[2],
'onboard_process': bitfield[3],
'wait_for_button': bitfield[4],
'build_cancelling': bitfield[5],
'heat_shutdown': bitfield[6],
'power_error': bitfield[7],
}
return flags
def extended_stop(self, halt_steppers, clear_buffer):
"""
Stop the stepper motor motion and/or reset the command buffer. This differs from the
reset and abort commands in that a soft reset of all functions isnt called.
@param boolean halt_steppers: A flag that if true will stop the steppers
@param boolean clear_buffer: A flag that, if true, will clear the buffer
"""
bitfield = 0
if halt_steppers:
bitfield |= 0x01
if clear_buffer:
bitfield |= 0x02
payload = struct.pack(
'<Bb',
makerbot_driver.<API key>['EXTENDED_STOP'],
bitfield,
)
response = self.writer.send_query_payload(payload)
[response_code, <API key>] = makerbot_driver.Encoder.unpack_response('<BB', response)
# TODO: check response_code
if <API key> != 0:
raise makerbot_driver.ExtendedStopError
def <API key>(self, tool_index, delay, timeout):
"""
Halts the machine until the specified toolhead reaches a ready state, or if the
timeout is reached. Toolhead is ready if its temperature is within a specified
range.
@param int tool_index: toolhead index
@param int delay: Time in ms between packets to query the toolhead
@param int timeout: Time to wait in seconds for the toolhead to heat up before moving on
"""
payload = struct.pack(
'<BBHH',
makerbot_driver.<API key>[
'<API key>'],
tool_index,
delay,
timeout
)
self.writer.send_action_payload(payload)
def wait_for_tool_ready(self, tool_index, delay, timeout):
"""
Halts the machine until the specified toolhead reaches a ready state, or if the
timeout is reached. Toolhead is ready if its temperature is within a specified
range.
@param int tool_index: toolhead index
@param int delay: Time in ms between packets to query the toolhead
@param int timeout: Time to wait in seconds for the toolhead to heat up before moving on
"""
payload = struct.pack(
'<BBHH',
makerbot_driver.<API key>['WAIT_FOR_TOOL_READY'],
tool_index,
delay,
timeout
)
self.writer.send_action_payload(payload)
def delay(self, delay):
"""
Halts all motion for the specified amount of time
@param int delay: delay time, in microseconds
"""
payload = struct.pack(
'<BI',
makerbot_driver.<API key>['DELAY'],
delay
)
self.writer.send_action_payload(payload)
def change_tool(self, tool_index):
"""
Change to the specified toolhead
@param int tool_index: toolhead index
"""
payload = struct.pack(
'<BB',
makerbot_driver.<API key>['CHANGE_TOOL'],
tool_index
)
self.writer.send_action_payload(payload)
def toggle_axes(self, axes, enable):
"""
Used to explicitly power steppers on or off.
@param list axes: Array of axis names ['x', 'y', ...] to configure
@param boolean enable: If true, enable all selected axes. Otherwise, disable the selected
axes.
"""
axes_bitfield = makerbot_driver.Encoder.encode_axes(axes)
if enable:
axes_bitfield |= 0x80
payload = struct.pack(
'<BB',
makerbot_driver.<API key>['ENABLE_AXES'],
axes_bitfield
)
self.writer.send_action_payload(payload)
def <API key>(self, position, duration, relative_axes):
"""
Queue a position with the new style! Moves to a certain position over a given duration
with either relative or absolute positioning. Relative vs. Absolute positioning
is done on an axis to axis basis.
@param list position: A 5 dimentional position in steps specifying where each axis should move to
@param int duration: The total duration of the move in miliseconds
@param list relative_axes: Array of axes whose coordinates should be considered relative
"""
if len(position) != s3g.<API key>:
raise makerbot_driver.PointLengthError(len(position))
payload = struct.pack(
'<BiiiiiIB',
makerbot_driver.<API key>[
'<API key>'],
position[0], position[1], position[2], position[3], position[4],
duration,
makerbot_driver.Encoder.encode_axes(relative_axes)
)
self.writer.send_action_payload(payload)
def <API key>(self, axes):
"""
Write the current axes locations to the EEPROM as the home position
@param list axes: Array of axis names ['x', 'y', ...] whose position should be saved
"""
payload = struct.pack(
'<BB',
makerbot_driver.<API key>['<API key>'],
makerbot_driver.Encoder.encode_axes(axes)
)
self.writer.send_action_payload(payload)
def <API key>(self, axis, value):
"""
Sets the value of the digital potentiometers that control the voltage references for the botsteps
@param axis: Axis whose potentiometers should be set. Each axis has a specific code:
X: 0,
Y: 1,
Z: 2,
A: 3,
B: 4,
@param int value: The value to set the digital potentiometer to.
"""
max_value = 127
value = min(value, max_value)
payload = struct.pack(
'<BBB',
makerbot_driver.<API key>['SET_POT_VALUE'],
axis,
value,
)
self.writer.send_action_payload(payload)
def set_beep(self, frequency, duration):
"""
Play a tone of the specified frequency for the specified duration.
@param int frequency: Frequency of the tone, in hz
@param int duration: Duration of the tone, in ms
"""
payload = struct.pack(
'<BHHB',
makerbot_driver.<API key>['SET_BEEP'],
frequency,
duration,
0x00
)
self.writer.send_action_payload(payload)
def set_RGB_LED(self, r, g, b, blink):
"""
Set the brightness and blink rate for RBG LEDs
@param int r: The r value (0-255) for the LEDs
@param int g: The g value (0-255) for the LEDs
@param int b: The b value (0-255) for the LEDs
@param int blink: The blink rate (0-255) for the LEDs
"""
payload = struct.pack(
'<BBBBBB',
makerbot_driver.<API key>['SET_RGB_LED'],
r,
g,
b,
blink,
0x00
)
self.writer.send_action_payload(payload)
def <API key>(self, axes):
"""
Recall and move to the home positions written to the EEPROM
@param axes: Array of axis names ['x', 'y', ...] whose position should be saved
"""
payload = struct.pack(
'<BB',
makerbot_driver.<API key>['<API key>'],
makerbot_driver.Encoder.encode_axes(axes)
)
self.writer.send_action_payload(payload)
def init(self):
"""
Sends 'init' packet to machine to Initialize the machine to a default state
"""
payload = struct.pack(
'<B',
makerbot_driver.<API key>['INIT']
)
self.writer.send_action_payload(payload)
def tool_query(self, tool_index, command, tool_payload=None):
"""
Query a toolhead for some information
@param int tool_index: toolhead index
@param int command: command to send to the toolhead
@param bytearray tool_payload: payload that goes along with the command, or None
if the command does not have a payload
@return bytearray payload: received from the tool
"""
if tool_index > makerbot_driver.max_tool_index or tool_index < 0:
raise makerbot_driver.ToolIndexError(1)
payload = struct.pack(
'<%s' % self.tool_query_code,
makerbot_driver.<API key>['TOOL_QUERY'],
tool_index,
command,
)
if tool_payload is not None:
payload += tool_payload
return self.writer.send_query_payload(payload)
def <API key>(self, name=None, context=None):
return self.eeprom_reader.read_data(name, context)
def read_from_EEPROM(self, offset, length):
"""
Read some data from the machine. The data structure is implementation specific.
@param byte offset: EEPROM location to begin reading from
@param int length: Number of bytes to read from the EEPROM (max 31)
@return byte array of data read from EEPROM
"""
# We can only read 31 bytes
if length > makerbot_driver.<API key> - 1:
raise makerbot_driver.EEPROMLengthError(length)
payload = struct.pack(
'<BHb',
makerbot_driver.<API key>['READ_FROM_EEPROM'],
offset,
length
)
response = self.writer.send_query_payload(payload)
return response[1:]
def write_to_EEPROM(self, offset, data):
"""
Write some data to the machine. The data structure is implementation specific.
@param byte offset: EEPROM location to begin writing to
@param int data: Data to write to the EEPROM
"""
code = '<Bhb'
# Check the length of data against <API key> and the compulsory packet values
if len(data) > makerbot_driver.<API key> - struct.calcsize(code):
raise makerbot_driver.EEPROMLengthError(len(data))
payload = struct.pack(
code,
makerbot_driver.<API key>['WRITE_TO_EEPROM'],
offset,
len(data),
)
payload += data
response = self.writer.send_query_payload(payload)
if response[1] != len(data):
raise makerbot_driver.EEPROMMismatchError(response[1])
def <API key>(self):
"""
Gets the available buffer size
@return Available buffer size, in bytes
"""
payload = struct.pack(
'<B',
makerbot_driver.<API key>[
'<API key>'],
)
response = self.writer.send_query_payload(payload)
[response_code, buffer_size] = makerbot_driver.Encoder.unpack_response(
'<BI', response)
# TODO: check response_code
return buffer_size
def abort_immediately(self):
"""
Stop the machine by disabling steppers, clearing the command buffers, and
instructing the toolheads to shut down
"""
payload = struct.pack(
'<B',
makerbot_driver.<API key>['ABORT_IMMEDIATELY']
)
resposne = self.writer.send_query_payload(payload)
def playback_capture(self, filename):
"""
Instruct the machine to play back (build) a file from it's SD card.
@param str filename: Name of the file to print. Should have been retrieved by
"""
payload = struct.pack(
'<B',
makerbot_driver.<API key>['PLAYBACK_CAPTURE'],
)
payload += filename
payload += '\x00'
response = self.writer.send_query_payload(payload)
[response_code, sd_response_code] = makerbot_driver.Encoder.unpack_response('<BB', response)
# TODO: check response_code
if sd_response_code != makerbot_driver.sd_error_dict['SUCCESS']:
raise makerbot_driver.SDCardError(sd_response_code)
def get_next_filename(self, reset):
"""
Gets the 'next' filename on the SD card if an SD card is inserted into the 'bot
@param boolean reset: If true, reset the file index to zero and return the first available filename.
@return the next filename on the machine, as a string.
"""
flag = 1 if reset else 0
payload = struct.pack(
'<Bb',
makerbot_driver.<API key>['GET_NEXT_FILENAME'],
flag,
)
response = self.writer.send_query_payload(payload)
[response_code, sd_response_code, filename] = makerbot_driver.Encoder.<API key>('<BB', response)
# TODO: check response_code
if sd_response_code != makerbot_driver.sd_error_dict['SUCCESS']:
raise makerbot_driver.SDCardError(sd_response_code)
return filename
def get_build_name(self):
"""
Get the build name of the file printing on the machine, if any.
@param str filename: The filename of the current print
"""
payload = struct.pack(
'<B',
makerbot_driver.<API key>['GET_BUILD_NAME']
)
response = self.writer.send_query_payload(payload)
[response_code, filename] = makerbot_driver.Encoder.<API key>('<B', response)
# TODO: check response_code
return filename
def <API key>(self):
"""
Gets the current machine position
@return tuple position: containing the current 5D position (x,y,z,a,b) location and endstop states.
"""
payload = struct.pack(
'<B',
makerbot_driver.<API key>['<API key>'],
)
response = self.writer.send_query_payload(payload)
[response_code,
x, y, z, a, b,
endstop_states] = makerbot_driver.Encoder.unpack_response('<BiiiiiH', response)
# TODO: check response_code
return [x, y, z, a, b], endstop_states
def find_axes_minimums(self, axes, rate, timeout):
"""
Move the toolhead in the negativedirection, along the specified axes,
until an endstop is reached or a timeout occurs.
@param list axes: Array of axis names ['x', 'y', ...] to move
@param double rate: Movement rate, in steps/??
@param double timeout: Amount of time in seconds to move before halting the command
"""
payload = struct.pack(
'<BBIH',
makerbot_driver.<API key>['FIND_AXES_MINIMUMS'],
makerbot_driver.Encoder.encode_axes(axes),
rate,
timeout
)
self.writer.send_action_payload(payload)
def find_axes_maximums(self, axes, rate, timeout):
"""
Move the toolhead in the positive direction, along the specified axes,
until an endstop is reached or a timeout occurs.
@param list axes: Array of axis names ['x', 'y', ...] to move
@param double rate: Movement rate, in steps/??
@param double timeout: Amount of time to move in seconds before halting the command
"""
payload = struct.pack(
'<BBIH',
makerbot_driver.<API key>['FIND_AXES_MAXIMUMS'],
makerbot_driver.Encoder.encode_axes(axes),
rate,
timeout
)
self.writer.send_action_payload(payload)
def tool_action_command(self, tool_index, command, tool_payload=''):
"""
Send a command to a toolhead
@param int tool_index: toolhead index
@param int command: command to send to the toolhead
@param bytearray tool_payload: payload that goes along with the command
"""
if tool_index > makerbot_driver.max_tool_index or tool_index < 0:
raise makerbot_driver.ToolIndexError(tool_index)
payload = struct.pack(
'<BBBB',
makerbot_driver.<API key>['TOOL_ACTION_COMMAND'],
tool_index, command, len(tool_payload)
)
if tool_payload != '':
payload += tool_payload
self.writer.send_action_payload(payload)
def <API key>(self, position, dda_rate, relative_axes, distance, feedrate):
"""
Queue a position with the x3g style! Moves to a certain position over a given duration
with either relative or absolute positioning. Relative vs. Absolute positioning
is done on an axis to axis basis.
@param list position: A 5 dimentional position in steps specifying where each axis should move to
@param int dda_rate: Steps per second along the master axis
@param list relative_axes: Array of axes whose coordinates should be considered relative
@param float distance: distance in millimeters moved in (x,y,z) space OR if distance(x,y,z) == 0, then max(distance(A),distance(B))
@param float feedrate: the actual feedrate in units of millimeters/second
"""
if len(position) != s3g.<API key>:
raise makerbot_driver.PointLengthError(len(position))
payload = struct.pack(
'<BiiiiiIBfh',
makerbot_driver.makerbot_driver.<API key>[
'<API key>'],
position[0], position[1], position[2], position[3], position[4],
dda_rate,
makerbot_driver.Encoder.encode_axes(relative_axes),
float(distance),
int(feedrate * 64.0)
)
self.writer.send_action_payload(payload)
def <API key>(self, position, dda_speed, e_distance, feedrate_mm_sec, relative_axes=[]):
"""
Queue a position: this function chooses the correct movement command based on the print_to_file_type
Moves to a certain position over a given duration with either relative or absolute positioning.
Relative vs. Absolute positioning is done on an axis to axis basis.
@param list position: A 5 dimentional position in steps specifying where each axis should move to
@param int dda_speed: microseconds per step
@param float e_distance: distance in millimeters moved in (x,y,z) space OR if distance(x,y,z) == 0, then max(distance(A),distance(B))
@param float feedrate_mm_sec: the actual feedrate in units of millimeters/second
@param list relative_axes: Array of axes whose coordinates should be considered relative
"""
if len(position) != s3g.<API key>:
raise makerbot_driver.PointLengthError(len(position))
if self.print_to_file_type == 'x3g' :
dda_rate = 1000000.0 / float(dda_speed)
self.<API key>(position, dda_rate, relative_axes,
e_distance, feedrate_mm_sec)
else:
self.<API key>(position, dda_speed)
def <API key>(self, position, dda_speed):
"""
Queue a position with the classic style! Moves to a certain position over a given duration
with either relative or absolute positioning. Relative vs. Absolute positioning
is done on an axis to axis basis.
@param list position: A 5 dimentional position in steps specifying where each axis should move to
@param int dda_speed: microseconds per step
"""
if len(position) != s3g.<API key>:
raise makerbot_driver.PointLengthError(len(position))
payload = struct.pack(
'<BiiiiiI',
makerbot_driver.<API key>[
'<API key>'],
position[0], position[1], position[2],
position[3], position[4], dda_speed
)
self.writer.send_action_payload(payload)
def <API key>(self, position):
"""
Inform the machine that it should consider this point its current point
@param list position: 5D position to set the machine to, in steps.
"""
if len(position) != s3g.<API key>:
raise makerbot_driver.PointLengthError(len(position))
payload = struct.pack(
'<Biiiii',
makerbot_driver.<API key>['<API key>'],
position[0], position[1], position[2],
position[3], position[4],
)
self.writer.send_action_payload(payload)
def wait_for_button(self, button, timeout, ready_on_timeout, reset_on_timeout, clear_screen):
"""
Wait until a user either presses a button on the interface board, or a timeout occurs
@param str button: A button, must be one of the following: up, down, left, right center.
@param double timeout: Duration, in seconds, the bot will wait for a response.
A timeout of 0 indicated no timeout. TimeoutReadyState, timeoutReset determine what
action is taken after timeout
@param boolean ready_on_timeout: Bot changes to the ready state after tiemout
@param boolean reset_on_timeout: Resets the bot on timeout
@param boolean clear_screen: Clears the screen on button press
"""
if button == 'center':
button = 0x01
elif button == 'right':
button = 0x02
elif button == 'left':
button = 0x04
elif button == 'down':
button = 0x08
elif button == 'up':
button = 0x10
else:
raise makerbot_driver.ButtonError(button)
optionsField = 0
if ready_on_timeout:
optionsField |= 0x01
if reset_on_timeout:
optionsField |= 0x02
if clear_screen:
optionsField |= 0x04
payload = struct.pack(
'<BBHB',
makerbot_driver.<API key>['WAIT_FOR_BUTTON'],
button,
timeout,
optionsField
)
self.writer.send_action_payload(payload)
def reset_to_factory(self):
"""
Calls factory reset on the EEPROM. Resets all values to their factory settings. Also soft resets the board
"""
payload = struct.pack(
'<BB',
makerbot_driver.<API key>['RESET_TO_FACTORY'],
0x00
)
self.writer.send_action_payload(payload)
def queue_song(self, song_id):
"""
Play predefined sogns on the piezo buzzer
@param int songId: The id of the song to play.
"""
payload = struct.pack(
'<BB',
makerbot_driver.<API key>['QUEUE_SONG'],
song_id
)
self.writer.send_action_payload(payload)
def set_build_percent(self, percent):
"""
Sets the percentage done for the current build. This value is displayed on the interface board's screen.
@param int percent: Percent of the build done (0-100)
"""
payload = struct.pack(
'<BBB',
makerbot_driver.<API key>['SET_BUILD_PERCENT'],
percent,
0x00
)
self.writer.send_action_payload(payload)
def display_message(self, row, col, message, timeout, clear_existing, last_in_group, wait_for_button):
"""
Display a message to the screen
@param int row: Row to draw the message at
@param int col: Column to draw the message at
@param str message: Message to write to the screen
@param int timeout: Amount of time to display the message for, in seconds.
If 0, leave the message up indefinately.
@param boolean clear_existing: If True, This will clear the existing message buffer and timeout
@param boolean last_in_group: If true, signifies that this message is the last in a group of messages
@param boolean wait_for_button: If true, waits for a button to be pressed before clearing the screen
"""
bitField = 0
if clear_existing:
bitField |= 0x01
if last_in_group:
bitField |= 0x02
if wait_for_button:
bitField |= 0x04
payload = struct.pack(
'<BBBBB',
makerbot_driver.<API key>['DISPLAY_MESSAGE'],
bitField, col, row, timeout,
)
payload += message
payload += '\x00'
self.writer.send_action_payload(payload)
def <API key>(self, build_name):
"""
Notify the machine that a build has been started.
If the build_name is too long, we will truncate it to its
maximum allowed length relative to the makerbot_driver.<API key>.
@param str build_name Name of the build
"""
<API key> = 7
if len(build_name) > makerbot_driver.<API key> - <API key>:
build_name = build_name[:makerbot_driver.<API key> -
<API key>]
payload = struct.pack(
'<BI',
makerbot_driver.<API key>[
'<API key>'], 0
)
payload += build_name
payload += '\x00'
self.writer.send_action_payload(payload)
def <API key>(self):
"""
Notify the machine that a build has been stopped.
"""
payload = struct.pack(
'<BB',
makerbot_driver.<API key>['<API key>'],
0,
)
self.writer.send_action_payload(payload)
def <API key>(self, tool_index):
"""
Get the firmware version number of the specified toolhead
@return double Version number
"""
payload = struct.pack(
'<H', makerbot_driver.s3g_version)
response = self.tool_query(
tool_index, makerbot_driver.<API key>['GET_VERSION'], payload)
[response_code, version] = makerbot_driver.Encoder.unpack_response(
'<BH', response)
# TODO: check response_code
return version
def get_PID_state(self, tool_index):
"""
Retrieve the state variables of the PID controller. This is intended for tuning the PID Constants
@param int tool_index: Which tool index to query for information
@return dictionary The terms associated with the tool_index'sError Term, Delta Term, Last Output
and the platform's Error Term, Delta Term and Last Output
"""
response = self.tool_query(
tool_index, makerbot_driver.<API key>['GET_PID_STATE'])
[response_code, exError, exDelta, exLast, plError, plDelta, plLast] = makerbot_driver.Encoder.unpack_response('<Bhhhhhh', response)
# TODO: check response_code
PIDVals = {
"ExtruderError": exError,
"ExtruderDelta": exDelta,
"ExtruderLastTerm": exLast,
"PlatformError": plError,
"PlatformDelta": plDelta,
"PlatformLastTerm": plLast,
}
return PIDVals
def get_tool_status(self, tool_index):
"""
Retrieve some information about the tool, as a status dictionary
statusDict = {
ExtruderReady : The extruder has reached target temp
<API key> : The extruder thermocouple is not detected by the bot
ExturderOverMaxTemp : The temperature measured at the extruder is greater than max allowed
ExtruderNotHeating : In the first 40 seconds after target temp was set, the extruder is not heating up as expected
<API key> : After reaching and maintaining temperature, the extruder temp has dropped 30 degrees below target
PlatformError: an error was detected with the platform heater (if the tool supports one).
The platform heater will fail if an error is detected with the sensor (thermocouple)
or if the temperature reading appears to be unreasonable.
ExtruderError: An error was detected with the extruder heater (if the tool supports one).
The extruder heater will fail if an error is detected with the sensor (thermocouple) or
if the temperature reading appears to be unreasonable
}
@param int tool_index: The tool we would like to query for information
@return A dictionary containing status information specified above
"""
response = self.tool_query(
tool_index, makerbot_driver.<API key>['GET_TOOL_STATUS'])
[resonse_code, bitfield] = makerbot_driver.Encoder.unpack_response(
'<BB', response)
# TODO: check response_code
bitfield = makerbot_driver.Encoder.decode_bitfield(bitfield)
returnDict = {
"ExtruderReady": bitfield[0],
"<API key>": bitfield[1],
"ExtruderOverMaxTemp": bitfield[2],
"ExtruderNotHeating": bitfield[3],
"<API key>": bitfield[4],
"PlatformError": bitfield[6],
"ExtruderError": bitfield[7],
}
return returnDict
def set_servo1_position(self, tool_index, theta):
"""
Sets the tool_index's servo as position 1 to a certain angle
@param int tool_index: The tool that will be set
@param int theta: angle to set the servo to
"""
payload = struct.pack(
'<B',
theta
)
self.tool_action_command(tool_index, makerbot_driver.<API key>[
'<API key>'], payload)
def toolhead_abort(self, tool_index):
"""
Used to terminate a build during printing. Disables any engaged heaters and motors
@param int tool_index: the tool which is to be aborted
"""
self.tool_action_command(
tool_index, makerbot_driver.<API key>['ABORT'])
def toolhead_pause(self, tool_index):
"""
This function is intended to be called infrequently by the end user to pause the toolhead
and make various adjustments during a print
@param int tool_index: The tool which is to be paused
"""
self.tool_action_command(
tool_index, makerbot_driver.<API key>['PAUSE'])
def toggle_motor1(self, tool_index, toggle, direction):
"""
Toggles the motor of a certain toolhead to be either on or off. Can also set direction.
@param int tool_index: the tool's motor that will be set
@param boolean toggle: The enable/disable flag. If true, will turn the motor on. If false, disables the motor.
@param boolean direction: If true, sets the motor to turn clockwise. If false, sets the motor to turn counter-clockwise
"""
bitfield = 0
if toggle:
bitfield |= 0x01
if direction:
bitfield |= 0x02
payload = struct.pack(
'<B',
bitfield,
)
self.tool_action_command(
tool_index, makerbot_driver.<API key>['TOGGLE_MOTOR_1'], payload)
def <API key>(self, tool_index, duration):
"""
This sets the motor speed as an RPM value
@param int tool_index : The tool's motor that will be set
@param int duration : Durtation of each rotation, in microseconds
"""
payload = struct.pack(
'<I',
duration
)
self.tool_action_command(tool_index, makerbot_driver.<API key>[
'<API key>'], payload)
def <API key>(self, tool_index, direction):
"""
This sets the direction of rotation for the motor
@param int tool_index: The tool's motor that will be set
@param boolean direction: If true, sets the motor to turn clockwise. If false, sets the motor to turn counter-clockwise
"""
clockwise = 0
if direction:
clockwise = 1
payload = struct.pack(
'<B',
clockwise
)
self.tool_action_command(tool_index, makerbot_driver.<API key>['<API key>'], payload)
def get_motor1_speed(self, tool_index):
"""
Gets the toohead's motor speed in Rotations per Minute (RPM)
@param int tool_index: The tool index that will be queried for Motor speed
@return int Duration of each rotation, in miliseconds
"""
response = self.tool_query(
tool_index, makerbot_driver.<API key>['<API key>'])
[response_code,
speed] = makerbot_driver.Encoder.unpack_response('<BI', response)
# TODO: check response_code
return speed
def <API key>(self, tool_index):
"""
Retrieve the toolhead temperature
@param int tool_index: Toolhead Index
@return int temperature: reported by the toolhead
"""
response = self.tool_query(
tool_index, makerbot_driver.<API key>['GET_TOOLHEAD_TEMP'])
[response_code, temperature] = makerbot_driver.Encoder.unpack_response(
'<BH', response)
# TODO: check response_code
return temperature
def is_tool_ready(self, tool_index):
"""
Determine if the tool is at temperature, and is therefore ready to be used.
@param int tool_index: Toolhead Index
@return boolean isReady: True if tool is done heating, false otherwise
"""
response = self.tool_query(
tool_index, makerbot_driver.<API key>['IS_TOOL_READY'])
[response_code,
ready] = makerbot_driver.Encoder.unpack_response('<BB', response)
# TODO: check response_code
isReady = False
if ready == 1:
isReady = True
elif ready == 0:
isReady = False
else:
raise makerbot_driver.<API key>(ready)
return isReady
def <API key>(self, tool_index, offset, length):
"""
Read some data from the toolhead. The data structure is implementation specific.
@param byte offset: EEPROM location to begin reading from
@param int length: Number of bytes to read from the EEPROM (max 31)
@return byte array: of data read from EEPROM
"""
# We can only read 31 bytes
if length > makerbot_driver.<API key> - 1:
raise makerbot_driver.EEPROMLengthError(length)
payload = struct.pack(
'<HB',
offset,
length
)
response = self.tool_query(
tool_index, makerbot_driver.<API key>['READ_FROM_EEPROM'], payload)
return response[1:]
def <API key>(self, tool_index, offset, data):
"""
Write some data to the toolhead. The data structure is implementation specific.
@param int tool_index: Index of tool to access
@param byte offset: EEPROM location to begin writing to
@param list data: Data to write to the EEPROM
"""
code = '<HB'
packet_length = struct.calcsize('%s%s' % (code, self.tool_query_code))
# Check the length of data against <API key> and the compulsory packet values
# (Including Tool Packet values
if len(data) > makerbot_driver.<API key> - packet_length:
raise makerbot_driver.EEPROMLengthError(len(data))
payload = struct.pack(
code,
offset,
len(data),
)
payload += data
response = self.tool_query(
tool_index, makerbot_driver.<API key>['WRITE_TO_EEPROM'], payload)
if response[1] != len(data):
raise makerbot_driver.EEPROMMismatchError(response[1])
def <API key>(self, tool_index):
"""
Retrieve the build platform temperature
@param int tool_index: Toolhead Index
@return int temperature: reported by the toolhead
"""
response = self.tool_query(
tool_index, makerbot_driver.<API key>['GET_PLATFORM_TEMP'])
[response_code, temperature] = makerbot_driver.Encoder.unpack_response(
'<BH', response)
# TODO: check response_code
return temperature
def <API key>(self, tool_index):
"""
Retrieve the toolhead target temperature (setpoint)
@param int tool_index: Toolhead Index
@return int temperature: that the toolhead is attempting to achieve
"""
response = self.tool_query(
tool_index, makerbot_driver.<API key>['<API key>'])
[response_code, temperature] = makerbot_driver.Encoder.unpack_response(
'<BH', response)
# TODO: check response_code
return temperature
def <API key>(self, tool_index):
"""
Retrieve the build platform target temperature (setpoint)
@param int tool_index: Toolhead Index
@return int temperature: that the build platform is attempting to achieve
"""
response = self.tool_query(
tool_index, makerbot_driver.<API key>['<API key>'])
[response_code, temperature] = makerbot_driver.Encoder.unpack_response(
'<BH', response)
# TODO: check response_code
return temperature
def is_platform_ready(self, tool_index):
"""
Determine if the platform is at temperature, and is therefore ready to be used.
@param int tool_index: Toolhead Index
@return boolean isReady: true if the platform is at target temperature, false otherwise
"""
response = self.tool_query(
tool_index, makerbot_driver.<API key>['IS_PLATFORM_READY'])
[response_code,
ready] = makerbot_driver.Encoder.unpack_response('<BB', response)
# TODO: check response_code
isReady = False
if ready == 1:
isReady = True
elif ready == 0:
isReady = False
else:
raise makerbot_driver.<API key>(ready)
return isReady
def toggle_fan(self, tool_index, state):
"""
Turn the fan output on or off
@param int tool_index: Toolhead Index
@param boolean state: If True, turn the fan on, otherwise off.
"""
if state is True:
payload = '\x01'
else:
payload = '\x00'
self.tool_action_command(
tool_index, makerbot_driver.<API key>['TOGGLE_FAN'], payload)
def toggle_extra_output(self, tool_index, state):
"""
Turn the extra output on or off
@param int tool_index: Toolhead Index
@param boolean state: If True, turn the extra output on, otherwise off.
"""
if state is True:
payload = '\x01'
else:
payload = '\x00'
self.tool_action_command(tool_index, makerbot_driver.<API key>[
'TOGGLE_EXTRA_OUTPUT'], payload)
def toolhead_init(self, tool_index):
"""
Resets a certain tool_index to its initialized boot state, which
consists of:
resetting target temp to 0, turn off all outputs, detaching all
servo devices, setting motor speed to 0
@param int tool_index: The tool to re-initialize
"""
self.tool_action_command(tool_index,
makerbot_driver.<API key>['INIT'])
def <API key>(self, tool_index, temperature):
"""
Set a certain toolhead's temperature
@param int tool_index: Toolhead Index
@param int Temperature: Temperature to heat up to in Celcius
"""
payload = struct.pack('<H', temperature)
self.tool_action_command(tool_index,
makerbot_driver.<API key>['<API key>'], payload)
def <API key>(self, tool_index, temperature):
"""
Set the platform's temperature
@param int tool_index: Platform Index
@param int Temperature: Temperature to heat up to in Celcius
"""
payload = struct.pack('<H', temperature)
self.tool_action_command(
tool_index,
makerbot_driver.<API key>['SET_PLATFORM_TEMP'], payload)
def toggle_ABP(self, tool_index, state):
"""
This sets the on/off state of the ABP's conveyor belt
@param boolean : Turns on or off the ABP's conveyor belt
"""
enable = 0
if state:
enable = 1
payload = struct.pack(
'<B',
enable
)
self.tool_action_command(tool_index, makerbot_driver.<API key>['TOGGLE_ABP'], payload)
def set_servo2_position(self, tool_index, theta):
"""
Sets the tool_index's servo as position 2 to a certain angle
@param int tool_index: The tool that will be set
@param int theta: angle to set the servo to
"""
payload = struct.pack(
'<B',
theta
)
self.tool_action_command(tool_index, makerbot_driver.<API key>['<API key>'], payload)
def x3g_version(self, high_bite, low_bite, checksum=0x0000, pid=0xB015):
"""
Send an x3g_version packet to inform the bot what version
x3g we are sending and potential checksum for succeeding
commands.
@param int high_bite: High bite for version (i.e. 1 for 1.0)
@param int low_bite: Low bite for version (i.e. 0 for 1.0)
@param int pid: PID for the bot you want to print to
@param int checksum: Checksum for succeeding commands
"""
payload = struct.pack(
'<BBBBIHBBBBBBBBBBB',
makerbot_driver.<API key>['X3G_VERSION'],
high_bite,
low_bite,
0,
checksum,
pid,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
)
self.writer.send_action_payload(payload) |
# This program is free software: you can redistribute it and/or modify
# published by the Free Software Foundation, either version 3 of the
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# modification, are permitted provided that the following conditions
# are met:
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of the author nor the names of other
# contributors may be used to endorse or promote products derived
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
# OF THE POSSIBILITY OF SUCH DAMAGE.
# This program is free software: you can redistribute it and/or modify
# published by the Free Software Foundation, either version 3 of the
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
"""Test cases for Gstudio's url_shortener"""
from __future__ import with_statement
import warnings
from django.test import TestCase
from gstudio.url_shortener import get_url_shortener
from gstudio import url_shortener as us_settings
from gstudio.url_shortener.backends.default import backend as default_backend
class <API key>(TestCase):
"""Test cases for gstudio.url_shortener"""
def setUp(self):
self.original_backend = us_settings.<API key>
def tearDown(self):
us_settings.<API key> = self.original_backend
def <API key>(self):
us_settings.<API key> = 'mymodule.myclass'
try:
with warnings.catch_warnings(record=True) as w:
self.assertEquals(get_url_shortener(), default_backend)
self.assertTrue(issubclass(w[-1].metatype, RuntimeWarning))
self.assertEquals(
str(w[-1].message),
'mymodule.myclass backend cannot be imported')
except AttributeError:
# Fail under Python2.5, because of'warnings.catch_warnings'
pass
us_settings.<API key> = 'gstudio.tests.<API key>'
try:
with warnings.catch_warnings(record=True) as w:
self.assertEquals(get_url_shortener(), default_backend)
self.assertTrue(issubclass(w[-1].metatype, RuntimeWarning))
self.assertEquals(
str(w[-1].message),
'This backend only exists for testing')
except AttributeError:
# Fail under Python2.5, because of'warnings.catch_warnings'
pass
us_settings.<API key> = 'gstudio.url_shortener'\
'.backends.default'
self.assertEquals(get_url_shortener(), default_backend) |
# -*- coding: utf-8 -*-
# Complete rewrite during flask migration
# Try to provide REST API
# privacyIDEA is a fork of LinOTP. Some code is adapted from
# the system-controller from LinOTP, which is
# linotp@lsexperts.de
# This code is free software; you can redistribute it and/or
# This code is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# You should have received a copy of the GNU Affero General Public
__doc__ = """The realm endpoints are used to define realms.
A realm groups together many users. Administrators can manage the tokens of
the users in such a realm. Policies and tokens can be assigned to realms.
A realm consists of several resolvers. Thus you can create a realm and gather
users from LDAP and flat file source into one realm or you can pick resolvers
that collect users from different points from your vast LDAP directory and
group these users into a realm.
You will only be able to see and use user object, that are contained in a realm.
The code of this module is tested in tests/test_api_system.py
"""
from flask import (Blueprint,
request, current_app)
from lib.utils import (getParam,
required,
send_result, <API key>)
from ..lib.log import log_with
from ..lib.realm import get_realms
from ..lib.realm import (set_default_realm,
get_default_realm,
set_realm,
delete_realm)
from ..lib.policy import ACTION
from ..api.lib.prepolicy import prepolicy, check_base_action
from flask import g
from gettext import gettext as _
import logging
log = logging.getLogger(__name__)
realm_blueprint = Blueprint('realm_blueprint', __name__)
<API key> = Blueprint('<API key>', __name__)
# REALM functions
@log_with(log)
@realm_blueprint.route('/<realm>', methods=['POST'])
@prepolicy(check_base_action, request, ACTION.RESOLVERWRITE)
def set_realm_api(realm=None):
"""
This call creates a new realm or reconfigures a realm.
The realm contains a list of resolvers.
In the result it returns a list of added resolvers and a list of
resolvers, that could not be added.
:param realm: The unique name of the realm
:param resolvers: A comma separated list of unique resolver names or a
list object
:type resolvers: string or list
:param priority: Additional parameters priority.<resolvername> define the
priority of the resolvers within this realm.
:return: a json result with a list of Realms
**Example request**:
To create a new realm "newrealm", that consists of the resolvers
"reso1_with_realm" and "reso2_with_realm" call:
.. sourcecode:: http
POST /realm/newrealm HTTP/1.1
Host: example.com
Accept: application/json
Content-Length: 26
Content-Type: application/<API key>
resolvers=reso1_with_realm, reso2_with_realm
priority.reso1_with_realm=1
priority.reso2_with_realm=2
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"status": true,
"value": {
"added": ["reso1_with_realm", "reso2_with_realm"],
"failed": []
}
}
"version": "privacyIDEA unknown"
}
"""
param = request.all_data
resolvers = getParam(param, "resolvers", required)
priority = <API key>(param)
if type(resolvers) == "list":
Resolvers = resolvers
else:
Resolvers = resolvers.split(',')
(added, failed) = set_realm(realm, Resolvers, priority=priority)
g.audit_object.log({'success': len(added) == len(Resolvers),
'info': "realm: %r, resolvers: %r" % (realm,
resolvers)})
return send_result({"added": added,
"failed": failed})
@log_with(log)
@realm_blueprint.route('/', methods=['GET'])
def get_realms_api():
"""
This call returns the list of all defined realms.
It takes no arguments.
:return: a json result with a list of realms
**Example request**:
.. sourcecode:: http
GET / HTTP/1.1
Host: example.com
Accept: application/json
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"status": true,
"value": {
"<API key>": {
"default": true,
"resolver": [
{
"name": "reso1_with_realm",
"type": "passwdresolver"
}
]
}
}
},
"version": "privacyIDEA unknown"
}
"""
realms = get_realms()
g.audit_object.log({"success": True})
# If the admin is not allowed to see all realms,
# (policy scope=system, action=read)
# the realms, where he has no administrative rights need,
# to be stripped.
'''
polPost = self.Policy.checkPolicyPost('system',
'getRealms',
{'realms': realms})
res = polPost['realms']
'''
return send_result(realms)
@log_with(log)
@realm_blueprint.route('/superuser', methods=['GET'])
def <API key>():
"""
This call returns the list of all superuser realms
as they are defined in *pi.cfg*.
See :ref:`cfgfile` for more information about this.
:return: a json result with a list of realms
**Example request**:
.. sourcecode:: http
GET /superuser HTTP/1.1
Host: example.com
Accept: application/json
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"status": true,
"value": ["superuser",
"realm2"]
}
},
"version": "privacyIDEA unknown"
}
"""
superuser_realms = current_app.config.get("SUPERUSER_REALM", [])
g.audit_object.log({"success": True})
return send_result(superuser_realms)
@log_with(log)
@<API key>.route('/<realm>', methods=['POST'])
@prepolicy(check_base_action, request, ACTION.RESOLVERWRITE)
def <API key>(realm=None):
"""
This call sets the default realm.
:param realm: the name of the realm, that should be the default realm
:return: a json result with either 1 (success) or 0 (fail)
"""
realm = realm.lower().strip()
r = set_default_realm(realm)
g.audit_object.log({"success": r,
"info": realm})
return send_result(r)
@log_with(log)
@<API key>.route('', methods=['DELETE'])
@prepolicy(check_base_action, request, ACTION.RESOLVERDELETE)
def <API key>(realm=None):
"""
This call deletes the default realm.
:return: a json result with either 1 (success) or 0 (fail)
**Example response**:
.. sourcecode:: http
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"status": true,
"value": 1
},
"version": "privacyIDEA unknown"
}
"""
r = set_default_realm("")
g.audit_object.log({"success": r,
"info": ""})
return send_result(r)
@log_with(log)
@<API key>.route('', methods=['GET'])
def <API key>():
"""
This call returns the default realm
:return: a json description of the default realm with the resolvers
**Example response**:
.. sourcecode:: http
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"status": true,
"value": {
"defrealm": {
"default": true,
"resolver": [
{
"name": "defresolver",
"type": "passwdresolver"
}
]
}
}
},
"version": "privacyIDEA unknown"
}
"""
res = {}
defRealm = get_default_realm()
if defRealm:
res = get_realms(defRealm)
g.audit_object.log({"success": True,
"info": defRealm})
return send_result(res)
@log_with(log)
#@system_blueprint.route('/delRealm', methods=['POST', 'DELETE'])
@realm_blueprint.route('/<realm>', methods=['DELETE'])
@prepolicy(check_base_action, request, ACTION.RESOLVERDELETE)
def delete_realm_api(realm=None):
"""
This call deletes the given realm.
:param realm: The name of the realm to delete
:return: a json result with value=1 if deleting the realm was successful
**Example request**:
.. sourcecode:: http
DELETE /realm/realm_to_delete HTTP/1.1
Host: example.com
Accept: application/json
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"status": true,
"value": 1
},
"version": "privacyIDEA unknown"
}
"""
ret = delete_realm(realm)
g.audit_object.log({"success": ret,
"info": realm})
return send_result(ret) |
/** @file Call Control messags, GSM 04.08 9.3. */
#include <iostream>
#include "GSML3CCMessages.h"
#include <Logger.h>
using namespace std;
using namespace GSM;
ostream& GSM::operator<<(ostream& os, L3CCMessage::MessageType val)
{
switch (val) {
case L3CCMessage::Alerting:
os << "Alerting"; break;
case L3CCMessage::Connect:
os << "Connect"; break;
case L3CCMessage::Disconnect:
os << "Disconnect"; break;
case L3CCMessage::ConnectAcknowledge:
os << "Connect Acknowledge"; break;
case L3CCMessage::Release:
os << "Release"; break;
case L3CCMessage::ReleaseComplete:
os << "Release Complete"; break;
case L3CCMessage::Setup:
os << "Setup"; break;
case L3CCMessage::EmergencySetup:
os << "Emergency Setup"; break;
case L3CCMessage::CCStatus:
os <<"Status"; break;
case L3CCMessage::CallConfirmed:
os <<"Call Confirmed"; break;
case L3CCMessage::CallProceeding:
os <<"Call Proceeding"; break;
case L3CCMessage::StartDTMF:
os << "Start DTMF"; break;
case L3CCMessage::StartDTMFReject:
os << "Start DTMF Reject"; break;
case L3CCMessage::<API key>:
os << "Start DTMF Acknowledge"; break;
case L3CCMessage::StopDTMF:
os << "Stop DTMF"; break;
case L3CCMessage::StopDTMFAcknowledge:
os << "Stop DTMF Acknowledge"; break;
case L3CCMessage::Hold:
os << "Hold"; break;
case L3CCMessage::HoldReject:
os << "Hold Reject"; break;
default: os << hex << "0x" << (int)val << dec;
}
return os;
}
L3CCMessage * GSM::L3CCFactory(L3CCMessage::MessageType MTI)
{
switch (MTI) {
case L3CCMessage::Connect: return new L3Connect();
case L3CCMessage::Alerting: return new L3Alerting();
case L3CCMessage::Setup: return new L3Setup();
case L3CCMessage::EmergencySetup: return new L3EmergencySetup();
case L3CCMessage::Disconnect: return new L3Disconnect();
case L3CCMessage::CallProceeding: return new L3CallProceeding();
case L3CCMessage::Release: return new L3Release();
case L3CCMessage::ReleaseComplete: return new L3ReleaseComplete();
case L3CCMessage::ConnectAcknowledge: return new <API key>();
case L3CCMessage::CCStatus: return new L3CCStatus();
case L3CCMessage::CallConfirmed: return new L3CallConfirmed();
case L3CCMessage::StartDTMF: return new L3StartDTMF();
case L3CCMessage::StopDTMF: return new L3StopDTMF();
case L3CCMessage::Hold: return new L3Hold();
default: {
LOG(NOTICE) << "no L3 CC factory support for message "<< MTI;
return NULL;
}
}
}
/* parser for Call control messages, will only parse uplink */
L3CCMessage * GSM::parseL3CC(const L3Frame& source)
{
// mask out bit #7 (1011 1111) so use 0xbf, see GSM 04.08 Table 10.3/3.
L3CCMessage::MessageType MTI = (L3CCMessage::MessageType)(0xbf & source.MTI());
LOG(DEBUG) << "MTI="<<MTI;
L3CCMessage *retVal = L3CCFactory(MTI);
if (retVal==NULL) return NULL;
retVal->TI(source.TI());
retVal->parse(source);
LOG(DEBUG) << *retVal;
return retVal;
}
void L3CCMessage::write(L3Frame& dest) const
{
// We override L3Message::write for the transaction identifier.
size_t l3len = bitsNeeded();
if (dest.size()!=l3len) dest.resize(l3len);
size_t wp = 0;
dest.writeField(wp,mTI,4);
dest.writeField(wp,PD(),4);
dest.writeField(wp,MTI(),8);
writeBody(dest,wp);
}
void L3CCMessage::text(ostream& os) const
{
os << "CC " << (MessageType) MTI();
os << " TI=" << mTI << " ";
}
size_t L3Alerting::l2BodyLength() const
{
size_t sum=0;
if (mHaveProgress) sum += mProgress.lengthTLV();
return sum;
}
void L3Alerting::writeBody(L3Frame &dest, size_t &wp) const
{
if (mHaveProgress) mProgress.writeTLV(0x1E,dest,wp);
}
void L3Alerting::parseBody(const L3Frame& src, size_t &rp)
{
skipTLV(0x1C,src,rp); // skip facility
mHaveProgress = mProgress.parseTLV(0x1E,src,rp);
// ignore the rest
}
void L3Alerting::text(ostream& os) const
{
L3CCMessage::text(os);
if (mHaveProgress) os << "progress=(" << mProgress << ")";
}
size_t L3CallProceeding::l2BodyLength() const
{
size_t sum=0;
if (mHaveProgress) sum += mProgress.lengthTLV();
if( <API key>) sum += mBearerCapability.lengthTLV();
return sum;
}
void L3CallProceeding::writeBody(L3Frame &dest, size_t &wp) const
{
if( <API key>) mBearerCapability.writeTLV(0x04, dest, wp);
if (mHaveProgress) mProgress.writeTLV(0x1E, dest, wp);
}
void L3CallProceeding::parseBody(const L3Frame& src, size_t &rp)
{
skipTV(0x0D,4,src,rp); // skip repeat indicator
skipTLV(0x04,src,rp); // skip bearer capability 1
skipTLV(0x04,src,rp); // skip bearer capability 2
skipTLV(0x1C,src,rp); // skip facility
mHaveProgress = mProgress.parseTLV(0x1E,src,rp);
}
void L3CallProceeding::text(ostream& os) const
{
L3CCMessage::text(os);
if (mHaveProgress) os << "progress=(" << mProgress << ")";
}
size_t L3Connect::l2BodyLength() const
{
size_t len=0;
if (mHaveProgress) len += mProgress.lengthTLV();
return len;
}
void L3Connect::writeBody(L3Frame &dest, size_t &wp) const
{
if (mHaveProgress) mProgress.writeTLV(0x1E,dest,wp);
}
void L3Connect::parseBody(const L3Frame& src, size_t &rp)
{
skipTLV(0x1c,src,rp); // facility
mHaveProgress = mProgress.parseTLV(0x1e,src,rp);
// ignore the rest
}
void L3Connect::text(ostream& os) const
{
L3CCMessage::text(os);
if (mHaveProgress) os << "progress=(" << mProgress << ")";
}
size_t L3Release::l2BodyLength() const
{
size_t sum = 0;
if (mHaveCause) sum += mCause.lengthTLV();
return sum;
}
void L3Release::writeBody(L3Frame& dest, size_t &wp) const
{
if (mHaveCause) mCause.writeTLV(0x08,dest,wp);
}
void L3Release::parseBody(const L3Frame& src, size_t &rp)
{
mHaveCause = mCause.parseTLV(0x08,src,rp);
// ignore the rest
}
void L3Release::text(ostream& os) const
{
L3CCMessage::text(os);
if (mHaveCause) os << "cause=(" << mCause << ")";
}
size_t L3ReleaseComplete::l2BodyLength() const
{
size_t sum = 0;
if (mHaveCause) sum += mCause.lengthTLV();
return sum;
}
void L3ReleaseComplete::writeBody(L3Frame& dest, size_t &wp) const
{
if (mHaveCause) mCause.writeTLV(0x08,dest,wp);
}
void L3ReleaseComplete::parseBody(const L3Frame& src, size_t &rp)
{
mHaveCause = mCause.parseTLV(0x08,src,rp);
// ignore the rest
}
void L3ReleaseComplete::text(ostream& os) const
{
L3CCMessage::text(os);
if (mHaveCause) os << "cause=(" << mCause << ")";
}
void L3Setup::writeBody( L3Frame &dest, size_t &wp ) const
{
if (<API key>) mBearerCapability.writeTLV(0x04, dest, wp);
if (<API key>) <API key>.writeTLV(0x5C,dest, wp);
if (<API key>) <API key>.writeTLV(0x5E,dest, wp);
}
void L3Setup::parseBody( const L3Frame &src, size_t &rp )
{
skipTV(0x0D,4,src,rp); // skip Repeat Indicator.
skipTLV(0x04,src,rp); // skip Bearer Capability 1.
skipTLV(0x04,src,rp); // skip Bearer Capability 2.
skipTLV(0x1C,src,rp); // skip Facility.
skipTLV(0x1E,src,rp); // skip Progress.
skipTLV(0x34,src,rp); // skip Signal.
<API key> = <API key>.parseTLV(0x5C,src,rp);
skipTLV(0x5D,src,rp); // skip Calling Party Subaddress
<API key> = <API key>.parseTLV(0x5E,src,rp);
// ignore the rest
}
size_t L3Setup::l2BodyLength() const
{
int len = 0;
if(<API key>) len += mBearerCapability.lengthTLV();
if(<API key>) len += <API key>.lengthTLV();
if(<API key>) len += <API key>.lengthTLV();
return len;
}
void L3Setup::text(ostream& os) const
{
L3CCMessage::text(os);
if(<API key>)
os <<"<API key>=("<<<API key><<")";
if(<API key>)
os <<"<API key>=("<<<API key><<")";
}
void L3CCStatus::parseBody( const L3Frame &src, size_t &rp )
{
mCause.parseLV(src, rp);
mCallState.parseV(src, rp);
}
void L3CCStatus::writeBody(L3Frame &dest, size_t &wp ) const
{
mCause.writeLV(dest, wp);
mCallState.writeV(dest, wp);
}
void L3CCStatus::text(ostream& os) const
{
L3CCMessage::text(os);
os << "cause=(" << mCause << ")";
os << " callState=" << mCallState;
}
void L3Disconnect::writeBody(L3Frame& dest, size_t &wp) const
{
mCause.writeLV(dest,wp);
}
void L3Disconnect::parseBody(const L3Frame& src, size_t &rp)
{
mCause.parseLV(src,rp);
}
void L3Disconnect::text(ostream& os) const
{
L3CCMessage::text(os);
os << "cause=(" << mCause << ")";
}
void L3CallConfirmed::parseBody(const L3Frame& src, size_t &rp)
{
skipTV(0x0D,4,src,rp); // skip repeat indicator
skipTLV(0x04,src,rp); // skip bearer capability 1
skipTLV(0x04,src,rp); // skip bearer capability 2
mHaveCause = mCause.parseTLV(0x08,src,rp);
// ignore call control capabilities
}
size_t L3CallConfirmed::l2BodyLength() const
{
size_t sum=0;
if (mHaveCause) sum += mCause.lengthTLV();
return sum;
}
void L3CallConfirmed::text(ostream& os) const
{
L3CCMessage::text(os);
if (mHaveCause) os << "cause=(" << mCause << ")";
}
void L3StartDTMF::text(ostream& os) const
{
L3CCMessage::text(os);
os << "key=" << mKey;
}
void <API key>::text(ostream& os) const
{
L3CCMessage::text(os);
os << "key=" << mKey;
}
void L3StartDTMFReject::text(ostream& os) const
{
L3CCMessage::text(os);
os << "cause=(" << mCause << ")";
}
size_t L3Progress::l2BodyLength() const
{
return mProgress.lengthLV();
}
void L3Progress::writeBody(L3Frame &dest, size_t &wp) const
{
mProgress.writeLV(dest,wp);
}
void L3Progress::parseBody(const L3Frame& src, size_t &rp)
{
mProgress.parseLV(src,rp);
// ignore the rest
}
void L3Progress::text(ostream& os) const
{
L3CCMessage::text(os);
os << "prog_ind=(" << mProgress << ")";
}
void L3HoldReject::text(ostream& os) const
{
L3CCMessage::text(os);
os << "cause=(" << mCause << ")";
}
// vim: ts=4 sw=4 |
<?php
return [
'news' => [
'slogan' => 'Il ritmo è solo ad un *click* di distanza!',
],
'landing' => [
'download' => 'Scarica ora',
'online' => '<strong>:players</strong> giocatori online ora in <strong>:games</strong> games',
'peak' => 'Picco, :count utenti online',
'players' => '<strong>:count</strong> utenti registrati',
'slogan' => [
// free to win => vinci gratuitamente, but maybe there's a better way to translate that
'main' => 'simulatore di cerchi dove vinci gratuitamente',
'sub' => 'il ritmo è solo ad un click di distanza',
],
],
]; |
# -*- coding: utf-8 -*-
"""
Tests for Python APIs of the Teams app
"""
from uuid import uuid4
import ddt
import mock
from opaque_keys.edx.keys import CourseKey
from course_modes.models import CourseMode
from lms.djangoapps.teams import api as teams_api
from lms.djangoapps.teams.models import CourseTeam
from lms.djangoapps.teams.tests.factories import CourseTeamFactory
from openedx.core.lib.teams_config import TeamsConfig, TeamsetType
from student.models import CourseEnrollment
from student.roles import CourseStaffRole
from student.tests.factories import <API key>, UserFactory
from xmodule.modulestore.tests.django_utils import <API key>
from xmodule.modulestore.tests.factories import CourseFactory
COURSE_KEY1 = CourseKey.from_string('edx/history/1')
COURSE_KEY2 = CourseKey.from_string('edx/math/1')
TOPIC1 = 'topic-1'
TOPIC2 = 'topic-2'
TOPIC3 = 'topic-3'
DISCUSSION_TOPIC_ID = uuid4().hex
@ddt.ddt
class PythonAPITests(<API key>):
"""
The set of tests for different API endpoints
"""
@classmethod
def setUpClass(cls):
super(PythonAPITests, cls).setUpClass()
cls.user1 = UserFactory.create(username='user1')
cls.user2 = UserFactory.create(username='user2')
cls.user3 = UserFactory.create(username='user3')
cls.user4 = UserFactory.create(username='user4')
topic_data = [
(TOPIC1, TeamsetType.private_managed.value),
(TOPIC2, TeamsetType.open.value),
(TOPIC3, TeamsetType.public_managed.value)
]
topics = [
{
'id': topic_id,
'name': 'name-' + topic_id,
'description': 'desc-' + topic_id,
'type': teamset_type
} for topic_id, teamset_type in topic_data
]
teams_config_1 = TeamsConfig({'topics': [topics[0]]})
teams_config_2 = TeamsConfig({'topics': [topics[1], topics[2]]})
cls.course1 = CourseFactory(
org=COURSE_KEY1.org,
course=COURSE_KEY1.course,
run=COURSE_KEY1.run,
teams_configuration=teams_config_1,
)
cls.course2 = CourseFactory(
org=COURSE_KEY2.org,
course=COURSE_KEY2.course,
run=COURSE_KEY2.run,
teams_configuration=teams_config_2,
)
for user in (cls.user1, cls.user2, cls.user3, cls.user4):
<API key>.create(user=user, course_id=COURSE_KEY1)
for user in (cls.user3, cls.user4):
<API key>.create(user=user, course_id=COURSE_KEY2)
cls.team1 = CourseTeamFactory(
course_id=COURSE_KEY1,
discussion_topic_id=DISCUSSION_TOPIC_ID,
team_id='team1',
topic_id=TOPIC1,
)
cls.team1a = CourseTeamFactory( # Same topic / team set as team1
course_id=COURSE_KEY1,
team_id='team1a',
topic_id=TOPIC1,
)
cls.team2 = CourseTeamFactory(course_id=COURSE_KEY2, team_id='team2', topic_id=TOPIC2)
cls.team2a = CourseTeamFactory( # Same topic / team set as team2
course_id=COURSE_KEY2,
team_id='team2a',
topic_id=TOPIC2
)
cls.team3 = CourseTeamFactory(course_id=COURSE_KEY2, team_id='team3', topic_id=TOPIC3)
cls.team1.add_user(cls.user1)
cls.team1.add_user(cls.user2)
cls.team2.add_user(cls.user3)
cls.team1a.add_user(cls.user4)
cls.team2a.add_user(cls.user4)
def <API key>(self):
self.assertIsNone(teams_api.<API key>('DO_NOT_EXIST'))
def <API key>(self):
team = teams_api.<API key>(DISCUSSION_TOPIC_ID)
self.assertEqual(team, self.team1)
def <API key>(self):
self.assertTrue(teams_api.<API key>(self.team1))
def <API key>(self):
self.assertFalse(teams_api.<API key>(None))
self.assertFalse(teams_api.<API key>(self.team2))
self.assertFalse(teams_api.<API key>(self.team3))
def <API key>(self):
self.assertTrue(teams_api.<API key>(self.team1))
self.assertFalse(teams_api.<API key>(self.team2))
self.assertTrue(teams_api.<API key>(self.team3))
def <API key>(self):
self.assertTrue(teams_api.<API key>(COURSE_KEY1, TOPIC1))
self.assertFalse(teams_api.<API key>(COURSE_KEY2, TOPIC2))
self.assertTrue(teams_api.<API key>(COURSE_KEY2, TOPIC3))
def <API key>(self):
self.assertTrue(teams_api.<API key>(self.user1, self.team1))
self.assertFalse(teams_api.<API key>(self.user1, None))
self.assertFalse(teams_api.<API key>(self.user1, self.team2))
def <API key>(self):
self.assertTrue(teams_api.<API key>(DISCUSSION_TOPIC_ID, self.user1))
self.assertTrue(teams_api.<API key>(DISCUSSION_TOPIC_ID, self.user2))
# self.assertFalse(teams_api.<API key>(DISCUSSION_TOPIC_ID, self.user3))
def <API key>(self):
self.assertTrue(teams_api.<API key>(self.team2.discussion_topic_id, self.user1))
self.assertTrue(teams_api.<API key>(self.team2.discussion_topic_id, self.user2))
self.assertTrue(teams_api.<API key>('DO_NOT_EXISTS', self.user3))
@ddt.unpack
@ddt.data(
(COURSE_KEY1, TOPIC1, ['team1', 'team1', None, 'team1a']),
(COURSE_KEY1, TOPIC2, [None, None, None, None]),
(COURSE_KEY2, TOPIC1, [None, None, None, None]),
(COURSE_KEY2, TOPIC2, [None, None, 'team2', 'team2a']),
)
def <API key>(self, course_key, topic_id, expected_team_ids):
user1_team = teams_api.<API key>(self.user1, str(course_key), topic_id)
user2_team = teams_api.<API key>(self.user2, str(course_key), topic_id)
user3_team = teams_api.<API key>(self.user3, str(course_key), topic_id)
user4_team = teams_api.<API key>(self.user4, str(course_key), topic_id)
self.assertEqual(user1_team.team_id if user1_team else None, expected_team_ids[0])
self.assertEqual(user2_team.team_id if user2_team else None, expected_team_ids[1])
self.assertEqual(user3_team.team_id if user3_team else None, expected_team_ids[2])
self.assertEqual(user4_team.team_id if user4_team else None, expected_team_ids[3])
@mock.patch('lms.djangoapps.teams.api.CourseTeam.objects')
def <API key>(self, mocked_manager):
"""
This is a test for a use case that is very unlikely to occur.
Currently users cannot be in multiple teams in a course, but even after we allow multiple
teams in a course then they should still be limited to one team per topic
"""
mocked_manager.get.side_effect = CourseTeam.<API key>()
expected_result = "This is somehow the first team"
mock_qs = mock.MagicMock()
mock_qs.first.return_value = expected_result
mocked_manager.filter.return_value = mock_qs
result = teams_api.<API key>(self.user1, str(COURSE_KEY1), TOPIC1)
self.assertEqual(result, expected_result)
def <API key>(self):
team = teams_api.<API key>(self.user1, 'nonsense/garbage/nonexistant', 'topic')
self.assertIsNone(team)
def <API key>(self):
invalid_course_id = 'lol!()#^$&course'
message = 'The supplied course id lol!()#^$&course is not valid'
with self.assertRaisesMessage(ValueError, message):
teams_api.<API key>(self.user1, invalid_course_id, 'who-cares')
def <API key>(self):
"""
A learner should be able to get the anonymous user IDs of their team members
"""
<API key> = teams_api.<API key>(self.user1, self.team1)
self.assertEqual(len(self.team1.users.all()), len(<API key>))
def <API key>(self):
"""
A learner should not be able to get IDs from members of a team they are not a member of
"""
self.assertRaises(Exception, teams_api.<API key>, self.user1, self.team2)
def <API key>(self):
"""
An exception should be thrown when a bad user or team are passed to the endpoint
"""
self.assertRaises(Exception, teams_api.<API key>, None, self.team1)
def <API key>(self):
"""
Course staff should be able to get anonymous IDs for teams in their course
"""
user_staff = UserFactory.create(username='user_staff')
<API key>.create(user=user_staff, course_id=COURSE_KEY1)
CourseStaffRole(COURSE_KEY1).add_users(user_staff)
<API key> = teams_api.<API key>(user_staff, self.team1)
self.assertEqual(len(self.team1.users.all()), len(<API key>))
@ddt.ddt
class TeamAccessTests(<API key>):
"""
The set of tests for API endpoints related to access of a team based on the users
"""
@classmethod
def setUpClass(cls):
super(TeamAccessTests, cls).setUpClass()
cls.user_audit = UserFactory.create(username='user_audit')
cls.user_staff = UserFactory.create(username='user_staff')
cls.user_masters = UserFactory.create(username='user_masters')
cls.user_unenrolled = UserFactory.create(username='user_unenrolled')
cls.users = {
'user_audit': cls.user_audit,
'user_staff': cls.user_staff,
'user_masters': cls.user_masters,
'user_unenrolled': cls.user_unenrolled,
}
cls.topic_id = 'RANDOM TOPIC'
cls.course_1 = CourseFactory.create(
teams_configuration=TeamsConfig({
'team_sets': [{'id': cls.topic_id, 'name': cls.topic_id, 'description': cls.topic_id}]
}),
org=COURSE_KEY1.org,
course=COURSE_KEY1.course,
run=COURSE_KEY1.run
)
for user in (cls.user_audit, cls.user_staff):
<API key>.create(user=user, course_id=COURSE_KEY1)
<API key>.create(user=cls.user_masters, course_id=COURSE_KEY1, mode=CourseMode.MASTERS)
CourseStaffRole(COURSE_KEY1).add_users(cls.user_staff)
cls.team_unprotected_1 = CourseTeamFactory(
course_id=COURSE_KEY1,
topic_id=cls.topic_id,
team_id='team_unprotected_1'
)
cls.team_unprotected_2 = CourseTeamFactory(
course_id=COURSE_KEY1,
topic_id=cls.topic_id,
team_id='team_unprotected_2'
)
cls.team_unprotected_3 = CourseTeamFactory(
course_id=COURSE_KEY1,
topic_id=cls.topic_id,
team_id='team_unprotected_3'
)
cls.team_protected_1 = CourseTeamFactory(
course_id=COURSE_KEY1,
team_id='team_protected_1',
topic_id=cls.topic_id,
<API key>=True
)
cls.team_protected_2 = CourseTeamFactory(
course_id=COURSE_KEY1,
team_id='team_protected_2',
topic_id=cls.topic_id,
<API key>=True
)
@ddt.data(
('user_audit', True),
('user_masters', True),
('user_staff', True),
('user_unenrolled', False),
)
@ddt.unpack
def <API key>(self, username, <API key>):
user = self.users[username]
self.assertEqual(
<API key>,
teams_api.has_team_api_access(user, COURSE_KEY1)
)
@ddt.data(
('user_audit', teams_api.<API key>.unprotected),
('user_masters', teams_api.<API key>.protected),
('user_staff', teams_api.<API key>.protection_exempt),
('user_unenrolled', None),
)
@ddt.unpack
def <API key>(self, username, <API key>):
user = self.users[username]
try:
self.assertEqual(
<API key>,
teams_api.<API key>(user, COURSE_KEY1)
)
except ValueError:
self.assertFalse(CourseEnrollment.is_enrolled(user, COURSE_KEY1))
@ddt.data(
('user_audit', True),
('user_masters', False),
('user_staff', True),
('user_unenrolled', False),
)
@ddt.unpack
def <API key>(self, username, expected_return):
user = self.users[username]
try:
self.assertEqual(
expected_return,
teams_api.<API key>(user, self.team_unprotected_1)
)
except ValueError:
self.assertFalse(CourseEnrollment.is_enrolled(user, self.team_unprotected_1.course_id))
@ddt.data(
('user_audit', False),
('user_masters', True),
('user_staff', True),
('user_unenrolled', False),
)
@ddt.unpack
def <API key>(self, username, expected_return):
user = self.users[username]
try:
self.assertEqual(
expected_return,
teams_api.<API key>(user, self.team_protected_1)
)
except ValueError:
self.assertFalse(CourseEnrollment.is_enrolled(user, self.team_protected_1.course_id))
@ddt.data(
('user_audit', 3),
('user_masters', 2),
('user_staff', 5),
('user_unenrolled', 3),
)
@ddt.unpack
def <API key>(self, username, expected_count):
user = self.users[username]
try:
<API key> = teams_api.<API key>(
user,
COURSE_KEY1
)
except ValueError:
self.assertFalse(CourseEnrollment.is_enrolled(user, COURSE_KEY1))
return
teams_query_set = teams_api.<API key>(
[self.topic_id],
COURSE_KEY1,
<API key>
)
self.assertEqual(
expected_count,
teams_query_set.count()
)
@ddt.data(
('user_audit', 3),
('user_masters', 2),
('user_staff', 5),
('user_unenrolled', 3),
)
@ddt.unpack
def <API key>(self, username, expected_team_count):
user = self.users[username]
try:
<API key> = teams_api.<API key>(
user,
COURSE_KEY1
)
except ValueError:
self.assertFalse(CourseEnrollment.is_enrolled(user, COURSE_KEY1))
return
topic = {
'id': self.topic_id
}
teams_api.add_team_count(
[topic],
COURSE_KEY1,
<API key>
)
self.assertEqual(
expected_team_count,
topic.get('team_count')
) |
// stdafx.cpp : source file that includes just the standard includes
// excxx_wce_sql.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h" |
describe('backbone history helper tests', function () {
'use strict';
var Backbone, history,
should = chai.should();
beforeEach(function (done) {
this.timeout(10000);
require(['backbone', 'cs!helpers/backbone/history'], function () {
Backbone = arguments[0];
history = arguments[1];
done();
});
});
describe('get fragment tests', function () {
it('should modify fragment', function () {
history.getFragment('/test', null).should.equal('test');
history.getFragment('#weird route ', null).should.equal('weird route');
history.getFragment('<API key>', null).should.equal('<API key>');
});
});
describe('navigate tests', function () {
it('should not do anything', function () {
// before Backbone.history is started
history.navigate('', true).should.equal(false);
Backbone.history.start();
history.fragment = 'test';
should.not.exist(history.navigate('test', true));
history.fragment.should.equal('test');
});
it('should trigger url to be loaded', function () {
sinon.spy(history, 'loadUrl');
history.navigate('test', true);
history.fragment.should.equal('test');
history.loadUrl.calledWith('test');
});
});
}); |
<?php
namespace Pydio\Editor\Video;
use Pydio\Access\Core\MetaStreamWrapper;
use Pydio\Access\Core\Exception\<API key>;
use Pydio\Access\Core\Model\AJXP_Node;
use Pydio\Access\Core\Model\UserSelection;
use Pydio\Core\Controller\Controller;
use Pydio\Core\Utils\Vars\PathUtils;
use Pydio\Core\Controller\HTMLWriter;
use Pydio\Core\PluginFramework\Plugin;
defined('AJXP_EXEC') or die( 'Access not allowed');
/**
* Streams video to a client
* @package Pydio\Editor\Video
*/
class VideoReader extends Plugin
{
/**
* @param $action
* @param $httpVars
* @param $filesVars
* @param \Pydio\Core\Model\ContextInterface $contextInterface
* @throws <API key>
*/
public function switchAction($action, $httpVars, $filesVars, \Pydio\Core\Model\ContextInterface $contextInterface)
{
$selection = UserSelection::fromContext($contextInterface, $httpVars);
$node = $selection->getUniqueNode();
if ($action == "read_video_data") {
if(!file_exists($node->getUrl()) || !is_readable($node->getUrl())){
throw new <API key>($node->getPath());
}
$this->logDebug("Reading video");
session_write_close();
$filesize = filesize($node->getUrl());
$filename = $node->getUrl();
$basename = PathUtils::<API key>($filename);
//$fp = fopen($destStreamURL.$file, "r");
if (preg_match("/\.ogv$/", $basename)) {
header("Content-Type: video/ogg; name=\"".$basename."\"");
} else if (preg_match("/\.mp4$/", $basename)) {
header("Content-Type: video/mp4; name=\"".$basename."\"");
} else if (preg_match("/\.m4v$/", $basename)) {
header("Content-Type: video/x-m4v; name=\"".$basename."\"");
} else if (preg_match("/\.webm$/", $basename)) {
header("Content-Type: video/webm; name=\"".$basename."\"");
}
if ( isset($_SERVER['HTTP_RANGE']) && $filesize != 0 ) {
$this->logDebug("Http range", array($_SERVER['HTTP_RANGE']));
// multiple ranges, which can become pretty complex, so ignore it for now
$ranges = explode('=', $_SERVER['HTTP_RANGE']);
$offsets = explode('-', $ranges[1]);
$offset = floatval($offsets[0]);
if($offset == 0){
$this->logInfo('Preview', 'Streaming content of '.$filename, array("files" => $filename));
}
$additionalOffset = 1;
if (isset($_SERVER['HTTP_USER_AGENT']) && strlen(strstr($_SERVER['HTTP_USER_AGENT'], 'Firefox')) > 0) {
$additionalOffset = 0;
}
$length = floatval($offsets[1]) - $offset + $additionalOffset;
if (!$length) $length = $filesize - $offset;
if ($length + $offset > $filesize || $length < 0) $length = $filesize - $offset;
header('HTTP/1.1 206 Partial Content');
header('Content-Range: bytes ' . $offset . '-' . ($offset + $length - 1) . '/' . $filesize);
header('Accept-Ranges:bytes');
header("Content-Length: ". $length);
$file = fopen($filename, 'rb');
if(!is_resource($file)) throw new <API key>($file);
fseek($file, 0);
$relOffset = $offset;
while ($relOffset > 2.0E9) {
// seek to the requested offset, this is 0 if it's not a partial content request
fseek($file, 2000000000, SEEK_CUR);
$relOffset -= 2000000000;
// This works because we never overcome the PHP 32 bit limit
}
fseek($file, $relOffset, SEEK_CUR);
while(ob_get_level()) ob_end_flush();
$readSize = 0.0;
while (!feof($file) && $readSize < $length && connection_status() == 0) {
if ($length < 2048){
echo fread($file, $length);
} else {
echo fread($file, 2048);
}
$readSize += 2048.0;
flush();
}
fclose($file);
} else {
$this->logInfo('Preview', 'Streaming content of '.$filename, array("files" => $filename));
header("Content-Length: ".$filesize);
header("Content-Range: bytes 0-" . ($filesize - 1) . "/" . $filesize. ";");
header('Cache-Control: public');
$stream = fopen("php://output", "a");
MetaStreamWrapper::copyFileInStream($node->getUrl(), $stream);
fflush($stream);
fclose($stream);
}
Controller::applyHook("node.read", array($node));
} else if ($action == "get_sess_id") {
HTMLWriter::charsetHeader("text/plain");
print(session_id());
}
}
/**
* @param AJXP_Node $ajxpNode
*/
public function <API key>(&$ajxpNode)
{
if(!preg_match('/\.mpg$|\.mp4$|\.ogv$|\.webm$/i', $ajxpNode->getLabel())) return;
if (file_exists(str_replace(".mpg","_PREVIEW.mp4", $ajxpNode->getUrl()))) {
$ajxpNode->mergeMetadata(array("<API key>" => str_replace(".mpg","_PREVIEW.mp4", $ajxpNode->getPath())));
}
$rotating = array("mp4","ogv", "webm");
foreach ($rotating as $ext) {
if (preg_match('/\.'.$ext.'$/i', $ajxpNode->getLabel())) {
foreach ($rotating as $other) {
if($other == $ext) continue;
if (file_exists(str_replace($ext, $other,$ajxpNode->getUrl()))) {
$ajxpNode->mergeMetadata(array("video_altversion_".$other => str_replace($ext, $other, $ajxpNode->getPath())));
}
}
}
}
}
} |
#include <bitcoin/explorer/commands/genaddr.hpp>
#include <iostream>
#include <bitcoin/explorer/define.hpp>
using namespace bc::explorer;
using namespace bc::explorer::commands;
console_result genaddr::invoke(std::ostream& output, std::ostream& error)
{
error << BX_GENADDR_OBSOLETE << std::endl;
return console_result::failure;
} |
package com.esofthead.mycollab.module.project.events
import com.esofthead.mycollab.eventmanager.ApplicationEvent
/**
* @author MyCollab Ltd.
* @since 5.0.3
*/
object RiskEvent {
class GotoAdd(source: AnyRef, data: AnyRef) extends ApplicationEvent(source, data) {}
class GotoEdit(source: AnyRef, data: AnyRef) extends ApplicationEvent(source, data) {}
class GotoList(source: AnyRef, data: AnyRef) extends ApplicationEvent(source, data) {}
class GotoRead(source: AnyRef, data: AnyRef) extends ApplicationEvent(source, data) {}
} |
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from '<API key>';
import <API key> from '<API key>';
import StatusContent from 'mastodon/components/status_content';
import AttachmentList from 'mastodon/components/attachment_list';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import <API key> from 'mastodon/containers/<API key>';
import AvatarComposite from 'mastodon/components/avatar_composite';
import Permalink from 'mastodon/components/permalink';
import IconButton from 'mastodon/components/icon_button';
import RelativeTimestamp from 'mastodon/components/relative_timestamp';
import { HotKeys } from 'react-hotkeys';
import { autoPlayGif } from 'mastodon/initial_state';
const messages = defineMessages({
more: { id: 'status.more', defaultMessage: 'More' },
open: { id: 'conversation.open', defaultMessage: 'View conversation' },
reply: { id: 'status.reply', defaultMessage: 'Reply' },
markAsRead: { id: 'conversation.mark_as_read', defaultMessage: 'Mark as read' },
delete: { id: 'conversation.delete', defaultMessage: 'Delete conversation' },
muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute conversation' },
unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute conversation' },
});
export default @injectIntl
class Conversation extends <API key> {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
conversationId: PropTypes.string.isRequired,
accounts: ImmutablePropTypes.list.isRequired,
lastStatus: ImmutablePropTypes.map,
unread:PropTypes.bool.isRequired,
onMoveUp: PropTypes.func,
onMoveDown: PropTypes.func,
markRead: PropTypes.func.isRequired,
delete: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
_updateEmojis () {
const node = this.namesNode;
if (!node || autoPlayGif) {
return;
}
const emojis = node.querySelectorAll('.custom-emoji');
for (var i = 0; i < emojis.length; i++) {
let emoji = emojis[i];
if (emoji.classList.contains('status-emoji')) {
continue;
}
emoji.classList.add('status-emoji');
emoji.addEventListener('mouseenter', this.<API key>, false);
emoji.addEventListener('mouseleave', this.<API key>, false);
}
}
componentDidMount () {
this._updateEmojis();
}
componentDidUpdate () {
this._updateEmojis();
}
<API key> = ({ target }) => {
target.src = target.getAttribute('data-original');
}
<API key> = ({ target }) => {
target.src = target.getAttribute('data-static');
}
handleClick = () => {
if (!this.context.router) {
return;
}
const { lastStatus, unread, markRead } = this.props;
if (unread) {
markRead();
}
this.context.router.history.push(`/statuses/${lastStatus.get('id')}`);
}
handleMarkAsRead = () => {
this.props.markRead();
}
handleReply = () => {
this.props.reply(this.props.lastStatus, this.context.router.history);
}
handleDelete = () => {
this.props.delete();
}
handleHotkeyMoveUp = () => {
this.props.onMoveUp(this.props.conversationId);
}
<API key> = () => {
this.props.onMoveDown(this.props.conversationId);
}
<API key> = () => {
this.props.onMute(this.props.lastStatus);
}
handleShowMore = () => {
this.props.onToggleHidden(this.props.lastStatus);
}
setNamesRef = (c) => {
this.namesNode = c;
}
render () {
const { accounts, lastStatus, unread, intl } = this.props;
if (lastStatus === null) {
return null;
}
const menu = [
{ text: intl.formatMessage(messages.open), action: this.handleClick },
null,
];
menu.push({ text: intl.formatMessage(lastStatus.get('muted') ? messages.unmuteConversation : messages.muteConversation), action: this.<API key> });
if (unread) {
menu.push({ text: intl.formatMessage(messages.markAsRead), action: this.handleMarkAsRead });
menu.push(null);
}
menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDelete });
const names = accounts.map(a => <Permalink to={`/accounts/${a.get('id')}`} href={a.get('url')} key={a.get('id')} title={a.get('acct')}><bdi><strong className='display-name__html' <API key>={{ __html: a.get('display_name_html') }} /></bdi></Permalink>).reduce((prev, cur) => [prev, ', ', cur]);
const handlers = {
reply: this.handleReply,
open: this.handleClick,
moveUp: this.handleHotkeyMoveUp,
moveDown: this.<API key>,
toggleHidden: this.handleShowMore,
};
return (
<HotKeys handlers={handlers}>
<div className='conversation focusable muted' tabIndex='0'>
<div className='<API key>'>
<AvatarComposite accounts={accounts} size={48} />
</div>
<div className='<API key>'>
<div className='<API key>'>
<div className='<API key>'>
<RelativeTimestamp timestamp={lastStatus.get('created_at')} />
</div>
<div className='<API key>' ref={this.setNamesRef}>
<FormattedMessage id='conversation.with' defaultMessage='With {names}' values={{ names: <span>{names}</span> }} />
</div>
</div>
<StatusContent
status={lastStatus}
onClick={this.handleClick}
expanded={!lastStatus.get('hidden')}
onExpandedToggle={this.handleShowMore}
collapsable
/>
{lastStatus.get('media_attachments').size > 0 && (
<AttachmentList
compact
media={lastStatus.get('media_attachments')}
/>
)}
<div className='status__action-bar'>
<IconButton className='<API key>' title={intl.formatMessage(messages.reply)} icon='reply' onClick={this.handleReply} />
<div className='<API key>'>
<<API key> status={lastStatus} items={menu} icon='ellipsis-h' size={18} direction='right' title={intl.formatMessage(messages.more)} />
</div>
</div>
</div>
</div>
</HotKeys>
);
}
} |
require 'rails_helper'
describe GraphQL::QueryTypeCreator do
let(:<API key>) do
{
<API key> => { fields: { title: :string } },
Proposal => { fields: { id: :integer, title: :string } }
}
end
let(:api_types) { GraphQL::ApiTypesCreator.create(<API key>) }
describe "::create" do
let(:query_type) { GraphQL::QueryTypeCreator.create(api_types) }
it 'creates a QueryType with fields to retrieve single objects whose model fields included an ID' do
field = query_type.fields['proposal']
expect(field).to be_a(GraphQL::Field)
expect(field.type).to eq(api_types[Proposal])
expect(field.name).to eq('proposal')
end
it 'creates a QueryType without fields to retrieve single objects whose model fields did not include an ID' do
expect(query_type.fields['<API key>']).to be_nil
end
it "creates a QueryType with connections to retrieve collections of objects" do
connection = query_type.fields['proposals']
expect(connection).to be_a(GraphQL::Field)
expect(connection.type).to eq(api_types[Proposal].connection_type)
expect(connection.name).to eq('proposals')
end
end
end |
package apicaller
import (
"github.com/juju/errors"
"github.com/juju/juju/agent"
"github.com/juju/juju/api/base"
"github.com/juju/juju/worker"
"github.com/juju/juju/worker/dependency"
)
// ManifoldConfig defines the names of the manifolds on which a Manifold will depend.
type ManifoldConfig struct {
AgentName string
}
// Manifold returns a manifold whose worker wraps an API connection made on behalf of
// the dependency identified by AgentName.
func Manifold(config ManifoldConfig) dependency.Manifold {
return dependency.Manifold{
Inputs: []string{
config.AgentName,
},
Output: outputFunc,
Start: startFunc(config),
}
}
// startFunc returns a StartFunc that creates a worker based on the manifolds
// named in the supplied config.
func startFunc(config ManifoldConfig) dependency.StartFunc {
return func(getResource dependency.GetResourceFunc) (worker.Worker, error) {
// Get dependencies and open a connection.
var a agent.Agent
if err := getResource(config.AgentName, &a); err != nil {
return nil, err
}
conn, err := openConnection(a)
if err != nil {
return nil, errors.Annotate(err, "cannot open api")
}
// Add the environment uuid to agent config if not present.
currentConfig := a.CurrentConfig()
if currentConfig.Environment().Id() == "" {
err := a.ChangeConfig(func(setter agent.ConfigSetter) error {
environTag, err := conn.EnvironTag()
if err != nil {
return errors.Annotate(err, "no environment uuid set on api")
}
return setter.Migrate(agent.MigrateParams{
Environment: environTag,
})
})
if err != nil {
logger.Warningf("unable to save environment uuid: %v", err)
// Not really fatal, just annoying.
}
}
// Return the worker.
return newApiConnWorker(conn)
}
}
// outputFunc extracts a base.APICaller from a *apiConnWorker.
func outputFunc(in worker.Worker, out interface{}) error {
inWorker, _ := in.(*apiConnWorker)
outPointer, _ := out.(*base.APICaller)
if inWorker == nil || outPointer == nil {
return errors.Errorf("expected %T->%T; got %T->%T", inWorker, outPointer, in, out)
}
*outPointer = inWorker.conn
return nil
} |
import Ember from 'ember';
export default Ember.Route.extend({
setupController(controller, model) {
controller.set('items', model);
controller.setData();
},
model() {
let <API key> = this.controllerFor('protected.machines.index');
<API key>.set('loadState', true);
var promise = this.get('store').query('machine', {});
promise
.catch(() => {
this.toast.error('Machine list could not be retrieved');
})
.finally(() => {
<API key>.set('loadState', false);
});
return promise;
},
actions : {
refreshModel() {
this.refresh();
},
}
}); |
# Produced at the Lawrence Livermore National Laboratory.
# This file is part of Spack.
# LLNL-CODE-647188
# This program is free software; you can redistribute it and/or modify
# published by the Free Software Foundation) version 2.1, February 1999.
# This program is distributed in the hope that it will be useful, but
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# You should have received a copy of the GNU Lesser General Public
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from spack import *
class Nekbone(Package):
"""NEK5000 emulation software called NEKbone. Nekbone captures the basic
structure and user interface of the extensive Nek5000 software.
Nek5000 is a high order, incompressible Navier-Stokes solver based on
the spectral element method."""
homepage = "https://github.com/Nek5000/Nekbone"
url = "https://github.com/Nek5000/Nekbone/tarball/v17.0"
tags = ['proxy-app', 'ecp-proxy-app']
version('17.0', '<API key>', git='https://github.com/Nek5000/Nekbone.git')
version('develop', git='https://github.com/Nek5000/Nekbone.git')
# Variants
variant('mpi', default=True, description='Build with MPI')
# dependencies
depends_on('mpi', when='+mpi')
@run_before('install')
def fortran_check(self):
if not self.compiler.fc:
msg = 'Nekbone can not be built without a Fortran compiler.'
raise RuntimeError(msg)
def install(self, spec, prefix):
mkdir(prefix.bin)
FC = self.compiler.fc
CC = self.compiler.cc
if '+mpi' in spec:
FC = spec['mpi'].mpif77
CC = spec['mpi'].mpicc
# Install Nekbone in prefix.bin
install_tree("../Nekbone", prefix.bin.Nekbone)
# Install scripts in prefix.bin
nekpmpi = 'test/example1/nekpmpi'
makenek = 'test/example1/makenek'
install(makenek, prefix.bin)
install(nekpmpi, prefix.bin)
with working_dir(prefix.bin):
filter_file(r'^SOURCE_ROOT\s*=.*', 'SOURCE_ROOT=\"' +
prefix.bin.Nekbone + '/src\"', 'makenek')
filter_file(r'^CC\s*=.*', 'CC=\"' + CC + '\"', 'makenek')
filter_file(r'^F77\s*=.*', 'F77=\"' + FC + '\"', 'makenek')
if '+mpi' not in spec:
filter_file(r'^#IFMPI=\"false\"', 'IFMPI=\"false\"', 'makenek') |
#include "ixmlnodevisitor.h"
#include "xmlproperty.h"
namespace qbs {
namespace gen {
namespace xml {
Property::Property(QByteArray name, QVariant value)
{
setName(std::move(name));
setValue(std::move(value));
}
void Property::accept(INodeVisitor *visitor) const
{
visitor->visitPropertyStart(this);
for (const auto &child : children())
child->accept(visitor);
visitor->visitPropertyEnd(this);
}
} // namespace xml
} // namespace gen
} // namespace qbs |
// <auto-generated>
// This code was generated by AsyncGenerator.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH2959
{
using System.Threading.Tasks;
[TestFixture]
public class FixtureAsync : BugTestCase
{
protected override bool AppliesTo(Engine.<API key> factory)
{
return factory.ConnectionProvider.Driver.<API key>;
}
protected override void OnSetUp()
{
using (ISession session = OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
var e1 = new DerivedEntity { Name = "Bob" };
session.Save(e1);
var e2 = new <API key> { Name = "Sally" };
session.Save(e2);
session.Flush();
transaction.Commit();
}
}
protected override void OnTearDown()
{
using (ISession session = OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Delete("from System.Object");
session.Flush();
transaction.Commit();
}
}
[Test]
public async Task <API key>()
{
using (ISession session = OpenSession())
using (session.BeginTransaction())
{
var results = await (session.CreateMultiCriteria()
.Add(session.CreateCriteria(typeof(BaseEntity)))
.ListAsync());
Assert.That(results, Has.Count.EqualTo(1));
Assert.That(results[0], Has.Count.EqualTo(2));
}
}
[Test]
public async Task <API key>()
{
using (ISession session = OpenSession())
using (session.BeginTransaction())
{
var results = await (session.CreateMultiQuery()
.Add(session.CreateQuery("from " + typeof(BaseEntity).FullName))
.ListAsync());
Assert.That(results, Has.Count.EqualTo(1));
Assert.That(results[0], Has.Count.EqualTo(2));
}
}
}
} |
function bmf_get2(nom,time1,time2,hgrid,vgrid,r4,imin,imax,jmin,jmax,kmin,kmax) &
result(error)
!
!AUTEUR Luc Corbeil (bmf_get)
!
!REVISION
! v208a V. Lee real*8 allocation corrected:NI*dtyp/10/4 -> NI*(dtyp/10/4)
!
!ARGUMENTS
!
!nom variable name character*4
!time1 timestamp 1 (yyymmdd) integer
!time2 timestamp2 (hhmmsscc) integer
!r4 destination array (dtyp=*) real/int/r8
!(ijk)min Size of destination array (lower bounds) integer
!(ijk)max Size of destination array (upper bounds) integer
!
!r4 will be considered as array of shape ( imin:imax
! , jmin:jmax , kmin:kmax )
!
!DESCRIPTION
! Routine that puts in the appropriate array the data retrieved by
! bmf_gobe. The use of dummy arguments for unneeded arrays is
! possible if "dtyp" is known in advance. The array must be shaped
! by following those rules:( imin:imax , jmin:jmax , kmin:kmax ) where
!
! imin <= 1 < ni <= imax
! jmin <= 1 < nj <= jmax
! kmin <= 1 < nk <= kmax,
!
! ni,nj,nk are the attributes of the corresponding field (see
! bmf_write) Then, it is possible to... (here, a,b >=0):
!
! ...write a field of size (1:nx,1:ny,1:nz) with bmf_write
! and to retrieve it with bmf_get in a larger array
!
! .. write a field of (1-a : nx+a , 1:ny , 1:nz ) with bmf_write
! (call bmf_write with ni = nx + 2a, istart=1, iend=nx+2a) and to
! read it in an array of (minx: maxx , miny:maxy , minz,maxz )
! where minx <=1-a <=nx+2a <= maxx (call bmf_get with
! imin=minx+a , imax= maxx+a)
!
! ... write a field of (1+a : nx-b,1:ny,1:nz) (obviously we have
! 1+a < nx -b) with a standard call to bmf_write. We read the
! field in an array of (minx: maxx , miny:maxy , minz,maxz )
! with a normal call to bmf_get.
!
use bmf_mod
implicit none
integer ni,nj,nk,error,time1,time2
character*4 nom
type(bmf_liste), pointer :: champ_courant
integer imin,imax,jmin,jmax,kmin,kmax,hgrid,vgrid
integer dtyp
integer r4(imin:imax,jmin:jmax,kmin:kmax)
integer i,j,k
integer istart,iend,jstart,jend,kstart,kend,ndata
integer indice
integer, allocatable, dimension(:) :: cdata
integer sizeofint, toto(2)
integer bmf_i2char, err
logical trouve
!
error=0
trouve=.false.
sizeofint=loc(toto(2))-loc(toto(1))
champ_courant=>liste
!
if((imin.gt.1).or.(jmin.gt.1).or.(kmin.gt.1)) then
write(*,*) 'ERROR BMF_GET: IMIN OR JMIN OR KMIN .GT. 1'
error=1
return
endif
do
if(.not.associated(champ_courant)) EXIT
if((champ_courant%bmf_champ%nom.eq.nom).and. &
(champ_courant%bmf_champ%time1.eq.time1).and. &
(champ_courant%bmf_champ%time2.eq.time2).and. &
(champ_courant%bmf_champ%hgrid.eq.hgrid).and. &
(champ_courant%bmf_champ%vgrid.eq.vgrid)) then
trouve = .true.
dtyp=champ_courant%bmf_champ%dtyp
istart=champ_courant%bmf_champ%istart
jstart=champ_courant%bmf_champ%jstart
kstart=champ_courant%bmf_champ%kstart
iend=champ_courant%bmf_champ%iend
jend=champ_courant%bmf_champ%jend
kend=champ_courant%bmf_champ%kend
ni=champ_courant%bmf_champ%ni
nj=champ_courant%bmf_champ%nj
nk=champ_courant%bmf_champ%nk
ndata=champ_courant%bmf_champ%ndata
if((imax.lt.ni).or.(jmax.lt.nj).or.(kmax.lt.nk)) then
write(*,*) 'ERROR BMF_GET: IMAX OR JMAX OR KMAX .LT. EXPECTED'
write(*,*) 'FOR VARIABLE ',nom
write(*,*) 'ni=',ni,'imax=',imax
write(*,*) 'nj=',nj,'jmax=',jmax
write(*,*) 'nk=',nk,'kmax=',kmax
error=1
return
endif
indice=0
if(dtyp.ne.bmf_character) then
call bmf_copie(ni*(dtyp/10/4),nj,nk, &
champ_courant%bmf_champ%tableau,r4,&
(imin-1)*(dtyp/10/4)+1,imax*(dtyp/10/4),jmin,jmax,kmin,kmax)
else
allocate(cdata(2+(ndata-1)/sizeofint))
call bmf_copie(2+(ndata-1)/sizeofint,1,1, &
champ_courant%bmf_champ%tableau,cdata,1,ndata,1,1,1,1)
err = bmf_i2char(r4,ndata,cdata,2+(ndata-1)/sizeofint)
endif
endif
champ_courant=>champ_courant%champ_suivant
enddo
if(.not.trouve) then
write(*,*) 'WARNING BMF_GET: Variable ',nom,' non trouvee'
error=1
endif
return
end
subroutine bmf_copie(ni,nj,nk,champi,champo,imin,imax,jmin,jmax,kmin,kmax)
! pour fudger la declaration de champo si on est en real*8
implicit none
integer ni,nj,nk, i,j,k
integer champi(ni,nj,nk)
integer imin,imax,jmin,jmax,kmin,kmax
integer champo(imin:imax,jmin:jmax,kmin:kmax)
do k=1,nk
do j=1,nj
do i=1,ni
champo(i,j,k)=champi(i,j,k)
enddo
enddo
enddo
return
end subroutine bmf_copie |
using System;
using System.Collections.Generic;
using System.Linq;
using Duplicati.Library.Interface;
using Duplicati.Library.Logging;
using System.Net.NetworkInformation;
using Duplicati.Library.Modules.Builtin.ResultSerialization;
namespace Duplicati.Library.Modules.Builtin
{
public class SendJabberMessage : ReportHelper
{
<summary>
The tag used for log messages
</summary>
private static readonly string LOGTAG = Logging.Log.LogTagFromType<SendJabberMessage>();
#region Option names
<summary>
Option used to specify server username
</summary>
private const string OPTION_USERNAME = "send-xmpp-username";
<summary>
Option used to specify server password
</summary>
private const string OPTION_<API key>;
<summary>
Option used to specify recipient(s)
</summary>
private const string OPTION_RECIPIENT = "send-xmpp-to";
<summary>
Option used to specify report body
</summary>
private const string OPTION_MESSAGE = "send-xmpp-message";
<summary>
Option used to specify report level
</summary>
private const string OPTION_SENDLEVEL = "send-xmpp-level";
<summary>
Option used to specify if reports are sent for other operations than backups
</summary>
private const string OPTION_SENDALL = "<API key>";
<summary>
Option used to specify what format the result is sent in.
</summary>
private const string <API key> = "<API key>";
<summary>
Option used to set the log level
</summary>
private const string OPTION_LOG_LEVEL = "send-xmpp-log-level";
<summary>
Option used to set the log level
</summary>
private const string OPTION_LOG_FILTER = "<API key>";
<summary>
Option used to set the maximum number of log lines
</summary>
private const string <API key> = "<API key>";
#endregion
#region Option defaults
<summary>
The default message body
</summary>
protected override string DEFAULT_BODY => string.Format("Duplicati %OPERATIONNAME% report for %backup-name%{0}{0}%RESULT%", Environment.NewLine);
<summary>
Don't use the subject for XMPP
</summary>
protected override string DEFAULT_SUBJECT => string.Empty;
#endregion
#region Private variables
<summary>
The server username
</summary>
private string m_username;
<summary>
The server password
</summary>
private string m_password;
<summary>
The XMPP recipient
</summary>
private string m_to;
#endregion
#region Implementation of IGenericModule
<summary>
The module key, used to activate or deactivate the module on the commandline
</summary>
public override string Key { get { return "sendxmpp"; } }
<summary>
A localized string describing the module with a friendly name
</summary>
public override string DisplayName { get { return Strings.SendJabberMessage.DisplayName;} }
<summary>
A localized description of the module
</summary>
public override string Description { get { return Strings.SendJabberMessage.Description; } }
<summary>
A boolean value that indicates if the module should always be loaded.
If true, the user can choose to not load the module by entering the appropriate commandline option.
If false, the user can choose to load the module by entering the appropriate commandline option.
</summary>
public override bool LoadAsDefault { get { return true; } }
<summary>
Gets a list of supported commandline arguments
</summary>
public override IList<<API key>> SupportedCommands
{
get
{
return new List<<API key>>(new <API key>[] {
new CommandLineArgument(OPTION_RECIPIENT, CommandLineArgument.ArgumentType.String, Strings.SendJabberMessage.SendxmpptoShort, Strings.SendJabberMessage.SendxmpptoLong),
new CommandLineArgument(OPTION_MESSAGE, CommandLineArgument.ArgumentType.String, Strings.SendJabberMessage.<API key>, Strings.SendJabberMessage.SendxmppmessageLong, DEFAULT_BODY),
new CommandLineArgument(OPTION_USERNAME, CommandLineArgument.ArgumentType.String, Strings.SendJabberMessage.<API key>, Strings.SendJabberMessage.<API key>),
new CommandLineArgument(OPTION_PASSWORD, CommandLineArgument.ArgumentType.String, Strings.SendJabberMessage.<API key>, Strings.SendJabberMessage.<API key>),
new CommandLineArgument(OPTION_SENDLEVEL, CommandLineArgument.ArgumentType.Enumeration, Strings.SendJabberMessage.SendxmpplevelShort, Strings.SendJabberMessage.SendxmpplevelLong(ParsedResultType.Success.ToString(), ParsedResultType.Warning.ToString(), ParsedResultType.Error.ToString(), ParsedResultType.Fatal.ToString(), "All"), DEFAULT_LEVEL, null, Enum.GetNames(typeof(ParsedResultType)).Union(new string[] { "All" } ).ToArray()),
new CommandLineArgument(OPTION_SENDALL, CommandLineArgument.ArgumentType.Boolean, Strings.SendJabberMessage.<API key>, Strings.SendJabberMessage.<API key>),
new CommandLineArgument(OPTION_LOG_LEVEL, CommandLineArgument.ArgumentType.Enumeration, Strings.ReportHelper.<API key>, Strings.ReportHelper.OptionLoglevelLong, DEFAULT_LOG_LEVEL.ToString(), null, Enum.GetNames(typeof(Logging.LogMessageType))),
new CommandLineArgument(OPTION_LOG_FILTER, CommandLineArgument.ArgumentType.String, Strings.ReportHelper.<API key>, Strings.ReportHelper.OptionLogfilterLong),
new CommandLineArgument(<API key>, CommandLineArgument.ArgumentType.Integer, Strings.ReportHelper.<API key>, Strings.ReportHelper.<API key>, DEFAULT_LOGLINES.ToString()),
new CommandLineArgument(<API key>, CommandLineArgument.ArgumentType.Enumeration, Strings.ReportHelper.ResultFormatShort, Strings.ReportHelper.ResultFormatLong(Enum.GetNames(typeof(ResultExportFormat))), <API key>.ToString(), null, Enum.GetNames(typeof(ResultExportFormat))),
});
}
}
protected override string SubjectOptionName => OPTION_MESSAGE;
protected override string BodyOptionName => OPTION_MESSAGE;
protected override string <API key> => OPTION_SENDLEVEL;
protected override string <API key> => OPTION_SENDALL;
protected override string LogLevelOptionName => OPTION_LOG_LEVEL;
protected override string LogFilterOptionName => OPTION_LOG_FILTER;
protected override string LogLinesOptionName => <API key>;
protected override string <API key> => <API key>;
<summary>
This method is the interception where the module can interact with the execution environment and modify the settings.
</summary>
<param name="commandlineOptions">A set of commandline options passed to Duplicati</param>
protected override bool ConfigureModule(IDictionary<string, string> commandlineOptions)
{
//We need at least a recipient
commandlineOptions.TryGetValue(OPTION_RECIPIENT, out m_to);
if (string.IsNullOrEmpty(m_to))
return false;
commandlineOptions.TryGetValue(OPTION_USERNAME, out m_username);
commandlineOptions.TryGetValue(OPTION_PASSWORD, out m_password);
return true;
}
#endregion
protected override string ReplaceTemplate(string input, object result, bool subjectline)
{
// No need to do the expansion as we throw away the result
if (subjectline)
return string.Empty;
return base.ReplaceTemplate(input, result, subjectline);
}
protected override void SendMessage(string subject, string body)
{
Exception ex = null;
var waitEvent = new System.Threading.ManualResetEvent(false);
var uri = new Library.Utility.Uri(m_username.Contains(":
var con = new agsXMPP.<API key>(uri.Host, uri.Port == -1 ? (uri.Scheme == "https" ? 5223 :5222) : uri.Port);
if (uri.Scheme == "https")
con.UseSSL = true;
var resource = uri.Path ?? "";
if (resource.StartsWith("/", StringComparison.Ordinal))
resource = resource.Substring(1);
if (string.IsNullOrWhiteSpace(resource))
resource = "Duplicati";
agsXMPP.ObjectHandler loginDelegate = (sender) =>
{
try
{
foreach(var recipient in m_to.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
con.Send(new agsXMPP.protocol.client.Message(recipient, agsXMPP.protocol.client.MessageType.chat, body));
}
catch (Exception e)
{
Logging.Log.WriteWarningMessage(LOGTAG, "XMPPSendError", e, "Failed to send to XMPP messages: {0}", e.Message);
ex = e;
}
finally
{
waitEvent.Set();
}
};
agsXMPP.ErrorHandler errorHandler = (sender, e) => {
Logging.Log.WriteWarningMessage(LOGTAG, "XMPPError", e, "An error ocurred in XMPP: {0}", e.Message);
ex = e;
waitEvent.Set();
};
agsXMPP.XmppElementHandler loginErroHandler = (sender, e) => {
Logging.Log.WriteWarningMessage(LOGTAG, "XMPPLoginError", null, "Failed to login to XMPP: {0}", e);
ex = new Exception(string.Format("Failed to log in: {0}", e));
waitEvent.Set();
};
con.OnLogin += loginDelegate;
con.OnError += errorHandler;
con.OnAuthError += loginErroHandler;
//con.OnBinded += (sender) => {Console.WriteLine("Binded: {0}", sender);};
//con.OnIq += (sender, iq) => {Console.WriteLine("Iq: {0}", iq);};
//con.OnReadXml += (sender, xml) => {Console.WriteLine("ReadXml: {0}", xml);};
//con.OnWriteXml += (sender, xml) => {Console.WriteLine("writeXml: {0}", xml);};;
con.Open(uri.Username, string.IsNullOrWhiteSpace(m_password) ? uri.Password : m_password, resource);
var timeout = !waitEvent.WaitOne(TimeSpan.FromSeconds(30), true);
con.OnLogin -= loginDelegate;
con.OnError -= errorHandler;
con.OnAuthError -= loginErroHandler;
try
{
con.Close();
}
catch (Exception lex)
{
Logging.Log.<API key>(LOGTAG, "<API key>", lex, "Failed to close XMPP connection: {0}", lex.Message);
}
if (ex != null)
throw ex;
if (timeout)
throw new TimeoutException(Strings.SendJabberMessage.LoginTimeoutError);
}
}
} |
#include "cppeditor.h"
#include "cppeditorplugin.h"
#include "cppeditortestcase.h"
#include <coreplugin/editormanager/editormanager.h>
#include <cpptools/<API key>.h>
#include <cplusplus/CppDocument.h>
#include <utils/fileutils.h>
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QKeyEvent>
#include <QString>
#include <QtTest>
/*!
Tests for inserting doxygen comments.
*/
using namespace Core;
using namespace CPlusPlus;
using namespace CppEditor::Internal;
namespace {
typedef QByteArray _;
/**
* Encapsulates the whole process of setting up an editor,
* pressing ENTER and checking the result.
*/
class DoxygenTestCase : public CppEditor::Internal::Tests::TestCase
{
public:
The '|' in the input denotes the cursor position.
DoxygenTestCase(const QByteArray &original, const QByteArray &expected)
{
QVERIFY(succeededSoFar());
CppEditor::Internal::Tests::TestDocument testDocument("file.cpp", original, '|');
QVERIFY(testDocument.hasCursorMarker());
testDocument.m_source.remove(testDocument.m_cursorPosition, 1);
QVERIFY(testDocument.writeToDisk());
// Update Code Model
QVERIFY(parseFiles(testDocument.filePath()));
// Open Editor
QVERIFY(openCppEditor(testDocument.filePath(), &testDocument.m_editor,
&testDocument.m_editorWidget));
<API key>(testDocument.m_editor);
// We want to test documents that start with a comment. By default, the
// editor will fold the very first comment it encounters, assuming
// expected (some blocks are still hidden in some test cases, so the
// cursor movements are not as expected). For the time being, we just
// prepend a declaration before the initial test comment.
// testDocument.m_editorWidget->unfoldAll();
testDocument.m_editor->setCursorPosition(testDocument.m_cursorPosition);
<API key>(testDocument.m_editorWidget);
// Send 'ENTER' key press
QKeyEvent event(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier);
QCoreApplication::sendEvent(testDocument.m_editorWidget, &event);
const QByteArray result = testDocument.m_editorWidget->document()->toPlainText().toUtf8();
QCOMPARE(QLatin1String(result), QLatin1String(expected));
testDocument.m_editorWidget->undo();
const QByteArray contentsAfterUndo
= testDocument.m_editorWidget->document()->toPlainText().toUtf8();
QCOMPARE(contentsAfterUndo, testDocument.m_source);
}
};
} // anonymous namespace
void CppEditorPlugin::<API key>()
{
QTest::addColumn<QByteArray>("given");
QTest::addColumn<QByteArray>("expected");
QTest::newRow("qt_style") << _(
"bool preventFolding;\n"
"/*!\n"
" * \\brief a\n"
" */\n"
"int a;\n"
);
QTest::newRow("<API key>") << _(
"bool preventFolding;\n"
"/*!\n"
" * \\brief a|\n"
" */\n"
"int a;\n"
) << _(
"bool preventFolding;\n"
"/*!\n"
" * \\brief a\n"
" * \n"
" */\n"
"int a;\n"
);
QTest::newRow("java_style") << _(
"bool preventFolding;\n"
"/**\n"
" * @brief a\n"
" */\n"
"int a;\n"
);
QTest::newRow("<API key>") << _(
"bool preventFolding;\n"
"/**\n"
" * @brief a|\n"
" */\n"
"int a;\n"
) << _(
"bool preventFolding;\n"
"/**\n"
" * @brief a\n"
" * \n"
" */\n"
"int a;\n"
);
QTest::newRow("cpp_styleA") << _(
"bool preventFolding;\n"
"
"int a;\n"
) << _(
"bool preventFolding;\n"
"
"/// \\brief a\n"
"
"int a;\n"
);
QTest::newRow("cpp_styleB") << _(
"bool preventFolding;\n"
"
"int a;\n"
) << _(
"bool preventFolding;\n"
"
"//! \\brief a\n"
"
"int a;\n"
);
QTest::newRow("<API key>") << _(
"bool preventFolding;\n"
"
"/// \\brief a|\n"
"
"int a;\n"
) << _(
"bool preventFolding;\n"
"
"/// \\brief a\n"
"
"
"int a;\n"
);
test cpp style doxygen comment when inside a indented scope
QTest::newRow("cpp_styleA_indented") << _(
" bool preventFolding;\n"
"
" int a;\n"
) << _(
" bool preventFolding;\n"
"
" /// \\brief a\n"
"
" int a;\n"
);
test cpp style doxygen comment continuation when inside a indented scope
QTest::newRow("<API key>") << _(
" bool preventFolding;\n"
"
" /// \\brief a|\n"
"
" int a;\n"
) << _(
" bool preventFolding;\n"
"
" /// \\brief a\n"
"
"
" int a;\n"
);
QTest::newRow("<API key>") << _(
"bool preventFolding;\n"
"
"void d();
) << _(
"bool preventFolding;\n"
"
"void d();
"\n"
);
}
void CppEditorPlugin::<API key>()
{
QFETCH(QByteArray, given);
QFETCH(QByteArray, expected);
DoxygenTestCase(given, expected);
} |
/**
* Implements the CFML Function <API key>
*/
package lucee.runtime.functions.other;
import java.util.ArrayList;
import lucee.commons.lang.CFTypes;
import lucee.commons.lang.StringUtil;
import lucee.runtime.PageContext;
import lucee.runtime.config.ConfigImpl;
import lucee.runtime.config.ConfigWebUtil;
import lucee.runtime.exp.ExpressionException;
import lucee.runtime.exp.FunctionException;
import lucee.runtime.exp.PageException;
import lucee.runtime.ext.function.Function;
import lucee.runtime.functions.system.CFFunction;
import lucee.runtime.op.Caster;
import lucee.runtime.type.Array;
import lucee.runtime.type.ArrayImpl;
import lucee.runtime.type.Collection;
import lucee.runtime.type.Collection.Key;
import lucee.runtime.type.FunctionArgument;
import lucee.runtime.type.KeyImpl;
import lucee.runtime.type.Struct;
import lucee.runtime.type.StructImpl;
import lucee.runtime.type.UDF;
import lucee.runtime.type.util.ArrayUtil;
import lucee.runtime.type.util.KeyConstants;
import lucee.transformer.library.function.FunctionLib;
import lucee.transformer.library.function.FunctionLibFunction;
import lucee.transformer.library.function.<API key>;
import lucee.transformer.library.tag.TagLibFactory;
public final class GetFunctionData implements Function {
private static final Collection.Key SOURCE = KeyConstants._source;
private static final Collection.Key RETURN_TYPE = KeyImpl.intern("returnType");
private static final Collection.Key ARGUMENT_TYPE = KeyImpl.intern("argumentType");
private static final Collection.Key ARG_MIN = KeyImpl.intern("argMin");
private static final Collection.Key ARG_MAX = KeyImpl.intern("argMax");
public static Struct call(PageContext pc , String strFunctionName) throws PageException {
return _call(pc, strFunctionName, pc.<API key>());
}
public static Struct call(PageContext pc , String strFunctionName, String strDialect) throws PageException {
int dialect=ConfigWebUtil.toDialect(strDialect,-1);
if(dialect==-1) throw new FunctionException(pc, "GetFunctionData", 2, "dialect", "value ["+strDialect+"] is invalid, valid values are [cfml,lucee]");
return _call(pc, strFunctionName, dialect);
}
private static Struct _call(PageContext pc , String strFunctionName, int dialect) throws PageException {
FunctionLib[] flds;
flds = ((ConfigImpl)pc.getConfig()).getFLDs(dialect);
FunctionLibFunction function=null;
for(int i=0;i<flds.length;i++) {
function = flds[i].getFunction(strFunctionName.toLowerCase());
if(function!=null)break;
}
if(function == null) throw new ExpressionException("function ["+strFunctionName+"] is not a built in function");
// CFML Based Function
Class clazz=null;
try{
clazz=function.<API key>().getClazz();
}
catch(Throwable t){}
if(clazz==lucee.runtime.functions.system.CFFunction.class){
return cfmlBasedFunction(pc,function);
}
return javaBasedFunction(function);
}
private static Struct javaBasedFunction(FunctionLibFunction function) throws PageException {
Struct sct=new StructImpl();
sct.set(KeyConstants._name,function.getName());
sct.set(KeyConstants._status,TagLibFactory.toStatus(function.getStatus()));
sct.set(KeyConstants._description,StringUtil.emptyIfNull(function.getDescription()));
if(!ArrayUtil.isEmpty(function.getKeywords()))sct.set("keywords",Caster.toArray(function.getKeywords()));
sct.set(RETURN_TYPE,StringUtil.emptyIfNull(function.<API key>()));
sct.set(ARGUMENT_TYPE,StringUtil.emptyIfNull(function.getArgTypeAsString()));
sct.set(ARG_MIN,Caster.toDouble(function.getArgMin()));
sct.set(ARG_MAX,Caster.toDouble(function.getArgMax()));
sct.set(KeyConstants._type,"java");
String[] names = function.getMemberNames();
if(!ArrayUtil.isEmpty(names) && function.getMemberType()!=CFTypes.TYPE_UNKNOW) {
StructImpl mem = new StructImpl();
sct.set(KeyConstants._member, mem);
mem.set(KeyConstants._name,names[0]);
mem.set(KeyConstants._chaining,Caster.toBoolean(function.getMemberChaining()));
mem.set(KeyConstants._type, function.<API key>());
mem.set("position", Caster.toDouble(function.getMemberPosition()));
}
Array _args=new ArrayImpl();
sct.set(KeyConstants._arguments,_args);
if(function.getArgType()!=FunctionLibFunction.ARG_DYNAMIC){
ArrayList<<API key>> args = function.getArg();
for(int i=0;i<args.size();i++) {
<API key> arg=args.get(i);
Struct _arg=new StructImpl();
_arg.set(KeyConstants._required,arg.getRequired()?Boolean.TRUE:Boolean.FALSE);
_arg.set(KeyConstants._type,StringUtil.emptyIfNull(arg.getTypeAsString()));
_arg.set(KeyConstants._name,StringUtil.emptyIfNull(arg.getName()));
_arg.set(KeyConstants._status,TagLibFactory.toStatus(arg.getStatus()));
_arg.set("defaultValue",arg.getDefaultValue());
_arg.set(KeyConstants._description,StringUtil.toStringEmptyIfNull(arg.getDescription()));
_args.append(_arg);
}
}
return sct;
}
private static Struct cfmlBasedFunction(PageContext pc, FunctionLibFunction function) throws PageException {
Struct sct=new StructImpl();
ArrayList<<API key>> args = function.getArg();
String filename = Caster.toString(args.get(0).getDefaultValue());
Key name = KeyImpl.toKey(args.get(1).getDefaultValue());
boolean isWeb = Caster.toBooleanValue(args.get(2).getDefaultValue());
UDF udf = CFFunction.loadUDF(pc, filename, name, isWeb);
sct.set(KeyConstants._name,function.getName());
sct.set(ARGUMENT_TYPE,"fixed");
sct.set(KeyConstants._description,StringUtil.emptyIfNull(udf.getHint()));
sct.set(RETURN_TYPE,StringUtil.emptyIfNull(udf.<API key>()));
sct.set(KeyConstants._type,"cfml");
sct.set(SOURCE,udf.getSource());
sct.set(KeyConstants._status,"implemeted");
FunctionArgument[] fas = udf.<API key>();
Array _args=new ArrayImpl();
sct.set(KeyConstants._arguments,_args);
int min=0,max=0;
for(int i=0;i<fas.length;i++) {
FunctionArgument fa=fas[i];
Struct meta = fa.getMetaData();
Struct _arg=new StructImpl();
if(fa.isRequired()) min++;
max++;
_arg.set(KeyConstants._required,fa.isRequired()?Boolean.TRUE:Boolean.FALSE);
_arg.set(KeyConstants._type,StringUtil.emptyIfNull(fa.getTypeAsString()));
_arg.set(KeyConstants._name,StringUtil.emptyIfNull(fa.getName()));
_arg.set(KeyConstants._description,StringUtil.emptyIfNull(fa.getHint()));
String status;
if(meta==null)status="implemeted";
else status=TagLibFactory.toStatus(TagLibFactory.toStatus(Caster.toString(meta.get(KeyConstants._status,"implemeted"))));
_arg.set(KeyConstants._status,status);
_args.append(_arg);
}
sct.set(ARG_MIN,Caster.toDouble(min));
sct.set(ARG_MAX,Caster.toDouble(max));
return sct;
}
} |
#ifndef QANIMATIONWRITER_H
#define QANIMATIONWRITER_H
#include <QImage>
QT_BEGIN_NAMESPACE
class <API key>;
class QAnimationWriter
{
public:
QAnimationWriter(const QString& filename, const char* format = "MNG");
~QAnimationWriter();
bool okay() const;
void setFrameRate(int);
void appendBlankFrame();
void appendFrame(const QImage&);
void appendFrame(const QImage&, const QPoint& offset);
private:
QImage prev;
QIODevice* dev;
<API key>* d;
};
QT_END_NAMESPACE
#endif |
#include "test.h"
pthread_mutex_t mutex1 = <API key>;
static int washere = 0;
void * func(void * arg)
{
assert(<API key>(&mutex1) == EBUSY);
washere = 1;
return 0;
}
int
main()
{
pthread_t t;
assert(pthread_mutex_lock(&mutex1) == 0);
assert(pthread_create(&t, NULL, func, NULL) == 0);
assert(pthread_join(t, NULL) == 0);
assert(<API key>(&mutex1) == 0);
assert(washere == 1);
return 0;
} |
#ifndef <API key>
#define <API key>
#include <texteditor/basetextdocument.h>
namespace VCSBase {
namespace Internal {
// A read-only text document.
class VCSBaseTextDocument : public TextEditor::BaseTextDocument
{
Q_OBJECT
public:
VCSBaseTextDocument();
bool isReadOnly() const;
bool isModified() const;
void setForceReadOnly(bool b);
bool isForceReadOnly() const;
private:
bool m_forceReadOnly;
};
} // namespace Internal
} // namespace VCSBase
#endif // <API key> |
#include "<API key>.h"
#include "qquickpath_p.h"
QT_BEGIN_NAMESPACE
/*!
\qmltype PathInterpolator
\instantiates <API key>
\inqmlmodule QtQuick 2
\ingroup <API key>
\brief Specifies how to manually animate along a path
PathInterpolator provides \c x, \c y, and \c angle information for a particular \c progress
along a path.
In the following example, we animate a green rectangle along a bezier path.
\snippet qml/pathinterpolator.qml 0
*/
<API key>::<API key>(QObject *parent) :
QObject(parent), _path(0), _x(0), _y(0), _angle(0), _progress(0)
{
}
/*!
\qmlproperty Path QtQuick2::PathInterpolator::path
This property holds the path to interpolate.
For more information on defining a path see the \l Path documentation.
*/
QQuickPath *<API key>::path() const
{
return _path;
}
void <API key>::setPath(QQuickPath *path)
{
if (_path == path)
return;
if (_path)
disconnect(_path, SIGNAL(changed()), this, SLOT(_q_pathUpdated()));
_path = path;
connect(_path, SIGNAL(changed()), this, SLOT(_q_pathUpdated()));
emit pathChanged();
}
/*!
\qmlproperty real QtQuick2::PathInterpolator::progress
This property holds the current progress along the path.
Typical usage of PathInterpolator is to set the progress
(often via a NumberAnimation), and read the corresponding
values for x, y, and angle (often via bindings to these values).
Progress ranges from 0.0 to 1.0.
*/
qreal <API key>::progress() const
{
return _progress;
}
void <API key>::setProgress(qreal progress)
{
progress = qMin(qMax(progress, (qreal)0.0), (qreal)1.0);
if (progress == _progress)
return;
_progress = progress;
emit progressChanged();
_q_pathUpdated();
}
/*!
\qmlproperty real QtQuick2::PathInterpolator::x
\qmlproperty real QtQuick2::PathInterpolator::y
These properties hold the position of the path at \l progress.
*/
qreal <API key>::x() const
{
return _x;
}
qreal <API key>::y() const
{
return _y;
}
/*!
\qmlproperty real QtQuick2::PathInterpolator::angle
This property holds the angle of the path tangent at \l progress.
Angles are reported clockwise, with zero degrees at the 3 o'clock position.
*/
qreal <API key>::angle() const
{
return _angle;
}
void <API key>::_q_pathUpdated()
{
if (! _path)
return;
qreal angle = 0;
const QPointF pt = _path->sequentialPointAt(_progress, &angle);
if (_x != pt.x()) {
_x = pt.x();
emit xChanged();
}
if (_y != pt.y()) {
_y = pt.y();
emit yChanged();
}
//convert to clockwise
angle = qreal(360) - angle;
if (qFuzzyCompare(angle, qreal(360)))
angle = qreal(0);
if (angle != _angle) {
_angle = angle;
emit angleChanged();
}
}
QT_END_NAMESPACE |
#ifndef <API key>
#define <API key>
#include <set>
#include <string>
#include <vector>
#include "olad/Plugin.h"
#include "ola/plugin_id.h"
#include "plugins/ftdidmx/FtdiDmxDevice.h"
namespace ola {
namespace plugin {
namespace ftdidmx {
class FtdiDmxPlugin : public Plugin {
public:
explicit FtdiDmxPlugin(ola::PluginAdaptor *plugin_adaptor)
: Plugin(plugin_adaptor) {
}
ola_plugin_id Id() const { return OLA_PLUGIN_FTDIDMX; }
string Name() const { return PLUGIN_NAME; }
string PluginPrefix() const { return PLUGIN_PREFIX; }
// This plugin is disabled unless explicitly enabled by a user.
bool DefaultMode() const { return false; }
void ConflictsWith(std::set<ola_plugin_id> *conflict_set) {
conflict_set->insert(ola::OLA_PLUGIN_USBPRO);
conflict_set->insert(ola::OLA_PLUGIN_OPENDMX);
}
string Description() const;
private:
typedef vector<FtdiDmxDevice*> FtdiDeviceVector;
FtdiDeviceVector m_devices;
void AddDevice(FtdiDmxDevice *device);
bool StartHook();
bool StopHook();
bool <API key>();
unsigned int GetFrequency();
static const char DEFAULT_FREQUENCY[];
static const char K_FREQUENCY[];
static const char PLUGIN_NAME[];
static const char PLUGIN_PREFIX[];
};
} // namespace ftdidmx
} // namespace plugin
} // namespace ola
#endif // <API key> |
// This file is part of the Marble Virtual Globe.
// the source code.
#ifndef <API key>
#define <API key>
#include "NewstuffModel.h"
#include <<API key>>
class OfflineDataModel : public <API key>
{
Q_OBJECT
Q_PROPERTY( int count READ count NOTIFY countChanged )
Q_FLAGS(VehicleType VehicleTypes)
public:
enum VehicleType {
None = 0x0,
Motorcar = 0x1,
Bicycle = 0x2,
Pedestrian = 0x4,
Any = Motorcar | Bicycle | Pedestrian
};
Q_DECLARE_FLAGS(VehicleTypes, VehicleType)
explicit OfflineDataModel( QObject* parent = 0 );
int count();
#if QT_VERSION >= 0x050000
QHash<int, QByteArray> roleNames() const;
#endif
virtual QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const;
public Q_SLOTS:
void <API key>( VehicleTypes filter );
void install( int index );
void uninstall( int index );
void cancel( int index );
Q_SIGNALS:
void countChanged();
void <API key>( int newstuffindex, qreal progress );
void <API key>( int newstuffindex );
void installationFailed( int newstuffindex, const QString &error );
void <API key>( int newstuffindex );
protected:
virtual bool filterAcceptsRow( int source_row, const QModelIndex &source_parent ) const;
private Q_SLOTS:
void <API key>( int index, qreal progress );
void <API key>( int index );
void <API key>( int index, const QString &error );
void <API key>( int index );
private:
int fromSource( int idx ) const;
int toSource( int idx ) const;
Marble::NewstuffModel m_newstuffModel;
VehicleTypes m_vehicleTypeFilter;
#if QT_VERSION >= 0x050000
QHash<int, QByteArray> m_roleNames;
#endif
};
#endif |
// Jubatus: Online machine learning framework for distributed environment
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#ifndef <API key>
#define <API key>
#include <string>
#include "string_filter.hpp"
#include "exception.hpp"
namespace jubatus {
namespace core {
namespace fv_converter {
class regexp_filter : public string_filter {
public:
regexp_filter(const std::string& regexp, const std::string& replace) {
throw JUBATUS_EXCEPTION(
converter_exception("regexp support is disabled"));
}
void filter(const std::string& input, std::string& output) const {}
};
} // namespace fv_converter
} // namespace core
} // namespace jubatus
#endif // <API key> |
package org.jboss.as.remoting.logging;
import static org.jboss.logging.Logger.Level.INFO;
import java.io.IOException;
import java.net.BindException;
import org.jboss.as.controller.<API key>;
import org.jboss.as.controller.PathAddress;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import org.jboss.msc.service.StartException;
@MessageLogger(projectCode = "WFLYRMT", length = 4)
public interface RemotingLogger extends BasicLogger {
/**
* A logger with a category of the package name.
*/
RemotingLogger ROOT_LOGGER = Logger.getMessageLogger(RemotingLogger.class, "org.jboss.as.remoting");
@LogMessage(level = INFO)
@Message(id = 1, value = "Listening on %s")
void listeningOnSocket(String address);
@Message(id = 2, value = "Could not start channel listener")
StartException <API key>(@Cause Exception e);
// @Message(id = 3, value = "Shutting down")
// <API key> channelShuttingDown();
@Message(id = 4, value = "%s")
StartException <API key>(String message, @Cause BindException e);
@Message(id = 5, value = "Failed to start service")
StartException couldNotStart(@Cause Exception e);
@Message(id = 6, value = "Endpoint is null")
<API key> endpointEmpty();
// id = 7; redundant parameter null check message
// id = 8; redundant parameter null check message
// id = 9; redundant parameter null check message
// id = 10; redundant parameter null check message
// @Message(id = 11, value = "A security realm has been specified but no supported mechanism identified")
// <API key> <API key>();
// @Message(id = 12, value = "ANONYMOUS mechanism so not expecting a callback")
// <API key> <API key>(@Param Callback current);
//@Message(id = 13, value = "Unable to create tmp dir for auth tokens as file already exists.")
//StartException <API key><API key>();
//@Message(id = 14, value = "Unable to create auth dir %s.")
//StartException <API key>(String dir);
// @Message(id = 15, value = "Could not connect")
// RuntimeException couldNotConnect(@Cause URISyntaxException e);
@Message(id = 16, value = "Invalid QOP value: %s")
<API key> invalidQOPV(String qop);
@Message(id = 17, value = "Invalid Strength value: %s")
<API key> invalidStrength(String strengthValue);
@Message(id = 18, value = "Cannot create a valid URI from %s
<API key> couldNotCreateURI(String uri, String msg);
// @Message(id = 19, value = "Unsupported Callback")
// <API key> unsupportedCallback(@Param Callback current);
@Message(id = 20, value = "Invalid Strength '%s' string given")
<API key> illegalStrength(String strength);
@Message(id = 21, value = "HTTP Upgrade request missing <API key> header")
IOException <API key>();
@Message(id = 22, value = "Worker configuration is no longer used, please use endpoint worker configuration")
<API key> <API key>();
@Message(id = 23, value = "Only one of '%s' configuration or '%s' configuration is allowed")
String <API key>(String workerThreads, String endpoint);
@LogMessage(level = INFO)
@Message(id = 24, value = "The remoting subsystem is present but no io subsystem was found. An io subsystem " +
"was not required when remoting schema '%s' was current but now is, so a default subsystem is being added.")
void addingIOSubsystem(String legacyNS);
@Message(id = 25, value = "Can't remove %s as JMX uses it as a remoting endpoint")
<API key> <API key>(PathAddress address);
@Message(id = 26, value = "Change of worker to '%s' in remoting might require the same change in resources depending on remoting.")
String <API key>(String worker);
@Message(id = 27, value = "Failed to obtain SSLContext")
StartException <API key>(@Cause Exception cause);
@Message(id = 28, value = "Invalid option '%s'.")
<API key> invalidOption(String message);
} |
#ifndef HELPPLUGIN_H
#define HELPPLUGIN_H
#include "helpwidget.h"
#include <coreplugin/helpmanager.h>
#include <coreplugin/icontext.h>
#include <extensionsystem/iplugin.h>
#include <QMap>
#include <QStringList>
QT_BEGIN_NAMESPACE
class QAction;
class QMenu;
class QToolButton;
class QUrl;
QT_END_NAMESPACE
namespace Core {
class IMode;
class MiniSplitter;
class SideBar;
class SideBarItem;
} // Core
namespace Utils { class StyledBar; }
namespace Help {
namespace Internal {
class CentralWidget;
class DocSettingsPage;
class FilterSettingsPage;
class GeneralSettingsPage;
class HelpMode;
class HelpViewer;
class LocalHelpManager;
class OpenPagesManager;
class SearchWidget;
class SearchTaskHandler;
class HelpPlugin : public ExtensionSystem::IPlugin
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QtCreatorPlugin" FILE "Help.json")
public:
HelpPlugin();
virtual ~HelpPlugin();
bool initialize(const QStringList &arguments, QString *errorMessage);
void <API key>();
ShutdownFlag aboutToShutdown();
static HelpViewer *createHelpViewer(qreal zoom);
private slots:
void modeChanged(Core::IMode *mode, Core::IMode *old);
void showContextHelp();
void activateIndex();
void activateContents();
void <API key>();
void showLinkInHelpMode(const QUrl &source);
void showLinksInHelpMode(const QMap<QString, QUrl> &links, const QString &key);
void slotHideRightPane();
void updateSideBarSource();
void updateSideBarSource(const QUrl &newUrl);
void fontChanged();
void <API key>();
void <API key>();
void handleHelpRequest(const QUrl &url, Core::HelpManager::HelpViewerLocation location);
void slotOpenSupportPage();
void slotReportBug();
private:
void resetFilter();
void activateHelpMode();
bool <API key>() const;
HelpViewer *<API key>(Core::HelpManager::HelpViewerLocation location);
HelpViewer *<API key>();
HelpWidget *createHelpWidget(const Core::Context &context, HelpWidget::WidgetStyle style);
void <API key>();
HelpViewer *externalHelpViewer();
void doSetupIfNeeded();
Core::HelpManager::HelpViewerLocation contextHelpOption() const;
private:
HelpMode *m_mode;
CentralWidget *m_centralWidget;
HelpWidget *<API key>;
DocSettingsPage *m_docSettingsPage;
FilterSettingsPage *<API key>;
GeneralSettingsPage *<API key>;
SearchTaskHandler *m_searchTaskHandler;
bool m_setupNeeded;
LocalHelpManager *m_helpManager;
OpenPagesManager *m_openPagesManager;
QString <API key>;
QPointer<HelpWidget> m_externalWindow;
QRect <API key>;
};
} // namespace Internal
} // namespace Help
#endif // HELPPLUGIN_H |
#include <QDomElement>
#include <QXmlStreamWriter>
#include "QXmppConstants_p.h"
#include "QXmppIbbIq.h"
QXmppIbbOpenIq::QXmppIbbOpenIq() : QXmppIq(QXmppIq::Set), m_block_size(1024)
{
}
long QXmppIbbOpenIq::blockSize() const
{
return m_block_size;
}
void QXmppIbbOpenIq::setBlockSize( long block_size )
{
m_block_size = block_size;
}
QString QXmppIbbOpenIq::sid() const
{
return m_sid;
}
void QXmppIbbOpenIq::setSid( const QString &sid )
{
m_sid = sid;
}
\cond
bool QXmppIbbOpenIq::isIbbOpenIq(const QDomElement &element)
{
QDomElement openElement = element.firstChildElement("open");
return openElement.namespaceURI() == ns_ibb;
}
void QXmppIbbOpenIq::<API key>(const QDomElement &element)
{
QDomElement openElement = element.firstChildElement("open");
m_sid = openElement.attribute( "sid" );
m_block_size = openElement.attribute( "block-size" ).toLong();
}
void QXmppIbbOpenIq::<API key>(QXmlStreamWriter *writer) const
{
writer->writeStartElement("open");
writer->writeAttribute( "xmlns",ns_ibb);
writer->writeAttribute( "sid",m_sid);
writer->writeAttribute( "block-size",QString::number(m_block_size) );
writer->writeEndElement();
}
\endcond
QXmppIbbCloseIq::QXmppIbbCloseIq() : QXmppIq(QXmppIq::Set)
{
}
QString QXmppIbbCloseIq::sid() const
{
return m_sid;
}
void QXmppIbbCloseIq::setSid( const QString &sid )
{
m_sid = sid;
}
\cond
bool QXmppIbbCloseIq::isIbbCloseIq(const QDomElement &element)
{
QDomElement openElement = element.firstChildElement("close");
return openElement.namespaceURI() == ns_ibb;
}
void QXmppIbbCloseIq::<API key>(const QDomElement &element)
{
QDomElement openElement = element.firstChildElement("close");
m_sid = openElement.attribute( "sid" );
}
void QXmppIbbCloseIq::<API key>(QXmlStreamWriter *writer) const
{
writer->writeStartElement("close");
writer->writeAttribute( "xmlns",ns_ibb);
writer->writeAttribute( "sid",m_sid);
writer->writeEndElement();
}
\endcond
QXmppIbbDataIq::QXmppIbbDataIq() : QXmppIq( QXmppIq::Set ), m_seq(0)
{
}
quint16 QXmppIbbDataIq::sequence() const
{
return m_seq;
}
void QXmppIbbDataIq::setSequence( quint16 seq )
{
m_seq = seq;
}
QString QXmppIbbDataIq::sid() const
{
return m_sid;
}
void QXmppIbbDataIq::setSid( const QString &sid )
{
m_sid = sid;
}
QByteArray QXmppIbbDataIq::payload() const
{
return m_payload;
}
void QXmppIbbDataIq::setPayload( const QByteArray &data )
{
m_payload = data;
}
\cond
bool QXmppIbbDataIq::isIbbDataIq(const QDomElement &element)
{
QDomElement dataElement = element.firstChildElement("data");
return dataElement.namespaceURI() == ns_ibb;
}
void QXmppIbbDataIq::<API key>(const QDomElement &element)
{
QDomElement dataElement = element.firstChildElement("data");
m_sid = dataElement.attribute( "sid" );
m_seq = dataElement.attribute( "seq" ).toLong();
m_payload = QByteArray::fromBase64( dataElement.text().toLatin1() );
}
void QXmppIbbDataIq::<API key>(QXmlStreamWriter *writer) const
{
writer->writeStartElement("data");
writer->writeAttribute( "xmlns",ns_ibb);
writer->writeAttribute( "sid",m_sid);
writer->writeAttribute( "seq",QString::number(m_seq) );
writer->writeCharacters( m_payload.toBase64() );
writer->writeEndElement();
}
\endcond |
#include "task.h"
#include <QDateTime>
#include <QString>
#include <QTimer>
#include <QPixmap>
#include <KDebug>
#include <KIconLoader>
#include <kcal/event.h>
#include "ktimetrackerutility.h"
#include "ktimetracker.h"
#include "preferences.h"
QVector<QPixmap*> *Task::icons = 0;
Task::Task( const QString& taskName, long minutes, long sessionTime,
DesktopList desktops, TaskView *parent, bool konsolemode )
: QObject(), QTreeWidgetItem(parent)
{
init( taskName, minutes, sessionTime, 0, desktops, 0, 0, konsolemode );
}
Task::Task( const QString& taskName, long minutes, long sessionTime,
DesktopList desktops, Task *parent)
: QObject(), QTreeWidgetItem(parent)
{
init( taskName, minutes, sessionTime, 0, desktops, 0, 0 );
}
Task::Task( KCal::Todo* todo, TaskView* parent, bool konsolemode )
: QObject(), QTreeWidgetItem( parent )
{
long minutes = 0;
QString name;
long sessionTime = 0;
QString sessionStartTiMe;
int percent_complete = 0;
int priority = 0;
DesktopList desktops;
parseIncidence( todo, minutes, sessionTime, sessionStartTiMe, name, desktops, percent_complete,
priority );
init( name, minutes, sessionTime, sessionStartTiMe, desktops, percent_complete, priority, konsolemode );
}
int Task::depth()
// Deliver the depth of a task, i.e. how many tasks are supertasks to it.
// A toplevel task has the depth 0.
{
kDebug(5970) << "Entering function";
int res=0;
Task* t=this;
while ( ( t = t->parent() ) ) res++;
kDebug(5970) << "Leaving function. depth is:" << res;
return res;
}
void Task::init( const QString& taskName, long minutes, long sessionTime, QString sessionStartTiMe,
DesktopList desktops, int percent_complete, int priority, bool konsolemode )
{
// If our parent is the taskview then connect our totalTimesChanged
// signal to its receiver
if ( ! parent() )
connect( this, SIGNAL( totalTimesChanged ( long, long ) ),
treeWidget(), SLOT( <API key>( long, long) ));
connect( this, SIGNAL( deletingTask( Task* ) ),
treeWidget(), SLOT( deletingTask( Task* ) ));
if (icons == 0)
{
icons = new QVector<QPixmap*>(8);
if (!konsolemode)
{
KIconLoader kil("ktimetracker");
for (int i=0; i<8; i++)
{
QPixmap *icon = new QPixmap();
QString name;
name.sprintf("watch-%d.xpm",i);
*icon = kil.loadIcon( name, KIconLoader::User );
icons->insert(i,icon);
}
}
}
mRemoving = false;
mName = taskName.trimmed();
mLastStart = QDateTime::currentDateTime();
mTotalTime = mTime = minutes;
mTotalSessionTime = mSessionTime = sessionTime;
mTimer = new QTimer(this);
mDesktops = desktops;
connect(mTimer, SIGNAL(timeout()), this, SLOT(updateActiveIcon()));
if ( !konsolemode ) setIcon(1, UserIcon(QString::fromLatin1("empty-watch.xpm")));
mCurrentPic = 0;
mPercentComplete = percent_complete;
mPriority = priority;
mSessionStartTiMe=KDateTime::fromString(sessionStartTiMe);
update();
<API key>( mSessionTime, mTime);
// alignment of the number items
for (int i = 1; i < columnCount(); ++i)
{
setTextAlignment( i, Qt::AlignRight );
}
// .. but not the priority column
setTextAlignment( 5, Qt::AlignCenter );
}
Task::~Task()
{
emit deletingTask(this);
delete mTimer;
}
void Task::delete_recursive()
{
while ( this->child(0) )
{
Task* t=(Task*) this->child(0);
t->delete_recursive();
}
delete this;
}
void Task::setRunning( bool on, timetrackerstorage* storage, const QDateTime &when )
// This is the back-end, the front-end is StartTimerFor()
{
kDebug(5970) << "Entering function";
if ( on )
{
if (!mTimer->isActive())
{
mTimer->start(1000);
storage->startTimer(this);
mCurrentPic=7;
mLastStart = when;
kDebug(5970) << "task has been started for " << when;
updateActiveIcon();
}
}
else
{
if (mTimer->isActive())
{
mTimer->stop();
if ( ! mRemoving )
{
storage->stopTimer(this, when);
setIcon(1, UserIcon(QString::fromLatin1("empty-watch.xpm")));
}
}
}
}
void Task::resumeRunning()
// setRunning is the back-end, the front-end is StartTimerFor().
// resumeRunning does the same as setRunning, but not add a new
// start date to the storage.
{
kDebug(5970) << "Entering function";
if (!mTimer->isActive())
{
mTimer->start(1000);
mCurrentPic=7;
updateActiveIcon();
}
}
void Task::setUid( const QString &uid )
{
mUid = uid;
}
bool Task::isRunning() const
{
return mTimer->isActive();
}
void Task::setName( const QString& name, timetrackerstorage* storage )
{
kDebug(5970) << "Entering function, name=" << name;
QString oldname = mName;
if ( oldname != name )
{
mName = name;
storage->setName(this, oldname);
update();
}
}
void Task::setPercentComplete(const int percent, timetrackerstorage *storage)
{
kDebug(5970) << "Entering function(" << percent <<", storage):" << mUid;
if (!percent)
mPercentComplete = 0;
else if (percent > 100)
mPercentComplete = 100;
else if (percent < 0)
mPercentComplete = 0;
else
mPercentComplete = percent;
if (isRunning() && mPercentComplete==100) taskView()->stopTimerFor(this);
setPixmapProgress();
// When parent marked as complete, mark all children as complete as well.
// This behavior is consistent with KOrganizer (as of 2003-09-24).
if (mPercentComplete == 100)
{
for ( int i = 0; i < childCount(); ++i )
{
Task *task = static_cast< Task* >( child( i ) );
task->setPercentComplete(mPercentComplete, storage);
}
}
// maybe there is a column "percent completed", so do a ...
update();
}
void Task::setPriority( int priority )
{
if ( priority < 0 )
{
priority = 0;
}
else if ( priority > 9 )
{
priority = 9;
}
mPriority = priority;
update();
}
void Task::setPixmapProgress()
{
kDebug(5970) << "Entering function";
QPixmap icon;
KIconLoader* kil = new KIconLoader();
if (mPercentComplete >= 100)
{
const QString iconcomplete=QString("task-complete.xpm");
icon = kil->loadIcon( iconcomplete, KIconLoader::User );
}
else
{
const QString iconincomplete=QString("task-incomplete.xpm");
icon = kil->loadIcon( iconincomplete, KIconLoader::User );
}
setIcon(0, icon);
delete kil;
kDebug(5970) << "Leaving function";
}
bool Task::isComplete() { return mPercentComplete == 100; }
void Task::setDesktopList ( DesktopList desktopList )
{
mDesktops = desktopList;
}
void Task::changeTime( long minutes, timetrackerstorage* storage )
{
changeTimes( minutes, minutes, storage);
}
QString Task::addTime( long minutes )
{
kDebug(5970) << "Entering function";
QString err;
mTime+=minutes;
this->addTotalTime( minutes );
kDebug(5970) << "Leaving function";
return err;
}
QString Task::addTotalTime( long minutes )
{
kDebug(5970) << "Entering function";
QString err;
mTotalTime+=minutes;
if ( parent() ) parent()->addTotalTime( minutes );
kDebug(5970) << "Leaving function";
return err;
}
QString Task::addSessionTime( long minutes )
{
kDebug(5970) << "Entering function";
QString err;
mSessionTime+=minutes;
this->addTotalSessionTime( minutes );
kDebug(5970) << "Leaving function";
return err;
}
QString Task::addTotalSessionTime( long minutes )
{
kDebug(5970) << "Entering function";
QString err;
mTotalSessionTime+=minutes;
if ( parent() ) parent()->addTotalSessionTime( minutes );
kDebug(5970) << "Leaving function";
return err;
}
QString Task::setTime( long minutes )
{
kDebug(5970) << "Entering function";
QString err;
mTime=minutes;
mTotalTime+=minutes;
kDebug(5970) << "Leaving function";
return err;
}
long Task::<API key>()
{
long result=0;
setTotalTime(0);
Task* child;
for (int i=0; i<this->childCount(); ++i)
child=(Task*)this->child(i);
addTotalTime(time());
result=totalTime();
return result;
}
QString Task::<API key>()
{
QString result;
setTotalSessionTime(0);
Task* child;
for (int i=0; i<this->childCount(); ++i)
child=(Task*)this->child(i);
addTotalSessionTime(time());
return result;
}
QString Task::setSessionTime( long minutes )
{
kDebug(5970) << "Entering function";
QString err;
mSessionTime=minutes;
mTotalSessionTime+=minutes;
kDebug(5970) << "Leaving function";
return err;
}
void Task::changeTimes( long minutesSession, long minutes, timetrackerstorage* storage)
{
kDebug(5970) << "Entering function";
kDebug() << "Task's sessionStartTiMe is " << mSessionStartTiMe;
if( minutesSession != 0 || minutes != 0)
{
mSessionTime += minutesSession;
mTime += minutes;
if ( storage ) storage->changeTime(this, minutes * secsPerMinute);
changeTotalTimes( minutesSession, minutes );
}
kDebug(5970) << "Leaving function";
}
void Task::changeTotalTimes( long minutesSession, long minutes )
{
kDebug(5970)
<< "Task::changeTotalTimes(" << minutesSession << ","
<< minutes << ") for" << name();
mTotalSessionTime += minutesSession;
mTotalTime += minutes;
update();
<API key>( minutesSession, minutes );
kDebug(5970) << "Leaving function";
}
void Task::resetTimes()
{
kDebug(5970) << "Entering function";
mTotalSessionTime -= mSessionTime;
mTotalTime -= mTime;
<API key>( -mSessionTime, -mTime);
mSessionTime = 0;
mTime = 0;
update();
kDebug(5970) << "Leaving function";
}
void Task::<API key>( long minutesSession, long minutes )
{
if ( isRoot() )
emit totalTimesChanged( minutesSession, minutes );
else
parent()->changeTotalTimes( minutesSession, minutes );
}
bool Task::remove( timetrackerstorage* storage)
{
kDebug(5970) << "entering function" << mName;
bool ok = true;
mRemoving = true;
storage->removeTask(this);
if( isRunning() ) setRunning( false, storage );
for ( int i = 0; i < childCount(); ++i )
{
Task *task = static_cast< Task* >( child( i ) );
if ( task->isRunning() )
task->setRunning( false, storage );
task->remove( storage );
}
<API key>( -mSessionTime, -mTime);
mRemoving = false;
return ok;
}
void Task::updateActiveIcon()
{
mCurrentPic = (mCurrentPic+1) % 8;
setIcon(1, *(*icons)[mCurrentPic]);
}
QString Task::fullName() const
{
if (isRoot())
return name();
else
return parent()->fullName() + QString::fromLatin1("/") + name();
}
KCal::Todo* Task::asTodo(KCal::Todo* todo) const
{
Q_ASSERT( todo != NULL );
kDebug(5970) <<"Task::asTodo: name() = '" << name() <<"'";
todo->setSummary( name() );
// Note: if the date start is empty, the KOrganizer GUI will have the
// checkbox blank, but will prefill the todo's starting datetime to the
// time the file is opened.
// todo->setDtStart( current );
todo->setCustomProperty( KGlobal::mainComponent().componentName().toUtf8(),
QByteArray( "totalTaskTime" ), QString::number( mTime ) );
todo->setCustomProperty( KGlobal::mainComponent().componentName().toUtf8(),
QByteArray( "totalSessionTime" ), QString::number( mSessionTime) );
todo->setCustomProperty( KGlobal::mainComponent().componentName().toUtf8(),
QByteArray( "sessionStartTiMe" ), mSessionStartTiMe.toString() );
kDebug() << "mSessionStartTiMe=" << mSessionStartTiMe.toString() ;
if (getDesktopStr().isEmpty())
todo-><API key>(KGlobal::mainComponent().componentName().toUtf8(), QByteArray("desktopList"));
else
todo->setCustomProperty( KGlobal::mainComponent().componentName().toUtf8(),
QByteArray( "desktopList" ), getDesktopStr() );
todo->setOrganizer( <API key>::userRealName() );
todo->setPercentComplete(mPercentComplete);
todo->setPriority( mPriority );
return todo;
}
bool Task::parseIncidence( KCal::Incidence* incident, long& minutes,
long& sessionMinutes, QString& sessionStartTiMe, QString& name, DesktopList& desktops,
int& percent_complete, int& priority )
{
kDebug(5970) << "Entering function";
bool ok;
name = incident->summary();
mUid = incident->uid();
mComment = incident->description();
ok = false;
// if a KDE-karm-duration exists and not <API key>, change this
if (
incident->customProperty( KGlobal::mainComponent().componentName().toUtf8(),
QByteArray( "totalTaskTime" )) == QString::null && incident->customProperty( "karm",
QByteArray( "totalTaskTime" )) != QString::null )
incident->setCustomProperty(
KGlobal::mainComponent().componentName().toUtf8(),
QByteArray( "totalTaskTime" ), incident->customProperty( "karm",
QByteArray( "totalTaskTime" )));
minutes = incident->customProperty( KGlobal::mainComponent().componentName().toUtf8(),
QByteArray( "totalTaskTime" )).toInt( &ok );
if ( !ok )
minutes = 0;
ok = false;
// if a <API key> exists and not <API key>, change this
if (
incident->customProperty( KGlobal::mainComponent().componentName().toUtf8(),
QByteArray( "totalSessionTime" )) == QString::null && incident->customProperty( "karm",
QByteArray( "totalSessionTime" )) != QString::null )
incident->setCustomProperty(
KGlobal::mainComponent().componentName().toUtf8(),
QByteArray( "totalSessionTime" ), incident->customProperty( "karm",
QByteArray( "totalSessionTime" )));
sessionMinutes = incident->customProperty( KGlobal::mainComponent().componentName().toUtf8(),
QByteArray( "totalSessionTime" )).toInt( &ok );
if ( !ok )
sessionMinutes = 0;
sessionStartTiMe=incident->customProperty( KGlobal::mainComponent().componentName().toUtf8(), QByteArray( "sessionStartTiMe" ));
// if a <API key> exists and no <API key>, change this
if (
incident->customProperty( KGlobal::mainComponent().componentName().toUtf8(),
QByteArray( "desktopList" )) == QString::null && incident->customProperty( "karm",
QByteArray( "desktopList" )) != QString::null )
incident->setCustomProperty(
KGlobal::mainComponent().componentName().toUtf8(),
QByteArray( "desktopList" ), incident->customProperty( "karm",
QByteArray( "desktopList" )));
QString desktopList = incident->customProperty( KGlobal::mainComponent().componentName().toUtf8(),
QByteArray( "desktopList" ) );
QStringList desktopStrList = desktopList.split( QString::fromLatin1(","),
QString::SkipEmptyParts );
desktops.clear();
for ( QStringList::iterator iter = desktopStrList.begin();
iter != desktopStrList.end();
++iter )
{
int desktopInt = (*iter).toInt( &ok );
if ( ok )
{
desktops.push_back( desktopInt );
}
}
percent_complete = static_cast<KCal::Todo*>(incident)->percentComplete();
priority = incident->priority();
return true;
}
QString Task::getDesktopStr() const
{
if ( mDesktops.empty() )
return QString();
QString desktopstr;
for ( DesktopList::const_iterator iter = mDesktops.begin();
iter != mDesktops.end();
++iter )
{
desktopstr += QString::number( *iter ) + QString::fromLatin1( "," );
}
desktopstr.remove( desktopstr.length() - 1, 1 );
return desktopstr;
}
void Task::cut()
// This is needed e.g. to move a task under its parent when loading.
{
kDebug(5970) << "Entering function";
<API key>( -mTotalSessionTime, -mTotalTime);
if ( ! parent() )
treeWidget()->takeTopLevelItem(treeWidget()->indexOfTopLevelItem(this));
else
parent()->takeChild(indexOfChild(this));
kDebug(5970) << "Leaving function";
}
void Task::paste(Task* destination)
// This is needed e.g. to move a task under its parent when loading.
{
kDebug(5970) << "Entering function";
destination->QTreeWidgetItem::insertChild(0,this);
<API key>( mTotalSessionTime, mTotalTime);
kDebug(5970) << "Leaving function";
}
void Task::move(Task* destination)
// This is used e.g. to move each task under its parent after loading.
{
kDebug(5970) << "Entering function";
cut();
paste(destination);
kDebug(5970) << "Leaving function";
}
void Task::update()
// Update a row, containing one task
{
kDebug( 5970 ) << "Entering function";
bool b = <API key>::decimalFormat();
setText( 0, mName );
setText( 1, formatTime( mSessionTime, b ) );
setText( 2, formatTime( mTime, b ) );
setText( 3, formatTime( mTotalSessionTime, b ) );
setText( 4, formatTime( mTotalTime, b ) );
setText( 5, mPriority > 0 ? QString::number( mPriority ) : "
setText( 6, QString::number( mPercentComplete ) );
kDebug( 5970 ) << "Leaving function";
}
void Task::addComment( const QString &comment, timetrackerstorage* storage )
{
mComment = mComment + QString::fromLatin1("\n") + comment;
storage->addComment(this, comment);
}
void Task::startNewSession()
{
changeTimes( -mSessionTime, 0 );
mSessionStartTiMe=KDateTime::<API key>();
}
//BEGIN Properties
QString Task::uid() const
{
return mUid;
}
QString Task::comment() const
{
return mComment;
}
int Task::percentComplete() const
{
return mPercentComplete;
}
int Task::priority() const
{
return mPriority;
}
QString Task::name() const
{
return mName;
}
QDateTime Task::startTime() const
{
return mLastStart;
}
long Task::time() const
{
return mTime;
}
long Task::totalTime() const
{
return mTotalTime;
}
long Task::sessionTime() const
{
return mSessionTime;
}
long Task::totalSessionTime() const
{
return mTotalSessionTime;
}
KDateTime Task::sessionStartTiMe() const
{
return mSessionStartTiMe;
}
DesktopList Task::desktops() const
{
return mDesktops;
}
//END
#include "task.moc" |
package org.nuxeo.ecm.platform.ec.notification.service;
import org.nuxeo.common.xmap.annotation.XNode;
import org.nuxeo.common.xmap.annotation.XObject;
/**
* @author <a href="mailto:npaslaru@nuxeo.com">Narcis Paslaru</a>
*
*/
@XObject("event")
public class <API key> {
@XNode("@name")
protected String name;
} |
/* -*- c-file-style: "ruby"; indent-tabs-mode: nil -*- */
#include "rbgdk3private.h"
#define RG_TARGET_NAMESPACE mGdk
ID id_call;
struct <API key> {
VALUE ary;
long n;
GdkPoint *result;
};
static VALUE
<API key>(VALUE value)
{
long i;
struct <API key> *args = (struct <API key> *)value;
for (i = 0; i < args->n; i++) {
VALUE points = rb_ary_to_ary(RARRAY_PTR(args->ary)[i]);
if (RARRAY_LEN(points) != 2)
rb_raise(rb_eArgError, "point %ld should be array of size 2", i);
args->result[i].x = NUM2INT(RARRAY_PTR(points)[0]);
args->result[i].y = NUM2INT(RARRAY_PTR(points)[1]);
}
return Qnil;
}
static G_GNUC_NORETURN VALUE
<API key>(VALUE value)
{
g_free(((struct <API key> *)value)->result);
rb_exc_raise(rb_errinfo());
}
GdkPoint *
<API key>(VALUE value, long *n)
{
struct <API key> args;
args.ary = rb_ary_to_ary(value);
args.n = RARRAY_LEN(args.ary);
args.result = g_new(GdkPoint, args.n + 1);
rb_rescue(<API key>, (VALUE)&args,
<API key>, (VALUE)&args);
*n = args.n;
return args.result;
}
struct <API key> {
VALUE ary;
long n;
GdkAtom *result;
};
static VALUE
<API key>(VALUE value)
{
long i;
struct <API key> *args = (struct <API key> *)value;
for (i = 0; i < args->n; i++)
args->result[i] = RVAL2ATOM(RARRAY_PTR(args->ary)[i]);
return Qnil;
}
static G_GNUC_NORETURN VALUE
<API key>(VALUE value)
{
g_free(((struct <API key> *)value)->result);
rb_exc_raise(rb_errinfo());
}
GdkAtom *
rbgdk_rval2gdkatoms(VALUE value, long *n)
{
struct <API key> args;
args.ary = rb_ary_to_ary(value);
args.n = RARRAY_LEN(args.ary);
args.result = g_new(GdkAtom, args.n + 1);
rb_rescue(<API key>, (VALUE)&args,
<API key>, (VALUE)&args);
*n = args.n;
return args.result;
}
struct <API key> {
VALUE ary;
long n;
GList *result;
};
static VALUE
<API key>(VALUE value)
{
long i;
struct <API key> *args = (struct <API key> *)value;
for (i = 0; i < args->n; i++)
args->result = g_list_append(args->result, RVAL2GDKPIXBUF(RARRAY_PTR(args->ary)[i]));
return Qnil;
}
static G_GNUC_NORETURN VALUE
<API key>(VALUE value)
{
g_list_free(((struct <API key> *)value)->result);
rb_exc_raise(rb_errinfo());
}
GList *
<API key>(VALUE value)
{
struct <API key> args;
args.ary = rb_ary_to_ary(value);
args.n = RARRAY_LEN(args.ary);
args.result = NULL;
rb_rescue(<API key>, (VALUE)&args,
<API key>, (VALUE)&args);
return args.result;
}
static VALUE
<API key>(G_GNUC_UNUSED VALUE self)
{
return CSTR2RVAL(<API key>());
}
/* deprecated
static VALUE
rg_s_set_locale(G_GNUC_UNUSED VALUE self)
{
return CSTR2RVAL(gdk_set_locale());
}
*/
/* deprecated
static VALUE
<API key>(VALUE self, VALUE id)
{
<API key>(<API key>(id));
return self;
}
*/
static VALUE
<API key>(int argc, VALUE *argv, VALUE self)
{
VALUE startup_id;
rb_scan_args(argc, argv, "01", &startup_id);
if (NIL_P(startup_id)) {
<API key>();
} else {
<API key>(RVAL2CSTR(startup_id));
}
return self;
}
static VALUE
rg_s_program_class(G_GNUC_UNUSED VALUE self)
{
return CSTR2RVAL(<API key>());
}
static VALUE
<API key>(VALUE self, VALUE program_class)
{
<API key>(RVAL2CSTR(program_class));
return self;
}
static VALUE
rg_s_display(G_GNUC_UNUSED VALUE self)
{
return CSTR2RVAL(gdk_get_display());
}
#ifdef HAVE_X11_XLIB_H
#ifdef HAVE_XGETERRORTEXT
#include <X11/Xlib.h>
#include <errno.h>
static VALUE rb_x_error;
static VALUE rb_x_io_error;
static int
rbgdk_x_error(Display *display, XErrorEvent *error)
{
gchar buf[64];
XGetErrorText(display, error->error_code, buf, 63);
rb_funcall((VALUE)rb_x_error, id_call, 4, INT2NUM(error->serial),
INT2NUM(error->error_code), INT2NUM(error->request_code),
INT2NUM(error->minor_code));
return 0;
}
static int
rbgdk_x_io_error(Display *display)
{
int errno_saved = errno;
const gchar* disp;
const gchar* error;
disp = display ? DisplayString(display) : <API key>();
if (! disp)
disp = "(none)";
error = g_strerror(errno_saved);
rb_funcall((VALUE)rb_x_io_error, id_call, 3, CSTR2RVAL(disp),
INT2NUM(errno), CSTR2RVAL(error));
return 0;
}
#endif
#endif
static VALUE
<API key>(VALUE self)
{
#ifdef HAVE_XGETERRORTEXT
rb_x_error = rb_block_proc();
G_RELATIVE(self, rb_x_error);
XSetErrorHandler(rbgdk_x_error);
#else
rb_warn("Not supported on this environment.");
#endif
return self;
}
static VALUE
<API key>(VALUE self)
{
#ifdef HAVE_XGETERRORTEXT
rb_x_io_error = rb_block_proc();
G_RELATIVE(self, rb_x_io_error);
XSetIOErrorHandler(rbgdk_x_io_error);
#else
rb_warn("Not supported on this environment.");
#endif
return self;
}
static VALUE
rg_s_flush(VALUE self)
{
gdk_flush();
return self;
}
static VALUE
rg_s_screen_width(G_GNUC_UNUSED VALUE self)
{
return INT2NUM(gdk_screen_width());
}
static VALUE
<API key>(G_GNUC_UNUSED VALUE self)
{
return INT2NUM(gdk_screen_width_mm());
}
static VALUE
rg_s_screen_height(G_GNUC_UNUSED VALUE self)
{
return INT2NUM(gdk_screen_height());
}
static VALUE
<API key>(G_GNUC_UNUSED VALUE self)
{
return INT2NUM(<API key>());
}
static VALUE
<API key>(VALUE self, VALUE msec)
{
<API key>(NUM2UINT(msec));
return self;
}
static VALUE
rg_s_beep(VALUE self)
{
gdk_beep();
return self;
}
static VALUE
<API key>(VALUE self)
{
gdk_error_trap_push();
return self;
}
static VALUE
rg_s_error_trap_pop(VALUE self)
{
gdk_error_trap_pop();
return self;
}
static VALUE
<API key>(G_GNUC_UNUSED VALUE self)
{
#ifdef GDK_WINDOWING_X11
return Qtrue;
#else
return Qfalse;
#endif
}
static VALUE
<API key>(G_GNUC_UNUSED VALUE self)
{
#ifdef GDK_WINDOWING_WIN32
return Qtrue;
#else
return Qfalse;
#endif
}
static VALUE
rg_s_windowing_fb_p(G_GNUC_UNUSED VALUE self)
{
#ifdef GDK_WINDOWING_FB
return Qtrue;
#else
return Qfalse;
#endif
}
static VALUE
<API key>(G_GNUC_UNUSED VALUE self)
{
#ifdef <API key>
return Qtrue;
#else
return Qfalse;
#endif
}
static VALUE
<API key>(G_GNUC_UNUSED VALUE self)
{
#ifdef <API key>
return Qtrue;
#else
return Qfalse;
#endif
}
static VALUE
rg_s_target(G_GNUC_UNUSED VALUE self)
{
return CSTR2RVAL(RUBY_GDK3_TARGET);
}
static VALUE
<API key>(G_GNUC_UNUSED VALUE self)
{
return Qtrue;
}
void
Init_gdk(void)
{
id_call = rb_intern("call");
VALUE RG_TARGET_NAMESPACE = rb_define_module("Gdk");
RG_DEF_SMETHOD(display_arg_name, 0);
/* deprecated
RG_DEF_SMETHOD(set_locale, 0);
RG_DEF_SMETHOD(set_sm_client_id, 1);
*/
RG_DEF_SMETHOD(<API key>, -1);
RG_DEF_SMETHOD(program_class, 0);
RG_DEF_SMETHOD(set_program_class, 1);
RG_DEF_SMETHOD(display, 0);
RG_DEF_SMETHOD(set_x_error_handler, 0);
RG_DEF_SMETHOD(<API key>, 0);
RG_DEF_SMETHOD(screen_width, 0);
RG_DEF_SMETHOD(screen_width_mm, 0);
RG_DEF_SMETHOD(screen_height, 0);
RG_DEF_SMETHOD(screen_height_mm, 0);
RG_DEF_SMETHOD(beep, 0);
RG_DEF_SMETHOD(flush, 0);
RG_DEF_SMETHOD(<API key>, 1);
RG_DEF_SMETHOD(error_trap_push, 0);
RG_DEF_SMETHOD(error_trap_pop, 0);
RG_DEF_SMETHOD_P(windowing_x11, 0);
RG_DEF_SMETHOD_P(windowing_win32, 0);
RG_DEF_SMETHOD_P(windowing_fb, 0);
RG_DEF_SMETHOD_P(windowing_quartz, 0);
RG_DEF_SMETHOD_P(windowing_directfb, 0);
RG_DEF_SMETHOD(target, 0);
RG_DEF_SMETHOD_P(cairo_available, 0);
G_DEF_CLASS(<API key>, "GrabStatus", RG_TARGET_NAMESPACE);
Init_gdk_atom(RG_TARGET_NAMESPACE);
Init_gdk_cairo();
Init_gdk_color(RG_TARGET_NAMESPACE);
Init_gdk_const(RG_TARGET_NAMESPACE);
Init_gdk_cursor(RG_TARGET_NAMESPACE);
Init_gdk_device(RG_TARGET_NAMESPACE);
<API key>(RG_TARGET_NAMESPACE);
Init_gdk_display(RG_TARGET_NAMESPACE);
<API key>(RG_TARGET_NAMESPACE);
<API key>(RG_TARGET_NAMESPACE);
Init_gdk_event(RG_TARGET_NAMESPACE);
Init_gdk_geometry(RG_TARGET_NAMESPACE);
Init_gdk_keymap(RG_TARGET_NAMESPACE);
Init_gdk_keyval(RG_TARGET_NAMESPACE);
Init_gdk_pango(RG_TARGET_NAMESPACE);
/* deprecated
<API key>(RG_TARGET_NAMESPACE);
*/
Init_gdk_pixbuf(RG_TARGET_NAMESPACE);
Init_gdk_property(RG_TARGET_NAMESPACE);
Init_gdk_rectangle(RG_TARGET_NAMESPACE);
/* deprecated
Init_gdk_rgb(RG_TARGET_NAMESPACE);
*/
Init_gdk_rgba(RG_TARGET_NAMESPACE);
Init_gdk_screen(RG_TARGET_NAMESPACE);
Init_gdk_selection(RG_TARGET_NAMESPACE);
Init_gdk_threads(RG_TARGET_NAMESPACE);
Init_gdk_timecoord(RG_TARGET_NAMESPACE);
Init_gdk_visual(RG_TARGET_NAMESPACE);
Init_gdk_window(RG_TARGET_NAMESPACE);
Init_gdk_windowattr(RG_TARGET_NAMESPACE);
} |
#include <QtWidgets>
#include "xbelreader.h"
XbelReader::XbelReader(QTreeWidget *treeWidget)
: treeWidget(treeWidget)
{
QStyle *style = treeWidget->style();
folderIcon.addPixmap(style->standardPixmap(QStyle::SP_DirClosedIcon),
QIcon::Normal, QIcon::Off);
folderIcon.addPixmap(style->standardPixmap(QStyle::SP_DirOpenIcon),
QIcon::Normal, QIcon::On);
bookmarkIcon.addPixmap(style->standardPixmap(QStyle::SP_FileIcon));
}
def read(self, device):
self.setDevice(device)
while not atEnd():
readNext()
if isStartElement():
if self.name() == "xbel" and self.attributes().value("version") == "1.0":
self.readXBEL()
else:
self.raiseError(QObject.tr("The file is not an XBEL version 1.0 file."));
return not self.error();
void XbelReader::readUnknownElement()
{
Q_ASSERT(isStartElement());
while (!atEnd()) {
readNext();
if (isEndElement())
break;
if (isStartElement())
readUnknownElement();
}
}
void XbelReader::readXBEL()
{
Q_ASSERT(isStartElement() && name() == "xbel");
while (!atEnd()) {
readNext();
if (isEndElement())
break;
if (isStartElement()) {
if (name() == "folder")
readFolder(0);
else if (name() == "bookmark")
readBookmark(0);
else if (name() == "separator")
readSeparator(0);
else
readUnknownElement();
}
}
}
void XbelReader::readTitle(QTreeWidgetItem *item)
{
Q_ASSERT(isStartElement() && name() == "title");
QString title = readElementText();
item->setText(0, title);
}
void XbelReader::readSeparator(QTreeWidgetItem *item)
{
QTreeWidgetItem *separator = createChildItem(item);
separator->setFlags(item->flags() & ~Qt::ItemIsSelectable);
separator->setText(0, QString(30, 0xB7));
readElementText();
}
void XbelReader::readFolder(QTreeWidgetItem *item)
{
Q_ASSERT(isStartElement() && name() == "folder");
QTreeWidgetItem *folder = createChildItem(item);
bool folded = (attributes().value("folded") != "no");
treeWidget->setItemExpanded(folder, !folded);
while (!atEnd()) {
readNext();
if (isEndElement())
break;
if (isStartElement()) {
if (name() == "title")
readTitle(folder);
else if (name() == "folder")
readFolder(folder);
else if (name() == "bookmark")
readBookmark(folder);
else if (name() == "separator")
readSeparator(folder);
else
readUnknownElement();
}
}
}
void XbelReader::readBookmark(QTreeWidgetItem *item)
{
Q_ASSERT(isStartElement() && name() == "bookmark");
QTreeWidgetItem *bookmark = createChildItem(item);
bookmark->setFlags(bookmark->flags() | Qt::ItemIsEditable);
bookmark->setIcon(0, bookmarkIcon);
bookmark->setText(0, QObject::tr("Unknown title"));
bookmark->setText(1, attributes().value("href").toString());
while (!atEnd()) {
readNext();
if (isEndElement())
break;
if (isStartElement()) {
if (name() == "title")
readTitle(bookmark);
else
readUnknownElement();
}
}
}
QTreeWidgetItem *XbelReader::createChildItem(QTreeWidgetItem *item)
{
QTreeWidgetItem *childItem;
if (item) {
childItem = new QTreeWidgetItem(item);
} else {
childItem = new QTreeWidgetItem(treeWidget);
}
childItem->setData(0, Qt::UserRole, name().toString());
return childItem;
} |
package lucee.commons.collection.concurrent;
import lucee.commons.collection.concurrent.<API key>.Entry;
public interface EvictionPolicy {
/**
* Defines if element access can alter the ordering of elements in the
* underlying cache. This method will be invoked by the underlying cache
* implementation when an entry access is generated.
*
* <p>Invoking the <tt>get</tt> cache method results in an access to
* the corresponding entry (assuming it exists after the invocation completes).
* <i>No other methods generate entry accesses.</i> In particular, operations
* on collection-views do <i>not</i> affect the order of iteration of
* the backing cache.
*
* @return true for access based ordering, false otherwise
*/
public boolean accessOrder();
/**
* Defines if element insertion can alter the ordering of elements in
* the underlying cache. This method will be invoked by the underlying
* cache implementation when an entry insertion is generated.
*
* <p>Invoking the <tt>put</tt> cache method results in an insertion of the
* corresponding entry. The <tt>putAll</tt> method generates one entry
* insertion for each mapping in the specified map, in the order that key-value
* mappings are provided by the specified map's entry set iterator.
* <i>No other methods generate entry insertions.</i>
*
* @return true for insertion based ordering, false otherwise
*/
public boolean insertionOrder();
/**
* This method will be invoked by the underlying cache implementation when a
* entry insertion is generated. For every entry insertion an entry eviction
* can take place if a cache size threshold has been defined and exceeded and
* this method's implementation returns a <i>not NULL<i> element. Invoking the
* <tt>put</tt> cache method results in an insertion of the corresponding entry.
* The <tt>putAll</tt> method generates one entry insertion for each mapping
* in the specified map, in the order that key-value mappings are provided by
* the specified map's entry set iterator. <i>No other methods generate entry
* insertions.</i> In particular, operations on collection-views do <i>not</i>
* trigger element eviction for the backing cache.
*
* @param head the head of the double linked list of all elements in cache
* @return the element that should be evicted or null if no eviction should happen
*/
public Entry<?, ?> evictElement(Entry<?, ?> head);
/**
* This method will be invoked by the underlying cache implementation when a
* entry insertion is generated. Invoking the <tt>put</tt> cache method results
* in an insertion of the corresponding entry. The <tt>putAll</tt> method
* generates one entry insertion for each mapping in the specified map,
* in the order that key-value mappings are provided by the specified map's
* entry set iterator. <i>No other methods generate entry insertions.</i>
*
* <p>This method has no effect if {@link #insertionOrder()} method is implemented
* to return false, whereas the newly inserted element will be placed at the end
* (just before the head) of the cache's double linked element list.
*
* @param head the head of the double linked list of all elements in cache
* @param insertedEntry the cache entry that is inserted
* @return the element that will be preceding the newly inserted element
*/
public Entry<?, ?> recordInsertion(Entry<?, ?> head, Entry<?, ?> insertedEntry);
/**
* This method will be invoked by the underlying cache implementation when a
* entry access is generated. Invoking the <tt>get</tt> cache method results
* in an access to the corresponding entry (assuming it exists after the
* invocation completes).<i>No other methods generate entry accesses.</i>
*
* <p>This method has no effect if {@link #accessOrder()} method is implemented
* to return false.
*
* @param head the head of the double linked list of all elements in cache
* @param accessEntry the cache entry that is accessed
* @return the element that will be preceding the newly accessed element
*/
public Entry<?, ?> recordAccess(Entry<?, ?> head, Entry<?, ?> accessedEntry);
} |
Races Example (example-races)
`../gradlew runEampleRaces` runs the examples loader.
This example performs the following steps, to show how to use the Java Client
API to load data from two disparate sources and then harmonize it:
* Loads documents "as-is" from the `data` directory. When this step is
complete, the database will have lots of JSON documents as staged data.
* Loads some RDF reference data.
* Invokes an in-place transform batch on the raw documents. This transform
invokes code generated by Entity Services to wrap the JSON documents and store
them in their canonical format. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.