answer stringlengths 15 1.25M |
|---|
#!/bin/bash
#: Set up OpenSSH client and server for Ubuntu.
#: Intended for Ubuntu 18.04
sudo apt update && sudo apt -y install openssh-client openssh-server
## Harden sshd - disallow root login and password auth
sshdConfig="/etc/ssh/sshd_config"
sudo cp "$sshdConfig" "${sshdConfig}_BACKUP.txt" # create backup
sudo sed -i -E 's/^\#?PermitRootLogin .*/PermitRootLogin no/' "$sshdConfig"
sudo sed -i -E 's/^\#?<API key> .*/<API key> no/' "$sshdConfig"
sudo service sshd restart
## create config files
mkdir -p ~/.ssh
touch ~/.ssh/authorized_keys |
<!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"/>
<title>GNU Radio 7f75d35b C++ API: gr_block_executor.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">GNU Radio 7f75d35b C++ API
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.7.6.1 -->
</div>
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
initNavTree('<API key>.html','');
</script>
<div id="doc-content">
<div class="header">
<div class="headertitle">
<div class="title">gr_block_executor.h</div> </div>
</div><!--header
<div class="contents">
<a href="<API key>.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment"></span>
<a name="l00022"></a>00022
<a name="l00023"></a>00023 <span class="preprocessor">#ifndef <API key></span>
<a name="l00024"></a>00024 <span class="preprocessor"></span><span class="preprocessor">#define <API key></span>
<a name="l00025"></a>00025 <span class="preprocessor"></span>
<a name="l00026"></a>00026 <span class="preprocessor">#include <<a class="code" href="gr__core__api_8h.html">gr_core_api.h</a>></span>
<a name="l00027"></a>00027 <span class="preprocessor">#include <<a class="code" href="<API key>.html">gr_runtime_types.h</a>></span>
<a name="l00028"></a>00028 <span class="preprocessor">#include <fstream></span>
<a name="l00029"></a>00029 <span class="preprocessor">#include <<a class="code" href="gr__tags_8h.html">gr_tags.h</a>></span>
<a name="l00030"></a>00030
<a name="l00031"></a>00031 <span class="comment">//class gr_block_executor;</span>
<a name="l00032"></a>00032 <span class="comment">//typedef boost::shared_ptr<gr_block_executor> <API key>;</span>
<a name="l00033"></a>00033
<a name="l00034"></a>00034 <span class="comment"></span>
<a name="l00035"></a>00035 <span class="comment">/*!</span>
<a name="l00036"></a>00036 <span class="comment"> * \brief Manage the execution of a single block.</span>
<a name="l00037"></a>00037 <span class="comment"> * \ingroup internal</span>
<a name="l00038"></a>00038 <span class="comment"> */</span>
<a name="l00039"></a>00039
<a name="l00040"></a><a class="code" href="<API key>.html">00040</a> <span class="keyword">class </span><a class="code" href="gr__core__api_8h.html#<API key>">GR_CORE_API</a> <a class="code" href="<API key>.html" title="Manage the execution of a single block.">gr_block_executor</a> {
<a name="l00041"></a>00041 <span class="keyword">protected</span>:
<a name="l00042"></a><a class="code" href="<API key>.html#<API key>">00042</a> <a class="code" href="<API key>.html">gr_block_sptr</a> <a class="code" href="<API key>.html#<API key>">d_block</a>; <span class="comment">// The block we're trying to run</span>
<a name="l00043"></a><a class="code" href="<API key>.html#<API key>">00043</a> std::ofstream *<a class="code" href="<API key>.html#<API key>">d_log</a>;
<a name="l00044"></a>00044
<a name="l00045"></a>00045 <span class="comment">// These are allocated here so we don't have to on each iteration</span>
<a name="l00046"></a>00046
<a name="l00047"></a><a class="code" href="<API key>.html#<API key>">00047</a> <a class="code" href="gr__types_8h.html#<API key>">gr_vector_int</a> <a class="code" href="<API key>.html#<API key>"><API key></a>;
<a name="l00048"></a><a class="code" href="<API key>.html#<API key>">00048</a> <a class="code" href="gr__types_8h.html#<API key>">gr_vector_int</a> <a class="code" href="<API key>.html#<API key>">d_ninput_items</a>;
<a name="l00049"></a><a class="code" href="<API key>.html#<API key>">00049</a> <a class="code" href="gr__types_8h.html#<API key>"><API key></a> <a class="code" href="<API key>.html#<API key>">d_input_items</a>;
<a name="l00050"></a><a class="code" href="<API key>.html#<API key>">00050</a> std::vector<bool> <a class="code" href="<API key>.html#<API key>">d_input_done</a>;
<a name="l00051"></a><a class="code" href="<API key>.html#<API key>">00051</a> <a class="code" href="gr__types_8h.html#<API key>">gr_vector_void_star</a> <a class="code" href="<API key>.html#<API key>">d_output_items</a>;
<a name="l00052"></a><a class="code" href="<API key>.html#<API key>">00052</a> std::vector<uint64_t> <a class="code" href="<API key>.html#<API key>">d_start_nitems_read</a>; <span class="comment">//stores where tag counts are before work</span>
<a name="l00053"></a><a class="code" href="<API key>.html#<API key>">00053</a> std::vector<gr_tag_t> <a class="code" href="<API key>.html#<API key>">d_returned_tags</a>;
<a name="l00054"></a><a class="code" href="<API key>.html#<API key>">00054</a> <span class="keywordtype">int</span> <a class="code" href="<API key>.html#<API key>">d_max_noutput_items</a>;
<a name="l00055"></a>00055
<a name="l00056"></a>00056 <span class="keyword">public</span>:
<a name="l00057"></a>00057 <a class="code" href="<API key>.html" title="Manage the execution of a single block.">gr_block_executor</a>(<a class="code" href="<API key>.html">gr_block_sptr</a> block, <span class="keywordtype">int</span> max_noutput_items=100000);
<a name="l00058"></a>00058 ~<a class="code" href="<API key>.html" title="Manage the execution of a single block.">gr_block_executor</a> ();
<a name="l00059"></a>00059
<a name="l00060"></a><a class="code" href="<API key>.html#<API key>">00060</a> <span class="keyword">enum</span> <a class="code" href="<API key>.html#<API key>">state</a> {
<a name="l00061"></a><a class="code" href="<API key>.html#<API key>">00061</a> <a class="code" href="<API key>.html#<API key>">READY</a>, <span class="comment">// We made progress; everything's cool.</span>
<a name="l00062"></a><a class="code" href="<API key>.html#<API key>">00062</a> <a class="code" href="<API key>.html#<API key>">READY_NO_OUTPUT</a>, <span class="comment">// We consumed some input, but produced no output.</span>
<a name="l00063"></a><a class="code" href="<API key>.html#<API key>">00063</a> <a class="code" href="<API key>.html#<API key>">BLKD_IN</a>, <span class="comment">// no progress; we're blocked waiting for input data.</span>
<a name="l00064"></a><a class="code" href="<API key>.html#<API key>">00064</a> <a class="code" href="<API key>.html#<API key>">BLKD_OUT</a>, <span class="comment">// no progress; we're blocked waiting for output buffer space.</span>
<a name="l00065"></a><a class="code" href="<API key>.html#<API key>">00065</a> <a class="code" href="<API key>.html#<API key>">DONE</a>, <span class="comment">// we're done; don't call me again.</span>
<a name="l00066"></a>00066 };
<a name="l00067"></a>00067
<a name="l00068"></a>00068 <span class="comment">/*</span>
<a name="l00069"></a>00069 <span class="comment"> * \brief Run one iteration.</span>
<a name="l00070"></a>00070 <span class="comment"> */</span>
<a name="l00071"></a>00071 state run_one_iteration();
<a name="l00072"></a>00072 };
<a name="l00073"></a>00073
<a name="l00074"></a>00074 <span class="preprocessor">#endif </span><span class="comment">/* <API key> */</span>
</pre></div></div><!-- contents -->
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="<API key>.html">gr_block_executor.h</a> </li>
<li class="footer">Generated on Thu Sep 27 2012 10:49:24 for GNU Radio 7f75d35b C++ API by
<a href="http:
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.6.1 </li>
</ul>
</div>
</body>
</html> |
package org.dragonet.proxy.network.translator.java.window;
import com.github.steveice10.mc.protocol.packet.ingame.server.window.<API key>;
import lombok.extern.log4j.Log4j2;
import org.dragonet.proxy.network.session.ProxySession;
import org.dragonet.proxy.network.session.cache.object.CachedWindow;
import org.dragonet.proxy.network.translator.misc.PacketTranslator;
import org.dragonet.proxy.util.registry.PacketRegisterInfo;
import org.dragonet.proxy.util.TextFormat;
@Log4j2
@PacketRegisterInfo(packet = <API key>.class)
public class <API key> extends PacketTranslator<<API key>> {
@Override
public void translate(ProxySession session, <API key> packet) {
CachedWindow cachedWindow = session.getWindowCache().getById(packet.getWindowId());
if(cachedWindow == null) {
//log.info(TextFormat.GRAY + "(debug) <API key>: cached window is null");
return;
}
cachedWindow.close(session);
}
} |
// Function: processfiles
// Parameters: source stream, code streams, comment stream
// Result: codes and comments in 2 different files
#include <string.h> // add String Library
#include "cdplfunc.h" // add CodePeel's function library
#define MAXRAWCHAR 1000 // Maximum characters for a raw line
#define MAXCODCHAR 1000 // Maximum characters for a code line
#define MAXCOMCHAR 1000 // Maximum characters for a comment line
// processfiles function separates code lines and comments from the source file
// it also write code lines and comments lines to the code and comment files
void processfiles(FILE *fsrc, FILE *fcod, FILE *fcom)
{
// initialize rawline, codline, comline array (initialized to an empty string for safety)
char rawline[MAXRAWCHAR] = "", codline[MAXCODCHAR] = "", comline[MAXCOMCHAR] = "";
// pointers to handle above arrays
char *rp, *cp, *cop;
// while there is lines to process
while (fgets(rawline, MAXRAWCHAR, fsrc) != NULL) { // using fgets to fill the rawline array from fsrc stream
rp = rawline; // rp initially points to the rawline's first element (base address)
cp = codline; // cp initially points to the codline's first element
cop = comline; // cop initially points to the comline's first element
n_rawlines++; // increment number of rawlines processed so far.
if (strlen(rawline) > 1) { // process if rawline is not a one character
// this prevents processing empty lines
if (*rp != ';') // if the string not begins with a ';' it's a code line
n_codelines++; // so increment the number of codelines processed so far
// this loop copy the codes from rawline[] to codline[]
while (*rp != ';' && *rp != '\n' && *rp != '\0') { // if rp is semi-colon, LF, or null end copying
*cp++ = *rp++; // copy character from rp to cp then increment cp and rp
*cop++ = ' '; // add a spaces in comline[] for each character copied into codline[]
}
// terminate the codline string
*cp = '\0';
// print the codline[] string on fcod stream
fprintf(fcod, "%s\n", codline);
// if a comment found
if (*rp == ';') {
// increment n_commlines (number of comment lines processed so far)
n_commlines++;
// while a LF or NULL char occurs copy rawline[] to comline[]
while (*rp != '\n' && *rp)
*cop++ = *rp++;
// terminate the comline[] string
*cop = '\0';
// print the comline[] string on fcom string
fprintf(fcom, "%s\n", comline);
}
}
}
} |
#include "mbed.h"
#include "PeriodicSensor.h"
PeriodicSensor::PeriodicSensor() :
__dataReady(false),
__interrupt(),
__sample_period(0),
<API key>(false),
__min_sample_period(0.05) {
__interrupt.detach();
}
PeriodicSensor::PeriodicSensor(float min_sample_period) :
__dataReady(false),
__interrupt(),
__sample_period(0),
<API key>(false),
__min_sample_period(0.05) {
if (min_sample_period > 0)
__min_sample_period = min_sample_period;
__interrupt.detach();
}
PeriodicSensor::~PeriodicSensor() { }
bool PeriodicSensor::isDataReady() {
return __dataReady;
}
void PeriodicSensor::<API key>(bool enable, float sample_period) {
if (enable && sample_period >= <API key>.0001) {
__sample_period = sample_period;
<API key> = true;
__interrupt.attach(this, &PeriodicSensor::__sample_data_ISR, sample_period);
}
else if (!enable) {
__sample_period = 0;
<API key> = false;
__interrupt.detach();
}
}
bool PeriodicSensor::<API key>() {
return <API key>;
}
float PeriodicSensor::getSamplePeriod() {
return __sample_period;
}
float PeriodicSensor::getMinSamplePeriod() {
return __min_sample_period;
} |
var grunt = require('grunt');
var config = grunt.config.get('custom');
module.exports = {
options: {
removeFiles: true
},
default: {
src: config.srcPath + '/index.html',
blocks: {
customScripts: {
src: [
config.javascriptPath + '*.js'
],
cwd: config.srcPath
},
customStyles: {
src: [
config.stylesheetPath + '*.css'
],
cwd: config.srcPath
}
}
},
test: {
src: config.testPath + '/index.html',
blocks: {
customScripts: {
src: [
config.javascriptPath + '*.js'
],
cwd: config.srcPath
},
testScripts: {
src: [
config.stylesheetPath + '*.css' |
#include "dmanager.h"
#include "dialogwidget.h"
class DManagerPrivate
{
public:
DialogWidget *widget;
};
DManager::DManager()
: SDialogMethod()
{
p = new DManagerPrivate;
p->widget = new DialogWidget( static_cast<QWidget*>(parent()) );
}
void DManager::insert( SDialog * )
{
}
void DManager::remove( SDialog * )
{
}
void DManager::remove( SPage * )
{
}
void DManager::pageTypeChanged( SPage::PageType )
{
}
void DManager::currentTabChanged( SPage * )
{
}
void DManager::<API key>( SDialog *dialog )
{
if( dialog != 0 )
dialog->setWindowFlags( Qt::Widget );
p->widget->set( dialog );
}
DManager::~DManager()
{
//delete p->widget;
delete p;
} |
package megan.classification.commandtemplates;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.Basic;
import jloda.util.ProgramProperties;
import jloda.util.parse.NexusStreamParser;
import megan.classification.<API key>;
import megan.classification.IdMapper;
import megan.importblast.ImportBlastDialog;
import megan.main.MeganProperties;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Set whether to use LCA for specific fViewer
* Daniel Huson, 1.2016
*/
public class SetUseLCACommand extends CommandBase implements ICommand {
public String getSyntax() {
return "set useLCA={true|false} cName=<name>;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set useLCA=");
boolean useLCA = np.getBoolean();
np.matchIgnoreCase("cName=");
final String cName = np.<API key>(Basic.toString(<API key>.<API key>(), " "));
np.matchIgnoreCase(";");
final Set<String> set = new HashSet<>(Arrays.asList(ProgramProperties.get(MeganProperties.<API key>, new String[0])));
if (useLCA)
set.add(cName);
else
set.remove(cName);
ProgramProperties.put(MeganProperties.<API key>, set.toArray(new String[0]));
if (getParent() instanceof ImportBlastDialog) {
final IdMapper mapper = <API key>.get(cName, true).getIdMapper();
((ImportBlastDialog) getParent()).getCommandManager().execute("use cViewer=" + cName + " state=" + mapper.hasActiveAndLoaded() + ";");
}
}
public void actionPerformed(ActionEvent event) {
}
public boolean isApplicable() {
return true;
}
public String getName() {
return null;
}
public String getDescription() {
return "Set whether to use the LCA algorithm for assignment (alternative: best hit)";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
} |
package org.halvors.nuclearphysics.common.item.block.reactor;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.halvors.nuclearphysics.common.Reference;
import org.halvors.nuclearphysics.common.item.block.ItemBlockTooltip;
import org.halvors.nuclearphysics.common.type.EnumColor;
import org.halvors.nuclearphysics.common.utility.InventoryUtility;
import org.halvors.nuclearphysics.common.utility.LanguageUtility;
import org.halvors.nuclearphysics.common.utility.VectorUtility;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
public class <API key> extends ItemBlockTooltip {
private static final String <API key> = "trackCoordinate";
public static final int energy = 1000;
public <API key>(final Block block) {
super(block);
setMaxStackSize(1);
}
@Override
@SideOnly(Side.CLIENT)
public void addInformation(@Nonnull final ItemStack itemStack, @Nullable final World world, @Nonnull final List<String> list, @Nonnull final ITooltipFlag flag) {
final BlockPos pos = getSavedCoordinate(itemStack);
if (pos != null) {
list.add(LanguageUtility.transelate("tooltip.trackingCoordinate") + ": ");
list.add(EnumColor.DARK_GREEN + "X: " + pos.getX() + ", Y: " + pos.getY() + ", Z: " + pos.getZ());
} else {
list.add(EnumColor.DARK_RED + LanguageUtility.transelate("tooltip.<API key>"));
}
super.addInformation(itemStack, world, list, flag);
}
@Override
public boolean placeBlockAt(@Nonnull final ItemStack itemStack, @Nonnull final EntityPlayer player, final World world, @Nonnull final BlockPos pos, final EnumFacing side, final float hitX, final float hitY, final float hitZ, @Nonnull final IBlockState state) {
final TileEntity tile = world.getTileEntity(pos);
if (!world.isRemote && tile != null) {
// Inject essential tile data.
final NBTTagCompound essentialNBT = new NBTTagCompound();
tile.writeToNBT(essentialNBT);
final NBTTagCompound setNbt = InventoryUtility.getNBTTagCompound(itemStack);
if (essentialNBT.hasKey(<API key>)) {
setNbt.setTag(<API key>, essentialNBT.getCompoundTag(<API key>));
}
tile.readFromNBT(setNbt);
}
return super.placeBlockAt(itemStack, player, world, pos, side, hitX, hitY, hitZ, state);
}
@Override
@Nonnull
public ActionResult<ItemStack> onItemRightClick(final World world, final EntityPlayer player, @Nonnull final EnumHand hand) {
final ItemStack itemStack = player.getHeldItemMainhand();
if (!world.isRemote) {
setSavedCoordinate(itemStack, null);
player.sendMessage(new TextComponentString(EnumColor.DARK_BLUE + "[" + Reference.NAME + "] " + EnumColor.GREY + LanguageUtility.transelate("tooltip.<API key>") + "."));
return new ActionResult<>(EnumActionResult.SUCCESS, itemStack);
}
return super.onItemRightClick(world, player, hand);
}
/*
* This is a workaround for buggy onItemUseFirst() function in 1.10.
* TODO: Review this for 1.11 and 1.12.
*/
@Override
public boolean doesSneakBypassUse(final ItemStack stack, final IBlockAccess world, final BlockPos pos, final EntityPlayer player) {
return true;
}
@Override
@Nonnull
public EnumActionResult onItemUse(final EntityPlayer player, final World world, final BlockPos pos, final EnumHand hand, final EnumFacing facing, final float hitX, final float hitY, final float hitZ) {
final ItemStack itemStack = player.getHeldItemMainhand();
if (player.isSneaking()) {
if (!world.isRemote) {
setSavedCoordinate(itemStack, pos);
player.sendMessage(new TextComponentString(EnumColor.DARK_BLUE + "[" + Reference.NAME + "] " + EnumColor.GREY + LanguageUtility.transelate("tooltip.trackingCoordinate") + ": " + pos.getX() + ", " + pos.getY() + ", " + pos.getZ()));
}
return EnumActionResult.SUCCESS;
}
return super.onItemUse(player, world, pos, hand, facing, hitX, hitY, hitZ);
}
public BlockPos getSavedCoordinate(final ItemStack itemStack) {
final NBTTagCompound tag = InventoryUtility.getNBTTagCompound(itemStack);
if (tag.hasKey(<API key>)) {
return VectorUtility.readFromNBT(tag.getCompoundTag(<API key>));
}
return null;
}
public void setSavedCoordinate(final ItemStack itemStack, final BlockPos pos) {
final NBTTagCompound tag = InventoryUtility.getNBTTagCompound(itemStack);
if (pos != null) {
tag.setTag(<API key>, VectorUtility.writeToNBT(pos, new NBTTagCompound()));
} else {
tag.removeTag(<API key>);
}
}
} |
package answers
import (
"errors"
"html/template"
"strconv"
"time"
"appengine/data"
"appengine/srv"
)
const (
TYPE_TESTSINGLE = iota + 1
TYPE_TESTMULTIPLE = iota + 1
ERR_ANSWERNOTFOUND = "Respuesta no encontrada"
<API key> = "Respuesta renderizada erroneamente"
<API key> = "Respuesta sin cuerpo definido"
ERR_BADANSWERTYPE = "Respuesta con tipo de cuerpo desconocido"
ERR_AUTHORID = "Respuesta con autor incorrecto"
)
var bodiesTable = []string{
TYPE_TESTSINGLE: "testsingles-bodies",
TYPE_TESTMULTIPLE: "<API key>"}
type Answer struct {
Id int64 `json:",string" datastore:"-"`
RawBody string `datastore:"-"`
QuestId int64 `json:",string"`
ExerciseId int64 `json:",string"`
AuthorId int64 `json:",string"`
TimeStamp time.Time
//Author *users.NUser
BodyType AnswerBodyType `json:",string"`
Body AnswerBody `datastore:"-"`
BodyId int64
Comment string
}
type AnswerBodyType int
type AnswerBody interface {
GetType() AnswerBodyType
Equals(master AnswerBody) bool
GetHTML(options []string) (template.HTML, error)
IsUnsolved() bool
data.DataItem
}
// Return an answer wihtout a body
func NewAnswer(questionId int64, authorId int64) *Answer {
a := new(Answer)
a.Id = 0
a.QuestId = questionId
a.ExerciseId = 0
a.AuthorId = authorId
a.Comment = ""
a.BodyType = -1
a.BodyId = -1
return a
}
// Return an answer with a blank body of bodyType
func NewAnswerWithBody(questionId int64, authorId int64, bodyType AnswerBodyType) (*Answer, error) {
a := NewAnswer(questionId, authorId)
a.BodyType = bodyType
err := a.BuildBody()
return a, err
}
// Try build a body of BodyType from the RawBody property
func (a *Answer) BuildBody() error {
var abody AnswerBody
if a.BodyType < 0 {
return errors.New(<API key>)
}
switch a.BodyType {
case TYPE_TESTSINGLE:
sol, err := strconv.ParseInt(a.RawBody, 10, 32)
if err != nil {
abody = NewTestSingleAnswer(-1)
} else {
abody = NewTestSingleAnswer(int(sol))
}
default:
return errors.New(ERR_BADANSWERTYPE)
}
a.SetBody(abody)
return nil
}
func (a *Answer) SetBody(abody AnswerBody) {
a.Body = abody
a.BodyType = abody.GetType()
}
func (a Answer) ID() int64 {
return a.Id
}
func (a *Answer) SetID(id int64) {
a.Id = id
}
type AnswerBuffer []*Answer
func NewAnswerBuffer() AnswerBuffer {
return make([]*Answer, 0)
}
func (v AnswerBuffer) At(i int) data.DataItem {
return data.DataItem(v[i])
}
func (v AnswerBuffer) Set(i int, t data.DataItem) {
v[i] = t.(*Answer)
}
func (v AnswerBuffer) Len() int {
return len(v)
}
// Get the answers for a question with questId, for a exercise with
// exerciseId from an author with authorId
func GetAnswers(wr srv.WrapperRequest, authorId int64, questId int64, exerciseId int64) ([]*Answer, error) {
as := NewAnswerBuffer()
q := data.NewConn(wr, "answers")
q.AddFilter("AuthorId =", authorId)
if questId > 0 {
q.AddFilter("QuestId =", questId)
}
if exerciseId > 0 {
q.AddFilter("ExerciseId =", exerciseId)
}
err := q.GetMany(&as)
if err != nil || len(as) == 0 {
return nil, errors.New(ERR_ANSWERNOTFOUND)
}
for i := range as {
getAnswerBody(wr, as[i])
}
return as, err
}
// Create or update an solution answer
func PutAnswer(wr srv.WrapperRequest, a *Answer) error {
if a.BodyType < 0 {
return errors.New(<API key>)
}
all, err := GetAnswers(wr, a.AuthorId, a.QuestId, a.ExerciseId)
qry := data.NewConn(wr, "answers")
if err != nil { // New
a.TimeStamp = time.Now()
a.AuthorId = wr.NU.ID()
err = putAnswerBody(wr, a)
if err != nil {
return err
}
qry.Put(a)
} else { // Updated
a2 := all[0]
a2.TimeStamp = time.Now()
a2.BodyType = a.BodyType
a2.Body = a.Body
// store the new body in the older id
a2.Body.SetID(a2.BodyId)
err = putAnswerBody(wr, a2)
if err != nil {
return err
}
qry.Put(a2)
}
return nil
}
func GetAnswersById(wr srv.WrapperRequest, id int64) (*Answer, error) {
a := NewAnswer(-1, -1)
qry := data.NewConn(wr, "answers")
a.Id = id
err := qry.Get(a)
if err != nil {
return a, errors.New(ERR_ANSWERNOTFOUND)
}
getAnswerBody(wr, a)
return a, nil
}
// Create or update an answer for an exercise
func putAnswer(wr srv.WrapperRequest, a *Answer) error {
return nil
}
func putAnswerBody(wr srv.WrapperRequest, a *Answer) error {
bodyTable := bodiesTable[a.BodyType]
q := data.NewConn(wr, bodyTable)
var err error
switch a.Body.GetType() {
case TYPE_TESTSINGLE:
tbody := a.Body.(*TestSingleBody)
q.Put(tbody)
a.BodyId = tbody.ID()
default:
err = errors.New(<API key>)
}
return err
}
func getAnswerBody(wr srv.WrapperRequest, a *Answer) error {
bodyTable := bodiesTable[a.BodyType]
q := data.NewConn(wr, bodyTable)
var err error
switch a.BodyType {
case TYPE_TESTSINGLE:
body := NewTestSingleAnswer(-1)
body.Solution = 0 // must be set to zero to unmarshall propertly in cache
body.Id = a.BodyId
err = q.Get(body)
a.Body = body
}
return err
}
/*
func getAnswers(wr srv.WrapperRequest, filters map[string][]string) (AnswerBuffer, error) {
as := NewAnswerBuffer()
var err error
if filters["id"] != nil {
a, err := GetAnswersById(wr, filters["id"][0])
as[0] = a
return as, err
}
return as, err
}
*/ |
#ifndef <API key>
#define <API key>
#include <string>
namespace org::modcpp::bluckbuild {
class BluckEnvironment {
public:
BluckEnvironment();
public:
void readConfigFile();
void readConfigFile(const std::string& fileName);
std::string translatePath(std::string path) const;
std::string getBluckRootPath() const { return bluckRootPath; }
std::string getWorkingPath() const { return workingPath; }
std::string getBinFolderName() const { return binFolderName; }
std::string getBinFolderPath() const { return bluckRootPath + binFolderName; }
std::string <API key>() const { return cppCompilerCommand; }
std::string getCppLinkerFlags() const { return cppLinkerFlags; }
std::string getCCompilerCommand() const { return cCompilerCommand; }
bool isDryRun() const { return dryRun; }
private:
std::string bluckRootPath;
std::string workingPath;
std::string binFolderName;
std::string cppCompilerCommand;
std::string cppLinkerFlags;
std::string cCompilerCommand;
bool dryRun;
};
}
#endif |
// Custom Border Forms
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#endregion
#endregion
// Custom Border Forms
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#endregion
#region Using directives
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Reflection; // used for logging
using Sardauscan.Core;
using Sardauscan.Properties;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Windows.Forms;
using Sardauscan.Gui.Forms.CustomForm;
using Sardauscan.Gui.Controls; // used for logging
#endregion
namespace Sardauscan.Gui.Forms
{
<summary>
Extended form class that suports drawing in non-client area.
</summary>
public class CustomAppForm : Form
{
#region Constructor
<summary>
Default ctor
</summary>
public CustomAppForm()
{
this.Layout += new LayoutEventHandler(<API key>);
ClientPaddingInfo = new System.Windows.Forms.Padding(Skin.BorderWidth, 2 * Skin.BorderWidth + Skin.IconSize, Skin.BorderWidth, Skin.BorderWidth);
InitSystemButtons();
UpdateButtonSkin();
}
private void InitSystemButtons()
{
_closeButton = new CustomCaptionButton();
_closeButton.Key = CaptionButtonKey.Close;
_closeButton.Visible = true;
_closeButton.HitTestCode = (int)NativeMethods.NCHITTEST.HTCLOSE;
_closeButton.SystemCommand = (int)NativeMethods.SystemCommands.SC_CLOSE;
_captionButtons.Add(_closeButton);
_restoreButton = new CustomCaptionButton();
_restoreButton.Key = CaptionButtonKey.Restore;
_restoreButton.Enabled = this.MaximizeBox;
_restoreButton.HitTestCode = (int)NativeMethods.NCHITTEST.HTMAXBUTTON;
_restoreButton.SystemCommand = (int)NativeMethods.SystemCommands.SC_RESTORE;
_captionButtons.Add(_restoreButton);
_maximizeButton = new CustomCaptionButton();
_maximizeButton.Key = CaptionButtonKey.Maximize;
_maximizeButton.Enabled = this.MaximizeBox;
_maximizeButton.HitTestCode = (int)NativeMethods.NCHITTEST.HTMAXBUTTON;
_maximizeButton.SystemCommand = (int)NativeMethods.SystemCommands.SC_MAXIMIZE;
_captionButtons.Add(_maximizeButton);
_minimizeButton = new CustomCaptionButton();
_minimizeButton.Key = CaptionButtonKey.Minimize;
_minimizeButton.Enabled = this.MinimizeBox;
_minimizeButton.HitTestCode = (int)NativeMethods.NCHITTEST.HTMINBUTTON;
_minimizeButton.SystemCommand = (int)NativeMethods.SystemCommands.SC_MINIMIZE;
_captionButtons.Add(_minimizeButton);
_helpButton = new CustomCaptionButton();
_helpButton.Key = CaptionButtonKey.Help;
_helpButton.Visible = this.HelpButton;
_helpButton.HitTestCode = (int)NativeMethods.NCHITTEST.HTHELP;
_helpButton.SystemCommand = (int)NativeMethods.SystemCommands.SC_CONTEXTHELP;
_captionButtons.Add(_helpButton);
_settingsButton = new CustomCaptionButton();
_settingsButton.Key = CaptionButtonKey.Settings;
_settingsButton.Visible = true;
_settingsButton.HitTestCode = (int)NativeMethods.NCHITTEST.HTOBJECT;
_settingsButton.SystemCommand = (int)-1;
_captionButtons.Add(_settingsButton);
_aboutButton = new CustomCaptionButton();
_aboutButton.Key = CaptionButtonKey.About;
_aboutButton.Visible = true;
_aboutButton.HitTestCode = (int)NativeMethods.NCHITTEST.HTHELP;
_aboutButton.SystemCommand = (int)-1;
_captionButtons.Add(_aboutButton);
OnUpdateWindowState();
}
#endregion
#region CreateParams
protected override System.Windows.Forms.CreateParams CreateParams
{
get
{
Int32 CS_VREDRAW = 0x1;
Int32 CS_HREDRAW = 0x2;
Int32 CS_OWNDC = 0x20;
CreateParams cp = base.CreateParams;
cp.ClassStyle = cp.ClassStyle | CS_VREDRAW | CS_HREDRAW | CS_OWNDC;
return cp;
}
}
#endregion
#region Variables
private bool <API key>;
private bool <API key> = true;
// Shortcuts to the standards buttons
private CustomCaptionButton _closeButton;
private CustomCaptionButton _restoreButton;
private CustomCaptionButton _maximizeButton;
private CustomCaptionButton _minimizeButton;
private CustomCaptionButton _helpButton;
private CustomCaptionButton _settingsButton;
private CustomCaptionButton _aboutButton;
private List<CustomCaptionButton> _captionButtons = new List<CustomCaptionButton>();
NativeMethods.TRACKMOUSEEVENT _trackMouseEvent;
bool _trakingMouse = false;
Icon _smallIcon;
private Padding ClientPaddingInfo;
private Padding TitlePadding = new Padding();
private SkinInfo Skin = new SkinInfo();
private Color <API key> = SkinInfo.<API key>;
private Color <API key> = SkinInfo.<API key>;
private Color <API key> = SkinInfo.<API key>;
private Color <API key> = SkinInfo.<API key>;
private Font _TitleFont = System.Drawing.SystemFonts.CaptionFont;
#endregion
#region Properties
[Browsable(false)]
public bool IsActive
{
get { return this.IsDesignMode() || Form.ActiveForm != null; }
}
[Browsable(false)]
public Color <API key>
{
get { return IsActive ? <API key> : <API key>; }
}
public Color <API key>
{
get { return <API key>; }
set { <API key> = value; Invalidate(); }
}
public Color <API key>
{
get { return <API key>; }
set { <API key> = value; Invalidate(); }
}
[Browsable(false)]
public Color TitleTextColor
{
get { return IsActive ? <API key> : <API key>; }
}
public Color <API key>
{
get { return <API key>; }
set { <API key> = value; Invalidate(); }
}
public Color <API key>
{
get { return <API key>; }
set { <API key> = value; Invalidate(); }
}
public Font TitleFont
{
get { return _TitleFont; }
set { _TitleFont = value; Invalidate(); }
}
[DefaultValue(false)]
public virtual bool <API key>
{
get { return <API key>; }
set
{
<API key> = value;
// No need to invalidate anything,
// next painting will use double-buffering.
}
}
[DefaultValue(true)]
public bool <API key>
{
get { return <API key>; }
set
{
<API key> = value;
InvalidateWindow();
}
}
public List<CustomCaptionButton> CaptionButtons
{
get { return _captionButtons; }
}
[DefaultValue(false)]
[Browsable(true)]
public bool SettingsBox
{
get { return _settingsButton.Visible; }
set { _settingsButton.Visible = value; }
}
[DefaultValue(false)]
[Browsable(true)]
public bool AboutBox
{
get { return _aboutButton.Visible; }
set { _aboutButton.Visible = value; }
}
public new bool MaximizeBox
{
get { return base.MaximizeBox; }
set
{
this._maximizeButton.Enabled = value;
this._minimizeButton.Visible = this._maximizeButton.Visible
= this._maximizeButton.Enabled | this._minimizeButton.Enabled;
base.MaximizeBox = value;
}
}
public new bool MinimizeBox
{
get { return base.MinimizeBox; }
set
{
this._minimizeButton.Enabled = value;
this._minimizeButton.Visible = this._maximizeButton.Visible
= this._maximizeButton.Enabled | this._minimizeButton.Enabled;
base.MinimizeBox = value;
}
}
public new bool ControlBox
{
get { return base.ControlBox; }
set
{
this._closeButton.Enabled = value;
base.ControlBox = value;
}
}
public new bool HelpButton
{
get { return base.HelpButton; }
set
{
this._helpButton.Visible = value;
base.HelpButton = value;
}
}
public new Icon Icon
{
get { return _smallIcon; }
set
{
_smallIcon = value;
base.Icon = value;
}
}
#endregion
#region On...
protected override void OnHandleCreated(EventArgs e)
{
// Disable theming on current window so we don't get
// any funny artifacts (round corners, etc.)
NativeMethods.SetWindowTheme(this.Handle, "", "");
#if !DEBUG
// When application window stops responding to messages
// system will finally loose patience and repaint it with default theme.
// This prevents such behavior for entire application.
NativeMethods.<API key>();
#endif
base.OnHandleCreated(e);
}
protected virtual void OnUpdateWindowState()
{
this._minimizeButton.Visible = this._maximizeButton.Enabled | this._minimizeButton.Enabled;
this._maximizeButton.Visible = this._minimizeButton.Visible && this.WindowState != FormWindowState.Maximized;
this._restoreButton.Visible = this._minimizeButton.Visible && this.WindowState == FormWindowState.Maximized;
}
protected virtual void OnSystemCommand(int sc)
{ }
<summary>Adjust the supplied Rectangle to the desired position of the client rectangle.</summary>
protected virtual void <API key>(ref Rectangle bounds, bool update)
{
if (update)
<API key>(bounds);
Padding clientPadding = ClientPaddingInfo;
bounds = new Rectangle(bounds.Left + clientPadding.Left, bounds.Top + clientPadding.Top,
bounds.Width - clientPadding.Horizontal, bounds.Height - clientPadding.Vertical);
}
<summary>
Returns a value from a NCHITTEST enumeration specifing the window element on given point.
</summary>
protected virtual int <API key>(Point p)
{
foreach (CustomCaptionButton button in this.CaptionButtons)
{
if (button.Visible && button.Bounds.Contains(p) && (button.HitTestCode > 0 || button.HitTestCode < -1))
return button.HitTestCode;
}
if (FormBorderStyle != FormBorderStyle.FixedToolWindow &&
FormBorderStyle != FormBorderStyle.SizableToolWindow)
{
if (GetIconRectangle().Contains(p))
return (int)NativeMethods.NCHITTEST.HTSYSMENU;
}
if (this.FormBorderStyle == FormBorderStyle.Sizable
|| this.FormBorderStyle == FormBorderStyle.SizableToolWindow)
{
#region Handle sizable window borders
if (p.X <= Skin.BorderWidth) // left border
{
if (p.Y <= Skin.BorderWidth)
return (int)NativeMethods.NCHITTEST.HTTOPLEFT;
else if (p.Y >= this.Height - Skin.BorderWidth)
return (int)NativeMethods.NCHITTEST.HTBOTTOMLEFT;
else
return (int)NativeMethods.NCHITTEST.HTLEFT;
}
else if (p.X >= this.Width - Skin.BorderWidth) // right border
{
if (p.Y <= Skin.BorderWidth)
return (int)NativeMethods.NCHITTEST.HTTOPRIGHT;
else if (p.Y >= this.Height - Skin.BorderWidth)
return (int)NativeMethods.NCHITTEST.HTBOTTOMRIGHT;
else
return (int)NativeMethods.NCHITTEST.HTRIGHT;
}
else if (p.Y <= Skin.BorderWidth) // top border
{
if (p.X <= Skin.BorderWidth)
return (int)NativeMethods.NCHITTEST.HTTOPLEFT;
if (p.X >= this.Width - Skin.BorderWidth)
return (int)NativeMethods.NCHITTEST.HTTOPRIGHT;
else
return (int)NativeMethods.NCHITTEST.HTTOP;
}
else if (p.Y >= this.Height - Skin.BorderWidth) // bottom border
{
if (p.X <= Skin.BorderWidth)
return (int)NativeMethods.NCHITTEST.HTBOTTOMLEFT;
if (p.X >= this.Width - Skin.BorderWidth)
return (int)NativeMethods.NCHITTEST.HTBOTTOMRIGHT;
else
return (int)NativeMethods.NCHITTEST.HTBOTTOM;
}
#endregion
}
// title bar
if (p.Y <= ClientPaddingInfo.Top)
return (int)NativeMethods.NCHITTEST.HTCAPTION;
// rest of non client area
if (p.X <= this.ClientPaddingInfo.Left || p.X >= this.ClientPaddingInfo.Right
|| p.Y >= this.ClientPaddingInfo.Bottom)
return (int)NativeMethods.NCHITTEST.HTBORDER;
return (int)NativeMethods.NCHITTEST.HTCLIENT;
}
<summary>
Delivers new mouse position when it is moved over the non client area of the window.
</summary>
protected virtual void <API key>(MouseEventArgs mouseEventArgs)
{
foreach (CustomCaptionButton button in this.CaptionButtons)
{
if (button.Visible && button.Bounds.Contains(mouseEventArgs.X, mouseEventArgs.Y) && button.HitTestCode > 0)
{
if (button.State != CaptionButtonState.Over)
{
button.State = CaptionButtonState.Over;
DrawButton(button);
HookMouseEvent();
}
}
else
{
if (button.State != CaptionButtonState.Normal)
{
button.State = CaptionButtonState.Normal;
DrawButton(button);
UnhookMouseEvent();
}
}
}
}
<summary>
Called when mouse cursor leaves the non client window area.
</summary>
<param name="args"></param>
protected virtual void <API key>(EventArgs args)
{
if (!_trakingMouse)
return;
foreach (CustomCaptionButton button in this.CaptionButtons)
{
if (button.State != CaptionButtonState.Normal)
{
button.State = CaptionButtonState.Normal;
DrawButton(button);
UnhookMouseEvent();
}
}
}
<summary>
Called each time one of the mouse buttons was pressed over the non-client area.
</summary>
<param name="args"><API key> contain mouse position, button pressed,
and hit-test code for current position. </param>
protected virtual void <API key>(<API key> args)
{
if (args.Button != MouseButtons.Left)
return;
// custom button
foreach (CustomCaptionButton button in this.CaptionButtons)
if (args.HitTest > short.MaxValue && args.HitTest == button.HitTestCode && button.Visible && button.Enabled)
{
// ((CustomCaptionButton)button).OnClick();
args.Handled = true;
return;
}
// find appropriate button
foreach (CustomCaptionButton button in this.CaptionButtons)
{
// [1530]: Don't execute any action when button is disabled or not visible.
if (args.HitTest == button.HitTestCode && button.Visible && button.Enabled)
{
Log(MethodInfo.GetCurrentMethod(), "MouseDown: button = {0}", button);
if (DepressButton(button))
{
if (button.SystemCommand >= 0)
{
int sc = button.SystemCommand;
if (button == _maximizeButton)
sc = (WindowState == FormWindowState.Maximized) ?
(int)NativeMethods.SystemCommands.SC_RESTORE : (int)NativeMethods.SystemCommands.SC_MAXIMIZE;
NativeMethods.SendMessage(this.Handle,
(int)NativeMethods.WindowMessages.WM_SYSCOMMAND,
(IntPtr)sc, IntPtr.Zero);
}
else if (button == _settingsButton)
{
if (SettingsClick != null)
SettingsClick(button, new EventArgs());
}
else if (button == _aboutButton)
{
if (AboutClick != null)
AboutClick(button, new EventArgs());
}
args.Handled = true;
}
return;
}
}
}
<summary>
Paints the client rect - e.ClipingRect has the correct window size, since this.Width, this.Height
aren't always correct when calling this methode (because window is actually resizing)
</summary>
<param name="e"></param>
protected virtual void <API key>(<API key> e)
{
// assign clip region to exclude client area
Region clipRegion = new Region(e.Bounds);
Rectangle rect = new Rectangle(ClientRectangle.Location, ClientRectangle.Size);
rect.Offset(ClientPaddingInfo.Left, ClientPaddingInfo.Top);
clipRegion.Exclude(rect);
clipRegion.Exclude(CustomDrawUtil.ExcludePadding(e.Bounds, ClientPaddingInfo));
e.Graphics.Clip = clipRegion;
Color bgColor = this.<API key>;
Color textColor = this.TitleTextColor;
Font textFont = this.TitleFont;
e.Graphics.FillRectangle(new SolidBrush(bgColor), 0, 0, e.Bounds.Width, e.Bounds.Height);
// paint borders
//ActiveFormSkin.NormalState.DrawImage(e.Graphics, e.Bounds);
//ControlPaint.DrawBorder(e.Graphics, e.Bounds, ForeColor, ButtonBorderStyle.Solid);
ControlPaint.DrawBorder3D(e.Graphics, e.Bounds, Border3DStyle.Flat);
//rect = new Rectangle(e.Bounds.Location, new Size(e.Bounds.Width, ClientPaddingInfo.Top));
int inflate = Skin.BorderWidth - 5;
rect.Inflate(inflate, inflate);
ControlPaint.DrawBorder3D(e.Graphics, rect, Border3DStyle.Flat);
int textOffset = 0;
// paint icon
if (ShowIcon &&
FormBorderStyle != FormBorderStyle.FixedToolWindow &&
FormBorderStyle != FormBorderStyle.SizableToolWindow)
{
Rectangle iconRect = GetIconRectangle();
textOffset += iconRect.Right;
if (_smallIcon != null)
e.Graphics.DrawIcon(_smallIcon, iconRect);
}
// paint caption
string text = this.Text;
if (!String.IsNullOrEmpty(text))
{
// disable text wrapping and request elipsis characters on overflow
using (StringFormat sf = new StringFormat())
{
sf.Trimming = StringTrimming.EllipsisCharacter;
sf.FormatFlags = StringFormatFlags.NoWrap;
sf.LineAlignment = StringAlignment.Center;
// find position of the first button from left
int firstButton = e.Bounds.Width;
foreach (CustomCaptionButton button in this.CaptionButtons)
if (button.Visible)
firstButton = Math.Min(firstButton, button.Bounds.X);
Padding padding = TitlePadding;
Rectangle textRect = new Rectangle(textOffset + padding.Left,
padding.Top, firstButton - textOffset - padding.Horizontal,
ClientPaddingInfo.Top - padding.Vertical);
if (Font != null)
textFont = Font;
// draw text
using (Brush b = new SolidBrush(textColor))
{
e.Graphics.DrawString(text, textFont, b, textRect, sf);
}
}
}
// Translate for the frame border
// if (this.WindowState == FormWindowState.Maximized)
// e.Graphics.TranslateTransform(0, SystemInformation.FrameBorderSize.Height);
// [2415] Because mouse actions over a button might cause it to repaint we need
// to buffer the background under the button in order to repaint it correctly.
// This is important when partially transparent images are used for some button states.
// foreach (CustomCaptionButton button in this.CaptionButtons)
// button.BackColor= this.BackColor;
// Paint all visible buttons (in this case the background doesn't need to be repainted)
foreach (CustomCaptionButton button in this.CaptionButtons)
button.DrawButton(e.Graphics, false, this.<API key>);
}
#endregion
#region Window Events
void <API key>(object sender, LayoutEventArgs e)
{
Rectangle bounds = new Rectangle(Left, Top, Width, Height);
<API key>(ref bounds, true);
OnUpdateWindowState();
InvalidateWindow();
}
#endregion
#region WndProc
protected override void WndProc(ref Message m)
{
Log(MethodInfo.GetCurrentMethod(), "Message = {0}", (NativeMethods.WindowMessages)m.Msg);
if (!this.<API key>)
{
base.WndProc(ref m);
return;
}
switch (m.Msg)
{
case (int)NativeMethods.WindowMessages.WM_NCCALCSIZE:
{
// Provides new coordinates for the window client area.
WmNCCalcSize(ref m);
break;
}
case (int)NativeMethods.WindowMessages.WM_NCHITTEST:
{
// Tell the system what element is at the current mouse location.
WmNCHitTest(ref m);
break;
}
case (int)NativeMethods.WindowMessages.WM_NCPAINT:
{
// Here should all our painting occur, but...
WmNCPaint(ref m);
break;
}
case (int)NativeMethods.WindowMessages.WM_NCACTIVATE:
{
// ... WM_NCACTIVATE does some painting directly
// without bothering with WM_NCPAINT ...
WmNCActivate(ref m);
break;
}
case (int)NativeMethods.WindowMessages.WM_SETTEXT:
{
// ... and some painting is required in here as well
WmSetText(ref m);
break;
}
case (int)NativeMethods.WindowMessages.WM_NCMOUSEMOVE:
{
WmNCMouseMove(ref m);
break;
}
case (int)NativeMethods.WindowMessages.WM_NCMOUSELEAVE:
{
WmNCMouseLeave(ref m);
break;
}
case (int)NativeMethods.WindowMessages.WM_NCLBUTTONDOWN:
{
WmNCLButtonDown(ref m);
break;
}
case 174: // ignore magic message number
{
Log(MethodInfo.GetCurrentMethod(), "
break;
}
case (int)NativeMethods.WindowMessages.WM_SYSCOMMAND:
{
WmSysCommand(ref m);
break;
}
/*
case (int)NativeMethods.WindowMessages.WM_WINDOWPOSCHANGED:
{
WmWindowPosChanged(ref m);
break;
}*/
case (int)NativeMethods.WindowMessages.WM_ERASEBKGND:
{
WmEraseBkgnd(ref m);
break;
}
default:
{
base.WndProc(ref m);
break;
}
}
}
#endregion
#region Wm ... (Windows message...)
private void WmEraseBkgnd(ref Message m)
{
base.WndProc(ref m);
Log(MethodInfo.GetCurrentMethod(), "{0}", WindowState);
OnUpdateWindowState();
}
private void WmWindowPosChanged(ref Message m)
{
base.WndProc(ref m);
Log(MethodInfo.GetCurrentMethod(), "{0}", WindowState);
OnUpdateWindowState();
}
private void WmSysCommand(ref Message m)
{
Log(MethodInfo.GetCurrentMethod(), "{0}", (NativeMethods.SystemCommands)m.WParam.ToInt32());
this.OnSystemCommand(m.WParam.ToInt32());
DefWndProc(ref m);
}
private void WmNCCalcSize(ref Message m)
{
if (m.WParam == NativeMethods.FALSE)
{
NativeMethods.RECT ncRect = (NativeMethods.RECT)m.GetLParam(typeof(NativeMethods.RECT));
Rectangle proposed = ncRect.Rect;
Log(MethodInfo.GetCurrentMethod(), string.Format("### Client Rect [0] = ({0},{1}) x ({2},{3})",
proposed.Left, proposed.Top, proposed.Width, proposed.Height));
<API key>(ref proposed, true);
ncRect = NativeMethods.RECT.FromRectangle(proposed);
Marshal.StructureToPtr(ncRect, m.LParam, false);
}
else if (m.WParam == NativeMethods.TRUE)
{
NativeMethods.NCCALCSIZE_PARAMS ncParams = (NativeMethods.NCCALCSIZE_PARAMS)m.GetLParam(typeof(NativeMethods.NCCALCSIZE_PARAMS));
Rectangle proposed = ncParams.rectProposed.Rect;
Log(MethodInfo.GetCurrentMethod(), string.Format("### Client Rect [1] = ({0},{1}) x ({2},{3})",
proposed.Left, proposed.Top, proposed.Width, proposed.Height));
<API key>(ref proposed, true);
ncParams.rectProposed = NativeMethods.RECT.FromRectangle(proposed);
Marshal.StructureToPtr(ncParams, m.LParam, false);
}
m.Result = IntPtr.Zero;
}
#endregion
#region WmNC ... (Windows message... Non Client)
private void WmNCHitTest(ref Message m)
{
Point screenPoint = new Point(m.LParam.ToInt32());
Log(MethodInfo.GetCurrentMethod(), string.Format("### Screen Point ({0},{1})", screenPoint.X, screenPoint.Y));
// convert to local coordinates
Point clientPoint = PointToWindow(screenPoint);
Log(MethodInfo.GetCurrentMethod(), string.Format("### Client Point ({0},{1})", clientPoint.X, clientPoint.Y));
m.Result = new System.IntPtr(<API key>(clientPoint));
}
private void WmNCMouseMove(ref Message msg)
{
Point clientPoint = this.PointToWindow(new Point(msg.LParam.ToInt32()));
<API key>(new MouseEventArgs(MouseButtons.None, 0,
clientPoint.X, clientPoint.Y, 0));
msg.Result = IntPtr.Zero;
}
private void WmNCMouseLeave(ref Message m)
{
<API key>(EventArgs.Empty);
}
private void WmNCLButtonDown(ref Message msg)
{
Point pt = this.PointToWindow(new Point(msg.LParam.ToInt32()));
<API key> args = new <API key>(
MouseButtons.Left, 1, pt.X, pt.Y, 0, msg.WParam.ToInt32());
<API key>(args);
if (!args.Handled)
{
DefWndProc(ref msg);
}
msg.Result = NativeMethods.TRUE;
}
private void WmNCPaint(ref Message msg)
{
// example in q. 2.9 on http://www.syncfusion.com/FAQ/WindowsForms/FAQ_c41c.aspx#q1026q
// The WParam contains handle to clipRegion or 1 if entire window should be repainted
PaintNonClientArea(msg.HWnd, (IntPtr)msg.WParam);
// we handled everything
msg.Result = NativeMethods.TRUE;
}
private void WmSetText(ref Message msg)
{
// allow the system to receive the new window title
DefWndProc(ref msg);
// repaint title bar
PaintNonClientArea(msg.HWnd, (IntPtr)1);
}
private void WmNCActivate(ref Message msg)
{
bool active = (msg.WParam == NativeMethods.TRUE);
Log(MethodInfo.GetCurrentMethod(), "### Draw active title bar = {0}", active);
if (WindowState == FormWindowState.Minimized)
DefWndProc(ref msg);
else
{
// repaint title bar
PaintNonClientArea(msg.HWnd, (IntPtr)1);
// allow to deactivate window
msg.Result = NativeMethods.TRUE;
}
}
#endregion
#region Size , Positioning ...
public Point PointToWindow(Point screenPoint)
{
return new Point(screenPoint.X - Location.X, screenPoint.Y - Location.Y);
}
protected override void SetClientSizeCore(int x, int y)
{
if (!<API key>)
base.SetClientSizeCore(x, y);
this.Size = SizeFromClientSize(x, y, true);
// this.clientWidth = x;
// this.clientHeight = y;
// this.OnClientSizeChanged(EventArgs.Empty);
// do this instead of above.
this.UpdateBounds(Location.X, Location.Y, Size.Width, Size.Height, x, y);
}
private Size SizeFromClientSize(int x, int y, bool updatebuttons)
{
Rectangle bounds = new Rectangle(0, 0, 1000, 1000);
<API key>(ref bounds, updatebuttons);
return new Size(x + (1000 - bounds.Width), y + (1000 - bounds.Height));
}
protected override Size SizeFromClientSize(Size clientSize)
{
if (!<API key>)
return base.SizeFromClientSize(clientSize);
return SizeFromClientSize(clientSize.Width, clientSize.Height, false);
}
#endregion
#region PaintNonClientArea
private void PaintNonClientArea(IntPtr hWnd, IntPtr hRgn)
{
NativeMethods.RECT windowRect = new NativeMethods.RECT();
if (NativeMethods.GetWindowRect(hWnd, ref windowRect) == 0)
return;
Rectangle bounds = new Rectangle(0, 0,
windowRect.right - windowRect.left,
windowRect.bottom - windowRect.top);
if (bounds.Width == 0 || bounds.Height == 0)
return;
// The update region is clipped to the window frame. When wParam is 1, the entire window frame needs to be updated.
Region clipRegion = null;
if (hRgn != (IntPtr)1)
{
clipRegion = System.Drawing.Region.FromHrgn(hRgn);
hRgn = (IntPtr)0;
}
// MSDN states that only WINDOW and INTERSECTRGN are needed,
// but other sources confirm that CACHE is required on Win9x
// and you need CLIPSIBLINGS to prevent painting on overlapping windows.
IntPtr hDC = NativeMethods.GetDCEx(hWnd, hRgn,
(int)(NativeMethods.DCX.DCX_WINDOW | NativeMethods.DCX.DCX_INTERSECTRGN
| NativeMethods.DCX.DCX_CACHE | NativeMethods.DCX.DCX_CLIPSIBLINGS));
if (hDC == IntPtr.Zero)
hDC = NativeMethods.GetWindowDC(hWnd);
if (hDC == IntPtr.Zero)
return;
try
{
if (!this.<API key>)
{
using (Graphics g = Graphics.FromHdc(hDC))
{
//cliping rect is not cliping rect but actual rectangle
<API key>(new <API key>(g, bounds, clipRegion));
}
//NOTE: The Graphics object would realease the HDC on Dispose.
// So there is no need to call NativeMethods.ReleaseDC(msg.HWnd, hDC);
}
else
{
IntPtr CompatiblehDC = NativeMethods.CreateCompatibleDC(hDC);
IntPtr CompatibleBitmap = NativeMethods.<API key>(hDC, bounds.Width, bounds.Height);
try
{
NativeMethods.SelectObject(CompatiblehDC, CompatibleBitmap);
// copy current screen to bitmap
NativeMethods.BitBlt(CompatiblehDC, 0, 0, bounds.Width, bounds.Height, hDC, 0, 0, NativeMethods.<API key>.SRCCOPY);
using (Graphics g = Graphics.FromHdc(CompatiblehDC))
{
<API key>(new <API key>(g, bounds, clipRegion));
}
// copy current from bitmap to screen
NativeMethods.BitBlt(hDC, 0, 0, bounds.Width, bounds.Height, CompatiblehDC, 0, 0, NativeMethods.<API key>.SRCCOPY);
}
finally
{
NativeMethods.DeleteObject(CompatibleBitmap);
NativeMethods.DeleteDC(CompatiblehDC);
}
#if !NET1X
// .NET 2.0 has this new class BufferedGraphics. But it paints the clien area in all black.
// I dont know how to use it properly.
//using (BufferedGraphics bg = <API key>.Current.Allocate(hDC, bounds))
// Graphics g = bg.Graphics;
// //Rectangle clientRect = this.ClientRectangle;
// //clientRect.Offset(this.PointToScreen(Point.Empty));
// //g2.SetClip(clientRect, CombineMode.Exclude);
// <API key>(new <API key>(g, bounds, clipRegion));
// bg.Render();
#endif
}
}
finally
{
NativeMethods.ReleaseDC(this.Handle, hDC);
}
}
#endregion
#region InvalidateWindow
<summary>
This method should invalidate entire window including the non-client area.
</summary>
protected void InvalidateWindow()
{
if (!IsDisposed && IsHandleCreated)
{
NativeMethods.SetWindowPos(this.Handle, IntPtr.Zero, 0, 0, 0, 0,
(int)(NativeMethods.SetWindowPosOptions.SWP_NOACTIVATE | NativeMethods.SetWindowPosOptions.SWP_NOMOVE | NativeMethods.SetWindowPosOptions.SWP_NOSIZE |
NativeMethods.SetWindowPosOptions.SWP_NOZORDER | NativeMethods.SetWindowPosOptions.SWP_NOOWNERZORDER | NativeMethods.SetWindowPosOptions.SWP_FRAMECHANGED));
NativeMethods.RedrawWindow(this.Handle, IntPtr.Zero, IntPtr.Zero,
(int)(NativeMethods.RedrawWindowOptions.RDW_FRAME | NativeMethods.RedrawWindowOptions.RDW_UPDATENOW | NativeMethods.RedrawWindowOptions.RDW_INVALIDATE));
}
}
#endregion
#region Log
//[Conditional("DEBUGFORM")]
protected internal static void Log(System.Reflection.MemberInfo callingMethod, string message, params object[] args)
{
/*
if (args != null)
message = String.Format(message, args);
Debug.WriteLine(String.Format("{0}.{1} - {2}", callingMethod.DeclaringType.Name, callingMethod.Name, message));
*/
}
#endregion //Log
#region Mouse events hook...
private void HookMouseEvent()
{
if (!_trakingMouse)
{
_trakingMouse = true;
if (this._trackMouseEvent == null)
{
this._trackMouseEvent = new NativeMethods.TRACKMOUSEEVENT();
this._trackMouseEvent.dwFlags =
(int)(NativeMethods.<API key>.TME_HOVER |
NativeMethods.<API key>.TME_LEAVE |
NativeMethods.<API key>.TME_NONCLIENT);
this._trackMouseEvent.hwndTrack = this.Handle;
}
if (NativeMethods.TrackMouseEvent(this._trackMouseEvent) == false)
// use getlasterror to see whats wrong
Log(MethodInfo.GetCurrentMethod(), "Failed enabling TrackMouseEvent: error {0}",
NativeMethods.GetLastError());
}
}
private void UnhookMouseEvent()
{
_trakingMouse = false;
}
#endregion
#region Update...
private void UpdateButtonSkin()
{
foreach (CustomCaptionButton button in _captionButtons)
{
Image img = SkinInfo.GetImage(button.Key);
if (button.Key == CaptionButtonKey.Maximize && this.WindowState == FormWindowState.Maximized)
img = SkinInfo.GetImage(CaptionButtonKey.Restore);
button.Skin = new CustomCaptionButton.CaptionButtonSkin(img);
}
}
private void <API key>(Rectangle windowRect)
{
// start from top-right corner
int x = windowRect.Width - Skin.BorderWidth;
int y = Skin.BorderWidth;
foreach (CustomCaptionButton button in this.CaptionButtons)
{
if (button.Visible && button.Skin != null)
{
int size = Skin.IconSize;
x -= (size);
button.Bounds = new Rectangle(x, y, size, size);
}
}
// Should I move this where this actually changes WM_GETMINMAXINFO ??
//maximizeButton.Appearance = (this.WindowState == FormWindowState.Maximized) ?
// _borderAppearance.RestoreButton : _borderAppearance.MaximizeButton;
}
#endregion
#region Misc...
<summary>
This method handles depressing the titlebar button. It captures the mouse and creates a message loop
filtring only the mouse buttons until a WM_MOUSEMOVE or WM_LBUTTONUP message is received.
</summary>
<param name="currentButton">The button that was pressed</param>
<returns>true if WM_LBUTTONUP occured over this button; false when mouse was moved away from this button.</returns>
private bool DepressButton(CustomCaptionButton currentButton)
{
try
{
// callect all mouse events (should do the same as SetCapture())
this.Capture = true;
// draw button in pressed mode
currentButton.State = CaptionButtonState.Pressed;
DrawButton(currentButton);
// loop until button is released
bool result = false;
bool done = false;
while (!done)
{
// NOTE: This struct needs to be here. We had strange error (starting from Beta 2).
// when this was defined at begining of this method. also check if types are correct (no overlap).
Message m = new Message();
if (NativeMethods.PeekMessage(ref m, IntPtr.Zero,
(int)NativeMethods.WindowMessages.WM_MOUSEFIRST, (int)NativeMethods.WindowMessages.WM_MOUSELAST,
(int)NativeMethods.PeekMessageOptions.PM_REMOVE))
{
Log(MethodInfo.GetCurrentMethod(), "Message = {0}, Button = {1}", (NativeMethods.WindowMessages)m.Msg, currentButton);
switch (m.Msg)
{
case (int)NativeMethods.WindowMessages.WM_LBUTTONUP:
{
if (currentButton.State == CaptionButtonState.Pressed)
{
currentButton.State = CaptionButtonState.Normal;
DrawButton(currentButton);
}
Point pt = PointToWindow(PointToScreen(new Point(m.LParam.ToInt32())));
Log(MethodInfo.GetCurrentMethod(), "### Point = ({0}, {1})", pt.X, pt.Y);
result = currentButton.Bounds.Contains(pt);
done = true;
}
break;
case (int)NativeMethods.WindowMessages.WM_MOUSEMOVE:
{
Point clientPoint = PointToWindow(PointToScreen(new Point(m.LParam.ToInt32())));
if (currentButton.Bounds.Contains(clientPoint))
{
if (currentButton.State == CaptionButtonState.Normal)
{
currentButton.State = CaptionButtonState.Pressed;
DrawButton(currentButton);
}
}
else
{
if (currentButton.State == CaptionButtonState.Pressed)
{
currentButton.State = CaptionButtonState.Normal;
DrawButton(currentButton);
}
}
// [1531]: These variables need to be reset here although thay aren't changed
// before reaching this point
result = false;
done = false;
}
break;
}
}
}
return result;
}
finally
{
this.Capture = false;
}
}
private void DrawButton(CustomCaptionButton button)
{
if (IsHandleCreated)
{
// MSDN states that only WINDOW and INTERSECTRGN are needed,
// but other sources confirm that CACHE is required on Win9x
// and you need CLIPSIBLINGS to prevent painting on overlapping windows.
IntPtr hDC = NativeMethods.GetDCEx(this.Handle, (IntPtr)1,
(int)(NativeMethods.DCX.DCX_WINDOW | NativeMethods.DCX.DCX_INTERSECTRGN
| NativeMethods.DCX.DCX_CACHE | NativeMethods.DCX.DCX_CLIPSIBLINGS));
if (hDC == IntPtr.Zero)
hDC = NativeMethods.GetWindowDC(this.Handle);
if (hDC != IntPtr.Zero)
{
using (Graphics g = Graphics.FromHdc(hDC))
{
button.DrawButton(g, true, this.<API key>);
}
}
NativeMethods.ReleaseDC(this.Handle, hDC);
}
}
private Rectangle GetIconRectangle()
{
return new Rectangle(Skin.BorderWidth, Skin.BorderWidth, Skin.IconSize, Skin.IconSize);
}
#endregion
#region FormSkin events...
public event EventHandler SettingsClick;
public event EventHandler AboutClick;
#endregion
private void InitializeComponent()
{
this.SuspendLayout();
// CustomAppForm
this.ClientSize = new System.Drawing.Size(284, 265);
this.Name = "CustomAppForm";
this.ResumeLayout(false);
}
}
} |
## Welcome to GitHub Pages
You can use the [editor on GitHub](https://github.com/fabianHS/LND2017/edit/master/README.md) to maintain and preview the content for your website in Markdown files.
Whenever you commit to this repository, GitHub Pages will run [Jekyll](https://jekyllrb.com/) to rebuild the pages in your site, from the content in your Markdown files.
Markdown
Markdown is a lightweight and easy-to-use syntax for styling your writing. It includes conventions for
markdown
Syntax highlighted code block
# Header 1
## Header 2
Header 3
- Bulleted
- List
1. Numbered
2. List
**Bold** and _Italic_ and `Code` text
[Link](url) and 
For more details see [GitHub Flavored Markdown](https://guides.github.com/features/mastering-markdown/).
Jekyll Themes
Your Pages site will use the layout and styles from the Jekyll theme you have selected in your [repository settings](https://github.com/fabianHS/LND2017/settings). The name of this theme is saved in the Jekyll `_config.yml` configuration file.
Support or Contact
Having trouble with Pages? Check out our [documentation](https: |
/**
* Low level pin manipulation routines - used by all the drivers.
*
* These are based on the LPC1768 pinMode, digitalRead & digitalWrite routines.
*
* Couldn't just call exact copies because the overhead killed the LCD update speed
* With an intermediate level the softspi was running in the 10-20kHz range which
* resulted in using about about 25% of the CPU's time.
*/
void u8g_SetPinOutput(uint8_t internal_pin_number);
void u8g_SetPinInput(uint8_t internal_pin_number);
void u8g_SetPinLevel(uint8_t pin, uint8_t pin_status);
uint8_t u8g_GetPinLevel(uint8_t pin); |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>CAPIRSolver: Class Members - Functions</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body onload='searchBox.OnSelectItem(0);'>
<!-- Generated by Doxygen 1.7.3 -->
<script type="text/javascript"><!
var searchBox = new SearchBox("searchBox", "search",false,'Search');
--></script>
<div id="top">
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="sheep-icon-normal.png"></td>
<td style="padding-left: 0.5em;">
<div id="projectname">CAPIRSolver <span id="projectnumber">1.0</span></div>
<div id="projectbrief">API documentation of CAPIRSolver</div>
</td>
</tr>
</tbody>
</table>
</div>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li id="searchli">
<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="inherits.html"><span>Class Hierarchy</span></a></li>
<li class="current"><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<div id="navrow3" class="tabs2">
<ul class="tablist">
<li><a href="functions.html"><span>All</span></a></li>
<li class="current"><a href="functions_func.html"><span>Functions</span></a></li>
<li><a href="functions_vars.html"><span>Variables</span></a></li>
<li><a href="functions_enum.html"><span>Enumerations</span></a></li>
</ul>
</div>
<div id="navrow4" class="tabs3">
<ul class="tablist">
<li><a href="functions_func.html#index_a"><span>a</span></a></li>
<li><a href="functions_func_0x62.html#index_b"><span>b</span></a></li>
<li class="current"><a href="functions_func_0x63.html#index_c"><span>c</span></a></li>
<li><a href="functions_func_0x64.html#index_d"><span>d</span></a></li>
<li><a href="functions_func_0x65.html#index_e"><span>e</span></a></li>
<li><a href="functions_func_0x66.html#index_f"><span>f</span></a></li>
<li><a href="functions_func_0x67.html#index_g"><span>g</span></a></li>
<li><a href="functions_func_0x68.html#index_h"><span>h</span></a></li>
<li><a href="functions_func_0x69.html#index_i"><span>i</span></a></li>
<li><a href="functions_func_0x6b.html#index_k"><span>k</span></a></li>
<li><a href="functions_func_0x6c.html#index_l"><span>l</span></a></li>
<li><a href="functions_func_0x6d.html#index_m"><span>m</span></a></li>
<li><a href="functions_func_0x6e.html#index_n"><span>n</span></a></li>
<li><a href="functions_func_0x6f.html#index_o"><span>o</span></a></li>
<li><a href="functions_func_0x70.html#index_p"><span>p</span></a></li>
<li><a href="functions_func_0x72.html#index_r"><span>r</span></a></li>
<li><a href="functions_func_0x73.html#index_s"><span>s</span></a></li>
<li><a href="functions_func_0x74.html#index_t"><span>t</span></a></li>
<li><a href="functions_func_0x75.html#index_u"><span>u</span></a></li>
<li><a href="functions_func_0x76.html#index_v"><span>v</span></a></li>
<li><a href="functions_func_0x77.html#index_w"><span>w</span></a></li>
<li><a href="functions_func_0x78.html#index_x"><span>x</span></a></li>
<li><a href="functions_func_0x7e.html#index_0x7e"><span>~</span></a></li>
</ul>
</div>
</div>
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
initNavTree('functions.html','');
</script>
<div id="doc-content">
<div class="contents">
 
<h3><a class="anchor" id="index_c"></a>- c -</h3><ul>
<li>calcShortestPath()
: <a class="el" href="class_agent.html#<API key>">Agent</a>
</li>
<li><API key>()
: <a class="el" href="class_agent.html#<API key>">Agent</a>
</li>
<li>canReact()
: <a class="el" href="class_g_b___ghost.html#<API key>">GB_Ghost</a>
, <a class="el" href="class_g_b___sheep.html#<API key>">GB_Sheep</a>
, <a class="el" href="class_g_b___ghost.html#<API key>">GB_Ghost</a>
, <a class="el" href="class_monster.html#<API key>">Monster</a>
</li>
<li>checkVisibility()
: <a class="el" href="class_maze.html#<API key>">Maze</a>
</li>
<li>clear()
: <a class="el" href="<API key>.html#<API key>">rapidxml::memory_pool< Ch ></a>
, <a class="el" href="<API key>.html#<API key>">rapidxml::xml_document< Ch ></a>
</li>
<li>clone_node()
: <a class="el" href="<API key>.html#<API key>">rapidxml::memory_pool< Ch ></a>
</li>
<li>cloneAbsState()
: <a class="el" href="class_utilities.html#<API key>">Utilities</a>
</li>
<li>constructCollabQFns()
: <a class="el" href="class_maze.html#<API key>">Maze</a>
</li>
<li>constructTRCompAct()
: <a class="el" href="class_maze.html#<API key>">Maze</a>
</li>
<li><API key>()
: <a class="el" href="class_maze.html#<API key>">Maze</a>
</li>
<li><API key>()
: <a class="el" href="class_utilities.html#<API key>">Utilities</a>
</li>
<li><API key>()
: <a class="el" href="class_utilities.html#<API key>">Utilities</a>
</li>
<li>copyInfoFrom()
: <a class="el" href="<API key>.html#<API key>">GB_FieryMaze</a>
, <a class="el" href="<API key>.html#<API key>">GB_SheepMaze</a>
, <a class="el" href="class_maze.html#<API key>">Maze</a>
</li>
<li>copyState()
: <a class="el" href="class_utilities.html#<API key>">Utilities</a>
</li>
<li>copyStateMap()
: <a class="el" href="class_maze.html#<API key>">Maze</a>
</li>
<li>copyValueQFns()
: <a class="el" href="class_maze.html#<API key>">Maze</a>
</li>
</ul>
</div>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="footer">Generated on Fri Jun 8 2012 01:14:50 for CAPIRSolver by 
<a href="http:
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.3 </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>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>Enumerations</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="<API key>">
<iframe src="" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</body>
</html> |
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="report.css" type="text/css"/>
<title></title>
<script type="text/javascript" src="report.js"></script>
<script type="text/javascript" src="link_popup.js"></script>
<script type="text/javascript" src="tooltip.js"></script>
</head>
<body style="margin-left: 10px; margin-right: 10px; margin-top: 10px; margin-bottom: 10px;">
<div style="position:absolute; z-index:21; visibility:hidden" id="vplink">
<table border="1" cellpadding="0" cellspacing="0" bordercolor="#A9BFD3">
<tr>
<td>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr style="background:#DDDDDD">
<td style="font-size: 12px;" align="left">
<select onchange="vpLinkToggleName()" id="vplink-linkType">
<option value="Project Link">Project Link</option>
<option value="Page URL">Page URL</option>
</select>
</td>
<td style="font-size: 12px;" align="right">
<input onclick="javascript: vpLinkToggleName()" id="vplink-checkbox" type="checkbox" />
<label for="vplink-checkbox">with Name</label> </td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<textarea id="vplink-text" style="width: 348px; height: 60px; border-color: #7EADD9; outline: none;"></textarea> </td>
</tr>
</table>
</div>
<div class="HeaderText">
<span>
discovery </span>
</div>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="HeaderLine1">
</td>
</tr>
<tr>
<td class="HeaderLine2">
</td>
</tr>
<tr>
<td class="HeaderLine3">
</td>
</tr>
</table>
<p>
<a href="<API key>.html" class="PageParentTitle">
Cours : Etat</a>
</p>
<p class="PageTitle">
Initial Pseudo State - <a onclick="javascript: showVpLink('discovery.vpp://modelelement/iHB02CKAUCgiawi1', '\ndiscovery.vpp://modelelement/iHB02CKAUCgiawi1', '', this); return false;" style="padding-left: 16px; font-size: 12px" href="
<img src="../images/icons/link.png" border="0"> Lien</a>
</p>
<p>
</p>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="Category">
Propriétés </td>
</tr>
<tr>
<td class="<API key>">
</td>
</tr>
</table>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td colSpan="4" class="TableHeaderLine">
</td>
</tr>
<tr>
<td colSpan="4" class="TableHeaderLine1">
</td>
</tr>
<tr class="TableHeader">
<td class="<API key>">
</td>
<td width="25%">
<span class="TableHeaderText">Nom</span> </td>
<td class="<API key>">
</td>
<td>
<span class="TableHeaderText">Valeur</span> </td>
</tr>
<tr>
<td colSpan="4" class="TableHeaderLine2">
</td>
</tr>
<tr class="TableRow1">
<td>
</td>
<td>
<span class="TableContent">Auteur</span> </td>
<td>
</td>
<td>
<span class="TableContent">jpdms</span> </td>
</tr>
<tr class="TableRow2">
<td>
</td>
<td>
<span class="TableContent">Date et heure de création</span> </td>
<td>
</td>
<td>
<span class="TableContent">10 févr. 2014 10:43:26</span> </td>
</tr>
<tr class="TableRow1">
<td>
</td>
<td>
<span class="TableContent">Dernière modification</span> </td>
<td>
</td>
<td>
<span class="TableContent">10 févr. 2014 10:47:14</span> </td>
</tr>
<tr class="TableRow2">
<td>
</td>
<td>
<span class="TableContent">Visibilité</span> </td>
<td>
</td>
<td>
<span class="TableContent">Unspecified</span> </td>
</tr>
</table>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="<API key>">
</td>
</tr>
<tr>
<td class="TableFooter">
</td>
</tr>
</table>
<p>
</p>
<p>
</p>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="Category">
Sommaire des relations </td>
</tr>
<tr>
<td class="<API key>">
</td>
</tr>
</table>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td colSpan="6" class="TableHeaderLine">
</td>
</tr>
<tr>
<td colSpan="6" class="TableHeaderLine1">
</td>
</tr>
<tr class="TableHeader">
<td class="<API key>">
</td>
<td width="25%">
<span class="TableHeaderText">Nom</span> </td>
<td class="<API key>">
</td>
<td>
<span class="TableHeaderText">Début</span> </td>
<td class="<API key>">
</td>
<td>
<span class="TableHeaderText">Fin</span> </td>
</tr>
<tr>
<td colSpan="6" class="TableHeaderLine2">
</td>
</tr>
<tr class="TableRow1">
<td class="<API key>">
</td>
<td>
<span class="TableContent">
<div style="float: left; width: 18px !important;height: 18px !important;background-image:url(../images/icons/Transition.png) !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/icons/Transition.png'); background-repeat: no-repeat;">
</div>
<a href="<API key>.html#76R02CKAUCgiawjA" class="ItemLink">/1er page : Transition</a> </span>
</td>
<td class="<API key>">
</td>
<td>
<span class="TableContent">
<div style="float: left; width: 18px !important;height: 18px !important;background-image:url(../images/icons/InitialPseudoState.png) !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/icons/InitialPseudoState.png'); background-repeat: no-repeat;">
</div>
<a href="<API key>.html" class="ItemLink"> : Initial Pseudo State</a> </span>
</td>
<td class="<API key>">
</td>
<td>
<span class="TableContent">
<div style="float: left; width: 18px !important;height: 18px !important;background-image:url(../images/icons/State.png) !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/icons/State.png'); background-repeat: no-repeat;">
</div>
<a href="<API key>.html" class="ItemLink">Cours i : Etat</a> </span>
</td>
</tr>
</table>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="<API key>">
</td>
</tr>
<tr>
<td class="TableFooter">
</td>
</tr>
</table>
<p>
</p>
<p>
</p>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="Category">
Détails des relation </td>
</tr>
<tr>
<td class="<API key>">
</td>
</tr>
</table>
<a name="76R02CKAUCgiawjA">
</a>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td colSpan="4" class="TableHeaderLine">
</td>
</tr>
<tr>
<td colSpan="4" class="TableHeaderLine1">
</td>
</tr>
<tr class="TableHeader">
<td class="<API key>">
</td>
<td width="25%">
<span class="TableHeaderText">Nom</span> </td>
<td class="<API key>">
</td>
<td>
<span class="TableHeaderText">Valeur</span> </td>
</tr>
<tr>
<td colSpan="4" class="TableHeaderLine2">
</td>
</tr>
<tr class="TableRow1">
<td>
</td>
<td>
<span class="TableContent">Nom</span> </td>
<td>
</td>
<td>
<span class="TableContent">/1er page</span> </td>
</tr>
<tr class="TableRow2">
<td>
</td>
<td>
<span class="TableContent">Auteur</span> </td>
<td>
</td>
<td>
<span class="TableContent">jpdms</span> </td>
</tr>
<tr class="TableRow1">
<td>
</td>
<td>
<span class="TableContent">Date et heure de création</span> </td>
<td>
</td>
<td>
<span class="TableContent">10 févr. 2014 10:43:33</span> </td>
</tr>
<tr class="TableRow2">
<td>
</td>
<td>
<span class="TableContent">Dernière modification</span> </td>
<td>
</td>
<td>
<span class="TableContent">10 févr. 2014 10:47:14</span> </td>
</tr>
<tr class="TableRow1">
<td>
</td>
<td>
<span class="TableContent">Kind</span> </td>
<td>
</td>
<td>
<span class="TableContent">External</span> </td>
</tr>
</table>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="<API key>">
</td>
</tr>
<tr>
<td class="TableFooter">
</td>
</tr>
</table>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td style="height: 5px;">
</td>
</tr>
</table>
<p>
</p>
<p>
</p>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="Category">
Diagrammes Occupés </td>
</tr>
<tr>
<td class="<API key>">
</td>
</tr>
</table>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td colSpan="4" class="TableHeaderLine">
</td>
</tr>
<tr>
<td colSpan="4" class="TableHeaderLine1">
</td>
</tr>
<tr class="TableHeader">
<td class="<API key>">
</td>
<td>
<span class="TableHeaderText">Diagramme</span> </td>
</tr>
<tr>
<td colSpan="2" class="TableHeaderLine2">
</td>
</tr>
<tr class="TableRow1">
<td class="<API key>">
</td>
<td>
<span class="TableContent">
<div style="float: left; width: 18px !important;height: 18px !important;background-image:url(../images/icons/StateDiagram.png) !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/icons/StateDiagram.png'); background-repeat: no-repeat;">
</div>
<a href="<API key>.html" class="ItemLink">IHM Client : Diagramme d'automate fini</a> </span>
</td>
</tr>
</table>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="<API key>">
</td>
</tr>
<tr>
<td class="TableFooter">
</td>
</tr>
</table>
<div style="height: 20px;">
</div>
<table border="0" cellpadding="0" width="100%" cellspacing="0">
<tr>
<td class="FooterLine">
</td>
</tr>
</table>
<div class="HeaderText">
discovery </div>
</body>
</html> |
<!DOCTYPE HTML PUBLIC "-
<html>
<head>
<title>MPC-HC WebServer - Player</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="default.css">
<script type="text/javascript" src="javascript.js"></script>
<link rel="shortcut icon" href="favicon.ico">
</head>
<body onload="playerInit()">
<div align="center">
<table id="player" cellpadding="0" cellspacing="0">
<tr>
<td colspan="3">
<table id="header" cellpadding="0" cellspacing="0">
<tr>
<td id="headericon"></td>
<td id="headerback"><div class="nobr" id="title"> </div></td>
<td id="headerclose" onclick="OnCommand(816)"></td>
</tr>
</table>
</td>
</tr>
<tr>
<td id="leftside"></td>
<td>
<table cellpadding="0" cellspacing="0" id="center">
<tr>
<td>
<table id="menu" width="100%">
<tr>
<td>File</td>
<td>View</td>
<td>Play</td>
<td>Navigate</td>
<td>Favorites</td>
<td width="100%" align="right">Help</td>
</tr>
</table>
</td>
</tr>
<tr>
<td id="video" align="center" onclick="OnCommand(889)">
<img src="snapshot.jpg" alt="snapshot" id="snapshot" onload="OnLoadSnapShot()" onabort="<API key>()" onerror="<API key>()">
</td>
</tr>
<tr>
<td>
<table width="100%" id="seekbar" cellpadding="0" cellspacing="0">
<tr>
<td id="seekbarleft"><img src="img/seekbarleft.png" alt="seekbarleft"></td>
<td id="seekbarchleft" width="0%"></td>
<td id="seekbargrip"><img src="img/seekbargrip.png" alt="seekbargrip"></td>
<td id="seekbarchright" width="100%"></td>
<td id="seekbarright"><img src="img/seekbarright.png" alt="seekbarright"></td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table width="100%" cellpadding="0" cellspacing="0" id="controlbar">
<tr>
<td id="controlbuttonplay" onclick="OnCommand(887)"></td>
<td id="controlbuttonpause" onclick="OnCommand(888)"></td>
<td id="controlbuttonstop" onclick="OnCommand(890)"></td>
<td id="<API key>" onclick="OnCommand(920)"></td>
<td id="<API key>" onclick="OnCommand(894)"></td>
<td id="<API key>" onclick="OnCommand(895)"></td>
<td id="<API key>" onclick="OnCommand(921)"></td>
<td id="controlbuttonstep" onclick="OnCommand(891)"></td>
<td> </td>
<td id="controlvolumemute" onclick="OnCommand(909)"></td>
<td id="controlvolumebar" valign="top">
<img src="img/controlvolumegrip.png" id="controlvolumegrip" alt="control volume grip">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table width="100%" id="statusbar">
<tr>
<td><div id="status"></div></td>
<td align="right"><div id="timer"> </div></td>
</tr>
</table>
</td>
</tr>
</table>
</td>
<td id="rightside"></td>
</tr>
<tr>
<td id="leftbottomside"></td>
<td id="bottomside"></td>
<td id="rightbottomside"></td>
</tr>
</table>
</div>
</body>
</html> |
<?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['allowguests'] = 'يسمح للمستخدمين الضيوف بالدخول إلى هذا المقرر الدراسي';
$string['password'] = 'كلمة السر';
$string['pluginname'] = 'دخول الضيف'; |
f = open("Sorted_Files.csv")
j = open("File_Percentages.csv",'w')
lines = f.readlines()
lineCount = 0
percentages = []
print("How many months were there?")
total = input()
print(int(total))
for line in lines:
if lineCount == 0:
lineCount +=1
continue
num = line.split(",")[1]
fi = line.split(",")[0]
percentages.append((fi,str(int((int(num)/int(total))*100))+"%"))
print(str((int(total)/int(num))*100))
print(percentages)
for i in percentages:
j.write(i[0]+","+i[1]+"\n")
f.close()
j.close() |
FROM bengosney/py-docker-gen
MAINTAINER Ben Gosney <bengosney@googlemail.com>
COPY nginx.tpl /opt/app/
CMD python /opt/app/py-docker-gen.py \
--filter hostname \
--notify nginx-proxy \
/opt/app/nginx.tpl \
/etc/nginx/conf.d/proxy.conf |
**Razuna Chrome Extension**
With the Razuna Chrome Extension you have a simple way to allow your users to browse the files in Razuna, download them and even upload new files within the extension.
**Installation**
All Chrome Extensions are hosted in the Google Chrome WebStore. Visit the [Razuna Chrome Extensions page](https://chrome.google.com/webstore/detail/<API key>?hl=en-US) and click on "Add to Chrome" button. You don't need to restart Chrome in order to use the plugin. Once installed you will see the Razuna icon in the upper right corner.
___
**Options**
The first time you click on the Razuna Icon you will be taken to the Option page. This is because you have not set a "Razuna address" the extension should connect to. The Razuna Chrome Extension works with the [Razuna Hosted Edition](http:

Once set, click on "Save Options". You can then close this window and click on the Razuna Icon again. This time it will connect you to your Razuna instance and prompts for the login information.
If you need to edit your options again, just do a right-click on the Razuna icon and select "Options" from the menu.
___
**Usage**
In order to browse your folders and files simply click on the Razuna icon. If you haven't signed in, you will be prompted to sign in. This are the same credentials as your standard Razuna account. As a fact, the Razuna Chrome Extension is a stripped down version of the standard Razuna experience.

Once you signed in, a list of your folders is displayed. Clicking on a folder will display the content of the folder with your files.

In this list you will have the option to view and download each of your files. Additional you have the option to upload new files to this folder by clicking on the "Upload" link. If you want to view or download a file just click on the file name and the link(s) to the file and available renditions will be shown.

___
**Upload**
If you visit a folder and you have the required permissions to be able to upload files you will have a "Upload" link in the upper right corner. This will present you with the standard Razuna Upload Tool that you came to love. Simply drag & drop your files into the window in order to upload them to Razuna. Files will be available in the standard Razuna application and in the Chrome Extension.
(Unfortunately there is no way within the Google Chrome Extension framework to do this within the same window, thus the Upload link takes you to a new popup window).
___
**Search**
The Razuna Chrome Extension also features the same search as you've come to know from Razuna itself. The same options and search syntax is available, thus making the Razuna Chrome Extension a valuable partner in browsing your Razuna library. |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc on Thu Nov 22 16:43:24 EST 2007 -->
<TITLE>
Xalan-Java 2.7.1: Uses of Class org.apache.xml.serializer.OutputPropertyUtils
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<A NAME="navbar_top"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<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"> <A HREF="../../../../../org/apache/xml/serializer/OutputPropertyUtils.html"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </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-all.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" TARGET="_top"><B>FRAMES</B></A>
<A HREF="OutputPropertyUtils.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
</TR>
</TABLE>
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.xml.serializer.OutputPropertyUtils</B></H2>
</CENTER>
No usage of org.apache.xml.serializer.OutputPropertyUtils
<P>
<HR>
<A NAME="navbar_bottom"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<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"> <A HREF="../../../../../org/apache/xml/serializer/OutputPropertyUtils.html"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </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-all.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" TARGET="_top"><B>FRAMES</B></A>
<A HREF="OutputPropertyUtils.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
</TR>
</TABLE>
<HR>
Copyright © 2006 Apache XML Project. All Rights Reserved.
</BODY>
</HTML> |
(function(){// Collections
Blockchain = new Mongo.Collection('blockchain', {connection: null});
Nodes = new Mongo.Collection('nodes', {connection: null});
Map = new Mongo.Collection('map', {connection: null});
/* Controllers */
var MAX_BINS = 40;
// Main Stats init
Blockchain.insert({
_id: 'meta',
frontierHash: '<API key>',
nodesTotal: 0,
nodesActive: 0,
bestBlock: 0,
lastBlock: 0,
lastDifficulty: 0,
upTimeTotal: 0,
avgBlockTime: 0,
blockPropagationAvg: 0,
avgHashrate: 0,
uncleCount: 0,
bestStats: {},
lastBlocksTime: _.fill(Array(MAX_BINS), 2),
difficultyChart: _.fill(Array(MAX_BINS), 2),
transactionDensity: _.fill(Array(MAX_BINS), 2),
gasSpending: _.fill(Array(MAX_BINS), 2),
miners: [],
map: [],
<API key>: [],
uncleCountChart: _.fill(Array(MAX_BINS), 2),
coinbases: [],
latency: 0,
currentApiVersion: "0.0.16",
predicate: localStorage.predicate || ['-pinned', '-stats.active', '-stats.block.number', 'stats.block.propagation'],
reverse: localStorage.reverse || false,
pinned: localStorage.pinned || [],
prefixPredicate: ['-pinned', '-stats.active'],
originalPredicate: ['-stats.block.number', 'stats.block.propagation']
});
// $scope.orderTable = function(predicate, reverse)
// if(!_.isEqual(predicate, $scope.originalPredicate))
// $scope.reverse = reverse;
// $scope.originalPredicate = predicate;
// $scope.predicate = _.union($scope.prefixPredicate, predicate);
// else
// $scope.reverse = !$scope.reverse;
// _.forEach(predicate, function (value, key) {
// $scope.predicate = _.union($scope.prefixPredicate, predicate);
// localStorage.predicate = $scope.predicate;
// localStorage.reverse = $scope.reverse;
// $scope.pinNode = function(id)
// index = findIndex({id: id});
// if( !_.isUndefined($scope.nodes[index]) )
// $scope.nodes[index].pinned = !$scope.nodes[index].pinned;
// if($scope.nodes[index].pinned)
// $scope.pinned.push(id);
// else
// $scope.pinned.splice($scope.pinned.indexOf(id), 1);
// localStorage.pinned = $scope.pinned;
// var timeout = setInterval(function ()
// $scope.$apply();
// }, 300);
// $scope.getNumber = function (num) {
// return new Array(num);
// Socket listeners
socket.on('open', function open() {
socket.emit('ready');
console.log('The connection has been opened.');
})
.on('end', function end() {
console.log('Socket connection ended.')
})
.on('error', function error(err) {
console.log(err);
})
.on('reconnecting', function reconnecting(opts) {
console.log('We are scheduling a reconnect operation', opts);
})
.on('data', function incoming(data) {
socketAction(data.action, data.data);
});
socket.on('init', function(data)
{
_.each(data.nodes, function(node){
Nodes.upsert(node.id, socketAction('init', node));
addToMap(node);
});
});
socket.on('client-latency', function(data)
{
Blockchain.update('meta', {$set: {
latency: data.latency
}});
})
function socketAction(action, data)
{
// console.log('Action: ', action);
// console.log('Data: ', data);
switch(action)
{
case "init":
var node = data;
// Init hashrate
if( _.isUndefined(node.stats.hashrate) )
node.stats.hashrate = 0;
// Init latency
latencyFilter(node);
// Init history
if( _.isUndefined(data.history) )
{
data.history = new Array(40);
_.fill(data.history, -1);
}
// Init or recover pin
node.pinned = (Blockchain.findOne().pinned.indexOf(node.id) >= 0 ? true : false);
if( Nodes.find().count() > 0 )
{
toastr['success']("Got nodes list", "Got nodes!");
updateActiveNodes();
}
return node;
case "add":
if( addNewNode(data) )
toastr['success']("New node "+ Nodes.findOne(data.id).info.name +" connected!", "New node!");
else
toastr['info']("Node "+ Nodes.findOne(data.id).info.name +" reconnected!", "Node is back!");
break;
// TODO: Remove when everybody updates api client to 0.0.12
case "update":
var foundNode = Nodes.findOne(data.id);
if( foundNode && !_.isUndefined(foundNode.stats) )
{
if( !_.isUndefined(foundNode.stats.latency) )
data.stats.latency = foundNode.stats.latency;
if( _.isUndefined(data.stats.hashrate) )
data.stats.hashrate = 0;
if( foundNode.stats.block.number < data.stats.block.number )
{
var best = Nodes.findOne({},{sort: {'stats.block.number': -1}});
if(best) {
if (data.block.number > best.stats.block.number) {
data.block.arrived = _.now();
} else {
data.block.arrived = best.stats.block.arrived;
}
}
foundNode.history = data.history;
}
foundNode.stats = data.stats;
foundNode.stats.block = data.block; // necessary?
if( !_.isUndefined(data.stats.latency) && _.get(foundNode, 'stats.latency', 0) !== data.stats.latency )
{
foundNode.stats.latency = data.stats.latency;
latencyFilter(foundNode);
}
Nodes.update(data.id, foundNode);
updateBestBlock();
}
break;
case "block":
var foundNode = Nodes.findOne(data.id);
if( foundNode && foundNode.stats )
{
var set = {};
if( foundNode.stats.block.number < data.block.number )
{
var best = Nodes.findOne({},{sort: {'stats.block.number': -1}});
if(best) {
if (data.block.number > best.stats.block.number) {
data.block.arrived = _.now();
} else {
data.block.arrived = best.stats.block.arrived;
}
}
set.history = data.history;
}
set['stats.block'] = data.block;
set['stats.propagationAvg'] = data.propagationAvg;
Nodes.update('meta', {$set: set});
updateBestBlock();
}
break;
case "pending":
var foundNode = Nodes.findOne(data.id);
if( !_.isUndefined(data.id) && foundNode )
{
if( !_.isUndefined(foundNode) && !_.isUndefined(foundNode.stats.pending) && !_.isUndefined(data.pending) )
Nodes.update(data.id, {$set: {
'stats.pending': data.pending
}});
}
break;
case "stats":
var foundNode = Nodes.findOne(data.id);
if( !_.isUndefined(data.id) && foundNode )
{
if( !_.isUndefined(foundNode) && !_.isUndefined(foundNode.stats) )
{
Nodes.update(foundNode._id, {$set:{
'stats.active': data.stats.active,
'stats.mining': data.stats.mining,
'stats.hashrate': data.stats.hashrate,
'stats.peers': data.stats.peers,
'stats.gasPrice': data.stats.gasPrice,
'stats.uptime': data.stats.uptime
}});
if( !_.isUndefined(data.stats.latency) && _.get(foundNode, 'stats.latency', 0) !== data.stats.latency )
{
Nodes.update(foundNode._id, {$set:{
'stats.latency': data.stats.latency
}});
latencyFilter(foundNode);
}
updateActiveNodes();
}
}
break;
case "info":
var foundNode = Nodes.findOne(data.id);
if( foundNode )
{
var set = {};
set.info = data.info;
if( _.isUndefined(foundNode.pinned) )
set.pinned = false;
Nodes.update(data.id, {$set: set});
// Init latency
latencyFilter(foundNode);
updateActiveNodes();
}
break;
case "<API key>":
Blockchain.update('meta', {$set:{
<API key>: data.histogram,
blockPropagationAvg: data.avg
}});
break;
case "uncleCount":
Blockchain.update('meta', {$set:{
uncleCount: data[0] + data[1],
uncleCountChart: (function(){
data.reverse();
return data;
})()
}});
break;
case "charts":
var meta = Blockchain.findOne('meta');
if( !_.isEqual(meta.avgBlockTime, data.avgBlocktime) )
meta.avgBlockTime = data.avgBlocktime;
if( !_.isEqual(meta.avgHashrate, data.avgHashrate) )
meta.avgHashrate = data.avgHashrate;
if( !_.isEqual(meta.lastBlocksTime, data.blocktime) && data.blocktime.length >= MAX_BINS )
meta.lastBlocksTime = data.blocktime;
if( !_.isEqual(meta.difficultyChart, data.difficulty) && data.difficulty.length >= MAX_BINS )
meta.difficultyChart = data.difficulty;
if( !_.isEqual(meta.<API key>, data.propagation.histogram) ) {
meta.<API key> = data.propagation.histogram;
meta.blockPropagationAvg = data.propagation.avg;
}
data.uncleCount.reverse();
if( !_.isEqual(meta.uncleCountChart, data.uncleCount) && data.uncleCount.length >= MAX_BINS ) {
meta.uncleCount = data.uncleCount[data.uncleCount.length-2] + data.uncleCount[data.uncleCount.length-1];
meta.uncleCountChart = data.uncleCount;
}
if( !_.isEqual(meta.transactionDensity, data.transactions) && data.transactions.length >= MAX_BINS )
meta.transactionDensity = data.transactions;
if( !_.isEqual(meta.gasSpending, data.gasSpending) && data.gasSpending.length >= MAX_BINS )
meta.gasSpending = data.gasSpending;
if( !_.isEqual(meta.miners, data.miners) ) {
meta.miners = data.miners;
getMinersNames(meta);
}
// update
delete meta._id;
Blockchain.update('meta', {$set: meta});
break;
case "inactive":
var foundNode = Nodes.findOne(data.id);
if( foundNode )
{
if( !_.isUndefined(data.stats) ) {
Nodes.update(data.id, {$set: {
stats: data.stats
}});
}
toastr['error']("Node "+ foundNode.info.name +" went away!", "Node connection was lost!");
updateActiveNodes();
}
break;
case "latency":
if( !_.isUndefined(data.id) && !_.isUndefined(data.latency) )
{
var foundNode = Nodes.findOne(data.id);
if( foundNode )
{
if( !_.isUndefined(foundNode) && !_.isUndefined(foundNode.stats) && !_.isUndefined(foundNode.stats.latency) && foundNode.stats.latency !== data.latency )
{
Nodes.update(data.id, {$set: {
'stats.latency': data.latency
}});
latencyFilter(foundNode);
}
}
}
break;
case "client-ping":
socket.emit('client-pong', {
serverTime: data.serverTime,
clientTime: _.now()
});
break;
}
// $scope.$apply();
}
function getMinersNames(meta)
{
if( meta.miners.length > 0 )
{
_.forIn(meta.miners, function (value, key)
{
if(value.name !== false)
return;
if(value.miner === "0000000000000000")
return;
if(miner = Nodes.findOne({'info.coinbase': value.miner}))
var name = miner.info.name;
if( !_.isUndefined(name) ) {
meta.miners[key].name = name;
}
});
}
return meta;
}
function addNewNode(data)
{
var foundNode = Nodes.findOne(data.id);
if( _.isUndefined(data.history) )
{
data.history = new Array(40);
_.fill(data.history, -1);
}
data.pinned = ( !_.isUndefined(foundNode.pinned) ? foundNode.pinned : false);
if( !_.isUndefined(foundNode.history) )
{
data.history = foundNode.history;
}
// update node
Nodes.upsert(data.id, {$set: data});
addToMap(data);
updateActiveNodes();
return false;
}
function addToMap(data) {
// add to map
var bestblock = Blockchain.findOne().bestBlock;
if(!Map.findOne(data.id) && data.geo != null)
Map.insert({
_id: data.id,
radius: 3,
latitude: data.geo.ll[0],
longitude: data.geo.ll[1],
nodeName: data.info.name,
fillClass: mainClass(data.stats, bestblock),
fillKey: mainClass(data.stats, bestblock).replace('text-', ''),
});
}
function updateActiveNodes()
{
updateBestBlock();
var nodesTotal = Nodes.find().count(),
nodesActive = 0,
upTimeTotal = 0;
// iterate over all nodes to get the correct data
_.each(Nodes.find().fetch(), function(node){
if(node.stats) {
if(node.stats.active)
nodesActive++
upTimeTotal += node.stats.uptime;
}
});
Blockchain.update('meta', {$set: {
nodesTotal: nodesTotal,
nodesActive: nodesActive,
upTimeTotal: upTimeTotal / nodesTotal
}});
}
function updateBestBlock()
{
if( Nodes.find().count() )
{
// var chains = {};
// var maxScore = 0;
// _($scope.nodes)
// .map(function (item)
// maxScore += (item.trusted ? 50 : 1);
// if( _.isUndefined(chains[item.stats.block.number]) )
// chains[item.stats.block.number] = [];
// if( _.isUndefined(chains[item.stats.block.number][item.stats.block.fork]) )
// chains[item.stats.block.number][item.stats.block.fork] = {
// fork: item.stats.block.fork,
// count: 0,
// trusted: 0,
// score: 0
// if(item.stats.block.trusted)
// chains[item.stats.block.number][item.stats.block.fork].trusted++;
// else
// chains[item.stats.block.number][item.stats.block.fork].count++;
// chains[item.stats.block.number][item.stats.block.fork].score = chains[item.stats.block.number][item.stats.block.fork].trusted * 50 + chains[item.stats.block.number][item.stats.block.fork].count;
// .value();
// $scope.maxScore = maxScore;
// $scope.chains = _.reduce(chains, function (result, item, key)
// result[key] = _.max(item, 'score');
// return result;
var bestBlock = Nodes.findOne({'stats.block.number': {$exists: true}},{sort: {'stats.block.number': -1}});
if( bestBlock && bestBlock.stats.block.number !== Blockchain.findOne().bestBlock )
{
console.log('bestblock', bestBlock.stats.block.number);
Blockchain.update('meta', {$set: {
bestBlock: bestBlock.stats.block.number,
bestStats: bestBlock.stats,
lastBlock: bestBlock.stats.block.arrived,
lastDifficulty: bestBlock.stats.block.difficulty
}});
}
}
}
// function forkFilter(node)
// if( _.isUndefined(node.readable) )
// node.readable = {};
// node.readable.forkClass = 'hidden';
// node.readable.forkMessage = '';
// return true;
// node.readable.forkClass = 'hidden';
// node.readable.forkMessage = '';
// return true;
// if( $scope.chains[node.stats.block.number].fork !== node.stats.block.fork )
// node.readable.forkClass = 'text-danger';
// node.readable.forkMessage = 'Wrong chain.<br/>This chain is a fork.';
// return false;
// if( $scope.chains[node.stats.block.number].score / $scope.maxScore < 0.5)
// node.readable.forkClass = 'text-warning';
// node.readable.forkMessage = 'May not be main chain.<br/>Waiting for more confirmations.';
// return false;
function latencyFilter(node)
{
// var set = {};
// if( _.isUndefined(node.readable) )
// set['node.readable'] = {};
// if( _.isUndefined(node.stats) ) {
// set['readable.latencyClass'] = 'text-danger';
// set['readable.latency'] = 'offline';
// set['readable.latencyClass'] = 'text-danger';
// set['readable.latency'] = 'offline';
// else
// if (node.stats.latency <= 100)
// set['readable.latencyClass'] = 'text-success';
// if (node.stats.latency > 100 && node.stats.latency <= 1000)
// set['readable.latencyClass'] = 'text-warning';
// if (node.stats.latency > 1000)
// set['readable.latencyClass'] = 'text-danger';
// set['readable.latency'] = node.stats.latency + ' ms';
// // update node
// Nodes.upsert(node.id, {$set: set});
}
})(); |
package org.openurp.edu.eams.util.stat
import scala.collection.mutable.HashSet
import scala.collection.mutable.Buffer
import scala.collection.mutable.ListBuffer
import org.beangle.commons.collection.Collections
object StatUtils {
def setValueToMap(key: String,
tempValue: AnyRef,
tempType: String,
m: collection.mutable.Map[Any, Any]) {
if ("integer" == tempType) {
if (m.contains(key)) {
m.put(key, new java.lang.Integer(m.get(key).asInstanceOf[java.lang.Integer].intValue() +
tempValue.asInstanceOf[java.lang.Integer].intValue()))
} else {
m.put(key, tempValue.asInstanceOf[java.lang.Integer])
}
} else if ("float" == tempType) {
if (m.contains(key)) {
m.put(key, new java.lang.Float(m.get(key).asInstanceOf[java.lang.Float].floatValue() +
tempValue.asInstanceOf[java.lang.Float].floatValue()))
} else {
m.put(key, (tempValue).asInstanceOf[java.lang.Float])
}
} else if ("list" == tempType) {
var tempList = new ListBuffer[Any]
if (m.contains(key)) {
tempList = m.get(key).asInstanceOf[ListBuffer[Any]]
}
tempList += tempValue
m.put(key, tempList)
} else if ("set" == tempType) {
var tempSet = Collections.newSet[Any]
if (m.contains(key)) {
tempSet = m.get(key).asInstanceOf[collection.mutable.Set[Any]]
}
tempSet.add(tempValue)
m.put(key, tempSet)
}
}
} |
#ifndef QSCXMLEVENT_P_H
#define QSCXMLEVENT_P_H
// W A R N I N G
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
// We mean it.
#include <QtScxml/qscxmlevent.h>
#include <QtScxml/private/<API key>.h>
#ifndef BUILD_QSCXMLC
#include <QtScxml/qscxmlstatemachine.h>
#endif
#include <QtCore/qatomic.h>
QT_BEGIN_NAMESPACE
#ifndef BUILD_QSCXMLC
class QScxmlEventBuilder
{
QScxmlStateMachine* stateMachine;
<API key>::StringId instructionLocation;
QString event;
<API key>::EvaluatorId eventexpr;
QString contents;
<API key>::EvaluatorId contentExpr;
const <API key>::Array<<API key>::ParameterInfo> *params;
QScxmlEvent::EventType eventType;
QString id;
QString idLocation;
QString target;
<API key>::EvaluatorId targetexpr;
QString type;
<API key>::EvaluatorId typeexpr;
const <API key>::Array<<API key>::StringId> *namelist;
static QAtomicInt idCounter;
QString generateId() const
{
QString id = QString::number(++idCounter);
id.prepend(QStringLiteral("id-"));
return id;
}
QScxmlEventBuilder()
{ init(); }
void init() // Because stupid VS2012 can't cope with non-static field initializers.
{
stateMachine = Q_NULLPTR;
eventexpr = <API key>::NoEvaluator;
contentExpr = <API key>::NoEvaluator;
params = Q_NULLPTR;
eventType = QScxmlEvent::ExternalEvent;
targetexpr = <API key>::NoEvaluator;
typeexpr = <API key>::NoEvaluator;
namelist = Q_NULLPTR;
}
public:
QScxmlEventBuilder(QScxmlStateMachine *stateMachine, const QString &eventName, const <API key>::DoneData *doneData)
{
init();
this->stateMachine = stateMachine;
Q_ASSERT(doneData);
instructionLocation = doneData->location;
event = eventName;
contents = stateMachine->tableData()->string(doneData->contents);
contentExpr = doneData->expr;
params = &doneData->params;
eventType = QScxmlEvent::InternalEvent;
}
QScxmlEventBuilder(QScxmlStateMachine *stateMachine, const <API key>::Send &send)
{
init();
this->stateMachine = stateMachine;
instructionLocation = send.instructionLocation;
event = stateMachine->tableData()->string(send.event);
eventexpr = send.eventexpr;
contents = stateMachine->tableData()->string(send.content);
contentExpr = send.contentexpr;
params = send.params();
id = stateMachine->tableData()->string(send.id);
idLocation = stateMachine->tableData()->string(send.idLocation);
target = stateMachine->tableData()->string(send.target);
targetexpr = send.targetexpr;
type = stateMachine->tableData()->string(send.type);
typeexpr = send.typeexpr;
namelist = &send.namelist;
}
QScxmlEvent *operator()() { return buildEvent(); }
QScxmlEvent *buildEvent();
static QScxmlEvent *errorEvent(QScxmlStateMachine *stateMachine, const QString &name,
const QString &message, const QString &sendid);
bool evaluate(const <API key>::ParameterInfo ¶m,
QScxmlStateMachine *stateMachine, QVariantMap &keyValues);
bool evaluate(
const <API key>::Array<<API key>::ParameterInfo> *params,
QScxmlStateMachine *stateMachine, QVariantMap &keyValues);
void submitError(const QString &type, const QString &msg, const QString &sendid = QString());
};
#endif // BUILD_QSCXMLC
class QScxmlEventPrivate
{
public:
QScxmlEventPrivate()
: eventType(QScxmlEvent::ExternalEvent)
, delayInMiliSecs(0)
{}
QString name;
QScxmlEvent::EventType eventType;
QVariant data; // extra data
QString sendid; // if set, or id of <send> if failure
QString origin; // uri to answer by setting the target of send, empty for internal and platform events
QString originType; // type to answer by setting the type of send, empty for internal and platform events
QString invokeId; // id of the invocation that triggered the child process if this was invoked
int delayInMiliSecs;
static QByteArray debugString(QScxmlEvent *event);
};
QT_END_NAMESPACE
#endif // QSCXMLEVENT_P_H |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Logging
{
<summary>
Attribute used to disable logging a given item
</summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, AllowMultiple = false, Inherited = true)]
public class <API key> : Attribute
{
}
} |
/** @file
* A simple TGA image dumper.
*/
#include <cstdio>
#include <memory>
#include "src/common/error.h"
#include "src/common/ustring.h"
#include "src/common/writefile.h"
#include "src/images/decoder.h"
namespace Images {
static void writePixel(Common::WriteStream &file, const byte *&data, PixelFormat format) {
if (format == kPixelFormatR8G8B8) {
file.writeByte(data[2]);
file.writeByte(data[1]);
file.writeByte(data[0]);
file.writeByte(0xFF);
data += 3;
} else if (format == kPixelFormatB8G8R8) {
file.writeByte(data[0]);
file.writeByte(data[1]);
file.writeByte(data[2]);
file.writeByte(0xFF);
data += 3;
} else if (format == <API key>) {
file.writeByte(data[2]);
file.writeByte(data[1]);
file.writeByte(data[0]);
file.writeByte(data[3]);
data += 4;
} else if (format == <API key>) {
file.writeByte(data[0]);
file.writeByte(data[1]);
file.writeByte(data[2]);
file.writeByte(data[3]);
data += 4;
} else if (format == kPixelFormatR5G6B5) {
uint16_t color = READ_LE_UINT16(data);
file.writeByte( color & 0x001F);
file.writeByte((color & 0x07E0) >> 5);
file.writeByte((color & 0xF800) >> 11);
file.writeByte(0xFF);
data += 2;
} else if (format == <API key>) {
uint16_t color = READ_LE_UINT16(data);
file.writeByte( color & 0x001F);
file.writeByte((color & 0x03E0) >> 5);
file.writeByte((color & 0x7C00) >> 10);
file.writeByte((color & 0x8000) ? 0xFF : 0x00);
data += 2;
} else if (format == kPixelFormatDepth16) {
uint16_t color = READ_LE_UINT16(data);
file.writeByte(color / 128);
file.writeByte(color / 128);
file.writeByte(color / 128);
file.writeByte((color >= 0x7FFF) ? 0x00 : 0xFF);
data += 2;
} else
throw Common::Exception("Unsupported pixel format: %d", (int) format);
}
static Common::WriteStream *openTGA(const Common::UString &fileName, int width, int height) {
std::unique_ptr<Common::WriteFile> file = std::make_unique<Common::WriteFile>(fileName);
file->writeByte(0); // ID Length
file->writeByte(0); // Palette size
file->writeByte(2); // Unmapped RGB
file->writeUint32LE(0); // Color map
file->writeByte(0); // Color map
file->writeUint16LE(0);
file->writeUint16LE(0);
file->writeUint16LE(width);
file->writeUint16LE(height);
file->writeByte(32); // Pixel depths
file->writeByte(0);
return file.release();
}
static void writeMipMap(Common::WriteStream &stream, const Decoder::MipMap &mipMap, PixelFormat format) {
const byte *data = mipMap.data.get();
uint32_t count = mipMap.width * mipMap.height;
while (count
writePixel(stream, data, format);
}
void dumpTGA(const Common::UString &fileName, const Decoder &image) {
if ((image.getLayerCount() < 1) || (image.getMipMapCount() < 1))
throw Common::Exception("No image");
int32_t width = image.getMipMap(0, 0).width;
int32_t height = 0;
for (size_t i = 0; i < image.getLayerCount(); i++) {
const Decoder::MipMap &mipMap = image.getMipMap(0, i);
if (mipMap.width != width)
throw Common::Exception("dumpTGA(): Unsupported image with variable layer width");
height += mipMap.height;
}
std::unique_ptr<Common::WriteStream> file(openTGA(fileName, width, height));
for (size_t i = 0; i < image.getLayerCount(); i++)
writeMipMap(*file, image.getMipMap(0, i), image.getFormat());
file->flush();
}
} // End of namespace Images |
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_51) on Fri Jul 19 02:58:57 EDT 2013 -->
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
Uses of Class org.apache.solr.cloud.Assign (Solr 4.4.0 API)
</TITLE>
<META NAME="date" CONTENT="2013-07-19">
<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 Class org.apache.solr.cloud.Assign (Solr 4.4.0 API)";
}
}
</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"> <A HREF="../../../../../org/apache/solr/cloud/Assign.html" title="class in org.apache.solr.cloud"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </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="../../../../../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?org/apache/solr/cloud//class-useAssign.html" target="_top"><B>FRAMES</B></A>
<A HREF="Assign.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 Class<br>org.apache.solr.cloud.Assign</B></H2>
</CENTER>
No usage of org.apache.solr.cloud.Assign
<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"> <A HREF="../../../../../org/apache/solr/cloud/Assign.html" title="class in org.apache.solr.cloud"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </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="../../../../../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?org/apache/solr/cloud//class-useAssign.html" target="_top"><B>FRAMES</B></A>
<A HREF="Assign.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>
<i>Copyright © 2000-2013 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</BODY>
</HTML> |
module.exports = function (app) {
app.get('/api/accounts', function (req, res) {
var results = [];
req.ledger.accounts().on('data', function(account) {
results.push(account);
})
.once('end', function () {
res.json(results);
});
});
}; |
package com.ocarballo.ocmanager.repository;
import java.util.List;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.<API key>;
import com.ocarballo.ocmanager.domain.Recipe;
import com.ocarballo.ocmanager.domain.Product;
import com.ocarballo.ocmanager.repository.RecipeDao;
import com.ocarballo.ocmanager.repository.ProductDao;
public class JPARecipeDaoTests {
private ApplicationContext context;
private RecipeDao recipeDao;
private ProductDao productDao;
@Before
public void setUp() {
context = new <API key>("classpath:test-context.xml");
recipeDao = (RecipeDao) context.getBean("recipeDao");
productDao = (ProductDao) context.getBean("productDao");
}
@Test
public void testGetRecipesList() {
List<Recipe> recipes = recipeDao.getRecipesList();
assertNotNull(recipes);
// Test provisional:
// assertEquals(recipes.size(), 0, 0);
}
@Test
public void testGetFirstAndLast() {
List<Recipe> recipes = recipeDao.getRecipesList();
Recipe firstRecipe = recipeDao.getRecipesList().get(0);
assertEquals(recipes.get(0).getDescription(), firstRecipe.getDescription());
assertEquals(recipes.get(0).getWorkTime(), firstRecipe.getWorkTime(), 0);
Recipe lastRecipe = recipeDao.getRecipesList().get(recipeDao.getRecipesList().size()-1);
assertEquals(recipes.get(recipes.size()-1).getDescription(), lastRecipe.getDescription());
assertEquals(recipes.get(recipes.size()-1).getWorkTime(), lastRecipe.getWorkTime(), 0);
}
@Test
public void <API key>() {
List<Recipe> recipes;
Product product = productDao.getProductsList().get(0);
recipes = recipeDao.<API key>(product);
System.out.println("Testing <API key>...");
for (Recipe r : recipes) {
System.out.println("Descripción: " + r.getDescription() + "; tiempo de trabajo: " + r.getWorkTime()+ ";");
}
}
/*
* Assumes two Materials on materialsList at least.
*/
// @Test
// public void testSaveRecipe() {
// // Set two RecipeElements:
// List<Material> materials = materialDao.getMaterialsList();
// Material m0 = materials.get(0);
// Material m1 = materials.get(1);
// Double quantity0 = 12.50;
// Double quantity1 = 20.50;
// assertNotNull(m0);
// assertNotNull(m1);
// RecipeElement testRecipeElement0 = new RecipeElement();
// RecipeElement testRecipeElement1 = new RecipeElement();
// testRecipeElement0.setMaterial(m0);
// testRecipeElement0.setQuantity(quantity0);
// testRecipeElement1.setMaterial(m1);
// testRecipeElement1.setQuantity(quantity1);
// // Set one Recipe:
// List<RecipeElement> elements = new ArrayList<RecipeElement>();
// Recipe recipe = new Recipe();
// elements.add(testRecipeElement0);
// elements.add(testRecipeElement1);
// recipe.setElements(elements);
// recipe.setDescription("Receta de tarta de manzana");
// recipe.setWorkTime(45);
// recipeDao.saveRecipe(recipe);
} |
# <API key>.sh
# We need to verify before entering this stage of CURRENT_STATUS="postinstall:ended"
# and <API key>=""
if [ "$<API key>" = "N" ]; then
Error "As the variable <API key> is set to \"N\" we cannot proceed stage $stage"
fi
# clear <API key> to be sure
<API key>=
if [ "$CURRENT_STATUS" = "postinstall:ended" ]; then
# nice we will now update our stage to "postinstall:start"
CURRENT_STATUS="$stage:start"
SetCurrentStatus "$STATUS_FILE" # write it to our STATUS_FILE
elif [ "$CURRENT_STATUS" = "postremove:start" ]; then
# ok we restarted the upgrade-ux
Log "Seems we restarted $PRODUCT and are still in status $CURRENT_STATUS"
else
Error "$CURRENT_STATUS is not in the correct state to start with stage $stage"
fi |
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="pt">
<head>
<!-- Generated by javadoc (1.8.0_65) on Fri Aug 26 13:56:37 GMT-03:00 2016 -->
<title>GuestDao</title>
<meta name="date" content="2016-08-26">
<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="GuestDao";
}
}
catch(err) {
}
var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance 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/GuestDao.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>Prev Class</li>
<li><a href="../../../../br/com/vmbackup/dao/HypervisorDao.html" title="class in br.com.vmbackup.dao"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?br/com/vmbackup/dao/GuestDao.html" target="_top">Frames</a></li>
<li><a href="GuestDao.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">br.com.vmbackup.dao</div>
<h2 title="Class GuestDao" class="title">Class GuestDao</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>br.com.vmbackup.dao.GuestDao</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">GuestDao</span>
extends java.lang.Object</pre>
</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="../../../../br/com/vmbackup/dao/GuestDao.html#GuestDao--">GuestDao</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="t2" class="tableTab"><span><a href="javascript:show(2);">Instance 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>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../br/com/vmbackup/dao/GuestDao.html#adicionarGuest-br.com.vmbackup.modelo.Guest-">adicionarGuest</a></span>(<a href="../../../../br/com/vmbackup/modelo/Guest.html" title="class in br.com.vmbackup.modelo">Guest</a> guest)</code> </td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code><a href="../../../../br/com/vmbackup/modelo/Guest.html" title="class in br.com.vmbackup.modelo">Guest</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../br/com/vmbackup/dao/GuestDao.html#<API key>.lang.String-">buscarPorHostname</a></span>(java.lang.String hostname)</code> </td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code><a href="../../../../br/com/vmbackup/modelo/Guest.html" title="class in br.com.vmbackup.modelo">Guest</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../br/com/vmbackup/dao/GuestDao.html#buscarPorId-int-">buscarPorId</a></span>(int id)</code> </td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../br/com/vmbackup/dao/GuestDao.html#excluir-br.com.vmbackup.modelo.Guest-">excluir</a></span>(<a href="../../../../br/com/vmbackup/modelo/Guest.html" title="class in br.com.vmbackup.modelo">Guest</a> guest)</code> </td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>java.util.List<<a href="../../../../br/com/vmbackup/modelo/Guest.html" title="class in br.com.vmbackup.modelo">Guest</a>></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../br/com/vmbackup/dao/GuestDao.html#getLista--">getLista</a></span>()</code> </td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../br/com/vmbackup/dao/GuestDao.html#upgrade-br.com.vmbackup.modelo.Guest-">upgrade</a></span>(<a href="../../../../br/com/vmbackup/modelo/Guest.html" title="class in br.com.vmbackup.modelo">Guest</a> guest)</code> </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="GuestDao
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>GuestDao</h4>
<pre>public GuestDao()</pre>
</li>
</ul>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method.detail">
</a>
<h3>Method Detail</h3>
<a name="adicionarGuest-br.com.vmbackup.modelo.Guest-">
</a>
<ul class="blockList">
<li class="blockList">
<h4>adicionarGuest</h4>
<pre>public void adicionarGuest(<a href="../../../../br/com/vmbackup/modelo/Guest.html" title="class in br.com.vmbackup.modelo">Guest</a> guest)</pre>
</li>
</ul>
<a name="getLista
</a>
<ul class="blockList">
<li class="blockList">
<h4>getLista</h4>
<pre>public java.util.List<<a href="../../../../br/com/vmbackup/modelo/Guest.html" title="class in br.com.vmbackup.modelo">Guest</a>> getLista()</pre>
</li>
</ul>
<a name="buscarPorId-int-">
</a>
<ul class="blockList">
<li class="blockList">
<h4>buscarPorId</h4>
<pre>public <a href="../../../../br/com/vmbackup/modelo/Guest.html" title="class in br.com.vmbackup.modelo">Guest</a> buscarPorId(int id)</pre>
</li>
</ul>
<a name="<API key>.lang.String-">
</a>
<ul class="blockList">
<li class="blockList">
<h4>buscarPorHostname</h4>
<pre>public <a href="../../../../br/com/vmbackup/modelo/Guest.html" title="class in br.com.vmbackup.modelo">Guest</a> buscarPorHostname(java.lang.String hostname)</pre>
</li>
</ul>
<a name="upgrade-br.com.vmbackup.modelo.Guest-">
</a>
<ul class="blockList">
<li class="blockList">
<h4>upgrade</h4>
<pre>public void upgrade(<a href="../../../../br/com/vmbackup/modelo/Guest.html" title="class in br.com.vmbackup.modelo">Guest</a> guest)</pre>
</li>
</ul>
<a name="excluir-br.com.vmbackup.modelo.Guest-">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>excluir</h4>
<pre>public void excluir(<a href="../../../../br/com/vmbackup/modelo/Guest.html" title="class in br.com.vmbackup.modelo">Guest</a> guest)</pre>
</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/GuestDao.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>Prev Class</li>
<li><a href="../../../../br/com/vmbackup/dao/HypervisorDao.html" title="class in br.com.vmbackup.dao"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?br/com/vmbackup/dao/GuestDao.html" target="_top">Frames</a></li>
<li><a href="GuestDao.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> |
#!/usr/bin/env python
import fileinput
import sys
import re
t0first=len(sys.argv) < 2 or sys.argv[1] != "1"
t0firstLayers=sys.argv[2:]
if len(t0firstLayers) == 0:
t0firstLayers=map(str,range(0,1000))
# t0firstLayers=["0"]
numeric="([-+]?(?:(?: \d* \. \d+ )|(?: \d+ \.? )))"
rX=re.compile("X"+numeric,re.VERBOSE)
rY=re.compile("Y"+numeric,re.VERBOSE)
rZ=re.compile("Z"+numeric,re.VERBOSE)
rF=re.compile("F"+numeric,re.VERBOSE)
rT=re.compile("T"+numeric,re.VERBOSE)
rD=re.compile("D"+numeric,re.VERBOSE)
rE=re.compile("E"+numeric,re.VERBOSE)
rL=re.compile(";LAYER:"+numeric,re.VERBOSE)
L=-1
T=0
X=0
Y=0
T0=[]
T1=[]
lX=[]
lY=[]
lZ=[]
lastT=-1
L=-1
B=0
Heater="M103"
finish=False
replenishD="G1 B1 F150 D0.30\n"
replenishE="G1 B1 F150 E0.30\n"
buffer=[]
prologue=[]
start=0
for line in fileinput.input("-"):
if finish:
prologue.append(line)
continue
lT=rT.findall(line)
if len(lT) > 0:
T=int(lT[0])
lZ=rZ.findall(line)
lX=rX.findall(line)
lY=rY.findall(line)
if len(lX) > 0:
X=float(lX[0])
if len(lY) > 0:
Y=float(lY[0])
reorder=L >= 0
if reorder and (re.match(Heater,line) or re.match("M140",line)):
line=""
if re.match("; Post print gcode",line):
finish=True
reorder=False
if reorder and not (re.match(";LAYER:",line) or len(lZ) > 0):
# if reorder and not (re.match(";LAYER:",line)): # For Automaker 4.0.0
if T == 0:
lD=rD.findall(line)
if T != lastT:
T0.append("G0 B0\n")
T0.append("T0 F12000 X"+str(X)+" Y"+str(Y)+"\n")
B=0
lastT=T
if B == 0:
if len(lD) > 0:
B=1
T0.append(replenishD)
T0.append(line)
elif T == 1:
if T != lastT:
T1.append("G0 B0\n")
T1.append("T1 F12000 X"+str(X)+" Y"+str(Y)+"\n")
B=0
lastT=T
if B == 0:
lE=rE.findall(line)
if len(lE) > 0:
B=1
T1.append(replenishE)
T1.append(line)
else:
buffer.append(line)
else:
if len(T0) > 0 and t0first:
for l in T0:
buffer.append(l)
T0=[]
if len(T1) > 0:
for l in T1:
buffer.append(l)
T1=[]
if len(T0) > 0 and not t0first:
for l in T0:
buffer.append(l)
T0=[]
lL=rL.findall(line)
if len(lL) > 0:
L=int(lL[0])
if L == 0 and start == 0:
start=len(buffer)
if L == 1:
Heater="M104"
if reorder:
buffer.append("G0 B0\n")
B=0
if L >= 0 and B == 0:
lD=rD.findall(line)
if len(lD) > 0:
T=0
B=1
buffer.append("T0\n"+replenishD)
lE=rE.findall(line)
if len(lE) > 0:
T=1
B=1
buffer.append("T1\n"+replenishE)
buffer.append(line)
lastT=-1
Heater="M103"
count=start
count0=0
count1=0
#pretime=100
pretime=60
posttime=100
primetime=pretime+posttime;
lastT=-1
T=lastT
time=0
X0=0
Y0=0
F=0
index=[0]*start
from math import sqrt
from bisect import bisect_left
while count < len(buffer):
lF=rF.findall(line)
lX=rX.findall(line)
lY=rY.findall(line)
if len(lF) > 0:
F=float(lF[0])/60
if len(lX) > 0:
X=float(lX[0])
if len(lY) > 0:
Y=float(lY[0])
dist=sqrt((X-X0)**2+(Y-Y0)**2)
time += dist/F
index.append(time)
X0=X
Y0=Y
line=buffer[count]
lL=rL.findall(line)
if len(lL) > 0:
L=int(lL[0])
if L == 1:
Heater="M104"
buffer.insert(count,"M140\n")
index.insert(count,index[count])
count += 1
lT=rT.findall(line)
if len(lT) > 0:
T=int(lT[0])
if T == 0:
if T != lastT:
lastT=T
if time-index[count1] > posttime:
buffer.insert(count1,Heater+" S0\n")
index.insert(count1,index[count1])
count += 1
i=max(count1+1,bisect_left(index,time-pretime))
if i > start and i < len(index):
buffer.insert(i,Heater+" S\n")
index.insert(i,index[i])
count += 1
count0=count
elif T == 1:
if T != lastT:
lastT=T
if time-index[count0] > posttime:
buffer.insert(count0,Heater+" T0\n")
index.insert(count0,index[count0])
count += 1
i=max(count0+1,bisect_left(index,time-pretime))
if i > start and i < len(index):
buffer.insert(i,Heater+" T\n")
index.insert(i,index[i])
count += 1
count1=count
count += 1
if T == 1 and time-index[count1] > pretime:
buffer.insert(count1,Heater+" S0\n")
index.insert(count1,index[count1])
if T == 0 and time-index[count0] > pretime:
buffer.insert(count0,Heater+" T0\n")
index.insert(count0,index[count0])
for line in buffer:
sys.stdout.write(line)
for line in prologue:
sys.stdout.write(line)
sys.stdout.flush() |
# LUWRAIN Extensions
LUWRAIN is a platform for the creation of apps for the blind and partially-sighted.
It provides a Java API for constructing <API key> apps
with the user interface adjusted to the perception of blind people.
Please visit [luwrain.org](http://luwrain.org/?lang=en) for further information. |
#include "llib_types.h"
#include "llib_err.h"
#include "llib_mem.h"
#include "llib_env.h"
#include "llib_str.h"
#include "llib_file.h"
#include "llib_list.h"
#include "llib_print.h"
#include "llib_snb.h"
#include "llib_i18n.h"
#include "llib_utf8.h"
#include "llib_global.h"
#include "llib_charmap.h"
LLIB_EXPORT
char* llib_gettext(char* s)
{
if (!s)
return NULL;
if (llib_global_po)
{
char* r;
if (<API key>(llib_global_po, s, &r))
s = r;
}
if (s[0] == '|')
{
char* set = llib_str_rchr(s, '|');
if (set)
++set;
else
set = s;
return set;
}
else
return s;
}
/* Parse a field: string must be terminated with whitespace */
static int <API key>(unsigned char** pp, unsigned char* kw)
{
unsigned char* p = *pp;
while(*kw && *kw==*p)
++kw, ++p;
if(!*kw && (!*p || *p==' ' || *p=='\t' || *p=='#' || *p=='\n' || *p=='\r'))
{
*pp = p;
return 0;
}
else
return -1;
}
/* Helpful little parsing utilities */
/* Skip whitespace and return first non-whitespace character */
static int <API key>(unsigned char** pp,int cmt)
{
unsigned char* p = *pp;
while (*p==' ' || *p=='\t')
++p;
if (*p=='\r' || *p=='\n' || *p==cmt)
*p = 0;
*pp = p;
return *p;
}
/** load a PO file from a file descriptor.
*
* The global variable llib_global_po is cleared and then filled
* if no failure occurs.
*
* @param[in] f (int) file descriptor to load.
* @return (lbool) boolean result of operation.
* @exception ENOMEM out of memory.
* @exception EBADF bad file descriptor.
* @todo better checks
*/
LLIB_EXPORT
lbool <API key>(int f)
{
unsigned char buf[1024] = { 0 };
unsigned char msgid[1024] = { 0 };
unsigned char msgstr[1024] = { 0 };
unsigned char* bf;
lbool res = TRUE;
lbool map_loaded = FALSE;
llib_charmap_t* po_map = llib_global_locale.map;
lbool preload_flag = FALSE;
lbool bye = FALSE;
LLIB_ERR_BADF(f);
bf = llib_mem_malloc(8192);
LLIB_ERR_NOMEM(bf);
<API key>(&llib_global_po);
if (!<API key>(&llib_global_po))
return FALSE;
while (!!bye && (preload_flag ||
llib_file_gets((char*)buf, 8191, f)))
{
unsigned char* p;
preload_flag = 0;
p = buf;
<API key>(&p, '
if (!<API key>(&p, (unsigned char*)"msgid"))
{
int ofst = 0;
int len;
msgid[0] = 0;
<API key>(&p, '
while ((len = <API key>((char**)&p, (char*)(msgid+ofst),
sizeof(msgid)-ofst, FALSE) >= 0))
{
preload_flag = 0;
ofst += len;
<API key>(&p, '
if (!*p)
{
if (llib_file_gets((char*)buf,sizeof(buf)-1, f))
{
p = buf;
preload_flag = 1;
<API key>(&p, '
}
else
{
bye = TRUE;
break;
}
}
}
}
else if (!<API key>(&p, (unsigned char*)"msgstr"))
{
int ofst = 0;
int len;
msgstr[0] = 0;
<API key>(&p, '
while ((len = <API key>((char**)&p, (char*)(msgstr+ofst),
sizeof(msgstr)-ofst, FALSE) >= 0))
{
preload_flag = 0;
ofst += len;
<API key>(&p, '
if (!*p)
{
if (llib_file_gets((char*)buf, sizeof(buf)-1, f))
{
p = buf;
preload_flag = 1;
<API key>(&p, '
}
else
break;
}
}
if (msgid[0] && msgstr[0])
{
/* Convert to locale character map */
llib_charmap_iconv((char*)bf, 8191, llib_global_locale.map,
(char*)msgstr, po_map);
/* Add to hash table */
if (!<API key>(llib_global_po, (char*)msgid,
(char*)bf, NULL))
res = FALSE;
}
else if (!msgid[0] && msgstr[0])
{
unsigned char* p;
p = (unsigned char*)llib_str_str((char*)msgstr, "charset=");
if (p)
{
/* Copy character set name up to next delimiter */
int x;
p += sizeof("charset=") - 1;
while (*p == ' ' || *p == '\t')
++p;
for (x = 0; p[x] && p[x] !='\n' && p[x] != '\r' && p[x] != ' ' &&
p[x] != '\t' && p[x] != ';' && p[x] != ','; ++x)
msgid[x] = p[x];
msgid[x] = 0;
po_map = llib_charmap_find((char*)msgid);
if (!po_map)
po_map = llib_global_locale.map;
else
map_loaded = TRUE;
}
}
}
}
if (map_loaded)
llib_charmap_free(&po_map);
llib_mem_free(bf);
llib_file_close(&f);
return res;
}
/** initialize gettext, loading a po file path name.
*
* @param[in] base (char*) base directory for PO files.
* @param[in] lang (char*) language (will load file lang.po) or NULL to use environment.
* @return (lbool) boolean result of operation (FALSE on error or if language or PO file was not found).
* @note this function updates llib_global_po variable.
* @exception EINVAL bad input parameter.
* @exception ENOTDIR base in not a directory.
* @exception ENOMEM out of memory.
*/
LLIB_EXPORT
lbool <API key>(const char* base, const char* lang)
{
int f;
char* l = NULL;
char* path;
lbool r = FALSE;
LLIB_ERR_INVAL0(base);
if (!llib_file_is_dir(base))
{
llib_err_set(ENOTDIR);
return FALSE;
}
if (!lang)
{
l = llib_env_get("LC_MESSAGES");
if (!l || !*l)
{
llib_mem_free(l);
l = llib_env_get("LANG");
}
}
else
{
l = llib_str_dup(lang);
LLIB_ERR_NOMEM(l);
}
if (!l)
return FALSE;
path = llib_str_concat("%s/%s.po", base, l);
llib_mem_free(l);
LLIB_ERR_NOMEM(path);
f = llib_file_open(path, O_RDONLY);
llib_mem_free(path);
if (f >= 0)
{
r = <API key>(f);
llib_file_close(&f);
}
return r;
} |
using System.Globalization;
using System.Windows.Controls;
namespace NETworkManager.Validators
{
public class PortValidator : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (!int.TryParse(value as string, out var portNumber))
return new ValidationResult(false, Localization.Resources.Strings.EnterValidPort);
if (portNumber > 0 && (portNumber < 65536))
return ValidationResult.ValidResult;
return new ValidationResult(false, Localization.Resources.Strings.EnterValidPort);
}
}
} |
<!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"/>
<title>GNU Radio 3.6.1 C++ API: gr_pll_freqdet_cf.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">GNU Radio 3.6.1 C++ API
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.7.6.1 -->
</div>
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
initNavTree('<API key>.html','');
</script>
<div id="doc-content">
<div class="header">
<div class="summary">
<a href="#nested-classes">Classes</a> |
<a href="#func-members">Functions</a> </div>
<div class="headertitle">
<div class="title">gr_pll_freqdet_cf.h File Reference</div> </div>
</div><!--header
<div class="contents">
<div class="textblock"><code>#include <<a class="el" href="<API key>.html">gr_core_api.h</a>></code><br/>
<code>#include <<a class="el" href="<API key>.html">gr_sync_block.h</a>></code><br/>
<code>#include <<a class="el" href="<API key>.html">gri_control_loop.h</a>></code><br/>
</div>
<p><a href="<API key>.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="nested-classes"></a>
Classes</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html">gr_pll_freqdet_cf</a></td></tr>
<tr><td class="mdescLeft"> </td><td class="mdescRight">Implements a PLL which locks to the input frequency and outputs an estimate of that frequency. Useful for FM Demod.input: stream of complex; output: stream of floats. <a href="<API key>.html#details">More...</a><br/></td></tr>
<tr><td colspan="2"><h2><a name="func-members"></a>
Functions</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="el" href="gr__core__api_8h.html#<API key>">GR_CORE_API</a> <a class="el" href="<API key>.html"><API key></a> </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>"><API key></a> (float loop_bw, float max_freq, float min_freq)</td></tr>
</table>
<hr/><h2>Function Documentation</h2>
<a class="anchor" id="<API key>"></a><!-- doxytag: member="gr_pll_freqdet_cf.h::<API key>" ref="<API key>" args="(float loop_bw, float max_freq, float min_freq)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="gr__core__api_8h.html#<API key>">GR_CORE_API</a> <a class="el" href="<API key>.html"><API key></a> <a class="el" href="<API key>.html#<API key>"><API key></a> </td>
<td>(</td>
<td class="paramtype">float </td>
<td class="paramname"><em>loop_bw</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">float </td>
<td class="paramname"><em>max_freq</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">float </td>
<td class="paramname"><em>min_freq</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div>
<div class="memdoc">
</div>
</div>
</div><!-- contents -->
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="<API key>.html">gr_pll_freqdet_cf.h</a> </li>
<li class="footer">Generated on Wed Jun 13 2012 21:29:00 for GNU Radio 3.6.1 C++ API by
<a href="http:
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.6.1 </li>
</ul>
</div>
</body>
</html> |
// client/command/remote/get.go
// This file is part of sss.
// sss is free software: you can redistribute it and/or modify
// (at your option) any later version.
// sss is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
package remote
import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
pb "gopkg.in/cheggaaa/pb.v1"
"google.golang.org/grpc"
"golang.org/x/sync/errgroup"
"github.com/itslab-kyushu/sss/cfg"
"github.com/itslab-kyushu/sss/kvs"
"github.com/itslab-kyushu/sss/sss"
"github.com/urfave/cli"
)
type getOpt struct {
Config *cfg.Config
Name string
OutputFile string
NConnection int
Log io.Writer
}
// CmdGet prepares get command and run cmdGet.
func CmdGet(c *cli.Context) (err error) {
if c.NArg() != 1 {
return cli.ShowSubcommandHelp(c)
}
conf, err := cfg.ReadConfig(c.String("config"))
if err != nil {
return
}
output := c.String("output")
if output == "" {
output = c.Args().First()
}
var log io.Writer
if c.GlobalBool("quiet") {
log = ioutil.Discard
} else {
log = os.Stderr
}
return cmdGet(&getOpt{
Config: conf,
Name: c.Args().First(),
OutputFile: output,
NConnection: c.Int("max-connection"),
Log: log,
})
}
func cmdGet(opt *getOpt) (err error) {
if opt.Config.NServers() == 0 {
return fmt.Errorf("No server information is given.")
}
fmt.Fprintln(opt.Log, "Downloading shares")
bar := pb.New(opt.Config.NServers())
bar.Output = opt.Log
bar.Prefix("Server")
bar.Start()
shares := make([]sss.Share, opt.Config.NServers())
wg, ctx := errgroup.WithContext(context.Background())
semaphore := make(chan struct{}, opt.NConnection)
var i int
for _, server := range opt.Config.Servers {
// Check the current context.
select {
case <-ctx.Done():
return ctx.Err()
default:
}
func(server cfg.Server, i int) {
semaphore <- struct{}{}
wg.Go(func() (err error) {
defer func() { <-semaphore }()
defer bar.Increment()
conn, err := grpc.Dial(
fmt.Sprintf("%s:%d", server.Address, server.Port),
grpc.WithInsecure(),
grpc.WithCompressor(grpc.NewGZIPCompressor()),
grpc.WithDecompressor(grpc.NewGZIPDecompressor()),
)
if err != nil {
return
}
defer conn.Close()
client := kvs.NewKvsClient(conn)
value, err := client.Get(ctx, &kvs.Key{
Name: opt.Name,
})
if err != nil {
return
}
share, err := FromValue(value)
if err != nil {
return
}
shares[i] = *share
return
})
}(server, i)
i++
}
err = wg.Wait()
bar.Finish()
if err != nil {
return
}
fmt.Fprintln(opt.Log, "Reconstructing the secret")
secret, err := sss.Reconstruct(shares)
if err != nil {
return err
}
return ioutil.WriteFile(opt.OutputFile, secret, 0644)
} |
package org.graylog2.messagehandlers.gelf;
/**
* <API key>.java: Sep 30, 2010 1:01:37 PM
* <p/>
* [description]
*
* @author Lennart Koopmann <lennart@socketfeed.com>
*/
class <API key> extends GELFException {
} |
package soot.jimple.parser.node;
import soot.jimple.parser.analysis.*;
@SuppressWarnings("nls")
public final class ALocalVariable extends PVariable
{
private PLocalName _localName_;
public ALocalVariable()
{
// Constructor
}
public ALocalVariable(
@SuppressWarnings("hiding") PLocalName _localName_)
{
// Constructor
setLocalName(_localName_);
}
@Override
public Object clone()
{
return new ALocalVariable(
cloneNode(this._localName_));
}
public void apply(Switch sw)
{
((Analysis) sw).caseALocalVariable(this);
}
public PLocalName getLocalName()
{
return this._localName_;
}
public void setLocalName(PLocalName node)
{
if(this._localName_ != null)
{
this._localName_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._localName_ = node;
}
@Override
public String toString()
{
return ""
+ toString(this._localName_);
}
@Override
void removeChild(@SuppressWarnings("unused") Node child)
{
// Remove child
if(this._localName_ == child)
{
this._localName_ = null;
return;
}
throw new RuntimeException("Not a child.");
}
@Override
void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild)
{
// Replace child
if(this._localName_ == oldChild)
{
setLocalName((PLocalName) newChild);
return;
}
throw new RuntimeException("Not a child.");
}
} |
<?php
namespace Claroline\ChatBundle\Form;
use Claroline\CoreBundle\Library\Configuration\<API key>;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\<API key>;
use Symfony\Component\OptionsResolver\<API key>;
class <API key> extends AbstractType
{
private $configHandler;
public function __construct(<API key> $configHandler)
{
$this->configHandler = $configHandler;
}
public function buildForm(<API key> $builder, array $options)
{
$xmppHost = $this->configHandler->getParameter('chat_xmpp_host');
$xmppMucHost = $this->configHandler->getParameter('chat_xmpp_muc_host');
$configPort = $this->configHandler->getParameter('chat_bosh_port');
$boshPort = empty($configPort) ? 5280 : $configPort;
$builder->add(
'host',
'text',
array(
'required' => false,
'data' => $xmppHost,
'mapped' => false,
'label' => 'host'
)
);
$builder->add(
'mucHost',
'text',
array(
'required' => false,
'data' => $xmppMucHost,
'mapped' => false,
'label' => 'muc_host'
)
);
$builder->add(
'port',
'integer',
array(
'required' => false,
'data' => $boshPort,
'mapped' => false,
'label' => 'bosh_server_port'
)
);
}
public function getName()
{
return '<API key>';
}
public function setDefaultOptions(<API key> $resolver)
{
$resolver->setDefaults(array('translation_domain' => 'chat'));
}
} |
package game;
final class C_100059_df extends C_100325_id
{
static String field_101594_F;
int field_101602_O;
static int field_101592_D;
static String field_101616_z;
static C_100026_hb field_101599_L;
static byte[] field_101603_H;
int field_101607_Q;
int field_101605_J;
static String field_101612_v;
static String[] field_101593_E;
static String[] field_101597_B;
boolean field_101617_y;
static String[] field_101601_N;
int field_101595_G;
int field_101608_P;
int field_101598_C;
static boolean field_101613_u;
static String field_101606_K;
static int field_101611_w;
static C_100127_tl field_101614_t;
int field_101610_R;
static C_100037_wb[] field_101604_I;
static int[] field_101600_M;
int field_101618_x;
static C_100037_wb field_101615_s;
C_100294_ki field_101596_A;
private static final String[] field_101609_S;
final void func_101591_j(int arg0)
{
// @00: aload_0
// @01: aconst_null
// @02: putfield game.C_100294_ki game.C_100059_df.field_101596_A
// @05: iload_1
// @06: bipush 8 (0x08)
// @08: if_icmpgt @11
// @0B: aload_0
// @0C: bipush 114 (0x72)
// @0E: putfield int game.C_100059_df.field_101618_x
// @11: goto @35
// @14: astore_2
// @15: aload_2
// @16: new java.lang.StringBuilder
// @19: dup
// @1A: invokespecial java.lang.StringBuilder.<init>()void
// @1D: getstatic java.lang.String[] game.C_100059_df.field_101609_S
// @20: iconst_4
// @21: aaload
// @22: invokevirtual java.lang.StringBuilder.append(java.lang.String)java.lang.StringBuilder
// @25: iload_1
// @26: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @29: bipush 41 (0x29)
// @2B: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @2E: invokevirtual java.lang.StringBuilder.toString()java.lang.String
// @31: invokestatic game.C_100181_cf.func_105695_a(java.lang.Throwable, java.lang.String)game.C_100170_cm
// @34: athrow
// @35: return
}
public static void func_101590_k(int arg0)
{
// @00: aconst_null
// @01: putstatic java.lang.String game.C_100059_df.field_101616_z
// @04: aconst_null
// @05: putstatic game.C_100037_wb game.C_100059_df.field_101615_s
// @08: aconst_null
// @09: putstatic game.C_100127_tl game.C_100059_df.field_101614_t
// @0C: aconst_null
// @0D: putstatic game.C_100026_hb game.C_100059_df.field_101599_L
// @10: aconst_null
// @11: putstatic java.lang.String game.C_100059_df.field_101612_v
// @14: aconst_null
// @15: putstatic java.lang.String game.C_100059_df.field_101606_K
// @18: aconst_null
// @19: putstatic java.lang.String game.C_100059_df.field_101594_F
// @1C: aconst_null
// @1D: putstatic byte[] game.C_100059_df.field_101603_H
// @20: aconst_null
// @21: putstatic game.C_100037_wb[] game.C_100059_df.field_101604_I
// @24: iload_0
// @25: sipush 128 (0x0080)
// @28: if_icmpeq @36
// @2B: aconst_null
// @2C: checkcast java.lang.String
// @2F: putstatic java.lang.String game.C_100059_df.field_101594_F
// @32: goto @36
// @35: athrow
// @36: aconst_null
// @37: putstatic int[] game.C_100059_df.field_101600_M
// @3A: aconst_null
// @3B: putstatic java.lang.String[] game.C_100059_df.field_101593_E
// @3E: aconst_null
// @3F: putstatic java.lang.String[] game.C_100059_df.field_101597_B
// @42: aconst_null
// @43: putstatic java.lang.String[] game.C_100059_df.field_101601_N
// @46: goto @6A
// @49: astore_1
// @4A: aload_1
// @4B: new java.lang.StringBuilder
// @4E: dup
// @4F: invokespecial java.lang.StringBuilder.<init>()void
// @52: getstatic java.lang.String[] game.C_100059_df.field_101609_S
// @55: iconst_2
// @56: aaload
// @57: invokevirtual java.lang.StringBuilder.append(java.lang.String)java.lang.StringBuilder
// @5A: iload_0
// @5B: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @5E: bipush 41 (0x29)
// @60: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @63: invokevirtual java.lang.StringBuilder.toString()java.lang.String
// @66: invokestatic game.C_100181_cf.func_105695_a(java.lang.Throwable, java.lang.String)game.C_100170_cm
// @69: athrow
// @6A: return
}
static final void func_101587_i(int arg0)
{
// @00: sipush -18973 (0xB5E3)
// @03: invokestatic game.C_100091_m.func_104503_a(int)void
// @06: bipush -24 (0xE8)
// @08: bipush 17 (0x11)
// @0A: iload_0
// @0B: isub
// @0C: bipush 49 (0x31)
// @0E: idiv
// @0F: irem
// @10: istore_1
// @11: iconst_1
// @12: iconst_4
// @13: invokestatic game.C_100152_bd.func_105184_a(boolean, int)void
// @16: goto @3A
// @19: astore_1
// @1A: aload_1
// @1B: new java.lang.StringBuilder
// @1E: dup
// @1F: invokespecial java.lang.StringBuilder.<init>()void
// @22: getstatic java.lang.String[] game.C_100059_df.field_101609_S
// @25: iconst_0
// @26: aaload
// @27: invokevirtual java.lang.StringBuilder.append(java.lang.String)java.lang.StringBuilder
// @2A: iload_0
// @2B: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @2E: bipush 41 (0x29)
// @30: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @33: invokevirtual java.lang.StringBuilder.toString()java.lang.String
// @36: invokestatic game.C_100181_cf.func_105695_a(java.lang.Throwable, java.lang.String)game.C_100170_cm
// @39: athrow
// @3A: return
}
final void func_101586_a(int arg0, boolean arg1, int arg2, int arg3)
{
// @000: getstatic int game.SteelSentinels.field_105275_O
// @003: istore
// @005: aload_0
// @006: getfield int game.C_100059_df.field_101602_O
// @009: ldc -588690648 (0xdce94b28)
// @00B: ishr
// @00C: iload_1
// @00D: iadd
// @00E: istore
// @010: aload_0
// @011: getfield int game.C_100059_df.field_101605_J
// @014: ldc 1728229800 (0x6702b1a8)
// @016: ishr
// @017: iload
// @019: iadd
// @01A: istore
// @01C: bipush -32 (0xE0)
// @01E: iload
// @020: if_icmpgt @04A
// @023: iload
// @025: sipush 672 (0x02A0)
// @028: if_icmpgt @04A
// @02B: goto @02F
// @02E: athrow
// @02F: bipush -32 (0xE0)
// @031: iload
// @033: if_icmpgt @04A
// @036: goto @03A
// @039: athrow
// @03A: iload
// @03C: sipush 672 (0x02A0)
// @03F: if_icmpgt @04A
// @042: goto @046
// @045: athrow
// @046: goto @04B
// @049: athrow
// @04A: return
// @04B: bipush 8 (0x08)
// @04D: aload_0
// @04E: getfield int game.C_100059_df.field_101598_C
// @051: imul
// @052: aload_0
// @053: getfield int game.C_100059_df.field_101618_x
// @056: idiv
// @057: istore
// @059: iload
// @05B: ifge @061
// @05E: iconst_0
// @05F: istore
// @061: iload
// @063: bipush 7 (0x07)
// @065: if_icmple @06C
// @068: bipush 7 (0x07)
// @06A: istore
// @06C: iconst_m1
// @06D: aload_0
// @06E: getfield int game.C_100059_df.field_101608_P
// @071: iconst_m1
// @072: ixor
// @073: if_icmpne @0E1
// @076: iload_2
// @077: ifeq @41D
// @07A: goto @07E
// @07D: athrow
// @07E: iconst_0
// @07F: bipush 15 (0x0F)
// @081: bipush 16 (0x10)
// @083: aload_0
// @084: getfield int game.C_100059_df.field_101598_C
// @087: imul
// @088: aload_0
// @089: getfield int game.C_100059_df.field_101618_x
// @08C: idiv
// @08D: invokestatic java.lang.Math.min(int, int)int
// @090: invokestatic java.lang.Math.max(int, int)int
// @093: istore
// @095: bipush 17 (0x11)
// @097: istore
// @099: getstatic game.C_100251_pm[] game.C_100084_ug.field_104485_j
// @09C: iload
// @09E: aaload
// @09F: iload
// @0A1: ineg
// @0A2: iload
// @0A4: iadd
// @0A5: iload
// @0A7: ineg
// @0A8: iload
// @0AA: iadd
// @0AB: iconst_2
// @0AC: iload
// @0AE: imul
// @0AF: iconst_2
// @0B0: iload
// @0B2: imul
// @0B3: aload_0
// @0B4: getfield int game.C_100059_df.field_101618_x
// @0B7: iconst_2
// @0B8: idiv
// @0B9: aload_0
// @0BA: getfield int game.C_100059_df.field_101598_C
// @0BD: if_icmpgt @0D6
// @0C0: sipush 500 (0x01F4)
// @0C3: aload_0
// @0C4: getfield int game.C_100059_df.field_101598_C
// @0C7: imul
// @0C8: aload_0
// @0C9: getfield int game.C_100059_df.field_101618_x
// @0CC: idiv
// @0CD: ineg
// @0CE: sipush 505 (0x01F9)
// @0D1: iadd
// @0D2: goto @0D9
// @0D5: athrow
// @0D6: sipush 255 (0x00FF)
// @0D9: invokevirtual game.C_100251_pm.func_102359_a(int, int, int, int, int)void
// @0DC: iload
// @0DE: ifeq @41D
// @0E1: aload_0
// @0E2: getfield int game.C_100059_df.field_101608_P
// @0E5: iconst_m1
// @0E6: ixor
// @0E7: bipush -2 (0xFE)
// @0E9: if_icmpne @124
// @0EC: goto @0F0
// @0EF: athrow
// @0F0: iload_2
// @0F1: ifeq @0FC
// @0F4: goto @0F8
// @0F7: athrow
// @0F8: goto @41D
// @0FB: athrow
// @0FC: bipush 16 (0x10)
// @0FE: istore
// @100: getstatic game.C_100037_wb[] game.C_100266_me.field_106651_e
// @103: iload
// @105: aaload
// @106: iload
// @108: iload
// @10A: isub
// @10B: iload
// @10D: iload
// @10F: ineg
// @110: iadd
// @111: iload
// @113: iconst_2
// @114: imul
// @115: iload
// @117: iconst_2
// @118: imul
// @119: sipush 128 (0x0080)
// @11C: invokevirtual game.C_100037_wb.func_102377_b(int, int, int, int, int)void
// @11F: iload
// @121: ifeq @41D
// @124: aload_0
// @125: getfield int game.C_100059_df.field_101608_P
// @128: iconst_m1
// @129: ixor
// @12A: bipush -4 (0xFC)
// @12C: if_icmpne @163
// @12F: goto @133
// @132: athrow
// @133: iload_2
// @134: ifne @41D
// @137: goto @13B
// @13A: athrow
// @13B: iconst_2
// @13C: istore
// @13E: getstatic game.C_100037_wb[] game.C_100266_me.field_106651_e
// @141: iload
// @143: aaload
// @144: iload
// @146: ineg
// @147: iload
// @149: iadd
// @14A: iload
// @14C: iload
// @14E: ineg
// @14F: iadd
// @150: iload
// @152: iconst_2
// @153: imul
// @154: iconst_2
// @155: iload
// @157: imul
// @158: sipush 128 (0x0080)
// @15B: invokevirtual game.C_100037_wb.func_102377_b(int, int, int, int, int)void
// @15E: iload
// @160: ifeq @41D
// @163: aload_0
// @164: getfield int game.C_100059_df.field_101608_P
// @167: iconst_2
// @168: if_icmpeq @3DE
// @16B: goto @16F
// @16E: athrow
// @16F: aload_0
// @170: getfield int game.C_100059_df.field_101608_P
// @173: iconst_4
// @174: if_icmpeq @3AA
// @177: goto @17B
// @17A: athrow
// @17B: aload_0
// @17C: getfield int game.C_100059_df.field_101608_P
// @17F: iconst_5
// @180: if_icmpne @1B7
// @183: goto @187
// @186: athrow
// @187: iload_2
// @188: ifne @41D
// @18B: goto @18F
// @18E: athrow
// @18F: iconst_4
// @190: istore
// @192: getstatic game.C_100037_wb[] game.C_100101_fc.field_103405_Y
// @195: iload
// @197: aaload
// @198: iload
// @19A: iload
// @19C: ineg
// @19D: iadd
// @19E: iload
// @1A0: ineg
// @1A1: iload
// @1A3: iadd
// @1A4: iconst_2
// @1A5: iload
// @1A7: imul
// @1A8: iload
// @1AA: iconst_2
// @1AB: imul
// @1AC: sipush 128 (0x0080)
// @1AF: invokevirtual game.C_100037_wb.func_102377_b(int, int, int, int, int)void
// @1B2: iload
// @1B4: ifeq @41D
// @1B7: bipush -7 (0xF9)
// @1B9: aload_0
// @1BA: getfield int game.C_100059_df.field_101608_P
// @1BD: iconst_m1
// @1BE: ixor
// @1BF: if_icmpeq @377
// @1C2: goto @1C6
// @1C5: athrow
// @1C6: bipush -8 (0xF8)
// @1C8: aload_0
// @1C9: getfield int game.C_100059_df.field_101608_P
// @1CC: iconst_m1
// @1CD: ixor
// @1CE: if_icmpne @208
// @1D1: goto @1D5
// @1D4: athrow
// @1D5: iload_2
// @1D6: ifeq @1E1
// @1D9: goto @1DD
// @1DC: athrow
// @1DD: goto @41D
// @1E0: athrow
// @1E1: iconst_1
// @1E2: istore
// @1E4: getstatic game.C_100037_wb[] game.C_100266_me.field_106651_e
// @1E7: iload
// @1E9: aaload
// @1EA: iload
// @1EC: iload
// @1EE: ineg
// @1EF: iadd
// @1F0: iload
// @1F2: iload
// @1F4: isub
// @1F5: iload
// @1F7: iconst_2
// @1F8: imul
// @1F9: iconst_2
// @1FA: iload
// @1FC: imul
// @1FD: sipush 128 (0x0080)
// @200: invokevirtual game.C_100037_wb.func_102377_b(int, int, int, int, int)void
// @203: iload
// @205: ifeq @41D
// @208: aload_0
// @209: getfield int game.C_100059_df.field_101608_P
// @20C: iconst_m1
// @20D: ixor
// @20E: bipush -9 (0xF7)
// @210: if_icmpne @25F
// @213: goto @217
// @216: athrow
// @217: iload_2
// @218: ifeq @223
// @21B: goto @21F
// @21E: athrow
// @21F: goto @41D
// @222: athrow
// @223: iconst_0
// @224: bipush 15 (0x0F)
// @226: bipush 16 (0x10)
// @228: aload_0
// @229: getfield int game.C_100059_df.field_101598_C
// @22C: imul
// @22D: aload_0
// @22E: getfield int game.C_100059_df.field_101618_x
// @231: idiv
// @232: invokestatic java.lang.Math.min(int, int)int
// @235: invokestatic java.lang.Math.max(int, int)int
// @238: istore
// @23A: iconst_4
// @23B: istore
// @23D: getstatic game.C_100251_pm[] game.C_100084_ug.field_104485_j
// @240: iload
// @242: aaload
// @243: iload
// @245: iload
// @247: ineg
// @248: iadd
// @249: iload
// @24B: ineg
// @24C: iload
// @24E: iadd
// @24F: iconst_2
// @250: iload
// @252: imul
// @253: iconst_2
// @254: iload
// @256: imul
// @257: invokevirtual game.C_100251_pm.func_102364_d(int, int, int, int)void
// @25A: iload
// @25C: ifeq @41D
// @25F: bipush -10 (0xF6)
// @261: aload_0
// @262: getfield int game.C_100059_df.field_101608_P
// @265: iconst_m1
// @266: ixor
// @267: if_icmpne @2B0
// @26A: goto @26E
// @26D: athrow
// @26E: iload_2
// @26F: ifne @41D
// @272: goto @276
// @275: athrow
// @276: iconst_4
// @277: istore
// @279: getstatic game.C_100037_wb[] game.C_100266_me.field_106651_e
// @27C: bipush 7 (0x07)
// @27E: iload
// @280: ineg
// @281: iadd
// @282: aaload
// @283: iload
// @285: iload
// @287: isub
// @288: iload
// @28A: ineg
// @28B: iload
// @28D: iadd
// @28E: iload
// @290: iconst_2
// @291: imul
// @292: iload
// @294: iconst_2
// @295: imul
// @296: sipush 200 (0x00C8)
// @299: aload_0
// @29A: getfield int game.C_100059_df.field_101598_C
// @29D: imul
// @29E: aload_0
// @29F: getfield int game.C_100059_df.field_101618_x
// @2A2: idiv
// @2A3: ineg
// @2A4: sipush 200 (0x00C8)
// @2A7: iadd
// @2A8: invokevirtual game.C_100037_wb.func_102359_a(int, int, int, int, int)void
// @2AB: iload
// @2AD: ifeq @41D
// @2B0: aload_0
// @2B1: getfield int game.C_100059_df.field_101608_P
// @2B4: bipush 12 (0x0C)
// @2B6: if_icmpne @2FE
// @2B9: goto @2BD
// @2BC: athrow
// @2BD: iload_2
// @2BE: ifne @41D
// @2C1: goto @2C5
// @2C4: athrow
// @2C5: iconst_2
// @2C6: istore
// @2C8: getstatic game.C_100037_wb[] game.C_100101_fc.field_103405_Y
// @2CB: iconst_2
// @2CC: iload
// @2CE: iand
// @2CF: aaload
// @2D0: iload
// @2D2: iload
// @2D4: ineg
// @2D5: iadd
// @2D6: iload
// @2D8: ineg
// @2D9: iload
// @2DB: iadd
// @2DC: iload
// @2DE: iconst_2
// @2DF: imul
// @2E0: iload
// @2E2: iconst_2
// @2E3: imul
// @2E4: sipush 250 (0x00FA)
// @2E7: aload_0
// @2E8: getfield int game.C_100059_df.field_101598_C
// @2EB: imul
// @2EC: aload_0
// @2ED: getfield int game.C_100059_df.field_101618_x
// @2F0: idiv
// @2F1: ineg
// @2F2: sipush 250 (0x00FA)
// @2F5: iadd
// @2F6: invokevirtual game.C_100037_wb.func_102377_b(int, int, int, int, int)void
// @2F9: iload
// @2FB: ifeq @41D
// @2FE: aload_0
// @2FF: getfield int game.C_100059_df.field_101608_P
// @302: iconst_m1
// @303: ixor
// @304: bipush -14 (0xF2)
// @306: if_icmpeq @34E
// @309: goto @30D
// @30C: athrow
// @30D: aload_0
// @30E: getfield int game.C_100059_df.field_101608_P
// @311: bipush 14 (0x0E)
// @313: if_icmpne @41D
// @316: goto @31A
// @319: athrow
// @31A: iload_2
// @31B: ifne @41D
// @31E: goto @322
// @321: athrow
// @322: iconst_2
// @323: aload_0
// @324: getfield int game.C_100059_df.field_101598_C
// @327: ineg
// @328: sipush 250 (0x00FA)
// @32B: iadd
// @32C: imul
// @32D: bipush 125 (0x7D)
// @32F: idiv
// @330: istore
// @332: iload
// @334: ldc -1679623580 (0x9be2fa64)
// @336: ishl
// @337: iload
// @339: ldc -1185769372 (0xb9529864)
// @33B: ishl
// @33C: iload
// @33E: ldc 957204388 (0x390dc7a4)
// @340: ishl
// @341: bipush 31 (0x1F)
// @343: getstatic int[] game.C_100129_tg.field_102747_tb
// @346: invokestatic game.C_100196_rb.func_105787_a(int, int, int, int, int[])void
// @349: iload
// @34B: ifeq @41D
// @34E: iload_2
// @34F: ifne @41D
// @352: goto @356
// @355: athrow
// @356: bipush 16 (0x10)
// @358: istore
// @35A: iload
// @35C: ldc -1100027964 (0xbe6ee7c4)
// @35E: ishl
// @35F: iload
// @361: ldc 1613298116 (0x6028f9c4)
// @363: ishl
// @364: iload
// @366: ldc -488379132 (0xe2e3ed04)
// @368: ishl
// @369: sipush 249 (0x00F9)
// @36C: getstatic int[] game.C_100129_tg.field_102753_wb
// @36F: invokestatic game.C_100196_rb.func_105787_a(int, int, int, int, int[])void
// @372: iload
// @374: ifeq @41D
// @377: iload_2
// @378: ifeq @383
// @37B: goto @37F
// @37E: athrow
// @37F: goto @41D
// @382: athrow
// @383: iconst_2
// @384: istore
// @386: getstatic game.C_100037_wb[] game.C_100101_fc.field_103405_Y
// @389: iload
// @38B: aaload
// @38C: iload
// @38E: iload
// @390: ineg
// @391: iadd
// @392: iload
// @394: iload
// @396: isub
// @397: iload
// @399: iconst_2
// @39A: imul
// @39B: iload
// @39D: iconst_2
// @39E: imul
// @39F: sipush 128 (0x0080)
// @3A2: invokevirtual game.C_100037_wb.func_102377_b(int, int, int, int, int)void
// @3A5: iload
// @3A7: ifeq @41D
// @3AA: iload_2
// @3AB: ifeq @3B6
// @3AE: goto @3B2
// @3B1: athrow
// @3B2: goto @41D
// @3B5: athrow
// @3B6: bipush 16 (0x10)
// @3B8: istore
// @3BA: getstatic game.C_100037_wb[] game.C_100101_fc.field_103405_Y
// @3BD: iload
// @3BF: aaload
// @3C0: iload
// @3C2: ineg
// @3C3: iload
// @3C5: iadd
// @3C6: iload
// @3C8: iload
// @3CA: isub
// @3CB: iconst_2
// @3CC: iload
// @3CE: imul
// @3CF: iconst_2
// @3D0: iload
// @3D2: imul
// @3D3: sipush 128 (0x0080)
// @3D6: invokevirtual game.C_100037_wb.func_102377_b(int, int, int, int, int)void
// @3D9: iload
// @3DB: ifeq @41D
// @3DE: iload_2
// @3DF: ifeq @41D
// @3E2: goto @3E6
// @3E5: athrow
// @3E6: iconst_0
// @3E7: bipush 15 (0x0F)
// @3E9: aload_0
// @3EA: getfield int game.C_100059_df.field_101598_C
// @3ED: bipush 16 (0x10)
// @3EF: imul
// @3F0: aload_0
// @3F1: getfield int game.C_100059_df.field_101618_x
// @3F4: idiv
// @3F5: invokestatic java.lang.Math.min(int, int)int
// @3F8: invokestatic java.lang.Math.max(int, int)int
// @3FB: istore
// @3FD: iconst_2
// @3FE: istore
// @400: getstatic game.C_100251_pm[] game.C_100084_ug.field_104485_j
// @403: iload
// @405: aaload
// @406: iload
// @408: iload
// @40A: ineg
// @40B: iadd
// @40C: iload
// @40E: ineg
// @40F: iload
// @411: iadd
// @412: iconst_2
// @413: iload
// @415: imul
// @416: iload
// @418: iconst_2
// @419: imul
// @41A: invokevirtual game.C_100251_pm.func_102364_d(int, int, int, int)void
// @41D: iload_3
// @41E: sipush 4958 (0x135E)
// @421: if_icmpeq @42C
// @424: iconst_1
// @425: putstatic boolean game.C_100059_df.field_101613_u
// @428: goto @42C
// @42B: athrow
// @42C: goto @46E
// @42F: astore
// @431: aload
// @433: new java.lang.StringBuilder
// @436: dup
// @437: invokespecial java.lang.StringBuilder.<init>()void
// @43A: getstatic java.lang.String[] game.C_100059_df.field_101609_S
// @43D: iconst_3
// @43E: aaload
// @43F: invokevirtual java.lang.StringBuilder.append(java.lang.String)java.lang.StringBuilder
// @442: iload_1
// @443: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @446: bipush 44 (0x2C)
// @448: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @44B: iload_2
// @44C: invokevirtual java.lang.StringBuilder.append(boolean)java.lang.StringBuilder
// @44F: bipush 44 (0x2C)
// @451: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @454: iload_3
// @455: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @458: bipush 44 (0x2C)
// @45A: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @45D: iload
// @45F: invokevirtual java.lang.StringBuilder.append(int)java.lang.StringBuilder
// @462: bipush 41 (0x29)
// @464: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @467: invokevirtual java.lang.StringBuilder.toString()java.lang.String
// @46A: invokestatic game.C_100181_cf.func_105695_a(java.lang.Throwable, java.lang.String)game.C_100170_cm
// @46D: athrow
// @46E: return
}
final void func_101585_b(boolean arg0)
{
// @000: getstatic int game.SteelSentinels.field_105275_O
// @003: istore_3
// @004: iload_1
// @005: ifeq @009
// @008: return
// @009: aload_0
// @00A: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @00D: ifnonnull @011
// @010: return
// @011: aload_0
// @012: dup
// @013: getfield int game.C_100059_df.field_101602_O
// @016: aload_0
// @017: getfield int game.C_100059_df.field_101595_G
// @01A: iadd
// @01B: putfield int game.C_100059_df.field_101602_O
// @01E: aload_0
// @01F: dup
// @020: getfield int game.C_100059_df.field_101605_J
// @023: aload_0
// @024: getfield int game.C_100059_df.field_101607_Q
// @027: iadd
// @028: putfield int game.C_100059_df.field_101605_J
// @02B: sipush -201 (0xFF37)
// @02E: aload_0
// @02F: getfield int game.C_100059_df.field_101598_C
// @032: iconst_m1
// @033: ixor
// @034: if_icmplt @03B
// @037: goto @04C
// @03A: athrow
// @03B: aload_0
// @03C: dup
// @03D: getfield int game.C_100059_df.field_101598_C
// @040: invokestatic java.lang.Math.random()double
// @043: ldc2_w 4.0
// @046: dmul
// @047: d2i
// @048: iadd
// @049: putfield int game.C_100059_df.field_101598_C
// @04C: aload_0
// @04D: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @050: getfield game.C_100171_cn game.C_100294_ki.field_106995_u
// @053: sipush 26294 (0x66B6)
// @056: invokevirtual game.C_100171_cn.func_105559_a(int)int
// @059: iconst_4
// @05A: if_icmpne @061
// @05D: goto @2A1
// @060: athrow
// @061: aload_0
// @062: getfield boolean game.C_100059_df.field_101617_y
// @065: ifeq @156
// @068: aload_0
// @069: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @06C: getfield game.C_100171_cn game.C_100294_ki.field_106995_u
// @06F: ldc 830205956 (0x317bf004)
// @071: aload_0
// @072: getfield int game.C_100059_df.field_101602_O
// @075: ldc -1266522588 (0xb4826624)
// @077: ishr
// @078: invokevirtual game.C_100171_cn.func_105563_a(int, int)int
// @07B: aload_0
// @07C: getfield int game.C_100059_df.field_101605_J
// @07F: ldc -1081539388 (0xbf8904c4)
// @081: ishr
// @082: ineg
// @083: if_icmplt @08E
// @086: goto @08A
// @089: athrow
// @08A: goto @260
// @08D: athrow
// @08E: aload_0
// @08F: getfield int game.C_100059_df.field_101608_P
// @092: iconst_2
// @093: if_icmpeq @0CE
// @096: bipush -4 (0xFC)
// @098: aload_0
// @099: getfield int game.C_100059_df.field_101608_P
// @09C: iconst_m1
// @09D: ixor
// @09E: if_icmpeq @0CE
// @0A1: goto @0A5
// @0A4: athrow
// @0A5: aload_0
// @0A6: getfield int game.C_100059_df.field_101608_P
// @0A9: iconst_m1
// @0AA: ixor
// @0AB: bipush -10 (0xF6)
// @0AD: if_icmpeq @0CE
// @0B0: goto @0B4
// @0B3: athrow
// @0B4: bipush 10 (0x0A)
// @0B6: aload_0
// @0B7: getfield int game.C_100059_df.field_101608_P
// @0BA: if_icmpeq @0CE
// @0BD: goto @0C1
// @0C0: athrow
// @0C1: aload_0
// @0C2: getfield int game.C_100059_df.field_101608_P
// @0C5: bipush 6 (0x06)
// @0C7: if_icmpne @100
// @0CA: goto @0CE
// @0CD: athrow
// @0CE: aload_0
// @0CF: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @0D2: getfield game.C_100171_cn game.C_100294_ki.field_106995_u
// @0D5: ldc 830205956 (0x317bf004)
// @0D7: aload_0
// @0D8: getfield int game.C_100059_df.field_101602_O
// @0DB: ldc 676877412 (0x28585464)
// @0DD: ishr
// @0DE: invokevirtual game.C_100171_cn.func_105563_a(int, int)int
// @0E1: aload_0
// @0E2: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @0E5: getfield game.C_100171_cn game.C_100294_ki.field_106995_u
// @0E8: sipush -25357 (0x9CF3)
// @0EB: aload_0
// @0EC: getfield int game.C_100059_df.field_101602_O
// @0EF: ldc -487332540 (0xe2f3e544)
// @0F1: ishr
// @0F2: invokevirtual game.C_100171_cn.func_105555_b(int, int)int
// @0F5: if_icmpne @100
// @0F8: goto @0FC
// @0FB: athrow
// @0FC: goto @11B
// @0FF: athrow
// @100: aload_0
// @101: aload_0
// @102: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @105: getfield game.C_100171_cn game.C_100294_ki.field_106995_u
// @108: ldc 830205956 (0x317bf004)
// @10A: aload_0
// @10B: getfield int game.C_100059_df.field_101602_O
// @10E: ldc -863873884 (0xcc8254a4)
// @110: ishr
// @111: invokevirtual game.C_100171_cn.func_105563_a(int, int)int
// @114: ldc -1371293372 (0xae43b944)
// @116: ishl
// @117: ineg
// @118: putfield int game.C_100059_df.field_101605_J
// @11B: aload_0
// @11C: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @11F: getfield game.C_100171_cn game.C_100294_ki.field_106995_u
// @122: ldc 830205956 (0x317bf004)
// @124: aload_0
// @125: getfield int game.C_100059_df.field_101602_O
// @128: ldc 1931599076 (0x7321dce4)
// @12A: ishr
// @12B: invokevirtual game.C_100171_cn.func_105563_a(int, int)int
// @12E: iconst_m1
// @12F: ixor
// @130: aload_0
// @131: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @134: getfield game.C_100171_cn game.C_100294_ki.field_106995_u
// @137: sipush -25357 (0x9CF3)
// @13A: aload_0
// @13B: getfield int game.C_100059_df.field_101602_O
// @13E: ldc 1283902756 (0x4c86cd24)
// @140: ishr
// @141: invokevirtual game.C_100171_cn.func_105555_b(int, int)int
// @144: iconst_m1
// @145: ixor
// @146: if_icmpne @260
// @149: aload_0
// @14A: iconst_0
// @14B: putfield boolean game.C_100059_df.field_101617_y
// @14E: iload_3
// @14F: ifeq @260
// @152: goto @156
// @155: athrow
// @156: aload_0
// @157: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @15A: getfield game.C_100171_cn game.C_100294_ki.field_106995_u
// @15D: sipush -25357 (0x9CF3)
// @160: aload_0
// @161: getfield int game.C_100059_df.field_101602_O
// @164: ldc 341788644 (0x145f47e4)
// @166: ishr
// @167: invokevirtual game.C_100171_cn.func_105555_b(int, int)int
// @16A: aload_0
// @16B: getfield int game.C_100059_df.field_101605_J
// @16E: ldc 1405789220 (0x53caa424)
// @170: ishr
// @171: ineg
// @172: if_icmple @260
// @175: goto @179
// @178: athrow
// @179: iconst_2
// @17A: aload_0
// @17B: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @17E: getfield game.C_100171_cn game.C_100294_ki.field_106995_u
// @181: sipush 26294 (0x66B6)
// @184: invokevirtual game.C_100171_cn.func_105559_a(int)int
// @187: if_icmpne @1C8
// @18A: goto @18E
// @18D: athrow
// @18E: sipush -2049 (0xF7FF)
// @191: aload_0
// @192: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @195: getfield game.C_100171_cn game.C_100294_ki.field_106995_u
// @198: sipush -25357 (0x9CF3)
// @19B: aload_0
// @19C: getfield int game.C_100059_df.field_101602_O
// @19F: ldc -1512280348 (0xa5dc6ee4)
// @1A1: ishr
// @1A2: invokevirtual game.C_100171_cn.func_105555_b(int, int)int
// @1A5: iconst_m1
// @1A6: ixor
// @1A7: if_icmple @1C8
// @1AA: goto @1AE
// @1AD: athrow
// @1AE: aload_0
// @1AF: dup
// @1B0: getfield int game.C_100059_df.field_101602_O
// @1B3: aload_0
// @1B4: getfield int game.C_100059_df.field_101595_G
// @1B7: isub
// @1B8: putfield int game.C_100059_df.field_101602_O
// @1BB: aload_0
// @1BC: iconst_0
// @1BD: putfield int game.C_100059_df.field_101595_G
// @1C0: iload_3
// @1C1: ifeq @260
// @1C4: goto @1C8
// @1C7: athrow
// @1C8: aload_0
// @1C9: getfield int game.C_100059_df.field_101608_P
// @1CC: iconst_m1
// @1CD: ixor
// @1CE: bipush -3 (0xFD)
// @1D0: if_icmpeq @20E
// @1D3: goto @1D7
// @1D6: athrow
// @1D7: aload_0
// @1D8: getfield int game.C_100059_df.field_101608_P
// @1DB: iconst_3
// @1DC: if_icmpeq @20E
// @1DF: goto @1E3
// @1E2: athrow
// @1E3: bipush -10 (0xF6)
// @1E5: aload_0
// @1E6: getfield int game.C_100059_df.field_101608_P
// @1E9: iconst_m1
// @1EA: ixor
// @1EB: if_icmpeq @20E
// @1EE: goto @1F2
// @1F1: athrow
// @1F2: bipush -11 (0xF5)
// @1F4: aload_0
// @1F5: getfield int game.C_100059_df.field_101608_P
// @1F8: iconst_m1
// @1F9: ixor
// @1FA: if_icmpeq @20E
// @1FD: goto @201
// @200: athrow
// @201: aload_0
// @202: getfield int game.C_100059_df.field_101608_P
// @205: bipush 6 (0x06)
// @207: if_icmpne @240
// @20A: goto @20E
// @20D: athrow
// @20E: aload_0
// @20F: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @212: getfield game.C_100171_cn game.C_100294_ki.field_106995_u
// @215: ldc 830205956 (0x317bf004)
// @217: aload_0
// @218: getfield int game.C_100059_df.field_101602_O
// @21B: ldc -932464060 (0xc86bba44)
// @21D: ishr
// @21E: invokevirtual game.C_100171_cn.func_105563_a(int, int)int
// @221: iconst_m1
// @222: ixor
// @223: aload_0
// @224: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @227: getfield game.C_100171_cn game.C_100294_ki.field_106995_u
// @22A: sipush -25357 (0x9CF3)
// @22D: aload_0
// @22E: getfield int game.C_100059_df.field_101602_O
// @231: ldc 837576932 (0x31ec68e4)
// @233: ishr
// @234: invokevirtual game.C_100171_cn.func_105555_b(int, int)int
// @237: iconst_m1
// @238: ixor
// @239: if_icmpeq @260
// @23C: goto @240
// @23F: athrow
// @240: aload_0
// @241: aload_0
// @242: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @245: getfield game.C_100171_cn game.C_100294_ki.field_106995_u
// @248: sipush -25357 (0x9CF3)
// @24B: aload_0
// @24C: getfield int game.C_100059_df.field_101602_O
// @24F: ldc 2034008420 (0x793c8164)
// @251: ishr
// @252: invokevirtual game.C_100171_cn.func_105555_b(int, int)int
// @255: ldc 650318436 (0x26c31264)
// @257: ishl
// @258: ineg
// @259: putfield int game.C_100059_df.field_101605_J
// @25C: goto @260
// @25F: athrow
// @260: aload_0
// @261: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @264: getfield game.C_100171_cn game.C_100294_ki.field_106995_u
// @267: bipush 109 (0x6D)
// @269: aload_0
// @26A: getfield int game.C_100059_df.field_101602_O
// @26D: ldc 436987236 (0x1a0be564)
// @26F: ishr
// @270: invokevirtual game.C_100171_cn.func_105560_c(int, int)int
// @273: iconst_m1
// @274: ixor
// @275: aload_0
// @276: getfield int game.C_100059_df.field_101605_J
// @279: ldc 690250660 (0x292463a4)
// @27B: ishr
// @27C: ineg
// @27D: iconst_m1
// @27E: ixor
// @27F: if_icmplt @286
// @282: goto @2A1
// @285: athrow
// @286: aload_0
// @287: aload_0
// @288: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @28B: getfield game.C_100171_cn game.C_100294_ki.field_106995_u
// @28E: bipush -75 (0xB5)
// @290: aload_0
// @291: getfield int game.C_100059_df.field_101602_O
// @294: ldc -1107886140 (0xbdf6ffc4)
// @296: ishr
// @297: invokevirtual game.C_100171_cn.func_105560_c(int, int)int
// @29A: ldc 193861508 (0xb8e1784)
// @29C: ishl
// @29D: ineg
// @29E: putfield int game.C_100059_df.field_101605_J
// @2A1: aload_0
// @2A2: getfield int game.C_100059_df.field_101608_P
// @2A5: bipush 10 (0x0A)
// @2A7: if_icmpeq @2CE
// @2AA: aload_0
// @2AB: bipush 9 (0x09)
// @2AD: aload_0
// @2AE: getfield int game.C_100059_df.field_101595_G
// @2B1: imul
// @2B2: bipush 10 (0x0A)
// @2B4: idiv
// @2B5: putfield int game.C_100059_df.field_101595_G
// @2B8: aload_0
// @2B9: aload_0
// @2BA: getfield int game.C_100059_df.field_101607_Q
// @2BD: bipush 9 (0x09)
// @2BF: imul
// @2C0: bipush 10 (0x0A)
// @2C2: idiv
// @2C3: putfield int game.C_100059_df.field_101607_Q
// @2C6: iload_3
// @2C7: ifeq @30B
// @2CA: goto @2CE
// @2CD: athrow
// @2CE: aload_0
// @2CF: dup
// @2D0: getfield int game.C_100059_df.field_101607_Q
// @2D3: aload_0
// @2D4: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @2D7: getfield int game.C_100294_ki.field_106964_J
// @2DA: iadd
// @2DB: putfield int game.C_100059_df.field_101607_Q
// @2DE: aload_0
// @2DF: getfield int game.C_100059_df.field_101610_R
// @2E2: iconst_0
// @2E3: aload_0
// @2E4: getfield boolean game.C_100059_df.field_101617_y
// @2E7: aload_0
// @2E8: getfield int game.C_100059_df.field_101605_J
// @2EB: iconst_0
// @2EC: aload_0
// @2ED: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @2F0: bipush -124 (0x84)
// @2F2: aload_0
// @2F3: getfield int game.C_100059_df.field_101602_O
// @2F6: bipush 9 (0x09)
// @2F8: bipush 100 (0x64)
// @2FA: invokestatic game.C_100157_db.func_103553_a(int, int, boolean, int, int, game.C_100294_ki, byte, int, int, int)game.C_100059_df
// @2FD: astore_2
// @2FE: aload_0
// @2FF: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @302: getfield game.C_100202_qi game.C_100294_ki.field_106949_hb
// @305: bipush 124 (0x7C)
// @307: aload_2
// @308: invokevirtual game.C_100202_qi.func_105901_a(int, game.C_100158_da)void
// @30B: aload_0
// @30C: dup
// @30D: getfield int game.C_100059_df.field_101598_C
// @310: iconst_1
// @311: iadd
// @312: putfield int game.C_100059_df.field_101598_C
// @315: aload_0
// @316: getfield int game.C_100059_df.field_101598_C
// @319: aload_0
// @31A: getfield int game.C_100059_df.field_101618_x
// @31D: if_icmple @331
// @320: aload_0
// @321: getfield game.C_100294_ki game.C_100059_df.field_101596_A
// @324: getfield game.C_100300_kc game.C_100294_ki.field_106950_D
// @327: bipush 125 (0x7D)
// @329: aload_0
// @32A: invokevirtual game.C_100300_kc.func_107058_a(int, game.C_100325_id)void
// @32D: goto @331
// @330: athrow
// @331: goto @355
// @334: astore_2
// @335: aload_2
// @336: new java.lang.StringBuilder
// @339: dup
// @33A: invokespecial java.lang.StringBuilder.<init>()void
// @33D: getstatic java.lang.String[] game.C_100059_df.field_101609_S
// @340: iconst_1
// @341: aaload
// @342: invokevirtual java.lang.StringBuilder.append(java.lang.String)java.lang.StringBuilder
// @345: iload_1
// @346: invokevirtual java.lang.StringBuilder.append(boolean)java.lang.StringBuilder
// @349: bipush 41 (0x29)
// @34B: invokevirtual java.lang.StringBuilder.append(char)java.lang.StringBuilder
// @34E: invokevirtual java.lang.StringBuilder.toString()java.lang.String
// @351: invokestatic game.C_100181_cf.func_105695_a(java.lang.Throwable, java.lang.String)game.C_100170_cm
// @354: athrow
// @355: return
}
static
{
// @000: iconst_5
// @001: anewarray java.lang.String
// @004: dup
// @005: iconst_0
// @006: ldc "uL&K\u007f"
// @008: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @00B: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @00E: aastore
// @00F: dup
// @010: iconst_1
// @011: ldc "uL&J\u007f"
// @013: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @016: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @019: aastore
// @01A: dup
// @01B: iconst_2
// @01C: ldc "uL&L\u007f"
// @01E: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @021: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @024: aastore
// @025: dup
// @026: iconst_3
// @027: ldc "uL&M\u007f"
// @029: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @02C: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @02F: aastore
// @030: dup
// @031: iconst_4
// @032: ldc "uL&I\u007f"
// @034: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @037: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @03A: aastore
// @03B: putstatic java.lang.String[] game.C_100059_df.field_101609_S
// @03E: iconst_3
// @03F: newarray byte[]
// @041: dup
// @042: iconst_0
// @043: iconst_2
// @044: bastore
// @045: dup
// @046: iconst_1
// @047: iconst_3
// @048: bastore
// @049: dup
// @04A: iconst_2
// @04B: bipush 6 (0x06)
// @04D: bastore
// @04E: putstatic byte[] game.C_100059_df.field_101603_H
// @051: ldc "-\u000f96wfK{(3tY|z8hOl(5h\n4-g/"
// @053: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @056: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @059: putstatic java.lang.String game.C_100059_df.field_101594_F
// @05C: bipush 48 (0x30)
// @05E: putstatic int game.C_100059_df.field_101592_D
// @061: ldc "RKem%p\n}xxuE\u007ffm1dgz:pF"
// @063: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @066: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @069: putstatic java.lang.String game.C_100059_df.field_101606_K
// @06C: ldc "HE}(?p\\m(3tIda9tN(|?t\naf!x^i|>~D&"
// @06E: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @071: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @074: putstatic java.lang.String game.C_100059_df.field_101616_z
// @077: bipush 11 (0x0B)
// @079: newarray int[]
// @07B: dup
// @07C: iconst_0
// @07D: bipush 108 (0x6C)
// @07F: iastore
// @080: dup
// @081: iconst_1
// @082: iconst_m1
// @083: iastore
// @084: dup
// @085: iconst_2
// @086: bipush 30 (0x1E)
// @088: iastore
// @089: dup
// @08A: iconst_3
// @08B: bipush 28 (0x1C)
// @08D: iastore
// @08E: dup
// @08F: iconst_4
// @090: bipush 29 (0x1D)
// @092: iastore
// @093: dup
// @094: iconst_5
// @095: iconst_m1
// @096: iastore
// @097: dup
// @098: bipush 6 (0x06)
// @09A: iconst_m1
// @09B: iastore
// @09C: dup
// @09D: bipush 7 (0x07)
// @09F: iconst_m1
// @0A0: iastore
// @0A1: dup
// @0A2: bipush 8 (0x08)
// @0A4: iconst_m1
// @0A5: iastore
// @0A6: dup
// @0A7: bipush 9 (0x09)
// @0A9: iconst_m1
// @0AA: iastore
// @0AB: dup
// @0AC: bipush 10 (0x0A)
// @0AE: iconst_m1
// @0AF: iastore
// @0B0: putstatic int[] game.C_100059_df.field_101600_M
// @0B3: iconst_0
// @0B4: putstatic int game.C_100059_df.field_101611_w
// @0B7: ldc "W_dd"
// @0B9: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @0BC: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @0BF: putstatic java.lang.String game.C_100059_df.field_101612_v
// @0C2: bipush 6 (0x06)
// @0C4: anewarray java.lang.String
// @0C7: dup
// @0C8: iconst_0
// @0C9: ldc "_kEM"
// @0CB: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @0CE: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @0D1: aastore
// @0D2: dup
// @0D3: iconst_1
// @0D4: ldc "Ck\\A\u0019V"
// @0D6: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @0D9: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @0DC: aastore
// @0DD: dup
// @0DE: iconst_2
// @0DF: ldc "AfIQ\u0012U"
// @0E1: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @0E4: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @0E7: aastore
// @0E8: dup
// @0E9: iconst_3
// @0EA: ldc "FeF"
// @0EC: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @0EF: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @0F2: aastore
// @0F3: dup
// @0F4: iconst_4
// @0F5: ldc "UxI_\u0019"
// @0F7: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @0FA: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @0FD: aastore
// @0FE: dup
// @0FF: iconst_5
// @100: ldc "]e[\\"
// @102: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @105: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @108: aastore
// @109: putstatic java.lang.String[] game.C_100059_df.field_101597_B
// @10C: bipush 6 (0x06)
// @10E: anewarray java.lang.String
// @111: dup
// @112: iconst_0
// @113: ldc "\\E~mwsKkcweE(|?t\nxz2gCg}$1Gmf\"1Fm~2}\u0004"
// @115: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @118: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @11B: aastore
// @11C: dup
// @11D: iconst_1
// @11E: ldc "CO|}%\u007f\n|gweBm(#~Z(d2gOd(8w\n|`21Gmf\"?"
// @120: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @123: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @126: aastore
// @127: dup
// @128: iconst_2
// @129: ldc "P_|gzcO{x8\u007fN(|81^`mw}K{|weBaf01Cf(.~_z(4yK|( xDlg ?"
// @12B: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @12E: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @131: aastore
// @132: dup
// @133: iconst_3
// @134: ldc "^ZmfweBm(\u0006dCkcwRBi|w|Of}y"
// @136: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @139: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @13C: aastore
// @13D: dup
// @13E: iconst_4
// @13F: ldc "COxm6e\n|`21Fi{#1^`a9v\nqg\"1Yia3?"
// @141: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @144: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @147: aastore
// @148: dup
// @149: iconst_5
// @14A: ldc "RFg{21^`mw@_ak<1i`i#1Gmf\"?"
// @14C: invokestatic game.C_100059_df.func_101589_z(java.lang.String)char[]
// @14F: invokestatic game.C_100059_df.func_101588_z(char[])java.lang.String
// @152: aastore
// @153: putstatic java.lang.String[] game.C_100059_df.field_101601_N
// @156: return
}
private static char[] func_101589_z(String arg0)
{
// @00: aload_0
// @01: invokevirtual java.lang.String.toCharArray()char[]
// @04: dup
// @05: arraylength
// @06: iconst_2
// @07: if_icmpge @13
// @0A: dup
// @0B: iconst_0
// @0C: dup2
// @0D: caload
// @0E: bipush 87 (0x57)
// @10: ixor
// @11: i2c
// @12: castore
// @13: areturn
}
private static String func_101588_z(char[] arg0)
{
// @00: aload_0
// @01: dup
// @02: arraylength
// @03: swap
// @04: iconst_0
// @05: istore_1
// @06: goto @4C
// @09: dup
// @0A: iload_1
// @0B: dup2
// @0C: caload
// @0D: iload_1
// @0E: iconst_5
// @0F: irem
// @10: tableswitch def: @44, for 0: @30, for 1: @35, for 2: @3A, for 3: @3F
// @30: bipush 17 (0x11)
// @32: goto @46
// @35: bipush 42 (0x2A)
// @37: goto @46
// @3A: bipush 8 (0x08)
// @3C: goto @46
// @3F: bipush 8 (0x08)
// @41: goto @46
// @44: bipush 87 (0x57)
// @46: ixor
// @47: i2c
// @48: castore
// @49: iinc #1 +1
// @4C: swap
// @4D: dup_x1
// @4E: iload_1
// @4F: if_icmpgt @09
// @52: new java.lang.String
// @55: dup_x1
// @56: swap
// @57: invokespecial java.lang.String.<init>(char[])void
// @5A: invokevirtual java.lang.String.intern()java.lang.String
// @5D: areturn
}
} |
using System.Collections.Generic;
namespace LeafStyle
{
public class <API key> : BasicStyleProperty<TextOverflowState>
{
public string String { get; set; }
public <API key>()
: base(
defaultState: default(TextOverflowState),
inherited: false,
animatable: false
)
{
this.StateValues = new Dictionary<string, TextOverflowState>()
{
{"clip", TextOverflowState.Clip},
{"ellipsis", TextOverflowState.Ellipsis},
{"string", TextOverflowState.String},
{"initial", TextOverflowState.Initial},
{"inherit", TextOverflowState.Inherit}
};
}
public override bool TrySetStateValue(string value)
{
if (base.TrySetStateValue(value))
{
return true;
}
else if (value != null)
{
this.String = value;
this.CurrentState = TextOverflowState.String;
return true;
}
// value was null
return false;
}
}
} |
package com.l2jglobal.gameserver.network.clientpackets;
import com.l2jglobal.commons.network.PacketReader;
import com.l2jglobal.gameserver.model.L2World;
import com.l2jglobal.gameserver.model.TradeItem;
import com.l2jglobal.gameserver.model.TradeList;
import com.l2jglobal.gameserver.model.actor.instance.L2PcInstance;
import com.l2jglobal.gameserver.network.SystemMessageId;
import com.l2jglobal.gameserver.network.client.L2GameClient;
import com.l2jglobal.gameserver.network.serverpackets.TradeOtherAdd;
import com.l2jglobal.gameserver.network.serverpackets.TradeOwnAdd;
import com.l2jglobal.gameserver.network.serverpackets.TradeUpdate;
public final class AddTradeItem implements <API key>
{
private int _tradeId;
private int _objectId;
private long _count;
@Override
public boolean read(L2GameClient client, PacketReader packet)
{
_tradeId = packet.readD();
_objectId = packet.readD();
_count = packet.readQ();
return true;
}
@Override
public void run(L2GameClient client)
{
final L2PcInstance player = client.getActiveChar();
if (player == null)
{
return;
}
final TradeList trade = player.getActiveTradeList();
if (trade == null)
{
_log.warning("Character: " + player.getName() + " requested item:" + _objectId + " add without active tradelist:" + _tradeId);
return;
}
final L2PcInstance partner = trade.getPartner();
if ((partner == null) || (L2World.getInstance().getPlayer(partner.getObjectId()) == null) || (partner.getActiveTradeList() == null))
{
// Trade partner not found, cancel trade
if (partner != null)
{
_log.warning("Character:" + player.getName() + " requested invalid trade object: " + _objectId);
}
player.sendPacket(SystemMessageId.<API key>);
player.cancelActiveTrade();
return;
}
if (trade.isConfirmed() || partner.getActiveTradeList().isConfirmed())
{
player.sendPacket(SystemMessageId.<API key>);
return;
}
if (!player.getAccessLevel().allowTransaction())
{
player.sendMessage("Transactions are disabled for your Access Level.");
player.cancelActiveTrade();
return;
}
if (!player.<API key>(_objectId, "trade"))
{
player.sendPacket(SystemMessageId.NOTHING_HAPPENED);
return;
}
final TradeItem item = trade.addItem(_objectId, _count);
if (item != null)
{
player.sendPacket(new TradeOwnAdd(item));
player.sendPacket(new TradeUpdate(player, item));
partner.sendPacket(new TradeOtherAdd(item));
}
}
} |
<?php
function is_ext($name, $err='ERROR') {
if (extension_loaded($name)) {
echo 'OK';
} else {
echo $err;
}
}
?>
<html>
<head>
<title>Ready for install Framzod</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
background-color: #ECEFF1;
}
h1 {
width: 100%;
text-align: center;
background-color: #607D8B;
color: white;
border-bottom: 2px solid #263238;
margin-bottom: 20px;
}
h2 {
width: 100%;
text-align: center;
background-color: #78909C;
color: white;
border-bottom: 2px solid #37474F;
margin-bottom: 0px;
}
h3 {
width: calc(100% - 30px);
padding-left: 30px;
text-align: left;
background-color: #B0BEC5;
color: black;
margin-bottom: 0px;
}
.explain {
width: 60%;
margin-right: auto;
margin-left: auto;
background-color: white;
border: 1px solid #546E7A;
box-shadow: 2px 2px 2px #546E7A;
margin-top: 10px;
margin-bottom: 10px;
padding: 10px;
}
</style>
</head>
<body>
<h1>Welcome to Framzod Framework</h1>
<h2>Requierements</h2>
<div class="explain">
[<?php is_ext('mcrypt'); ?>] MCRYPT extention<br />
[<?php is_ext('mysqli', 'WARN'); ?>] MYSQLI extention (optionnal)<br />
[<?php is_ext('pgsql', 'WARN'); ?>] PGSQL extention (optionnal)<br />
</div>
<h2>Configuration.</h2>
<div class="explain">
<?php
if (file_exists('config.php')) {
?>
[OK] The configuration is ready
<?php
} else {
?>
[ERROR] You need to copy config.inc.php to config.php and edit for your convenience.
<?php
}
?>
</div>
<h2>Serveur configuration</h2>
<h3>Apache configuration</h3>
<div class="explain">
Rewrite mod need to be enable. <br />
After, you need to create (or add in existant) an htaccess file with rewrites rules: <br />
<pre>
rewrite ^/(.+\..+)$ /$1 last;
rewrite ^/(.*)/(.*)$ /index.php?class=$1&method=$2 last;
rewrite ^/(.+)$ /index.php?class=$1 last;
</pre>
</div>
<h3>Nginx configuration</h3>
<div class="explain">
Add the rewrites rules in your site configuration :
<pre>
rewrite ^/$ /main.php last;
rewrite ^/(.+\..+)$ /$1 last;
rewrite ^/(.*)/(.*)$ /main.php?class=$1&method=$2 last;
rewrite ^/(.+)$ /main.php?class=$1 last;
</pre>
</div>
</body>
</html> |
<?php
/**
* Koken cache warmup script.
*
* @author Sylvain Deloux <github@eax.fr>
* @author Georg Peters <georg90@github>
*/
if ('cli' !== php_sapi_name()) {
exit;
}
/**
* Custom configuration goes here
*/
// Root dir of your Koken installation (contains i.php)
$rootDir = dirname('html');
// List of Koken internal images formats names
$formats = array('tiny', 'tiny.2x', 'small', 'small.2x', 'medium', 'medium.2x', 'medium_large', 'medium_large.2x', 'large', 'large.2x', 'xlarge', 'xlarge.2x', 'huge', 'huge.2x');
$publicURL = 'http://neil.panchal.io'; // can also be 127.0.0.1 if you have configured apache etc. accordingly
/**
* End of configuration
*/
$storageDir = sprintf('%s%sstorage%s', $rootDir, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR);
$configDir = sprintf('%s%sconfiguration%s', $storageDir, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR);
$cachePath = sprintf('%s/i.php?', $publicURL);
$databaseConfigFile = sprintf('%sdatabase.php', $configDir);
if (!file_exists($databaseConfigFile)) {
printf("ERROR: Unable to find %s database config file. Make sure the Koken root dir is correctly configured.\n", $databaseConfig);
exit(1);
}
$KOKEN_DATABASE = require($databaseConfigFile);
try {
$pdo = new PDO(sprintf('mysql:dbname=%s;host=%s', $KOKEN_DATABASE['database'], $KOKEN_DATABASE['hostname']), $KOKEN_DATABASE['username'], $KOKEN_DATABASE['password']);
} catch (PDOException $e) {
printf("ERROR: Unable to access database (%s).\n", $e->getMessage());
exit(1);
}
$imageQueryStatement = $pdo->prepare(sprintf('SELECT * FROM %scontent', $KOKEN_DATABASE['prefix']));
$images = $imageQueryStatement->execute();
$imagesCount = $imageQueryStatement->rowCount();
if (0 === $imagesCount) {
printf("No content found, exiting\n");
exit(0);
}
$urlCount = $imagesCount * count($formats);
echo "\n";
echo "
echo "\n";
printf("Photos found : %d\n", $imagesCount);
printf("URLs to call : %d\n", $urlCount);
echo "\n";
echo "This script may be long to execute, depending on your content count.\n";
echo "\n";
echo "
echo "\n";
$i = 0;
while ($image = $imageQueryStatement->fetch(PDO::FETCH_ASSOC)) {
$identifier = str_pad($image['id'], 6, 0, STR_PAD_LEFT);
$parts = str_split($identifier, 3);
list($fileBasename, $fileExtension) = explode('.', $image['filename']);
printf("%5.1f%% - %s ", $i * 100 / $imagesCount, $fileBasename);
foreach ($formats as $format) {
$url = sprintf('%s/%s/%s/%s,%s.%d.%s', $cachePath, $parts[0], $parts[1], $fileBasename, $format, $image['file_modified_on'], $fileExtension);
printf($format);
printf("|");
$curl = curl_init($url);
//curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, <API key>, true);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, <API key>, false); // ifnore SSL errors
curl_setopt($curl, <API key>, false); // ignore SSL errors
$curlReturn = curl_exec($curl);
curl_close($curl);
// echo '.';
}
echo "\n";
$i++;
} |
package com.shumz.think.ex004;
public class ExFour19 {
public void stringImporter(String... args) {
for (int i = 0; i < args.length; i++) {
System.out.println(i + "). " + args[i]);
}
}
public static void main(String[] args) {
ExFour19 object = new ExFour19();
object.stringImporter("qwerty", "asdfgh", "zxcvbn");
System.out.println();
System.out.println();
String[] str_array = new String[] { "qwe", "asd", "zxc" };
object.stringImporter(str_array);
}
} |
package org.cloudsimplus.hostfaultinjection;
import java.util.*;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import org.cloudsimplus.testbeds.ExperimentRunner;
import javax.swing.text.html.HTMLDocument;
/**
* * Runs the {@link <API key>} the number of
* times defines by {@link #getSimulationRuns()} and compute statistics.
*
* @author raysaoliveira
*/
class <API key> extends ExperimentRunner<<API key>> {
/**
* Different lengths that will be randomly assigned to created Cloudlets.
*/
static final long[] CLOUDLET_LENGTHS = {10000_000_000L, 9800_00_000L, 990000_000L};
static final int CLOUDLETS = 12;
/**
* Datacenter availability for each experiment.
*/
private List<Double> availability;
/**
* The percentage of brokers meeting Availability average for all the
* experiments.
*/
private List<Double> <API key>;
/**
* Average number of VMs for each existing Host.
*/
private List<Double> ratioVmsPerHost;
/**
* The percentage of brokers meeting Cost average for all the
* experiments.
*/
private List<Double> <API key>;
/**
* Indicates if each experiment will output execution logs or not.
*/
private final boolean experimentVerbose = false;
/**
* Starts the execution of the experiments the number of times defines in
* {@link #getSimulationRuns()}.
*
* @param args command line arguments
*/
public static void main(String[] args) {
new <API key>(true, 1475098589732L)
.setSimulationRuns(10)
.setNumberOfBatches(5) //Comment this or set to 0 to disable the "Batch Means Method"
.setVerbose(true)
.run();
}
<API key>(final boolean <API key>, final long baseSeed) {
super(<API key>, baseSeed);
availability = new ArrayList<>();
<API key> = new ArrayList<>();
ratioVmsPerHost = new ArrayList<>();
<API key> = new ArrayList<>();
}
@Override
protected <API key> createExperiment(int i) {
<API key> exp = new <API key>(i, this);
exp.setVerbose(experimentVerbose)
.<API key>(this::<API key>);
return exp;
}
/**
* Method automatically called after every experiment finishes running. It
* performs some post-processing such as collection of data for statistic
* analysis.
*
* @param exp the finished experiment
*/
private void <API key>(<API key> exp) {
availability.add(exp.getFaultInjection().availability() * 100);
<API key>.add(exp.<API key>() * 100);
ratioVmsPerHost.add(exp.getRatioVmsPerHost());
<API key>.add(exp.<API key>() * 100);
}
@Override
protected void setup() {}
@Override
protected Map<String, List<Double>> createMetricsMap() {
Map<String, List<Double>> map = new HashMap<>();
map.put("Average of Total Availability of Simulation", availability);
map.put("Percentagem of brokers meeting the Availability: ", <API key>);
map.put("VMs/Hosts Ratio: ", ratioVmsPerHost);
map.put("Percentagem of brokers meeting the Cost: ", <API key>);
return map;
}
@Override
protected void <API key>() {
System.out.printf("Executing %d experiments. Please wait ... It may take a while.\n", getSimulationRuns());
System.out.println("Experiments configurations:");
System.out.printf("\tBase seed: %d | Number of Cloudlets: %d\n", getBaseSeed(), CLOUDLETS);
System.out.printf("\tApply Antithetic Variates Technique: %b\n", <API key>());
if (<API key>()) {
System.out.println("\tApply Batch Means Method to reduce simulation results correlation: true");
System.out.printf("\tNumber of Batches for Batch Means Method: %d", getNumberOfBatches());
System.out.printf("\tBatch Size: %d\n", batchSizeCeil());
}
System.out.printf("\nSimulated Annealing Parameters\n");
}
@Override
protected void printFinalResults(String metricName, SummaryStatistics stats) {
System.out.printf("\n# %s for %d simulation runs\n", metricName, getSimulationRuns());
if (!<API key>()) {
System.out.println("\tBatch means method was not be applied because the number of simulation runs is not greater than the number of batches.");
}
if (getSimulationRuns() > 1) {
<API key>(stats);
}
}
private void <API key>(SummaryStatistics stats) {
// Calculate 95% confidence interval
double intervalSize = <API key>(stats, 0.95);
double lower = stats.getMean() - intervalSize;
double upper = stats.getMean() + intervalSize;
System.out.printf(
"\t This METRIC mean 95%% Confidence Interval: %.4f ∓ %.4f, that is [%.4f to %.4f]\n",
stats.getMean(), intervalSize, lower, upper);
System.out.printf("\tStandard Deviation: %.4f \n", stats.<API key>());
}
} |
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
@file AP_Mission.cpp
@brief Handles the MAVLINK command mission stack. Reads and writes mission to storage.
#include "AP_Mission.h"
#include <AP_Terrain/AP_Terrain.h>
const AP_Param::GroupInfo AP_Mission::var_info[] PROGMEM = {
// @Param: TOTAL
// @DisplayName: Total mission commands
// @Description: The number of mission mission items that has been loaded by the ground station. Do not change this manually.
// @Range: 0 32766
// @Increment: 1
// @User: Advanced
AP_GROUPINFO("TOTAL", 0, AP_Mission, _cmd_total, 0),
// @Param: RESTART
// @DisplayName: Mission Restart when entering Auto mode
// @Description: Controls mission starting point when entering Auto mode (either restart from beginning of mission or resume from last command run)
// @Values: 0:Resume Mission, 1:Restart Mission
AP_GROUPINFO("RESTART", 1, AP_Mission, _restart, <API key>),
AP_GROUPEND
};
extern const AP_HAL::HAL& hal;
// storage object
StorageAccess AP_Mission::_storage(StorageManager::StorageMission);
public mission methods
init - initialises this library including checks the version in eeprom matches this library
void AP_Mission::init()
{
// <API key> - checks version of missions stored in eeprom matches this library
// command list will be cleared if they do not match
<API key>();
// prevent an easy programming error, this will be optimised out
if (sizeof(union Content) != 12) {
hal.scheduler->panic(PSTR("AP_Mission Content must be 12 bytes"));
}
<API key> = hal.scheduler->millis();
}
start - resets current commands to point to the beginning of the mission
To-Do: should we validate the mission first and return true/false?
void AP_Mission::start()
{
_flags.state = MISSION_RUNNING;
reset(); // reset mission to the first command, resets jump tracking
// advance to the first command
if (!<API key>()) {
// on failure set mission complete
complete();
}
}
stop - stops mission execution. subsequent calls to update() will have no effect until the mission is started or resumed
void AP_Mission::stop()
{
_flags.state = MISSION_STOPPED;
}
resume - continues the mission execution from where we last left off
previous running commands will be re-initialised
void AP_Mission::resume()
{
// if mission had completed then start it from the first command
if (_flags.state == MISSION_COMPLETE) {
start();
return;
}
// if mission had stopped then restart it
if (_flags.state == MISSION_STOPPED) {
_flags.state = MISSION_RUNNING;
// if no valid nav command index restart from beginning
if (_nav_cmd.index == <API key>) {
start();
return;
}
}
// ensure cache coherence
// don't bother checking if the read is successful. If it fails _nav_cmd
// won't change and we'll continue flying the old cached command.
<API key>(_nav_cmd.index, _nav_cmd);
// restart active navigation command. We run these on resume()
// regardless of whether the mission was stopped, as we may be
// re-entering AUTO mode and the nav_cmd callback needs to be run
// to setup the current target waypoint
// Note: if there is no active command then the mission must have been stopped just after the previous nav command completed
// update will take care of finding and starting the nav command
if (_flags.nav_cmd_loaded) {
_cmd_start_fn(_nav_cmd);
}
// restart active do command
if (_flags.do_cmd_loaded && _do_cmd.index != <API key>) {
_cmd_start_fn(_do_cmd);
}
}
start_or_resume - if MIS_AUTORESTART=0 this will call resume(), otherwise it will call start()
void AP_Mission::start_or_resume()
{
if (_restart) {
start();
} else {
resume();
}
}
reset - reset mission to the first command
void AP_Mission::reset()
{
_flags.nav_cmd_loaded = false;
_flags.do_cmd_loaded = false;
_flags.do_cmd_all_done = false;
_nav_cmd.index = <API key>;
_do_cmd.index = <API key>;
_prev_nav_cmd_index = <API key>;
<API key> = <API key>;
init_jump_tracking();
}
clear - clears out mission
returns true if mission was running so it could not be cleared
bool AP_Mission::clear()
{
// do not allow clearing the mission while it is running
if (_flags.state == MISSION_RUNNING) {
return false;
}
// remove all commands
_cmd_total.set_and_save(0);
// clear index to commands
_nav_cmd.index = <API key>;
_do_cmd.index = <API key>;
_flags.nav_cmd_loaded = false;
_flags.do_cmd_loaded = false;
// return success
return true;
}
trucate - truncate any mission items beyond index
void AP_Mission::truncate(uint16_t index)
{
if ((unsigned)_cmd_total > index) {
_cmd_total.set_and_save(index);
}
}
update - ensures the command queues are loaded with the next command and calls main programs command_init and command_verify functions to progress the mission
should be called at 10hz or higher
void AP_Mission::update()
{
// exit immediately if not running or no mission commands
if (_flags.state != MISSION_RUNNING || _cmd_total == 0) {
return;
}
// check if we have an active nav command
if (!_flags.nav_cmd_loaded || _nav_cmd.index == <API key>) {
// advance in mission if no active nav command
if (!<API key>()) {
// failure to advance nav command means mission has completed
complete();
return;
}
}else{
// run the active nav command
if (_cmd_verify_fn(_nav_cmd)) {
// market _nav_cmd as complete (it will be started on the next iteration)
_flags.nav_cmd_loaded = false;
// immediately advance to the next mission command
if (!<API key>()) {
// failure to advance nav command means mission has completed
complete();
return;
}
}
}
// check if we have an active do command
if (!_flags.do_cmd_loaded) {
<API key>();
}else{
// run the active do command
if (_cmd_verify_fn(_do_cmd)) {
// market _nav_cmd as complete (it will be started on the next iteration)
_flags.do_cmd_loaded = false;
}
}
}
public command methods
add_cmd - adds a command to the end of the command list and writes to storage
returns true if successfully added, false on failure
cmd.index is updated with it's new position in the mission
bool AP_Mission::add_cmd(Mission_Command& cmd)
{
// attempt to write the command to storage
bool ret = <API key>(_cmd_total, cmd);
if (ret) {
// update command's index
cmd.index = _cmd_total;
// increment total number of commands
_cmd_total.set_and_save(_cmd_total + 1);
}
return ret;
}
replace_cmd - replaces the command at position 'index' in the command list with the provided cmd
replacing the current active command will have no effect until the command is restarted
returns true if successfully replaced, false on failure
bool AP_Mission::replace_cmd(uint16_t index, Mission_Command& cmd)
{
// sanity check index
if (index >= (unsigned)_cmd_total) {
return false;
}
// attempt to write the command to storage
return <API key>(index, cmd);
}
is_nav_cmd - returns true if the command's id is a "navigation" command, false if "do" or "conditional" command
bool AP_Mission::is_nav_cmd(const Mission_Command& cmd)
{
return (cmd.id <= MAV_CMD_NAV_LAST);
}
int16_t AP_Mission::<API key>()
{
// Get the number of commands for the current mission
int16_t num_cmd = num_commands();
// Stores the current cmd item
AP_Mission::Mission_Command current_cmd;
// Start iterating from the end of the mission
for(int16_t i=num_cmd-1; i>=0; i
{
get_next_nav_cmd(i, current_cmd);
// If the current command is a NAV command
if(current_cmd.id == MAV_CMD_NAV_LAND)
return current_cmd.index;
}
// If I ended the for loop and the return value is -1, it means that the current mission has no
// landing waypoints.
return -1;
}
int16_t AP_Mission::<API key>()
{
// Get the number of commands for the current mission
int16_t num_cmd = num_commands();
// Stores the current cmd item
AP_Mission::Mission_Command current_cmd;
// Start iterating from the end of the mission, looking for the n-th last DO_NAV waypoint.
for(int16_t i=num_cmd-1; i>=0; i
{
get_next_nav_cmd(i, current_cmd);
// If the current command is a NAV command
if(current_cmd.id == <API key>)
return current_cmd.index;
}
// If I ended the for loop and the return value is -1, it means that the current mission has no
// navigation waypoints.
return -1;
}
This function calculates the position of the cmd item after which generating the virtual waypoints.
int16_t AP_Mission::<API key>(int16_t n)
{
// Get the number of commands for the current mission
int16_t num_cmd = num_commands();
// Stores the current cmd item
AP_Mission::Mission_Command next_cmd;
// Current number of NAV commands found
int16_t <API key> = 0;
// Start iterating from the end of the mission, looking for the n-th last DO_NAV waypoint.
for(int16_t i=num_cmd-1; i>=0; i
{
get_next_nav_cmd(i, next_cmd);
// If the current command is a NAV command
if(next_cmd.id == <API key>)
++<API key>;
// When I reach the n-th DO_NAV command, I get out the loop
if(<API key> == (n+1))
return next_cmd.index;
}
// If I ended the for loop and the return value is zero, it means that
// the current mission has up to 2 mission waypoints. It's not common but
// it can happen.
return (int16_t)0;
}
get_next_nav_cmd - gets next "navigation" command found at or after start_index
returns true if found, false if not found (i.e. reached end of mission command list)
accounts for do_jump commands but never increments the jump's num_times_run (<API key> is responsible for this)
bool AP_Mission::get_next_nav_cmd(uint16_t start_index, Mission_Command& cmd)
{
uint16_t cmd_index = start_index;
// search until the end of the mission command list
while(cmd_index < (unsigned)_cmd_total) {
// get next command
if (!get_next_cmd(cmd_index, cmd, false)) {
// no more commands so return failure
return false;
}else{
// if found a "navigation" command then return it
if (is_nav_cmd(cmd)) {
return true;
}else{
// move on in list
cmd_index++;
}
}
}
// if we got this far we did not find a navigation command
return false;
}
get the ground course of the next navigation leg in centidegrees
from 0 36000. Return default_angle if next navigation
leg cannot be determined
int32_t AP_Mission::<API key>(int32_t default_angle)
{
Mission_Command cmd;
if (!get_next_nav_cmd(_nav_cmd.index+1, cmd)) {
return default_angle;
}
return get_bearing_cd(_nav_cmd.content.location, cmd.content.location);
}
// set_current_cmd - jumps to command specified by index
bool AP_Mission::set_current_cmd(uint16_t index)
{
Mission_Command cmd;
// sanity check index and that we have a mission
if (index >= (unsigned)_cmd_total || _cmd_total == 1) {
return false;
}
// stop the current running do command
_do_cmd.index = <API key>;
_flags.do_cmd_loaded = false;
_flags.do_cmd_all_done = false;
// stop current nav cmd
_flags.nav_cmd_loaded = false;
// if index is zero then the user wants to completely restart the mission
if (index == 0 || _flags.state == MISSION_COMPLETE) {
_prev_nav_cmd_index = <API key>;
<API key> = <API key>;
// reset the jump tracking to zero
init_jump_tracking();
if (index == 0) {
index = 1;
}
}
// if the mission is stopped or completed move the nav_cmd index to the specified point and set the state to stopped
// so that if the user resumes the mission it will begin at the specified index
if (_flags.state != MISSION_RUNNING) {
// search until we find next nav command or reach end of command list
while (!_flags.nav_cmd_loaded) {
// get next command
if (!get_next_cmd(index, cmd, true)) {
_nav_cmd.index = <API key>;
return false;
}
// check if navigation or "do" command
if (is_nav_cmd(cmd)) {
// set current navigation command
_nav_cmd = cmd;
_flags.nav_cmd_loaded = true;
}else{
// set current do command
if (!_flags.do_cmd_loaded) {
_do_cmd = cmd;
_flags.do_cmd_loaded = true;
}
}
// move onto next command
index = cmd.index+1;
}
// if we have not found a do command then set flag to show there are no do-commands to be run before nav command completes
if (!_flags.do_cmd_loaded) {
_flags.do_cmd_all_done = true;
}
// if we got this far then the mission can safely be "resumed" from the specified index so we set the state to "stopped"
_flags.state = MISSION_STOPPED;
return true;
}
// the state must be MISSION_RUNNING
// search until we find next nav command or reach end of command list
while (!_flags.nav_cmd_loaded) {
// get next command
if (!get_next_cmd(index, cmd, true)) {
// if we run out of nav commands mark mission as complete
complete();
// return true because we did what was requested
// which was apparently to jump to a command at the end of the mission
return true;
}
// check if navigation or "do" command
if (is_nav_cmd(cmd)) {
// save previous nav command index
_prev_nav_cmd_index = _nav_cmd.index;
// save separate previous nav command index if it contains lat,long,alt
if (!(cmd.content.location.lat == 0 && cmd.content.location.lng == 0)) {
<API key> = _nav_cmd.index;
}
// set current navigation command and start it
_nav_cmd = cmd;
_flags.nav_cmd_loaded = true;
_cmd_start_fn(_nav_cmd);
}else{
// set current do command and start it (if not already set)
if (!_flags.do_cmd_loaded) {
_do_cmd = cmd;
_flags.do_cmd_loaded = true;
_cmd_start_fn(_do_cmd);
}
}
// move onto next command
index = cmd.index+1;
}
// if we have not found a do command then set flag to show there are no do-commands to be run before nav command completes
if (!_flags.do_cmd_loaded) {
_flags.do_cmd_all_done = true;
}
// if we got this far we must have successfully advanced the nav command
return true;
}
<API key> - load command from storage
true is return if successful
bool AP_Mission::<API key>(uint16_t index, Mission_Command& cmd) const
{
// exit immediately if index is beyond last command but we always let cmd #0 (i.e. home) be read
if (index > (unsigned)_cmd_total && index != 0) {
return false;
}
// special handling for command #0 which is home
if (index == 0) {
cmd.index = 0;
cmd.id = <API key>;
cmd.p1 = 0;
cmd.content.location = _ahrs.get_home();
}else{
// Find out proper location in memory by using the start_byte position + the index
// we can load a command, we don't process it yet
// read WP position
uint16_t pos_in_storage = 4 + (index * <API key>);
cmd.id = _storage.read_byte(pos_in_storage);
cmd.p1 = _storage.read_uint16(pos_in_storage+1);
_storage.read_block(cmd.content.bytes, pos_in_storage+3, 12);
// set command's index to it's position in eeprom
cmd.index = index;
}
// return success
return true;
}
<API key> - write a command to storage
index is used to calculate the storage location
true is returned if successful
bool AP_Mission::<API key>(uint16_t index, Mission_Command& cmd)
{
// range check cmd's index
if (index >= num_commands_max()) {
return false;
}
// calculate where in storage the command should be placed
uint16_t pos_in_storage = 4 + (index * <API key>);
_storage.write_byte(pos_in_storage, cmd.id);
_storage.write_uint16(pos_in_storage+1, cmd.p1);
_storage.write_block(pos_in_storage+3, cmd.content.bytes, 12);
// remember when the mission last changed
<API key> = hal.scheduler->millis();
// return success
return true;
}
<API key> - writes the special purpose cmd 0 (home) to storage
home is taken directly from ahrs
void AP_Mission::<API key>()
{
Mission_Command home_cmd = {};
home_cmd.id = <API key>;
home_cmd.content.location = _ahrs.get_home();
<API key>(0,home_cmd);
}
// <API key> - converts mavlink message to an AP_Mission::Mission_Command object which can be stored to eeprom
// return true on success, false on failure
bool AP_Mission::<API key>(const <API key>& packet, AP_Mission::Mission_Command& cmd)
{
bool copy_location = false;
bool copy_alt = false;
uint8_t num_turns, radius_m; // used by <API key> & _TO_ALT
uint8_t heading_req; // used by <API key>
// command's position in mission list and mavlink id
cmd.index = packet.seq;
cmd.id = packet.command;
cmd.content.location.options = 0;
// command specific conversions from mavlink packet to mission command
switch (cmd.id) {
case <API key>: // MAV ID: 16
copy_location = true;
/*
the 15 byte limit means we can't fit both delay and radius
in the cmd structure. When we expand the mission structure
we can do this properly
*/
#if APM_BUILD_TYPE(APM_BUILD_ArduPlane)
// acceptance radius in meters
cmd.p1 = packet.param2;
#else
// delay at waypoint in seconds
cmd.p1 = packet.param1;
#endif
break;
case <API key>: // MAV ID: 17
copy_location = true;
cmd.content.location.flags.loiter_ccw = (packet.param3 < 0); // -1 = counter clockwise, +1 = clockwise
break;
case <API key>: // MAV ID: 18
copy_location = true;
num_turns = packet.param1; // number of times to circle is held in param1
radius_m = fabsf(packet.param3); // radius in meters is held in high in param3
cmd.p1 = (((uint16_t)radius_m)<<8) | (uint16_t)num_turns; // store radius in high byte of p1, num turns in low byte of p1
cmd.content.location.flags.loiter_ccw = (packet.param3 < 0);
break;
case <API key>: // MAV ID: 19
copy_location = true;
cmd.p1 = packet.param1; // loiter time in seconds
cmd.content.location.flags.loiter_ccw = (packet.param3 < 0);
break;
case <API key>: // MAV ID: 20
copy_location = true;
break;
case MAV_CMD_NAV_LAND: // MAV ID: 21
copy_location = true;
cmd.p1 = packet.param1; // abort target altitude(m) (plane only)
break;
case MAV_CMD_NAV_TAKEOFF: // MAV ID: 22
copy_location = true; // only altitude is used
cmd.p1 = packet.param1; // minimum pitch (plane only)
break;
case <API key>: // MAV ID: 30
copy_location = true; // lat/lng used for heading lock
cmd.p1 = packet.param1; // Climb/Descend
// 0 = Neutral, cmd complete at +/- 5 of indicated alt.
// 1 = Climb, cmd complete at or above indicated alt.
// 2 = Descend, cmd complete at or below indicated alt.
break;
case <API key>: // MAV ID: 31
copy_location = true;
heading_req = packet.param1; //heading towards next waypoint required (0 = False)
cmd.content.location.flags.loiter_ccw = (packet.param2 < 0);
//Don't give users the impression I can set the radius size.
//I can only set the direction at this time and so can every
//other command, despite what is implied (I'm looking at YOU
//NAV_LOITER_TURNS):
radius_m = 1;
cmd.p1 = (((uint16_t)radius_m)<<8) | (uint16_t)heading_req; // store "radius" in high byte of p1, heading_req in low byte of p1
break;
case <API key>: // MAV ID: 82
copy_location = true;
cmd.p1 = packet.param1; // delay at waypoint in seconds
break;
case <API key>: // MAV ID: 92
cmd.p1 = packet.param1; // on/off. >0.5 means "on", hand-over control to external controller
break;
case <API key>: // MAV ID: 112
cmd.content.delay.seconds = packet.param1; // delay in seconds
break;
case <API key>: // MAV ID: 113
copy_alt = true; // only altitude is used
cmd.content.location.lat = packet.param1 * 100; // climb/descent converted from m/s to cm/s. To-Do: store in proper climb_rate structure
break;
case <API key>: // MAV ID: 114
cmd.content.distance.meters = packet.param1; // distance in meters from next waypoint
break;
case <API key>: // MAV ID: 115
cmd.content.yaw.angle_deg = packet.param1; // target angle in degrees
cmd.content.yaw.turn_rate_dps = packet.param2; // 0 = use default turn rate otherwise specific turn rate in deg/sec
cmd.content.yaw.direction = packet.param3; // -1 = ccw, +1 = cw
cmd.content.yaw.relative_angle = packet.param4; // lng=0: absolute angle provided, lng=1: relative angle provided
break;
case MAV_CMD_DO_SET_MODE: // MAV ID: 176
cmd.p1 = packet.param1; // flight mode identifier
break;
case MAV_CMD_DO_JUMP: // MAV ID: 177
cmd.content.jump.target = packet.param1; // jump-to command number
cmd.content.jump.num_times = packet.param2; // repeat count
break;
case <API key>: // MAV ID: 178
cmd.content.speed.speed_type = packet.param1; // 0 = airspeed, 1 = ground speed
cmd.content.speed.target_ms = packet.param2; // target speed in m/s
cmd.content.speed.throttle_pct = packet.param3; // throttle as a percentage from 0 ~ 100%
break;
case MAV_CMD_DO_SET_HOME:
copy_location = true;
cmd.p1 = packet.param1; // p1=0 means use current location, p=1 means use provided location
break;
case <API key>: // MAV ID: 180
cmd.p1 = packet.param1; // parameter number
cmd.content.location.alt = packet.param2; // parameter value
break;
case <API key>: // MAV ID: 181
cmd.content.relay.num = packet.param1; // relay number
cmd.content.relay.state = packet.param2; // 0:off, 1:on
break;
case <API key>: // MAV ID: 182
cmd.content.repeat_relay.num = packet.param1; // relay number
cmd.content.repeat_relay.repeat_count = packet.param2; // count
cmd.content.repeat_relay.cycle_time = packet.param3; // time converted from seconds to milliseconds
break;
case <API key>: // MAV ID: 183
cmd.content.servo.channel = packet.param1; // channel
cmd.content.servo.pwm = packet.param2; // PWM
break;
case <API key>: // MAV ID: 184
cmd.content.repeat_servo.channel = packet.param1; // channel
cmd.content.repeat_servo.pwm = packet.param2; // PWM
cmd.content.repeat_servo.repeat_count = packet.param3; // count
cmd.content.repeat_servo.cycle_time = packet.param4; // time in seconds
break;
case <API key>: // MAV ID: 189
copy_location = true;
break;
case MAV_CMD_DO_SET_ROI: // MAV ID: 201
copy_location = true;
cmd.p1 = packet.param1; // 0 = no roi, 1 = next waypoint, 2 = waypoint number, 3 = fixed location, 4 = given target (not supported)
break;
case <API key>: // MAV ID: 202
cmd.content.digicam_configure.shooting_mode = packet.param1;
cmd.content.digicam_configure.shutter_speed = packet.param2;
cmd.content.digicam_configure.aperture = packet.param3;
cmd.content.digicam_configure.ISO = packet.param4;
cmd.content.digicam_configure.exposure_type = packet.x;
cmd.content.digicam_configure.cmd_id = packet.y;
cmd.content.digicam_configure.engine_cutoff_time = packet.z;
break;
case <API key>: // MAV ID: 203
cmd.content.digicam_control.session = packet.param1;
cmd.content.digicam_control.zoom_pos = packet.param2;
cmd.content.digicam_control.zoom_step = packet.param3;
cmd.content.digicam_control.focus_lock = packet.param4;
cmd.content.digicam_control.shooting_cmd = packet.x;
cmd.content.digicam_control.cmd_id = packet.y;
break;
case <API key>: // MAV ID: 205
cmd.content.mount_control.pitch = packet.param1;
cmd.content.mount_control.roll = packet.param2;
cmd.content.mount_control.yaw = packet.param3;
break;
case <API key>: // MAV ID: 206
cmd.content.cam_trigg_dist.meters = packet.param1; // distance between camera shots in meters
break;
case <API key>: // MAV ID: 207
cmd.p1 = packet.param1; // action 0=disable, 1=enable
break;
case <API key>: // MAV ID: 208
cmd.p1 = packet.param1; // action 0=disable, 1=enable, 2=release. See PARACHUTE_ACTION enum
break;
case <API key>: // MAV ID: 210
cmd.p1 = packet.param1; // normal=0 inverted=1
break;
case MAV_CMD_DO_GRIPPER: // MAV ID: 211
cmd.content.gripper.num = packet.param1; // gripper number
cmd.content.gripper.action = packet.param2; // action 0=release, 1=grab. See GRIPPER_ACTION enum
break;
case <API key>: // MAV ID: 222
cmd.p1 = packet.param1; // max time in seconds the external controller will be allowed to control the vehicle
cmd.content.guided_limits.alt_min = packet.param2; // min alt below which the command will be aborted. 0 for no lower alt limit
cmd.content.guided_limits.alt_max = packet.param3; // max alt above which the command will be aborted. 0 for no upper alt limit
cmd.content.guided_limits.horiz_max = packet.param4;// max horizontal distance the vehicle can move before the command will be aborted. 0 for no horizontal limit
break;
case <API key>: // MAV ID: 211
cmd.p1 = packet.param1; // disable=0 enable=1
break;
case <API key>: // MAV ID: 83
cmd.content.altitude_wait.altitude = packet.param1;
cmd.content.altitude_wait.descent_rate = packet.param2;
cmd.content.altitude_wait.wiggle_time = packet.param3;
break;
default:
// unrecognised command
return false;
}
// copy location from mavlink to command
if (copy_location || copy_alt) {
// sanity check location
if (copy_location) {
if (fabsf(packet.x) > 90.0f || fabsf(packet.y) > 180.0f) {
return false;
}
}
switch (packet.frame) {
case MAV_FRAME_MISSION:
case MAV_FRAME_GLOBAL:
if (copy_location) {
cmd.content.location.lat = 1.0e7f * packet.x; // floating point latitude to int32_t
cmd.content.location.lng = 1.0e7f * packet.y; // floating point longitude to int32_t
}
cmd.content.location.alt = packet.z * 100.0f; // convert packet's alt (m) to cmd alt (cm)
cmd.content.location.flags.relative_alt = 0;
break;
case <API key>:
if (copy_location) {
cmd.content.location.lat = 1.0e7f * packet.x; // floating point latitude to int32_t
cmd.content.location.lng = 1.0e7f * packet.y; // floating point longitude to int32_t
}
cmd.content.location.alt = packet.z * 100.0f; // convert packet's alt (m) to cmd alt (cm)
cmd.content.location.flags.relative_alt = 1;
break;
#ifdef MAV_FRAME_LOCAL_NED
case MAV_FRAME_LOCAL_NED: // local (relative to home position)
if (copy_location) {
cmd.content.location.lat = 1.0e7f*ToDeg(packet.x/
(RADIUS_OF_EARTH*cosf(ToRad(home.lat/1.0e7f)))) + _ahrs.get_home().lat;
cmd.content.location.lng = 1.0e7f*ToDeg(packet.y/RADIUS_OF_EARTH) + _ahrs.get_home().lng;
}
cmd.content.location.alt = -packet.z*1.0e2f;
cmd.content.location.flags.relative_alt = 1;
break;
#endif
#ifdef MAV_FRAME_LOCAL
case MAV_FRAME_LOCAL: // local (relative to home position)
if (copy_location) {
cmd.content.location.lat = 1.0e7f*ToDeg(packet.x/
(RADIUS_OF_EARTH*cosf(ToRad(home.lat/1.0e7f)))) + _ahrs.get_home().lat;
cmd.content.location.lng = 1.0e7f*ToDeg(packet.y/RADIUS_OF_EARTH) + _ahrs.get_home().lng;
}
cmd.content.location.alt = packet.z*1.0e2f;
cmd.content.location.flags.relative_alt = 1;
break;
#endif
#if <API key>
case <API key>:
if (copy_location) {
cmd.content.location.lat = 1.0e7f * packet.x; // floating point latitude to int32_t
cmd.content.location.lng = 1.0e7f * packet.y; // floating point longitude to int32_t
}
cmd.content.location.alt = packet.z * 100.0f; // convert packet's alt (m) to cmd alt (cm)
// we mark it as a relative altitude, as it doesn't have
// home alt added
cmd.content.location.flags.relative_alt = 1;
// mark altitude as above terrain, not above home
cmd.content.location.flags.terrain_alt = 1;
break;
#endif
default:
return false;
}
}
// if we got this far then it must have been succesful
return true;
}
// <API key> - converts an AP_Mission::Mission_Command object to a mavlink message which can be sent to the GCS
// return true on success, false on failure
bool AP_Mission::<API key>(const AP_Mission::Mission_Command& cmd, <API key>& packet)
{
bool copy_location = false;
bool copy_alt = false;
// command's position in mission list and mavlink id
packet.seq = cmd.index;
packet.command = cmd.id;
// set defaults
packet.current = 0; // 1 if we are passing back the mission command that is currently being executed
packet.param1 = 0;
packet.param2 = 0;
packet.param3 = 0;
packet.param4 = 0;
packet.autocontinue = 1;
// command specific conversions from mission command to mavlink packet
switch (cmd.id) {
case <API key>: // MAV ID: 16
copy_location = true;
#if APM_BUILD_TYPE(APM_BUILD_ArduPlane)
// acceptance radius in meters
packet.param2 = cmd.p1;
#else
// delay at waypoint in seconds
packet.param1 = cmd.p1;
#endif
break;
case <API key>: // MAV ID: 17
copy_location = true;
if (cmd.content.location.flags.loiter_ccw) {
packet.param3 = -1;
}else{
packet.param3 = 1;
}
break;
case <API key>: // MAV ID: 18
copy_location = true;
packet.param1 = LOWBYTE(cmd.p1); // number of times to circle is held in low byte of p1
packet.param3 = HIGHBYTE(cmd.p1); // radius is held in high byte of p1
if (cmd.content.location.flags.loiter_ccw) {
packet.param3 = -packet.param3;
}
break;
case <API key>: // MAV ID: 19
copy_location = true;
packet.param1 = cmd.p1; // loiter time in seconds
if (cmd.content.location.flags.loiter_ccw) {
packet.param3 = -1;
}else{
packet.param3 = 1;
}
break;
case <API key>: // MAV ID: 20
copy_location = true;
break;
case MAV_CMD_NAV_LAND: // MAV ID: 21
copy_location = true;
packet.param1 = cmd.p1; // abort target altitude(m) (plane only)
break;
case MAV_CMD_NAV_TAKEOFF: // MAV ID: 22
copy_location = true; // only altitude is used
packet.param1 = cmd.p1; // minimum pitch (plane only)
break;
case <API key>: // MAV ID: 30
copy_location = true; // lat/lng used for heading lock
packet.param1 = cmd.p1; // Climb/Descend
// 0 = Neutral, cmd complete at +/- 5 of indicated alt.
// 1 = Climb, cmd complete at or above indicated alt.
// 2 = Descend, cmd complete at or below indicated alt.
break;
case <API key>: // MAV ID: 31
copy_location = true;
packet.param1 = LOWBYTE(cmd.p1); //heading towards next waypoint required (0 = False)
packet.param2 = HIGHBYTE(cmd.p1); //loiter radius(m)
if (cmd.content.location.flags.loiter_ccw) {
packet.param2 = -packet.param2;
}
break;
case <API key>: // MAV ID: 82
copy_location = true;
packet.param1 = cmd.p1; // delay at waypoint in seconds
break;
case <API key>: // MAV ID: 92
packet.param1 = cmd.p1; // on/off. >0.5 means "on", hand-over control to external controller
break;
case <API key>: // MAV ID: 112
packet.param1 = cmd.content.delay.seconds; // delay in seconds
break;
case <API key>: // MAV ID: 113
copy_alt = true; // only altitude is used
packet.param1 = cmd.content.location.lat / 100.0f; // climb/descent rate converted from cm/s to m/s. To-Do: store in proper climb_rate structure
break;
case <API key>: // MAV ID: 114
packet.param1 = cmd.content.distance.meters; // distance in meters from next waypoint
break;
case <API key>: // MAV ID: 115
packet.param1 = cmd.content.yaw.angle_deg; // target angle in degrees
packet.param2 = cmd.content.yaw.turn_rate_dps; // 0 = use default turn rate otherwise specific turn rate in deg/sec
packet.param3 = cmd.content.yaw.direction; // -1 = ccw, +1 = cw
packet.param4 = cmd.content.yaw.relative_angle; // 0 = absolute angle provided, 1 = relative angle provided
break;
case MAV_CMD_DO_SET_MODE: // MAV ID: 176
packet.param1 = cmd.p1; // set flight mode identifier
break;
case MAV_CMD_DO_JUMP: // MAV ID: 177
packet.param1 = cmd.content.jump.target; // jump-to command number
packet.param2 = cmd.content.jump.num_times; // repeat count
break;
case <API key>: // MAV ID: 178
packet.param1 = cmd.content.speed.speed_type; // 0 = airspeed, 1 = ground speed
packet.param2 = cmd.content.speed.target_ms; // speed in m/s
packet.param3 = cmd.content.speed.throttle_pct; // throttle as a percentage from 0 ~ 100%
break;
case MAV_CMD_DO_SET_HOME: // MAV ID: 179
copy_location = true;
packet.param1 = cmd.p1; // p1=0 means use current location, p=1 means use provided location
break;
case <API key>: // MAV ID: 180
packet.param1 = cmd.p1; // parameter number
packet.param2 = cmd.content.location.alt; // parameter value
break;
case <API key>: // MAV ID: 181
packet.param1 = cmd.content.relay.num; // relay number
packet.param2 = cmd.content.relay.state; // 0:off, 1:on
break;
case <API key>: // MAV ID: 182
packet.param1 = cmd.content.repeat_relay.num; // relay number
packet.param2 = cmd.content.repeat_relay.repeat_count; // count
packet.param3 = cmd.content.repeat_relay.cycle_time; // time in seconds
break;
case <API key>: // MAV ID: 183
packet.param1 = cmd.content.servo.channel; // channel
packet.param2 = cmd.content.servo.pwm; // PWM
break;
case <API key>: // MAV ID: 184
packet.param1 = cmd.content.repeat_servo.channel; // channel
packet.param2 = cmd.content.repeat_servo.pwm; // PWM
packet.param3 = cmd.content.repeat_servo.repeat_count; // count
packet.param4 = cmd.content.repeat_servo.cycle_time; // time in milliseconds converted to seconds
break;
case <API key>: // MAV ID: 189
copy_location = true;
break;
case MAV_CMD_DO_SET_ROI: // MAV ID: 201
copy_location = true;
packet.param1 = cmd.p1; // 0 = no roi, 1 = next waypoint, 2 = waypoint number, 3 = fixed location, 4 = given target (not supported)
break;
case <API key>: // MAV ID: 202
packet.param1 = cmd.content.digicam_configure.shooting_mode;
packet.param2 = cmd.content.digicam_configure.shutter_speed;
packet.param3 = cmd.content.digicam_configure.aperture;
packet.param4 = cmd.content.digicam_configure.ISO;
packet.x = cmd.content.digicam_configure.exposure_type;
packet.y = cmd.content.digicam_configure.cmd_id;
packet.z = cmd.content.digicam_configure.engine_cutoff_time;
break;
case <API key>: // MAV ID: 203
packet.param1 = cmd.content.digicam_control.session;
packet.param2 = cmd.content.digicam_control.zoom_pos;
packet.param3 = cmd.content.digicam_control.zoom_step;
packet.param4 = cmd.content.digicam_control.focus_lock;
packet.x = cmd.content.digicam_control.shooting_cmd;
packet.y = cmd.content.digicam_control.cmd_id;
break;
case <API key>: // MAV ID: 205
packet.param1 = cmd.content.mount_control.pitch;
packet.param2 = cmd.content.mount_control.roll;
packet.param3 = cmd.content.mount_control.yaw;
break;
case <API key>: // MAV ID: 206
packet.param1 = cmd.content.cam_trigg_dist.meters; // distance between camera shots in meters
break;
case <API key>: // MAV ID: 207
packet.param1 = cmd.p1; // action 0=disable, 1=enable
break;
case <API key>: // MAV ID: 208
packet.param1 = cmd.p1; // action 0=disable, 1=enable, 2=release. See PARACHUTE_ACTION enum
break;
case <API key>: // MAV ID: 210
packet.param1 = cmd.p1; // normal=0 inverted=1
break;
case MAV_CMD_DO_GRIPPER: // MAV ID: 211
packet.param1 = cmd.content.gripper.num; // gripper number
packet.param2 = cmd.content.gripper.action; // action 0=release, 1=grab. See GRIPPER_ACTION enum
break;
case <API key>: // MAV ID: 222
packet.param1 = cmd.p1; // max time in seconds the external controller will be allowed to control the vehicle
packet.param2 = cmd.content.guided_limits.alt_min; // min alt below which the command will be aborted. 0 for no lower alt limit
packet.param3 = cmd.content.guided_limits.alt_max; // max alt above which the command will be aborted. 0 for no upper alt limit
packet.param4 = cmd.content.guided_limits.horiz_max;// max horizontal distance the vehicle can move before the command will be aborted. 0 for no horizontal limit
break;
case <API key>:
packet.param1 = cmd.p1; // disable=0 enable=1
break;
case <API key>: // MAV ID: 83
packet.param1 = cmd.content.altitude_wait.altitude;
packet.param2 = cmd.content.altitude_wait.descent_rate;
packet.param3 = cmd.content.altitude_wait.wiggle_time;
break;
default:
// unrecognised command
return false;
}
// copy location from mavlink to command
if (copy_location) {
packet.x = cmd.content.location.lat / 1.0e7f; // int32_t latitude to float
packet.y = cmd.content.location.lng / 1.0e7f; // int32_t longitude to float
}
if (copy_location || copy_alt) {
packet.z = cmd.content.location.alt / 100.0f; // cmd alt in cm to m
if (cmd.content.location.flags.relative_alt) {
packet.frame = <API key>;
}else{
packet.frame = MAV_FRAME_GLOBAL;
}
#if <API key>
if (cmd.content.location.flags.terrain_alt) {
// this is a above-terrain altitude
if (!cmd.content.location.flags.relative_alt) {
// refuse to return non-relative terrain mission
// items. Internally we do have these, and they
// have home.alt added, but we should never be
// returning them to the GCS, as the GCS doesn't know
// our home.alt, so it would have no way to properly
// interpret it
return false;
}
packet.z = cmd.content.location.alt * 0.01f;
packet.frame = <API key>;
}
#else
// don't ever return terrain mission items if no terrain support
if (cmd.content.location.flags.terrain_alt) {
return false;
}
#endif
}
// if we got this far then it must have been successful
return true;
}
private methods
complete - mission is marked complete and clean-up performed including calling the mission_complete_fn
void AP_Mission::complete()
{
// flag mission as complete
_flags.state = MISSION_COMPLETE;
// callback to main program's mission complete function
<API key>();
}
<API key> - moves current nav command forward
do command will also be loaded
accounts for do-jump commands
// returns true if command is advanced, false if failed (i.e. mission completed)
bool AP_Mission::<API key>()
{
Mission_Command cmd;
uint16_t cmd_index;
// exit immediately if we're not running
if (_flags.state != MISSION_RUNNING) {
return false;
}
// exit immediately if current nav command has not completed
if (_flags.nav_cmd_loaded) {
return false;
}
// stop the current running do command
_do_cmd.index = <API key>;
_flags.do_cmd_loaded = false;
_flags.do_cmd_all_done = false;
// get starting point for search
cmd_index = _nav_cmd.index;
if (cmd_index == <API key>) {
// start from beginning of the mission command list
cmd_index = <API key>;
}else{
// start from one position past the current nav command
cmd_index++;
}
// avoid endless loops
uint8_t max_loops = 255;
// search until we find next nav command or reach end of command list
while (!_flags.nav_cmd_loaded) {
// get next command
if (!get_next_cmd(cmd_index, cmd, true)) {
return false;
}
// check if navigation or "do" command
if (is_nav_cmd(cmd)) {
// save previous nav command index
_prev_nav_cmd_index = _nav_cmd.index;
// save separate previous nav command index if it contains lat,long,alt
if (!(cmd.content.location.lat == 0 && cmd.content.location.lng == 0)) {
<API key> = _nav_cmd.index;
}
// set current navigation command and start it
_nav_cmd = cmd;
_flags.nav_cmd_loaded = true;
_cmd_start_fn(_nav_cmd);
}else{
// set current do command and start it (if not already set)
if (!_flags.do_cmd_loaded) {
_do_cmd = cmd;
_flags.do_cmd_loaded = true;
_cmd_start_fn(_do_cmd);
} else {
// protect against endless loops of do-commands
if (max_loops
return false;
}
}
}
// move onto next command
cmd_index = cmd.index+1;
}
// if we have not found a do command then set flag to show there are no do-commands to be run before nav command completes
if (!_flags.do_cmd_loaded) {
_flags.do_cmd_all_done = true;
}
// if we got this far we must have successfully advanced the nav command
return true;
}
<API key> - moves current do command forward
accounts for do-jump commands
void AP_Mission::<API key>()
{
Mission_Command cmd;
uint16_t cmd_index;
// exit immediately if we're not running or we've completed all possible "do" commands
if (_flags.state != MISSION_RUNNING || _flags.do_cmd_all_done) {
return;
}
// get starting point for search
cmd_index = _do_cmd.index;
if (cmd_index == <API key>) {
cmd_index = <API key>;
}else{
// start from one position past the current do command
cmd_index++;
}
// check if we've reached end of mission
if (cmd_index >= (unsigned)_cmd_total) {
// set flag to stop unnecessarily searching for do commands
_flags.do_cmd_all_done = true;
return;
}
// find next do command
if (get_next_do_cmd(cmd_index, cmd)) {
// set current do command and start it
_do_cmd = cmd;
_flags.do_cmd_loaded = true;
_cmd_start_fn(_do_cmd);
}else{
// set flag to stop unnecessarily searching for do commands
_flags.do_cmd_all_done = true;
}
}
get_next_cmd - gets next command found at or after start_index
returns true if found, false if not found (i.e. mission complete)
accounts for do_jump commands
<API key> should be set to true if advancing the active navigation command
bool AP_Mission::get_next_cmd(uint16_t start_index, Mission_Command& cmd, bool <API key>)
{
uint16_t cmd_index = start_index;
Mission_Command temp_cmd;
uint16_t jump_index = <API key>;
// search until the end of the mission command list
uint8_t max_loops = 64;
while(cmd_index < (unsigned)_cmd_total) {
// load the next command
if (!<API key>(cmd_index, temp_cmd)) {
// this should never happen because of check above but just in case
return false;
}
// check for do-jump command
if (temp_cmd.id == MAV_CMD_DO_JUMP) {
if (max_loops
return false;
}
// check for invalid target
if ((temp_cmd.content.jump.target >= (unsigned)_cmd_total) || (temp_cmd.content.jump.target == 0)) {
// To-Do: log an error?
return false;
}
// check for endless loops
if (!<API key> && jump_index == cmd_index) {
// we have somehow reached this jump command twice and there is no chance it will complete
// To-Do: log an error?
return false;
}
// record this command so we can check for endless loops
if (jump_index == <API key>) {
jump_index = cmd_index;
}
// check if jump command is 'repeat forever'
if (temp_cmd.content.jump.num_times == <API key>) {
// continue searching from jump target
cmd_index = temp_cmd.content.jump.target;
}else{
// get number of times jump command has already been run
int16_t jump_times_run = get_jump_times_run(temp_cmd);
if (jump_times_run < temp_cmd.content.jump.num_times) {
// update the record of the number of times run
if (<API key>) {
<API key>(temp_cmd);
}
// continue searching from jump target
cmd_index = temp_cmd.content.jump.target;
}else{
// jump has been run specified number of times so move search to next command in mission
cmd_index++;
}
}
}else{
// this is a non-jump command so return it
cmd = temp_cmd;
return true;
}
}
// if we got this far we did not find a navigation command
return false;
}
get_next_do_cmd - gets next "do" or "conditional" command after start_index
returns true if found, false if not found
stops and returns false if it hits another navigation command before it finds the first do or conditional command
accounts for do_jump commands but never increments the jump's num_times_run (<API key> is responsible for this)
bool AP_Mission::get_next_do_cmd(uint16_t start_index, Mission_Command& cmd)
{
Mission_Command temp_cmd;
// check we have not passed the end of the mission list
if (start_index >= (unsigned)_cmd_total) {
return false;
}
// get next command
if (!get_next_cmd(start_index, temp_cmd, false)) {
// no more commands so return failure
return false;
}else if (is_nav_cmd(temp_cmd)) {
// if it's a "navigation" command then return false because we do not progress past nav commands
return false;
}else{
// this must be a "do" or "conditional" and is not a do-jump command so return it
cmd = temp_cmd;
return true;
}
}
jump handling methods
// init_jump_tracking - initialise jump_tracking variables
void AP_Mission::init_jump_tracking()
{
for(uint8_t i=0; i<<API key>; i++) {
_jump_tracking[i].index = <API key>;
_jump_tracking[i].num_times_run = 0;
}
}
get_jump_times_run - returns number of times the jump command has been run
int16_t AP_Mission::get_jump_times_run(const Mission_Command& cmd)
{
// exit immediatley if cmd is not a do-jump command or target is invalid
if ((cmd.id != MAV_CMD_DO_JUMP) || (cmd.content.jump.target >= (unsigned)_cmd_total) || (cmd.content.jump.target == 0)) {
// To-Do: log an error?
return <API key>;
}
// search through jump_tracking array for this cmd
for (uint8_t i=0; i<<API key>; i++) {
if (_jump_tracking[i].index == cmd.index) {
return _jump_tracking[i].num_times_run;
}else if(_jump_tracking[i].index == <API key>) {
// we've searched through all known jump commands and haven't found it so allocate new space in _jump_tracking array
_jump_tracking[i].index = cmd.index;
_jump_tracking[i].num_times_run = 0;
return 0;
}
}
// if we've gotten this far then the _jump_tracking array must be full
// To-Do: log an error?
return <API key>;
}
<API key> - increments the recorded number of times the jump command has been run
void AP_Mission::<API key>(Mission_Command& cmd)
{
// exit immediately if cmd is not a do-jump command
if (cmd.id != MAV_CMD_DO_JUMP) {
// To-Do: log an error?
return;
}
// search through jump_tracking array for this cmd
for (uint8_t i=0; i<<API key>; i++) {
if (_jump_tracking[i].index == cmd.index) {
_jump_tracking[i].num_times_run++;
return;
}else if(_jump_tracking[i].index == <API key>) {
// we've searched through all known jump commands and haven't found it so allocate new space in _jump_tracking array
_jump_tracking[i].index = cmd.index;
_jump_tracking[i].num_times_run = 1;
return;
}
}
// if we've gotten this far then the _jump_tracking array must be full
// To-Do: log an error
return;
}
// <API key> - checks version of missions stored in eeprom matches this library
// command list will be cleared if they do not match
void AP_Mission::<API key>()
{
uint32_t eeprom_version = _storage.read_uint32(0);
// if eeprom version does not match, clear the command list and update the eeprom version
if (eeprom_version != <API key>) {
if (clear()) {
_storage.write_uint32(0, <API key>);
}
}
}
/*
return total number of commands that can fit in storage space
*/
uint16_t AP_Mission::num_commands_max(void) const
{
// -4 to remove space for eeprom version number
return (_storage.size() - 4) / <API key>;
}
// find the nearest landing sequence starting point (DO_LAND_START) and
// return its index. Returns 0 if no appropriate DO_LAND_START point can
// be found.
uint16_t AP_Mission::<API key>()
{
struct Location current_loc;
if (!_ahrs.get_position(current_loc)) {
return 0;
}
uint16_t landing_start_index = 0;
float min_distance = -1;
// Go through mission looking for nearest landing start command
for (uint16_t i = 0; i < num_commands(); i++) {
Mission_Command tmp;
if (!<API key>(i, tmp)) {
continue;
}
if (tmp.id == <API key>) {
float tmp_distance = get_distance(tmp.content.location, current_loc);
if (min_distance < 0 || tmp_distance < min_distance) {
min_distance = tmp_distance;
landing_start_index = i;
}
}
}
return landing_start_index;
} |
<?php
/**
* @package WPSEO\XML_Sitemaps
*/
/**
* Class WPSEO_Sitemaps
*
* @todo: [JRF => whomever] If at all possible, move the adding of rewrite rules, actions and filters
* elsewhere and only load this file when an actual sitemap is being requested.
*/
class WPSEO_Sitemaps {
/**
* Content of the sitemap to output.
*
* @var string $sitemap
*/
protected $sitemap = '';
/**
* XSL stylesheet for styling a sitemap for web browsers
*
* @var string $stylesheet
*/
private $stylesheet = '';
/**
* Flag to indicate if this is an invalid or empty sitemap.
*
* @var bool $bad_sitemap
*/
public $bad_sitemap = false;
/**
* Whether or not the XML sitemap was served from a transient or not.
*
* @var bool $transient
*/
private $transient = false;
/**
* The maximum number of entries per sitemap page
*
* @var int $max_entries
*/
private $max_entries;
/**
* Holds the post type's newest publish dates
*
* @var array $post_type_dates
*/
private $post_type_dates;
/**
* Holds the WP SEO options
*
* @var array $options
*/
private $options = array();
/**
* Holds the n variable
*
* @var int $n
*/
private $n = 1;
/**
* Holds the home_url() value to speed up loops
*
* @var string $home_url
*/
private $home_url = '';
/**
* Holds the get_bloginfo( 'charset' ) value to reuse for performance
*
* @var string $charset
*/
private $charset = '';
/**
* Holds the timezone string value to reuse for performance
*
* @var string $timezone_string
*/
private $timezone_string = '';
/**
* Class constructor
*/
function __construct() {
if ( ! defined( 'ENT_XML1' ) ) {
define( 'ENT_XML1', 16 );
}
add_action( 'after_setup_theme', array( $this, 'reduce_query_load' ), 99 );
add_filter( 'posts_where', array( $this, '<API key>' ) );
add_action( 'pre_get_posts', array( $this, 'redirect' ), 1 );
add_filter( 'redirect_canonical', array( $this, 'canonical' ) );
add_action( '<API key>', array( $this, 'hit_sitemap_index' ) );
// default stylesheet
$this->stylesheet = '<?xml-stylesheet type="text/xsl" href="' . preg_replace( '/(^http[s]?:)/', '', esc_url( home_url( 'main-sitemap.xsl' ) ) ) . '"?>';
$this->options = WPSEO_Options::get_all();
$this->max_entries = $this->options['entries-per-page'];
$this->home_url = home_url();
$this->charset = get_bloginfo( 'charset' );
}
/**
* Check the current request URI, if we can determine it's probably an XML sitemap, kill loading the widgets
*/
public function reduce_query_load() {
if ( ! isset( $_SERVER['REQUEST_URI'] ) ) {
return;
}
$request_uri = $_SERVER['REQUEST_URI'];
$extension = substr( $request_uri, -4 );
if ( false !== stripos( $request_uri, 'sitemap' ) && ( in_array( $extension, array( '.xml', '.xsl', ) ) ) ) {
remove_all_actions( 'widgets_init' );
}
}
/**
* This query invalidates the main query on purpose so it returns nice and quickly
*
* @param string $where
*
* @return string
*/
function <API key>( $where ) {
// check if $wp_query is properly set which isn't always the case in older WP development versions
if ( ! is_object( $GLOBALS['wp_query'] ) ) {
return $where;
}
if ( is_main_query() && ( get_query_var( 'sitemap' ) != '' || get_query_var( 'xsl' ) != '' ) ) {
$where = ' AND 0=1 ' . $where;
}
return $where;
}
/**
* Returns the server HTTP protocol to use for output, if it's set.
*
* @return string
*/
private function http_protocol() {
return ( isset( $_SERVER['SERVER_PROTOCOL'] ) && $_SERVER['SERVER_PROTOCOL'] !== '' ) ? sanitize_text_field( $_SERVER['SERVER_PROTOCOL'] ) : 'HTTP/1.1';
}
private function <API key>() {
// if site timezone string exists, return it
if ( $timezone = get_option( 'timezone_string' ) ) {
return $timezone;
}
// get UTC offset, if it isn't set then return UTC
if ( 0 === ( $utc_offset = get_option( 'gmt_offset', 0 ) ) ) {
return 'UTC';
}
// adjust UTC offset from hours to seconds
$utc_offset *= HOUR_IN_SECONDS;
// attempt to guess the timezone string from the UTC offset
$timezone = <API key>( '', $utc_offset );
// last try, guess timezone string manually
if ( false === $timezone ) {
$is_dst = date( 'I' );
foreach ( <API key>() as $abbr ) {
foreach ( $abbr as $city ) {
if ( $city['dst'] == $is_dst && $city['offset'] == $utc_offset ) {
return $city['timezone_id'];
}
}
}
}
// fallback to UTC
return 'UTC';
}
/**
* Returns the correct timezone string
*
* @return string
*/
private function get_timezone_string() {
if ( '' == $this->timezone_string ) {
$this->timezone_string = $this-><API key>();
}
return $this->timezone_string;
}
/**
* Register your own sitemap. Call this during 'init'.
*
* @param string $name The name of the sitemap
* @param callback $function Function to build your sitemap
* @param string $rewrite Optional. Regular expression to match your sitemap with
*/
function register_sitemap( $name, $function, $rewrite = '' ) {
add_action( 'wpseo_do_sitemap_' . $name, $function );
if ( ! empty( $rewrite ) ) {
add_rewrite_rule( $rewrite, 'index.php?sitemap=' . $name, 'top' );
}
}
/**
* Register your own XSL file. Call this during 'init'.
*
* @param string $name The name of the XSL file
* @param callback $function Function to build your XSL file
* @param string $rewrite Optional. Regular expression to match your sitemap with
*/
function register_xsl( $name, $function, $rewrite = '' ) {
add_action( 'wpseo_xsl_' . $name, $function );
if ( ! empty( $rewrite ) ) {
add_rewrite_rule( $rewrite, 'index.php?xsl=' . $name, 'top' );
}
}
/**
* Set the sitemap n to allow creating partial sitemaps with wp-cli
* in an one-off process.
*
* @param integer $n The part that should be generated.
*/
public function set_n( $n ) {
if ( is_scalar( $n ) && intval( $n ) > 0 ) {
$this->n = intval( $n );
}
}
/**
* Set the sitemap content to display after you have generated it.
*
* @param string $sitemap The generated sitemap to output
*/
function set_sitemap( $sitemap ) {
$this->sitemap = $sitemap;
}
/**
* Set a custom stylesheet for this sitemap. Set to empty to just remove
* the default stylesheet.
*
* @param string $stylesheet Full xml-stylesheet declaration
*/
public function set_stylesheet( $stylesheet ) {
$this->stylesheet = $stylesheet;
}
/**
* Set as true to make the request 404. Used stop the display of empty sitemaps or
* invalid requests.
*
* @param bool $bool Is this a bad request. True or false.
*/
function set_bad_sitemap( $bool ) {
$this->bad_sitemap = (bool) $bool;
}
/**
* Prevent stupid plugins from running shutdown scripts when we're obviously not outputting HTML.
*
* @since 1.4.16
*/
function sitemap_close() {
remove_all_actions( 'wp_footer' );
die();
}
/**
* Hijack requests for potential sitemaps and XSL files.
*
* @param \WP_Query $query
*/
function redirect( $query ) {
if ( ! $query->is_main_query() ) {
return;
}
$xsl = get_query_var( 'xsl' );
if ( ! empty( $xsl ) ) {
$this->xsl_output( $xsl );
$this->sitemap_close();
}
$type = get_query_var( 'sitemap' );
if ( empty( $type ) ) {
return;
}
$this->set_n( get_query_var( 'sitemap_n' ) );
/**
* Filter: '<API key>' - Allow disabling the transient cache
*
* @api bool $unsigned Enable cache or not, defaults to true
*/
$caching = apply_filters( '<API key>', true );
if ( $caching ) {
if ( is_ssl() ) {
$cache_key = '<API key>' . $type . '_' . $this->n;
}
else {
$cache_key = '<API key>' . $type . '_' . $this->n;
}
do_action( '<API key>' . $type, $this );
$this->sitemap = get_transient( $cache_key );
}
if ( ! $this->sitemap || '' == $this->sitemap ) {
$this->build_sitemap( $type );
// 404 for invalid or emtpy sitemaps
if ( $this->bad_sitemap ) {
$GLOBALS['wp_query']->set_404();
status_header( 404 );
return;
}
if ( $caching ) {
set_transient( $cache_key, $this->sitemap, DAY_IN_SECONDS );
}
}
else {
$this->transient = true;
}
$this->output();
$this->sitemap_close();
}
/**
* Attempt to build the requested sitemap. Sets $bad_sitemap if this isn't
* for the root sitemap, a post type or taxonomy.
*
* @param string $type The requested sitemap's identifier.
*/
function build_sitemap( $type ) {
$type = apply_filters( '<API key>', $type );
if ( $type == 1 ) {
$this->build_root_map();
}
elseif ( post_type_exists( $type ) ) {
$this->build_post_type_map( $type );
}
elseif ( $tax = get_taxonomy( $type ) ) {
$this->build_tax_map( $tax );
}
elseif ( $type == 'author' ) {
$this->build_user_map();
}
elseif ( has_action( 'wpseo_do_sitemap_' . $type ) ) {
do_action( 'wpseo_do_sitemap_' . $type );
}
else {
$this->bad_sitemap = true;
}
}
/**
* Build the root sitemap -- example.com/sitemap_index.xml -- which lists sub-sitemaps
* for other content types.
*/
function build_root_map() {
global $wpdb;
$this->sitemap = '<sitemapindex xmlns="http:
// reference post type specific sitemaps
$post_types = get_post_types( array( 'public' => true ) );
if ( is_array( $post_types ) && $post_types !== array() ) {
foreach ( $post_types as $post_type ) {
if ( isset( $this->options[ 'post_types-' . $post_type . '-not_in_sitemap' ] ) && $this->options[ 'post_types-' . $post_type . '-not_in_sitemap' ] === true ) {
continue;
}
else {
if ( apply_filters( '<API key>', false, $post_type ) ) {
continue;
}
}
// using same filters for filtering join and where parts of the query.
$join_filter = apply_filters( '<API key>', '', $post_type );
$where_filter = apply_filters( '<API key>', '', $post_type );
// using the same query with build_post_type_map($post_type) function to count number of posts.
$query = $wpdb->prepare( "SELECT COUNT(ID) FROM $wpdb->posts {$join_filter} WHERE post_status IN ('publish','inherit') AND post_password = '' AND post_date != '0000-00-00 00:00:00' AND post_type = %s " . $where_filter, $post_type );
$count = $wpdb->get_var( $query );
if ( $count == 0 ) {
continue;
}
$n = ( $count > $this->max_entries ) ? (int) ceil( $count / $this->max_entries ) : 1;
for ( $i = 0; $i < $n; $i ++ ) {
$count = ( $n > 1 ) ? ( $i + 1 ) : '';
if ( empty( $count ) || $count == $n ) {
$date = $this->get_last_modified( $post_type );
}
else {
if ( ! isset( $all_dates ) ) {
$all_dates = $wpdb->get_col( $wpdb->prepare( "SELECT post_modified_gmt FROM (SELECT @rownum:=@rownum+1 rownum, $wpdb->posts.post_modified_gmt FROM (SELECT @rownum:=0) r, $wpdb->posts WHERE post_status IN ('publish','inherit') AND post_type = %s ORDER BY post_modified_gmt ASC) x WHERE rownum %%%d=0", $post_type, $this->max_entries ) );
}
$datetime = new DateTime( $all_dates[ $i ], new DateTimeZone( $this->get_timezone_string() ) );
$date = $datetime->format( 'c' );
unset( $all_dates, $datetime );
}
$this->sitemap .= '<sitemap>' . "\n";
$this->sitemap .= '<loc>' . <API key>( $post_type . '-sitemap' . $count . '.xml' ) . '</loc>' . "\n";
$this->sitemap .= '<lastmod>' . htmlspecialchars( $date ) . '</lastmod>' . "\n";
$this->sitemap .= '</sitemap>' . "\n";
}
unset( $count, $n, $i, $date );
}
}
unset( $post_types, $post_type, $join_filter, $where_filter, $query );
// reference taxonomy specific sitemaps
$taxonomies = get_taxonomies( array( 'public' => true ), 'objects' );
$taxonomy_names = array_keys( $taxonomies );
if ( is_array( $taxonomy_names ) && $taxonomy_names !== array() ) {
foreach ( $taxonomy_names as $tax ) {
if ( in_array( $tax, array( 'link_category', 'nav_menu', 'post_format' ) ) ) {
unset( $taxonomy_names[ $tax ], $taxonomies[ $tax ] );
continue;
}
if ( apply_filters( '<API key>', false, $tax ) ) {
unset( $taxonomy_names[ $tax ], $taxonomies[ $tax ] );
continue;
}
if ( isset( $this->options[ 'taxonomies-' . $tax . '-not_in_sitemap' ] ) && $this->options[ 'taxonomies-' . $tax . '-not_in_sitemap' ] === true ) {
unset( $taxonomy_names[ $tax ], $taxonomies[ $tax ] );
continue;
}
}
unset( $tax );
// Retrieve all the taxonomies and their terms so we can do a proper count on them.
$hide_empty = ( apply_filters( '<API key>', true, $taxonomy_names ) ) ? 'count != 0 AND' : '';
$query = "SELECT taxonomy, term_id FROM $wpdb->term_taxonomy WHERE $hide_empty taxonomy IN ('" . implode( "','", $taxonomy_names ) . "');";
$all_taxonomy_terms = $wpdb->get_results( $query );
$all_taxonomies = array();
foreach ( $all_taxonomy_terms as $obj ) {
$all_taxonomies[ $obj->taxonomy ][] = $obj->term_id;
}
unset( $hide_empty, $query, $all_taxonomy_terms, $obj );
foreach ( $taxonomies as $tax_name => $tax ) {
$steps = $this->max_entries;
$count = ( isset ( $all_taxonomies[ $tax_name ] ) ) ? count( $all_taxonomies[ $tax_name ] ) : 1;
$n = ( $count > $this->max_entries ) ? (int) ceil( $count / $this->max_entries ) : 1;
for ( $i = 0; $i < $n; $i ++ ) {
$count = ( $n > 1 ) ? ( $i + 1 ) : '';
if ( ! is_array( $tax->object_type ) || count( $tax->object_type ) == 0 ) {
continue;
}
if ( ( empty( $count ) || $count == $n ) ) {
$date = $this->get_last_modified( $tax->object_type );
}
else {
$terms = array_splice( $all_taxonomies[ $tax_name ], 0, $steps );
if ( ! $terms ) {
continue;
}
$args = array(
'post_type' => $tax->object_type,
'tax_query' => array(
array(
'taxonomy' => $tax_name,
'field' => 'slug',
'terms' => $terms,
),
),
'orderby' => 'modified',
'order' => 'DESC',
);
$query = new WP_Query( $args );
$date = '';
if ( $query->have_posts() ) {
$datetime = new DateTime( $query->posts[0]->post_modified_gmt, new DateTimeZone( $this->get_timezone_string() ) );
$date = $datetime->format( 'c' );
unset( $datetime );
}
else {
$date = $this->get_last_modified( $tax->object_type );
}
unset( $terms, $args, $query );
}
$this->sitemap .= '<sitemap>' . "\n";
$this->sitemap .= '<loc>' . <API key>( $tax_name . '-sitemap' . $count . '.xml' ) . '</loc>' . "\n";
$this->sitemap .= '<lastmod>' . htmlspecialchars( $date ) . '</lastmod>' . "\n";
$this->sitemap .= '</sitemap>' . "\n";
}
unset( $steps, $count, $n, $i, $date );
}
}
unset( $taxonomies, $taxonomy_names, $all_taxonomies, $tax_name, $tax );
if ( $this->options['disable-author'] === false && $this->options['<API key>'] === false ) {
// reference user profile specific sitemaps
$users = get_users( array( 'who' => 'authors', 'fields' => 'id' ) );
$count = count( $users );
$n = ( $count > $this->max_entries ) ? (int) ceil( $count / $this->max_entries ) : 1;
for ( $i = 0; $i < $n; $i ++ ) {
$count = ( $n > 1 ) ? ( $i + 1 ) : '';
// must use custom raw query because WP User Query does not support ordering by usermeta
// Retrieve the newest updated profile timestamp overall
$date_query = "
SELECT mt1.meta_value FROM $wpdb->users
INNER JOIN $wpdb->usermeta ON ($wpdb->users.ID = $wpdb->usermeta.user_id)
INNER JOIN $wpdb->usermeta AS mt1 ON ($wpdb->users.ID = mt1.user_id) WHERE 1=1
AND ( ($wpdb->usermeta.meta_key = %s AND CAST($wpdb->usermeta.meta_value AS CHAR) != '0')
AND mt1.meta_key = '<API key>' ) ORDER BY mt1.meta_value
";
if ( empty( $count ) || $count == $n ) {
$date = $wpdb->get_var(
$wpdb->prepare(
$date_query . ' ASC LIMIT 1',
$wpdb->get_blog_prefix() . 'user_level'
)
);
// Retrieve the newest updated profile timestamp by an offset
}
else {
$date = $wpdb->get_var(
$wpdb->prepare(
$date_query . ' DESC LIMIT 1 OFFSET %d',
$wpdb->get_blog_prefix() . 'user_level',
( ( $this->max_entries * ( $i + 1 ) ) - 1 )
)
);
}
$date = new DateTime( date( 'y-m-d H:i:s', $date ), new DateTimeZone( $this->get_timezone_string() ) );
$this->sitemap .= '<sitemap>' . "\n";
$this->sitemap .= '<loc>' . <API key>( 'author-sitemap' . $count . '.xml' ) . '</loc>' . "\n";
$this->sitemap .= '<lastmod>' . htmlspecialchars( $date->format( 'c' ) ) . '</lastmod>' . "\n";
$this->sitemap .= '</sitemap>' . "\n";
}
unset( $users, $count, $n, $i, $date_query, $date );
}
// allow other plugins to add their sitemaps to the index
$this->sitemap .= apply_filters( 'wpseo_sitemap_index', '' );
$this->sitemap .= '</sitemapindex>';
}
/**
* Function to dynamically filter the change frequency
*
* @param string $filter Expands to wpseo_sitemap_$filter_change_freq, allowing for a change of the frequency for numerous specific URLs
* @param string $default The default value for the frequency
* @param string $url The URL of the currenty entry
*
* @return mixed|void
*/
private function filter_frequency( $filter, $default, $url ) {
/**
* Filter: 'wpseo_sitemap_' . $filter . '_change_freq' - Allow filtering of the specific change frequency
*
* @api string $default The default change frequency
*/
$change_freq = apply_filters( 'wpseo_sitemap_' . $filter . '_change_freq', $default, $url );
if ( ! in_array( $change_freq, array(
'always',
'hourly',
'daily',
'weekly',
'monthly',
'yearly',
'never',
) )
) {
$change_freq = $default;
}
return $change_freq;
}
/**
* Build a sub-sitemap for a specific post type -- example.com/post_type-sitemap.xml
*
* @param string $post_type Registered post type's slug
*/
function build_post_type_map( $post_type ) {
global $wpdb;
if (
( isset( $this->options[ 'post_types-' . $post_type . '-not_in_sitemap' ] ) && $this->options[ 'post_types-' . $post_type . '-not_in_sitemap' ] === true )
|| in_array( $post_type, array( 'revision', 'nav_menu_item' ) )
|| apply_filters( '<API key>', false, $post_type )
) {
$this->bad_sitemap = true;
return;
}
$output = '';
$steps = ( 100 > $this->max_entries ) ? $this->max_entries : 100;
$n = (int) $this->n;
$offset = ( $n > 1 ) ? ( ( $n - 1 ) * $this->max_entries ) : 0;
$total = ( $offset + $this->max_entries );
$join_filter = apply_filters( '<API key>', '', $post_type );
$where_filter = apply_filters( '<API key>', '', $post_type );
$query = $wpdb->prepare( "SELECT COUNT(ID) FROM $wpdb->posts {$join_filter} WHERE post_status IN ('publish','inherit') AND post_password = '' AND post_date != '0000-00-00 00:00:00' AND post_type = %s " . $where_filter, $post_type );
$typecount = $wpdb->get_var( $query );
if ( $total > $typecount ) {
$total = $typecount;
}
if ( $n === 1 ) {
$front_id = get_option( 'page_on_front' );
if ( ! $front_id && ( $post_type == 'post' || $post_type == 'page' ) ) {
$output .= $this->sitemap_url(
array(
'loc' => $this->home_url,
'pri' => 1,
'chf' => $this->filter_frequency( 'homepage', 'daily', $this->home_url ),
)
);
}
elseif ( $front_id && $post_type == 'post' ) {
$page_for_posts = get_option( 'page_for_posts' );
if ( $page_for_posts ) {
$page_for_posts_url = get_permalink( $page_for_posts );
$output .= $this->sitemap_url(
array(
'loc' => $page_for_posts_url,
'pri' => 1,
'chf' => $this->filter_frequency( 'blogpage', 'daily', $page_for_posts_url ),
)
);
unset( $page_for_posts_url );
}
}
$archive_url = <API key>( $post_type );
/**
* Filter: '<API key>' - Allow changing the URL WordPress SEO uses in the XML sitemap for this post type archive.
*
* @api float $archive_url The URL of this archive
*
* @param string $post_type The post type this archive is for
*/
$archive_url = apply_filters( '<API key>', $archive_url, $post_type );
if ( $archive_url ) {
/**
* Filter: '<API key>' - Allow changing the priority of the URL WordPress SEO uses in the XML sitemap.
*
* @api float $priority The priority for this URL, ranging from 0 to 1
*
* @param string $post_type The post type this archive is for
*/
$output .= $this->sitemap_url(
array(
'loc' => $archive_url,
'pri' => apply_filters( '<API key>', 0.8, $post_type ),
'chf' => $this->filter_frequency( $post_type . '_archive', 'weekly', $archive_url ),
'mod' => $this->get_last_modified( $post_type ),
// <API key>( 'gmt', $post_type ) #17455
)
);
}
}
if ( $typecount == 0 && empty( $archive ) ) {
$this->bad_sitemap = true;
return;
}
$stackedurls = array();
// Make sure you're wpdb->preparing everything you throw into this!!
$join_filter = apply_filters( 'wpseo_posts_join', false, $post_type );
$where_filter = apply_filters( 'wpseo_posts_where', false, $post_type );
$status = ( $post_type == 'attachment' ) ? 'inherit' : 'publish';
$parsed_home = parse_url( $this->home_url );
$host = '';
$scheme = 'http';
if ( isset( $parsed_home['host'] ) && ! empty( $parsed_home['host'] ) ) {
$host = str_replace( 'www.', '', $parsed_home['host'] );
}
if ( isset( $parsed_home['scheme'] ) && ! empty( $parsed_home['scheme'] ) ) {
$scheme = $parsed_home['scheme'];
}
/**
* We grab post_date, post_name and post_status too so we can throw these objects
* into get_permalink, which saves a get_post call for each permalink.
*/
while ( $total > $offset ) {
$query = $wpdb->prepare( "SELECT l.ID, post_title, post_content, post_name, post_parent, post_modified_gmt, post_date, post_date_gmt FROM ( SELECT ID FROM $wpdb->posts {$join_filter} WHERE post_status = '%s' AND post_password = '' AND post_type = '%s' AND post_date != '0000-00-00 00:00:00' {$where_filter} ORDER BY post_modified ASC LIMIT %d OFFSET %d ) o JOIN $wpdb->posts l ON l.ID = o.ID ORDER BY l.ID",
$status, $post_type, $steps, $offset
);
$posts = $wpdb->get_results( $query );
$post_ids = array();
foreach ( $posts as $p ) {
$post_ids[] = $p->ID;
}
unset( $p );
if ( count( $post_ids ) > 0 ) {
update_meta_cache( 'post', $post_ids );
$imploded_post_ids = implode( $post_ids, ',' );
$attachments = $this->get_attachments( $imploded_post_ids );
$thumbnails = $this->get_thumbnails( $imploded_post_ids );
$this-><API key>( $attachments, $thumbnails );
unset( $imploded_post_ids );
}
unset( $post_ids );
$offset = ( $offset + $steps );
if ( is_array( $posts ) && $posts !== array() ) {
foreach ( $posts as $p ) {
$p->post_type = $post_type;
$p->post_status = 'publish';
$p->filter = 'sample';
if ( WPSEO_Meta::get_value( 'meta-robots-noindex', $p->ID ) === '1' && WPSEO_Meta::get_value( 'sitemap-include', $p->ID ) !== 'always' ) {
continue;
}
if ( WPSEO_Meta::get_value( 'sitemap-include', $p->ID ) === 'never' ) {
continue;
}
if ( WPSEO_Meta::get_value( 'redirect', $p->ID ) !== '' ) {
continue;
}
$url = array();
if ( isset( $p->post_modified_gmt ) && $p->post_modified_gmt != '0000-00-00 00:00:00' && $p->post_modified_gmt > $p->post_date_gmt ) {
$url['mod'] = $p->post_modified_gmt;
}
else {
if ( '0000-00-00 00:00:00' != $p->post_date_gmt ) {
$url['mod'] = $p->post_date_gmt;
}
else {
$url['mod'] = $p->post_date;
}
}
$url['loc'] = get_permalink( $p );
/**
* Filter: '<API key>' - Allow changing the URL WordPress SEO uses in the XML sitemap.
*
* Note that only absolute local URLs are allowed as the check after this removes external URLs.
*
* @api string $url URL to use in the XML sitemap
*
* @param object $p Post object for the URL
*/
$url['loc'] = apply_filters( '<API key>', $url['loc'], $p );
$url['chf'] = $this->filter_frequency( $post_type . '_single', 'weekly', $url['loc'] );
if ( false === strpos( $url['loc'], $this->home_url ) ) {
continue;
}
$canonical = WPSEO_Meta::get_value( 'canonical', $p->ID );
if ( $canonical !== '' && $canonical !== $url['loc'] ) {
/* Let's assume that if a canonical is set for this page and it's different from
the URL of this post, that page is either already in the XML sitemap OR is on
an external site, either way, we shouldn't include it here. */
continue;
}
else {
if ( $this->options['trailingslash'] === true && $p->post_type != 'post' ) {
$url['loc'] = trailingslashit( $url['loc'] );
}
}
unset( $canonical );
$url['pri'] = $this->calculate_priority( $p );
$url['images'] = array();
$content = $p->post_content;
$content = '<p><img src="' . $this->image_url( <API key>( $p->ID ) ) . '" alt="' . $p->post_title . '" /></p>' . $content;
if ( preg_match_all( '`<img [^>]+>`', $content, $matches ) ) {
foreach ( $matches[0] as $img ) {
if ( preg_match( '`src=["\']([^"\']+)["\']`', $img, $match ) ) {
$src = $match[1];
if ( WPSEO_Utils::is_url_relative( $src ) === true ) {
if ( $src[0] !== '/' ) {
continue;
}
else {
// The URL is relative, we'll have to make it absolute
$src = $this->home_url . $src;
}
}
elseif ( strpos( $src, 'http' ) !== 0 ) {
// Protocol relative url, we add the scheme as the standard requires a protocol
$src = $scheme . ':' . $src;
}
if ( strpos( $src, $host ) === false ) {
continue;
}
if ( $src != esc_url( $src ) ) {
continue;
}
if ( isset( $url['images'][ $src ] ) ) {
continue;
}
$image = array(
'src' => apply_filters( '<API key>', $src, $p )
);
if ( preg_match( '`title=["\']([^"\']+)["\']`', $img, $title_match ) ) {
$image['title'] = str_replace( array( '-', '_' ), ' ', $title_match[1] );
}
unset( $title_match );
if ( preg_match( '`alt=["\']([^"\']+)["\']`', $img, $alt_match ) ) {
$image['alt'] = str_replace( array( '-', '_' ), ' ', $alt_match[1] );
}
unset( $alt_match );
$image = apply_filters( '<API key>', $image, $p );
$url['images'][] = $image;
}
unset( $match, $src );
}
}
unset( $content, $matches, $img );
if ( strpos( $p->post_content, '[gallery' ) !== false ) {
if ( is_array( $attachments ) && $attachments !== array() ) {
$url['images'] = $this->parse_attachments( $attachments, $p );
}
unset( $attachment, $src, $image, $alt );
}
$url['images'] = apply_filters( '<API key>', $url['images'], $p->ID );
if ( ! in_array( $url['loc'], $stackedurls ) ) {
// Use this filter to adjust the entry before it gets added to the sitemap
$url = apply_filters( 'wpseo_sitemap_entry', $url, 'post', $p );
if ( is_array( $url ) && $url !== array() ) {
$output .= $this->sitemap_url( $url );
$stackedurls[] = $url['loc'];
}
}
// Clear the post_meta and the term cache for the post, as we no longer need it now.
// wp_cache_delete( $p->ID, 'post_meta' );
// <API key>( $p->ID, $post_type );
}
unset( $p, $url );
}
}
if ( empty( $output ) ) {
$this->bad_sitemap = true;
return;
}
$this->sitemap = '<urlset xmlns:xsi="http:
$this->sitemap .= 'xsi:schemaLocation="http:
$this->sitemap .= 'xmlns="http:
$this->sitemap .= $output;
// Filter to allow adding extra URLs, only do this on the first XML sitemap, not on all.
if ( $n === 1 ) {
$this->sitemap .= apply_filters( 'wpseo_sitemap_' . $post_type . '_content', '' );
}
$this->sitemap .= '</urlset>';
}
/**
* Build a sub-sitemap for a specific taxonomy -- example.com/tax-sitemap.xml
*
* @param string $taxonomy Registered taxonomy's slug
*/
function build_tax_map( $taxonomy ) {
if (
( isset( $this->options[ 'taxonomies-' . $taxonomy->name . '-not_in_sitemap' ] ) && $this->options[ 'taxonomies-' . $taxonomy->name . '-not_in_sitemap' ] === true )
|| in_array( $taxonomy, array( 'link_category', 'nav_menu', 'post_format' ) )
|| apply_filters( '<API key>', false, $taxonomy->name )
) {
$this->bad_sitemap = true;
return;
}
global $wpdb;
$output = '';
$steps = $this->max_entries;
$n = (int) $this->n;
$offset = ( $n > 1 ) ? ( ( $n - 1 ) * $this->max_entries ) : 0;
/**
* Filter: '<API key>' - Allow people to include empty terms in sitemap
*
* @api bool $hide_empty Whether or not to hide empty terms, defaults to true.
*
* @param object $taxonomy The taxonomy we're getting terms for.
*/
$hide_empty = apply_filters( '<API key>', true, $taxonomy );
$terms = get_terms( $taxonomy->name, array( 'hide_empty' => $hide_empty ) );
$terms = array_splice( $terms, $offset, $steps );
if ( is_array( $terms ) && $terms !== array() ) {
foreach ( $terms as $c ) {
$url = array();
$tax_noindex = WPSEO_Taxonomy_Meta::get_term_meta( $c, $c->taxonomy, 'noindex' );
$tax_sitemap_inc = WPSEO_Taxonomy_Meta::get_term_meta( $c, $c->taxonomy, 'sitemap_include' );
if ( ( is_string( $tax_noindex ) && $tax_noindex === 'noindex' ) && ( ! is_string( $tax_sitemap_inc ) || $tax_sitemap_inc !== 'always' ) ) {
continue;
}
if ( $tax_sitemap_inc === 'never' ) {
continue;
}
$url['loc'] = WPSEO_Taxonomy_Meta::get_term_meta( $c, $c->taxonomy, 'canonical' );
if ( ! is_string( $url['loc'] ) || $url['loc'] === '' ) {
$url['loc'] = get_term_link( $c, $c->taxonomy );
if ( $this->options['trailingslash'] === true ) {
$url['loc'] = trailingslashit( $url['loc'] );
}
}
if ( $c->count > 10 ) {
$url['pri'] = 0.6;
}
else {
if ( $c->count > 3 ) {
$url['pri'] = 0.4;
}
else {
$url['pri'] = 0.2;
}
}
// Grab last modified date
$sql = $wpdb->prepare(
"
SELECT MAX(p.post_modified_gmt) AS lastmod
FROM $wpdb->posts AS p
INNER JOIN $wpdb->term_relationships AS term_rel
ON term_rel.object_id = p.ID
INNER JOIN $wpdb->term_taxonomy AS term_tax
ON term_tax.term_taxonomy_id = term_rel.term_taxonomy_id
AND term_tax.taxonomy = %s
AND term_tax.term_id = %d
WHERE p.post_status IN ('publish','inherit')
AND p.post_password = ''",
$c->taxonomy,
$c->term_id
);
$url['mod'] = $wpdb->get_var( $sql );
$url['chf'] = $this->filter_frequency( $c->taxonomy . '_term', 'weekly', $url['loc'] );
// Use this filter to adjust the entry before it gets added to the sitemap
$url = apply_filters( 'wpseo_sitemap_entry', $url, 'term', $c );
if ( is_array( $url ) && $url !== array() ) {
$output .= $this->sitemap_url( $url );
}
}
unset( $c, $url, $tax_noindex, $tax_sitemap_inc, $sql );
}
if ( empty( $output ) ) {
$this->bad_sitemap = true;
return;
}
$this->sitemap = '<urlset xmlns:xsi="http:
$this->sitemap .= 'xsi:schemaLocation="http:
$this->sitemap .= 'xmlns="http:
if ( is_string( $output ) && trim( $output ) !== '' ) {
$this->sitemap .= $output;
}
else {
// If the sitemap is empty, add the homepage URL to make sure it doesn't throw errors in GWT.
$this->sitemap .= $this->sitemap_url( home_url() );
}
$this->sitemap .= '</urlset>';
}
/**
* Build the sub-sitemap for authors
*
* @since 1.4.8
*/
function build_user_map() {
if ( $this->options['disable-author'] === true || $this->options['<API key>'] === true ) {
$this->bad_sitemap = true;
return;
}
$output = '';
$steps = $this->max_entries;
$n = (int) $this->n;
$offset = ( $n > 1 ) ? ( ( $n - 1 ) * $this->max_entries ) : 0;
// initial query to fill in missing usermeta with the current timestamp
$users = get_users(
array(
'who' => 'authors',
'meta_query' => array(
array(
'key' => '<API key>',
'value' => '<API key>', // This is ignored, but is necessary...
'compare' => 'NOT EXISTS',
),
)
)
);
if ( is_array( $users ) && $users !== array() ) {
foreach ( $users as $user ) {
update_user_meta( $user->ID, '<API key>', time() );
}
}
unset( $users, $user );
// query for users with this meta
$users = get_users(
array(
'who' => 'authors',
'offset' => $offset,
'number' => $steps,
'meta_key' => '<API key>',
'orderby' => 'meta_value_num',
'order' => 'ASC',
)
);
add_filter( '<API key>', array( $this, '<API key>' ), 8 );
$users = apply_filters( '<API key>', $users );
// ascending sort
usort( $users, array( $this, 'user_map_sorter' ) );
if ( is_array( $users ) && $users !== array() ) {
foreach ( $users as $user ) {
$author_link = <API key>( $user->ID );
if ( $author_link !== '' ) {
$url = array(
'loc' => $author_link,
'pri' => 0.8,
'chf' => $this->filter_frequency( 'author_archive', 'daily', $author_link ),
'mod' => date( 'c', isset( $user-><API key> ) ? $user-><API key> : time() ),
);
// Use this filter to adjust the entry before it gets added to the sitemap
$url = apply_filters( 'wpseo_sitemap_entry', $url, 'user', $user );
if ( is_array( $url ) && $url !== array() ) {
$output .= $this->sitemap_url( $url );
}
}
}
unset( $user, $author_link, $url );
}
if ( empty( $output ) ) {
$this->bad_sitemap = true;
return;
}
$this->sitemap = '<urlset xmlns:xsi="http:
$this->sitemap .= 'xsi:schemaLocation="http:
$this->sitemap .= 'xmlns="http:
$this->sitemap .= $output;
// Filter to allow adding extra URLs, only do this on the first XML sitemap, not on all.
if ( $n === 1 ) {
$this->sitemap .= apply_filters( '<API key>', '' );
}
$this->sitemap .= '</urlset>';
}
/**
* Spits out the XSL for the XML sitemap.
*
* @param string $type
*
* @since 1.4.13
*/
function xsl_output( $type ) {
if ( $type == 'main' ) {
header( $this->http_protocol() . ' 200 OK', true, 200 );
// Prevent the search engines from indexing the XML Sitemap.
header( 'X-Robots-Tag: noindex, follow', true );
header( 'Content-Type: text/xml' );
// Make the browser cache this file properly.
$expires = YEAR_IN_SECONDS;
header( 'Pragma: public' );
header( 'Cache-Control: maxage=' . $expires );
header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', ( time() + $expires ) ) . ' GMT' );
require_once( WPSEO_PATH . 'css/xml-sitemap-xsl.php' );
}
else {
do_action( 'wpseo_xsl_' . $type );
}
}
/**
* Spit out the generated sitemap and relevant headers and encoding information.
*/
function output() {
if ( ! headers_sent() ) {
header( $this->http_protocol() . ' 200 OK', true, 200 );
// Prevent the search engines from indexing the XML Sitemap.
header( 'X-Robots-Tag: noindex,follow', true );
header( 'Content-Type: text/xml' );
}
echo '<?xml version="1.0" encoding="', esc_attr( $this->charset ), '"?>';
if ( $this->stylesheet ) {
echo apply_filters( '<API key>', $this->stylesheet ), "\n";
}
echo $this->sitemap;
echo "\n", '<!-- XML Sitemap generated by Yoast WordPress SEO -->';
$debug_display = defined( 'WP_DEBUG_DISPLAY' ) && true === WP_DEBUG_DISPLAY;
$debug = defined( 'WP_DEBUG' ) && true === WP_DEBUG;
$wpseo_debug = defined( 'WPSEO_DEBUG' ) && true === WPSEO_DEBUG;
if ( $debug_display && ( $debug || $wpseo_debug ) ) {
if ( $this->transient ) {
echo "\n", '<!-- ', number_format( ( <API key>() / 1024 / 1024 ), 2 ), 'MB | Served from transient cache -->';
}
else {
echo "\n", '<!-- ', number_format( ( <API key>() / 1024 / 1024 ), 2 ), 'MB | ', esc_attr( $GLOBALS['wpdb']->num_queries ), ' -->';
if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
echo "\n", '<!--', print_r( $GLOBALS['wpdb']->queries, true ), '-->';
}
}
}
}
/**
* Build the <url> tag for a given URL.
*
* @param array $url Array of parts that make up this entry
*
* @return string
*/
function sitemap_url( $url ) {
$date = null;
if ( ! empty( $url['mod'] ) ) {
// Create a DateTime object date in the correct timezone
$date = $this-><API key>( $url['mod'] );
}
$url['loc'] = htmlspecialchars( $url['loc'] );
$output = "\t<url>\n";
$output .= "\t\t<loc>" . $url['loc'] . "</loc>\n";
$output .= empty( $date ) ? '' : "\t\t<lastmod>" . $date->format( 'c' ) . "</lastmod>\n";
$output .= "\t\t<changefreq>" . $url['chf'] . "</changefreq>\n";
$output .= "\t\t<priority>" . str_replace( ',', '.', $url['pri'] ) . "</priority>\n";
if ( isset( $url['images'] ) && ( is_array( $url['images'] ) && $url['images'] !== array() ) ) {
foreach ( $url['images'] as $img ) {
if ( ! isset( $img['src'] ) || empty( $img['src'] ) ) {
continue;
}
$output .= "\t\t<image:image>\n";
$output .= "\t\t\t<image:loc>" . esc_html( $img['src'] ) . "</image:loc>\n";
if ( isset( $img['title'] ) && ! empty( $img['title'] ) ) {
$output .= "\t\t\t<image:title><![CDATA[" . _wp_specialchars( html_entity_decode( $img['title'], ENT_QUOTES, $this->charset ) ) . "]]></image:title>\n";
}
if ( isset( $img['alt'] ) && ! empty( $img['alt'] ) ) {
$output .= "\t\t\t<image:caption><![CDATA[" . _wp_specialchars( html_entity_decode( $img['alt'], ENT_QUOTES, $this->charset ) ) . "]]></image:caption>\n";
}
$output .= "\t\t</image:image>\n";
}
unset( $img );
}
$output .= "\t</url>\n";
return $output;
}
/**
* Make a request for the sitemap index so as to cache it before the arrival of the search engines.
*/
function hit_sitemap_index() {
$url = <API key>( 'sitemap_index.xml' );
wp_remote_get( $url );
}
/**
* Hook into redirect_canonical to stop trailing slashes on sitemap.xml URLs
*
* @param string $redirect The redirect URL currently determined.
*
* @return bool|string $redirect
*/
public function canonical( $redirect ) {
$sitemap = get_query_var( 'sitemap' );
if ( ! empty( $sitemap ) ) {
return false;
}
$xsl = get_query_var( 'xsl' );
if ( ! empty( $xsl ) ) {
return false;
}
return $redirect;
}
/**
* Get the modification date for the last modified post in the post type:
*
* @param array $post_types Post types to get the last modification date for
*
* @return string
*/
function get_last_modified( $post_types ) {
global $wpdb;
if ( ! is_array( $post_types ) ) {
$post_types = array( $post_types );
}
// We need to do this only once, as otherwise we'd be doing a query for each post type
if ( ! is_array( $this->post_type_dates ) ) {
$this->post_type_dates = array();
$query = "SELECT post_type, MAX(post_modified_gmt) AS date FROM $wpdb->posts WHERE post_status IN ('publish','inherit') AND post_type IN ('" . implode( "','", get_post_types( array( 'public' => true ) ) ) . "') GROUP BY post_type ORDER BY post_modified_gmt DESC";
$results = $wpdb->get_results( $query );
foreach ( $results as $obj ) {
$this->post_type_dates[ $obj->post_type ] = $obj->date;
}
unset( $query, $results, $obj );
}
if ( count( $post_types ) === 1 && isset( $this->post_type_dates[ $post_types[0] ] ) ) {
$result = $this->post_type_dates[ $post_types[0] ];
}
else {
$result = null;
foreach ( $post_types as $post_type ) {
if ( isset( $this->post_type_dates[ $post_type ] ) && strtotime( $this->post_type_dates[ $post_type ] ) > $result ) {
$result = $this->post_type_dates[ $post_type ];
}
}
unset( $post_type );
}
$date = new DateTime( $result, new DateTimeZone( $this->get_timezone_string() ) );
return $date->format( 'c' );
}
/**
* Get the datetime object is the datetime string was valid with a timezone
*
* @param string $datetime The datetime string that needs to be converted to a Datetime object
*
* @return DateTime|string
*/
private function <API key>( $datetime ) {
if ( ! empty( $datetime ) && WPSEO_Utils::is_valid_datetime( $datetime ) ) {
return new DateTime( $datetime, new DateTimeZone( $this->get_timezone_string() ) );
}
return null;
}
/**
* Sorts an array of WP_User by the <API key> meta field
*
* since 1.6
*
* @param Wp_User $a The first WP user
* @param Wp_User $b The second WP user
*
* @return int 0 if equal, 1 if $a is larger else or -1;
*/
private function user_map_sorter( $a, $b ) {
if ( ! isset( $a-><API key> ) ) {
$a-><API key> = time();
}
if ( ! isset( $b-><API key> ) ) {
$b-><API key> = time();
}
if ( $a-><API key> == $b-><API key> ) {
return 0;
}
return ( ( $a-><API key> > $b-><API key> ) ? 1 : -1 );
}
/**
* Filter users that should be excluded from the sitemap (by author metatag: <API key>).
*
* Also filtering users that should be exclude by excluded role.
*
* @param array $users
*
* @return array all the user that aren't excluded from the sitemap
*/
public function <API key>( $users ) {
if ( is_array( $users ) && $users !== array() ) {
$options = get_option( 'wpseo_xml' );
foreach ( $users as $user_key => $user ) {
$exclude_user = false;
$is_exclude_on = get_the_author_meta( '<API key>', $user->ID );
if ( $is_exclude_on === 'on' ) {
$exclude_user = true;
}
elseif ( $options['<API key>'] === true ) {
$count_posts = count_user_posts( $user->ID );
$exclude_user = ( $count_posts == 0 );
unset( $count_posts );
}
else {
$user_role = $user->roles[0];
$target_key = "user_role-{$user_role}-not_in_sitemap";
$exclude_user = $options[ $target_key ];
unset( $user_rol, $target_key );
}
if ( $exclude_user === true ) {
unset( $users[ $user_key ] );
}
}
}
return $users;
}
/**
* Get attached image URL - Adapted from core for speed
*
* @param int $post_id
*
* @return string
*/
private function image_url( $post_id ) {
static $uploads;
if ( empty( $uploads ) ) {
$uploads = wp_upload_dir();
}
if ( false !== $uploads['error'] ) {
return '';
}
$url = '';
if ( $file = get_post_meta( $post_id, '_wp_attached_file', true ) ) { // Get attached file
if ( 0 === strpos( $file, $uploads['basedir'] ) ) { // Check that the upload base exists in the file location
$url = str_replace( $uploads['basedir'], $uploads['baseurl'], $file );
}
// Replace file location with url location
elseif ( false !== strpos( $file, 'wp-content/uploads' ) ) {
$url = $uploads['baseurl'] . substr( $file, ( strpos( $file, 'wp-content/uploads' ) + 18 ) );
}
// It's a newly uploaded file, therefore $file is relative to the baseurl.
else {
$url = $uploads['baseurl'] . "/$file";
}
}
return $url;
}
/**
* Getting the attachments from database
*
* @param string $post_ids
*
* @return mixed
*/
private function get_attachments( $post_ids ) {
global $wpdb;
$child_query = "SELECT ID, post_title, post_parent FROM $wpdb->posts WHERE post_status = 'inherit' AND post_type = 'attachment' AND post_parent IN (" . $post_ids . ')';
$wpdb->query( $child_query );
$attachments = $wpdb->get_results( $child_query );
return $attachments;
}
/**
* Getting thumbnails
*
* @param array $post_ids
*
* @return mixed
*/
private function get_thumbnails( $post_ids ) {
global $wpdb;
$thumbnail_query = "SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = '_thumbnail_id' AND post_id IN (" . $post_ids . ')';
$wpdb->query( $thumbnail_query );
$thumbnails = $wpdb->get_results( $thumbnail_query );
return $thumbnails;
}
/**
* Parsing attachment_ids and do the caching
*
* Function will pluck ID from attachments and meta_value from thumbnails and marge them into one array. This
* array will be used to do the caching
*
* @param array $attachments
* @param array $thumbnails
*/
private function <API key>( $attachments, $thumbnails ) {
$attachment_ids = wp_list_pluck( $attachments, 'ID' );
$thumbnail_ids = wp_list_pluck( $thumbnails, 'meta_value' );
$attachment_ids = array_unique( array_merge( $thumbnail_ids, $attachment_ids ) );
_prime_post_caches( $attachment_ids );
update_meta_cache( 'post', $attachment_ids );
}
/**
* Parses the given attachments
*
* @param array $attachments
* @param stdobject $post
*
* @return array
*/
private function parse_attachments( $attachments, $post ) {
$return = array();
foreach ( $attachments as $attachment ) {
if ( $attachment->post_parent !== $post->ID ) {
continue;
}
$src = $this->image_url( $attachment->ID );
$image = array(
'src' => apply_filters( '<API key>', $src, $post )
);
$alt = get_post_meta( $attachment->ID, '<API key>', true );
if ( $alt !== '' ) {
$image['alt'] = $alt;
}
unset( $alt );
$image['title'] = $attachment->post_title;
$image = apply_filters( '<API key>', $image, $post );
$return[] = $image;
}
return $return;
}
/**
* Calculate the priority of the post
*
* @param stdobject $post
*
* @return float|mixed
*/
private function calculate_priority( $post ) {
$front_id = get_option( 'page_on_front' );
$pri = WPSEO_Meta::get_value( 'sitemap-prio', $post->ID );
if ( is_numeric( $pri ) ) {
$return = (float) $pri;
}
else {
if ( $post->post_parent == 0 && $post->post_type == 'page' ) {
$return = 0.8;
}
else {
$return = 0.6;
}
}
if ( isset( $front_id ) && $post->ID == $front_id ) {
$return = 1.0;
}
/**
* Filter: '<API key>' - Allow changing the priority of the URL
* WordPress SEO uses in the XML sitemap.
*
* @api float $priority The priority for this URL, ranging from 0 to 1
*
* @param string $post_type The post type this archive is for
* @param object $p The post object
*/
$return = apply_filters( '<API key>', $return, $post->post_type, $post );
return $return;
}
} /* End of class */ |
#pragma once
#include <dazzle.h>
G_BEGIN_DECLS
#define <API key> (<API key>())
<API key> (GbpMessagesPanel, gbp_messages_panel, GBP, MESSAGES_PANEL, DzlDockWidget)
G_END_DECLS |
package org.thoughtcrime.ssl.pinning;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.security.<API key>;
import java.security.KeyStoreException;
import java.security.<API key>;
import java.security.<API key>;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.<API key>;
import org.apache.http.params.<API key>;
import org.apache.http.params.HttpParams;
public class <API key> extends SSLSocketFactory {
private final javax.net.ssl.SSLSocketFactory <API key>;
/**
* Constructs a <API key> with a set of valid pins.
*
* @param pins An array of encoded pins to match a seen certificate
* chain against. A pin is a hex-encoded hash of a X.509 certificate's
* <API key>. A pin can be generated using the provided pin.py
* script: python ./tools/pin.py certificate_file.pem
*
* @param <API key> A timestamp (in milliseconds) when pins will stop being
* enforced. Normal non-pinned certificate validation
* will continue. Set this to some period after your build
* date, or to 0 to enforce pins forever.
*/
public <API key>(String[] pins,
long <API key>) throws <API key>,
<API key>, <API key>, KeyStoreException {
super(null);
final SystemKeyStore keyStore = SystemKeyStore.getInstance();
final SSLContext pinningSslContext = SSLContext.getInstance(TLS);
final TrustManager[] <API key> = <API key>(
keyStore, pins, <API key>);
pinningSslContext.init(null, <API key>, null);
this.<API key> = pinningSslContext.getSocketFactory();
}
@Override
public Socket createSocket() throws IOException {
return <API key>.createSocket();
}
@Override
public Socket connectSocket(final Socket sock, final String host,
final int port, final InetAddress localAddress, int localPort,
final HttpParams params) throws IOException {
final SSLSocket sslSock = (SSLSocket) ((sock != null) ? sock
: createSocket());
if ((localAddress != null) || (localPort > 0)) {
if (localPort < 0) {
localPort = 0;
}
sslSock.bind(new InetSocketAddress(localAddress, localPort));
}
final int connTimeout = <API key>
.<API key>(params);
final int soTimeout = <API key>.getSoTimeout(params);
final InetSocketAddress remoteAddress = new InetSocketAddress(host,
port);
sslSock.connect(remoteAddress, connTimeout);
sslSock.setSoTimeout(soTimeout);
try {
SSLSocketFactory.<API key>.verify(host, sslSock);
} catch (IOException iox) {
try {
sslSock.close();
} catch (Exception ignored) {
}
throw iox;
}
return sslSock;
}
@Override
public Socket createSocket(final Socket socket, final String host,
int port, final boolean autoClose) throws IOException {
if (port == -1) {
port = 443;
}
final SSLSocket sslSocket = (SSLSocket) <API key>
.createSocket(socket, host, port, autoClose);
SSLSocketFactory.<API key>.verify(host, sslSocket);
return sslSocket;
}
@Override
public void setHostnameVerifier(<API key> hostnameVerifier) {
throw new <API key>(
"Only strict hostname verification (default) "
+ "is supported!");
}
@Override
public <API key> getHostnameVerifier() {
return SSLSocketFactory.<API key>;
}
private TrustManager[] <API key>(
SystemKeyStore keyStore, String[] pins,
long <API key>) {
final TrustManager[] trustManagers = new TrustManager[1];
trustManagers[0] = new PinningTrustManager(keyStore, pins,
<API key>);
return trustManagers;
}
} |
import sys
from math import sqrt
def opr(f):
def op(registers, args):
registers[args[2]] = f(registers[args[0]], registers[args[1]])
return op
def opi(f):
def op(registers, args):
registers[args[2]] = f(registers[args[0]], args[1])
return op
def opir(f):
def op(registers, args):
registers[args[2]] = f(args[0], registers[args[1]])
return op
def setr(registers, args):
registers[args[2]] = registers[args[0]]
def seti(registers, args):
registers[args[2]] = args[0]
ops = {
'addr': opr(lambda a, b: a + b),
'addi': opi(lambda a, b: a + b),
'mulr': opr(lambda a, b: a * b),
'muli': opi(lambda a, b: a * b),
'banr': opr(lambda a, b: a & b),
'bani': opi(lambda a, b: a & b),
'borr': opr(lambda a, b: a | b),
'bori': opi(lambda a, b: a | b),
'setr': setr,
'seti': seti,
'gtrr': opr(lambda a, b: 1 if a > b else 0),
'gtri': opi(lambda a, b: 1 if a > b else 0),
'gtir': opir(lambda a, b: 1 if a > b else 0),
'eqrr': opr(lambda a, b: 1 if a == b else 0),
'eqri': opi(lambda a, b: 1 if a == b else 0),
'eqir': opir(lambda a, b: 1 if a == b else 0)
}
def step1(ip, instructions):
registers = [0, 0, 0, 0, 0, 0]
while 0 <= registers[ip] < len(instructions):
instruction = instructions[registers[ip]]
op = ops[instruction[0]]
op(registers, instruction[1:])
if registers[ip] + 1 >= len(instructions):
break
registers[ip] += 1
return registers[0]
def step2(ip, instructions):
registers = [1, 0, 0, 0, 0, 0]
while 0 <= registers[ip] < len(instructions):
if 2 == registers[ip] or 13 == registers[ip]:
# The instructions are an algorithm for summing divisors of register 2
num = registers[2]
r = 0
for i in range(1, int(sqrt(num)) + 1):
if num % i == 0:
r += i + num
return r
instruction = instructions[registers[ip]]
op = ops[instruction[0]]
op(registers, instruction[1:])
if registers[ip] + 1 >= len(instructions):
break
registers[ip] += 1
return registers[0]
def parse_input():
instructions = []
ip = None
for s in sys.stdin:
args = s.split()
if args[0] == '
ip = int(args[1])
else:
instructions += [[args[0]] + list(map(int, args[1:]))]
return ip, instructions
ip, instructions = parse_input()
print(step1(ip, instructions))
print(step2(ip, instructions)) |
#! /bin/bash
# Usage: $0
# Create VDM specification files from source file.
function writevdm {
# $1: File name
# $2: Module name
# Remove VDM++ comments:
SLFILE=`perl -p -e 's/^-- VDM\+\+:.*\n//g' $1.src`
# Create VDMSL flat file:
cat <<EOF>$1flat.vdm
$SLFILE
EOF
# Create VDMSL module file:
cat <<EOF>$1.vdm
module $2
exports all
definitions
$SLFILE
end $2
EOF
}
function writevpp {
# $1: File name
# $2: Class name
# Extract VDM++ comments:
PPFILE=`perl -p -e 's/^-- VDM\+\+: //g' $1.src`
# Create VDM++ file:
cat <<EOF>$1.vpp
class $2
$PPFILE
end $2
EOF
}
function writeall {
# $1: File name
# $2: Class/module name
writevdm $1 $2
writevpp $1 $2
}
NAME=MATH
name=math
writeall $name $NAME
NAME=IO
name=io
writeall $name $NAME
NAME=VDMUtil
name=VDMUtil
writeall $name $NAME
NAME=VDMByteUtil
name=VDMByteUtil
writeall $name $NAME |
#include "agent_interface.h"
#include "../common.h"
CAgentInterface::CAgentInterface()
{
this->agent_interface.id = get_unique_id();
this->agent_interface.body_type = <API key>;
}
CAgentInterface::CAgentInterface( struct sAgentInterface agent_interface,
class CAgentGroup *agent_group, unsigned long int group_id):CAgentBody(agent_interface.body_id)
{
this->agent_interface = agent_interface;
this->agent_group = agent_group;
this->agent_interface.fitness = 0.0;
this->agent_interface.agent_intensity = 1.0;
this->agent_interface.body_type = <API key>;
this->agent_interface.state = 0;
this->agent_interface.id = get_unique_id();
this->agent_interface.group_id = group_id;
this->agent_interface.robot_time = get_ms_time();
this->agent_interface.color.r = 1.0;
this->agent_interface.color.g = 1.0;
this->agent_interface.color.b = 1.0;
#ifdef _DEBUG_COMMON_
printf("%lu : agent interface created\n", (unsigned long int)this);
#endif
}
CAgentInterface::~CAgentInterface()
{
}
unsigned int CAgentInterface::get_id()
{
return agent_interface.id;
} |
#ifndef <API key>
#define <API key>
#include "vector.h"
namespace yamcr {
Vector <API key>(const Point2 &uv, float *pdf) {
float phi = 2.f * M_PI * uv[0];
float cosTheta = std::sqrt(uv[1]), sinTheta = std::sqrt(1.f - uv[1]);
Vector dir(std::cos(phi) * sinTheta,
std::sin(phi) * sinTheta,
cosTheta);
*pdf = cosTheta * (1.f / M_PI);
return dir;
}
Vector <API key>(const Point2 &uv, const Normal &n, float *pdf) {
Vector dir = <API key>(uv, pdf);
Vector s, t;
CoordinateSystem(n, s, t);
dir = Vector(s[0]*dir[0] + t[0]*dir[1] + n[0]*dir[2],
s[1]*dir[0] + t[1]*dir[1] + n[1]*dir[2],
s[2]*dir[0] + t[2]*dir[1] + n[2]*dir[2]);
return dir;
}
float <API key>(const Vector &dir, const Normal &n) {
float dot = dir.dot(n);
return dot < 0.f ? 0.f : dot * (1.f / M_PI);
}
}
#endif //<API key> |
package incboard.api;
/**
*
* @author RobertoPinho
*/
public interface DataItemInterface {
public String getURI();
public int getCol();
public int getRow();
void setCol(int x);
void setRow(int y);
public Double getDistance(DataItemInterface other);
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http:
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>localflavor.za.forms — django-localflavor 1.2 documentation</title>
<link rel="stylesheet" href="../../../_static/classic.css" type="text/css" />
<link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var <API key> = {
URL_ROOT: '../../../',
VERSION: '1.2',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../../../_static/jquery.js"></script>
<script type="text/javascript" src="../../../_static/underscore.js"></script>
<script type="text/javascript" src="../../../_static/doctools.js"></script>
<link rel="top" title="django-localflavor 1.2 documentation" href="../../../index.html" />
<link rel="up" title="Module code" href="../../index.html" />
</head>
<body role="document">
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../../../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../../../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="nav-item nav-item-0"><a href="../../../index.html">django-localflavor 1.2 documentation</a> »</li>
<li class="nav-item nav-item-1"><a href="../../index.html" accesskey="U">Module code</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<h1>Source code for localflavor.za.forms</h1><div class="highlight"><pre>
<span></span><span class="sd">"""</span>
<span class="sd">South Africa-specific Form helpers</span>
<span class="sd">"""</span>
<span class="kn">from</span> <span class="nn">__future__</span> <span class="kn">import</span> <span class="n">unicode_literals</span>
<span class="kn">import</span> <span class="nn">re</span>
<span class="kn">from</span> <span class="nn">datetime</span> <span class="kn">import</span> <span class="n">date</span>
<span class="kn">from</span> <span class="nn">django.core.validators</span> <span class="kn">import</span> <span class="n">EMPTY_VALUES</span>
<span class="kn">from</span> <span class="nn">django.forms</span> <span class="kn">import</span> <span class="n">ValidationError</span>
<span class="kn">from</span> <span class="nn">django.forms.fields</span> <span class="kn">import</span> <span class="n">CharField</span><span class="p">,</span> <span class="n">RegexField</span><span class="p">,</span> <span class="n">Select</span>
<span class="kn">from</span> <span class="nn">django.utils.translation</span> <span class="kn">import</span> <span class="n">gettext_lazy</span> <span class="k">as</span> <span class="n">_</span>
<span class="kn">from</span> <span class="nn">localflavor.generic.checksums</span> <span class="kn">import</span> <span class="n">luhn</span>
<span class="n">id_re</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">r'^(?P<yy>\d\d)(?P<mm>\d\d)(?P<dd>\d\d)(?P<mid>\d{4})(?P<end>\d{3})'</span><span class="p">)</span>
<div class="viewcode-block" id="ZAIDField"><a class="viewcode-back" href="../../../localflavor/za.html#localflavor.za.forms.ZAIDField">[docs]</a><span class="k">class</span> <span class="nc">ZAIDField</span><span class="p">(</span><span class="n">CharField</span><span class="p">):</span>
<span class="sd">"""</span>
<span class="sd"> A form field for South African ID numbers -- the checksum is validated</span>
<span class="sd"> using the Luhn checksum, and uses a simlistic (read: not entirely accurate)</span>
<span class="sd"> check for the birthdate</span>
<span class="sd"> """</span>
<span class="n"><API key></span> <span class="o">=</span> <span class="p">{</span>
<span class="s1">'invalid'</span><span class="p">:</span> <span class="n">_</span><span class="p">(</span><span class="s1">'Enter a valid South African ID number'</span><span class="p">),</span>
<span class="p">}</span>
<span class="k">def</span> <span class="nf">clean</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
<span class="nb">super</span><span class="p">(</span><span class="n">ZAIDField</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">clean</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="k">if</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">EMPTY_VALUES</span><span class="p">:</span>
<span class="k">return</span> <span class="s1">''</span>
<span class="c1"># strip spaces and dashes</span>
<span class="n">value</span> <span class="o">=</span> <span class="n">value</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s1">' '</span><span class="p">,</span> <span class="s1">''</span><span class="p">)</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s1">'-'</span><span class="p">,</span> <span class="s1">''</span><span class="p">)</span>
<span class="n">match</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="n">id_re</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">match</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">ValidationError</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">error_messages</span><span class="p">[</span><span class="s1">'invalid'</span><span class="p">])</span>
<span class="n">g</span> <span class="o">=</span> <span class="n">match</span><span class="o">.</span><span class="n">groupdict</span><span class="p">()</span>
<span class="k">try</span><span class="p">:</span>
<span class="c1"># The year 2000 is conveniently a leapyear.</span>
<span class="c1"># This algorithm will break in xx00 years which aren't leap years</span>
<span class="c1"># There is no way to guess the century of a ZA ID number</span>
<span class="n">date</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="n">g</span><span class="p">[</span><span class="s1">'yy'</span><span class="p">])</span> <span class="o">+</span> <span class="mi">2000</span><span class="p">,</span> <span class="nb">int</span><span class="p">(</span><span class="n">g</span><span class="p">[</span><span class="s1">'mm'</span><span class="p">]),</span> <span class="nb">int</span><span class="p">(</span><span class="n">g</span><span class="p">[</span><span class="s1">'dd'</span><span class="p">]))</span>
<span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
<span class="k">raise</span> <span class="n">ValidationError</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">error_messages</span><span class="p">[</span><span class="s1">'invalid'</span><span class="p">])</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">luhn</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
<span class="k">raise</span> <span class="n">ValidationError</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">error_messages</span><span class="p">[</span><span class="s1">'invalid'</span><span class="p">])</span>
<span class="k">return</span> <span class="n">value</span></div>
<div class="viewcode-block" id="ZAPostCodeField"><a class="viewcode-back" href="../../../localflavor/za.html#localflavor.za.forms.ZAPostCodeField">[docs]</a><span class="k">class</span> <span class="nc">ZAPostCodeField</span><span class="p">(</span><span class="n">RegexField</span><span class="p">):</span>
<span class="sd">"""</span>
<span class="sd"> A form field that validates input as a South African postcode. Valid</span>
<span class="sd"> postcodes must have four digits.</span>
<span class="sd"> """</span>
<span class="n"><API key></span> <span class="o">=</span> <span class="p">{</span>
<span class="s1">'invalid'</span><span class="p">:</span> <span class="n">_</span><span class="p">(</span><span class="s1">'Enter a valid South African postal code'</span><span class="p">),</span>
<span class="p">}</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">max_length</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">min_length</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="nb">super</span><span class="p">(</span><span class="n">ZAPostCodeField</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="s1">r'^\d{4}$'</span><span class="p">,</span>
<span class="n">max_length</span><span class="p">,</span> <span class="n">min_length</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span></div>
<div class="viewcode-block" id="ZAProvinceSelect"><a class="viewcode-back" href="../../../localflavor/za.html#localflavor.za.forms.ZAProvinceSelect">[docs]</a><span class="k">class</span> <span class="nc">ZAProvinceSelect</span><span class="p">(</span><span class="n">Select</span><span class="p">):</span>
<span class="sd">"""</span>
<span class="sd"> A Select widget that uses a list of South African Provinces as its choices.</span>
<span class="sd"> """</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">attrs</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
<span class="kn">from</span> <span class="nn">.za_provinces</span> <span class="kn">import</span> <span class="n">PROVINCE_CHOICES</span>
<span class="nb">super</span><span class="p">(</span><span class="n">ZAProvinceSelect</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="n">attrs</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="n">PROVINCE_CHOICES</span><span class="p">)</span></div>
</pre></div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="<API key>">
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="../../../search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../../../genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="../../../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="nav-item nav-item-0"><a href="../../../index.html">django-localflavor 1.2 documentation</a> »</li>
<li class="nav-item nav-item-1"><a href="../../index.html" >Module code</a> »</li>
</ul>
</div>
<div class="footer" role="contentinfo">
© Copyright Django Software Foundation and individual contributors.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.4.1.
</div>
</body>
</html> |
using VariantAnnotation.AnnotatedPositions.Transcript;
using Xunit;
namespace UnitTests.VariantAnnotation.AnnotatedPositions.Transcript
{
public sealed class <API key>
{
[Theory]
[InlineData(null,null,0)]
[InlineData("abc",null,0)]
[InlineData("abc", "abgg", 2)]
[InlineData("abcfdg", "abgg", 2)]
public void CommonPrefixLength(string a, string b, int expResult)
{
Assert.Equal(expResult,a.CommonPrefixLength(b));
}
[Theory]
[InlineData(null, null, 0)]
[InlineData("abc", null, 0)]
[InlineData("abc", "abgg", 0)]
[InlineData("abcfdg", "abgg", 1)]
public void CommonSuffixLength(string a, string b, int expResult)
{
Assert.Equal(expResult, a.CommonSuffixLength(b));
}
}
} |
#!/usr/bin/python
# provided that the following conditions are met:
# * Ciaran Farrell, the buttermill project and its contributors may not be used to endorse or
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# 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.
# This script parses the output of the buttermill wind logger
from datetime import datetime
import sys
import os
import re
# these config settings should be taken from your anemometer handbook
ROTOR_1 = 1.144
ROTOR_2 = 1.144
ROTOR_3 = 1.144
class ButtermillParser:
def __init__(self,input_file):
try:
self.fd = open(input_file,'r')
except IOError,e:
raise IOError,"Could not open %s for parsing: %s"%(input_file,str(e))
else:
pass
self.data_container = [] # all reading dicts are stored here
self.badlines = [] # store the lines that didn't parse too
self.gaga = []
def parse(self):
# TODO: secs=1285858049 w1=294 w2=365 w3=482 temp=+26 light=005
# Some of the strings written to the sd card are corrupted - there are some
# corruptions which occur often enough in the same place that we can subsitute
# the corrupted character. For example secs= is normally correctly written but
# there are numerous examples of sec3= being written
pattern = re.compile(r'sec[3s]=(?P<secs>[\d]+)\s.*?w1=\s*(?P<w1>[\d]+)\s.*?w2=\s*(?P<w2>[\d]+)\s.*?w3=\s*(?P<w3>[\d]+)\s.*?temp=\s*(?P<t>[\+\-]?[\.\d]+)\s.*?light=\s*(?P<l>[\d]+)')
i = 0 # keep count of where we are (needed to avoid certain lines)
for line in self.fd:
m = pattern.match(line)
if not m:
self.badlines.append(line)
continue
else:
try:
p = self.data_container[i-1]
except IndexError:
have_predecessor = False
else:
have_predecessor = True
container = {}
container['raw_secs'] = int(m.groupdict()['secs'])
container['tstamp'] = datetime.fromtimestamp(container['raw_secs'])
if container['tstamp'].year != 2010:
self.gaga.append(line)
container['raw_w1'] = int(m.groupdict()['w1'])
if have_predecessor:
old_secs = self.data_container[i-1]['raw_secs']
secs_passed = container['raw_secs'] - old_secs
container['w1_ticks_per_sec'] = (container['raw_w1']/secs_passed)*1.0 # pulses per sec (as float)
container['w1_avg_ms'] = container['w1_ticks_per_sec']*ROTOR_1
container['raw_w2'] = int(m.groupdict()['w2'])
if have_predecessor:
old_secs = self.data_container[i-1]['raw_secs']
secs_passed = container['raw_secs'] - old_secs
container['w2_ticks_per_sec'] = (container['raw_w2']/secs_passed)*1.0 # pulses per sec (as float)
container['w2_avg_ms'] = container['w2_ticks_per_sec']*ROTOR_2
container['raw_w3'] = int(m.groupdict()['w3'])
if have_predecessor:
old_secs = self.data_container[i-1]['raw_secs']
secs_passed = container['raw_secs'] - old_secs
container['w3_ticks_per_sec'] = (container['raw_w3']/secs_passed)*1.0 # pulses per sec (as float)
container['w3_avg_ms'] = container['w3_ticks_per_sec']*ROTOR_3
t = m.groupdict()['t']
if t.startswith('+'):
t = float(t.strip('+'))
else:
t = -1.0*(float(t.strip('-')))
container['temp'] = t
container['light'] = int(m.groupdict()['l'])
self.data_container.append(container)
i+=1
def __calcmean__(self,entries):
if len(entries) == 0:
raise StandardError,'Division by zero because of empty input list'
return float(sum(entries)/len(entries))
def mean(self,period='daily'):
yearly,monthly,weekly,daily,hourly,minutely = {},{},{},{},{},{}
period = period.lower()
if period not in ['minutely','hourly','daily','weekly','monthly','yearly']:
raise StandardError, '%s is not a recognised mean period'%period
if len(self.data_container) == 0:
raise StandardError, 'There is no data available in the data container'
if period == 'yearly':
for entry in self.data_container[1:]:
t = entry
if yearly.has_key(t['tstamp'].year):
yearly[t['tstamp'].year]['r1'].append(t['w1_avg_ms'])
yearly[t['tstamp'].year]['r2'].append(t['w2_avg_ms'])
yearly[t['tstamp'].year]['r3'].append(t['w3_avg_ms'])
yearly[t['tstamp'].year]['t'].append(t['temp'])
yearly[t['tstamp'].year]['l'].append(t['light'])
else:
yearly[t['tstamp'].year] = {'r1':[t['w1_avg_ms']],'r2':[t['w2_avg_ms']],'r3':[t['w3_avg_ms']],\
't':[t['temp']],'l':[t['light']]}
means = {}
for year in yearly.keys():
means[year] = {}
yearly[year]['r1_mean'] = self.__calcmean__(yearly[year]['r1'])
means[year]['r1'] = yearly[year]['r1_mean']
yearly[year]['r2_mean'] = self.__calcmean__(yearly[year]['r2'])
means[year]['r2'] = yearly[year]['r2_mean']
yearly[year]['r3_mean'] = self.__calcmean__(yearly[year]['r3'])
means[year]['r3'] = yearly[year]['r3_mean']
yearly[year]['t_mean'] = self.__calcmean__(yearly[year]['t'])
means[year]['t'] = yearly[year]['t_mean']
yearly[year]['l_mean'] = self.__calcmean__(yearly[year]['l'])
means[year]['l'] = yearly[year]['l_mean']
return means
if period == 'monthly':
for entry in self.data_container[1:]:
t = entry
month_key = t['tstamp'].strftime("%Y-%m")
if monthly.has_key(month_key):
monthly[month_key]['r1'].append(t['w1_avg_ms'])
monthly[month_key]['r2'].append(t['w2_avg_ms'])
monthly[month_key]['r3'].append(t['w3_avg_ms'])
monthly[month_key]['t'].append(t['temp'])
monthly[month_key]['l'].append(t['light'])
else:
monthly[month_key] = {'r1':[t['w1_avg_ms']],'r2':[t['w2_avg_ms']],'r3':[t['w3_avg_ms']],\
't':[t['temp']],'l':[t['light']]}
means = {}
for month in monthly.keys():
means[month] = {}
monthly[month]['r1_mean'] = self.__calcmean__(monthly[month]['r1'])
means[month]['r1'] = monthly[month]['r1_mean']
monthly[month]['r2_mean'] = self.__calcmean__(monthly[month]['r2'])
means[month]['r2'] = monthly[month]['r2_mean']
monthly[month]['r3_mean'] = self.__calcmean__(monthly[month]['r3'])
means[month]['r3'] = monthly[month]['r3_mean']
monthly[month]['t_mean'] = self.__calcmean__(monthly[month]['t'])
means[month]['t'] = monthly[month]['t_mean']
monthly[month]['l_mean'] = self.__calcmean__(monthly[month]['l'])
means[month]['l'] = monthly[month]['l_mean']
return means
if period == 'weekly':
for entry in self.data_container[1:]:
t = entry
month_key = t['tstamp'].strftime("%Y-%m")
if monthly.has_key(month_key):
monthly[month_key]['r1'].append(t['w1_avg_ms'])
monthly[month_key]['r2'].append(t['w2_avg_ms'])
monthly[month_key]['r3'].append(t['w3_avg_ms'])
monthly[month_key]['t'].append(t['temp'])
monthly[month_key]['l'].append(t['light'])
else:
monthly[month_key] = {'r1':[t['w1_avg_ms']],'r2':[t['w2_avg_ms']],'r3':[t['w3_avg_ms']],\
't':[t['temp']],'l':[t['light']]}
means = {}
for month in monthly.keys():
means[month] = {}
monthly[month]['r1_mean'] = self.__calcmean__(monthly[month]['r1'])
means[month]['r1'] = monthly[month]['r1_mean']
monthly[month]['r2_mean'] = self.__calcmean__(monthly[month]['r2'])
means[month]['r2'] = monthly[month]['r2_mean']
monthly[month]['r3_mean'] = self.__calcmean__(monthly[month]['r3'])
means[month]['r3'] = monthly[month]['r3_mean']
monthly[month]['t_mean'] = self.__calcmean__(monthly[month]['t'])
means[month]['t'] = monthly[month]['t_mean']
monthly[month]['l_mean'] = self.__calcmean__(monthly[month]['l'])
means[month]['l'] = monthly[month]['l_mean']
return means
if period == 'daily':
for entry in self.data_container[1:]:
t = entry
day_key = t['tstamp'].strftime("%Y-%m-%d")
if daily.has_key(day_key):
daily[day_key]['r1'].append(t['w1_avg_ms'])
daily[day_key]['r2'].append(t['w2_avg_ms'])
daily[day_key]['r3'].append(t['w3_avg_ms'])
daily[day_key]['t'].append(t['temp'])
daily[day_key]['l'].append(t['light'])
else:
daily[day_key] = {'r1':[t['w1_avg_ms']],'r2':[t['w2_avg_ms']],'r3':[t['w3_avg_ms']],\
't':[t['temp']],'l':[t['light']]}
means = {}
for day in daily.keys():
means[day] = {}
daily[day]['r1_mean'] = self.__calcmean__(daily[day]['r1'])
means[day]['r1'] = daily[day]['r1_mean']
daily[day]['r2_mean'] = self.__calcmean__(daily[day]['r2'])
means[day]['r2'] = daily[day]['r2_mean']
daily[day]['r3_mean'] = self.__calcmean__(daily[day]['r3'])
mean[day]['r3'] = daily[day]['r3_mean']
daily[day]['t_mean'] = self.__calcmean__(daily[day]['t'])
mean[day]['t'] = daily[day]['t_mean']
daily[day]['l_mean'] = self.__calcmean__(daily[day]['l'])
mean[day]['l'] = daily[day]['l_mean']
return means
if __name__ == '__main__':
from optparse import OptionParser
oparser = OptionParser()
(options, args) = oparser.parse_args()
if len(args) != 1:
oparser.error("You need to provide this script with exactly one argument - the DATA.txt file produced by the buttermill")
sys.exit(1)
else:
parser = ButtermillParser(args[0])
parser.parse()
for r in parser.data_container[1:]: # we didn't parse the first item in the list (see above)
print "%s\trotor 1: %.2f m/s\trotor 2: %.2f m/s\trotor 3: %.2f m/s\ttemp: %d light: %s"%(datetime.strftime(r['tstamp'],"%Y-%m-%d %H:%M:%S"),r['w1_avg_ms'],r['w2_avg_ms'],r['w3_avg_ms'],r['temp'],r['light']) |
# <API key>
The Other Maps style for Architectural Styles of buildings |
/* This file is part of the program and library */
/* fuer Informationstechnik Berlin */
/* along with SCIP; see the file COPYING. If not email to scip@zib.de. */
/**@file branch_leastinf.c
* @brief least infeasible LP branching rule
* @author Tobias Achterberg
* @author Stefan Vigerske
*/
#include <assert.h>
#include <string.h>
#include "scip/branch_leastinf.h"
#define BRANCHRULE_NAME "leastinf"
#define BRANCHRULE_DESC "least infeasible branching"
#define BRANCHRULE_PRIORITY 50
#define BRANCHRULE_MAXDEPTH -1
#define <API key> 1.0
/*
* Local methods
*/
/** compares the so far best branching candidate with a new candidate and updates best candidate, if new candidate is better */
static
void updateBestCandidate(
SCIP* scip, /**< SCIP data structure */
SCIP_VAR** bestvar, /**< best branching candidate */
SCIP_Real* bestscore, /**< score of best branching candidate */
SCIP_Real* bestobj, /**< absolute objective value of best branching candidate */
SCIP_Real* bestsol, /**< proposed branching point of best branching candidate */
SCIP_VAR* cand, /**< branching candidate to consider */
SCIP_Real candscore, /**< scoring of branching candidate */
SCIP_Real candsol /**< proposed branching point of branching candidate */
)
{
SCIP_Real obj;
assert(scip != NULL);
assert(bestvar != NULL);
assert(bestscore != NULL);
assert(bestobj != NULL);
assert(*bestobj >= 0.0);
assert(cand != NULL);
/* a branching variable candidate should either be an active problem variable or a multi-aggregated variable */
assert(SCIPvarIsActive(SCIPvarGetProbvar(cand)) ||
SCIPvarGetStatus(SCIPvarGetProbvar(cand)) == <API key>);
if( SCIPvarGetStatus(SCIPvarGetProbvar(cand)) == <API key> )
{
/* for a multi-aggregated variable, we call updateBestCandidate function recursively with all variables in the multi-aggregation */
SCIP_VAR** multvars;
int nmultvars;
int i;
SCIP_Bool success;
SCIP_Real multvarlb;
SCIP_Real multvarub;
cand = SCIPvarGetProbvar(cand);
multvars = <API key>(cand);
nmultvars = <API key>(cand);
/* if we have a candidate branching point, then first register only aggregation variables
* for which we can compute a corresponding branching point too (see also comments below)
* if this fails, then register all (unfixed) aggregation variables, thereby forgetting about candsol
*/
success = FALSE;
if( candsol != SCIP_INVALID ) /*lint !e777*/
{
SCIP_Real* multscalars;
SCIP_Real minact;
SCIP_Real maxact;
SCIP_Real aggrvarsol;
SCIP_Real aggrvarsol1;
SCIP_Real aggrvarsol2;
multscalars = <API key>(cand);
/* for computing the branching point, we need the current bounds of the multi-aggregated variable */
minact = <API key>(scip, cand);
maxact = <API key>(scip, cand);
for( i = 0; i < nmultvars; ++i )
{
/* skip fixed variables */
multvarlb = <API key>(scip, multvars[i]);
multvarub = <API key>(scip, multvars[i]);
if( SCIPisEQ(scip, multvarlb, multvarub) )
continue;
assert(multscalars != NULL);
assert(multscalars[i] != 0.0);
/* we cannot ensure that both the upper bound in the left node and the lower bound in the right node
* will be candsol by a clever choice for the branching point of multvars[i],
* but we can try to ensure that at least one of them will be at candsol
*/
if( multscalars[i] > 0.0 )
{
/* cand >= candsol
* if multvars[i] >= (candsol - (maxact - multscalars[i] * ub(multvars[i]))) / multscalars[i]
* = (candsol - maxact) / multscalars[i] + ub(multvars[i])
*/
aggrvarsol1 = (candsol - maxact) / multscalars[i] + multvarub;
/* cand <= candsol
* if multvars[i] <= (candsol - (minact - multscalar[i] * lb(multvars[i]))) / multscalars[i]
* = (candsol - minact) / multscalars[i] + lb(multvars[i])
*/
aggrvarsol2 = (candsol - minact) / multscalars[i] + multvarlb;
}
else
{
/* cand >= candsol
* if multvars[i] <= (candsol - (maxact - multscalars[i] * lb(multvars[i]))) / multscalars[i]
* = (candsol - maxact) / multscalars[i] + lb(multvars[i])
*/
aggrvarsol2 = (candsol - maxact) / multscalars[i] + multvarlb;
/* cand <= candsol
* if multvars[i] >= (candsol - (minact - multscalar[i] * ub(multvars[i]))) / multscalars[i]
* = (candsol - minact) / multscalars[i] + ub(multvars[i])
*/
aggrvarsol1 = (candsol - minact) / multscalars[i] + multvarub;
}
/* by the above choice, aggrvarsol1 <= ub(multvars[i]) and aggrvarsol2 >= lb(multvars[i])
* if aggrvarsol1 <= lb(multvars[i]) or aggrvarsol2 >= ub(multvars[i]), then choose the other one
* if both are out of bounds, then give up
* if both are inside bounds, then choose the one closer to 0.0 (someone has better idea???)
*/
if( SCIPisFeasLE(scip, aggrvarsol1, multvarlb) )
{
if( SCIPisFeasGE(scip, aggrvarsol2, multvarub) )
continue;
else
aggrvarsol = aggrvarsol2;
}
else
{
if( SCIPisFeasGE(scip, aggrvarsol2, multvarub) )
aggrvarsol = aggrvarsol1;
else
aggrvarsol = REALABS(aggrvarsol1) < REALABS(aggrvarsol2) ? aggrvarsol1 : aggrvarsol2;
}
success = TRUE;
updateBestCandidate(scip, bestvar, bestscore, bestobj, bestsol,
multvars[i], candscore, aggrvarsol);
}
}
if( !success )
for( i = 0; i < nmultvars; ++i )
{
/* skip fixed variables */
multvarlb = <API key>(scip, multvars[i]);
multvarub = <API key>(scip, multvars[i]);
if( SCIPisEQ(scip, multvarlb, multvarub) )
continue;
updateBestCandidate(scip, bestvar, bestscore, bestobj, bestsol,
multvars[i], candscore, SCIP_INVALID);
}
assert(*bestvar != NULL); /* if all variables were fixed, something is strange */
return;
}
candscore *= <API key>(cand);
obj = SCIPvarGetObj(cand);
obj = REALABS(obj);
if( SCIPisInfinity(scip, *bestscore)
|| (!SCIPisInfinity(scip, candscore) &&
(SCIPisLT(scip, candscore, *bestscore) || (SCIPisLE(scip, candscore, *bestscore) && obj > *bestobj))) )
{
*bestvar = cand;
*bestscore = candscore;
*bestobj = obj;
*bestsol = candsol;
}
}
/*
* Callback methods
*/
/** copy method for branchrule plugins (called when SCIP copies plugins) */
static
<API key>(branchCopyLeastinf)
{ /*lint --e{715}*/
assert(scip != NULL);
assert(branchrule != NULL);
assert(strcmp(<API key>(branchrule), BRANCHRULE_NAME) == 0);
/* call inclusion method of branchrule */
SCIP_CALL( <API key>(scip) );
return SCIP_OKAY;
}
/** branching execution method for fractional LP solutions */
static
<API key>(<API key>)
{ /*lint --e{715}*/
SCIP_VAR** lpcands;
SCIP_Real* lpcandsfrac;
int nlpcands;
SCIP_Real infeasibility;
SCIP_Real score;
SCIP_Real obj;
SCIP_Real bestscore;
SCIP_Real bestobj;
int bestcand;
int i;
assert(branchrule != NULL);
assert(strcmp(<API key>(branchrule), BRANCHRULE_NAME) == 0);
assert(scip != NULL);
assert(result != NULL);
SCIPdebugMsg(scip, "Execlp method of leastinf branching\n");
/* get branching candidates */
SCIP_CALL( <API key>(scip, &lpcands, NULL, &lpcandsfrac, NULL, &nlpcands, NULL) );
assert(nlpcands > 0);
/* search the least infeasible candidate */
bestscore = SCIP_REAL_MIN;
bestobj = 0.0;
bestcand = -1;
for( i = 0; i < nlpcands; ++i )
{
assert(lpcands[i] != NULL);
infeasibility = lpcandsfrac[i];
infeasibility = MIN(infeasibility, 1.0-infeasibility);
score = 1.0 - infeasibility;
score *= <API key>(lpcands[i]);
obj = SCIPvarGetObj(lpcands[i]);
obj = REALABS(obj);
if( SCIPisGT(scip, score, bestscore)
|| (SCIPisGE(scip, score, bestscore) && obj > bestobj) )
{
bestscore = score;
bestobj = obj;
bestcand = i;
}
}
assert(bestcand >= 0);
SCIPdebugMsg(scip, " -> %d candidates, selected candidate %d: variable <%s> (frac=%g, obj=%g, factor=%g, score=%g)\n",
nlpcands, bestcand, SCIPvarGetName(lpcands[bestcand]), lpcandsfrac[bestcand], bestobj,
<API key>(lpcands[bestcand]), bestscore);
/* perform the branching */
SCIP_CALL( SCIPbranchVar(scip, lpcands[bestcand], NULL, NULL, NULL) );
*result = SCIP_BRANCHED;
return SCIP_OKAY;
}
/** branching execution method for external candidates */
static
<API key>(<API key>)
{ /*lint --e{715}*/
SCIP_VAR** externcands;
SCIP_Real* externcandssol;
SCIP_Real* externcandsscore;
int nexterncands;
SCIP_VAR* bestcand;
SCIP_Real bestscore;
SCIP_Real bestobj;
SCIP_Real bestsol;
SCIP_Real brpoint;
int i;
SCIP_NODE* downchild;
SCIP_NODE* eqchild;
SCIP_NODE* upchild;
assert(branchrule != NULL);
assert(strcmp(<API key>(branchrule), BRANCHRULE_NAME) == 0);
assert(scip != NULL);
assert(result != NULL);
SCIPdebugMsg(scip, "Execext method of leastinf branching\n");
/* get branching candidates */
SCIP_CALL( <API key>(scip, &externcands, &externcandssol, &externcandsscore, NULL, &nexterncands, NULL, NULL, NULL) );
assert(nexterncands > 0);
/* search the least infeasible candidate */
bestscore = SCIPinfinity(scip);
bestobj = 0.0;
bestcand = NULL;
bestsol = SCIP_INVALID;
for( i = 0; i < nexterncands; ++i )
{
updateBestCandidate(scip, &bestcand, &bestscore, &bestobj, &bestsol, externcands[i], externcandsscore[i], externcandssol[i]);
}
if( bestcand == NULL )
{
SCIPerrorMessage("<API key> failed to select a branching variable from %d candidates\n", nexterncands);
*result = SCIP_DIDNOTRUN;
return SCIP_OKAY;
}
brpoint = <API key>(scip, bestcand, bestsol);
SCIPdebugMsg(scip, " -> %d candidates, selected variable <%s> (infeas=%g, obj=%g, factor=%g, score=%g), branching point=%g\n",
nexterncands, SCIPvarGetName(bestcand), bestsol, bestobj,
<API key>(bestcand), bestscore, brpoint);
/* perform the branching */
SCIP_CALL( SCIPbranchVarVal(scip, bestcand, brpoint, &downchild, &eqchild, &upchild) );
if( downchild != NULL || eqchild != NULL || upchild != NULL )
{
*result = SCIP_BRANCHED;
}
else
{
/* if there are no children, then variable should have been fixed by SCIPbranchVarVal */
assert(SCIPisEQ(scip, SCIPvarGetLbLocal(bestcand), SCIPvarGetUbLocal(bestcand)));
*result = SCIP_REDUCEDDOM;
}
return SCIP_OKAY;
}
/*
* branching specific interface methods
*/
/** creates the least infeasible LP branching rule and includes it in SCIP */
SCIP_RETCODE <API key>(
SCIP* scip /**< SCIP data structure */
)
{
SCIP_BRANCHRULE* branchrule;
/* include branching rule */
branchrule = NULL;
SCIP_CALL( <API key>(scip, &branchrule, BRANCHRULE_NAME, BRANCHRULE_DESC, BRANCHRULE_PRIORITY,
BRANCHRULE_MAXDEPTH, <API key>, NULL) );
assert(branchrule != NULL);
SCIP_CALL( <API key>(scip, branchrule, branchCopyLeastinf) );
SCIP_CALL( <API key>(scip, branchrule, <API key>) );
SCIP_CALL( <API key>(scip, branchrule, <API key>) );
return SCIP_OKAY;
} |
#include "bitfieldwidget.h"
#include "ui_bitfieldwidget.h"
#include "math.h"
using namespace adiscope;
BitfieldWidget::BitfieldWidget(QWidget *parent, QDomElement *bitfield) :
QWidget(parent),
ui(new Ui::BitfieldWidget()),
bitfield(bitfield)
{
ui->setupUi(this);
/*get bitfield information from the element*/
name = bitfield->firstChildElement("Name").text();
width = bitfield->firstChildElement("Width").text().toInt();
access = bitfield->firstChildElement("Access").text();
description = bitfield->firstChildElement("Description").text();
notes = bitfield->firstChildElement("Notes").text();
regOffset = bitfield->firstChildElement("RegOffset").text().toInt();
sliceWidth = bitfield->firstChildElement("SliceWidth").text().toInt();
defaultValue = bitfield->firstChildElement("DefaultValue").text().toInt();
options = bitfield->firstChildElement("Options");
createWidget(); //build the widget
}
BitfieldWidget::BitfieldWidget(QWidget *parent, int bitNumber) :
QWidget(parent),
ui(new Ui::BitfieldWidget())
{
ui->setupUi(this);
ui->bitLabel->setText(QString(" Bit %1 ").arg(bitNumber, 0, 10));
ui->descriptionLabel->hide();
ui->stackedWidget->setCurrentIndex(1);
sliceWidth = 1;
regOffset = bitNumber;
width = 1;
defaultValue = 0;
ui->valueSpinBox->setEnabled(false);
ui->valueSpinBox->setMaximum(1);
connect(ui->valueSpinBox, SIGNAL(valueChanged(int)), this,
SLOT(setValue(int))); //connect spinBox singnal to the value changed signal
}
BitfieldWidget::~BitfieldWidget()
{
delete ui;
}
void BitfieldWidget::createWidget()
{
QLabel *label;
ui->descriptionLabel->setText(name);
ui->bitLabel->setText(QString("Bit %1 ").arg(regOffset));
for (int i = 1; i < width; i++) {
label = new QLabel(this);
label->setText(QString("Bit %1 ").arg(regOffset + i));
ui->bitHorizontalLayout->insertWidget(1,label);
}
/*Set comboBox or spinBox*/
if (options.isNull()) {
/*set spinBox*/
ui->stackedWidget->setCurrentIndex(1);
int temp = (int)pow(2, width) - 1;
ui->valueSpinBox->setMaximum(temp);
connect(ui->valueSpinBox, SIGNAL(valueChanged(int)), this,
SLOT(setValue(int))); //connect spinBox singnal to the value changed signal
} else {
/*set comboBox*/
ui->stackedWidget->setCurrentIndex(0);
QDomElement temp = options.firstChildElement("Option");
while (options.lastChildElement() != temp) {
ui->valueComboBox->addItem(temp.firstChildElement("Description").text());
temp = temp.nextSiblingElement();
}
ui->valueComboBox->addItem(temp.firstChildElement("Description").text());
connect(ui->valueComboBox,SIGNAL(currentIndexChanged(int)), this,
SLOT(setValue(int))); //connect comboBox signal to the value changed signal
}
}
void BitfieldWidget::updateValue(uint32_t& value)
{
int temp = value & ((uint32_t)pow(2, width) - 1);
if (ui->stackedWidget->currentIndex() == 1) {
ui->valueSpinBox->setValue(temp);
} else {
ui->valueComboBox->setCurrentIndex(value & ((uint32_t)pow(2, width) - 1));
}
value = (value >> width);
}
int BitfieldWidget::getRegOffset() const
{
return regOffset;
}
int BitfieldWidget::getSliceWidth() const
{
return sliceWidth;
}
void BitfieldWidget::setValue(int value)
{
this->value = value << regOffset;
uint32_t mask = (uint32_t)(pow(2, width) - 1) << regOffset;
Q_EMIT valueChanged(this->value, mask);
}
uint32_t BitfieldWidget::getDefaultValue(void) const
{
return defaultValue;
} |
#include <stdlib.h>
#include <time.h>
#include <errno.h>
#include <string.h>
#include "cw/capwap.h"
#include "cw/conn.h"
#include "cw/radioinfo.h"
#include "cw/log.h"
#include "cw/dtls.h"
#include "cw/sock.h"
#include "cw/cw_util.h"
#include "cw/capwap_items.h"
#include "wtp_conf.h"
#include "cw/timer.h"
#include "cw/capwap.h"
#include "cw/conn.h"
#include "wtp_interface.h"
int run()
{
struct conn *conn = get_conn();
conn->capwap_state = CW_STATE_RUN;
do {
int echo_interval = mbag_get_word(conn->config,<API key>,CAPWAP_TIMERS)&0xff;
time_t timer = cw_timer_start(echo_interval);
int rc;
while (!cw_timer_timeout(timer) && conn->capwap_state == CW_STATE_RUN) {
rc = cw_read_messages(conn);
if (rc < 0 && errno == EAGAIN) {
continue;
}
if ( !cw_rcok(rc))
break;
}
if (rc<0 && errno == EAGAIN){
rc = cw_send_request(conn,CW_MSG_ECHO_REQUEST);
if (!cw_rcok(rc)) {
cw_log(LOG_ERR,"Error in run state: %d %s",rc,cw_strrc(rc));
break;
}
continue;
}
if (!cw_rcok(rc)) {
cw_log(LOG_ERR,"Error in run state: %d %s",rc,cw_strrc(rc));
break;
}
} while (conn->capwap_state == CW_STATE_RUN);
// int rc = cw_send_request(conn,<API key>);
// if ( !cw_rcok(rc) ) {
// cw_strresult(rc);
return 0;
}
/*
static int echo_interval_timer;
struct cwrmsg * get_response(struct conn * conn, int type,int seqnum)
{
struct cwrmsg * cwrmsg;
int i;
for(i=0; i<<API key>; i++){
cwrmsg = conn_get_message(conn);
if ( cwrmsg==0){
//printf("null message \n");
continue;
}
if (cwrmsg->type==type && cwrmsg->seqnum==seqnum)
return cwrmsg;
printf("another message was detected %i %i\n",cwrmsg->type,cwrmsg->seqnum);
}
return 0;
}
*/
/*
struct cwrmsg * send_request(struct conn * conn,struct cwmsg *cwmsg)
{
int i;
for (i=0; i<conf_max_retransmit; i++){
#ifdef WITH_CW_LOG_DEBUG
if (i>0){
// cw_log_debug1("Retransmitting request, type=%i,seqnum=%i",cwmsg->type,cwmsg->seqnum);
}
#endif
int rc = conn_send_cwmsg(conn,cwmsg);
if (rc<0){
// cw_log_debug1("Error sending request, type=%i, seqnum %i, %s",cwmsg->type,cwmsg->seqnum,strerror(errno));
return 0;
}
struct cwrmsg * r = get_response(conn,cwmsg->type+1,cwmsg->seqnum);
if (r)
return r;
}
return 0;
}
*/
//extern struct conn * get_conn();
/*
int run(struct conn * conn)
{
conn = get_conn();
printf("Running with conn %p\n");
struct radioinfo radioinfo;
memset(&radioinfo,0,sizeof(radioinfo));
struct cwrmsg * cwrmsg;
echo_interval_timer=time(NULL);
while (1){
if (time(NULL)-echo_interval_timer >= conf_echo_interval)
{
// struct cwmsg cwmsg;
// uint8_t buffer[CWMSG_MAX_SIZE];
// cwsend_echo_request(conn,&radioinfo);
// cw_log_debug1("Sending echo request");
struct cwmsg *cwmsg=&conn->req_msg;
uint8_t * buffer = conn->req_buffer;
struct wtpinfo * wtpinfo = get_wtpinfo();
struct radioinfo *rip = &(wtpinfo->radioinfo[0]);
<API key>(cwmsg,buffer,conn,rip);
printf("Echo ->>>>>>>>>>>>>>>>>>>>> Seqnum %d\n",conn->req_msg.seqnum);
printf("Conn target is %s",sock_addr2str(&conn->addr));
printf("Calling conn send req\n");
printf("conn max retrans: %d\n",conn->max_retransmit);
struct cwrmsg * rc = conn_send_request(conn);
printf("Back from conn send req\n");
// printf("conn->seqnum %i\n",conn->seqnum);
// struct cwrmsg * rc = get_response(conn,CWMSG_ECHO_RESPONSE,conn->seqnum);
if (rc==0){
printf("Error !\n");
// dtls_shutdown(conn);
// cw_log_debug1("Connection lost, no echo response");
// return 0;
}
echo_interval_timer=time(NULL);
}
time_t rt = cw_timer_start(5);
cwrmsg = <API key>(conn,0,rt);
struct wtpinfo * wtpinfo = get_wtpinfo();
struct radioinfo *rip = &(wtpinfo->radioinfo[0]);
if(cwrmsg){
<API key>(cwrmsg->msgelems,cwrmsg->msgelems_len);
<API key>(conn,cwrmsg->seqnum,rip);
}
sleep(1);
}
exit(0);
}
*/ |
using System;
using System.Collections.Generic;
using SwinGame;
namespace Khet
{
public class RotateWidget: Widget
{
private bool _rotateClockwise;
public RotateWidget(Dictionary<string, Bitmap> allImages, GamePiece piece, int zIndex, bool rotateClockwise):
base(allImages, zIndex)
{
_rotateClockwise = rotateClockwise;
}
public override void Draw()
{
if (Active) {
if (MouseHover) {
if (_rotateClockwise)
DrawWidgetImage(_allImages["<API key>"]);
else
DrawWidgetImage(_allImages["<API key>"]);
} else {
DrawWidgetImage(_currentImage);
}
}
}
}
} |
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
db = SQLAlchemy()
class BaseTable(db.Model):
__abstract__ = True
updated = db.Column(db.DateTime, default=func.now(), onupdate=func.current_timestamp())
created = db.Column(db.DateTime, default=func.now())
# Server -> Namespace -> Repository -> Branch -> Commit -> Deploy -> Log
class Server(BaseTable):
__tablename__ = 'server'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255))
namespace = relationship("Namespace", order_by="Namespace.id", backref="server")
class Namespace(BaseTable):
__tablename__ = 'namespace'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255))
server_id = db.Column(db.Integer, db.ForeignKey('server.id'))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
repository = relationship("Repository", order_by="Repository.id", backref="namespace")
class Repository(BaseTable):
__tablename__ = 'repository'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255))
namespace_id = db.Column(db.Integer, db.ForeignKey('namespace.id'))
branch = relationship("Branch", order_by="Branch.updated.desc()", backref="repository")
class Branch(BaseTable):
__tablename__ = 'branch'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255))
repository_id = db.Column(db.Integer, db.ForeignKey('repository.id'))
commit = relationship("Commit", order_by="Commit.created.desc()", backref="branch")
class Commit(BaseTable):
__tablename__ = 'commit'
id = db.Column(db.Integer, primary_key=True)
sha = db.Column(db.String(40))
name = db.Column(db.String(255))
description = db.Column(db.String(1024))
status = db.Column(db.Enum('ERROR', 'WARNING', 'OK', 'UNKNOWN', 'RUNNING', name='commit_status_type'))
runtime = db.Column(db.Integer)
branch_id = db.Column(db.Integer, db.ForeignKey('branch.id'))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
deploy = relationship("Deploy", order_by="Deploy.id", backref="commit")
class Deploy(BaseTable):
__tablename__ = 'deploy'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255))
uri = db.Column(db.String(1024))
status = db.Column(db.Enum('ERROR', 'WARNING', 'OK', 'UNKNOWN', 'RUNNING', name='deploy_status_type'))
runtime = db.Column(db.Integer)
commit_id = db.Column(db.Integer, db.ForeignKey('commit.id'))
log = relationship("Log", order_by="Log.id", backref="deploy")
class Log(BaseTable):
__tablename__ = 'log'
id = db.Column(db.Integer, primary_key=True)
data = db.Column(db.String(1024))
status = db.Column(db.Enum('ERROR', 'WARNING', 'OK', 'UNKNOWN', name='log_status_type'))
deploy_id = db.Column(db.Integer, db.ForeignKey('deploy.id'))
class User(BaseTable):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(255))
last_name = db.Column(db.String(255))
email = db.Column(db.String(255))
password = db.Column(db.String(255))
commit = relationship("Commit", order_by="Commit.id", backref="user")
namespace = relationship("Namespace", order_by="Namespace.id", backref="user") |
from django.conf.urls import include, url
from django.contrib import admin
# from rest_framework import routers
from <API key> import routers
from stackoverflow import views
router = routers.SimpleRouter()
router.register(r'questions', views.QuestionViewSet)
router.register(r'users', views.UserViewSet)
questions_router = routers.NestedSimpleRouter(router, r'questions', lookup='question')
questions_router.register(r'answers', views.AnswerViewSet)
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include(router.urls)),
url(r'^api/', include(questions_router.urls)),
url(r'^docs/', include('<API key>.urls')),
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
] |
#include "<API key>.h"
#include "gcal-utils.h"
void
<API key> (GtkWidget *widget,
GtkSnapshot *snapshot,
GtkOrientation orientation,
const GdkRGBA *line_color,
gint width,
gint height)
{
GdkRGBA color;
gboolean ltr;
gdouble column_width;
guint i;
ltr = <API key> (widget) != GTK_TEXT_DIR_RTL;
color = *line_color;
column_width = width / 7.0;
switch (orientation)
{
case <API key>:
for (i = 0; i < 7; i++)
{
gdouble x;
if (ltr)
x = column_width * i;
else
x = width - column_width * i;
<API key> (snapshot,
&color,
&GRAPHENE_RECT_INIT (x, 0.f, 1.0, height));
}
break;
case <API key>:
/* Main lines */
for (i = 1; i < 24; i++)
{
<API key> (snapshot,
line_color,
&GRAPHENE_RECT_INIT (0.f,
ALIGNED ((height / 24.0) * i),
width,
1.0));
}
/* In-between lines */
color.alpha /= 2.0;
for (i = 0; i < 24; i++)
{
gdouble half_cell_height = (height / 24.0) / 2.0;
<API key> (snapshot,
&color,
&GRAPHENE_RECT_INIT (0.f,
ALIGNED ((height / 24.0) * i + half_cell_height),
width,
1.0));
}
break;
}
} |
import DS from 'ember-data';
import Ember from 'ember';
import { <API key> } from '<API key>';
export default <API key>.extend(DS.<API key>, {
attrs: {
conditions: { embedded: 'always' },
symptoms: { embedded: 'always' },
treatments: { embedded: 'always' }
},
serialize() {
var json = this._super(...arguments);
json.<API key> = json.conditions;
delete json.conditions;
json.symptoms_attributes = json.symptoms;
delete json.symptoms;
json.<API key> = json.treatments;
json.<API key>.forEach(function(item) {
if (Ember.isPresent(item.dose)) {
item.value = item.dose.name;
delete item.dose;
} else {
item.value = null;
}
});
delete json.treatments;
return json;
}
}); |
// NScD Oak Ridge National Laboratory, European Spallation Source
// & Institut Laue - Langevin
#ifndef <API key>
#define <API key>
#include "MantidAPI/Algorithm.h"
#include "MantidAPI/Run.h"
#include "MantidAPI/SpectrumInfo.h"
#include "MantidAPI/WorkspaceGroup_fwd.h"
#include "MantidAPI/Workspace_fwd.h"
#include "MantidDataObjects/EventList.h"
#include "MantidDataObjects/EventWorkspace.h"
#include "MantidHistogramData/Histogram.h"
#include "MantidKernel/System.h"
namespace Mantid {
namespace Algorithms {
enum OperandType { eEventList = 0, eHistogram = 1, eNumber = 2 };
/**
BinaryOperation supports the implementation of a binary operation on two input
workspaces.
It inherits from the Algorithm class, and overrides the init() & exec() methods.
Required Properties:
<UL>
<LI> InputWorkspace1 - The name of the workspace forming the left hand
operand</LI>
<LI> InputWorkspace2 - The name of the workspace forming the right hand operand
</LI>
<LI> OutputWorkspace - The name of the workspace in which to store the result
</LI>
</UL>
@author Nick Draper
@date 14/12/2007
*/
class DLLExport BinaryOperation : public API::Algorithm {
public:
Algorithm's category for identification overriding a virtual method
const std::string category() const override { return "Arithmetic"; }
/** <API key>: a list of ints.
* Index into vector: workspace index in the lhs;
* Value at that index: workspace index of the rhs to apply to the WI in the
* lhs. -1 if not found.
*/
using <API key> = std::vector<int64_t>;
using <API key> = boost::shared_ptr<<API key>>;
static <API key>
<API key>(const API::<API key> &lhs,
const API::<API key> &rhs);
protected:
Parallel::ExecutionMode <API key>(
const std::map<std::string, Parallel::StorageMode> &storageModes)
const override;
// Overridden Algorithm methods
void exec() override;
void init() override;
bool <API key>();
Execution method for event workspaces, to be overridden as needed.
virtual void execEvent(DataObjects::<API key> lhs,
DataObjects::<API key> rhs);
The name of the first input workspace property
virtual std::string inputPropName1() const { return "LHSWorkspace"; }
The name of the second input workspace property
virtual std::string inputPropName2() const { return "RHSWorkspace"; }
The name of the output workspace property
virtual std::string outputPropName() const { return "OutputWorkspace"; }
Checks the compatibility of the two workspaces
virtual bool
checkCompatibility(const API::<API key> lhs,
const API::<API key> rhs) const;
Checks the compatibility of event-based processing of the two workspaces
virtual bool
<API key>(const API::<API key> lhs,
const API::<API key> rhs);
Checks the overall size compatibility of two workspaces
virtual std::string
<API key>(const API::<API key> lhs,
const API::<API key> rhs) const;
virtual bool <API key>(const API::SpectrumInfo &lhsSpectrumInfo,
const API::SpectrumInfo &rhsSpectrumInfo,
const int64_t index,
API::MatrixWorkspace &out,
API::SpectrumInfo &outSpectrumInfo);
/** Carries out the binary operation on a single spectrum, with another
*spectrum as the right-hand operand.
*
* @param lhs :: Lhs histogram data
* @param rhs :: Rhs histogram data
* @param YOut :: Data values resulting from the operation
* @param EOut :: Drror values resulting from the operation
*/
virtual void <API key>(const HistogramData::Histogram &lhs,
const HistogramData::Histogram &rhs,
HistogramData::HistogramY &YOut,
HistogramData::HistogramE &EOut) = 0;
/** Carries out the binary operation when the right hand operand is a single
*number.
*
* @param lhs :: Lhs histogram data
* @param rhsY :: The rhs data value
* @param rhsE :: The lhs data value
* @param YOut :: Data values resulting from the operation
* @param EOut :: Error values resulting from the operation
*/
virtual void <API key>(const HistogramData::Histogram &lhs,
const double rhsY, const double rhsE,
HistogramData::HistogramY &YOut,
HistogramData::HistogramE &EOut) = 0;
/** Carries out the binary operation IN-PLACE on a single EventList,
* with another EventList as the right-hand operand.
* The event lists simply get appended.
*
* @param lhs :: Reference to the EventList that will be modified in place.
* @param rhs :: Const reference to the EventList on the right hand side.
*/
virtual void <API key>(DataObjects::EventList &lhs,
const DataObjects::EventList &rhs);
/** Carries out the binary operation IN-PLACE on a single EventList,
* with another (histogrammed) spectrum as the right-hand operand.
*
* @param lhs :: Reference to the EventList that will be modified in place.
* @param rhsX :: Rhs X bin boundaries
* @param rhsY :: Rhs data values
* @param rhsE :: Rhs error values
*/
virtual void <API key>(DataObjects::EventList &lhs,
const MantidVec &rhsX,
const MantidVec &rhsY,
const MantidVec &rhsE);
/** Carries out the binary operation IN-PLACE on a single EventList,
* with a single (double) value as the right-hand operand
*
* @param lhs :: Reference to the EventList that will be modified in place.
* @param rhsY :: The rhs data value
* @param rhsE :: The rhs error value
*/
virtual void <API key>(DataObjects::EventList &lhs,
const double &rhsY,
const double &rhsE);
/** Should be overridden by operations that need to manipulate the units of
* the output workspace.
* Does nothing by default.
* @param lhs :: The first input workspace
* @param rhs :: The second input workspace
* @param out :: The output workspace
*/
virtual void setOutputUnits(const API::<API key> lhs,
const API::<API key> rhs,
API::<API key> out) {
(void)lhs; // Avoid compiler warning
(void)rhs;
(void)out;
}
/** Only overridden by operations that affect the properties of the run (e.g.
* Plus
* where the proton currents (charges) are added). Otherwise it does nothing.
* @param lhs :: One of the workspaces to operate on
* @param rhs :: The other workspace
* @param ans :: The output workspace
*/
virtual void operateOnRun(const API::Run &lhs, const API::Run &rhs,
API::Run &ans) const {
(void)lhs; // Avoid compiler warning
(void)rhs;
(void)ans;
};
OperandType getOperandType(const API::<API key> ws);
virtual void checkRequirements();
Left-hand side workspace
API::<API key> m_lhs;
Left-hand side EventWorkspace
DataObjects::<API key> m_elhs;
Right-hand side workspace
API::<API key> m_rhs;
Right-hand side EventWorkspace
DataObjects::<API key> m_erhs;
Output workspace
API::<API key> m_out;
Output EventWorkspace
DataObjects::EventWorkspace_sptr m_eout;
The property value
bool <API key>{false};
Flag to clear RHS workspace in binary operation
bool m_ClearRHSWorkspace{false};
Cache for LHS workspace's blocksize
size_t m_lhsBlocksize;
Cache for RHS workspace's blocksize
size_t m_rhsBlocksize;
matchXSize set to true if the X sizes of histograms must match.
bool m_matchXSize{false};
flipSides set to true if the rhs and lhs operands should be flipped - for
commutative binary operations, normally.
bool m_flipSides{false};
Variable set to true if the operation allows the output to stay as an
EventWorkspace. If this returns false, any EventWorkspace will be
converted to Workspace2D. This is ignored if the lhs operand is not an
EventWorkspace.
bool <API key>{false};
/** Are we going to use the histogram representation of the RHS event list
* when performing the operation?
* e.g. divide and multiply? Plus and Minus will set this to false (default).
*/
bool <API key>{false};
/** Special case for plus/minus: if there is only one bin on the RHS, use the
* 2D method (appending event lists)
* so that the single bin is not treated as a scalar
*/
bool <API key>{false};
private:
void doSingleValue();
void doSingleSpectrum();
void doSingleColumn();
void do2D(bool mismatchedSpectra);
void propagateBinMasks(const API::<API key> rhs,
API::<API key> out);
Progress reporting
std::unique_ptr<API::Progress> m_progress = nullptr;
};
} // namespace Algorithms
} // namespace Mantid
#endif /*<API key>*/ |
package ar.gov.rosario.siat.bal.buss.dao;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.classic.Session;
import ar.gov.rosario.siat.bal.buss.bean.Balance;
import ar.gov.rosario.siat.bal.buss.bean.ImpPar;
import ar.gov.rosario.siat.base.buss.dao.GenericDAO;
import ar.gov.rosario.siat.base.buss.dao.SiatHibernateUtil;
import coop.tecso.demoda.iface.helper.DateUtil;
import coop.tecso.demoda.iface.helper.DemodaUtil;
public class ImpParDAO extends GenericDAO {
private Log log = LogFactory.getLog(ImpParDAO.class);
public ImpParDAO(){
super(ImpPar.class);
}
public Double <API key>(Date fecha){
Session session = SiatHibernateUtil.currentSession();
String queryString = "select sum(t.importeEjeAct+t.importeEjeVen) from ImpPar t";
queryString += " where t.fecha < :fecha ";
Query query = session.createQuery(queryString);
query.setDate("fecha", fecha);
Double totalRecaudado = (Double) query.uniqueResult();
Double result = 0D;
if(totalRecaudado != null)
result = totalRecaudado;
return result;
}
public Double <API key>(int anio){
Session session = SiatHibernateUtil.currentSession();
String queryString = "select sum(t.importeEjeAct+t.importeEjeVen) from bal_ImpPar t";
queryString += " where YEAR(t.fecha) = "+anio;
Query query = session.createSQLQuery(queryString);
BigDecimal totalRecaudado = (BigDecimal) query.uniqueResult();
Double result = 0D;
if(totalRecaudado != null)
result = totalRecaudado.doubleValue();
return result;
}
/**
* Elimina los registros de ImpPar (Maestro de Rentas) que corresponden al Balance.
*
* @param balance
* @return int
*/
public int deleteAllByBalance (Balance balance){
String queryString = "delete from ImpPar t ";
queryString += " where t.balance.id = "+balance.getId();
Session session = SiatHibernateUtil.currentSession();
Query query = session.createQuery(queryString);
return query.executeUpdate();
}
/**
* Obtiene una lista de Totales por Partidas.
*
* @param balance
* @return
* @throws Exception
*/
public List<Object[]> <API key>(Balance balance) throws Exception{
String funcName = DemodaUtil.currentMethodName();
if (log.isDebugEnabled()) log.debug(funcName + ": enter");
Session session = SiatHibernateUtil.currentSession();
String queryString = "select p.codPartida, p.desPartida, sum(t.importeEjeVen), sum(t.importeEjeAct) from ImpPar t, Partida p";
queryString += " where t.balance.id = "+balance.getId();
queryString += " and p.id=t.partida.id";
queryString += " group by p.codPartida, p.desPartida";
queryString += " order by p.codPartida";
if (log.isDebugEnabled()) log.debug(funcName + ": Query: " + queryString);
Query query = session.createQuery(queryString);
List<Object[]> listResult = (ArrayList<Object[]>) query.list();
if (log.isDebugEnabled()) log.debug(funcName + ": exit");
return listResult;
}
/**
* Obtiene el importe total (actual y vencido) para todos los registros con fecha entre las pasadas y la partida
* indicada como parametro.
*
* @param idPartida
* @param fechaDesde
* @param fechaHasta
* @return importe
*/
public Double <API key>(Long idPartida, Date fechaDesde, Date fechaHasta){
String queryString = "select sum(t.importeEjeVen + t.importeEjeAct) as total FROM bal_impPar t " +
" WHERE t.idPartida = "+idPartida;
queryString += " and (t.fecha >= TO_DATE('" +
DateUtil.formatDate(fechaDesde, DateUtil.ddSMMSYYYY_MASK) + "','%d/%m/%Y')) ";
queryString += " and (t.fecha <= TO_DATE('" +
DateUtil.formatDate(fechaHasta, DateUtil.ddSMMSYYYY_MASK) + "','%d/%m/%Y')) ";
Session session = currentSession();
// Obtenemos el resultado de la consulta
Query query;
query = session.createSQLQuery(queryString).addScalar("total", Hibernate.DOUBLE);
return (Double) query.uniqueResult();
}
/**
* Obtiene el importe total, total actual y total vencido para todos los registros con fecha entre las pasadas (si balance es null) y la partida
* indicada como parametro. Si se pasa el parametro Balance, se ignoran las fechas pasadas y se totaliza en el
* maestro de renta por idBalance.
*
* @param idPartida
* @param fechaDesde
* @param fechaHasta
* @param balance
* @return total Vencido, total Actual y total
*/
public Object[] <API key>(Long idPartida, Date fechaDesde, Date fechaHasta, Balance balance){
String queryString = "select sum(t.importeEjeVen) as totVen, sum(t.importeEjeAct) as totAct, sum(t.importeEjeVen + t.importeEjeAct) as total FROM bal_impPar t " +
" WHERE t.idPartida = "+idPartida;
if(balance == null){
queryString += " and (t.fecha >= TO_DATE('" +
DateUtil.formatDate(fechaDesde, DateUtil.ddSMMSYYYY_MASK) + "','%d/%m/%Y')) ";
queryString += " and (t.fecha <= TO_DATE('" +
DateUtil.formatDate(fechaHasta, DateUtil.ddSMMSYYYY_MASK) + "','%d/%m/%Y')) ";
}else{
queryString += " and t.idBalance = " + balance.getId();
}
Session session = currentSession();
// Obtenemos el resultado de la consulta
Query query;
query = session.createSQLQuery(queryString).addScalar("totVen", Hibernate.DOUBLE)
.addScalar("totAct", Hibernate.DOUBLE)
.addScalar("total", Hibernate.DOUBLE);
return (Object[]) query.uniqueResult();
}
/**
* Obtiene una lista de Totales por Partidas.
*
* @param balance
* @return
* @throws Exception
*/
public List<Object[]> <API key>(Date fechaDesde, Date fechaHasta, Long idBalance) throws Exception{
String funcName = DemodaUtil.currentMethodName();
if (log.isDebugEnabled()) log.debug(funcName + ": enter");
Session session = SiatHibernateUtil.currentSession();
String queryString = "select p.codPartida,p.desPartida, sum(t.importeEjeVen), sum(t.importeEjeAct) from ImpPar t, Partida p";
queryString += " where p.id=t.partida.id";
if(idBalance == null){
queryString += " and (t.fecha >= TO_DATE('" + DateUtil.formatDate(fechaDesde, DateUtil.ddSMMSYYYY_MASK) + "','%d/%m/%Y')) ";
queryString += " and (t.fecha <= TO_DATE('" + DateUtil.formatDate(fechaHasta, DateUtil.ddSMMSYYYY_MASK) + "','%d/%m/%Y')) ";
}else{
queryString += " and t.balance.id = "+idBalance;
}
queryString += " group by p.codPartida, p.desPartida";
queryString += " order by p.codPartida";
if (log.isDebugEnabled()) log.debug(funcName + ": Query: " + queryString);
Query query = session.createQuery(queryString);
List<Object[]> listResult = (ArrayList<Object[]>) query.list();
if (log.isDebugEnabled()) log.debug(funcName + ": exit");
return listResult;
}
/**
* Obtiene el importe total, total actual y total vencido para todos los registros con fecha entre las pasadas y la partida
* indicada como parametro.
*
* @param idPartida
* @param fechaDesde
* @param fechaHasta
* @return total Vencido, total Actual y total
*/
public List<Object[]> <API key>(Long idPartida, Date fechaDesde, Date fechaHasta){
String queryString = "select t.fecha as fecha, sum(t.importeEjeVen) as totVen, sum(t.importeEjeAct) as totAct, sum(t.importeEjeVen + t.importeEjeAct) as total FROM bal_impPar t " +
" WHERE t.idPartida = "+idPartida;
queryString += " and (t.fecha >= TO_DATE('" +
DateUtil.formatDate(fechaDesde, DateUtil.ddSMMSYYYY_MASK) + "','%d/%m/%Y')) ";
queryString += " and (t.fecha <= TO_DATE('" +
DateUtil.formatDate(fechaHasta, DateUtil.ddSMMSYYYY_MASK) + "','%d/%m/%Y')) ";
queryString += " group by fecha order by fecha";
Session session = currentSession();
// Obtenemos el resultado de la consulta
Query query;
query = session.createSQLQuery(queryString).addScalar("fecha", Hibernate.DATE)
.addScalar("totVen", Hibernate.DOUBLE)
.addScalar("totAct", Hibernate.DOUBLE)
.addScalar("total", Hibernate.DOUBLE);
return (ArrayList<Object[]>) query.list();
}
} |
using BreadPlayer.Core.Models;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Windows.Storage;
namespace BreadPlayer.PlaylistBus
{
internal interface IPlaylist
{
Task<IEnumerable<Mediafile>> LoadPlaylist(StorageFile file);
Task<bool> SavePlaylist(IEnumerable<Mediafile> songs, Stream fileStream);
}
} |
<?php
namespace App\Policies;
use App\User;
use App\Matter;
use Illuminate\Auth\Access\<API key>;
class MatterPolicy
{
use <API key>;
/**
* Determine whether the user can view any matters.
*
* @param \App\User $user
* @return mixed
*/
public function viewAny(User $user)
{
return true;
}
/**
* Determine whether the user can view the matter.
*
* @param \App\User $user
* @param \App\Matter $matter
* @return mixed
*/
public function view(User $user, Matter $matter)
{
if ($user->default_role === 'CLI') {
if ($matter->client->count()) {
return $user->id === $matter->client->actor_id;
} else {
return false;
}
} else {
return true;
};
}
/**
* Determine whether the user can create matters.
*
* @param \App\User $user
* @return mixed
*/
public function create(User $user)
{
return true;
}
/**
* Determine whether the user can update the matter.
*
* @param \App\User $user
* @param \App\Matter $matter
* @return mixed
*/
public function update(User $user, Matter $matter)
{
return true;
}
/**
* Determine whether the user can delete the matter.
*
* @param \App\User $user
* @param \App\Matter $matter
* @return mixed
*/
public function delete(User $user, Matter $matter)
{
return true;
}
} |
import { Spawner } from '../../../../base/Spawner';
const npcIds = [
'Thanksgiving Turkey Target'
];
export class <API key> extends Spawner {
constructor(room, opts) {
super(room, opts, {
respawnRate: 0,
initialSpawn: 0,
maxCreatures: 20,
spawnRadius: 0,
randomWalkRadius: 0,
leashRadius: 0,
shouldBeActive: true,
npcIds
});
}
} |
$(document).on("click", '.report_summary', function(event) {
var addressValue = $(this).attr("href");
var a = reverse('view_report', function(url) {
var request_url = url + "/?" + addressValue;
$.ajax({
url: request_url,
success: function(data){
BootstrapDialog.show({
size: BootstrapDialog.SIZE_WIDE,
title: '<b>Report Summary</b>',
message: data,
buttons: [{
icon: 'glyphicon glyphicon-ok',
cssClass: 'btn btn-success',
label: ' Close',
action: function(dialogItself){
dialogItself.close();
}
}]
})
}
})
});
return false;
}); |
using System.Collections.Generic;
using System.Windows.Forms;
namespace DataCommander.Providers.OleDb
{
internal sealed class ProcedureNode : ITreeNode
{
private readonly string name;
public ProcedureNode(string name)
{
this.name = name;
}
public string Name
{
get
{
var name = this.name;
if (name == null)
name = "[No procedures found]";
return name;
}
}
public bool IsLeaf => true;
public IEnumerable<ITreeNode> GetChildren(bool refresh)
{
return null;
}
public bool Sortable => false;
public string Query
{
get
{
string query;
if (name != null)
query = "exec " + name;
else
query = null;
return query;
}
}
public ContextMenuStrip ContextMenu => null;
}
} |
package org.opensourcephysics.cabrillo.tracker;
import java.util.*;
import java.util.logging.Level;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URL;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileFilter;
import org.opensourcephysics.cabrillo.tracker.deploy.TrackerStarter;
import org.opensourcephysics.controls.OSPLog;
import org.opensourcephysics.controls.XML;
import org.opensourcephysics.display.OSPRuntime;
import org.opensourcephysics.media.core.IntegerField;
import org.opensourcephysics.media.core.VideoIO;
import org.opensourcephysics.tools.ExtensionsManager;
import org.opensourcephysics.tools.FontSizer;
import org.opensourcephysics.tools.ResourceLoader;
/**
* This displays and sets preferences for a TrackerPanel.
*
* @author Douglas Brown
*/
public class PrefsDialog extends JDialog {
// static constants
final static Color MEDIUM_RED = new Color(255, 120, 140);
// static fields
protected static boolean <API key>;
protected static String userHome, javaHome;
protected static FilenameFilter trackerJarFilter;
protected static File codeBaseDir;
// instance fields
protected TrackerPanel trackerPanel;
protected TFrame frame;
protected JButton okButton, cancelButton;
protected JButton allButton, noneButton, applyButton, saveButton;
protected JButton relaunchButton, clearRecentButton, <API key>;
protected JButton clearHostButton, browseCacheButton, clearCacheButton, setCacheButton, setRunButton;
protected JTextField cacheField, runField;
protected JPanel checkPanel;
protected JPanel mainButtonBar;
protected JTabbedPane tabbedPane;
protected JPanel configPanel, runtimePanel, videoPanel, generalPanel,
displayPanel;
protected TitledBorder checkPanelBorder, lfSubPanelBorder, langSubPanelBorder, hintsSubPanelBorder,
unitsSubPanelBorder, <API key>, jreSubPanelBorder, <API key>, runSubPanelBorder,
<API key>, <API key>, <API key>, <API key>,
cacheSubPanelBorder, <API key>, <API key>, fontSubPanelBorder;
protected IntegerField memoryField;
protected JLabel memoryLabel, recentSizeLabel, lookFeelLabel, cacheLabel,
versionLabel, runLabel;
protected JCheckBox <API key>, hintsCheckbox, vidWarningCheckbox,
xuggleErrorCheckbox, <API key>;
protected int memorySize = Tracker.requestedMemorySize;
protected JSpinner recentSizeSpinner, runSpinner;
protected JComboBox lookFeelDropdown, languageDropdown, jreDropdown,
<API key>, versionDropdown, logLevelDropdown, fontSizeDropdown;
protected JRadioButton vm32Button, vm64Button;
protected JRadioButton xuggleButton, qtButton, noEngineButton;
protected JRadioButton radiansButton, degreesButton;
protected JRadioButton xuggleFastButton, xuggleSlowButton;
protected String[] trackerVersions;
protected String recent32bitVM, recent64bitVM;
protected String recentEngine;
private boolean refreshing = false;
protected boolean relaunching = false;
// previous values
protected Set<String> prevEnabled = new TreeSet<String>();
protected int prevMemory, prevRecentCount, prevUpgradeInterval, prevFontLevel;
protected String prevLookFeel, prevLocaleName, prevJRE, prevTrackerJar, prevEngine;
protected boolean prevHints, prevRadians, prevFastXuggle,
<API key>, prevWarnXuggleError, <API key>,
<API key>, prevUse32BitVM, prevWarnCopyFailed;
protected File prevCache;
protected String[] prevExecutables;
static {
trackerJarFilter = new org.opensourcephysics.cabrillo.tracker.deploy.TrackerJarFilter();
try {
userHome = System.getProperty("user.home"); //$NON-NLS-1$
javaHome = System.getProperty("java.home"); //$NON-NLS-1$
URL url = TrackerStarter.class.getProtectionDomain().getCodeSource().getLocation();
// File jarFile = new File(url.getPath());
File jarFile = new File(url.toURI());
codeBaseDir = jarFile.getParentFile();
}
catch (Exception ex) {}
}
/**
* Constructs a PrefsDialog.
*
* @param panel the tracker panel
* @param frame the parent TFrame
*/
public PrefsDialog(TrackerPanel panel, TFrame frame) {
// non-modal
super(frame, false);
trackerPanel = panel;
this.frame = frame;
setTitle(TrackerRes.getString("ConfigInspector.Title")); //$NON-NLS-1$
findTrackerJars();
createGUI();
}
@Override
public void setVisible(boolean vis) {
super.setVisible(vis);
if (vis) {
savePrevious();
findTrackerJars();
refreshGUI();
}
}
public void setFontLevel(int level) {
FontSizer.setFonts(this, level);
Object[] borders = new Object[] {
checkPanelBorder, lfSubPanelBorder, langSubPanelBorder, hintsSubPanelBorder,
unitsSubPanelBorder, <API key>, jreSubPanelBorder, <API key>, runSubPanelBorder,
<API key>, <API key>, <API key>, <API key>,
cacheSubPanelBorder, <API key>, <API key>, fontSubPanelBorder};
FontSizer.setFonts(borders, level);
JComboBox[] dropdowns = new JComboBox[] {lookFeelDropdown, languageDropdown,
jreDropdown, <API key>, versionDropdown, logLevelDropdown};
for (JComboBox next: dropdowns) {
int n = next.getSelectedIndex();
Object[] items = new Object[next.getItemCount()];
for (int i=0; i<items.length; i++) {
items[i] = next.getItemAt(i);
}
<API key> model = new <API key>(items);
next.setModel(model);
next.setSelectedItem(n);
}
}
//<API key> private methods <API key>
/**
* Finds the tracker jars.
*/
private void findTrackerJars() {
if (Tracker.trackerHome==null || codeBaseDir==null) {
trackerVersions = new String[] {"0"}; //$NON-NLS-1$
return;
}
String jarHome = OSPRuntime.isMac()?
codeBaseDir.getAbsolutePath(): Tracker.trackerHome;
File dir = new File(jarHome);
String[] fileNames = dir.list(trackerJarFilter);
if (fileNames!=null && fileNames.length>0) {
TreeSet<String> versions = new TreeSet<String>();
for (int i=0; i<fileNames.length; i++) {
if ("tracker.jar".equals(fileNames[i].toLowerCase())) {//$NON-NLS-1$
versions.add("0"); //$NON-NLS-1$
}
else {
versions.add(fileNames[i].substring(8, fileNames[i].length()-4));
}
}
trackerVersions = versions.toArray(new String[versions.size()]);
}
}
/**
* Creates the visible components of this panel.
*/
private void createGUI() {
tabbedPane = new JTabbedPane();
JPanel contentPane = new JPanel(new BorderLayout());
setContentPane(contentPane);
contentPane.add(tabbedPane, BorderLayout.CENTER);
// ok button
okButton = new JButton();
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applyPrefs();
setVisible(false);
// refresh the frame
if (frame != null) frame.refresh();
}
});
// cancel button
cancelButton = new JButton();
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
revert();
setVisible(false);
// refresh the frame
if (frame != null) frame.refresh();
}
});
// relaunch button
relaunchButton = new JButton();
relaunchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
applyPrefs();
ArrayList<String> filenames = new ArrayList<String>();
for (int i = 0; i<frame.getTabCount(); i++) {
TrackerPanel next = frame.getTrackerPanel(i);
if (!next.save()) return;
File datafile = next.getDataFile();
if (datafile!=null) {
String fileName = datafile.getAbsolutePath();
filenames.add(fileName);
}
}
String[] args = filenames.isEmpty()? null: filenames.toArray(new String[0]);
TrackerStarter.relaunch(args, false);
// TrackerStarter exits current VM after relaunching new one
}
});
// configuration panel
configPanel = new JPanel(new BorderLayout());
tabbedPane.addTab(null, configPanel);
Color color = Color.WHITE;
// config checkPanel
int n = 1+Tracker.getFullConfig().size()/2;
checkPanel = new JPanel(new GridLayout(n, 2));
checkPanel.setBackground(color);
checkPanelBorder = BorderFactory.createTitledBorder(
TrackerRes.getString("ConfigInspector.Border.Title")); //$NON-NLS-1$
checkPanel.setBorder(checkPanelBorder);
// config checkboxes
Iterator<String> it = Tracker.getFullConfig().iterator();
while (it.hasNext()) {
String item = it.next();
JCheckBoxMenuItem checkbox = new JCheckBoxMenuItem(item);
checkbox.setOpaque(false);
checkPanel.add(checkbox);
}
JScrollPane scroller = new JScrollPane(checkPanel);
scroller.setPreferredSize(new Dimension(380, 200));
configPanel.add(scroller, BorderLayout.CENTER);
// apply button
applyButton = new JButton();
applyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateConfig();
refreshGUI();
frame.refresh();
}
});
// create all and none buttons
allButton = new JButton();
allButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component[] checkboxes = checkPanel.getComponents();
for (int i = 0; i < checkboxes.length; i++) {
JCheckBoxMenuItem checkbox = (JCheckBoxMenuItem)checkboxes[i];
checkbox.setSelected(true);
}
}
});
noneButton = new JButton();
noneButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component[] checkboxes = checkPanel.getComponents();
for (int i = 0; i < checkboxes.length; i++) {
JCheckBoxMenuItem checkbox = (JCheckBoxMenuItem)checkboxes[i];
checkbox.setSelected(false);
}
}
});
// save button
saveButton = new JButton();
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveConfigAsDefault();
}
});
JPanel configButtonBar = new JPanel();
configButtonBar.add(allButton);
configButtonBar.add(noneButton);
configButtonBar.add(applyButton);
configButtonBar.add(saveButton);
configPanel.add(configButtonBar, BorderLayout.NORTH);
Border etched = BorderFactory.createEtchedBorder();
// display panel
displayPanel = new JPanel(new BorderLayout());
tabbedPane.addTab(null, displayPanel);
Box box = Box.createVerticalBox();
displayPanel.add(box, BorderLayout.CENTER);
// look and feel subpanel
JPanel lfSubPanel = new JPanel();
box.add(lfSubPanel);
lfSubPanel.setBackground(color);
lfSubPanelBorder = BorderFactory.createTitledBorder(
TrackerRes.getString("PrefsDialog.LookFeel.BorderTitle")); //$NON-NLS-1$
lfSubPanel.setBorder(BorderFactory.<API key>(etched, lfSubPanelBorder));
lookFeelDropdown = new JComboBox();
lookFeelDropdown.addItem(OSPRuntime.DEFAULT_LF.toLowerCase());
Object selectedItem = OSPRuntime.DEFAULT_LF;
// get alphabetical list of look/feel types
Set<String> lfTypes = new TreeSet<String>();
for (String next: OSPRuntime.LOOK_AND_FEEL_TYPES.keySet()) {
if (next.equals(OSPRuntime.DEFAULT_LF)) continue;
lfTypes.add(next.toLowerCase());
if (next.equals(Tracker.lookAndFeel))
selectedItem = next.toLowerCase();
}
for (String next: lfTypes) {
lookFeelDropdown.addItem(next);
}
lookFeelDropdown.setSelectedItem(selectedItem);
lookFeelDropdown.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
String lf = lookFeelDropdown.getSelectedItem().toString().toUpperCase();
if (!lf.equals(Tracker.lookAndFeel)) {
Tracker.lookAndFeel = lf;
}
}
});
lfSubPanel.add(lookFeelDropdown);
// language subpanel
JPanel langSubPanel = new JPanel();
box.add(langSubPanel);
langSubPanel.setBackground(color);
langSubPanelBorder = BorderFactory.createTitledBorder(
TrackerRes.getString("PrefsDialog.Language.BorderTitle")); //$NON-NLS-1$
langSubPanel.setBorder(BorderFactory.<API key>(etched, langSubPanelBorder));
languageDropdown = new JComboBox();
Object selected = TrackerRes.getString("PrefsDialog.Language.Default"); //$NON-NLS-1$
languageDropdown.addItem(selected);
for (Locale next: Tracker.locales) {
String s = OSPRuntime.getDisplayLanguage(next);
languageDropdown.addItem(s);
if (next.equals(Locale.getDefault())
&& next.toString().equals(Tracker.preferredLocale)) {
selected = s;
}
}
languageDropdown.setSelectedItem(selected);
languageDropdown.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
String s = languageDropdown.getSelectedItem().toString();
if (s.equals(TrackerRes.getString("PrefsDialog.Language.Default"))) //$NON-NLS-1$
Tracker.setPreferredLocale(null);
else for (Locale next: Tracker.locales) {
if (s.equals(OSPRuntime.getDisplayLanguage(next))) {
// TrackerRes.setLocale(next);
Tracker.setPreferredLocale(next.toString());
break;
}
}
}
});
langSubPanel.add(languageDropdown);
// font level subpanel
JPanel fontSubPanel = new JPanel();
box.add(fontSubPanel);
fontSubPanel.setBackground(color);
fontSubPanelBorder = BorderFactory.createTitledBorder(
TrackerRes.getString("PrefsDialog.FontSize.BorderTitle")); //$NON-NLS-1$
fontSubPanel.setBorder(BorderFactory.<API key>(etched, fontSubPanelBorder));
// create font size dropdown
fontSizeDropdown = new JComboBox();
String defaultLevel = TrackerRes.getString("TMenuBar.MenuItem.DefaultFontSize"); //$NON-NLS-1$
fontSizeDropdown.addItem(defaultLevel);
int preferredLevel = Tracker.preferredFontLevel + Tracker.<API key>;
int maxLevel = Math.max(preferredLevel, 6);
for (int i=1; i<=maxLevel; i++) {
String s = "+"+i; //$NON-NLS-1$
fontSizeDropdown.addItem(s);
}
fontSizeDropdown.setSelectedIndex(preferredLevel);
fontSizeDropdown.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
int preferredLevel = fontSizeDropdown.getSelectedIndex();
Tracker.preferredFontLevel = Math.min(preferredLevel, 3);
Tracker.<API key> = preferredLevel - Tracker.preferredFontLevel;
}
});
fontSubPanel.add(fontSizeDropdown);
// hints subpanel
hintsCheckbox = new JCheckBox();
hintsCheckbox.setOpaque(false);
hintsCheckbox.setSelected(Tracker.showHintsByDefault);
hintsCheckbox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Tracker.showHintsByDefault = hintsCheckbox.isSelected();
}
});
JPanel hintsSubPanel = new JPanel();
box.add(hintsSubPanel);
hintsSubPanel.setBackground(color);
hintsSubPanelBorder = BorderFactory.createTitledBorder(
TrackerRes.getString("PrefsDialog.Hints.BorderTitle")); //$NON-NLS-1$
hintsSubPanel.setBorder(BorderFactory.<API key>(etched, hintsSubPanelBorder));
hintsSubPanel.add(hintsCheckbox);
// angle units subpanel
JPanel unitsSubPanel = new JPanel();
box.add(unitsSubPanel);
unitsSubPanel.setBackground(color);
unitsSubPanelBorder = BorderFactory.createTitledBorder(
TrackerRes.getString("TMenuBar.Menu.AngleUnits")); //$NON-NLS-1$
unitsSubPanel.setBorder(BorderFactory.<API key>(etched, unitsSubPanelBorder));
ButtonGroup buttonGroup = new ButtonGroup();
radiansButton = new JRadioButton();
radiansButton.setOpaque(false);
radiansButton.setBorder(BorderFactory.createEmptyBorder(2, 0, 2, 10));
radiansButton.setSelected(Tracker.isRadians);
buttonGroup.add(radiansButton);
degreesButton = new JRadioButton();
degreesButton.setOpaque(false);
degreesButton.setBorder(BorderFactory.createEmptyBorder(2, 0, 2, 10));
degreesButton.setSelected(!Tracker.isRadians);
buttonGroup.add(degreesButton);
unitsSubPanel.add(radiansButton);
unitsSubPanel.add(degreesButton);
// runtime panel
runtimePanel = new JPanel(new BorderLayout());
tabbedPane.addTab(null, runtimePanel);
box = Box.createVerticalBox();
runtimePanel.add(box, BorderLayout.CENTER);
// tracker version subpanel
JPanel versionSubPanel = new JPanel();
box.add(versionSubPanel);
versionSubPanel.setBackground(color);
<API key> = BorderFactory.createTitledBorder(
TrackerRes.getString("PrefsDialog.Version.BorderTitle")); //$NON-NLS-1$
versionSubPanel.setBorder(BorderFactory.<API key>(etched, <API key>));
int preferred = 0;
versionDropdown = new JComboBox();
for (int i = 0; i<trackerVersions.length; i++) {
String next = trackerVersions[i];
if (next.equals("0")) { //$NON-NLS-1$
String s = TrackerRes.getString("PrefsDialog.Version.Default"); //$NON-NLS-1$
versionDropdown.addItem(s);
}
else versionDropdown.addItem(next);
if (Tracker.preferredTrackerJar!=null
&& Tracker.preferredTrackerJar.indexOf("tracker-")>-1 //$NON-NLS-1$
&& Tracker.preferredTrackerJar.indexOf(next)>-1) {
preferred = i;
}
}
versionDropdown.setSelectedIndex(preferred);
versionDropdown.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
Object ver = versionDropdown.getSelectedItem();
String jar = null;
if (ver!=null && !TrackerRes.getString("PrefsDialog.Version.Default").equals(ver)) { //$NON-NLS-1$
jar = "tracker-"+ver+".jar"; //$NON-NLS-1$ //$NON-NLS-2$
}
if (jar==null && Tracker.preferredTrackerJar!=null) {
Tracker.preferredTrackerJar = null;
}
else if (jar!=null && !jar.equals(Tracker.preferredTrackerJar)) {
Tracker.preferredTrackerJar = jar;
}
}
});
versionSubPanel.add(versionDropdown);
// jre subpanel
JPanel jreSubPanel = new JPanel(new BorderLayout());
box.add(jreSubPanel);
jreSubPanel.setBackground(color);
jreSubPanelBorder = BorderFactory.createTitledBorder(
TrackerRes.getString("PrefsDialog.JRE.BorderTitle")); //$NON-NLS-1$
jreSubPanel.setBorder(BorderFactory.<API key>(etched, jreSubPanelBorder));
JPanel jreNorthPanel = new JPanel();
jreNorthPanel.setBackground(color);
jreSubPanel.add(jreNorthPanel, BorderLayout.NORTH);
JPanel jreSouthPanel = new JPanel();
jreSouthPanel.setBackground(color);
jreSubPanel.add(jreSouthPanel, BorderLayout.SOUTH);
int vmBitness = OSPRuntime.getVMBitness();
Tracker.use32BitMode = vmBitness==32;
vm32Button = new JRadioButton();
vm32Button.setOpaque(false);
vm32Button.setBorder(BorderFactory.createEmptyBorder(2, 0, 2, 10));
vm32Button.setSelected(vmBitness==32);
vm32Button.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (!vm32Button.isSelected()) return;
if (OSPRuntime.isMac()) {
Tracker.use32BitMode = true;
refreshJREDropdown(32);
// must run QT engine in 32-bit VM
if (qtButton.isSelected()) return;
// check with user
int selected = JOptionPane.showConfirmDialog(trackerPanel.getTFrame(),
TrackerRes.getString("PrefsDialog.Dialog.SwitchTo32.Message"), //$NON-NLS-1$
TrackerRes.getString("PrefsDialog.Dialog.SwitchEngine.Title"), //$NON-NLS-1$
JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null);
if(selected==JOptionPane.OK_OPTION) {
qtButton.setSelected(true);
}
else {
Tracker.use32BitMode = false;
vm64Button.setSelected(true);
}
}
else if (OSPRuntime.isWindows()) {
refreshJREDropdown(32);
if (noEngineButton.isSelected()) {
Tracker.engineKnown = false;
}
}
}
});
jreNorthPanel.add(vm32Button);
vm64Button = new JRadioButton();
vm64Button.setOpaque(false);
vm64Button.setBorder(BorderFactory.createEmptyBorder(2, 10, 2, 0));
vm64Button.setSelected(vmBitness==64);
vm64Button.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (!vm64Button.isSelected()) return;
double xuggleVersion = VideoIO.guessXuggleVersion();
if (OSPRuntime.isMac()) {
Tracker.use32BitMode = false;
refreshJREDropdown(64);
if (xuggleButton.isSelected() || noEngineButton.isSelected()) return;
// if no xuggle engine, show warning
if (xuggleVersion==0) {
int selected = JOptionPane.showConfirmDialog(trackerPanel.getTFrame(),
TrackerRes.getString("PrefsDialog.Dialog.NoEngineIn64bitVM.Message1")+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$
TrackerRes.getString("PrefsDialog.Dialog.NoEngineIn64bitVM.Message2")+"\n\n"+ //$NON-NLS-1$ //$NON-NLS-2$
TrackerRes.getString("PrefsDialog.Dialog.NoEngineIn64bitVM.Question"), //$NON-NLS-1$
TrackerRes.getString("PrefsDialog.Dialog.NoEngineIn64bitVM.Title"), //$NON-NLS-1$
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null);
if(selected==JOptionPane.YES_OPTION) {
noEngineButton.setSelected(true);
}
else {
vm32Button.setSelected(true); // revert to 32-bit VM
}
return;
}
// set engine to Xuggle and inform user
int selected = JOptionPane.showConfirmDialog(trackerPanel.getTFrame(),
TrackerRes.getString("PrefsDialog.Dialog.SwitchTo64.Message"), //$NON-NLS-1$
TrackerRes.getString("PrefsDialog.Dialog.SwitchEngine.Title"), //$NON-NLS-1$
JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null);
if(selected==JOptionPane.OK_OPTION) {
xuggleButton.setSelected(true);
}
else {
Tracker.use32BitMode = true;
vm32Button.setSelected(true);
}
}
else if (OSPRuntime.isWindows()) {
refreshJREDropdown(64);
if (xuggleButton.isSelected() && xuggleVersion==5.4) return;
if (noEngineButton.isSelected()) return;
// if no xuggle 5.4 engine, show warning
if (xuggleVersion==0 || xuggleVersion==3.4) {
// inform that no engine available in 64-bit VM
int selected = JOptionPane.showConfirmDialog(trackerPanel.getTFrame(),
TrackerRes.getString("PrefsDialog.Dialog.NoEngineIn64bitVM.Message1")+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$
TrackerRes.getString("PrefsDialog.Dialog.NoEngineIn64bitVM.Message2")+"\n\n"+ //$NON-NLS-1$ //$NON-NLS-2$
TrackerRes.getString("PrefsDialog.Dialog.NoEngineIn64bitVM.Question"), //$NON-NLS-1$
TrackerRes.getString("PrefsDialog.Dialog.NoEngineIn64bitVM.Title"), //$NON-NLS-1$
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null);
if (selected==JOptionPane.YES_OPTION) {
noEngineButton.setSelected(true);
}
else {
vm32Button.setSelected(true); // revert to 32-bit VM
}
return;
}
// set engine to Xuggle and inform user
xuggleButton.setSelected(true);
JOptionPane.showMessageDialog(trackerPanel.getTFrame(),
TrackerRes.getString("PrefsDialog.Dialog.SwitchToXuggle.Message"), //$NON-NLS-1$
TrackerRes.getString("PrefsDialog.Dialog.SwitchToXuggle.Title"), //$NON-NLS-1$
JOptionPane.INFORMATION_MESSAGE);
}
}
});
jreNorthPanel.add(vm64Button);
jreDropdown = new JComboBox();
String pref = Tracker.preferredJRE;
if (pref==null && vm64Button.isSelected()) {
pref = Tracker.preferredJRE64;
}
if (pref==null && vm32Button.isSelected()) {
pref = Tracker.preferredJRE32;
}
if (pref==null) {
pref = System.getProperty("java.home"); //$NON-NLS-1$
}
jreDropdown.addItem(pref);
jreDropdown.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (refreshing) return;
Object selected = jreDropdown.getSelectedItem();
if (selected==null) return;
if (vm64Button.isSelected()) {
recent64bitVM = selected.toString();
}
else {
recent32bitVM = selected.toString();
}
}
});
jreSouthPanel.add(jreDropdown);
refreshJREDropdown(vmBitness);
// jreField = new JTextField(24);
// jreSouthPanel.add(jreField);
// final Action setJREAction = new AbstractAction() {
// public void actionPerformed(ActionEvent e) {
// String jre = jreField.getText();
// File javaFile = OSPRuntime.getJavaFile(jre);
// String path = OSPRuntime.getJREPath(javaFile);
// if (path==null) {
// if ("".equals(jre)) { //$NON-NLS-1$
// Tracker.preferredJRE = null;
// else {
// Toolkit.getDefaultToolkit().beep();
// else if ("".equals(path)) { //$NON-NLS-1$
// Tracker.preferredJRE = null;
// else if (!path.equals(Tracker.preferredJRE)) {
// Tracker.preferredJRE = path;
// refreshTextFields();
// updateDisplay();
// jreField.addKeyListener(new KeyAdapter() {
// public void keyPressed(KeyEvent e) {
// jreField.setBackground(Color.yellow);
// jreField.addFocusListener(new FocusAdapter() {
// public void focusLost(FocusEvent e) {
// if (jreField.getBackground()==Color.yellow)
// setJREAction.actionPerformed(null);
// jreField.addActionListener(setJREAction);
// setJREButton = new TButton(openFileIcon);
// setJREButton.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// int result = JFileChooser.CANCEL_OPTION;
// String path = Tracker.preferredJRE;
// if (path==null || "".equals(path)) //$NON-NLS-1$
// path = System.getProperty("java.home"); //$NON-NLS-1$
// File jreDir = new File(path);
// if (OSPRuntime.isMac()) {
// // java home is ".../Contents/Home/" so move up 2 more levels
// jreDir = jreDir.getParentFile().getParentFile();
// if (jreDir.getName().equals("jre") && //$NON-NLS-1$
// (jreDir.getParentFile().getName().indexOf("jdk")>-1 //$NON-NLS-1$
// || jreDir.getParentFile().getName().indexOf("sun")>-1)) { //$NON-NLS-1$
// jreDir = jreDir.getParentFile();
// JFileChooser chooser = getFileChooser(jreDir.getParentFile(), true);
// chooser.setDialogTitle(TrackerRes.getString("PrefsDialog.FileChooser.Title.JRE")); //$NON-NLS-1$
// chooser.setSelectedFile(jreDir);
// result = chooser.showDialog(PrefsDialog.this,
// TrackerRes.getString("PrefsDialog.FileChooser.Title.JRE")); //$NON-NLS-1$
// if(result==JFileChooser.APPROVE_OPTION) {
// File file = chooser.getSelectedFile();
// if (file!=null) {
// jreField.setText(file.getPath());
// setJREAction.actionPerformed(null);
Border buttonBorder = BorderFactory.createEtchedBorder();
Border space = BorderFactory.createEmptyBorder(2,2,2,2);
buttonBorder = BorderFactory.<API key>(buttonBorder, space);
// setJREButton.setBorder(buttonBorder);
// setJREButton.<API key>(false);
// jreSouthPanel.add(setJREButton);
// memory subpanel
JPanel memorySubPanel = new JPanel();
box.add(memorySubPanel);
memorySubPanel.setBackground(color);
<API key> = BorderFactory.createTitledBorder(
TrackerRes.getString("PrefsDialog.Memory.BorderTitle")); //$NON-NLS-1$
memorySubPanel.setBorder(BorderFactory.<API key>(etched, <API key>));
memorySubPanel.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
<API key>();
}
});
<API key> = new JCheckBox();
<API key>.setOpaque(false);
memoryLabel = new JLabel("MB"); //$NON-NLS-1$
memoryField = new IntegerField(4);
memoryField.setMinValue(Tracker.minimumMemorySize);
memoryField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
if (memorySize!=memoryField.getIntValue()) {
memorySize = memoryField.getIntValue();
}
}
});
memoryField.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (<API key>.isSelected()) {
<API key>.doClick(0);
}
}
});
memoryField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
memorySize = memoryField.getIntValue();
}
});
<API key>.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean selected = <API key>.isSelected();
if (selected) {
memoryField.setEnabled(false);
memoryLabel.setEnabled(false);
memoryField.setText(null);
}
else {
memoryField.setEnabled(true);
memoryLabel.setEnabled(true);
memoryField.setValue(memorySize);
memoryField.<API key>();
memoryField.selectAll();
}
}
});
if (Tracker.preferredMemorySize>-1)
memoryField.setValue(Tracker.preferredMemorySize);
else {
<API key>.setSelected(true);
memoryField.setEnabled(false);
memoryLabel.setEnabled(false);
memoryField.setText(null);
}
memorySubPanel.add(<API key>);
memorySubPanel.add(Box.createRigidArea(new Dimension(40, 1)));
memorySubPanel.add(memoryField);
memorySubPanel.add(memoryLabel);
// run subpanel
JPanel runSubPanel = new JPanel();
box.add(runSubPanel);
runSubPanel.setBackground(color);
runSubPanelBorder = BorderFactory.createTitledBorder(
TrackerRes.getString("PrefsDialog.Run.BorderTitle")); //$NON-NLS-1$
runSubPanel.setBorder(BorderFactory.<API key>(etched, runSubPanelBorder));
final Action setRunAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
String path = runField.getText();
int n = (Integer)runSpinner.getValue();
ArrayList<String> paths = new ArrayList<String>();
if (Tracker.<API key>.length>n) { // deal with existing entry
if (path.equals(Tracker.<API key>[n])) // no change
return;
if ("".equals(path)) { // eliminate entry //$NON-NLS-1$
Tracker.<API key>[n] = path;
path = null; // done with this
}
else { // change entry
Tracker.<API key>[n] = path;
path = null; // done with this
}
}
// clean and relist existing entries
for (String next: Tracker.<API key>) {
if (next!=null && !"".equals(next) && !paths.contains(next)) //$NON-NLS-1$
paths.add(next);
}
// add new entry, if any
if (path!=null && !"".equals(path) && !paths.contains(path)) //$NON-NLS-1$
paths.add(path);
Tracker.<API key> = paths.toArray(new String[0]);
for (int i = 0; i<Tracker.<API key>.length; i++) {
if (Tracker.<API key>[i].equals(path)) {
runSpinner.setValue(i);
break;
}
}
refreshTextFields();
}
};
SpinnerModel model = new SpinnerNumberModel(0, 0, 6, 1);
runSpinner = new JSpinner(model);
JSpinner.NumberEditor editor = new JSpinner.NumberEditor(runSpinner);
runSpinner.setEditor(editor);
runSpinner.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if(runField.getBackground()==Color.yellow) {
setRunAction.actionPerformed(null);
} else {
refreshTextFields();
}
}
});
runSubPanel.add(runSpinner);
runField = new JTextField(27);
runSubPanel.add(runField);
runField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
runField.setBackground(Color.yellow);
}
});
runField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
if (runField.getBackground()==Color.yellow)
setRunAction.actionPerformed(null);
}
});
runField.addActionListener(setRunAction);
Icon openFileIcon = new ImageIcon(Tracker.class.getResource("resources/images/open.gif")); //$NON-NLS-1$
setRunButton = new TButton(openFileIcon);
setRunButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int result = JFileChooser.CANCEL_OPTION;
File f = Tracker.trackerHome==null? new File("."): new File(Tracker.trackerHome); //$NON-NLS-1$
JFileChooser chooser = getFileChooser(f, false);
chooser.setDialogTitle(TrackerRes.getString("PrefsDialog.FileChooser.Title.Run")); //$NON-NLS-1$
result = chooser.showOpenDialog(PrefsDialog.this);
if(result==JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
if (file!=null) {
runField.setText(file.getPath());
setRunAction.actionPerformed(null);
}
}
}
});
setRunButton.setBorder(buttonBorder);
setRunButton.<API key>(false);
runSubPanel.add(setRunButton);
// video panel
videoPanel = new JPanel(new BorderLayout());
tabbedPane.addTab(null, videoPanel);
box = Box.createVerticalBox();
videoPanel.add(box, BorderLayout.CENTER);
// videoType subpanel
JPanel videoTypeSubPanel = new JPanel();
box.add(videoTypeSubPanel);
videoTypeSubPanel.setBackground(color);
<API key> = BorderFactory.createTitledBorder(
TrackerRes.getString("PrefsDialog.VideoPref.BorderTitle")); //$NON-NLS-1$
videoTypeSubPanel.setBorder(BorderFactory.<API key>(etched, <API key>));
boolean xuggleInstalled = VideoIO.isEngineInstalled(VideoIO.ENGINE_XUGGLE);
xuggleButton = new JRadioButton();
xuggleButton.setOpaque(false);
xuggleButton.setBorder(BorderFactory.createEmptyBorder(2, 0, 2, 10));
xuggleButton.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
xuggleFastButton.setEnabled(xuggleButton.isSelected());
xuggleSlowButton.setEnabled(xuggleButton.isSelected());
xuggleErrorCheckbox.setEnabled(xuggleButton.isSelected());
if (!xuggleButton.isSelected()) return;
Tracker.engineKnown = true;
// OSX: if 32-bit, set preferred VM to 64-bit and inform user
if (OSPRuntime.isMac() && vm32Button.isSelected()) {
int selected = JOptionPane.showConfirmDialog(trackerPanel.getTFrame(),
TrackerRes.getString("PrefsDialog.Dialog.SwitchToXuggle64.Message"), //$NON-NLS-1$
TrackerRes.getString("PrefsDialog.Dialog.SwitchVM.Title"), //$NON-NLS-1$
JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null);
if(selected==JOptionPane.OK_OPTION) {
vm64Button.setSelected(true); // triggers selection of default or recent 64-bit VM
}
else {
// revert to previous engine
if (recentEngine.equals(VideoIO.ENGINE_QUICKTIME)) {
qtButton.setSelected(true);
}
else if (recentEngine.equals(VideoIO.ENGINE_NONE)) {
noEngineButton.setSelected(true);
}
}
}
// Windows: if xuggle 3.4 and 64-bit, set preferred VM to 32-bit and inform user
else if (OSPRuntime.isWindows() && VideoIO.guessXuggleVersion()==3.4 && vm64Button.isSelected()) {
boolean has32BitVM = ExtensionsManager.getManager().getDefaultJRE(32)!=null;
if (has32BitVM) {
vm32Button.setSelected(true);
JOptionPane.showMessageDialog(trackerPanel.getTFrame(),
TrackerRes.getString("PrefsDialog.Dialog.SwitchToXuggle32.Message"), //$NON-NLS-1$
TrackerRes.getString("PrefsDialog.Dialog.SwitchVM.Title"), //$NON-NLS-1$
JOptionPane.INFORMATION_MESSAGE);
}
else { // help user download 32-bit VM
Object[] options = new Object[] {
TrackerRes.getString("PrefsDialog.Button.ShowHelpNow"), //$NON-NLS-1$
TrackerRes.getString("Dialog.Button.OK")}; //$NON-NLS-1$
int response = JOptionPane.showOptionDialog(trackerPanel.getTFrame(),
TrackerRes.getString("PrefsDialog.Dialog.No32bitVMXuggle.Message")+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$
TrackerRes.getString("PrefsDialog.Dialog.No32bitVM.Message"), //$NON-NLS-1$
TrackerRes.getString("PrefsDialog.Dialog.No32bitVM.Title"), //$NON-NLS-1$
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
noEngineButton.setSelected(true);
if (response==0) {
trackerPanel.getTFrame().showHelp("install", 0); //$NON-NLS-1$
}
}
}
if (xuggleButton.isSelected()) {
recentEngine = VideoIO.ENGINE_XUGGLE;
}
}
});
xuggleButton.setEnabled(xuggleInstalled);
qtButton = new JRadioButton();
qtButton.setOpaque(false);
qtButton.setBorder(BorderFactory.createEmptyBorder(2, 10, 2, 0));
qtButton.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (!qtButton.isSelected()) return;
if (vm32Button.isSelected()) return;
Tracker.engineKnown = true;
// if 64-bit, set preferred VM to 32-bit and inform user
boolean has32BitVM = OSPRuntime.isMac() || ExtensionsManager.getManager().getDefaultJRE(32)!=null;
if (has32BitVM) {
int selected = JOptionPane.showConfirmDialog(trackerPanel.getTFrame(),
TrackerRes.getString("PrefsDialog.Dialog.SwitchToQT.Message"), //$NON-NLS-1$
TrackerRes.getString("PrefsDialog.Dialog.SwitchVM.Title"), //$NON-NLS-1$
JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null);
if(selected==JOptionPane.OK_OPTION) {
vm32Button.setSelected(true); // triggers selection of default or recent 32-bit VM
}
else {
// revert to previous engine
if (recentEngine.equals(VideoIO.ENGINE_XUGGLE)) {
xuggleButton.setSelected(true);
}
else if (recentEngine.equals(VideoIO.ENGINE_NONE)) {
noEngineButton.setSelected(true);
}
}
}
else { // help user download 32-bit VM
Object[] options = new Object[] {
TrackerRes.getString("PrefsDialog.Button.ShowHelpNow"), //$NON-NLS-1$
TrackerRes.getString("Dialog.Button.OK")}; //$NON-NLS-1$
int response = JOptionPane.showOptionDialog(trackerPanel.getTFrame(),
TrackerRes.getString("PrefsDialog.Dialog.No32bitVMQT.Message")+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$
TrackerRes.getString("PrefsDialog.Dialog.No32bitVM.Message"), //$NON-NLS-1$
TrackerRes.getString("PrefsDialog.Dialog.No32bitVM.Title"), //$NON-NLS-1$
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
noEngineButton.setSelected(true);
if (response==0) {
trackerPanel.getTFrame().showHelp("install", 0); //$NON-NLS-1$
}
}
if (qtButton.isSelected()) {
recentEngine = VideoIO.ENGINE_QUICKTIME;
}
}
});
qtButton.setEnabled(VideoIO.isEngineInstalled(VideoIO.ENGINE_QUICKTIME));
noEngineButton= new JRadioButton();
noEngineButton.setOpaque(false);
noEngineButton.setBorder(BorderFactory.createEmptyBorder(2, 10, 2, 0));
noEngineButton.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (!noEngineButton.isSelected()) return;
recentEngine = VideoIO.ENGINE_NONE;
VideoIO.setEngine(VideoIO.ENGINE_NONE);
Tracker.engineKnown = true;
}
});
videoTypeSubPanel.add(xuggleButton);
videoTypeSubPanel.add(qtButton);
videoTypeSubPanel.add(noEngineButton);
// xuggle speed subpanel
JPanel xuggleSpeedSubPanel = new JPanel();
box.add(xuggleSpeedSubPanel);
xuggleSpeedSubPanel.setBackground(color);
<API key> = BorderFactory.createTitledBorder(
TrackerRes.getString("PrefsDialog.Xuggle.Speed.BorderTitle")); //$NON-NLS-1$
if (!xuggleInstalled)
<API key>.setTitleColor(new Color(153, 153, 153));
xuggleSpeedSubPanel.setBorder(BorderFactory.<API key>(etched, <API key>));
buttonGroup = new ButtonGroup();
xuggleFastButton = new JRadioButton();
xuggleFastButton.setOpaque(false);
xuggleFastButton.setBorder(BorderFactory.createEmptyBorder(2, 0, 2, 10));
xuggleFastButton.setSelected(xuggleInstalled && Tracker.isXuggleFast);
buttonGroup.add(xuggleFastButton);
xuggleSlowButton = new JRadioButton();
xuggleSlowButton.setOpaque(false);
xuggleSlowButton.setBorder(BorderFactory.createEmptyBorder(2, 10, 2, 0));
xuggleSlowButton.setSelected(xuggleInstalled && !Tracker.isXuggleFast);
buttonGroup.add(xuggleSlowButton);
xuggleSpeedSubPanel.add(xuggleFastButton);
xuggleSpeedSubPanel.add(xuggleSlowButton);
// warnings subpanel
vidWarningCheckbox = new JCheckBox();
vidWarningCheckbox.setOpaque(false);
vidWarningCheckbox.setSelected(Tracker.warnNoVideoEngine);
vidWarningCheckbox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Tracker.warnNoVideoEngine = vidWarningCheckbox.isSelected();
}
});
xuggleErrorCheckbox = new JCheckBox();
xuggleErrorCheckbox.setOpaque(false);
xuggleErrorCheckbox.setSelected(Tracker.warnXuggleError);
xuggleErrorCheckbox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Tracker.warnXuggleError = xuggleErrorCheckbox.isSelected();
}
});
<API key> = new JCheckBox();
<API key>.setOpaque(false);
<API key>.setSelected(Tracker.<API key>);
<API key>.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Tracker.<API key> = <API key>.isSelected();
}
});
JPanel warningsSubPanel = new JPanel(new BorderLayout());
box.add(warningsSubPanel);
warningsSubPanel.setBackground(color);
<API key> = BorderFactory.createTitledBorder(
TrackerRes.getString("PrefsDialog.NoVideoWarning.BorderTitle")); //$NON-NLS-1$
warningsSubPanel.setBorder(BorderFactory.<API key>(etched, <API key>));
JPanel warningsNorthPanel = new JPanel();
warningsNorthPanel.setBackground(color);
warningsSubPanel.add(warningsNorthPanel, BorderLayout.NORTH);
JPanel warningsCenterPanel = new JPanel();
warningsCenterPanel.setBackground(color);
JPanel warningsSouthPanel = new JPanel();
warningsSouthPanel.setBackground(color);
JPanel centerSouthPanel = new JPanel(new BorderLayout());
centerSouthPanel.add(warningsCenterPanel, BorderLayout.NORTH);
centerSouthPanel.add(warningsSouthPanel, BorderLayout.CENTER);
warningsSubPanel.add(centerSouthPanel, BorderLayout.CENTER);
warningsNorthPanel.add(vidWarningCheckbox);
warningsNorthPanel.add(<API key>);
warningsCenterPanel.add(xuggleErrorCheckbox);
// set selected states of engine buttons AFTER creating the xugglefast, xuggleslow and warnxuggle buttons
if (VideoIO.getEngine().equals(VideoIO.ENGINE_QUICKTIME)
&& VideoIO.getVideoType("QT", null)!=null) { //$NON-NLS-1$
qtButton.setSelected(true);
}
else if (VideoIO.getEngine().equals(VideoIO.ENGINE_XUGGLE)
&& VideoIO.getVideoType("Xuggle", null)!=null) { //$NON-NLS-1$
xuggleButton.setSelected(true);
}
else noEngineButton.setSelected(true);
// "general" panel
generalPanel = new JPanel(new BorderLayout());
tabbedPane.addTab(null, generalPanel);
box = Box.createVerticalBox();
generalPanel.add(box, BorderLayout.CENTER);
// recent menu subpanel
JPanel recentSubPanel = new JPanel();
box.add(recentSubPanel);
recentSubPanel.setBackground(color);
<API key> = BorderFactory.createTitledBorder(
TrackerRes.getString("PrefsDialog.RecentFiles.BorderTitle")); //$NON-NLS-1$
recentSubPanel.setBorder(BorderFactory.<API key>(etched, <API key>));
// create clear recent button
clearRecentButton = new JButton();
clearRecentButton.setEnabled(!Tracker.recentFiles.isEmpty());
clearRecentButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Tracker.recentFiles.clear();
if (trackerPanel!=null) TMenuBar.getMenuBar(trackerPanel).refresh();
clearRecentButton.setEnabled(false);
}
});
recentSubPanel.add(clearRecentButton);
// create recent size spinner
JPanel spinnerPanel = new JPanel();
spinnerPanel.setOpaque(false);
spinnerPanel.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0));
n = Tracker.recentFilesSize;
model = new SpinnerNumberModel(n, 0, 12, 1);
recentSizeSpinner = new JSpinner(model);
editor = new JSpinner.NumberEditor(recentSizeSpinner, "0"); //$NON-NLS-1$
editor.getTextField().<API key>(SwingConstants.LEFT);
recentSizeSpinner.setEditor(editor);
spinnerPanel.add(recentSizeSpinner);
recentSizeLabel = new JLabel();
spinnerPanel.add(recentSizeLabel);
recentSubPanel.add(spinnerPanel);
// cache subpanel
JPanel cacheSubPanel = new JPanel(new BorderLayout());
box.add(cacheSubPanel);
cacheSubPanel.setBackground(color);
cacheSubPanelBorder = BorderFactory.createTitledBorder(
TrackerRes.getString("PrefsDialog.CacheFiles.BorderTitle")); //$NON-NLS-1$
cacheSubPanel.setBorder(BorderFactory.<API key>(etched, cacheSubPanelBorder));
// cacheNorthPanel: label, field and browse cache button
JPanel cacheNorthPanel = new JPanel();
cacheNorthPanel.setBackground(color);
cacheLabel = new JLabel();
cacheNorthPanel.add(cacheLabel);
cacheField = new JTextField(27);
cacheNorthPanel.add(cacheField);
final Action setCacheAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
String cachePath = XML.stripExtension(cacheField.getText());
Tracker.setCache(cachePath);
refreshTextFields();
}
};
cacheField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
cacheField.setBackground(Color.yellow);
}
});
cacheField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
if (cacheField.getBackground()==Color.yellow)
setCacheAction.actionPerformed(null);
}
});
cacheField.addActionListener(setCacheAction);
browseCacheButton = new TButton(openFileIcon);
browseCacheButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
File cache = ResourceLoader.getOSPCache();
Desktop desktop = Desktop.getDesktop();
try {
desktop.open(cache);
} catch (IOException ex) {
}
}
});
browseCacheButton.setBorder(buttonBorder);
browseCacheButton.<API key>(false);
cacheNorthPanel.add(browseCacheButton);
cacheSubPanel.add(cacheNorthPanel, BorderLayout.NORTH);
// cacheSouthPanel: clear cache button and set cache button
JPanel cacheSouthPanel = new JPanel();
cacheSouthPanel.setBackground(color);
clearHostButton = new JButton();
clearHostButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// get list of host directories
File cache = ResourceLoader.getOSPCache();
if (cache==null) return;
final File[] hosts = cache.listFiles(ResourceLoader.OSP_CACHE_FILTER);
// make popup menu with items to clear individual hosts
JPopupMenu popup = new JPopupMenu();
ActionListener clearAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (File host: hosts) {
if (host.getAbsolutePath().equals(e.getActionCommand())) {
ResourceLoader.clearOSPCacheHost(host);
refreshTextFields();
return;
}
}
}
};
for (File next: hosts) {
String host = next.getName().substring(4).replace('_', '.');
long bytes = getFileSize(next);
long size = bytes/(1024*1024);
if (bytes>0) {
if (size>0) host += " ("+size+" MB)"; //$NON-NLS-1$ //$NON-NLS-2$
else host += " ("+bytes/1024+" kB)"; //$NON-NLS-1$ //$NON-NLS-2$
}
JMenuItem item = new JMenuItem(host);
item.setActionCommand(next.getAbsolutePath());
popup.add(item);
item.addActionListener(clearAction);
}
FontSizer.setFonts(popup, FontSizer.getLevel());
popup.show(clearHostButton, 0, clearHostButton.getHeight());
}
});
cacheSouthPanel.add(clearHostButton);
clearCacheButton = new JButton();
clearCacheButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
File cache = ResourceLoader.getOSPCache();
ResourceLoader.clearOSPCache(cache, false);
refreshTextFields();
}
});
cacheSouthPanel.add(clearCacheButton);
setCacheButton = new JButton();
setCacheButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
File newCache = ResourceLoader.chooseOSPCache(trackerPanel.getTFrame());
if (newCache!=null) {
cacheField.setText(newCache.getPath());
setCacheAction.actionPerformed(null);
}
}
});
cacheSouthPanel.add(setCacheButton);
cacheSubPanel.add(cacheSouthPanel, BorderLayout.SOUTH);
// check for upgrades subpanel
<API key> = new JButton();
<API key>.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Tracker.loadCurrentVersion(true, false);
Tracker.lastMillisChecked = System.currentTimeMillis();
if (trackerPanel!=null) TTrackBar.getTrackbar(trackerPanel).refresh();
String message = TrackerRes.getString("PrefsDialog.Dialog.NewVersion.None.Message"); //$NON-NLS-1$
if (Tracker.newerVersion!=null) { // new version available
message = TrackerRes.getString("PrefsDialog.Dialog.NewVersion.Message1") //$NON-NLS-1$
+" "+Tracker.newerVersion+" " //$NON-NLS-1$ //$NON-NLS-2$
+TrackerRes.getString("PrefsDialog.Dialog.NewVersion.Message2") //$NON-NLS-1$
+XML.NEW_LINE+Tracker.trackerWebsite;
}
JOptionPane.showMessageDialog(PrefsDialog.this,
message,
TrackerRes.getString("PrefsDialog.Dialog.NewVersion.Title"), //$NON-NLS-1$
JOptionPane.INFORMATION_MESSAGE);
}
});
logLevelDropdown = new JComboBox();
defaultLevel = TrackerRes.getString("PrefsDialog.Version.Default").toUpperCase(); //$NON-NLS-1$
defaultLevel += " ("+Tracker.DEFAULT_LOG_LEVEL.toString().toLowerCase()+")"; //$NON-NLS-1$ //$NON-NLS-2$
selected = defaultLevel;
logLevelDropdown.addItem(defaultLevel);
for (int i=OSPLog.levels.length-1; i>=0; i
String s = OSPLog.levels[i].toString();
logLevelDropdown.addItem(s);
if (OSPLog.levels[i].equals(Tracker.preferredLogLevel)
&& !Tracker.preferredLogLevel.equals(Tracker.DEFAULT_LOG_LEVEL)) {
selected = s;
}
}
logLevelDropdown.setSelectedItem(selected);
logLevelDropdown.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
String s = logLevelDropdown.getSelectedItem().toString();
Level level = OSPLog.parseLevel(s);
if (level==null) level = Tracker.DEFAULT_LOG_LEVEL;
Tracker.preferredLogLevel = level;
}
});
JPanel logLevelSubPanel = new JPanel();
box.add(logLevelSubPanel);
logLevelSubPanel.setBackground(color);
<API key> = BorderFactory.createTitledBorder(
TrackerRes.getString("PrefsDialog.LogLevel.BorderTitle")); //$NON-NLS-1$
logLevelSubPanel.setBorder(BorderFactory.<API key>(etched, <API key>));
logLevelSubPanel.add(logLevelDropdown);
<API key> = new JComboBox();
selected = null;
for (String next: Tracker.<API key>) {
String s = TrackerRes.getString(next);
<API key>.addItem(s);
if (Tracker.<API key>.get(next).equals(
Tracker.<API key>)) {
selected = s;
}
}
<API key>.setSelectedItem(selected);
<API key>.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
String s = <API key>.getSelectedItem().toString();
for (String next: Tracker.<API key>) {
if (s.equals(TrackerRes.getString(next))) {
Tracker.<API key> = Tracker.<API key>.get(next);
break;
}
}
}
});
JPanel dropdownPanel = new JPanel();
dropdownPanel.setOpaque(false);
dropdownPanel.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0));
JPanel upgradeSubPanel = new JPanel();
box.add(upgradeSubPanel);
upgradeSubPanel.setBackground(color);
<API key> = BorderFactory.createTitledBorder(
TrackerRes.getString("PrefsDialog.Upgrades.BorderTitle")); //$NON-NLS-1$
upgradeSubPanel.setBorder(BorderFactory.<API key>(etched, <API key>));
upgradeSubPanel.add(<API key>);
dropdownPanel.add(<API key>);
upgradeSubPanel.add(dropdownPanel);
// main button bar
mainButtonBar = new JPanel();
mainButtonBar.add(relaunchButton);
mainButtonBar.add(okButton);
mainButtonBar.add(cancelButton);
contentPane.add(mainButtonBar, BorderLayout.SOUTH);
tabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (tabbedPane.<API key>()==runtimePanel) {
<API key>.setEnabled(!OSPRuntime.isWebStart());
if (OSPRuntime.isWebStart() && !<API key>) {
<API key> = true;
JOptionPane.showMessageDialog(PrefsDialog.this,
TrackerRes.getString("PrefsDialog.Dialog.WebStart.Message"), //$NON-NLS-1$
TrackerRes.getString("PrefsDialog.Dialog.WebStart.Title"), //$NON-NLS-1$
JOptionPane.INFORMATION_MESSAGE);
}
}
}
});
// add VM buttons to buttongroups
buttonGroup = new ButtonGroup();
buttonGroup.add(vm32Button);
buttonGroup.add(vm64Button);
// add engine buttons to buttongroups
buttonGroup = new ButtonGroup();
buttonGroup.add(xuggleButton);
buttonGroup.add(qtButton);
buttonGroup.add(noEngineButton);
// enable/disable buttons
xuggleFastButton.setEnabled(xuggleButton.isSelected());
xuggleSlowButton.setEnabled(xuggleButton.isSelected());
xuggleErrorCheckbox.setEnabled(xuggleButton.isSelected());
if (OSPRuntime.isWindows()) {
Runnable runner = new Runnable() {
public void run() {
vm32Button.setEnabled(!ExtensionsManager.getManager().getPublicJREs(32).isEmpty());
vm64Button.setEnabled(!ExtensionsManager.getManager().getPublicJREs(64).isEmpty());
}
};
new Thread(runner).start();
}
else if (OSPRuntime.isLinux()) {
int bitness = OSPRuntime.getVMBitness();
vm32Button.setEnabled(bitness==32);
vm64Button.setEnabled(bitness==64);
}
refreshGUI();
}
private void savePrevious() {
prevEnabled.clear();
if (trackerPanel!=null) prevEnabled.addAll(trackerPanel.getEnabled());
prevMemory = Tracker.preferredMemorySize;
prevLookFeel = Tracker.lookAndFeel;
prevRecentCount = Tracker.recentFilesSize;
prevLocaleName = Tracker.preferredLocale;
prevFontLevel = Tracker.preferredFontLevel;
prevHints = Tracker.showHintsByDefault;
prevRadians = Tracker.isRadians;
prevFastXuggle = Tracker.isXuggleFast;
prevJRE = Tracker.preferredJRE;
prevTrackerJar = Tracker.preferredTrackerJar;
prevExecutables = Tracker.<API key>;
<API key> = Tracker.warnNoVideoEngine;
prevWarnXuggleError = Tracker.warnXuggleError;
prevCache = ResourceLoader.getOSPCache();
prevUpgradeInterval = Tracker.<API key>;
prevUse32BitVM = Tracker.use32BitMode;
prevEngine = VideoIO.getEngine();
recentEngine = VideoIO.getEngine();
}
private void revert() {
if (trackerPanel!=null) trackerPanel.setEnabled(prevEnabled);
Tracker.preferredMemorySize = prevMemory;
Tracker.lookAndFeel = prevLookFeel;
Tracker.recentFilesSize = prevRecentCount;
Tracker.setPreferredLocale(prevLocaleName);
Tracker.preferredFontLevel = prevFontLevel;
Tracker.showHintsByDefault = prevHints;
Tracker.isRadians = prevRadians;
Tracker.isXuggleFast = prevFastXuggle;
Tracker.preferredJRE = prevJRE;
Tracker.preferredTrackerJar = prevTrackerJar;
Tracker.<API key> = prevExecutables;
Tracker.warnNoVideoEngine = <API key>;
Tracker.warnXuggleError = prevWarnXuggleError;
ResourceLoader.setOSPCache(prevCache);
Tracker.<API key> = prevUpgradeInterval;
Tracker.use32BitMode = prevUse32BitVM;
// reset JRE dropdown to initial state
int vmBitness = OSPRuntime.getVMBitness();
if (vmBitness==32) {
recent32bitVM = null;
vm32Button.setSelected(true);
}
else {
recent64bitVM = null;
vm64Button.setSelected(true);
}
}
/**
* Updates the configuration to reflect the current checkbox states.
*/
private void updateConfig() {
if (trackerPanel==null) return;
// get the checkboxes
Component[] checkboxes = checkPanel.getComponents();
for (int i = 0; i < checkboxes.length; i++) {
JCheckBoxMenuItem checkbox = (JCheckBoxMenuItem)checkboxes[i];
if (checkbox.isSelected())
trackerPanel.getEnabled().add(checkbox.getText());
else
trackerPanel.getEnabled().remove(checkbox.getText());
}
}
/**
* Refreshes the GUI.
*/
protected void refreshGUI() {
cancelButton.setText(TrackerRes.getString("Dialog.Button.Cancel")); //$NON-NLS-1$
saveButton.setText(TrackerRes.getString("ConfigInspector.Button.SaveAsDefault")); //$NON-NLS-1$
okButton.setText(TrackerRes.getString("PrefsDialog.Button.Save")); //$NON-NLS-1$
applyButton.setText(TrackerRes.getString("Dialog.Button.Apply")); //$NON-NLS-1$
applyButton.setEnabled(trackerPanel!=null);
allButton.setText(TrackerRes.getString("Dialog.Button.All")); //$NON-NLS-1$
noneButton.setText(TrackerRes.getString("Dialog.Button.None")); //$NON-NLS-1$
relaunchButton.setText(TrackerRes.getString("PrefsDialog.Button.Relaunch")); //$NON-NLS-1$
clearRecentButton.setText(TrackerRes.getString("PrefsDialog.Button.ClearRecent")); //$NON-NLS-1$
cacheLabel.setText(TrackerRes.getString("PrefsDialog.Label.Path")+":"); //$NON-NLS-1$ //$NON-NLS-2$
clearCacheButton.setToolTipText(TrackerRes.getString("PrefsDialog.Button.ClearCache.Tooltip")); //$NON-NLS-1$
clearHostButton.setText(TrackerRes.getString("PrefsDialog.Button.ClearHost")); //$NON-NLS-1$
clearHostButton.setToolTipText(TrackerRes.getString("PrefsDialog.Button.ClearHost.Tooltip")); //$NON-NLS-1$
setCacheButton.setText(TrackerRes.getString("PrefsDialog.Button.SetCache")); //$NON-NLS-1$
<API key>.setText(TrackerRes.getString("PrefsDialog.Button.CheckForUpgrade")); //$NON-NLS-1$
recentSizeLabel.setText(TrackerRes.getString("PrefsDialog.Label.RecentSize")); //$NON-NLS-1$
<API key>.setText(TrackerRes.getString("PrefsDialog.Checkbox.DefaultSize")); //$NON-NLS-1$
hintsCheckbox.setText(TrackerRes.getString("PrefsDialog.Checkbox.HintsOn")); //$NON-NLS-1$
vm32Button.setText(TrackerRes.getString("PrefsDialog.Checkbox.32BitVM")); //$NON-NLS-1$
vm64Button.setText(TrackerRes.getString("PrefsDialog.Checkbox.64BitVM")); //$NON-NLS-1$
xuggleButton.setText(TrackerRes.getString("PrefsDialog.Button.Xuggle")); //$NON-NLS-1$
qtButton.setText(TrackerRes.getString("PrefsDialog.Button.QT")); //$NON-NLS-1$
noEngineButton.setText(TrackerRes.getString("PrefsDialog.Button.NoEngine")); //$NON-NLS-1$
radiansButton.setText(TrackerRes.getString("TMenuBar.MenuItem.Radians")); //$NON-NLS-1$
degreesButton.setText(TrackerRes.getString("TMenuBar.MenuItem.Degrees")); //$NON-NLS-1$
xuggleFastButton.setText(TrackerRes.getString("PrefsDialog.Xuggle.Fast")); //$NON-NLS-1$
xuggleSlowButton.setText(TrackerRes.getString("PrefsDialog.Xuggle.Slow")); //$NON-NLS-1$
vidWarningCheckbox.setText(TrackerRes.getString("PrefsDialog.Checkbox.WarnIfNoEngine")); //$NON-NLS-1$
<API key>.setText(TrackerRes.getString("PrefsDialog.Checkbox.<API key>")); //$NON-NLS-1$
xuggleErrorCheckbox.setText(TrackerRes.getString("PrefsDialog.Checkbox.WarnIfXuggleError")); //$NON-NLS-1$
setTabTitle(configPanel, TrackerRes.getString("PrefsDialog.Tab.Configuration.Title")); //$NON-NLS-1$
setTabTitle(runtimePanel, TrackerRes.getString("PrefsDialog.Tab.Runtime.Title")); //$NON-NLS-1$
setTabTitle(videoPanel, TrackerRes.getString("PrefsDialog.Tab.Video.Title")); //$NON-NLS-1$
setTabTitle(displayPanel, TrackerRes.getString("PrefsDialog.Tab.Display.Title")); //$NON-NLS-1$
setTabTitle(generalPanel, TrackerRes.getString("PrefsDialog.Tab.General.Title")); //$NON-NLS-1$
refreshTextFields();
setFontLevel(FontSizer.getLevel());
pack();
updateDisplay();
}
private void refreshJREDropdown(final int vmBitness) {
// refresh JRE dropdown in background thread
Runnable runner = new Runnable() {
public void run() {
while (!ExtensionsManager.isReady()) {
try {
Thread.sleep(200);
} catch (<API key> e) {
}
}
Runnable refresher = new Runnable() {
public void run() {
refreshing = true; // suppresses dropdown actions
// replace items in dropdown
jreDropdown.removeAllItems();
ExtensionsManager manager = ExtensionsManager.getManager();
Set<String> availableJREs = manager.getAllJREs(vmBitness);
for (String next: availableJREs) {
jreDropdown.addItem(next);
}
// set selected item
String selectedItem = null;
if (vmBitness==32 && recent32bitVM!=null) {
selectedItem = recent32bitVM;
}
else if (vmBitness==64 && recent64bitVM!=null) {
selectedItem = recent64bitVM;
}
if (selectedItem==null) {
selectedItem = Tracker.preferredJRE;
if (selectedItem==null || !availableJREs.contains(selectedItem)) {
selectedItem = vmBitness==32? Tracker.preferredJRE32: Tracker.preferredJRE64;
if (selectedItem==null || !availableJREs.contains(selectedItem)) {
selectedItem = manager.getDefaultJRE(vmBitness);
}
}
}
jreDropdown.setSelectedItem(selectedItem);
// save selected item for future refreshing
if (vmBitness==32) {
recent32bitVM = selectedItem;
}
else {
recent64bitVM = selectedItem;
}
refreshing = false;
if (vmBitness==32 && relaunching) {
// check that not canceled by user
if (!"cancel".equals(vm32Button.getName())) { //$NON-NLS-1$
relaunching = false;
relaunchButton.doClick(0);
}
}
}
};
SwingUtilities.invokeLater(refresher);
}
};
new Thread(runner).start();
}
private void refreshTextFields() {
// run field
int n = (Integer)runSpinner.getValue();
if (Tracker.<API key>.length>n
&& Tracker.<API key>[n]!=null) {
runField.setText(Tracker.<API key>[n]);
runField.setToolTipText(Tracker.<API key>[n]);
runField.setBackground(new File(Tracker.<API key>[n]).exists()? Color.white: MEDIUM_RED);
}
else {
runField.setText(null);
runField.setToolTipText(null);
runField.setBackground(Color.white);
}
// cache field and button
String s = TrackerRes.getString("PrefsDialog.Button.ClearCache"); //$NON-NLS-1$
File cache = ResourceLoader.getOSPCache();
if (cache!=null) {
cacheField.setText(cache.getPath());
cacheField.setToolTipText(cache.getAbsolutePath());
cacheField.setBackground(cache.canWrite()? Color.white: MEDIUM_RED);
long bytes = getFileSize(cache);
long size = bytes/(1024*1024);
if (bytes>0) {
if (size>0) s += " ("+size+" MB)"; //$NON-NLS-1$ //$NON-NLS-2$
else s += " ("+bytes/1024+" kB)"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
else {
cacheField.setText(""); //$NON-NLS-1$
cacheField.setToolTipText(""); //$NON-NLS-1$
cacheField.setBackground(MEDIUM_RED);
}
clearCacheButton.setText(s);
boolean isEmpty = cache==null || !cache.exists()
|| cache.listFiles(ResourceLoader.OSP_CACHE_FILTER).length==0;
clearCacheButton.setEnabled(!isEmpty);
clearHostButton.setEnabled(!isEmpty);
}
/**
* Applies and saves the current preferences.
*/
private void applyPrefs() {
// look/feel, language, video, hints, fontlevel are set directly by components
// update configuration
updateConfig();
// update recent menu
Integer val = (Integer)recentSizeSpinner.getValue();
Tracker.setRecentSize(val);
if (trackerPanel!=null) TMenuBar.getMenuBar(trackerPanel).refresh();
// update preferred memory size
if (<API key>.isSelected())
Tracker.preferredMemorySize = -1;
else
Tracker.preferredMemorySize = memoryField.getIntValue();
// update preferred JRE
Object selected = jreDropdown.getSelectedItem();
if (selected !=null && !selected.equals(Tracker.preferredJRE)) {
Tracker.preferredJRE = selected.toString();
if (ExtensionsManager.getManager().is32BitVM(Tracker.preferredJRE)) {
Tracker.preferredJRE32 = Tracker.preferredJRE;
}
else Tracker.preferredJRE64 = Tracker.preferredJRE;
}
// video engine
if (xuggleButton.isSelected() && xuggleButton.isEnabled()) {
VideoIO.setEngine(VideoIO.ENGINE_XUGGLE);
}
else if (qtButton.isSelected() && qtButton.isEnabled()) {
VideoIO.setEngine(VideoIO.ENGINE_QUICKTIME);
}
else VideoIO.setEngine(VideoIO.ENGINE_NONE);
Tracker.isRadians = radiansButton.isSelected();
Tracker.isXuggleFast = xuggleFastButton.isSelected();
if (frame!=null) frame.setAnglesInRadians(Tracker.isRadians);
// save the tracker and tracker_starter preferences
String path = Tracker.savePreferences();
if (path!=null)
OSPLog.info("saved tracker preferences in "+XML.getAbsolutePath(new File(path))); //$NON-NLS-1$
}
/**
* Saves the current configuration as the default.
*/
private void saveConfigAsDefault() {
Component[] checkboxes = checkPanel.getComponents();
Set<String> enabled = new TreeSet<String>();
for (int i = 0; i < checkboxes.length; i++) {
JCheckBoxMenuItem checkbox = (JCheckBoxMenuItem)checkboxes[i];
if (checkbox.isSelected())
enabled.add(checkbox.getText());
}
// applyButton.doClick(0);
Tracker.setDefaultConfig(enabled);
}
/**
* Updates this dialog to show the TrackerPanel's current preferences.
*/
protected void updateDisplay() {
// configuration
Component[] checkboxes = checkPanel.getComponents();
for (int i = 0; i < checkboxes.length; i++) {
// check the checkbox if its text is in the current config
JCheckBoxMenuItem checkbox = (JCheckBoxMenuItem)checkboxes[i];
Set<String> enabled = trackerPanel!=null? trackerPanel.getEnabled(): Tracker.getDefaultConfig();
checkbox.setSelected(enabled.contains(checkbox.getText()));
}
// memory size
<API key>.setSelected(Tracker.preferredMemorySize<0);
memoryField.setEnabled(Tracker.preferredMemorySize>=0);
memoryLabel.setEnabled(Tracker.preferredMemorySize>=0);
if (Tracker.preferredMemorySize>=0)
memoryField.setValue(Tracker.preferredMemorySize);
else {
memoryField.setText(null);
}
// look and feel
if (Tracker.lookAndFeel!=null)
lookFeelDropdown.setSelectedItem(Tracker.lookAndFeel.toLowerCase());
// recent files
recentSizeSpinner.setValue(Tracker.recentFilesSize);
// hints
hintsCheckbox.setSelected(Tracker.showHintsByDefault);
// warnings
vidWarningCheckbox.setSelected(Tracker.warnNoVideoEngine);
<API key>.setSelected(Tracker.<API key>);
xuggleErrorCheckbox.setSelected(Tracker.warnXuggleError);
// locale
for (Locale next: Tracker.locales) {
if (next.equals(Locale.getDefault())) {
languageDropdown.setSelectedItem(OSPRuntime.getDisplayLanguage(next));
break;
}
}
// tracker jar
int selected = 0;
for (int i = 0, count = versionDropdown.getItemCount(); i<count; i++) {
String next = versionDropdown.getItemAt(i).toString();
if (Tracker.preferredTrackerJar!=null && Tracker.preferredTrackerJar.indexOf(next)>-1) {
selected = i;
break;
}
}
if (versionDropdown.getItemCount()>selected) {
versionDropdown.setSelectedIndex(selected);
}
// VM dropdown
selected = 0;
for (int i = 0, count = jreDropdown.getItemCount(); i<count; i++) {
String next = jreDropdown.getItemAt(i).toString();
if (next.equals(Tracker.preferredJRE)) {
selected = i;
break;
}
}
if (jreDropdown.getItemCount()>selected) {
jreDropdown.setSelectedIndex(selected);
}
// log level
selected = 0;
if (!Tracker.preferredLogLevel.equals(Tracker.DEFAULT_LOG_LEVEL)) {
for (int i = 1, count = logLevelDropdown.getItemCount(); i<count; i++) {
String next = logLevelDropdown.getItemAt(i).toString();
if (Tracker.preferredLogLevel.toString().equals(next)) {
selected = i;
break;
}
}
}
if (logLevelDropdown.getItemCount()>selected) {
logLevelDropdown.setSelectedIndex(selected);
}
// checkForUpgrade
selected = 0;
for (int i = 1, count = Tracker.<API key>.size(); i<count; i++) {
String next = Tracker.<API key>.get(i);
if (Tracker.<API key>.get(next)==Tracker.<API key>) {
selected = i;
break;
}
}
if (<API key>.getItemCount()>selected) {
<API key>.setSelectedIndex(selected);
}
// video
if (VideoIO.getEngine().equals(VideoIO.ENGINE_QUICKTIME)) {
qtButton.setSelected(true);
}
else if (VideoIO.getEngine().equals(VideoIO.ENGINE_XUGGLE)) {
xuggleButton.setSelected(true);
}
qtButton.setEnabled(true);
vm32Button.setEnabled(true);
// // if running OSX version 10.10 or later, disable 32-bit VM and QuickTime buttons
// if (OSPRuntime.isMac()) {
// String version = System.getProperty("os.version"); //$NON-NLS-1$
// if (version!=null) {
// int n = version.indexOf("."); //$NON-NLS-1$
// if (n>-1) {
// version = version.substring(n+1);
// if (version.length()>1) {
// try {
// int vers = Integer.parseInt(version.substring(0, 2));
// if (vers>=10) {
// // disable 32-bit VM and QuickTime buttons
// qtButton.setEnabled(false);
// vm32Button.setEnabled(false);
// vm64Button.setSelected(true);
// Tracker.preferredJRE32 = null;
// } catch (<API key> e) {
repaint();
}
/**
* Sets the title of a specified tab.
*/
private void setTabTitle(JPanel tab, String title) {
for (int i = 0; i<tabbedPane.getTabCount(); i++) {
if (tabbedPane.getComponentAt(i)==tab)
tabbedPane.setTitleAt(i, title);
}
}
/**
* Relaunches after changing preferred VM to 32-bit
*/
protected void relaunch32Bit() {
relaunching = true;
vm32Button.setSelected(true); // also sets default video engine
}
/**
* Gets the total size of a folder.
*
* @param folder the folder
* @return the size in bytes
*/
private long getFileSize(File folder) {
if (folder==null) return 0;
long foldersize = 0;
File cache = ResourceLoader.getOSPCache();
File[] files = folder.equals(cache)?
folder.listFiles(ResourceLoader.OSP_CACHE_FILTER):
folder.listFiles();
if (files==null) return 0;
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
foldersize += getFileSize(files[i]);
} else {
foldersize += files[i].length();
}
}
return foldersize;
}
/**
* Gets a file chooser.
*
* @param file the initial file to select
* @param useJREFilter true if setting JRE
* @return the file chooser
*/
protected static JFileChooser getFileChooser(File file, boolean useJREFilter) {
JFileChooser chooser = new JFileChooser(file);
if (useJREFilter) {
FileFilter folderFilter = new FileFilter() {
// accept directories or "jre/jdk" files only
public boolean accept(File f) {
if (f==null) return false;
if (f.isDirectory()) return true;
if (f.getPath().indexOf("jre")>-1) return true; //$NON-NLS-1$
if (f.getPath().indexOf("jdk")>-1) return true; //$NON-NLS-1$
return false;
}
public String getDescription() {
return TrackerRes.getString("PrefsDialog.FileFilter.JRE"); //$NON-NLS-1$
}
};
if (OSPRuntime.isMac())
chooser.<API key>(JFileChooser.<API key>);
else
chooser.<API key>(JFileChooser.DIRECTORIES_ONLY);
chooser.<API key>(false);
chooser.<API key>(folderFilter);
}
FontSizer.setFonts(chooser, FontSizer.getLevel());
return chooser;
}
} |
#!/bin/bash
# set -x
# replace an image with a new one
function Finish() {
local rc=${1:-$?}
local pid=$$
trap - INT QUIT TERM EXIT
if [[ $rc -ne 0 ]]; then
echo
date
echo " pid $pid exited with rc=$rc"
fi
rm $lockfile
exit $rc
}
function ImagesInRunShuffled() {
(set +f; cd ~tinderbox/run; ls -d * 2>/dev/null | shuf)
}
function FreeSlotAvailable() {
r=$(ls /run/tinderbox 2>/dev/null | wc -l)
s=$(pgrep -c -f $(dirname $0)/setup_img.sh)
[[ $(( r+s )) -lt $desired_count && $(ImagesInRunShuffled | wc -l) -lt $desired_count ]]
}
function <API key>() {
local msg="kicked off b/c: $(cat ~tinderbox/img/$oldimg/var/tmp/tb/REPLACE_ME)"
if __is_running $oldimg; then
echo
date
echo " stopping: $oldimg"
touch ~tinderbox/img/$oldimg/var/tmp/tb/STOP
local i=1800
while __is_locked $oldimg
do
if ! (( --i )); then
echo " give up to wait for $oldimg"
return 1
fi
sleep 1
done
echo "done"
else
echo "$oldimg $msg"
fi
}
function setupNewImage() {
echo
date
echo " setup a new image ..."
sudo $(dirname $0)/setup_img.sh
}
set -euf
export PATH="/usr/sbin:/usr/bin:/sbin:/bin:/opt/tb/bin"
export LANG=C.utf8
if [[ "$(whoami)" != "tinderbox" ]]; then
echo " you must be tinderbox"
exit 1
fi
source $(dirname $0)/lib.sh
desired_count=13 # number of images to be run
while getopts n:u: opt
do
case "$opt" in
n) desired_count="$OPTARG" ;;
u) echo "user decision" >> ~tinderbox/img/$(basename $OPTARG)/var/tmp/tb/REPLACE_ME ;;
*) echo " opt not implemented: '$opt'"; exit 1 ;;
esac
done
# do not run in parallel from here
lockfile="/tmp/$(basename $0).lck"
if [[ -s "$lockfile" ]]; then
if kill -0 $(cat $lockfile) 2>/dev/null; then
exit 1 # a previous instance is (still) running
else
echo " found stale lockfile content:"
cat $lockfile
fi
fi
echo $$ > "$lockfile" || exit 1
trap Finish INT QUIT TERM EXIT
while :
do
if FreeSlotAvailable; then
if ! setupNewImage; then
echo " setup failed, sleep 10 min ..."
if ! sleep 600; then
: # allow to kill it
fi
continue
fi
fi
while read -r oldimg
do
if ! __is_running $oldimg; then
hours=$(( (EPOCHSECONDS-$(stat -c %Y ~tinderbox/img/$oldimg/var/tmp/tb/task))/3600 ))
if [[ $hours -ge 36 ]]; then
echo -e "last task $hours hour/s ago" >> ~tinderbox/img/$oldimg/var/tmp/tb/REPLACE_ME
fi
fi
if [[ -f ~tinderbox/run/$oldimg/var/tmp/tb/REPLACE_ME ]]; then
if <API key>; then
rm ~tinderbox/run/$oldimg ~tinderbox/logs/$oldimg.log
continue 2
fi
fi
done < <(ImagesInRunShuffled)
break
done
Finish 0 |
package packinglib
import (
"fmt"
"sort"
"strings"
)
// Property is used to describe an attribute of a context that should be
// user understandable. Users will choose which properties apply to a given
// context.
type Property string
// PropertySet is a map holding a list of Properties. A value of true
// indicates that the Property is allowed. A value of false indicates
// that the presence of that property is not allowed. Properties are
// ORed together: Any allowed Property satisfies the item, but any
// disallowed Property causes the item to reject.
type PropertySet map[Property]bool
var allProperties = map[Property]string{
"Art": "gonna do some drawing",
"BigTrip": "this is a big deal",
"Boat": "on a boat! (or floating in a tube)",
"Bright": "sun, and therefore sunscreen.",
"Burn": "",
"Business": "some work happening.",
"BYOB": "need to pack some booze",
"Camping": "",
"CarRide": "includes a long drive",
"Con": "convention of any sort",
"Climbing": "",
"Dog": "Bringing the doggo",
"LeadClimbing": "Extra gear for lead",
"Cycling": "moderate amount of biking",
"CyclingLongRide": "biking a long distance",
"Dark": "mostly for camping, but anytime you'll be wandering in the dark",
"Dirt": "are you going to get dirty?",
"DiningOut": "",
"Flight": "",
"GrumpCamping": "A special type of burn",
"Handy": "need tools?",
"HasToiletries": "",
"Hiking": "tromping through the woods",
"Insecure": "Don't bring valuables",
"International": "",
"Karaoke": "Belting out some classics",
"Lodging": "Paid lodging like a hotel or airbnb",
"Loud": "",
"Nevermore": "",
"NoCheckedLuggage": "",
"NoFire": "Used when there's camping, but no fire allowed at all",
"NYC": "New York City???",
"PaidEvent": "Concerts, shows, cons, etc",
"PaidTravel": "Paying to travel (Flight, rail, bus, etc)",
"Projector": "Movies on the big screen",
"Speaker": "Need to play some music",
"Suiting": "",
"Partying": "",
"Playtime": "",
"Skiing": "",
"Snow": "",
"Sweat": "are you gonna sweat up the car?",
"Swimming": "",
"Tarping": "Putting up tarps",
"Tiny House": "",
"UltraFormal": "do you need to *really* dress up?",
"Vax Proof": "proof of vaccination needed?",
"PA System": "Need the PA",
"Performing": "Use this for all music, and then add the specific ones",
"Modular": "",
"DJing": "",
"MiniMixxx": "",
}
// RegisterProperty adds a new Property to the database so it can be used.
// desc should be a user-visible description of the property.
// Does not verify that all of the properties are in the allProperties map.
func RegisterProperty(prop Property, desc string) {
// Don't worry if the property already exists.
allProperties[prop] = desc
}
func buildPropertySet(allow, disallow []string) PropertySet {
propSet := make(PropertySet)
for _, a := range allow {
propSet[Property(a)] = true
}
for _, d := range disallow {
if _, ok := propSet[Property(d)]; ok {
panic(fmt.Sprintf("Contradiction: Property already registered in allowed side: %s", d))
}
propSet[Property(d)] = false
}
return propSet
}
// ListProperties returns all of the registered properties as a slice of strings.
func ListProperties() []Property {
var l []Property
for k := range allProperties {
l = append(l, k)
}
less := func(i, j int) bool {
return strings.ToLower(string(l[i])) < strings.ToLower(string(l[j]))
}
sort.Slice(l, less)
return l
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="author" content="cTn"/>
<link type="text/css" rel="stylesheet" href="./css/main.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./js/libraries/jquery.nouislider.min.css"/>
<link type="text/css" rel="stylesheet" href="./js/libraries/jquery.nouislider.pips.min.css"/>
<link type="text/css" rel="stylesheet" href="./js/libraries/flightindicators.css"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/landing.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/setup.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/setup_osd.css" media="all" />
<link type="text/css" rel="stylesheet" href="./css/tabs/help.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/ports.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/configuration.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/pid_tuning.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/receiver.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/servos.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/gps.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/motors.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/led_strip.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/sensors.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/cli.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/logging.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/onboard_logging.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/firmware_flasher.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/adjustments.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/auxiliary.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/failsafe.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/osd.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/power.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/tabs/transponder.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/font-awesome/css/font-awesome.min.css" media="all">
<link type="text/css" rel="stylesheet" href="./css/opensans_webfontkit/fonts.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./css/dropdown-lists/css/style_lists.css" media="all"/>
<link type="text/css" rel="stylesheet" href="./js/libraries/switchery/switchery.css" media="all"/>
<link rel="stylesheet" type="text/css" href="./js/libraries/jbox/jBox.css"/>
<script type="text/javascript" src="./node_modules/lru_map/lru.js"></script>
<script type="text/javascript" src="./node_modules/i18next/i18next.js"></script>
<script type="text/javascript" src="./node_modules/i18next-xhr-backend/i18nextXHRBackend.js"></script>
<script type="text/javascript" src="./node_modules/marked/marked.min.js"></script>
<script type="text/javascript" src="./node_modules/universal-ga/lib/analytics.min.js"></script>
<script type="text/javascript" src="./node_modules/short-unique-id/dist/short-unique-id.min.js"></script>
<script type="text/javascript" src="./node_modules/object-hash/dist/object_hash.js"></script>
<script type="text/javascript" src="./js/libraries/q.js"></script>
<script type="text/javascript" src="./js/libraries/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="./js/libraries/jquery-ui-1.11.4.min.js"></script>
<script type="text/javascript" src="./js/libraries/d3.min.js"></script>
<script type="text/javascript" src="./js/libraries/jquery.nouislider.all.min.js"></script>
<script type="text/javascript" src="./js/libraries/three/three.min.js"></script>
<script type="text/javascript" src="./js/libraries/three/Projector.js"></script>
<script type="text/javascript" src="./js/libraries/three/CanvasRenderer.js"></script>
<script type="text/javascript" src="./js/libraries/jquery.flightindicators.js"></script>
<script type="text/javascript" src="./js/libraries/semver.js"></script>
<script type="text/javascript" src="./js/libraries/jbox/jBox.min.js"></script>
<script type="text/javascript" src="./js/libraries/switchery/switchery.js"></script>
<script type="text/javascript" src="./js/libraries/bluebird.min.js"></script>
<script type="text/javascript" src="./js/libraries/jquery.<API key>.min.js"></script>
<script type="text/javascript" src="./js/libraries/inflection.min.js"></script>
<script type="text/javascript" src="./js/libraries/analytics.js"></script>
<script type="text/javascript" src="./js/injected_methods.js"></script>
<script type="text/javascript" src="./js/data_storage.js"></script>
<script type="text/javascript" src="./js/fc.js"></script>
<script type="text/javascript" src="./js/port_handler.js"></script>
<script type="text/javascript" src="./js/port_usage.js"></script>
<script type="text/javascript" src="./js/serial.js"></script>
<script type="text/javascript" src="./js/gui.js"></script>
<script type="text/javascript" src="./js/huffman.js"></script>
<script type="text/javascript" src="./js/<API key>.js"></script>
<script type="text/javascript" src="./js/model.js"></script>
<script type="text/javascript" src="./js/serial_backend.js"></script>
<script type="text/javascript" src="./js/msp/MSPCodes.js"></script>
<script type="text/javascript" src="./js/msp.js"></script>
<script type="text/javascript" src="./js/msp/MSPHelper.js"></script>
<script type="text/javascript" src="./js/backup_restore.js"></script>
<script type="text/javascript" src="./js/peripherals.js"></script>
<script type="text/javascript" src="./js/protocols/stm32.js"></script>
<script type="text/javascript" src="./js/protocols/stm32usbdfu.js"></script>
<script type="text/javascript" src="./js/localization.js"></script>
<script type="text/javascript" src="./js/boards.js"></script>
<script type="text/javascript" src="./js/RateCurve.js"></script>
<script type="text/javascript" src="./js/Features.js"></script>
<script type="text/javascript" src="./js/Beepers.js"></script>
<script type="text/javascript" src="./js/release_checker.js"></script>
<script type="text/javascript" src="./js/jenkins_loader.js"></script>
<script type="text/javascript" src="./js/Analytics.js"></script>
<script type="text/javascript" src="./js/main.js"></script>
<script type="text/javascript" src="./js/tabs/landing.js"></script>
<script type="text/javascript" src="./js/tabs/setup.js"></script>
<script type="text/javascript" src="./js/tabs/setup_osd.js"></script>
<script type="text/javascript" src="./js/tabs/help.js"></script>
<script type="text/javascript" src="./js/tabs/ports.js"></script>
<script type="text/javascript" src="./js/tabs/configuration.js"></script>
<script type="text/javascript" src="./js/tabs/pid_tuning.js"></script>
<script type="text/javascript" src="./js/tabs/receiver.js"></script>
<script type="text/javascript" src="./js/tabs/auxiliary.js"></script>
<script type="text/javascript" src="./js/tabs/adjustments.js"></script>
<script type="text/javascript" src="./js/tabs/servos.js"></script>
<script type="text/javascript" src="./js/tabs/gps.js"></script>
<script type="text/javascript" src="./js/tabs/motors.js"></script>
<script type="text/javascript" src="./js/tabs/led_strip.js"></script>
<script type="text/javascript" src="./js/tabs/sensors.js"></script>
<script type="text/javascript" src="./js/tabs/cli.js"></script>
<script type="text/javascript" src="./js/tabs/logging.js"></script>
<script type="text/javascript" src="./js/tabs/onboard_logging.js"></script>
<script type="text/javascript" src="./js/FirmwareCache.js"></script>
<script type="text/javascript" src="./js/tabs/firmware_flasher.js"></script>
<script type="text/javascript" src="./js/tabs/failsafe.js"></script>
<script type="text/javascript" src="./js/LogoManager.js"></script>
<script type="text/javascript" src="./js/tabs/osd.js"></script>
<script type="text/javascript" src="./js/tabs/power.js"></script>
<script type="text/javascript" src="./js/tabs/transponder.js"></script>
<title i18n="windowTitle"></title>
</head>
<body>
<div id="main-wrapper">
<div class="headerbar">
<div id="logo">
<div class="logo_text">
CONFIGURATOR
<div class="version"></div>
</div>
</div>
<a id="options" href="#" i18n_title="options_title"></a>
<div id="port-picker">
<div class="connect_controls" id="connectbutton">
<div class="connect_b">
<a class="connect disabled" href="
</div>
<a class="connect_state" i18n="connect"></a>
</div>
<div id="portsinput">
<div class="dropdown dropdown-dark">
<select class="dropdown-select" id="port" i18n_title="<API key>">
<option value="manual">Manual</option>
<!-- port list gets generated here -->
</select>
</div>
<div class="dropdown dropdown-dark">
<select class="dropdown-select" id="baud" i18n_title="<API key>">
<option value="1000000">1000000</option>
<option value="500000">500000</option>
<option value="250000">250000</option>
<option value="115200" selected="selected">115200</option>
<option value="57600">57600</option>
<option value="38400">38400</option>
<option value="28800">28800</option>
<option value="19200">19200</option>
<option value="14400">14400</option>
<option value="9600">9600</option>
<option value="4800">4800</option>
<option value="2400">2400</option>
<option value="1200">1200</option>
</select>
</div>
<div id="<API key>">
<label for="port-override"><span i18n="portOverrideText">Port:</span> <input id="port-override" type="text"
value="/dev/rfcomm0"/></label>
</div>
<div>
<label><input class="auto_connect togglesmall" type="checkbox"/><span
class="auto_connect" i18n="autoConnect"></span></label>
</div>
</div>
</div>
<div class="header-wrapper">
<div id="<API key>">
<div class="noflash_global" align="center" i18n="<API key>"></div>
<ul class="<API key>">
<li class="<API key>">
<div class="legend" i18n="<API key>"></div>
</li>
</ul>
<div id="expertMode" align="center">
<label>
<input name="expertModeCheckbox" class="togglesmall" type="checkbox"/>
<span i18n="expertMode"></span>
</label>
</div>
</div>
<div id="sensor-status" class="sensor_state mode-connected">
<ul>
<li class="gyro" i18n_title="sensorStatusGyro">
<div class="gyroicon" i18n="<API key>"></div>
</li>
<li class="accel" i18n_title="sensorStatusAccel">
<div class="accicon" i18n="<API key>"></div>
</li>
<li class="mag" i18n_title="sensorStatusMag">
<div class="magicon" i18n="<API key>"></div>
</li>
<li class="baro" i18n_title="sensorStatusBaro">
<div class="baroicon" i18n="<API key>"></div>
</li>
<li class="gps" i18n_title="sensorStatusGPS">
<div class="gpsicon" i18n="<API key>"></div>
</li>
<li class="sonar" i18n_title="sensorStatusSonar">
<div class="sonaricon" i18n="<API key>"></div>
</li>
</ul>
</div>
<div id="quad-status_wrapper">
<div class="battery-icon">
<div class="<API key>">
<div class="battery-status"></div>
</div>
</div>
<div class="battery-legend">Battery voltage</div>
<div class="bottomStatusIcons">
<div class="armedicon cf_tip" i18n_title="mainHelpArmed"></div>
<div class="failsafeicon cf_tip" i18n_title="mainHelpFailsafe"></div>
<div class="linkicon cf_tip" i18n_title="mainHelpLink"></div>
</div>
</div>
</div>
</div>
<div class="clear-both"></div>
<div id="log">
<div class="logswitch">
<a href="#" id="showlog" i18n="logActionShow"></a>
</div>
<div id="scrollicon"></div>
<div class="wrapper"></div>
</div>
<div class="tab_container">
<div id="tabs">
<ul class="mode-disconnected">
<li class="tab_landing"><a href="#" i18n="tabLanding" class="tabicon ic_welcome" i18n_title="tabLanding"></a>
</li>
<li class="tab_help"><a href="#" i18n="tabHelp" class="tabicon ic_help"
i18n_title="tabHelp"></a></li>
<li class="<API key>"><a href="#" i18n="tabFirmwareFlasher" class="tabicon ic_flasher"
i18n_title="tabFirmwareFlasher"></a></li>
</ul>
<ul class="mode-connected">
<li class="tab_setup"><a href="#" i18n="tabSetup" class="tabicon ic_setup" i18n_title="tabSetup"></a></li>
<li class="tab_setup_osd"><a href="#" i18n="tabSetupOSD" class="tabicon ic_setup" i18n_title="tabSetupOSD"></a></li>
<li class="tab_ports"><a href="#" i18n="tabPorts" class="tabicon ic_ports" i18n_title="tabPorts"></a></li>
<li class="tab_configuration"><a href="#" i18n="tabConfiguration" class="tabicon ic_config"
i18n_title="tabConfiguration"></a></li>
<li class="tab_power"><a href="#" i18n="tabPower" class="tabicon ic_power"
i18n_title="tabPower"></a></li>
<li class="tab_failsafe"><a href="#" i18n="tabFailsafe" class="tabicon ic_failsafe"
i18n_title="tabFailsafe"></a></li>
<li class="tab_pid_tuning"><a href="#" i18n="tabPidTuning" class="tabicon ic_pid"
i18n_title="tabPidTuning"></a></li>
<li class="tab_receiver"><a href="#" i18n="tabReceiver" class="tabicon ic_rx" i18n_title="tabReceiver"></a></li>
<li class="tab_auxiliary"><a href="#" i18n="tabAuxiliary" class="tabicon ic_modes" i18n_title="tabAuxiliary"></a>
</li>
<li class="tab_adjustments"><a href="#" i18n="tabAdjustments" class="tabicon ic_adjust"
i18n_title="tabAdjustments"></a></li>
<li class="tab_servos"><a href="#" i18n="tabServos" class="tabicon ic_servo" i18n_title="tabServos"></a></li>
<li class="tab_gps"><a href="#" i18n="tabGPS" class="tabicon ic_gps" i18n_title="tabGPS"></a></li>
<li class="tab_motors"><a href="#" i18n="tabMotorTesting" class="tabicon ic_motor" i18n_title="tabMotorTesting"></a>
</li>
<li class="tab_osd"><a href="#" i18n="tabOsd" class="tabicon ic_osd" i18n_title="tabOsd"></a></li>
<li class="tab_transponder"><a href="#" i18n="tabTransponder" class="tabicon ic_transponder"
i18n_title="tabTransponder"></a></li>
<li class="tab_led_strip"><a href="#" i18n="tabLedStrip" class="tabicon ic_led" i18n_title="tabLedStrip"></a>
</li>
<li class="tab_sensors"><a href="#" i18n="tabRawSensorData" class="tabicon ic_sensors"
i18n_title="tabRawSensorData"></a></li>
<li class="tab_logging"><a href="#" i18n="tabLogging" class="tabicon ic_log"
i18n_title="tabLogging"></a></li>
<li class="tab_onboard_logging"><a href="#" i18n="tabOnboardLogging" class="tabicon ic_data"
i18n_title="tabOnboardLogging"></a></li>
<!-- spare icons
<li class=""><a href="#"class="tabicon ic_mission">Mission (spare icon)</a></li>
<li class=""><a href="#"class="tabicon ic_advanced">Advanced (spare icon)</a></li>
<li class=""><a href="#"class="tabicon ic_wizzard">Wizzard (spare icon)</a></li>
</ul>
<ul class="mode-connected mode-connected-cli">
<li class="tab_cli">
<a href="#" i18n="tabCLI" class="tabicon ic_cli" i18n_title="tabCLI"></a>
</li>
</ul>
</div>
<div class="clear-both"></div>
</div>
<div id="content"></div>
<div id="status-bar">
<div>
<span i18n="<API key>"></span> <span class="port_usage_down">D: 0%</span> <span
class="port_usage_up">U: 0%</span>
</div>
<div>
<span i18n="<API key>"></span> <span class="packet-error">0</span>
</div>
<div>
<span i18n="statusbar_i2c_error"></span> <span class="i2c-error">0</span>
</div>
<div>
<span i18n="<API key>"></span> <span class="cycle-time">0</span>
</div>
<div>
<span class="cpu-load"> </span>
</div>
<div class="version">
<!-- configuration version generated here -->
</div>
</div>
<div id="cache">
<div class="data-loading">
<p>Waiting for data ...</p>
</div>
</div>
</div>
<dialog class="<API key>">
<h3 i18n="noticeTitle"></h3>
<div class="content">
<div class="<API key>" style="margin-top: 10px"></div>
</div>
<div class="buttons">
<a href="#" class="<API key> regular-button" i18n="<API key>"></a>
<a href="#" class="<API key> regular-button" i18n="close"></a>
</div>
</dialog>
<dialog class="<API key>">
<h3 i18n="warningTitle"></h3>
<div class="content">
<div class="<API key>" style="margin-top: 10px"></div>
</div>
<div class="buttons">
<a href="#" class="<API key> regular-button" i18n="close"></a>
</div>
</dialog>
<dialog class="dialogError">
<h3 i18n="errorTitle"></h3>
<div class="content">
<div class="dialogError-content" style="margin-top: 10px"></div>
</div>
<div class="buttons">
<a href="#" class="<API key> regular-button" i18n="close"></a>
</div>
</dialog>
</body>
</html> |
import re
import time
import isodate
import requests
from cloudbot import hook
from cloudbot.util import timeformat
from cloudbot.util.formatting import pluralize
from cloudbot.util.colors import parse
youtube_re = re.compile(r'(?:youtube.*?(?:v=|/v/)|youtu\.be/|yooouuutuuube.*?id=)([-_a-zA-Z0-9]+)', re.I)
base_url = 'https:
api_url = base_url + 'videos?part=contentDetails%2C+snippet%2C+statistics&id={}&key={}'
search_api_url = base_url + 'search?part=id&maxResults=1'
playlist_api_url = base_url + 'playlists?part=snippet%2CcontentDetails%2Cstatus'
video_url = "http://youtu.be/%s"
err_no_api = "The YouTube API is off in the Google Developers Console."
time_last_request = time.time()
def <API key>(video_id):
global time_last_request
time_elapsed = time.time() - time_last_request
if time_elapsed > 10:
time_last_request = time.time()
else:
#return "This looks like a YouTube video. However, the YT api have been called too much, I'm sorry I won't be able to fetch details for you."
return None
json = requests.get(api_url.format(video_id, dev_key)).json()
if json.get('error'):
if json['error']['code'] == 403:
return err_no_api
else:
return
data = json['items']
snippet = data[0]['snippet']
statistics = data[0]['statistics']
content_details = data[0]['contentDetails']
out = '\x02{}\x02'.format(snippet['title'])
if not content_details.get('duration'):
return out
length = isodate.parse_duration(content_details['duration'])
out += ' - length \x02{}\x02'.format(timeformat.format_time(int(length.total_seconds()), simple=True))
total_votes = float(statistics['likeCount']) + float(statistics['dislikeCount'])
if total_votes != 0:
# format
likes = pluralize(int(statistics['likeCount']), "like")
dislikes = pluralize(int(statistics['dislikeCount']), "dislike")
percent = 100 * float(statistics['likeCount']) / total_votes
likes = parse("$(dark_green)" + likes + "$(clear)")
dislikes = parse("$(dark_red)" + dislikes + "$(clear)")
out += ' - {}, {} (\x02{:.1f}\x02%)'.format(likes,
dislikes, percent)
if 'viewCount' in statistics:
views = int(statistics['viewCount'])
out += ' - \x02{:,}\x02 view{}'.format(views, "s"[views == 1:])
uploader = snippet['channelTitle']
upload_time = time.strptime(snippet['publishedAt'], "%Y-%m-%dT%H:%M:%S.000Z")
out += ' - \x02{}\x02 on \x02{}\x02'.format(uploader,
time.strftime("%Y.%m.%d", upload_time))
if 'contentRating' in content_details:
out += ' - \x034NSFW\x02'
# return re.sub(
# '[URL]', out)
return out.replace("youtu", "you tu") #nup. No spam please
@hook.on_start()
def load_key(bot):
global dev_key
dev_key = bot.config.get("api_keys", {}).get("google_dev_key", None)
@hook.regex(youtube_re)
def youtube_url(match, event):
if event.chan == "#harmonyhosting": # if the channel is #harmonyhosting
return None # return None, canceling the action
return <API key>(match.group(1))
@hook.command("youtube", "you", "yt", "y")
def youtube(text):
"""youtube <query> -- Returns the first YouTube search result for <query>."""
if not dev_key:
return "This command requires a Google Developers Console API key."
json = requests.get(search_api_url, params={"q": text, "key": dev_key, "type": "video"}).json()
if json.get('error'):
if json['error']['code'] == 403:
return err_no_api
else:
return 'Error performing search.'
if json['pageInfo']['totalResults'] == 0:
return 'No results found.'
video_id = json['items'][0]['id']['videoId']
return <API key>(video_id) + " - " + video_url % video_id
@hook.command("youtime", "ytime")
def youtime(text):
"""youtime <query> -- Gets the total run time of the first YouTube search result for <query>."""
if not dev_key:
return "This command requires a Google Developers Console API key."
json = requests.get(search_api_url, params={"q": text, "key": dev_key, "type": "video"}).json()
if json.get('error'):
if json['error']['code'] == 403:
return err_no_api
else:
return 'Error performing search.'
if json['pageInfo']['totalResults'] == 0:
return 'No results found.'
video_id = json['items'][0]['id']['videoId']
json = requests.get(api_url.format(video_id, dev_key)).json()
if json.get('error'):
return
data = json['items']
snippet = data[0]['snippet']
content_details = data[0]['contentDetails']
statistics = data[0]['statistics']
if not content_details.get('duration'):
return
length = isodate.parse_duration(content_details['duration'])
l_sec = int(length.total_seconds())
views = int(statistics['viewCount'])
total = int(l_sec * views)
length_text = timeformat.format_time(l_sec, simple=True)
total_text = timeformat.format_time(total, accuracy=8)
return 'The video \x02{}\x02 has a length of {} and has been viewed {:,} times for ' \
'a total run time of {}!'.format(snippet['title'], length_text, views,
total_text)
ytpl_re = re.compile(r'(.*:)
@hook.regex(ytpl_re)
def ytplaylist_url(match, event):
global time_last_request
time_elapsed = time.time() - time_last_request
if time_elapsed > 10:
time_last_request = time.time()
else:
#return "This looks like a YouTube Playlist. However, the YT api have been called too much, I'm sorry I won't be able to fetch details for you."
return None
if event.chan == "#harmonyhosting": # if the channel is #harmonyhosting
return None # return None, canceling the action
location = match.group(4).split("=")[-1]
json = requests.get(playlist_api_url, params={"id": location, "key": dev_key}).json()
if json.get('error'):
if json['error']['code'] == 403:
return err_no_api
else:
return 'Error looking up playlist.'
data = json['items']
snippet = data[0]['snippet']
content_details = data[0]['contentDetails']
title = snippet['title']
author = snippet['channelTitle']
num_videos = int(content_details['itemCount'])
count_videos = ' - \x02{:,}\x02 video{}'.format(num_videos, "s"[num_videos == 1:])
return "\x02{}\x02 {} - \x02{}\x02".format(title, count_videos, author) |
#undef <API key>
#ifdef <API key>
#include "../matrix.h"
#include <vector>
#include "../optimization/<API key>.h"
namespace dlib
{
class <API key>
{
/*!
WHAT THIS OBJECT REPRESENTS
This object defines the interface a feature extractor must implement
if it is to be used with the sequence_labeler defined at the bottom
of this file.
The model used by sequence_labeler objects is the following.
Given an input sequence x, predict an output label sequence y
such that:
y == argmax_Y dot(w, PSI(x,Y))
Where w is a parameter vector.
Therefore, a feature extractor defines how the PSI(x,y) feature vector
is calculated. It also defines how many output labels there are as
well as the order of the model.
Finally, note that PSI(x,y) is a sum of feature vectors, each derived
from the entire input sequence x but only part of the label sequence y.
Each of these constituent feature vectors is defined by the get_features()
method of this class.
THREAD SAFETY
Instances of this object should be thread safe, that is, it should
be safe for multiple threads to make concurrent calls to the member
functions of this object.
!*/
public:
// This should be the type used to represent an input sequence. It can be
// anything so long as it has a .size() which returns the length of the sequence.
typedef <API key> sequence_type;
<API key> (
);
/*!
ensures
- this object is properly initialized
!*/
unsigned long num_features (
) const;
/*!
ensures
- returns the dimensionality of the PSI() feature vector.
!*/
unsigned long order(
) const;
/*!
ensures
- This object represents a Markov model on the output labels.
This parameter defines the order of the model. That is, this
value controls how many previous label values get to be taken
into consideration when performing feature extraction for a
particular element of the input sequence. Note that the runtime
of the algorithm is exponential in the order. So don't make order
very large.
!*/
unsigned long num_labels(
) const;
/*!
ensures
- returns the number of possible output labels.
!*/
template <typename EXP>
bool reject_labeling (
const sequence_type& x,
const matrix_exp<EXP>& y,
unsigned long position
) const;
/*!
requires
- EXP::type == unsigned long
(i.e. y contains unsigned longs)
- position < x.size()
- y.size() == min(position, order()) + 1
- is_vector(y) == true
- max(y) < num_labels()
ensures
- for all valid i:
- interprets y(i) as the label corresponding to x[position-i]
- if (the labeling in y for x[position] is always the wrong labeling) then
- returns true
(note that reject_labeling() is just an optional tool to allow you
to overrule the normal labeling algorithm. You don't have to use
it. So if you don't include a reject_labeling() method in your
feature extractor it is the same as including one that always
returns false.)
- else
- returns false
!*/
template <typename feature_setter, typename EXP>
void get_features (
feature_setter& set_feature,
const sequence_type& x,
const matrix_exp<EXP>& y,
unsigned long position
) const;
/*!
requires
- EXP::type == unsigned long
(i.e. y contains unsigned longs)
- reject_labeling(x,y,position) == false
- position < x.size()
- y.size() == min(position, order()) + 1
- is_vector(y) == true
- max(y) < num_labels()
- set_feature is a function object which allows expressions of the form:
- set_features((unsigned long)feature_index, (double)feature_value);
- set_features((unsigned long)feature_index);
ensures
- for all valid i:
- interprets y(i) as the label corresponding to x[position-i]
- This function computes the part of PSI() corresponding to the x[position]
element of the input sequence. Moreover, this part of PSI() is returned as
a sparse vector by invoking set_feature(). For example, to set the feature
with an index of 55 to the value of 1 this method would call:
set_feature(55);
Or equivalently:
set_feature(55,1);
Therefore, the first argument to set_feature is the index of the feature
to be set while the second argument is the value the feature should take.
Additionally, note that calling set_feature() multiple times with the same
feature index does NOT overwrite the old value, it adds to the previous
value. For example, if you call set_feature(55) 3 times then it will
result in feature 55 having a value of 3.
- This function only calls set_feature() with feature_index values < num_features()
!*/
};
void serialize(
const <API key>& item,
std::ostream& out
);
/*!
provides serialization support
!*/
void deserialize(
<API key>& item,
std::istream& in
);
/*!
provides deserialization support
!*/
template <
typename feature_extractor
>
bool <API key> (
const feature_extractor& fe,
const typename feature_extractor::sequence_type& x,
const std::vector<unsigned long>& y
);
/*!
requires
- feature_extractor must be an object that implements an interface compatible
with the <API key> discussed above.
ensures
- if (x.size() != y.size() ||
fe.reject_labeling() rejects any of the labels in y) then
- returns true
- else
- returns false
!*/
template <
typename feature_extractor
>
bool <API key> (
const feature_extractor& fe,
const std::vector<typename feature_extractor::sequence_type>& x,
const std::vector<std::vector<unsigned long> >& y
);
/*!
requires
- feature_extractor must be an object that implements an interface compatible
with the <API key> discussed above.
ensures
- if (x.size() != y.size() ||
<API key>(fe,x[i],y[i]) == true for some i ) then
- returns true
- else
- returns false
!*/
template <
typename feature_extractor
>
class sequence_labeler
{
/*!
REQUIREMENTS ON feature_extractor
It must be an object that implements an interface compatible with
the <API key> discussed above.
WHAT THIS OBJECT REPRESENTS
This object is a tool for doing sequence labeling. In particular,
it is capable of representing sequence labeling models such as
those produced by Hidden Markov SVMs or Conditional Random fields.
See the following papers for an introduction to these techniques:
- Hidden Markov Support Vector Machines by
Y. Altun, I. Tsochantaridis, T. Hofmann
- Shallow Parsing with Conditional Random Fields by
Fei Sha and Fernando Pereira
The model used by this object is the following. Given
an input sequence x, predict an output label sequence y
such that:
y == argmax_Y dot(get_weights(), PSI(x,Y))
Where PSI() is defined by the feature_extractor template
argument.
!*/
public:
typedef typename feature_extractor::sequence_type <API key>;
typedef std::vector<unsigned long> <API key>;
sequence_labeler(
);
/*!
ensures
- #<API key>() == feature_extractor()
(i.e. it will have its default value)
- #get_weights().size() == #<API key>().num_features()
- #get_weights() == 0
!*/
explicit sequence_labeler(
const matrix<double,0,1>& weights
);
/*!
requires
- feature_extractor().num_features() == weights.size()
ensures
- #<API key>() == feature_extractor()
(i.e. it will have its default value)
- #get_weights() == weights
!*/
sequence_labeler(
const matrix<double,0,1>& weights,
const feature_extractor& fe
);
/*!
requires
- fe.num_features() == weights.size()
ensures
- #<API key>() == fe
- #get_weights() == weights
!*/
const feature_extractor& <API key> (
) const;
/*!
ensures
- returns the feature extractor used by this object
!*/
const matrix<double,0,1>& get_weights (
) const;
/*!
ensures
- returns the parameter vector associated with this sequence labeler.
The length of the vector is <API key>().num_features().
!*/
unsigned long num_labels (
) const;
/*!
ensures
- returns <API key>().num_labels()
(i.e. returns the number of possible output labels for each
element of a sequence)
!*/
<API key> operator() (
const <API key>& x
) const;
/*!
requires
- num_labels() > 0
ensures
- returns a vector Y of label values such that:
- Y.size() == x.size()
- for all valid i:
- Y[i] == the predicted label for x[i]
- 0 <= Y[i] < num_labels()
!*/
void label_sequence (
const <API key>& x,
<API key>& y
) const;
/*!
requires
- num_labels() > 0
ensures
- #y == (*this)(x)
(i.e. This is just another interface to the operator() routine
above. This one avoids returning the results by value and therefore
might be a little faster in some cases)
!*/
};
template <
typename feature_extractor
>
void serialize (
const sequence_labeler<feature_extractor>& item,
std::ostream& out
);
/*!
provides serialization support
!*/
template <
typename feature_extractor
>
void deserialize (
sequence_labeler<feature_extractor>& item,
std::istream& in
);
/*!
provides deserialization support
!*/
}
#endif // <API key> |
#ifndef <API key>
#define <API key>
#include <x/mcguffinmapfwd.H>
namespace LIBCXX_NAMESPACE {
#if 0
};
#endif
template<typename K,
typename ref_type,
typename C,
typename Allocator>
class <API key>;
//! Weak mcguffin multi-map container.
//! A \ref mcguffinmap "weak mcguffin map container" that uses
//! a \c std::multimap.
//! \see mcguffinmap
template<typename K, typename ref_type,
typename C=std::less<K>,
typename Allocator=std::allocator
<std::pair<const K, typename <API key><ref_type>
::container_element_t > > >
using mcguffinmultimap
=ref<mcguffinmapObj<K, ref_type,
std::multimap<K, typename
<API key><ref_type>
::container_element_t, C>>,
<API key><K, ref_type, C, Allocator> >;
//! A nullable pointer reference to a \ref mcguffinmultimap "weak mcguffin multimap container".
template<typename K, typename ref_type,
typename C=std::less<K>,
typename Allocator=std::allocator
<std::pair<const K, typename <API key><ref_type>
::container_element_t > > >
using mcguffinmultimapptr
=ptr<mcguffinmapObj<K, ref_type,
std::multimap<K, typename
<API key><ref_type>
::container_element_t, C, Allocator>>,
<API key><K, ref_type, C, Allocator> >;
//! A reference to a constant \ref mcguffinmultimap "weak mcguffin multimap container".
template<typename K, typename ref_type,
typename C=std::less<K>,
typename Allocator=std::allocator
<std::pair<const K, typename <API key><ref_type>
::container_element_t > > >
using <API key>=
const_ref<mcguffinmapObj
<K, ref_type,
std::multimap<K, typename
<API key><ref_type>
::container_element_t, C, Allocator>>,
<API key>
<K, ref_type, C, Allocator> >;
//! A nullable pointer reference to a constant \ref mcguffinmultimap "weak mcguffin multimap container".
template<typename K, typename ref_type,
typename C=std::less<K>,
typename Allocator=std::allocator
<std::pair<const K, typename <API key><ref_type>
::container_element_t > > >
using <API key>=
const_ptr<mcguffinmapObj<K, ref_type,
std::multimap<K, typename
<API key>
<ref_type>
::container_element_t, C,
Allocator>>,
<API key>
<K, ref_type, C, Allocator> >;
#if 0
{
#endif
}
#endif |
#include <sstream>
#include "mex.h"
#include "matrix.h"
#include "icp/icp_base.h"
using namespace icp::math;
double* getFieldSafe(const mxArray* arr, const int index, const char* field_name) {
mxArray* internal_array = mxGetField(arr, index, field_name);
if (internal_array == NULL) {
std::stringstream ss;
ss << field_name << " field is missing";
mexErrMsgIdAndTxt("MATLAB:icp:invalidInput", ss.str().c_str());
}
if (mxGetClassID(internal_array) != mxDOUBLE_CLASS) {
std::stringstream ss;
ss << field_name << " field is not double type";
mexErrMsgIdAndTxt("MATLAB:icp:invalidInput", ss.str().c_str());
}
if (<API key>(internal_array) != 2) {
std::stringstream ss;
ss << field_name << " has an invalid number of dimensions";
mexErrMsgIdAndTxt("MATLAB:icp:invalidInput", ss.str().c_str());
}
return static_cast<double*>(mxGetData(internal_array));
}
double* <API key>(const mxArray* arr, const int index, const char* field_name) {
mxArray* internal_array = mxGetField(arr, index, field_name);
if (internal_array == NULL || mxGetClassID(internal_array) != mxDOUBLE_CLASS) {
return NULL;
}
return static_cast<double*>(mxGetData(internal_array));
}
template <class T>
T* <API key>(const mxArray* arr, const int index,
const char* field_name, const mxClassID classId) {
mxArray* internal_array = mxGetField(arr, index, field_name);
if (internal_array == NULL) {
return NULL;
}
if (mxGetClassID(internal_array) != classId) {
return NULL;
}
return (T*)mxGetData(internal_array);
}
// The gateway function
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
// First check that the inputs and output exist
if (nlhs != 2 && nlhs != 1) {
mexErrMsgIdAndTxt("MATLAB:icp:invalidNumOutput",
"You must define one or two return values!");
}
if (nrhs != 1) {
mexErrMsgIdAndTxt("MATLAB:icp:invalidNumInput",
"Invalid number of inputs");
}
if (!mxIsStruct(prhs[0])) {
mexErrMsgIdAndTxt("MATLAB:icp:invalidInput",
"Invalid input type (struct expected)");
}
// Get the fields
double* p_num_iterations = getFieldSafe(prhs[0], 0, "num_iterations");
double* p_pc1 = getFieldSafe(prhs[0], 0, "pc1");
double* p_m_pc2_initial = getFieldSafe(prhs[0], 0, "m_pc2_initial");
double* p_pc2 = getFieldSafe(prhs[0], 0, "pc2");
double* p_min_distance_sq = <API key>(prhs[0], 0, "min_distance_sq");
double* p_max_distance_sq = <API key>(prhs[0], 0, "max_distance_sq");
double* <API key> = <API key>(prhs[0], 0,
"<API key>");
double* p_npc1 = <API key>(prhs[0], 0, "npc1");
double* p_npc2 = <API key>(prhs[0], 0, "npc2");
if ((p_npc1 == NULL) != (p_npc2 == NULL)) {
mexErrMsgIdAndTxt("MATLAB:icp:invalidInput",
"either define npc1 AND npc2 or don't define both");
}
double* p_method = <API key>(prhs[0], 0, "method");
double* p_match_scale = <API key>(prhs[0], 0, "match_scale");
// Check the dimension and sizing of pc1, pc2
mxArray* arr;
arr = mxGetField(prhs[0], 0, "pc1");
uint32_t num_points_pc1 = static_cast<uint32_t>(mxGetN(arr));
uint32_t dim_pc1 = static_cast<uint32_t>(mxGetM(arr));
arr = mxGetField(prhs[0], 0, "pc2");
uint32_t num_points_pc2 = static_cast<uint32_t>(mxGetN(arr));
uint32_t dim_pc2 = static_cast<uint32_t>(mxGetM(arr));
if (dim_pc1 != 3 || dim_pc2 != 3) {
mexErrMsgIdAndTxt("MATLAB:icp:invalidInput",
"pc1 or pc2 dimension is not 3 (number of rows should be 3)");
}
// Check the dimension and sizing of npc1, npc2
if (p_npc1 != NULL) {
arr = mxGetField(prhs[0], 0, "npc1");
uint32_t num_points = static_cast<uint32_t>(mxGetN(arr));
uint32_t dim = static_cast<uint32_t>(mxGetM(arr));
if (num_points != num_points_pc1 || dim != 3) {
mexErrMsgIdAndTxt("MATLAB:icp:invalidInput",
"npc1 is not the correct size!");
}
}
if (p_npc2 != NULL) {
arr = mxGetField(prhs[0], 0, "npc2");
uint32_t num_points = static_cast<uint32_t>(mxGetN(arr));
uint32_t dim = static_cast<uint32_t>(mxGetM(arr));
if (num_points != num_points_pc2 || dim != 3) {
mexErrMsgIdAndTxt("MATLAB:icp:invalidInput",
"npc2 is not the correct size!");
}
}
ICP<double>* p_icp = new ICP<double>();
p_icp->num_iterations = static_cast<uint32_t>(*p_num_iterations);
if (p_min_distance_sq != NULL) {
p_icp->min_distance_sq = static_cast<float>(*p_min_distance_sq);
}
if (p_max_distance_sq != NULL) {
p_icp->max_distance_sq = static_cast<float>(*p_max_distance_sq);
}
if (<API key> != NULL) {
p_icp-><API key> = static_cast<float>(*<API key>);
}
p_icp->verbose = false;
int method = (int)ICPMethod::BFGS_ICP;
if (p_method != NULL) {
method = static_cast<int>(*p_method);
}
if (method < 0 || method >= (int)ICPMethod::NUM_METHODS) {
mexErrMsgIdAndTxt("MATLAB:icp:invalidInput",
"method options are 0 - SVD, 1 - BFGS, 2 - PSO, 3 - Umeyama!");
}
p_icp->icp_method = (icp::math::ICPMethod)method;
p_icp->match_scale = true;
if (p_match_scale != NULL) {
p_icp->match_scale = *p_match_scale != 0;
}
Mat4x4<double> m_pc2_initial;
Mat4x4<double> m_pc2_final;
memcpy(&m_pc2_final[0], p_m_pc2_initial, sizeof(m_pc2_final[0]) * 4 * 4);
double pos_error = p_icp->match(m_pc2_final, p_pc1, num_points_pc1, p_pc2,
num_points_pc2, m_pc2_initial, p_npc1, p_npc2);
delete p_icp;
// Allocate the output array and copy the final matrix to the output
plhs[0] = <API key>(4, 4, mxREAL);
double* m_pc2_return = mxGetPr(plhs[0]);
for (uint32_t i = 0; i < 16; i++) {
m_pc2_return[i] = m_pc2_final[i];
}
if (nlhs == 2) {
plhs[1] = <API key>(1, 1, mxREAL);
*mxGetPr(plhs[1]) = pos_error;
}
} |
#include "../basecode/header.h"
#include "../randnum/randnum.h"
#include "RandSpike.h"
// MsgSrc definitions
static SrcFinfo1< double > *spikeOut()
{
static SrcFinfo1< double > spikeOut( "spikeOut",
"Sends out a trigger for an event.");
return &spikeOut;
}
const Cinfo* RandSpike::initCinfo()
{
// Shared message definitions
static DestFinfo process( "process",
"Handles process call",
new ProcOpFunc< RandSpike >( &RandSpike::process ) );
static DestFinfo reinit( "reinit",
"Handles reinit call",
new ProcOpFunc< RandSpike >( &RandSpike::reinit ) );
static Finfo* processShared[] =
{
&process, &reinit
};
static SharedFinfo proc( "proc",
"Shared message to receive Process message from scheduler",
processShared, sizeof( processShared ) / sizeof( Finfo* ) );
// Dest Finfos.
// Value Finfos.
static ValueFinfo< RandSpike, double > rate( "rate",
"Specifies rate for random spike train. Note that this is"
"probabilistic, so the instantaneous rate may differ. "
"If the rate is assigned be message and it varies slowly then "
"the average firing rate will approach the specified rate",
&RandSpike::setRate,
&RandSpike::getRate
);
static ValueFinfo< RandSpike, double > refractT( "refractT",
"Refractory Time.",
&RandSpike::setRefractT,
&RandSpike::getRefractT
);
static ValueFinfo< RandSpike, double > lastEventT( "lastEventT",
"Time of last event. Set this if you want to phase-shift periodic activity.",
&RandSpike::setLastEvent,
&RandSpike::getLastEvent
);
static ValueFinfo< RandSpike, double > absRefract( "abs_refract",
"Absolute refractory time. Synonym for refractT.",
&RandSpike::setRefractT,
&RandSpike::getRefractT
);
static ValueFinfo< RandSpike, bool > doPeriodic( "doPeriodic",
"Flag: when false, do Poisson process with specified mean rate.\n"
"When true, fire periodically at specified rate.\n"
"Defaults to false. Note that refractory time overrides this: "
"Rate cannot exceed 1/refractT.",
&RandSpike::setDoPeriodic,
&RandSpike::getDoPeriodic
);
static ReadOnlyValueFinfo< RandSpike, bool > hasFired( "hasFired",
"True if RandSpike has just fired",
&RandSpike::getFired
);
static Finfo* spikeGenFinfos[] =
{
spikeOut(), // SrcFinfo
&proc, // Shared
&rate, // Value
&refractT, // Value
&lastEventT, // Value
&absRefract, // Value
&doPeriodic, // Value
&hasFired, // ReadOnlyValue
};
static string doc[] =
{
"Name", "RandSpike",
"Author", "Upi Bhalla",
"Description", "RandSpike object, generates random or regular "
"spikes at "
"specified mean rate. Based closely on GENESIS randspike. "
};
static Dinfo< RandSpike > dinfo;
static Cinfo spikeGenCinfo(
"RandSpike",
Neutral::initCinfo(),
spikeGenFinfos, sizeof( spikeGenFinfos ) / sizeof( Finfo* ),
&dinfo,
doc,
sizeof(doc)/sizeof(string)
);
return &spikeGenCinfo;
}
static const Cinfo* spikeGenCinfo = RandSpike::initCinfo();
RandSpike::RandSpike()
:
rate_( 0.0 ),
realRate_( 0.0 ),
refractT_(0.0),
lastEvent_(0.0),
threshold_(0.0),
fired_( false ),
doPeriodic_( false )
{
;
}
// Here we put the RandSpike class functions.
// Value Field access function definitions.
void RandSpike::setRate( double rate )
{
if ( rate < 0.0 )
{
cout <<"Warning: RandSpike::setRate: Rate must be >= 0. Using 0.\n";
rate = 0.0;
}
rate_ = rate;
double prob = 1.0 - rate * refractT_;
if ( prob <= 0.0 )
{
cout << "Warning: RandSpike::setRate: Rate is too high compared to refractory time\n";
realRate_ = rate_;
}
else
{
realRate_ = rate_ / prob;
}
}
double RandSpike::getRate() const
{
return rate_;
}
void RandSpike::setRefractT( double val )
{
refractT_ = val;
}
double RandSpike::getRefractT() const
{
return refractT_;
}
void RandSpike::setLastEvent( double val )
{
lastEvent_ = val;
}
double RandSpike::getLastEvent() const
{
return lastEvent_;
}
bool RandSpike::getFired() const
{
return fired_;
}
void RandSpike::setDoPeriodic( bool val )
{
doPeriodic_ = val;
}
bool RandSpike::getDoPeriodic() const
{
return doPeriodic_;
}
// RandSpike::Dest function definitions.
void RandSpike::process( const Eref& e, ProcPtr p )
{
if ( refractT_ > p->currTime - lastEvent_ || rate_ <= 0.0 )
return;
fired_ = false;
if (doPeriodic_)
{
if ( (p->currTime - lastEvent_) > 1.0/rate_ )
{
lastEvent_ = p->currTime;
spikeOut()->send( e, p->currTime );
fired_ = true;
}
}
else
{
double prob = realRate_ * p->dt;
if ( prob >= 1.0 || prob >= moose::mtrand() )
{
lastEvent_ = p->currTime;
spikeOut()->send( e, p->currTime );
fired_ = true;
}
}
}
// Set it so that first spike is allowed.
void RandSpike::reinit( const Eref& e, ProcPtr p )
{
if ( rate_ <= 0.0 )
{
lastEvent_ = 0.0;
realRate_ = 0.0;
}
else
{
double prob = moose::mtrand();
double m = 1.0 / rate_;
lastEvent_ = m * log( prob );
}
} |
using System;
using System.Collections;
namespace Server.Spells.First
{
public class ReactiveArmorSpell : MagerySpell
{
private static readonly SpellInfo m_Info = new SpellInfo(
"Reactive Armor", "Flam Sanct",
236,
9011,
Reagent.Garlic,
Reagent.SpidersSilk,
Reagent.SulfurousAsh);
private static readonly Hashtable m_Table = new Hashtable();
public ReactiveArmorSpell(Mobile caster, Item scroll)
: base(caster, scroll, m_Info)
{
}
public override SpellCircle Circle
{
get
{
return SpellCircle.First;
}
}
public static void EndArmor(Mobile m)
{
if (m_Table.Contains(m))
{
ResistanceMod[] mods = (ResistanceMod[])m_Table[m];
if (mods != null)
{
for (int i = 0; i < mods.Length; ++i)
m.RemoveResistanceMod(mods[i]);
}
m_Table.Remove(m);
BuffInfo.RemoveBuff(m, BuffIcon.ReactiveArmor);
}
}
public override bool CheckCast()
{
if (Core.AOS)
return true;
if (this.Caster.MeleeDamageAbsorb > 0)
{
this.Caster.<API key>(1005559); // This spell is already in effect.
return false;
}
else if (!this.Caster.CanBeginAction(typeof(DefensiveSpell)))
{
this.Caster.<API key>(1005385); // The spell will not adhere to you at this time.
return false;
}
return true;
}
public override void OnCast()
{
if (Core.AOS)
{
Mobile targ = this.Caster;
if (this.CheckBSequence(targ))
{
ResistanceMod[] mods = (ResistanceMod[])m_Table[targ];
if (mods == null)
{
targ.PlaySound(0x1E9);
targ.FixedParticles(0x376A, 9, 32, 5008, EffectLayer.Waist);
mods = new ResistanceMod[5]
{
new ResistanceMod(ResistanceType.Physical, 15 + (int)(targ.Skills[SkillName.Inscribe].Value / 20)),
new ResistanceMod(ResistanceType.Fire, -5),
new ResistanceMod(ResistanceType.Cold, -5),
new ResistanceMod(ResistanceType.Poison, -5),
new ResistanceMod(ResistanceType.Energy, -5)
};
m_Table[targ] = mods;
for (int i = 0; i < mods.Length; ++i)
targ.AddResistanceMod(mods[i]);
int physresist = 15 + (int)(targ.Skills[SkillName.Inscribe].Value / 20);
string args = String.Format("{0}\t{1}\t{2}\t{3}\t{4}", physresist, 5, 5, 5, 5);
BuffInfo.AddBuff(this.Caster, new BuffInfo(BuffIcon.ReactiveArmor, 1075812, 1075813, args.ToString()));
}
else
{
targ.PlaySound(0x1ED);
targ.FixedParticles(0x376A, 9, 32, 5008, EffectLayer.Waist);
m_Table.Remove(targ);
for (int i = 0; i < mods.Length; ++i)
targ.RemoveResistanceMod(mods[i]);
BuffInfo.RemoveBuff(this.Caster, BuffIcon.ReactiveArmor);
}
}
this.FinishSequence();
}
else
{
if (this.Caster.MeleeDamageAbsorb > 0)
{
this.Caster.<API key>(1005559); // This spell is already in effect.
}
else if (!this.Caster.CanBeginAction(typeof(DefensiveSpell)))
{
this.Caster.<API key>(1005385); // The spell will not adhere to you at this time.
}
else if (this.CheckSequence())
{
if (this.Caster.BeginAction(typeof(DefensiveSpell)))
{
int value = (int)(this.Caster.Skills[SkillName.Magery].Value + this.Caster.Skills[SkillName.Meditation].Value + this.Caster.Skills[SkillName.Inscribe].Value);
value /= 3;
if (value < 0)
value = 1;
else if (value > 75)
value = 75;
this.Caster.MeleeDamageAbsorb = value;
this.Caster.FixedParticles(0x376A, 9, 32, 5008, EffectLayer.Waist);
this.Caster.PlaySound(0x1F2);
}
else
{
this.Caster.<API key>(1005385); // The spell will not adhere to you at this time.
}
}
this.FinishSequence();
}
}
}
} |
-- Variable TextID Description text
-- General Texts
<API key> = 6381; -- You cannot obtain the item <item>. Come back again after sorting your inventory.
<API key> = 6385; -- You cannot obtain the #. Try trading again after sorting your inventory.
ITEM_OBTAINED = 6387; -- Obtained: <item>.
GIL_OBTAINED = 6388; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6390; -- Obtained key item: <keyitem>.
ITEMS_OBTAINED = 7477; -- You obtain
<API key> = 7269; -- You can't fish here.
-- Other dialog
<API key> = 7369; -- There is nothing out of the ordinary here.
-- Logging
<API key> = 7386; -- Logging is possible here if you have
-- Shop Texts
<API key> = 7418; -- I'm selling goods direct from the Carpenters' Guild.
-- conquest Base
CONQUEST_BASE = 7048; -- Tallying conquest results... |
package smf;
import com.alee.laf.WebLookAndFeel;
import com.alee.extended.filechooser.WebDirectoryChooser;
import com.alee.utils.swing.DialogOptions;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
*
* @author Imron02
*/
public class SMF extends JFrame {
/**
* @param args the command line arguments
*/
static String path;
public SMF() {
initUI();
}
private void initUI() {
initLookAndFeel();
createMenuBar();
createForm();
setTitle("Show My Files");
setSize(300, 160);
ImageIcon frameIcon = new ImageIcon(this.getClass().getResource("/images/app.png"));
setIconImage(frameIcon.getImage());
setResizable(false);
<API key>(null);
<API key>(EXIT_ON_CLOSE);
}
private static void initLookAndFeel() {
WebLookAndFeel.install();
// try {
// UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
// catch (<API key> e) {
// System.err.println("Did you include the L&F library in the class path?");
// System.err.println("Using the default look and feel.");
// catch (<API key> e) {
// System.err.println("Can't use the specified look and feel on this platform.");
// System.err.println("Using the default look and feel.");
// catch (Exception e) {
// System.err.println("Couldn't get specified look and feel for some reason.");
// System.err.println("Using the default look and feel.");
// e.printStackTrace();
}
private void createMenuBar() {
JMenuBar menuBar = new JMenuBar();
ImageIcon exitIcon = new ImageIcon(this.getClass().getResource("/images/exit.png"));
ImageIcon aboutIcon = new ImageIcon(this.getClass().getResource("/images/about.png"));
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic(KeyEvent.VK_H);
JMenuItem exitMenuItem = new JMenuItem("Exit", exitIcon);
exitMenuItem.setMnemonic(KeyEvent.VK_E);
exitMenuItem.setToolTipText("Exit Application");
exitMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JMenuItem helpMenuItem = new JMenuItem("About", aboutIcon);
helpMenuItem.setMnemonic(KeyEvent.VK_A);
helpMenuItem.setToolTipText("Abotu application");
helpMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(SMF.this,
"This application is for unhide file and folder"
+ " after malware virus attack",
"Error Message",
JOptionPane.INFORMATION_MESSAGE);
}
});
fileMenu.add(exitMenuItem);
helpMenu.add(helpMenuItem);
menuBar.add(fileMenu);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
}
private void createForm() {
JLabel driveLabel = new JLabel("Drive Letter:");
driveLabel.setBounds(10, 10, 80, 25);
JTextField driveTextField = new JTextField();
driveTextField.setBounds(85, 10, 160, 25);
driveTextField.setEditable(false);
JButton chooseButton = new JButton("...");
chooseButton.setBounds(250, 10, 30, 25);
JButton okButton = new JButton("Ok");
okButton.setBounds(130, 70, 70, 30);
JButton quitButton = new JButton("Quit");
quitButton.setBounds(210, 70, 70, 30);
JPanel panel = new JPanel();
panel.setLayout(null);
panel.add(driveLabel);
panel.add(driveTextField);
panel.add(chooseButton);
panel.add(okButton);
panel.add(quitButton);
add(panel);
chooseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
WebDirectoryChooser chooser = new WebDirectoryChooser(SMF.this,
"Select target directory");
chooser.setVisible(true);
if (chooser.getResult() == DialogOptions.OK_OPTION) {
final File file = chooser.<API key>();
path = file.toString();
driveTextField.setText(path);
}
// JFileChooser chooser = new JFileChooser();
// chooser.<API key>(JFileChooser.DIRECTORIES_ONLY);
// chooser.setCurrentDirectory(chooser.getFileSystemView()
// .getParentDirectory(new File("C:\\")));
// chooser.setDialogTitle("Select target directory");
// int returnVal = chooser.showOpenDialog(SMF.this);
// if (returnVal == JFileChooser.APPROVE_OPTION) {
// path = chooser.getSelectedFile().getAbsolutePath();
// driveTextField.setText(path);
}
});
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(path == null || path.isEmpty()) {
JOptionPane.showMessageDialog(SMF.this,
"Please choose drive/directory.",
"Error Message",
JOptionPane.ERROR_MESSAGE);
} else {
System.out.println("Success");
fixDrive(path);
}
}
});
quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
private void fixDrive(String param) {
String command = "attrib -s -h -a /s /d "+param+"\\*.*";
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO code application logic here
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new SMF().setVisible(true);
}
});
}
} |
\input{res/chapter/design/progettazione}
\newpage
\input{res/chapter/design/accessibilita}
\newpage
\input{res/chapter/design/usabilita}
\newpage
\input{res/chapter/design/perl}
\newpage
\input{res/chapter/design/javascript}
\newpage
\input{res/chapter/design/html}
\newpage
\input{res/chapter/design/css}
\newpage
\input{res/chapter/design/xml} |
#! /usr/bin/env python
# python script to generate a valid stepfile for WRF cycling
import sys
import pandas
import calendar
filename = 'stepfile' # default filename
lleap = True # allow leap days (not used in some GCM calendars)
lecho = False
lperiod = False
dateargs = [] # list of date arguments passed to date_range
for arg in sys.argv[1:]:
if arg[:11] == '--interval=':
freq = arg[11:].lower() # remains a string and is interpreted by date_range
elif arg[:8] == '--steps=':
lperiod = True; periods = int(arg[8:]) + 1 # each step is bounded by two timestamps
elif arg == '-l' or arg == '--noleap':
lleap = False # omit leap days to accomodate some GCM calendars
elif arg == '-e' or arg == '--echo':
lecho = True
elif arg == '-h' or arg == '--help':
print('')
print("Usage: "+sys.argv[0]+" [-e] [-h] [--interval=interval] [--steps=steps] begin-date [end-date]")
print(" Interval, begin-date and end-date or steps must be specified.")
print("")
print(" --interval= step spacing / interval (D=days, W=weeks, M=month)")
print(" --steps= number of steps in stepfile")
print(" -l | --noleap omit leap days (to accomodate some GCM calendars)")
print(" -e | --echo print steps to stdout instead of writing to stepfile")
print(" -h | --help print this message")
print('')
sys.exit(1)
else:
dateargs.append(arg)
# output patterns
lmonthly = False
dateform = '%Y-%m-%d_%H:%M:%S'
# N.B.: because pandas date_range always anchors intervals at the end of the month, we have to subtract one
# day and add it again later, in order to re-anchor at the first of the month
stepform = '%Y-%m-%d'
offset = pandas.DateOffset() # no offset
if 'w' in freq:
oo = 1 if '-sun' in freq else 0
offset = pandas.DateOffset(days=pandas.to_datetime(dateargs[0]).dayofweek + oo)
elif 'm' in freq:
lmonthly = True
stepform = '%Y-%m'
offset = pandas.DateOffset(days=pandas.to_datetime(dateargs[0]).day)
#print dateargs
begindate = pandas.to_datetime(dateargs[0]) - offset
# check input and generate datelist
if lperiod:
if len(dateargs) != 1: raise ValueError('Can only specify begin-date, if the number of periods is given.')
datelist = pandas.date_range(begindate, periods=periods, freq=freq) # generate datelist
else:
if len(dateargs) != 2: raise ValueError('Specify begin-date and end-date, if no number of periods is given.')
enddate = pandas.to_datetime(dateargs[1]) - offset
datelist = pandas.date_range(begindate, enddate, freq=freq) # generate datelist
# open file, if not writing to stdout
if not lecho: stepfile = open(filename, mode='w')
# iterate over dates (skip first)
lastdate = datelist[0] + offset # first element
llastleap = False
for date in datelist[1:]:
lcurrleap = False
currentdate = date + offset
# N.B.: offset is not the interval/frequency; it is an offset at the beginning of the month or week
if lmonthly:
mon = date.month +1
if mon == 2: maxdays = 29 if calendar.isleap(date.year) else 28
elif mon in [4, 6, 9, 11]: maxdays = 30
else: maxdays = 31
if currentdate > date + pandas.DateOffset(days=maxdays):
currentdate = date + pandas.DateOffset(days=maxdays)
# handle calendars without leap days (turn Feb. 29th into Mar. 1st)
if not lleap and calendar.isleap(currentdate.year) and ( currentdate.month==2 and currentdate.day==29 ):
lcurrleap = True
currentdate += pandas.DateOffset(days=1) # move one day ahead
# generate line for last step
# print currentdate.month,currentdate.day
if lleap or not (freq.lower()=='1d' and llastleap):
# skip if this is daily output, a leap day, and a non-leap-year calendar...
stepline = "{0:s} '{1:s}' '{2:s}'\n".format(lastdate.strftime(stepform),lastdate.strftime(dateform),
currentdate.strftime(dateform))
# write to appropriate output
if lecho: sys.stdout.write(stepline)
else: stepfile.write(stepline)
# remember last step
lastdate = currentdate
llastleap = lcurrleap
# close file
if not lecho: stepfile.close() |
<?php
declare(strict_types=1);
namespace AOE\Crawler\Tests\Acceptance\Support\Helper;
use AcceptanceTester;
use Facebook\WebDriver\Remote\RemoteWebElement;
use Facebook\WebDriver\WebDriverBy;
/**
* Helper class to interact with the page tree
*/
abstract class AbstractPageTree
{
// Selectors
public static $<API key> = '#typo3-pagetree';
public static $pageTreeSelector = '#<API key>';
public static $treeItemSelector = 'g.nodes > .node';
public static $<API key> = 'text.node-name';
/**
* @var AcceptanceTester
*/
protected $tester;
/**
* Open the given hierarchical path in the pagetree and click the last page.
*
* Example to open "styleguide -> elements basic" page:
* [
* 'styleguide TCA demo',
* 'elements basic',
* ]
*
* @param string[] $path
*/
public function openPath(array $path): void
{
$context = $this->getPageTreeElement();
foreach ($path as $pageName) {
$context = $this-><API key>($pageName, $context);
}
$context->findElement(WebDriverBy::cssSelector(self::$<API key>))->click();
}
/**
* Check if the pagetree is visible end return the web element object
*
* @return RemoteWebElement
*/
public function getPageTreeElement()
{
$I = $this->tester;
$I->switchToIFrame();
return $I->executeInSelenium(function (\Facebook\WebDriver\Remote\RemoteWebDriver $webdriver) {
return $webdriver->findElement(WebDriverBy::cssSelector(self::$pageTreeSelector));
});
}
/**
* Search for an element with the given link text in the provided context.
*
* @return RemoteWebElement
*/
protected function <API key>(string $nodeText, RemoteWebElement $context)
{
$I = $this->tester;
$I->see($nodeText, self::$treeItemSelector);
/** @var RemoteWebElement $context */
$context = $I->executeInSelenium(function () use ($nodeText, $context
) { |
<?php
namespace Modules\Linkus\Controllers\Admin;
use Ilch\Validation;
class Settings extends \Ilch\Controller\Admin
{
public function init()
{
$items = [
[
'name' => 'manage',
'active' => false,
'icon' => 'fa fa-th-list',
'url' => $this->getLayout()->getUrl(['controller' => 'index', 'action' => 'index'])
],
[
'name' => 'settings',
'active' => true,
'icon' => 'fa fa-cogs',
'url' => $this->getLayout()->getUrl(['controller' => 'settings', 'action' => 'index'])
]
];
$this->getLayout()->addMenu
(
'menuLinkus',
$items
);
}
public function indexAction()
{
$this->getLayout()->getAdminHmenu()
->add($this->getTranslator()->trans('menuLinkus'), ['controller' => 'index', 'action' => 'index'])
->add($this->getTranslator()->trans('settings'), ['action' => 'index']);
if ($this->getRequest()->isPost()) {
Validation::<API key>([
'showHtml' => 'htmlForWebsite',
'showBBCode' => 'bbcodeForForum',
]);
$validation = Validation::create($this->getRequest()->getPost(), [
'showHtml' => 'required|numeric|integer|min:0|max:1',
'showBBCode' => 'required|numeric|integer|min:0|max:1',
]);
if ($validation->isValid()) {
$this->getConfig()->set('linkus_html', $this->getRequest()->getPost('showHtml'));
$this->getConfig()->set('linkus_bbcode', $this->getRequest()->getPost('showBBCode'));
$this->addMessage('saveSuccess');
} else {
$this->addMessage($validation->getErrorBag()->getErrorMessages(), 'danger', true);
$this->redirect()
->withInput()
->withErrors($validation->getErrorBag())
->to(['action' => 'index']);
}
}
$this->getView()->set('linkus_html', $this->getConfig()->get('linkus_html'));
$this->getView()->set('linkus_bbcode', $this->getConfig()->get('linkus_bbcode'));
}
} |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
module Wiretap.Analysis.Lock
( locksetSimulation
, lockset
, lockMap
, nonreentrant
, lockOf
, LockMap
, sharedLocks
)
where
import Wiretap.Data.Event
import Wiretap.Data.History
-- import Wiretap.Utils
-- import Wiretap.Graph
-- import Debug.Trace
import qualified Data.List as L
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.Unique
-- import qualified Data.Set as S
-- import Debug.Trace
-- import Control.Lens (over, _1)
-- import Control.Monad
import Control.Monad.State.Strict
-- import Control.Monad.Trans.Either
-- import Debug.Trace
type LockMap = UniqueMap (M.Map Ref UE)
-- | Lockset simulation, walks over a history and calculates the lockset
-- | of each event. The function produces a tuple of an assignment a lockset
-- | to every event, and the hold lockset of every thread.
-- | Notice this function only works if locks are local, and if there no re-entrant
-- | lock.
locksetSimulation :: PartialHistory h
=> M.Map Thread [(Ref, UE)]
-> h
-> (LockMap, M.Map Thread [(Ref, UE)])
locksetSimulation !s history =
(fromUniques $ map (fmap toLockMap) lockstacks, state')
where
(lockstacks, !state') = runState (simulateM step history) s
filterFirst p = L.deleteBy (const p) undefined
step u@(Unique _ e) =
case operation e of
Acquire l ->
updateAndGet t ((l,u):)
Release l ->
updateAndGet t . filterFirst $ (l ==) . fst
_ ->
gets $ fromMaybe [] . M.lookup t
where t = thread e
updateAndGet
:: Thread
-> ([(Ref, UE)] -> [(Ref, UE)])
-> State (M.Map Thread [(Ref, UE)]) [(Ref,UE)]
updateAndGet t f = do
m <- get
let l = fromMaybe [] $ M.lookup t m
let rs = f l
put $! M.insert t rs m
return l
-- | toLockMap converges the lock stack to a map where all locks reference
-- | points to the first event to grab it.
toLockMap :: [(Ref, UE)] -> M.Map Ref UE
toLockMap =
M.fromList
sharedLocks :: LockMap -> UE -> UE -> M.Map Ref (UE, UE)
sharedLocks u a b =
M.intersectionWith (,) (u ! a) (u ! b)
lockMap
:: PartialHistory h
=> h
-> LockMap
lockMap =
fst . locksetSimulation M.empty
lockset :: PartialHistory h
=> h
-> [(Event, (M.Map Ref UE))]
lockset h =
map (\e -> (normal e, locks ! e)) $ enumerate h
where locks = lockMap h
-- A non reentrant lock has does not have it's own lock in
-- the its own lockset.
nonreentrant :: LockMap -> UE -> Ref -> Bool
nonreentrant lm e l =
M.notMember l (lm ! e)
lockOf :: UE -> Maybe Ref
lockOf (Unique _ e) =
case operation e of
Acquire l -> Just l
Request l -> Just l
Release l -> Just l
_ -> Nothing |
class <API key> < ActiveRecord::Migration
def change
create_table :canonical_vehicles do |t|
t.string :make
t.string :model
t.integer :year
t.timestamps null: false
end
end
end |
package com.mucommander.ui.list;
import com.mucommander.commons.collections.AlteredVector;
import com.mucommander.text.Translator;
import com.mucommander.ui.button.ArrowButton;
import javax.swing.*;
import java.awt.*;
/**
* SortableListPanel is a JPanel which contains a scrollable {@link DynamicList} in the center and two buttons
* 'Move up' and 'Move down' buttons on the right side of the list which allow to move the items up and down and
* easily reorder them within the list.
*
* @author Maxence Bernard
*/
public class SortableListPanel<E> extends JPanel {
private DynamicList<E> dynamicList;
/**
* Creates a new SortableListPanel with a {@link DynamicList} that uses the provided items {@link AlteredVector}.
*
* @param items the items Vector used by DynamicList
*/
public SortableListPanel(AlteredVector<E> items) {
super(new BorderLayout());
this.dynamicList = new DynamicList<>(items);
// Allow vertical scrolling in bookmarks list
add(new JScrollPane(dynamicList), BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(new GridLayout(2, 1));
// create 'Move item up' button
JButton moveButton = new ArrowButton(dynamicList.getMoveUpAction(), ArrowButton.UP_DIRECTION);
// Constrain the button's size which by default is huge under Windows/Java 1.5
moveButton.setPreferredSize(new Dimension(19, 0));
// Make the button non focusable so that it doesn't steal focus from the list
moveButton.setFocusable(false);
moveButton.setToolTipText(Translator.get("sortable_list.move_up"));
buttonPanel.add(moveButton);
// create 'Move item down' button
moveButton = new ArrowButton(dynamicList.getMoveDownAction(), ArrowButton.DOWN_DIRECTION);
// Constrain the button's size which by default is huge under Windows/Java 1.5
moveButton.setPreferredSize(new Dimension(19, 0));
// Make the button non focusable so that it doesn't steal focus from the list
moveButton.setFocusable(false);
moveButton.setToolTipText(Translator.get("sortable_list.move_down"));
buttonPanel.add(moveButton);
add(buttonPanel, BorderLayout.EAST);
}
/**
* Returns the {@link DynamicList} used by this SortableListPanel.
*
* @return the {@link DynamicList} used by this SortableListPanel
*/
public DynamicList<E> getDynamicList() {
return dynamicList;
}
} |
# This file is part of PySCAP.
# PySCAP is free software: you can redistribute it and/or modify
# (at your option) any later version.
# PySCAP is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
from scap.Model import Model
import logging
logger = logging.getLogger(__name__)
class <API key>(Model):
MODEL_MAP = {
'tag_name': 'GeneralSuffix',
'attributes': {
'Type': {},
'Code': {},
'*': {},
}
} |
#!/usr/bin/python
# aes.py: implements AES - Advanced Encryption Standard
import math
import os
def <API key>(s):
"""return s padded to a multiple of 16-bytes by PKCS7 padding"""
numpads = 16 - (len(s) % 16)
return s + numpads * chr(numpads)
def strip_PKCS7_padding(s):
"""return s stripped of PKCS7 padding"""
if len(s) % 16 or not s:
raise ValueError("String of len %d can't be PCKS7-padded" % len(s))
numpads = ord(s[-1])
if numpads > 16:
raise ValueError("String ending with %r can't be PCKS7-padded" % s[-1])
if not all(numpads == x for x in map(ord, s[-numpads:-1])):
raise ValueError("Invalid PKCS7 padding")
return s[:-numpads]
class AES(object):
# valid key sizes
keySize = dict(SIZE_128=16, SIZE_192=24, SIZE_256=32)
# Rijndael S-box
sbox = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67,
0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59,
0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7,
0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1,
0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05,
0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83,
0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29,
0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa,
0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c,
0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc,
0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19,
0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee,
0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49,
0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4,
0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6,
0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70,
0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9,
0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e,
0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1,
0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0,
0x54, 0xbb, 0x16]
# Rijndael Inverted S-box
rsbox = [0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3,
0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f,
0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54,
0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b,
0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24,
0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8,
0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d,
0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda,
0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab,
0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3,
0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1,
0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41,
0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6,
0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9,
0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d,
0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0,
0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07,
0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60,
0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f,
0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5,
0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b,
0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55,
0x21, 0x0c, 0x7d]
def getSBoxValue(self, num):
"""Retrieves a given S-Box Value"""
return self.sbox[num]
def getSBoxInvert(self, num):
"""Retrieves a given Inverted S-Box Value"""
return self.rsbox[num]
@staticmethod
def rotate(word):
""" Rijndael's key schedule rotate operation.
Rotate a word eight bits to the left: eg, rotate(1d2c3a4f) == 2c3a4f1d
Word is an char list of size 4 (32 bits overall).
"""
return word[1:] + word[:1]
# Rijndael Rcon
Rcon = [0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,
0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97,
0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72,
0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66,
0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04,
0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d,
0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,
0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61,
0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40,
0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc,
0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5,
0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a,
0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d,
0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35,
0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4,
0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08,
0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,
0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2,
0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74,
0xe8, 0xcb]
def getRconValue(self, num):
"""Retrieves a given Rcon Value"""
return self.Rcon[num]
def core(self, word, iteration):
"""Key schedule core."""
# rotate the 32-bit word 8 bits to the left
word = self.rotate(word)
# apply S-Box substitution on all 4 parts of the 32-bit word
for i in range(4):
word[i] = self.getSBoxValue(word[i])
# XOR the output of the rcon operation with i to the first part
# (leftmost) only
word[0] = word[0] ^ self.getRconValue(iteration)
return word
def expandKey(self, key, size, expandedKeySize):
"""Rijndael's key expansion.
Expands an 128,192,256 key into an 176,208,240 bytes key
expandedKey is a char list of large enough size,
key is the non-expanded key.
"""
# current expanded keySize, in bytes
currentSize = 0
rconIteration = 1
expandedKey = [0] * expandedKeySize
# set the 16, 24, 32 bytes of the expanded key to the input key
for j in range(size):
expandedKey[j] = key[j]
currentSize += size
while currentSize < expandedKeySize:
# assign the previous 4 bytes to the temporary value t
t = expandedKey[currentSize - 4:currentSize]
# every 16,24,32 bytes we apply the core schedule to t
# and increment rconIteration afterwards
if currentSize % size == 0:
t = self.core(t, rconIteration)
rconIteration += 1
# For 256-bit keys, we add an extra sbox to the calculation
if size == self.keySize["SIZE_256"] and (
(currentSize % size) == 16):
for l in range(4):
t[l] = self.getSBoxValue(t[l])
# We XOR t with the four-byte block 16,24,32 bytes before the new
# expanded key. This becomes the next four bytes in the expanded
# key.
for m in range(4):
expandedKey[currentSize] = expandedKey[currentSize - size] ^ \
t[m]
currentSize += 1
return expandedKey
@staticmethod
def addRoundKey(state, roundKey):
"""Adds (XORs) the round key to the state."""
for i in range(16):
state[i] ^= roundKey[i]
return state
@staticmethod
def createRoundKey(expandedKey, roundKeyPointer):
"""Create a round key.
Creates a round key from the given expanded key and the
position within the expanded key.
"""
roundKey = [0] * 16
for i in range(4):
for j in range(4):
roundKey[j * 4 + i] = expandedKey[roundKeyPointer + i * 4 + j]
return roundKey
@staticmethod
def <API key>(a, b):
"""Galois multiplication of 8 bit characters a and b."""
p = 0
for counter in range(8):
if b & 1: p ^= a
hi_bit_set = a & 0x80
a <<= 1
# keep a 8 bit
a &= 0xFF
if hi_bit_set:
a ^= 0x1b
b >>= 1
return p
# substitute all the values from the state with the value in the SBox
# using the state value as index for the SBox
def subBytes(self, state, isInv):
if isInv:
getter = self.getSBoxInvert
else:
getter = self.getSBoxValue
for i in range(16):
state[i] = getter(state[i])
return state
# iterate over the 4 rows and call shiftRow() with that row
def shiftRows(self, state, isInv):
for i in range(4):
state = self.shiftRow(state, i * 4, i, isInv)
return state
# each iteration shifts the row to the left by 1
@staticmethod
def shiftRow(state, statePointer, nbr, isInv):
for i in range(nbr):
if isInv:
state[statePointer:statePointer + 4] = \
state[statePointer + 3:statePointer + 4] + \
state[statePointer:statePointer + 3]
else:
state[statePointer:statePointer + 4] = \
state[statePointer + 1:statePointer + 4] + \
state[statePointer:statePointer + 1]
return state
# galois multiplication of the 4x4 matrix
def mixColumns(self, state, isInv):
# iterate over the 4 columns
for i in range(4):
# construct one column by slicing over the 4 rows
column = state[i:i + 16:4]
# apply the mixColumn on one column
column = self.mixColumn(column, isInv)
# put the values back into the state
state[i:i + 16:4] = column
return state
# galois multiplication of 1 column of the 4x4 matrix
def mixColumn(self, column, isInv):
if isInv:
mult = [14, 9, 13, 11]
else:
mult = [2, 1, 1, 3]
cpy = list(column)
g = self.<API key>
column[0] = g(cpy[0], mult[0]) ^ g(cpy[3], mult[1]) ^ \
g(cpy[2], mult[2]) ^ g(cpy[1], mult[3])
column[1] = g(cpy[1], mult[0]) ^ g(cpy[0], mult[1]) ^ \
g(cpy[3], mult[2]) ^ g(cpy[2], mult[3])
column[2] = g(cpy[2], mult[0]) ^ g(cpy[1], mult[1]) ^ \
g(cpy[0], mult[2]) ^ g(cpy[3], mult[3])
column[3] = g(cpy[3], mult[0]) ^ g(cpy[2], mult[1]) ^ \
g(cpy[1], mult[2]) ^ g(cpy[0], mult[3])
return column
# applies the 4 operations of the forward round in sequence
def aes_round(self, state, roundKey):
state = self.subBytes(state, False)
state = self.shiftRows(state, False)
state = self.mixColumns(state, False)
state = self.addRoundKey(state, roundKey)
return state
# applies the 4 operations of the inverse round in sequence
def aes_invRound(self, state, roundKey):
state = self.shiftRows(state, True)
state = self.subBytes(state, True)
state = self.addRoundKey(state, roundKey)
state = self.mixColumns(state, True)
return state
# Perform the initial operations, the standard round, and the final
# operations of the forward aes, creating a round key for each round
def aes_main(self, state, expandedKey, nbrRounds):
state = self.addRoundKey(state, self.createRoundKey(expandedKey, 0))
i = 1
while i < nbrRounds:
state = self.aes_round(state,
self.createRoundKey(expandedKey, 16 * i))
i += 1
state = self.subBytes(state, False)
state = self.shiftRows(state, False)
state = self.addRoundKey(
state, self.createRoundKey(expandedKey, 16 * nbrRounds))
return state
# Perform the initial operations, the standard round, and the final
# operations of the inverse aes, creating a round key for each round
def aes_invMain(self, state, expandedKey, nbrRounds):
state = self.addRoundKey(
state, self.createRoundKey(expandedKey, 16 * nbrRounds))
i = nbrRounds - 1
while i > 0:
state = self.aes_invRound(state,
self.createRoundKey(expandedKey, 16 * i))
i -= 1
state = self.shiftRows(state, True)
state = self.subBytes(state, True)
state = self.addRoundKey(state, self.createRoundKey(expandedKey, 0))
return state
# encrypts a 128 bit input block against the given key of size specified
def encrypt(self, iput, key, size):
output = [0] * 16
# the number of rounds
nbrRounds = 0
# the 128 bit block to encode
block = [0] * 16
# set the number of rounds
if size == self.keySize["SIZE_128"]:
nbrRounds = 10
elif size == self.keySize["SIZE_192"]:
nbrRounds = 12
elif size == self.keySize["SIZE_256"]:
nbrRounds = 14
else:
return None
# the expanded keySize
expandedKeySize = 16 * (nbrRounds + 1)
# Set the block values, for the block:
# a0,0 a0,1 a0,2 a0,3
# a1,0 a1,1 a1,2 a1,3
# a2,0 a2,1 a2,2 a2,3
# a3,0 a3,1 a3,2 a3,3
# the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3
# iterate over the columns
for i in range(4):
# iterate over the rows
for j in range(4):
block[(i + (j * 4))] = iput[(i * 4) + j]
# expand the key into an 176, 208, 240 bytes key
# the expanded key
expandedKey = self.expandKey(key, size, expandedKeySize)
# encrypt the block using the expandedKey
block = self.aes_main(block, expandedKey, nbrRounds)
# unmap the block again into the output
for k in range(4):
# iterate over the rows
for l in range(4):
output[(k * 4) + l] = block[(k + (l * 4))]
return output
# decrypts a 128 bit input block against the given key of size specified
def decrypt(self, iput, key, size):
output = [0] * 16
# the number of rounds
nbrRounds = 0
# the 128 bit block to decode
block = [0] * 16
# set the number of rounds
if size == self.keySize["SIZE_128"]:
nbrRounds = 10
elif size == self.keySize["SIZE_192"]:
nbrRounds = 12
elif size == self.keySize["SIZE_256"]:
nbrRounds = 14
else:
return None
# the expanded keySize
expandedKeySize = 16 * (nbrRounds + 1)
# Set the block values, for the block:
# a0,0 a0,1 a0,2 a0,3
# a1,0 a1,1 a1,2 a1,3
# a2,0 a2,1 a2,2 a2,3
# a3,0 a3,1 a3,2 a3,3
# the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3
# iterate over the columns
for i in range(4):
# iterate over the rows
for j in range(4):
block[(i + (j * 4))] = iput[(i * 4) + j]
# expand the key into an 176, 208, 240 bytes key
expandedKey = self.expandKey(key, size, expandedKeySize)
# decrypt the block using the expandedKey
block = self.aes_invMain(block, expandedKey, nbrRounds)
# unmap the block again into the output
for k in range(4):
# iterate over the rows
for l in range(4):
output[(k * 4) + l] = block[(k + (l * 4))]
return output
class AESModeOfOperation(object):
aes = AES()
# structure of supported modes of operation
modeOfOperation = dict(OFB=0, CFB=1, CBC=2)
# converts a 16 character string into a number array
def convertString(self, string, start, end, mode):
if end - start > 16: end = start + 16
if mode == self.modeOfOperation["CBC"]:
ar = [0] * 16
else:
ar = []
i = start
j = 0
while len(ar) < end - start:
ar.append(0)
while i < end:
ar[j] = ord(string[i])
j += 1
i += 1
return ar
# Mode of Operation Encryption
# stringIn - Input String
# mode - mode of type modeOfOperation
# hexKey - a hex key of the bit length size
# size - the bit length of the key
# hexIV - the 128 bit hex Initilization Vector
def encrypt(self, stringIn, mode, key, size, IV):
if len(key) % size:
return None
if len(IV) % 16:
return None
# the AES input/output
plaintext = []
iput = [0] * 16
output = []
ciphertext = [0] * 16
# the output cipher string
cipherOut = []
# char firstRound
firstRound = True
if stringIn is not None:
for j in range(int(math.ceil(float(len(stringIn)) / 16))):
start = j * 16
end = j * 16 + 16
if end > len(stringIn):
end = len(stringIn)
plaintext = self.convertString(stringIn, start, end, mode)
# print 'PT@%s:%s' % (j, plaintext)
if mode == self.modeOfOperation["CFB"]:
if firstRound:
output = self.aes.encrypt(IV, key, size)
firstRound = False
else:
output = self.aes.encrypt(iput, key, size)
for i in range(16):
if len(plaintext) - 1 < i:
ciphertext[i] = 0 ^ output[i]
elif len(output) - 1 < i:
ciphertext[i] = plaintext[i] ^ 0
elif len(plaintext) - 1 < i and len(output) < i:
ciphertext[i] = 0 ^ 0
else:
ciphertext[i] = plaintext[i] ^ output[i]
for k in range(end - start):
cipherOut.append(ciphertext[k])
iput = ciphertext
elif mode == self.modeOfOperation["OFB"]:
if firstRound:
output = self.aes.encrypt(IV, key, size)
firstRound = False
else:
output = self.aes.encrypt(iput, key, size)
for i in range(16):
if len(plaintext) - 1 < i:
ciphertext[i] = 0 ^ output[i]
elif len(output) - 1 < i:
ciphertext[i] = plaintext[i] ^ 0
elif len(plaintext) - 1 < i and len(output) < i:
ciphertext[i] = 0 ^ 0
else:
ciphertext[i] = plaintext[i] ^ output[i]
for k in range(end - start):
cipherOut.append(ciphertext[k])
iput = output
elif mode == self.modeOfOperation["CBC"]:
for i in range(16):
if firstRound:
iput[i] = plaintext[i] ^ IV[i]
else:
iput[i] = plaintext[i] ^ ciphertext[i]
# print 'IP@%s:%s' % (j, iput)
firstRound = False
ciphertext = self.aes.encrypt(iput, key, size)
# always 16 bytes because of the padding for CBC
for k in range(16):
cipherOut.append(ciphertext[k])
return mode, len(stringIn), cipherOut
# Mode of Operation Decryption
# cipherIn - Encrypted String
# originalsize - The unencrypted string length - required for CBC
# mode - mode of type modeOfOperation
# key - a number array of the bit length size
# size - the bit length of the key
# IV - the 128 bit number array Initilization Vector
def decrypt(self, cipherIn, originalsize, mode, key, size, IV):
# cipherIn = unescCtrlChars(cipherIn)
if len(key) % size:
return None
if len(IV) % 16:
return None
# the AES input/output
ciphertext = []
iput = []
output = []
plaintext = [0] * 16
# the output plain text string
stringOut = ''
# char firstRound
firstRound = True
if cipherIn is not None:
for j in range(int(math.ceil(float(len(cipherIn)) / 16))):
start = j * 16
end = j * 16 + 16
if j * 16 + 16 > len(cipherIn):
end = len(cipherIn)
ciphertext = cipherIn[start:end]
if mode == self.modeOfOperation["CFB"]:
if firstRound:
output = self.aes.encrypt(IV, key, size)
firstRound = False
else:
output = self.aes.encrypt(iput, key, size)
for i in range(16):
if len(output) - 1 < i:
plaintext[i] = 0 ^ ciphertext[i]
elif len(ciphertext) - 1 < i:
plaintext[i] = output[i] ^ 0
elif len(output) - 1 < i and len(ciphertext) < i:
plaintext[i] = 0 ^ 0
else:
plaintext[i] = output[i] ^ ciphertext[i]
for k in range(end - start):
stringOut += chr(plaintext[k])
iput = ciphertext
elif mode == self.modeOfOperation["OFB"]:
if firstRound:
output = self.aes.encrypt(IV, key, size)
firstRound = False
else:
output = self.aes.encrypt(iput, key, size)
for i in range(16):
if len(output) - 1 < i:
plaintext[i] = 0 ^ ciphertext[i]
elif len(ciphertext) - 1 < i:
plaintext[i] = output[i] ^ 0
elif len(output) - 1 < i and len(ciphertext) < i:
plaintext[i] = 0 ^ 0
else:
plaintext[i] = output[i] ^ ciphertext[i]
for k in range(end - start):
stringOut += chr(plaintext[k])
iput = output
elif mode == self.modeOfOperation["CBC"]:
output = self.aes.decrypt(ciphertext, key, size)
for i in range(16):
if firstRound:
plaintext[i] = IV[i] ^ output[i]
else:
plaintext[i] = iput[i] ^ output[i]
firstRound = False
if originalsize is not None and originalsize < end:
for k in range(originalsize - start):
stringOut += chr(plaintext[k])
else:
for k in range(end - start):
stringOut += chr(plaintext[k])
iput = ciphertext
return stringOut
def encryptData(key, data, mode=AESModeOfOperation.modeOfOperation["CBC"]):
"""encrypt `data` using `key`
`key` should be a string of bytes.
returned cipher is a string of bytes prepended with the initialization
vector.
"""
key = map(ord, key)
if mode == AESModeOfOperation.modeOfOperation["CBC"]:
data = <API key>(data)
keysize = len(key)
assert keysize in AES.keySize.values(), 'invalid key size: %s' % keysize
# create a new iv using random data
iv = [ord(i) for i in os.urandom(16)]
moo = AESModeOfOperation()
(mode, length, ciph) = moo.encrypt(data, mode, key, keysize, iv)
# With padding, the original length does not need to be known. It's a bad
# idea to store the original message length.
# prepend the iv.
return ''.join(map(chr, iv)) + ''.join(map(chr, ciph))
def decryptData(key, data, mode=AESModeOfOperation.modeOfOperation["CBC"]):
"""decrypt `data` using `key`
`key` should be a string of bytes.
`data` should have the initialization vector prepended as a string of
ordinal values.
"""
key = map(ord, key)
keysize = len(key)
assert keysize in AES.keySize.values(), 'invalid key size: %s' % keysize
# iv is first 16 bytes
iv = map(ord, data[:16])
data = map(ord, data[16:])
moo = AESModeOfOperation()
decr = moo.decrypt(data, None, mode, key, keysize, iv)
if mode == AESModeOfOperation.modeOfOperation["CBC"]:
decr = strip_PKCS7_padding(decr)
return decr
if __name__ == "__main__":
moo = AESModeOfOperation()
cleartext = "This is a test!"
cypherkey = [143, 194, 34, 208, 145, 203, 230, 143, 177, 246, 97, 206, 145,
92, 255, 84]
iv = [103, 35, 148, 239, 76, 213, 47, 118, 255, 222, 123, 176, 106, 134, 98,
92]
mode, orig_len, ciph = moo.encrypt(cleartext, moo.modeOfOperation["CBC"],
cypherkey, moo.aes.keySize["SIZE_128"],
iv)
print 'm=%s, ol=%s (%s), ciph=%s' % (mode, orig_len, len(cleartext), ciph)
decr = moo.decrypt(ciph, orig_len, mode, cypherkey,
moo.aes.keySize["SIZE_128"], iv)
print decr |
#include <QLabel>
#include <QGridLayout>
#include <QPushButton>
#include <QDir>
#include <QDebug>
#include <QMessageBox>
#include <QApplication>
#include "include_h/sys_defs.h"
#include "logonui.h"
#include "climesgobsev.h"
LogonUi::LogonUi():QDialog(0, Qt::Window),
hight(300), width(430),cfgPath(QDir::homePath()+"/"+SYSCFGROOT)
{
dbptr = ClientSqlDb::getInstance();
setDisplayLogLayout();
setLogonInfoLayout();
setSysSetingLayout1();
setSysSetingLayout2();
topHalfPtr = new QVBoxLayout;
topHalfPtr->addWidget(displayLabelPtr);
downHalfPtr = new QVBoxLayout;
downHalfPtr->addLayout(logonInfoHlayoutPtr);
downHalfPtr->addWidget(sysSetingBoxPtr1);
mainLayoutPtr = new QVBoxLayout();
mainLayoutPtr->addLayout(topHalfPtr);
mainLayoutPtr->addLayout(downHalfPtr);
setLayout(mainLayoutPtr);
setWindowTitle(QStringLiteral(""));
setFixedHeight(hight);
setFixedWidth(width);
QDir cfgDir(cfgPath);
if (!cfgDir.exists()){
cfgDir.mkpath(cfgPath);
}
imChannelPtr = ImmesageChannel::getInstance();
imChannelPtr->regOneImobsever(new ImesgApplyNumObsev, this);
imChannelPtr->regOneImobsever(new ImesgLononObsev, this);
connect(imChannelPtr, SIGNAL(sockerror(int, const QString&)), this, SLOT(<API key>(int, const QString&)));
connect(this, SIGNAL(logonAuthStateSig(int)), this, SLOT(logonAuthStateSlot(int)));
oldSevAddr[0] = 0;
}
LogonUi::~LogonUi()
{
dbptr->close();
imChannelPtr->close();
}
void LogonUi::<API key>(int errn, const QString &errstr)
{
QMessageBox::warning(this, QStringLiteral(""), QStringLiteral("%1, %2").arg(errstr).arg(errn), QMessageBox::Ok);
logOnBtnPtr->setDisabled(0);
}
void LogonUi::setApplyNumInfo(const char *name, const char *pass, int uid, int avicon)
{
QString userinfo = QStringLiteral("") + name;
userinfo += QStringLiteral("\n ") + pass;
userinfo += QStringLiteral("\n ") + QString::number(uid);
displayLabelPtr->clear();
displayLabelPtr->setText(userinfo);
dbptr->setUsrBaseInfo(uid, name, pass, avicon);
<API key>();
}
void LogonUi::logonAuthStateSlot(int succ)
{
logOnBtnPtr->setDisabled(0);
if (!succ){
QMessageBox::warning(this, QStringLiteral(""), QStringLiteral(""),QMessageBox::Ok);
}else{
accept();
}
}
void LogonUi::setLogonAuthState(int succd)
{
emit logonAuthStateSig(succd);
}
void LogonUi::setDisplayLogLayout()
{
displayLabelPtr = new QLabel(QStringLiteral(""));
displayLabelPtr->setFixedSize(QSize(width, hight/2));
QFont f;
f.setBold(0);
f.setPointSize(15);
displayLabelPtr->setFont(f);
}
void LogonUi::setLogonInfoLayout()
{
logonInfoHlayoutPtr = new QHBoxLayout;
QHBoxLayout *hlayoutPtr = logonInfoHlayoutPtr;
QLabel *l = new QLabel();
l->setFixedSize(QSize(width/5, hight/2));
hlayoutPtr->addWidget(l);
QGridLayout *layoutGridLogonPtr = new QGridLayout;
layoutGridLogonPtr->addWidget(labUserIdPtr= new QLabel(QStringLiteral(" ")),0, 0);
lineUserName.setEditable(1);
<API key>();
layoutGridLogonPtr->addWidget(&lineUserName,0,1);
applyNumBtnPtr = new QPushButton(QStringLiteral(""));
connect(applyNumBtnPtr, SIGNAL(clicked(bool)), this, SLOT(applyNumFromServer()));
layoutGridLogonPtr->addWidget(applyNumBtnPtr,0,2);
layoutGridLogonPtr->addWidget(labUserPasswdPtr = new QLabel(QStringLiteral(" ")),1, 0);
layoutGridLogonPtr->addWidget(&linePasswd,1, 1);
logOnBtnPtr = new QPushButton(QStringLiteral(" "));
logOnBtnPtr->setDefault(1);
connect(logOnBtnPtr, SIGNAL(clicked(bool)), this, SLOT(sendLogonMessage()));
layoutGridLogonPtr->addWidget(logOnBtnPtr, 2,1);
hlayoutPtr->addLayout(layoutGridLogonPtr);
}
void LogonUi::setSysSetingLayout1()
{
sysSetingBoxPtr1 = new QGroupBox;
QHBoxLayout *<API key> = new QHBoxLayout;
setingBtnPtr = new QPushButton (QStringLiteral(""));
setingBtnPtr->setFixedWidth(70);
connect(setingBtnPtr, SIGNAL(clicked(bool)), this, SLOT(dispSeting()));
<API key>->addWidget(setingBtnPtr,Qt::AlignLeft);
<API key>->addStretch();
<API key>->setMargin(0);
sysSetingBoxPtr1->setLayout(<API key>);
}
void LogonUi::setSysSetingLayout2()
{
sysSetingBoxPtr2 = new QGroupBox;
QHBoxLayout *<API key> = new QHBoxLayout;
<API key> = new QLineEdit();
<API key>->setInputMask("000.000.000.000");
<API key>->setFixedWidth(105);
<API key> = new QLineEdit();
<API key>->setFixedWidth(35);
<API key>->setInputMask("00000");
<API key> = new QLineEdit;
<API key>->setFixedWidth(35);
<API key>->setInputMask("00000");
<API key> = new QLabel(QStringLiteral(""));
<API key> = new QLabel (QStringLiteral("TCP"));
<API key> = new QLabel(QStringLiteral("UDP"));
<API key>->addWidget(<API key>);
<API key>->addWidget(<API key>);
//<API key>->addSpacing(220);
<API key>->addWidget(<API key>);
<API key>->addWidget(<API key>);
<API key>->addWidget(<API key>);
<API key>->addWidget(<API key>);
setServerOkBtnPtr = new QPushButton(QStringLiteral(""));
setServerOkBtnPtr->setFixedWidth(35);
<API key> = new QPushButton(QStringLiteral(""));
<API key>->setFixedWidth(35);
connect(setServerOkBtnPtr, SIGNAL(clicked(bool)), this, SLOT(getLogonSevSeting()));
connect(<API key>, SIGNAL(clicked(bool)), this, SLOT(dispSeting()));
<API key>->addWidget(setServerOkBtnPtr);
<API key>->addWidget(<API key>);
<API key>->setMargin(0);
sysSetingBoxPtr2->setLayout(<API key>);
sysSetingBoxPtr2->setFlat(0);
}
void LogonUi::dispSeting()
{
static int clkSetingBtn = 1;
QGroupBox *sysSetingBoxPtrs[2] = {sysSetingBoxPtr2, sysSetingBoxPtr1};
lineUserName.setDisabled(clkSetingBtn);
linePasswd.setDisabled(clkSetingBtn);
applyNumBtnPtr->setDisabled(clkSetingBtn);
logOnBtnPtr->setDisabled(clkSetingBtn);
sysSetingBoxPtrs[clkSetingBtn]->hide();
downHalfPtr->replaceWidget(sysSetingBoxPtrs[clkSetingBtn], sysSetingBoxPtrs[!clkSetingBtn]);
sysSetingBoxPtrs[!clkSetingBtn]->show();
if (clkSetingBtn){
int tport, uport;
const char *addr;
if ((addr = dbptr->queryLogonSevAddr()) &&
(tport = dbptr->queryLogonSevTcport()) > 0 &&
(uport = dbptr->queryLogonSevUdport()) > 0){
<API key>(addr, tport, uport);
}
}
clkSetingBtn = !clkSetingBtn;
}
void LogonUi::getLogonSevSeting()
{
bool b;
dispSeting();
b = dbptr->setLogonSevSeting(<API key>->text().toStdString().c_str(),
<API key>->text().toUInt(),
<API key>->text().toUInt(), oldSevAddr);
if (!b){
<API key>(0, QStringLiteral(":") + QString(dbptr->getErrorStr()));
}
}
void LogonUi::<API key>(const char *sev, int tport, int uport)
{
if (sev){
strncpy(oldSevAddr, sev, sizeof(oldSevAddr));
<API key>->setText(sev);
<API key>->setText(QString::number(tport));
<API key>->setText(QString::number(uport));
}
}
void LogonUi::applyNumFromServer()
{
int tport, uport;
const char *addr;
if ((addr = dbptr->queryLogonSevAddr()) &&
(tport = dbptr->queryLogonSevTcport()) > 0 &&
(uport = dbptr->queryLogonSevUdport()) > 0){
ImmessageData m(IMMESG_APPLYNUM);
//imChannelPtr->sendTcpData2Server(oldSevAddr, tport, m);
imChannelPtr->pushTcpDataOut(m, addr, tport);
}else{
<API key>(0, QStringLiteral("") + QString(dbptr->getErrorStr()));
}
}
void LogonUi::<API key>()
{
SqlQueryDataRows row;
if (dbptr->queryAllUsrId(row)){
lineUserName.clear();
for (uint32_t i = 0; i < row.size(); ++i){
lineUserName.addItem(QString::number(row[i][0].getInt()));
}
}
}
void LogonUi::sendLogonMessage()
{
ImmessageData m(IMMESG_USER_LOGON);
ImmesgDecorLogon logon(&m);
int tport;
const char *addr;
if ((addr = dbptr->queryLogonSevAddr()) &&
(tport = dbptr->queryLogonSevTcport()) > 0){
logon.setDstSrcUsr(0, lineUserName.currentText().toInt());
logon.setLogonPassword(linePasswd.text().toStdString().c_str());
imChannelPtr->pushTcpDataOut(m, addr,tport);
logOnBtnPtr->setDisabled(1);
}else{
<API key>(0, QStringLiteral(""));
}
} |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;
using System.Text;
namespace AutoMainTreeMaker
{
class <API key>
{
List<CRichTextbox> richs;
public <API key>()
{
richs = new List<CRichTextbox>();
foreach (CRichTextbox r in richs)
{
r.SaveNowSelectInfo();
}
}
public void SetInterface(List<CRichTextbox> richs)
{
if (!(richs.Count >= 1))
throw new ArgumentException("CRichInterface CRichBox .");
this.richs = richs;
foreach(CRichTextbox rich in this.richs)
{
rich.MouseClick += new System.Windows.Forms.MouseEventHandler(this.<API key>);
rich.KeyUp += new System.Windows.Forms.KeyEventHandler(this.<API key>);
}
}
private void <API key>(object sender, MouseEventArgs e)
{
CRichTextbox thisBox = (CRichTextbox)sender;
int beginIndex = thisBox.SelectionStart;
int currentLine = thisBox.<API key>(beginIndex);
foreach (CRichTextbox r in richs)
{
if ( currentLine <= r.Lines.Length - 1)
{
r.<API key>();
r.<API key>(currentLine);
}
}
}
private void <API key>(object sender, KeyEventArgs e)
{
}
public void <API key>()
{
int max = GetMaxmimumLines();
foreach(CRichTextbox rich in richs)
{
if(rich.Lines.Length < max)
{
int adjustion = max - rich.Lines.Length;
for(int i=0; i < adjustion; i++)
rich.AppendText("\n");
}
}
}
private void SetScrollbar()
{
// richs[0].AutoScrollOffset =
}
public int GetMaxmimumLines()
{
int lines = 0;
foreach(var rich in richs)
{
if(lines < rich.Lines.Length)
{
lines = rich.Lines.Length;
}
}
return lines;
}
}
} |
/* Finite impulse response (FIR) resampler with adjustable FIR size */
/* C Conversion by Eke-Eke for use in Genesis Plus GX (2009). */
#include "Fir_Resampler.h"
#include "shared.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
/* sound buffer */
static sample_t *buffer = NULL;
static int buffer_size = 0;
static sample_t impulses[MAX_RES][WIDTH];
static sample_t* write_pos = NULL;
static int res = 1;
static int imp_phase = 0;
static unsigned long skip_bits = 0;
static int step = STEREO;
static int input_per_cycle;
static SysDDec ratio = 1.0;
static void gen_sinc(SysDDec rolloff, int width, SysDDec offset, SysDDec spacing, SysDDec scale, int count, sample_t *out )
{
SysDDec w, rolloff_cos_a, num, den, sinc;
SysDDec const maxh = 256;
SysDDec const fstep = M_PI / maxh * spacing;
SysDDec const to_w = maxh * 2 / width;
SysDDec const pow_a_n = pow( rolloff, maxh );
scale /= maxh * 2;
SysDDec angle = (count / 2 - 1 + offset) * -fstep;
do
{
*out++ = 0;
w = angle * to_w;
if ( fabs( w ) < (SysDDec)M_PI )
{
rolloff_cos_a = rolloff * cos( angle );
num = 1 - rolloff_cos_a -
pow_a_n * cos( maxh * angle ) +
pow_a_n * rolloff * cos( (maxh - 1) * angle );
den = 1 - rolloff_cos_a - rolloff_cos_a + rolloff * rolloff;
sinc = scale * num / den - scale;
out [-1] = (short) (cos( w ) * sinc + sinc);
}
angle += fstep;
}
while(--count);
}
/*static int available( long input_count )
{
int cycle_count = input_count / input_per_cycle;
int output_count = cycle_count * res * STEREO;
input_count -= cycle_count * input_per_cycle;
unsigned long skip = skip_bits >> imp_phase;
int remain = res - imp_phase;
while ( input_count >= 0 )
{
input_count -= step + (skip & 1) * STEREO;
skip >>= 1;
if ( !--remain )
{
skip = skip_bits;
remain = res;
}
output_count += 2;
}
return output_count;
}
*/
int Fir_Resampler_avail()
{
long count = 0;
sample_t* in = buffer;
sample_t* end_pos = write_pos;
unsigned long skip = skip_bits >> imp_phase;
int remain = res - imp_phase;
if ( end_pos - in >= WIDTH * STEREO )
{
end_pos -= WIDTH * STEREO;
do
{
count++;
remain
in += (skip * STEREO) & STEREO;
skip >>= 1;
in += step;
if ( !remain )
{
skip = skip_bits;
remain = res;
}
}
while ( in <= end_pos );
}
return count;
}
int <API key>( int new_size )
{
res = 1;
skip_bits = 0;
imp_phase = 0;
step = STEREO;
ratio = 1.0;
buffer = (sample_t *) realloc( buffer, (new_size + WRITE_OFFSET) * sizeof (sample_t) );
write_pos = 0;
if ( !buffer ) return 0;
buffer_size = new_size + WRITE_OFFSET;
Fir_Resampler_clear();
return 1;
}
void <API key>( void )
{
if (buffer) free(buffer);
buffer = 0;
buffer_size = 0;
write_pos = 0;
}
void Fir_Resampler_clear()
{
imp_phase = 0;
if ( buffer_size )
{
write_pos = &buffer [WRITE_OFFSET];
memset( buffer, 0, buffer_size * sizeof (sample_t) );
}
}
SysDDec <API key>( SysDDec new_factor, SysDDec rolloff )
{
ratio = new_factor;
int i, r;
SysDDec nearest, error;
SysDDec fstep = 0.0;
SysDDec least_error = 2;
SysDDec pos = 0.0;
res = -1;
for ( r = 1; r <= MAX_RES; r++ )
{
pos += ratio;
nearest = floor( pos + 0.5 );
error = fabs( pos - nearest );
if ( error < least_error )
{
res = r;
fstep = nearest / res;
least_error = error;
}
}
skip_bits = 0;
step = STEREO * (int) floor( fstep );
ratio = fstep;
fstep = fmod( fstep, 1.0 );
SysDDec filter = (ratio < 1.0) ? 1.0 : 1.0 / ratio;
pos = 0.0;
input_per_cycle = 0;
memset(impulses, 0, MAX_RES*WIDTH*sizeof(sample_t));
for ( i = 0; i < res; i++ )
{
gen_sinc( rolloff, (int) (WIDTH * filter + 1) & ~1, pos, filter,
(SysDDec) (0x7FFF * GAIN * filter),
(int) WIDTH, impulses[i] );
pos += fstep;
input_per_cycle += step;
if ( pos >= 0.9999999 )
{
pos -= 1.0;
skip_bits |= 1 << i;
input_per_cycle++;
}
}
Fir_Resampler_clear();
return ratio;
}
/* Current ratio */
SysDDec Fir_Resampler_ratio( void )
{
return ratio;
}
/* Number of input samples that can be written */
int <API key>( void )
{
return buffer + buffer_size - write_pos;
}
/* Pointer to place to write input samples */
sample_t* <API key>( void )
{
return write_pos;
}
/* Number of input samples in buffer */
int <API key>( void )
{
return write_pos - &buffer [WRITE_OFFSET];
}
/* Number of output samples available */
/*int Fir_Resampler_avail( void )
{
return available( write_pos - &buffer [WIDTH * STEREO] );
}*/
void Fir_Resampler_write( long count )
{
write_pos += count;
}
int Fir_Resampler_read( sample_t* out, long count )
{
sample_t* out_ = out;
sample_t* in = buffer;
sample_t* end_pos = write_pos;
unsigned long skip = skip_bits >> imp_phase;
sample_t const* imp = impulses [imp_phase];
int remain = res - imp_phase;
int n;
int pt0,pt1;
sample_t* i;
long l,r;
if ( end_pos - in >= WIDTH * STEREO )
{
end_pos -= WIDTH * STEREO;
do
{
count
if ( count < 0 )
break;
/* accumulate in extended precision */
l = 0;
r = 0;
i = in;
for ( n = WIDTH / 2; n; --n )
{
pt0 = imp [0];
l += pt0 * i [0];
r += pt0 * i [1];
pt1 = imp [1];
imp += 2;
l += pt1 * i [2];
r += pt1 * i [3];
i += 4;
}
remain
l >>= 15;
r >>= 15;
in += (skip * STEREO) & STEREO;
skip >>= 1;
in += step;
if ( !remain )
{
imp = impulses [0];
skip = skip_bits;
remain = res;
}
*out++ = (sample_t) l;
*out++ = (sample_t) r;
}
while ( in <= end_pos );
}
imp_phase = res - remain;
int left = write_pos - in;
write_pos = &buffer [left];
memmove( buffer, in, left * sizeof *in );
return out - out_;
}
/* fixed (Eke_Eke) */
int <API key>( long output_count )
{
long input_count = 0;
unsigned long skip = skip_bits >> imp_phase;
int remain = res - imp_phase;
while ( (output_count) > 0 )
{
input_count += step + (skip & 1) * STEREO;
skip >>= 1;
if ( !--remain )
{
skip = skip_bits;
remain = res;
}
output_count
}
long input_extra = input_count - (write_pos - &buffer [WRITE_OFFSET]);
if ( input_extra < 0 )
input_extra = 0;
return (input_extra >> 1);
}
int <API key>( long count )
{
int remain = write_pos - buffer;
int max_count = remain - WIDTH * STEREO;
if ( count > max_count )
count = max_count;
remain -= count;
write_pos = &buffer [remain];
memmove( buffer, &buffer [count], remain * sizeof buffer [0] );
return count;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.