answer stringlengths 15 1.25M |
|---|
# -*- coding: utf-8 -*-
# File : echotorch/nn/ESN.py
# Description : An Echo State Network module.
# Date : 26th of January, 2018
# This file is part of EchoTorch. EchoTorch is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# This program is distributed in the hope that it will be useful, but WITHOUT
# details.
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import torch
from .LiESNCell import LiESNCell
from .ESN import ESN
# Leaky-Integrated Echo State Network module
class LiESN(ESN):
"""
Leaky-Integrated Echo State Network module
"""
# Constructor
def __init__(self, input_dim, hidden_dim, output_dim, spectral_radius=0.9,
bias_scaling=0, input_scaling=1.0, w=None, w_in=None, w_bias=None, sparsity=None,
input_set=[1.0, -1.0], w_sparsity=None, nonlin_func=torch.tanh, learning_algo='inv', ridge_param=0.0,
leaky_rate=1.0, train_leaky_rate=False, feedbacks=False, wfdb_sparsity=None,
normalize_feedbacks=False, softmax_output=False, seed=None, washout=0, w_distrib='uniform',
win_distrib='uniform', wbias_distrib='uniform', win_normal=(0.0, 1.0), w_normal=(0.0, 1.0),
wbias_normal=(0.0, 1.0), dtype=torch.float32):
"""
Constructor
:param input_dim:
:param hidden_dim:
:param output_dim:
:param spectral_radius:
:param bias_scaling:
:param input_scaling:
:param w:
:param w_in:
:param w_bias:
:param sparsity:
:param input_set:
:param w_sparsity:
:param nonlin_func:
:param learning_algo:
:param ridge_param:
:param leaky_rate:
:param train_leaky_rate:
:param feedbacks:
"""
super(LiESN, self).__init__(input_dim, hidden_dim, output_dim, spectral_radius=spectral_radius,
bias_scaling=bias_scaling, input_scaling=input_scaling,
w=w, w_in=w_in, w_bias=w_bias, sparsity=sparsity, input_set=input_set,
w_sparsity=w_sparsity, nonlin_func=nonlin_func, learning_algo=learning_algo,
ridge_param=ridge_param, create_cell=False, feedbacks=feedbacks,
wfdb_sparsity=wfdb_sparsity, normalize_feedbacks=normalize_feedbacks,
softmax_output=softmax_output, seed=seed, washout=washout, w_distrib=w_distrib,
win_distrib=win_distrib, wbias_distrib=wbias_distrib, win_normal=win_normal,
w_normal=w_normal, wbias_normal=wbias_normal, dtype=torch.float32)
# Recurrent layer
self.esn_cell = LiESNCell(leaky_rate, train_leaky_rate, input_dim, hidden_dim, spectral_radius=spectral_radius,
bias_scaling=bias_scaling, input_scaling=input_scaling,
w=w, w_in=w_in, w_bias=w_bias, sparsity=sparsity, input_set=input_set,
w_sparsity=w_sparsity, nonlin_func=nonlin_func, feedbacks=feedbacks,
feedbacks_dim=output_dim, wfdb_sparsity=wfdb_sparsity,
normalize_feedbacks=normalize_feedbacks, seed=seed, w_distrib=w_distrib,
win_distrib=win_distrib, wbias_distrib=wbias_distrib, win_normal=win_normal,
w_normal=w_normal, wbias_normal=wbias_normal, dtype=torch.float32)
# end __init__
# PROPERTIES
# PUBLIC
# PRIVATE
# end ESNCell |
<?php
// Laravel classes
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
/**
* Class BlogTables
*/
class BlogTables extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (!Schema::hasTable('posts')) {
Schema::create('posts', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id')->unsigned();
$table->integer('<API key>')->unsigned();
$table->foreign('<API key>')->references('id')->on('<API key>');
$table->string('title');
$table->string('slug')->unique();
$table->text('content');
$table->text('excerpt');
$table->string('meta_description');
$table->text('canonical_url');
$table->string('featured_image');
$table->string('image')->nullable();
$table->boolean('enabled')->default(true);
$table->boolean('postupdate')->default(false);
$table->boolean('sticky')->default(false);
$table->date('publish_on');
$table->timestamp('created_at')->nullable();
$table->integer('created_by')->nullable()->unsigned();
$table->foreign('created_by')->references('id')->on('users');
$table->timestamp('updated_at')->nullable();
$table->integer('updated_by')->nullable()->unsigned();
$table->foreign('updated_by')->references('id')->on('users');
$table->timestamp('locked_at')->nullable();
$table->integer('locked_by')->nullable()->unsigned();
$table->foreign('locked_by')->references('id')->on('users');
});
}
if (!Schema::hasTable('post_category')) {
Schema::create('post_category', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->integer('post_id')->unsigned()->index();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->primary(['post_id', 'category_id']);
});
}
if (!Schema::hasTable('post_tag')) {
Schema::create('post_tag', function (Blueprint $table) {
$table->integer('post_id')->unsigned()->index();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->integer('tag_id')->unsigned()->index();
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
$table->primary(['post_id', 'tag_id']);
});
}
if (!Schema::hasTable('postupdates')) {
Schema::create('postupdates', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id')->unsigned();
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->string('title')->unique();
$table->text('content');
$table->text('excerpt');
$table->boolean('enabled')->default(true);
$table->date('publish_on');
$table->timestamp('created_at');
$table->integer('created_by')->unsigned();
$table->foreign('created_by')->references('id')->on('users');
$table->timestamp('updated_at')->nullable();
$table->integer('updated_by')->unsigned();
$table->foreign('updated_by')->references('id')->on('users');
$table->timestamp('locked_at')->nullable();
$table->integer('locked_by')->nullable()->unsigned();
$table->foreign('locked_by')->references('id')->on('users');
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
// Disable foreign key constraints or these DROPs will not work
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
Schema::table('post_tag', function($table){
$table->dropIndex('<API key>');
$table->dropForeign('<API key>');
$table->dropIndex('<API key>');
$table->dropForeign('<API key>');
});
Schema::dropIfExists('post_tag');
Schema::table('post_category', function($table){
$table->dropIndex('<API key>');
$table->dropForeign('<API key>');
$table->dropIndex('<API key>');
$table->dropForeign('<API key>');
});
Schema::dropIfExists('post_category');
Schema::table('posts', function($table){
$table->dropIndex('posts_slug_unique');
$table->dropIndex('<API key>');
$table->dropForeign('<API key>');
$table->dropForeign('<API key>');
$table->dropForeign('<API key>');
$table->dropForeign('<API key>');
});
Schema::dropIfExists('posts');
Schema::table('postupdates', function($table){
$table->dropForeign('<API key>');
$table->dropForeign('<API key>');
$table->dropForeign('<API key>');
$table->dropForeign('<API key>');
});
Schema::dropIfExists('postupdates');
// Enable foreign key constraints
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}
} |
#include "SPIFlash.h"
#if defined (ARDUINO_ARCH_SAM) || defined (ARDUINO_ARCH_SAMD) || defined (<API key>)
#define _delay_us(us) delayMicroseconds(us)
#else
#include <util/delay.h>
#endif
// Uncomment the code below to run a diagnostic if your flash //
// does not respond //
// Error codes will be generated and returned on functions //
//#define RUNDIAGNOSTIC //
// Uncomment the code below to increase the speed of the library //
// by disabling _notPrevWritten() //
// Make sure the sectors being written to have been erased beforehand //
//#define HIGHSPEED
#if defined (ARDUINO_ARCH_AVR)
#ifdef __AVR_ATtiny85__
#define CHIP_SELECT PORTB &= ~cs_mask;
#define CHIP_DESELECT PORTB |= cs_mask;
#define SPIBIT \
USICR = ((1<<USIWM0)|(1<<USITC)); \
USICR = ((1<<USIWM0)|(1<<USITC)|(1<<USICLK));
static uint8_t xfer(uint8_t n) {
USIDR = n;
SPIBIT
SPIBIT
SPIBIT
SPIBIT
SPIBIT
SPIBIT
SPIBIT
SPIBIT
return USIDR;
}
#else
#include <SPI.h>
#define CHIP_SELECT *cs_port &= ~cs_mask;
#define CHIP_DESELECT *cs_port |= cs_mask;
#define xfer(n) SPI.transfer(n)
#endif
#elif defined (<API key>) || defined (ARDUINO_ARCH_SAMD) || defined (ARDUINO_ARCH_SAM)
#include <SPI.h>
#define CHIP_SELECT digitalWrite(csPin, LOW);
#define CHIP_DESELECT digitalWrite(csPin, HIGH);
#define xfer(n) SPI.transfer(n)
#endif
// Constructor
#if defined (ARDUINO_ARCH_AVR)
SPIFlash::SPIFlash(uint8_t cs, bool overflow) {
csPin = cs;
#ifndef __AVR_ATtiny85__
cs_port = portOutputRegister(digitalPinToPort(csPin));
#endif
cs_mask = digitalPinToBitMask(csPin);
pageOverflow = overflow;
pinMode(cs, OUTPUT);
}
#elif defined (<API key>) || defined (ARDUINO_ARCH_SAMD) || defined (ARDUINO_ARCH_SAM)
SPIFlash::SPIFlash(uint8_t cs, bool overflow) {
csPin = cs;
pageOverflow = overflow;
pinMode(cs, OUTPUT);
}
#endif
// Private functions used by read, write and erase operations //
//Double checks all parameters before calling a read or write. Comes in two variants
//Variant A: Takes address and returns the address if true, else returns false. Throws an error if there is a problem.
bool SPIFlash::_prep(uint8_t opcode, uint32_t address, uint32_t size) {
switch (opcode) {
case PAGEPROG:
if (!_addressCheck(address, size)) {
return false;
}
if(!_notBusy() || !_writeEnable()){
return false;
}
#ifndef HIGHSPEED
if(!_notPrevWritten(address, size)) {
return false;
}
#endif
return true;
break;
default:
if (!_addressCheck(address, size)) {
return false;
}
if (!_notBusy()){
return false;
}
return true;
break;
}
}
//Variant B: Take the opcode, page number, offset and size of data block as arguments
bool SPIFlash::_prep(uint8_t opcode, uint32_t page_number, uint8_t offset, uint32_t size) {
uint32_t address = _getAddress(page_number, offset);
return _prep(opcode, address, size);
}
bool SPIFlash::_transferAddress(void) {
#ifdef __AVR_ATtiny85__
(void)xfer(_currentAddress >> 16);
(void)xfer(_currentAddress >> 8);
(void)xfer(_currentAddress);
#else
SPI.transfer(_currentAddress >> 16);
SPI.transfer(_currentAddress >> 8);
SPI.transfer(_currentAddress);
#endif
}
//Initiates SPI operation - but data is not transferred yet. Always call _prep() before this function (especially when it involved writing or reading to/from an address)
bool SPIFlash::_beginSPI(uint8_t opcode) {
switch (opcode) {
case READDATA:
SPI.setDataMode(SPI_MODE0);
SPI.setBitOrder(MSBFIRST);
//SPI.setClockDivider(SPI_CLOCK_DIV4); //Uncomment this if more than one SPI device is presaent on the bus
SPI.begin();
CHIP_SELECT
#ifdef __AVR_ATtiny85__
(void)xfer(opcode);
#else
SPI.transfer(opcode);
#endif
_transferAddress();
break;
case FASTREAD:
SPI.setDataMode(SPI_MODE0);
SPI.setBitOrder(MSBFIRST);
//SPI.setClockDivider(SPI_CLOCK_DIV4); //Uncomment this if more than one SPI device is presaent on the bus
SPI.begin();
CHIP_SELECT
#ifdef __AVR_ATtiny85__
(void)xfer(opcode);
#else
SPI.transfer(opcode);
#endif
_transferAddress();
break;
case PAGEPROG:
SPI.setDataMode(SPI_MODE0);
SPI.setBitOrder(MSBFIRST);
//SPI.setClockDivider(SPI_CLOCK_DIV4); //Uncomment this if more than one SPI device is presaent on the bus
SPI.begin();
CHIP_SELECT
#ifdef __AVR_ATtiny85__
(void)xfer(opcode);
#else
SPI.transfer(opcode);
#endif
_transferAddress();
break;
default:
SPI.setDataMode(SPI_MODE0);
SPI.setBitOrder(MSBFIRST);
//SPI.setClockDivider(SPI_CLOCK_DIV4); //Uncomment this if more than one SPI device is presaent on the bus
SPI.begin();
CHIP_SELECT
#ifdef __AVR_ATtiny85__
(void)xfer(opcode);
#else
SPI.transfer(opcode);
#endif
break;
}
return true;
}
//SPI data lines are left open until _endSPI() is called
//Reads/Writes next byte. Call 'n' times to read/write 'n' number of bytes. Should be called after _begin()
uint8_t SPIFlash::_nextByte(uint8_t opcode, uint8_t data) {
switch (opcode) {
case READDATA:
uint8_t result;
#ifdef __AVR_ATtiny85__
result = xfer(NULLBYTE);
#else
result = SPI.transfer(NULLBYTE);
#endif
return result;
break;
case PAGEPROG:
#ifdef __AVR_ATtiny85__
xfer(data);
#else
SPI.transfer(data);
#endif
return true;
break;
default:
return false;
break;
}
}
//Stops all operations. Should be called after all the required data is read/written from repeated _readNextByte()/_nextByte(PAGEPROG, ) calls
void SPIFlash::_endSPI(void) {
CHIP_DESELECT
}
// Checks if status register 1 can be accessed - used during powerdown and power up and for debugging
uint8_t SPIFlash::_readStat1(void) {
_beginSPI(READSTAT1);
uint8_t stat1 = _nextByte(READDATA);
_endSPI();
return stat1;
}
// Checks if status register 2 can be accessed, if yes, reads and returns it
uint8_t SPIFlash::_readStat2(void) {
_beginSPI(READSTAT2);
uint8_t stat2 = _nextByte(READDATA);
_endSPI();
return stat2;
}
// Checks the erase/program suspend flag before enabling/disabling a program/erase suspend operation
bool SPIFlash::_noSuspend(void) {
if(_readStat2() & SUS)
return false;
return true;
}
// Polls the status register 1 until busy flag is cleared or timeout
bool SPIFlash::_notBusy(uint32_t timeout) {
uint32_t startTime = millis();
do {
state = _readStat1();
if((millis()-startTime) > timeout){
errorcode = CHIPBUSY;
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
return false;
}
} while(state & BUSY);
return true;
}
//Enables writing to chip by setting the WRITEENABLE bit
bool SPIFlash::_writeEnable(uint32_t timeout) {
uint32_t startTime = millis();
if (!(state & WRTEN)) {
do {
_beginSPI(WRITEENABLE);
_endSPI();
state = _readStat1();
if((millis()-startTime) > timeout) {
errorcode = CANTENWRITE;
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
return false;
}
} while (!(state & WRTEN));
}
return true;
}
//Disables writing to chip by setting the Write Enable Latch (WEL) bit in the Status Register to 0
//_writeDisable() is not required under the following conditions because the Write Enable Latch (WEL) flag is cleared to 0
// i.e. to write disable state:
// Power-up, Write Disable, Page Program, Quad Page Program, Sector Erase, Block Erase, Chip Erase, Write Status Register,
// Erase Security Register and Program Security register
bool SPIFlash::_writeDisable(void) {
_beginSPI(WRITEDISABLE);
_endSPI();
return true;
}
//Gets address from page number and offset. Takes two arguments:
// 1. page_number --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
uint32_t SPIFlash::_getAddress(uint16_t page_number, uint8_t offset) {
uint32_t address = page_number;
return ((address << 8) + offset);
}
//Checks the device ID to establish storage parameters
bool SPIFlash::_getManId(uint8_t *b1, uint8_t *b2) {
if(!_notBusy())
return false;
_beginSPI(MANID);
_nextByte(READDATA);
_nextByte(READDATA);
_nextByte(READDATA);
*b1 = _nextByte(READDATA);
*b2 = _nextByte(READDATA);
_endSPI();
return true;
}
//Checks for presence of chip by requesting JEDEC ID
bool SPIFlash::_getJedecId(uint8_t *b1, uint8_t *b2, uint8_t *b3) {
if(!_notBusy())
return false;
_beginSPI(JEDECID);
*b1 = SPI.transfer(READDATA); // manufacturer id
*b2 = SPI.transfer(READDATA); // manufacturer id
*b3 = SPI.transfer(READDATA); // capacity
_endSPI();
return true;
}
//Identifies the chip
bool SPIFlash::_chipID(void) {
//Get Manfucturer/Device ID so the library can identify the chip
uint8_t manID, capID, devID ;
//_getManId(&manID, &devID);
_getJedecId(&manID, &capID, &devID);
//Serial.println(manID, HEX);
//Serial.println(capID, HEX);
//Serial.println(devID, HEX);
if (manID != WINBOND_MANID && manID != MICROCHIP_MANID){ //If the chip is not a Winbond Chip
errorcode = UNKNOWNCHIP; //Error code for unidentified chip
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
while(1);
}
//Check flash memory type and identify capacity
uint8_t i;
//capacity & chip name
for (i = 0; i < sizeof(devType); i++)
{
if (devID == devType[i]) {
capacity = memSize[i];
name = chipName[i];
//Serial.println(devID, HEX);
//Serial.println(capacity);
//Serial.println(name);
}
}
if (capacity == 0) {
errorcode = UNKNOWNCAP; //Error code for unidentified capacity
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
while(1);
}
maxPage = capacity/PAGESIZE;
/*#ifdef RUNDIAGNOSTIC
char buffer[64];
sprintf(buffer, "Manufacturer ID: %02xh\nMemory Type: %02xh\nCapacity: %lu\nmaxPage: %d", manID, devID, capacity, maxPage);
Serial.println(buffer);
#endif*/
return true;
}
//Checks to see if pageOverflow is permitted and assists with determining next address to read/write.
//Sets the global address variable
bool SPIFlash::_addressCheck(uint32_t address, uint32_t size) {
if (capacity == 0) {
errorcode = CALLBEGIN;
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
}
for (uint32_t i = 0; i < size; i++) {
if (address + i >= maxAddress) {
if (!pageOverflow) {
errorcode = OUTOFBOUNDS;
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
return false; // At end of memory - (!pageOverflow)
}
else {
_currentAddress = 0x00;
return true; // At end of memory - (pageOverflow)
}
}
}
_currentAddress = address;
return true; // Not at end of memory if (address < capacity)
}
bool SPIFlash::_notPrevWritten(uint32_t address, uint32_t size) {
//_prep(READDATA, address, size);
_beginSPI(READDATA);
for (uint16_t i = 0; i < size; i++) {
if (_nextByte(READDATA) != 0xFF) {
_endSPI();
return false;
}
}
_endSPI();
return true;
}
#ifdef RUNDIAGNOSTIC
//Troubleshooting function. Called when #ifdef RUNDIAGNOSTIC is uncommented at the top of this file.
void SPIFlash::_troubleshoot() {
switch (errorcode) {
case SUCCESS:
#if defined (__AVR_ATmega328P__) || defined (__AVR_ATmega32U4__) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x0");
Serial.println(SUCCESS, HEX);
#else
Serial.println("Action completed successfully");
#endif
break;
case CALLBEGIN:
#if defined (__AVR_ATmega328P__) || defined (__AVR_ATmega32U4__) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x0");
Serial.println(CALLBEGIN, HEX);
#else
Serial.println("*<API key>*.begin() was not called in void setup()");
#endif
break;
case UNKNOWNCHIP:
#if defined (__AVR_ATmega328P__) || defined (__AVR_ATmega32U4__) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x0");
Serial.println(UNKNOWNCHIP, HEX);
#else
Serial.println("Unable to identify chip. Are you sure this is a Winbond Flash chip");
Serial.println("Please raise an issue at http:
#endif
break;
case UNKNOWNCAP:
#if defined (__AVR_ATmega328P__) || defined (__AVR_ATmega32U4__) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x0");
Serial.println(UNKNOWNCAP, HEX);
#else
Serial.println("Unable to identify capacity.");
Serial.println("Please raise an issue at http:
#endif
break;
case CHIPBUSY:
#if defined (__AVR_ATmega328P__) || defined (__AVR_ATmega32U4__) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x0");
Serial.println(CHIPBUSY, HEX);
#else
Serial.println("Chip is busy.");
Serial.println("Make sure all pins have been connected properly");
Serial.print("If it still doesn't work, ");
Serial.println("please raise an issue at http:
#endif
break;
case OUTOFBOUNDS:
#if defined (__AVR_ATmega328P__) || defined (__AVR_ATmega32U4__) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x0");
Serial.println(OUTOFBOUNDS, HEX);
#else
Serial.println("Page overflow has been disabled and the address called exceeds the memory");
#endif
break;
case CANTENWRITE:
#if defined (__AVR_ATmega328P__) || defined (__AVR_ATmega32U4__) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x0");
Serial.println(CANTENWRITE, HEX);
#else
Serial.println("Unable to Enable Writing to chip.");
Serial.println("Please make sure the HOLD & WRITEPROTECT pins are connected properly to VCC & GND respectively");
Serial.print("If you are still facing issues, ");
Serial.println("please raise an issue at http:
#endif
break;
case PREVWRITTEN:
#if defined (__AVR_ATmega328P__) || defined (__AVR_ATmega32U4__) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x0");
Serial.println(PREVWRITTEN, HEX);
#else
Serial.println("This sector already contains data.");
Serial.println("Please make sure the sectors being written to are erased.");
Serial.print("If you are still facing issues, ");
Serial.println("please raise an issue at http:
#endif
break;
default:
#if defined (__AVR_ATmega328P__) || defined (__AVR_ATmega32U4__) || defined (__AVR_ATtiny85__)
Serial.print("Error code: 0x");
Serial.println(UNKNOWNERROR, HEX);
#else
Serial.println("Unknown error");
Serial.println("Please raise an issue at http:
#endif
break;
}
}
#endif
// Public functions used for read, write and erase operations //
//Identifies chip and establishes parameters
void SPIFlash::begin(void) {
_chipID();
}
uint8_t SPIFlash::error() {
return errorcode;
}
//Returns capacity of chip
uint32_t SPIFlash::getCapacity() {
return capacity;
}
//Returns maximum number of pages
uint32_t SPIFlash::getMaxPage() {
return maxPage;
}
//Returns identifying name of the chip
uint16_t SPIFlash::getChipName() {
return name;
}
//Checks for and initiates the chip by requesting the Manufacturer ID which is returned as a 16 bit int
uint16_t SPIFlash::getManID() {
uint8_t b1, b2;
_getManId(&b1, &b2);
uint32_t id = b1;
id = (id << 8)|(b2 << 0);
return id;
}
//Checks for and initiates the chip by requesting JEDEC ID which is returned as a 32 bit int
uint32_t SPIFlash::getJEDECID() {
uint8_t b1, b2, b3;
_getJedecId(&b1, &b2, &b3);
uint32_t id = b1;
id = (id << 8)|(b2 << 0);
id = (id << 8)|(b3 << 0);
return id;
}
//Gets the next available address for use. Has two variants:
// A. Takes the size of the data as an argument and returns a 32-bit address
// B. Takes a three variables, the size of the data and two other variables to return a page number value & an offset into.
// All addresses in the in the sketch must be obtained via this function or not at all.
// Variant A
uint32_t SPIFlash::getAddress(uint16_t size) {
if (!_addressCheck(currentAddress, size)){
errorcode = OUTOFBOUNDS;
#ifdef RUNDIAGNOSTIC
_troubleshoot();
#endif
return false;
}
else {
uint32_t address = currentAddress;
/*Serial.print("Current Address: ");
Serial.println(currentAddress);*/
currentAddress+=size;
return address;
}
}
// Variant B
bool SPIFlash::getAddress(uint16_t size, uint16_t &page_number, uint8_t &offset) {
uint32_t address = getAddress(size);
offset = (address >> 0);
page_number = (address >> 8);
return true;
}
//Function for returning the size of the string (only to be used for the getAddress() function)
uint16_t SPIFlash::sizeofStr(String &inputStr) {
//uint16_t inStrLen = inputStr.length() + 1;
uint16_t size;
//inputStr.toCharArray(inputChar, inStrLen);
//size=(sizeof(char)*inStrLen);
size = (sizeof(char)*(inputStr.length()+1));
size+=sizeof(inputStr.length()+1/*inStrLen*/);
return size;
}
// Reads a byte of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to maxAddress
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
uint8_t SPIFlash::readByte(uint32_t address, bool fastRead) {
uint8_t data;
if (!_prep(READDATA, address, sizeof(data))) {
return false;
}
switch (fastRead) {
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
data = _nextByte(READDATA);
_endSPI();
return data;
}
// Variant B
uint8_t SPIFlash::readByte(uint16_t page_number, uint8_t offset, bool fastRead) {
uint32_t address = _getAddress(page_number, offset);
return readByte(address, fastRead);
}
// Reads a char of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to maxAddress
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
int8_t SPIFlash::readChar(uint32_t address, bool fastRead) {
int8_t data;
if (!_prep(READDATA, address, sizeof(data))) {
return false;
}
switch (fastRead) {
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
data = _nextByte(READDATA);
_endSPI();
return data;
}
// Variant B
int8_t SPIFlash::readChar(uint16_t page_number, uint8_t offset, bool fastRead) {
uint32_t address = _getAddress(page_number, offset);
return readChar(address, fastRead);
}
// Reads an array of bytes starting from a specific location in a page.// Has two variants:
// A. Takes three arguments
// 1. address --> Any address from 0 to maxAddress
// 2. data_buffer --> The array of bytes to be read from the flash memory - starting at the address indicated
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes four arguments
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data_buffer --> The array of bytes to be read from the flash memory - starting at the offset on the page indicated
// 4. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
bool SPIFlash::readByteArray(uint32_t address, uint8_t *data_buffer, uint16_t bufferSize, bool fastRead) {
if (!_prep(READDATA, address, bufferSize)) {
return false;
}
switch (fastRead) {
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
for (uint16_t a = 0; a < bufferSize; a++) {
data_buffer[a] = _nextByte(READDATA);
}
_endSPI();
return true;
}
// Variant B
bool SPIFlash::readByteArray(uint16_t page_number, uint8_t offset, uint8_t *data_buffer, uint16_t bufferSize, bool fastRead) {
uint32_t address = _getAddress(page_number, offset);
return readByteArray(address, data_buffer, bufferSize, fastRead);
}
// Reads an array of chars starting from a specific location in a page.// Has two variants:
// A. Takes three arguments
// 1. address --> Any address from 0 to maxAddress
// 2. data_buffer --> The array of bytes to be read from the flash memory - starting at the address indicated
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes four arguments
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data_buffer --> The array of bytes to be read from the flash memory - starting at the offset on the page indicated
// 4. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
bool SPIFlash::readCharArray(uint32_t address, char *data_buffer, uint16_t bufferSize, bool fastRead) {
if (!_prep(READDATA, address, bufferSize)) {
return false;
}
switch (fastRead) {
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
for (uint16_t a = 0; a < bufferSize; a++) {
data_buffer[a] = _nextByte(READDATA);
}
_endSPI();
return true;
}
// Variant B
bool SPIFlash::readCharArray(uint16_t page_number, uint8_t offset, char *data_buffer, uint16_t bufferSize, bool fastRead) {
uint32_t address = _getAddress(page_number, offset);
return readCharArray(address, data_buffer, bufferSize, fastRead);
}
// Reads an unsigned int of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to maxAddress
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
uint16_t SPIFlash::readWord(uint32_t address, bool fastRead) {
union
{
byte b[sizeof(uint16_t)];
uint16_t I;
} data;
if (!_prep(READDATA, address, sizeof(data.I))) {
return false;
}
switch (fastRead) {
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
for (uint16_t i=0; i < (sizeof(data.I)); i++) {
data.b[i] = _nextByte(READDATA);
}
_endSPI();
return data.I;
}
// Variant B
uint16_t SPIFlash::readWord(uint16_t page_number, uint8_t offset, bool fastRead) {
uint32_t address = _getAddress(page_number, offset);
return readWord(address, fastRead);
}
// Reads a signed int of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to maxAddress
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
int16_t SPIFlash::readShort(uint32_t address, bool fastRead) {
union
{
byte b[sizeof(int16_t)];
int16_t s;
} data;
if (!_prep(READDATA, address, sizeof(data.s))) {
return false;
}
switch (fastRead) {
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
for (uint16_t i=0; i < (sizeof(data.s)); i++) {
data.b[i] = _nextByte(READDATA);
}
_endSPI();
return data.s;
}
// Variant B
int16_t SPIFlash::readShort(uint16_t page_number, uint8_t offset, bool fastRead) {
uint32_t address = _getAddress(page_number, offset);
return readShort(address, fastRead);
}
// Reads an unsigned long of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to maxAddress
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
uint32_t SPIFlash::readULong(uint32_t address, bool fastRead) {
union
{
byte b[sizeof(uint32_t)];
uint32_t l;
} data;
if (!_prep(READDATA, address, sizeof(data.l))) {
return false;
}
switch (fastRead) {
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
for (uint16_t i=0; i < (sizeof(data.l)); i++) {
data.b[i] = _nextByte(READDATA);
}
_endSPI();
return data.l;
}
// Variant B
uint32_t SPIFlash::readULong(uint16_t page_number, uint8_t offset, bool fastRead) {
uint32_t address = _getAddress(page_number, offset);
return readULong(address, fastRead);
}
// Reads a signed long of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to maxAddress
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
int32_t SPIFlash::readLong(uint32_t address, bool fastRead) {
union
{
byte b[sizeof(int32_t)];
int32_t l;
} data;
if (!_prep(READDATA, address, sizeof(data.l))) {
return false;
}
switch (fastRead) {
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
for (uint16_t i=0; i < (sizeof(data.l)); i++) {
data.b[i] = _nextByte(READDATA);
}
_endSPI();
return data.l;
}
// Variant B
int32_t SPIFlash::readLong(uint16_t page_number, uint8_t offset, bool fastRead) {
uint32_t address = _getAddress(page_number, offset);
return readLong(address, fastRead);
}
// Reads a signed long of data from a specific location in a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to maxAddress
// 2. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// Variant A
float SPIFlash::readFloat(uint32_t address, bool fastRead) {
union
{
byte b[(sizeof(float))];
float f;
} data;
if (!_prep(READDATA, address, sizeof(data.f))) {
return false;
}
switch (fastRead) {
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
for (uint16_t i=0; i < (sizeof(float)); i++) {
data.b[i] = _nextByte(READDATA);
}
_endSPI();
return data.f;
}
// Variant B
float SPIFlash::readFloat(uint16_t page_number, uint8_t offset, bool fastRead) {
uint32_t address = _getAddress(page_number, offset);
return readFloat(address, fastRead);
}
// Reads a string from a specific location on a page.
// Has two variants:
// A. Takes three arguments
// 1. address --> Any address from 0 to maxAddress
// 2. outputString --> String variable to write the output to
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
// B. Takes four arguments
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. outputString --> String variable to write the output to
// 4. fastRead --> defaults to false - executes _beginFastRead() if set to true
// This function first reads a short from the address to figure out the size of the String object stored and
// then reads the String object data
// Variant A
bool SPIFlash::readStr(uint32_t address, String &outStr, bool fastRead) {
uint16_t strLen;
strLen = readShort(address);
address+=(sizeof(strLen));
/*if (!_prep(READDATA, address, (strLen + sizeof(strLen)))) {
return false;
}*/
char outputChar[strLen];
readCharArray(address, outputChar, strLen, fastRead);
outStr = String(outputChar);
return true;
}
// Variant B
bool SPIFlash::readStr(uint16_t page_number, uint8_t offset, String &outStr, bool fastRead) {
uint32_t address = _getAddress(page_number, offset);
return readStr(address, outStr, fastRead);
}
// Reads a page of data into a page buffer. Takes three arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. data_buffer --> a data buffer to read the data into (This HAS to be an array of 256 bytes)
// 3. fastRead --> defaults to false - executes _beginFastRead() if set to true
bool SPIFlash::readPage(uint16_t page_number, uint8_t *data_buffer, bool fastRead) {
uint32_t address = _getAddress(page_number);
if(!_prep(READDATA, address, PAGESIZE)) {
return false;
}
switch (fastRead) {
case false:
_beginSPI(READDATA);
break;
case true:
_beginSPI(FASTREAD);
break;
default:
break;
}
for (int a = 0; a < PAGESIZE; a++) {
data_buffer[a] = _nextByte(READDATA);
}
_endSPI();
return true;
}
// Writes a byte of data to a specific location in a page.
// Has two variants:
// A. Takes three arguments -
// 1. address --> Any address - from 0 to maxAddress
// 2. data --> One byte of data to be written to a particular location on a page
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data --> One byte of data to be written to a particular location on a page
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// Variant A
bool SPIFlash::writeByte(uint32_t address, uint8_t data, bool errorCheck) {
if(!_prep(PAGEPROG, address, sizeof(data))) {
return false;
}
_beginSPI(PAGEPROG);
_nextByte(PAGEPROG, data);
_endSPI();
switch (errorCheck) {
case true:
return _writeErrorCheck(address, data);
break;
case false:
return true;
break;
}
}
// Variant B
bool SPIFlash::writeByte(uint16_t page_number, uint8_t offset, uint8_t data, bool errorCheck) {
uint32_t address = _getAddress(page_number, offset);
return writeByte(address, data, errorCheck);
}
// Writes a char of data to a specific location in a page.
// Has two variants:
// A. Takes three arguments -
// 1. address --> Any address - from 0 to maxAddress
// 2. data --> One char of data to be written to a particular location on a page
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data --> One char of data to be written to a particular location on a page
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// Variant A
bool SPIFlash::writeChar(uint32_t address, int8_t data, bool errorCheck) {
if (!_prep(PAGEPROG, address, sizeof(data)))
return false;
_beginSPI(PAGEPROG);
_nextByte(PAGEPROG, data);
_endSPI();
if (!errorCheck) {
return true;
}
else {
return _writeErrorCheck(address, data);
}
}
// Variant B
bool SPIFlash::writeChar(uint16_t page_number, uint8_t offset, int8_t data, bool errorCheck) {
uint32_t address = _getAddress(page_number, offset);
return writeChar(address, data, errorCheck);
}
// Writes an array of bytes starting from a specific location in a page.
// Has two variants:
// A. Takes three arguments -
// 1. address --> Any address - from 0 to maxAddress
// 2. data --> An array of bytes to be written to a particular location on a page
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data --> An array of bytes to be written to a particular location on a page
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// Variant A
bool SPIFlash::writeByteArray(uint32_t address, uint8_t *data_buffer, uint16_t bufferSize, bool errorCheck) {
if (!_prep(PAGEPROG, address, bufferSize))
return false;
_beginSPI(PAGEPROG);
for (uint16_t i = 0; i < bufferSize; i++) {
_nextByte(PAGEPROG, data_buffer[i]);
}
_endSPI();
if (!errorCheck)
return true;
else
return _writeErrorCheck(address, data_buffer);
}
// Variant B
bool SPIFlash::writeByteArray(uint16_t page_number, uint8_t offset, uint8_t *data_buffer, uint16_t bufferSize, bool errorCheck) {
uint32_t address = _getAddress(page_number, offset);
return writeByteArray(address, data_buffer, bufferSize, errorCheck);
}
// Writes an array of bytes starting from a specific location in a page.
// Has two variants:
// A. Takes three arguments -
// 1. address --> Any address - from 0 to maxAddress
// 2. data --> An array of chars to be written to a particular location on a page
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data --> An array of chars to be written to a particular location on a page
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// Variant A
bool SPIFlash::writeCharArray(uint32_t address, char *data_buffer, uint16_t bufferSize, bool errorCheck) {
if (!_prep(PAGEPROG, address, bufferSize))
return false;
_beginSPI(PAGEPROG);
for (uint16_t i = 0; i < bufferSize; i++) {
_nextByte(PAGEPROG, data_buffer[i]);
}
_endSPI();
if (!errorCheck)
return true;
else
return _writeErrorCheck(address, data_buffer);
}
// Variant B
bool SPIFlash::writeCharArray(uint16_t page_number, uint8_t offset, char *data_buffer, uint16_t bufferSize, bool errorCheck) {
uint32_t address = _getAddress(page_number, offset);
return writeCharArray(address, data_buffer, bufferSize, errorCheck);
}
// Writes an unsigned int as two bytes starting from a specific location in a page.
// Has two variants:
// A. Takes three arguments -
// 1. address --> Any address - from 0 to maxAddress
// 2. data --> One unsigned int of data to be written to a particular location on a page
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data --> One unsigned int of data to be written to a particular location on a page
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// Variant A
bool SPIFlash::writeWord(uint32_t address, uint16_t data, bool errorCheck) {
if(!_prep(PAGEPROG, address, sizeof(data)))
return false;
union
{
uint8_t b[sizeof(data)];
uint16_t w;
} var;
var.w = data;
_beginSPI(PAGEPROG);
for (uint16_t j = 0; j < sizeof(data); j++) {
_nextByte(PAGEPROG, var.b[j]);
}
_endSPI();
if (!errorCheck)
return true;
else
return _writeErrorCheck(address, data);
}
// Variant B
bool SPIFlash::writeWord(uint16_t page_number, uint8_t offset, uint16_t data, bool errorCheck) {
uint32_t address = _getAddress(page_number, offset);
return writeWord(address, data, errorCheck);
}
// Writes a signed int as two bytes starting from a specific location in a page.
// Has two variants:
// A. Takes three arguments -
// 1. address --> Any address - from 0 to maxAddress
// 2. data --> One signed int of data to be written to a particular location on a page
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data --> One signed int of data to be written to a particular location on a page
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// Variant A
bool SPIFlash::writeShort(uint32_t address, int16_t data, bool errorCheck) {
if(!_prep(PAGEPROG, address, sizeof(data)))
return false;
union
{
uint8_t b[sizeof(data)];
int16_t s;
} var;
var.s = data;
_beginSPI(PAGEPROG);
for (uint16_t j = 0; j < (sizeof(data)); j++) {
_nextByte(PAGEPROG, var.b[j]);
}
_endSPI();
if (!errorCheck)
return true;
else
return _writeErrorCheck(address, data);
}
// Variant B
bool SPIFlash::writeShort(uint16_t page_number, uint8_t offset, int16_t data, bool errorCheck) {
uint32_t address = _getAddress(page_number, offset);
return writeShort(address, data, errorCheck);
}
// Writes an unsigned long as four bytes starting from a specific location in a page.
// Has two variants:
// A. Takes three arguments -
// 1. address --> Any address - from 0 to maxAddress
// 2. data --> One unsigned long of data to be written to a particular location on a page
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data --> One unsigned long of data to be written to a particular location on a page
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// Variant A
bool SPIFlash::writeULong(uint32_t address, uint32_t data, bool errorCheck) {
if(!_prep(PAGEPROG, address, sizeof(data)))
return false;
union
{
uint8_t b[sizeof(data)];
uint32_t l;
} var;
var.l = data;
_beginSPI(PAGEPROG);
for (uint16_t j = 0; j < (sizeof(data)); j++) {
_nextByte(PAGEPROG, var.b[j]);
}
_endSPI();
if (!errorCheck)
return true;
else
return _writeErrorCheck(address, data);
}
// Variant B
bool SPIFlash::writeULong(uint16_t page_number, uint8_t offset, uint32_t data, bool errorCheck) {
uint32_t address = _getAddress(page_number, offset);
return writeULong(address, data, errorCheck);
}
// Writes a signed long as four bytes starting from a specific location in a page.
// Has two variants:
// A. Takes three arguments -
// 1. address --> Any address - from 0 to maxAddress
// 2. data --> One signed long of data to be written to a particular location on a page
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data --> One signed long of data to be written to a particular location on a page
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// Variant A
bool SPIFlash::writeLong(uint32_t address, int32_t data, bool errorCheck) {
if(!_prep(PAGEPROG, address, sizeof(data)))
return false;
union
{
uint8_t b[sizeof(data)];
int32_t l;
} var;
var.l = data;
_beginSPI(PAGEPROG);
for (uint16_t j = 0; j < (sizeof(data)); j++) {
_nextByte(PAGEPROG, var.b[j]);
}
_endSPI();
if (!errorCheck)
return true;
else
return _writeErrorCheck(address, data);
}
// Variant B
bool SPIFlash::writeLong(uint16_t page_number, uint8_t offset, int32_t data, bool errorCheck) {
uint32_t address = _getAddress(page_number, offset);
return writeLong(address, data, errorCheck);
}
// Writes a float as four bytes starting from a specific location in a page.
// Has two variants:
// A. Takes three arguments -
// 1. address --> Any address - from 0 to maxAddress
// 2. data --> One float of data to be written to a particular location on a page
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. data --> One float of data to be written to a particular location on a page
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// Variant A
bool SPIFlash::writeFloat(uint32_t address, float data, bool errorCheck) {
if(!_prep(PAGEPROG, address, sizeof(data)))
return false;
union
{
uint8_t b[sizeof(data)];
float f;
} var;
var.f = data;
_beginSPI(PAGEPROG);
for (uint16_t j = 0; j < (sizeof(data)); j++) {
_nextByte(PAGEPROG, var.b[j]);
}
_endSPI();
if (!errorCheck)
return true;
else
return _writeErrorCheck(address, data);
}
// Variant B
bool SPIFlash::writeFloat(uint16_t page_number, uint8_t offset, float data, bool errorCheck) {
uint32_t address = _getAddress(page_number, offset);
return writeFloat(address, data, errorCheck);
}
// Reads a string from a specific location on a page.
// Has two variants:
// A. Takes two arguments -
// 1. address --> Any address from 0 to maxAddress
// 2. inputString --> String variable to write the data from
// 3. errorCheck --> Turned on by default. Checks for writing errors
// B. Takes four arguments -
// 1. page --> Any page number from 0 to maxPage
// 2. offset --> Any offset within the page - from 0 to 255
// 3. inputString --> String variable to write the data from
// 4. errorCheck --> Turned on by default. Checks for writing errors
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
// This function first writes the size of the string as an unsigned int to the address to figure out the size of the String object stored and
// then writes the String object data. Therefore it takes up two bytes more than the size of the String itself.
// Variant A
bool SPIFlash::writeStr(uint32_t address, String &inputStr, bool errorCheck) {
uint16_t inStrLen = inputStr.length() +1;
char inputChar[inStrLen];
union
{
uint8_t b[sizeof(inStrLen)];
uint16_t w;
}var;
var.w = inStrLen;
inputStr.toCharArray(inputChar, inStrLen);
if(!_prep(PAGEPROG, address, inStrLen))
return false;
_beginSPI(PAGEPROG);
for (uint16_t j = 0; j < sizeof(inStrLen); j++) {
_nextByte(PAGEPROG, var.b[j]);
}
for (uint16_t i = 0; i <inStrLen; i++) {
_nextByte(PAGEPROG, inputChar[i]);
}
_endSPI();
if (!errorCheck) {
return true;
}
else {
String tempStr;
readStr(address, tempStr);
return inputStr.equals(tempStr);
}
}
// Variant B
bool SPIFlash::writeStr(uint16_t page_number, uint8_t offset, String &inputStr, bool errorCheck) {
uint32_t address = _getAddress(page_number, offset);
return writeStr(address, inputStr, errorCheck);
}
// Writes a page of data from a data_buffer array. Make sure the sizeOf(uint8_t data_buffer[]) >= PAGESIZE.
// errorCheck --> Turned on by default. Checks for writing errors.
// WARNING: You can only write to previously erased memory locations (see datasheet).
// Use the eraseSector()/eraseBlock32K/eraseBlock64K commands to first clear memory (write 0xFFs)
bool SPIFlash::writePage(uint16_t page_number, const uint8_t *data_buffer, bool errorCheck) {
uint32_t address = _getAddress(page_number);
if (!_prep(PAGEPROG, address, PAGESIZE)) {
return false;
}
_beginSPI(PAGEPROG);
for (uint16_t i = 0; i < PAGESIZE; i++){
_nextByte(PAGEPROG, data_buffer[i]);
}
_endSPI();
if (!errorCheck)
return true;
else {
_beginSPI(READDATA);
for (uint16_t j = 0; j < PAGESIZE; j++){
if (data_buffer[j] != _nextByte(READDATA)) {
return false;
}
}
_endSPI();
return true;
}
}
//Erases one 4k sector. Has two variants:
// A. Takes the address as the argument and erases the sector containing the address.
// B. Takes page to be erased as the argument and erases the sector containing the page.
// The sectors are numbered 0 - 255 containing 16 pages each.
// Page 0-15 --> Sector 0; Page 16-31 --> Sector 1;......Page 4080-4095 --> Sector 255
// Variant A
bool SPIFlash::eraseSector(uint32_t address) {
if(!_notBusy()||!_writeEnable())
return false;
_beginSPI(SECTORERASE);
#ifdef __AVR_ATtiny85__
(void)xfer(address >> 16);
(void)xfer(address >> 8);
(void)xfer(0);
#else
SPI.transfer(address >> 16);
SPI.transfer(address >> 8);
SPI.transfer(NULLBYTE);
#endif
_endSPI();
if(!_notBusy(500L))
return false; //Datasheet says erasing a sector takes 400ms max
//_writeDisable(); //_writeDisable() is not required because the Write Enable Latch (WEL) flag is cleared to 0
// i.e. to write disable state upon the following conditions:
// Power-up, Write Disable, Page Program, Quad Page Program, ``Sector Erase``, Block Erase, Chip Erase, Write Status Register,
// Erase Security Register and Program Security register
return true;
}
// Variant B
bool SPIFlash::eraseSector(uint16_t page_number, uint8_t offset) {
uint32_t address = _getAddress(page_number, offset);
return eraseSector(address);
}
//Erases one 32k block. Has two variants:
// A. Takes the address as the argument and erases the block containing the address.
// B. Takes page to be erased as the argument and erases the block containing the page.
// The blocks are numbered 0 - 31 containing 128 pages each.
// Page 0-127 --> Block 0; Page 128-255 --> Block 1;......Page 3968-4095 --> Block 31
// Variant A
bool SPIFlash::eraseBlock32K(uint32_t address) {
if(!_notBusy()||!_writeEnable()) {
return false;
}
_beginSPI(BLOCK32ERASE);
#ifdef __AVR_ATtiny85__
(void)xfer(address >> 16);
(void)xfer(address >> 8);
(void)xfer(0);
#else
SPI.transfer(address >> 16);
SPI.transfer(address >> 8);
SPI.transfer(NULLBYTE);
#endif
_endSPI();
if(!_notBusy(1000L))
return false; //Datasheet says erasing a sector takes 400ms max
//_writeDisable(); //_writeDisable() is not required because the Write Enable Latch (WEL) flag is cleared to 0
// i.e. to write disable state upon the following conditions:
// Power-up, Write Disable, Page Program, Quad Page Program, Sector Erase, ``Block Erase``, Chip Erase, Write Status Register,
// Erase Security Register and Program Security register
return true;
}
// Variant B
bool SPIFlash::eraseBlock32K(uint16_t page_number, uint8_t offset) {
uint32_t address = _getAddress(page_number, offset);
return eraseBlock32K(address);
}
//Erases one 64k block. Has two variants:
// A. Takes the address as the argument and erases the block containing the address.
// B. Takes page to be erased as the argument and erases the block containing the page.
// The blocks are numbered 0 - 15 containing 256 pages each.
// Page 0-255 --> Block 0; Page 256-511 --> Block 1;......Page 3840-4095 --> Block 15
// Variant A
bool SPIFlash::eraseBlock64K(uint32_t address) {
if(!_notBusy()||!_writeEnable()) {
return false;
}
_beginSPI(BLOCK64ERASE);
#ifdef __AVR_ATtiny85__
(void)xfer(address >> 16);
(void)xfer(address >> 8);
(void)xfer(0);
#else
SPI.transfer(address >> 16);
SPI.transfer(address >> 8);
SPI.transfer(NULLBYTE);
#endif
_endSPI();
if(!_notBusy(1200L))
return false; //Datasheet says erasing a sector takes 400ms max
//_writeDisable(); //_writeDisable() is not required because the Write Enable Latch (WEL) flag is cleared to 0
// i.e. to write disable state upon the following conditions:
// Power-up, Write Disable, Page Program, Quad Page Program, Sector Erase, ``Block Erase``, Chip Erase, Write Status Register,
// Erase Security Register and Program Security register
return true;
}
// Variant B
bool SPIFlash::eraseBlock64K(uint16_t page_number, uint8_t offset) {
uint32_t address = _getAddress(page_number, offset);
return eraseBlock64K(address);
}
//Erases whole chip. Think twice before using.
bool SPIFlash::eraseChip(void) {
if(!_notBusy()||!_writeEnable())
return false;
_beginSPI(CHIPERASE);
_endSPI();
if(!_notBusy(50000L))
return false; //Datasheet says erasing chip takes 6s max
//_writeDisable(); //_writeDisable() is not required because the Write Enable Latch (WEL) flag is cleared to 0
// i.e. to write disable state upon the following conditions:
// Power-up, Write Disable, Page Program, Quad Page Program, Sector Erase, Block Erase, ``Chip Erase``, Write Status Register,
// Erase Security Register and Program Security register
return true;
}
//Suspends current Block Erase/Sector Erase/Page Program. Does not suspend chipErase().
//Page Program, Write Status Register, Erase instructions are not allowed.
//Erase suspend is only allowed during Block/Sector erase.
//Program suspend is only allowed during Page/Quad Page Program
bool SPIFlash::suspendProg(void) {
if(_notBusy() || !_noSuspend())
return false;
_beginSPI(SUSPEND);
_endSPI();
_delay_us(20);
if(!_notBusy(50) || _noSuspend()) //Max suspend Enable time according to datasheet
return false;
return true;
}
//Resumes previously suspended Block Erase/Sector Erase/Page Program.
bool SPIFlash::resumeProg(void) {
if(!_notBusy() || _noSuspend())
return false;
_beginSPI(RESUME);
_endSPI();
_delay_us(20);
if(_notBusy(10) || !_noSuspend())
return false;
return true;
}
//Puts device in low power state. Good for battery powered operations.
//Typical current consumption during power-down is 1mA with a maximum of 5mA. (Datasheet 7.4)
//In powerDown() the chip will only respond to powerUp()
bool SPIFlash::powerDown(void) {
if(!_notBusy(20))
return false;
_beginSPI(POWERDOWN);
_endSPI();
_delay_us(5); //Max powerDown enable time according to the Datasheet
uint8_t status1 = _readStat1();
uint8_t status2 = _readStat1();
status1 = _readStat1();
if (status1 != 0xFF && status2 != 0xFF) {
if (status1 == status2 || status1 == 0x00 || status2 == 0x00) {
status1 = _readStat1();
status2 = _readStat1();
}
else if (status1 != status2)
return true;
}
else if (status1 == 0xFF && status2 == 0xFF)
return true;
else if (status1 == 0x00 && status2 == 0x00)
return false;
return true;
}
//Wakes chip from low power state.
bool SPIFlash::powerUp(void) {
_beginSPI(RELEASE);
_endSPI();
_delay_us(3); //Max release enable time according to the Datasheet
if (_readStat1() == 0xFF)
return false;
return true;
} |
package eu.siacs.conversations.ui;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import eu.siacs.conversations.Config;
import eu.siacs.conversations.R;
import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.ui.adapter.ConversationAdapter;
import eu.siacs.conversations.xmpp.jid.InvalidJidException;
import eu.siacs.conversations.xmpp.jid.Jid;
public class ShareWithActivity extends XmppActivity {
private class Share {
public List<Uri> uris = new ArrayList<>();
public boolean image;
public String account;
public String contact;
public String text;
}
private Share share;
private static final int <API key> = 0x0501;
private ListView mListView;
private List<Conversation> mConversations = new ArrayList<>();
private UiCallback<Message> attachFileCallback = new UiCallback<Message>() {
@Override
public void userInputRequried(PendingIntent pi, Message object) {
// TODO Auto-generated method stub
}
@Override
public void success(Message message) {
<API key>.sendMessage(message);
}
@Override
public void error(int errorCode, Message object) {
// TODO Auto-generated method stub
}
};
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == <API key>
&& resultCode == RESULT_OK) {
share.contact = data.getStringExtra("contact");
share.account = data.getStringExtra("account");
}
if (<API key>
&& share != null
&& share.contact != null
&& share.account != null) {
share();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getActionBar() != null) {
getActionBar().<API key>(false);
getActionBar().<API key>(false);
}
setContentView(R.layout.share_with);
setTitle(getString(R.string.<API key>));
mListView = (ListView) findViewById(R.id.<API key>);
ConversationAdapter mAdapter = new ConversationAdapter(this,
this.mConversations);
mListView.setAdapter(mAdapter);
mListView.<API key>(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
share(mConversations.get(position));
}
});
this.share = new Share();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.share_with, menu);
return true;
}
@Override
public boolean <API key>(final MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add:
final Intent intent = new Intent(<API key>(), <API key>.class);
<API key>(intent, <API key>);
return true;
}
return super.<API key>(item);
}
@Override
public void onStart() {
super.onStart();
Intent intent = getIntent();
if (intent == null) {
return;
}
final String type = intent.getType();
if (Intent.ACTION_SEND.equals(intent.getAction())) {
final Uri uri = getIntent().getParcelableExtra(Intent.EXTRA_STREAM);
if (type != null && uri != null && !type.equalsIgnoreCase("text/plain")) {
this.share.uris.add(uri);
this.share.image = type.startsWith("image/") || isImage(uri);
} else {
this.share.text = getIntent().getStringExtra(Intent.EXTRA_TEXT);
}
} else if (Intent.<API key>.equals(intent.getAction())) {
this.share.image = type != null && type.startsWith("image/");
if (!this.share.image) {
return;
}
this.share.uris = intent.<API key>(Intent.EXTRA_STREAM);
}
if (<API key>) {
<API key>.<API key>(mConversations, this.share.uris.size() == 0);
}
}
protected boolean isImage(Uri uri) {
try {
String guess = URLConnection.<API key>(uri.toString());
return (guess != null && guess.startsWith("image/"));
} catch (final <API key> ignored) {
return false;
}
}
@Override
void onBackendConnected() {
if (<API key> && share != null
&& share.contact != null && share.account != null) {
share();
return;
}
<API key>.<API key>(mConversations,
this.share != null && this.share.uris.size() == 0);
}
private void share() {
Account account;
try {
account = <API key>.findAccountByJid(Jid.fromString(share.account));
} catch (final InvalidJidException e) {
account = null;
}
if (account == null) {
return;
}
final Conversation conversation;
try {
conversation = <API key>
.<API key>(account, Jid.fromString(share.contact), false);
} catch (final InvalidJidException e) {
return;
}
share(conversation);
}
private void share(final Conversation conversation) {
if (share.uris.size() != 0) {
OnPresenceSelected callback = new OnPresenceSelected() {
@Override
public void onPresenceSelected() {
if (share.image) {
Toast.makeText(<API key>(),
getText(R.string.preparing_image),
Toast.LENGTH_LONG).show();
for (Iterator<Uri> i = share.uris.iterator(); i.hasNext(); i.remove()) {
ShareWithActivity.this.<API key>
.<API key>(conversation, i.next(),
attachFileCallback);
}
} else {
Toast.makeText(<API key>(),
getText(R.string.preparing_file),
Toast.LENGTH_LONG).show();
ShareWithActivity.this.<API key>
.<API key>(conversation, share.uris.get(0),
attachFileCallback);
}
<API key>(conversation, null, true);
finish();
}
};
if (conversation.getAccount().httpUploadAvailable()) {
callback.onPresenceSelected();
} else {
selectPresence(conversation, callback);
}
} else {
<API key>(conversation, this.share.text, true);
finish();
}
}
} |
# -*- coding: utf-8 -*-
# System modules
import os
import logging
import unittest
import json
from functools import wraps
# External modules
# Internal modules
from .test_data import *
# get a logger
logger = logging.getLogger(__name__)
all tests should import this
# basic test class with utilities
class BasicTest(unittest.TestCase):
Properties
@property
def logger(self):
""" the logging.Logger used for logging.
Defaults to logging.getLogger(__name__).
"""
try: # try to return the internal property
return self._logger
except AttributeError: # didn't work
return logging.getLogger(__name__) # return default logger
@logger.setter
def logger(self, logger):
assert isinstance(logger, logging.Logger), \
"logger property has to be a logging.Logger"
self._logger = logger
# test decorator
# decorate every test method with this
# the test name will be printed in INFO context before and after the test
def testname(name="unnamed"):
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
logger.info("
res = f(*args, **kwargs)
logger.info("
return res
return wrapped
return decorator
# read json from a filename
def read_json_from_file(filename):
"""
read json from a file given then filename
args:
filename (str): The path to the file to read
returns:
dict, empty dict if error occured during read
"""
try: # open and read, return result
with open(filename, "r") as f:
return json.load(f)
except: # didn't work, return empty dict
return {}
# get all subclasses of a given class
def all_subclasses(cls):
subclasses = set()
for subclass in cls.__subclasses__():
subclasses.add(subclass)
subclasses.update(all_subclasses(subclass))
return subclasses |
/*actions.h*/
void autobaudstart(void);
void clear_writeprotect(void);
void set_writeprotect(void);
void clear_readprotect(void);
void set_readprotect(void);
void globalerase_flash(void);
void pageserase_flash(void);
void program_memory(void);
void read_memory(void);
void get_commands(void);
void get_version(void);
void get_id(void);
void go_jump(void);
void setdtr(void);
void clrdtr(void);
void setrts(void);
void clrrts(void);
void targopts_init(void);
void testfunction(void); |
#!/bin/bash
printf "#include \"weak.h\"\n\n// DO NOT EDIT MANUALLY: Generated from script.\n\nconst char *version = \"%s\";\n" $(git describe) > version.c |
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
# This program is free software: you can redistribute it and/or modify
# published by the Free Software Foundation.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import os
import stat
from ._base import FileBase
class Script(FileBase):
def __init__(
self,
source,
source_dir,
source_tag=None,
source_commit=None,
source_branch=None,
source_depth=None,
source_checksum=None,
source_submodules=None,
):
super().__init__(
source,
source_dir,
source_tag,
source_commit,
source_branch,
source_depth,
source_checksum,
source_submodules,
)
def download(self, filepath: str = None) -> str:
filepath = super().download(filepath=filepath)
st = os.stat(self.file)
os.chmod(self.file, st.st_mode | stat.S_IEXEC)
return filepath |
const Ava = require('ava')
const Sinon = require('sinon')
const { getCard } = require('../deck')
const Junkyard = require('../junkyard')
const { find } = require('../util')
Ava.test('should steal health from a player and give to another', (t) => {
const announceCallback = Sinon.spy()
const game = new Junkyard('player1', 'Jay', announceCallback)
game.addPlayer('player2', 'Kevin')
game.start()
const [player1, player2] = game.players
const siphon = getCard('siphon')
player1.hp = 5
player1.hand.push(siphon)
game.play(player1, siphon)
game.pass(player2)
t.is(player1.hp, 6)
t.is(player2.hp, player2.maxHp - 1)
t.is(player1.hand.length, player1.maxHand)
t.is(game.discardPile.length, 1)
t.truthy(find(game.discardPile, siphon))
})
Ava.test('should not give a player more than their max HP', (t) => {
const announceCallback = Sinon.spy()
const game = new Junkyard('player1', 'Jay', announceCallback)
game.addPlayer('player2', 'Kevin')
game.start()
const [player1, player2] = game.players
const siphon = getCard('siphon')
player1.hp = player1.maxHp + 5
player1.hand.push(siphon)
game.play(player1, siphon)
game.pass(player2)
t.is(player1.hp, player1.maxHp + 5)
t.is(player2.hp, player2.maxHp - 1)
t.is(player1.hand.length, player1.maxHand)
t.is(game.discardPile.length, 1)
t.truthy(find(game.discardPile, siphon))
})
Ava.test('should have a conditional weight', (t) => {
const game = new Junkyard('player1', 'Jay')
game.addPlayer('player2', 'Kevin')
game.start()
const [player1, player2] = game.players
const siphon = getCard('siphon')
player1.hand = [siphon]
let plays = siphon.validPlays(player1, player2, game)
t.true(Array.isArray(plays))
t.truthy(plays.length)
plays.forEach((play) => {
t.true(Array.isArray(play.cards))
t.truthy(play.cards.length)
t.is(typeof play.weight, 'number')
t.is(play.weight, 2)
})
player2.conditionCards.push(getCard('deflector'))
plays = siphon.validPlays(player1, player2, game)
plays.forEach((play) => {
t.is(play.weight, 5)
})
}) |
(function(){var __modFun = function(__require){ __modFun = undefined;
var __execute = function(promiseland, extra){ __execute = undefined;
if (promiseland._hasModule({ hashStr: "<API key>" })){ return promiseland._getModule("<API key>"); };
var PL$1 = (function(){
"use strict";
;
;
var PL$2/*dummy*/ = {
"newNext": (function(){
;
;}),
"newPrev": (function(){
;
;}),
"fun": (function(){
;
;})
};
;
return (function(PL$3/*base*/, PL$4/*property*/){
;
var PL$5/*orig*/ = PL$3/*base*/[PL$4/*property*/];
;
var PL$6/*last*/;
;
var PL$7/*setFun*/ = (function(PL$8/*parFun*/){
;
PL$3/*base*/[PL$4/*property*/] = PL$8/*parFun*/;
;});
;
var PL$9/*first*/ = (function(){
;
return {
"newNext": (function(PL$10){
;
if(PL$10){
var PL$11/*nextFun*/ = PL$10/*n*/["fun"];
;
PL$7/*setFun*/((function(){
var PL$12/*arguments*/ = arguments;
;
PL$5/*orig*/["apply"](PL$3/*base*/, PL$12/*arguments*/);
PL$11/*nextFun*/["apply"](null, PL$12/*arguments*/);
;}));
}else{
PL$7/*setFun*/(PL$5/*orig*/);
PL$6/*last*/ = PL$9/*first*/;
};
;
;}),
"newPrev": (function(){
;
;})
};
;})();
;
PL$6/*last*/ = PL$9/*first*/;
return (function(PL$13/*conFun*/, PL$14/*newBase*/){
;
var PL$15/*next*/ = PL$2/*dummy*/;
;
var PL$11/*nextFun*/ = PL$15/*next*/["fun"];
;
var PL$16/*prev*/ = PL$6/*last*/;
;
var PL$17 = {
"newNext": (function(PL$10){
;
if(PL$10){
PL$15/*next*/ = PL$10/*n*/;
}else{
PL$15/*next*/ = PL$2/*dummy*/;
PL$6/*last*/ = PL$17/*s*/;
};
;
PL$11/*nextFun*/ = PL$15/*next*/["fun"];
;}),
"newPrev": (function(PL$18){
;
PL$16/*prev*/ = PL$18/*p*/;
;}),
"fun": (PL$14/*newBase*/ ? (function(){
var PL$12/*arguments*/ = arguments;
;
PL$13/*conFun*/["apply"](PL$14/*newBase*/, PL$12/*arguments*/);
PL$11/*nextFun*/["apply"](null, PL$12/*arguments*/);
;}) : (function(){
var PL$12/*arguments*/ = arguments;
;
PL$13/*conFun*/["apply"](null, PL$12/*arguments*/);
PL$11/*nextFun*/["apply"](null, PL$12/*arguments*/);
;}))
};
;
PL$6/*last*/["newNext"](PL$17/*s*/);
PL$6/*last*/ = PL$17/*s*/;
return (function(){
;
PL$16/*prev*/["newNext"](PL$15/*next*/);
PL$15/*next*/["newPrev"](PL$16/*prev*/);
PL$16/*prev*/ = PL$2/*dummy*/;
PL$15/*next*/ = PL$2/*dummy*/;
;});
;});
;});
;})();
;return PL$1;
}; return function(){ return __execute.apply(null, arguments); }; };
if (typeof exports == "object" && typeof module == "object"){ // CommonJS
module.exports = __modFun(function(modulesAr, callback, errBack){
// the require function for CommonJs
var args = [];
try{
var i = 0;
var l = modulesAr.length;
for (i; i < l; ++i){
args.push(require(modulesAr[i]));
};
}catch(e){
errBack(e);
return;
};
callback.apply(callback, args);
});
}else if (typeof define == "function" && define.amd){ // AMD
define("promiseland/modules/Chainable", ["require"], __modFun);
}else{ // Plain browser env
__modFun(function(){ throw { msg: "require not possible in non loader mode" }; });
};
})(); |
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc (1.8.0_152) on Wed Dec 20 15:14:52 CET 2017 -->
<title>UserService</title>
<meta name="date" content="2017-12-20">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<script type="text/javascript" src="../script.js"></script>
</head>
<body>
<script type="text/javascript"><!
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="UserService";
}
}
catch(err) {
}
var methods = {"i0":9,"i1":9,"i2":9,"i3":9,"i4":9};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar.top">
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/UserService.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../services/StockService.html" title="class in services"><span class="typeNameLink">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../index.html?services/UserService.html" target="_top">Frames</a></li>
<li><a href="UserService.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
</a></div>
<div class="header">
<div class="subTitle">services</div>
<h2 title="Class UserService" class="title">Class UserService</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>services.UserService</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">UserService</span>
extends java.lang.Object</pre>
<div class="block">Beschreibung: Modelclass for user administration</div>
<dl>
<dt><span class="simpleTagLabel">Author:</span></dt>
<dd>Ansprechpartner Fabian Meise</dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../services/UserService.html#UserService--">UserService</a></span>()</code> </td>
</tr>
</table>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method.summary">
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../services/UserService.html#AddUser-classes.User-">AddUser</a></span>(<a href="../classes/User.html" title="class in classes">User</a> user)</code>
<div class="block">Füge neuen Nutzer hinzu</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>static <a href="../classes/User.html" title="class in classes">User</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../services/UserService.html#GetUser-java.lang.String-">GetUser</a></span>(java.lang.String pattern)</code>
<div class="block">Erhalte einen Nutzer anhand des Namens</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>static java.util.ArrayList<<a href="../classes/User.html" title="class in classes">User</a>></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../services/UserService.html#GetUsers-java.lang.String-int-">GetUsers</a></span>(java.lang.String pattern,
int utid)</code>
<div class="block">Erhalte alle Nutzer anhand des Loginnamens</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../services/UserService.html#UpdateUser-classes.User-">UpdateUser</a></span>(<a href="../classes/User.html" title="class in classes">User</a> user)</code>
<div class="block">Aktualisere Nutzerdaten</div>
</td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../services/UserService.html#<API key>.User-int-">UpdateUserRights</a></span>(<a href="../classes/User.html" title="class in classes">User</a> user,
int rightnum)</code>
<div class="block">Aktualisere Nutzerrechte</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
</a>
<h3>Constructor Detail</h3>
<a name="UserService
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>UserService</h4>
<pre>public UserService()</pre>
</li>
</ul>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method.detail">
</a>
<h3>Method Detail</h3>
<a name="AddUser-classes.User-">
</a>
<ul class="blockList">
<li class="blockList">
<h4>AddUser</h4>
<pre>public static int AddUser(<a href="../classes/User.html" title="class in classes">User</a> user)</pre>
<div class="block">Füge neuen Nutzer hinzu</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>user</code> - hinzuzufügender Nutzer</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>-1 bei Fehler anosnten id des hinzufügten Datensatzes</dd>
</dl>
</li>
</ul>
<a name="GetUsers-java.lang.String-int-">
</a>
<ul class="blockList">
<li class="blockList">
<h4>GetUsers</h4>
<pre>public static java.util.ArrayList<<a href="../classes/User.html" title="class in classes">User</a>> GetUsers(java.lang.String pattern,
int utid)
throws java.sql.SQLException,
java.io.IOException</pre>
<div class="block">Erhalte alle Nutzer anhand des Loginnamens</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>pattern</code> - Suchwert</dd>
<dd><code>utid</code> - Nutzertyp</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>ArrayList der zutreffenden Nutzer</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.sql.SQLException</code></dd>
<dd><code>java.io.IOException</code></dd>
</dl>
</li>
</ul>
<a name="GetUser-java.lang.String-">
</a>
<ul class="blockList">
<li class="blockList">
<h4>GetUser</h4>
<pre>public static <a href="../classes/User.html" title="class in classes">User</a> GetUser(java.lang.String pattern)
throws java.sql.SQLException,
java.io.IOException</pre>
<div class="block">Erhalte einen Nutzer anhand des Namens</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>pattern</code> - Suchwert</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>spezifischer Nutzer</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.sql.SQLException</code></dd>
<dd><code>java.io.IOException</code></dd>
</dl>
</li>
</ul>
<a name="UpdateUser-classes.User-">
</a>
<ul class="blockList">
<li class="blockList">
<h4>UpdateUser</h4>
<pre>public static void UpdateUser(<a href="../classes/User.html" title="class in classes">User</a> user)</pre>
<div class="block">Aktualisere Nutzerdaten</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>zu</code> - aktualierender Nutzer</dd>
</dl>
</li>
</ul>
<a name="<API key>.User-int-">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>UpdateUserRights</h4>
<pre>public static void UpdateUserRights(<a href="../classes/User.html" title="class in classes">User</a> user,
int rightnum)</pre>
<div class="block">Aktualisere Nutzerrechte</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>user</code> - zu aktualisierender Nutzer</dd>
<dd><code>rightnum</code> - neues Nutzerrecht</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="bottomNav"><a name="navbar.bottom">
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/UserService.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../services/StockService.html" title="class in services"><span class="typeNameLink">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../index.html?services/UserService.html" target="_top">Frames</a></li>
<li><a href="UserService.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
</a></div>
</body>
</html> |
package com.rivetlogic.tipday.panel.application.list;
//import com.rivetlogic.tipday.panel.constants.<API key>;
import com.rivetlogic.tipday.panel.constants.<API key>;
import com.liferay.application.list.BasePanelApp;
import com.liferay.application.list.PanelApp;
import com.liferay.portal.kernel.model.Portlet;
import com.liferay.application.list.constants.PanelCategoryKeys;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
/**
* @author alejandrosoto
*/
@Component(
immediate = true,
property = {
"panel.app.order:Integer=100",
"panel.category.key=" + PanelCategoryKeys.<API key>
},
service = PanelApp.class
)
public class TipDayPanelPanelApp extends BasePanelApp {
@Override
public String getPortletId() {
return <API key>.TipDayPanel;
}
@Override
@Reference(
target = "(javax.portlet.name=" + <API key>.TipDayPanel + ")",
unbind = "-"
)
public void setPortlet(Portlet portlet) {
super.setPortlet(portlet);
}
} |
#include "master/master.h"
/**
* Distribute common input data among all workers.
*
* params A structure holding all parameters needed for calculation;
* comm the communicator used to communicate with the workers.-
*
*/
static void
<API key> (Parameters *params,
MPI_Comm comm)
{
// broadcast the common parameters structure
MPI_Bcast (params,
sizeof (Parameters),
MPI_BYTE,
<API key>,
comm);
}
/**
* Sends transmitter input data to the specified worker.
*
*
* params A structure holding all parameters needed for calculation;
* tx_params a structure holding <API key> parameters;
* comm the communicator used to communicate with the worker;
* worker_rank the target worker.-
*
*/
static void
send_tx_data (Parameters *params,
Tx_parameters *tx_params,
MPI_Comm comm,
int worker_rank)
{
// MPI data type for the radius-calculation area of this transmitter
MPI_Datatype Radius_area;
MPI_Type_vector (tx_params->nrows,
tx_params->ncols,
params->ncols,
MPI_DOUBLE,
&Radius_area);
MPI_Type_commit (&Radius_area);
// send the <API key> parameters to this worker
MPI_Send (tx_params,
sizeof (Tx_parameters),
MPI_BYTE,
worker_rank,
1,
comm);
// send DEM data to worker
MPI_Send (&(params->m_dem[tx_params->map_north_idx][tx_params->map_west_idx]),
1,
Radius_area,
worker_rank,
1,
comm);
// send clutter data to worker
MPI_Send (&(params->m_clut[tx_params->map_north_idx][tx_params->map_west_idx]),
1,
Radius_area,
worker_rank,
1,
comm);
// also send the field measurements matrix if in optimization mode
if (params->use_opt)
{
MPI_Send (&(params->m_field_meas[tx_params->map_north_idx][tx_params->map_west_idx]),
1,
Radius_area,
worker_rank,
1,
comm);
}
}
/**
* Receives the path-loss results of one transmitter from a worker process.
*
* params a structure holding configuration parameters which are
* common to all transmitters;
* worker_rank rank of the worker sending the data;
* tx_name name of the transmitter for which the results are being
* received;
* comm the MPI communicator to use.-
*
*/
static void
receive_tx_results (Parameters *params,
const int worker_rank,
const char *tx_name,
MPI_Comm *comm)
{
MPI_Status status;
Tx_parameters *tx_params = params->tx_params;
// look for the correct transmitter
int tx_id;
for (tx_id = 0; tx_id < params->ntx; tx_id ++)
{
if (strncmp (tx_name, tx_params[tx_id].tx_name, strlen (tx_name)) == 0)
break;
}
// the transmitter is always found
assert (tx_id < params->ntx);
// the received results will be saved here
double *rcv_results = (double *) calloc (sizeof (double),
tx_params[tx_id].nrows *
tx_params[tx_id].ncols);
// receive the <API key> results
MPI_Recv (rcv_results,
tx_params[tx_id].nrows * tx_params[tx_id].ncols,
MPI_DOUBLE,
worker_rank,
<API key>,
*comm,
&status);
if (status.MPI_ERROR)
{
fprintf (stderr,
"*** ERROR: Transmitter parameters incorrectly received\n");
fflush (stderr);
exit (1);
}
else
{
// save the received results on the corresponding
// location of the transmitter
int r_work, c_work;
/*
// DEBUG only!
//
fprintf (stdout,
"-- Rank %d (%s) -- Map extent (N, W)\t(%.2f,%.2f)\n",
worker_rank,
tx_name,
tx_params[tx_id].map_north,
tx_params[tx_id].map_west);*/
for (r_work = 0; r_work < tx_params[tx_id].nrows; r_work ++)
{
int r_mast = r_work + tx_params[tx_id].map_north_idx;
for (c_work = 0; c_work < tx_params[tx_id].ncols; c_work ++)
{
int c_mast = c_work + tx_params[tx_id].map_west_idx;
int elem_id = r_work * tx_params[tx_id].ncols + c_work;
// best server aggregation
if (!isnan (rcv_results[elem_id]))
{
double signal_level = tx_params[tx_id].tx_power;
signal_level -= rcv_results[elem_id];
if (isnan (params->m_loss[r_mast][c_mast]))
params->m_loss[r_mast][c_mast] = signal_level;
else
{
if (signal_level > params->m_loss[r_mast][c_mast])
params->m_loss[r_mast][c_mast] = signal_level;
}
}
/*
// DEBUG only!
//
float east_coord = tx_params[tx_id].map_west + c_work * params->map_ew_res;
float north_coord = tx_params[tx_id].map_north - r_work * params->map_ns_res;
float rcv_signal = (float) rcv_results[elem_id];
if ((!isnan (rcv_signal)) && (rcv_signal != params->fcell_null_value))
fprintf (stdout, "%.2f|%.2f|%.5f\n", east_coord,
north_coord,
rcv_signal);*/
}
}
}
free (rcv_results);
}
/**
* Initializes the coverage calculation by reading the configuration
* parameters in the INI file passed as argument.
* This function uses the 'params' parameter to save its results.-
*
* ini_file Pointer to the stream object containing the INI file;
* tx_section name of the section containing <API key> parameters;
* params a structure holding configuration parameters which are common
* to all transmitters;
* tx_params the output parameter: a structure holding <API key>
* configuration parameters needed for calculation.-
*
*/
static void
<API key> (FILE *ini_file,
const char *tx_section,
Parameters *params,
Tx_parameters *tx_params)
{
int errno;
// parse the INI file containing the transmitter's configuration values
rewind (ini_file);
errno = ini_parse_file (ini_file,
tx_params_handler,
tx_params,
tx_section);
if (errno < 0)
G_fatal_error ("Can't parse INI memory buffer\n");
// round the Tx coordinates to the map resolution
tx_params->tx_north_coord = (int) (tx_params->tx_north_coord / params->map_ns_res);
tx_params->tx_north_coord *= (int) params->map_ns_res;
tx_params->tx_east_coord = (int) (tx_params->tx_east_coord / params->map_ew_res);
tx_params->tx_east_coord *= (int) params->map_ew_res;
// calculate the subregion (within the area) where this transmitter is
// located, taking into account its location and the calculation radius
double radius_in_meters = params->radius * 1000;
int radius_in_pixels = (int) (radius_in_meters / params->map_ew_res);
tx_params->nrows = 2 * radius_in_pixels;
tx_params->ncols = 2 * radius_in_pixels;
tx_params->map_north = tx_params->tx_north_coord + radius_in_meters;
tx_params->map_east = tx_params->tx_east_coord + radius_in_meters;
tx_params->map_south = tx_params->tx_north_coord - radius_in_meters;
tx_params->map_west = tx_params->tx_east_coord - radius_in_meters;
tx_params->map_north_idx = (int) ((params->map_north - tx_params->map_north) /
params->map_ns_res);
tx_params->map_east_idx = tx_params->map_west_idx + tx_params->ncols;
tx_params->map_south_idx = tx_params->map_north_idx + tx_params->nrows;
tx_params->map_west_idx = (int) ((tx_params->map_west - params->map_west) /
params->map_ew_res);
tx_params->tx_north_coord_idx = radius_in_pixels;
tx_params->tx_east_coord_idx = radius_in_pixels;
// initialize the pointers within the transmitter structure
tx_params->diagram = NULL;
tx_params->m_dem = params->m_dem;
tx_params->m_dem_dev = NULL;
tx_params->m_clut = params->m_clut;
tx_params->m_clut_dev = NULL;
tx_params->m_field_meas = NULL;
tx_params->m_field_meas_dev = NULL;
tx_params->field_meas_count = 0;
tx_params->m_loss = params->m_loss;
tx_params->m_loss_dev = NULL;
tx_params->m_antenna_loss = NULL;
tx_params->m_antenna_loss_dev = NULL;
tx_params->m_radio_zone = NULL;
tx_params->m_radio_zone_dev = NULL;
tx_params->m_obst_height = NULL;
tx_params->m_obst_height_dev = NULL;
tx_params->m_obst_dist = NULL;
tx_params->m_obst_dist_dev = NULL;
tx_params->m_obst_offset = NULL;
tx_params->v_partial_sum = NULL;
tx_params->v_partial_sum_dev = NULL;
tx_params->v_clutter_loss_dev = NULL;
tx_params->ocl_obj = NULL;
}
/**
* Splits the comma-separated list of INI sections received.
* This function writes its output in the last parameter, returning the
* number of sections found.
*
* tx_section_list The comma-separated string to be splitted;
* tx_sections an array of strings containing each of the sections.-
*
*/
static int
split_sections (char *tx_section_list,
char *tx_sections [])
{
int ret_value = 0;
char *list_ptr;
list_ptr = &(tx_section_list[0]);
while (list_ptr != NULL)
{
char *found;
// look for a comma
found = strchr (list_ptr, ',');
// ignore possible white spaces
while (isspace (*list_ptr))
list_ptr ++;
// section name found
tx_sections[ret_value ++] = list_ptr;
// move to the first character after the comma
list_ptr = found + 1;
// smash the comma found with the end-string character
if (found != NULL)
*found = '\0';
else
break;
}
return ret_value;
}
/**
* Calculates the coverage prediction of several transmitters over MPI.
*
* params a structure holding all parameters needed for calculation;
* nworkers the number of available workers within the group;
* worker_comm the MPI communicator, to which the workers are connected;
*
*/
static void
coverage_mpi (Parameters *params,
const int nworkers,
MPI_Comm *worker_comm)
{
MPI_Status status;
char buff [_CHAR_BUFFER_SIZE_];
// start <API key> loop
int worker_rank;
int tx_count = params->ntx;
int running_workers = nworkers;
while (running_workers > 0)
{
MPI_Recv (&buff,
_CHAR_BUFFER_SIZE_,
MPI_BYTE,
MPI_ANY_SOURCE,
MPI_ANY_TAG,
*worker_comm,
&status);
worker_rank = status.MPI_SOURCE;
#ifdef <API key>
// previous result dump finished
measure_time_id (NULL,
worker_rank);
// async messaging for <API key> support
measure_time_id ("Async message",
worker_rank);
#endif
switch (status.MPI_TAG)
{
case (<API key>):
// send calculation data, if we still have transmitters
if (tx_count > 0)
{
// tell the worker to keep working
MPI_Send (NULL,
0,
MPI_BYTE,
worker_rank,
<API key>,
*worker_comm);
#ifdef <API key>
// async messaging finished
measure_time_id (NULL,
worker_rank);
// start transmitter-data send
measure_time_id ("Transmitter data send",
worker_rank);
#endif
// starting transmitter-data send
send_tx_data (params,
&(params->tx_params[-- tx_count]),
*worker_comm,
worker_rank);
#ifdef <API key>
// transmitter-data send finished
measure_time_id (NULL,
worker_rank);
// start coverage calculation
measure_time_id ("Coverage calculation",
worker_rank);
#endif
}
else
{
// send the shutdown order to this worker
MPI_Send (NULL,
0,
MPI_BYTE,
worker_rank,
<API key>,
*worker_comm);
running_workers
#ifdef <API key>
// async messaging finished
measure_time_id (NULL,
worker_rank);
// coverage calculation and result dump finished
measure_time_id (NULL,
worker_rank);
#endif
}
break;
case (<API key>):
#ifdef <API key>
// coverage calculation finished,
measure_time_id (NULL,
worker_rank);
// start result dump
measure_time_id ("Result dump",
worker_rank);
#endif
receive_tx_results (params,
worker_rank,
buff,
worker_comm);
break;
default:
fprintf (stderr,
"*** WARNING: Unknown message from %d. worker\n",
worker_rank);
}
}
// output the coverage data that has been already aggregated
int r, c;
fprintf (stderr,
"*** WARNING: the following data is valid only in the case when workers send the\n");
fprintf (stderr,
"\tintermediate results back to the master; otherwise external DB\n");
fprintf (stderr,
"\taggregation is needed for the coverage to be valid\n");
for (r = 0; r < params->nrows; r ++)
{
for (c = 0; c < params->ncols; c ++)
{
float east_coord = params->map_west + c * params->map_ew_res;
float north_coord = params->map_north - r * params->map_ns_res;
float rcv_signal = (float) params->m_loss[r][c];
if ((!isnan (rcv_signal)) && (rcv_signal != params->fcell_null_value) && (rcv_signal != 0))
fprintf (stdout, "%.2f|%.2f|%.5f\n", east_coord,
north_coord,
rcv_signal);
}
}
}
/**
* Optimizes the clutter-category losses using differential evolution on
* the master process and evaluating the objective function on the workers.
*
* params a structure holding all parameters needed for calculation;
* nworkers the number of available workers within the group;
* worker_comm the MPI communicator, to which the workers are connected;
*
*/
static void
optimize_mpi (Parameters *params,
const int nworkers,
MPI_Comm *worker_comm)
{
MPI_Status status;
char buff [_CHAR_BUFFER_SIZE_];
// start coverage-processing loop
int worker_rank;
int tx_count = params->ntx;
int running_workers = nworkers;
while (running_workers > 0)
{
MPI_Recv (&buff,
0,
MPI_BYTE,
MPI_ANY_SOURCE,
MPI_ANY_TAG,
*worker_comm,
&status);
worker_rank = status.MPI_SOURCE;
switch (status.MPI_TAG)
{
case (<API key>):
// send transmitter data, before starting the optimization loop
if (tx_count > 0)
{
// tell the worker to keep working
MPI_Send (NULL,
0,
MPI_BYTE,
worker_rank,
<API key>,
*worker_comm);
#ifdef <API key>
measure_time_id ("Load field measurements",
worker_rank);
#endif
// allocate a matrix for loading the field measurements
if (params->m_field_meas == NULL)
params->m_field_meas = <API key> (params->nrows,
params->ncols,
params->m_field_meas);
// load the measurements from a raster map
<API key> (params->tx_params[-- tx_count].field_meas_map,
params->m_field_meas);
#ifdef <API key>
measure_time_id (NULL,
worker_rank);
measure_time_id ("Transmitter data send",
worker_rank);
#endif
// starting transmitter-data send
send_tx_data (params,
&(params->tx_params[tx_count]),
*worker_comm,
worker_rank);
#ifdef <API key>
// transmitter-data send finished,
measure_time_id (NULL,
worker_rank);
#endif
// clear the field-measurement matrix to
// avoid data clashing with the next transmitter
if (params->m_field_meas != NULL)
{
free (params->m_field_meas[0]);
free (params->m_field_meas);
params->m_field_meas = NULL;
}
// reduce the number of transmitter-data still to be sent
running_workers
}
break;
default:
fprintf (stderr,
"*** WARNING: Unknown message from worker with rank [%d]\n",
worker_rank);
}
}
// optimize locally on the workers or together, evaluating on the master?
if (params->use_master_opt)
{
fprintf (stdout,
"*** INFO: All transmitter data sent. Starting master optimization ...\n");
optimize_on_master (params,
params->tx_params,
worker_comm);
}
else if (params->use_opt)
{
fprintf (stdout,
"*** INFO: All transmitter data sent. Starting local optimization on the workers ...\n");
}
}
/**
* Initializes the coverage calculation by reading the configuration
* parameters in the [Common] section of the INI file passed as argument.
* This function returns a pointer to the newly created parameters structure.
*
* ini_file Pointer to the stream containing the configuration read
* from the INI file;
* tx_sections_list the names of the sections containing <API key>
* configuration;
* params the output parameter, into which everything is saved.-
*
*/
void
init_coverage (FILE *ini_file,
char *tx_sections_list,
Parameters *params)
{
int i, errno;
// initialize matrix pointers inside the Parameters structure
params->m_dem = NULL;
params->m_clut = NULL;
params->m_loss = NULL;
params->m_field_meas = NULL;
// initialize all clutter categories to zero (0)
params-><API key> = 0;
for (i = 0; i < _CHAR_BUFFER_SIZE_; i ++)
params->clutter_loss[i] = 0;
// parse the INI file containing the common configuration values
rewind (ini_file);
errno = ini_parse_file (ini_file,
<API key>,
params,
NULL);
if (errno < 0)
G_fatal_error ("Can't parse INI memory buffer\n");
// mapset names are kept here
char *mapset = (char *) calloc (_CHAR_BUFFER_SIZE_, sizeof (char));
char *mapset2 = (char *) calloc (_CHAR_BUFFER_SIZE_, sizeof (char));
int row, col;
int infd, infd2; // file descriptors
// returns NULL if the map was not found in any mapset
mapset = G_find_cell2 (params->dem_map, mapset);
if (mapset == NULL)
G_fatal_error("Raster map <%s> not found", params->dem_map);
mapset2 = G_find_cell2 (params->clutter_map, mapset2);
if (mapset2 == NULL)
G_fatal_error("Raster map <%s> not found", params->clutter_map);
// returns a negative value if the map cannot be opened
infd = G_open_cell_old (params->dem_map, mapset);
if (infd < 0)
G_fatal_error("Unable to open raster map <%s>", params->dem_map);
infd2 = G_open_cell_old (params->clutter_map, mapset2);
if (infd2 < 0)
G_fatal_error("Unable to open raster map <%s>", params->clutter_map);
// read metadata of each map, making sure they match
struct Cell_head *metadata = (struct Cell_head *) malloc (sizeof (struct Cell_head));
struct Cell_head *window = (struct Cell_head *) malloc (sizeof (struct Cell_head));
// DEM metadata
errno = G_get_cellhd (params->dem_map,
mapset,
metadata);
if (errno == 0)
{
// NULL value in DEM maps
G_set_f_null_value ((FCELL *) &(params->fcell_null_value), 1);
if (metadata->format != sizeof (params->fcell_null_value) - 1)
{
fprintf (stderr,
"*** WARNING: DEM map-cell format (%d) is not recognized.\n",
metadata->format);
fprintf (stderr,
"\tMake sure it is of type FCELL to avoid undefined behaviour!\n");
}
// get map metadata
params->map_east = metadata->east;
params->map_west = metadata->west;
params->map_north = metadata->north;
params->map_south = metadata->south;
params->map_ew_res = metadata->ew_res;
params->map_ns_res = metadata->ns_res;
}
else
G_fatal_error ("Unable to open raster map <%s>",
params->dem_map);
// clutter metadata
errno = G_get_cellhd (params->clutter_map,
mapset2,
metadata);
if (errno == 0)
{
// NULL value in clutter maps
G_set_c_null_value ((CELL *) &(params->cell_null_value), 1);
if (metadata->format != sizeof (params->cell_null_value) - 1)
{
fprintf (stderr,
"*** WARNING: Clutter map-cell format (%d) is not recognized.\n",
metadata->format);
fprintf (stderr,
"\tMake sure it is of type CELL to avoid undefined behaviour!\n");
}
if (!(params->map_east >= metadata->east &&
params->map_west <= metadata->west &&
params->map_north >= metadata->north &&
params->map_south <= metadata->south &&
params->map_ew_res == metadata->ew_res &&
params->map_ns_res == metadata->ns_res))
G_fatal_error ("Map metadata of input maps do not match.");
}
else
G_fatal_error ("Unable to open raster map <%s>", params->clutter_map);
// check that the current active window matches the loaded data
G_get_window (window);
if (params->map_east != window->east ||
params->map_west != window->west ||
params->map_north != window->north ||
params->map_south != window->south ||
params->map_ew_res != window->ew_res ||
params->map_ns_res != window->ns_res)
G_fatal_error ("Loaded map metadata does not match with your current GRASS window.\nRun 'g.region -p' to check the settings.");
// number of rows and columns within the maps
params->nrows = metadata->rows;
params->ncols = metadata->cols;
// allocate memory for the resulting path-loss matrix
if (params->m_loss == NULL)
{
params->m_loss = <API key> (params->nrows,
params->ncols,
params->m_loss);
// initialize all matrix elements to the NULL value
int r, c;
for (r = 0; r < params->nrows; r ++)
for (c = 0; c < params->ncols; c ++)
params->m_loss[r][c] = params->fcell_null_value;
}
// allocate the reading buffers for DEM and clutter data
void *inrast = <API key> (FCELL_TYPE);
void *inrast2 = <API key> (FCELL_TYPE);
// allocate memory to contain the both DEM and clutter maps
if ((params->m_dem == NULL) && (params->m_clut == NULL))
{
// DEM
params->m_dem = <API key> (params->nrows,
params->ncols,
params->m_dem);
// CLUTTER
params->m_clut = <API key> (params->nrows,
params->ncols,
params->m_clut);
// read files (DEM and clutter) into their respective arrays
for (row = 0; row < params->nrows; row ++)
{
// read DEM map data
if (G_get_raster_row (infd, inrast, row, FCELL_TYPE) < 0)
G_fatal_error ("Unable to read raster map <%s> row %d",
params->dem_map,
row);
// read Clutter map data
if (G_get_raster_row (infd2, inrast2, row, FCELL_TYPE) < 0)
G_fatal_error ("Unable to read raster map <%s> row %d",
params->clutter_map,
row);
// process the data
for (col = 0; col < params->ncols; col ++)
{
FCELL f_in = ((FCELL *) inrast)[col];
FCELL f_in2 = ((FCELL *)inrast2)[col];
params->m_dem[row][col] = (double) f_in;
params->m_clut[row][col] = (double) f_in2;
}
}
}
// create an array containing the transmitters to be processed
char *tx_sections [20 * _CHAR_BUFFER_SIZE_];
params->ntx = split_sections (tx_sections_list,
tx_sections);
// allocate and parse the per-transmitter parameters structure
params->tx_params = (Tx_parameters *) calloc (params->ntx,
sizeof (Tx_parameters));
for (i = 0; i < params->ntx; i ++)
{
<API key> (ini_file,
tx_sections[i],
params,
&(params->tx_params[i]));
printf ("*** INFO: Tx [%s] initialized!\n",
params->tx_params[i].tx_name);
}
// free the allocated metadata
free (window);
free (metadata);
free (mapset);
free (mapset2);
// free the read buffers for DEM and clutter data
G_free (inrast2);
G_free (inrast);
// close raster maps
G_close_cell (infd);
G_close_cell (infd2);
#ifdef _DEBUG_INFO_
int r, c;
for (r = 0; r < params->tx_params->nrows; r ++)
{
for (c = 0; c < params->tx_params->ncols; c ++)
{
fprintf (stdout,
"%.f|%.f|%.f\n",
params->map_west + 12.5 + (c * params->map_ew_res),
params->map_north - 12.5 - (r * params->map_ns_res),
params->tx_params->m_clut[r][c]);
}
}
fflush (stderr);
exit (1);
#endif
}
/**
* Initializes the MPI environment for master and workers.
*
* argc Number of command line parameters;
* argv array containing command line parameters;
* params a structure holding all parameters needed for calculation.-
*
*/
void
init_mpi (int argc,
char *argv [],
Parameters *params)
{
int nworkers = -1;
MPI_Comm worker_comm;
MPI_Init (&argc, &argv);
worker_comm = MPI_COMM_WORLD;
MPI_Comm_size (worker_comm, &nworkers);
// one is the master process
nworkers -= 1;
// in optimization mode, we may only process as many transmitters
// as there are worker processes
if ((params->use_opt) && (params->ntx > nworkers))
{
fprintf (stderr,
"*** WARNING Only the first %d transmitters will take part in the optimization\n",
nworkers);
params->ntx = nworkers;
}
// sync point: pass common input data to all workers
MPI_Barrier (worker_comm);
#ifdef <API key>
measure_time ("Common data distribution");
#endif
<API key> (params,
worker_comm);
// sync point: common data distribution finished
MPI_Barrier (worker_comm);
#ifdef <API key>
measure_time (NULL);
#endif
// do we have to start coverage or optimization calculation?
if (params->use_opt)
optimize_mpi (params,
nworkers,
&worker_comm);
else
coverage_mpi (params,
nworkers,
&worker_comm);
// close the MPI environment
MPI_Finalize ( );
} |
using System;
using Server;
using Server.Gumps;
using Server.Mobiles;
using Server.Network;
namespace Server.Factions
{
public class VoteGump : FactionGump
{
private PlayerMobile m_From;
private Election m_Election;
public override void OnResponse( GameClient sender, RelayInfo info )
{
if ( info.ButtonID == 0 )
{
m_From.SendGump( new FactionStoneGump( m_From, m_Election.Faction ) );
}
else
{
if ( !m_Election.CanVote( m_From ) )
{
return;
}
int index = info.ButtonID - 1;
if ( index >= 0 && index < m_Election.Candidates.Count )
{
m_Election.Candidates[index].Voters.Add( new Voter( m_From, m_Election.Candidates[index].Mobile ) );
}
m_From.SendGump( new VoteGump( m_From, m_Election ) );
}
}
public VoteGump( PlayerMobile from, Election election )
: base( 50, 50 )
{
m_From = from;
m_Election = election;
bool canVote = election.CanVote( from );
AddPage( 0 );
AddBackground( 0, 0, 420, 350, 5054 );
AddBackground( 10, 10, 400, 330, 3000 );
AddHtmlText( 20, 20, 380, 20, election.Faction.Definition.Header, false, false );
if ( canVote )
{
AddHtmlLocalized( 20, 60, 380, 20, 1011428, false, false ); // VOTE FOR LEADERSHIP
}
else
{
AddHtmlLocalized( 20, 60, 380, 20, 1038032, false, false ); // You have already voted in this election.
}
for ( int i = 0; i < election.Candidates.Count; ++i )
{
Candidate cd = election.Candidates[i];
if ( canVote )
{
AddButton( 20, 100 + ( i * 20 ), 4005, 4007, i + 1, GumpButtonType.Reply, 0 );
}
AddLabel( 55, 100 + ( i * 20 ), 0, cd.Mobile.Name );
AddLabel( 300, 100 + ( i * 20 ), 0, cd.Votes.ToString() );
}
AddButton( 20, 310, 4005, 4007, 0, GumpButtonType.Reply, 0 );
AddHtmlLocalized( 55, 310, 100, 20, 1011012, false, false ); // CANCEL
}
}
} |
package SnakeView;
import SnakeController.<API key>;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.io.File;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
/**
*
* @author Leonardo
*/
public class SwingGui extends javax.swing.JFrame implements IGui, <API key> {
private <API key> controller;
private int lastInput;
private JLabel[][] labels;
private final boolean borderSet;
private final Color background = new Color(192, 243, 217);
ImageIcon manzana = new ImageIcon(new ImageIcon(getClass().getResource("manzana.gif")).getImage());
ImageIcon naranja = new ImageIcon(new ImageIcon(getClass().getResource("naranja.gif")).getImage());
ImageIcon verde = new ImageIcon(new ImageIcon(getClass().getResource("verde.gif")).getImage());
ImageIcon ventana = new ImageIcon(new ImageIcon(getClass().getResource("manzana.png")).getImage());
ImageIcon toasty = new ImageIcon(new ImageIcon(getClass().getResource("toasty.png")).getImage());
private GameOver form;
private Instrucciones formInstrucciones;
/**
* Creates new form SwingGui
*/
public SwingGui() {
super();
form = new GameOver();
formInstrucciones = new Instrucciones();
formInstrucciones.setPadre(this);
form.setPadre(this);
formInstrucciones.setVisible(false);
form.setVisible(false);
initComponents();
borderSet = false;
}
public <API key> getController()
{
return this.controller;
}
public void setController(<API key> controller) {
this.controller = controller;
jPanel1.setPreferredSize(new Dimension(controller.getAncho() * 20,
controller.getAlto()* 20));
jPanel1.setLayout(new GridLayout(controller.getAlto(), controller
.getAlto()));
jPanel1.setBackground(background);
initLabels();
jPanel1.setFocusable(true);
}
private void initLabels() {
labels = new JLabel[controller.getAncho()][controller.getAlto()];
for (int j = 0; j < controller.getAlto(); j++) {
for (int i = 0; i < controller.getAncho(); i++) {
JLabel newLabel = new JLabel(" ");
labels[i][j] = newLabel;
newLabel.setVisible(true);
newLabel.updateUI();
jPanel1.add(newLabel);
}
}
jPanel1.updateUI();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jSeparator1 = new javax.swing.JSeparator();
jSeparator2 = new javax.swing.JSeparator();
jMenu2 = new javax.swing.JMenu();
jLabel1 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();
jMenu2.setText("jMenu2");
<API key>(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Snake Game");
setIconImage(ventana.getImage());
setPreferredSize(new java.awt.Dimension(600, 600));
jLabel1.setText("Puntaje:");
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jPanel1.setPreferredSize(new java.awt.Dimension(388, 362));
jPanel1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jPanel1KeyPressed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 384, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 358, Short.MAX_VALUE)
);
jMenu1.setText("Archivo");
jMenuItem1.setText("Jugar");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
<API key>(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuItem2.setText("Salir");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
<API key>(evt);
}
});
jMenu1.add(jMenuItem2);
jMenuItem3.setText("Instrucciones");
jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
<API key>(evt);
}
});
jMenu1.add(jMenuItem3);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.<API key>()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.<API key>()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(53, Short.MAX_VALUE))
.addGroup(layout.<API key>()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2)
.addGap(118, 118, 118))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.<API key>()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(30, 30, 30)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(39, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void <API key>(java.awt.event.ActionEvent evt) {//GEN-FIRST:<API key>
controller.stopJugar();
controller.resetJuego();
Thread starter = new StarterThread();
starter.start();
}//GEN-LAST:<API key>
private void <API key>(java.awt.event.ActionEvent evt) {//GEN-FIRST:<API key>
this.terminate();
}//GEN-LAST:<API key>
public void terminate()
{
controller.stopJugar();
this.dispose() ;
}
private void jPanel1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:<API key>
char keyChar = evt.getKeyChar();
// 1 = up, 2 = right, 3 = down, 4 = left, other is ignored
if (keyChar == 'w') {
lastInput = 1;
}
else if (keyChar == 'd')
{
lastInput = 2;
}
else if (keyChar == 's')
{
lastInput = 3;
}
else if (keyChar == 'a')
{
lastInput = 4;
}
else if (keyChar == 'l')
{
controller.siguiente();
}
else if (keyChar == 'k')
{
controller.anterior();
}
else if (keyChar == 'm')
{
controller.stopMusicaPublic();
}
else if (keyChar == 'p')
{
controller.<API key>();
}
else {
lastInput = -1; //detecta la entrada x teclado y la guarda en una variable que
//la devuelve con el getEntrada
}
}//GEN-LAST:<API key>
private void <API key>(java.awt.event.ActionEvent evt) {//GEN-FIRST:<API key>
// TODO add your handling code here:
formInstrucciones.setVisible(true);
}//GEN-LAST:<API key>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.<API key>()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (<API key> ex) {
java.util.logging.Logger.getLogger(SwingGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (<API key> ex) {
java.util.logging.Logger.getLogger(SwingGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (<API key> ex) {
java.util.logging.Logger.getLogger(SwingGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.<API key> ex) {
java.util.logging.Logger.getLogger(SwingGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SwingGui().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JPanel jPanel1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
// End of variables declaration//GEN-END:variables
@Override
public void setSnake(int x, int y) {
labels[x][y].setIcon(verde);
}
@Override
public void setManzanas(int x, int y) {
labels[x][y].setIcon(manzana);
}
@Override
public void setBordes(int x, int y) {
if (!borderSet) {
labels[x][y].setIcon(naranja);
}
}
@Override
public void setVacio(int x, int y) {
labels[x][y].setBackground(background);
labels[x][y].setIcon(null);
}
@Override
public void setPuntaje(int score) {
jLabel1.setText("Puntaje: " + score);
form.setScore(score);
}
@Override
public void perdiste()
{
form.setVisible(true);
}
@Override
public int getEntrada() {
return lastInput; //retorna la ultimadireccion seteada mediante teclado por el usuario
}
//CLASE PRIVADA QUE REPRESENTA UN THREAD, COLOCA EN TRUE EL ESTA JUGANDO Y EJECUTA EL LOOP
private class StarterThread extends Thread {
@Override
public void run() {
lastInput = -1;
controller.setEstaJugando();
controller.jugar();
}
}
} |
import {Component, NgZone, ElementRef, <API key>} from '@angular/core';
import {toggleClass} from '../..//toggle-class.service';
@Component({
selector: 'cmp-ten',
template: `
<a class="on-push">Cmp10</a>
`,
changeDetection: <API key>.OnPush
})
export class ComponentTen {
constructor(private zone: NgZone, private el: ElementRef) {}
ngAfterViewChecked() {
toggleClass(this.el, this.zone);
}
<API key> () { }
} |
#!/bin/bash
#PBS -l walltime=1:00:00
#PBS -l select=1:ncpus=2:mpiprocs=2
#PBS -o job.out
#PBS -e job.err
#PBS -A cin_staff
cd ${PBS_O_WORKDIR}
echo ${PBS_O_WORKDIR}
# modules to be loaded for petsc version 3.5.2
#module load intel/cs-xe-2015--binary
#module load intelmpi/5.0.2--binary
#module load petsc/3.5.2--intelmpi--5.0.2--binary
# modules to be loaded for petsc version 3.6.3
module load profile/advanced
module load intel/pe-xe-2016--binary
module load intelmpi/5.1.1--binary
module load petsc/3.6.3--intelmpi--5.1.1--binary
mpirun -np 2 ./<API key> -da_grid_x 64 -da_grid_y 64 -<API key> -ksp_view |
package org.kirhgoff.phoneprettifier.mechanics;
import org.kirhgoff.phoneprettifier.ArrayUtilsTrait;
import org.kirhgoff.phoneprettifier.model.MatchResult;
import org.kirhgoff.phoneprettifier.model.DigitsArray;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
public class WordMatcherTest implements ArrayUtilsTrait {
@Test
public void testSimpleMatching() throws Exception {
//Full match
checkMatches(
digits(3, 6, 6, 5),
strings("fool"),
strings("FOOL-[]")
);
//One diff
checkMatches(
digits(3, 8, 6, 5),
strings("fool"),
strings("F8OL-[]")
);
//Two non-consecutive diffs
checkMatches(
digits(3, 8, 6, 4),
strings("fool"),
strings("F8O4-[]")
);
//No match
checkMatches(
digits(2, 8, 6, 4),
strings("fool"),
strings("#-[2, 8, 6, 4]")
);
}
private void checkMatches(DigitsArray phone, String[] dictionaryContent, String[] expectedResult) {
Dictionary dictionary = new Dictionary();
dictionary.addWords(Arrays.asList(dictionaryContent));
WordMatcher matcher = new WordMatcher();
Set<MatchResult> results = matcher.match(phone, dictionary, false);
List<String> printed = results.stream()
.map(i -> i.getHead().toString() + "-" + i.getRemainder().toString())
.collect(Collectors.toList());
assertThat(printed).containsOnly(expectedResult);
}
} |
package PCA;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import MatrixScripts.MatrixStruct;
import MatrixScripts.MyMatrix;
import Tools.JSONutil;
import Tools.Script;
public class RlogLargeMatrix extends Script<RlogLargeMatrix>
{
//This is doing the DESeq normalization, which does not use replicate information.
//Also works for matrixes of larger then MAXint sizes
//static String expressionFN = "E:/Groningen/Data/Annique/<API key>.<API key>.txt.gz";
String expressionFN = null;//"E:/Groningen/Data/RNAseq_clinic/5GPM/GRCh38/<API key>.txt.gz";//"/groups/umcg-wijmenga/tmp04/umcg-jkarjalainen/31.txt";
String writeFolder = null;//if null becomes new File(expressionFN).getParent()+"/";
String geoFN = null;//"E:/Groningen/Scripts/Tests/Rlog.java/DESeqNorm2/geoMean.txt";//"E:/Groningen/Data/Juha/Genes31995/DuplicatesRemoved/geoMean.txt";//if null calculates geometric means based on this dataset
boolean writeAll = true; //write all intemediary files too
double logAdd = 0.5;//previously used to multiply the results by this number, but seems pointless since it does not have any effect, so does not do anything anymore
boolean roundValues = true;//rounds expression values to whole counts
public RlogLargeMatrix()
{
}
RlogLargeMatrix(String[] args)
{
checkArgs(args);
run();
}
public void run()
{ try
{
log("Input filename =" + expressionFN);
if(writeFolder == null)
writeFolder = new File(expressionFN).getParent()+"/DESeqNorm/";
if(!new File(writeFolder).exists())
new File(writeFolder).mkdir();
MyMatrix expression = new MyMatrix(expressionFN);
if(roundValues)
expression.roundValues();
rLog(writeFolder, expression, writeAll, geoFN);
log(" 7. Log transforming");
expression.logTransform(2,logAdd);//adds +0.5 before log
expression.write(writeFolder + new File(expressionFN).getName().replace(".txt", "").replace(".gz","")+".DESeqNorm.Log2.txt.gz");
end();
}catch(Exception e){e.printStackTrace();}
}
private void writeVars()
{
//JSONutil<RlogLargeMatrix> writer = new JSONutil<RlogLargeMatrix>();
//writer.
writeConfig(jsonFN, this);
}
public String getWritePath(String name)
{
if(!name.contains("\\") && !name.contains("/"))
return getFolderName(this.writeFolder)+name;
return name;
}
public String getFolderName(String fn)
{
if(!fn.endsWith("/") && !fn.endsWith("\\"))
fn = fn+"/";
return fn;
}
public void rLog(String writeFolder, MyMatrix expression, boolean writeAll, String geoFN) throws IOException
{
MatrixStruct geoMean = null;
if(geoFN!= null)
geoMean = new MatrixStruct(geoFN);
expression.putGenesOnRows();
String swapFN = writeFolder + "swapFile.txt";
expression.write(swapFN);
log(" 6. Rlog without log");
String correctedNotLogged = writeFolder + new File(expressionFN).getName().replace(".txt", "").replace(".gz","") + ".DESeqNorm.txt.gz";
rLog(expression, writeFolder, swapFN, geoMean, null);
if(writeAll)
expression.write(correctedNotLogged);
}
public void rLog(MyMatrix expression, String writeFolder, String fileName, String writeGeoFN) throws IOException
{
rLog(expression, writeFolder, fileName, null, writeGeoFN);
}
public void rLog(MyMatrix expression, String writeFolder, String fileName, MatrixStruct geoMean, String writeGeoFN) throws IOException
{
if(geoMean == null)
{
geoMean = getGeoMeans(expression, writeFolder, writeGeoFN);
//need to read the matrix again here...
expression.readFile(fileName);
}
MyMatrix geoMeanMat = new MyMatrix(geoMean);
geoMeanMat.keepRows(expression);//keep only the rows that are also in the geomean file
expression.write(fileName.replace(".txt", "geoRowsOnly.txt"));
MatrixStruct denominators = new MatrixStruct(expression.cols(),1);
denominators.setRowHeaders(expression.getColHeaders());
//determine the denominator per sample
for(int c = 0; c < expression.cols(); c++)
{
//get the correct denominator
double[] column = new double[expression.rows()];
for(int r = 0; r < column.length; r++)
{
column[r] = (expression.matrix.get(r,c)) / geoMean.matrix.get(r,0);
}
Arrays.sort(column);
org.apache.commons.math3.stat.descriptive.rank.Median med = new org.apache.commons.math3.stat.descriptive.rank.Median();
denominators.matrix.set(c,0,med.evaluate(column));
}
if(writeFolder != null)
denominators.write(writeFolder + "Denominators.txt");
expression.readFile(fileName);
//calculate the normalized readcounts
for(int c = 0; c < expression.cols(); c++)
{
for(int r = 0; r < expression.rows(); r++)
{
expression.matrix.set(r,c,expression.matrix.get(r,c)/denominators.matrix.get(c,0));
}
}
}
private MatrixStruct getGeoMeans(MyMatrix expression ,String writeFolder, String writeGeoFN) throws IOException {
expression.logTransform(10,0);
MatrixStruct geoMean = new MatrixStruct(expression.rows(),1);
geoMean.setRowHeaders(expression.getRowHeaders());
MatrixStruct keepGenes = new MatrixStruct(expression.rows(),1);
for(int r =0; r < expression.rows(); r++)
{
double gM = expression.sumRow(r)/expression.cols();
if(Double.isFinite(gM))
{
geoMean.matrix.set(r,0,gM);
geoMean.matrix.set(r,0,Math.pow(10,geoMean.matrix.get(r,0)));
keepGenes.setRowHeader(r, expression.getRowHeaders()[r]);
}
}
geoMean.keepRows(keepGenes);
if(writeGeoFN == null)
writeGeoFN = writeFolder+ "geoMean.txt";
log("geofilename=" + writeGeoFN);
this.geoFN=writeGeoFN;
geoMean.write(writeGeoFN);
return geoMean;
}
RlogLargeMatrix checkArgs(String[] args)
{
if(args.length < 1)
{
log("Script requires the following arguments:\n"
+ "1. filename=<expressionFN.txt> - Expression file with genes on rows samples on columns\n"
+ "2. writeFolder=<writeFolderFN.txt> - Folder where the files will be written (default=parentFolder(input.txt))\n"
+ "3. geoFN=<geoFn.txt> - Optional file with geometric mean per gene to use (default=null)\n");
writeVars();
System.exit(1);
}
for(int a = 0; a < args.length; a++)
{
String arg = args[a].split("=")[0];
String value = args[a].split("=")[1];
switch (arg.toLowerCase())
{
case "json":
;
break;
case "filename":
expressionFN =value;
break;
case "writefolder":
writeFolder = value;
break;
case "geofn":
geoFN = value;
break;
case "writeall":
writeAll = Boolean.parseBoolean(value);
break;
case "totalreadcount":
logAdd = Double.parseDouble(value);
break;
case "roundvalues":
roundValues = Boolean.parseBoolean(value);
break;
default:
log("Incorrect argument supplied:\n"+ args[a] +"\nexiting");
System.exit(1);
}
}
writeVars();
return this;
}
} |
This file is part of CCAPI.
Copyright (C) 2014 MCPM Team and Contributors
CCAPI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CCAPI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with CCAPI. If not, see <http:
]]
local lfs = require("lfs")
local modname = ...
local M = {
util={},
ccversion="CraftOS 1.63",
version="CCAPI 0.0.0",
}
if ccapi_DebugKernel then
print("cleaning up ccapi_DebugKernel - debug mode enabled")
ccapi_DebugKernel = nil
M.debug = true
end
do
local type,rawset,next = type,rawset,next
local function check(obj, todo, copies)
if copies[obj] ~= nil then
return copies[obj]
elseif type(obj) == "table" then
local t = {}
todo[obj] = t
copies[obj] = t
return t
end
return obj
end
M.simplecopy = function(inp)
local out, todo = {}, {}
local copies = {}
todo[inp], copies[inp] = out, out
-- we can't use pairs() here because we modify todo
while next(todo) do
local i, o = next(todo)
todo[i] = nil
for k, v in next, i do
rawset(o, check(k, todo, copies), check(v, todo, copies))
end
end
return out
end
end
do
local strmatch, strrep = string.match, string.rep
function M.util.getline(str, lno)
if lno == 0 then
return strmatch(str, "^([^\n]*)")
end
return strmatch(str, "^" .. strrep("[^\n]*\n", lno) .. "([^\n]*)")
end
end
-- Prepare basic env
M.prepareEnv = function(ccEnv, eventQueue)
local select,type,error = select,type,error
local setfenv,getfenv = setfenv,getfenv
local cyield = coroutine.yield
local luapath = package.path
local pc = {} -- pc = "package config"
-- ds = "directory separator"
-- ps = "path separator"
-- np = "name point"
-- ed = "executable directory"
-- im = "ignore mark"
pc.ds,pc.ps,pc.np,pc.ed,pc.im = package.config:match("^([^\n]*)\n([^\n]*)\n([^\n]*)\n([^\n]*)\n([^\n]*)")
-- make it so every new function has ccEnv as the env
setfenv(1,ccEnv)
-- setup eventQueue
eventQueue.count = 0
eventQueue.current = 1
function eventQueue:push(evt,...)
local newcount = self.count + 1
self[newcount] = {n=select('#',...), evt, ...}
self.count = newcount
end
function eventQueue:pop()
if self.count < self.current then
return nil
else
local current = self.current
self.current = current + 1
return self[current]
end
end
if not ccEnv.os then
ccEnv.os = {}
end
ccEnv.os.pullEventRaw = cyield
ccEnv.os.queueEvent = function(evt,...)
if evt == nil then error("Expected string") end -- todo test this
eventQueue:push(evt,...)
end
do
-- No I'm not gonna take 5 parameters like a fucking PEASANT!
-- TAKE THAT, COMPUTERCRAFT!
local function parseEvent(evt, ...)
if evt == "terminate" then
error("Terminated")
end
return evt, ...
end
ccEnv.os.pullEvent = function(_evt)
return parseEvent(cyield(_evt))
end
end
setfenv(1,getfenv(0))
return ccEnv, eventQueue,function()
setfenv(1,ccEnv)
-- TODO properly
for x in luapath:gmatch("([^" .. pc.ps .. "]+)") do
local path = x:gsub("%" .. pc.np, (modname:gsub("%.", pc.ds))):gsub("^%./", assert(lfs.currentdir()):gsub("%%","%%%%") .. "/")
local f,e = io.open(path,"r")
if f then
f:close()
local p1, p2 = path:match("(.*)" .. pc.ds .. "(.*)$")
path = p1 .. p2:gsub(modname:match("%.?([^%.]*)$"),"kernel")
local f,e = loadfile(path)
if f then
local s,e = pcall(f, M, path)
if s then
break
end
if M.debug and (e or not s) then
print(s,e)
end
end
if M.debug and (e or not f) then
print(f,e)
end
end
if M.debug and (e or not f) then
print(f,e)
end
end
setfenv(1,getfenv(0))
end
end
function M.runCC(func, env, eventQueue, id)
local env, eventQueue, loadkernel = M.prepareEnv(env or M.simplecopy(_G), eventQueue or {})
-- main loop
while true do
-- TODO
end
end
return M |
JFLAGS = -g
JC = javac
JAR = jar
.SUFFIXES: .java .class
.java.class:
$(JC) $(JFLAGS) $*.java
CLASSES = CRISPR.java CRISPRFinder.java CRISPRUtil.java DNASequence.java FASTAReader.java SearchUtil.java minced.java IntervalSearchTree.java
default: classes minced.jar
classes: $(CLASSES:.java=.class)
minced.jar: classes
$(JAR) cfm minced.jar MANIFEST.txt *class
clean:
$(RM) *.class
test: minced.jar
@echo "Testing..."
@./minced -gff t/<API key>.fna >t/<API key>.output
@diff -q t/<API key>.output t/<API key>.expected > /dev/null || (echo "Failed" && exit 1)
@echo "Passed" |
package org.langera.freud.optional.javasource.block;
import org.langera.freud.optional.javasource.classdecl.ClassDeclaration;
import org.langera.freud.optional.javasource.methodcall.MethodCall;
import org.langera.freud.optional.javasource.methoddecl.MethodDeclaration;
import java.util.List;
public interface CodeBlock
{
boolean isStaticBlock();
boolean <API key>();
MethodDeclaration <API key>();
ClassDeclaration getClassDeclaration();
List<MethodCall> <API key>(String methodName);
int getNumberOfLines();
} |
-- luacheck: globals love DEBUG
local IMGUI = require 'imgui'
local DB = require 'database'
local tween = require 'helpers.tween'
local Class = require "steaming.extra_libs.hump.class"
local ELEMENT = require "steaming.classes.primitives.element"
local MENU_WIDTH = 240
local MENU_MAX_HEIGHT = 600
local GUI = Class {
__includes = { ELEMENT }
}
local DOMAINS = {
'body', 'actor', 'appearance', 'sector',
'card', 'cardset', 'collection',
'drop', 'faction', 'zone', 'theme',
body = "Body Type",
actor = "Actor Type",
appearance = "Appearance",
sector = "Sector Type",
card = "Card",
cardset = "Card Set",
collection = "Collection",
drop = "Drop",
faction = "Faction",
theme = "Theme",
zone = "Zone",
}
local RESOURCES = {
'font', 'texture', 'sprite', 'tileset', 'sfx', 'bgm',
font = "Font",
texture = "Texture",
sfx = "Sound Effect",
bgm = "Background Music",
sprite = "Animated Sprite",
tileset = "TileSet",
}
local _VIEW = {}
-- This automatically loads all devmode menus in debug/view
for _,file in ipairs(love.filesystem.getDirectoryItems "devmode/view") do
if file:match "^.+%.lua$" then
file = file:gsub("%.lua", "")
_VIEW[file] = require('devmode.view.' .. file)
end
end
function GUI:init()
ELEMENT.init(self)
self.exception = true
self.stack = {}
self.active = false
self.current_level = 1
self.demo_window = false
IMGUI.StyleColorsDark()
IMGUI.<API key>("assets/font/PTMono-Regular.ttf", 18)
end
function GUI:length()
local length = 0
for _,view in ipairs(self.stack) do
length = length + view.size
end
return length
end
Pushes a menu. Menus in devmode mode appear from left to right and behave
-- like a stack. It's easier to understand if you play and check it out.
function GUI:push(viewname, ...)
local level = self.current_level+1
self:pop(level)
local title, size, render = _VIEW[viewname](...)
local length = self:length()
local width = MENU_WIDTH * size
local x = tween.start(
(length-size)*MENU_WIDTH,
8 + length*MENU_WIDTH + #self.stack * 8,
5
)
self.stack[level] = {
size = size,
draw = function (view)
IMGUI.SetNextWindowPos(x(), 40, "Always")
IMGUI.<API key>(width, 80, width, MENU_MAX_HEIGHT)
IMGUI.PushStyleVar("WindowPadding", 16, 16)
local open = IMGUI.Begin(title, true,
{ "NoCollapse", "AlwaysAutoResize",
"<API key>" })
if open then
open = not render(view)
end
IMGUI.End()
IMGUI.PopStyleVar()
return open
end
}
end
function GUI:pop(level)
for i=level,#self.stack do
self.stack[i] = nil
end
end
function GUI:draw()
if DEBUG and not self.active then
self.active = true
elseif not DEBUG then
self.stack = {}
self.active = false
return
end
self.current_level = 0
local g = love.graphics
IMGUI.NewFrame()
IMGUI.PushStyleVar('FramePadding', 8, 4)
if IMGUI.BeginMainMenuBar() then
if IMGUI.BeginMenu("Route") then
if IMGUI.MenuItem("Bodies") then
self:push('bodies_menu')
end
IMGUI.EndMenu()
end
if IMGUI.BeginMenu("Domains") then
for _,name in ipairs(DOMAINS) do
local title = DOMAINS[name]
if IMGUI.MenuItem(title.."s") then
self:push("category_list", 'domains', name, title)
end
end
IMGUI.Separator()
if IMGUI.MenuItem("Refresh") then
DB.refresh(DB.loadCategory('domains'))
end
if IMGUI.MenuItem("Save") then
DB.save(DB.loadCategory('domains'))
end
IMGUI.EndMenu()
end
if IMGUI.BeginMenu("Resources") then
for _,name in ipairs(RESOURCES) do
local title = RESOURCES[name]
if IMGUI.MenuItem(title.."s") then
self:push("category_list", 'resources', name, title)
end
end
IMGUI.Separator()
if IMGUI.MenuItem("Refresh") then
DB.refresh(DB.loadCategory('resources'))
end
if IMGUI.MenuItem("Save") then
DB.save(DB.loadCategory('resources'))
end
IMGUI.EndMenu()
end
if IMGUI.BeginMenu("IMGUI") then
if IMGUI.MenuItem("Demo Window") then
self.demo_window = true
end
IMGUI.EndMenu()
end
IMGUI.EndMainMenuBar()
end
for level,view in ipairs(self.stack) do
self.current_level = level
if not view.draw(self) then
if level > 0 then
self:pop(level)
break
end
end
end
if self.demo_window then
self.demo_window = IMGUI.ShowDemoWindow(self.demo_window)
end
g.setBackgroundColor(50/255, 80/255, 80/255, 1)
g.setColor(1, 1, 1)
IMGUI.PopStyleVar(1)
IMGUI.Render()
end
return GUI |
/**
* @file core/<API key>.c
* @brief code for managing low-level 'plaintext' connections with transport (key exchange may or may not be done yet)
* @author Christian Grothoff
*/
#include "platform.h"
#include "gnunet_util_lib.h"
#include "<API key>.h"
#include "<API key>.h"
#include "gnunet-service-core.h"
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
#include "gnunet_constants.h"
/**
* Message ready for transmission via transport service. This struct
* is followed by the actual content of the message.
*/
struct <API key>
{
/**
* We keep messages in a doubly linked list.
*/
struct <API key> *next;
/**
* We keep messages in a doubly linked list.
*/
struct <API key> *prev;
/**
* By when are we supposed to transmit this message?
*/
struct <API key> deadline;
/**
* How long is the message? (number of bytes following the "struct
* MessageEntry", but not including the size of "struct
* MessageEntry" itself!)
*/
size_t size;
};
/**
* Data kept per transport-connected peer.
*/
struct Neighbour
{
/**
* Head of the batched message queue (already ordered, transmit
* starting with the head).
*/
struct <API key> *message_head;
/**
* Tail of the batched message queue (already ordered, append new
* messages to tail).
*/
struct <API key> *message_tail;
/**
* Handle for pending requests for transmission to this peer
* with the transport service. NULL if no request is pending.
*/
struct <API key> *th;
/**
* Information about the key exchange with the other peer.
*/
struct GSC_KeyExchangeInfo *kxinfo;
/**
* Identity of the other peer.
*/
struct GNUNET_PeerIdentity peer;
/**
* ID of task used for re-trying plaintext scheduling.
*/
<API key> <API key>;
};
/**
* Map of peer identities to 'struct Neighbour'.
*/
static struct <API key> *neighbours;
/**
* Transport service.
*/
static struct <API key> *transport;
/**
* Find the entry for the given neighbour.
*
* @param peer identity of the neighbour
* @return NULL if we are not connected, otherwise the
* neighbour's entry.
*/
static struct Neighbour *
find_neighbour (const struct GNUNET_PeerIdentity *peer)
{
if (NULL == neighbours)
return NULL;
return <API key> (neighbours, &peer->hashPubKey);
}
/**
* Free the given entry for the neighbour.
*
* @param n neighbour to free
*/
static void
free_neighbour (struct Neighbour *n)
{
struct <API key> *m;
GNUNET_log (<API key>,
"Destroying neighbour entry for peer `%4s'\n",
GNUNET_i2s (&n->peer));
while (NULL != (m = n->message_head))
{
<API key> (n->message_head, n->message_tail, m);
GNUNET_free (m);
}
if (NULL != n->th)
{
<API key> (n->th);
n->th = NULL;
}
<API key> (GSC_stats,
gettext_noop
("# sessions terminated by transport disconnect"),
1, GNUNET_NO);
GSC_SESSIONS_end (&n->peer);
if (NULL != n->kxinfo)
{
GSC_KX_stop (n->kxinfo);
n->kxinfo = NULL;
}
if (n-><API key> != <API key>)
{
<API key> (n-><API key>);
n-><API key> = <API key>;
}
GNUNET_assert (GNUNET_OK ==
<API key> (neighbours,
&n->peer.hashPubKey, n));
<API key> (GSC_stats,
gettext_noop ("# neighbour entries allocated"),
<API key> (neighbours),
GNUNET_NO);
GNUNET_free (n);
}
/**
* Check if we have encrypted messages for the specified neighbour
* pending, and if so, check with the transport about sending them
* out.
*
* @param n neighbour to check.
*/
static void
process_queue (struct Neighbour *n);
/**
* Function called when the transport service is ready to receive a
* message for the respective peer
*
* @param cls neighbour to use message from
* @param size number of bytes we can transmit
* @param buf where to copy the message
* @return number of bytes transmitted
*/
static size_t
transmit_ready (void *cls, size_t size, void *buf)
{
struct Neighbour *n = cls;
struct <API key> *m;
size_t ret;
char *cbuf;
n->th = NULL;
m = n->message_head;
if (m == NULL)
{
GNUNET_break (0);
return 0;
}
<API key> (n->message_head, n->message_tail, m);
if (buf == NULL)
{
GNUNET_log (<API key>,
"Transmission of message of type %u and size %u failed\n",
(unsigned int)
ntohs (((struct <API key> *) &m[1])->type),
(unsigned int) m->size);
GNUNET_free (m);
process_queue (n);
return 0;
}
cbuf = buf;
GNUNET_assert (size >= m->size);
memcpy (cbuf, &m[1], m->size);
ret = m->size;
GNUNET_log (<API key>,
"Copied message of type %u and size %u into transport buffer for `%4s'\n",
(unsigned int)
ntohs (((struct <API key> *) &m[1])->type),
(unsigned int) ret, GNUNET_i2s (&n->peer));
GNUNET_free (m);
process_queue (n);
<API key> (GSC_stats,
gettext_noop
("# encrypted bytes given to transport"), ret,
GNUNET_NO);
return ret;
}
/**
* Check if we have messages for the specified neighbour pending, and
* if so, check with the transport about sending them out.
*
* @param n neighbour to check.
*/
static void
process_queue (struct Neighbour *n)
{
struct <API key> *m;
if (n->th != NULL)
return; /* request already pending */
m = n->message_head;
if (m == NULL)
{
/* notify sessions that the queue is empty and more messages
* could thus be queued now */
<API key> (&n->peer);
return;
}
GNUNET_log (<API key>,
"Asking transport for transmission of %u bytes to `%4s' in next %llu ms\n",
(unsigned int) m->size, GNUNET_i2s (&n->peer),
(unsigned long long)
<API key> (m->deadline).rel_value);
n->th =
<API key> (transport, &n->peer, m->size, 0,
<API key>
(m->deadline), &transmit_ready,
n);
if (n->th != NULL)
return;
/* message request too large or duplicate request */
GNUNET_break (0);
/* discard encrypted message */
<API key> (n->message_head, n->message_tail, m);
GNUNET_free (m);
process_queue (n);
}
/**
* Function called by transport to notify us that
* a peer connected to us (on the network level).
*
* @param cls closure
* @param peer the peer that connected
* @param atsi performance data
* @param atsi_count number of entries in ats (excluding 0-termination)
*/
static void
<API key> (void *cls,
const struct GNUNET_PeerIdentity *peer,
const struct <API key> *atsi,
uint32_t atsi_count)
{
struct Neighbour *n;
if (0 == memcmp (peer, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
{
GNUNET_break (0);
return;
}
n = find_neighbour (peer);
if (n != NULL)
{
/* duplicate connect notification!? */
GNUNET_break (0);
return;
}
GNUNET_log (<API key>, "Received connection from `%4s'.\n",
GNUNET_i2s (peer));
n = GNUNET_malloc (sizeof (struct Neighbour));
n->peer = *peer;
GNUNET_assert (GNUNET_OK ==
<API key> (neighbours,
&n->peer.hashPubKey, n,
<API key>));
<API key> (GSC_stats,
gettext_noop ("# neighbour entries allocated"),
<API key> (neighbours),
GNUNET_NO);
n->kxinfo = GSC_KX_start (peer);
}
/**
* Function called by transport telling us that a peer
* disconnected.
*
* @param cls closure
* @param peer the peer that disconnected
*/
static void
<API key> (void *cls,
const struct GNUNET_PeerIdentity *peer)
{
struct Neighbour *n;
GNUNET_log (<API key>,
"Peer `%4s' disconnected from us; received notification from transport.\n",
GNUNET_i2s (peer));
n = find_neighbour (peer);
if (n == NULL)
{
GNUNET_break (0);
return;
}
free_neighbour (n);
}
/**
* Function called by the transport for each received message.
*
* @param cls closure
* @param peer (claimed) identity of the other peer
* @param message the message
* @param atsi performance data
* @param atsi_count number of entries in ats (excluding 0-termination)
*/
static void
<API key> (void *cls, const struct GNUNET_PeerIdentity *peer,
const struct <API key> *message,
const struct <API key> *atsi,
uint32_t atsi_count)
{
struct Neighbour *n;
uint16_t type;
GNUNET_log (<API key>,
"Received message of type %u from `%4s', demultiplexing.\n",
(unsigned int) ntohs (message->type), GNUNET_i2s (peer));
if (0 == memcmp (peer, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity)))
{
GNUNET_break (0);
return;
}
n = find_neighbour (peer);
if (n == NULL)
{
/* received message from peer that is not connected!? */
GNUNET_break (0);
return;
}
type = ntohs (message->type);
switch (type)
{
case <API key>:
<API key> (n->kxinfo, message);
break;
case <API key>:
GSC_KX_handle_ping (n->kxinfo, message);
break;
case <API key>:
GSC_KX_handle_pong (n->kxinfo, message);
break;
case <API key>:
<API key> (n->kxinfo, message, atsi, atsi_count);
break;
default:
GNUNET_log (<API key>,
_
("Unsupported message of type %u (%u bytes) received from peer `%s'\n"),
(unsigned int) type, (unsigned int) ntohs (message->size),
GNUNET_i2s (peer));
return;
}
}
/**
* Transmit the given message to the given target.
*
* @param target peer that should receive the message (must be connected)
* @param msg message to transmit
* @param timeout by when should the transmission be done?
*/
void
<API key> (const struct GNUNET_PeerIdentity *target,
const struct <API key> *msg,
struct <API key> timeout)
{
struct <API key> *me;
struct Neighbour *n;
size_t msize;
n = find_neighbour (target);
if (NULL == n)
{
GNUNET_break (0);
return;
}
msize = ntohs (msg->size);
me = GNUNET_malloc (sizeof (struct <API key>) + msize);
me->deadline = <API key> (timeout);
me->size = msize;
memcpy (&me[1], msg, msize);
<API key> (n->message_head, n->message_tail, me);
process_queue (n);
}
/**
* Initialize neighbours subsystem.
*/
int
GSC_NEIGHBOURS_init ()
{
neighbours = <API key> (128);
transport =
<API key> (GSC_cfg, &GSC_my_identity, NULL,
&<API key>,
&<API key>,
&<API key>);
if (NULL == transport)
{
<API key> (neighbours);
neighbours = NULL;
return GNUNET_SYSERR;
}
return GNUNET_OK;
}
/**
* Wrapper around 'free_neighbour'.
*
* @param cls unused
* @param key peer identity
* @param value the 'struct Neighbour' to free
* @return GNUNET_OK (continue to iterate)
*/
static int
<API key> (void *cls, const GNUNET_HashCode * key, void *value)
{
struct Neighbour *n = value;
/* transport should have 'disconnected' all neighbours... */
GNUNET_break (0);
free_neighbour (n);
return GNUNET_OK;
}
/**
* Shutdown neighbours subsystem.
*/
void
GSC_NEIGHBOURS_done ()
{
if (NULL == transport)
return;
<API key> (transport);
transport = NULL;
<API key> (neighbours, &<API key>,
NULL);
<API key> (neighbours);
neighbours = NULL;
}
/* end of <API key>.c */ |
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Unity - Scripting API: <API key>.areas</title>
<meta name="description" content="Develop once, publish everywhere! Unity is the ultimate tool for video game development, architectural visualizations, and interactive media installations - publish to the web, Windows, OS X, Wii, Xbox 360, and iPhone with many more platforms to come." />
<meta name="author" content="Unity Technologies" />
<link rel="shortcut icon" href="../StaticFiles/images/favicons/favicon.ico" />
<link rel="icon" type="image/png" href="../StaticFiles/images/favicons/favicon.png" />
<link rel="<API key>" sizes="152x152" href="../StaticFiles/images/favicons/<API key>.png" />
<link rel="<API key>" sizes="144x144" href="../StaticFiles/images/favicons/<API key>.png" />
<link rel="<API key>" sizes="120x120" href="../StaticFiles/images/favicons/<API key>.png" />
<link rel="<API key>" sizes="114x114" href="../StaticFiles/images/favicons/<API key>.png" />
<link rel="<API key>" sizes="72x72" href="../StaticFiles/images/favicons/<API key>.png" />
<link rel="<API key>" href="../StaticFiles/images/favicons/apple-touch-icon.png" />
<meta name="<API key>" content="#222c37" />
<meta name="<API key>" content="../StaticFiles/images/favicons/tileicon-144x144.png" />
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-2854981-1']);
_gaq.push(['_setDomainName', 'unity3d.com']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https:
var s = document.<API key>('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<script type="text/javascript" src="../StaticFiles/js/jquery.js">
</script>
<script type="text/javascript" src="docdata/toc.js">//toc</script>
<!--local TOC
<script type="text/javascript" src="docdata/global_toc.js">//toc</script>
<!--global TOC, including other platforms
<script type="text/javascript" src="../StaticFiles/js/core.js">
</script>
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,700,400italic" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="../StaticFiles/css/core.css" />
</head>
<body>
<div class="header-wrapper">
<div id="header" class="header">
<div class="content">
<div class="spacer">
<div class="menu">
<div class="logo">
<a href="http://docs.unity3d.com">
</a>
</div>
<div class="search-form">
<form action="30_search.html" method="get" class="apisearch">
<input type="text" name="q" placeholder="Search scripting..." autosave="Unity Reference" results="5" class="sbox field" id="q">
</input>
<input type="submit" class="submit">
</input>
</form>
</div>
<ul>
<li>
<a href="http://docs.unity3d.com">Overview</a>
</li>
<li>
<a href="../Manual/index.html">Manual</a>
</li>
<li>
<a href="../ScriptReference/index.html" class="selected">Scripting API</a>
</li>
</ul>
</div>
</div>
<div class="more">
<div class="filler">
</div>
<ul>
<li>
<a href="http://unity3d.com/">unity3d.com</a>
</li>
</ul>
</div>
</div>
</div>
<div class="toolbar">
<div class="content clear">
<div class="lang-switcher hide">
<div class="current toggle" data-target=".lang-list">
<div class="lbl">Language: <span class="b">English</span></div>
<div class="arrow">
</div>
</div>
<div class="lang-list" style="display:none;">
<ul>
<li>
<a href="">English</a>
</li>
</ul>
</div>
</div>
<div class="script-lang">
<ul>
<li class="selected" data-lang="CS">C
<li data-lang="JS">JS</li>
</ul>
<div id="script-lang-dialog" class="dialog hide">
<div class="dialog-content clear">
<h2>Script language</h2>
<div class="close">
</div>
<p class="clear">Select your preferred scripting language. All code snippets will be displayed in this language.</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="master-wrapper" class="master-wrapper clear">
<div id="sidebar" class="sidebar">
<div class="sidebar-wrap">
<div class="content">
<div class="sidebar-menu">
<div class="toc">
<h2>Scripting API</h2>
</div>
</div>
<p>
<a href="40_history.html" class="cw">History</a>
</p>
</div>
</div>
</div>
<div id="content-wrap" class="content-wrap">
<div class="content-block">
<div class="content">
<div class="section">
<div class="mb20 clear">
<h1 class="heading inherit">
<a href="<API key>.html"><API key></a>.areas</h1>
<div class="clear">
</div>
<div class="clear">
</div>
<div class="suggest">
<a class="blue-btn sbtn">Suggest a change</a>
<div class="suggest-wrap rel hide">
<div class="loading hide">
<div>
</div>
<div>
</div>
<div>
</div>
</div>
<div class="suggest-success hide">
<h2>Success!</h2>
<p>Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.</p>
<a class="gray-btn sbtn close">Close</a>
</div>
<div class="suggest-failed hide">
<h2>Sumbission failed</h2>
<p>For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.</p>
<a class="gray-btn sbtn close">Close</a>
</div>
<div class="suggest-form clear">
<label for="suggest_name">Your name</label>
<input id="suggest_name" type="text">
</input>
<label for="suggest_email">Your email</label>
<input id="suggest_email" type="email">
</input>
<label for="suggest_body" class="clear">Suggestion <span class="r">*</span></label>
<textarea id="suggest_body" class="req">
</textarea>
<button id="suggest_submit" class="blue-btn mr10">Submit suggestion</button>
<p class="mb0">
<a class="cancel left lh42 cn">Cancel</a>
</p>
</div>
</div>
</div>
<a href="" class="switch-link gray-btn sbtn left hide">Switch to Manual</a>
<div class="clear">
</div>
</div>
<div class="subsection">
<div class="signature">
<div class="signature-JS sig-block">public
var <span class="sig-kw">areas</span>: int[];
</div>
<div class="signature-CS sig-block">public int[] <span class="sig-kw">areas</span>;
</div>
</div>
</div>
<div class="subsection">
<h2>Description</h2>
<p>NavMesh area indices for the navmesh triangulation.</p>
</div>
<div class="subsection">
<p>Contains one element for each triangle.</p>
</div>
</div>
<div class="footer-wrapper">
<div class="footer clear">
<div class="copy">Copyright © 2014 Unity Technologies</div>
<div class="menu">
<a href="http://unity3d.com/learn">Learn</a>
<a href="http://unity3d.com/community">Community</a>
<a href="http://unity3d.com/asset-store">Asset Store</a>
<a href="https://store.unity3d.com">Buy</a>
<a href="http://unity3d.com/unity/download">Download</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html> |
// Synthesizer
#include "synth.h"
#include "wtosc.h"
#include "dacspi.h"
#include "scan.h"
#include "ui.h"
#include "uart_midi.h"
#include "midi.h"
#include "adsr.h"
#include "lfo.h"
#include "tuner.h"
#include "assigner.h"
#include "arp.h"
#include "seq.h"
#include "clock.h"
#include "storage.h"
#include "vca_curves.h"
#include "vcnoise_curves.h"
#include "../xnormidi/midi.h"
#include "lpc17xx_gpio.h"
#include "lpc17xx_pinsel.h"
#define <API key> (1<<26)
#define WAVEDATA_PATH "/WAVEDATA"
#define MAX_BANKS 100
#define MAX_BANK_WAVES 200
#define POT_DEAD_ZONE 512
volatile uint32_t currentTick=0; // 500hz
static struct
{
int bankCount;
int curWaveCount;
char bankNames[MAX_BANKS][MAX_FILENAME];
char curWaveNames[MAX_BANK_WAVES][MAX_FILENAME];
int8_t bankSorted;
int8_t curWaveSorted;
int8_t curWaveABX;
char curWaveBank[128];
uint16_t sampleData[4][WTOSC_MAX_SAMPLES]; // 0: OscA, 1: OscB, 2: XOvr source, 3: XOvr mix
uint16_t sampleCount[4];
DIR curDir;
FILINFO curFile;
char lfname[_MAX_LFN + 1];
} waveData;
static struct
{
struct wtosc_s osc[SYNTH_VOICE_COUNT][2];
struct adsr_s filEnvs[SYNTH_VOICE_COUNT];
struct adsr_s ampEnvs[SYNTH_VOICE_COUNT];
struct lfo_s lfo[2];
uint16_t oscANoteCV[SYNTH_VOICE_COUNT];
uint16_t oscBNoteCV[SYNTH_VOICE_COUNT];
uint16_t filterNoteCV[SYNTH_VOICE_COUNT];
uint16_t oscATargetCV[SYNTH_VOICE_COUNT];
uint16_t oscBTargetCV[SYNTH_VOICE_COUNT];
uint16_t filterTargetCV[SYNTH_VOICE_COUNT];
struct
{
int16_t benderCVs[cvAmp-cvAVol+1];
int16_t benderAmount;
uint16_t modwheelAmount;
int16_t glideAmount;
int8_t gliding;
uint32_t <API key>;
uint16_t <API key>;
uint8_t wmodMask;
uint32_t syncResetsMask;
int32_t oldCrossOver;
} partState;
uint8_t pendingExtClock;
int32_t wmodAVal, wmodEnvAmt;
} synth;
extern const uint16_t attackCurveLookup[]; // for modulation delay
const uint16_t extClockDividers[16] = {192,168,144,128,96,72,48,36,24,18,12,9,6,4,3,2};
static const uint8_t abx2bsp[3] = {spABank_Legacy, spBBank_Legacy, spXOvrBank_Legacy};
static const uint8_t abx2wsp[3] = {spAWave_Legacy, spBWave_Legacy, spXOvrWave_Legacy};
// Non speed critical internal code
static void computeTunedCVs(void)
{
uint16_t cva,cvb,cvf;
uint8_t note,baseCutoffNote,baseANote,baseBNote,trackingNote;
int8_t v;
uint16_t baseAPitch,baseBPitch,baseCutoff;
int16_t mTune,fineBFreq,detune;
uint16_t baseBPitchRaw,baseCutoffRaw,mTuneRaw,fineBFreqRaw,detuneRaw,trackRaw;
uint8_t chrom;
for(v=0;v<SYNTH_VOICE_COUNT;++v)
{
if (!<API key>(v,¬e))
continue;
// get raw values
mTuneRaw=currentPreset.<API key>[cpMasterTune];
fineBFreqRaw=currentPreset.<API key>[cpBFineFreq];
baseCutoffRaw=currentPreset.<API key>[cpCutoff];
baseBPitchRaw=currentPreset.<API key>[cpBFreq];
detuneRaw=currentPreset.<API key>[cpUnisonDetune];
trackRaw=currentPreset.<API key>[cpFilKbdAmt];
chrom=currentPreset.steppedParameters[spChromaticPitch];
// compute for oscs & filters
mTune=(mTuneRaw>>7)+INT8_MIN*2;
fineBFreq=(fineBFreqRaw>>8)+INT8_MIN;
baseCutoff=((uint32_t)baseCutoffRaw*3)>>2; // 75% of raw cutoff
if(baseBPitchRaw>=HALF_RANGE)
{
baseAPitch=0;
baseBPitch=(<API key>)>>1;
}
else
{
baseAPitch=(<API key>)>>1;
baseBPitch=0;
}
baseCutoffNote=baseCutoff>>8;
baseANote=baseAPitch>>8; // 64 semitones
baseBNote=baseBPitch>>8;
baseCutoff&=0xff;
if(chrom>0)
{
baseAPitch=0;
baseBPitch=0;
if(chrom>1)
{
baseANote-=baseANote%12;
baseBNote-=baseBNote%12;
}
}
else
{
baseAPitch&=0xff;
baseBPitch&=0xff;
}
// oscs
cva=satAddU16S32(<API key>(v,baseANote+note,baseAPitch,cvAPitch),(int32_t)synth.partState.benderCVs[cvAPitch]+mTune);
cvb=satAddU16S32(<API key>(v,baseBNote+note,baseBPitch,cvBPitch),(int32_t)synth.partState.benderCVs[cvBPitch]+mTune+fineBFreq);
detune=(1+(v>>1))*(v&1?-1:1)*(detuneRaw>>9);
cva=satAddU16S16(cva,detune);
cvb=satAddU16S16(cvb,detune);
// filter
trackingNote=baseCutoffNote+((note*(trackRaw>>8))>>8);
cvf=satAddU16S16(<API key>(v,trackingNote,baseCutoff,cvCutoff),synth.partState.benderCVs[cvCutoff]);
// glide
if(synth.partState.gliding)
{
synth.oscATargetCV[v]=cva;
synth.oscBTargetCV[v]=cvb;
synth.filterTargetCV[v]=cvf;
if(trackRaw<POT_DEAD_ZONE)
synth.filterNoteCV[v]=cvf; // no glide if no tracking for filter
}
else
{
synth.oscANoteCV[v]=cva;
synth.oscBNoteCV[v]=cvb;
synth.filterNoteCV[v]=cvf;
}
}
}
void computeBenderCVs(void)
{
static const int8_t br[]={3,5,12,0};
int32_t bend;
bend=synth.partState.benderAmount;
switch(currentPreset.steppedParameters[spBenderTarget])
{
case modPitch:
bend*=<API key>(0,br[currentPreset.steppedParameters[spBenderRange]]*2,0,cvAPitch)-<API key>(0,0,0,cvAPitch);
bend/=UINT16_MAX;
synth.partState.benderCVs[cvAPitch]=bend;
synth.partState.benderCVs[cvBPitch]=bend;
break;
case modFil:
bend*=<API key>(0,br[currentPreset.steppedParameters[spBenderRange]]*8,0,cvCutoff)-<API key>(0,0,0,cvCutoff);
bend/=UINT16_MAX;
synth.partState.benderCVs[cvCutoff]=bend;
break;
case modAmp:
bend=(bend*br[currentPreset.steppedParameters[spBenderRange]])/12;
synth.partState.benderCVs[cvAmp]=bend;
break;
}
}
static void <API key>(void)
{
int8_t v;
for(v=0;v<SYNTH_VOICE_COUNT;++v)
{
// when amp env finishes, voice is done
if(<API key>(v,NULL) && adsr_getStage(&synth.ampEnvs[v])==sWait)
assigner_voiceDone(v);
// if voice isn't assigned, silence it
if(!<API key>(v,NULL) && adsr_getStage(&synth.ampEnvs[v])!=sWait)
{
adsr_reset(&synth.ampEnvs[v]);
adsr_reset(&synth.filEnvs[v]);
}
}
}
static void <API key>(void)
{
static const uint8_t vc2msk[7]={1,3,7,15,31,63};
if(currentPreset.steppedParameters[spUnison]!=assigner_getMono())
{
if(currentPreset.steppedParameters[spUnison])
<API key>();
else
assigner_setPoly();
assigner_getPattern(currentPreset.voicePattern,NULL);
}
assigner_setPattern(currentPreset.voicePattern,currentPreset.steppedParameters[spUnison]);
<API key>(currentPreset.steppedParameters[spAssignerPriority]);
<API key>(vc2msk[currentPreset.steppedParameters[spVoiceCount]]);
}
static void refreshEnvSettings(int8_t type)
{
int8_t slow;
int8_t i;
struct adsr_s * a;
for(i=0;i<SYNTH_VOICE_COUNT;++i)
{
slow=currentPreset.steppedParameters[(type)?spFilEnvSlow:spAmpEnvSlow];
if(type)
{
a=&synth.filEnvs[i];
adsr_setShape(a,currentPreset.steppedParameters[spFilEnvLin]?0:1);
}
else
{
a=&synth.ampEnvs[i];
}
adsr_setSpeedShift(a,(slow)?3:1,5);
adsr_setCVs(&synth.ampEnvs[i],
currentPreset.<API key>[cpAmpAtt],
currentPreset.<API key>[cpAmpDec],
currentPreset.<API key>[cpAmpSus],
currentPreset.<API key>[cpAmpRel],
0,0x0f);
adsr_setCVs(&synth.filEnvs[i],
currentPreset.<API key>[cpFilAtt],
currentPreset.<API key>[cpFilDec],
currentPreset.<API key>[cpFilSus],
currentPreset.<API key>[cpFilRel],
0,0x0f);
}
}
static void refreshLfoSettings(void)
{
static const int8_t mr[]={5,3,1,0};
uint16_t mwAmt,lfoAmt,lfo2Amt,dlyAmt;
uint32_t elapsed;
lfo_setShape(&synth.lfo[0],currentPreset.steppedParameters[spLFOShape]);
lfo_setShape(&synth.lfo[1],currentPreset.steppedParameters[spLFO2Shape]);
lfo_setSpeedShift(&synth.lfo[0],1+currentPreset.steppedParameters[spLFOShift]*3,5);
lfo_setSpeedShift(&synth.lfo[1],1+currentPreset.steppedParameters[spLFO2Shift]*3,5);
// wait <API key> then progressively increase over
// <API key> time, following an exponential curve
dlyAmt=0;
if(synth.partState.<API key>!=UINT32_MAX)
{
if(currentPreset.<API key>[cpModDelay]<POT_DEAD_ZONE)
{
dlyAmt=UINT16_MAX;
}
else if(currentTick>=synth.partState.<API key>+synth.partState.<API key>)
{
elapsed=currentTick-(synth.partState.<API key>+synth.partState.<API key>);
if(elapsed>=synth.partState.<API key>)
dlyAmt=UINT16_MAX;
else
dlyAmt=attackCurveLookup[(elapsed<<8)/synth.partState.<API key>];
}
}
mwAmt=synth.partState.modwheelAmount>>mr[currentPreset.steppedParameters[spModwheelRange]];
lfoAmt=currentPreset.<API key>[cpLFOAmt];
lfoAmt=(lfoAmt<POT_DEAD_ZONE)?0:(<API key>);
lfo2Amt=currentPreset.<API key>[cpLFO2Amt];
lfo2Amt=(lfo2Amt<POT_DEAD_ZONE)?0:(<API key>);
if(currentPreset.steppedParameters[spModwheelTarget]==0) // targeting lfo1?
{
lfo_setCVs(&synth.lfo[0],
currentPreset.<API key>[cpLFOFreq],
satAddU16U16(lfoAmt,mwAmt));
lfo_setCVs(&synth.lfo[1],
currentPreset.<API key>[cpLFO2Freq],
scaleU16U16(lfo2Amt,dlyAmt));
}
else
{
lfo_setCVs(&synth.lfo[0],
currentPreset.<API key>[cpLFOFreq],
scaleU16U16(lfoAmt,dlyAmt));
lfo_setCVs(&synth.lfo[1],
currentPreset.<API key>[cpLFO2Freq],
satAddU16U16(lfo2Amt,mwAmt));
}
}
static void <API key>(int8_t refreshTickCount)
{
int8_t anyPressed, anyAssigned;
static int8_t prevAnyPressed=0;
anyPressed=<API key>();
anyAssigned=<API key>();
if(!anyAssigned)
{
synth.partState.<API key>=UINT32_MAX;
}
if(anyPressed && !prevAnyPressed)
{
synth.partState.<API key>=currentTick;
}
prevAnyPressed=anyPressed;
if(refreshTickCount)
synth.partState.<API key>=exponentialCourse(<API key>.<API key>[cpModDelay],12000.0f,2500.0f);
}
static void refreshMisc(void)
{
// arp
clock_setSpeed(settings.seqArpClock);
// glide
synth.partState.glideAmount=exponentialCourse(currentPreset.<API key>[cpGlide],11000.0f,2100.0f);
synth.partState.gliding=synth.partState.glideAmount<2000;
// WaveMod mask
synth.partState.wmodMask=0;
if(currentPreset.steppedParameters[spAWModType]==wmAliasing)
synth.partState.wmodMask|=1;
if(currentPreset.steppedParameters[spAWModType]==wmWidth)
synth.partState.wmodMask|=2;
if(currentPreset.steppedParameters[spAWModType]==wmFrequency)
synth.partState.wmodMask|=4;
if(currentPreset.steppedParameters[spAWModEnvEn])
synth.partState.wmodMask|=8;
if(currentPreset.steppedParameters[spBWModType]==wmAliasing)
synth.partState.wmodMask|=16;
if(currentPreset.steppedParameters[spBWModType]==wmWidth)
synth.partState.wmodMask|=32;
if(currentPreset.steppedParameters[spBWModType]==wmFrequency)
synth.partState.wmodMask|=64;
if(currentPreset.steppedParameters[spBWModEnvEn])
synth.partState.wmodMask|=128;
// waveforms
for(int i=0;i<SYNTH_VOICE_COUNT;++i)
{
int p=currentPreset.steppedParameters[spAWModType]==wmCrossOver?3:0;
wtosc_setSampleData(&synth.osc[i][0],waveData.sampleData[p],waveData.sampleCount[p]);
wtosc_setSampleData(&synth.osc[i][1],waveData.sampleData[1],waveData.sampleCount[1]);
}
}
void refreshFullState(void)
{
<API key>(1);
<API key>();
refreshLfoSettings();
refreshEnvSettings(0);
refreshEnvSettings(1);
refreshMisc();
computeBenderCVs();
computeTunedCVs();
}
void <API key>(int8_t abx, int8_t loadDefault, int8_t sort)
{
int i,bankNum,waveNum,oriBankNum,oriWaveNum,newBankNum,newWaveNum;
char fn[MAX_FILENAME];
if(loadDefault)
{
bankNum=-1;
waveNum=-1;
}
else
{
bankNum=currentPreset.steppedParameters[abx2bsp[abx]];
waveNum=currentPreset.steppedParameters[abx2wsp[abx]];
}
oriWaveNum=waveNum;
oriBankNum=bankNum;
refreshBankNames(sort);
reload:
newBankNum=-1;
fn[0]=0;
if(bankNum<0 || bankNum>=waveData.bankCount)
strcpy(fn,<API key>);
else
strcpy(fn,waveData.bankNames[bankNum]);
for(i=0;i<waveData.bankCount;++i)
{
if(!stricmp(fn,waveData.bankNames[i]))
{
newBankNum=i;
break;
}
}
if(newBankNum<0) // in case bank not found, reload default wave and bank
{
rprintf(0,"Error: abx %d bank %s not found!\n",abx,fn);
bankNum=-1;
goto reload;
}
strcpy(currentPreset.oscBank[abx],waveData.bankNames[newBankNum]);
refreshCurWaveNames(abx,sort);
newWaveNum=-1;
fn[0]=0;
if(waveNum<0 || waveNum>=waveData.curWaveCount)
strcpy(fn,<API key>);
else
strcpy(fn,waveData.curWaveNames[waveNum]);
for(i=0;i<waveData.curWaveCount;++i)
{
if(!stricmp(fn,waveData.curWaveNames[i]))
{
newWaveNum=i;
break;
}
}
if(newWaveNum<0) // in case wave not found, reload default wave and bank
{
rprintf(0,"Error: abx %d waveform %s not found!\n",abx,fn);
bankNum=-1;
waveNum=-1;
goto reload;
}
strcpy(currentPreset.oscWave[abx],waveData.curWaveNames[newWaveNum]);
if (oriBankNum!=newBankNum || oriWaveNum!=newWaveNum)
rprintf(0,"<API key> abx %d from %d/%d to %d/%d\n",abx,oriBankNum,oriWaveNum,newBankNum,newWaveNum);
}
int getBankCount(void)
{
return waveData.bankCount;
}
int getCurWaveCount(void)
{
return waveData.curWaveCount;
}
int8_t getBankName(int bankIndex, char * res)
{
if(bankIndex<0 || bankIndex>=waveData.bankCount)
{
res[0]=0;
return 0;
}
strcpy(res,waveData.bankNames[bankIndex]);
return 1;
}
int8_t getWaveName(int waveIndex, char * res)
{
if(waveIndex<0 || waveIndex>=waveData.curWaveCount)
{
res[0]=0;
return 0;
}
strcpy(res,waveData.curWaveNames[waveIndex]);
return 1;
}
void refreshBankNames(int8_t sort)
{
FRESULT res;
if(waveData.bankSorted==sort) // already loaded and same state
return;
waveData.bankCount=0;
if((res=f_opendir(&waveData.curDir,WAVEDATA_PATH)))
{
rprintf(0,"f_opendir res=%d\n",res);
return;
}
if((res=f_readdir(&waveData.curDir,&waveData.curFile)))
rprintf(0,"f_readdir res=%d\n",res);
while(!res)
{
if(strcmp(waveData.curFile.fname,".") && strcmp(waveData.curFile.fname,".."))
{
strncpy(waveData.bankNames[waveData.bankCount],waveData.curFile.lfname,waveData.curFile.lfsize);
++waveData.bankCount;
}
res=f_readdir(&waveData.curDir,&waveData.curFile);
if (!waveData.curFile.fname[0] || waveData.bankCount>=MAX_BANKS)
break;
}
if(sort)
qsort(waveData.bankNames,waveData.bankCount,sizeof(waveData.bankNames[0]),stringCompare);
waveData.bankSorted=sort;
#ifdef DEBUG
rprintf(0,"bankCount %d\n",waveData.bankCount);
#endif
}
void refreshCurWaveNames(int8_t abx, int8_t sort)
{
FRESULT res;
char fn[128];
strcpy(fn,WAVEDATA_PATH "/");
strcat(fn,currentPreset.oscBank[abx]);
if(!strcmp(waveData.curWaveBank,fn) && waveData.curWaveSorted==sort && waveData.curWaveABX==abx) // already loaded and same state
return;
waveData.curWaveCount=0;
#ifdef DEBUG
rprintf(0,"loading %s\n",fn);
#endif
if((res=f_opendir(&waveData.curDir,fn)))
{
rprintf(0,"f_opendir res=%d\n",res);
return;
}
if((res=f_readdir(&waveData.curDir,&waveData.curFile)))
rprintf(0,"f_readdir res=%d\n",res);
while(!res)
{
if(strstr(waveData.curFile.fname,".WAV") || strstr(waveData.curFile.fname,".wav"))
{
strncpy(waveData.curWaveNames[waveData.curWaveCount],waveData.curFile.lfname,waveData.curFile.lfsize);
++waveData.curWaveCount;
}
res=f_readdir(&waveData.curDir,&waveData.curFile);
if (!waveData.curFile.fname[0] || waveData.curWaveCount>=MAX_BANK_WAVES)
break;
}
if(sort)
qsort(waveData.curWaveNames,waveData.curWaveCount,sizeof(waveData.curWaveNames[0]),stringCompare);
waveData.curWaveSorted=sort;
waveData.curWaveABX=abx;
strcpy(waveData.curWaveBank,fn);
#ifdef DEBUG
rprintf(0,"curWaveCount %d %d\n",abx,waveData.curWaveCount);
#endif
}
void refreshWaveforms(int8_t abx)
{
int i;
FIL f;
FRESULT res;
char fn[256];
int16_t data[WTOSC_MAX_SAMPLES];
int32_t d;
int32_t smpSize = 0;
strcpy(fn,WAVEDATA_PATH "/");
strcat(fn,currentPreset.oscBank[abx]);
strcat(fn,"/");
strcat(fn,currentPreset.oscWave[abx]);
#ifdef DEBUG
rprintf(0,"loading %s\n",fn);
#endif
if(!f_open(&f,fn,FA_READ))
{
if((res=f_lseek(&f,0x28)))
rprintf(0,"f_lseek res=%d\n",res);
if((res=f_read(&f,&smpSize,sizeof(smpSize),&i)))
rprintf(0,"f_read res=%d\n",res);
smpSize=MIN(smpSize,WTOSC_MAX_SAMPLES*2);
#ifdef DEBUG
rprintf(0, "smpSize %d\n", smpSize);
#endif
if((res=f_read(&f,data,smpSize,&i)))
rprintf(0,"f_read res=%d\n",res);
f_close(&f);
for(i=0;i<WTOSC_MAX_SAMPLES;++i)
{
d=data[i];
d=(d*(<API key>))>>15;
d-=INT16_MIN;
waveData.sampleData[abx][i]=d;
}
waveData.sampleCount[abx]=smpSize>>1;
}
// XOvr mix waveform
waveData.sampleCount[3]=MAX(waveData.sampleCount[0], waveData.sampleCount[2]);
synth.partState.oldCrossOver=-1;
}
static void handleBitInputs(void)
{
uint32_t cur;
static uint32_t last=0;
cur=GPIO_ReadValue(3);
// control footswitch
if(arp_getMode()==amOff && currentPreset.steppedParameters[spUnison] && !(cur&<API key>) && last&<API key>)
{
<API key>();
assigner_getPattern( currentPreset.voicePattern,NULL);
}
else if((cur&<API key>)!=(last&<API key>))
{
if(arp_getMode()!=amOff)
{
arp_setMode(arp_getMode(),(cur&<API key>)?0:1);
}
else
{
assigner_holdEvent((cur&<API key>)?0:1);
}
}
// this must stay last
last=cur;
}
// Speed critical internal code
static inline void computeGlide(uint16_t * out, const uint16_t target, const uint16_t amount)
{
uint16_t diff;
if(*out<target)
{
diff=target-*out;
*out+=MIN(amount,diff);
}
else if(*out>target)
{
diff=*out-target;
*out-=MIN(amount,diff);
}
}
static FORCEINLINE uint16_t adjustCV(cv_t cv, uint32_t value)
{
switch(cv)
{
case cvCutoff:
value=UINT16_MAX-value;
break;
case cvAmp:
value=(6*value)/16; // limit VCA output level to 4Vpp
value=computeShape(value<<8,<API key>,1);
break;
case cvNoiseVol:
value=computeShape(value<<8,<API key>,1);
break;
default:
;
}
return value;
}
static FORCEINLINE void refreshCV(int8_t voice, cv_t cv, uint32_t v)
{
uint16_t value,channel;
v=__USAT(v,16);
value=adjustCV(cv,v);
switch(cv)
{
case cvAmp:
channel=voice;
break;
case cvNoiseVol:
channel=6;
break;
case cvResonance:
channel=7;
break;
case cvCutoff:
channel=voice+8;
break;
case cvAVol:
channel=14;
break;
case cvBVol:
channel=15;
break;
default:
return;
}
dacspi_setCVValue(channel,value);
}
static void refreshCrossOver(int32_t wmod, int32_t wmodEnvAmt)
{
int i;
int8_t v;
uint32_t xovr;
uint16_t *p0,*p2,*p3;
xovr=wmod;
// paraphonic filter envelope mod
if(currentPreset.steppedParameters[spAWModEnvEn])
{
v=<API key>(NULL);
if(v>=0)
{
xovr+=scaleU16S16(synth.filEnvs[v].output,wmodEnvAmt)<<1;
xovr=__USAT(xovr,16);
}
}
if(xovr==synth.partState.oldCrossOver)
return;
p0=waveData.sampleData[0];
p2=waveData.sampleData[2];
p3=waveData.sampleData[3];
for(i=0;i<WTOSC_MAX_SAMPLES/4;++i)
{
*p3++=lerp16(*p0++,*p2++,xovr);
*p3++=lerp16(*p0++,*p2++,xovr);
*p3++=lerp16(*p0++,*p2++,xovr);
*p3++=lerp16(*p0++,*p2++,xovr);
}
synth.partState.oldCrossOver=xovr;
}
static FORCEINLINE void refreshVoice(int8_t v,int32_t wmodEnvAmt,int32_t filEnvAmt,int32_t pitchAVal,int32_t pitchBVal,int32_t wmodAVal,int32_t wmodBVal,int32_t filterVal,int32_t ampVal,uint8_t wmodMask)
{
int32_t vpa,vpb,vma,vmb,vf,vamp,envVal,envValScale;
// envs
adsr_update(&synth.ampEnvs[v]);
adsr_update(&synth.filEnvs[v]);
envVal=synth.filEnvs[v].output;
// filter
vf=filterVal;
vf+=scaleU16S16(envVal,filEnvAmt);
vf+=synth.filterNoteCV[v];
refreshCV(v,cvCutoff,vf);
// oscs
envValScale=scaleU16S16(envVal,wmodEnvAmt);
vma=wmodAVal;
if(wmodMask&8)
{
vma+=envValScale;
vma=__USAT(vma,16);
}
vmb=wmodBVal;
if(wmodMask&128)
{
vmb+=envValScale;
vmb=__USAT(vmb,16);
}
vpa=pitchAVal;
if(wmodMask&4)
vpa+=vma-HALF_RANGE;
vpb=pitchBVal;
if(wmodMask&64)
vpb+=vmb-HALF_RANGE;
// osc A
vpa+=synth.oscANoteCV[v];
vpa=__USAT(vpa,16);
wtosc_setParameters(&synth.osc[v][0],vpa,(wmodMask&1)?vma:0,(wmodMask&2)?vma:HALF_RANGE);
// osc B
vpb+=synth.oscBNoteCV[v];
vpb=__USAT(vpb,16);
wtosc_setParameters(&synth.osc[v][1],vpb,(wmodMask&16)?vmb:0,(wmodMask&32)?vmb:HALF_RANGE);
// amplifier
vamp=scaleU16U16(synth.ampEnvs[v].output,ampVal);
refreshCV(v,cvAmp,vamp);
}
// Synth main code
void synth_init(void)
{
int i;
memset(&synth,0,sizeof(synth));
memset(&waveData,0,sizeof(waveData));
waveData.bankSorted=-1;
waveData.curWaveSorted=-1;
waveData.curWaveABX=-1;
// init footswitch in
GPIO_SetDir(3,1<<26,0);
<API key>(3,26,<API key>);
<API key>(3,26,<API key>);
// init wavetable oscs
for(i=0;i<SYNTH_VOICE_COUNT;++i)
{
wtosc_init(&synth.osc[i][0],i*2);
wtosc_init(&synth.osc[i][1],i*2+1);
}
// give it some memory
waveData.curFile.lfname=waveData.lfname;
waveData.curFile.lfsize=sizeof(waveData.lfname);
for(i=0;i<4;++i)
waveData.sampleCount[i]=WTOSC_MAX_SAMPLES;
// init subsystems
// ui_init() done in main.c
dacspi_init();
scan_init();
tuner_init();
assigner_init();
uartMidi_init();
seq_init();
arp_init();
midi_init();
for(i=0;i<SYNTH_VOICE_COUNT;++i)
{
adsr_init(&synth.ampEnvs[i]);
adsr_init(&synth.filEnvs[i]);
adsr_setShape(&synth.ampEnvs[i],1);
adsr_setShape(&synth.filEnvs[i],1);
}
lfo_init(&synth.lfo[0]);
lfo_init(&synth.lfo[1]);
// load settings from storage; tune when they are bad
if(!settings_load())
{
<API key>();
tuner_tuneSynth();
}
__enable_irq();
refreshBankNames(1);
// upgrade presets from before storing bank/wave names
<API key>();
// load last preset & do a full refresh
if(!preset_loadCurrent(settings.presetNumber))
preset_loadDefault(1);
<API key>(0);
refreshFullState();
refreshWaveforms(0);
refreshWaveforms(1);
refreshWaveforms(2);
}
void synth_update(void)
{
#if 0
putc_serial0('.');
#else
static int32_t frc=0,prevTick=0;
++frc;
if(<API key>>TICKER_1S)
{
rprintf(0,"%d u/s\n",frc);
frc=0;
prevTick=currentTick;
}
#endif
scan_update();
ui_update();
refreshLfoSettings();
synth.partState.syncResetsMask=currentPreset.steppedParameters[spOscSync]?UINT32_MAX:0;
}
// Synth interrupts
// @ 500Hz from system timer
void <API key>(void)
{
int32_t resVal,resoFactor;
resVal=currentPreset.<API key>[cpResonance];
resVal+=scaleU16S16(currentPreset.<API key>[cpLFOResAmt],synth.lfo[0].output);
resVal+=scaleU16S16(currentPreset.<API key>[cpLFO2ResAmt],synth.lfo[1].output);
resVal=__USAT(resVal,16);
// compensate pre filter mixer level for resonance
resoFactor=(30*UINT16_MAX+110*(uint32_t)MAX(0,resVal-6000))/(100*256);
// CV update
refreshCV(-1,cvAVol,(uint32_t)currentPreset.<API key>[cpAVol]*resoFactor/256);
refreshCV(-1,cvBVol,(uint32_t)currentPreset.<API key>[cpBVol]*resoFactor/256);
refreshCV(-1,cvNoiseVol,(uint32_t)currentPreset.<API key>[cpNoiseVol]*resoFactor/256);
refreshCV(-1,cvResonance,resVal);
// midi
midi_update();
// crossover
if(currentPreset.steppedParameters[spAWModType]==wmCrossOver)
refreshCrossOver(synth.wmodAVal,synth.wmodEnvAmt);
// bit inputs (footswitch / tape in)
handleBitInputs();
// assigner
<API key>();
// clocking
if(settings.syncMode==smInternal || synth.pendingExtClock)
{
if(synth.pendingExtClock)
--synth.pendingExtClock;
if (clock_update())
{
// sequencer
if(seq_getMode(0)!=smOff || seq_getMode(1)!=smOff)
seq_update();
// arpeggiator
if(arp_getMode()!=amOff)
arp_update();
}
}
// glide
for(int8_t v=0;v<SYNTH_VOICE_COUNT;++v)
{
int16_t amt=synth.partState.glideAmount;
if(synth.partState.gliding)
{
computeGlide(&synth.oscANoteCV[v],synth.oscATargetCV[v],amt);
computeGlide(&synth.oscBNoteCV[v],synth.oscBTargetCV[v],amt);
computeGlide(&synth.filterNoteCV[v],synth.filterTargetCV[v],amt);
}
}
// 500hz tick counter
++currentTick;
}
// Synth internal events
// @ 3Khz from dacspi CV update
void <API key>(void)
{
int32_t val,pitchAVal,pitchBVal,wmodAVal,wmodBVal,filterVal,ampVal,wmodEnvAmt,filEnvAmt;
// lfos
lfo_update(&synth.lfo[0]);
lfo_update(&synth.lfo[1]);
// global computations
// pitch
pitchAVal=pitchBVal=0;
val=scaleU16S16(currentPreset.<API key>[cpLFOPitchAmt],synth.lfo[0].output>>1);
if(currentPreset.steppedParameters[spLFOTargets]&otA)
pitchAVal+=val;
if(currentPreset.steppedParameters[spLFOTargets]&otB)
pitchBVal+=val;
val=scaleU16S16(currentPreset.<API key>[cpLFO2PitchAmt],synth.lfo[1].output>>1);
if(currentPreset.steppedParameters[spLFO2Targets]&otA)
pitchAVal+=val;
if(currentPreset.steppedParameters[spLFO2Targets]&otB)
pitchBVal+=val;
// filter
filterVal=scaleU16S16(currentPreset.<API key>[cpLFOFilAmt],synth.lfo[0].output);
filterVal+=scaleU16S16(currentPreset.<API key>[cpLFO2FilAmt],synth.lfo[1].output);
// amplifier
ampVal=synth.partState.benderCVs[cvAmp]+UINT16_MAX;
ampVal-=scaleU16U16(currentPreset.<API key>[cpLFOAmpAmt],synth.lfo[0].levelCV>>1);
ampVal+=scaleU16S16(currentPreset.<API key>[cpLFOAmpAmt],synth.lfo[0].output);
ampVal-=scaleU16U16(currentPreset.<API key>[cpLFO2AmpAmt],synth.lfo[1].levelCV>>1);
ampVal+=scaleU16S16(currentPreset.<API key>[cpLFO2AmpAmt],synth.lfo[1].output);
// misc
filEnvAmt=currentPreset.<API key>[cpFilEnvAmt];
filEnvAmt+=INT16_MIN;
wmodAVal=currentPreset.<API key>[cpABaseWMod];
if(currentPreset.steppedParameters[spLFOTargets]&otA)
wmodAVal+=scaleU16S16(currentPreset.<API key>[cpLFOWModAmt],synth.lfo[0].output);
if(currentPreset.steppedParameters[spLFO2Targets]&otA)
wmodAVal+=scaleU16S16(currentPreset.<API key>[cpLFO2WModAmt],synth.lfo[1].output);
wmodBVal=currentPreset.<API key>[cpBBaseWMod];
if(currentPreset.steppedParameters[spLFOTargets]&otB)
wmodBVal+=scaleU16S16(currentPreset.<API key>[cpLFOWModAmt],synth.lfo[0].output);
if(currentPreset.steppedParameters[spLFO2Targets]&otB)
wmodBVal+=scaleU16S16(currentPreset.<API key>[cpLFO2WModAmt],synth.lfo[1].output);
wmodEnvAmt=currentPreset.<API key>[cpWModFilEnv];
wmodEnvAmt+=INT16_MIN;
// restrict range
pitchAVal=__SSAT(pitchAVal,16);
pitchBVal=__SSAT(pitchBVal,16);
wmodAVal=__USAT(wmodAVal,16);
wmodBVal=__USAT(wmodBVal,16);
filterVal=__SSAT(filterVal,16);
ampVal=__USAT(ampVal,16);
// voices computations
for(int8_t v=0;v<SYNTH_VOICE_COUNT;++v)
refreshVoice(v,wmodEnvAmt,filEnvAmt,pitchAVal,pitchBVal,wmodAVal,wmodBVal,filterVal,ampVal,synth.partState.wmodMask);
synth.wmodAVal=wmodAVal;
synth.wmodEnvAmt=wmodEnvAmt;
}
#define <API key>(v) \
FORCEINLINE static void updateDACsVoice##v(int32_t start, int32_t end) \
{ \
uint32_t syncResets; /* /!\ this won't work if count > 32 */ \
wtosc_update(&synth.osc[v][0],start,end,osmMaster,&syncResets); \
syncResets&=synth.partState.syncResetsMask; \
wtosc_update(&synth.osc[v][1],start,end,osmSlave,&syncResets); \
}
<API key>(0);
<API key>(1);
<API key>(2);
<API key>(3);
<API key>(4);
<API key>(5);
void <API key>(int32_t start, int32_t count)
{
int32_t end=start+count-1;
updateDACsVoice0(start,end);
updateDACsVoice1(start,end);
updateDACsVoice2(start,end);
updateDACsVoice3(start,end);
updateDACsVoice4(start,end);
updateDACsVoice5(start,end);
}
void synth_assignerEvent(uint8_t note, int8_t gate, int8_t voice, uint16_t velocity, int8_t flags)
{
#ifdef DEBUG_
rprintf(0,"assign note %d gate %d voice %d velocity %d flags %d\n",note,gate,voice,velocity,flags);
#endif
uint16_t velAmt;
// mod delay
<API key>(0);
// prepare CVs
computeTunedCVs();
// set gates (don't retrigger gate, unless we're arpeggiating)
if(!(flags&<API key>) || arp_getMode()!=amOff)
{
adsr_setGate(&synth.filEnvs[voice],gate);
adsr_setGate(&synth.ampEnvs[voice],gate);
}
if(gate)
// handle velocity
{
velAmt=currentPreset.<API key>[cpFilVelocity];
adsr_setCVs(&synth.filEnvs[voice],0,0,0,0,(UINT16_MAX-velAmt)+scaleU16U16(velocity,velAmt),0x10);
velAmt=currentPreset.<API key>[cpAmpVelocity];
adsr_setCVs(&synth.ampEnvs[voice],0,0,0,0,(UINT16_MAX-velAmt)+scaleU16U16(velocity,velAmt),0x10);
}
// stolen voices must be entirely reset
else if(flags&<API key>)
{
adsr_reset(&synth.filEnvs[voice]);
adsr_reset(&synth.ampEnvs[voice]);
}
}
void synth_uartEvent(uint8_t data)
{
#ifdef DEBUG_
rprintf(0,"midi %x\n",data);
#endif
midi_newData(data);
}
void synth_wheelEvent(int16_t bend, uint16_t modulation, uint8_t mask)
{
#ifdef DEBUG_
rprintf(0,"wheel bend %d mod %d mask %d\n",bend,modulation,mask);
#endif
if(mask&1)
{
synth.partState.benderAmount=bend;
computeBenderCVs();
computeTunedCVs();
}
if(mask&2)
{
synth.partState.modwheelAmount=modulation;
refreshLfoSettings();
}
}
void synth_realtimeEvent(uint8_t midiEvent)
{
if(settings.syncMode!=smMIDI)
return;
switch(midiEvent)
{
case MIDI_CLOCK:
++synth.pendingExtClock;
break;
case MIDI_START:
seq_resetCounter(0,0);
seq_resetCounter(1,0);
arp_resetCounter(0);
clock_reset(); // always do a beat reset on MIDI START
synth.pendingExtClock=0;
break;
case MIDI_STOP:
seq_silence(0);
seq_silence(1);
break;
}
} |
from django.db.models import Model, CharField, DateField, URLField, \
DateTimeField, TextField, ForeignKey, permalink, IntegerField
from taggit.managers import TaggableManager
from django.contrib.auth.models import User
class Conference(Model):
title = CharField(max_length=300)
start_date = DateField('conference start date')
end_date = DateField('conference end date')
city = CharField(max_length=300)
state = CharField(max_length=300, help_text="State / Province / District")
country = CharField(max_length=300, default="USA")
conference_home_url = URLField()
tags = TaggableManager(blank=True)
short_name = CharField(max_length=30, blank=True)
twitter_hashtag = CharField(max_length=30, blank=True)
<API key> = IntegerField(editable=False, blank=True)
created = DateTimeField(auto_now_add=True)
updated = DateTimeField(auto_now=True)
@property
def name(self):
return self.title
def __unicode__(self):
return self.title
@permalink
def get_absolute_url(self):
return ('conference_detail', [self.pk])
class Talk(Model):
type_choices = (('workshop', 'Workshop'),
('presentation', 'Presentation'),
('poster', 'Poster Presentation'),
('panel', 'Panel Discussion'))
title = CharField(max_length=300)
type = CharField(max_length=12, choices=type_choices)
description = TextField(blank=True)
tags = TaggableManager(blank=True)
created = DateTimeField(auto_now_add=True)
updated = DateTimeField(auto_now=True)
user = ForeignKey(User, editable=False)
@property
def name(self):
return self.title
def __unicode__(self):
return self.title
@permalink
def get_absolute_url(self):
return ('index', None)
@permalink
def edit_view(self):
return ('edit_talk', [self.pk])
class Appearance(Model):
talk = ForeignKey(Talk)
conference = ForeignKey(Conference)
date = DateField('presentation date')
authors = TextField()
created = DateTimeField(auto_now_add=True)
updated = DateTimeField(auto_now=True)
@property
def name(self):
return '-'.join(
[self.talk.title, str(self.date)])
def __unicode__(self):
return self.name
@permalink
def get_absolute_url(self):
return ('appearance_detail', [self.pk])
class Resource(Model):
talk = ForeignKey(Talk)
title = CharField(max_length=300)
description = TextField()
url = URLField()
tags = TaggableManager()
created = DateTimeField(auto_now_add=True)
updated = DateTimeField(auto_now=True)
@property
def name(self):
return self.title
def __unicode__(self):
return self.title
@permalink
def get_absolute_url(self):
return ('resource_detail', [self.pk]) |
<div class="padding20 block-shadow">
<form name="vm.userForm" ng-submit="vm.signin(vm.userForm.$valid)" class="signin form-horizontal" novalidate autocomplete="off" data-role="validator">
<h1 class="text-light">Masuk idHotspot</h1>
<hr class="thin"/>
<br/>
<div class="row align-center flex-just-center">
<button class="image-button bg-darkBlue fg-white" ng-click="vm.callOauthProvider('/api/auth/facebook')">
Masuk dengan akun Facebook
<span class="icon mif-facebook bg-darkBlue"></span>
</button>
</div>
<div class="row align-center flex-just-center">
<span>or</span>
</div>
<div class="input-control modern text iconic">
<input type="text" id="username" name="username" ng-model="vm.credentials.username" lowercase required>
<span class="label">Username</span>
<span class="informer">Silahkan masukkan username</span>
<span class="placeholder">Username</span>
<span class="icon mif-user"></span>
</div>
<br />
<div class="input-control modern password iconic" data-role="input">
<input type="password" id="password" name="password" ng-model="vm.credentials.password" required>
<span class="label">Sandi</span>
<span class="informer">Silahkan masukkan sandi</span>
<span class="placeholder">Sandi</span>
<span class="icon mif-lock"></span>
<button class="button helper-button reveal"><span class="mif-looks"></span></button>
</div>
<br />
<br />
<div class="form-actions align-center">
<button type="submit" class="button primary">Masuk</button>
</div>
<uib-alert type="danger" ng-show="vm.error" class="padding10 align-center fg-crimson">
<span ng-bind="vm.error"></span>
</uib-alert>
</form>
<div class="fb-ad" data-placementid="<API key>" data-format="300x250" data-testmode="true"></div>
</div> |
package TUIO6dof;
import remixlab.tersehandling.generic.profile.Actionable;
public enum ClickAction implements Actionable<GlobalAction> {
CHANGE_COLOR(GlobalAction.CHANGE_COLOR), CHANGE_ROTATION(
GlobalAction.CHANGE_ROTATION), <API key>(
GlobalAction.<API key>);
@Override
public GlobalAction referenceAction() {
return act;
}
@Override
public String description() {
return "A simple click action";
}
public boolean is2D() {
return true;
}
@Override
public int dofs() {
return 0;
}
GlobalAction act;
ClickAction(GlobalAction a) {
act = a;
}
} |
package biomine.bmgraph;
import java.io.File;
import java.io.<API key>;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.PriorityQueue;
import biomine.bmgraph.read.BMGraphReader;
import biomine.bmgraph.write.BMGraphWriter;
/**
* BMGraphUtils. Helpers for working with BMGraph graphs.
*/
public class BMGraphUtils {
/**
* Read a file specified by name into a new BMGraph.
* <p>Note: No exception handling is done in this helper.
* @param filename The name/path of the BMGraph file.
* @return A new BMGraph, or null in case of failure.
*/
public static BMGraph readBMGraph (String filename)
throws <API key> {
assert filename != null : "Null filename";
BMGraphReader reader = new BMGraphReader();
return reader.parseFile(filename) ? reader.getGraph() : null;
}
/**
* Read a file specified by a File object into a new BMGraph.
* @param File The File object of the BMGraph file.
* @return A new BMGraph, or null in case of failure.
*/
public static BMGraph readBMGraph (File file) {
assert file != null : "Null file";
BMGraphReader reader = new BMGraphReader();
return reader.parseFile(file) ? reader.getGraph() : null;
}
/**
* Read a new BMGraph from an InputStream.
* @param stream The InputStream from which the graph is read.
* @return A new BMGraph, or null in case of failure.
*/
public static BMGraph readBMGraph (InputStream stream) {
assert stream != null : "Null stream";
BMGraphReader reader = new BMGraphReader();
return reader.parseStream(stream, null) ? reader.getGraph() : null;
}
/**
* Find an edge between two nodes in a BMGraph.
*
* <p>The search is undirected in the sense that if an edge exists
* between the parameter nodes it is found regardless of its
* direction or the order of the parameters.
*
* <p>In case there are multiple edges between the given nodes, any
* one of these edges may be returned (it is NOT guaranteed to be any
* particular edge; this may or may not be completely undeterministic,
* and may change without any notification).
*
* @param graph The BMGraph in which to find the edge.
* @param node1 The first BMNode.
* @param node2 The second BMNode.
* @return A BMEdge representing an edge found between the two nodes
* in the given graph, or null if none found. UNDETERMINTISTIC!
*/
public static BMEdge findEdge (BMGraph graph, BMNode node1, BMNode node2) {
assert graph != null : "Null graph";
assert node1 != null : "Null node 1";
assert node2 != null : "Null node 2";
// Find the node with fewer edges and search those for a match
List<BMEdge> edges = graph.getNodeEdges(node1);
List<BMEdge> edges2 = graph.getNodeEdges(node2);
if (edges.size() > edges2.size()) {
// Use the list with fewer edges
BMNode tmp = node1;
node1 = node2;
node2 = tmp;
edges = edges2;
}
for (BMEdge edge : edges) {
if (edge.otherNode(node1) == node2)
return edge;
}
return null;
}
/**
* Find all edges between two nodes in a BMGraph.
*
* <p>The search is undirected in the sense that if an edge exists
* between the parameter nodes it is found regardless of its
* direction or the order of the parameters.
*
* <p>In case there are multiple edges between the given nodes, all
* of these edges are returned.
*
* @param graph The BMGraph in which to find the edge.
* @param node1 The first BMNode.
* @param node2 The second BMNode.
* @return A list of BMEdges containing all edges found between
* the two nodes in the given graph, or null if no edge were found.
*/
public static List<BMEdge> findEdges (BMGraph graph, BMNode node1,
BMNode node2) {
assert graph != null : "Null graph";
assert node1 != null : "Null node 1";
assert node2 != null : "Null node 2";
// Find the node with fewer edges and search those for a match
List<BMEdge> edges = graph.getNodeEdges(node1);
List<BMEdge> edges2 = graph.getNodeEdges(node2);
if (edges.size() > edges2.size()) {
// Use the list with fewer edges
BMNode tmp = node1;
node1 = node2;
node2 = tmp;
edges = edges2;
}
List<BMEdge> edgelist = new ArrayList<BMEdge>();
for (BMEdge edge : edges) {
if (edge.otherNode(node1) == node2) {
edgelist.add(edge);
}
}
return edgelist.isEmpty() ? null : edgelist;
}
/**
* Writes the given BMGraph to a file specified by name.
* @param graph The BMGraph to write.
* @param file The filename/path of the file to write the BMGraph into.
*/
public static void writeBMGraph (BMGraph graph, String file) throws IOException {
assert graph != null : "Null graph";
assert file != null : "Null file";
assert file.length() != 0 : "Empty filename";
FileOutputStream fos = new FileOutputStream(file);
BMGraphWriter bmGraphWriter = new BMGraphWriter(graph, fos);
bmGraphWriter.writeSorted(true);
fos.close();
}
/**
* Writes the given BMGraph to a file specified by File object.
* @param graph The BMGraph to write.
* @param file The File object representing the file in which to write the
* BMGraph.
*/
public static void writeBMGraph (BMGraph graph, File file) throws IOException {
assert graph != null : "Null graph";
assert file != null : "Null file";
FileOutputStream fos = new FileOutputStream(file);
BMGraphWriter bmGraphWriter = new BMGraphWriter(graph, fos);
bmGraphWriter.writeSorted(true);
fos.close();
}
/**
* Writes the given BMGraph to an OutputStream, without closing it.
* @param graph The BMGraph to write.
* @param stream The OutputStream in which to write the graph (the
* stream is NOT closed after writing).
*/
public static void writeBMGraph (BMGraph graph, OutputStream stream) throws IOException {
assert graph != null : "Null graph";
assert stream != null : "Null stream";
BMGraphWriter bmGraphWriter = new BMGraphWriter(graph, stream);
bmGraphWriter.writeSorted(true);
}
/**
* Create a new, empty BMGraph using an existing BMGraph as
* a template for settings and metadata.
* @param graph The existing BMGraph to copy graph metadata from.
* @return A new BMGraph with no nodes or edges.
*/
public static BMGraph graphFromTemplate (BMGraph graph) {
assert graph != null : "Null graph";
BMGraph g = new BMGraph();
// DEBUG: Should regular (non-special) comments be copied?
g.createAttributeMaps = graph.createAttributeMaps;
g.database = graph.database.clone();
// Copy linktype definitions from template
g.canonicalDirections = new HashSet<String>(graph.canonicalDirections.size());
g.canonicalDirections.addAll(graph.canonicalDirections);
g.reverseLinktype = new HashMap<String, String>(graph.reverseLinktype.size(), 0.9f);
g.reverseLinktype.putAll(graph.reverseLinktype);
// Copy special comments (complicated, since they can be either
// Sets or Maps, and we don't want to recycle the same instances
// in case the original graph is modified).
g.<API key>(graph);
return g;
}
/**
* Finds "inbound" and "outbound" goodness for each vertex in graph.
* For a vertex v in graph, the outbound goodness of v is the sum of
* goodness values of all edges adjacent to v in supergraph but
* not in graph. The inbound goodness of v is the sum of goodness values
* of all edges adjacent to v in graph. Any numeric attribute can be used
* (see parameter goodnessAttribute).
* <p>
* Calculated outbound goodness values are added to "output_goodness"
* vertex attributes. Inbound goodness values are added to
* "inbound_goodness" vertex attributes. Here _goodness will be replaced
* by goodnessAttribute; for example, if goodnessAttribute = "reliability",
* added attributes will be "inbound_reliability" and
* "<API key>".
* <p>
* Any supergraph edges that have both endpoints in graph are silently
* ignored.
*
* @param graph graph for which adjancent goodness is calculated
* @param supergraph supergraph of graph
* @param goodnessAttribute use the value of this edge attribute as goodness
*/
public static void <API key>(BMGraph graph,
BMGraph supergraph, String goodnessAttribute) {
for (BMNode n : graph.getNodes()) {
double inpr = 0.0;
double outpr = 0.0;
for (BMEdge e : supergraph.getNodeEdges(n)) {
double goodness = Double.parseDouble(e.get(goodnessAttribute));
if (graph.hasEdge(e)) {
inpr += goodness;
continue;
}
if (graph.hasNode(e.getSource())
&& graph.hasNode(e.getTarget())) {
continue;
}
outpr += goodness;
}
n.put("outbound_ " + goodnessAttribute, String.valueOf(outpr));
n.put("inbound_" + goodnessAttribute, String.valueOf(inpr));
}
}
/**
* Convert BMGraph to a random walk matrix.
*
* Random walk can be restarting or non-restarting. If restartProbability
* is greater than zero, the walk is restarted to startNode with that
* probability at each node. If <API key> is non-null,
* each node u that has such attribute with value pr is assumed to have
* edge (u, startNode) with probability pr.
* <p>
* Node-to-index and index-to-node mappings are recorded to the given
* map references. Note that both maps will be cleared.
*
* @param graph BMGraph where the random walk is done.
* @param startNode Starting node for the walk.
* @param restartProbability Global restart probability (for random walk
* with restart).
* @param <API key> Node attribute name for transition
* probability.
* @param <API key> Node attribute name for node-specific
* restart probability.
* @param nodeToIndexMap Mapping from node set to state set.
* @param indexToNodeMap Mapping from state set to node set.
* @return Stochastic adjacency matrix, where M[i][j] is the transition
* probability from state i to j.
*/
public static double[][] convertToRWMatrix(
BMGraph graph,
BMNode startNode,
double restartProbability,
String <API key>,
String <API key>,
Map<BMNode, Integer> nodeToIndexMap,
Map<Integer, BMNode> indexToNodeMap) {
int N = graph.numNodes();
double[][] M = new double[N][N];
// create indexes
nodeToIndexMap.clear();
indexToNodeMap.clear();
int i = 0;
for (BMNode n : graph.getNodes()) {
nodeToIndexMap.put(n, i);
indexToNodeMap.put(i, n);
i++;
}
// create adjacency matrix, one row at a time
for (i = 0; i < N; i++) {
BMNode u = indexToNodeMap.get(i);
// calculate total (normalization) probability
// first go through neighbors
// add also neighbors' indices to a priority queue for later use
double totalPr = 0.0;
List<BMNode> neighbors = graph.getNeighbors(u);
PriorityQueue<Integer> neighborIds = new PriorityQueue<Integer>();
for (BMNode v : neighbors) {
int k = nodeToIndexMap.get(v);
neighborIds.add(k);
List<BMEdge> edges = BMGraphUtils.findEdges(graph, u, v);
for (BMEdge e : edges) {
totalPr += Double.parseDouble
(e.get(<API key>));
}
}
// check for restart probability attribute
double nodeRestartPr = 0.0;
if (<API key> != null) {
String nodeRestartValue = u.get(<API key>);
if (nodeRestartValue != null) {
nodeRestartPr = Double.parseDouble(nodeRestartValue);
}
}
totalPr += nodeRestartPr;
double edgePr;
boolean restartDone = false;
for (BMNode v : neighbors) {
int k = nodeToIndexMap.get(v);
// fill M[i][k]
edgePr = 0.0;
List<BMEdge> edges = BMGraphUtils.findEdges
(graph, indexToNodeMap.get(i),
indexToNodeMap.get(k));
for (BMEdge e : edges) {
edgePr += Double.parseDouble
(e.get(<API key>));
}
double transitionPr;
if (v.equals(startNode)) {
edgePr += nodeRestartPr;
transitionPr = restartProbability
+ (1 - restartProbability) * edgePr / totalPr;
restartDone = true;
} else {
transitionPr = (1 - restartProbability) * edgePr / totalPr;
}
M[i][k] = transitionPr;
}
int j = 0;
while (j < N) {
// fill M[i][j..k-1] with zeros, where k is the index
// of next neighboring node
int k = neighborIds.isEmpty() ? N : neighborIds.poll();
while (j < k) {
M[i][j] = 0.0;
j++;
}
j++;
}
// fill restart transition probability, if needed
if (!restartDone) {
int k = nodeToIndexMap.get(startNode);
M[i][k] = restartProbability
+ (1 - restartProbability) * nodeRestartPr / totalPr;
}
}
return M;
}
} |
<?php
// Poster Printer Order Submission
// index.php
// Page to allow the user to submit poster files
// David Slater
// April 2007
//include files for the script to run
require_once 'includes/main.inc.php';
require_once 'includes/session.inc.php';
if (isset($_POST['cancel'])) {
$session->destroy_session();
header('Location: index.php');
}
require_once 'includes/header.inc.php';
?>
<form action='' method='post' id='posterInfo' name='posterInfo'>
<fieldset id='poster_field'>
<input type='hidden' name='session' id='session' value='<?php echo $session->get_session_id(); ?>'>
<div class='row'>
<table class='table table-bordered table-sm'>
<thead>
<tr><th colspan='2'>Paper Size</th></tr>
<tr><td colspan='2'><em>Please choose a width and length for your poster. The maximum width is <?php echo poster::<API key>($db); ?> inches.</em></td></tr>
</thead>
<tr><td class='text-right' style='vertical-align:middle;'>Width:</td>
<td class='left'>
<div class='input-group col-md-5'><input class='form-control' text='text' name='width' id='width' maxlength='6' size='6'><div class='input-group-append'><span class='input-group-text'> Inches</span></div></div></td></tr>
<tr><td class='text-right' style='vertical-align:middle;'>Length:</td>
<td class='left'>
<div class='input-group col-md-5'><input class='form-control' type='text' name='length' id='length' maxlength='6' size='6'><div class='input-group-append'><span class='input-group-text'> Inches</span></div></div></td></tr>
</table>
</div>
<div class='row'>
<div class='mx-auto btn-toolbar'>
<p><button class='btn btn-warning' type='submit' name='cancel'>Cancel</button>
<button class='btn btn-primary' type='submit' name='step1' onClick='first_step()'>Next</button>
</p>
</div>
</div>
</fieldset>
</form>
<div id='message'>
<?php if (isset($message)) { echo $message; } ?>
</div>
<?php require_once 'includes/footer.inc.php'; ?> |
import uuid
from django.db import models
from django.core.mail.message import EmailMessage
from django.conf import settings
from tendenci.apps.perms.models import TendenciBaseModel
from tinymce import models as tinymce_models
from tendenci.apps.site_settings.utils import get_setting
class Email(TendenciBaseModel):
guid = models.CharField(max_length=50)
priority = models.IntegerField(default=0)
subject =models.CharField(max_length=255)
body = tinymce_models.HTMLField()
#body = models.TextField()
sender = models.CharField(max_length=255)
sender_display = models.CharField(max_length=255)
reply_to = models.CharField(max_length=255)
recipient = models.CharField(max_length=255, blank=True, default='')
recipient_dispaly = models.CharField(max_length=255, blank=True, default='')
recipient_cc = models.CharField(max_length=255, blank=True, default='')
<API key> = models.CharField(max_length=255, blank=True, default='')
recipient_bcc = models.CharField(max_length=255, blank=True, default='')
attachments = models.CharField(max_length=500, blank=True, default='')
content_type = models.CharField(max_length=255, default='text/html', choices=(('text/html','text/html'),('text','text'),))
#create_dt = models.DateTimeField(auto_now_add=True)
#status = models.NullBooleanField(default=True, choices=((True,'Active'),(False,'Inactive'),))
class Meta:
app_label = 'emails'
@models.permalink
def get_absolute_url(self):
return ("email.view", [self.pk])
def __unicode__(self):
return self.subject
def send(self, fail_silently=False, **kwargs):
recipient_list = []
recipient_bcc_list = []
headers = kwargs.get('headers', {})
attachments = kwargs.get('attachments', [])
if isinstance(self.recipient, basestring):
recipient_list = self.recipient.split(',')
recipient_list = [recipient.strip() for recipient in recipient_list \
if recipient.strip() <> '']
else:
recipient_list = list(self.recipient)
if isinstance(self.recipient_cc, basestring):
recipient_cc_list = self.recipient_cc.split(',')
recipient_cc_list = [recipient_cc.strip() for recipient_cc in recipient_cc_list if \
recipient_cc.strip() <> '']
recipient_list += recipient_cc_list
else:
recipient_list += list(self.recipient_cc)
if isinstance(self.recipient_bcc, basestring):
recipient_bcc_list = self.recipient_bcc.split(',')
recipient_bcc_list = [recipient_bcc.strip() for recipient_bcc in recipient_bcc_list if \
recipient_bcc.strip() <> '']
else:
recipient_bcc_list = list(self.recipient_bcc)
if self.reply_to:
headers['Reply-To'] = self.reply_to
if not self.sender:
self.sender = get_setting('site', 'global', '<API key>') or settings.DEFAULT_FROM_EMAIL
if self.sender_display:
headers['From'] = '%s<%s>' % (self.sender_display, self.sender)
if self.priority and self.priority == 1:
headers['X-Priority'] = '1'
headers['X-MSMail-Priority'] = 'High'
if recipient_list or recipient_bcc_list:
msg = EmailMessage(self.subject,
self.body,
self.sender,
recipient_list,
recipient_bcc_list,
headers=headers,
connection=kwargs.get('connection', None))
if self.content_type == 'html' or self.content_type == 'text/html':
msg.content_subtype = 'html'
if attachments:
msg.attachments = attachments
msg.send(fail_silently=fail_silently)
def save(self, user=None, *args, **kwargs):
if not self.id:
self.guid = uuid.uuid1()
if user and not user.is_anonymous():
self.creator=user
self.creator_username=user.username
if user and not user.is_anonymous():
self.owner=user
self.owner_username=user.username
super(Email, self).save(*args, **kwargs)
# if this email allows view by user2_compare
def allow_view_by(self, user2_compare):
boo = False
if user2_compare.profile.is_superuser:
boo = True
else:
if user2_compare == self.creator or user2_compare == self.owner:
if self.status:
boo = True
else:
if user2_compare.has_perm('emails.view_email', self):
if self.status == 1 and self.status_detail=='active':
boo = True
return boo
# if this email allows edit by user2_compare
def allow_edit_by(self, user2_compare):
boo = False
if user2_compare.profile.is_superuser:
boo = True
else:
if user2_compare == self.user:
boo = True
else:
if user2_compare == self.creator or user2_compare == self.owner:
if self.status:
boo = True
else:
if user2_compare.has_perm('emails.edit_email', self):
if self.status:
boo = True
return boo
def template_body(self, email_d):
"""
build the email body from the template and variables passed in by a dictionary
"""
import os.path
from django.template.loader import render_to_string
template = email_d.get('template_path_name', '')
# check if this template exists
boo = False
for dir in settings.TEMPLATE_DIRS:
if os.path.isfile(os.path.join(dir, template)):
boo = True
break
if not boo:
# log an event
# notify admin of missing template
pass
else:
self.body = render_to_string(template)
for key in email_d.keys():
# need to convert [blah] to %5Bblah%5D for replace line
tmp_value = "%5B" + key[1:-1] + "%5D"
if email_d[key] <> None:
self.body = self.body.replace(key, email_d[key])
self.body = self.body.replace(tmp_value, email_d[key])
else:
self.body = self.body.replace(key, '')
self.body = self.body.replace(tmp_value, '')
return boo |
package alfio.model.modification;
import alfio.model.PriceContainer.VatStatus;
import alfio.model.subscription.<API key>;
import alfio.model.subscription.<API key>.<API key>;
import alfio.model.subscription.<API key>.<API key>;
import alfio.model.subscription.<API key>.<API key>;
import alfio.model.transaction.PaymentProxy;
import alfio.util.MonetaryUtil;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import java.math.BigDecimal;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@Getter
public class <API key> {
private final UUID id;
private final Map<String, String> title;
private final Map<String, String> description;
private final Integer maxAvailable;
private final ZonedDateTime onSaleFrom;
private final ZonedDateTime onSaleTo;
private final BigDecimal price;
private final BigDecimal vat;
private final VatStatus vatStatus;
private final String currency;
private final Boolean isPublic;
private final int organizationId;
private final Integer maxEntries;
private final <API key> validityType;
private final <API key> validityTimeUnit;
private final Integer validityUnits;
private final ZonedDateTime validityFrom;
private final ZonedDateTime validityTo;
private final <API key> usageType;
private final String <API key>;
private final String privacyPolicyUrl;
private final String fileBlobId;
private final List<PaymentProxy> paymentProxies;
private final ZoneId timeZone;
public <API key>(@JsonProperty("id") UUID id,
@JsonProperty("title") Map<String, String> title,
@JsonProperty("description") Map<String, String> description,
@JsonProperty("maxAvailable") Integer maxAvailable,
@JsonProperty("onSaleFrom") ZonedDateTime onSaleFrom,
@JsonProperty("onSaleTo") ZonedDateTime onSaleTo,
@JsonProperty("price") BigDecimal price,
@JsonProperty("vat") BigDecimal vat,
@JsonProperty("vatStatus") VatStatus vatStatus,
@JsonProperty("currency") String currency,
@JsonProperty("isPublic") Boolean isPublic,
@JsonProperty("organizationId") int organizationId,
@JsonProperty("maxEntries") Integer maxEntries,
@JsonProperty("validityType") <API key> validityType,
@JsonProperty("validityTimeUnit") <API key> validityTimeUnit,
@JsonProperty("validityUnits") Integer validityUnits,
@JsonProperty("validityFrom") ZonedDateTime validityFrom,
@JsonProperty("validityTo") ZonedDateTime validityTo,
@JsonProperty("usageType") <API key> usageType,
@JsonProperty("<API key>") String <API key>,
@JsonProperty("privacyPolicyUrl") String privacyPolicyUrl,
@JsonProperty("fileBlobId") String fileBlobId,
@JsonProperty("paymentProxies") List<PaymentProxy> paymentProxies,
@JsonProperty("timeZone") ZoneId timeZone) {
this.id = id;
this.title = title;
this.description = description;
this.maxAvailable = maxAvailable;
this.onSaleFrom = onSaleFrom;
this.onSaleTo = onSaleTo;
this.price = price;
this.vat = vat;
this.vatStatus = vatStatus;
this.currency = currency;
this.isPublic = isPublic;
this.organizationId = organizationId;
this.maxEntries = maxEntries;
this.validityType = validityType;
this.validityTimeUnit = validityTimeUnit;
this.validityUnits = validityUnits;
this.validityFrom = validityFrom;
this.validityTo = validityTo;
this.usageType = usageType;
this.<API key> = <API key>;
this.privacyPolicyUrl = privacyPolicyUrl;
this.fileBlobId = fileBlobId;
this.paymentProxies = paymentProxies;
this.timeZone = timeZone;
}
public int getPriceCts() {
return MonetaryUtil.unitToCents(price, currency);
}
public <API key> <API key>() {
return <API key>.fromZonedDateTime(validityFrom);
}
public <API key> getValidityToModel() {
return <API key>.fromZonedDateTime(validityTo);
}
public <API key> getOnSaleFromModel() {
return <API key>.fromZonedDateTime(onSaleFrom);
}
public <API key> getOnSaleToModel() {
return <API key>.fromZonedDateTime(onSaleTo);
}
public String getPublicIdentifier() {
return getId().toString();
}
public static <API key> fromModel(<API key> <API key>) {
return new <API key>(
<API key>.getId(),
<API key>.getTitle(),
<API key>.getDescription(),
<API key>.getMaxAvailable(),
<API key>.getOnSaleFrom(),
<API key>.getOnSaleTo(),
MonetaryUtil.centsToUnit(<API key>.getPrice(), <API key>.getCurrency()),
<API key>.getVat(),
<API key>.getVatStatus(),
<API key>.getCurrency(),
<API key>.isPublic(),
<API key>.getOrganizationId(),
<API key>.getMaxEntries(),
<API key>.getValidityType(),
<API key>.getValidityTimeUnit(),
<API key>.getValidityUnits(),
<API key>.getValidityFrom(),
<API key>.getValidityTo(),
<API key>.getUsageType(),
<API key>.<API key>(),
<API key>.getPrivacyPolicyUrl(),
<API key>.getFileBlobId(),
<API key>.getPaymentProxies(),
<API key>.getZoneId());
}
} |
#include "image/handler/sparse.h"
namespace MR
{
namespace Image
{
namespace Handler
{
Sparse::Sparse (Default& handler, const std::string& sparse_class, const size_t sparse_size, const File::Entry entry) :
Default (handler),
class_name (sparse_class),
class_size (sparse_size),
file (entry),
data_end (0) { }
void Sparse::load()
{
Default::load();
std::fstream stream (file.name.c_str(), std::ios_base::in | std::ios_base::binary);
stream.seekg (0, std::ios::end);
const uint64_t file_size = stream.tellg();
stream.close();
const uint64_t <API key> = file_size - file.start;
if (<API key>) {
mmap.reset (new File::MMap (file, Base::writable, true, <API key>));
data_end = <API key>;
} else if (Base::writable) {
//CONF option: <API key>
//CONF default: 16777216
//CONF initial buffer size for data in MRtrix sparse image format file (in bytes).
// Default = initialise 16MB, this is enough to store whole-brain fixel data at 2.5mm resolution
const uint64_t <API key> = File::Config::get_int ("<API key>", 16777216);
const size_t new_file_size = file.start + <API key>;
DEBUG ("Initialising output sparse data file " + file.name + ": new file size " + str(new_file_size) + " (" + str(<API key>) + " of which is initial sparse data buffer)");
File::resize (file.name, new_file_size);
mmap.reset (new File::MMap (file, Base::writable, false, <API key>));
// Writes a single uint32_t(0) to the start of the sparse data region
// Any voxel that has its value initialised to 0 will point here, and therefore dereferencing of any
// such voxel will yield a Sparse::Value with zero elements
memset (off2mem (0), 0x00, sizeof (uint32_t));
data_end = sizeof(uint32_t);
}
// If this is the formation of a new image, want to explicitly zero all of the
// raw image data - otherwise any random data could be misinterpreted as a large
// pointer offset from the start of the sparse image data
if (Base::is_new) {
for (auto i = Default::mmaps.begin(); i != Default::mmaps.end(); ++i)
memset ((*i)->address(), 0x00, (*i)->size());
}
}
void Sparse::unload()
{
Default::unload();
const uint64_t truncate_file_size = (data_end == size()) ? 0 : file.start + data_end;
// Null the excess data before closing the memory map to prevent std::ofstream from giving an error
// (writing uninitialised values)
memset (off2mem(data_end), 0x00, size() - data_end);
mmap.reset();
if (truncate_file_size) {
DEBUG ("truncating sparse image data file " + file.name + " to " + str(truncate_file_size) + " bytes");
File::resize (file.name, truncate_file_size);
}
}
uint32_t Sparse::get_numel (const uint64_t offset) const
{
return *(reinterpret_cast<uint32_t*>(off2mem(offset)));
}
uint64_t Sparse::set_numel (const uint64_t old_offset, const uint32_t numel)
{
assert (Base::writable);
// Before allocating new memory, verify that the current offset does not point to
// a voxel that has more elements than is required
if (old_offset) {
assert (old_offset < data_end);
const uint32_t existing_numel = get_numel (old_offset);
if (existing_numel >= numel) {
// Set the new number of elements, clear the unwanted data, and return
memcpy (off2mem(old_offset), &numel, sizeof(uint32_t));
memset (off2mem(old_offset) + sizeof(uint32_t) + (numel * class_size), 0x00, ((existing_numel - numel) * class_size));
// If this voxel is being cleared (i.e. no elements), rather than returning a pointer to a voxel with
// zero elements, instead return a pointer to the start of the sparse data, where there's a single
// uint32_t(0) which can be used for any and all voxels with zero elements
return numel ? old_offset : 0;
} else {
// Existing memory allocation for this voxel is not sufficient; erase it
// Note that the handler makes no attempt at re-using this memory later; new data is just concatenated
// to the end of the buffer
memset (off2mem(old_offset), 0x00, sizeof(uint32_t) + (existing_numel * class_size));
}
}
// Don't allocate memory for voxels with no sparse data; just point them all to the start of the
// sparse data where theres a single uint32_t(0)
if (!numel)
return 0;
const int64_t requested_size = sizeof (uint32_t) + (numel * class_size);
if (data_end + requested_size > size()) {
// size() should never be empty if data is being written...
assert (size());
uint64_t <API key> = 2 * size();
// Cover rare case where a huge memory request occurs early
while (<API key> < data_end + requested_size)
<API key> *= 2;
// Memory error arises due to the uninitialised data between the end of the sparse data and the end
// of the file at its current size being written using std::ofstream
// Therefore, explicitly null all data that hasn't already been written
// (this does not prohibit the use of this memory for subsequent sparse data though)
memset (off2mem(data_end), 0x00, size() - data_end);
mmap.reset();
const size_t new_file_size = file.start + <API key>;
DEBUG ("Resizing sparse data file " + file.name + ": new file size " + str(new_file_size) + " (" + str(<API key>) + " of which is for sparse data)");
File::resize (file.name, new_file_size);
mmap.reset (new File::MMap (file, Base::writable, true, <API key>));
}
// Write the uint32_t indicating the number of elements in this voxel
memcpy (off2mem(data_end), &numel, sizeof(uint32_t));
// The return value is the offset from the beginning of the sparse data
const uint64_t ret = data_end;
data_end += requested_size;
return ret;
}
uint8_t* Sparse::get (const uint64_t voxel_offset, const size_t index) const
{
assert (index < get_numel (voxel_offset));
const uint64_t offset = sizeof(uint32_t) + (index * class_size);
assert (voxel_offset + offset + class_size <= data_end);
uint8_t* const ptr = off2mem(voxel_offset) + offset;
return ptr;
}
}
}
} |
package com.isode.stroke.network;
public class <API key> implements ConnectionFactory {
private DomainNameResolver resolver_;
private ConnectionFactory connectionFactory_;
private TimerFactory timerFactory_;
private String proxyHost_ = "";
private int proxyPort_;
public <API key>(DomainNameResolver resolver, ConnectionFactory connectionFactory, TimerFactory timerFactory, final String proxyHost, int proxyPort) {
resolver_ = resolver;
connectionFactory_ = connectionFactory;
timerFactory_ = timerFactory;
proxyHost_ = proxyHost;
proxyPort_ = proxyPort;
}
public Connection createConnection() {
return <API key>.create(resolver_, connectionFactory_, timerFactory_, proxyHost_, proxyPort_);
}
} |
#include "XML/Evaluator.h"
namespace XmlTools {
void Evaluator::setSystemOfUnits(double meter,
double kilogram,
double second,
double ampere,
double kelvin,
double mole,
double candela,
double radians)
{
const double kilo_ = 1.e+03; // chilioi (Greek) "thousand"
const double mega_ = 1.e+06; // megas (Greek) "large"
const double giga_ = 1.e+09; // gigas (Greek) "giant"
const double tera_ = 1.e+12; // teras (Greek) "monster"
const double peta_ = 1.e+15; // pente (Greek) "five"
const double deci_ = 1.e-01; // decimus (Latin) "tenth"
const double centi_ = 1.e-02; // centum (Latin) "hundred"
const double milli_ = 1.e-03; // mille (Latin) "thousand"
const double micro_ = 1.e-06; // micro (Latin) or mikros (Greek) "small"
const double nano_ = 1.e-09; // nanus (Latin) or nanos (Greek) "dwarf"
const double pico_ = 1.e-12; // pico (Spanish) "bit"
// Base (default) SI units
// for the basic measurable quantities (dimensions):
// Length
// metrum (Latin) and metron (Greek) "measure"
const double m = meter;
setVariable("meter", m);
setVariable("metre", m);
setVariable("m", m);
// Mass
const double kg = kilogram;
setVariable("kilogram", kg);
setVariable("kg", kg);
// Time
// minuta secundam (Latin) "second small one"
const double s = second;
setVariable("second", s);
setVariable("s", s);
// Current
const double A = ampere;
setVariable("ampere", A);
setVariable("amp", A);
setVariable("A", A);
// Temperature
const double K = kelvin;
setVariable("kelvin", K);
setVariable("K", K);
// Amount of substance
const double mol = mole;
setVariable("mole", mol);
setVariable("mol", mol);
// Luminous intensity
const double cd = candela;
setVariable("candela", cd);
setVariable("cd", cd);
// Supplementary SI units having special symbols:
const double pi = 3.<API key>;
// Plane angle
// const double rad = 1.; // Geant4 (rad units)
//const double rad = pi; // Degree units
const double rad = radians ;
setVariable("radian", rad);
setVariable("rad", rad);
setVariable("milliradian", milli_ * rad);
setVariable("mrad", milli_ * rad);
const double deg = rad*pi/180.;
setVariable("degree", deg);
setVariable("deg", deg);
// Solid angle
const double sr = 1.;
setVariable("steradian", sr);
setVariable("sr", sr);
// Derived SI units having special symbols:
// Frequency
const double Hz = 1./s;
setVariable("hertz", Hz);
setVariable("Hz", Hz);
// Force
const double N = m * kg / (s*s);
setVariable("newton", N);
setVariable("N", N);
// Pressure
const double Pa = N / (m*m);
setVariable("pascal", Pa);
setVariable("Pa", Pa);
setVariable("hPa", 100.0*Pa);
const double atm = 101325. * Pa;
setVariable("atmosphere", atm);
setVariable("atm", atm);
const double bar = 100000*Pa;
setVariable("bar", bar);
// Energy
const double J = N * m;
setVariable("joule", J);
setVariable("J", J);
// Power
const double W = J / s;
setVariable("watt", W);
setVariable("W", W);
// Electric charge
const double C = A * s;
setVariable("coulomb", C);
setVariable("C", C);
// Electric potential
const double V = J / C;
setVariable("volt", V);
setVariable("V", V);
// Electric resistance
const double ohm = V / A;
setVariable("ohm", ohm);
// Electric conductance
// his brother Sir William (Karl Wilhelm von) Siemens (1823-1883)
// of Germany (England)
const double S = 1./ ohm;
setVariable("siemens", S);
setVariable("S", S);
// Electric capacitance
const double F = C / V;
setVariable("farad", F);
setVariable("F", F);
// Magnetic flux density
const double T = V * s / (m*m);
setVariable("tesla", T);
setVariable("T", T);
const double Gs = 1.e-4*T;
setVariable("gauss", Gs);
setVariable("Gs", Gs);
// Magnetic flux
const double Wb = V * s;
setVariable("weber", Wb);
setVariable("Wb", Wb);
// Inductance
const double H = Wb / A;
setVariable("henry", H);
setVariable("H", H);
// Luminous flux
const double lm = cd * sr;
setVariable("lumen", lm);
setVariable("lm", lm);
// Illuminace
const double lx = lm / (m*m);
setVariable("lux", lx);
setVariable("lx", lx);
// Radioactivity
const double Bq = 1./s;
setVariable("becquerel", Bq);
setVariable("Bq", Bq);
// and Marie Sklodowska Curie (1867-1934) of Poland
setVariable("curie", 3.7e+10 * Bq);
setVariable("Ci", 3.7e+10 * Bq);
// Specific energy
const double Gy = J / kg;
setVariable("gray", Gy);
setVariable("Gy", Gy);
// Dose equivalent
const double Sv = J / kg;
setVariable("sievert", Sv);
setVariable("Sv", Sv);
// Selected units:
// Length
const double mm = milli_ * m;
setVariable("millimeter", mm);
setVariable("mm", mm);
const double cm = centi_ * m;
setVariable("centimeter", cm);
setVariable("cm", cm);
setVariable("decimeter", deci_ * m);
const double km = kilo_ * m;
setVariable("kilometer", km);
setVariable("km", km);
setVariable("micrometer", micro_ * m);
setVariable("micron", micro_ * m);
setVariable("nanometer", nano_ * m);
setVariable("angstrom", 1.e-10 * m);
setVariable("fermi", 1.e-15 * m);
// Length^2
setVariable("m2", m*m);
setVariable("mm2", mm*mm);
setVariable("cm2", cm*cm);
setVariable("km2", km*km);
const double barn = 1.e-28 * m*m;
setVariable("barn", barn);
setVariable("millibarn", milli_ * barn);
setVariable("mbarn", milli_ * barn);
setVariable("microbarn", micro_ * barn);
setVariable("nanobarn", nano_ * barn);
setVariable("picobarn", pico_ * barn);
// LengthL^3
setVariable("m3", m*m*m);
setVariable("mm3", mm*mm*mm);
setVariable("cm3", cm*cm*cm);
setVariable("cc", cm*cm*cm);
setVariable("km3", km*km*km);
const double L = 1.e-3*m*m*m;
setVariable("liter", L);
setVariable("litre", L);
setVariable("L", L);
setVariable("centiliter", centi_ * L);
setVariable("cL", centi_ * L);
setVariable("milliliter", milli_ * L);
setVariable("mL", milli_ * L);
// Length^-1
const double dpt = 1./m;
setVariable("diopter", dpt);
setVariable("dioptre", dpt);
setVariable("dpt", dpt);
// Mass
const double g = 0.001*kg;
setVariable("gram", g);
setVariable("g", g);
setVariable("milligram", milli_ * g);
setVariable("mg", milli_ * g);
// Time
setVariable("millisecond", milli_ * s);
setVariable("ms", milli_ * s);
setVariable("microsecond", micro_ * s);
setVariable("nanosecond", nano_ * s);
setVariable("ns", nano_ * s);
setVariable("picosecond", pico_ * s);
// Current
setVariable("milliampere", milli_ * A);
setVariable("mA", milli_ * A);
setVariable("microampere", micro_ * A);
setVariable("nanoampere", nano_ * A);
// Frequency
setVariable("kilohertz", kilo_ * Hz);
setVariable("kHz", kilo_ * Hz);
setVariable("megahertz", mega_ * Hz);
setVariable("MHz", mega_ * Hz);
// Force
setVariable("kilonewton", kilo_ * N);
setVariable("kN", kilo_ * N);
// Pressure
setVariable("kilobar", kilo_ * bar);
setVariable("kbar", kilo_ * bar);
setVariable("millibar", milli_ * bar);
setVariable("mbar", milli_ * bar);
// Energy
setVariable("kilojoule", kilo_ * J);
setVariable("kJ", kilo_ * J);
setVariable("megajoule", mega_ * J);
setVariable("MJ", mega_ * J);
setVariable("gigajoule", giga_ * J);
setVariable("GJ", giga_ * J);
const double e_SI = 1.60217733e-19; // positron charge in coulomb
const double ePlus = e_SI * C; // positron charge
const double eV = ePlus * V;
setVariable("electronvolt", eV);
setVariable("eV", eV);
setVariable("kiloelectronvolt", kilo_ * eV);
setVariable("keV", kilo_ * eV);
setVariable("megaelectronvolt", mega_ * eV);
setVariable("MeV", mega_ * eV);
setVariable("gigaelectronvolt", giga_ * eV);
setVariable("GeV", giga_ * eV);
setVariable("teraelectronvolt", tera_ * eV);
setVariable("TeV", tera_ * eV);
setVariable("petaelectronvolt", peta_ * eV);
setVariable("PeV", peta_ * eV);
// Power
setVariable("kilowatt", kilo_ * W);
setVariable("kW", kilo_ * W);
setVariable("megawatt", mega_ * W);
setVariable("MW", mega_ * W);
setVariable("gigawatt", giga_ * W);
setVariable("GW", giga_ * W);
// Electric potential
setVariable("kilovolt", kilo_ * V);
setVariable("kV", kilo_ * V);
setVariable("megavolt", mega_ * V);
setVariable("MV", mega_ * V);
// Electric capacitance
setVariable("millifarad", milli_ * F);
setVariable("mF", milli_ * F);
setVariable("microfarad", micro_ * F);
setVariable("uF", micro_ * F);
setVariable("nanofarad", nano_ * F);
setVariable("nF", nano_ * F);
setVariable("picofarad", pico_ * F);
setVariable("pF", pico_ * F);
// Magnetic flux density
setVariable("kilogauss", kilo_ * Gs);
setVariable("kGs", kilo_ * Gs);
}
} // namespace XmlTools |
## Synopsis
Python Twitter bot originally intended to replicate the in{,s}anity of @johnflinchbaugh. Primary components are:
1. `markovgen.py`: class that reads in a plain text corpus and generates random sentences based on the input
2. `flinchbot.py`: class that connects to a Twitter account, checks for and responds to mentions, and occasionally posts a random tweet
3. `messageparse.py`: simple script for extracting messages from a Facebook data dump `messages.htm` file and outputting plain text
## Examples
1. `python markovgen.py -n 12 -c 3 < input.txt`: generates a random fragment of (at least) 12 words where each 3-token phrase appears somewhere in the input file
2. `python flinchbot.py`: responds to any new mentions and posts a new tweet with some small probability
3. `python messageparse.py -n 'John Fontana Flinchbaugh' < messages.htm`: processes Facebook messages and extracts plain text contents of messages from John Fontana Flinchbaugh
## Possible Extensions
1. Would be nice to have responses be vaguely context aware. One possible approach: identify most significant/unusual words, find a list of related words, and seed the sentence generator with one of them.
2. Cache data structure somewhere so that it doesn't have to be constructed from text each time. More complicated logic like the above idea would likely require this to avoid excessive computational cost. |
#include "profil.h"
const QString Profil::ProfilDirectory = "Profils";
Profil::Profil(QObject *parent) :
QObject(parent)
{
m_initialised = false;
}
bool Profil::isInitialised() const
{
return m_initialised;
}
void Profil::baseSave(QSettings *iniFile)
{
iniFile->setValue("name", name);
iniFile->setValue("description", description);
}
void Profil::baseLoad(QSettings *iniFile)
{
name = iniFile->value("name").toString();
description = iniFile->value("description").toString();
} |
#include "filter.hpp"
#include <components/compiler/locals.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/world.hpp"
#include "../mwbase/journal.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/dialoguemanager.hpp"
#include "../mwbase/scriptmanager.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/inventorystore.hpp"
#include "../mwworld/cellstore.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwmechanics/npcstats.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwmechanics/magiceffects.hpp"
#include "selectwrapper.hpp"
bool MWDialogue::Filter::testActor (const ESM::DialInfo& info) const
{
bool isCreature = (mActor.getTypeName() != typeid (ESM::NPC).name());
// actor id
if (!info.mActor.empty())
{
if ( !Misc::StringUtils::ciEqual(info.mActor, mActor.getClass().getId (mActor)))
return false;
}
else if (isCreature)
{
// Creatures must not have topics aside of those specific to their id
return false;
}
// NPC race
if (!info.mRace.empty())
{
if (isCreature)
return false;
MWWorld::LiveCellRef<ESM::NPC> *cellRef = mActor.get<ESM::NPC>();
if (!Misc::StringUtils::ciEqual(info.mRace, cellRef->mBase->mRace))
return false;
}
// NPC class
if (!info.mClass.empty())
{
if (isCreature)
return false;
MWWorld::LiveCellRef<ESM::NPC> *cellRef = mActor.get<ESM::NPC>();
if ( !Misc::StringUtils::ciEqual(info.mClass, cellRef->mBase->mClass))
return false;
}
// NPC faction
if (!info.mFaction.empty())
{
if (isCreature)
return false;
MWMechanics::NpcStats& stats = mActor.getClass().getNpcStats (mActor);
std::map<std::string, int>::iterator iter = stats.getFactionRanks().find ( Misc::StringUtils::lowerCase (info.mFaction));
if (iter==stats.getFactionRanks().end())
return false;
// check rank
if (iter->second < info.mData.mRank)
return false;
}
else if (info.mData.mRank != -1)
{
if (isCreature)
return false;
// Rank requirement, but no faction given. Use the actor's faction, if there is one.
MWMechanics::NpcStats& stats = mActor.getClass().getNpcStats (mActor);
if (!stats.getFactionRanks().size())
return false;
// check rank
if (stats.getFactionRanks().begin()->second < info.mData.mRank)
return false;
}
// Gender
if (!isCreature)
{
MWWorld::LiveCellRef<ESM::NPC>* npc = mActor.get<ESM::NPC>();
if (info.mData.mGender==(npc->mBase->mFlags & npc->mBase->Female ? 0 : 1))
return false;
}
return true;
}
bool MWDialogue::Filter::testPlayer (const ESM::DialInfo& info) const
{
const MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayerPtr();
// check player faction
if (!info.mPcFaction.empty())
{
MWMechanics::NpcStats& stats = player.getClass().getNpcStats (player);
std::map<std::string,int>::iterator iter = stats.getFactionRanks().find (Misc::StringUtils::lowerCase (info.mPcFaction));
if(iter==stats.getFactionRanks().end())
return false;
// check rank
if (iter->second < info.mData.mPCrank)
return false;
}
// check cell
if (!info.mCell.empty())
{
// supports partial matches, just like getPcCell
const std::string& playerCell = player.getCell()->getCell()->mName;
bool match = playerCell.length()>=info.mCell.length() &&
Misc::StringUtils::ciEqual(playerCell.substr (0, info.mCell.length()), info.mCell);
if (!match)
return false;
}
return true;
}
bool MWDialogue::Filter::testSelectStructs (const ESM::DialInfo& info) const
{
for (std::vector<ESM::DialInfo::SelectStruct>::const_iterator iter (info.mSelects.begin());
iter != info.mSelects.end(); ++iter)
if (!testSelectStruct (*iter))
return false;
return true;
}
bool MWDialogue::Filter::testDisposition (const ESM::DialInfo& info, bool invert) const
{
bool isCreature = (mActor.getTypeName() != typeid (ESM::NPC).name());
if (isCreature)
return true;
int actorDisposition = MWBase::Environment::get().getMechanicsManager()-><API key>(mActor)
+ MWBase::Environment::get().getDialogueManager()-><API key>();
// For service refusal, the disposition check is inverted. However, a value of 0 still means "always succeed".
return invert ? (info.mData.mDisposition == 0 || actorDisposition < info.mData.mDisposition)
: (actorDisposition >= info.mData.mDisposition);
}
bool MWDialogue::Filter::testSelectStruct (const SelectWrapper& select) const
{
if (select.isNpcOnly() && (mActor.getTypeName() != typeid (ESM::NPC).name()))
// If the actor is a creature, we do not test the conditions applicable
// only to NPCs. Such conditions can never be satisfied, apart
// inverted ones (NotClass, NotRace, NotFaction return true
// because creatures are not of any race, class or faction).
return select.getType() == SelectWrapper::Type_Inverted;
switch (select.getType())
{
case SelectWrapper::Type_None: return true;
case SelectWrapper::Type_Integer: return select.selectCompare (<API key> (select));
case SelectWrapper::Type_Numeric: return <API key> (select);
case SelectWrapper::Type_Boolean: return select.selectCompare (<API key> (select));
// We must not do the comparison for inverted functions (eg. Function_NotClass)
case SelectWrapper::Type_Inverted: return <API key> (select);
}
return true;
}
bool MWDialogue::Filter::<API key> (const SelectWrapper& select) const
{
switch (select.getFunction())
{
case SelectWrapper::Function_Global:
// internally all globals are float :(
return select.selectCompare (
MWBase::Environment::get().getWorld()->getGlobalFloat (select.getName()));
case SelectWrapper::Function_Local:
{
std::string scriptName = mActor.getClass().getScript (mActor);
if (scriptName.empty())
return false; // no script
std::string name = Misc::StringUtils::lowerCase (select.getName());
const Compiler::Locals& localDefs =
MWBase::Environment::get().getScriptManager()->getLocals (scriptName);
char type = localDefs.getType (name);
if (type==' ')
return false; // script does not have a variable of this name.
int index = localDefs.getIndex (name);
const MWScript::Locals& locals = mActor.getRefData().getLocals();
switch (type)
{
case 's': return select.selectCompare (static_cast<int> (locals.mShorts[index]));
case 'l': return select.selectCompare (locals.mLongs[index]);
case 'f': return select.selectCompare (locals.mFloats[index]);
}
throw std::logic_error ("unknown local variable type in dialogue filter");
}
case SelectWrapper::<API key>:
{
MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayerPtr();
float ratio = player.getClass().getCreatureStats (player).getHealth().getCurrent() /
player.getClass().getCreatureStats (player).getHealth().getModified();
return select.selectCompare (static_cast<int>(ratio*100));
}
case SelectWrapper::<API key>:
{
MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayerPtr();
float value = player.getClass().getCreatureStats (player).
getDynamic (select.getArgument()).getCurrent();
return select.selectCompare (value);
}
case SelectWrapper::<API key>:
{
float ratio = mActor.getClass().getCreatureStats (mActor).getHealth().getCurrent() /
mActor.getClass().getCreatureStats (mActor).getHealth().getModified();
return select.selectCompare (ratio);
}
default:
throw std::runtime_error ("unknown numeric select function");
}
}
int MWDialogue::Filter::<API key> (const SelectWrapper& select) const
{
MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayerPtr();
switch (select.getFunction())
{
case SelectWrapper::Function_Journal:
return MWBase::Environment::get().getJournal()->getJournalIndex (select.getName());
case SelectWrapper::Function_Item:
{
MWWorld::ContainerStore& store = player.getClass().getContainerStore (player);
return store.count(select.getName());
}
case SelectWrapper::Function_Dead:
return MWBase::Environment::get().getMechanicsManager()->countDeaths (select.getName());
case SelectWrapper::Function_Choice:
return mChoice;
case SelectWrapper::Function_AiSetting:
return mActor.getClass().getCreatureStats (mActor).getAiSetting (
(MWMechanics::CreatureStats::AiSetting)select.getArgument()).getModified();
case SelectWrapper::<API key>:
return player.getClass().getCreatureStats (player).
getAttribute (select.getArgument()).getModified();
case SelectWrapper::Function_PcSkill:
return static_cast<int> (player.getClass().
getNpcStats (player).getSkill (select.getArgument()).getModified());
case SelectWrapper::<API key>:
{
int hits = mActor.getClass().getCreatureStats (mActor).getFriendlyHits();
return hits>4 ? 4 : hits;
}
case SelectWrapper::Function_PcLevel:
return player.getClass().getCreatureStats (player).getLevel();
case SelectWrapper::Function_PcGender:
return player.get<ESM::NPC>()->mBase->isMale() ? 0 : 1;
case SelectWrapper::<API key>:
{
MWWorld::InventoryStore& store = player.getClass().getInventoryStore (player);
int value = 0;
for (int i=0; i<=15; ++i) // everything except thigns held in hands and amunition
{
MWWorld::<API key> slot = store.getSlot (i);
if (slot!=store.end())
value += slot->getClass().getValue (*slot);
}
return value;
}
case SelectWrapper::<API key>:
return player.getClass().getNpcStats (player).getBounty();
case SelectWrapper::<API key>:
{
if (mActor.getClass().getNpcStats (mActor).getFactionRanks().empty())
return 0;
std::string faction =
mActor.getClass().getNpcStats (mActor).getFactionRanks().begin()->first;
int rank = getFactionRank (player, faction);
if (rank>=9)
return 0; // max rank
int result = 0;
if (<API key> (player, faction, rank+1))
result += 1;
if (<API key> (player, faction, rank+1))
result += 2;
return result;
}
case SelectWrapper::Function_Level:
return mActor.getClass().getCreatureStats (mActor).getLevel();
case SelectWrapper::<API key>:
return player.getClass().getNpcStats (player).getReputation();
case SelectWrapper::Function_Weather:
return MWBase::Environment::get().getWorld()->getCurrentWeather();
case SelectWrapper::Function_Reputation:
return mActor.getClass().getNpcStats (mActor).getReputation();
case SelectWrapper::<API key>:
{
if (mActor.getClass().getNpcStats (mActor).getFactionRanks().empty())
return 0;
std::pair<std::string, int> faction =
*mActor.getClass().getNpcStats (mActor).getFactionRanks().begin();
int rank = getFactionRank (player, faction.first);
return rank-faction.second;
}
case SelectWrapper::<API key>:
return player.getClass().getNpcStats (player).getWerewolfKills();
case SelectWrapper::Function_RankLow:
case SelectWrapper::Function_RankHigh:
{
bool low = select.getFunction()==SelectWrapper::Function_RankLow;
if (mActor.getClass().getNpcStats (mActor).getFactionRanks().empty())
return 0;
std::string factionId =
mActor.getClass().getNpcStats (mActor).getFactionRanks().begin()->first;
int value = 0;
MWMechanics::NpcStats& playerStats = player.getClass().getNpcStats (player);
std::map<std::string, int>::const_iterator playerFactionIt = playerStats.getFactionRanks().begin();
for (; playerFactionIt != playerStats.getFactionRanks().end(); ++playerFactionIt)
{
int reaction = MWBase::Environment::get().getDialogueManager()->getFactionReaction(factionId, playerFactionIt->first);
if (low ? reaction < value : reaction > value)
value = reaction;
}
return value;
}
default:
throw std::runtime_error ("unknown integer select function");
}
}
bool MWDialogue::Filter::<API key> (const SelectWrapper& select) const
{
MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayerPtr();
switch (select.getFunction())
{
case SelectWrapper::Function_False:
return false;
case SelectWrapper::Function_NotId:
return !Misc::StringUtils::ciEqual(mActor.getClass().getId (mActor), select.getName());
case SelectWrapper::Function_NotFaction:
return !Misc::StringUtils::ciEqual(mActor.get<ESM::NPC>()->mBase->mFaction, select.getName());
case SelectWrapper::Function_NotClass:
return !Misc::StringUtils::ciEqual(mActor.get<ESM::NPC>()->mBase->mClass, select.getName());
case SelectWrapper::Function_NotRace:
return !Misc::StringUtils::ciEqual(mActor.get<ESM::NPC>()->mBase->mRace, select.getName());
case SelectWrapper::Function_NotCell:
return !Misc::StringUtils::ciEqual(mActor.getCell()->getCell()->mName, select.getName());
case SelectWrapper::Function_NotLocal:
{
std::string scriptName = mActor.getClass().getScript (mActor);
if (scriptName.empty())
// This actor has no attached script, so there is no local variable
return true;
const Compiler::Locals& localDefs =
MWBase::Environment::get().getScriptManager()->getLocals (scriptName);
return localDefs.getIndex (Misc::StringUtils::lowerCase (select.getName()))==-1;
}
case SelectWrapper::Function_SameGender:
return (player.get<ESM::NPC>()->mBase->mFlags & ESM::NPC::Female)==
(mActor.get<ESM::NPC>()->mBase->mFlags & ESM::NPC::Female);
case SelectWrapper::Function_SameRace:
return !Misc::StringUtils::ciEqual(mActor.get<ESM::NPC>()->mBase->mRace, player.get<ESM::NPC>()->mBase->mRace);
case SelectWrapper::<API key>:
return mActor.getClass().getNpcStats (mActor).isSameFaction (
player.getClass().getNpcStats (player));
case SelectWrapper::<API key>:
return player.getClass().getCreatureStats (player).hasCommonDisease();
case SelectWrapper::<API key>:
return player.getClass().getCreatureStats (player).hasBlightDisease();
case SelectWrapper::Function_PcCorprus:
return player.getClass().getCreatureStats (player).
getMagicEffects().get (ESM::MagicEffect::Corprus).mMagnitude!=0;
case SelectWrapper::Function_PcExpelled:
{
if (mActor.getClass().getNpcStats (mActor).getFactionRanks().empty())
return false;
std::string faction =
mActor.getClass().getNpcStats (mActor).getFactionRanks().begin()->first;
return player.getClass().getNpcStats(player).getExpelled(faction);
}
case SelectWrapper::Function_PcVampire:
return player.getClass().getCreatureStats(player).getMagicEffects().
get(ESM::MagicEffect::Vampirism).mMagnitude > 0;
case SelectWrapper::Function_TalkedToPc:
return mTalkedToPlayer;
case SelectWrapper::Function_Alarmed:
return mActor.getClass().getCreatureStats (mActor).isAlarmed();
case SelectWrapper::Function_Detected:
return MWBase::Environment::get().getMechanicsManager()->awarenessCheck(player, mActor);
case SelectWrapper::Function_Attacked:
return mActor.getClass().getCreatureStats (mActor).getAttacked();
case SelectWrapper::<API key>:
return MWBase::Environment::get().getMechanicsManager()->isAggressive(mActor,
MWBase::Environment::get().getWorld()->getPlayerPtr());
case SelectWrapper::<API key>:
return mActor.getClass().getCreatureStats (mActor).<API key>();
case SelectWrapper::Function_Werewolf:
return mActor.getClass().getNpcStats (mActor).isWerewolf();
default:
throw std::runtime_error ("unknown boolean select function");
}
}
int MWDialogue::Filter::getFactionRank (const MWWorld::Ptr& actor, const std::string& factionId) const
{
MWMechanics::NpcStats& stats = actor.getClass().getNpcStats (actor);
std::map<std::string, int>::const_iterator iter = stats.getFactionRanks().find (factionId);
if (iter==stats.getFactionRanks().end())
return -1;
return iter->second;
}
bool MWDialogue::Filter::<API key> (const MWWorld::Ptr& actor,
const std::string& factionId, int rank) const
{
if (rank<0 || rank>=10)
throw std::runtime_error ("rank index out of range");
if (!actor.getClass().getNpcStats (actor).hasSkillsForRank (factionId, rank))
return false;
const ESM::Faction& faction =
*MWBase::Environment::get().getWorld()->getStore().get<ESM::Faction>().find (factionId);
MWMechanics::CreatureStats& stats = actor.getClass().getCreatureStats (actor);
return stats.getAttribute (faction.mData.mAttribute[0]).getBase()>=faction.mData.mRankData[rank].mAttribute1 &&
stats.getAttribute (faction.mData.mAttribute[1]).getBase()>=faction.mData.mRankData[rank].mAttribute2;
}
bool MWDialogue::Filter::<API key> (const MWWorld::Ptr& actor,
const std::string& factionId, int rank) const
{
if (rank<0 || rank>=10)
throw std::runtime_error ("rank index out of range");
MWMechanics::NpcStats& stats = actor.getClass().getNpcStats (actor);
const ESM::Faction& faction =
*MWBase::Environment::get().getWorld()->getStore().get<ESM::Faction>().find (factionId);
return stats.<API key> (factionId)>=faction.mData.mRankData[rank].mFactReaction;
}
MWDialogue::Filter::Filter (const MWWorld::Ptr& actor, int choice, bool talkedToPlayer)
: mActor (actor), mChoice (choice), mTalkedToPlayer (talkedToPlayer)
{}
const ESM::DialInfo* MWDialogue::Filter::search (const ESM::Dialogue& dialogue, const bool <API key>) const
{
std::vector<const ESM::DialInfo *> suitableInfos = list (dialogue, <API key>, false);
if (suitableInfos.empty())
return NULL;
else
return suitableInfos[0];
}
std::vector<const ESM::DialInfo *> MWDialogue::Filter::list (const ESM::Dialogue& dialogue,
bool <API key>, bool searchAll, bool invertDisposition) const
{
std::vector<const ESM::DialInfo *> infos;
bool infoRefusal = false;
// Iterate over topic responses to find a matching one
for (ESM::Dialogue::InfoContainer::const_iterator iter = dialogue.mInfo.begin();
iter!=dialogue.mInfo.end(); ++iter)
{
if (testActor (*iter) && testPlayer (*iter) && testSelectStructs (*iter))
{
if (testDisposition (*iter, invertDisposition)) {
infos.push_back(&*iter);
if (!searchAll)
break;
}
else
infoRefusal = true;
}
}
if (infos.empty() && infoRefusal && <API key>)
{
// No response is valid because of low NPC disposition,
// search a response in the topic "Info Refusal"
const MWWorld::Store<ESM::Dialogue> &dialogues =
MWBase::Environment::get().getWorld()->getStore().get<ESM::Dialogue>();
const ESM::Dialogue& infoRefusalDialogue = *dialogues.find ("Info Refusal");
for (ESM::Dialogue::InfoContainer::const_iterator iter = infoRefusalDialogue.mInfo.begin();
iter!=infoRefusalDialogue.mInfo.end(); ++iter)
if (testActor (*iter) && testPlayer (*iter) && testSelectStructs (*iter) && testDisposition(*iter, invertDisposition)) {
infos.push_back(&*iter);
if (!searchAll)
break;
}
}
return infos;
}
bool MWDialogue::Filter::responseAvailable (const ESM::Dialogue& dialogue) const
{
for (ESM::Dialogue::InfoContainer::const_iterator iter = dialogue.mInfo.begin();
iter!=dialogue.mInfo.end(); ++iter)
{
if (testActor (*iter) && testPlayer (*iter) && testSelectStructs (*iter))
return true;
}
return false;
} |
/**
* Optimisation stage that removes unused variables and functions.
*/
#pragma once
#include <libyul/optimiser/ASTWalker.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/YulString.h>
#include <map>
#include <set>
namespace yul
{
struct Dialect;
struct SideEffects;
/**
* Optimisation stage that removes unused variables and functions and also
* removes side-effect-free expression statements.
*
* If msize is used, we cannot remove any statements that access memory.
* Because of that, the Unused Pruner should only be invoked on full ASTs,
* such that it can check for the presence of msize itself, or
* the `<API key>` needs to be passed.
*
* Note that this does not remove circular references.
*
* Prerequisite: Disambiguator
*/
class UnusedPruner: public ASTModifier
{
public:
static constexpr char const* name{"UnusedPruner"};
static void run(<API key>& _context, Block& _ast) {
UnusedPruner::<API key>(_context.dialect, _ast, _context.reservedIdentifiers);
}
using ASTModifier::operator();
void operator()(Block& _block) override;
// @returns true iff the code changed in the previous run.
bool shouldRunAgain() const { return m_shouldRunAgain; }
// Run the pruner until the code does not change anymore.
static void runUntilStabilised(
Dialect const& _dialect,
Block& _ast,
bool <API key>,
std::map<YulString, SideEffects> const* <API key> = nullptr,
std::set<YulString> const& <API key> = {}
);
static void run(
Dialect const& _dialect,
Block& _ast,
std::set<YulString> const& <API key> = {}
)
{
<API key>(_dialect, _ast, <API key>);
}
Run the pruner until the code does not change anymore.
The provided block has to be a full AST.
The pruner itself determines if msize is used and which user-defined functions
are side-effect free.
static void <API key>(
Dialect const& _dialect,
Block& _ast,
std::set<YulString> const& <API key> = {}
);
// Run the pruner until the code does not change anymore.
// Only run on the given function.
// @param <API key> if true, allows to remove instructions
// whose only side-effect is a potential change of the return value of
// the msize instruction.
static void runUntilStabilised(
Dialect const& _dialect,
FunctionDefinition& _functionDefinition,
bool <API key>,
std::set<YulString> const& <API key> = {}
);
private:
UnusedPruner(
Dialect const& _dialect,
Block& _ast,
bool <API key>,
std::map<YulString, SideEffects> const* <API key> = nullptr,
std::set<YulString> const& <API key> = {}
);
UnusedPruner(
Dialect const& _dialect,
FunctionDefinition& _function,
bool <API key>,
std::set<YulString> const& <API key> = {}
);
bool used(YulString _name) const;
void subtractReferences(std::map<YulString, size_t> const& _subtrahend);
Dialect const& m_dialect;
bool <API key> = false;
std::map<YulString, SideEffects> const* <API key> = nullptr;
bool m_shouldRunAgain = false;
std::map<YulString, size_t> m_references;
};
} |
// @flow
import circle from './style_layer/circle_style_layer';
import heatmap from './style_layer/heatmap_style_layer';
import hillshade from './style_layer/<API key>';
import fill from './style_layer/fill_style_layer';
import fillExtrusion from './style_layer/<API key>';
import line from './style_layer/line_style_layer';
import symbol from './style_layer/symbol_style_layer';
import background from './style_layer/<API key>';
import raster from './style_layer/raster_style_layer';
const subclasses = {
circle,
heatmap,
hillshade,
fill,
'fill-extrusion': fillExtrusion,
line,
symbol,
background,
raster
};
export default function createStyleLayer(layer: LayerSpecification) {
return new subclasses[layer.type](layer);
} |
using System;
using UnityEngine;
namespace CommandLibrary
{
public static partial class Commands
{
public static CommandDelegate Log(string text)
{
return Commands.Do( () => Debug.Log(text) );
}
public static CommandDelegate LogError(string text)
{
return Commands.Do (() => Debug.LogError(text));
}
public static CommandDelegate LogWarning(string text)
{
return Commands.Do (() => Debug.LogWarning (text));
}
public static CommandDelegate LogException(Exception e)
{
return Commands.Do (() => Debug.LogException (e));
}
public static CommandDelegate Enable(MonoBehaviour behaviour, bool isEnabled = true)
{
return Commands.Do (() => behaviour.enabled = isEnabled);
}
public static CommandDelegate SetActive(GameObject gm, bool isActive)
{
return Commands.Do (() => gm.SetActive (isActive));
}
public static CommandDelegate SendMessage(GameObject gm, string eventName, object obj = null, SendMessageOptions options = SendMessageOptions.DontRequireReceiver)
{
return Commands.Do( () => gm.SendMessage (eventName, obj, options));
}
}
} |
package com.springcloud.template.authserverjwt.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.<API key>;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.<API key>;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.<API key>;
import org.springframework.security.oauth2.config.annotation.web.configuration.<API key>;
import org.springframework.security.oauth2.config.annotation.web.configuration.<API key>;
import org.springframework.security.oauth2.config.annotation.web.configuration.<API key>;
import org.springframework.security.oauth2.config.annotation.web.configurers.<API key>;
import org.springframework.security.oauth2.config.annotation.web.configurers.<API key>;
import org.springframework.security.oauth2.provider.token.<API key>;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.<API key>;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import org.springframework.security.web.authentication.www.Basic<API key>;
import javax.sql.DataSource;
import java.security.SecureRandom;
@Configuration
@<API key>
@<API key>
public class OAuth2Configuration extends <API key> {
@Autowired
@Qualifier("<API key>")
private UserDetailsService userDetailsService;
@Override
public void configure(<API key> security) throws Exception {
super.configure(security);
security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
@Autowired
private DataSource dataSource;
@Override
public void configure(<API key> clients) throws Exception {
clients.jdbc(dataSource);
}
@Autowired
private <API key> <API key>;
@Override
public void configure(<API key> endpoints) throws Exception {
endpoints.<API key>(<API key>);
endpoints.userDetailsService(userDetailsService);
endpoints.tokenStore(tokenStore()).tokenEnhancer(jwtTokenEnhancer()).<API key>(<API key>);
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(jwtTokenEnhancer());
}
@Bean
protected <API key> jwtTokenEnhancer() {
// KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "mySecretKey".toCharArray());
KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "openstack".toCharArray());
<API key> converter = new <API key>();
converter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt"));
return converter;
}
@Bean
@Primary
public <API key> getTokenService(){
<API key> <API key> = new <API key>();
<API key>.setTokenStore(tokenStore());
<API key>.<API key>(true);
return <API key>;
}
@Bean
public static PasswordEncoder getPasswordEncod() {
Integer seed = 9;
return new <API key>(8, new SecureRandom(seed.toString().getBytes()));
}
} |
metadata = dict(
name='Vermont',
abbreviation='vt',
capitol_timezone='America/New_York',
legislature_name='Vermont General Assembly',
legislature_url='http://legislature.vermont.gov/',
chambers = {
'upper': {'name': 'Senate', 'title': 'Senator', 'term': 2},
'lower': {'name': 'House', 'title': 'Representative', 'term': 2},
},
terms=[{'name': '2009-2010',
'start_year': 2009,
'end_year': 2010,
'sessions': ['2009-2010']},
{'name': '2011-2012',
'start_year': 2011,
'end_year': 2012,
'sessions': ['2011-2012']},
{'name': '2013-2014',
'start_year': 2013,
'end_year': 2014,
'sessions': ['2013-2014']},
{'name': '2015-2016',
'start_year': 2015,
'end_year': 2016,
'sessions': ['2015-2016']},
{'name': '2017-2018',
'start_year': 2017,
'end_year': 2018,
'sessions': ['2017-2018']},
],
session_details={'2009-2010': {'type': 'primary',
'display_name': '2009-2010 Regular Session',
'_scraped_name': '2009-2010 Session',
},
'2011-2012': {'type': 'primary',
'display_name': '2011-2012 Regular Session',
'_scraped_name': '2011-2012 Session',
},
'2013-2014': {'type': 'primary',
'display_name': '2013-2014 Regular Session',
'_scraped_name': '2013-2014 Session',
},
'2015-2016': {'type': 'primary',
'display_name': '2015-2016 Regular Session',
'_scraped_name': '2015-2016 Session',
},
'2017-2018': {'type': 'primary',
'display_name': '2017-2018 Regular Session',
'_scraped_name': '2017-2018 Session',
},
},
feature_flags=[],
<API key>= ['2009 Special Session']
) |
set(CMAKE_C_COMPILER "/usr/sbin/cc")
set(<API key> "")
set(CMAKE_C_COMPILER_ID "GNU")
set(<API key> "6.3.1")
set(<API key> "")
set(<API key> "11")
set(<API key> "<API key>;c_restrict;c_variadic_macros;c_static_assert")
set(<API key> "<API key>")
set(<API key> "c_restrict;c_variadic_macros")
set(<API key> "c_static_assert")
set(CMAKE_C_PLATFORM_ID "Linux")
set(CMAKE_C_SIMULATE_ID "")
set(<API key> "")
set(CMAKE_AR "/usr/sbin/ar")
set(CMAKE_RANLIB "/usr/sbin/ranlib")
set(CMAKE_LINKER "/usr/sbin/ld")
set(<API key> 1)
set(<API key> 1)
set(<API key> TRUE)
set(<API key> TRUE)
set(<API key> )
set(<API key> )
if(<API key>)
set(CYGWIN 1)
set(UNIX 1)
endif()
set(<API key> "CC")
if(<API key>)
set(MINGW 1)
endif()
set(<API key> 1)
set(<API key> c;m)
set(<API key> h;H;o;O;obj;OBJ;def;DEF;rc;RC)
set(<API key> 10)
# Save compiler ABI information.
set(<API key> "8")
set(<API key> "ELF")
set(<API key> "")
if(<API key>)
set(CMAKE_SIZEOF_VOID_P "${<API key>}")
endif()
if(<API key>)
set(<API key> "${<API key>}")
endif()
if(<API key>)
set(<API key> "")
endif()
set(<API key> "")
if(<API key>)
set(<API key> "${<API key>}")
endif()
set(<API key> "c")
set(<API key> "/usr/lib/gcc/x86_64-pc-linux-gnu/6.3.1;/usr/lib;/lib")
set(<API key> "") |
<?xml version="1.0" encoding="utf-8"?>
<html>
<head>
<title>GLib.Proxy.<API key> -- Vala Binding Reference</title>
<link href="../style.css" rel="stylesheet" type="text/css"/><script src="../scripts.js" type="text/javascript">
</script>
</head>
<body>
<div class="site_header">GLib.Proxy.<API key> Reference Manual</div>
<div class="site_body">
<div class="site_navigation">
<ul class="navi_main">
<li class="package_index"><a href="../index.html">Packages</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="package"><a href="index.htm">gio-2.0</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="namespace"><a href="GLib.html">GLib</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="interface"><a href="GLib.Proxy.html">Proxy</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="static_method"><API key></li>
<li class="abstract_method"><a href="GLib.Proxy.connect.html">connect</a></li>
<li class="abstract_method"><a href="GLib.Proxy.connect_async.html">connect_async</a></li>
<li class="abstract_method"><a href="GLib.Proxy.supports_hostname.html">supports_hostname</a></li>
</ul>
</div>
<div class="site_content">
<h1 class="main_title"><API key></h1>
<hr class="main_hr"/>
<h2 class="main_title">Description:</h2>
<div class="<API key>"><span class="main_keyword">public</span> <span class="main_keyword">static</span> <span class="main_type"><a href="GLib.Proxy.html" class="interface">Proxy</a></span> <b><span css="static_method"><API key></span></b> (<span class="main_basic_type"><a href="../glib-2.0/string.html" class="class">string</a></span> protocol)
</div>
</div>
</div><br/>
<div class="site_footer">Generated by <a href="http:
</div>
</body>
</html> |
package com.sun.phobos.script.util;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
/*
* Abstract super class for factory implementations.
*
* @version 1.0
* @author Mike Grogan
* @since 1.6
*/
public abstract class <API key> implements ScriptEngineFactory {
public String getName() {
return (String)getParameter(ScriptEngine.NAME);
}
@Override
public String getEngineName() {
return (String)getParameter(ScriptEngine.ENGINE);
}
@Override
public String getEngineVersion() {
return (String)getParameter(ScriptEngine.ENGINE_VERSION);
}
@Override
public String getLanguageName() {
return (String)getParameter(ScriptEngine.LANGUAGE);
}
@Override
public String getLanguageVersion() {
return (String)getParameter(ScriptEngine.LANGUAGE_VERSION);
}
} |
<?php
$array = array("type" => 2,
"boost" => 999
);
echo json_encode($array);
?> |
/** \file
* This C header file was generated by $ANTLR version 3.2 Sep 23, 2009 12:02:23
*
* - From the grammar source file : /home/dfranusic/antlr-c-test/smsfs.g
* - On : 2012-01-30 19:07:13
* - for the parser : smsfsParserParser *
* Editing it, at least manually, is not wise.
*
* C language generator and runtime by Jim Idle, jimi|hereisanat|idle|dotgoeshere|ws.
*
*
* The parser smsfsParser has the callable functions (rules) shown below,
* which will invoke the code for the associated rule in the source grammar
* assuming that the input stream is pointing to a token/text stream that could begin
* this rule.
*
* For instance if you call the first (topmost) rule in a parser grammar, you will
* get the results of a full parse, but calling a rule half way through the grammar will
* allow you to pass part of a full token stream to the parser, such as for syntax checking
* in editors and so on.
*
* The parser entry points are called indirectly (by function pointer to function) via
* a parser context typedef psmsfsParser, which is returned from a call to smsfsParserNew().
*
* The methods in psmsfsParser are as follows:
*
* - <API key> psmsfsParser->input(psmsfsParser)
* - <API key> psmsfsParser->eval_nai(psmsfsParser)
* - <API key> psmsfsParser->smpp_eval_np(psmsfsParser)
* - <API key> psmsfsParser->eval_np(psmsfsParser)
* - <API key> psmsfsParser->eval_gti(psmsfsParser)
* - <API key> psmsfsParser->eval_dcs(psmsfsParser)
* - <API key> psmsfsParser->smpp_eval_dcs(psmsfsParser)
* - <API key> psmsfsParser->smpp_eval_esm_mm(psmsfsParser)
* - <API key> psmsfsParser->smpp_eval_esm_mt(psmsfsParser)
* - <API key> psmsfsParser->smpp_eval_esm_gf(psmsfsParser)
* - <API key> psmsfsParser->smpp_eval_rd_smscdr(psmsfsParser)
* - <API key> psmsfsParser->smpp_eval_rd_smeoa(psmsfsParser)
* - <API key> psmsfsParser->smpp_eval_rd_in(psmsfsParser)
* - <API key> psmsfsParser->eval_string(psmsfsParser)
* - <API key> psmsfsParser->eval_number(psmsfsParser)
* - <API key> psmsfsParser->eval_ton(psmsfsParser)
* - <API key> psmsfsParser->smpp_eval_ton(psmsfsParser)
* - <API key> psmsfsParser->eval_msg_type(psmsfsParser)
* - <API key> psmsfsParser->evalsimple(psmsfsParser)
* - <API key> psmsfsParser->listmethod(psmsfsParser)
* - <API key> psmsfsParser->floodmethod(psmsfsParser)
* - <API key> psmsfsParser->regexdef(psmsfsParser)
* - <API key> psmsfsParser->regex(psmsfsParser)
* - <API key> psmsfsParser->smpp_esm_mm(psmsfsParser)
* - <API key> psmsfsParser->smpp_esm_mt(psmsfsParser)
* - <API key> psmsfsParser->smpp_esm_gf(psmsfsParser)
* - <API key> psmsfsParser->smpp_rd_smscdr(psmsfsParser)
* - <API key> psmsfsParser->smpp_rd_smeoa(psmsfsParser)
* - <API key> psmsfsParser->smpp_rd_in(psmsfsParser)
* - <API key> psmsfsParser->nai(psmsfsParser)
* - <API key> psmsfsParser->np(psmsfsParser)
* - <API key> psmsfsParser->smpp_np(psmsfsParser)
* - <API key> psmsfsParser->gti(psmsfsParser)
* - <API key> psmsfsParser->smpp_dcs(psmsfsParser)
* - <API key> psmsfsParser->dcs(psmsfsParser)
* - <API key> psmsfsParser->smpp_typeofnum(psmsfsParser)
* - <API key> psmsfsParser->typeofnum(psmsfsParser)
* - <API key> psmsfsParser->msgtype(psmsfsParser)
* - <API key> psmsfsParser->evalobj(psmsfsParser)
* - <API key> psmsfsParser->eval(psmsfsParser)
* - <API key> psmsfsParser->curlyblock(psmsfsParser)
* - <API key> psmsfsParser->m3ua(psmsfsParser)
* - <API key> psmsfsParser->modifier_method(psmsfsParser)
* - <API key> psmsfsParser->modify(psmsfsParser)
* - <API key> psmsfsParser->modifybody(psmsfsParser)
* - <API key> psmsfsParser->ruleeval(psmsfsParser)
* - <API key> psmsfsParser->rulealw(psmsfsParser)
* - <API key> psmsfsParser->ruledny(psmsfsParser)
* - <API key> psmsfsParser->rulebody(psmsfsParser)
* - <API key> psmsfsParser->rule(psmsfsParser)
* - <API key> psmsfsParser->filter(psmsfsParser)
* - <API key> psmsfsParser->comparison(psmsfsParser)
* - <API key> psmsfsParser->action(psmsfsParser)
*
* The return type for any particular rule is of course determined by the source
* grammar file.
*/
// [The "BSD licence"]
// modification, are permitted provided that the following conditions
// are met:
// documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef _smsfsParser_H
#define _smsfsParser_H
#include <antlr3.h>
#ifdef __cplusplus
extern "C" {
#endif
// Forward declare the context typedef so that we can use it before it is
// properly defined. Delegators and delegates (from import statements) are
// interdependent and their context structures contain pointers to each other
// C only allows such things to be declared if you pre-declare the typedef.
typedef struct <API key> smsfsParser, * psmsfsParser;
#ifdef ANTLR3_WINDOWS
// Disable: Unreferenced parameter, - Rules with parameters that are not used
// constant conditional, - ANTLR realizes that a prediction is always true (synpred usually)
// initialized but unused variable - tree rewrite variables declared but not needed
// Unreferenced local variable - lexer rule declares but does not always use _type
// potentially unitialized variable used - retval always returned from a rule
// unreferenced local function has been removed - susually getTokenNames or freeScope, they can go without warnigns
// These are only really displayed at warning level /W4 but that is the code ideal I am aiming at
// and the codegen must generate some of these warnings by necessity, apart from 4100, which is
// usually generated when a parser rule is given a parameter that it does not use. Mostly though
// this is a matter of orthogonality hence I disable that one.
#pragma warning( disable : 4100 )
#pragma warning( disable : 4101 )
#pragma warning( disable : 4127 )
#pragma warning( disable : 4189 )
#pragma warning( disable : 4505 )
#pragma warning( disable : 4701 )
#endif
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
pANTLR3_STRING regexdef_res;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
typedef struct <API key>
{
/** Generic return elements for ANTLR3 rules that are not in tree parsers or returning trees
*/
<API key> start;
<API key> stop;
pANTLR3_BASE_TREE tree;
}
<API key>;
/** Context tracking structure for smsfsParser
*/
struct <API key>
{
/** Built in ANTLR3 context tracker contains all the generic elements
* required for context tracking.
*/
pANTLR3_PARSER pParser;
<API key> (*input) (struct <API key> * ctx);
<API key> (*eval_nai) (struct <API key> * ctx);
<API key> (*smpp_eval_np) (struct <API key> * ctx);
<API key> (*eval_np) (struct <API key> * ctx);
<API key> (*eval_gti) (struct <API key> * ctx);
<API key> (*eval_dcs) (struct <API key> * ctx);
<API key> (*smpp_eval_dcs) (struct <API key> * ctx);
<API key> (*smpp_eval_esm_mm) (struct <API key> * ctx);
<API key> (*smpp_eval_esm_mt) (struct <API key> * ctx);
<API key> (*smpp_eval_esm_gf) (struct <API key> * ctx);
<API key> (*smpp_eval_rd_smscdr) (struct <API key> * ctx);
<API key> (*smpp_eval_rd_smeoa) (struct <API key> * ctx);
<API key> (*smpp_eval_rd_in) (struct <API key> * ctx);
<API key> (*eval_string) (struct <API key> * ctx);
<API key> (*eval_number) (struct <API key> * ctx);
<API key> (*eval_ton) (struct <API key> * ctx);
<API key> (*smpp_eval_ton) (struct <API key> * ctx);
<API key> (*eval_msg_type) (struct <API key> * ctx);
<API key> (*evalsimple) (struct <API key> * ctx);
<API key> (*listmethod) (struct <API key> * ctx);
<API key> (*floodmethod) (struct <API key> * ctx);
<API key> (*regexdef) (struct <API key> * ctx);
<API key> (*regex) (struct <API key> * ctx);
<API key> (*smpp_esm_mm) (struct <API key> * ctx);
<API key> (*smpp_esm_mt) (struct <API key> * ctx);
<API key> (*smpp_esm_gf) (struct <API key> * ctx);
<API key> (*smpp_rd_smscdr) (struct <API key> * ctx);
<API key> (*smpp_rd_smeoa) (struct <API key> * ctx);
<API key> (*smpp_rd_in) (struct <API key> * ctx);
<API key> (*nai) (struct <API key> * ctx);
<API key> (*np) (struct <API key> * ctx);
<API key> (*smpp_np) (struct <API key> * ctx);
<API key> (*gti) (struct <API key> * ctx);
<API key> (*smpp_dcs) (struct <API key> * ctx);
<API key> (*dcs) (struct <API key> * ctx);
<API key> (*smpp_typeofnum) (struct <API key> * ctx);
<API key> (*typeofnum) (struct <API key> * ctx);
<API key> (*msgtype) (struct <API key> * ctx);
<API key> (*evalobj) (struct <API key> * ctx);
<API key> (*eval) (struct <API key> * ctx);
<API key> (*curlyblock) (struct <API key> * ctx);
<API key> (*m3ua) (struct <API key> * ctx);
<API key> (*modifier_method) (struct <API key> * ctx);
<API key> (*modify) (struct <API key> * ctx);
<API key> (*modifybody) (struct <API key> * ctx);
<API key> (*ruleeval) (struct <API key> * ctx);
<API key> (*rulealw) (struct <API key> * ctx);
<API key> (*ruledny) (struct <API key> * ctx);
<API key> (*rulebody) (struct <API key> * ctx);
<API key> (*rule) (struct <API key> * ctx);
<API key> (*filter) (struct <API key> * ctx);
<API key> (*comparison) (struct <API key> * ctx);
<API key> (*action) (struct <API key> * ctx);
// Delegated rules
const char * (*getGrammarFileName)();
void (*free) (struct <API key> * ctx);
/* @headerFile.members() */
<API key> adaptor;
<API key> vectors;
/* End @headerFile.members() */
};
// Function protoypes for the constructor functions that external translation units
// such as delegators and delegates may wish to call.
ANTLR3_API psmsfsParser smsfsParserNew (<API key> instream);
ANTLR3_API psmsfsParser smsfsParserNewSSD (<API key> instream, <API key> state);
/** Symbolic definitions of all the tokens that the parser will work with.
* \{
*
* Antlr will define EOF, but we can't use that as it it is too common in
* in C header files and that would be confusing. There is no way to filter this out at the moment
* so we just undef it here for now. That isn't the value we get back from C recognizers
* anyway. We are looking for ANTLR3_TOKEN_EOF.
*/
#ifdef EOF
#undef EOF
#endif
#ifdef Tokens
#undef Tokens
#endif
#define SMPP_RD_IN_YES 72
#define HEX_P 206
#define T__259 259
#define REMOTE_IP 241
#define T__258 258
#define T__257 257
#define MAP_MSISDN 99
#define <API key> 103
#define DQUOTE 216
#define T__260 260
#define T__261 261
#define ALW_Q 179
#define SMPP_DELIVERY_TIME 26
#define R_CR_B 189
#define EOF -1
#define GTI_NONE 143
#define HLR_RESULT_NNN 114
#define SMPP_RD_SMEOA_NO 67
#define F_SMPP_MO 191
#define SPAM_REMOVE_LST 154
#define SMPP_NP_PRIVATE 60
#define OFF 197
#define FLOOD_ALL_MAX 167
#define SCCP_GT_CALLED_GTI 94
#define SCCP_GT_CALLED_NP 92
#define NP_MARITIME 134
#define FLOOD_GLOBAL 165
#define NP_ISDN_TELEPHONE 130
#define GOTO 217
#define F_SMPP_MT 193
#define <API key> 125
#define SMPP_DATA_CODING 32
#define LOCAL_PORT 240
#define <API key> 11
#define M3UA_OPC 101
#define NP_GENERIC 131
#define <API key> 22
#define <API key> 30
#define <API key> 63
#define GTI_NAI 144
#define MD5_REMOVE_LST 158
#define MD5_SMS_TPDU_UD 119
#define WS 248
#define M3UA_CONNECTION 237
#define DCS_UCS2 150
#define ESCAPESEQUENCE 256
#define CONN_N_APP 245
#define FLOOD_ALL 171
#define RULE_EVAL 222
#define SMPP_DC_IA5_ASCII 74
#define MSG_TYPE_SINGLE 151
#define SL_COMMENT 254
#define LESS_THAN 207
#define DCS_8BIT 149
#define <API key> 118
#define GT 208
#define SMPP_RD_IN_NO 71
#define <API key> 52
#define DNY_Q 183
#define <API key> 44
#define HLR_REQUEST 159
#define STMTSEP 204
#define NP_ISDN_MOBILE 136
#define MD5_UPDATE_LST 157
#define MODIFY 214
#define DUMMY_RULE_DEF 231
#define SMPP_SERVICE_TYPE 14
#define <API key> 42
#define HLR_IMSI 108
#define SMPP_DC_KS_C_5601 85
#define SMPP_ESM_GF_NO 43
#define NP_TELEX 133
#define F_MO 190
#define NAI_INTERNATIONAL 142
#define <API key> 141
#define MODIFIER_STATUS 234
#define <API key> 21
#define <API key> 23
#define SMPP_DC_JIS 78
#define TON_UNKNOWN 122
#define RULE_REGEX 225
#define ASTERISK 219
#define HLR_RESULT_ANNN 115
#define RULE_STATUS 223
#define <API key> 102
#define <API key> 126
#define NP_PRIVATE 137
#define SMPP_ORIGINATOR_NP 16
#define L_SQ_B 187
#define SMPP_ESM_MT_DEFAULT 40
#define <API key> 51
#define RP_SMS_TPDU_UD 117
#define <API key> 139
#define <API key> 140
#define <API key> 69
#define RULE_EVAL_ATOM 224
#define PLUS 211
#define SMPP_TON_NATIONAL 49
#define SMPP_NP_NATIONAL 59
#define <API key> 86
#define GTI_TTNPENOA 147
#define SMPP_DC_DEFAULT 73
#define SMPP_IP_DESTINATION 9
#define <API key> 41
#define <API key> 75
#define F_HLR 194
#define <API key> 77
#define FLOOD_GLOBAL_MAX 166
#define SQUOTE 215
#define MINUS 212
#define <API key> 87
#define NP_LAND_MOBILE 135
#define CONNECTION_LABEL 238
#define SMS_TPDU_UD 106
#define COLON 203
#define MAP_SCOA_WL 6
#define SCCP_GT_CALLED_TT 88
#define DECIMAL 255
#define RULE_EVAL_TRUE 227
#define <API key> 155
#define STRINGLITERAL 249
#define SMPP_IP_SOURCE 8
#define SCCP_GT_CALLING_GTI 95
#define TON_ABBREVIATED 128
#define RULE_REGEX_EXPR 226
#define SPAM_SMS_TPDU_UD 116
#define CONN_DPC 243
#define RULE_DEF 230
#define F_MT 192
#define <API key> 156
#define MAP_IMSI 98
#define SMPP_DC_ISO_8859_5 79
#define <API key> 65
#define FLOOD_DAY 170
#define SMPP_DC_ISO_8859_1 76
#define CONT_Q 177
#define <API key> 105
#define MODIFIER_METHOD 235
#define SMPP_SYSTEM_ID 12
#define SMPP_ESM_MM_FORWARD 38
#define DICT_SMS_TPDU_UD 107
#define SMPP_RD_SMSCDR_NO 64
#define MAP_SCDA 97
#define HLR_NNN 110
#define MODIFIER 233
#define SMPP_DC_ISO_8859_8 80
#define SMPP_RD_SMEOA_BOTH 70
#define <API key> 27
#define DCS_DEFAULT 148
#define WORD 251
#define SMPP_RD_SMEOA_ACK 68
#define HLR_ANNN 111
#define <API key> 45
#define SCCP_GT_CALLED_WL 4
#define <API key> 53
#define ALWU_Q 181
#define <API key> 84
#define SMPP_PROTOCOL_ID 24
#define L_PAREN 184
#define NP_UNKNOWN 129
#define NP_DATA_X121 132
#define HLR_SCA 112
#define SMPP_NP_TELEX 57
#define SMPP_ESM_MM_DEFAULT 36
#define SMPP_NP_UNKNOWN 54
#define NEQUAL 202
#define <API key> 31
#define RULE 173
#define SCCP_GT_CALLING_NAI 91
#define ON 196
#define <API key> 48
#define SMPP_RD_SME_ACK 29
#define LOCAL_IP 239
#define TON_INTERNATIONAL 123
#define SMS_TPDU_DCS 120
#define SMPP_RECIPIENT_TON 18
#define <API key> 33
#define LIST 172
#define RULE_EVAL_FALSE 228
#define NAI_UNKNOWN 138
#define SMPP_NP_ERMES 61
#define <API key> 20
#define <API key> 104
#define FLOOD 163
#define NOT_IN 175
#define R_SQ_B 186
#define FILTER_NODE 221
#define OR 201
#define M3UA_DPC 100
#define SMPP_NP_LAND_MOBILE 58
#define NO_DR 160
#define <API key> 152
#define SMPP_NP_DATA_X121 56
#define SCCP_GT_CALLING_NP 93
#define HLR_MSISDN 109
#define CONVERT_SMPP 162
#define DIGITS 250
#define REMOTE_PORT 242
#define REGEX_BLOCK 218
#define GTE 210
#define ALWU 180
#define L_CR_B 188
#define SCCP_GT_CALLED_NAI 90
#define SMPP_DC_PICTOGRAM 82
#define SMPP_PASSWORD 13
#define F_M3UA 195
#define AND 213
#define SMPP_DC_ISO_2011_JP 83
#define SMPP_SM 35
#define LTE 209
#define ANNT 198
#define DNY 182
#define SCCP_GT_CALLING_WL 5
#define ALW 178
#define ML_COMMENT 253
#define FLOOD_MINUTE 169
#define GTI_TT 145
#define IN 174
#define IP 252
#define SMPP_TON_UNKNOWN 47
#define SMPP_ORIGINATOR_TON 15
#define COMMA 220
#define <API key> 39
#define EQUAL 199
#define SMPP_NP_INTERNET_IP 62
#define HLR_RESULT_IMSI 113
#define SMS_MSG_TYPE 121
#define CONN_SC 247
#define <API key> 55
#define SMPP_PRIORITY_FLAG 25
#define TON_ALPHANUMERIC 127
#define GTI_TTNPE 146
#define PERCENT 205
#define <API key> 17
#define MAP_SCOA 96
#define CONVERT_SS7 161
#define SCCP_GT_CALLING_TT 89
#define SMPP_RECIPIENT_NP 19
#define CONN_RC 246
#define TON_NATIONAL 124
#define SMPP_TCP_SOURCE 10
#define FLOOD_MAX 164
#define R_PAREN 185
#define <API key> 37
#define MAP_SCDA_WL 7
#define SPAM_UPDATE_LST 153
#define RULE_EVAL_POINTS 229
#define CONT 176
#define <API key> 66
#define SMPP_SM_LENGTH 34
#define SMPP_DC_UCS2 81
#define ASSIGN 200
#define <API key> 28
#define FLOOD_HOUR 168
#define CONN_OPC 244
#define MODIFIER_LABEL 236
#define RULE_LABEL 232
#define <API key> 46
#define <API key> 50
#ifdef EOF
#undef EOF
#define EOF ANTLR3_TOKEN_EOF
#endif
#ifndef TOKENSOURCE
#define TOKENSOURCE(lxr) lxr->pLexer->rec->state->tokSource
#endif
#ifdef __cplusplus
}
#endif
#endif
/* END - Note:Keep extra line feed to satisfy UNIX systems */ |
<?php
// Moodle is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Moodle is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
defined('MOODLE_INTERNAL') || die();
$string['downloadas'] = 'Descargar datos de tabla como {$a->formatsmenu} {$a->downloadbutton}';
$string['downloadcsv'] = 'Archivo de texto con valores separados por comas';
$string['downloadexcel'] = 'Hoja de cálculo en formato: Microsoft Excel';
$string['downloadods'] = 'Hoja de cálculo en formato OpenDocument (ODS)';
$string['downloadoptions'] = 'Elija las opciones de descarga';
$string['downloadtsv'] = 'Archivo de texto con valores separados por tabuladores';
$string['downloadxhtml'] = 'Documento XHTML no paginado'; |
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_07) on Wed Dec 08 12:09:11 CET 2010 -->
<TITLE>
Uses of Package de.wwu.muggl.symbolic.structures
</TITLE>
<META NAME="date" CONTENT="2010-12-08">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package de.wwu.muggl.symbolic.structures";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?de/wwu/muggl/symbolic/structures/package-use.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<CENTER>
<H2>
<B>Uses of Package<br>de.wwu.muggl.symbolic.structures</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../de/wwu/muggl/symbolic/structures/package-summary.html">de.wwu.muggl.symbolic.structures</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#de.wwu.muggl.vm.impl.symbolic"><B>de.wwu.muggl.vm.impl.symbolic</B></A></TD>
<TD>Provides the symbolic virtual machine implementation. </TD>
</TR>
</TABLE>
<P>
<A NAME="de.wwu.muggl.vm.impl.symbolic"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Classes in <A HREF="../../../../../de/wwu/muggl/symbolic/structures/package-summary.html">de.wwu.muggl.symbolic.structures</A> used by <A HREF="../../../../../de/wwu/muggl/vm/impl/symbolic/package-summary.html">de.wwu.muggl.vm.impl.symbolic</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><B><A HREF="../../../../../de/wwu/muggl/symbolic/structures/class-use/Loop.html#de.wwu.muggl.vm.impl.symbolic"><B>Loop</B></A></B>
<BR>
A Loop symbolizes a sequence of instructions that form a loop in the program flow.</TD>
</TR>
</TABLE>
<P>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?de/wwu/muggl/symbolic/structures/package-use.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
</BODY>
</HTML> |
## GA5
`GA5` is equivalent to `DiracGamma[5]` and denotes $\gamma^5$.
See also
[Overview](Extra/FeynCalc.md), [DiracGamma](DiracGamma.md), [GA](GA.md), [GS](GS.md).
Examples
mathematica
GA5
% // StandardForm
$$\bar{\gamma }^5$$
(*DiracGamma[5]*) |
#ifndef HEADER_NET_ETHER
#define HEADER_NET_ETHER
#include <stdint.h>
#define ETH_TYPE_IP 0x0080
#define ETH_TYPE_IPv6 0xDD86
struct ETH_HEADER {
uint8_t dst_mac[6];
uint8_t src_mac[6];
uint16_t len_type;
};
void eth_handler(struct ETH_HEADER *eth, int len);
#endif
#include "debug.h"
static char *get_mac_str(uint8_t *mac);
void eth_handler(struct ETH_HEADER *eth, int len)
{
dbgf("len = %d\n", len);
dbgf("mac: %s => ", get_mac_str(eth->dst_mac));
dbgf("%s\n", get_mac_str(eth->src_mac));
dbgf("type = %X: ", eth->len_type);
if (eth->len_type == ETH_TYPE_IP)
{
dbgf("IP\n");
}
else if (eth->len_type == ETH_TYPE_IPv6)
{
dbgf("IPv6\n");
}
else
{
dbgf("Unknown\n");
}
}
static char *get_mac_str(uint8_t *mac)
{
static char s[32];
snprintf(s, 32, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return s;
} |
import React, { Component } from "react";
import PropTypes from "prop-types";
import classNames from "classnames";
import IconComposer from "global/components/utility/IconComposer";
export default class Notification extends Component {
static propTypes = {
id: PropTypes.string,
heading: PropTypes.string,
body: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
level: PropTypes.number,
removeNotification: PropTypes.func,
style: PropTypes.string
};
// Close notification in handler in case event access is required
handleClose = () => {
this.props.removeNotification(this.props.id);
};
get wrapperClass() {
return classNames({
notification: true,
"<API key>": this.props.level === 0,
"<API key>": this.props.level === 1,
"notification--error": this.props.level === 2,
"<API key>": this.props.style === "drawer",
"<API key>": this.props.style === "header"
});
}
bodyCopy() {
let output = null;
if (this.props.body) {
output = <p className="notification__body">{this.props.body}</p>;
}
return output;
}
render() {
return (
<div className={this.wrapperClass} key={this.props.id}>
<div className="<API key>">
<div role="status">
<p className="<API key>">{this.props.heading}</p>
</div>
{this.bodyCopy()}
<button
className="<API key>"
onClick={this.handleClose}
data-id="close"
>
<IconComposer
icon="close32"
size={36}
iconClass="<API key>"
/>
<span className="screen-reader-text">{"Dismiss"}</span>
</button>
</div>
</div>
);
}
} |
<?php
namespace CViniciusSDias\GoogleCrawler\Proxy;
use CViniciusSDias\GoogleCrawler\Exception\<API key>;
use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;
/**
* Class that for using the kproxy.com servers
*
* @package CViniciusSDias\GoogleCrawler\Proxy
* @author Vinicius Dias
*/
class KProxy implements <API key>
{
/** @var string $endpoint */
protected $endpoint;
/** @var int $serverNumber */
protected $serverNumber;
/**
* Constructor that initializes the proxy service in one of its servers, which go from 1 to 9
*
* @param int $serverNumber
*/
public function __construct(int $serverNumber)
{
if ($serverNumber > 9 || $serverNumber < 1) {
throw new \<API key>();
}
$this->serverNumber = $serverNumber;
$this->endpoint = "http://server{$serverNumber}.kproxy.com";
}
/**
* {@inheritdoc}
* @throws \GuzzleHttp\Exception\ServerException If the proxy was overused
* @throws \GuzzleHttp\Exception\ConnectException If the proxy is unavailable
*/
public function getHttpResponse(string $url): ResponseInterface
{
$httpClient = new Client(['cookies' => true]);
$this->accessMainPage($httpClient);
$this->sendRequestToProxy($httpClient, $url);
$parsedUrl = parse_url($url);
$queryString = $parsedUrl['query'];
$actualUrl = "{$this->endpoint}/servlet/redirect.srv/swh/suxm/sqyudex/spqr/p1/search?{$queryString}";
return $httpClient->request('GET', $actualUrl);
}
/**
* Accesses the main page of the kproxy.com server. This is mandatory.
*
* @param Client $httpClient
*/
private function accessMainPage(Client $httpClient): void
{
$httpClient->request('GET', "{$this->endpoint}/index.jsp");
}
/** {@inheritdoc} */
public function parseUrl(string $url): string
{
$parsedUrl = parse_url($url);
parse_str($parsedUrl['query'], $link);
if (!array_key_exists('q', $link)) {
// Generally a book suggestion
throw new <API key>();
}
$url = filter_var($link['q'], FILTER_VALIDATE_URL);
// If this is not a valid URL, so the result is (probably) an image, news or video suggestion
if (!$url) {
throw new <API key>();
}
return $url;
}
/**
* Sends the request to the proxy service that saves the info in session. After this we can redirect
* the user to the search results
*
* @param Client $httpClient
* @param string $url
*/
private function sendRequestToProxy(Client $httpClient, string $url): void
{
$encodedUrl = urlencode($url);
$postData = ['page' => $encodedUrl, 'x' => 0, 'y' => 0];
$headers = [
'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
];
$httpClient->request(
'POST',
"{$this->endpoint}/doproxy.jsp",
['form_params' => $postData, 'headers' => $headers]
);
}
} |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>TestResult xref</title>
<link type="text/css" rel="stylesheet" href="../../../stylesheet.css" />
</head>
<body>
<div id="overview"><a href="../../../../testapidocs/fspotcloud/botdispatch/bot/TestResult.html">View Javadoc</a></div><pre>
<a class="jxr_linenumber" name="1" href="#1">1</a> <strong class="jxr_keyword">package</strong> fspotcloud.botdispatch.bot;
<a class="jxr_linenumber" name="2" href="#2">2</a>
<a class="jxr_linenumber" name="3" href="#3">3</a> <strong class="jxr_keyword">import</strong> java.io.Serializable;
<a class="jxr_linenumber" name="4" href="#4">4</a>
<a class="jxr_linenumber" name="5" href="#5">5</a> <strong class="jxr_keyword">import</strong> net.customware.gwt.dispatch.shared.Result;
<a class="jxr_linenumber" name="6" href="#6">6</a>
<a class="jxr_linenumber" name="7" href="#7">7</a> <strong class="jxr_keyword">import</strong> com.google.gwt.user.client.rpc.IsSerializable;
<a class="jxr_linenumber" name="8" href="#8">8</a>
<a class="jxr_linenumber" name="9" href="#9">9</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">class</strong> <a href="../../../fspotcloud/botdispatch/bot/TestResult.html">TestResult</a> <strong class="jxr_keyword">implements</strong> Result, IsSerializable, Serializable{
<a class="jxr_linenumber" name="10" href="#10">10</a>
<a class="jxr_linenumber" name="11" href="#11">11</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="12" href="#12">12</a> <em class="jxr_javadoccomment"> * </em>
<a class="jxr_linenumber" name="13" href="#13">13</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="14" href="#14">14</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">final</strong> <strong class="jxr_keyword">long</strong> serialVersionUID = 2320328423L;
<a class="jxr_linenumber" name="15" href="#15">15</a> <strong class="jxr_keyword">private</strong> String message;
<a class="jxr_linenumber" name="16" href="#16">16</a>
<a class="jxr_linenumber" name="17" href="#17">17</a> TestResult() {
<a class="jxr_linenumber" name="18" href="#18">18</a> }
<a class="jxr_linenumber" name="19" href="#19">19</a> <strong class="jxr_keyword">public</strong> <a href="../../../fspotcloud/botdispatch/bot/TestResult.html">TestResult</a>(String message) {
<a class="jxr_linenumber" name="20" href="#20">20</a> <strong class="jxr_keyword">this</strong>.message = message;
<a class="jxr_linenumber" name="21" href="#21">21</a> }
<a class="jxr_linenumber" name="22" href="#22">22</a> <strong class="jxr_keyword">public</strong> String getMessage() {
<a class="jxr_linenumber" name="23" href="#23">23</a> <strong class="jxr_keyword">return</strong> message;
<a class="jxr_linenumber" name="24" href="#24">24</a> }
<a class="jxr_linenumber" name="25" href="#25">25</a>
<a class="jxr_linenumber" name="26" href="#26">26</a> }
</pre>
<hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body>
</html> |
{-|
Module : Export.<API key>
Description : Primarily defines a function used to render SVGs with times.
-}
module Export.<API key>
(renderTable, renderTableHelper, times) where
import Data.List (intersperse)
import qualified Data.Text as T
import Diagrams.Backend.SVG
import Diagrams.Prelude
days :: [T.Text]
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
-- |A list of lists of Texts, which has the "times" from 8:00 to 12:00, and
-- 1:00 to 8:00.times
times :: [[T.Text]]
times = map (\x -> [T.pack (show x ++ ":00")]) ([8..12] ++ [1..8] :: [Int])
blue3 :: Colour Double
blue3 = sRGB24read "#437699"
pink1 :: Colour Double
pink1 = sRGB24read "#DB94B8"
pomegranate :: Colour Double
pomegranate = sRGB24read "#F20C00"
cellWidth :: Double
cellWidth = 2
timeCellWidth :: Double
timeCellWidth = 1.2
cellHeight :: Double
cellHeight = 0.4
cellPaddingHeight :: Double
cellPaddingHeight = 0.1
fs :: Double
fs = 14
cell :: Diagram B
cell = rect cellWidth cellHeight
cellPadding :: Diagram B
cellPadding = rect cellWidth cellPaddingHeight
timeCell :: Diagram B
timeCell = rect timeCellWidth cellHeight # lw none
timeCellPadding :: Diagram B
timeCellPadding = rect timeCellWidth cellPaddingHeight # lw none
cellText :: T.Text -> Diagram B
cellText s = font "Trebuchet MS" $ text (T.unpack s) # fontSizeO (1024/900 * fs)
-- | Creates and accumulates cells according to the number of course.
makeCell :: Int -> [T.Text] -> Diagram B
makeCell maxCourse sList =
let actualCourse = length sList
emptyCellNum = if maxCourse == 0 then 1 else maxCourse - actualCourse
extraCell = replicate emptyCellNum [cellPadding # fc white # lc white, cellText "" # fc white <> cell # fc white # lc white]
in vsep 0.030 $
concat $ map (\x -> [cellPadding # fc background # lc background, cellText x # fc white <> cell # fc background # lc background]) sList ++ extraCell
where
background = getBackground sList
getBackground :: [T.Text] -> Colour Double
getBackground s
| null s = white
| length s == 1 = blue3
| otherwise = pomegranate
header :: T.Text -> Diagram B
header session = hcat (makeSessionCell session : map makeHeaderCell days)
makeSessionCell :: T.Text -> Diagram B
makeSessionCell s =
timeCellPadding === (cellText s <> timeCell)
makeHeaderCell :: T.Text -> Diagram B
makeHeaderCell s =
(cellPadding
makeTimeCell :: T.Text -> Diagram B
makeTimeCell s =
timeCellPadding === (cellText s <> timeCell)
makeRow :: [[T.Text]] -> Diagram B
makeRow ([x]:xs) =
let maxCourse = maximum (map length xs)
in (# centerX) . hcat $
makeTimeCell x : map (makeCell maxCourse) xs
makeRow _ = error "invalid timetable format"
headerBorder :: Diagram B
headerBorder = hrule 11.2 # lw medium # lc pink1
rowBorder :: Diagram B
rowBorder = hrule 11.2 # lw thin # lc pink1
makeTable :: [[[T.Text]]] -> T.Text -> Diagram B
makeTable s session = vsep 0.04 $ header session: intersperse rowBorder (map makeRow s)
-- |Creates a timetable by zipping the time and course tables.
renderTable :: String -> T.Text -> T.Text -> IO ()
renderTable filename courses session = do
let courseTable = partition5 $ map (\x -> [x | not (T.null x)]) $ T.splitOn "_" courses
renderTableHelper filename (zipWith (:) times courseTable) session
where
partition5 [] = []
partition5 lst = take 5 lst : partition5 (drop 5 lst)
-- |Renders an SVG with a width of 1024, though the documentation doesn't
-- specify the units, it is assumed that these are pixels.
renderTableHelper :: String -> [[[T.Text]]] -> T.Text -> IO ()
renderTableHelper filename schedule session = do
let g = makeTable schedule session
renderSVG filename (mkWidth 1024) g |
package hcm.ssj.core.event;
import java.util.Arrays;
import hcm.ssj.core.Cons;
public class FloatEvent extends Event {
public float[] data;
public FloatEvent() {
type = Cons.Type.FLOAT;
data = null;
}
public FloatEvent(float[] data) {
type = Cons.Type.FLOAT;
this.data = data;
}
public float[] ptr() {
return data;
}
public float[] ptrF() {
return data;
}
public String ptrStr() {
return Arrays.toString(data);
}
public void setData(Object data) {
this.data = (float[])data;
}
public void setData(float[] data) {
this.data = data;
}
} |
#include <float.h>
#include <math.h>
#include <time.h>
#include <assert.h>
#include "pbl.h"
double getMillSecond() {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
return ts.tv_sec*1000.0 + ts.tv_nsec/1000000.0;
}
void initFloat(size_t len, float* d) {
for(size_t i = 0; i < len; i++) { |
package net.mcwintercraft.wintercraft.holidays;
import org.bukkit.event.Listener;
public class NewYear implements Listener {
//TODO: HAPPY NEW YEAR, FIREWORKS
} |
#import "<API key>.h"
#import "SBAppSwitcherModel.h"
#import "SBDisplayItem.h"
#import "<API key>.h"
#import "<API key>.h"
#import "<API key>.h"
#import "<API key>.h" |
data = {
".*(coucou|bonjour|salut).*": ["joue:salut", "joue:bonjour", "joue:coucou"],
".*(comment tu t'appelles|comment t'appelles tu|quel est ton nom).*": ["joue:mon_nom_est_milo", "joue:je_mappelle_milo"],
".*(ça va|comment ça va|comment vas tu|comment tu vas).*": ["joue:ca_va_bien_et_toi", "joue:ca_va_merci_et_toi"],
".*(que fais tu|tu fais quoi).*": ["joue:<API key>", "joue:rien_je_mennuie"],
".*(tu es |es tu) occupé.*": ["joue:<API key>"],
".*(raconte.*moi|fais moi|tu connais).*(blague|histoire).*": ["joue:blague_du_papier","joue:blague_racine"],
".*(qui es tu|parle moi de toi|(raconte moi|quelle est) ton histoire|(présente toi|peux tu te présenter)).*": ["joue:presentation"],
".*(qui sont).*(créateurs).*": ["joue:createurs"],
".*qu.*(tu.*aime|aime.*tu).*": ["joue:jaime_linformatique", "joue:jaime_parler", "joue:jaime_le_chocolat"],
".*(pense|mot).*jury.*": ["joue:jury"],
".*qu.*age.*": ["joue:immortel"],
".*pourquoi.*grandes oreilles.*": ["joue:pour_mieux_tecouter"],
".*qu.*m.*aime.*": ["joue:bien_sur","joue:qui_ne_taime_pas","joue:difficile_aimer"],
".*tu.*aime.*lycée.*": ["joue:lycee"],
".*ressens.*sentiments.*": ["joue:bien_sur","joue:question_vexante"],
".*(tes créateurs|eliott).*gentil.*toi.*": ["joue:adorable"],
".*(oriane|amandine).*gentille.*toi.*": ["joue:adorable", "joue:gentille"],
".*(eliott|oriane|amandine).*bonne note.*": ["joue:bien_sur"],
".*(quel|comment|parle).*futur.*": ["joue:futur"],
".*quoi.*(crois.*tu|tu.*crois).*": ["joue:je_crois_humanite","joue:je_crois_createurs"],
".*qu.*nourris.*": ["joue:nourriture"],
".*pense.*intelligent.*": ["joue:<API key>"],
".*es.*(lapin|robot).*": ["joue:je_suis_chat"],
".*qu.*souhaite.*": ["joue:milo_president","joue:des_carottes","joue:soeur"],
".*qu.*programme politique.*": ["joue:interner_createurs","joue:paye_karrotz","joue:domination_lapin"],
".*pourquoi.*appelle.*milo.*": ["joue:coup_tordu","joue:nom_question"],
".*(ai|veu).*carottes.*": ["joue:des_carottes","joue:a_moi","joue:carotte_pas_fraiche"],
".*pense.*tu.*cortana.*": ["joue:cortana"],
".*(joue|chante).*(chanson|musique).*": ["joue:i_kissed_a_girl", "joue:si_je_men_sors", "joue:trem_bala"],
".*bonne nuit.*": ["execute:sudo killall -s 9 main.py && sudo poweroff"],
}
default = ["joue:pas_compris", "joue:pas_compris_repete", "joue:<API key>"] |
--TEST
method overloading with different method signature
--INI
error_reporting=8191
--FILE
<?php
class test {
function foo() {}
}
class test2 extends test {
function foo() {}
}
class test3 extends test {
function foo($arg) {}
}
echo "Done\n";
?>
--EXPECTF
Strict Standards: Declaration of test3::foo() should be compatible with that of test::foo() in %s on line %d
Done |
/* Calling bose(n) generates a network
* to sort n items. See R. C. Bose & R. J. Nelson,
* "A Sorting Problem", JACM Vol. 9, Pp. 282-296. */
#include <stdio.h>
P(int i, int j)
{
/* print out in 0 based notation */
printf("swap(%d, %d);\n", i-1, j-1);
}
void Pbracket(int i, /* value of first element in sequence 1 */
int x, /* length of sequence 1 */
int j, /* value of first element in sequence 2 */
int y) /* length of sequence 2 */
{
int a, b;
if(x == 1 && y == 1)
P(i, j); /* 1 comparison sorts 2 items */
else if(x == 1 && y == 2)
{
/* 2 comparisons inserts an item into an
* already sorted sequence of length 2. */
P(i, (j + 1));
P(i, j);
}
else if(x == 2 && y == 1)
{
/* As above, but inserting j */
P(i, j);
P((i + 1), j);
}
else
{
/* Recurse on shorter sequences, attempting
* to make the length of one subsequence odd
* and the length of the other even. If we
* can do this, we eventually merge the two. */
a = x/2;
b = (x & 1) ? (y/2) : ((y + 1)/2);
Pbracket(i, a, j, b);
Pbracket((i + a), (x - a), (j + b), (y - b));
Pbracket((i + a), (x - a), j, b);
}
}
void Pstar(int i, /* value of first element in sequence */
int m) /* length of sequence */
{
int a;
if(m > 1)
{
/* Partition into 2 shorter sequences,
* generate a sorting method for each,
* and merge the two sub-networks. */
a = m/2;
Pstar(i, a);
Pstar((i + a), (m - a));
Pbracket(i, a, (i + a), (m - a));
}
}
void bose(int n)
{
Pstar(1, n); /* sort the sequence {X1,...,Xn} */
}
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("Usage:\n");
printf("\t bose-nelson <n>\n");
printf("\t\twhere n is the number of items to sort\n");
return(-1);
}
int n = atoi(argv[1]);
bose(n);
return 0;
}
/* End of File */ |
#include "ValidateTraverser.h"
#include "Checksum.h"
#include "Backup.h"
#include "IOBuffer.h"
/*! Default constructor
*/
ValidateTraverser::ValidateTraverser()
{
m_sizeOfBackupPath = 0;
}
/*! \returns Returns the digests map.
*
*/
DigestsMap &ValidateTraverser::digests()
{
return m_digests;
}
/*! Set the current backup path
*
* \param path the absolute path to the current backup path
*/
void ValidateTraverser::setBackupPath(const QString &path)
{
m_backupPath = path;
m_sizeOfBackupPath = path.length();
}
void ValidateTraverser::evaluate(SnapshotMetaInfo &metaInfo)
{
if (metaInfo.fileCount() != files()) {
emit report(tr("%1 files expected, but %2 files found.").arg(metaInfo.fileCount()).arg(files()) + "<br>");
countError();
}
if (metaInfo.dataSize() != processed()) {
emit report(tr("%1 Bytes expected, but %2 Bytes found.").arg(metaInfo.dataSize()).arg(processed()) + "<br>");
countError();
}
QList<QString> keys = m_digests.keys();
if (keys.size() > 0) {
report(tr("The following files are missing in the backup snapshot:") + "<br>");
for (int i = 0; i < keys.size(); i++) {
if (i < 25) {
emit report(keys[i] + "<br>");
} else if (i == 25) {
emit report(tr("More files are missing...") + "<br>");
}
countFile();
}
emit report("<br>");
}
if (Backup::instance().config().verifyDigest() == false) {
emit report(tr("WARNING: Content digests not verified (disabled).") + "<br>");
}
if (errors() > 0) {
metaInfo.setQuality(SnapshotMetaInfo::Unknown);
emit report(tr("Backup snapshot status set to 'Unknown'.") + "<br><br>");
} else {
metaInfo.setQuality(SnapshotMetaInfo::Reliable);
emit report(tr("All files validated, Backup snapshot is reliable.") + "<br><br>");
}
}
/*! Create a digest of the file content.
*
* The number of processed bytes are added to byte counter.
* Digest computing can be aborted by flagging.
*
* \param sourcefilename the absolute path to the file to be copied
* \return Computed digest of the file content
*/
QByteArray ValidateTraverser::computeDigestOfFile(const QString &sourcefilename)
{
Checksum checksum;
qint64 bytesRead;
bool success;
QFile source(sourcefilename);
success = source.open(QIODevice::ReadOnly);
if (!success) {
return QByteArray();
}
IOBuffer &iobuffer = IOBuffer::instance();
do {
iobuffer.begin();
bytesRead = source.read(iobuffer.buffer().data(), iobuffer.chunkSize());
checksum.update(iobuffer.buffer(), bytesRead);
iobuffer.finished();
countProcessed(bytesRead);
countTransferred(bytesRead);
} while (bytesRead == iobuffer.chunkSize() && !shouldAbort());
return checksum.finish();
}
/*! Is called during directory traversal if a file was found.
*
* \param absoluteFilePath the absolute path to the found file
*/
void ValidateTraverser::onFile(const QString &absoluteFilePath)
{
QString key = "." + absoluteFilePath.mid(m_sizeOfBackupPath);
if (Backup::instance().config().verifyDigest()) {
QByteArray previousDigest = m_digests.value(key);
QByteArray currentDigest = computeDigestOfFile(absoluteFilePath);
if (previousDigest != currentDigest) {
if (errors() < 25) {
emit report(tr("File '%1' has beed modified.").arg(absoluteFilePath) + "<br>");
} else if (errors() == 25) {
emit report(tr("More files have been modified...") + "<br>");
}
countError();
}
} else {
QFile file(absoluteFilePath);
countProcessed(file.size());
}
m_digests.remove(key);
countFile();
} |
# Windows template platform definition CMake file
# Included from ../CMakeLists.txt
# remember that the current source dir is the project root; this file is in Win/
file (GLOB PLATFORM RELATIVE ${<API key>}
Win/[^.]*.cpp
Win/[^.]*.h
Win/[^.]*.cmake
)
# use this to add preprocessor definitions
add_definitions(
/D "<API key>"
)
SOURCE_GROUP(Win FILES ${PLATFORM})
set (SOURCES
${SOURCES}
${PLATFORM}
)
add_windows_plugin(${PROJECT_NAME} SOURCES)
# This is an example of how to add a build step to sign the plugin DLL before
# the WiX installer builds. The first filename (certificate.pfx) should be
# the path to your pfx file. If it requires a passphrase, the passphrase
# should be located inside the second file. If you don't need a passphrase
# then set the second filename to "". If you don't want signtool to timestamp
# your DLL then make the last parameter "".
# Note that this will not attempt to sign if the certificate isn't there --
# that's so that you can have development machines without the cert and it'll
# still work. Your cert should only be on the build machine and shouldn't be in
# source control!
# -- uncomment lines below this to enable signing --
#<API key>(${PROJECT_NAME}
# "${<API key>}/sign/certificate.pfx"
# "${<API key>}/sign/passphrase.txt"
# add library dependencies here; leave ${<API key>} there unless you know what you're doing!
<API key>(${PROJECT_NAME}
${<API key>}
${<API key>}
)
set(WIX_HEAT_FLAGS
-gg # Generate GUIDs
-srd # Suppress Root Dir
-cg PluginDLLGroup # Set the Component group name
-dr INSTALLDIR # Set the directory ID to put the files in
)
add_wix_installer( ${PLUGIN_NAME}
${<API key>}/Win/WiX/AXRInstaller.wxs
PluginDLLGroup
${FB_BIN_DIR}/${PLUGIN_NAME}/${CMAKE_CFG_INTDIR}/
${FB_BIN_DIR}/${PLUGIN_NAME}/${CMAKE_CFG_INTDIR}/${<API key>}.dll
${PROJECT_NAME}
)
# This is an example of how to add a build step to sign the WiX installer
# -- uncomment lines below this to enable signing --
#<API key>("${PLUGIN_NAME}_WiXInstall"
# "${FB_BIN_DIR}/${PLUGIN_NAME}/${CMAKE_CFG_INTDIR}/${PLUGIN_NAME}.msi"
# "${<API key>}/sign/certificate.pfx"
# "${<API key>}/sign/passphrase.txt"
# This is an example of how to create a cab
# -- uncomment lines below this to enable signing --
#create_cab(${PLUGIN_NAME}
# ${<API key>}/Win/Wix/AXR.ddf
# ${<API key>}/Win/Wix/AXR.inf
# ${FB_BIN_DIR}/${PLUGIN_NAME}/${CMAKE_CFG_INTDIR}/
# ${PROJECT_NAME}_WiXInstallExe |
"use strict";
tutao.provide('tutao.entity.sys.SaltReturn');
/**
* @constructor
* @param {Object=} data The json data to store in this entity.
*/
tutao.entity.sys.SaltReturn = function(data) {
if (data) {
this.updateData(data);
} else {
this.__format = "0";
this._salt = null;
}
this._entityHelper = new tutao.entity.EntityHelper(this);
this.prototype = tutao.entity.sys.SaltReturn.prototype;
};
/**
* Updates the data of this entity.
* @param {Object=} data The json data to store in this entity.
*/
tutao.entity.sys.SaltReturn.prototype.updateData = function(data) {
this.__format = data._format;
this._salt = data.salt;
};
/**
* The version of the model this type belongs to.
* @const
*/
tutao.entity.sys.SaltReturn.MODEL_VERSION = '16';
/**
* The url path to the resource.
* @const
*/
tutao.entity.sys.SaltReturn.PATH = '/rest/sys/saltservice';
/**
* The encrypted flag.
* @const
*/
tutao.entity.sys.SaltReturn.prototype.ENCRYPTED = false;
/**
* Provides the data of this instances as an object that can be converted to json.
* @return {Object} The json object.
*/
tutao.entity.sys.SaltReturn.prototype.toJsonData = function() {
return {
_format: this.__format,
salt: this._salt
};
};
/**
* The id of the SaltReturn type.
*/
tutao.entity.sys.SaltReturn.prototype.TYPE_ID = 420;
/**
* The id of the salt attribute.
*/
tutao.entity.sys.SaltReturn.prototype.SALT_ATTRIBUTE_ID = 422;
/**
* Sets the format of this SaltReturn.
* @param {string} format The format of this SaltReturn.
*/
tutao.entity.sys.SaltReturn.prototype.setFormat = function(format) {
this.__format = format;
return this;
};
/**
* Provides the format of this SaltReturn.
* @return {string} The format of this SaltReturn.
*/
tutao.entity.sys.SaltReturn.prototype.getFormat = function() {
return this.__format;
};
/**
* Sets the salt of this SaltReturn.
* @param {string} salt The salt of this SaltReturn.
*/
tutao.entity.sys.SaltReturn.prototype.setSalt = function(salt) {
this._salt = salt;
return this;
};
/**
* Provides the salt of this SaltReturn.
* @return {string} The salt of this SaltReturn.
*/
tutao.entity.sys.SaltReturn.prototype.getSalt = function() {
return this._salt;
};
/**
* Loads from the service.
* @param {tutao.entity.sys.SaltData} entity The entity to send to the service.
* @param {Object.<string, string>} parameters The parameters to send to the service.
* @param {?Object.<string, string>} headers The headers to send to the service. If null, the default authentication data is used.
* @return {Promise.<tutao.entity.sys.SaltReturn>} Resolves to SaltReturn or an exception if the loading failed.
*/
tutao.entity.sys.SaltReturn.load = function(entity, parameters, headers) {
if (!headers) {
headers = tutao.entity.EntityHelper.createAuthHeaders();
}
parameters["v"] = 16;
return tutao.locator.entityRestClient.getService(tutao.entity.sys.SaltReturn, tutao.entity.sys.SaltReturn.PATH, entity, parameters, headers);
};
/**
* Provides the entity helper of this entity.
* @return {tutao.entity.EntityHelper} The entity helper.
*/
tutao.entity.sys.SaltReturn.prototype.getEntityHelper = function() {
return this._entityHelper;
}; |
#ifndef KOSTATE_H_INCLUDED
#define KOSTATE_H_INCLUDED
#include "config.h"
#include <vector>
#include "FastState.h"
#include "FullBoard.h"
class KoState : public FastState {
public:
void init_game(int size, float komi);
bool superko() const;
void reset_game();
void play_move(int color, int vertex);
void play_move(int vertex);
private:
std::vector<std::uint64_t> m_ko_hash_history;
};
#endif |
import scala.util.Random
/* An Interface provides methods for all interaction for a single player. This
* includes both interactive and non-interactive (ie, cpu player) instances.
*/
abstract class Interface {
// Yields a WonderSide for a given Wonder, or None on bad input
def chooseWonderSide(wonder: Wonder): Option[WonderSide]
// Yields an Action for a given player in a given GameState, or None on bad input
def chooseAction(p: PlayerState, g: GameState): Option[Action]
// Do special action for Babylon
def specialBabylon(p: PlayerState, g: GameState): Option[<API key>]
// Search discard pile for a Halikarnassos draw
def <API key>(p: PlayerState, g: GameState, newDiscards: List[Card]): Option[<API key>]
def persistRequest[T,S](a: (T => Option[S]))(p: T) = {
var result: Option[S] = None
while(result == None)
result = a(p)
result.get
}
// def persistWonderSide(wonder: Wonder) = persistRequest(chooseWonderSide) _
// def persistAction(p: PlayerState, g: GameState) = persistRequest(chooseAction) _
// def persistBabylon(p: PlayerState, g: GameState) = persistRequest(specialBabylon) _
// def <API key>(p: PlayerState, g: GameState, newDiscards: List[Card]) = persistRequest(<API key>.curry) _
}
// a non-interactive interface
abstract class AI extends Interface
/* Completely dumb AI. Always picks first card, discards if it can't be played. */
class DumbAI extends AI {
def chooseAction(p: PlayerState, g: GameState) = {
p.hand.cards.head.categorize(p, Resources(), Resources()) match {
case option: CardFree => Some(ActionPick(option))
case option => Some(ActionDiscard(option))
}
}
// Yields a WonderSide for a given Wonder, or None on bad input
def chooseWonderSide(wonder: Wonder): Option[WonderSide] = {
Some(wonder.sides(Random.nextInt(wonder.sides.length)))
}
// Do special action for Babylon
def specialBabylon(p: PlayerState, g: GameState): Option[<API key>] = None
// Search discard pile for a Halikarnassos draw
def <API key>(p: PlayerState, g: GameState, newDiscards: List[Card]): Option[<API key>] = None
}
/* Slightly less dumb AI - picks any available option randomly, including
* (random) trades.
*/
class SlightlyLessDumbAI extends AI {
def chooseAction(p: PlayerState, g: GameState) = {
Random.shuffle(p.hand.cards) map ( _.categorize(p, (p lefty g).resources, (p righty g).resources) ) collectFirst {
case o: CardFree => ActionPick(o)
case o: CardTrade => decideTrade(p, g, o) tradeOffer(p, o) getOrElse {
println("bad trade? this is a bug :(")
ActionDiscard(o)
}
} orElse {
Some(ActionDiscard(p.hand.cards(Random.nextInt(p.hand.cards.length))))
}
}
// Yields a WonderSide for a given Wonder, or None on bad input
def chooseWonderSide(wonder: Wonder): Option[WonderSide] = {
Some(wonder.sides(Random.nextInt(wonder.sides.length)))
}
// We don't build wonders so this can never happen
def specialBabylon(p: PlayerState, g: GameState): Option[<API key>] = None
// We don't build wonders so this can never happen
def <API key>(p: PlayerState, g: GameState, newDiscards: List[Card]): Option[<API key>] = None
def decideTrade(p: PlayerState, g: GameState, t: TradeOption): Trade = {
// random trade option
val costs = t.allCosts(p)
val pick = costs(Random.nextInt(costs.length))
Trade(pick._1, pick._2)
}
}
/* Specialized AI, always picks the option with maximum VP value.
*/
class SimpleGreedyAI extends AI {
def chooseAction(p: PlayerState, g: GameState) = {
val options = p.hand.cards map ( _.categorize(p, (p lefty g).resources, (p righty g).resources) ) collect {
case o: CardFree => ActionPick(o)
case o: CardTrade => decideTrade(p, g, o) tradeOffer(p, o) getOrElse {
println("bad trade? this is a bug :(")
ActionDiscard(o)
}
}
if(options.isEmpty)
Some(ActionDiscard(p.hand.cards.head))
else
Some(options maxBy( action => action(p, g)._1 totalvp(g) ))
}
// Yields a WonderSide for a given Wonder, or None on bad input
def chooseWonderSide(wonder: Wonder): Option[WonderSide] = {
Some(wonder.sides(Random.nextInt(wonder.sides.length)))
}
// We don't build wonders so this can never happen
def specialBabylon(p: PlayerState, g: GameState): Option[<API key>] = None
// We don't build wonders so this can never happen
def <API key>(p: PlayerState, g: GameState, newDiscards: List[Card]): Option[<API key>] = None
// Just pay the minimum costs
def decideTrade(p: PlayerState, g: GameState, t: TradeOption): Trade = {
// pick minimum costs, with a small penalty for lopsided distribution
val costs = t.allCosts(p) minBy ( x => (x._1 + x._2) + 0.1*(x._1-x._2).abs )
Trade(costs._1, costs._2)
}
}
object AI {
def random: AI = {
new SimpleGreedyAI()
}
} |
package au.id.villar.json;
public class JSONReaderException extends Exception {
public JSONReaderException(String message) {
super(message);
}
public JSONReaderException(Throwable cause) {
super(cause);
}
public JSONReaderException(String message, Throwable cause) {
super(message, cause);
}
} |
// NScD Oak Ridge National Laboratory, European Spallation Source
// & Institut Laue - Langevin
#ifndef <API key>
#define <API key>
#include "MantidQtWidgets/SliceViewer/NullPeaksPresenter.h"
#include "MockObjects.h"
#include <cxxtest/TestSuite.h>
#include <gmock/gmock.h>
using namespace MantidQt::SliceViewer;
class <API key> : public CxxTest::TestSuite {
public:
void test_construction() { <API key>(NullPeaksPresenter p); }
void <API key>() {
NullPeaksPresenter presenter;
PeaksPresenter &base =
presenter; // compile-time test for the is-a relationship
UNUSED_ARG(base);
}
/* Test individual methods on the interface */
void <API key>() {
NullPeaksPresenter presenter;
<API key>(presenter.update());
}
void <API key>() {
NullPeaksPresenter presenter;
PeakBoundingBox region;
<API key>(presenter.<API key>(region));
}
void <API key>() {
NullPeaksPresenter presenter;
TS_ASSERT(!presenter.changeShownDim(0, 1));
}
void <API key>() {
NullPeaksPresenter presenter;
TS_ASSERT(!presenter.isLabelOfFreeAxis(""));
}
void <API key>() {
NullPeaksPresenter presenter;
SetPeaksWorkspaces workspaces = presenter.presentedWorkspaces();
TS_ASSERT_EQUALS(0, workspaces.size());
}
void <API key>() {
NullPeaksPresenter presenter;
<API key>(presenter.setForegroundColor(PeakViewColor()));
}
void <API key>() {
NullPeaksPresenter presenter;
<API key>(presenter.setBackgroundColor(PeakViewColor()));
}
void <API key>() {
NullPeaksPresenter presenter;
<API key>(presenter.setShown(true));
<API key>(presenter.setShown(false));
}
return a box collapsed to a point at 0, 0.
void <API key>() {
NullPeaksPresenter presenter;
PeakBoundingBox result = presenter.getBoundingBox(0);
TS_ASSERT_EQUALS(0, result.left());
TS_ASSERT_EQUALS(0, result.right());
TS_ASSERT_EQUALS(0, result.top());
TS_ASSERT_EQUALS(0, result.bottom());
}
void <API key>() {
NullPeaksPresenter presenter;
<API key>(presenter.<API key>(1));
}
void <API key>() {
NullPeaksPresenter presenter;
<API key>(presenter.<API key>(1));
}
void <API key>() {
NullPeaksPresenter presenter;
TS_ASSERT_EQUALS(0, presenter.<API key>());
}
void <API key>() {
NullPeaksPresenter presenter;
TS_ASSERT_EQUALS(0, presenter.<API key>());
}
void <API key>() {
NullPeaksPresenter presenter;
MockPeaksPresenter other;
TS_ASSERT(presenter.contentsDifferent(&other));
}
void test_peakEditMode() {
NullPeaksPresenter presenter;
<API key>(presenter.peakEditMode(AddPeaks););
}
void test_deletePeaksIn() {
NullPeaksPresenter presenter;
PeakBoundingBox fake;
<API key>(presenter.deletePeaksIn(fake));
}
};
#endif |
<?php
/**
* @see Zend_Gdata_eed
*/
require_once 'Zend/Gdata/Feed.php';
/**
* @see Zend_Gdata_Media
*/
require_once 'Zend/Gdata/Media.php';
/**
* @see <API key>
*/
require_once 'Zend/Gdata/Media/Entry.php';
class <API key> extends Zend_Gdata_Feed
{
/**
* The classname for individual feed elements.
*
* @var string
*/
protected $_entryClassName = '<API key>';
/**
* Create a new instance.
*
* @param DOMElement $element (optional) DOMElement from which this
* object should be constructed.
*/
public function __construct($element = null)
{
$this-><API key>(Zend_Gdata_Media::$namespaces);
parent::__construct($element);
}
} |
<!DOCTYPE html>
<html lang="en"
xmlns:th="http:
<head>
<meta charset="UTF-8">
<title th:text="${name}"></title>
</head>
<body>
<p>Someone (hopefully you) requested we reset your password at <span th:text="${name}"></span>. If you want to change it, click</p>
<p><a th:href="${url}" th:text="${url}"></a></p>
<p>If not, just ignore this message.</p>
</body>
</html> |
#include "stdafx.h"
#include "ahumantarget.h"
//
//
class EffectorEndocrine : public MindEffector {
private:
bool continueRunFlag;
public:
EffectorEndocrine( EffectorArea *area );
virtual ~EffectorEndocrine();
virtual const char *getClass() { return( "EffectorEndocrine" ); };
public:
// effector lifecycle
virtual void createEffector( <API key> *createInfo );
virtual void configureEffector( Xml config );
virtual void startEffector() {};
virtual void stopEffector() {};
virtual void <API key>( NeuroLink *link , NeuroSignal *signal ) {};
private:
void <API key>( <API key> *createInfo , <API key> *connector );
void <API key>( <API key> *createInfo , <API key> *connector );
NeuroSignal *sourceHandler( NeuroLink *link , NeuroLinkSource *point );
NeuroSignalSet *targetHandler( NeuroLink *link , NeuroLinkTarget *point , NeuroSignal *srcData );
private:
Xml config;
};
MindEffector *AHumanTarget::createEndocrine( EffectorArea *area ) {
return( new EffectorEndocrine( area ) );
}
//
//
EffectorEndocrine::EffectorEndocrine( EffectorArea *p_area )
: MindEffector( p_area ) {
attachLogger();
continueRunFlag = false;
}
EffectorEndocrine::~EffectorEndocrine() {
}
void EffectorEndocrine::configureEffector( Xml p_config ) {
config = p_config;
}
void EffectorEndocrine::createEffector( <API key> *createInfo ) {
// set connectors
TargetRegionDef *info = MindEffector::getEffectorInfo();
MindRegionTypeDef *type = info -> getType();
ClassList<<API key>>& connectors = type -> getConnectors();
for( int k = 0; k < connectors.count(); k++ ) {
<API key> *connector = connectors.get( k );
if( connector -> isTarget() )
<API key>( createInfo , connector );
else
<API key>( createInfo , connector );
}
}
void EffectorEndocrine::<API key>( <API key> *createInfo , <API key> *connector ) {
NeuroLinkSource *source = new NeuroLinkSource();
source -> create( this , connector -> getId() );
source -> setHandler( ( MindRegion::<API key> )&EffectorEndocrine::sourceHandler );
}
void EffectorEndocrine::<API key>( <API key> *createInfo , <API key> *connector ) {
NeuroLinkTarget *target = new NeuroLinkTarget();
target -> create( this , connector -> getId() );
target -> setHandler( ( MindRegion::<API key> )&EffectorEndocrine::targetHandler );
}
NeuroSignal *EffectorEndocrine::sourceHandler( NeuroLink *link , NeuroLinkSource *point ) {
return( NULL );
}
NeuroSignalSet *EffectorEndocrine::targetHandler( NeuroLink *link , NeuroLinkTarget *point , NeuroSignal *srcData ) {
return( NULL );
} |
/* program str07.c */
/* demo string application */
#include <string.h>
main()
{
void tlb(char **);
void ttb(char **);
char *s = " Turbo C ";
tlb(&s);
ttb(&s);
printf("%s\n",s);
}
void tlb(char **s) /* trancate leading blank */
{
int i;
for ( i=0 ; i<strlen(*s) ; i++ )
if ( *(*s+i) != ' ')
break;
*s = strchr(*s,*(*s+i));
}
void ttb(char **s) /* trancate backing blank */
{
int i;
for ( i=strlen(*s)-1 ; i>=0 ; i
if ( *(*s+i) != ' ')
break;
*(*s+i+1) = '\0';
}
|
#ifndef MAPDIALOG_H
#define MAPDIALOG_H
#include <QDialog>
#include "Global/vespucciworkspace.h"
class MainWindow;
namespace Ui {
class MapDialog;
}
class MapDialog : public QDialog
{
Q_OBJECT
public:
explicit MapDialog(MainWindow *parent, QStringList data_keys, QSharedPointer<VespucciWorkspace> ws);
~MapDialog();
private slots:
void <API key>();
void <API key>(int arg1);
private:
Ui::MapDialog *ui;
MainWindow *main_window_;
QSharedPointer<VespucciWorkspace> workspace_;
QSharedPointer<VespucciDataset> dataset_;
QStringList data_keys_;
};
#endif // MAPDIALOG_H |
<?php
namespace pocketmine\block;
class CocoaBlock extends Solid {
protected $id = self::COCOA_BLOCK;
public function __construct($meta = 0){
$this->meta = $meta;
}
public function getName(){
return "Cocoa Block";
}
} |
<?php
namespace Alchemy\Tests\Phrasea\Notification\Mail;
use Alchemy\Phrasea\Notification\Mail\<API key>;
/**
* @group functional
* @group legacy
* @covers Alchemy\Phrasea\Notification\Mail\<API key>
*/
class <API key> extends MailTestCase
{
public function getMail()
{
return <API key>::create(
$this->getApp(),
$this->getReceiverMock(),
$this->getEmitterMock(),
$this->getMessage()
);
}
} |
#include <mps/mps.h>
#include <string.h>
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifndef HAVE_STRNDUP
char *
mps_strndup (const char * source, size_t n)
{
char *dest;
size_t length = strlen (source);
/* Lower n if it's greater than the length of the original
* string that we should copy. */
if (length < n)
n = length;
dest = mps_newv (char, n + 1);
memmove (dest, source, n);
return dest;
}
#endif |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.7"/>
<title>Prototype 3D: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">Prototype 3D
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.7 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Packages</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Properties</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="<API key>">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespace_microsoft.html">Microsoft</a></li><li class="navelem"><a class="el" href="<API key>.html">Samples</a></li><li class="navelem"><a class="el" href="<API key>.html">Kinect</a></li><li class="navelem"><a class="el" href="<API key>.html">Avateering</a></li><li class="navelem"><a class="el" href="<API key>.html">CoordinateCross</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">Microsoft.Samples.Kinect.Avateering.CoordinateCross Member List</div> </div>
</div><!--header
<div class="contents">
<p>This is the complete list of members for <a class="el" href="<API key>.html">Microsoft.Samples.Kinect.Avateering.CoordinateCross</a>, including all inherited members.</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="<API key>.html#<API key>">CoordinateCross</a>(Game game, float axisLength)</td><td class="entry"><a class="el" href="<API key>.html">Microsoft.Samples.Kinect.Avateering.CoordinateCross</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="<API key>.html#<API key>"><API key></a>(float axisLength)</td><td class="entry"><a class="el" href="<API key>.html">Microsoft.Samples.Kinect.Avateering.CoordinateCross</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="<API key>.html#<API key>">Draw</a>(GameTime gameTime, Matrix world, Matrix view, Matrix projection)</td><td class="entry"><a class="el" href="<API key>.html">Microsoft.Samples.Kinect.Avateering.CoordinateCross</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="<API key>.html#<API key>">LoadContent</a>()</td><td class="entry"><a class="el" href="<API key>.html">Microsoft.Samples.Kinect.Avateering.CoordinateCross</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Wed May 28 2014 10:44:25 for Prototype 3D by &
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.7
</small></address>
</body>
</html> |
from flask_ask import audio, statement, question
from flask import request
from plexmusicplayer import ask, queue
# Amazon Playback - Intents
@ask.launch
def new_ask():
welcome = "Welcome to the Plex Music Player. What would you like to hear?"
reprompt = "I did not quite catch that. Could you repeat that please?"
return question(welcome) \
.reprompt(reprompt)
@ask.on_playback_started()
def started(offset):
offset /= 1000
print("Playback started at %s" % offset)
@ask.on_playback_stopped()
def stopped(offset):
offset /= 1000
print("Playback stopped at %s" % offset)
queue.current.set_offset(offset)
@ask.<API key>()
def nearly_finished():
next = queue.whats_next
if next:
return audio().enqueue(next.stream_url)
@ask.<API key>()
def play_back_finished():
if queue.whats_next:
queue.go_next()
@ask.intent('AMAZON.NextIntent')
def next_song():
if queue.whats_next:
return audio("").play(queue.go_next().stream_url)
else:
return audio("Sorry, something went wrong selecting the next song.").stop()
@ask.intent('AMAZON.PreviousIntent')
def previous_song():
if queue.whats_prev:
return audio("").play(queue.go_prev().stream_url)
else:
return audio("Sorry, something went wrong selecting the previous song.").stop()
@ask.intent('AMAZON.StartOverIntent')
def restart_track():
if queue.current:
return audio("").play(queue.current.stream_url, offset=0)
@ask.intent('AMAZON.PauseIntent')
def pause():
return audio("").stop()
@ask.intent('AMAZON.ResumeIntent')
def resume():
return audio("").resume()
@ask.intent('AMAZON.ShuffleOnIntent')
def shuffle():
queue.shuffle()
return statement("Playlist shuffled")
@ask.intent('AMAZON.StopIntent')
def stop():
return audio('Goodbye').clear_queue(stop=True)
@ask.session_ended
def session_ended():
return "", 200 |
/**
* \addtogroup LILodTool LodTool
* @{
*/
#include "lipsofsuna/model.h"
#include "lipsofsuna/system.h"
int main (int argc, char** argv)
{
int i;
LIMdlBuilder* builder;
LIMdlModel* model;
if (!argc || !strcmp (argv[1], "--help") || !strcmp (argv[1], "-h"))
{
printf ("Usage: %s [lmdl...]\n", argv[0]);
return 0;
}
for (i = 1 ; i < argc ; i++)
{
/* Load the model. */
model = <API key> (argv[i], 1);
if (model == NULL)
{
lisys_error_report ();
continue;
}
/* Check for existing LOD. */
if (!model->lod.array[0].indices.count)
{
printf (" Unneeded %s\n", argv[i]);
continue;
}
if (model->lod.count > 1)
{
printf ("%3d%%: Existing %s\n", 100 - 100 *
model->lod.array[model->lod.count - 1].indices.count /
model->lod.array[0].indices.count, argv[i]);
limdl_model_free (model);
continue;
}
/* Build the detail levels. */
builder = limdl_builder_new (model);
if (builder == NULL)
{
lisys_error_report ();
limdl_model_free (model);
continue;
}
<API key> (builder, 5, 0.05f);
<API key> (builder);
limdl_builder_free (builder);
/* Save the modified model. */
printf ("%3d%%: Built %s\n", 100 - 100 *
model->lod.array[model->lod.count - 1].indices.count /
model->lod.array[0].indices.count, argv[i]);
<API key> (model, argv[i]);
limdl_model_free (model);
}
return 0;
} |
#include "crud_marca.h"
CRUD_Marca::CRUD_Marca()
{
} |
#include "stdafx.h"
#include "CAutoFreeMemory.h"
#include "CException.h"
using namespace Unmanaged;
CAutoFreeMemory::CAutoFreeMemory(void* ptr) : CAutoFreeMemory(ptr, true)
{
}
CAutoFreeMemory::CAutoFreeMemory(void* ptr, bool verify) : _ptr(ptr)
{
if (verify && !_ptr)
throw CExceptionMemory();
}
CAutoFreeMemory::~CAutoFreeMemory()
{
Release();
}
void CAutoFreeMemory::ChangePointer(void* ptr, bool verify, bool releaseOld)
{
if (releaseOld)
Release();
_ptr = ptr;
if (verify && !_ptr)
throw CExceptionMemory();
}
void CAutoFreeMemory::Release()
{
if (_ptr)
{
free(_ptr);
_ptr = nullptr;
}
} |
#include "../config.h"
#if ENABLED(TOUCH_UI_FTDI_EVE)
#include "screens.h"
#include "../../../../../feature/host_actions.h"
using namespace ExtUI;
void <API key>::onRedraw(draw_mode_t) {
drawMessage(GET_TEXT_F(MSG_ABORT_WARNING));
drawYesNoButtons();
}
bool <API key>::onTouchEnd(uint8_t tag) {
switch (tag) {
case 1:
GOTO_PREVIOUS();
if (ExtUI::isPrintingFromMedia())
ExtUI::stopPrint();
#ifdef ACTION_ON_CANCEL
else host_action_cancel();
#endif
return true;
default:
return DialogBoxBaseClass::onTouchEnd(tag);
}
}
#endif // TOUCH_UI_FTDI_EVE |
<?php
//Check user identity
require "auth.php";
$debug = @$_GET['debug'];
include "header.php";
echo '<td width="100%" valign="top"><div dojoType="ContentPane" id="content" executeScripts="true" parseContent="true" cacheContent="false">';
include "default_content.php";
echo '</div></td></tr></table>';
if (isset($debug))
echo '<div dojoType="DebugConsole"'.
'title="Debug Window"'.
'style="width: 400px; position: absolute; height: 200px; left: 50px; top: 550px;"></div>';
include "footer.php";
?> |
// <summary>
// </summary>
namespace PdbReader
{
<summary>
</summary>
internal struct DbiDbgHdr
{
<summary>
</summary>
internal ushort snException; // 2..3 (deprecated)
<summary>
</summary>
internal ushort snFPO;
<summary>
</summary>
internal ushort snFixup;
<summary>
</summary>
internal ushort snNewFPO; // 18..19
<summary>
</summary>
internal ushort snOmapFromSrc;
<summary>
</summary>
internal ushort snOmapToSrc;
<summary>
</summary>
internal ushort snPdata; // 16..17
<summary>
</summary>
internal ushort snSectionHdr; // 10..11
<summary>
</summary>
internal ushort snSectionHdrOrig; // 20..21
<summary>
</summary>
internal ushort snTokenRidMap; // 12..13
<summary>
</summary>
internal ushort snXdata; // 14..15
<summary>
</summary>
<param name="bits">
</param>
internal DbiDbgHdr(BitAccess bits)
{
bits.ReadUInt16(out this.snFPO);
bits.ReadUInt16(out this.snException);
bits.ReadUInt16(out this.snFixup);
bits.ReadUInt16(out this.snOmapToSrc);
bits.ReadUInt16(out this.snOmapFromSrc);
bits.ReadUInt16(out this.snSectionHdr);
bits.ReadUInt16(out this.snTokenRidMap);
bits.ReadUInt16(out this.snXdata);
bits.ReadUInt16(out this.snPdata);
bits.ReadUInt16(out this.snNewFPO);
bits.ReadUInt16(out this.snSectionHdrOrig);
}
}
} |
package com.petercassetta.pdrebalanced.actors.mobs;
import com.petercassetta.pdrebalanced.Badges;
import com.petercassetta.pdrebalanced.sprites.ShieldedSprite;
public class Shielded extends Brute {
{
name = "shielded brute";
spriteClass = ShieldedSprite.class;
defenseSkill = 20;
}
@Override
public int dr() {
return 10;
}
@Override
public String defenseVerb() {
return "blocked";
}
@Override
public void die( Object cause ) {
super.die( cause );
Badges.validateRare( this );
}
} |
package com.weatherapp.exceptions;
public class <API key> extends RuntimeException {
private static final long serialVersionUID = 1L;
public <API key>(String message) {
super(message);
}
} |
<?php
namespace Nawork\NaworkUri\ViewHelpers;
use Nawork\NaworkUri\Domain\Model\Domain;
use Nawork\NaworkUri\Domain\Model\Language;
use Nawork\NaworkUri\Utility\<API key>;
use Nawork\NaworkUri\Utility\<API key>;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper;
class <API key> extends AbstractViewHelper
{
/**
* @var bool
*/
protected $escapeOutput = false;
public function initializeArguments()
{
parent::initializeArguments();
$this->registerArgument('url', 'Nawork\NaworkUri\Domain\Model\Url', 'The url to get the redirect target for', true);
$this->registerArgument('as', 'string', 'Variable name, that the result should be assigned to, when rendering the children');
}
/**
* @param \Nawork\NaworkUri\Domain\Model\Url $url
* @param string|null $as
*
* @return string
*/
public function render($url, $as = null)
{
$pageUid = $url->getPageUid();
$parameters = $url->getParameters();
$language = $url->getLanguage();
if ($language instanceof Language) {
$language = $language->getUid();
}
if ($language === null) {
$language = 0;
}
$domainName = $url->getDomain() instanceof Domain ? $url->getDomain()->getDomainname() : GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY');
<API key>::getConfiguration($domainName);
/* @var $translator \Nawork\NaworkUri\Utility\<API key> */
$translator = GeneralUtility::makeInstance(<API key>::class);
$newUrlParameters = array_merge(
\Nawork\NaworkUri\Utility\GeneralUtility::explode_parameters($parameters),
['id' => $pageUid, 'L' => $language]
);
// try to find a new url or create one, if it does not exist
try {
$newUrl = $translator->params2uri(
\Nawork\NaworkUri\Utility\GeneralUtility::implode_parameters($newUrlParameters, false),
false,
true
);
if (substr($newUrl, 0, 1) !== '/') {
$newUrl = '/' . $newUrl;
}
} catch (\Exception $e) {
/**
* @todo Log this some where
*/
$newUrl = '';
}
if (!empty($as)) {
$this-><API key>->add($as, $newUrl);
$content = $this->renderChildren();
$this-><API key>->remove($as);
return $content;
}
return $newUrl;
}
} |
# web
Web site for ZoondEngine project |
<?php
class <API key> extends Controller {
public function index() {
$this->language->load('error/not_found');
$this->document->setTitle($this->language->get('heading_title'));
$this->data['heading_title'] = $this->language->get('heading_title');
$this->data['text_not_found'] = $this->language->get('text_not_found');
$this->data['breadcrumbs'] = array();
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
'separator' => false
);
$this->data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL'),
'separator' => ' :: '
);
$this->template = 'error/not_found.tpl';
$this->children = array(
'common/header',
'common/footer'
);
$this->response->setOutput($this->render());
}
} |
package mobilprogramlama.ders.berkay.hm1_quiz.activity;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import mobilprogramlama.ders.berkay.hm1_quiz.R;
import mobilprogramlama.ders.berkay.hm1_quiz.database.DatabaseContract;
import mobilprogramlama.ders.berkay.hm1_quiz.fragment.TimePickerFragment;
public class RegisterActivity extends Activity {
private EditText mUsername;
private Button mPickBirthday;
private TextView mDateDisplay;
private String pickedBirthday;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mUsername = (EditText) findViewById(R.id.<API key>);
mPickBirthday = (Button) findViewById(R.id.<API key>);
mDateDisplay = (TextView) findViewById(R.id.<API key>);
}
@Override
protected void onStart() {
super.onStart();
// Set the current date to the screen.
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
SetDate(cal);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the birthday information to Bundle using.
outState.putString(DatabaseContract.PlayersContract.<API key>, pickedBirthday);
}
@Override
protected void <API key>(Bundle savedInstanceState) {
super.<API key>(savedInstanceState);
// Saved instance is restored in <API key> because it is called after onStart() method.
pickedBirthday = savedInstanceState.getString(DatabaseContract.PlayersContract.<API key>);
mDateDisplay.setText(pickedBirthday);
}
public void <API key>(View view){
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
public void <API key>(View view) {
if(!mUsername.getText().toString().isEmpty()){
Intent menuIntent = new Intent(this, MenuActivity.class);
String name = mUsername.getText().toString();
menuIntent.putExtra(DatabaseContract.PlayersContract.<API key>, name);
menuIntent.putExtra(DatabaseContract.PlayersContract.<API key>, pickedBirthday);
// Clear the Activity from Activity stack.
menuIntent.setFlags(Intent.<API key> | Intent.<API key>);
startActivity(menuIntent);
this.finish();
} else{
Toast.makeText(this, getString(R.string.toast_enter_name), Toast.LENGTH_SHORT).show();
}
}
/**
* Sets the date on the screen and the {@link RegisterActivity#pickedBirthday} string.
* @param calendar {@link Calendar} object that holds the date information.
*/
public void SetDate(Calendar calendar){
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy");
String formatted = format1.format(calendar.getTime());
mDateDisplay.setText(formatted);
pickedBirthday = formatted;
}
} |
/** NAME : kgraph_map_bd.h **/
/** AUTHOR : Sebastien FOURESTIER (v6.0) **/
/** FUNCTION : These lines are the data declaration **/
/** for the band graph partitioning **/
/** routine for distributed graphs. **/
/** DATES : # Version 6.0 : from : 05 jan 2010 **/
/** to : 20 feb 2012 **/
/*
** The defines.
*/
/*+ Flag array accessors. +*/
#define kgraphMapBdFlagSize(n) (((n) + (sizeof (int) << 3) - 1) / (sizeof (int) << 3))
#define kgraphMapBdFlagVal(a,n) (((a)[(n) / (sizeof (int) << 3)] >> ((n) & ((sizeof (int) << 3) - 1))) & 1)
#define kgraphMapBdFlagSet(a,n) (a)[(n) / (sizeof (int) << 3)] |= (1 << ((n) & ((sizeof (int) << 3) - 1)))
/*
** The type and structure definitions.
*/
/*+ This structure holds the method parameters. +*/
typedef struct KgraphMapBdParam_ {
INT distmax; /*+ Width of band surrounding the frontier +*/
Strat * stratbnd; /*+ Strategy for band graph +*/
Strat * stratorg; /*+ Strategy for original graph +*/
} KgraphMapBdParam;
/*
** The function prototypes.
*/
#ifndef KGRAPH_MAP_BD
#define static
#endif
int kgraphMapBd (Kgraph * const, const KgraphMapBdParam * const);
#undef static |
define(['knockout','jquery','currentuser'], function (ko, $, currentuser) {
var EditFamilyModal = function EditFamilyModal(params) {
var <API key> = ko.observable();
var <API key> = ko.observable();
var <API key> = ko.observable();
var <API key> = ko.observable();
var <API key> = ko.observable();
var familyIndex = ko.observable();
function setFamilyProperties(theFamily) {
if (!theFamily) {
return;
}
<API key>(theFamily.firstname);
<API key>(theFamily.lastname);
<API key>(theFamily.relationToUser);
<API key>(theFamily.phone);
<API key>(theFamily.email);
}
function setIndex(theIndex){
familyIndex(theIndex);
}
// save family info
function saveFamilyInfo(){
var data = {
"firstname" : <API key>(),
"lastname" : <API key>(),
"relationToUser" : <API key>(),
"phone" : <API key>(),
"email" : <API key>(),
};
var id = currentuser._id;
$.ajax({
url: "/api/userProfileInfo/users/" + id + "/family/" + familyIndex(),
type: "PUT",
contentType: "application/json",
data: ko.toJSON(data)
})
.done(function(){
$('#familyModal').modal('hide');
})
.fail(function(req, status, err){
console.log(err);
});
}
params.family.subscribe(setFamilyProperties);
params.familyToEditIndex.subscribe(setIndex);
return {
<API key>: <API key>,
<API key>: <API key>,
<API key>: <API key>,
<API key>: <API key>,
<API key>: <API key>,
saveFamilyInfo: saveFamilyInfo
};
};
return EditFamilyModal;
}); |
package org.kdm.gogomtnaejang.node;
public class Node {
public int id;
public String name="No name";
public float lat=0.0f;
public float lng=0.0f;
public float alt=0.0f;
public Node(int id){
this.id = id;
}
public int getID(){
return id;
}
public String getName(){
return name;
}
public float getLat(){
return lng;
}
public float getAlt(){
return alt;
}
} |
/* styles for the navigation filter on main page */
/* styles for the search form on main page*/ |
/**
* @file mi2_interface.h
*
* @brief Handle the actions sent to the debugger and parsing information
* from the debugger.
*
* The interface for sending the actions to the debugger. The parsing of the
* information sent by the debugger are handled by the parser object. See
* mi2_parser.h for more information.
*
* If an action needs options a form is set up for user interactions.
*/
#ifndef MI2_INTERFACE_H
#define MI2_INTERFACE_H
#include <unistd.h>
#include "view.h"
#include "configuration.h"
/**
* Map of available debugger actions.
*/
enum mi2_actions
{
/**
* @name Compound actions.
*
* Compound action built up by sending multiple commands or using non mi2
* commands.
*/
ACTION_INT_START, /**< Run the debugger to main (). */
ACTION_INT_UPDATE, /**< Send commands to debugger for update inforamtion. */
/**
* @name Execution actions.
*
* The -exec- family commands.
*/
ACTION_EXEC_CONT, /**< Continue the execution. */
<API key>,/**< Continue the execution with options. */
ACTION_EXEC_FINISH, /**< Execute to end of function. */
ACTION_EXEC_INTR, /**< Send signal to the debugger. */
ACTION_EXEC_JUMP, /**< Jump to a location. */
ACTION_EXEC_NEXT, /**< Execut one source line. */
ACTION_EXEC_NEXTI, /**< Execute one instruction. */
ACTION_EXEC_RETURN, /**< Return from function directly. */
ACTION_EXEC_RUN, /**< Execute from beginning. */
ACTION_EXEC_STEP, /**< Execute one source line, step into functions. */
ACTION_EXEC_STEPI, /**< Execute one instruction, step into functions. */
ACTION_EXEC_UNTIL, /**< Execute until given location. */
/**
* @name Stack actions.
*
* The -stack- family comands.
*/
<API key>, /**< List frames in stack. */
<API key>, /**< List variables in the current frame. */
/**
* @name Breakpoint actions.
*
* The -break- family commands.
*/
ACTION_BP_SIMPLE, /**< Set breakpoint at current cursor line. */
ACTION_BP_ADVANCED, /**< Set up a breakpoint with options. */
<API key>, /**< Set up a watchpoint. */
/**
* @name Thread actions.
*
* The thread commands.
*/
<API key>, /**< Selects thread. */
ACTION_THREAD_INFO, /**< Ask for thread information. */
/**
* @name File actions.
*
* The file command.
*/
<API key>, /**< List source files. */
/**
* @name Data actions.
*
* The available data commands.
*/
<API key>, /**< Ask for disassemble information. */
};
typedef struct mi2_interface_t mi2_interface;
mi2_interface *mi2_create (int fd, pid_t pid, view * view,
configuration * conf);
void mi2_free (mi2_interface * mi2);
int mi2_parse (mi2_interface * mi2, char *line);
int mi2_do_action (mi2_interface * mi2, int action, int param);
void <API key> (mi2_interface * mi2);
#endif |
/* include main */
#include "unpipc.h"
#define MAXNTHREADS 100
int nloop;
struct {
int semid;
long counter;
} shared;
struct sembuf postop, waitop;
void *incr(void *);
int
main(int argc, char **argv)
{
int i, nthreads;
pthread_t tid[MAXNTHREADS];
union semun arg;
if (argc != 3)
err_quit("usage: incr_svsem1 <#loops> <#threads>");
nloop = atoi(argv[1]);
nthreads = min(atoi(argv[2]), MAXNTHREADS);
/* 4create semaphore and initialize to 0 */
shared.semid = Semget(IPC_PRIVATE, 1, IPC_CREAT | SVSEM_MODE);
arg.val = 0;
Semctl(shared.semid, 0, SETVAL, arg);
postop.sem_num = 0; /* and init the two semop() structures */
postop.sem_op = 1;
postop.sem_flg = 0;
waitop.sem_num = 0;
waitop.sem_op = -1;
waitop.sem_flg = 0;
/* 4create all the threads */
Set_concurrency(nthreads);
for (i = 0; i < nthreads; i++) {
Pthread_create(&tid[i], NULL, incr, NULL);
}
/* 4start the timer and release the semaphore */
Start_time();
Semop(shared.semid, &postop, 1); /* up by 1 */
/* 4wait for all the threads */
for (i = 0; i < nthreads; i++) {
Pthread_join(tid[i], NULL);
}
printf("microseconds: %.0f usec\n", Stop_time());
if (shared.counter != nloop * nthreads)
printf("error: counter = %ld\n", shared.counter);
Semctl(shared.semid, 0, IPC_RMID);
exit(0);
}
/* end main */
/* include incr */
void *
incr(void *arg)
{
int i;
for (i = 0; i < nloop; i++) {
Semop(shared.semid, &waitop, 1);
shared.counter++;
Semop(shared.semid, &postop, 1);
}
return(NULL);
}
/* end incr */ |
#include "config.h"
#include <string.h>
#include "internals.h"
#define PLUSD_HEADER_LENGTH 22
static libspectrum_error
identify_machine( size_t buffer_length, libspectrum_snap *snap );
static libspectrum_error
<API key>( const libspectrum_byte *buffer,
size_t buffer_length, libspectrum_snap *snap );
static libspectrum_error
<API key>( const libspectrum_byte *buffer,
libspectrum_snap *snap );
static libspectrum_byte
readbyte( libspectrum_snap *snap, libspectrum_word address );
static void
<API key>( libspectrum_snap *snap,
const libspectrum_byte *buffer );
libspectrum_error
<API key>( libspectrum_snap *snap, const libspectrum_byte *buffer,
size_t buffer_length )
{
int error;
error = identify_machine( buffer_length, snap );
if( error != <API key> ) return error;
error = <API key>( buffer, buffer_length, snap );
if( error != <API key> ) return error;
buffer += PLUSD_HEADER_LENGTH;
error = <API key>( buffer, snap );
if( error != <API key> ) return error;
return <API key>;
}
static libspectrum_error
identify_machine( size_t buffer_length, libspectrum_snap *snap )
{
switch( buffer_length ) {
case PLUSD_HEADER_LENGTH + 0xc000:
<API key>( snap, <API key> );
break;
case PLUSD_HEADER_LENGTH + 1 + 0x20000:
<API key>( snap, <API key> );
break;
default:
<API key>( <API key>,
"plusd identify_machine: unknown length" );
return <API key>;
}
return <API key>;
}
static libspectrum_error
<API key>( const libspectrum_byte *buffer,
size_t buffer_length, libspectrum_snap *snap )
{
libspectrum_byte i;
<API key> ( snap, buffer[ 0] + buffer[ 1] * 0x100 );
<API key> ( snap, buffer[ 2] + buffer[ 3] * 0x100 );
<API key>( snap, buffer[ 4] + buffer[ 5] * 0x100 );
<API key>( snap, buffer[ 6] + buffer[ 7] * 0x100 );
<API key>( snap, buffer[ 8] + buffer[ 9] * 0x100 );
<API key> ( snap, buffer[10] );
<API key> ( snap, buffer[11] );
<API key> ( snap, buffer[12] + buffer[13] * 0x100 );
<API key> ( snap, buffer[14] + buffer[15] * 0x100 );
<API key> ( snap, buffer[16] + buffer[17] * 0x100 );
/* Header offset 18 is 'rubbish' */
i = buffer[19]; <API key>( snap, i );
<API key> ( snap, buffer[20] + buffer[21] * 0x100 );
/* Make a guess at the interrupt mode depending on what I was set to */
<API key>( snap, ( i == 0 || i == 63 ) ? 1 : 2 );
return <API key>;
}
static libspectrum_error
<API key>( const libspectrum_byte *buffer,
libspectrum_snap *snap )
{
libspectrum_byte iff;
libspectrum_word sp;
int error;
sp = libspectrum_snap_sp( snap );
/* We must have 0x4000 <= SP <= 0xfffa so we can rescue the stacked
registers */
if( sp < 0x4000 || sp > 0xfffa ) {
<API key>(
<API key>,
"<API key>: SP invalid (0x%04x)", sp
);
return <API key>;
}
switch( <API key>( snap ) ) {
case <API key>:
/* Split the RAM into separate pages */
error = <API key>( snap, buffer );
if( error != <API key> ) return error;
break;
case <API key>:
<API key>( snap, buffer[0] );
buffer++;
<API key>( snap, buffer );
break;
default:
<API key>( <API key>,
"<API key>: unknown machine" );
return <API key>;
}
/* R, IFF, AF and PC are stored on the stack */
iff = readbyte( snap, sp ) & 0x04;
<API key> ( snap, readbyte( snap, sp + 1 ) );
<API key>( snap, iff );
<API key>( snap, iff );
<API key> ( snap, readbyte( snap, sp + 2 ) );
<API key> ( snap, readbyte( snap, sp + 3 ) );
<API key> ( snap, readbyte( snap, sp + 4 ) +
readbyte( snap, sp + 5 ) * 0x100 );
/* Store SP + 6 to account for those unstacked values */
<API key>( snap, sp + 6 );
return <API key>;
}
static libspectrum_byte
readbyte( libspectrum_snap *snap, libspectrum_word address )
{
int page;
switch( address >> 14 ) {
case 1:
page = 5;
break;
case 2:
page = 2;
break;
case 3:
page = <API key>( snap ) & 0x07;
break;
default:
return 0;
}
return <API key>( snap, page )[ address & 0x3fff ];
}
static void
<API key>( libspectrum_snap *snap,
const libspectrum_byte *buffer )
{
int i;
for( i=0; i<8; i++ ) {
libspectrum_byte *ram;
ram = libspectrum_new( libspectrum_byte, 0x4000 );
<API key>( snap, i, ram );
memcpy( ram, buffer, 0x4000 );
buffer += 0x4000;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.