code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
# containers | brandl-muc/containers | README.md | Markdown | gpl-3.0 | 12 |
/*
* generated by Xtext
*/
package org.eclectic.frontend.parser.antlr;
import com.google.inject.Inject;
import org.eclipse.xtext.parser.antlr.XtextTokenStream;
import org.eclectic.frontend.services.TaoGrammarAccess;
public class TaoParser extends org.eclipse.xtext.parser.antlr.AbstractAntlrParser {
@Inject
private TaoGrammarAccess grammarAccess;
@Override
protected void setInitialHiddenTokens(XtextTokenStream tokenStream) {
tokenStream.setInitialHiddenTokens("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT");
}
@Override
protected org.eclectic.frontend.parser.antlr.internal.InternalTaoParser createParser(XtextTokenStream stream) {
return new org.eclectic.frontend.parser.antlr.internal.InternalTaoParser(stream, getGrammarAccess());
}
@Override
protected String getDefaultRuleName() {
return "TaoTransformation";
}
public TaoGrammarAccess getGrammarAccess() {
return this.grammarAccess;
}
public void setGrammarAccess(TaoGrammarAccess grammarAccess) {
this.grammarAccess = grammarAccess;
}
}
| jesusc/eclectic | plugins/org.eclectic.frontend.syntax/src-gen/org/eclectic/frontend/parser/antlr/TaoParser.java | Java | gpl-3.0 | 1,041 |
<?php
require "common.inc.php";
verifica_seguranca($_SESSION[PAP_RESP_MUTIRAO]);
top();
?>
<?php
$action = request_get("action",-1);
if($action==-1) $action=ACAO_EXIBIR_LEITURA;
$est_cha=request_get("est_cha",-1);
if($est_cha==-1)
{
if(isset($_SESSION['cha_id_pref']))
{
$est_cha=$_SESSION['cha_id_pref'];
}
}
$_SESSION['cha_id_pref']=$est_cha;
if ($est_cha<>-1)
{
$sql = "SELECT prodt_nome, DATE_FORMAT(cha_dt_entrega,'%d/%m/%Y') cha_dt_entrega, cha_taxa_percentual, ((cha_dt_prazo_contabil is null) OR (cha_dt_prazo_contabil > now() ) ) as cha_dentro_prazo, date_format(cha_dt_prazo_contabil,'%d/%m/%Y %H:%i') cha_dt_prazo_contabil ";
$sql.= "FROM chamadas LEFT JOIN produtotipos ON prodt_id = cha_prodt ";
$sql.= "WHERE cha_id = " . prep_para_bd($est_cha);
$res = executa_sql($sql);
if ($row = mysqli_fetch_array($res,MYSQLI_ASSOC))
{
$prodt_nome = $row["prodt_nome"];
$cha_dt_entrega = $row["cha_dt_entrega"];
$cha_taxa_percentual = $row["cha_taxa_percentual"];
$cha_dt_prazo_contabil = $row["cha_dt_prazo_contabil"];
$cha_dentro_prazo = $row["cha_dentro_prazo"];
}
}
if ($action == ACAO_SALVAR) // salvar formulário preenchido
{
// salva disponibilidade de produtos
$n = isset($_REQUEST['est_prod']) ? sizeof($_REQUEST['est_prod']) : 0;
for($i=0;$i<$n;$i++)
{
$est_cha_bd = prep_para_bd($est_cha);
$qtde_antes_bd = $_REQUEST['est_prod_qtde_antes'][$i] <>"" ? prep_para_bd(formata_numero_para_mysql($_REQUEST['est_prod_qtde_antes'][$i])) : 'NULL';
$obs_antes_bd = $_REQUEST['est_obs_antes'][$i] <>"" ? prep_para_bd($_REQUEST['est_obs_antes'][$i]) : 'NULL';
$sql = "INSERT INTO estoque (est_cha, est_prod, est_prod_qtde_antes, est_obs_antes ) ";
$sql.= "VALUES ( " . $est_cha_bd . " ," . prep_para_bd($_REQUEST['est_prod'][$i]) . ", ";
$sql.= $qtde_antes_bd . ", " . $obs_antes_bd . ") ";
$sql.= "ON DUPLICATE KEY UPDATE ";
$sql.= " est_prod_qtde_antes = " . $qtde_antes_bd . ", ";
$sql.= " est_obs_antes = " . $obs_antes_bd . " ";
$res = executa_sql($sql);
}
if($res)
{
$action=ACAO_EXIBIR_LEITURA; //volta para modo visualização somente leitura
adiciona_mensagem_status(MSG_TIPO_SUCESSO,"As informações de estoque relacionado à chamada " . $cha_dt_entrega . " foram salvas com sucesso.");
}
else
{
adiciona_mensagem_status(MSG_TIPO_ERRO,"Erro ao tentar salvar informações de estoque da chamada para o dia " . $cha_dt_entrega . ".");
}
escreve_mensagem_status();
}
if ($action == ACAO_EXIBIR_LEITURA || $action == ACAO_EXIBIR_EDICAO ) // exibir para visualização, ou exibir para edição
{
}
?>
<ul class="nav nav-tabs">
<li><a href="mutirao.php">Mutirão</a></li>
<li class="active"><a href="#"><i class="glyphicon glyphicon-bed"></i> Estoque Pré-Mutirão</a></li>
<li><a href="recebimento.php"><i class="glyphicon glyphicon-road"></i> Recebimento</a></li>
<li><a href="distribuicao_consolidado_por_produtor.php"><i class="glyphicon glyphicon-fullscreen"></i> Distribuição</a></li>
<li><a href="estoque_pos.php"><i class="glyphicon glyphicon-bed"></i> Estoque Pós-Mutirão</a></li>
<li><a href="mutirao_divergencias.php"><i class="glyphicon glyphicon-eye-open"></i> Divergências</a></li>
</ul>
<br>
<div class="panel panel-default">
<div class="panel-heading">
<strong>Estoque Pré-Mutirão</strong>
</div>
<?php
if($action==ACAO_EXIBIR_LEITURA) //visualização somente leitura
{
?>
<div class="panel-body">
<form class="form-inline" method="get" name="frm_filtro" id="frm_filtro">
<?php
?>
<fieldset>
<div class="form-group">
<label for="est_cha">Chamada: </label>
<select name="est_cha" id="est_cha" onchange="javascript:frm_filtro.submit();" class="form-control">
<option value="-1">SELECIONE</option>
<?php
$sql = "SELECT cha_id, prodt_nome, cha_dt_entrega cha_dt_entrega_original, DATE_FORMAT(cha_dt_entrega,'%d/%m/%Y') cha_dt_entrega ";
$sql.= "FROM chamadas LEFT JOIN produtotipos ON prodt_id = cha_prodt ";
$sql.= "WHERE prodt_mutirao = '1' ";
$sql.= "ORDER BY cha_dt_entrega_original DESC LIMIT 10";
$res = executa_sql($sql);
if($res)
{
$achou=false;
while ($row = mysqli_fetch_array($res,MYSQLI_ASSOC))
{
echo("<option value='" . $row['cha_id'] . "'");
if($row['cha_id']==$est_cha)
{
echo(" selected");
$achou=true;
}
echo (">" . $row['prodt_nome'] . " - " . $row['cha_dt_entrega'] . "</option>");
}
if($est_cha!=-1 && !$achou)
{
$sql = "SELECT cha_id, prodt_nome, cha_dt_entrega cha_dt_entrega_original, DATE_FORMAT(cha_dt_entrega,'%d/%m/%Y') cha_dt_entrega ";
$sql.= "FROM chamadas LEFT JOIN produtotipos ON prodt_id = cha_prodt ";
$sql.= "WHERE cha_id = " . prep_para_bd($est_cha);
$res2 = executa_sql($sql);
$row = mysqli_fetch_array($res2,MYSQLI_ASSOC);
if($row)
{
echo("<option value='" . $row['cha_id'] . "' selected>");
echo ($row['prodt_nome'] . " - " . $row['cha_dt_entrega'] . "</option>");
}
}
}
?>
</select>
<?php
if($est_cha!=-1)
{
?>
<label for="cha_dt_prazo_contabil">Prazo para Edição: </label> <?php echo($cha_dt_prazo_contabil?$cha_dt_prazo_contabil:"ainda não configurado"); ?>
<?php
if(!$cha_dentro_prazo)
{
echo("<span class='alert alert-danger'>(encerrado)</span>");
}
}
?>
</div>
</fieldset>
</form>
</div>
<?php
if($est_cha!=-1)
{
$sql = "SELECT prod_id, prod_nome, estoque.est_prod_qtde_antes est_atual_prod_qtde_antes, ";
$sql.= "estoque.est_obs_antes est_atual_obs_antes, ";
$sql.= "estoque_anterior.est_prod_qtde_depois est_anterior_prod_qtde_depois, prod_unidade, ";
$sql.= "chaprod_prod, forn_nome_curto, forn_nome_completo, forn_id FROM chamadaprodutos ";
$sql.= "LEFT JOIN produtos on chaprod_prod = prod_id ";
$sql.= "LEFT JOIN chamadas on chaprod_cha = cha_id ";
$sql.= "LEFT JOIN fornecedores on prod_forn = forn_id ";
$sql.= "LEFT JOIN estoque on est_cha = cha_id AND est_prod = chaprod_prod ";
$sql.="LEFT JOIN estoque estoque_anterior ON estoque_anterior.est_prod = chaprod_prod AND estoque_anterior.est_cha = " . prep_para_bd(get_chamada_anterior($est_cha)) . " ";
$sql.= "WHERE prod_ini_validade<=NOW() AND prod_fim_validade>=NOW() ";
$sql.= "AND chaprod_cha = " . prep_para_bd($est_cha) . " AND chaprod_disponibilidade > 0 ";
$sql.= " AND (estoque.est_prod_qtde_antes >0 OR estoque_anterior.est_prod_qtde_depois > 0 OR estoque.est_obs_antes IS NOT NULL ) ";
$sql.= "ORDER BY forn_nome_curto, prod_nome, prod_unidade ";
$res = executa_sql($sql);
if($res && mysqli_num_rows($res)==0)
{
?>
<div class="panel-body">
<!--
<button type="button" class="btn btn-default btn-enviando" data-loading-text="importando..." onclick="javascript:location.href='estoque_pre.php?action=<?php echo(ACAO_EXIBIR_LEITURA);?>&est_cha=<?php echo($est_cha); ?>&importar=sim'">
<i class="icon glyphicon glyphicon-resize-small"></i> importar estoque do último mutirão
</button>
-->
<br /><div class='well'> Sem produtos em estoque. Se de fato houver, clique em editar para registrar. </div><br />
</div>
<?php
}
else if($res)
{
?>
<table class="table table-striped table-bordered table-condensed table-hover">
<thead>
<tr>
<th colspan="3">Informações de Estoque Pré-Mutirão da Entrega de <?php echo($prodt_nome . " - " . $cha_dt_entrega); ?></th>
<th colspan="2">
<?php
if($cha_dentro_prazo)
{
?>
<a class="btn btn-primary" href="estoque_pre.php?action=<?php echo(ACAO_EXIBIR_EDICAO); ?>&cha_id=<?php echo($est_cha); ?>"><i class="glyphicon glyphicon-edit"></i> editar</a>
<?php
}
else
{
echo(" ");
}
?>
</th>
</tr>
</thead>
<tbody>
<?php
$ultimo_forn = "";
while ($row = mysqli_fetch_array($res,MYSQLI_ASSOC))
{
if($row["forn_nome_curto"]!=$ultimo_forn)
{
$ultimo_forn = $row["forn_nome_curto"];
?>
<tr>
<th>
<?php echo($row["forn_nome_curto"]);
adiciona_popover_descricao("",$row["forn_nome_completo"]);
?>
</th>
<th>Unidade</th>
<th>Estoque Pré-Mutirão Esperado<?php adiciona_popover_descricao("Descrição", " = Estoque final informado pelo Mutirão anterior"); ?></th>
<th>Estoque Pré-Mutirão Real</th>
<th>Observação</th>
</tr>
<?php
}
?>
<tr>
<td><?php echo($row["prod_nome"]);?></td>
<td><?php echo($row["prod_unidade"]); ?></td>
<td>
<?php if($row["est_anterior_prod_qtde_depois"]) echo_digitos_significativos($row["est_anterior_prod_qtde_depois"]); else echo(" "); ?>
</td>
<td <?php if($row["est_anterior_prod_qtde_depois"] != $row["est_atual_prod_qtde_antes"]) echo(" class='" . (($row["est_atual_obs_antes"]) ? "info" : "danger") . "'");?>>
<?php if($row["est_atual_prod_qtde_antes"]) echo_digitos_significativos($row["est_atual_prod_qtde_antes"]); else echo(" "); ?>
</td>
<td>
<?php echo( ($row["est_atual_obs_antes"]) ? $row["est_atual_obs_antes"] : " ") ; ?>
</td>
</tr>
<?php
}
echo("</tbody></table>");
}
?>
</div>
<?php
if($est_cha!=-1 && $cha_dentro_prazo)
{
?>
<div align="right">
<a class="btn btn-primary" href="estoque_pre.php?action=<?php echo(ACAO_EXIBIR_EDICAO); ?>&est_cha=<?php echo($est_cha); ?>"><i class="glyphicon glyphicon-edit glyphicon-white"></i> editar</a>
</div>
<?php
}
} // fim if est_cha !=-1
?>
<?php
}
else //visualização para edição
{
?>
<form class="form-horizontal" method="post">
<div class="panel-body">
<div align="right">
<button type="submit" class="btn btn-primary btn-enviando" data-loading-text="salvando estoque...">
<i class="glyphicon glyphicon-ok glyphicon-white"></i> salvar alterações</button>
<button class="btn btn-default" type="button" onclick="javascript:location.href='estoque_pre.php?action=<?php echo(ACAO_EXIBIR_LEITURA); ?>&est_cha=<?php echo($est_cha); ?>';"><i class="glyphicon glyphicon-off"></i> descartar alterações</button>
</div>
</div>
<fieldset>
<input type="hidden" name="est_cha" value="<?php echo($est_cha); ?>" />
<input type="hidden" name="action" value="<?php echo(ACAO_SALVAR); ?>" />
<div class="form-group">
<div class="container">
<?php
$sql = "SELECT prod_id, prod_nome, estoque.est_prod_qtde_antes est_atual_prod_qtde_antes, ";
$sql.= "estoque.est_obs_antes est_atual_obs_antes, ";
$sql.= "estoque_anterior.est_prod_qtde_depois est_anterior_prod_qtde_depois, prod_unidade, ";
$sql.= "chaprod_prod, forn_nome_curto, forn_nome_completo, forn_id FROM chamadaprodutos ";
$sql.= "LEFT JOIN produtos on chaprod_prod = prod_id ";
$sql.= "LEFT JOIN chamadas on chaprod_cha = cha_id ";
$sql.= "LEFT JOIN fornecedores on prod_forn = forn_id ";
$sql.= "LEFT JOIN estoque on est_cha = cha_id AND est_prod = chaprod_prod ";
$sql.="LEFT JOIN estoque estoque_anterior ON estoque_anterior.est_prod = chaprod_prod AND estoque_anterior.est_cha = " . prep_para_bd(get_chamada_anterior($est_cha)) . " ";
$sql.= "WHERE prod_ini_validade<=NOW() AND prod_fim_validade>=NOW() ";
$sql.= "AND chaprod_cha = " . prep_para_bd($est_cha) . " AND chaprod_disponibilidade > 0 ";
$sql.= "ORDER BY forn_nome_curto, prod_nome, prod_unidade ";
$res = executa_sql($sql);
if($res)
{
?>
<table class='table table-striped table-bordered table-condensed table-hover'>
<thead>
<tr>
<th colspan="5">
Informações de Estoque Pré-Mutirão relacionado à chamada de <?php echo($prodt_nome . " - " . $cha_dt_entrega); ?>
</th>
</tr>
</thead>
<tbody>
<tr>
<td> </td><td> </td>
<td colspan="2">
<button type="button" class="btn btn-info" name="copia_produtos_pedido" id="copia_produtos_pedido" onclick="javascript:replicaDados('replica-origem','replica-destino');">
<i class="glyphicon glyphicon-paste"></i> replicar do estoque esperado
</button>
</td>
<td> </td>
</tr>
<?php
$ultimo_forn = "";
while ($row = mysqli_fetch_array($res,MYSQLI_ASSOC))
{
if($row["forn_nome_curto"]!=$ultimo_forn)
{
$ultimo_forn = $row["forn_nome_curto"];
?>
<tr>
<th>
<?php echo($row["forn_nome_curto"]);
adiciona_popover_descricao("",$row["forn_nome_completo"]);
?>
</th>
<th>Unidade</th>
<th>Estoque Pré-Mutirão Esperado<?php adiciona_popover_descricao("Descrição", " = Estoque final informado pelo Mutirão anterior"); ?></th>
<th>Estoque Pré-Mutirão Real</th>
<th>Observação</th>
</tr>
<?php
}
?>
<tr>
<input type="hidden" name="est_prod[]" value="<?php echo($row["prod_id"]); ?>"/>
<td><?php echo($row["prod_nome"]);?></td>
<td><?php echo($row["prod_unidade"]); ?></td>
<td style="text-align:center">
<input type="hidden" name="est_anterior_prod_qtde_depois[]" class="replica-origem" value="<?php if($row["est_anterior_prod_qtde_depois"]) echo_digitos_significativos($row["est_anterior_prod_qtde_depois"]); ?>">
<?php if($row["est_anterior_prod_qtde_depois"]) echo_digitos_significativos($row["est_anterior_prod_qtde_depois"],"0"); ?>
</td>
<td>
<input type="text" class="replica-destino form-control propaga-colar numero-positivo" style="font-size:18px; text-align:center;" value="<?php if($row["est_atual_prod_qtde_antes"]) echo_digitos_significativos($row["est_atual_prod_qtde_antes"],"0"); ?>" name="est_prod_qtde_antes[]" id="est_prod_qtde_antes_<?php echo($row["prod_id"]); ?>"/>
</td>
<td>
<input type="text" class="form-control" value="<?php if($row["est_atual_obs_antes"]) echo($row["est_atual_obs_antes"]); ?>" name="est_obs_antes[]" id="est_obs_antes_<?php echo($row["prod_id"]); ?>"/>
</td>
</tr>
<?php
}
echo("</tbody></table>");
}
?>
</div>
</div>
<div align="right">
<button type="submit" class="btn btn-primary btn-enviando" data-loading-text="salvando estoque...">
<i class="glyphicon glyphicon-ok glyphicon-white"></i> salvar alterações</button>
<button class="btn btn-default" type="button" onclick="javascript:location.href='estoque_pre.php?action=<?php echo(ACAO_EXIBIR_LEITURA); ?>&est_cha=<?php echo($est_cha); ?>';"><i class="glyphicon glyphicon-off"></i> descartar alterações</button>
</div>
</fieldset>
</form>
<?php
}
footer();
?>
| redeecologica/pedidos | estoque_pre.php | PHP | gpl-3.0 | 19,108 |
jQuery(document).ready(function($) {
$('#slide-left').flexslider({
animation: "slide",
controlNav: "thumbnails",
start: function(slider) {
$('ol.flex-control-thumbs li img.flex-active').parent('li').addClass('active');
}
});
});
jQuery(document).ready(function($) {
$('#slide').flexslider({
animation: "slide",
controlNav: false,
directionNav: true
});
}); | vietnamframework/vietnamframework | app/view/newstreecolumn/js/jquery.flexslider.init.js | JavaScript | gpl-3.0 | 414 |
/*
* This file is part of the command-line tool sosicon.
* Copyright (C) 2014 Espen Andersen, Norwegian Broadcast Corporation (NRK)
*
* This is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "converter_sosi2tsv.h"
void sosicon::ConverterSosi2tsv::
run( bool* ) {
}
| espena/sosicon | src/converter_sosi2tsv.cpp | C++ | gpl-3.0 | 877 |
use crate::cube::Cube;
use glium;
use glium::{Display, Program, Surface, implement_vertex};
use glium::index::{IndexBuffer, PrimitiveType};
use std::rc::Rc;
pub fn solid_fill_program(display: &Display) -> Program {
let vertex_shader_src = include_str!("shaders/solid.vert");
let fragment_shader_src = include_str!("shaders/solid.frag");
Program::from_source(display, vertex_shader_src, fragment_shader_src, None).unwrap()
}
#[derive(Copy, Clone)]
struct Vertex { position: [f32; 3] }
implement_vertex!(Vertex, position);
pub struct BoundingBox {
vertexes: glium::VertexBuffer<Vertex>,
program: Rc<Program>,
indices: IndexBuffer<u16>,
}
impl BoundingBox {
pub fn new(display: &Display, c: &Cube, program: Rc<Program>) -> BoundingBox {
let vertex_data = [
Vertex { position: [c.xmin, c.ymin, c.zmin] },
Vertex { position: [c.xmax, c.ymin, c.zmin] },
Vertex { position: [c.xmax, c.ymax, c.zmin] },
Vertex { position: [c.xmin, c.ymax, c.zmin] },
Vertex { position: [c.xmin, c.ymin, c.zmax] },
Vertex { position: [c.xmax, c.ymin, c.zmax] },
Vertex { position: [c.xmax, c.ymax, c.zmax] },
Vertex { position: [c.xmin, c.ymax, c.zmax] },
];
const INDICES: &[u16] = &[0, 1, 1, 2, 2, 3, 3, 0, // front
4, 5, 5, 6, 6, 7, 7, 4, // back
0, 4, 1, 5, 2, 6, 3, 7]; // sides
BoundingBox {
vertexes: glium::VertexBuffer::new(display, &vertex_data).unwrap(),
program: program,
indices: IndexBuffer::new(display, PrimitiveType::LinesList, INDICES).unwrap(),
}
}
pub fn draw<U>(&self, frame: &mut glium::Frame,
uniforms: &U) where U: glium::uniforms::Uniforms {
let params = glium::DrawParameters {
depth: glium::Depth {
test: glium::draw_parameters::DepthTest::IfLess,
write: true,
..Default::default()
},
blend: glium::Blend::alpha_blending(),
..Default::default()
};
frame.draw(&self.vertexes, &self.indices, &self.program, uniforms, ¶ms).unwrap();
}
}
| codewiz/mandelwow | bounding_box.rs | Rust | gpl-3.0 | 2,271 |
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace DrakSolz.Projectiles {
public class ChickenEgg : ModProjectile {
public override string Texture { get { return "Terraria/Projectile_318"; } }
public override void SetStaticDefaults() {
DisplayName.SetDefault("Chicken Egg");
}
public override void SetDefaults() {
projectile.CloneDefaults(ProjectileID.RottenEgg);
projectile.aiStyle = 2;
projectile.friendly = false;
projectile.hostile = true;
projectile.penetrate = -1;
projectile.timeLeft = 600;
}
public override bool TileCollideStyle(ref int width, ref int height, ref bool fallThrough) {
width = 5;
height = 5;
return true;
}
public override void Kill(int timeLeft) {
Utils.PoofOfSmoke(projectile.Center);
NPC.NewNPC((int) projectile.Center.X, (int) projectile.Center.Y, ModContent.NPCType<NPCs.Enemy.PreHardMode.EvilChicken>());
}
}
} | Xahlicem/DrakSolz | Projectiles/ChickenEgg.cs | C# | gpl-3.0 | 1,089 |
---
date: 2020-01-07T17:53:33+0000
title: "Hazy State"
authors: "Collective Arts Brewing"
rating: 3.5
drink_of: https://untappd.com/b/collective-arts-brewing-hazy-state/3104704
checkin:
title: The Griffin
lat: 51.525
long: -0.082
weather:
summary: Overcast
temperature: 11.5
badges:
- title: I Believe in IPA! (Level 9)
id: 619792722
posting_method: https://ownyour.beer
---
| chrisburnell/chrisburnell.github.io | src/posts/beer/2020-01-07-852755619.md | Markdown | gpl-3.0 | 391 |
<?php
/*
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Free Content / Management System #
# / #
# #
# #
# Copyright 2005-2011 by webspell.org #
# #
# visit webSPELL.org, webspell.info to get webSPELL for free #
# - Script runs under the GNU GENERAL PUBLIC LICENSE #
# - It's NOT allowed to remove this copyright-tag #
# -- http://www.fsf.org/licensing/licenses/gpl.html #
# #
# Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), #
# Far Development by Development Team - webspell.org #
# #
# visit webspell.org #
# #
##########################################################################
##########################################################################
# #
# Version 4 / / / #
# -----------__---/__---__------__----__---/---/- #
# | /| / /___) / ) (_ ` / ) /___) / / #
# _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ #
# Society / Edition #
# / #
# #
# modified by webspell|k3rmit (Stefan Giesecke) in 2009 #
# #
# - Modifications are released under the GNU GENERAL PUBLIC LICENSE #
# - It is NOT allowed to remove this copyright-tag #
# - http://www.fsf.org/licensing/licenses/gpl.html #
# #
##########################################################################
*/
$_language->read_module('gallery');
if(!isgalleryadmin($userID) OR mb_substr(basename($_SERVER['REQUEST_URI']),0,15) != "admincenter.php") die($_language->module['access_denied']);
$galclass = new Gallery;
if(isset($_GET['part'])) $part = $_GET['part'];
else $part = '';
if(isset($_GET['action'])) $action = $_GET['action'];
else $action = '';
if($part=="groups") {
if(isset($_POST['save'])) {
$CAPCLASS = new Captcha;
if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) {
if(checkforempty(Array('name'))) safe_query("INSERT INTO ".PREFIX."gallery_groups ( name, sort ) values( '".$_POST['name']."', '1' ) ");
else echo $_language->module['information_incomplete'];
} else echo $_language->module['transaction_invalid'];
}
elseif(isset($_POST['saveedit'])) {
$CAPCLASS = new Captcha;
if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) {
if(checkforempty(Array('name'))) safe_query("UPDATE ".PREFIX."gallery_groups SET name='".$_POST['name']."' WHERE groupID='".$_POST['groupID']."'");
else echo $_language->module['information_incomplete'];
} else echo $_language->module['transaction_invalid'];
}
elseif(isset($_POST['sort'])) {
$CAPCLASS = new Captcha;
if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) {
if(isset($_POST['sortlist'])){
if(is_array($_POST['sortlist'])) {
foreach($_POST['sortlist'] as $sortstring) {
$sorter=explode("-", $sortstring);
safe_query("UPDATE ".PREFIX."gallery_groups SET sort='$sorter[1]' WHERE groupID='$sorter[0]' ");
}
}
}
} else echo $_language->module['transaction_invalid'];
}
elseif(isset($_GET['delete'])) {
$CAPCLASS = new Captcha;
if($CAPCLASS->check_captcha(0, $_GET['captcha_hash'])) {
$db_result=safe_query("SELECT * FROM ".PREFIX."gallery WHERE groupID='".$_GET['groupID']."'");
$any=mysql_num_rows($db_result);
if($any){
echo $_language->module['galleries_available'].'<br /><br />';
}
else{
safe_query("DELETE FROM ".PREFIX."gallery_groups WHERE groupID='".$_GET['groupID']."'");
}
} else echo $_language->module['transaction_invalid'];
}
if($action=="add") {
$CAPCLASS = new Captcha;
$CAPCLASS->create_transaction();
$hash = $CAPCLASS->get_hash();
echo'<h1>¤ <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> » <a href="admincenter.php?site=gallery&part=groups" class="white">'.$_language->module['groups'].'</a> » '.$_language->module['add_group'].'</h1>';
echo'<form method="post" action="admincenter.php?site=gallery&part=groups">
<table width="100%" border="0" cellspacing="1" cellpadding="3">
<tr>
<td width="15%"><b>'.$_language->module['group_name'].'</b></td>
<td width="85%"><input type="text" name="name" size="60" /></td>
</tr>
<tr>
<td><input type="hidden" name="captcha_hash" value="'.$hash.'" /></td>
<td><input type="submit" name="save" value="'.$_language->module['add_group'].'" /></td>
</tr>
</table>
</form>';
}
elseif($action=="edit") {
$CAPCLASS = new Captcha;
$CAPCLASS->create_transaction();
$hash = $CAPCLASS->get_hash();
$ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups WHERE groupID='".$_GET['groupID']."'");
$ds=mysql_fetch_array($ergebnis);
echo'<h1>¤ <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> » <a href="admincenter.php?site=gallery&part=groups" class="white">'.$_language->module['groups'].'</a> » '.$_language->module['edit_group'].'</h1>';
echo'<form method="post" action="admincenter.php?site=gallery&part=groups">
<table width="100%" border="0" cellspacing="1" cellpadding="3">
<tr>
<td width="15%"><b>'.$_language->module['group_name'].'</b></td>
<td><input type="text" name="name" size="60" value="'.getinput($ds['name']).'" /></td>
</tr>
<tr>
<td><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="hidden" name="groupID" value="'.$ds['groupID'].'" /></td>
<td><input type="submit" name="saveedit" value="'.$_language->module['edit_group'].'" /></td>
</tr>
</table>
</form>';
}
else {
echo'<h1>¤ <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> » '.$_language->module['groups'].'</h1>';
echo'<input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&part=groups&action=add\');return document.MM_returnValue" value="'.$_language->module['new_group'].'" /><br /><br />';
$ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups ORDER BY sort");
echo'<form method="post" name="ws_gallery" action="admincenter.php?site=gallery&part=groups">
<table width="100%" border="0" cellspacing="1" cellpadding="3" bgcolor="#DDDDDD">
<tr>
<td width="70%" class="title"><b>'.$_language->module['group_name'].'</b></td>
<td width="20%" class="title"><b>'.$_language->module['actions'].'</b></td>
<td width="10%" class="title"><b>'.$_language->module['sort'].'</b></td>
</tr>';
$n=1;
$CAPCLASS = new Captcha;
$CAPCLASS->create_transaction();
$hash = $CAPCLASS->get_hash();
while($ds=mysql_fetch_array($ergebnis)) {
if($n%2) { $td='td1'; }
else { $td='td2'; }
$list = '<select name="sortlist[]">';
for($i=1;$i<=mysql_num_rows($ergebnis);$i++) {
$list.='<option value="'.$ds['groupID'].'-'.$i.'">'.$i.'</option>';
}
$list .= '</select>';
$list = str_replace('value="'.$ds['groupID'].'-'.$ds['sort'].'"','value="'.$ds['groupID'].'-'.$ds['sort'].'" selected="selected"',$list);
echo'<tr>
<td class="'.$td.'">'.$ds['name'].'</td>
<td class="'.$td.'" align="center"><input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&part=groups&action=edit&groupID='.$ds['groupID'].'\');return document.MM_returnValue" value="'.$_language->module['edit'].'" />
<input type="button" onclick="MM_confirm(\''.$_language->module['really_delete_group'].'\', \'admincenter.php?site=gallery&part=groups&delete=true&groupID='.$ds['groupID'].'&captcha_hash='.$hash.'\')" value="'.$_language->module['delete'].'" /></td>
<td class="'.$td.'" align="center">'.$list.'</td>
</tr>';
$n++;
}
echo'<tr>
<td class="td_head" colspan="3" align="right"><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="submit" name="sort" value="'.$_language->module['to_sort'].'" /></td>
</tr>
</table>
</form>';
}
}
//part: gallerys
elseif($part=="gallerys") {
if(isset($_POST['save'])) {
$CAPCLASS = new Captcha;
if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) {
if(checkforempty(Array('name'))) {
safe_query("INSERT INTO ".PREFIX."gallery ( name, date, groupID ) values( '".$_POST['name']."', '".time()."', '".$_POST['group']."' ) ");
$id = mysql_insert_id();
} else echo $_language->module['information_incomplete'];
} else echo $_language->module['transaction_invalid'];
}
elseif(isset($_POST['saveedit'])) {
$CAPCLASS = new Captcha;
if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) {
if(checkforempty(Array('name'))) {
if(!isset($_POST['group'])) {
$_POST['group'] = 0;
}
safe_query("UPDATE ".PREFIX."gallery SET name='".$_POST['name']."', groupID='".$_POST['group']."' WHERE galleryID='".$_POST['galleryID']."'");
} else echo $_language->module['information_incomplete'];
} else echo $_language->module['transaction_invalid'];
}
elseif(isset($_POST['saveftp'])) {
$dir = '../images/gallery/';
$pictures = array();
if(isset($_POST['comment'])) $comment = $_POST['comment'];
if(isset($_POST['name'])) $name = $_POST['name'];
if(isset($_POST['pictures'])) $pictures = $_POST['pictures'];
$i=0;
$CAPCLASS = new Captcha;
if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) {
foreach($pictures as $picture) {
$typ = getimagesize($dir.$picture);
switch ($typ[2]) {
case 1: $typ = '.gif'; break;
case 2: $typ = '.jpg'; break;
case 3: $typ = '.png'; break;
}
if($name[$i]) $insertname = $name[$i];
else $insertname = $picture;
safe_query("INSERT INTO ".PREFIX."gallery_pictures ( galleryID, name, comment, comments) VALUES ('".$_POST['galleryID']."', '".$insertname."', '".$comment[$i]."', '".$_POST['comments']."' )");
$insertid = mysql_insert_id();
copy($dir.$picture, $dir.'large/'.$insertid.$typ);
$galclass->savethumb($dir.'large/'.$insertid.$typ, $dir.'thumb/'.$insertid.'.jpg');
@unlink($dir.$picture);
$i++;
}
} else echo $_language->module['transaction_invalid'];
}
elseif(isset($_POST['saveform'])) {
$dir = '../images/gallery/';
$picture = $_FILES['picture'];
$CAPCLASS = new Captcha;
if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) {
if($picture['name'] != "") {
if($_POST['name']) $insertname = $_POST['name'];
else $insertname = $picture['name'];
safe_query("INSERT INTO ".PREFIX."gallery_pictures ( galleryID, name, comment, comments) VALUES ('".$_POST['galleryID']."', '".$insertname."', '".$_POST['comment']."', '".$_POST['comments']."' )");
$insertid = mysql_insert_id();
$typ = getimagesize($picture['tmp_name']);
switch ($typ[2]) {
case 1: $typ = '.gif'; break;
case 2: $typ = '.jpg'; break;
case 3: $typ = '.png'; break;
}
move_uploaded_file($picture['tmp_name'], $dir.'large/'.$insertid.$typ);
$galclass->savethumb($dir.'large/'.$insertid.$typ, $dir.'thumb/'.$insertid.'.jpg');
}
} else echo $_language->module['transaction_invalid'];
}
elseif(isset($_GET['delete'])) {
//SQL
$CAPCLASS = new Captcha;
if($CAPCLASS->check_captcha(0, $_GET['captcha_hash'])) {
if(safe_query("DELETE FROM ".PREFIX."gallery WHERE galleryID='".$_GET['galleryID']."'")) {
//FILES
$ergebnis=safe_query("SELECT picID FROM ".PREFIX."gallery_pictures WHERE galleryID='".$_GET['galleryID']."'");
while($ds=mysql_fetch_array($ergebnis)) {
@unlink('../images/gallery/thumb/'.$ds['picID'].'.jpg'); //thumbnails
$path = '../images/gallery/large/';
if(file_exists($path.$ds['picID'].'.jpg')) $path = $path.$ds['picID'].'.jpg';
elseif(file_exists($path.$ds['picID'].'.png')) $path = $path.$ds['picID'].'.png';
else $path = $path.$ds['picID'].'.gif';
@unlink($path); //large
safe_query("DELETE FROM ".PREFIX."comments WHERE parentID='".$ds['picID']."' AND type='ga'");
}
safe_query("DELETE FROM ".PREFIX."gallery_pictures WHERE galleryID='".$_GET['galleryID']."'");
}
} else echo $_language->module['transaction_invalid'];
}
if($action=="add") {
$ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups");
$any=mysql_num_rows($ergebnis);
if($any){
$groups = '<select name="group">';
while($ds=mysql_fetch_array($ergebnis)) {
$groups.='<option value="'.$ds['groupID'].'">'.getinput($ds['name']).'</option>';
}
$groups.='</select>';
$CAPCLASS = new Captcha;
$CAPCLASS->create_transaction();
$hash = $CAPCLASS->get_hash();
echo'<h1>¤ <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> » <a href="admincenter.php?site=gallery&part=gallerys" class="white">'.$_language->module['galleries'].'</a> » '.$_language->module['add_gallery'].'</h1>';
echo'<form method="post" action="admincenter.php?site=gallery&part=gallerys&action=upload">
<table width="100%" border="0" cellspacing="1" cellpadding="3">
<tr>
<td width="15%"><b>'.$_language->module['gallery_name'].'</b></td>
<td width="85%"><input type="text" name="name" size="60" /></td>
</tr>
<tr>
<td><b>'.$_language->module['group'].'</b></td>
<td>'.$groups.'</td>
</tr>
<tr>
<td><b>'.$_language->module['pic_upload'].'</b></td>
<td><select name="upload">
<option value="ftp">'.$_language->module['ftp'].'</option>
<option value="form">'.$_language->module['formular'].'</option>
</select></td>
</tr>
<tr>
<td><input type="hidden" name="captcha_hash" value="'.$hash.'" /></td>
<td><input type="submit" name="save" value="'.$_language->module['add_gallery'].'" /></td>
</tr>
</table>
</form>
<br /><small>'.$_language->module['ftp_info'].' "http://'.$hp_url.'/images/gallery"</small>';
}
else{
echo '<br>'.$_language->module['need_group'];
}
}
elseif($action=="edit") {
$CAPCLASS = new Captcha;
$CAPCLASS->create_transaction();
$hash = $CAPCLASS->get_hash();
$ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups");
$groups = '<select name="group">';
while($ds=mysql_fetch_array($ergebnis)) {
$groups.='<option value="'.$ds['groupID'].'">'.getinput($ds['name']).'</option>';
}
$groups.='</select>';
$ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery WHERE galleryID='".$_GET['galleryID']."'");
$ds=mysql_fetch_array($ergebnis);
$groups = str_replace('value="'.$ds['groupID'].'"','value="'.$ds['groupID'].'" selected="selected"',$groups);
echo'<h1>¤ <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> » <a href="admincenter.php?site=gallery&part=gallerys" class="white">'.$_language->module['galleries'].'</a> » '.$_language->module['edit_gallery'].'</h1>';
echo'<form method="post" action="admincenter.php?site=gallery&part=gallerys">
<table width="100%" border="0" cellspacing="1" cellpadding="3">
<tr>
<td width="15%"><b>'.$_language->module['gallery_name'].'</b></td>
<td width="85%"><input type="text" name="name" value="'.getinput($ds['name']).'" /></td>
</tr>';
if($ds['userID'] != 0) echo '
<tr>
<td><b>'.$_language->module['usergallery_of'].'</b></td>
<td><a href="../index.php?site=profile&id='.$userID.'" target="_blank">'.getnickname($ds['userID']).'</a></td>
</tr>';
else echo '<tr>
<td><b>'.$_language->module['group'].'</b></td>
<td>'.$groups.'</td>
</tr>';
echo'<tr>
<td><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="hidden" name="galleryID" value="'.$ds['galleryID'].'" /></td>
<td><input type="submit" name="saveedit" value="'.$_language->module['edit_gallery'].'" /></td>
</tr>
</table>
</form>';
}
elseif($action=="upload") {
echo'<h1>¤ <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> » <a href="admincenter.php?site=gallery&part=gallerys" class="white">'.$_language->module['galleries'].'</a> » '.$_language->module['upload'].'</h1>';
$dir = '../images/gallery/';
if(isset($_POST['upload'])) $upload_type = $_POST['upload'];
elseif(isset($_GET['upload'])) $upload_type = $_GET['upload'];
else $upload_type = null;
if(isset($_GET['galleryID'])) $id=$_GET['galleryID'];
if($upload_type == "ftp") {
$CAPCLASS = new Captcha;
$CAPCLASS->create_transaction();
$hash = $CAPCLASS->get_hash();
echo'<form method="post" action="admincenter.php?site=gallery&part=gallerys">
<table width="100%" border="0" cellspacing="1" cellpadding="3">
<tr>
<td>';
$pics = Array();
$picdir = opendir($dir);
while (false !== ($file = readdir($picdir))) {
if ($file != "." && $file != "..") {
if(is_file($dir.$file)) {
if($info = getimagesize($dir.$file)) {
if($info[2]==1 OR $info[2]==2 || $info[2]==3) $pics[] = $file;
}
}
}
}
closedir($picdir);
natcasesort ($pics);
reset ($pics);
echo '<script language="JavaScript" type="text/javascript">
function fillcomments(){
document.getElementById(\'comments\').value=getselection(\'access\');
}
</script>
<table border="0" width="100%" cellspacing="1" cellpadding="1">
<tr>
<td></td>
<td><b>'.$_language->module['filename'].'</b></td>
<td><b>'.$_language->module['name'].'</b></td>
<td><b>'.$_language->module['comment'].'</b></td>
</tr>';
foreach($pics as $val) {
if(is_file($dir.$val)) {
echo '<tr>
<td><input type="checkbox" value="'.$val.'" name="pictures[]" checked="checked" /></td>
<td><a href="'.$dir.$val.'" target="_blank">'.$val.'</a></td>
<td><input type="text" name="name[]" size="40" /></td>
<td><input type="text" name="comment[]" size="40" /></td>
</tr>';
}
}
$accesses=generateaccessdropdown('access', 'access', '', 'fillcomments();');
echo '</table></td>
</tr>
<tr>
<td><br /><b>'.$_language->module['visitor_comments'].'</b>
'.$accesses.'
<input type="hidden" value="" name="comments" id="comments" /></td>
</tr>
<tr>
<td><br /><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="hidden" name="galleryID" value="'.$id.'" />
<input type="submit" name="saveftp" value="'.$_language->module['upload'].'" /></td>
</tr>
</table>
</form>';
} elseif($upload_type == "form") {
$CAPCLASS = new Captcha;
$CAPCLASS->create_transaction();
$hash = $CAPCLASS->get_hash();
$accesses=generateaccessdropdown('access', 'access', '', 'fillcomments();');
echo '<script language="JavaScript" type="text/javascript">
function fillcomments(){
document.getElementById(\'comments\').value=getselection(\'access\');
}
</script>
<form method="post" action="admincenter.php?site=gallery&part=gallerys" enctype="multipart/form-data">
<table width="100%" border="0" cellspacing="1" cellpadding="3">
<tr>
<td width="20%"><b>'.$_language->module['name'].'</b></td>
<td width="80%"><input type="text" name="name" size="60" /></td>
</tr>
<tr>
<td><b>'.$_language->module['comment'].'</b></td>
<td><input type="text" name="comment" size="60" maxlength="255" /></td>
</tr>
<tr>
<td valign="top"><b>'.$_language->module['visitor_comments'].'</b></td>
<td>
'.$accesses.'
<input type="hidden" value="" name="comments" id="comments" />
</td>
</tr>
<tr>
<td><b>'.$_language->module['picture'].'</b></td>
<td><input name="picture" type="file" size="40" /></td>
</tr>
<tr>
<td><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="hidden" name="galleryID" value="'.$id.'" /></td>
<td><input type="submit" name="saveform" value="'.$_language->module['upload'].'" /></td>
</tr>
</table>
</form>';
}
}
else {
echo'<h1>¤ <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> » '.$_language->module['galleries'].'</h1>';
echo'<input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&part=gallerys&action=add\');return document.MM_returnValue" value="'.$_language->module['new_gallery'].'" /><br /><br />';
echo'<form method="post" name="ws_gallery" action="admincenter.php?site=gallery&part=gallerys">
<table width="100%" border="0" cellspacing="1" cellpadding="3" bgcolor="#DDDDDD">
<tr>
<td width="50%" class="title"><b>'.$_language->module['gallery_name'].'</b></td>
<td width="50%" class="title" colspan="2"><b>'.$_language->module['actions'].'</b></td>
</tr>';
$ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups ORDER BY sort");
while($ds=mysql_fetch_array($ergebnis)) {
echo'<tr>
<td class="td_head" colspan="3"><b>'.getinput($ds['name']).'</b></td>
</tr>';
$galleries=safe_query("SELECT * FROM ".PREFIX."gallery WHERE groupID='$ds[groupID]' AND userID='0' ORDER BY date");
$CAPCLASS = new Captcha;
$CAPCLASS->create_transaction();
$hash = $CAPCLASS->get_hash();
$i=1;
while($db=mysql_fetch_array($galleries)) {
if($i%2) { $td='td1'; }
else { $td='td2'; }
echo'<tr>
<td class="'.$td.'" width="50%"><a href="../index.php?site=gallery&galleryID='.$db['galleryID'].'" target="_blank">'.getinput($db['name']).'</a></td>
<td class="'.$td.'" width="30%" align="center"><input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&part=gallerys&action=upload&upload=form&galleryID='.$db['galleryID'].'\');return document.MM_returnValue" value="'.$_language->module['add_img'].' ('.$_language->module['per_form'].')" style="margin:1px;" /> <input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&part=gallerys&action=upload&upload=ftp&galleryID='.$db['galleryID'].'\');return document.MM_returnValue" value="'.$_language->module['add_img'].' ('.$_language->module['per_ftp'].')" style="margin:1px;" /></td>
<td class="'.$td.'" width="20%" align="center"><input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&part=gallerys&action=edit&galleryID='.$db['galleryID'].'\');return document.MM_returnValue" value="'.$_language->module['edit'].'" />
<input type="button" onclick="MM_confirm(\''.$_language->module['really_delete_gallery'].'\', \'admincenter.php?site=gallery&part=gallerys&delete=true&galleryID='.$db['galleryID'].'&captcha_hash='.$hash.'\')" value="'.$_language->module['delete'].'" /></td>
</tr>';
$i++;
}
}
echo'</table></form><br /><br />';
echo'<h1>¤ <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> » '.$_language->module['usergalleries'].'</h1>';
$ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery WHERE userID!='0'");
echo'<form method="post" name="ws_gallery" action="admincenter.php?site=gallery&part=gallerys">
<table width="100%" border="0" cellspacing="1" cellpadding="3" bgcolor="#DDDDDD">
<tr>
<td width="50%" class="title"><b>'.$_language->module['gallery_name'].'</b></td>
<td width="30%" class="title"><b>'.$_language->module['usergallery_of'].'</b></td>
<td width="20%" class="title"><b>'.$_language->module['actions'].'</b></td>
</tr>';
$CAPCLASS = new Captcha;
$CAPCLASS->create_transaction();
$hash = $CAPCLASS->get_hash();
$i=1;
while($ds=mysql_fetch_array($ergebnis)) {
if($i%2) { $td='td1'; }
else { $td='td2'; }
echo'<tr>
<td class="'.$td.'"><a href="../index.php?site=gallery&galleryID='.$ds['galleryID'].'" target="_blank">'.getinput($ds['name']).'</a></td>
<td class="'.$td.'"><a href="../index.php?site=profile&id='.$userID.'" target="_blank">'.getnickname($ds['userID']).'</a></td>
<td class="'.$td.'" align="center"><input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&part=gallerys&action=edit&galleryID='.$ds['galleryID'].'\');return document.MM_returnValue" value="'.$_language->module['edit'].'" />
<input type="button" onclick="MM_confirm(\''.$_language->module['really_delete_gallery'].'\', \'admincenter.php?site=gallery&part=gallerys&delete=true&galleryID='.$ds['galleryID'].'&captcha_hash='.$hash.'\')" value="'.$_language->module['delete'].'" /></td>
</tr>';
$i++;
}
echo'</table></form>';
}
}
?> | webSPELL/webSPELL-4.2.3SE | admin/gallery.php | PHP | gpl-3.0 | 27,665 |
# Example implementing 5 layer encoder
# Original code taken from
# https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/autoencoder.py
# The model trained here is restored in load.py
from __future__ import division, print_function, absolute_import
# Import MNIST data
# from tensorflow.examples.tutorials.mnist import input_data
# data_set = input_data.read_data_sets("/tmp/data/", one_hot=True)
# Import libraries
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import sys
import scipy.io as sio
sys.path.insert(0, '../..') # Add path to where TF_Model.py is, if not in the same dir
from TF_Model import *
from utils import *
# 01 thumb
# 10 pinky
action_map = {}
action_map[1] = [0,1]
action_map[2] = [1,0]
# thumb up
mat_contents_t0 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_pinky_Jan5_0.mat')
mat_contents_t1 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_pinky_Jan5_1.mat')
mat_contents_test0 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_pinky_jan5_2.mat')
data_t0 = mat_contents_t0['EMGdata']
data_t1 = mat_contents_t1['EMGdata']
data_test0 = mat_contents_test0['EMGdata']
batch_y_t0, batch_x_t0 = get_batch_from_raw_data_new_format(data_t0, action_map, [0])
batch_y_t1, batch_x_t1 = get_batch_from_raw_data_new_format(data_t1, action_map, [0])
batch_y_test0, batch_x_test0 = get_batch_from_raw_data_new_format(data_test0, action_map, [0])
# pinky up
mat_contents_p0 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_thumb_Jan5_0.mat')
mat_contents_p1 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_thumb_Jan5_1.mat')
mat_contents_test1 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_thumb_Jan5_2.mat')
data_p0 = mat_contents_p0['EMGdata']
data_p1 = mat_contents_p1['EMGdata']
data_test1 = mat_contents_test1['EMGdata']
batch_y_p0, batch_x_p0 = get_batch_from_raw_data_new_format(data_p0, action_map, [0])
batch_y_p1, batch_x_p1 = get_batch_from_raw_data_new_format(data_p1, action_map, [0])
batch_y_test1, batch_x_test1 = get_batch_from_raw_data_new_format(data_test1, action_map, [0])
print("done reading data")
# Create TF_Model, a wrapper for models created using tensorflow
# Note that the configuration file 'config.txt' must be present in the directory
model = TF_Model('model')
# Parameters
learning_rate = 0.05
training_epochs = 200
batch_size = 256
display_step = 1
examples_to_show = 10
# total_batch = int(data_set.train.num_examples/batch_size)
dropout = tf.placeholder(tf.float32)
# Create variables for inputs, outputs and predictions
x = tf.placeholder(tf.float32, [None, 1000])
y = tf.placeholder(tf.float32, [None, 2])
y_true = y
y_pred = model.predict(x)
# Cost function
cost = tf.reduce_mean(tf.pow(y_true - y_pred, 2))
optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost)
# Initializing the variables
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
model_output = model.predict(x)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(model_output), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(model_output,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# Train
for epoch in range(training_epochs):
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x_t0, y: batch_y_t0})
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x_t1, y: batch_y_t1})
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x_p0, y: batch_y_p0})
_, c = sess.run([optimizer, cost], feed_dict={x: batch_x_p1, y: batch_y_p1})
# Display logs per epoch step
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c))
print(sess.run(accuracy, feed_dict={x: batch_x_test0, y: batch_y_test0}))
print(sess.run(accuracy, feed_dict={x: batch_x_test1, y: batch_y_test1}))
print("===final===")
print(sess.run(accuracy, feed_dict={x: batch_x_test0, y: batch_y_test0}))
print(sess.run(accuracy, feed_dict={x: batch_x_test1, y: batch_y_test1}))
# Save
model.save(sess, 'example_3')
| LindaLS/Sausage_Biscuits | architecture/tests/2_test/train.py | Python | gpl-3.0 | 4,265 |
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.github.mdsimmo.pixeldungeon.levels.painters;
import com.github.mdsimmo.pixeldungeon.items.Gold;
import com.github.mdsimmo.pixeldungeon.items.Heap;
import com.github.mdsimmo.pixeldungeon.items.keys.IronKey;
import com.github.mdsimmo.pixeldungeon.levels.Level;
import com.github.mdsimmo.pixeldungeon.levels.Room;
import com.github.mdsimmo.pixeldungeon.levels.Terrain;
import com.github.mdsimmo.utils.Random;
public class TreasuryPainter extends Painter {
public static void paint( Level level, Room room ) {
fill( level, room, Terrain.WALL );
fill( level, room, 1, Terrain.EMPTY );
set( level, room.center(), Terrain.STATUE );
Heap.Type heapType = Random.Int( 2 ) == 0 ? Heap.Type.CHEST : Heap.Type.HEAP;
int n = Random.IntRange( 2, 3 );
for ( int i = 0; i < n; i++ ) {
int pos;
do {
pos = room.random();
} while ( level.map[pos] != Terrain.EMPTY || level.heaps.get( pos ) != null );
level.drop( new Gold().random(), pos ).type = (i == 0 && heapType == Heap.Type.CHEST ? Heap.Type.MIMIC : heapType);
}
if ( heapType == Heap.Type.HEAP ) {
for ( int i = 0; i < 6; i++ ) {
int pos;
do {
pos = room.random();
} while ( level.map[pos] != Terrain.EMPTY );
level.drop( new Gold( Random.IntRange( 1, 3 ) ), pos );
}
}
room.entrance().set( Room.Door.Type.LOCKED );
level.addItemToSpawn( new IronKey() );
}
}
| mdsimmo/cake-dungeon | java/com/github/mdsimmo/pixeldungeon/levels/painters/TreasuryPainter.java | Java | gpl-3.0 | 2,296 |
/*
* object.c
*
* Copyright (C) 2012 - Dr.NP
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Universal hash array object
*
* @package bsp::libbsp-core
* @author Dr.NP <[email protected]>
* @update 05/21/2013
* @changelog
* [06/11/2012] - Creation
* [08/14/2012] - Float / Double byte order
* [09/28/2012] - Array support
* [05/21/2013] - Remove float / double byte-order reverse
* [12/17/2013] - Lightuserdata supported
* [08/05/2014] - Rebuild
*/
#include "bsp.h"
/* Set values */
/*
void set_item_int8(BSP_VALUE *val, const int8_t value)
{
if (val)
{
set_int8(value, val->lval);
val->type = BSP_VAL_INT8;
}
return;
}
void set_item_int16(BSP_VALUE *val, const int16_t value)
{
if (val)
{
set_int16(value, val->lval);
val->type = BSP_VAL_INT16;
}
return;
}
void set_item_int32(BSP_VALUE *val, const int32_t value)
{
if (val)
{
set_int32(value, val->lval);
val->type = BSP_VAL_INT32;
}
return;
}
void set_item_int64(BSP_VALUE *val, const int64_t value)
{
if (val)
{
set_int64(value, val->lval);
item->value.type = BSP_VAL_INT64;
}
return;
}
*/
// Set value to value
void value_set_int(BSP_VALUE *val, const int64_t value)
{
if (val)
{
set_vint(value, val->lval);
val->type = BSP_VAL_INT;
}
}
void value_set_float(BSP_VALUE *val, const float value)
{
if (val)
{
set_float(value, val->lval);
val->type = BSP_VAL_FLOAT;
}
return;
}
void value_set_double(BSP_VALUE *val, const double value)
{
if (val)
{
set_double(value, val->lval);
val->type = BSP_VAL_DOUBLE;
}
return;
}
void value_set_boolean_true(BSP_VALUE *val)
{
if (val)
{
set_vint(1, val->lval);
val->type = BSP_VAL_BOOLEAN_TRUE;
}
return;
}
void value_set_boolean_false(BSP_VALUE *val)
{
if (val)
{
set_vint(0, val->lval);
val->type = BSP_VAL_BOOLEAN_FALSE;
}
return;
}
void value_set_pointer(BSP_VALUE *val, const void *p)
{
if (val)
{
val->rval = (void *) p;
val->type = BSP_VAL_POINTER;
}
return;
}
void value_set_string(BSP_VALUE *val, BSP_STRING *str)
{
if (val && str)
{
val->rval = (void *) str;
val->type = BSP_VAL_STRING;
}
return;
}
void value_set_object(BSP_VALUE *val, BSP_OBJECT *obj)
{
if (val && obj)
{
val->rval = (void *) obj;
val->type = BSP_VAL_OBJECT;
}
return;
}
void value_set_null(BSP_VALUE *val)
{
if (val)
{
val->type = BSP_VAL_NULL;
}
return;
}
// Get value from value
int64_t value_get_int(BSP_VALUE *val)
{
int64_t ret = 0;
if (val)
{
if (BSP_VAL_INT == val->type)
{
// int64
ret = get_vint(val->lval, NULL);
}
else if (BSP_VAL_INT29 == val->type)
{
// int29
ret = get_vint29(val->lval, NULL);
}
}
return ret;
}
int value_get_boolean(BSP_VALUE *val)
{
int ret = BSP_BOOLEAN_FALSE;
if (val && BSP_VAL_BOOLEAN_TRUE == val->type)
{
ret = BSP_BOOLEAN_TRUE;
}
return ret;
}
float value_get_float(BSP_VALUE *val)
{
float ret = 0.0;
if (val && BSP_VAL_FLOAT == val->type)
{
ret = get_float(val->rval);
}
return ret;
}
double value_get_double(BSP_VALUE *val)
{
double ret = 0.0;
if (val && BSP_VAL_DOUBLE == val->type)
{
ret = get_double(val->rval);
}
return ret;
}
void * value_get_pointer(BSP_VALUE *val)
{
void *ret = NULL;
if (val && BSP_VAL_POINTER == val->type)
{
ret = val->rval;
}
return ret;
}
BSP_STRING * value_get_string(BSP_VALUE *val)
{
BSP_STRING *ret = NULL;
if (val && BSP_VAL_STRING == val->type)
{
ret = (BSP_STRING *) val->rval;
}
return ret;
}
BSP_OBJECT * value_get_object(BSP_VALUE *val)
{
BSP_OBJECT *ret = NULL;
if (val && BSP_VAL_OBJECT == val->type)
{
ret = (BSP_OBJECT *) val->rval;
}
return ret;
}
/* Object & Value */
BSP_OBJECT * new_object(char type)
{
BSP_OBJECT *obj = bsp_calloc(1, sizeof(BSP_OBJECT));
if (obj)
{
obj->type = type;
bsp_spin_init(&obj->lock);
}
return obj;
}
void del_object(BSP_OBJECT *obj)
{
if (!obj)
{
return;
}
BSP_VALUE *val = NULL;
struct bsp_array_t *array = NULL;
struct bsp_hash_t *hash = NULL;
struct bsp_hash_item_t *item = NULL, *old = NULL;
size_t idx, bucket, seq;
bsp_spin_lock(&obj->lock);
switch (obj->type)
{
case OBJECT_TYPE_SINGLE :
val = (BSP_VALUE *) obj->node;
del_value(val);
break;
case OBJECT_TYPE_ARRAY :
array = (struct bsp_array_t *) obj->node;
if (array)
{
for (idx = 0; idx < array->nitems; idx ++)
{
bucket = (idx / ARRAY_BUCKET_SIZE);
seq = idx % ARRAY_BUCKET_SIZE;
if (bucket < array->nbuckets && array->items[bucket])
{
val = array->items[bucket][seq];
del_value(val);
}
}
bsp_free(array);
}
break;
case OBJECT_TYPE_HASH :
hash = (struct bsp_hash_t *) obj->node;
if (hash)
{
item = hash->head;
while (item)
{
del_string(item->key);
del_value(item->value);
old = item;
item = old->lnext;
bsp_free(old);
}
bsp_free(hash);
}
break;
case OBJECT_TYPE_UNDETERMINED :
default :
break;
}
bsp_spin_unlock(&obj->lock);
bsp_free(obj);
return;
}
BSP_VALUE * new_value()
{
return (BSP_VALUE *) bsp_calloc(1, sizeof(BSP_VALUE));
}
void del_value(BSP_VALUE *val)
{
if (val)
{
if (BSP_VAL_POINTER == val->type)
{
// Just ignore, we cannot determine what you are
}
else if (BSP_VAL_STRING == val->type)
{
del_string((BSP_STRING *) val->rval);
}
else if (BSP_VAL_OBJECT == val->type)
{
del_object((BSP_OBJECT *) val->rval);
}
else
{
// Local value, Just free
}
}
return bsp_free(val);
}
/* Item cursor operates */
// TODO : Not thread-safe, but maybe not neccessery
BSP_VALUE * curr_item(BSP_OBJECT *obj)
{
if (!obj)
{
return NULL;
}
BSP_VALUE *curr = NULL;
struct bsp_array_t *array = NULL;
struct bsp_hash_t *hash = NULL;
switch (obj->type)
{
case OBJECT_TYPE_SINGLE :
curr = (BSP_VALUE *) obj->node;
break;
case OBJECT_TYPE_ARRAY :
array = (struct bsp_array_t *) obj->node;
if (array)
{
size_t bucket = (array->curr / ARRAY_BUCKET_SIZE);
if (array->curr < array->nitems && bucket < array->nbuckets && array->items[bucket])
{
curr = array->items[bucket][array->curr % ARRAY_BUCKET_SIZE];
}
}
break;
case OBJECT_TYPE_HASH :
hash = (struct bsp_hash_t *) obj->node;
if (hash && hash->curr)
{
// Just value
// You can get current key with curr_item_key()
curr = hash->curr->value;
}
break;
default :
curr = NULL;
break;
}
return curr;
}
// Current array index
size_t curr_array_index(BSP_OBJECT *obj)
{
size_t idx = 0;
if (obj && OBJECT_TYPE_ARRAY == obj->type)
{
struct bsp_array_t *array = (struct bsp_array_t *) obj->node;
if (array)
{
idx = array->curr;
}
}
return idx;
}
// Current hash key
BSP_STRING * curr_hash_key(BSP_OBJECT *obj)
{
BSP_STRING *key = NULL;
if (obj && OBJECT_TYPE_HASH == obj->type)
{
struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node;
if (hash && hash->curr)
{
key = hash->curr->key;
}
}
return key;
}
size_t object_size(BSP_OBJECT *obj)
{
size_t ret = 0;
struct bsp_array_t *array = NULL;
struct bsp_hash_t *hash = NULL;
if (obj)
{
switch (obj->type)
{
case OBJECT_TYPE_SINGLE :
if (obj->node)
{
ret = 1;
}
break;
case OBJECT_TYPE_ARRAY :
array = (struct bsp_array_t *) obj->node;
if (array)
{
ret = array->nitems;
}
break;
case OBJECT_TYPE_HASH :
hash = (struct bsp_hash_t *) obj->node;
if (hash)
{
ret = hash->nitems;
}
break;
default :
break;
}
}
return ret;
}
void reset_object(BSP_OBJECT *obj)
{
if (!obj)
{
return;
}
struct bsp_array_t *array = NULL;
struct bsp_hash_t *hash = NULL;
switch (obj->type)
{
case OBJECT_TYPE_ARRAY :
array = (struct bsp_array_t *) obj->node;
if (array)
{
array->curr = 0;
}
break;
case OBJECT_TYPE_HASH :
hash = (struct bsp_hash_t *) obj->node;
if (hash)
{
hash->curr = hash->head;
}
break;
case OBJECT_TYPE_SINGLE :
default :
// Nothing to do
break;
}
return;
}
void next_item(BSP_OBJECT *obj)
{
if (!obj)
{
return;
}
struct bsp_array_t *array = NULL;
struct bsp_hash_t *hash = NULL;
switch (obj->type)
{
case OBJECT_TYPE_ARRAY :
array = (struct bsp_array_t *) obj->node;
if (array && array->curr < array->nitems)
{
array->curr ++;
}
break;
case OBJECT_TYPE_HASH :
hash = (struct bsp_hash_t *) obj->node;
if (hash && hash->curr)
{
hash->curr = hash->curr->lnext;
}
break;
case OBJECT_TYPE_SINGLE :
default :
// Nothing to NEXT
break;
}
return;
}
void prev_item(BSP_OBJECT *obj)
{
if (!obj)
{
return;
}
struct bsp_array_t *array = NULL;
struct bsp_hash_t *hash = NULL;
switch (obj->type)
{
case OBJECT_TYPE_ARRAY :
array = (struct bsp_array_t *) obj->node;
if (array && array->curr > 0)
{
array->curr --;
}
break;
case OBJECT_TYPE_HASH :
hash = (struct bsp_hash_t *) obj->node;
if (hash && hash->curr)
{
hash->curr = hash->curr->lprev;
}
break;
case OBJECT_TYPE_SINGLE :
default :
// Nothing to PREV
break;
}
}
/* Sort */
/*
inline static int __sort_compare(const char *v1,
size_t v1_len,
long long int v1_int,
const char *v2,
size_t v2_len,
long long int v2_int)
{
register int is_d1 = 1, is_d2 = 1;
if (v1_int == 0)
{
if (0 != strcmp(v1, "0"))
{
is_d1 = 0;
}
}
if (v2_int == 0)
{
if (0 != strcmp(v2, "0"))
{
is_d2 = 0;
}
}
if (is_d1 && is_d2)
{
if (v1_int > v2_int)
{
return 1;
}
else
{
return -1;
}
}
if (!is_d1 && !is_d2)
{
// Strings
if (v1_len > v2_len)
{
return memcmp(v1, v2, v2_len);
}
else
{
return memcmp(v1, v2, v1_len);
}
}
return (is_d1 > is_d2) ? -1 : 1;
}
inline static int _sort_compare(const char *v1,
size_t v1_len,
long long int v1_int,
const char *v2,
size_t v2_len,
long long int v2_int)
{
return (v1_len > v2_len) ? memcmp(v1, v2, v2_len) : memcmp(v1, v2, v1_len);
}
inline static void _sort_qsort(BSP_OBJECT_ITEM **list, size_t nitems)
{
int64_t begin_stack[256];
int64_t end_stack[256];
register int64_t begin;
register int64_t end;
register int64_t middle;
register int64_t pivot;
register int64_t seg1;
register int64_t seg2;
register int loop, c1, c2, c3;
register BSP_OBJECT_ITEM *tmp;
begin_stack[0] = 0;
end_stack[0] = nitems - 1;
for (loop = 0; loop >= 0; loop --)
{
begin = begin_stack[loop];
end = end_stack[loop];
while (begin < end)
{
// Find pivot
middle = (end - begin) >> 1;
c1 = _sort_compare(
list[begin]->key,
list[begin]->key_len,
list[begin]->key_int,
list[middle]->key,
list[middle]->key_len,
list[middle]->key_int);
c2 = _sort_compare(
list[middle]->key,
list[middle]->key_len,
list[middle]->key_int,
list[end]->key,
list[end]->key_len,
list[end]->key_int);
c3 = _sort_compare(
list[end]->key,
list[end]->key_len,
list[end]->key_int,
list[begin]->key,
list[begin]->key_len,
list[begin]->key_int);
if (c1 >= 0)
{
pivot = (c2 >= 0) ? middle : ((c3 >= 0) ? begin : end);
}
else
{
pivot = (c2 < 0) ? middle : ((c3 < 0) ? begin : end);
}
if (pivot != begin)
{
// Swap pivot & begin
tmp = list[begin]; list[begin] = list[pivot]; list[pivot] = tmp;
}
seg1 = begin + 1;
seg2 = end;
while (1)
{
for (
;
seg1 < seg2 && _sort_compare(
list[begin]->key,
list[begin]->key_len,
list[begin]->key_int,
list[seg1]->key,
list[seg1]->key_len,
list[seg1]->key_int) > 0;
seg1 ++);
for (
;
seg2 >= seg1 && _sort_compare(
list[seg2]->key,
list[seg2]->key_len,
list[seg2]->key_int,
list[begin]->key,
list[begin]->key_len,
list[begin]->key_int) > 0;
seg2 --);
if (seg1 >= seg2)
{
break;
}
tmp = list[seg1]; list[seg1] = list[seg2]; list[seg2] = tmp;
seg1 ++;
seg2 --;
}
// Swap begin & seg2
tmp = list[begin]; list[begin] = list[seg2]; list[seg2] = tmp;
if ((seg2 - begin) <= (end - seg2))
{
if ((seg2 + 1) < end)
{
begin_stack[loop] = seg2 + 1;
end_stack[loop ++] = end;
}
end = seg2 - 1;
}
else
{
if ((seg2 - 1) > begin)
{
begin_stack[loop] = begin;
end_stack[loop ++] = seg2 - 1;
}
begin = seg2 + 1;
}
}
}
return;
}
// Quicksort
int sort_object(BSP_OBJECT *obj)
{
if (!obj || 2 > obj->nitems )
{
return BSP_RTN_ERROR_GENERAL;
}
// Make a copy of item link
BSP_OBJECT_ITEM **list = bsp_calloc(obj->nitems, sizeof(BSP_OBJECT_ITEM *));
if (!list)
{
return BSP_RTN_ERROR_MEMORY;
}
bsp_spin_lock(&obj->obj_lock);
BSP_OBJECT_ITEM *curr = NULL;
int i = 0;
reset_object(obj);
curr = curr_item(obj);
while (curr)
{
if (i > obj->nitems - 1)
{
break;
}
list[i ++] = curr;
next_item(obj);
curr = curr_item(obj);
}
_sort_qsort(list, obj->nitems);
// Relink item link
for (i = 1; i < obj->nitems - 1; i ++)
{
list[i]->lnext = list[i + 1];
list[i]->lprev = list[i - 1];
}
list[0]->lnext = list[1];
list[0]->lprev = NULL;
obj->head = list[0];
list[obj->nitems - 1]->lnext = NULL;
list[obj->nitems - 1]->lprev = list[obj->nitems - 2];
obj->tail = list[obj->nitems - 1];
bsp_spin_unlock(&obj->obj_lock);
bsp_free(list);
return BSP_RTN_SUCCESS;
}
*/
// Find item from hash
static inline struct bsp_hash_item_t * _find_hash(struct bsp_hash_t *hash, BSP_STRING *key)
{
struct bsp_hash_item_t *ret = NULL;
if (hash && key && hash->hash_table)
{
uint32_t hash_key = bsp_hash(STR_STR(key), STR_LEN(key));
struct bsp_hash_item_t *bucket = &hash->hash_table[hash_key % hash->hash_size];
struct bsp_hash_item_t *curr = bucket->next;
while (curr)
{
if (STR_IS_EQUAL(key, curr->key))
{
ret = curr;
break;
}
curr = curr->next;
}
}
return ret;
}
static inline struct bsp_hash_item_t * _find_hash_str(struct bsp_hash_t *hash, const char *key)
{
struct bsp_hash_item_t *ret = NULL;
if (hash && key && hash->hash_table)
{
uint32_t hash_key = bsp_hash(key, -1);
struct bsp_hash_item_t *bucket = &hash->hash_table[hash_key % hash->hash_size];
struct bsp_hash_item_t *curr = bucket->next;
while (curr)
{
if (0 == strncmp(key, STR_STR(curr->key), STR_LEN(curr->key)))
{
ret = curr;
break;
}
curr = curr->next;
}
}
return ret;
}
// Remove item from hash
static inline int _remove_hash(struct bsp_hash_t *hash, BSP_STRING *key)
{
int ret = 0;
struct bsp_hash_item_t *item = _find_hash(hash, key);
if (item)
{
if (hash->head == item)
{
hash->head = item->lnext;
}
if (hash->tail == item)
{
hash->tail = item->lprev;
}
if (hash->curr == item)
{
hash->curr = item->lnext;
}
if (item->lnext)
{
item->lnext->lprev = item->lprev;
}
if (item->next)
{
item->next->prev = item->prev;
}
if (item->lprev)
{
item->lprev->lnext = item->lnext;
}
if (item->prev)
{
item->prev->next = item->next;
}
ret = 1;
// Delete item
del_value(item->value);
del_string(item->key);
bsp_free(item);
item = NULL;
}
return ret;
}
static inline int _remove_hash_str(struct bsp_hash_t *hash, const char *key)
{
int ret = 0;
struct bsp_hash_item_t *item = _find_hash_str(hash, key);
if (item)
{
if (hash->head == item)
{
hash->head = item->lnext;
}
if (hash->tail == item)
{
hash->tail = item->lprev;
}
if (hash->curr == item)
{
hash->curr = item->lnext;
}
if (item->lnext)
{
item->lnext->lprev = item->lprev;
}
if (item->next)
{
item->next->prev = item->prev;
}
if (item->lprev)
{
item->lprev->lnext = item->lnext;
}
if (item->prev)
{
item->prev->next = item->next;
}
ret = 1;
// Delete item
del_value(item->value);
del_string(item->key);
bsp_free(item);
item = NULL;
}
return ret;
}
// Insert an item into hash
static int _insert_hash(struct bsp_hash_t *hash, BSP_STRING *key, BSP_VALUE *val)
{
int ret = 0;
if (hash && hash->hash_table && key && val)
{
struct bsp_hash_item_t *item = _find_hash(hash, key);
if (item)
{
// Just overwrite value
if (item->value)
{
del_value(item->value);
}
item->value = val;
}
else
{
item = bsp_calloc(1, sizeof(struct bsp_hash_item_t));
item->key = key;
item->value = val;
// Insert into link
if (!hash->head)
{
hash->head = item;
}
if (hash->tail)
{
hash->tail->lnext = item;
item->lprev = hash->tail;
}
hash->tail = item;
// Insert into hash table
uint32_t hash_key = bsp_hash(STR_STR(key), STR_LEN(key));
struct bsp_hash_item_t *bucket = &hash->hash_table[hash_key % hash->hash_size];
item->next = bucket->next;
item->prev = bucket;
bucket->next = item;
ret = 1;
}
}
return ret;
}
static int _insert_hash_str(struct bsp_hash_t *hash, const char *key, BSP_VALUE *val)
{
int ret = 0;
if (hash && hash->hash_table && key && val)
{
struct bsp_hash_item_t *item = _find_hash_str(hash, key);
if (item)
{
// Just overwrite value
if (item->value)
{
del_value(item->value);
}
item->value = val;
}
else
{
item = bsp_calloc(1, sizeof(struct bsp_hash_item_t));
item->key = new_string(key, -1);
item->value = val;
// Insert into link
if (!hash->head)
{
hash->head = item;
}
if (hash->tail)
{
hash->tail->lnext = item;
item->lprev = hash->tail;
}
hash->tail = item;
// Insert into hash table
uint32_t hash_key = bsp_hash(key, -1);
struct bsp_hash_item_t *bucket = &hash->hash_table[hash_key % hash->hash_size];
item->next = bucket->next;
item->prev = bucket;
bucket->next = item;
ret = 1;
}
}
return ret;
}
// Enlarge hash table, rebuild hash link
static void _rebuild_hash(struct bsp_hash_t *hash, size_t new_hash_size)
{
if (hash && new_hash_size)
{
if (new_hash_size == hash->hash_size)
{
return;
}
if (hash->hash_table)
{
bsp_free(hash->hash_table);
}
hash->hash_table = bsp_calloc(new_hash_size, sizeof(struct bsp_hash_item_t));
hash->hash_size = new_hash_size;
// Insert every item from link
struct bsp_hash_item_t *curr = hash->head;
struct bsp_hash_item_t *bucket;
uint32_t hash_key;
while (curr && curr->key)
{
hash_key = bsp_hash(STR_STR(curr->key), STR_LEN(curr->key));
bucket = &hash->hash_table[hash_key % hash->hash_size];
curr->next = bucket->next;
curr->prev = bucket;
bucket->next = curr;
curr = curr->lnext;
}
}
return;
}
// Evalute a single (Number / String / Boolean etc) to a object
void object_set_single(BSP_OBJECT *obj, BSP_VALUE *val)
{
if (obj && OBJECT_TYPE_SINGLE == obj->type)
{
bsp_spin_lock(&obj->lock);
if (obj->node)
{
BSP_VALUE *old = (BSP_VALUE *) obj->node;
del_value(old);
}
obj->node = (BSP_VALUE *) val;
bsp_spin_unlock(&obj->lock);
}
return;
}
// Add an item into array
void object_set_array(BSP_OBJECT *obj, ssize_t idx, BSP_VALUE *val)
{
if (obj && OBJECT_TYPE_ARRAY == obj->type)
{
bsp_spin_lock(&obj->lock);
struct bsp_array_t *array = (struct bsp_array_t *) obj->node;
if (!array)
{
// Make a new array
array = bsp_calloc(1, sizeof(struct bsp_array_t));
obj->node = (void *) array;
}
if (idx < 0)
{
idx = array->nitems;
}
size_t bucket = (idx / ARRAY_BUCKET_SIZE);
size_t seq = idx % ARRAY_BUCKET_SIZE;
size_t nbuckets = array->nbuckets;
if (bucket >= nbuckets)
{
// Enlarge buckets
nbuckets = 2 << (int) (log2(bucket + 1));
array->items = bsp_realloc(array->items, nbuckets * sizeof(struct BSP_VAL **));
size_t i;
for (i = array->nbuckets; i < nbuckets; i ++)
{
array->items[i] = NULL;
}
array->nbuckets = nbuckets;
}
if (!array->items[bucket])
{
// New bucket
array->items[bucket] = bsp_calloc(ARRAY_BUCKET_SIZE, sizeof(struct BSP_VAL *));
}
if (array->items[bucket][seq])
{
// Remove old value
del_value(array->items[bucket][seq]);
}
array->items[bucket][seq] = val;
if (idx >= array->nitems)
{
array->nitems = idx + 1;
}
bsp_spin_unlock(&obj->lock);
}
return;
}
// Insert / Remove an item into / from a hash
void object_set_hash(BSP_OBJECT *obj, BSP_STRING *key, BSP_VALUE *val)
{
if (obj && OBJECT_TYPE_HASH == obj->type && key)
{
bsp_spin_lock(&obj->lock);
struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node;
if (!hash)
{
// Make a new hash
hash = bsp_calloc(1, sizeof(struct bsp_hash_t));
hash->hash_size = HASH_SIZE_INITIAL;
hash->hash_table = bsp_calloc(HASH_SIZE_INITIAL, sizeof(struct bsp_hash_item_t));
obj->node = (void *) hash;
}
if (val)
{
// Insert
hash->nitems += _insert_hash(hash, key, val);
if (hash->nitems > 8 * hash->hash_size)
{
// Rehash
_rebuild_hash(hash, hash->hash_size * 8);
}
}
else
{
// Remove
hash->nitems -= _remove_hash(hash, key);
}
bsp_spin_unlock(&obj->lock);
}
return;
}
void object_set_hash_str(BSP_OBJECT *obj, const char *key, BSP_VALUE *val)
{
if (obj && OBJECT_TYPE_HASH == obj->type && key)
{
bsp_spin_lock(&obj->lock);
struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node;
if (!hash)
{
// Make a new hash
hash = bsp_calloc(1, sizeof(struct bsp_hash_t));
hash->hash_size = HASH_SIZE_INITIAL;
hash->hash_table = bsp_calloc(HASH_SIZE_INITIAL, sizeof(struct bsp_hash_item_t));
obj->node = (void *) hash;
}
if (val)
{
// Insert
hash->nitems += _insert_hash_str(hash, key, val);
if (hash->nitems > 8 * hash->hash_size)
{
// Rehash
_rebuild_hash(hash, hash->hash_size * 8);
}
}
else
{
// Remove
hash->nitems -= _remove_hash_str(hash, key);
}
bsp_spin_unlock(&obj->lock);
}
return;
}
// Get single value from object
BSP_VALUE * object_get_single(BSP_OBJECT *obj)
{
BSP_VALUE *ret = NULL;
if (obj && OBJECT_TYPE_SINGLE == obj->type)
{
bsp_spin_lock(&obj->lock);
ret = (BSP_VALUE *) obj->node;
bsp_spin_unlock(&obj->lock);
}
return ret;
}
// Get value from array by given index
BSP_VALUE * object_get_array(BSP_OBJECT *obj, size_t idx)
{
BSP_VALUE *ret = NULL;
if (obj && OBJECT_TYPE_ARRAY == obj->type)
{
bsp_spin_lock(&obj->lock);
struct bsp_array_t *array = (struct bsp_array_t *) obj->node;
size_t bucket = idx / ARRAY_BUCKET_SIZE;
size_t seq = idx % ARRAY_BUCKET_SIZE;
if (array && idx < array->nitems && bucket < array->nbuckets && array->items[bucket])
{
ret = array->items[bucket][seq];
}
bsp_spin_unlock(&obj->lock);
}
return ret;
}
// Get value from hash table
BSP_VALUE * object_get_hash(BSP_OBJECT *obj, BSP_STRING *key)
{
BSP_VALUE *ret = NULL;
if (obj && key && OBJECT_TYPE_HASH == obj->type)
{
bsp_spin_lock(&obj->lock);
struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node;
if (hash)
{
struct bsp_hash_item_t *item = _find_hash(hash, key);
if (item)
{
ret = item->value;
}
}
bsp_spin_unlock(&obj->lock);
}
return ret;
}
BSP_VALUE * object_get_hash_str(BSP_OBJECT *obj, const char *key)
{
BSP_VALUE *ret = NULL;
if (obj && key && OBJECT_TYPE_HASH == obj->type)
{
bsp_spin_lock(&obj->lock);
struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node;
if (hash)
{
struct bsp_hash_item_t *item = _find_hash_str(hash, key);
if (item)
{
ret = item->value;
}
}
bsp_spin_unlock(&obj->lock);
}
return ret;
}
/* Magic path */
BSP_VALUE * object_get_value(BSP_OBJECT *obj, const char *path)
{
if (!obj)
{
return NULL;
}
BSP_VALUE *ret = NULL;
BSP_VALUE *curr_val = NULL;
BSP_OBJECT *curr_obj = obj;
BSP_STRING *key = NULL;
size_t idx = 0;
size_t i;
ssize_t start = -1;
int invalid = 0;
unsigned char c;
char *endptr = NULL;
if (OBJECT_TYPE_SINGLE == obj->type)
{
// Return full
ret = object_get_single(obj);
}
else
{
if (!path || 0 == strlen(path))
{
// No path
}
else
{
// Parse path normally
for (i = 0; i <= strlen(path); i ++)
{
c = (unsigned char) path[i];
if ('.' == c || '\0' == c)
{
// Hash seg
if (start < i && start >= 0 && curr_obj)
{
if (OBJECT_TYPE_HASH == curr_obj->type)
{
key = new_string_const(path + start, (i - start));
curr_val = object_get_hash(curr_obj, key);
del_string(key);
if (!curr_val)
{
// False
invalid = 1;
break;
}
curr_obj = value_get_object(curr_val);
start = -1;
}
else if (OBJECT_TYPE_ARRAY == curr_obj->type)
{
idx = (size_t) strtoull(path + start, &endptr, 0);
if (!idx && (path + start) == endptr)
{
// No digital
invalid = 1;
break;
}
curr_val = object_get_array(curr_obj, idx);
if (!curr_val)
{
invalid = 1;
break;
}
curr_obj = value_get_object(curr_val);
start = -1;
}
else
{
// False
curr_val = object_get_single(curr_obj);
break;
}
}
else
{
invalid = 1;
break;
}
}
else
{
// Normal char
if (start < 0)
{
start = i;
}
}
}
if (!invalid)
{
ret = curr_val;
}
}
}
return ret;
}
/* Serializer & Unserializer */
static void _pack_key(BSP_STRING *str, BSP_STRING *key);
static void _pack_value(BSP_STRING *str, BSP_VALUE *val);
static void _pack_object(BSP_STRING *str, BSP_OBJECT *obj);
static void _pack_key(BSP_STRING *str, BSP_STRING *key)
{
if (str)
{
char buf[9];
if (key)
{
string_append(str, buf, set_vint(STR_LEN(key), buf));
string_append(str, STR_STR(key), STR_LEN(key));
}
else
{
string_append(str, buf, set_vint(strlen(NO_HASH_KEY), buf));
string_append(str, NO_HASH_KEY, -1);
}
}
return;
}
static void _pack_value(BSP_STRING *str, BSP_VALUE *val)
{
char tmp[9];
int tmp_len;
BSP_STRING *sub_str = NULL;
BSP_OBJECT *sub_obj = NULL;
if (val && str)
{
string_append(str, &val->type, 1);
switch (val->type)
{
case BSP_VAL_INT :
string_append(str, val->lval, vintlen(val->lval, -1));
break;
case BSP_VAL_FLOAT :
string_append(str, val->lval, sizeof(float));
break;
case BSP_VAL_DOUBLE :
string_append(str, val->lval, sizeof(float));
break;
case BSP_VAL_STRING :
sub_str = (BSP_STRING *) val->rval;
if (sub_str)
{
tmp_len = set_vint(STR_LEN(sub_str), tmp);
string_append(str, tmp, tmp_len);
string_append(str, STR_STR(sub_str), STR_LEN(sub_str));
}
else
{
tmp[0] = 0;
string_append(str, tmp, 1);
}
break;
case BSP_VAL_POINTER :
set_pointer(val->rval, tmp);
string_append(str, tmp, sizeof(void *));
break;
case BSP_VAL_OBJECT :
sub_obj = (BSP_OBJECT *) val->rval;
if (sub_obj)
{
_pack_object(str, sub_obj);
}
break;
case BSP_VAL_BOOLEAN_TRUE :
case BSP_VAL_BOOLEAN_FALSE :
case BSP_VAL_NULL :
case BSP_VAL_UNKNOWN :
default :
// No value
break;
}
}
return;
}
static void _pack_object(BSP_STRING *str, BSP_OBJECT *obj)
{
char value_type[1];
BSP_VALUE *val = NULL;
if (obj && str)
{
bsp_spin_lock(&obj->lock);
switch (obj->type)
{
case OBJECT_TYPE_SINGLE :
// A single value
value_type[0] = BSP_VAL_OBJECT_SINGLE;
string_append(str, value_type, 1);
// Push value
val = (BSP_VALUE *) obj->node;
_pack_value(str, val);
value_type[0] = BSP_VAL_OBJECT_SINGLE_END;
string_append(str, value_type, 1);
break;
case OBJECT_TYPE_ARRAY :
// Array
value_type[0] = BSP_VAL_OBJECT_ARRAY;
string_append(str, value_type, 1);
// Every item
struct bsp_array_t *array = (struct bsp_array_t *) obj->node;
size_t idx, bucket, seq;
if (array)
{
for (idx = 9; idx < array->nitems; idx ++)
{
bucket = idx / ARRAY_BUCKET_SIZE;
seq = idx % ARRAY_BUCKET_SIZE;
val = NULL;
if (bucket < array->nbuckets && array->items[bucket])
{
val = array->items[bucket][seq];
_pack_value(str, val);
}
else
{
// Empty
value_type[0] = BSP_VAL_NULL;
string_append(str, value_type, 1);
}
}
}
value_type[0] = BSP_VAL_OBJECT_ARRAY_END;
string_append(str, value_type, 1);
break;
case OBJECT_TYPE_HASH :
// Dict
value_type[0] = BSP_VAL_OBJECT_HASH;
string_append(str, value_type, 1);
// Traverse items
BSP_STRING *key;
reset_object(obj);
val = curr_item(obj);
while (val)
{
key = curr_hash_key(obj);
// Set key and value
_pack_key(str, key);
_pack_value(str, val);
next_item(obj);
val = curr_item(obj);
}
value_type[0] = BSP_VAL_OBJECT_HASH_END;
string_append(str, value_type, 1);
break;
case OBJECT_TYPE_UNDETERMINED :
default :
// Yaaaahhh~~~?
break;
}
bsp_spin_unlock(&obj->lock);
}
return;
}
BSP_STRING * object_serialize(BSP_OBJECT *obj)
{
BSP_STRING * ret = new_string(NULL, 0);
if (obj && ret)
{
_pack_object(ret, obj);
}
return ret;
}
static BSP_STRING * _unpack_key(BSP_STRING *str);
static BSP_VALUE * _unpack_value(BSP_STRING *str);
static BSP_OBJECT * _unpack_object(BSP_STRING *str);
static BSP_STRING * _unpack_key(BSP_STRING *str)
{
BSP_STRING *ret = NULL;
char *data;
if (str)
{
size_t left = STR_LEN(str) - str->cursor;
size_t vlen = 0;
if (left > 0)
{
data = STR_STR(str);
vlen = vintlen(data, left);
if (left >= vlen)
{
int nouse = 0;
int64_t str_len = get_vint(data, &nouse);
if (left >= vlen + str_len)
{
ret = new_string(data + vlen, str_len);
vlen += str_len;
}
}
}
str->cursor += vlen;
}
return ret;
}
static BSP_VALUE * _unpack_value(BSP_STRING *str)
{
BSP_VALUE *ret = NULL;
char *data;
char type;
if (str)
{
size_t left = STR_LEN(str) - str->cursor;
size_t vlen = 0;
BSP_OBJECT *obj = NULL;
if (left > 0)
{
// 1st byte : Type
type = STR_STR(str)[str->cursor];
data = STR_STR(str) + 1;
ret = new_value();
ret->type = type;
switch (type)
{
case BSP_VAL_INT :
vlen = vintlen(data, left - 1);
memcpy(ret->lval, data, vlen);
break;
case BSP_VAL_FLOAT :
vlen = (left > sizeof(float)) ? sizeof(float) : (left - 1);
memcpy(ret->lval, data, vlen);
break;
case BSP_VAL_DOUBLE :
vlen = (left > sizeof(double)) ? sizeof(double) : (left - 1);
memcpy(ret->lval, data, vlen);
break;
case BSP_VAL_STRING :
vlen = vintlen(data, left - 1);
if (left >= vlen)
{
int nouse = 0;
int64_t str_len = get_vint(data, &nouse);
if (left >= vlen + str_len)
{
ret->rval = (void *) new_string(data + vlen, str_len);
vlen += str_len;
}
}
break;
case BSP_VAL_POINTER :
vlen = (left > sizeof(void *)) ? sizeof(void *) : (left - 1);
memcpy(&ret->rval, data, vlen);
break;
case BSP_VAL_OBJECT :
obj = _unpack_object(str);
ret->rval = (void *) obj;
break;
case BSP_VAL_BOOLEAN_TRUE :
case BSP_VAL_BOOLEAN_FALSE :
case BSP_VAL_NULL :
case BSP_VAL_UNKNOWN :
default :
// Single values
break;
}
str->cursor += vlen + 1;
}
}
return ret;
}
static BSP_OBJECT * _unpack_object(BSP_STRING *str)
{
BSP_OBJECT *obj = NULL;
if (str)
{
bsp_spin_lock(&str->lock);
if (str->cursor < STR_LEN(str))
{
// Read first
BSP_VALUE *val = NULL;
BSP_STRING *key = NULL;
char type = STR_STR(str)[str->cursor];
obj = new_object(type);
str->cursor ++;
switch (type)
{
case BSP_VAL_OBJECT_SINGLE :
val = _unpack_value(str);
object_set_single(obj, val);
// Pass endding
str->cursor ++;
break;
case BSP_VAL_OBJECT_ARRAY :
while (1)
{
val = _unpack_value(str);
if (!val)
{
break;
}
if (str->cursor < STR_LEN(str) && BSP_VAL_OBJECT_ARRAY_END == STR_STR(str)[str->cursor])
{
// Endding
str->cursor ++;
break;
}
object_set_array(obj, -1, val);
}
break;
case BSP_VAL_OBJECT_HASH :
while (1)
{
// Read key first
key = _unpack_key(str);
if (!key)
{
break;
}
val = _unpack_value(str);
if (!val)
{
break;
}
if (str->cursor < STR_LEN(str) && BSP_VAL_OBJECT_HASH_END == STR_STR(str)[str->cursor])
{
// Endding
str->cursor ++;
break;
}
object_set_hash(obj, key, val);
}
break;
default :
break;
}
}
bsp_spin_unlock(&str->lock);
}
return obj;
}
BSP_OBJECT * object_unserialize(BSP_STRING *str)
{
BSP_OBJECT * ret = NULL;
if (str)
{
str->cursor = 0;
ret = _unpack_object(str);
}
return ret;
}
/* Object <-> LUA stack */
static void _push_value_to_lua(lua_State *s, BSP_VALUE *val);
static void _push_object_to_lua(lua_State *s, BSP_OBJECT *obj);
static void _push_value_to_lua(lua_State *s, BSP_VALUE *val)
{
if (!s)
{
return;
}
if (!val)
{
lua_pushnil(s);
return;
}
int v_intlen = 0;
uint64_t v_int = 0;
float v_float = 0.0;
double v_double = 0.0;
BSP_STRING *v_str = NULL;
void *v_ptr = NULL;
BSP_OBJECT *v_obj = NULL;
switch (val->type)
{
case BSP_VAL_INT :
v_int = get_vint(val->lval, &v_intlen);
lua_pushinteger(s, (lua_Integer) v_int);
break;
case BSP_VAL_FLOAT :
v_float = get_float(val->lval);
lua_pushnumber(s, (lua_Number) v_float);
break;
case BSP_VAL_DOUBLE :
v_double = get_double(val->lval);
lua_pushnumber(s, (lua_Number) v_double);
break;
case BSP_VAL_BOOLEAN_TRUE :
lua_pushboolean(s, BSP_BOOLEAN_TRUE);
break;
case BSP_VAL_BOOLEAN_FALSE :
lua_pushboolean(s, BSP_BOOLEAN_FALSE);
break;
case BSP_VAL_STRING :
v_str = (BSP_STRING *) val->rval;
lua_pushlstring(s, STR_STR(v_str), STR_LEN(v_str));
break;
case BSP_VAL_POINTER :
v_ptr = val->rval;
lua_pushlightuserdata(s, v_ptr);
break;
case BSP_VAL_OBJECT :
v_obj = (BSP_OBJECT *) val->rval;
_push_object_to_lua(s, v_obj);
break;
case BSP_VAL_NULL :
case BSP_VAL_UNKNOWN :
default :
lua_pushnil(s);
break;
}
return;
}
static void _push_object_to_lua(lua_State *s, BSP_OBJECT *obj)
{
if (!s)
{
return;
}
if (!obj)
{
lua_pushnil(s);
return;
}
BSP_VALUE *val = NULL;
BSP_STRING *key = NULL;
bsp_spin_lock(&obj->lock);
lua_checkstack(s, 1);
switch (obj->type)
{
case OBJECT_TYPE_SINGLE :
// Single value
val = (BSP_VALUE *) obj->node;
_push_value_to_lua(s, val);
break;
case OBJECT_TYPE_ARRAY :
// Array
lua_newtable(s);
struct bsp_array_t *array = (struct bsp_array_t *) obj->node;
size_t idx;
if (array)
{
for (idx = 0; idx < array->nitems; idx ++)
{
size_t bucket = idx / ARRAY_BUCKET_SIZE;
size_t seq = idx % ARRAY_BUCKET_SIZE;
if (bucket < array->nbuckets && array->items[bucket])
{
val = array->items[bucket][seq];
if (val)
{
lua_checkstack(s, 2);
lua_pushinteger(s, (lua_Integer) idx + 1);
_push_value_to_lua(s, val);
lua_settable(s, -3);
}
}
}
}
break;
case OBJECT_TYPE_HASH :
// Hash
lua_newtable(s);
reset_object(obj);
val = curr_item(obj);
while (val)
{
key = curr_hash_key(obj);
if (key)
{
lua_checkstack(s, 2);
lua_pushlstring(s, STR_STR(key), STR_LEN(key));
_push_value_to_lua(s, val);
if (lua_istable(s, -3))
{
lua_settable(s, -3);
}
}
next_item(obj);
val = curr_item(obj);
}
break;
case OBJECT_TYPE_UNDETERMINED :
default :
lua_pushnil(s);
break;
}
bsp_spin_unlock(&obj->lock);
return;
}
void object_to_lua_stack(lua_State *s, BSP_OBJECT *obj)
{
if (!obj || !s)
{
return;
}
_push_object_to_lua(s, obj);
return;
}
static BSP_VALUE * _lua_value_to_value(lua_State *s);
static BSP_OBJECT * _lua_table_to_object(lua_State *s);
static BSP_VALUE * _lua_value_to_value(lua_State *s)
{
if (!s)
{
return NULL;
}
BSP_VALUE *ret = new_value();
if (ret)
{
lua_Number v_number = 0;
int v_boolean = 0;
size_t str_len = 0;
const char *v_str = NULL;
void *v_ptr = NULL;
BSP_OBJECT *v_obj = NULL;
switch (lua_type(s, -1))
{
case LUA_TNIL :
value_set_null(ret);
break;
case LUA_TNUMBER :
v_number = lua_tonumber(s, -1);
if (v_number == (lua_Number)(int64_t) v_number)
{
// Integer
value_set_int(ret, (const int64_t) v_number);
}
else
{
// Double / Float
value_set_double(ret, (const double) v_number);
}
break;
case LUA_TBOOLEAN :
v_boolean = lua_toboolean(s, -1);
if (BSP_BOOLEAN_FALSE == v_boolean)
{
value_set_boolean_false(ret);
}
else
{
value_set_boolean_true(ret);
}
break;
case LUA_TSTRING :
v_str = lua_tolstring(s, -1, &str_len);
value_set_string(ret, new_string(v_str, str_len));
break;
case LUA_TUSERDATA :
v_ptr = lua_touserdata(s, -1);
value_set_pointer(ret, (const void *) v_ptr);
break;
case LUA_TTABLE :
v_obj = _lua_table_to_object(s);
value_set_object(ret, v_obj);
break;
default :
value_set_null(ret);
break;
}
}
return ret;
}
static BSP_OBJECT * _lua_table_to_object(lua_State *s)
{
if (!s || !lua_istable(s, -1))
{
return NULL;
}
BSP_OBJECT *ret = NULL;
BSP_VALUE *val = NULL;
// Is array or hash?
if (luaL_len(s, -1) == lua_table_size(s, -1))
{
// Array
ret = new_object(OBJECT_TYPE_ARRAY);
size_t idx;
for (idx = 1; idx <= luaL_len(s, -1); idx ++)
{
lua_rawgeti(s, -1, idx);
val = _lua_value_to_value(s);
object_set_array(ret, idx - 1, val);
}
}
else
{
// Hash
ret = new_object(OBJECT_TYPE_HASH);
const char *key_str = NULL;
size_t key_len = 0;
BSP_STRING *key = NULL;
lua_checkstack(s, 2);
lua_pushnil(s);
while (0 != lua_next(s, -2))
{
// Key
key_str = lua_tolstring(s, -2, &key_len);
key = new_string(key_str, key_len);
// Value
val = _lua_value_to_value(s);
object_set_hash(ret, key, val);
lua_pop(s, 1);
}
}
return ret;
}
BSP_OBJECT * lua_stack_to_object(lua_State *s)
{
if (!s)
{
return NULL;
}
BSP_OBJECT *ret = NULL;
if (lua_istable(s, -1))
{
// Array or hash
ret = _lua_table_to_object(s);
}
else
{
// Single
ret = new_object(OBJECT_TYPE_SINGLE);
object_set_single(ret, _lua_value_to_value(s));
}
return ret;
}
| drnp/bsp | src/lib/bsp-core/object.c | C | gpl-3.0 | 53,620 |
/**
* Copyright (c) 2012-2015 Piotr Sipika; see the AUTHORS file for more.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* See the COPYRIGHT file for more information.
*/
/* Defines the layout of the location structure */
#ifndef LXWEATHER_LOCATION_HEADER
#define LXWEATHER_LOCATION_HEADER
#include <glib.h>
#include <string.h>
/* */
#define LOCATIONINFO_GROUP_NAME "Location"
#define LOCATIONINFO_GROUP_NAME_LENGTH strlen(LOCATIONINFO_GROUP_NAME)
/* LocationInfo struct definition */
typedef struct
{
gchar * alias_;
gchar * city_;
gchar * state_;
gchar * country_;
gchar * woeid_;
gchar units_;
guint interval_;
gboolean enabled_;
} LocationInfo;
/* Configuration helpers */
typedef enum
{
ALIAS = 0,
CITY,
STATE,
COUNTRY,
WOEID,
UNITS,
INTERVAL,
ENABLED,
LOCATIONINFO_FIELD_COUNT
} LocationInfoField;
/* Defined in the .c file - specifies the array of field names */
extern const gchar * LocationInfoFieldNames[];
/**
* Provides the mechanism to free any data associated with
* the LocationInfo structure
*
* @param location Location entry to free.
*
*/
void
location_free(gpointer location);
/**
* Prints the contents of the supplied entry to stdout
*
* @param locatrion Location entry contents of which to print.
*
*/
void
location_print(gpointer location);
/**
* Sets the given property for the location
*
* @param location Pointer to the location to modify.
* @param property Name of the property to set.
* @param value Value to assign to the property.
* @param len Length of the value to assign to the property (think strlen())
*/
void
location_property_set(gpointer location,
const gchar * property,
const gchar * value,
gsize len);
/**
* Copies a location entry.
*
* @param dst Address of the pointer to the location to set.
* @param src Pointer to the location to use/copy.
*
* @note Destination is first freed, if non-NULL, otherwise a new allocation
* is made. Both source and destination locations must be released by
* the caller.
*/
void
location_copy(gpointer * dst, gpointer src);
#endif
| psipika/lxweather | src/location.h | C | gpl-3.0 | 2,872 |
/*
Copyright (C) 2016 Sergo Pasoevi.
This pragram is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Written by Sergo Pasoevi <[email protected]>
*/
#include "util.h"
#include <math.h>
/* Geometry helper functions */
double distance(int x1, int y1, int x2, int y2)
{
int dx = x1 - x2;
int dy = y1 - y2;
return sqrt(dx * dx + dy * dy);
}
void each_actor(struct engine *engine, TCOD_list_t lst,
void (*action)(struct engine *engine,
struct actor *actor))
{
struct actor **iterator;
for (iterator = (struct actor **) TCOD_list_begin(engine->actors);
iterator != (struct actor **) TCOD_list_end(engine->actors);
iterator++)
action(engine, *iterator);
}
const char *generate_name(const char *filename)
{
TCOD_namegen_parse(filename, TCOD_random_get_instance());
return TCOD_namegen_generate("Celtic male", false);
}
void free_name_generator(void)
{
TCOD_namegen_destroy();
}
| pasoev/dungeons | src/util.c | C | gpl-3.0 | 1,578 |
# FAQ Summary
1. General information and availability
1. What is the CImg Library ?
2. What platforms are supported ?
3. How is CImg distributed ?
4. What kind of people are concerned by CImg ?
5. What are the specificities of the CeCILL license ?
6. Who is behind CImg ?
2. C++ related questions
1. What is the level of C++ knowledge needed to use CImg ?
2. How to use CImg in my own C++ program ?
3. Why is CImg entirely contained in a single header file ?
3. Other resources
1. Translations
## 1. General information and availability
### 1.1. What is the CImg Library ?
The CImg Library is an open-source C++ toolkit for image processing.
It mainly consists in a (big) single header file CImg.h providing a set of C++ classes and functions that can be used in your own sources, to load/save, manage/process and display generic images. It's actually a very simple and pleasant toolkit for coding image processing stuff in C++ : Just include the header file CImg.h, and you are ready to handle images in your C++ programs.
### 1.2. What platforms are supported ?
CImg has been designed with portability in mind. It is regularly tested on different architectures and compilers, and should also work on any decent OS having a decent C++ compiler. Before each release, the CImg Library is compiled under these different configurations :
- PC Linux 32 bits, with g++.
- PC Windows 32 bits, with Visual C++ 6.0.
- PC Windows 32 bits, with Visual C++ Express Edition.
- Sun SPARC Solaris 32 bits, with g++.
- Mac PPC with OS X and g++.
CImg has a minimal number of dependencies. In its minimal version, it can be compiled only with standard C++ headers. Anyway, it has interesting extension capabilities and can use external libraries to perform specific tasks more efficiently (Fourier Transform computation using FFTW for instance).
### 1.3. How is CImg distributed ?
The CImg Library is freely distributed as a complete .zip compressed package, hosted at the CImg server.
The package is distributed under the CeCILL license.
This package contains :
- The main library file CImg.h (C++ header file).
- Several C++ source code showing examples of using CImg.
- A complete library documentation, in HTML and PDF formats.
- Additional library plug-ins that can be used to extend library capabilities for specific uses.
The CImg Library is a quite lightweight library which is easy to maintain (due to its particular structure), and thus has a fast rythm of release. A new version of the CImg package is released approximately every three months.
### 1.4. What kind of people are concerned by CImg ?
The CImg library is an image processing library, primarily intended for computer scientists or students working in the fields of image processing or computer vision, and knowing bases of C++. As the library is handy and really easy to use, it can be also used by any programmer needing occasional tools for dealing with images in C++, since there are no standard library yet for this purpose.
### 1.5. What are the specificities of the CeCILL license ?
The CeCILL license governs the use of the CImg Library. This is an open-source license which gives you rights to access, use, modify and redistribute the source code, under certains conditions. There are two different variants of the CeCILL license used in CImg (namely CeCILL and CeCILL-C, all open-source), corresponding to different constraints on the source files :
- The CeCILL-C license is the most permissive one, close to the GNU LGPL license, and applies only on the main library file CImg.h. Basically, this license allows to use CImg.h in a closed-source product without forcing you to redistribute the entire software source code. Anyway, if one modifies the CImg.h source file, one has to redistribute the modified version of the file that must be governed by the same CeCILL-C license.
- The CeCILL license applies to all other files (source examples, plug-ins and documentation) of the CImg Library package, and is close (even compatible) with the GNU GPL license. It does not allow the use of these files in closed-source products.
You are invited to read the complete descriptions of the the CeCILL-C and CeCILL licenses before releasing a software based on the CImg Library.
### 1.6. Who is behind CImg ?
CImg has been started by David Tschumperle at the beginning of his PhD thesis, in October 1999. He is still the main coordinator of the project. Since the first release, a growing number of contributors has appeared. Due to the very simple and compact form of the library, submitting a contribution is quite easy and can be fastly integrated into the supported releases. List of contributors can be found on the front page.
## 2. C++ related questions
### 2.1 What is the level of C++ knowledge needed to use CImg ?
The CImg Library has been designed using C++ templates and object-oriented programming techniques, but in a very accessible level. There are only public classes without any derivation (just like C structures) and there is at most one template parameter for each CImg class (defining the pixel type of the images). The design is simple but clean, making the library accessible even for non professional C++ programmers, while proposing strong extension capabilities for C++ experts.
### 2.2 How to use CImg in my own C++ program ?
Basically, you need to add these two lines in your C++ source code, in order to be able to work with CImg images :
```c++
#include "CImg.h"
using namespace cimg_library;
```
### 2.3 Why is CImg entirely contained in a single header file ?
People are often surprised to see that the complete code of the library is contained in a single (big) C++ header file CImg.h. There are good practical and technical reasons to do that. Some arguments are listed below to justify this approach, so (I hope) you won't think this is a awkwardly C++ design of the CImg library :
- First, the library is based on template datatypes (images with generic pixel type), meaning that the programmer is free to decide what type of image he instanciates in his code. Even if there are roughly a limited number of fully supported types (basically, the "atomic" types of C++ : unsigned char, int, float, ...), this is not imaginable to pre-compile the library classes and functions for all possible atomic datatypes, since many functions and methods can have two or three arguments having different template parameters. This really means a huge number of possible combinations. The size of the object binary file generated to cover all possible cases would be just colossal. Is the STL library a pre-compiled one ? No, CImg neither. CImg is not using a classical .cpp and .h mechanism, just like the STL. Architectures of C++ template-based libraries are somewhat special in this sense. This is a proven technical fact.
- Second, why CImg does not have several header files, just like the STL does (one for each class for instance) ? This would be possible of course. There are only 4 classes in CImg, the two most important being CImg<T> and CImgList<T> representing respectively an image and a collection of images. But contrary to the STL library, these two CImg classes are strongly inter-dependent. All CImg algorithms are actually not defined as separate functions acting on containers (as the STL does with his header <algorithm>), but are directly methods of the image and image collection classes. This inter-dependence practically means that you will undoubtly need these two main classes at the same time if you are using CImg. If they were defined in separate header files, you would be forced to include both of them. What is the gain then ? No gain.
Concerning the two other classes : You can disable the third most important class CImgDisplay of the CImg library, by setting the compilation macro cimg_display to 0, avoiding thus to compile this class if you don't use display capabilities of CImg in your code. But to be honest, this is a quite small class and doing this doesn't save much compilation time. The last and fourth class is CImgException, which is only few lines long and is obviously required in almost all methods of CImg. Including this one is mandatory.
As a consequence, having a single header file instead of several ones is just a way for you to avoid including all of them, without any consequences on compilation time. This is both good technical and practical reasons to do like this.
- Third, having a single header file has plenty of advantages : Simplicity for the user, and for the developers (maintenance is in fact easier). Look at the CImg.h file, it looks like a mess at a first glance, but it is in fact very well organized and structured. Finding pieces of code in CImg functions or methods is particularly easy and fast. Also, how about the fact that library installation problems just disappear ? Just bring CImg.h with you, put it in your source directory, and the library is ready to go !
I admit the compilation time of CImg-based programs can be sometime long, but don't think that it is due to the fact that you are using a single header file. Using several header files wouldn't arrange anything since you would need all of them. Having a pre-compiled library object would be the only solution to speed up compilation time, but it is not possible at all, due to the too much generic nature of the library.
## 3. Other resources
### 3.1 Translations
This FAQ has been translated to Serbo-Croatian language by Web Geeks .
| likev/CImg-docs | FAQ-Frequently-Asked-Questions.md | Markdown | gpl-3.0 | 9,558 |
{% extends "userspace/journal/base.html" %}
{% load i18n rules %}
{% block title %}{{ block.super }}{% endblock title %}
{% block breadcrumb %}{{ block.super }}
<li><a href="{% url 'userspace:journal:subscription:list' scope_current_journal.pk %}">{% trans "Abonnements" %}</a></li>
{% endblock breadcrumb %}
{% block section_title %}
{% trans "Abonnements" %}
{% endblock %}
{% block content_main %}
<ul class="tabs">
{% has_perm 'subscription.manage_individual_subscription' request.user scope_current_journal as can_manage_individual_subscription %}
{% has_perm 'subscription.manage_institutional_subscription' request.user scope_current_journal as can_manage_institutional_subscription %}
{% if can_manage_institutional_subscription %}
<li class="tabs__item{% if view.is_org_view %} tabs__item_active{% endif %}">
<a href="{% url 'userspace:journal:subscription:org_list' scope_current_journal.pk %}">{% trans "Institutionnels" %}</a>
</li>
{% endif %}
{% if can_manage_individual_subscription %}
<li class="tabs__item{% if not view.is_org_view %} tabs__item_active{% endif %}">
<a href="{% url 'userspace:journal:subscription:list' scope_current_journal.pk %}">{% trans "Individuels" %}</a>
</li>
{% endif %}
</ul>
{% endblock content_main %}
| erudit/zenon | eruditorg/templates/userspace/journal/subscription/base.html | HTML | gpl-3.0 | 1,281 |
// Copyright 2014 The go-krypton Authors
// This file is part of the go-krypton library.
//
// The go-krypton library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-krypton library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-krypton library. If not, see <http://www.gnu.org/licenses/>.
// Package trie implements Merkle Patricia Tries.
package trie
import (
"bytes"
"errors"
"fmt"
"hash"
"github.com/krypton/go-krypton/common"
"github.com/krypton/go-krypton/crypto"
"github.com/krypton/go-krypton/crypto/sha3"
"github.com/krypton/go-krypton/logger"
"github.com/krypton/go-krypton/logger/glog"
"github.com/krypton/go-krypton/rlp"
)
const defaultCacheCapacity = 800
var (
// The global cache stores decoded trie nodes by hash as they get loaded.
globalCache = newARC(defaultCacheCapacity)
// This is the known root hash of an empty trie.
emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
// This is the known hash of an empty state trie entry.
emptyState = crypto.Sha3Hash(nil)
)
var ErrMissingRoot = errors.New("missing root node")
// Database must be implemented by backing stores for the trie.
type Database interface {
DatabaseWriter
// Get returns the value for key from the database.
Get(key []byte) (value []byte, err error)
}
// DatabaseWriter wraps the Put method of a backing store for the trie.
type DatabaseWriter interface {
// Put stores the mapping key->value in the database.
// Implementations must not hold onto the value bytes, the trie
// will reuse the slice across calls to Put.
Put(key, value []byte) error
}
// Trie is a Merkle Patricia Trie.
// The zero value is an empty trie with no database.
// Use New to create a trie that sits on top of a database.
//
// Trie is not safe for concurrent use.
type Trie struct {
root node
db Database
*hasher
}
// New creates a trie with an existing root node from db.
//
// If root is the zero hash or the sha3 hash of an empty string, the
// trie is initially empty and does not require a database. Otherwise,
// New will panics if db is nil or root does not exist in the
// database. Accessing the trie loads nodes from db on demand.
func New(root common.Hash, db Database) (*Trie, error) {
trie := &Trie{db: db}
if (root != common.Hash{}) && root != emptyRoot {
if db == nil {
panic("trie.New: cannot use existing root without a database")
}
if v, _ := trie.db.Get(root[:]); len(v) == 0 {
return nil, ErrMissingRoot
}
trie.root = hashNode(root.Bytes())
}
return trie, nil
}
// Iterator returns an iterator over all mappings in the trie.
func (t *Trie) Iterator() *Iterator {
return NewIterator(t)
}
// Get returns the value for key stored in the trie.
// The value bytes must not be modified by the caller.
func (t *Trie) Get(key []byte) []byte {
key = compactHexDecode(key)
tn := t.root
for len(key) > 0 {
switch n := tn.(type) {
case shortNode:
if len(key) < len(n.Key) || !bytes.Equal(n.Key, key[:len(n.Key)]) {
return nil
}
tn = n.Val
key = key[len(n.Key):]
case fullNode:
tn = n[key[0]]
key = key[1:]
case nil:
return nil
case hashNode:
tn = t.resolveHash(n)
default:
panic(fmt.Sprintf("%T: invalid node: %v", tn, tn))
}
}
return tn.(valueNode)
}
// Update associates key with value in the trie. Subsequent calls to
// Get will return value. If value has length zero, any existing value
// is deleted from the trie and calls to Get will return nil.
//
// The value bytes must not be modified by the caller while they are
// stored in the trie.
func (t *Trie) Update(key, value []byte) {
k := compactHexDecode(key)
if len(value) != 0 {
t.root = t.insert(t.root, k, valueNode(value))
} else {
t.root = t.delete(t.root, k)
}
}
func (t *Trie) insert(n node, key []byte, value node) node {
if len(key) == 0 {
return value
}
switch n := n.(type) {
case shortNode:
matchlen := prefixLen(key, n.Key)
// If the whole key matches, keep this short node as is
// and only update the value.
if matchlen == len(n.Key) {
return shortNode{n.Key, t.insert(n.Val, key[matchlen:], value)}
}
// Otherwise branch out at the index where they differ.
var branch fullNode
branch[n.Key[matchlen]] = t.insert(nil, n.Key[matchlen+1:], n.Val)
branch[key[matchlen]] = t.insert(nil, key[matchlen+1:], value)
// Replace this shortNode with the branch if it occurs at index 0.
if matchlen == 0 {
return branch
}
// Otherwise, replace it with a short node leading up to the branch.
return shortNode{key[:matchlen], branch}
case fullNode:
n[key[0]] = t.insert(n[key[0]], key[1:], value)
return n
case nil:
return shortNode{key, value}
case hashNode:
// We've hit a part of the trie that isn't loaded yet. Load
// the node and insert into it. This leaves all child nodes on
// the path to the value in the trie.
//
// TODO: track whkrypton insertion changed the value and keep
// n as a hash node if it didn't.
return t.insert(t.resolveHash(n), key, value)
default:
panic(fmt.Sprintf("%T: invalid node: %v", n, n))
}
}
// Delete removes any existing value for key from the trie.
func (t *Trie) Delete(key []byte) {
k := compactHexDecode(key)
t.root = t.delete(t.root, k)
}
// delete returns the new root of the trie with key deleted.
// It reduces the trie to minimal form by simplifying
// nodes on the way up after deleting recursively.
func (t *Trie) delete(n node, key []byte) node {
switch n := n.(type) {
case shortNode:
matchlen := prefixLen(key, n.Key)
if matchlen < len(n.Key) {
return n // don't replace n on mismatch
}
if matchlen == len(key) {
return nil // remove n entirely for whole matches
}
// The key is longer than n.Key. Remove the remaining suffix
// from the subtrie. Child can never be nil here since the
// subtrie must contain at least two other values with keys
// longer than n.Key.
child := t.delete(n.Val, key[len(n.Key):])
switch child := child.(type) {
case shortNode:
// Deleting from the subtrie reduced it to another
// short node. Merge the nodes to avoid creating a
// shortNode{..., shortNode{...}}. Use concat (which
// always creates a new slice) instead of append to
// avoid modifying n.Key since it might be shared with
// other nodes.
return shortNode{concat(n.Key, child.Key...), child.Val}
default:
return shortNode{n.Key, child}
}
case fullNode:
n[key[0]] = t.delete(n[key[0]], key[1:])
// Check how many non-nil entries are left after deleting and
// reduce the full node to a short node if only one entry is
// left. Since n must've contained at least two children
// before deletion (otherwise it would not be a full node) n
// can never be reduced to nil.
//
// When the loop is done, pos contains the index of the single
// value that is left in n or -2 if n contains at least two
// values.
pos := -1
for i, cld := range n {
if cld != nil {
if pos == -1 {
pos = i
} else {
pos = -2
break
}
}
}
if pos >= 0 {
if pos != 16 {
// If the remaining entry is a short node, it replaces
// n and its key gets the missing nibble tacked to the
// front. This avoids creating an invalid
// shortNode{..., shortNode{...}}. Since the entry
// might not be loaded yet, resolve it just for this
// check.
cnode := t.resolve(n[pos])
if cnode, ok := cnode.(shortNode); ok {
k := append([]byte{byte(pos)}, cnode.Key...)
return shortNode{k, cnode.Val}
}
}
// Otherwise, n is replaced by a one-nibble short node
// containing the child.
return shortNode{[]byte{byte(pos)}, n[pos]}
}
// n still contains at least two values and cannot be reduced.
return n
case nil:
return nil
case hashNode:
// We've hit a part of the trie that isn't loaded yet. Load
// the node and delete from it. This leaves all child nodes on
// the path to the value in the trie.
//
// TODO: track whkrypton deletion actually hit a key and keep
// n as a hash node if it didn't.
return t.delete(t.resolveHash(n), key)
default:
panic(fmt.Sprintf("%T: invalid node: %v (%v)", n, n, key))
}
}
func concat(s1 []byte, s2 ...byte) []byte {
r := make([]byte, len(s1)+len(s2))
copy(r, s1)
copy(r[len(s1):], s2)
return r
}
func (t *Trie) resolve(n node) node {
if n, ok := n.(hashNode); ok {
return t.resolveHash(n)
}
return n
}
func (t *Trie) resolveHash(n hashNode) node {
if v, ok := globalCache.Get(n); ok {
return v
}
enc, err := t.db.Get(n)
if err != nil || enc == nil {
// TODO: This needs to be improved to properly distinguish errors.
// Disk I/O errors shouldn't produce nil (and cause a
// consensus failure or weird crash), but it is unclear how
// they could be handled because the entire stack above the trie isn't
// prepared to cope with missing state nodes.
if glog.V(logger.Error) {
glog.Errorf("Dangling hash node ref %x: %v", n, err)
}
return nil
}
dec := mustDecodeNode(n, enc)
if dec != nil {
globalCache.Put(n, dec)
}
return dec
}
// Root returns the root hash of the trie.
// Deprecated: use Hash instead.
func (t *Trie) Root() []byte { return t.Hash().Bytes() }
// Hash returns the root hash of the trie. It does not write to the
// database and can be used even if the trie doesn't have one.
func (t *Trie) Hash() common.Hash {
root, _ := t.hashRoot(nil)
return common.BytesToHash(root.(hashNode))
}
// Commit writes all nodes to the trie's database.
// Nodes are stored with their sha3 hash as the key.
//
// Committing flushes nodes from memory.
// Subsequent Get calls will load nodes from the database.
func (t *Trie) Commit() (root common.Hash, err error) {
if t.db == nil {
panic("Commit called on trie with nil database")
}
return t.CommitTo(t.db)
}
// CommitTo writes all nodes to the given database.
// Nodes are stored with their sha3 hash as the key.
//
// Committing flushes nodes from memory. Subsequent Get calls will
// load nodes from the trie's database. Calling code must ensure that
// the changes made to db are written back to the trie's attached
// database before using the trie.
func (t *Trie) CommitTo(db DatabaseWriter) (root common.Hash, err error) {
n, err := t.hashRoot(db)
if err != nil {
return (common.Hash{}), err
}
t.root = n
return common.BytesToHash(n.(hashNode)), nil
}
func (t *Trie) hashRoot(db DatabaseWriter) (node, error) {
if t.root == nil {
return hashNode(emptyRoot.Bytes()), nil
}
if t.hasher == nil {
t.hasher = newHasher()
}
return t.hasher.hash(t.root, db, true)
}
type hasher struct {
tmp *bytes.Buffer
sha hash.Hash
}
func newHasher() *hasher {
return &hasher{tmp: new(bytes.Buffer), sha: sha3.NewKeccak256()}
}
func (h *hasher) hash(n node, db DatabaseWriter, force bool) (node, error) {
hashed, err := h.replaceChildren(n, db)
if err != nil {
return hashNode{}, err
}
if n, err = h.store(hashed, db, force); err != nil {
return hashNode{}, err
}
return n, nil
}
// hashChildren replaces child nodes of n with their hashes if the encoded
// size of the child is larger than a hash.
func (h *hasher) replaceChildren(n node, db DatabaseWriter) (node, error) {
var err error
switch n := n.(type) {
case shortNode:
n.Key = compactEncode(n.Key)
if _, ok := n.Val.(valueNode); !ok {
if n.Val, err = h.hash(n.Val, db, false); err != nil {
return n, err
}
}
if n.Val == nil {
// Ensure that nil children are encoded as empty strings.
n.Val = valueNode(nil)
}
return n, nil
case fullNode:
for i := 0; i < 16; i++ {
if n[i] != nil {
if n[i], err = h.hash(n[i], db, false); err != nil {
return n, err
}
} else {
// Ensure that nil children are encoded as empty strings.
n[i] = valueNode(nil)
}
}
if n[16] == nil {
n[16] = valueNode(nil)
}
return n, nil
default:
return n, nil
}
}
func (h *hasher) store(n node, db DatabaseWriter, force bool) (node, error) {
// Don't store hashes or empty nodes.
if _, isHash := n.(hashNode); n == nil || isHash {
return n, nil
}
h.tmp.Reset()
if err := rlp.Encode(h.tmp, n); err != nil {
panic("encode error: " + err.Error())
}
if h.tmp.Len() < 32 && !force {
// Nodes smaller than 32 bytes are stored inside their parent.
return n, nil
}
// Larger nodes are replaced by their hash and stored in the database.
h.sha.Reset()
h.sha.Write(h.tmp.Bytes())
key := hashNode(h.sha.Sum(nil))
if db != nil {
err := db.Put(key, h.tmp.Bytes())
return key, err
}
return key, nil
}
| covertress/go-krypton | trie/trie.go | GO | gpl-3.0 | 13,056 |
#!/bin/csh
# ---------------------------------------------------------------------------
#
# Script to Read in a new substructure file to the database
#
# ---------------------------------------------------------------------------
#set verbose on
if ( $#argv != 1 ) then
echo "Usage: $0 FileRoot"
echo " FileROOT : The substructure information file (rootname without sdf extension)"
echo " The file is assumed to be in the current directory"
exit(1)
endif
#--------------------------------------------------------------------------
# Set up inputs, files and program
#--------------------------------------------------------------------------
# The program and the input file pattern
set CHEMPROG = $REACTROOT/bin/runchem.sh
set REFERENCE = $REACTROOT/programs/inputs/ReadSubsFromFile.inp
# The current input file and the standard (established) input file
set NEWFILE = $1
# The combined input file (all the substructures are formed again)
set STANDARDSUBFILE = standard
set STANDARD = $REACTROOT/data/mol/subs/standard.sdf
set TEMPDIR = $REACTROOT/tmp
set TEMPFILE = $REACTROOT/tmp/read.prg
set TEMPOUTFILE = $REACTROOT/tmp/read.out
set INFILE = $NEWFILE.sdf
#--------------------------------------------------------------------------
# Modify program and merge input data files
#--------------------------------------------------------------------------
sed "s/XXXXX/$NEWFILE/g"\
$REFERENCE >! $TEMPFILE
cat $INFILE > $STANDARD
#--------------------------------------------------------------------------
# Put Substructures in Database
#--------------------------------------------------------------------------
pushd $TEMPDIR
$CHEMPROG read < read.prg
rm $TEMPFILE
popd
mv $TEMPOUTFILE $NEWFILE.out
| blurock/REACT | programs/scripts/readsubs.sh | Shell | gpl-3.0 | 1,817 |
class Solution {
public:
string addBinary(string a, string b) {
string sum = "";
int carry = 0;
for (int i = a.size() - 1, j = b.size() - 1; i >= 0 || j >= 0; i--, j--) {
int m = (i >= 0 && a[i] == '1');
int n = (j >= 0 && b[j] == '1');
sum += to_string((m + n + carry) & 0x1); // &0x1 only get the last binary digit
//It's better to avoid pattern string = char + string in loop. Use s[i] to alter string.
//just directly writing the output string and reversing it at last.
carry = (m + n + carry) >> 1; // >>1 is /2
}
reverse(sum.begin(), sum.end());
if(carry) sum = '1' + sum;
else sum = '0' + sum; //in case of two null input string
size_t i=0;
while(sum[i] == '0' && i < sum.length()-1) i++;
sum = sum.substr(i);
return sum;
}
}; | zemli/Cpp-Tutorial | algorithm/string/Add Binary-optimized.cpp | C++ | gpl-3.0 | 1,206 |
---
title: "कांग्रेस का नया नारा 'अब होगा NYAY', चुनावी कैम्पेन लांच"
layout: item
category: ["politics"]
date: 2019-04-07T08:05:44.259Z
image: 1554624344259congress.jpg
---
<p>नई दिल्ली: कांग्रेस लोकसभा चुनाव के लिए रविवार को अपने प्रचार अभियान की औपचारिक रूप से शुरुआत की। इस अभियान के तहत पार्टी ने प्रिंट, इलेक्ट्रॉनिक और डिजिटल मीडिया माध्यमों पर दिए जाने वाले पार्टी के प्रचार अभियान का ब्यौरा पेश किया। कांग्रेस के वरिष्ठ नेता आनंद शर्मा की अध्यक्षता वाली प्रचार अभियान की समिति ने प्रचार अभियान का पूरा ब्यौरा देते हुए स्लोगन लॉन्च किया। स्लोगन की टैगलाइन है- अब होगा न्याय। न्याय कैम्पेन वीडियो के लिए लिरिक्स जावेद अख्तर ने लिखे हैं। निखिल अडवाणी ने इसे निर्देशित किया है।</p>
<div class="tw-container"><div class="tweet" data-tweet="1114790612199333888"></div></div>
<p>आनंद शर्मा ने कहा कि मोदी सरकार ने लोगों को सपने दिखाकर चकनाचूर किया। उन्होंने बताया कि 'परसेप्ट' नाम की एजेंसी चुनाव प्रचार अभियान की अगुवाई करेगी। इसके अलावा अन्य सहयोगी एजेंसियां हैं जिनमें निक्सन और डिजाइन बॉक्स हैं। उन्होंने कहा कि कैंपेन की खास बात है कि हम स्पेशल कंटेनर ट्रक का इस्तेमाल करेंगे।</p>
<div class="tw-container"><div class="tweet" data-tweet="1114798893240209408"></div></div>
<p>कांग्रेस अपने प्रचार अभियान में रोजगार, नौजवान, किसान और महिलाओं पर मुख्य रूप से केंद्रित रखेगी तथा विभिन्न मुद्दों को लेकर मोदी सरकार को घेरने पर भी जोर दिया।</p>
<div class="tw-container"><div class="tweet" data-tweet="1114797055937892352"></div></div> | InstantKhabar/_source | _source/news/2019-04-07-congress (1).html | HTML | gpl-3.0 | 3,103 |
{-# LANGUAGE FlexibleContexts, CPP, JavaScriptFFI #-}
module Carnap.GHCJS.Action.TreeDeductionCheck (treeDeductionCheckAction) where
import Lib hiding (content)
import Data.Tree
import Data.Either
import Data.Map as M (lookup,Map, toList)
import Data.IORef (IORef, readIORef, newIORef, writeIORef)
import Data.Typeable (Typeable)
import Data.Aeson.Types
import Data.Text (pack)
import qualified Text.Parsec as P (parse)
import Control.Monad.State (modify,get,execState,State)
import Control.Lens
import Control.Concurrent
import Control.Monad (mplus, (>=>))
import Control.Monad.IO.Class (liftIO)
import Carnap.Core.Unification.Unification (MonadVar,FirstOrder, applySub)
import Carnap.Core.Unification.ACUI (ACUI)
import Carnap.Core.Data.Types
import Carnap.Core.Data.Classes
import Carnap.Core.Data.Optics
import Carnap.Languages.ClassicalSequent.Syntax
import Carnap.Languages.ClassicalSequent.Parser
import Carnap.Languages.PurePropositional.Syntax
import Carnap.Languages.Util.LanguageClasses
import Carnap.Calculi.Util
import Carnap.Calculi.NaturalDeduction.Syntax
import Carnap.Calculi.NaturalDeduction.Checker
import Carnap.Calculi.Tableau.Data
import Carnap.Languages.PurePropositional.Logic (ofPropTreeSys)
import Carnap.Languages.PureFirstOrder.Logic (ofFOLTreeSys)
import Carnap.GHCJS.Util.ProofJS
import Carnap.GHCJS.SharedTypes
import GHCJS.DOM.HTMLElement (getInnerText, castToHTMLElement)
import GHCJS.DOM.Element (setInnerHTML, click, keyDown, input, setAttribute )
import GHCJS.DOM.Node (appendChild, removeChild, getParentNode, insertBefore, getParentElement)
import GHCJS.DOM.Types (Element, Document, IsElement)
import GHCJS.DOM.Document (createElement, getActiveElement)
import GHCJS.DOM.KeyboardEvent
import GHCJS.DOM.EventM
import GHCJS.DOM
import GHCJS.Types
treeDeductionCheckAction :: IO ()
treeDeductionCheckAction =
do initializeCallback "checkProofTreeInfo" njCheck
initElements getCheckers activateChecker
return ()
where njCheck = maybe (error "can't find PropNJ") id $ (\calc -> checkProofTree calc Nothing >=> return . fst) `ofPropTreeSys` "PropNJ"
getCheckers :: IsElement self => Document -> self -> IO [Maybe (Element, Element, Map String String)]
getCheckers w = genInOutElts w "div" "div" "treedeductionchecker"
activateChecker :: Document -> Maybe (Element, Element, Map String String) -> IO ()
activateChecker _ Nothing = return ()
activateChecker w (Just (i, o, opts)) = case (setupWith `ofPropTreeSys` sys)
`mplus` (setupWith `ofFOLTreeSys` sys)
of Just io -> io
Nothing -> error $ "couldn't parse tree system: " ++ sys
where sys = case M.lookup "system" opts of
Just s -> s
Nothing -> "propNK"
setupWith calc = do
mgoal <- parseGoal calc
let content = M.lookup "content" opts
root <- case (content >>= decodeJSON, mgoal) of
(Just val,_) -> let Just c = content in initRoot c o
(_, Just seq) | "prepopulate" `inOpts` opts ->
initRoot ("{\"label\": \"" ++ show (view rhs seq)
++ "\", \"rule\":\"\", \"forest\": []}") o
_ -> initRoot "{\"label\": \"\", \"rule\":\"\", \"forest\": []}" o
memo <- newIORef mempty
threadRef <- newIORef (Nothing :: Maybe ThreadId)
bw <- createButtonWrapper w o
let submit = submitTree w memo opts calc root mgoal
btStatus <- createSubmitButton w bw submit opts
if "displayJSON" `inOpts` opts
then do
Just displayDiv <- createElement w (Just "div")
setAttribute displayDiv "class" "jsonDisplay"
setAttribute displayDiv "contenteditable" "true"
val <- toCleanVal root
setInnerHTML displayDiv . Just $ toJSONString val
toggleDisplay <- newListener $ do
kbe <- event
isCtrl <- getCtrlKey kbe
code <- liftIO $ keyString kbe
liftIO $ print code
if isCtrl && code == "?"
then do
preventDefault
mparent <- getParentNode displayDiv
case mparent of
Just p -> removeChild o (Just displayDiv)
_ -> appendChild o (Just displayDiv)
return ()
else return ()
addListener o keyDown toggleDisplay False
updateRoot <- newListener $ liftIO $ do
Just json <- getInnerText (castToHTMLElement displayDiv)
replaceRoot root json
addListener displayDiv input updateRoot False
root `onChange` (\_ -> do
mfocus <- getActiveElement w
--don't update when the display is
--focussed, to avoid cursor jumping
if Just displayDiv /= mfocus then do
val <- toCleanVal root
setInnerHTML displayDiv . Just $ toJSONString val
else return ())
return ()
else return ()
initialCheck <- newListener $ liftIO $ do
forkIO $ do
threadDelay 500000
mr <- toCleanVal root
case mr of
Just r -> do (info,mseq) <- checkProofTree calc (Just memo) r
decorate root info
Just wrap <- getParentElement i
updateInfo calc mgoal mseq wrap
Nothing -> return ()
return ()
addListener i initialize initialCheck False --initial check in case we preload a tableau
doOnce i mutate False $ liftIO $ btStatus Edited
case M.lookup "init" opts of Just "now" -> dispatchCustom w i "initialize"; _ -> return ()
root `onChange` (\_ -> dispatchCustom w i "mutate")
root `onChange` (\_ -> checkOnChange memo threadRef calc mgoal i root)
parseGoal calc = do
let seqParse = parseSeqOver $ tbParseForm calc
case M.lookup "goal" opts of
Just s -> case P.parse seqParse "" s of
Left e -> do setInnerHTML i (Just $ "Couldn't Parse This Goal:" ++ s)
error "couldn't parse goal"
Right seq -> do setInnerHTML i (Just . tbNotation calc . show $ seq)
return $ Just seq
Nothing -> do setInnerHTML i (Just "Awaiting a proof")
return Nothing
updateInfo _ (Just goal) (Just seq) wrap | seq `seqSubsetUnify` goal = setAttribute wrap "class" "success"
updateInfo _ (Just goal) (Just seq) wrap = setAttribute wrap "class" "failure"
updateInfo calc Nothing (Just seq) wrap = setInnerHTML wrap (Just . tbNotation calc . show $ seq)
updateInfo _ Nothing Nothing wrap = setInnerHTML wrap (Just "Awaiting a proof")
updateInfo _ _ _ wrap = setAttribute wrap "class" ""
submitTree w memo opts calc root (Just seq) l =
do Just val <- liftIO $ toCleanVal root
case parse parseTreeJSON val of
Error s -> message $ "Something has gone wrong. Here's the error:" ++ s
Success tree -> case toProofTree calc tree of
Left _ | "exam" `inOpts` opts -> trySubmit w DeductionTree opts l (DeductionTreeData (pack (show seq)) tree (toList opts)) False
Left _ -> message "Something is wrong with the proof... Try again?"
Right prooftree -> do
validation <- liftIO $ hoReduceProofTreeMemo memo (structuralRestriction prooftree) prooftree
case validation of
Right seq' | "exam" `inOpts` opts || (seq' `seqSubsetUnify` seq)
-> trySubmit w DeductionTree opts l (DeductionTreeData (pack (show seq)) tree (toList opts)) (seq' `seqSubsetUnify` seq)
_ -> message "Something is wrong with the proof... Try again?"
checkOnChange :: ( ReLex lex
, Sequentable lex
, Inference rule lex sem
, FirstOrder (ClassicalSequentOver lex)
, ACUI (ClassicalSequentOver lex)
, MonadVar (ClassicalSequentOver lex) (State Int)
, StaticVar (ClassicalSequentOver lex)
, Schematizable (lex (ClassicalSequentOver lex))
, CopulaSchema (ClassicalSequentOver lex)
, Typeable sem
, Show rule
, PrismSubstitutionalVariable lex
, FirstOrderLex (lex (ClassicalSequentOver lex))
, StructuralOverride rule (ProofTree rule lex sem)
, StructuralInference rule lex (ProofTree rule lex sem)
) => ProofMemoRef lex sem rule -> IORef (Maybe ThreadId) -> TableauCalc lex sem rule
-> Maybe (ClassicalSequentOver lex (Sequent sem)) -> Element -> JSVal -> IO ()
checkOnChange memo threadRef calc mgoal i root = do
mt <- readIORef threadRef
case mt of Just t -> killThread t
Nothing -> return ()
t' <- forkIO $ do
threadDelay 500000
Just changedVal <- toCleanVal root
(theInfo, mseq) <- checkProofTree calc (Just memo) changedVal
decorate root theInfo
Just wrap <- getParentElement i
updateInfo calc mgoal mseq wrap
writeIORef threadRef (Just t')
toProofTree :: ( Typeable sem
, ReLex lex
, Sequentable lex
, StructuralOverride rule (ProofTree rule lex sem)
, Inference rule lex sem
) => TableauCalc lex sem rule -> Tree (String,String) -> Either (TreeFeedback lex) (ProofTree rule lex sem)
toProofTree calc (Node (l,r) f)
| all isRight parsedForest && isRight newNode = handleOverride <$> (Node <$> newNode <*> sequence parsedForest)
| isRight newNode = Left $ Node Waiting (map cleanTree parsedForest)
| Left n <- newNode = Left n
where parsedLabel = (SS . liftToSequent) <$> P.parse (tbParseForm calc) "" l
parsedRules = P.parse (tbParseRule calc) "" r
parsedForest = map (toProofTree calc) f
cleanTree (Left fs) = fs
cleanTree (Right fs) = fmap (const Waiting) fs
newNode = case ProofLine 0 <$> parsedLabel <*> parsedRules of
Right l -> Right l
Left e -> Left (Node (ProofError $ NoParse e 0) (map cleanTree parsedForest))
handleOverride f@(Node l fs) = case structuralOverride f (head (rule l)) of
Nothing -> f
Just rs -> Node (l {rule = rs}) fs
checkProofTree :: ( ReLex lex
, Sequentable lex
, Inference rule lex sem
, FirstOrder (ClassicalSequentOver lex)
, ACUI (ClassicalSequentOver lex)
, MonadVar (ClassicalSequentOver lex) (State Int)
, StaticVar (ClassicalSequentOver lex)
, Schematizable (lex (ClassicalSequentOver lex))
, CopulaSchema (ClassicalSequentOver lex)
, Typeable sem
, Show rule
, StructuralOverride rule (ProofTree rule lex sem)
, StructuralInference rule lex (ProofTree rule lex sem)
) => TableauCalc lex sem rule -> Maybe (ProofMemoRef lex sem rule) -> Value -> IO (Value, Maybe (ClassicalSequentOver lex (Sequent sem)))
checkProofTree calc mmemo v = case parse parseTreeJSON v of
Success t -> case toProofTree calc t of
Left feedback -> return (toInfo feedback, Nothing)
Right tree -> do (val,mseq) <- validateProofTree calc mmemo tree
return (toInfo val, mseq)
Error s -> do print (show v)
error s
validateProofTree :: ( ReLex lex
, Sequentable lex
, Inference rule lex sem
, FirstOrder (ClassicalSequentOver lex)
, ACUI (ClassicalSequentOver lex)
, MonadVar (ClassicalSequentOver lex) (State Int)
, StaticVar (ClassicalSequentOver lex)
, Schematizable (lex (ClassicalSequentOver lex))
, CopulaSchema (ClassicalSequentOver lex)
, Typeable sem
, Show rule
, StructuralInference rule lex (ProofTree rule lex sem)
) => TableauCalc lex sem rule -> Maybe (ProofMemoRef lex sem rule)
-> ProofTree rule lex sem -> IO (TreeFeedback lex, Maybe (ClassicalSequentOver lex (Sequent sem)))
validateProofTree calc mmemo t@(Node _ fs) = do rslt <- case mmemo of
Nothing -> return $ hoReduceProofTree (structuralRestriction t) t
Just memo -> hoReduceProofTreeMemo memo (structuralRestriction t) t
case rslt of
Left msg -> (,) <$> (Node <$> pure (ProofError msg) <*> mapM (validateProofTree calc mmemo >=> return . fst) fs)
<*> pure Nothing
Right seq -> (,) <$> (Node <$> pure (ProofData (tbNotation calc . show $ seq)) <*> mapM (validateProofTree calc mmemo >=> return . fst) fs)
<*> pure (Just seq)
| gleachkr/Carnap | Carnap-GHCJS/src/Carnap/GHCJS/Action/TreeDeductionCheck.hs | Haskell | gpl-3.0 | 15,280 |
/*
* Darmix-Core Copyright (C) 2013 Deremix
* Integrated Files: CREDITS.md and LICENSE.md
*/
#ifndef BLIZZLIKE_OBJECTACCESSOR_H
#define BLIZZLIKE_OBJECTACCESSOR_H
#include "Platform/Define.h"
#include "Policies/Singleton.h"
#include <ace/Thread_Mutex.h>
#include "Utilities/UnorderedMap.h"
#include "Policies/ThreadingModel.h"
#include "ByteBuffer.h"
#include "UpdateData.h"
#include "GridDefines.h"
#include "Object.h"
#include "Player.h"
#include <set>
class Creature;
class Corpse;
class Unit;
class GameObject;
class DynamicObject;
class WorldObject;
class Map;
template <class T>
class HashMapHolder
{
public:
typedef UNORDERED_MAP<uint64, T*> MapType;
typedef ACE_Thread_Mutex LockType;
typedef BlizzLike::GeneralLock<LockType > Guard;
static void Insert(T* o)
{
Guard guard(i_lock);
m_objectMap[o->GetGUID()] = o;
}
static void Remove(T* o)
{
Guard guard(i_lock);
m_objectMap.erase(o->GetGUID());
}
static T* Find(uint64 guid)
{
Guard guard(i_lock);
typename MapType::iterator itr = m_objectMap.find(guid);
return (itr != m_objectMap.end()) ? itr->second : NULL;
}
static MapType& GetContainer() { return m_objectMap; }
static LockType* GetLock() { return &i_lock; }
private:
//Non instanceable only static
HashMapHolder() {}
static LockType i_lock;
static MapType m_objectMap;
};
class ObjectAccessor : public BlizzLike::Singleton<ObjectAccessor, BlizzLike::ClassLevelLockable<ObjectAccessor, ACE_Thread_Mutex> >
{
friend class BlizzLike::OperatorNew<ObjectAccessor>;
ObjectAccessor();
~ObjectAccessor();
ObjectAccessor(const ObjectAccessor&);
ObjectAccessor& operator=(const ObjectAccessor&);
public:
typedef UNORDERED_MAP<uint64, Corpse*> Player2CorpsesMapType;
typedef UNORDERED_MAP<Player*, UpdateData>::value_type UpdateDataValueType;
// returns object if is in world
template<class T> static T* GetObjectInWorld(uint64 guid, T* /*typeSpecifier*/)
{
return HashMapHolder<T>::Find(guid);
}
// Player may be not in world while in ObjectAccessor
static Player* GetObjectInWorld(uint64 guid, Player* /*typeSpecifier*/)
{
Player* player = HashMapHolder<Player>::Find(guid);
if (player && player->IsInWorld())
return player;
return NULL;
}
static Unit* GetObjectInWorld(uint64 guid, Unit* /*typeSpecifier*/)
{
if (IS_PLAYER_GUID(guid))
return (Unit*)GetObjectInWorld(guid, (Player*)NULL);
if (IS_PET_GUID(guid))
return (Unit*)GetObjectInWorld(guid, (Pet*)NULL);
return (Unit*)GetObjectInWorld(guid, (Creature*)NULL);
}
// returns object if is in map
template<class T> static T* GetObjectInMap(uint64 guid, Map * map, T* /*typeSpecifier*/)
{
assert(map);
if (T * obj = GetObjectInWorld(guid, (T*)NULL))
if (obj->GetMap() == map)
return obj;
return NULL;
}
template<class T> static T* GetObjectInWorld(uint32 mapid, float x, float y, uint64 guid, T* /*fake*/)
{
T* obj = HashMapHolder<T>::Find(guid);
if (!obj || obj->GetMapId() != mapid)
return NULL;
CellPair p = BlizzLike::ComputeCellPair(x, y);
if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
{
sLog.outError("ObjectAccessor::GetObjectInWorld: invalid coordinates supplied X:%f Y:%f grid cell [%u:%u]", x, y, p.x_coord, p.y_coord);
return NULL;
}
CellPair q = BlizzLike::ComputeCellPair(obj->GetPositionX(),obj->GetPositionY());
if (q.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || q.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP)
{
sLog.outError("ObjectAccessor::GetObjecInWorld: object (GUID: %u TypeId: %u) has invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), q.x_coord, q.y_coord);
return NULL;
}
int32 dx = int32(p.x_coord) - int32(q.x_coord);
int32 dy = int32(p.y_coord) - int32(q.y_coord);
if (dx > -2 && dx < 2 && dy > -2 && dy < 2)
return obj;
else
return NULL;
}
// these functions return objects only if in map of specified object
static Object* GetObjectByTypeMask(WorldObject const&, uint64, uint32 typemask);
static Corpse* GetCorpse(WorldObject const& u, uint64 guid);
static GameObject* GetGameObject(WorldObject const& u, uint64 guid);
static DynamicObject* GetDynamicObject(WorldObject const& u, uint64 guid);
static Unit* GetUnit(WorldObject const&, uint64 guid);
static Creature* GetCreature(WorldObject const& u, uint64 guid);
static Pet* GetPet(WorldObject const&, uint64 guid);
static Player* GetPlayer(WorldObject const&, uint64 guid);
static Creature* GetCreatureOrPet(WorldObject const&, uint64);
// these functions return objects if found in whole world
// ACCESS LIKE THAT IS NOT THREAD SAFE
static Pet* FindPet(uint64);
static Player* FindPlayer(uint64);
static Unit* FindUnit(uint64);
Player* FindPlayerByName(const char* name);
// when using this, you must use the hashmapholder's lock
HashMapHolder<Player>::MapType& GetPlayers()
{
return HashMapHolder<Player>::GetContainer();
}
template<class T> void AddObject(T* object)
{
HashMapHolder<T>::Insert(object);
}
template<class T> void RemoveObject(T* object)
{
HashMapHolder<T>::Remove(object);
}
void RemoveObject(Player* pl)
{
HashMapHolder<Player>::Remove(pl);
RemoveUpdateObject((Object*)pl);
}
void SaveAllPlayers();
void AddUpdateObject(Object* obj)
{
Guard guard(i_updateGuard);
i_objects.insert(obj);
}
void RemoveUpdateObject(Object* obj)
{
Guard guard(i_updateGuard);
i_objects.erase(obj);
}
void Update(uint32 diff);
Corpse* GetCorpseForPlayerGUID(uint64 guid);
void RemoveCorpse(Corpse* corpse);
void AddCorpse(Corpse* corpse);
void AddCorpsesToGrid(GridPair const& gridpair, GridType& grid, Map* map);
Corpse* ConvertCorpseForPlayer(uint64 player_guid, bool insignia = false);
void RemoveOldCorpses();
typedef ACE_Thread_Mutex LockType;
typedef BlizzLike::GeneralLock<LockType> Guard;
private:
Player2CorpsesMapType i_player2corpse;
static void _buildChangeObjectForPlayer(WorldObject*, UpdateDataMapType&);
static void _buildPacket(Player*, Object*, UpdateDataMapType&);
void _update();
std::set<Object*> i_objects;
LockType i_updateGuard;
LockType i_corpseGuard;
};
#endif
| deremix/darmixcore | src/game/ObjectAccessor.h | C | gpl-3.0 | 7,431 |
#include "stdafx.h"
#include <gtest/gtest.h>
#include "MonsterHeadingCalculator.h"
namespace PacMan
{
namespace Logic
{
namespace Tests
{
using namespace Logic;
void test_calculate_sets_heading (
Row monster_row,
Column monster_column,
Row pacman_row,
Column pacman_column,
Heading expected )
{
// Arrange
MonsterHeadingCalculator sut{};
sut.monster_row = monster_row;
sut.monster_column = monster_column;
sut.pacman_row = pacman_row;
sut.pacman_column = pacman_column;
// Act
sut.calculate();
// Assert
Heading actual = sut.get_heading();
EXPECT_EQ(expected, actual);
}
TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_0_0_and_pac_man_1_1)
{
test_calculate_sets_heading(
Row{0},
Column{0},
Row{1},
Column{1},
Heading_Down);
}
TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_0_1_and_pac_man_1_1)
{
test_calculate_sets_heading(
Row{0},
Column{1},
Row{1},
Column{1},
Heading_Down);
}
TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_0_2_and_pac_man_1_1)
{
test_calculate_sets_heading(
Row{0},
Column{2},
Row{1},
Column{1},
Heading_Down);
}
TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_1_0_and_pac_man_1_1)
{
test_calculate_sets_heading(
Row{1},
Column{0},
Row{1},
Column{1},
Heading_Right);
}
TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_1_1_and_pac_man_1_1)
{
test_calculate_sets_heading(
Row{1},
Column{1},
Row{1},
Column{1},
Heading_Unknown);
}
TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_1_2_and_pac_man_1_1)
{
test_calculate_sets_heading(
Row{1},
Column{2},
Row{1},
Column{1},
Heading_Left);
}
TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_2_0_and_pac_man_1_1)
{
using namespace Logic;
test_calculate_sets_heading(
Row{2},
Column{0},
Row{1},
Column{1},
Heading_Up);
}
TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_2_1_and_pac_man_1_1)
{
test_calculate_sets_heading(
Row{2},
Column{1},
Row{1},
Column{1},
Heading_Up);
}
TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_2_2_and_pac_man_1_1)
{
test_calculate_sets_heading(
Row{2},
Column{2},
Row{1},
Column{1},
Heading_Up);
}
};
};
};
| tschroedter/cpp_examples | vs2015/Katas/KataPacMan/PacMan.Logic.Tests/MonsterHeadingCalculator.Tests.cpp | C++ | gpl-3.0 | 4,978 |
/** Author: Sharmin Akter **/
/** Created at: 4/30/2012 12:07:26 AM **/
#include<stdio.h>
int main()
{
int i,j,k,p,m,n,t;
while(scanf("%d",&t)==1)
{
for(i=1;i<=t;i++)
{
scanf("%d",&p);
if(p==2||p==3||p==5||p==7||p==13||p==17)
printf("Yes\n");
else
printf("No\n");
getchar();
}
}
return 0;
}
| sajinia/UVa-Online-Judge | Volume-11/1180-(2 numbery).cpp | C++ | gpl-3.0 | 437 |
"""
Tests for closeness centrality.
"""
import pytest
import networkx as nx
from networkx.testing import almost_equal
class TestClosenessCentrality:
@classmethod
def setup_class(cls):
cls.K = nx.krackhardt_kite_graph()
cls.P3 = nx.path_graph(3)
cls.P4 = nx.path_graph(4)
cls.K5 = nx.complete_graph(5)
cls.C4 = nx.cycle_graph(4)
cls.T = nx.balanced_tree(r=2, h=2)
cls.Gb = nx.Graph()
cls.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)])
F = nx.florentine_families_graph()
cls.F = F
cls.LM = nx.les_miserables_graph()
# Create random undirected, unweighted graph for testing incremental version
cls.undirected_G = nx.fast_gnp_random_graph(n=100, p=0.6, seed=123)
cls.undirected_G_cc = nx.closeness_centrality(cls.undirected_G)
def test_wf_improved(self):
G = nx.union(self.P4, nx.path_graph([4, 5, 6]))
c = nx.closeness_centrality(G)
cwf = nx.closeness_centrality(G, wf_improved=False)
res = {0: 0.25, 1: 0.375, 2: 0.375, 3: 0.25, 4: 0.222, 5: 0.333, 6: 0.222}
wf_res = {0: 0.5, 1: 0.75, 2: 0.75, 3: 0.5, 4: 0.667, 5: 1.0, 6: 0.667}
for n in G:
assert almost_equal(c[n], res[n], places=3)
assert almost_equal(cwf[n], wf_res[n], places=3)
def test_digraph(self):
G = nx.path_graph(3, create_using=nx.DiGraph())
c = nx.closeness_centrality(G)
cr = nx.closeness_centrality(G.reverse())
d = {0: 0.0, 1: 0.500, 2: 0.667}
dr = {0: 0.667, 1: 0.500, 2: 0.0}
for n in sorted(self.P3):
assert almost_equal(c[n], d[n], places=3)
assert almost_equal(cr[n], dr[n], places=3)
def test_k5_closeness(self):
c = nx.closeness_centrality(self.K5)
d = {0: 1.000, 1: 1.000, 2: 1.000, 3: 1.000, 4: 1.000}
for n in sorted(self.K5):
assert almost_equal(c[n], d[n], places=3)
def test_p3_closeness(self):
c = nx.closeness_centrality(self.P3)
d = {0: 0.667, 1: 1.000, 2: 0.667}
for n in sorted(self.P3):
assert almost_equal(c[n], d[n], places=3)
def test_krackhardt_closeness(self):
c = nx.closeness_centrality(self.K)
d = {
0: 0.529,
1: 0.529,
2: 0.500,
3: 0.600,
4: 0.500,
5: 0.643,
6: 0.643,
7: 0.600,
8: 0.429,
9: 0.310,
}
for n in sorted(self.K):
assert almost_equal(c[n], d[n], places=3)
def test_florentine_families_closeness(self):
c = nx.closeness_centrality(self.F)
d = {
"Acciaiuoli": 0.368,
"Albizzi": 0.483,
"Barbadori": 0.4375,
"Bischeri": 0.400,
"Castellani": 0.389,
"Ginori": 0.333,
"Guadagni": 0.467,
"Lamberteschi": 0.326,
"Medici": 0.560,
"Pazzi": 0.286,
"Peruzzi": 0.368,
"Ridolfi": 0.500,
"Salviati": 0.389,
"Strozzi": 0.4375,
"Tornabuoni": 0.483,
}
for n in sorted(self.F):
assert almost_equal(c[n], d[n], places=3)
def test_les_miserables_closeness(self):
c = nx.closeness_centrality(self.LM)
d = {
"Napoleon": 0.302,
"Myriel": 0.429,
"MlleBaptistine": 0.413,
"MmeMagloire": 0.413,
"CountessDeLo": 0.302,
"Geborand": 0.302,
"Champtercier": 0.302,
"Cravatte": 0.302,
"Count": 0.302,
"OldMan": 0.302,
"Valjean": 0.644,
"Labarre": 0.394,
"Marguerite": 0.413,
"MmeDeR": 0.394,
"Isabeau": 0.394,
"Gervais": 0.394,
"Listolier": 0.341,
"Tholomyes": 0.392,
"Fameuil": 0.341,
"Blacheville": 0.341,
"Favourite": 0.341,
"Dahlia": 0.341,
"Zephine": 0.341,
"Fantine": 0.461,
"MmeThenardier": 0.461,
"Thenardier": 0.517,
"Cosette": 0.478,
"Javert": 0.517,
"Fauchelevent": 0.402,
"Bamatabois": 0.427,
"Perpetue": 0.318,
"Simplice": 0.418,
"Scaufflaire": 0.394,
"Woman1": 0.396,
"Judge": 0.404,
"Champmathieu": 0.404,
"Brevet": 0.404,
"Chenildieu": 0.404,
"Cochepaille": 0.404,
"Pontmercy": 0.373,
"Boulatruelle": 0.342,
"Eponine": 0.396,
"Anzelma": 0.352,
"Woman2": 0.402,
"MotherInnocent": 0.398,
"Gribier": 0.288,
"MmeBurgon": 0.344,
"Jondrette": 0.257,
"Gavroche": 0.514,
"Gillenormand": 0.442,
"Magnon": 0.335,
"MlleGillenormand": 0.442,
"MmePontmercy": 0.315,
"MlleVaubois": 0.308,
"LtGillenormand": 0.365,
"Marius": 0.531,
"BaronessT": 0.352,
"Mabeuf": 0.396,
"Enjolras": 0.481,
"Combeferre": 0.392,
"Prouvaire": 0.357,
"Feuilly": 0.392,
"Courfeyrac": 0.400,
"Bahorel": 0.394,
"Bossuet": 0.475,
"Joly": 0.394,
"Grantaire": 0.358,
"MotherPlutarch": 0.285,
"Gueulemer": 0.463,
"Babet": 0.463,
"Claquesous": 0.452,
"Montparnasse": 0.458,
"Toussaint": 0.402,
"Child1": 0.342,
"Child2": 0.342,
"Brujon": 0.380,
"MmeHucheloup": 0.353,
}
for n in sorted(self.LM):
assert almost_equal(c[n], d[n], places=3)
def test_weighted_closeness(self):
edges = [
("s", "u", 10),
("s", "x", 5),
("u", "v", 1),
("u", "x", 2),
("v", "y", 1),
("x", "u", 3),
("x", "v", 5),
("x", "y", 2),
("y", "s", 7),
("y", "v", 6),
]
XG = nx.Graph()
XG.add_weighted_edges_from(edges)
c = nx.closeness_centrality(XG, distance="weight")
d = {"y": 0.200, "x": 0.286, "s": 0.138, "u": 0.235, "v": 0.200}
for n in sorted(XG):
assert almost_equal(c[n], d[n], places=3)
#
# Tests for incremental closeness centrality.
#
@staticmethod
def pick_add_edge(g):
u = nx.utils.arbitrary_element(g)
possible_nodes = set(g.nodes())
neighbors = list(g.neighbors(u)) + [u]
possible_nodes.difference_update(neighbors)
v = nx.utils.arbitrary_element(possible_nodes)
return (u, v)
@staticmethod
def pick_remove_edge(g):
u = nx.utils.arbitrary_element(g)
possible_nodes = list(g.neighbors(u))
v = nx.utils.arbitrary_element(possible_nodes)
return (u, v)
def test_directed_raises(self):
with pytest.raises(nx.NetworkXNotImplemented):
dir_G = nx.gn_graph(n=5)
prev_cc = None
edge = self.pick_add_edge(dir_G)
insert = True
nx.incremental_closeness_centrality(dir_G, edge, prev_cc, insert)
def test_wrong_size_prev_cc_raises(self):
with pytest.raises(nx.NetworkXError):
G = self.undirected_G.copy()
edge = self.pick_add_edge(G)
insert = True
prev_cc = self.undirected_G_cc.copy()
prev_cc.pop(0)
nx.incremental_closeness_centrality(G, edge, prev_cc, insert)
def test_wrong_nodes_prev_cc_raises(self):
with pytest.raises(nx.NetworkXError):
G = self.undirected_G.copy()
edge = self.pick_add_edge(G)
insert = True
prev_cc = self.undirected_G_cc.copy()
num_nodes = len(prev_cc)
prev_cc.pop(0)
prev_cc[num_nodes] = 0.5
nx.incremental_closeness_centrality(G, edge, prev_cc, insert)
def test_zero_centrality(self):
G = nx.path_graph(3)
prev_cc = nx.closeness_centrality(G)
edge = self.pick_remove_edge(G)
test_cc = nx.incremental_closeness_centrality(G, edge, prev_cc, insertion=False)
G.remove_edges_from([edge])
real_cc = nx.closeness_centrality(G)
shared_items = set(test_cc.items()) & set(real_cc.items())
assert len(shared_items) == len(real_cc)
assert 0 in test_cc.values()
def test_incremental(self):
# Check that incremental and regular give same output
G = self.undirected_G.copy()
prev_cc = None
for i in range(5):
if i % 2 == 0:
# Remove an edge
insert = False
edge = self.pick_remove_edge(G)
else:
# Add an edge
insert = True
edge = self.pick_add_edge(G)
# start = timeit.default_timer()
test_cc = nx.incremental_closeness_centrality(G, edge, prev_cc, insert)
# inc_elapsed = (timeit.default_timer() - start)
# print(f"incremental time: {inc_elapsed}")
if insert:
G.add_edges_from([edge])
else:
G.remove_edges_from([edge])
# start = timeit.default_timer()
real_cc = nx.closeness_centrality(G)
# reg_elapsed = (timeit.default_timer() - start)
# print(f"regular time: {reg_elapsed}")
# Example output:
# incremental time: 0.208
# regular time: 0.276
# incremental time: 0.00683
# regular time: 0.260
# incremental time: 0.0224
# regular time: 0.278
# incremental time: 0.00804
# regular time: 0.208
# incremental time: 0.00947
# regular time: 0.188
assert set(test_cc.items()) == set(real_cc.items())
prev_cc = test_cc
| SpaceGroupUCL/qgisSpaceSyntaxToolkit | esstoolkit/external/networkx/algorithms/centrality/tests/test_closeness_centrality.py | Python | gpl-3.0 | 10,220 |
/**
* This file is part of JsonFL.
*
* JsonFL is free software: you can redistribute it and/or modify it under the
* terms of the Lesser GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* JsonFL is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the Lesser GNU General Public License for more
* details.
*
* You should have received a copy of the Lesser GNU General Public License
* along with JsonFL. If not, see <http://www.gnu.org/licenses/>.
*/
package au.com.houliston.jsonfl;
/**
* Is thrown when the creation string for the JsonFL is invalid
*
* @author Trent Houliston
* @version 1.0
*/
public class InvalidJsonFLException extends Exception
{
/**
* Creates a new InvalidJsonFLException with the passed message
*
* @param message The message to set
*/
public InvalidJsonFLException(String message)
{
super(message);
}
/**
* Creates a new InvalidJsonFLException along with a message and a cause
*
* @param message The message to set
* @param cause The root cause which made this exception
*/
public InvalidJsonFLException(String message, Throwable cause)
{
super(message, cause);
}
}
| TrentHouliston/JsonFL | src/main/java/au/com/houliston/jsonfl/InvalidJsonFLException.java | Java | gpl-3.0 | 1,371 |
package edu.kit.iti.formal.mandatsverteilung.generierer;
import edu.kit.iti.formal.mandatsverteilung.datenhaltung.Bundestagswahl;
/**
* Modelliert eine Einschränkung an das Ergebnis des Generierers, dass der
* Bundestag eine bestimmte Größe haben soll.
*
* @author Jan
*
*/
public class SitzzahlEinschraenkung extends Einschraenkung {
public SitzzahlEinschraenkung(int wert, int abweichung) {
assert wert > 0;
assert abweichung > 0;
this.wert = wert;
this.abweichung = abweichung;
gewichtung = 1.0;
}
@Override
int ueberpruefeErgebnis(Bundestagswahl b) {
int tatsaechlicheSitzzahl = b.getSitzzahl();
int genauigkeit = RandomisierterGenerierer.getGenauigkeit();
double minD = (minDistance(genauigkeit * tatsaechlicheSitzzahl,
genauigkeit * wert, genauigkeit * abweichung));
return (int) (gewichtung * minD);
}
}
| Bundeswahlrechner/Bundeswahlrechner | mandatsverteilung/src/main/java/edu/kit/iti/formal/mandatsverteilung/generierer/SitzzahlEinschraenkung.java | Java | gpl-3.0 | 934 |
#include "definitions.h"
CustomWeakForm::CustomWeakForm(std::vector<std::string> newton_boundaries, double heatcap, double rho, double tau,
double lambda, double alpha, double temp_ext, MeshFunctionSharedPtr<double> sln_prev_time, bool JFNK) : WeakForm<double>(1, JFNK)
{
this->set_ext(sln_prev_time);
// Jacobian forms - volumetric.
add_matrix_form(new JacobianFormVol(0, 0, heatcap, rho, lambda, tau));
// Jacobian forms - surface.
add_matrix_form_surf(new JacobianFormSurf(0, 0, newton_boundaries, alpha, lambda));
// Residual forms - volumetric.
ResidualFormVol* res_form = new ResidualFormVol(0, heatcap, rho, lambda, tau);
add_vector_form(res_form);
// Residual forms - surface.
add_vector_form_surf(new ResidualFormSurf(0, newton_boundaries, alpha, lambda, temp_ext));
}
double CustomWeakForm::JacobianFormVol::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomVol<double> *e, Func<double> **ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * (heatcap * rho * u->val[i] * v->val[i] / tau
+ lambda * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]));
return result;
}
Ord CustomWeakForm::JacobianFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord> **ext) const
{
// Returning the sum of the degrees of the basis and test function plus two.
return Ord(10);
}
MatrixFormVol<double>* CustomWeakForm::JacobianFormVol::clone() const
{
return new CustomWeakForm::JacobianFormVol(*this);
}
double CustomWeakForm::JacobianFormSurf::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u,
Func<double> *v, GeomSurf<double> *e, Func<double> **ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * alpha * lambda * u->val[i] * v->val[i];
return result;
}
Ord CustomWeakForm::JacobianFormSurf::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v,
GeomSurf<Ord> *e, Func<Ord> **ext) const
{
// Returning the sum of the degrees of the basis and test function plus two.
return Ord(10);
}
MatrixFormSurf<double>* CustomWeakForm::JacobianFormSurf::clone() const
{
return new CustomWeakForm::JacobianFormSurf(*this);
}
double CustomWeakForm::ResidualFormVol::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomVol<double> *e, Func<double> **ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * (heatcap * rho * (u_ext[0]->val[i] - ext[0]->val[i]) * v->val[i] / tau
+ lambda * (u_ext[0]->dx[i] * v->dx[i] + u_ext[0]->dy[i] * v->dy[i]));
return result;
}
Ord CustomWeakForm::ResidualFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomVol<Ord> *e, Func<Ord> **ext) const
{
// Returning the sum of the degrees of the test function and solution plus two.
return Ord(10);
}
VectorFormVol<double>* CustomWeakForm::ResidualFormVol::clone() const
{
return new CustomWeakForm::ResidualFormVol(*this);
}
double CustomWeakForm::ResidualFormSurf::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v,
GeomSurf<double> *e, Func<double> **ext) const
{
double result = 0;
for (int i = 0; i < n; i++)
result += wt[i] * alpha * lambda * (u_ext[0]->val[i] - temp_ext) * v->val[i];
return result;
}
Ord CustomWeakForm::ResidualFormSurf::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v,
GeomSurf<Ord> *e, Func<Ord> **ext) const
{
// Returning the sum of the degrees of the test function and solution plus two.
return Ord(10);
}
VectorFormSurf<double>* CustomWeakForm::ResidualFormSurf::clone() const
{
return new CustomWeakForm::ResidualFormSurf(*this);
} | hpfem/hermes-tutorial | F-trilinos/03-trilinos-timedep/definitions.cpp | C++ | gpl-3.0 | 3,694 |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding unique constraint on 'Vendeur', fields ['code_permanent']
db.create_unique(u'encefal_vendeur', ['code_permanent'])
def backwards(self, orm):
# Removing unique constraint on 'Vendeur', fields ['code_permanent']
db.delete_unique(u'encefal_vendeur', ['code_permanent'])
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'encefal.exemplaire': {
'Meta': {'object_name': 'Exemplaire'},
'actif': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'date_creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'etat': ('django.db.models.fields.CharField', [], {'default': "'VENT'", 'max_length': '4'}),
'facture': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'exemplaires'", 'null': 'True', 'db_column': "'facture'", 'to': u"orm['encefal.Facture']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'livre': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'exemplaires'", 'db_column': "'livre'", 'to': u"orm['encefal.Livre']"}),
'prix': ('django.db.models.fields.IntegerField', [], {}),
'vendeur': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'exemplaires'", 'db_column': "'vendeur'", 'to': u"orm['encefal.Vendeur']"})
},
u'encefal.facture': {
'Meta': {'object_name': 'Facture'},
'actif': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'date_creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'employe': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'factures'", 'blank': 'True', 'db_column': "'employe'", 'to': u"orm['auth.User']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'session': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'factures'", 'blank': 'True', 'db_column': "'session'", 'to': u"orm['encefal.Session']"})
},
u'encefal.livre': {
'Meta': {'object_name': 'Livre'},
'actif': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'auteur': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'date_creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'edition': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'isbn': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '13', 'blank': 'True'}),
'titre': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'vendeur': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'livres'", 'symmetrical': 'False', 'through': u"orm['encefal.Exemplaire']", 'db_column': "'vendeur'", 'to': u"orm['encefal.Vendeur']"})
},
u'encefal.session': {
'Meta': {'object_name': 'Session'},
'actif': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'date_creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_debut': ('django.db.models.fields.DateField', [], {}),
'date_fin': ('django.db.models.fields.DateField', [], {}),
'date_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nom': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
},
u'encefal.vendeur': {
'Meta': {'object_name': 'Vendeur'},
'actif': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'code_permanent': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '12'}),
'date_creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nom': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'prenom': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'telephone': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'})
}
}
complete_apps = ['encefal'] | nilovna/EnceFAL | project/encefal/migrations/0003_auto__add_unique_vendeur_code_permanent.py | Python | gpl-3.0 | 8,651 |
# $Id$
# Copyright 2013 Matthew Wall
# See the file LICENSE.txt for your full rights.
#
# Thanks to Eddie De Pieri for the first Python implementation for WS-28xx.
# Eddie did the difficult work of decompiling HeavyWeather then converting
# and reverse engineering into a functional Python implementation. Eddie's
# work was based on reverse engineering of HeavyWeather 2800 v 1.54
#
# Thanks to Lucas Heijst for enumerating the console message types and for
# debugging the transceiver/console communication timing issues.
"""Classes and functions for interfacing with WS-28xx weather stations.
LaCrosse makes a number of stations in the 28xx series, including:
WS-2810, WS-2810U-IT
WS-2811, WS-2811SAL-IT, WS-2811BRN-IT, WS-2811OAK-IT
WS-2812, WS-2812U-IT
WS-2813
WS-2814, WS-2814U-IT
WS-2815, WS-2815U-IT
C86234
The station is also sold as the TFA Primus, TFA Opus, and TechnoLine.
HeavyWeather is the software provided by LaCrosse.
There are two versions of HeavyWeather for the WS-28xx series: 1.5.4 and 1.5.4b
Apparently there is a difference between TX59UN-1-IT and TX59U-IT models (this
identifier is printed on the thermo-hygro sensor).
HeavyWeather Version Firmware Version Thermo-Hygro Model
1.54 333 or 332 TX59UN-1-IT
1.54b 288, 262, 222 TX59U-IT
HeavyWeather provides the following weather station settings:
time display: 12|24 hour
temperature display: C|F
air pressure display: inhg|hpa
wind speed display: m/s|knots|bft|km/h|mph
rain display: mm|inch
recording interval: 1m
keep weather station in hi-speed communication mode: true/false
According to the HeavyWeatherPro User Manual (1.54, rev2), "Hi speed mode wears
down batteries on your display much faster, and similarly consumes more power
on the PC. We do not believe most users need to enable this setting. It was
provided at the request of users who prefer ultra-frequent uploads."
The HeavyWeatherPro 'CurrentWeather' view is updated as data arrive from the
console. The console sends current weather data approximately every 13
seconds.
Historical data are updated less frequently - every 2 hours in the default
HeavyWeatherPro configuration.
According to the User Manual, "The 2800 series weather station uses the
'original' wind chill calculation rather than the 2001 'North American'
formula because the original formula is international."
Apparently the station console determines when data will be sent, and, once
paired, the transceiver is always listening. The station console sends a
broadcast on the hour. If the transceiver responds, the station console may
continue to broadcast data, depending on the transceiver response and the
timing of the transceiver response.
According to the C86234 Operations Manual (Revision 7):
- Temperature and humidity data are sent to the console every 13 seconds.
- Wind data are sent to the temperature/humidity sensor every 17 seconds.
- Rain data are sent to the temperature/humidity sensor every 19 seconds.
- Air pressure is measured every 15 seconds.
Each tip of the rain bucket is 0.26 mm of rain.
The following information was obtained by logging messages from the ws28xx.py
driver in weewx and by capturing USB messages between Heavy Weather Pro for
ws2800 and the TFA Primus Weather Station via windows program USB sniffer
busdog64_v0.2.1.
Pairing
The transceiver must be paired with a console before it can receive data. Each
frame sent by the console includes the device identifier of the transceiver
with which it is paired.
Synchronizing
When the console and transceiver stop communicating, they can be synchronized
by one of the following methods:
- Push the SET button on the console
- Wait till the next full hour when the console sends a clock message
In each case a Request Time message is received by the transceiver from the
console. The 'Send Time to WS' message should be sent within ms (10 ms
typical). The transceiver should handle the 'Time SET' message then send a
'Time/Config written' message about 85 ms after the 'Send Time to WS' message.
When complete, the console and transceiver will have been synchronized.
Timing
Current Weather messages, History messages, getConfig/setConfig messages, and
setTime messages each have their own timing. Missed History messages - as a
result of bad timing - result in console and transceiver becoming out of synch.
Current Weather
The console periodically sends Current Weather messages, each with the latest
values from the sensors. The CommModeInterval determines how often the console
will send Current Weather messages.
History
The console records data periodically at an interval defined by the
HistoryInterval parameter. The factory default setting is 2 hours.
Each history record contains a timestamp. Timestamps use the time from the
console clock. The console can record up to 1797 history records.
Reading 1795 history records took about 110 minutes on a raspberry pi, for
an average of 3.6 seconds per history record.
Reading 1795 history records took 65 minutes on a synology ds209+ii, for
an average of 2.2 seconds per history record.
Reading 1750 history records took 19 minutes using HeavyWeatherPro on a
Windows 7 64-bit laptop.
Message Types
The first byte of a message determines the message type.
ID Type Length
01 ? 0x0f (15)
d0 SetRX 0x15 (21)
d1 SetTX 0x15 (21)
d5 SetFrame 0x111 (273)
d6 GetFrame 0x111 (273)
d7 SetState 0x15 (21)
d8 SetPreamblePattern 0x15 (21)
d9 Execute 0x0f (15)
dc ReadConfigFlash< 0x15 (21)
dd ReadConfigFlash> 0x15 (21)
de GetState 0x0a (10)
f0 WriteReg 0x05 (5)
In the following sections, some messages are decomposed using the following
structure:
start position in message buffer
hi-lo data starts on first (hi) or second (lo) nibble
chars data length in characters (nibbles)
rem remark
name variable
-------------------------------------------------------------------------------
1. 01 message (15 bytes)
000: 01 15 00 0b 08 58 3f 53 00 00 00 00 ff 15 0b (detected via USB sniffer)
000: 01 15 00 57 01 92 3f 53 00 00 00 00 ff 15 0a (detected via USB sniffer)
00: messageID
02-15: ??
-------------------------------------------------------------------------------
2. SetRX message (21 bytes)
000: d0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
020: 00
00: messageID
01-20: 00
-------------------------------------------------------------------------------
3. SetTX message (21 bytes)
000: d1 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
020: 00
00: messageID
01-20: 00
-------------------------------------------------------------------------------
4. SetFrame message (273 bytes)
Action:
00: rtGetHistory - Ask for History message
01: rtSetTime - Ask for Send Time to weather station message
02: rtSetConfig - Ask for Send Config to weather station message
03: rtGetConfig - Ask for Config message
05: rtGetCurrent - Ask for Current Weather message
c0: Send Time - Send Time to WS
40: Send Config - Send Config to WS
000: d5 00 09 DevID 00 CfgCS cIntThisAdr xx xx xx rtGetHistory
000: d5 00 09 DevID 01 CfgCS cIntThisAdr xx xx xx rtReqSetTime
000: d5 00 09 f0 f0 02 CfgCS cIntThisAdr xx xx xx rtReqFirstConfig
000: d5 00 09 DevID 02 CfgCS cIntThisAdr xx xx xx rtReqSetConfig
000: d5 00 09 DevID 03 CfgCS cIntThisAdr xx xx xx rtGetConfig
000: d5 00 09 DevID 05 CfgCS cIntThisAdr xx xx xx rtGetCurrent
000: d5 00 0c DevID c0 CfgCS [TimeData . .. .. .. Send Time
000: d5 00 30 DevID 40 CfgCS [ConfigData .. .. .. Send Config
All SetFrame messages:
00: messageID
01: 00
02: Message Length (starting with next byte)
03-04: DeviceID [DevID]
05: Action
06-07: Config checksum [CfgCS]
Additional bytes rtGetCurrent, rtGetHistory, rtSetTime messages:
08-09hi: ComInt [cINT] 1.5 bytes (high byte first)
09lo-11: ThisHistoryAddress [ThisAdr] 2.5 bytes (high byte first)
Additional bytes Send Time message:
08: seconds
09: minutes
10: hours
11hi: DayOfWeek
11lo: day_lo (low byte)
12hi: month_lo (low byte)
12lo: day_hi (high byte)
13hi: (year-2000)_lo (low byte)
13lo: month_hi (high byte)
14lo: (year-2000)_hi (high byte)
-------------------------------------------------------------------------------
5. GetFrame message
Response type:
20: WS SetTime / SetConfig - Data written
40: GetConfig
60: Current Weather
80: Actual / Outstanding History
a1: Request First-Time Config
a2: Request SetConfig
a3: Request SetTime
000: 00 00 06 DevID 20 64 CfgCS xx xx xx xx xx xx xx xx xx Time/Config written
000: 00 00 30 DevID 40 64 [ConfigData .. .. .. .. .. .. .. GetConfig
000: 00 00 d7 DevID 60 64 CfgCS [CurData .. .. .. .. .. .. Current Weather
000: 00 00 1e DevID 80 64 CfgCS 0LateAdr 0ThisAdr [HisData Outstanding History
000: 00 00 1e DevID 80 64 CfgCS 0LateAdr 0ThisAdr [HisData Actual History
000: 00 00 06 DevID a1 64 CfgCS xx xx xx xx xx xx xx xx xx Request FirstConfig
000: 00 00 06 DevID a2 64 CfgCS xx xx xx xx xx xx xx xx xx Request SetConfig
000: 00 00 06 DevID a3 64 CfgCS xx xx xx xx xx xx xx xx xx Request SetTime
ReadConfig example:
000: 01 2e 40 5f 36 53 02 00 00 00 00 81 00 04 10 00 82 00 04 20
020: 00 71 41 72 42 00 05 00 00 00 27 10 00 02 83 60 96 01 03 07
040: 21 04 01 00 00 00 CfgCS
WriteConfig example:
000: 01 2e 40 64 36 53 02 00 00 00 00 00 10 04 00 81 00 20 04 00
020: 82 41 71 42 72 00 00 05 00 00 00 10 27 01 96 60 83 02 01 04
040: 21 07 03 10 00 00 CfgCS
00: messageID
01: 00
02: Message Length (starting with next byte)
03-04: DeviceID [devID]
05hi: responseType
06: Quality (in steps of 5)
Additional byte GetFrame messages except Request SetConfig and Request SetTime:
05lo: BatteryStat 8=WS bat low; 4=TMP bat low; 2=RAIN bat low; 1=WIND bat low
Additional byte Request SetConfig and Request SetTime:
05lo: RequestID
Additional bytes all GetFrame messages except ReadConfig and WriteConfig
07-08: Config checksum [CfgCS]
Additional bytes Outstanding History:
09lo-11: LatestHistoryAddress [LateAdr] 2.5 bytes (Latest to sent)
12lo-14: ThisHistoryAddress [ThisAdr] 2.5 bytes (Outstanding)
Additional bytes Actual History:
09lo-11: LatestHistoryAddress [ThisAdr] 2.5 bytes (LatestHistoryAddress is the)
12lo-14: ThisHistoryAddress [ThisAdr] 2.5 bytes (same as ThisHistoryAddress)
Additional bytes ReadConfig and WriteConfig
43-45: ResetMinMaxFlags (Output only; not included in checksum calculation)
46-47: Config checksum [CfgCS] (CheckSum = sum of bytes (00-42) + 7)
-------------------------------------------------------------------------------
6. SetState message
000: d7 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00: messageID
01-14: 00
-------------------------------------------------------------------------------
7. SetPreamblePattern message
000: d8 aa 00 00 00 00 00 00 00 00 00 00 00 00 00
00: messageID
01: ??
02-14: 00
-------------------------------------------------------------------------------
8. Execute message
000: d9 05 00 00 00 00 00 00 00 00 00 00 00 00 00
00: messageID
01: ??
02-14: 00
-------------------------------------------------------------------------------
9. ReadConfigFlash in - receive data
000: dc 0a 01 f5 00 01 78 a0 01 02 0a 0c 0c 01 2e ff ff ff ff ff - freq correction
000: dc 0a 01 f9 01 02 0a 0c 0c 01 2e ff ff ff ff ff ff ff ff ff - transceiver data
00: messageID
01: length
02-03: address
Additional bytes frequency correction
05lo-07hi: frequency correction
Additional bytes transceiver data
05-10: serial number
09-10: DeviceID [devID]
-------------------------------------------------------------------------------
10. ReadConfigFlash out - ask for data
000: dd 0a 01 f5 cc cc cc cc cc cc cc cc cc cc cc - Ask for freq correction
000: dd 0a 01 f9 cc cc cc cc cc cc cc cc cc cc cc - Ask for transceiver data
00: messageID
01: length
02-03: address
04-14: cc
-------------------------------------------------------------------------------
11. GetState message
000: de 14 00 00 00 00 (between SetPreamblePattern and first de16 message)
000: de 15 00 00 00 00 Idle message
000: de 16 00 00 00 00 Normal message
000: de 0b 00 00 00 00 (detected via USB sniffer)
00: messageID
01: stateID
02-05: 00
-------------------------------------------------------------------------------
12. Writereg message
000: f0 08 01 00 00 - AX5051RegisterNames.IFMODE
000: f0 10 01 41 00 - AX5051RegisterNames.MODULATION
000: f0 11 01 07 00 - AX5051RegisterNames.ENCODING
...
000: f0 7b 01 88 00 - AX5051RegisterNames.TXRATEMID
000: f0 7c 01 23 00 - AX5051RegisterNames.TXRATELO
000: f0 7d 01 35 00 - AX5051RegisterNames.TXDRIVER
00: messageID
01: register address
02: 01
03: AX5051RegisterName
04: 00
-------------------------------------------------------------------------------
13. Current Weather message
start hi-lo chars rem name
0 hi 4 DevID
2 hi 2 Action
3 hi 2 Quality
4 hi 4 DeviceCS
6 hi 4 6 _AlarmRingingFlags
8 hi 1 _WeatherTendency
8 lo 1 _WeatherState
9 hi 1 not used
9 lo 10 _TempIndoorMinMax._Max._Time
14 lo 10 _TempIndoorMinMax._Min._Time
19 lo 5 _TempIndoorMinMax._Max._Value
22 hi 5 _TempIndoorMinMax._Min._Value
24 lo 5 _TempIndoor (C)
27 lo 10 _TempOutdoorMinMax._Max._Time
32 lo 10 _TempOutdoorMinMax._Min._Time
37 lo 5 _TempOutdoorMinMax._Max._Value
40 hi 5 _TempOutdoorMinMax._Min._Value
42 lo 5 _TempOutdoor (C)
45 hi 1 not used
45 lo 10 1 _WindchillMinMax._Max._Time
50 lo 10 2 _WindchillMinMax._Min._Time
55 lo 5 1 _WindchillMinMax._Max._Value
57 hi 5 1 _WindchillMinMax._Min._Value
60 lo 6 _Windchill (C)
63 hi 1 not used
63 lo 10 _DewpointMinMax._Max._Time
68 lo 10 _DewpointMinMax._Min._Time
73 lo 5 _DewpointMinMax._Max._Value
76 hi 5 _DewpointMinMax._Min._Value
78 lo 5 _Dewpoint (C)
81 hi 10 _HumidityIndoorMinMax._Max._Time
86 hi 10 _HumidityIndoorMinMax._Min._Time
91 hi 2 _HumidityIndoorMinMax._Max._Value
92 hi 2 _HumidityIndoorMinMax._Min._Value
93 hi 2 _HumidityIndoor (%)
94 hi 10 _HumidityOutdoorMinMax._Max._Time
99 hi 10 _HumidityOutdoorMinMax._Min._Time
104 hi 2 _HumidityOutdoorMinMax._Max._Value
105 hi 2 _HumidityOutdoorMinMax._Min._Value
106 hi 2 _HumidityOutdoor (%)
107 hi 10 3 _RainLastMonthMax._Time
112 hi 6 3 _RainLastMonthMax._Max._Value
115 hi 6 _RainLastMonth (mm)
118 hi 10 3 _RainLastWeekMax._Time
123 hi 6 3 _RainLastWeekMax._Max._Value
126 hi 6 _RainLastWeek (mm)
129 hi 10 _Rain24HMax._Time
134 hi 6 _Rain24HMax._Max._Value
137 hi 6 _Rain24H (mm)
140 hi 10 _Rain24HMax._Time
145 hi 6 _Rain24HMax._Max._Value
148 hi 6 _Rain24H (mm)
151 hi 1 not used
152 lo 10 _LastRainReset
158 lo 7 _RainTotal (mm)
160 hi 1 _WindDirection5
160 lo 1 _WindDirection4
161 hi 1 _WindDirection3
161 lo 1 _WindDirection2
162 hi 1 _WindDirection1
162 lo 1 _WindDirection (0-15)
163 hi 18 unknown data
172 hi 6 _WindSpeed (km/h)
175 hi 1 _GustDirection5
175 lo 1 _GustDirection4
176 hi 1 _GustDirection3
176 lo 1 _GustDirection2
177 hi 1 _GustDirection1
177 lo 1 _GustDirection (0-15)
178 hi 2 not used
179 hi 10 _GustMax._Max._Time
184 hi 6 _GustMax._Max._Value
187 hi 6 _Gust (km/h)
190 hi 10 4 _PressureRelative_MinMax._Max/Min._Time
195 hi 5 5 _PressureRelative_inHgMinMax._Max._Value
197 lo 5 5 _PressureRelative_hPaMinMax._Max._Value
200 hi 5 _PressureRelative_inHgMinMax._Max._Value
202 lo 5 _PressureRelative_hPaMinMax._Max._Value
205 hi 5 _PressureRelative_inHgMinMax._Min._Value
207 lo 5 _PressureRelative_hPaMinMax._Min._Value
210 hi 5 _PressureRelative_inHg
212 lo 5 _PressureRelative_hPa
214 lo 430 end
Remarks
1 since factory reset
2 since software reset
3 not used?
4 should be: _PressureRelative_MinMax._Max._Time
5 should be: _PressureRelative_MinMax._Min._Time
6 _AlarmRingingFlags (values in hex)
80 00 = Hi Al Gust
40 00 = Al WindDir
20 00 = One or more WindDirs set
10 00 = Hi Al Rain24H
08 00 = Hi Al Outdoor Humidity
04 00 = Lo Al Outdoor Humidity
02 00 = Hi Al Indoor Humidity
01 00 = Lo Al Indoor Humidity
00 80 = Hi Al Outdoor Temp
00 40 = Lo Al Outdoor Temp
00 20 = Hi Al Indoor Temp
00 10 = Lo Al Indoor Temp
00 08 = Hi Al Pressure
00 04 = Lo Al Pressure
00 02 = not used
00 01 = not used
-------------------------------------------------------------------------------
14. History Message
start hi-lo chars rem name
0 hi 4 DevID
2 hi 2 Action
3 hi 2 Quality (%)
4 hi 4 DeviceCS
6 hi 6 LatestAddress
9 hi 6 ThisAddress
12 hi 1 not used
12 lo 3 Gust (m/s)
14 hi 1 WindDirection (0-15, also GustDirection)
14 lo 3 WindSpeed (m/s)
16 hi 3 RainCounterRaw (total in period in 0.1 inch)
17 lo 2 HumidityOutdoor (%)
18 lo 2 HumidityIndoor (%)
19 lo 5 PressureRelative (hPa)
22 hi 3 TempOutdoor (C)
23 lo 3 TempIndoor (C)
25 hi 10 Time
29 lo 60 end
-------------------------------------------------------------------------------
15. Set Config Message
start hi-lo chars rem name
0 hi 4 DevID
2 hi 2 Action
3 hi 2 Quality
4 hi 1 1 _WindspeedFormat
4 lo 0,25 2 _RainFormat
4 lo 0,25 3 _PressureFormat
4 lo 0,25 4 _TemperatureFormat
4 lo 0,25 5 _ClockMode
5 hi 1 _WeatherThreshold
5 lo 1 _StormThreshold
6 hi 1 _LowBatFlags
6 lo 1 6 _LCDContrast
7 hi 4 7 _WindDirAlarmFlags (reverse group 1)
9 hi 4 8 _OtherAlarmFlags (reverse group 1)
11 hi 10 _TempIndoorMinMax._Min._Value (reverse group 2)
_TempIndoorMinMax._Max._Value (reverse group 2)
16 hi 10 _TempOutdoorMinMax._Min._Value (reverse group 3)
_TempOutdoorMinMax._Max._Value (reverse group 3)
21 hi 2 _HumidityIndoorMinMax._Min._Value
22 hi 2 _HumidityIndoorMinMax._Max._Value
23 hi 2 _HumidityOutdoorMinMax._Min._Value
24 hi 2 _HumidityOutdoorMinMax._Max._Value
25 hi 1 not used
25 lo 7 _Rain24HMax._Max._Value (reverse bytes)
29 hi 2 _HistoryInterval
30 hi 1 not used
30 lo 5 _GustMax._Max._Value (reverse bytes)
33 hi 10 _PressureRelative_hPaMinMax._Min._Value (rev grp4)
_PressureRelative_inHgMinMax._Min._Value(rev grp4)
38 hi 10 _PressureRelative_hPaMinMax._Max._Value (rev grp5)
_PressureRelative_inHgMinMax._Max._Value(rev grp5)
43 hi 6 9 _ResetMinMaxFlags
46 hi 4 10 _InBufCS
47 lo 96 end
Remarks
1 0=m/s 1=knots 2=bft 3=km/h 4=mph
2 0=mm 1=inch
3 0=inHg 2=hPa
4 0=F 1=C
5 0=24h 1=12h
6 values 0-7 => LCD contrast 1-8
7 WindDir Alarms (not-reversed values in hex)
80 00 = NNW
40 00 = NW
20 00 = WNW
10 00 = W
08 00 = WSW
04 00 = SW
02 00 = SSW
01 00 = S
00 80 = SSE
00 40 = SE
00 20 = ESE
00 10 = E
00 08 = ENE
00 04 = NE
00 02 = NNE
00 01 = N
8 Other Alarms (not-reversed values in hex)
80 00 = Hi Al Gust
40 00 = Al WindDir
20 00 = One or more WindDirs set
10 00 = Hi Al Rain24H
08 00 = Hi Al Outdoor Humidity
04 00 = Lo Al Outdoor Humidity
02 00 = Hi Al Indoor Humidity
01 00 = Lo Al Indoor Humidity
00 80 = Hi Al Outdoor Temp
00 40 = Lo Al Outdoor Temp
00 20 = Hi Al Indoor Temp
00 10 = Lo Al Indoor Temp
00 08 = Hi Al Pressure
00 04 = Lo Al Pressure
00 02 = not used
00 01 = not used
9 ResetMinMaxFlags (not-reversed values in hex)
"Output only; not included in checksum calc"
80 00 00 = Reset DewpointMax
40 00 00 = Reset DewpointMin
20 00 00 = not used
10 00 00 = Reset WindchillMin*
"*Reset dateTime only; Min._Value is preserved"
08 00 00 = Reset TempOutMax
04 00 00 = Reset TempOutMin
02 00 00 = Reset TempInMax
01 00 00 = Reset TempInMin
00 80 00 = Reset Gust
00 40 00 = not used
00 20 00 = not used
00 10 00 = not used
00 08 00 = Reset HumOutMax
00 04 00 = Reset HumOutMin
00 02 00 = Reset HumInMax
00 01 00 = Reset HumInMin
00 00 80 = not used
00 00 40 = Reset Rain Total
00 00 20 = Reset last month?
00 00 10 = Reset lastweek?
00 00 08 = Reset Rain24H
00 00 04 = Reset Rain1H
00 00 02 = Reset PresRelMax
00 00 01 = Reset PresRelMin
10 Checksum = sum bytes (0-42) + 7
-------------------------------------------------------------------------------
16. Get Config Message
start hi-lo chars rem name
0 hi 4 DevID
2 hi 2 Action
3 hi 2 Quality
4 hi 1 1 _WindspeedFormat
4 lo 0,25 2 _RainFormat
4 lo 0,25 3 _PressureFormat
4 lo 0,25 4 _TemperatureFormat
4 lo 0,25 5 _ClockMode
5 hi 1 _WeatherThreshold
5 lo 1 _StormThreshold
6 hi 1 _LowBatFlags
6 lo 1 6 _LCDContrast
7 hi 4 7 _WindDirAlarmFlags
9 hi 4 8 _OtherAlarmFlags
11 hi 5 _TempIndoorMinMax._Min._Value
13 lo 5 _TempIndoorMinMax._Max._Value
16 hi 5 _TempOutdoorMinMax._Min._Value
18 lo 5 _TempOutdoorMinMax._Max._Value
21 hi 2 _HumidityIndoorMinMax._Max._Value
22 hi 2 _HumidityIndoorMinMax._Min._Value
23 hi 2 _HumidityOutdoorMinMax._Max._Value
24 hi 2 _HumidityOutdoorMinMax._Min._Value
25 hi 1 not used
25 lo 7 _Rain24HMax._Max._Value
29 hi 2 _HistoryInterval
30 hi 5 _GustMax._Max._Value
32 lo 1 not used
33 hi 5 _PressureRelative_hPaMinMax._Min._Value
35 lo 5 _PressureRelative_inHgMinMax._Min._Value
38 hi 5 _PressureRelative_hPaMinMax._Max._Value
40 lo 5 _PressureRelative_inHgMinMax._Max._Value
43 hi 6 9 _ResetMinMaxFlags
46 hi 4 10 _InBufCS
47 lo 96 end
Remarks
1 0=m/s 1=knots 2=bft 3=km/h 4=mph
2 0=mm 1=inch
3 0=inHg 2=hPa
4 0=F 1=C
5 0=24h 1=12h
6 values 0-7 => LCD contrast 1-8
7 WindDir Alarms (values in hex)
80 00 = NNW
40 00 = NW
20 00 = WNW
10 00 = W
08 00 = WSW
04 00 = SW
02 00 = SSW
01 00 = S
00 80 = SSE
00 40 = SE
00 20 = ESE
00 10 = E
00 08 = ENE
00 04 = NE
00 02 = NNE
00 01 = N
8 Other Alarms (values in hex)
80 00 = Hi Al Gust
40 00 = Al WindDir
20 00 = One or more WindDirs set
10 00 = Hi Al Rain24H
08 00 = Hi Al Outdoor Humidity
04 00 = Lo Al Outdoor Humidity
02 00 = Hi Al Indoor Humidity
01 00 = Lo Al Indoor Humidity
00 80 = Hi Al Outdoor Temp
00 40 = Lo Al Outdoor Temp
00 20 = Hi Al Indoor Temp
00 10 = Lo Al Indoor Temp
00 08 = Hi Al Pressure
00 04 = Lo Al Pressure
00 02 = not used
00 01 = not used
9 ResetMinMaxFlags (values in hex)
"Output only; input = 00 00 00"
10 Checksum = sum bytes (0-42) + 7
-------------------------------------------------------------------------------
Examples of messages
readCurrentWeather
Cur 000: 01 2e 60 5f 05 1b 00 00 12 01 30 62 21 54 41 30 62 40 75 36
Cur 020: 59 00 60 70 06 35 00 01 30 62 31 61 21 30 62 30 55 95 92 00
Cur 040: 53 10 05 37 00 01 30 62 01 90 81 30 62 40 90 66 38 00 49 00
Cur 060: 05 37 00 01 30 62 21 53 01 30 62 22 31 75 51 11 50 40 05 13
Cur 080: 80 13 06 22 21 40 13 06 23 19 37 67 52 59 13 06 23 06 09 13
Cur 100: 06 23 16 19 91 65 86 00 00 00 00 00 00 00 00 00 00 00 00 00
Cur 120: 00 00 00 00 00 00 00 00 00 13 06 23 09 59 00 06 19 00 00 51
Cur 140: 13 06 22 20 43 00 01 54 00 00 00 01 30 62 21 51 00 00 38 70
Cur 160: a7 cc 7b 50 09 01 01 00 00 00 00 00 00 fc 00 a7 cc 7b 14 13
Cur 180: 06 23 14 06 0e a0 00 01 b0 00 13 06 23 06 34 03 00 91 01 92
Cur 200: 03 00 91 01 92 02 97 41 00 74 03 00 91 01 92
WeatherState: Sunny(Good) WeatherTendency: Rising(Up) AlarmRingingFlags: 0000
TempIndoor 23.500 Min:20.700 2013-06-24 07:53 Max:25.900 2013-06-22 15:44
HumidityIndoor 59.000 Min:52.000 2013-06-23 19:37 Max:67.000 2013-06-22 21:40
TempOutdoor 13.700 Min:13.100 2013-06-23 05:59 Max:19.200 2013-06-23 16:12
HumidityOutdoor 86.000 Min:65.000 2013-06-23 16:19 Max:91.000 2013-06-23 06:09
Windchill 13.700 Min: 9.000 2013-06-24 09:06 Max:23.800 2013-06-20 19:08
Dewpoint 11.380 Min:10.400 2013-06-22 23:17 Max:15.111 2013-06-22 15:30
WindSpeed 2.520
Gust 4.320 Max:37.440 2013-06-23 14:06
WindDirection WSW GustDirection WSW
WindDirection1 SSE GustDirection1 SSE
WindDirection2 W GustDirection2 W
WindDirection3 W GustDirection3 W
WindDirection4 SSE GustDirection4 SSE
WindDirection5 SW GustDirection5 SW
RainLastMonth 0.000 Max: 0.000 1900-01-01 00:00
RainLastWeek 0.000 Max: 0.000 1900-01-01 00:00
Rain24H 0.510 Max: 6.190 2013-06-23 09:59
Rain1H 0.000 Max: 1.540 2013-06-22 20:43
RainTotal 3.870 LastRainReset 2013-06-22 15:10
PresRelhPa 1019.200 Min:1007.400 2013-06-23 06:34 Max:1019.200 2013-06-23 06:34
PresRel_inHg 30.090 Min: 29.740 2013-06-23 06:34 Max: 30.090 2013-06-23 06:34
Bytes with unknown meaning at 157-165: 50 09 01 01 00 00 00 00 00
-------------------------------------------------------------------------------
readHistory
His 000: 01 2e 80 5f 05 1b 00 7b 32 00 7b 32 00 0c 70 0a 00 08 65 91
His 020: 01 92 53 76 35 13 06 24 09 10
Time 2013-06-24 09:10:00
TempIndoor= 23.5
HumidityIndoor= 59
TempOutdoor= 13.7
HumidityOutdoor= 86
PressureRelative= 1019.2
RainCounterRaw= 0.0
WindDirection= SSE
WindSpeed= 1.0
Gust= 1.2
-------------------------------------------------------------------------------
readConfig
In 000: 01 2e 40 5f 36 53 02 00 00 00 00 81 00 04 10 00 82 00 04 20
In 020: 00 71 41 72 42 00 05 00 00 00 27 10 00 02 83 60 96 01 03 07
In 040: 21 04 01 00 00 00 05 1b
-------------------------------------------------------------------------------
writeConfig
Out 000: 01 2e 40 64 36 53 02 00 00 00 00 00 10 04 00 81 00 20 04 00
Out 020: 82 41 71 42 72 00 00 05 00 00 00 10 27 01 96 60 83 02 01 04
Out 040: 21 07 03 10 00 00 05 1b
OutBufCS= 051b
ClockMode= 0
TemperatureFormat= 1
PressureFormat= 1
RainFormat= 0
WindspeedFormat= 3
WeatherThreshold= 3
StormThreshold= 5
LCDContrast= 2
LowBatFlags= 0
WindDirAlarmFlags= 0000
OtherAlarmFlags= 0000
HistoryInterval= 0
TempIndoor_Min= 1.0
TempIndoor_Max= 41.0
TempOutdoor_Min= 2.0
TempOutdoor_Max= 42.0
HumidityIndoor_Min= 41
HumidityIndoor_Max= 71
HumidityOutdoor_Min= 42
HumidityOutdoor_Max= 72
Rain24HMax= 50.0
GustMax= 100.0
PressureRel_hPa_Min= 960.1
PressureRel_inHg_Min= 28.36
PressureRel_hPa_Max= 1040.1
PressureRel_inHg_Max= 30.72
ResetMinMaxFlags= 100000 (Output only; Input always 00 00 00)
-------------------------------------------------------------------------------
class EHistoryInterval:
Constant Value Message received at
hi01Min = 0 00:00, 00:01, 00:02, 00:03 ... 23:59
hi05Min = 1 00:00, 00:05, 00:10, 00:15 ... 23:55
hi10Min = 2 00:00, 00:10, 00:20, 00:30 ... 23:50
hi15Min = 3 00:00, 00:15, 00:30, 00:45 ... 23:45
hi20Min = 4 00:00, 00:20, 00:40, 01:00 ... 23:40
hi30Min = 5 00:00, 00:30, 01:00, 01:30 ... 23:30
hi60Min = 6 00:00, 01:00, 02:00, 03:00 ... 23:00
hi02Std = 7 00:00, 02:00, 04:00, 06:00 ... 22:00
hi04Std = 8 00:00, 04:00, 08:00, 12:00 ... 20:00
hi06Std = 9 00:00, 06:00, 12:00, 18:00
hi08Std = 0xA 00:00, 08:00, 16:00
hi12Std = 0xB 00:00, 12:00
hi24Std = 0xC 00:00
-------------------------------------------------------------------------------
WS SetTime - Send time to WS
Time 000: 01 2e c0 05 1b 19 14 12 40 62 30 01
time sent: 2013-06-24 12:14:19
-------------------------------------------------------------------------------
ReadConfigFlash data
Ask for frequency correction
rcfo 000: dd 0a 01 f5 cc cc cc cc cc cc cc cc cc cc cc
readConfigFlash frequency correction
rcfi 000: dc 0a 01 f5 00 01 78 a0 01 02 0a 0c 0c 01 2e ff ff ff ff ff
frequency correction: 96416 (0x178a0)
adjusted frequency: 910574957 (3646456d)
Ask for transceiver data
rcfo 000: dd 0a 01 f9 cc cc cc cc cc cc cc cc cc cc cc
readConfigFlash serial number and DevID
rcfi 000: dc 0a 01 f9 01 02 0a 0c 0c 01 2e ff ff ff ff ff ff ff ff ff
transceiver ID: 302 (0x012e)
transceiver serial: 01021012120146
Program Logic
The RF communication thread uses the following logic to communicate with the
weather station console:
Step 1. Perform in a while loop getState commands until state 0xde16
is received.
Step 2. Perform a getFrame command to read the message data.
Step 3. Handle the contents of the message. The type of message depends on
the response type:
Response type (hex):
20: WS SetTime / SetConfig - Data written
confirmation the setTime/setConfig setFrame message has been received
by the console
40: GetConfig
save the contents of the configuration for later use (i.e. a setConfig
message with one ore more parameters changed)
60: Current Weather
handle the weather data of the current weather message
80: Actual / Outstanding History
ignore the data of the actual history record when there is no data gap;
handle the data of a (one) requested history record (note: in step 4 we
can decide to request another history record).
a1: Request First-Time Config
prepare a setFrame first time message
a2: Request SetConfig
prepare a setFrame setConfig message
a3: Request SetTime
prepare a setFrame setTime message
Step 4. When you didn't receive the message in step 3 you asked for (see
step 5 how to request a certain type of message), decide if you want
to ignore or handle the received message. Then go to step 5 to
request for a certain type of message unless the received message
has response type a1, a2 or a3, then prepare first the setFrame
message the wireless console asked for.
Step 5. Decide what kind of message you want to receive next time. The
request is done via a setFrame message (see step 6). It is
not guaranteed that you will receive that kind of message the next
time but setting the proper timing parameters of firstSleep and
nextSleep increase the chance you will get the requested type of
message.
Step 6. The action parameter in the setFrame message sets the type of the
next to receive message.
Action (hex):
00: rtGetHistory - Ask for History message
setSleep(0.300,0.010)
01: rtSetTime - Ask for Send Time to weather station message
setSleep(0.085,0.005)
02: rtSetConfig - Ask for Send Config to weather station message
setSleep(0.300,0.010)
03: rtGetConfig - Ask for Config message
setSleep(0.400,0.400)
05: rtGetCurrent - Ask for Current Weather message
setSleep(0.300,0.010)
c0: Send Time - Send Time to WS
setSleep(0.085,0.005)
40: Send Config - Send Config to WS
setSleep(0.085,0.005)
Note: after the Request First-Time Config message (response type = 0xa1)
perform a rtGetConfig with setSleep(0.085,0.005)
Step 7. Perform a setTX command
Step 8. Go to step 1 to wait for state 0xde16 again.
"""
# TODO: how often is currdat.lst modified with/without hi-speed mode?
# TODO: thread locking around observation data
# TODO: eliminate polling, make MainThread get data as soon as RFThread updates
# TODO: get rid of Length/Buffer construct, replace with a Buffer class or obj
# FIXME: the history retrieval assumes a constant archive interval across all
# history records. this means anything that modifies the archive
# interval should clear the history.
from datetime import datetime
import StringIO
import sys
import syslog
import threading
import time
import traceback
import usb
import weewx.drivers
import weewx.wxformulas
import weeutil.weeutil
DRIVER_NAME = 'WS28xx'
DRIVER_VERSION = '0.33'
def loader(config_dict, engine):
return WS28xxDriver(**config_dict[DRIVER_NAME])
def configurator_loader(config_dict):
return WS28xxConfigurator()
def confeditor_loader():
return WS28xxConfEditor()
# flags for enabling/disabling debug verbosity
DEBUG_COMM = 0
DEBUG_CONFIG_DATA = 0
DEBUG_WEATHER_DATA = 0
DEBUG_HISTORY_DATA = 0
DEBUG_DUMP_FORMAT = 'auto'
def logmsg(dst, msg):
syslog.syslog(dst, 'ws28xx: %s: %s' %
(threading.currentThread().getName(), msg))
def logdbg(msg):
logmsg(syslog.LOG_DEBUG, msg)
def loginf(msg):
logmsg(syslog.LOG_INFO, msg)
def logcrt(msg):
logmsg(syslog.LOG_CRIT, msg)
def logerr(msg):
logmsg(syslog.LOG_ERR, msg)
def log_traceback(dst=syslog.LOG_INFO, prefix='**** '):
sfd = StringIO.StringIO()
traceback.print_exc(file=sfd)
sfd.seek(0)
for line in sfd:
logmsg(dst, prefix + line)
del sfd
def log_frame(n, buf):
logdbg('frame length is %d' % n)
strbuf = ''
for i in xrange(0,n):
strbuf += str('%02x ' % buf[i])
if (i + 1) % 16 == 0:
logdbg(strbuf)
strbuf = ''
if strbuf:
logdbg(strbuf)
def get_datum_diff(v, np, ofl):
if abs(np - v) < 0.001 or abs(ofl - v) < 0.001:
return None
return v
def get_datum_match(v, np, ofl):
if np == v or ofl == v:
return None
return v
def calc_checksum(buf, start, end=None):
if end is None:
end = len(buf[0]) - start
cs = 0
for i in xrange(0, end):
cs += buf[0][i+start]
return cs
def get_next_index(idx):
return get_index(idx + 1)
def get_index(idx):
if idx < 0:
return idx + WS28xxDriver.max_records
elif idx >= WS28xxDriver.max_records:
return idx - WS28xxDriver.max_records
return idx
def tstr_to_ts(tstr):
try:
return int(time.mktime(time.strptime(tstr, "%Y-%m-%d %H:%M:%S")))
except (OverflowError, ValueError, TypeError):
pass
return None
def bytes_to_addr(a, b, c):
return ((((a & 0xF) << 8) | b) << 8) | c
def addr_to_index(addr):
return (addr - 416) / 18
def index_to_addr(idx):
return 18 * idx + 416
def print_dict(data):
for x in sorted(data.keys()):
if x == 'dateTime':
print '%s: %s' % (x, weeutil.weeutil.timestamp_to_string(data[x]))
else:
print '%s: %s' % (x, data[x])
class WS28xxConfEditor(weewx.drivers.AbstractConfEditor):
@property
def default_stanza(self):
return """
[WS28xx]
# This section is for the La Crosse WS-2800 series of weather stations.
# Radio frequency to use between USB transceiver and console: US or EU
# US uses 915 MHz, EU uses 868.3 MHz. Default is US.
transceiver_frequency = US
# The station model, e.g., 'LaCrosse C86234' or 'TFA Primus'
model = LaCrosse WS28xx
# The driver to use:
driver = weewx.drivers.ws28xx
"""
def prompt_for_settings(self):
print "Specify the frequency used between the station and the"
print "transceiver, either 'US' (915 MHz) or 'EU' (868.3 MHz)."
freq = self._prompt('frequency', 'US', ['US', 'EU'])
return {'transceiver_frequency': freq}
class WS28xxConfigurator(weewx.drivers.AbstractConfigurator):
def add_options(self, parser):
super(WS28xxConfigurator, self).add_options(parser)
parser.add_option("--check-transceiver", dest="check",
action="store_true",
help="check USB transceiver")
parser.add_option("--pair", dest="pair", action="store_true",
help="pair the USB transceiver with station console")
parser.add_option("--info", dest="info", action="store_true",
help="display weather station configuration")
parser.add_option("--set-interval", dest="interval",
type=int, metavar="N",
help="set logging interval to N minutes")
parser.add_option("--current", dest="current", action="store_true",
help="get the current weather conditions")
parser.add_option("--history", dest="nrecords", type=int, metavar="N",
help="display N history records")
parser.add_option("--history-since", dest="recmin",
type=int, metavar="N",
help="display history records since N minutes ago")
parser.add_option("--maxtries", dest="maxtries", type=int,
help="maximum number of retries, 0 indicates no max")
def do_options(self, options, parser, config_dict, prompt):
maxtries = 3 if options.maxtries is None else int(options.maxtries)
self.station = WS28xxDriver(**config_dict[DRIVER_NAME])
if options.check:
self.check_transceiver(maxtries)
elif options.pair:
self.pair(maxtries)
elif options.interval is not None:
self.set_interval(maxtries, options.interval, prompt)
elif options.current:
self.show_current(maxtries)
elif options.nrecords is not None:
self.show_history(maxtries, count=options.nrecords)
elif options.recmin is not None:
ts = int(time.time()) - options.recmin * 60
self.show_history(maxtries, ts=ts)
else:
self.show_info(maxtries)
self.station.closePort()
def check_transceiver(self, maxtries):
"""See if the transceiver is installed and operational."""
print 'Checking for transceiver...'
ntries = 0
while ntries < maxtries:
ntries += 1
if self.station.transceiver_is_present():
print 'Transceiver is present'
sn = self.station.get_transceiver_serial()
print 'serial: %s' % sn
tid = self.station.get_transceiver_id()
print 'id: %d (0x%04x)' % (tid, tid)
break
print 'Not found (attempt %d of %d) ...' % (ntries, maxtries)
time.sleep(5)
else:
print 'Transceiver not responding.'
def pair(self, maxtries):
"""Pair the transceiver with the station console."""
print 'Pairing transceiver with console...'
maxwait = 90 # how long to wait between button presses, in seconds
ntries = 0
while ntries < maxtries or maxtries == 0:
if self.station.transceiver_is_paired():
print 'Transceiver is paired to console'
break
ntries += 1
msg = 'Press and hold the [v] key until "PC" appears'
if maxtries > 0:
msg += ' (attempt %d of %d)' % (ntries, maxtries)
else:
msg += ' (attempt %d)' % ntries
print msg
now = start_ts = int(time.time())
while (now - start_ts < maxwait and
not self.station.transceiver_is_paired()):
time.sleep(5)
now = int(time.time())
else:
print 'Transceiver not paired to console.'
def get_interval(self, maxtries):
cfg = self.get_config(maxtries)
if cfg is None:
return None
return getHistoryInterval(cfg['history_interval'])
def get_config(self, maxtries):
start_ts = None
ntries = 0
while ntries < maxtries or maxtries == 0:
cfg = self.station.get_config()
if cfg is not None:
return cfg
ntries += 1
if start_ts is None:
start_ts = int(time.time())
else:
dur = int(time.time()) - start_ts
print 'No data after %d seconds (press SET to sync)' % dur
time.sleep(30)
return None
def set_interval(self, maxtries, interval, prompt):
"""Set the station archive interval"""
print "This feature is not yet implemented"
def show_info(self, maxtries):
"""Query the station then display the settings."""
print 'Querying the station for the configuration...'
cfg = self.get_config(maxtries)
if cfg is not None:
print_dict(cfg)
def show_current(self, maxtries):
"""Get current weather observation."""
print 'Querying the station for current weather data...'
start_ts = None
ntries = 0
while ntries < maxtries or maxtries == 0:
packet = self.station.get_observation()
if packet is not None:
print_dict(packet)
break
ntries += 1
if start_ts is None:
start_ts = int(time.time())
else:
dur = int(time.time()) - start_ts
print 'No data after %d seconds (press SET to sync)' % dur
time.sleep(30)
def show_history(self, maxtries, ts=0, count=0):
"""Display the indicated number of records or the records since the
specified timestamp (local time, in seconds)"""
print "Querying the station for historical records..."
ntries = 0
last_n = nrem = None
last_ts = int(time.time())
self.station.start_caching_history(since_ts=ts, num_rec=count)
while nrem is None or nrem > 0:
if ntries >= maxtries:
print 'Giving up after %d tries' % ntries
break
time.sleep(30)
ntries += 1
now = int(time.time())
n = self.station.get_num_history_scanned()
if n == last_n:
dur = now - last_ts
print 'No data after %d seconds (press SET to sync)' % dur
else:
ntries = 0
last_ts = now
last_n = n
nrem = self.station.get_uncached_history_count()
ni = self.station.get_next_history_index()
li = self.station.get_latest_history_index()
msg = " scanned %s records: current=%s latest=%s remaining=%s\r" % (n, ni, li, nrem)
sys.stdout.write(msg)
sys.stdout.flush()
self.station.stop_caching_history()
records = self.station.get_history_cache_records()
self.station.clear_history_cache()
print
print 'Found %d records' % len(records)
for r in records:
print r
class WS28xxDriver(weewx.drivers.AbstractDevice):
"""Driver for LaCrosse WS28xx stations."""
max_records = 1797
def __init__(self, **stn_dict) :
"""Initialize the station object.
model: Which station model is this?
[Optional. Default is 'LaCrosse WS28xx']
transceiver_frequency: Frequency for transceiver-to-console. Specify
either US or EU.
[Required. Default is US]
polling_interval: How often to sample the USB interface for data.
[Optional. Default is 30 seconds]
comm_interval: Communications mode interval
[Optional. Default is 3]
device_id: The USB device ID for the transceiver. If there are
multiple devices with the same vendor and product IDs on the bus,
each will have a unique device identifier. Use this identifier
to indicate which device should be used.
[Optional. Default is None]
serial: The transceiver serial number. If there are multiple
devices with the same vendor and product IDs on the bus, each will
have a unique serial number. Use the serial number to indicate which
transceiver should be used.
[Optional. Default is None]
"""
self.model = stn_dict.get('model', 'LaCrosse WS28xx')
self.polling_interval = int(stn_dict.get('polling_interval', 30))
self.comm_interval = int(stn_dict.get('comm_interval', 3))
self.frequency = stn_dict.get('transceiver_frequency', 'US')
self.device_id = stn_dict.get('device_id', None)
self.serial = stn_dict.get('serial', None)
self.vendor_id = 0x6666
self.product_id = 0x5555
now = int(time.time())
self._service = None
self._last_rain = None
self._last_obs_ts = None
self._last_nodata_log_ts = now
self._nodata_interval = 300 # how often to check for no data
self._last_contact_log_ts = now
self._nocontact_interval = 300 # how often to check for no contact
self._log_interval = 600 # how often to log
global DEBUG_COMM
DEBUG_COMM = int(stn_dict.get('debug_comm', 0))
global DEBUG_CONFIG_DATA
DEBUG_CONFIG_DATA = int(stn_dict.get('debug_config_data', 0))
global DEBUG_WEATHER_DATA
DEBUG_WEATHER_DATA = int(stn_dict.get('debug_weather_data', 0))
global DEBUG_HISTORY_DATA
DEBUG_HISTORY_DATA = int(stn_dict.get('debug_history_data', 0))
global DEBUG_DUMP_FORMAT
DEBUG_DUMP_FORMAT = stn_dict.get('debug_dump_format', 'auto')
loginf('driver version is %s' % DRIVER_VERSION)
loginf('frequency is %s' % self.frequency)
self.startUp()
@property
def hardware_name(self):
return self.model
# this is invoked by StdEngine as it shuts down
def closePort(self):
self.shutDown()
def genLoopPackets(self):
"""Generator function that continuously returns decoded packets."""
while True:
now = int(time.time()+0.5)
packet = self.get_observation()
if packet is not None:
ts = packet['dateTime']
if self._last_obs_ts is None or self._last_obs_ts != ts:
self._last_obs_ts = ts
self._last_nodata_log_ts = now
self._last_contact_log_ts = now
else:
packet = None
# if no new weather data, return an empty packet
if packet is None:
packet = {'usUnits': weewx.METRIC, 'dateTime': now}
# if no new weather data for awhile, log it
if self._last_obs_ts is None or \
now - self._last_obs_ts > self._nodata_interval:
if now - self._last_nodata_log_ts > self._log_interval:
msg = 'no new weather data'
if self._last_obs_ts is not None:
msg += ' after %d seconds' % (
now - self._last_obs_ts)
loginf(msg)
self._last_nodata_log_ts = now
# if no contact with console for awhile, log it
ts = self.get_last_contact()
if ts is None or now - ts > self._nocontact_interval:
if now - self._last_contact_log_ts > self._log_interval:
msg = 'no contact with console'
if ts is not None:
msg += ' after %d seconds' % (now - ts)
msg += ': press [SET] to sync'
loginf(msg)
self._last_contact_log_ts = now
yield packet
time.sleep(self.polling_interval)
def genStartupRecords(self, ts):
loginf('Scanning historical records')
maxtries = 65
ntries = 0
last_n = n = nrem = None
last_ts = now = int(time.time())
self.start_caching_history(since_ts=ts)
while nrem is None or nrem > 0:
if ntries >= maxtries:
logerr('No historical data after %d tries' % ntries)
return
time.sleep(60)
ntries += 1
now = int(time.time())
n = self.get_num_history_scanned()
if n == last_n:
dur = now - last_ts
loginf('No data after %d seconds (press SET to sync)' % dur)
else:
ntries = 0
last_ts = now
last_n = n
nrem = self.get_uncached_history_count()
ni = self.get_next_history_index()
li = self.get_latest_history_index()
loginf("Scanned %s records: current=%s latest=%s remaining=%s" %
(n, ni, li, nrem))
self.stop_caching_history()
records = self.get_history_cache_records()
self.clear_history_cache()
loginf('Found %d historical records' % len(records))
last_ts = None
for r in records:
if last_ts is not None and r['dateTime'] is not None:
r['usUnits'] = weewx.METRIC
r['interval'] = (r['dateTime'] - last_ts) / 60
yield r
last_ts = r['dateTime']
# FIXME: do not implement hardware record generation until we figure
# out how to query the historical records faster.
# def genArchiveRecords(self, since_ts):
# pass
# FIXME: implement retries for this so that rf thread has time to get
# configuration data from the station
# @property
# def archive_interval(self):
# cfg = self.get_config()
# return getHistoryInterval(cfg['history_interval']) * 60
# FIXME: implement set/get time
# def setTime(self):
# pass
# def getTime(self):
# pass
def startUp(self):
if self._service is not None:
return
self._service = CCommunicationService()
self._service.setup(self.frequency,
self.vendor_id, self.product_id, self.device_id,
self.serial, comm_interval=self.comm_interval)
self._service.startRFThread()
def shutDown(self):
self._service.stopRFThread()
self._service.teardown()
self._service = None
def transceiver_is_present(self):
return self._service.DataStore.getTransceiverPresent()
def transceiver_is_paired(self):
return self._service.DataStore.getDeviceRegistered()
def get_transceiver_serial(self):
return self._service.DataStore.getTransceiverSerNo()
def get_transceiver_id(self):
return self._service.DataStore.getDeviceID()
def get_last_contact(self):
return self._service.getLastStat().last_seen_ts
def get_observation(self):
data = self._service.getWeatherData()
ts = data._timestamp
if ts is None:
return None
# add elements required for weewx LOOP packets
packet = {}
packet['usUnits'] = weewx.METRIC
packet['dateTime'] = ts
# data from the station sensors
packet['inTemp'] = get_datum_diff(data._TempIndoor,
CWeatherTraits.TemperatureNP(),
CWeatherTraits.TemperatureOFL())
packet['inHumidity'] = get_datum_diff(data._HumidityIndoor,
CWeatherTraits.HumidityNP(),
CWeatherTraits.HumidityOFL())
packet['outTemp'] = get_datum_diff(data._TempOutdoor,
CWeatherTraits.TemperatureNP(),
CWeatherTraits.TemperatureOFL())
packet['outHumidity'] = get_datum_diff(data._HumidityOutdoor,
CWeatherTraits.HumidityNP(),
CWeatherTraits.HumidityOFL())
packet['pressure'] = get_datum_diff(data._PressureRelative_hPa,
CWeatherTraits.PressureNP(),
CWeatherTraits.PressureOFL())
packet['windSpeed'] = get_datum_diff(data._WindSpeed,
CWeatherTraits.WindNP(),
CWeatherTraits.WindOFL())
packet['windGust'] = get_datum_diff(data._Gust,
CWeatherTraits.WindNP(),
CWeatherTraits.WindOFL())
packet['windDir'] = getWindDir(data._WindDirection,
packet['windSpeed'])
packet['windGustDir'] = getWindDir(data._GustDirection,
packet['windGust'])
# calculated elements not directly reported by station
packet['rainRate'] = get_datum_match(data._Rain1H,
CWeatherTraits.RainNP(),
CWeatherTraits.RainOFL())
if packet['rainRate'] is not None:
packet['rainRate'] /= 10 # weewx wants cm/hr
rain_total = get_datum_match(data._RainTotal,
CWeatherTraits.RainNP(),
CWeatherTraits.RainOFL())
delta = weewx.wxformulas.calculate_rain(rain_total, self._last_rain)
self._last_rain = rain_total
packet['rain'] = delta
if packet['rain'] is not None:
packet['rain'] /= 10 # weewx wants cm
# track the signal strength and battery levels
laststat = self._service.getLastStat()
packet['rxCheckPercent'] = laststat.LastLinkQuality
packet['windBatteryStatus'] = getBatteryStatus(
laststat.LastBatteryStatus, 'wind')
packet['rainBatteryStatus'] = getBatteryStatus(
laststat.LastBatteryStatus, 'rain')
packet['outTempBatteryStatus'] = getBatteryStatus(
laststat.LastBatteryStatus, 'th')
packet['inTempBatteryStatus'] = getBatteryStatus(
laststat.LastBatteryStatus, 'console')
return packet
def get_config(self):
logdbg('get station configuration')
cfg = self._service.getConfigData().asDict()
cs = cfg.get('checksum_out')
if cs is None or cs == 0:
return None
return cfg
def start_caching_history(self, since_ts=0, num_rec=0):
self._service.startCachingHistory(since_ts, num_rec)
def stop_caching_history(self):
self._service.stopCachingHistory()
def get_uncached_history_count(self):
return self._service.getUncachedHistoryCount()
def get_next_history_index(self):
return self._service.getNextHistoryIndex()
def get_latest_history_index(self):
return self._service.getLatestHistoryIndex()
def get_num_history_scanned(self):
return self._service.getNumHistoryScanned()
def get_history_cache_records(self):
return self._service.getHistoryCacheRecords()
def clear_history_cache(self):
self._service.clearHistoryCache()
def set_interval(self, interval):
# FIXME: set the archive interval
pass
# The following classes and methods are adapted from the implementation by
# eddie de pieri, which is in turn based on the HeavyWeather implementation.
class BadResponse(Exception):
"""raised when unexpected data found in frame buffer"""
pass
class DataWritten(Exception):
"""raised when message 'data written' in frame buffer"""
pass
class BitHandling:
# return a nonzero result, 2**offset, if the bit at 'offset' is one.
@staticmethod
def testBit(int_type, offset):
mask = 1 << offset
return int_type & mask
# return an integer with the bit at 'offset' set to 1.
@staticmethod
def setBit(int_type, offset):
mask = 1 << offset
return int_type | mask
# return an integer with the bit at 'offset' set to 1.
@staticmethod
def setBitVal(int_type, offset, val):
mask = val << offset
return int_type | mask
# return an integer with the bit at 'offset' cleared.
@staticmethod
def clearBit(int_type, offset):
mask = ~(1 << offset)
return int_type & mask
# return an integer with the bit at 'offset' inverted, 0->1 and 1->0.
@staticmethod
def toggleBit(int_type, offset):
mask = 1 << offset
return int_type ^ mask
class EHistoryInterval:
hi01Min = 0
hi05Min = 1
hi10Min = 2
hi15Min = 3
hi20Min = 4
hi30Min = 5
hi60Min = 6
hi02Std = 7
hi04Std = 8
hi06Std = 9
hi08Std = 0xA
hi12Std = 0xB
hi24Std = 0xC
class EWindspeedFormat:
wfMs = 0
wfKnots = 1
wfBFT = 2
wfKmh = 3
wfMph = 4
class ERainFormat:
rfMm = 0
rfInch = 1
class EPressureFormat:
pfinHg = 0
pfHPa = 1
class ETemperatureFormat:
tfFahrenheit = 0
tfCelsius = 1
class EClockMode:
ct24H = 0
ctAmPm = 1
class EWeatherTendency:
TREND_NEUTRAL = 0
TREND_UP = 1
TREND_DOWN = 2
TREND_ERR = 3
class EWeatherState:
WEATHER_BAD = 0
WEATHER_NEUTRAL = 1
WEATHER_GOOD = 2
WEATHER_ERR = 3
class EWindDirection:
wdN = 0
wdNNE = 1
wdNE = 2
wdENE = 3
wdE = 4
wdESE = 5
wdSE = 6
wdSSE = 7
wdS = 8
wdSSW = 9
wdSW = 0x0A
wdWSW = 0x0B
wdW = 0x0C
wdWNW = 0x0D
wdNW = 0x0E
wdNNW = 0x0F
wdERR = 0x10
wdInvalid = 0x11
wdNone = 0x12
def getWindDir(wdir, wspeed):
if wspeed is None or wspeed == 0:
return None
if wdir < 0 or wdir >= 16:
return None
return wdir * 360 / 16
class EResetMinMaxFlags:
rmTempIndoorHi = 0
rmTempIndoorLo = 1
rmTempOutdoorHi = 2
rmTempOutdoorLo = 3
rmWindchillHi = 4
rmWindchillLo = 5
rmDewpointHi = 6
rmDewpointLo = 7
rmHumidityIndoorLo = 8
rmHumidityIndoorHi = 9
rmHumidityOutdoorLo = 0x0A
rmHumidityOutdoorHi = 0x0B
rmWindspeedHi = 0x0C
rmWindspeedLo = 0x0D
rmGustHi = 0x0E
rmGustLo = 0x0F
rmPressureLo = 0x10
rmPressureHi = 0x11
rmRain1hHi = 0x12
rmRain24hHi = 0x13
rmRainLastWeekHi = 0x14
rmRainLastMonthHi = 0x15
rmRainTotal = 0x16
rmInvalid = 0x17
class ERequestType:
rtGetCurrent = 0
rtGetHistory = 1
rtGetConfig = 2
rtSetConfig = 3
rtSetTime = 4
rtFirstConfig = 5
rtINVALID = 6
class EAction:
aGetHistory = 0
aReqSetTime = 1
aReqSetConfig = 2
aGetConfig = 3
aGetCurrent = 5
aSendTime = 0xc0
aSendConfig = 0x40
class ERequestState:
rsQueued = 0
rsRunning = 1
rsFinished = 2
rsPreamble = 3
rsWaitDevice = 4
rsWaitConfig = 5
rsError = 6
rsChanged = 7
rsINVALID = 8
class EResponseType:
rtDataWritten = 0x20
rtGetConfig = 0x40
rtGetCurrentWeather = 0x60
rtGetHistory = 0x80
rtRequest = 0xa0
rtReqFirstConfig = 0xa1
rtReqSetConfig = 0xa2
rtReqSetTime = 0xa3
# frequency standards and their associated transmission frequencies
class EFrequency:
fsUS = 'US'
tfUS = 905000000
fsEU = 'EU'
tfEU = 868300000
def getFrequency(standard):
if standard == EFrequency.fsUS:
return EFrequency.tfUS
elif standard == EFrequency.fsEU:
return EFrequency.tfEU
logerr("unknown frequency standard '%s', using US" % standard)
return EFrequency.tfUS
def getFrequencyStandard(frequency):
if frequency == EFrequency.tfUS:
return EFrequency.fsUS
elif frequency == EFrequency.tfEU:
return EFrequency.fsEU
logerr("unknown frequency '%s', using US" % frequency)
return EFrequency.fsUS
# HWPro presents battery flags as WS/TH/RAIN/WIND
# 0 - wind
# 1 - rain
# 2 - thermo-hygro
# 3 - console
batterybits = {'wind':0, 'rain':1, 'th':2, 'console':3}
def getBatteryStatus(status, flag):
"""Return 1 if bit is set, 0 otherwise"""
bit = batterybits.get(flag)
if bit is None:
return None
if BitHandling.testBit(status, bit):
return 1
return 0
history_intervals = {
EHistoryInterval.hi01Min: 1,
EHistoryInterval.hi05Min: 5,
EHistoryInterval.hi10Min: 10,
EHistoryInterval.hi20Min: 20,
EHistoryInterval.hi30Min: 30,
EHistoryInterval.hi60Min: 60,
EHistoryInterval.hi02Std: 120,
EHistoryInterval.hi04Std: 240,
EHistoryInterval.hi06Std: 360,
EHistoryInterval.hi08Std: 480,
EHistoryInterval.hi12Std: 720,
EHistoryInterval.hi24Std: 1440,
}
def getHistoryInterval(i):
return history_intervals.get(i)
# NP - not present
# OFL - outside factory limits
class CWeatherTraits(object):
windDirMap = {
0: "N", 1: "NNE", 2: "NE", 3: "ENE", 4: "E", 5: "ESE", 6: "SE",
7: "SSE", 8: "S", 9: "SSW", 10: "SW", 11: "WSW", 12: "W",
13: "WNW", 14: "NW", 15: "NWN", 16: "err", 17: "inv", 18: "None" }
forecastMap = {
0: "Rainy(Bad)", 1: "Cloudy(Neutral)", 2: "Sunny(Good)", 3: "Error" }
trendMap = {
0: "Stable(Neutral)", 1: "Rising(Up)", 2: "Falling(Down)", 3: "Error" }
@staticmethod
def TemperatureNP():
return 81.099998
@staticmethod
def TemperatureOFL():
return 136.0
@staticmethod
def PressureNP():
return 10101010.0
@staticmethod
def PressureOFL():
return 16666.5
@staticmethod
def HumidityNP():
return 110.0
@staticmethod
def HumidityOFL():
return 121.0
@staticmethod
def RainNP():
return -0.2
@staticmethod
def RainOFL():
return 16666.664
@staticmethod
def WindNP():
return 183.6 # km/h = 51.0 m/s
@staticmethod
def WindOFL():
return 183.96 # km/h = 51.099998 m/s
@staticmethod
def TemperatureOffset():
return 40.0
class CMeasurement:
_Value = 0.0
_ResetFlag = 23
_IsError = 1
_IsOverflow = 1
_Time = None
def Reset(self):
self._Value = 0.0
self._ResetFlag = 23
self._IsError = 1
self._IsOverflow = 1
class CMinMaxMeasurement(object):
def __init__(self):
self._Min = CMeasurement()
self._Max = CMeasurement()
# firmware XXX has bogus date values for these fields
_bad_labels = ['RainLastMonthMax','RainLastWeekMax','PressureRelativeMin']
class USBHardware(object):
@staticmethod
def isOFL2(buf, start, StartOnHiNibble):
if StartOnHiNibble:
result = (buf[0][start+0] >> 4) == 15 \
or (buf[0][start+0] & 0xF) == 15
else:
result = (buf[0][start+0] & 0xF) == 15 \
or (buf[0][start+1] >> 4) == 15
return result
@staticmethod
def isOFL3(buf, start, StartOnHiNibble):
if StartOnHiNibble:
result = (buf[0][start+0] >> 4) == 15 \
or (buf[0][start+0] & 0xF) == 15 \
or (buf[0][start+1] >> 4) == 15
else:
result = (buf[0][start+0] & 0xF) == 15 \
or (buf[0][start+1] >> 4) == 15 \
or (buf[0][start+1] & 0xF) == 15
return result
@staticmethod
def isOFL5(buf, start, StartOnHiNibble):
if StartOnHiNibble:
result = (buf[0][start+0] >> 4) == 15 \
or (buf[0][start+0] & 0xF) == 15 \
or (buf[0][start+1] >> 4) == 15 \
or (buf[0][start+1] & 0xF) == 15 \
or (buf[0][start+2] >> 4) == 15
else:
result = (buf[0][start+0] & 0xF) == 15 \
or (buf[0][start+1] >> 4) == 15 \
or (buf[0][start+1] & 0xF) == 15 \
or (buf[0][start+2] >> 4) == 15 \
or (buf[0][start+2] & 0xF) == 15
return result
@staticmethod
def isErr2(buf, start, StartOnHiNibble):
if StartOnHiNibble:
result = (buf[0][start+0] >> 4) >= 10 \
and (buf[0][start+0] >> 4) != 15 \
or (buf[0][start+0] & 0xF) >= 10 \
and (buf[0][start+0] & 0xF) != 15
else:
result = (buf[0][start+0] & 0xF) >= 10 \
and (buf[0][start+0] & 0xF) != 15 \
or (buf[0][start+1] >> 4) >= 10 \
and (buf[0][start+1] >> 4) != 15
return result
@staticmethod
def isErr3(buf, start, StartOnHiNibble):
if StartOnHiNibble:
result = (buf[0][start+0] >> 4) >= 10 \
and (buf[0][start+0] >> 4) != 15 \
or (buf[0][start+0] & 0xF) >= 10 \
and (buf[0][start+0] & 0xF) != 15 \
or (buf[0][start+1] >> 4) >= 10 \
and (buf[0][start+1] >> 4) != 15
else:
result = (buf[0][start+0] & 0xF) >= 10 \
and (buf[0][start+0] & 0xF) != 15 \
or (buf[0][start+1] >> 4) >= 10 \
and (buf[0][start+1] >> 4) != 15 \
or (buf[0][start+1] & 0xF) >= 10 \
and (buf[0][start+1] & 0xF) != 15
return result
@staticmethod
def isErr5(buf, start, StartOnHiNibble):
if StartOnHiNibble:
result = (buf[0][start+0] >> 4) >= 10 \
and (buf[0][start+0] >> 4) != 15 \
or (buf[0][start+0] & 0xF) >= 10 \
and (buf[0][start+0] & 0xF) != 15 \
or (buf[0][start+1] >> 4) >= 10 \
and (buf[0][start+1] >> 4) != 15 \
or (buf[0][start+1] & 0xF) >= 10 \
and (buf[0][start+1] & 0xF) != 15 \
or (buf[0][start+2] >> 4) >= 10 \
and (buf[0][start+2] >> 4) != 15
else:
result = (buf[0][start+0] & 0xF) >= 10 \
and (buf[0][start+0] & 0xF) != 15 \
or (buf[0][start+1] >> 4) >= 10 \
and (buf[0][start+1] >> 4) != 15 \
or (buf[0][start+1] & 0xF) >= 10 \
and (buf[0][start+1] & 0xF) != 15 \
or (buf[0][start+2] >> 4) >= 10 \
and (buf[0][start+2] >> 4) != 15 \
or (buf[0][start+2] & 0xF) >= 10 \
and (buf[0][start+2] & 0xF) != 15
return result
@staticmethod
def reverseByteOrder(buf, start, Count):
nbuf=buf[0]
for i in xrange(0, Count >> 1):
tmp = nbuf[start + i]
nbuf[start + i] = nbuf[start + Count - i - 1]
nbuf[start + Count - i - 1 ] = tmp
buf[0]=nbuf
@staticmethod
def readWindDirectionShared(buf, start):
return (buf[0][0+start] & 0xF, buf[0][start] >> 4)
@staticmethod
def toInt_2(buf, start, StartOnHiNibble):
"""read 2 nibbles"""
if StartOnHiNibble:
rawpre = (buf[0][start+0] >> 4)* 10 \
+ (buf[0][start+0] & 0xF)* 1
else:
rawpre = (buf[0][start+0] & 0xF)* 10 \
+ (buf[0][start+1] >> 4)* 1
return rawpre
@staticmethod
def toRain_7_3(buf, start, StartOnHiNibble):
"""read 7 nibbles, presentation with 3 decimals; units of mm"""
if (USBHardware.isErr2(buf, start+0, StartOnHiNibble) or
USBHardware.isErr5(buf, start+1, StartOnHiNibble)):
result = CWeatherTraits.RainNP()
elif (USBHardware.isOFL2(buf, start+0, StartOnHiNibble) or
USBHardware.isOFL5(buf, start+1, StartOnHiNibble)):
result = CWeatherTraits.RainOFL()
elif StartOnHiNibble:
result = (buf[0][start+0] >> 4)* 1000 \
+ (buf[0][start+0] & 0xF)* 100 \
+ (buf[0][start+1] >> 4)* 10 \
+ (buf[0][start+1] & 0xF)* 1 \
+ (buf[0][start+2] >> 4)* 0.1 \
+ (buf[0][start+2] & 0xF)* 0.01 \
+ (buf[0][start+3] >> 4)* 0.001
else:
result = (buf[0][start+0] & 0xF)* 1000 \
+ (buf[0][start+1] >> 4)* 100 \
+ (buf[0][start+1] & 0xF)* 10 \
+ (buf[0][start+2] >> 4)* 1 \
+ (buf[0][start+2] & 0xF)* 0.1 \
+ (buf[0][start+3] >> 4)* 0.01 \
+ (buf[0][start+3] & 0xF)* 0.001
return result
@staticmethod
def toRain_6_2(buf, start, StartOnHiNibble):
'''read 6 nibbles, presentation with 2 decimals; units of mm'''
if (USBHardware.isErr2(buf, start+0, StartOnHiNibble) or
USBHardware.isErr2(buf, start+1, StartOnHiNibble) or
USBHardware.isErr2(buf, start+2, StartOnHiNibble) ):
result = CWeatherTraits.RainNP()
elif (USBHardware.isOFL2(buf, start+0, StartOnHiNibble) or
USBHardware.isOFL2(buf, start+1, StartOnHiNibble) or
USBHardware.isOFL2(buf, start+2, StartOnHiNibble)):
result = CWeatherTraits.RainOFL()
elif StartOnHiNibble:
result = (buf[0][start+0] >> 4)* 1000 \
+ (buf[0][start+0] & 0xF)* 100 \
+ (buf[0][start+1] >> 4)* 10 \
+ (buf[0][start+1] & 0xF)* 1 \
+ (buf[0][start+2] >> 4)* 0.1 \
+ (buf[0][start+2] & 0xF)* 0.01
else:
result = (buf[0][start+0] & 0xF)* 1000 \
+ (buf[0][start+1] >> 4)* 100 \
+ (buf[0][start+1] & 0xF)* 10 \
+ (buf[0][start+2] >> 4)* 1 \
+ (buf[0][start+2] & 0xF)* 0.1 \
+ (buf[0][start+3] >> 4)* 0.01
return result
@staticmethod
def toRain_3_1(buf, start, StartOnHiNibble):
"""read 3 nibbles, presentation with 1 decimal; units of 0.1 inch"""
if StartOnHiNibble:
hibyte = buf[0][start+0]
lobyte = (buf[0][start+1] >> 4) & 0xF
else:
hibyte = 16*(buf[0][start+0] & 0xF) + ((buf[0][start+1] >> 4) & 0xF)
lobyte = buf[0][start+1] & 0xF
if hibyte == 0xFF and lobyte == 0xE :
result = CWeatherTraits.RainNP()
elif hibyte == 0xFF and lobyte == 0xF :
result = CWeatherTraits.RainOFL()
else:
val = USBHardware.toFloat_3_1(buf, start, StartOnHiNibble) # 0.1 inch
result = val * 2.54 # mm
return result
@staticmethod
def toFloat_3_1(buf, start, StartOnHiNibble):
"""read 3 nibbles, presentation with 1 decimal"""
if StartOnHiNibble:
result = (buf[0][start+0] >> 4)*16**2 \
+ (buf[0][start+0] & 0xF)* 16**1 \
+ (buf[0][start+1] >> 4)* 16**0
else:
result = (buf[0][start+0] & 0xF)*16**2 \
+ (buf[0][start+1] >> 4)* 16**1 \
+ (buf[0][start+1] & 0xF)* 16**0
result = result / 10.0
return result
@staticmethod
def toDateTime(buf, start, StartOnHiNibble, label):
"""read 10 nibbles, presentation as DateTime"""
result = None
if (USBHardware.isErr2(buf, start+0, StartOnHiNibble)
or USBHardware.isErr2(buf, start+1, StartOnHiNibble)
or USBHardware.isErr2(buf, start+2, StartOnHiNibble)
or USBHardware.isErr2(buf, start+3, StartOnHiNibble)
or USBHardware.isErr2(buf, start+4, StartOnHiNibble)):
logerr('ToDateTime: bogus date for %s: error status in buffer' %
label)
else:
year = USBHardware.toInt_2(buf, start+0, StartOnHiNibble) + 2000
month = USBHardware.toInt_2(buf, start+1, StartOnHiNibble)
days = USBHardware.toInt_2(buf, start+2, StartOnHiNibble)
hours = USBHardware.toInt_2(buf, start+3, StartOnHiNibble)
minutes = USBHardware.toInt_2(buf, start+4, StartOnHiNibble)
try:
result = datetime(year, month, days, hours, minutes)
except ValueError:
if label not in _bad_labels:
logerr(('ToDateTime: bogus date for %s:'
' bad date conversion from'
' %s %s %s %s %s') %
(label, minutes, hours, days, month, year))
if result is None:
# FIXME: use None instead of a really old date to indicate invalid
result = datetime(1900, 01, 01, 00, 00)
return result
@staticmethod
def toHumidity_2_0(buf, start, StartOnHiNibble):
"""read 2 nibbles, presentation with 0 decimal"""
if USBHardware.isErr2(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.HumidityNP()
elif USBHardware.isOFL2(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.HumidityOFL()
else:
result = USBHardware.toInt_2(buf, start, StartOnHiNibble)
return result
@staticmethod
def toTemperature_5_3(buf, start, StartOnHiNibble):
"""read 5 nibbles, presentation with 3 decimals; units of degree C"""
if USBHardware.isErr5(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.TemperatureNP()
elif USBHardware.isOFL5(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.TemperatureOFL()
else:
if StartOnHiNibble:
rawtemp = (buf[0][start+0] >> 4)* 10 \
+ (buf[0][start+0] & 0xF)* 1 \
+ (buf[0][start+1] >> 4)* 0.1 \
+ (buf[0][start+1] & 0xF)* 0.01 \
+ (buf[0][start+2] >> 4)* 0.001
else:
rawtemp = (buf[0][start+0] & 0xF)* 10 \
+ (buf[0][start+1] >> 4)* 1 \
+ (buf[0][start+1] & 0xF)* 0.1 \
+ (buf[0][start+2] >> 4)* 0.01 \
+ (buf[0][start+2] & 0xF)* 0.001
result = rawtemp - CWeatherTraits.TemperatureOffset()
return result
@staticmethod
def toTemperature_3_1(buf, start, StartOnHiNibble):
"""read 3 nibbles, presentation with 1 decimal; units of degree C"""
if USBHardware.isErr3(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.TemperatureNP()
elif USBHardware.isOFL3(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.TemperatureOFL()
else:
if StartOnHiNibble :
rawtemp = (buf[0][start+0] >> 4)* 10 \
+ (buf[0][start+0] & 0xF)* 1 \
+ (buf[0][start+1] >> 4)* 0.1
else:
rawtemp = (buf[0][start+0] & 0xF)* 10 \
+ (buf[0][start+1] >> 4)* 1 \
+ (buf[0][start+1] & 0xF)* 0.1
result = rawtemp - CWeatherTraits.TemperatureOffset()
return result
@staticmethod
def toWindspeed_6_2(buf, start):
"""read 6 nibbles, presentation with 2 decimals; units of km/h"""
result = (buf[0][start+0] >> 4)* 16**5 \
+ (buf[0][start+0] & 0xF)* 16**4 \
+ (buf[0][start+1] >> 4)* 16**3 \
+ (buf[0][start+1] & 0xF)* 16**2 \
+ (buf[0][start+2] >> 4)* 16**1 \
+ (buf[0][start+2] & 0xF)
result /= 256.0
result /= 100.0 # km/h
return result
@staticmethod
def toWindspeed_3_1(buf, start, StartOnHiNibble):
"""read 3 nibbles, presentation with 1 decimal; units of m/s"""
if StartOnHiNibble :
hibyte = buf[0][start+0]
lobyte = (buf[0][start+1] >> 4) & 0xF
else:
hibyte = 16*(buf[0][start+0] & 0xF) + ((buf[0][start+1] >> 4) & 0xF)
lobyte = buf[0][start+1] & 0xF
if hibyte == 0xFF and lobyte == 0xE:
result = CWeatherTraits.WindNP()
elif hibyte == 0xFF and lobyte == 0xF:
result = CWeatherTraits.WindOFL()
else:
result = USBHardware.toFloat_3_1(buf, start, StartOnHiNibble) # m/s
result *= 3.6 # km/h
return result
@staticmethod
def readPressureShared(buf, start, StartOnHiNibble):
return (USBHardware.toPressure_hPa_5_1(buf,start+2,1-StartOnHiNibble),
USBHardware.toPressure_inHg_5_2(buf,start,StartOnHiNibble))
@staticmethod
def toPressure_hPa_5_1(buf, start, StartOnHiNibble):
"""read 5 nibbles, presentation with 1 decimal; units of hPa (mbar)"""
if USBHardware.isErr5(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.PressureNP()
elif USBHardware.isOFL5(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.PressureOFL()
elif StartOnHiNibble :
result = (buf[0][start+0] >> 4)* 1000 \
+ (buf[0][start+0] & 0xF)* 100 \
+ (buf[0][start+1] >> 4)* 10 \
+ (buf[0][start+1] & 0xF)* 1 \
+ (buf[0][start+2] >> 4)* 0.1
else:
result = (buf[0][start+0] & 0xF)* 1000 \
+ (buf[0][start+1] >> 4)* 100 \
+ (buf[0][start+1] & 0xF)* 10 \
+ (buf[0][start+2] >> 4)* 1 \
+ (buf[0][start+2] & 0xF)* 0.1
return result
@staticmethod
def toPressure_inHg_5_2(buf, start, StartOnHiNibble):
"""read 5 nibbles, presentation with 2 decimals; units of inHg"""
if USBHardware.isErr5(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.PressureNP()
elif USBHardware.isOFL5(buf, start+0, StartOnHiNibble):
result = CWeatherTraits.PressureOFL()
elif StartOnHiNibble :
result = (buf[0][start+0] >> 4)* 100 \
+ (buf[0][start+0] & 0xF)* 10 \
+ (buf[0][start+1] >> 4)* 1 \
+ (buf[0][start+1] & 0xF)* 0.1 \
+ (buf[0][start+2] >> 4)* 0.01
else:
result = (buf[0][start+0] & 0xF)* 100 \
+ (buf[0][start+1] >> 4)* 10 \
+ (buf[0][start+1] & 0xF)* 1 \
+ (buf[0][start+2] >> 4)* 0.1 \
+ (buf[0][start+2] & 0xF)* 0.01
return result
class CCurrentWeatherData(object):
def __init__(self):
self._timestamp = None
self._checksum = None
self._PressureRelative_hPa = CWeatherTraits.PressureNP()
self._PressureRelative_hPaMinMax = CMinMaxMeasurement()
self._PressureRelative_inHg = CWeatherTraits.PressureNP()
self._PressureRelative_inHgMinMax = CMinMaxMeasurement()
self._WindSpeed = CWeatherTraits.WindNP()
self._WindDirection = EWindDirection.wdNone
self._WindDirection1 = EWindDirection.wdNone
self._WindDirection2 = EWindDirection.wdNone
self._WindDirection3 = EWindDirection.wdNone
self._WindDirection4 = EWindDirection.wdNone
self._WindDirection5 = EWindDirection.wdNone
self._Gust = CWeatherTraits.WindNP()
self._GustMax = CMinMaxMeasurement()
self._GustDirection = EWindDirection.wdNone
self._GustDirection1 = EWindDirection.wdNone
self._GustDirection2 = EWindDirection.wdNone
self._GustDirection3 = EWindDirection.wdNone
self._GustDirection4 = EWindDirection.wdNone
self._GustDirection5 = EWindDirection.wdNone
self._Rain1H = CWeatherTraits.RainNP()
self._Rain1HMax = CMinMaxMeasurement()
self._Rain24H = CWeatherTraits.RainNP()
self._Rain24HMax = CMinMaxMeasurement()
self._RainLastWeek = CWeatherTraits.RainNP()
self._RainLastWeekMax = CMinMaxMeasurement()
self._RainLastMonth = CWeatherTraits.RainNP()
self._RainLastMonthMax = CMinMaxMeasurement()
self._RainTotal = CWeatherTraits.RainNP()
self._LastRainReset = None
self._TempIndoor = CWeatherTraits.TemperatureNP()
self._TempIndoorMinMax = CMinMaxMeasurement()
self._TempOutdoor = CWeatherTraits.TemperatureNP()
self._TempOutdoorMinMax = CMinMaxMeasurement()
self._HumidityIndoor = CWeatherTraits.HumidityNP()
self._HumidityIndoorMinMax = CMinMaxMeasurement()
self._HumidityOutdoor = CWeatherTraits.HumidityNP()
self._HumidityOutdoorMinMax = CMinMaxMeasurement()
self._Dewpoint = CWeatherTraits.TemperatureNP()
self._DewpointMinMax = CMinMaxMeasurement()
self._Windchill = CWeatherTraits.TemperatureNP()
self._WindchillMinMax = CMinMaxMeasurement()
self._WeatherState = EWeatherState.WEATHER_ERR
self._WeatherTendency = EWeatherTendency.TREND_ERR
self._AlarmRingingFlags = 0
self._AlarmMarkedFlags = 0
self._PresRel_hPa_Max = 0.0
self._PresRel_inHg_Max = 0.0
@staticmethod
def calcChecksum(buf):
return calc_checksum(buf, 6)
def checksum(self):
return self._checksum
def read(self, buf):
self._timestamp = int(time.time() + 0.5)
self._checksum = CCurrentWeatherData.calcChecksum(buf)
nbuf = [0]
nbuf[0] = buf[0]
self._StartBytes = nbuf[0][6]*0xF + nbuf[0][7] # FIXME: what is this?
self._WeatherTendency = (nbuf[0][8] >> 4) & 0xF
if self._WeatherTendency > 3:
self._WeatherTendency = 3
self._WeatherState = nbuf[0][8] & 0xF
if self._WeatherState > 3:
self._WeatherState = 3
self._TempIndoorMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 19, 0)
self._TempIndoorMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 22, 1)
self._TempIndoor = USBHardware.toTemperature_5_3(nbuf, 24, 0)
self._TempIndoorMinMax._Min._IsError = (self._TempIndoorMinMax._Min._Value == CWeatherTraits.TemperatureNP())
self._TempIndoorMinMax._Min._IsOverflow = (self._TempIndoorMinMax._Min._Value == CWeatherTraits.TemperatureOFL())
self._TempIndoorMinMax._Max._IsError = (self._TempIndoorMinMax._Max._Value == CWeatherTraits.TemperatureNP())
self._TempIndoorMinMax._Max._IsOverflow = (self._TempIndoorMinMax._Max._Value == CWeatherTraits.TemperatureOFL())
self._TempIndoorMinMax._Max._Time = None if self._TempIndoorMinMax._Max._IsError or self._TempIndoorMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 9, 0, 'TempIndoorMax')
self._TempIndoorMinMax._Min._Time = None if self._TempIndoorMinMax._Min._IsError or self._TempIndoorMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 14, 0, 'TempIndoorMin')
self._TempOutdoorMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 37, 0)
self._TempOutdoorMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 40, 1)
self._TempOutdoor = USBHardware.toTemperature_5_3(nbuf, 42, 0)
self._TempOutdoorMinMax._Min._IsError = (self._TempOutdoorMinMax._Min._Value == CWeatherTraits.TemperatureNP())
self._TempOutdoorMinMax._Min._IsOverflow = (self._TempOutdoorMinMax._Min._Value == CWeatherTraits.TemperatureOFL())
self._TempOutdoorMinMax._Max._IsError = (self._TempOutdoorMinMax._Max._Value == CWeatherTraits.TemperatureNP())
self._TempOutdoorMinMax._Max._IsOverflow = (self._TempOutdoorMinMax._Max._Value == CWeatherTraits.TemperatureOFL())
self._TempOutdoorMinMax._Max._Time = None if self._TempOutdoorMinMax._Max._IsError or self._TempOutdoorMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 27, 0, 'TempOutdoorMax')
self._TempOutdoorMinMax._Min._Time = None if self._TempOutdoorMinMax._Min._IsError or self._TempOutdoorMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 32, 0, 'TempOutdoorMin')
self._WindchillMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 55, 0)
self._WindchillMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 58, 1)
self._Windchill = USBHardware.toTemperature_5_3(nbuf, 60, 0)
self._WindchillMinMax._Min._IsError = (self._WindchillMinMax._Min._Value == CWeatherTraits.TemperatureNP())
self._WindchillMinMax._Min._IsOverflow = (self._WindchillMinMax._Min._Value == CWeatherTraits.TemperatureOFL())
self._WindchillMinMax._Max._IsError = (self._WindchillMinMax._Max._Value == CWeatherTraits.TemperatureNP())
self._WindchillMinMax._Max._IsOverflow = (self._WindchillMinMax._Max._Value == CWeatherTraits.TemperatureOFL())
self._WindchillMinMax._Max._Time = None if self._WindchillMinMax._Max._IsError or self._WindchillMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 45, 0, 'WindchillMax')
self._WindchillMinMax._Min._Time = None if self._WindchillMinMax._Min._IsError or self._WindchillMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 50, 0, 'WindchillMin')
self._DewpointMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 73, 0)
self._DewpointMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 76, 1)
self._Dewpoint = USBHardware.toTemperature_5_3(nbuf, 78, 0)
self._DewpointMinMax._Min._IsError = (self._DewpointMinMax._Min._Value == CWeatherTraits.TemperatureNP())
self._DewpointMinMax._Min._IsOverflow = (self._DewpointMinMax._Min._Value == CWeatherTraits.TemperatureOFL())
self._DewpointMinMax._Max._IsError = (self._DewpointMinMax._Max._Value == CWeatherTraits.TemperatureNP())
self._DewpointMinMax._Max._IsOverflow = (self._DewpointMinMax._Max._Value == CWeatherTraits.TemperatureOFL())
self._DewpointMinMax._Min._Time = None if self._DewpointMinMax._Min._IsError or self._DewpointMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 68, 0, 'DewpointMin')
self._DewpointMinMax._Max._Time = None if self._DewpointMinMax._Max._IsError or self._DewpointMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 63, 0, 'DewpointMax')
self._HumidityIndoorMinMax._Max._Value = USBHardware.toHumidity_2_0(nbuf, 91, 1)
self._HumidityIndoorMinMax._Min._Value = USBHardware.toHumidity_2_0(nbuf, 92, 1)
self._HumidityIndoor = USBHardware.toHumidity_2_0(nbuf, 93, 1)
self._HumidityIndoorMinMax._Min._IsError = (self._HumidityIndoorMinMax._Min._Value == CWeatherTraits.HumidityNP())
self._HumidityIndoorMinMax._Min._IsOverflow = (self._HumidityIndoorMinMax._Min._Value == CWeatherTraits.HumidityOFL())
self._HumidityIndoorMinMax._Max._IsError = (self._HumidityIndoorMinMax._Max._Value == CWeatherTraits.HumidityNP())
self._HumidityIndoorMinMax._Max._IsOverflow = (self._HumidityIndoorMinMax._Max._Value == CWeatherTraits.HumidityOFL())
self._HumidityIndoorMinMax._Max._Time = None if self._HumidityIndoorMinMax._Max._IsError or self._HumidityIndoorMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 81, 1, 'HumidityIndoorMax')
self._HumidityIndoorMinMax._Min._Time = None if self._HumidityIndoorMinMax._Min._IsError or self._HumidityIndoorMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 86, 1, 'HumidityIndoorMin')
self._HumidityOutdoorMinMax._Max._Value = USBHardware.toHumidity_2_0(nbuf, 104, 1)
self._HumidityOutdoorMinMax._Min._Value = USBHardware.toHumidity_2_0(nbuf, 105, 1)
self._HumidityOutdoor = USBHardware.toHumidity_2_0(nbuf, 106, 1)
self._HumidityOutdoorMinMax._Min._IsError = (self._HumidityOutdoorMinMax._Min._Value == CWeatherTraits.HumidityNP())
self._HumidityOutdoorMinMax._Min._IsOverflow = (self._HumidityOutdoorMinMax._Min._Value == CWeatherTraits.HumidityOFL())
self._HumidityOutdoorMinMax._Max._IsError = (self._HumidityOutdoorMinMax._Max._Value == CWeatherTraits.HumidityNP())
self._HumidityOutdoorMinMax._Max._IsOverflow = (self._HumidityOutdoorMinMax._Max._Value == CWeatherTraits.HumidityOFL())
self._HumidityOutdoorMinMax._Max._Time = None if self._HumidityOutdoorMinMax._Max._IsError or self._HumidityOutdoorMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 94, 1, 'HumidityOutdoorMax')
self._HumidityOutdoorMinMax._Min._Time = None if self._HumidityOutdoorMinMax._Min._IsError or self._HumidityOutdoorMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 99, 1, 'HumidityOutdoorMin')
self._RainLastMonthMax._Max._Time = USBHardware.toDateTime(nbuf, 107, 1, 'RainLastMonthMax')
self._RainLastMonthMax._Max._Value = USBHardware.toRain_6_2(nbuf, 112, 1)
self._RainLastMonth = USBHardware.toRain_6_2(nbuf, 115, 1)
self._RainLastWeekMax._Max._Time = USBHardware.toDateTime(nbuf, 118, 1, 'RainLastWeekMax')
self._RainLastWeekMax._Max._Value = USBHardware.toRain_6_2(nbuf, 123, 1)
self._RainLastWeek = USBHardware.toRain_6_2(nbuf, 126, 1)
self._Rain24HMax._Max._Time = USBHardware.toDateTime(nbuf, 129, 1, 'Rain24HMax')
self._Rain24HMax._Max._Value = USBHardware.toRain_6_2(nbuf, 134, 1)
self._Rain24H = USBHardware.toRain_6_2(nbuf, 137, 1)
self._Rain1HMax._Max._Time = USBHardware.toDateTime(nbuf, 140, 1, 'Rain1HMax')
self._Rain1HMax._Max._Value = USBHardware.toRain_6_2(nbuf, 145, 1)
self._Rain1H = USBHardware.toRain_6_2(nbuf, 148, 1)
self._LastRainReset = USBHardware.toDateTime(nbuf, 151, 0, 'LastRainReset')
self._RainTotal = USBHardware.toRain_7_3(nbuf, 156, 0)
(w ,w1) = USBHardware.readWindDirectionShared(nbuf, 162)
(w2,w3) = USBHardware.readWindDirectionShared(nbuf, 161)
(w4,w5) = USBHardware.readWindDirectionShared(nbuf, 160)
self._WindDirection = w
self._WindDirection1 = w1
self._WindDirection2 = w2
self._WindDirection3 = w3
self._WindDirection4 = w4
self._WindDirection5 = w5
if DEBUG_WEATHER_DATA > 2:
unknownbuf = [0]*9
for i in xrange(0,9):
unknownbuf[i] = nbuf[163+i]
strbuf = ""
for i in unknownbuf:
strbuf += str("%.2x " % i)
logdbg('Bytes with unknown meaning at 157-165: %s' % strbuf)
self._WindSpeed = USBHardware.toWindspeed_6_2(nbuf, 172)
# FIXME: read the WindErrFlags
(g ,g1) = USBHardware.readWindDirectionShared(nbuf, 177)
(g2,g3) = USBHardware.readWindDirectionShared(nbuf, 176)
(g4,g5) = USBHardware.readWindDirectionShared(nbuf, 175)
self._GustDirection = g
self._GustDirection1 = g1
self._GustDirection2 = g2
self._GustDirection3 = g3
self._GustDirection4 = g4
self._GustDirection5 = g5
self._GustMax._Max._Value = USBHardware.toWindspeed_6_2(nbuf, 184)
self._GustMax._Max._IsError = (self._GustMax._Max._Value == CWeatherTraits.WindNP())
self._GustMax._Max._IsOverflow = (self._GustMax._Max._Value == CWeatherTraits.WindOFL())
self._GustMax._Max._Time = None if self._GustMax._Max._IsError or self._GustMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 179, 1, 'GustMax')
self._Gust = USBHardware.toWindspeed_6_2(nbuf, 187)
# Apparently the station returns only ONE date time for both hPa/inHg
# Min Time Reset and Max Time Reset
self._PressureRelative_hPaMinMax._Max._Time = USBHardware.toDateTime(nbuf, 190, 1, 'PressureRelative_hPaMax')
self._PressureRelative_inHgMinMax._Max._Time = self._PressureRelative_hPaMinMax._Max._Time
self._PressureRelative_hPaMinMax._Min._Time = self._PressureRelative_hPaMinMax._Max._Time # firmware bug, should be: USBHardware.toDateTime(nbuf, 195, 1)
self._PressureRelative_inHgMinMax._Min._Time = self._PressureRelative_hPaMinMax._Min._Time
(self._PresRel_hPa_Max, self._PresRel_inHg_Max) = USBHardware.readPressureShared(nbuf, 195, 1) # firmware bug, should be: self._PressureRelative_hPaMinMax._Min._Time
(self._PressureRelative_hPaMinMax._Max._Value, self._PressureRelative_inHgMinMax._Max._Value) = USBHardware.readPressureShared(nbuf, 200, 1)
(self._PressureRelative_hPaMinMax._Min._Value, self._PressureRelative_inHgMinMax._Min._Value) = USBHardware.readPressureShared(nbuf, 205, 1)
(self._PressureRelative_hPa, self._PressureRelative_inHg) = USBHardware.readPressureShared(nbuf, 210, 1)
def toLog(self):
logdbg("_WeatherState=%s _WeatherTendency=%s _AlarmRingingFlags %04x" % (CWeatherTraits.forecastMap[self._WeatherState], CWeatherTraits.trendMap[self._WeatherTendency], self._AlarmRingingFlags))
logdbg("_TempIndoor= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._TempIndoor, self._TempIndoorMinMax._Min._Value, self._TempIndoorMinMax._Min._Time, self._TempIndoorMinMax._Max._Value, self._TempIndoorMinMax._Max._Time))
logdbg("_HumidityIndoor= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._HumidityIndoor, self._HumidityIndoorMinMax._Min._Value, self._HumidityIndoorMinMax._Min._Time, self._HumidityIndoorMinMax._Max._Value, self._HumidityIndoorMinMax._Max._Time))
logdbg("_TempOutdoor= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._TempOutdoor, self._TempOutdoorMinMax._Min._Value, self._TempOutdoorMinMax._Min._Time, self._TempOutdoorMinMax._Max._Value, self._TempOutdoorMinMax._Max._Time))
logdbg("_HumidityOutdoor=%8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._HumidityOutdoor, self._HumidityOutdoorMinMax._Min._Value, self._HumidityOutdoorMinMax._Min._Time, self._HumidityOutdoorMinMax._Max._Value, self._HumidityOutdoorMinMax._Max._Time))
logdbg("_Windchill= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._Windchill, self._WindchillMinMax._Min._Value, self._WindchillMinMax._Min._Time, self._WindchillMinMax._Max._Value, self._WindchillMinMax._Max._Time))
logdbg("_Dewpoint= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._Dewpoint, self._DewpointMinMax._Min._Value, self._DewpointMinMax._Min._Time, self._DewpointMinMax._Max._Value, self._DewpointMinMax._Max._Time))
logdbg("_WindSpeed= %8.3f" % self._WindSpeed)
logdbg("_Gust= %8.3f _Max=%8.3f (%s)" % (self._Gust, self._GustMax._Max._Value, self._GustMax._Max._Time))
logdbg('_WindDirection= %3s _GustDirection= %3s' % (CWeatherTraits.windDirMap[self._WindDirection], CWeatherTraits.windDirMap[self._GustDirection]))
logdbg('_WindDirection1= %3s _GustDirection1= %3s' % (CWeatherTraits.windDirMap[self._WindDirection1], CWeatherTraits.windDirMap[self._GustDirection1]))
logdbg('_WindDirection2= %3s _GustDirection2= %3s' % (CWeatherTraits.windDirMap[self._WindDirection2], CWeatherTraits.windDirMap[self._GustDirection2]))
logdbg('_WindDirection3= %3s _GustDirection3= %3s' % (CWeatherTraits.windDirMap[self._WindDirection3], CWeatherTraits.windDirMap[self._GustDirection3]))
logdbg('_WindDirection4= %3s _GustDirection4= %3s' % (CWeatherTraits.windDirMap[self._WindDirection4], CWeatherTraits.windDirMap[self._GustDirection4]))
logdbg('_WindDirection5= %3s _GustDirection5= %3s' % (CWeatherTraits.windDirMap[self._WindDirection5], CWeatherTraits.windDirMap[self._GustDirection5]))
if (self._RainLastMonth > 0) or (self._RainLastWeek > 0):
logdbg("_RainLastMonth= %8.3f _Max=%8.3f (%s)" % (self._RainLastMonth, self._RainLastMonthMax._Max._Value, self._RainLastMonthMax._Max._Time))
logdbg("_RainLastWeek= %8.3f _Max=%8.3f (%s)" % (self._RainLastWeek, self._RainLastWeekMax._Max._Value, self._RainLastWeekMax._Max._Time))
logdbg("_Rain24H= %8.3f _Max=%8.3f (%s)" % (self._Rain24H, self._Rain24HMax._Max._Value, self._Rain24HMax._Max._Time))
logdbg("_Rain1H= %8.3f _Max=%8.3f (%s)" % (self._Rain1H, self._Rain1HMax._Max._Value, self._Rain1HMax._Max._Time))
logdbg("_RainTotal= %8.3f _LastRainReset= (%s)" % (self._RainTotal, self._LastRainReset))
logdbg("PressureRel_hPa= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s) " % (self._PressureRelative_hPa, self._PressureRelative_hPaMinMax._Min._Value, self._PressureRelative_hPaMinMax._Min._Time, self._PressureRelative_hPaMinMax._Max._Value, self._PressureRelative_hPaMinMax._Max._Time))
logdbg("PressureRel_inHg=%8.3f _Min=%8.3f (%s) _Max=%8.3f (%s) " % (self._PressureRelative_inHg, self._PressureRelative_inHgMinMax._Min._Value, self._PressureRelative_inHgMinMax._Min._Time, self._PressureRelative_inHgMinMax._Max._Value, self._PressureRelative_inHgMinMax._Max._Time))
###logdbg('(* Bug in Weather Station: PressureRelative._Min._Time is written to location of _PressureRelative._Max._Time')
###logdbg('Instead of PressureRelative._Min._Time we get: _PresRel_hPa_Max= %8.3f, _PresRel_inHg_max =%8.3f;' % (self._PresRel_hPa_Max, self._PresRel_inHg_Max))
class CWeatherStationConfig(object):
def __init__(self):
self._InBufCS = 0 # checksum of received config
self._OutBufCS = 0 # calculated config checksum from outbuf config
self._ClockMode = 0
self._TemperatureFormat = 0
self._PressureFormat = 0
self._RainFormat = 0
self._WindspeedFormat = 0
self._WeatherThreshold = 0
self._StormThreshold = 0
self._LCDContrast = 0
self._LowBatFlags = 0
self._WindDirAlarmFlags = 0
self._OtherAlarmFlags = 0
self._ResetMinMaxFlags = 0 # output only
self._HistoryInterval = 0
self._TempIndoorMinMax = CMinMaxMeasurement()
self._TempOutdoorMinMax = CMinMaxMeasurement()
self._HumidityIndoorMinMax = CMinMaxMeasurement()
self._HumidityOutdoorMinMax = CMinMaxMeasurement()
self._Rain24HMax = CMinMaxMeasurement()
self._GustMax = CMinMaxMeasurement()
self._PressureRelative_hPaMinMax = CMinMaxMeasurement()
self._PressureRelative_inHgMinMax = CMinMaxMeasurement()
def setTemps(self,TempFormat,InTempLo,InTempHi,OutTempLo,OutTempHi):
f1 = TempFormat
t1 = InTempLo
t2 = InTempHi
t3 = OutTempLo
t4 = OutTempHi
if f1 not in [ETemperatureFormat.tfFahrenheit,
ETemperatureFormat.tfCelsius]:
logerr('setTemps: unknown temperature format %s' % TempFormat)
return 0
if t1 < -40.0 or t1 > 59.9 or t2 < -40.0 or t2 > 59.9 or \
t3 < -40.0 or t3 > 59.9 or t4 < -40.0 or t4 > 59.9:
logerr('setTemps: one or more values out of range')
return 0
self._TemperatureFormat = f1
self._TempIndoorMinMax._Min._Value = t1
self._TempIndoorMinMax._Max._Value = t2
self._TempOutdoorMinMax._Min._Value = t3
self._TempOutdoorMinMax._Max._Value = t4
return 1
def setHums(self,InHumLo,InHumHi,OutHumLo,OutHumHi):
h1 = InHumLo
h2 = InHumHi
h3 = OutHumLo
h4 = OutHumHi
if h1 < 1 or h1 > 99 or h2 < 1 or h2 > 99 or \
h3 < 1 or h3 > 99 or h4 < 1 or h4 > 99:
logerr('setHums: one or more values out of range')
return 0
self._HumidityIndoorMinMax._Min._Value = h1
self._HumidityIndoorMinMax._Max._Value = h2
self._HumidityOutdoorMinMax._Min._Value = h3
self._HumidityOutdoorMinMax._Max._Value = h4
return 1
def setRain24H(self,RainFormat,Rain24hHi):
f1 = RainFormat
r1 = Rain24hHi
if f1 not in [ERainFormat.rfMm, ERainFormat.rfInch]:
logerr('setRain24: unknown format %s' % RainFormat)
return 0
if r1 < 0.0 or r1 > 9999.9:
logerr('setRain24: value outside range')
return 0
self._RainFormat = f1
self._Rain24HMax._Max._Value = r1
return 1
def setGust(self,WindSpeedFormat,GustHi):
# When the units of a max gust alarm are changed in the weather
# station itself, automatically the value is converted to the new
# unit and rounded to a whole number. Weewx receives a value
# converted to km/h.
#
# It is too much trouble to sort out what exactly the internal
# conversion algoritms are for the other wind units.
#
# Setting a value in km/h units is tested and works, so this will
# be the only option available.
f1 = WindSpeedFormat
g1 = GustHi
if f1 < EWindspeedFormat.wfMs or f1 > EWindspeedFormat.wfMph:
logerr('setGust: unknown format %s' % WindSpeedFormat)
return 0
if f1 != EWindspeedFormat.wfKmh:
logerr('setGust: only units of km/h are supported')
return 0
if g1 < 0.0 or g1 > 180.0:
logerr('setGust: value outside range')
return 0
self._WindSpeedFormat = f1
self._GustMax._Max._Value = int(g1) # apparently gust value is always an integer
return 1
def setPresRels(self,PressureFormat,PresRelhPaLo,PresRelhPaHi,PresRelinHgLo,PresRelinHgHi):
f1 = PressureFormat
p1 = PresRelhPaLo
p2 = PresRelhPaHi
p3 = PresRelinHgLo
p4 = PresRelinHgHi
if f1 not in [EPressureFormat.pfinHg, EPressureFormat.pfHPa]:
logerr('setPresRel: unknown format %s' % PressureFormat)
return 0
if p1 < 920.0 or p1 > 1080.0 or p2 < 920.0 or p2 > 1080.0 or \
p3 < 27.10 or p3 > 31.90 or p4 < 27.10 or p4 > 31.90:
logerr('setPresRel: value outside range')
return 0
self._RainFormat = f1
self._PressureRelative_hPaMinMax._Min._Value = p1
self._PressureRelative_hPaMinMax._Max._Value = p2
self._PressureRelative_inHgMinMax._Min._Value = p3
self._PressureRelative_inHgMinMax._Max._Value = p4
return 1
def getOutBufCS(self):
return self._OutBufCS
def getInBufCS(self):
return self._InBufCS
def setResetMinMaxFlags(self, resetMinMaxFlags):
logdbg('setResetMinMaxFlags: %s' % resetMinMaxFlags)
self._ResetMinMaxFlags = resetMinMaxFlags
def parseRain_3(self, number, buf, start, StartOnHiNibble, numbytes):
'''Parse 7-digit number with 3 decimals'''
num = int(number*1000)
parsebuf=[0]*7
for i in xrange(7-numbytes,7):
parsebuf[i] = num%10
num = num//10
if StartOnHiNibble:
buf[0][0+start] = parsebuf[6]*16 + parsebuf[5]
buf[0][1+start] = parsebuf[4]*16 + parsebuf[3]
buf[0][2+start] = parsebuf[2]*16 + parsebuf[1]
buf[0][3+start] = parsebuf[0]*16 + (buf[0][3+start] & 0xF)
else:
buf[0][0+start] = (buf[0][0+start] & 0xF0) + parsebuf[6]
buf[0][1+start] = parsebuf[5]*16 + parsebuf[4]
buf[0][2+start] = parsebuf[3]*16 + parsebuf[2]
buf[0][3+start] = parsebuf[1]*16 + parsebuf[0]
def parseWind_6(self, number, buf, start):
'''Parse float number to 6 bytes'''
num = int(number*100*256)
parsebuf=[0]*6
for i in xrange(0,6):
parsebuf[i] = num%16
num = num//16
buf[0][0+start] = parsebuf[5]*16 + parsebuf[4]
buf[0][1+start] = parsebuf[3]*16 + parsebuf[2]
buf[0][2+start] = parsebuf[1]*16 + parsebuf[0]
def parse_0(self, number, buf, start, StartOnHiNibble, numbytes):
'''Parse 5-digit number with 0 decimals'''
num = int(number)
nbuf=[0]*5
for i in xrange(5-numbytes,5):
nbuf[i] = num%10
num = num//10
if StartOnHiNibble:
buf[0][0+start] = nbuf[4]*16 + nbuf[3]
buf[0][1+start] = nbuf[2]*16 + nbuf[1]
buf[0][2+start] = nbuf[0]*16 + (buf[0][2+start] & 0x0F)
else:
buf[0][0+start] = (buf[0][0+start] & 0xF0) + nbuf[4]
buf[0][1+start] = nbuf[3]*16 + nbuf[2]
buf[0][2+start] = nbuf[1]*16 + nbuf[0]
def parse_1(self, number, buf, start, StartOnHiNibble, numbytes):
'''Parse 5 digit number with 1 decimal'''
self.parse_0(number*10.0, buf, start, StartOnHiNibble, numbytes)
def parse_2(self, number, buf, start, StartOnHiNibble, numbytes):
'''Parse 5 digit number with 2 decimals'''
self.parse_0(number*100.0, buf, start, StartOnHiNibble, numbytes)
def parse_3(self, number, buf, start, StartOnHiNibble, numbytes):
'''Parse 5 digit number with 3 decimals'''
self.parse_0(number*1000.0, buf, start, StartOnHiNibble, numbytes)
def read(self,buf):
nbuf=[0]
nbuf[0]=buf[0]
self._WindspeedFormat = (nbuf[0][4] >> 4) & 0xF
self._RainFormat = (nbuf[0][4] >> 3) & 1
self._PressureFormat = (nbuf[0][4] >> 2) & 1
self._TemperatureFormat = (nbuf[0][4] >> 1) & 1
self._ClockMode = nbuf[0][4] & 1
self._StormThreshold = (nbuf[0][5] >> 4) & 0xF
self._WeatherThreshold = nbuf[0][5] & 0xF
self._LowBatFlags = (nbuf[0][6] >> 4) & 0xF
self._LCDContrast = nbuf[0][6] & 0xF
self._WindDirAlarmFlags = (nbuf[0][7] << 8) | nbuf[0][8]
self._OtherAlarmFlags = (nbuf[0][9] << 8) | nbuf[0][10]
self._TempIndoorMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 11, 1)
self._TempIndoorMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 13, 0)
self._TempOutdoorMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 16, 1)
self._TempOutdoorMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 18, 0)
self._HumidityIndoorMinMax._Max._Value = USBHardware.toHumidity_2_0(nbuf, 21, 1)
self._HumidityIndoorMinMax._Min._Value = USBHardware.toHumidity_2_0(nbuf, 22, 1)
self._HumidityOutdoorMinMax._Max._Value = USBHardware.toHumidity_2_0(nbuf, 23, 1)
self._HumidityOutdoorMinMax._Min._Value = USBHardware.toHumidity_2_0(nbuf, 24, 1)
self._Rain24HMax._Max._Value = USBHardware.toRain_7_3(nbuf, 25, 0)
self._HistoryInterval = nbuf[0][29]
self._GustMax._Max._Value = USBHardware.toWindspeed_6_2(nbuf, 30)
(self._PressureRelative_hPaMinMax._Min._Value, self._PressureRelative_inHgMinMax._Min._Value) = USBHardware.readPressureShared(nbuf, 33, 1)
(self._PressureRelative_hPaMinMax._Max._Value, self._PressureRelative_inHgMinMax._Max._Value) = USBHardware.readPressureShared(nbuf, 38, 1)
self._ResetMinMaxFlags = (nbuf[0][43]) <<16 | (nbuf[0][44] << 8) | (nbuf[0][45])
self._InBufCS = (nbuf[0][46] << 8) | nbuf[0][47]
self._OutBufCS = calc_checksum(buf, 4, end=39) + 7
"""
Reset DewpointMax 80 00 00
Reset DewpointMin 40 00 00
not used 20 00 00
Reset WindchillMin* 10 00 00 *dateTime only; Min._Value is preserved
Reset TempOutMax 08 00 00
Reset TempOutMin 04 00 00
Reset TempInMax 02 00 00
Reset TempInMin 01 00 00
Reset Gust 00 80 00
not used 00 40 00
not used 00 20 00
not used 00 10 00
Reset HumOutMax 00 08 00
Reset HumOutMin 00 04 00
Reset HumInMax 00 02 00
Reset HumInMin 00 01 00
not used 00 00 80
Reset Rain Total 00 00 40
Reset last month? 00 00 20
Reset last week? 00 00 10
Reset Rain24H 00 00 08
Reset Rain1H 00 00 04
Reset PresRelMax 00 00 02
Reset PresRelMin 00 00 01
"""
#self._ResetMinMaxFlags = 0x000000
#logdbg('set _ResetMinMaxFlags to %06x' % self._ResetMinMaxFlags)
"""
setTemps(self,TempFormat,InTempLo,InTempHi,OutTempLo,OutTempHi)
setHums(self,InHumLo,InHumHi,OutHumLo,OutHumHi)
setPresRels(self,PressureFormat,PresRelhPaLo,PresRelhPaHi,PresRelinHgLo,PresRelinHgHi)
setGust(self,WindSpeedFormat,GustHi)
setRain24H(self,RainFormat,Rain24hHi)
"""
# Examples:
#self.setTemps(ETemperatureFormat.tfCelsius,1.0,41.0,2.0,42.0)
#self.setHums(41,71,42,72)
#self.setPresRels(EPressureFormat.pfHPa,960.1,1040.1,28.36,30.72)
#self.setGust(EWindspeedFormat.wfKmh,040.0)
#self.setRain24H(ERainFormat.rfMm,50.0)
# Set historyInterval to 5 minutes (default: 2 hours)
self._HistoryInterval = EHistoryInterval.hi05Min
# Clear all alarm flags, otherwise the datastream from the weather
# station will pause during an alarm and connection will be lost.
self._WindDirAlarmFlags = 0x0000
self._OtherAlarmFlags = 0x0000
def testConfigChanged(self,buf):
nbuf = [0]
nbuf[0] = buf[0]
nbuf[0][0] = 16*(self._WindspeedFormat & 0xF) + 8*(self._RainFormat & 1) + 4*(self._PressureFormat & 1) + 2*(self._TemperatureFormat & 1) + (self._ClockMode & 1)
nbuf[0][1] = self._WeatherThreshold & 0xF | 16 * self._StormThreshold & 0xF0
nbuf[0][2] = self._LCDContrast & 0xF | 16 * self._LowBatFlags & 0xF0
nbuf[0][3] = (self._OtherAlarmFlags >> 0) & 0xFF
nbuf[0][4] = (self._OtherAlarmFlags >> 8) & 0xFF
nbuf[0][5] = (self._WindDirAlarmFlags >> 0) & 0xFF
nbuf[0][6] = (self._WindDirAlarmFlags >> 8) & 0xFF
# reverse buf from here
self.parse_2(self._PressureRelative_inHgMinMax._Max._Value, nbuf, 7, 1, 5)
self.parse_1(self._PressureRelative_hPaMinMax._Max._Value, nbuf, 9, 0, 5)
self.parse_2(self._PressureRelative_inHgMinMax._Min._Value, nbuf, 12, 1, 5)
self.parse_1(self._PressureRelative_hPaMinMax._Min._Value, nbuf, 14, 0, 5)
self.parseWind_6(self._GustMax._Max._Value, nbuf, 17)
nbuf[0][20] = self._HistoryInterval & 0xF
self.parseRain_3(self._Rain24HMax._Max._Value, nbuf, 21, 0, 7)
self.parse_0(self._HumidityOutdoorMinMax._Max._Value, nbuf, 25, 1, 2)
self.parse_0(self._HumidityOutdoorMinMax._Min._Value, nbuf, 26, 1, 2)
self.parse_0(self._HumidityIndoorMinMax._Max._Value, nbuf, 27, 1, 2)
self.parse_0(self._HumidityIndoorMinMax._Min._Value, nbuf, 28, 1, 2)
self.parse_3(self._TempOutdoorMinMax._Max._Value + CWeatherTraits.TemperatureOffset(), nbuf, 29, 1, 5)
self.parse_3(self._TempOutdoorMinMax._Min._Value + CWeatherTraits.TemperatureOffset(), nbuf, 31, 0, 5)
self.parse_3(self._TempIndoorMinMax._Max._Value + CWeatherTraits.TemperatureOffset(), nbuf, 34, 1, 5)
self.parse_3(self._TempIndoorMinMax._Min._Value + CWeatherTraits.TemperatureOffset(), nbuf, 36, 0, 5)
# reverse buf to here
USBHardware.reverseByteOrder(nbuf, 7, 32)
# do not include the ResetMinMaxFlags bytes when calculating checksum
nbuf[0][39] = (self._ResetMinMaxFlags >> 16) & 0xFF
nbuf[0][40] = (self._ResetMinMaxFlags >> 8) & 0xFF
nbuf[0][41] = (self._ResetMinMaxFlags >> 0) & 0xFF
self._OutBufCS = calc_checksum(nbuf, 0, end=39) + 7
nbuf[0][42] = (self._OutBufCS >> 8) & 0xFF
nbuf[0][43] = (self._OutBufCS >> 0) & 0xFF
buf[0] = nbuf[0]
if self._OutBufCS == self._InBufCS and self._ResetMinMaxFlags == 0:
if DEBUG_CONFIG_DATA > 2:
logdbg('testConfigChanged: checksum not changed: OutBufCS=%04x' % self._OutBufCS)
changed = 0
else:
if DEBUG_CONFIG_DATA > 0:
logdbg('testConfigChanged: checksum or resetMinMaxFlags changed: OutBufCS=%04x InBufCS=%04x _ResetMinMaxFlags=%06x' % (self._OutBufCS, self._InBufCS, self._ResetMinMaxFlags))
if DEBUG_CONFIG_DATA > 1:
self.toLog()
changed = 1
return changed
def toLog(self):
logdbg('OutBufCS= %04x' % self._OutBufCS)
logdbg('InBufCS= %04x' % self._InBufCS)
logdbg('ClockMode= %s' % self._ClockMode)
logdbg('TemperatureFormat= %s' % self._TemperatureFormat)
logdbg('PressureFormat= %s' % self._PressureFormat)
logdbg('RainFormat= %s' % self._RainFormat)
logdbg('WindspeedFormat= %s' % self._WindspeedFormat)
logdbg('WeatherThreshold= %s' % self._WeatherThreshold)
logdbg('StormThreshold= %s' % self._StormThreshold)
logdbg('LCDContrast= %s' % self._LCDContrast)
logdbg('LowBatFlags= %01x' % self._LowBatFlags)
logdbg('WindDirAlarmFlags= %04x' % self._WindDirAlarmFlags)
logdbg('OtherAlarmFlags= %04x' % self._OtherAlarmFlags)
logdbg('HistoryInterval= %s' % self._HistoryInterval)
logdbg('TempIndoor_Min= %s' % self._TempIndoorMinMax._Min._Value)
logdbg('TempIndoor_Max= %s' % self._TempIndoorMinMax._Max._Value)
logdbg('TempOutdoor_Min= %s' % self._TempOutdoorMinMax._Min._Value)
logdbg('TempOutdoor_Max= %s' % self._TempOutdoorMinMax._Max._Value)
logdbg('HumidityIndoor_Min= %s' % self._HumidityIndoorMinMax._Min._Value)
logdbg('HumidityIndoor_Max= %s' % self._HumidityIndoorMinMax._Max._Value)
logdbg('HumidityOutdoor_Min= %s' % self._HumidityOutdoorMinMax._Min._Value)
logdbg('HumidityOutdoor_Max= %s' % self._HumidityOutdoorMinMax._Max._Value)
logdbg('Rain24HMax= %s' % self._Rain24HMax._Max._Value)
logdbg('GustMax= %s' % self._GustMax._Max._Value)
logdbg('PressureRel_hPa_Min= %s' % self._PressureRelative_hPaMinMax._Min._Value)
logdbg('PressureRel_inHg_Min= %s' % self._PressureRelative_inHgMinMax._Min._Value)
logdbg('PressureRel_hPa_Max= %s' % self._PressureRelative_hPaMinMax._Max._Value)
logdbg('PressureRel_inHg_Max= %s' % self._PressureRelative_inHgMinMax._Max._Value)
logdbg('ResetMinMaxFlags= %06x (Output only)' % self._ResetMinMaxFlags)
def asDict(self):
return {
'checksum_in': self._InBufCS,
'checksum_out': self._OutBufCS,
'format_clock': self._ClockMode,
'format_temperature': self._TemperatureFormat,
'format_pressure': self._PressureFormat,
'format_rain': self._RainFormat,
'format_windspeed': self._WindspeedFormat,
'threshold_weather': self._WeatherThreshold,
'threshold_storm': self._StormThreshold,
'lcd_contrast': self._LCDContrast,
'low_battery_flags': self._LowBatFlags,
'alarm_flags_wind_dir': self._WindDirAlarmFlags,
'alarm_flags_other': self._OtherAlarmFlags,
# 'reset_minmax_flags': self._ResetMinMaxFlags,
'history_interval': self._HistoryInterval,
'indoor_temp_min': self._TempIndoorMinMax._Min._Value,
'indoor_temp_min_time': self._TempIndoorMinMax._Min._Time,
'indoor_temp_max': self._TempIndoorMinMax._Max._Value,
'indoor_temp_max_time': self._TempIndoorMinMax._Max._Time,
'indoor_humidity_min': self._HumidityIndoorMinMax._Min._Value,
'indoor_humidity_min_time': self._HumidityIndoorMinMax._Min._Time,
'indoor_humidity_max': self._HumidityIndoorMinMax._Max._Value,
'indoor_humidity_max_time': self._HumidityIndoorMinMax._Max._Time,
'outdoor_temp_min': self._TempOutdoorMinMax._Min._Value,
'outdoor_temp_min_time': self._TempOutdoorMinMax._Min._Time,
'outdoor_temp_max': self._TempOutdoorMinMax._Max._Value,
'outdoor_temp_max_time': self._TempOutdoorMinMax._Max._Time,
'outdoor_humidity_min': self._HumidityOutdoorMinMax._Min._Value,
'outdoor_humidity_min_time':self._HumidityOutdoorMinMax._Min._Time,
'outdoor_humidity_max': self._HumidityOutdoorMinMax._Max._Value,
'outdoor_humidity_max_time':self._HumidityOutdoorMinMax._Max._Time,
'rain_24h_max': self._Rain24HMax._Max._Value,
'rain_24h_max_time': self._Rain24HMax._Max._Time,
'wind_gust_max': self._GustMax._Max._Value,
'wind_gust_max_time': self._GustMax._Max._Time,
'pressure_min': self._PressureRelative_hPaMinMax._Min._Value,
'pressure_min_time': self._PressureRelative_hPaMinMax._Min._Time,
'pressure_max': self._PressureRelative_hPaMinMax._Max._Value,
'pressure_max_time': self._PressureRelative_hPaMinMax._Max._Time
# do not bother with pressure inHg
}
class CHistoryData(object):
def __init__(self):
self.Time = None
self.TempIndoor = CWeatherTraits.TemperatureNP()
self.HumidityIndoor = CWeatherTraits.HumidityNP()
self.TempOutdoor = CWeatherTraits.TemperatureNP()
self.HumidityOutdoor = CWeatherTraits.HumidityNP()
self.PressureRelative = None
self.RainCounterRaw = 0
self.WindSpeed = CWeatherTraits.WindNP()
self.WindDirection = EWindDirection.wdNone
self.Gust = CWeatherTraits.WindNP()
self.GustDirection = EWindDirection.wdNone
def read(self, buf):
nbuf = [0]
nbuf[0] = buf[0]
self.Gust = USBHardware.toWindspeed_3_1(nbuf, 12, 0)
self.GustDirection = (nbuf[0][14] >> 4) & 0xF
self.WindSpeed = USBHardware.toWindspeed_3_1(nbuf, 14, 0)
self.WindDirection = (nbuf[0][14] >> 4) & 0xF
self.RainCounterRaw = USBHardware.toRain_3_1(nbuf, 16, 1)
self.HumidityOutdoor = USBHardware.toHumidity_2_0(nbuf, 17, 0)
self.HumidityIndoor = USBHardware.toHumidity_2_0(nbuf, 18, 0)
self.PressureRelative = USBHardware.toPressure_hPa_5_1(nbuf, 19, 0)
self.TempIndoor = USBHardware.toTemperature_3_1(nbuf, 23, 0)
self.TempOutdoor = USBHardware.toTemperature_3_1(nbuf, 22, 1)
self.Time = USBHardware.toDateTime(nbuf, 25, 1, 'HistoryData')
def toLog(self):
"""emit raw historical data"""
logdbg("Time %s" % self.Time)
logdbg("TempIndoor= %7.1f" % self.TempIndoor)
logdbg("HumidityIndoor= %7.0f" % self.HumidityIndoor)
logdbg("TempOutdoor= %7.1f" % self.TempOutdoor)
logdbg("HumidityOutdoor= %7.0f" % self.HumidityOutdoor)
logdbg("PressureRelative= %7.1f" % self.PressureRelative)
logdbg("RainCounterRaw= %7.3f" % self.RainCounterRaw)
logdbg("WindSpeed= %7.3f" % self.WindSpeed)
logdbg("WindDirection= % 3s" % CWeatherTraits.windDirMap[self.WindDirection])
logdbg("Gust= %7.3f" % self.Gust)
logdbg("GustDirection= % 3s" % CWeatherTraits.windDirMap[self.GustDirection])
def asDict(self):
"""emit historical data as a dict with weewx conventions"""
return {
'dateTime': tstr_to_ts(str(self.Time)),
'inTemp': self.TempIndoor,
'inHumidity': self.HumidityIndoor,
'outTemp': self.TempOutdoor,
'outHumidity': self.HumidityOutdoor,
'pressure': self.PressureRelative,
'rain': self.RainCounterRaw / 10, # weewx wants cm
'windSpeed': self.WindSpeed,
'windDir': getWindDir(self.WindDirection, self.WindSpeed),
'windGust': self.Gust,
'windGustDir': getWindDir(self.GustDirection, self.Gust),
}
class HistoryCache:
def __init__(self):
self.clear_records()
def clear_records(self):
self.since_ts = 0
self.num_rec = 0
self.start_index = None
self.next_index = None
self.records = []
self.num_outstanding_records = None
self.num_scanned = 0
self.last_ts = 0
class CDataStore(object):
class TTransceiverSettings(object):
def __init__(self):
self.VendorId = 0x6666
self.ProductId = 0x5555
self.VersionNo = 1
self.manufacturer = "LA CROSSE TECHNOLOGY"
self.product = "Weather Direct Light Wireless Device"
self.FrequencyStandard = EFrequency.fsUS
self.Frequency = getFrequency(self.FrequencyStandard)
self.SerialNumber = None
self.DeviceID = None
class TLastStat(object):
def __init__(self):
self.LastBatteryStatus = None
self.LastLinkQuality = None
self.LastHistoryIndex = None
self.LatestHistoryIndex = None
self.last_seen_ts = None
self.last_weather_ts = 0
self.last_history_ts = 0
self.last_config_ts = 0
def __init__(self):
self.transceiverPresent = False
self.commModeInterval = 3
self.registeredDeviceID = None
self.LastStat = CDataStore.TLastStat()
self.TransceiverSettings = CDataStore.TTransceiverSettings()
self.StationConfig = CWeatherStationConfig()
self.CurrentWeather = CCurrentWeatherData()
def getFrequencyStandard(self):
return self.TransceiverSettings.FrequencyStandard
def setFrequencyStandard(self, val):
logdbg('setFrequency: %s' % val)
self.TransceiverSettings.FrequencyStandard = val
self.TransceiverSettings.Frequency = getFrequency(val)
def getDeviceID(self):
return self.TransceiverSettings.DeviceID
def setDeviceID(self,val):
logdbg("setDeviceID: %04x" % val)
self.TransceiverSettings.DeviceID = val
def getRegisteredDeviceID(self):
return self.registeredDeviceID
def setRegisteredDeviceID(self, val):
if val != self.registeredDeviceID:
loginf("console is paired to device with ID %04x" % val)
self.registeredDeviceID = val
def getTransceiverPresent(self):
return self.transceiverPresent
def setTransceiverPresent(self, val):
self.transceiverPresent = val
def setLastStatCache(self, seen_ts=None,
quality=None, battery=None,
weather_ts=None,
history_ts=None,
config_ts=None):
if DEBUG_COMM > 1:
logdbg('setLastStatCache: seen=%s quality=%s battery=%s weather=%s history=%s config=%s' %
(seen_ts, quality, battery, weather_ts, history_ts, config_ts))
if seen_ts is not None:
self.LastStat.last_seen_ts = seen_ts
if quality is not None:
self.LastStat.LastLinkQuality = quality
if battery is not None:
self.LastStat.LastBatteryStatus = battery
if weather_ts is not None:
self.LastStat.last_weather_ts = weather_ts
if history_ts is not None:
self.LastStat.last_history_ts = history_ts
if config_ts is not None:
self.LastStat.last_config_ts = config_ts
def setLastHistoryIndex(self,val):
self.LastStat.LastHistoryIndex = val
def getLastHistoryIndex(self):
return self.LastStat.LastHistoryIndex
def setLatestHistoryIndex(self,val):
self.LastStat.LatestHistoryIndex = val
def getLatestHistoryIndex(self):
return self.LastStat.LatestHistoryIndex
def setCurrentWeather(self, data):
self.CurrentWeather = data
def getDeviceRegistered(self):
if ( self.registeredDeviceID is None
or self.TransceiverSettings.DeviceID is None
or self.registeredDeviceID != self.TransceiverSettings.DeviceID ):
return False
return True
def getCommModeInterval(self):
return self.commModeInterval
def setCommModeInterval(self,val):
logdbg("setCommModeInterval to %x" % val)
self.commModeInterval = val
def setTransceiverSerNo(self,val):
logdbg("setTransceiverSerialNumber to %s" % val)
self.TransceiverSettings.SerialNumber = val
def getTransceiverSerNo(self):
return self.TransceiverSettings.SerialNumber
class sHID(object):
"""USB driver abstraction"""
def __init__(self):
self.devh = None
self.timeout = 1000
self.last_dump = None
def open(self, vid, pid, did, serial):
device = self._find_device(vid, pid, did, serial)
if device is None:
logcrt('Cannot find USB device with Vendor=0x%04x ProdID=0x%04x Device=%s Serial=%s' % (vid, pid, did, serial))
raise weewx.WeeWxIOError('Unable to find transceiver on USB')
self._open_device(device)
def close(self):
self._close_device()
def _find_device(self, vid, pid, did, serial):
for bus in usb.busses():
for dev in bus.devices:
if dev.idVendor == vid and dev.idProduct == pid:
if did is None or dev.filename == did:
if serial is None:
loginf('found transceiver at bus=%s device=%s' %
(bus.dirname, dev.filename))
return dev
else:
handle = dev.open()
try:
buf = self.readCfg(handle, 0x1F9, 7)
sn = str("%02d" % (buf[0]))
sn += str("%02d" % (buf[1]))
sn += str("%02d" % (buf[2]))
sn += str("%02d" % (buf[3]))
sn += str("%02d" % (buf[4]))
sn += str("%02d" % (buf[5]))
sn += str("%02d" % (buf[6]))
if str(serial) == sn:
loginf('found transceiver at bus=%s device=%s serial=%s' % (bus.dirname, dev.filename, sn))
return dev
else:
loginf('skipping transceiver with serial %s (looking for %s)' % (sn, serial))
finally:
del handle
return None
def _open_device(self, dev, interface=0):
self.devh = dev.open()
if not self.devh:
raise weewx.WeeWxIOError('Open USB device failed')
loginf('manufacturer: %s' % self.devh.getString(dev.iManufacturer,30))
loginf('product: %s' % self.devh.getString(dev.iProduct,30))
loginf('interface: %d' % interface)
# be sure kernel does not claim the interface
try:
self.devh.detachKernelDriver(interface)
except Exception:
pass
# attempt to claim the interface
try:
logdbg('claiming USB interface %d' % interface)
self.devh.claimInterface(interface)
self.devh.setAltInterface(interface)
except usb.USBError, e:
self._close_device()
logcrt('Unable to claim USB interface %s: %s' % (interface, e))
raise weewx.WeeWxIOError(e)
# FIXME: this seems to be specific to ws28xx?
# FIXME: check return values
usbWait = 0.05
self.devh.getDescriptor(0x1, 0, 0x12)
time.sleep(usbWait)
self.devh.getDescriptor(0x2, 0, 0x9)
time.sleep(usbWait)
self.devh.getDescriptor(0x2, 0, 0x22)
time.sleep(usbWait)
self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
0xa, [], 0x0, 0x0, 1000)
time.sleep(usbWait)
self.devh.getDescriptor(0x22, 0, 0x2a9)
time.sleep(usbWait)
def _close_device(self):
try:
logdbg('releasing USB interface')
self.devh.releaseInterface()
except Exception:
pass
self.devh = None
def setTX(self):
buf = [0]*0x15
buf[0] = 0xD1
if DEBUG_COMM > 1:
self.dump('setTX', buf, fmt=DEBUG_DUMP_FORMAT)
self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
request=0x0000009,
buffer=buf,
value=0x00003d1,
index=0x0000000,
timeout=self.timeout)
def setRX(self):
buf = [0]*0x15
buf[0] = 0xD0
if DEBUG_COMM > 1:
self.dump('setRX', buf, fmt=DEBUG_DUMP_FORMAT)
self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
request=0x0000009,
buffer=buf,
value=0x00003d0,
index=0x0000000,
timeout=self.timeout)
def getState(self,StateBuffer):
buf = self.devh.controlMsg(requestType=usb.TYPE_CLASS |
usb.RECIP_INTERFACE | usb.ENDPOINT_IN,
request=usb.REQ_CLEAR_FEATURE,
buffer=0x0a,
value=0x00003de,
index=0x0000000,
timeout=self.timeout)
if DEBUG_COMM > 1:
self.dump('getState', buf, fmt=DEBUG_DUMP_FORMAT)
StateBuffer[0]=[0]*0x2
StateBuffer[0][0]=buf[1]
StateBuffer[0][1]=buf[2]
def readConfigFlash(self, addr, numBytes, data):
if numBytes > 512:
raise Exception('bad number of bytes')
while numBytes:
buf=[0xcc]*0x0f #0x15
buf[0] = 0xdd
buf[1] = 0x0a
buf[2] = (addr >>8) & 0xFF
buf[3] = (addr >>0) & 0xFF
if DEBUG_COMM > 1:
self.dump('readCfgFlash>', buf, fmt=DEBUG_DUMP_FORMAT)
self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
request=0x0000009,
buffer=buf,
value=0x00003dd,
index=0x0000000,
timeout=self.timeout)
buf = self.devh.controlMsg(requestType=usb.TYPE_CLASS |
usb.RECIP_INTERFACE |
usb.ENDPOINT_IN,
request=usb.REQ_CLEAR_FEATURE,
buffer=0x15,
value=0x00003dc,
index=0x0000000,
timeout=self.timeout)
new_data=[0]*0x15
if numBytes < 16:
for i in xrange(0, numBytes):
new_data[i] = buf[i+4]
numBytes = 0
else:
for i in xrange(0, 16):
new_data[i] = buf[i+4]
numBytes -= 16
addr += 16
if DEBUG_COMM > 1:
self.dump('readCfgFlash<', buf, fmt=DEBUG_DUMP_FORMAT)
data[0] = new_data # FIXME: new_data might be unset
def setState(self,state):
buf = [0]*0x15
buf[0] = 0xd7
buf[1] = state
if DEBUG_COMM > 1:
self.dump('setState', buf, fmt=DEBUG_DUMP_FORMAT)
self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
request=0x0000009,
buffer=buf,
value=0x00003d7,
index=0x0000000,
timeout=self.timeout)
def setFrame(self,data,numBytes):
buf = [0]*0x111
buf[0] = 0xd5
buf[1] = numBytes >> 8
buf[2] = numBytes
for i in xrange(0, numBytes):
buf[i+3] = data[i]
if DEBUG_COMM == 1:
self.dump('setFrame', buf, 'short')
elif DEBUG_COMM > 1:
self.dump('setFrame', buf, fmt=DEBUG_DUMP_FORMAT)
self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
request=0x0000009,
buffer=buf,
value=0x00003d5,
index=0x0000000,
timeout=self.timeout)
def getFrame(self,data,numBytes):
buf = self.devh.controlMsg(requestType=usb.TYPE_CLASS |
usb.RECIP_INTERFACE |
usb.ENDPOINT_IN,
request=usb.REQ_CLEAR_FEATURE,
buffer=0x111,
value=0x00003d6,
index=0x0000000,
timeout=self.timeout)
new_data=[0]*0x131
new_numBytes=(buf[1] << 8 | buf[2])& 0x1ff
for i in xrange(0, new_numBytes):
new_data[i] = buf[i+3]
if DEBUG_COMM == 1:
self.dump('getFrame', buf, 'short')
elif DEBUG_COMM > 1:
self.dump('getFrame', buf, fmt=DEBUG_DUMP_FORMAT)
data[0] = new_data
numBytes[0] = new_numBytes
def writeReg(self,regAddr,data):
buf = [0]*0x05
buf[0] = 0xf0
buf[1] = regAddr & 0x7F
buf[2] = 0x01
buf[3] = data
buf[4] = 0x00
if DEBUG_COMM > 1:
self.dump('writeReg', buf, fmt=DEBUG_DUMP_FORMAT)
self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
request=0x0000009,
buffer=buf,
value=0x00003f0,
index=0x0000000,
timeout=self.timeout)
def execute(self, command):
buf = [0]*0x0f #*0x15
buf[0] = 0xd9
buf[1] = command
if DEBUG_COMM > 1:
self.dump('execute', buf, fmt=DEBUG_DUMP_FORMAT)
self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
request=0x0000009,
buffer=buf,
value=0x00003d9,
index=0x0000000,
timeout=self.timeout)
def setPreamblePattern(self,pattern):
buf = [0]*0x15
buf[0] = 0xd8
buf[1] = pattern
if DEBUG_COMM > 1:
self.dump('setPreamble', buf, fmt=DEBUG_DUMP_FORMAT)
self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
request=0x0000009,
buffer=buf,
value=0x00003d8,
index=0x0000000,
timeout=self.timeout)
# three formats, long, short, auto. short shows only the first 16 bytes.
# long shows the full length of the buffer. auto shows the message length
# as indicated by the length in the message itself for setFrame and
# getFrame, or the first 16 bytes for any other message.
def dump(self, cmd, buf, fmt='auto'):
strbuf = ''
msglen = None
if fmt == 'auto':
if buf[0] in [0xd5, 0x00]:
msglen = buf[2] + 3 # use msg length for set/get frame
else:
msglen = 16 # otherwise do same as short format
elif fmt == 'short':
msglen = 16
for i,x in enumerate(buf):
strbuf += str('%02x ' % x)
if (i+1) % 16 == 0:
self.dumpstr(cmd, strbuf)
strbuf = ''
if msglen is not None and i+1 >= msglen:
break
if strbuf:
self.dumpstr(cmd, strbuf)
# filter output that we do not care about, pad the command string.
def dumpstr(self, cmd, strbuf):
pad = ' ' * (15-len(cmd))
# de15 is idle, de14 is intermediate
if strbuf in ['de 15 00 00 00 00 ','de 14 00 00 00 00 ']:
if strbuf != self.last_dump or DEBUG_COMM > 2:
logdbg('%s: %s%s' % (cmd, pad, strbuf))
self.last_dump = strbuf
else:
logdbg('%s: %s%s' % (cmd, pad, strbuf))
self.last_dump = None
def readCfg(self, handle, addr, numBytes):
while numBytes:
buf=[0xcc]*0x0f #0x15
buf[0] = 0xdd
buf[1] = 0x0a
buf[2] = (addr >>8) & 0xFF
buf[3] = (addr >>0) & 0xFF
handle.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE,
request=0x0000009,
buffer=buf,
value=0x00003dd,
index=0x0000000,
timeout=1000)
buf = handle.controlMsg(requestType=usb.TYPE_CLASS |
usb.RECIP_INTERFACE | usb.ENDPOINT_IN,
request=usb.REQ_CLEAR_FEATURE,
buffer=0x15,
value=0x00003dc,
index=0x0000000,
timeout=1000)
new_data=[0]*0x15
if numBytes < 16:
for i in xrange(0, numBytes):
new_data[i] = buf[i+4]
numBytes = 0
else:
for i in xrange(0, 16):
new_data[i] = buf[i+4]
numBytes -= 16
addr += 16
return new_data
class CCommunicationService(object):
reg_names = dict()
class AX5051RegisterNames:
REVISION = 0x0
SCRATCH = 0x1
POWERMODE = 0x2
XTALOSC = 0x3
FIFOCTRL = 0x4
FIFODATA = 0x5
IRQMASK = 0x6
IFMODE = 0x8
PINCFG1 = 0x0C
PINCFG2 = 0x0D
MODULATION = 0x10
ENCODING = 0x11
FRAMING = 0x12
CRCINIT3 = 0x14
CRCINIT2 = 0x15
CRCINIT1 = 0x16
CRCINIT0 = 0x17
FREQ3 = 0x20
FREQ2 = 0x21
FREQ1 = 0x22
FREQ0 = 0x23
FSKDEV2 = 0x25
FSKDEV1 = 0x26
FSKDEV0 = 0x27
IFFREQHI = 0x28
IFFREQLO = 0x29
PLLLOOP = 0x2C
PLLRANGING = 0x2D
PLLRNGCLK = 0x2E
TXPWR = 0x30
TXRATEHI = 0x31
TXRATEMID = 0x32
TXRATELO = 0x33
MODMISC = 0x34
FIFOCONTROL2 = 0x37
ADCMISC = 0x38
AGCTARGET = 0x39
AGCATTACK = 0x3A
AGCDECAY = 0x3B
AGCCOUNTER = 0x3C
CICDEC = 0x3F
DATARATEHI = 0x40
DATARATELO = 0x41
TMGGAINHI = 0x42
TMGGAINLO = 0x43
PHASEGAIN = 0x44
FREQGAIN = 0x45
FREQGAIN2 = 0x46
AMPLGAIN = 0x47
TRKFREQHI = 0x4C
TRKFREQLO = 0x4D
XTALCAP = 0x4F
SPAREOUT = 0x60
TESTOBS = 0x68
APEOVER = 0x70
TMMUX = 0x71
PLLVCOI = 0x72
PLLCPEN = 0x73
PLLRNGMISC = 0x74
AGCMANUAL = 0x78
ADCDCLEVEL = 0x79
RFMISC = 0x7A
TXDRIVER = 0x7B
REF = 0x7C
RXMISC = 0x7D
def __init__(self):
logdbg('CCommunicationService.init')
self.shid = sHID()
self.DataStore = CDataStore()
self.firstSleep = 1
self.nextSleep = 1
self.pollCount = 0
self.running = False
self.child = None
self.thread_wait = 60.0 # seconds
self.command = None
self.history_cache = HistoryCache()
# do not set time when offset to whole hour is <= _a3_offset
self._a3_offset = 3
def buildFirstConfigFrame(self, Buffer, cs):
logdbg('buildFirstConfigFrame: cs=%04x' % cs)
newBuffer = [0]
newBuffer[0] = [0]*9
comInt = self.DataStore.getCommModeInterval()
historyAddress = 0xFFFFFF
newBuffer[0][0] = 0xf0
newBuffer[0][1] = 0xf0
newBuffer[0][2] = EAction.aGetConfig
newBuffer[0][3] = (cs >> 8) & 0xff
newBuffer[0][4] = (cs >> 0) & 0xff
newBuffer[0][5] = (comInt >> 4) & 0xff
newBuffer[0][6] = (historyAddress >> 16) & 0x0f | 16 * (comInt & 0xf)
newBuffer[0][7] = (historyAddress >> 8 ) & 0xff
newBuffer[0][8] = (historyAddress >> 0 ) & 0xff
Buffer[0] = newBuffer[0]
Length = 0x09
return Length
def buildConfigFrame(self, Buffer):
logdbg("buildConfigFrame")
newBuffer = [0]
newBuffer[0] = [0]*48
cfgBuffer = [0]
cfgBuffer[0] = [0]*44
changed = self.DataStore.StationConfig.testConfigChanged(cfgBuffer)
if changed:
self.shid.dump('OutBuf', cfgBuffer[0], fmt='long')
newBuffer[0][0] = Buffer[0][0]
newBuffer[0][1] = Buffer[0][1]
newBuffer[0][2] = EAction.aSendConfig # 0x40 # change this value if we won't store config
newBuffer[0][3] = Buffer[0][3]
for i in xrange(0,44):
newBuffer[0][i+4] = cfgBuffer[0][i]
Buffer[0] = newBuffer[0]
Length = 48 # 0x30
else: # current config not up to date; do not write yet
Length = 0
return Length
def buildTimeFrame(self, Buffer, cs):
logdbg("buildTimeFrame: cs=%04x" % cs)
now = time.time()
tm = time.localtime(now)
newBuffer=[0]
newBuffer[0]=Buffer[0]
#00000000: d5 00 0c 00 32 c0 00 8f 45 25 15 91 31 20 01 00
#00000000: d5 00 0c 00 32 c0 06 c1 47 25 15 91 31 20 01 00
# 3 4 5 6 7 8 9 10 11
newBuffer[0][2] = EAction.aSendTime # 0xc0
newBuffer[0][3] = (cs >> 8) & 0xFF
newBuffer[0][4] = (cs >> 0) & 0xFF
newBuffer[0][5] = (tm[5] % 10) + 0x10 * (tm[5] // 10) #sec
newBuffer[0][6] = (tm[4] % 10) + 0x10 * (tm[4] // 10) #min
newBuffer[0][7] = (tm[3] % 10) + 0x10 * (tm[3] // 10) #hour
#DayOfWeek = tm[6] - 1; #ole from 1 - 7 - 1=Sun... 0-6 0=Sun
DayOfWeek = tm[6] #py from 0 - 6 - 0=Mon
newBuffer[0][8] = DayOfWeek % 10 + 0x10 * (tm[2] % 10) #DoW + Day
newBuffer[0][9] = (tm[2] // 10) + 0x10 * (tm[1] % 10) #day + month
newBuffer[0][10] = (tm[1] // 10) + 0x10 * ((tm[0] - 2000) % 10) #month + year
newBuffer[0][11] = (tm[0] - 2000) // 10 #year
Buffer[0]=newBuffer[0]
Length = 0x0c
return Length
def buildACKFrame(self, Buffer, action, cs, hidx=None):
if DEBUG_COMM > 1:
logdbg("buildACKFrame: action=%x cs=%04x historyIndex=%s" %
(action, cs, hidx))
newBuffer = [0]
newBuffer[0] = [0]*9
for i in xrange(0,2):
newBuffer[0][i] = Buffer[0][i]
comInt = self.DataStore.getCommModeInterval()
# When last weather is stale, change action to get current weather
# This is only needed during long periods of history data catchup
if self.command == EAction.aGetHistory:
now = int(time.time())
age = now - self.DataStore.LastStat.last_weather_ts
# Morphing action only with GetHistory requests,
# and stale data after a period of twice the CommModeInterval,
# but not with init GetHistory requests (0xF0)
if action == EAction.aGetHistory and age >= (comInt +1) * 2 and newBuffer[0][1] != 0xF0:
if DEBUG_COMM > 0:
logdbg('buildACKFrame: morphing action from %d to 5 (age=%s)' % (action, age))
action = EAction.aGetCurrent
if hidx is None:
if self.command == EAction.aGetHistory:
hidx = self.history_cache.next_index
elif self.DataStore.getLastHistoryIndex() is not None:
hidx = self.DataStore.getLastHistoryIndex()
if hidx is None or hidx < 0 or hidx >= WS28xxDriver.max_records:
haddr = 0xffffff
else:
haddr = index_to_addr(hidx)
if DEBUG_COMM > 1:
logdbg('buildACKFrame: idx: %s addr: 0x%04x' % (hidx, haddr))
newBuffer[0][2] = action & 0xF
newBuffer[0][3] = (cs >> 8) & 0xFF
newBuffer[0][4] = (cs >> 0) & 0xFF
newBuffer[0][5] = (comInt >> 4) & 0xFF
newBuffer[0][6] = (haddr >> 16) & 0x0F | 16 * (comInt & 0xF)
newBuffer[0][7] = (haddr >> 8 ) & 0xFF
newBuffer[0][8] = (haddr >> 0 ) & 0xFF
#d5 00 09 f0 f0 03 00 32 00 3f ff ff
Buffer[0]=newBuffer[0]
return 9
def handleWsAck(self,Buffer,Length):
logdbg('handleWsAck')
self.DataStore.setLastStatCache(seen_ts=int(time.time()),
quality=(Buffer[0][3] & 0x7f),
battery=(Buffer[0][2] & 0xf))
def handleConfig(self,Buffer,Length):
logdbg('handleConfig: %s' % self.timing())
if DEBUG_CONFIG_DATA > 2:
self.shid.dump('InBuf', Buffer[0], fmt='long')
newBuffer=[0]
newBuffer[0] = Buffer[0]
newLength = [0]
now = int(time.time())
self.DataStore.StationConfig.read(newBuffer)
if DEBUG_CONFIG_DATA > 1:
self.DataStore.StationConfig.toLog()
self.DataStore.setLastStatCache(seen_ts=now,
quality=(Buffer[0][3] & 0x7f),
battery=(Buffer[0][2] & 0xf),
config_ts=now)
cs = newBuffer[0][47] | (newBuffer[0][46] << 8)
self.setSleep(0.300,0.010)
newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetHistory, cs)
Buffer[0] = newBuffer[0]
Length[0] = newLength[0]
def handleCurrentData(self,Buffer,Length):
if DEBUG_WEATHER_DATA > 0:
logdbg('handleCurrentData: %s' % self.timing())
now = int(time.time())
# update the weather data cache if changed or stale
chksum = CCurrentWeatherData.calcChecksum(Buffer)
age = now - self.DataStore.LastStat.last_weather_ts
if age >= 10 or chksum != self.DataStore.CurrentWeather.checksum():
if DEBUG_WEATHER_DATA > 2:
self.shid.dump('CurWea', Buffer[0], fmt='long')
data = CCurrentWeatherData()
data.read(Buffer)
self.DataStore.setCurrentWeather(data)
if DEBUG_WEATHER_DATA > 1:
data.toLog()
# update the connection cache
self.DataStore.setLastStatCache(seen_ts=now,
quality=(Buffer[0][3] & 0x7f),
battery=(Buffer[0][2] & 0xf),
weather_ts=now)
newBuffer = [0]
newBuffer[0] = Buffer[0]
newLength = [0]
cs = newBuffer[0][5] | (newBuffer[0][4] << 8)
cfgBuffer = [0]
cfgBuffer[0] = [0]*44
changed = self.DataStore.StationConfig.testConfigChanged(cfgBuffer)
inBufCS = self.DataStore.StationConfig.getInBufCS()
if inBufCS == 0 or inBufCS != cs:
# request for a get config
logdbg('handleCurrentData: inBufCS of station does not match')
self.setSleep(0.300,0.010)
newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetConfig, cs)
elif changed:
# Request for a set config
logdbg('handleCurrentData: outBufCS of station changed')
self.setSleep(0.300,0.010)
newLength[0] = self.buildACKFrame(newBuffer, EAction.aReqSetConfig, cs)
else:
# Request for either a history message or a current weather message
# In general we don't use EAction.aGetCurrent to ask for a current
# weather message; they also come when requested for
# EAction.aGetHistory. This we learned from the Heavy Weather Pro
# messages (via USB sniffer).
self.setSleep(0.300,0.010)
newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetHistory, cs)
Length[0] = newLength[0]
Buffer[0] = newBuffer[0]
def handleHistoryData(self, buf, buflen):
if DEBUG_HISTORY_DATA > 0:
logdbg('handleHistoryData: %s' % self.timing())
now = int(time.time())
self.DataStore.setLastStatCache(seen_ts=now,
quality=(buf[0][3] & 0x7f),
battery=(buf[0][2] & 0xf),
history_ts=now)
newbuf = [0]
newbuf[0] = buf[0]
newlen = [0]
data = CHistoryData()
data.read(newbuf)
if DEBUG_HISTORY_DATA > 1:
data.toLog()
cs = newbuf[0][5] | (newbuf[0][4] << 8)
latestAddr = bytes_to_addr(buf[0][6], buf[0][7], buf[0][8])
thisAddr = bytes_to_addr(buf[0][9], buf[0][10], buf[0][11])
latestIndex = addr_to_index(latestAddr)
thisIndex = addr_to_index(thisAddr)
ts = tstr_to_ts(str(data.Time))
nrec = get_index(latestIndex - thisIndex)
logdbg('handleHistoryData: time=%s'
' this=%d (0x%04x) latest=%d (0x%04x) nrec=%d' %
(data.Time, thisIndex, thisAddr, latestIndex, latestAddr, nrec))
# track the latest history index
self.DataStore.setLastHistoryIndex(thisIndex)
self.DataStore.setLatestHistoryIndex(latestIndex)
nextIndex = None
if self.command == EAction.aGetHistory:
if self.history_cache.start_index is None:
nreq = 0
if self.history_cache.num_rec > 0:
loginf('handleHistoryData: request for %s records' %
self.history_cache.num_rec)
nreq = self.history_cache.num_rec
else:
loginf('handleHistoryData: request records since %s' %
weeutil.weeutil.timestamp_to_string(self.history_cache.since_ts))
span = int(time.time()) - self.history_cache.since_ts
# FIXME: what if we do not have config data yet?
cfg = self.getConfigData().asDict()
arcint = 60 * getHistoryInterval(cfg['history_interval'])
# FIXME: this assumes a constant archive interval for all
# records in the station history
nreq = int(span / arcint) + 5 # FIXME: punt 5
if nreq > nrec:
loginf('handleHistoryData: too many records requested (%d)'
', clipping to number stored (%d)' % (nreq, nrec))
nreq = nrec
idx = get_index(latestIndex - nreq)
self.history_cache.start_index = idx
self.history_cache.next_index = idx
self.DataStore.setLastHistoryIndex(idx)
self.history_cache.num_outstanding_records = nreq
logdbg('handleHistoryData: start_index=%s'
' num_outstanding_records=%s' % (idx, nreq))
nextIndex = idx
elif self.history_cache.next_index is not None:
# thisIndex should be the next record after next_index
thisIndexTst = get_next_index(self.history_cache.next_index)
if thisIndexTst == thisIndex:
self.history_cache.num_scanned += 1
# get the next history record
if ts is not None and self.history_cache.since_ts <= ts:
# Check if two records in a row with the same ts
if self.history_cache.last_ts == ts:
logdbg('handleHistoryData: remove previous record'
' with duplicate timestamp: %s' %
weeutil.weeutil.timestamp_to_string(ts))
self.history_cache.records.pop()
self.history_cache.last_ts = ts
# append to the history
logdbg('handleHistoryData: appending history record'
' %s: %s' % (thisIndex, data.asDict()))
self.history_cache.records.append(data.asDict())
self.history_cache.num_outstanding_records = nrec
elif ts is None:
logerr('handleHistoryData: skip record: this_ts=None')
else:
logdbg('handleHistoryData: skip record: since_ts=%s this_ts=%s' % (weeutil.weeutil.timestamp_to_string(self.history_cache.since_ts), weeutil.weeutil.timestamp_to_string(ts)))
self.history_cache.next_index = thisIndex
else:
loginf('handleHistoryData: index mismatch: %s != %s' %
(thisIndexTst, thisIndex))
nextIndex = self.history_cache.next_index
logdbg('handleHistoryData: next=%s' % nextIndex)
self.setSleep(0.300,0.010)
newlen[0] = self.buildACKFrame(newbuf, EAction.aGetHistory, cs, nextIndex)
buflen[0] = newlen[0]
buf[0] = newbuf[0]
def handleNextAction(self,Buffer,Length):
newBuffer = [0]
newBuffer[0] = Buffer[0]
newLength = [0]
newLength[0] = Length[0]
self.DataStore.setLastStatCache(seen_ts=int(time.time()),
quality=(Buffer[0][3] & 0x7f))
cs = newBuffer[0][5] | (newBuffer[0][4] << 8)
if (Buffer[0][2] & 0xEF) == EResponseType.rtReqFirstConfig:
logdbg('handleNextAction: a1 (first-time config)')
self.setSleep(0.085,0.005)
newLength[0] = self.buildFirstConfigFrame(newBuffer, cs)
elif (Buffer[0][2] & 0xEF) == EResponseType.rtReqSetConfig:
logdbg('handleNextAction: a2 (set config data)')
self.setSleep(0.085,0.005)
newLength[0] = self.buildConfigFrame(newBuffer)
elif (Buffer[0][2] & 0xEF) == EResponseType.rtReqSetTime:
logdbg('handleNextAction: a3 (set time data)')
now = int(time.time())
age = now - self.DataStore.LastStat.last_weather_ts
if age >= (self.DataStore.getCommModeInterval() +1) * 2:
# always set time if init or stale communication
self.setSleep(0.085,0.005)
newLength[0] = self.buildTimeFrame(newBuffer, cs)
else:
# When time is set at the whole hour we may get an extra
# historical record with time stamp a history period ahead
# We will skip settime if offset to whole hour is too small
# (time difference between WS and server < self._a3_offset)
m, s = divmod(now, 60)
h, m = divmod(m, 60)
logdbg('Time: hh:%02d:%02d' % (m,s))
if (m == 59 and s >= (60 - self._a3_offset)) or (m == 0 and s <= self._a3_offset):
logdbg('Skip settime; time difference <= %s s' % int(self._a3_offset))
self.setSleep(0.300,0.010)
newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetHistory, cs)
else:
# set time
self.setSleep(0.085,0.005)
newLength[0] = self.buildTimeFrame(newBuffer, cs)
else:
logdbg('handleNextAction: %02x' % (Buffer[0][2] & 0xEF))
self.setSleep(0.300,0.010)
newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetHistory, cs)
Length[0] = newLength[0]
Buffer[0] = newBuffer[0]
def generateResponse(self, Buffer, Length):
if DEBUG_COMM > 1:
logdbg('generateResponse: %s' % self.timing())
newBuffer = [0]
newBuffer[0] = Buffer[0]
newLength = [0]
newLength[0] = Length[0]
if Length[0] == 0:
raise BadResponse('zero length buffer')
bufferID = (Buffer[0][0] <<8) | Buffer[0][1]
respType = (Buffer[0][2] & 0xE0)
if DEBUG_COMM > 1:
logdbg("generateResponse: id=%04x resp=%x length=%x" %
(bufferID, respType, Length[0]))
deviceID = self.DataStore.getDeviceID()
if bufferID != 0xF0F0:
self.DataStore.setRegisteredDeviceID(bufferID)
if bufferID == 0xF0F0:
loginf('generateResponse: console not paired, attempting to pair to 0x%04x' % deviceID)
newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetConfig, deviceID, 0xFFFF)
elif bufferID == deviceID:
if respType == EResponseType.rtDataWritten:
# 00000000: 00 00 06 00 32 20
if Length[0] == 0x06:
self.DataStore.StationConfig.setResetMinMaxFlags(0)
self.shid.setRX()
raise DataWritten()
else:
raise BadResponse('len=%x resp=%x' % (Length[0], respType))
elif respType == EResponseType.rtGetConfig:
# 00000000: 00 00 30 00 32 40
if Length[0] == 0x30:
self.handleConfig(newBuffer, newLength)
else:
raise BadResponse('len=%x resp=%x' % (Length[0], respType))
elif respType == EResponseType.rtGetCurrentWeather:
# 00000000: 00 00 d7 00 32 60
if Length[0] == 0xd7: #215
self.handleCurrentData(newBuffer, newLength)
else:
raise BadResponse('len=%x resp=%x' % (Length[0], respType))
elif respType == EResponseType.rtGetHistory:
# 00000000: 00 00 1e 00 32 80
if Length[0] == 0x1e:
self.handleHistoryData(newBuffer, newLength)
else:
raise BadResponse('len=%x resp=%x' % (Length[0], respType))
elif respType == EResponseType.rtRequest:
# 00000000: 00 00 06 f0 f0 a1
# 00000000: 00 00 06 00 32 a3
# 00000000: 00 00 06 00 32 a2
if Length[0] == 0x06:
self.handleNextAction(newBuffer, newLength)
else:
raise BadResponse('len=%x resp=%x' % (Length[0], respType))
else:
raise BadResponse('unexpected response type %x' % respType)
elif respType not in [0x20,0x40,0x60,0x80,0xa1,0xa2,0xa3]:
# message is probably corrupt
raise BadResponse('unknown response type %x' % respType)
else:
msg = 'message from console contains unknown device ID (id=%04x resp=%x)' % (bufferID, respType)
logdbg(msg)
log_frame(Length[0],Buffer[0])
raise BadResponse(msg)
Buffer[0] = newBuffer[0]
Length[0] = newLength[0]
def configureRegisterNames(self):
self.reg_names[self.AX5051RegisterNames.IFMODE] =0x00
self.reg_names[self.AX5051RegisterNames.MODULATION]=0x41 #fsk
self.reg_names[self.AX5051RegisterNames.ENCODING] =0x07
self.reg_names[self.AX5051RegisterNames.FRAMING] =0x84 #1000:0100 ##?hdlc? |1000 010 0
self.reg_names[self.AX5051RegisterNames.CRCINIT3] =0xff
self.reg_names[self.AX5051RegisterNames.CRCINIT2] =0xff
self.reg_names[self.AX5051RegisterNames.CRCINIT1] =0xff
self.reg_names[self.AX5051RegisterNames.CRCINIT0] =0xff
self.reg_names[self.AX5051RegisterNames.FREQ3] =0x38
self.reg_names[self.AX5051RegisterNames.FREQ2] =0x90
self.reg_names[self.AX5051RegisterNames.FREQ1] =0x00
self.reg_names[self.AX5051RegisterNames.FREQ0] =0x01
self.reg_names[self.AX5051RegisterNames.PLLLOOP] =0x1d
self.reg_names[self.AX5051RegisterNames.PLLRANGING]=0x08
self.reg_names[self.AX5051RegisterNames.PLLRNGCLK] =0x03
self.reg_names[self.AX5051RegisterNames.MODMISC] =0x03
self.reg_names[self.AX5051RegisterNames.SPAREOUT] =0x00
self.reg_names[self.AX5051RegisterNames.TESTOBS] =0x00
self.reg_names[self.AX5051RegisterNames.APEOVER] =0x00
self.reg_names[self.AX5051RegisterNames.TMMUX] =0x00
self.reg_names[self.AX5051RegisterNames.PLLVCOI] =0x01
self.reg_names[self.AX5051RegisterNames.PLLCPEN] =0x01
self.reg_names[self.AX5051RegisterNames.RFMISC] =0xb0
self.reg_names[self.AX5051RegisterNames.REF] =0x23
self.reg_names[self.AX5051RegisterNames.IFFREQHI] =0x20
self.reg_names[self.AX5051RegisterNames.IFFREQLO] =0x00
self.reg_names[self.AX5051RegisterNames.ADCMISC] =0x01
self.reg_names[self.AX5051RegisterNames.AGCTARGET] =0x0e
self.reg_names[self.AX5051RegisterNames.AGCATTACK] =0x11
self.reg_names[self.AX5051RegisterNames.AGCDECAY] =0x0e
self.reg_names[self.AX5051RegisterNames.CICDEC] =0x3f
self.reg_names[self.AX5051RegisterNames.DATARATEHI]=0x19
self.reg_names[self.AX5051RegisterNames.DATARATELO]=0x66
self.reg_names[self.AX5051RegisterNames.TMGGAINHI] =0x01
self.reg_names[self.AX5051RegisterNames.TMGGAINLO] =0x96
self.reg_names[self.AX5051RegisterNames.PHASEGAIN] =0x03
self.reg_names[self.AX5051RegisterNames.FREQGAIN] =0x04
self.reg_names[self.AX5051RegisterNames.FREQGAIN2] =0x0a
self.reg_names[self.AX5051RegisterNames.AMPLGAIN] =0x06
self.reg_names[self.AX5051RegisterNames.AGCMANUAL] =0x00
self.reg_names[self.AX5051RegisterNames.ADCDCLEVEL]=0x10
self.reg_names[self.AX5051RegisterNames.RXMISC] =0x35
self.reg_names[self.AX5051RegisterNames.FSKDEV2] =0x00
self.reg_names[self.AX5051RegisterNames.FSKDEV1] =0x31
self.reg_names[self.AX5051RegisterNames.FSKDEV0] =0x27
self.reg_names[self.AX5051RegisterNames.TXPWR] =0x03
self.reg_names[self.AX5051RegisterNames.TXRATEHI] =0x00
self.reg_names[self.AX5051RegisterNames.TXRATEMID] =0x51
self.reg_names[self.AX5051RegisterNames.TXRATELO] =0xec
self.reg_names[self.AX5051RegisterNames.TXDRIVER] =0x88
def initTransceiver(self, frequency_standard):
logdbg('initTransceiver: frequency_standard=%s' % frequency_standard)
self.DataStore.setFrequencyStandard(frequency_standard)
self.configureRegisterNames()
# calculate the frequency then set frequency registers
freq = self.DataStore.TransceiverSettings.Frequency
loginf('base frequency: %d' % freq)
freqVal = long(freq / 16000000.0 * 16777216.0)
corVec = [None]
self.shid.readConfigFlash(0x1F5, 4, corVec)
corVal = corVec[0][0] << 8
corVal |= corVec[0][1]
corVal <<= 8
corVal |= corVec[0][2]
corVal <<= 8
corVal |= corVec[0][3]
loginf('frequency correction: %d (0x%x)' % (corVal,corVal))
freqVal += corVal
if not (freqVal % 2):
freqVal += 1
loginf('adjusted frequency: %d (0x%x)' % (freqVal,freqVal))
self.reg_names[self.AX5051RegisterNames.FREQ3] = (freqVal >>24) & 0xFF
self.reg_names[self.AX5051RegisterNames.FREQ2] = (freqVal >>16) & 0xFF
self.reg_names[self.AX5051RegisterNames.FREQ1] = (freqVal >>8) & 0xFF
self.reg_names[self.AX5051RegisterNames.FREQ0] = (freqVal >>0) & 0xFF
logdbg('frequency registers: %x %x %x %x' % (
self.reg_names[self.AX5051RegisterNames.FREQ3],
self.reg_names[self.AX5051RegisterNames.FREQ2],
self.reg_names[self.AX5051RegisterNames.FREQ1],
self.reg_names[self.AX5051RegisterNames.FREQ0]))
# figure out the transceiver id
buf = [None]
self.shid.readConfigFlash(0x1F9, 7, buf)
tid = buf[0][5] << 8
tid += buf[0][6]
loginf('transceiver identifier: %d (0x%04x)' % (tid,tid))
self.DataStore.setDeviceID(tid)
# figure out the transceiver serial number
sn = str("%02d"%(buf[0][0]))
sn += str("%02d"%(buf[0][1]))
sn += str("%02d"%(buf[0][2]))
sn += str("%02d"%(buf[0][3]))
sn += str("%02d"%(buf[0][4]))
sn += str("%02d"%(buf[0][5]))
sn += str("%02d"%(buf[0][6]))
loginf('transceiver serial: %s' % sn)
self.DataStore.setTransceiverSerNo(sn)
for r in self.reg_names:
self.shid.writeReg(r, self.reg_names[r])
def setup(self, frequency_standard,
vendor_id, product_id, device_id, serial,
comm_interval=3):
self.DataStore.setCommModeInterval(comm_interval)
self.shid.open(vendor_id, product_id, device_id, serial)
self.initTransceiver(frequency_standard)
self.DataStore.setTransceiverPresent(True)
def teardown(self):
self.shid.close()
# FIXME: make this thread-safe
def getWeatherData(self):
return self.DataStore.CurrentWeather
# FIXME: make this thread-safe
def getLastStat(self):
return self.DataStore.LastStat
# FIXME: make this thread-safe
def getConfigData(self):
return self.DataStore.StationConfig
def startCachingHistory(self, since_ts=0, num_rec=0):
self.history_cache.clear_records()
if since_ts is None:
since_ts = 0
self.history_cache.since_ts = since_ts
if num_rec > WS28xxDriver.max_records - 2:
num_rec = WS28xxDriver.max_records - 2
self.history_cache.num_rec = num_rec
self.command = EAction.aGetHistory
def stopCachingHistory(self):
self.command = None
def getUncachedHistoryCount(self):
return self.history_cache.num_outstanding_records
def getNextHistoryIndex(self):
return self.history_cache.next_index
def getNumHistoryScanned(self):
return self.history_cache.num_scanned
def getLatestHistoryIndex(self):
return self.DataStore.LastStat.LatestHistoryIndex
def getHistoryCacheRecords(self):
return self.history_cache.records
def clearHistoryCache(self):
self.history_cache.clear_records()
def startRFThread(self):
if self.child is not None:
return
logdbg('startRFThread: spawning RF thread')
self.running = True
self.child = threading.Thread(target=self.doRF)
self.child.setName('RFComm')
self.child.setDaemon(True)
self.child.start()
def stopRFThread(self):
self.running = False
logdbg('stopRFThread: waiting for RF thread to terminate')
self.child.join(self.thread_wait)
if self.child.isAlive():
logerr('unable to terminate RF thread after %d seconds' %
self.thread_wait)
else:
self.child = None
def isRunning(self):
return self.running
def doRF(self):
try:
logdbg('setting up rf communication')
self.doRFSetup()
logdbg('starting rf communication')
while self.running:
self.doRFCommunication()
except Exception, e:
logerr('exception in doRF: %s' % e)
if weewx.debug:
log_traceback(dst=syslog.LOG_DEBUG)
self.running = False
raise
finally:
logdbg('stopping rf communication')
# it is probably not necessary to have two setPreamblePattern invocations.
# however, HeavyWeatherPro seems to do it this way on a first time config.
# doing it this way makes configuration easier during a factory reset and
# when re-establishing communication with the station sensors.
def doRFSetup(self):
self.shid.execute(5)
self.shid.setPreamblePattern(0xaa)
self.shid.setState(0)
time.sleep(1)
self.shid.setRX()
self.shid.setPreamblePattern(0xaa)
self.shid.setState(0x1e)
time.sleep(1)
self.shid.setRX()
self.setSleep(0.085,0.005)
def doRFCommunication(self):
time.sleep(self.firstSleep)
self.pollCount = 0
while self.running:
StateBuffer = [None]
self.shid.getState(StateBuffer)
self.pollCount += 1
if StateBuffer[0][0] == 0x16:
break
time.sleep(self.nextSleep)
else:
return
DataLength = [0]
DataLength[0] = 0
FrameBuffer=[0]
FrameBuffer[0]=[0]*0x03
self.shid.getFrame(FrameBuffer, DataLength)
try:
self.generateResponse(FrameBuffer, DataLength)
self.shid.setFrame(FrameBuffer[0], DataLength[0])
except BadResponse, e:
logerr('generateResponse failed: %s' % e)
except DataWritten, e:
logdbg('SetTime/SetConfig data written')
self.shid.setTX()
# these are for diagnostics and debugging
def setSleep(self, firstsleep, nextsleep):
self.firstSleep = firstsleep
self.nextSleep = nextsleep
def timing(self):
s = self.firstSleep + self.nextSleep * (self.pollCount - 1)
return 'sleep=%s first=%s next=%s count=%s' % (
s, self.firstSleep, self.nextSleep, self.pollCount)
| sai9/weewx-gitsvn | bin/weewx/drivers/ws28xx.py | Python | gpl-3.0 | 174,398 |
# frozen_string_literal: true
RSpec.shared_examples 'vcs: having remote' do
describe '#remote' do
it 'sets @remote' do
object.remote = 'some-value'
expect(object.instance_variable_get(:@remote)).to eq 'some-value'
end
end
describe '#remote' do
subject(:remote) { object.remote }
let(:remote_class) { object.send(:remote_class) }
before do
allow(object).to receive(:remote_file_id).and_return 'remote-id'
allow(remote_class).to receive(:new).and_return 'new-instance'
hook if defined?(hook)
object.remote
end
it 'returns an instance of remote class' do
expect(remote_class).to have_received(:new).with('remote-id')
end
it 'sets @remote to new instance' do
expect(object.instance_variable_get(:@remote)).to eq 'new-instance'
end
context 'when @remote is already set' do
let(:hook) { object.instance_variable_set(:@remote, 'existing-value') }
it { is_expected.to eq 'existing-value' }
end
end
describe '#reload' do
before do
allow(object).to receive(:reset_remote)
allow(object.class).to receive(:find)
object.reload
end
it { expect(object).to have_received(:reset_remote) }
it 'reloads the object from database' do
expect(object.class).to have_received(:find)
end
end
describe '#reset_remote' do
subject(:reset_remote) { object.send(:reset_remote) }
before do
object.instance_variable_set(:@remote, 'some-value')
end
it 'resets @remote to nil' do
reset_remote
expect(object.instance_variable_get(:@remote)).to eq nil
end
end
describe '#remote_class' do
subject { object.send(:remote_class) }
it { is_expected.to eq Providers::GoogleDrive::FileSync }
end
end
| UpshiftOne/upshift | spec/models/shared_examples/vcs/having_remote.rb | Ruby | gpl-3.0 | 1,792 |
// NOTE: nbApp is defined in app.js
nbApp.directive("languageContainerDirective", function() {
return {
restrict : 'E',
templateUrl : 'js/templates/language-container.html',
scope: {
color: "@",
language: "@",
reading: "@",
writing: "@",
listening: "@",
speaking: "@",
flag: "@",
},
link: function(scope, element, attrs) {
scope.color = attrs.color;
scope.language = attrs.language;
scope.reading = attrs.reading;
scope.writing = attrs.writing;
scope.listening = attrs.listening;
scope.speaking = attrs.speaking;
scope.flag = attrs.flag;
scope.$watch('language', function(nV, oV) {
if(nV){
RadarChart.defaultConfig.color = function() {};
RadarChart.defaultConfig.radius = 3;
RadarChart.defaultConfig.w = 250;
RadarChart.defaultConfig.h = 250;
/*
* 0 - No Practical Proficiency
* 1 - Elementary Proficiency
* 2 - Limited Working Proficiency
* 3 - Minimum Professional Proficiency
* 4 - Full Professional Proficiency
* 5 - Native or Bilingual Proficiency
Read: the ability to read and understand texts written in the language
Write: the ability to formulate written texts in the language
Listen: the ability to follow and understand speech in the language
Speak: the ability to produce speech in the language and be understood by its speakers.
*/
var data = [
{
className: attrs.language, // optional can be used for styling
axes: [
{axis: "Reading", value: attrs.reading},
{axis: "Writing", value: attrs.writing},
{axis: "Listening", value: attrs.listening},
{axis: "Speaking", value: attrs.speaking},
]
},
];
function mapData() {
return data.map(function(d) {
return {
className: d.className,
axes: d.axes.map(function(axis) {
return {axis: axis.axis, value: axis.value};
})
};
});
}
// chart.config.w;
// chart.config.h;
// chart.config.axisText = true;
// chart.config.levels = 5;
// chart.config.maxValue = 5;
// chart.config.circles = true;
// chart.config.actorLegend = 1;
var chart = RadarChart.chart();
var cfg = chart.config(); // retrieve default config
cfg = chart.config({axisText: true, levels: 5, maxValue: 5, circles: true}); // retrieve default config
var svg = d3.select('.' + attrs.language).append('svg')
.attr('width', 250)
.attr('height', 270);
svg.append('g').classed('single', 1).datum(mapData()).call(chart);
console.log('Rendering new language Radar Viz! --> ' + attrs.language);
}
})
}
};
});
| nbuechler/nb.com-v8 | js/directives/language-container-directive.js | JavaScript | gpl-3.0 | 3,501 |
//=============================================================================
/*! return transposed _dsymatrix */
inline _dsymatrix t(const _dsymatrix& mat)
{CPPL_VERBOSE_REPORT;
#ifdef CPPL_DEBUG
WARNING_REPORT;
std::cerr << "This function call has no effect since the matrix is symmetric." << std::endl;
#endif//CPPL_DEBUG
return mat;
}
//=============================================================================
/*! return its inverse matrix */
inline _dsymatrix i(const _dsymatrix& mat)
{CPPL_VERBOSE_REPORT;
dsymatrix mat_cp(mat);
dsymatrix mat_inv(mat_cp.n);
mat_inv.identity();
char UPLO('l');
CPPL_INT NRHS(mat.n), LDA(mat.n), *IPIV(new CPPL_INT[mat.n]), LDB(mat.n), LWORK(-1), INFO(1);
double *WORK( new double[1] );
dsysv_(&UPLO, &mat_cp.n, &NRHS, mat_cp.array, &LDA, IPIV, mat_inv.array, &LDB, WORK, &LWORK, &INFO);
LWORK = CPPL_INT(WORK[0]);
delete [] WORK;
WORK = new double[LWORK];
dsysv_(&UPLO, &mat_cp.n, &NRHS, mat_cp.array, &LDA, IPIV, mat_inv.array, &LDB, WORK, &LWORK, &INFO);
delete [] WORK;
delete [] IPIV;
if(INFO!=0){
WARNING_REPORT;
std::cerr << "Serious trouble happend. INFO = " << INFO << "." << std::endl;
}
return _(mat_inv);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//=============================================================================
/*! search the index of element having the largest absolute value
in 0-based numbering system */
inline void idamax(CPPL_INT& i, CPPL_INT& j, const _dsymatrix& mat)
{CPPL_VERBOSE_REPORT;
dsymatrix newmat =mat;
idamax(i, j, newmat);
}
//=============================================================================
/*! return its largest absolute value */
inline double damax(const _dsymatrix& mat)
{CPPL_VERBOSE_REPORT;
dsymatrix newmat =mat;
return damax(newmat);
}
| j-otsuki/SpM | thirdparty/cpplapack/include/_dsymatrix-/_dsymatrix-calc.hpp | C++ | gpl-3.0 | 2,027 |
package name.parsak.controller;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import name.parsak.api.Tcpip;
import name.parsak.dto.UsrDptRole;
import name.parsak.model.Department;
import name.parsak.model.Menu;
import name.parsak.model.Role;
import name.parsak.model.User;
import name.parsak.service.UserDBService;
@Controller
public class WebController {
final private String project_name = "JWC";
final private String user_cookie_name = "user";
final private String blank = "";
final private int max_login_time = 7200;
private UserDBService userDBService;
@Autowired(required=true)
@Qualifier(value="UserDBService")
public void setUserDBService(UserDBService us){
this.userDBService = us;
}
// Create Admin User, if it doesn't exist
@RequestMapping(value="setup")
public String setup() {
this.userDBService.setup();
return "redirect:/";
}
// Default page
@RequestMapping({"/", "index"})
public String index(
Model model,
@CookieValue(value = user_cookie_name, defaultValue = blank) String userid,
@ModelAttribute(project_name)Menu menu) {
if (! userid.equals(blank)) {
int id = Integer.parseInt(userid);
User user = this.userDBService.getUserById(id);
if (user != null) {
model.addAttribute("id", userid);
model.addAttribute("name", user.getName());
model.addAttribute("lastname", user.getLastname());
model.addAttribute("email", user.getEmail());
if (this.userDBService.isUserAdmin(user)) {
model.addAttribute("admin", "true");
}
try {
String name = menu.getName();
if (name != null) {
this.userDBService.AddMenu(menu);
}
} catch (NullPointerException e) {}
// menu.id is used to browse
long menuid = menu.getId();
model.addAttribute("menu", this.userDBService.getMenuDtoById(menuid));
model.addAttribute("parent", menuid);
model.addAttribute("menulist", this.userDBService.getMenuByParent(menuid));
}
}
return "index";
}
// Login User
@RequestMapping(value="login")
public String login(
Model model, @ModelAttribute(project_name)User u,
HttpServletResponse response) {
Long userid = u.getId();
// In case user enters /login without submitting a login form
if (userid != 0) {
User user = this.userDBService.getUser(u.getId(), u.getPassword());
if (user != null) {
Cookie cookie = new Cookie(user_cookie_name, String.valueOf(user.getId()));
cookie.setMaxAge(max_login_time);
response.addCookie(cookie);
}
}
return "redirect:/";
}
// Logout User
@RequestMapping(value="logout")
public String logout(
HttpServletResponse response) {
Cookie cookie = new Cookie(user_cookie_name,blank);
cookie.setMaxAge(0);
response.addCookie(cookie);
return "redirect:/";
}
// Display All Users
@RequestMapping(value="users")
public String users(
Model model,
@CookieValue(value = user_cookie_name, defaultValue = blank) String userid) {
if (! userid.equals(blank)) {
int adminid = Integer.parseInt(userid);
User admin = this.userDBService.getUserById(adminid);
if (admin != null) {
if (this.userDBService.isUserAdmin(admin)) {
model.addAttribute("id", userid);
model.addAttribute("admin", "true");
model.addAttribute("userslist", this.userDBService.listUsers());
return "users";
}
}
}
return "redirect:/";
}
// Display All Departments
@RequestMapping(value="departments")
public String departments(
Model model,
@CookieValue(value = user_cookie_name, defaultValue = blank) String userid) {
if (! userid.equals(blank)) {
int adminid = Integer.parseInt(userid);
User admin = this.userDBService.getUserById(adminid);
if (admin != null) {
if (this.userDBService.isUserAdmin(admin)) {
model.addAttribute("id", userid);
model.addAttribute("admin", "true");
model.addAttribute("deptlist", this.userDBService.listDepartments());
model.addAttribute("rolelist", this.userDBService.listRoles());
return "departments";
}
}
}
return "redirect:/";
}
@RequestMapping(value="department")
public String department(
Model model,
@CookieValue(value = user_cookie_name, defaultValue = blank) String userid,
@ModelAttribute(project_name)UsrDptRole usrdptrole){
if (! userid.equals(blank)) {
int adminid = Integer.parseInt(userid);
User admin = this.userDBService.getUserById(adminid);
if (admin != null) {
if (this.userDBService.isUserAdmin(admin)) {
model.addAttribute("id", userid);
model.addAttribute("admin", "true");
String DeptName = usrdptrole.getDeptname();
System.out.println(">> Displaying "+DeptName);
Department department = this.userDBService.getDepartmentByName(DeptName);
model.addAttribute("department", department.getDepartment_name());
//
model.addAttribute("deptrolelist", this.userDBService.getDepartmentUsers(department));
return "department";
}
}
}
return "redirect:/";
}
@RequestMapping(value="add_user")
public String add_user(
Model model,
@ModelAttribute(project_name)User user,
HttpServletResponse response) {
String user_name = null;
String user_lastname = null;
String user_email = null;
String user_password = null;
try {
user_name = user.getName();
user_lastname = user.getLastname();
user_email = user.getEmail();
user_password = user.getPassword();
} catch (NullPointerException e) {}
if (user_name != null && user_lastname != null && user_email != null && user_password != null) {
this.userDBService.addUser(user);
}
return "redirect:/users";
}
@RequestMapping(value="update_user")
public String update_user(
Model model,
@ModelAttribute(project_name)User user,
HttpServletResponse response) {
String user_name = null;
String user_lastname = null;
String user_email = null;
String user_password = null;
try {
user_name = user.getName();
user_lastname = user.getLastname();
user_email = user.getEmail();
user_password = user.getPassword();
} catch (NullPointerException e) {}
if (user_name != null && user_lastname != null && user_email != null && user_password != null) {
this.userDBService.updateUser(user);
}
return "redirect:/user"+user.getId();
}
// Assign UserRole to a user
@RequestMapping(value="add_user_role")
public String AddUserRole(@ModelAttribute(project_name)UsrDptRole usrdptrole) {
String deptname = usrdptrole.getDeptname();
String rolename = usrdptrole.getRolename();
long userid = usrdptrole.getUserid();
if (userid != 0 && !deptname.equals(blank) && !rolename.equals(blank)) {
User user = this.userDBService.getUserById((int) userid);
Department department = this.userDBService.getDepartmentByName(deptname);
Role role = this.userDBService.getRoleByName(rolename);
this.userDBService.AddUserRole(user, department, role);
}
return "redirect:/user"+userid;
}
@RequestMapping(value="remove_userrole")
public String RemoveUserRole(@ModelAttribute(project_name) UsrDptRole deptrole) {
this.userDBService.removeUserRoleById(deptrole.getId());
return "redirect:/user"+deptrole.getUserid();
}
// Display User{id}
@RequestMapping(value="/user{id}")
public String user(
Model model,
@CookieValue(value = user_cookie_name, defaultValue = blank) String userid,
@PathVariable("id") int id) {
if (! userid.equals(blank)) {
int adminid = Integer.parseInt(userid);
User admin = this.userDBService.getUserById(adminid);
if (admin != null) {
if (this.userDBService.isUserAdmin(admin)) {
model.addAttribute("id", userid);
model.addAttribute("admin", "true");
User user = this.userDBService.getUserById(id);
model.addAttribute("userid",user.getId());
model.addAttribute("name",user.getName());
model.addAttribute("lastname",user.getLastname());
model.addAttribute("email",user.getEmail());
model.addAttribute("User", user); // To populate Edit Form
model.addAttribute("deptrolelist",this.userDBService.getUsrDptRoles(user));
model.addAttribute("deptlist", this.userDBService.listDepartments());
model.addAttribute("rolelist", this.userDBService.listRoles());
return "user";
}
}
}
return "redirect:/";
}
// Remove User{id}
@RequestMapping(value="/removeuser{id}")
public String removeuser(
Model model,
@CookieValue(value = user_cookie_name, defaultValue = blank) String userid,
@PathVariable("id") int id) {
if (! userid.equals(blank)) {
int adminid = Integer.parseInt(userid);
User admin = this.userDBService.getUserById(adminid);
if (admin != null) {
if (this.userDBService.isUserAdmin(admin)) {
model.addAttribute("id", userid);
model.addAttribute("admin", "true");
User user = this.userDBService.getUserById(id);
this.userDBService.RemoveUserRoleByUser(user);
this.userDBService.removeUser(user);
return "redirect:/users";
}
}
}
return "redirect:/";
}
@RequestMapping(value="/add_department")
public String addNewDepartment(@ModelAttribute(project_name) UsrDptRole deptrole) {
this.userDBService.AddDepartment(deptrole.getDeptname());
return "redirect:/departments";
}
@RequestMapping(value="/add_role")
public String addNewRole(@ModelAttribute(project_name) UsrDptRole deptrole) {
this.userDBService.AddRole(deptrole.getRolename());
return "redirect:/departments";
}
@RequestMapping(value="/api_test")
public String test_api(Model model) {
Tcpip tcpip = new Tcpip();
String response = tcpip.get("http://www.google.com");
model.addAttribute("response", response);
return "api_test";
}
} | yparsak/JWC | src/main/java/name/parsak/controller/WebController.java | Java | gpl-3.0 | 10,545 |
#pragma once
//
// njhseq - A library for analyzing sequence data
// Copyright (C) 2012-2018 Nicholas Hathaway <[email protected]>,
//
// This file is part of njhseq.
//
// njhseq is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// njhseq is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with njhseq. If not, see <http://www.gnu.org/licenses/>.
//
//
// alnInfoHolder.hpp
//
// Created by Nicholas Hathaway on 1/13/14.
//
#include "njhseq/alignment/alnCache/alnInfoHolderBase.hpp"
#if __APPLE__ == 1 && __cpp_lib_shared_timed_mutex < 201402L && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ <= 101106
#include <sharedMutex.h>
#else
#include <shared_mutex>
#endif
namespace njhseq {
class alnInfoMasterHolder {
public:
// constructors
alnInfoMasterHolder();
alnInfoMasterHolder(const gapScoringParameters & gapPars,
const substituteMatrix & scoringArray);
alnInfoMasterHolder(const std::string &masterDirName, const gapScoringParameters & gapPars,
const substituteMatrix & scoringArray, bool verbose = false);
// members
std::unordered_map<std::string, alnInfoHolderBase<alnInfoLocal>> localHolder_;
std::unordered_map<std::string, alnInfoHolderBase<alnInfoGlobal>> globalHolder_;
std::hash<std::string> strH_;
void clearHolders();
void addHolder(const gapScoringParameters & gapPars,
const substituteMatrix & scoringArray);
// reading
void read(const std::string &masterDirName, bool verbose = false);
// writing
void write(const std::string &masterDirName, bool verbose = false);
void mergeOtherHolder(const alnInfoMasterHolder & otherHolder);
};
namespace alignment {
static std::mutex alnCacheDirSearchLock;
static std::unordered_map<std::string, std::unique_ptr<std::shared_timed_mutex>> alnCacheDirLocks;
} // namespace alignment
} // namespace njhseq
| bailey-lab/bibseq | src/njhseq/alignment/alnCache/alnInfoHolder.hpp | C++ | gpl-3.0 | 2,293 |
#include "common_header.h"
namespace {
using ArrayType = std::vector<int>;
/** Given a sorted array and a number x, find the pair in array whose sum is closest to x
*
* @reference https://www.geeksforgeeks.org/given-sorted-array-number-x-find-pair-array-whose-sum-closest-x/
*
* Given a sorted array and a number x, find a pair in array whose sum is closest to x.
*
* @reference 2 Sum Closest
* https://aaronice.gitbook.io/lintcode/high_frequency/2sum_closest
*
* Given an array nums of n integers, find two integers in nums such that the sum is
* closest to a given number, target. Return the difference between the sum of the two
* integers and the target.
*
* @reference Two elements whose sum is closest to zero
* https://www.geeksforgeeks.org/two-elements-whose-sum-is-closest-to-zero/
*/
auto ClosestSumPair_Sorted_TwoPointer(const ArrayType &elements,
const ArrayType::value_type x) {
assert(std::is_sorted(elements.cbegin(), elements.cend()));
auto diff = std::numeric_limits<ArrayType::value_type>::max();
std::pair<ArrayType::value_type, ArrayType::value_type> output;
if (not elements.empty()) {
auto left = elements.cbegin();
auto right = std::prev(elements.cend());
while (left != right and diff) {
const auto sum = *left + *right;
const auto new_diff = std::abs(sum - x);
if (new_diff < diff) {
diff = new_diff;
output = std::pair(*left, *right);
}
if (sum < x) {
++left;
} else {
--right;
}
}
}
return output;
}
inline auto
ClosestSumPair_Sort(ArrayType elements, const ArrayType::value_type x) {
std::sort(elements.begin(), elements.end());
return ClosestSumPair_Sorted_TwoPointer(elements, x);
}
/**
* @reference 3Sum Closest
* https://leetcode.com/problems/3sum-closest/
*
* Given an array nums of n integers and an integer target, find three integers in nums
* such that the sum is closest to target. Return the sum of the three integers. You may
* assume that each input would have exactly one solution.
*/
auto ThreeSum(ArrayType nums, const int target) {
std::sort(nums.begin(), nums.end());
int min_diff = INT_MAX;
int result = 0;
for (std::size_t i = 0; i < nums.size() and min_diff; ++i) {
int left = i + 1;
int right = nums.size() - 1;
while (left < right) {
const int sum = nums[i] + nums[left] + nums[right];
if (std::abs(target - sum) < min_diff) {
min_diff = std::abs(target - sum);
result = sum;
}
if (sum < target) {
++left;
} else {
--right;
}
}
}
return result;
}
/**
* @reference Two Sum Less Than K
* https://wentao-shao.gitbook.io/leetcode/two-pointers/1099.two-sum-less-than-k
*
* Given an array A of integers and integer K, return the maximum S such that there
* exists i < j with A[i] + A[j] = S and S < K. If no i, j exist satisfying this
* equation, return -1.
*/
auto TwoSumLessThan(ArrayType nums, const int K) {
std::sort(nums.begin(), nums.end());
int left = 0;
int right = nums.size() - 1;
int result = -1;
while (left < right) {
const auto sum = nums[left] + nums[right];
if (sum >= K) {
--right;
} else {
result = std::max(result, sum);
++left;
}
}
return result;
}
}//namespace
const ArrayType SAMPLE1 = {10, 22, 28, 29, 30, 40};
const ArrayType SAMPLE2 = {1, 3, 4, 7, 10};
const ArrayType SAMPLE3 = {1, 60, -10, 70, -80, 85};
THE_BENCHMARK(ClosestSumPair_Sorted_TwoPointer, SAMPLE1, 54);
SIMPLE_TEST(ClosestSumPair_Sorted_TwoPointer, TestSample1, std::pair(22, 30),
SAMPLE1, 54);
SIMPLE_TEST(ClosestSumPair_Sorted_TwoPointer, TestSample2, std::pair(4, 10),
SAMPLE2, 15);
SIMPLE_TEST(ClosestSumPair_Sort, TestSample3, std::pair(-80, 85), SAMPLE3, 0);
const ArrayType SAMPLE4 = {-1, 2, 1, -4};
THE_BENCHMARK(ThreeSum, SAMPLE4, 1);
SIMPLE_TEST(ThreeSum, TestSample4, 2, SAMPLE4, 1);
const ArrayType SAMPLE1L = {34, 23, 1, 24, 75, 33, 54, 8};
const ArrayType SAMPLE2L = {10, 20, 30};
THE_BENCHMARK(TwoSumLessThan, SAMPLE1L, 60);
SIMPLE_TEST(TwoSumLessThan, TestSample1, 58, SAMPLE1L, 60);
SIMPLE_TEST(TwoSumLessThan, TestSample2, -1, SAMPLE2L, 15);
| yyang-even/algorithms | mathematics/arithmetics/sum/closest_sum_pair_to_x.cpp | C++ | gpl-3.0 | 4,582 |
<!DOCTYPE html>
<html lang="en" prefix="og: http://ogp.me/ns# fb: https://www.facebook.com/2008/fbml" >
<head>
<title>misc - jm33_ng</title>
<!-- Using the latest rendering mode for IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://jm33.me/img/icon.png" rel="icon">
<meta name="author" content="jm33" />
<meta name="keywords" content="misc" />
<!-- Open Graph tags -->
<meta property="og:site_name" content="jm33_ng" />
<meta property="og:type" content="website" />
<meta property="og:title" content="jm33_ng" />
<meta property="og:url" content="https://jm33.me" />
<meta property="og:description" content="jm33_ng" />
<!-- Bootstrap -->
<link rel="stylesheet" href="https://jm33.me/theme/css/bootstrap.sandstone.min.css" type="text/css" />
<link href="https://jm33.me/theme/css/font-awesome.min.css" rel="stylesheet">
<link href="https://jm33.me/theme/css/pygments/monokai.css" rel="stylesheet">
<link rel="stylesheet" href="https://jm33.me/theme/css/style.css" type="text/css" />
<!-- FontAwesome -->
<!-- -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Noto Sans SC font -->
<!-- -->
<link href="https://fonts.googleapis.com/css?family=Noto+Sans+SC&display=swap" rel="stylesheet">
<!-- Source Code Pro -->
<link href="https://fonts.googleapis.com/css?family=Source+Code+Pro&display=swap" rel="stylesheet">
<!-- asciinema css -->
<link rel="stylesheet" type="text/css" href="https://jm33.me/theme/css/asciinema-player.css" />
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="https://jm33.me/" class="navbar-brand">
jm33_ng </a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li >
<a href="https://jm33.me/category/cryptography.html">Cryptography</a>
</li>
<li >
<a href="https://jm33.me/category/ctf.html">Ctf</a>
</li>
<li class="active" >
<a href="https://jm33.me/category/misc.html">Misc</a>
</li>
<li >
<a href="https://jm33.me/category/pentest.html">Pentest</a>
</li>
<li >
<a href="https://jm33.me/category/programming.html">Programming</a>
</li>
<li >
<a href="https://jm33.me/category/tools.html">Tools</a>
</li>
<li >
<a href="https://jm33.me/category/vulnerabilities.html">Vulnerabilities</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
</div> <!-- /.navbar -->
<!-- Banner -->
<style>
#banner {
background-image:url("https://jm33.me/img/banner.webp");
}
</style>
<div id="banner">
<div class="container">
<div class="copy" style="border-radius: 4px">
<h1>jm33_ng</h1>
<br>
<p class="intro">an <s>infosec</s> newbie's <s>tech</s> blog</p>
</div>
</div>
</div> <!-- End Banner -->
<!-- Content Container -->
<div class="container">
<div class="row">
<div class="col-sm-9">
<article>
<h2><a href="https://jm33.me/sh4d0ws0cks-over-obfsproxy-scramblesuit.html">Sh4d0ws0cks Over Obfsproxy (Scramblesuit)</a></h2>
<div class="well well-sm">
<footer class="post-info">
<span class="label label-default">Date</span>
<span class="published">
<i class="fa fa-calendar"></i><time datetime="2016-05-16T00:00:00+08:00"> Mon 16 May 2016</time>
</span>
<span class="label label-default">Tags</span>
<a href="https://jm33.me/tag/greatwall.html">Greatwall</a>
/
<a href="https://jm33.me/tag/obfsproxy.html">obfsproxy</a>
/
<a href="https://jm33.me/tag/scramblesuit.html">scramblesuit</a>
/
<a href="https://jm33.me/tag/dpi.html">DPI</a>
/
<a href="https://jm33.me/tag/censorship.html">censorship</a>
/
<a href="https://jm33.me/tag/openwrt.html">openwrt</a>
/
<a href="https://jm33.me/tag/pi.html">pi</a>
</footer><!-- /.post-info --> </div>
<div class="summary"><blockquote>
<p>如果您看不懂英文,请点击<a href="/shi-yong-obfsproxy-scramblesuit-hun-yao-sh4d0ws0cksliu-liang.html">这里</a>以查看简体中文版本</p>
</blockquote>
<h2 id="get-obfsproxy-for-your-server">Get <em>obfsproxy</em> for your server</h2>
<h3 id="tor-official-debianubuntu-repo"><em>TOR</em> official Debian/Ubuntu repo</h3>
<ul>
<li>
<p>You can find your repo <a href="https://www.torproject.org/docs/debian.html.en" title="Get your repo">here</a></p>
</li>
<li>
<p>For Debian Jessie users like me, simply add the following to your <code>/etc/apt/sources.list</code></p>
</li>
</ul>
<div class="highlight"><pre><span></span>deb http://deb.torproject.org/torproject.org jessie main
deb-src http://deb.torproject.org …</pre></div>
<p><small><a href="https://jm33.me/sh4d0ws0cks-over-obfsproxy-scramblesuit.html#disqus_thread" >View comments</a>.</small></p> <a class="btn btn-default btn-xs" href="https://jm33.me/sh4d0ws0cks-over-obfsproxy-scramblesuit.html">more ...</a>
</div>
</article>
<hr/>
<article>
<h2><a href="https://jm33.me/glowing-bear.html">Glowing Bear</a></h2>
<div class="well well-sm">
<footer class="post-info">
<span class="label label-default">Date</span>
<span class="published">
<i class="fa fa-calendar"></i><time datetime="2016-05-09T00:00:00+08:00"> Mon 09 May 2016</time>
</span>
<span class="label label-default">Tags</span>
<a href="https://jm33.me/tag/misc.html">Misc</a>
/
<a href="https://jm33.me/tag/glowing-bear.html">Glowing Bear</a>
/
<a href="https://jm33.me/tag/irc.html">IRC</a>
/
<a href="https://jm33.me/tag/weechat.html">weechat</a>
/
<a href="https://jm33.me/tag/ssl.html">SSL</a>
</footer><!-- /.post-info --> </div>
<div class="summary"><h2 id="get-certs-ready">Get certs ready</h2>
<ul>
<li>
<p>Get Letsencrypt with <code>git clone https://github.com/letsencrypt/letsencrypt</code></p>
</li>
<li>
<p>Enter git directory, and <code>./letsencrypt-auto certonly -d <your domain></code></p>
</li>
<li>
<p>Find your certs in <code>cd /etc/letsencrypt/live/<your domain></code>, you will see the following</p>
</li>
</ul>
<p><img alt="certs" src="/img/certs.png"></p>
<ul>
<li>You will need to combine <code>privkey.pem</code> and <code>fullchain.pem</code>, fire up the …</li></ul>
<p><small><a href="https://jm33.me/glowing-bear.html#disqus_thread" >View comments</a>.</small></p> <a class="btn btn-default btn-xs" href="https://jm33.me/glowing-bear.html">more ...</a>
</div>
</article>
<hr/>
<ul class="pagination">
<li class="prev"><a href="https://jm33.me/category/misc12.html">«</a>
</li>
<li class=""><a
href="https://jm33.me/category/misc.html">1</a></li>
<li class=""><a
href="https://jm33.me/category/misc2.html">2</a></li>
<li class=""><a
href="https://jm33.me/category/misc3.html">3</a></li>
<li class=""><a
href="https://jm33.me/category/misc4.html">4</a></li>
<li class=""><a
href="https://jm33.me/category/misc5.html">5</a></li>
<li class=""><a
href="https://jm33.me/category/misc6.html">6</a></li>
<li class=""><a
href="https://jm33.me/category/misc7.html">7</a></li>
<li class=""><a
href="https://jm33.me/category/misc8.html">8</a></li>
<li class=""><a
href="https://jm33.me/category/misc9.html">9</a></li>
<li class=""><a
href="https://jm33.me/category/misc10.html">10</a></li>
<li class=""><a
href="https://jm33.me/category/misc11.html">11</a></li>
<li class=""><a
href="https://jm33.me/category/misc12.html">12</a></li>
<li class="active"><a
href="https://jm33.me/category/misc13.html">13</a></li>
<li class=""><a
href="https://jm33.me/category/misc14.html">14</a></li>
<li class="next"><a
href="https://jm33.me/category/misc14.html">»</a></li>
</ul>
</div>
<div class="col-sm-3" id="sidebar">
<aside>
<div id="aboutme">
<p>
<img width="100%" class="img-thumbnail" src="https://jm33.me//img/profile.webp"/>
</p>
<p>
<strong>About jm33</strong><br/>
<h3>Who</h3>
<ul>
<li><strong><em>weaponizer / linux user / vimer / pythonist / gopher / gray hat / male / siscon / freak</em></strong></li>
</ul>
<h3>Contact</h3>
<ul>
<li>
<p><strong><a href="/pages/jm33-ngs-cv.html" target="_blank" title="Check my CV">Online CV</a></strong></p>
</li>
<li>
<p><strong><a href="/[email protected]" target="_blank" title="My GPG public key">3A5DBF07</a></strong></p>
</li>
<li>
<p><strong><a href="https://jm33.me/pages/got-something-to-say.html" target="_blank">Leave a message</a></strong></p>
</li>
</ul>
</p>
</div><!-- Sidebar -->
<section class="well well-sm">
<ul class="list-group list-group-flush">
<!-- Sidebar/Social -->
<li class="list-group-item">
<h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Social</span></h4>
<ul class="list-group" id="social">
<li class="list-group-item"><a href="https://twitter.com/jm33_m0"><i class="fa fa-twitter-square fa-lg"></i> Twitter</a></li>
<li class="list-group-item"><a href="https://cn.linkedin.com/in/jim-mee-80ba7a111"><i class="fa fa-linkedin-square fa-lg"></i> LinkedIn</a></li>
<li class="list-group-item"><a href="https://stackoverflow.com/users/5230333/jm33-m0"><i class="fa fa-stack-overflow fa-lg"></i> StackOverflow</a></li>
<li class="list-group-item"><a href="https://github.com/jm33-m0"><i class="fa fa-github-square fa-lg"></i> Github</a></li>
</ul>
</li>
<!-- End Sidebar/Social -->
<!-- Sidebar/Recent Posts -->
<li class="list-group-item">
<h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Recent Posts</span></h4>
<ul class="list-group" id="recentposts">
<li class="list-group-item"><a href="https://jm33.me/digging-into-a-macos-kernel-panic.html">Digging Into A macOS Kernel Panic</a></li>
<li class="list-group-item"><a href="https://jm33.me/killer-wireless-kills-my-network.html">Killer Wireless Kills My Network</a></li>
<li class="list-group-item"><a href="https://jm33.me/fa-da-cai.html">发大财</a></li>
<li class="list-group-item"><a href="https://jm33.me/tan-tan-career.html">谈谈career</a></li>
<li class="list-group-item"><a href="https://jm33.me/enabling-new-pgp-key.html">Enabling New PGP Key</a></li>
</ul>
</li>
<!-- End Sidebar/Recent Posts -->
<!-- Sidebar/Tag Cloud -->
<li class="list-group-item">
<a href="https://jm33.me/tags.html"><h4><i class="fa fa-tags fa-lg"></i><span class="icon-label">Tags</span></h4></a>
<ul class="list-group list-inline tagcloud" id="tags">
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/443.html">443</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/active-directory.html">active directory</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/ad.html">ad</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/announcement.html">announcement</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/anonymity.html">anonymity</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/antivirus.html">antivirus</a>
</li>
<li class="list-group-item tag-2">
<a href="https://jm33.me/tag/anyconnect.html">anyconnect</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/apache.html">apache</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/assembly.html">assembly</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/baidu.html">baidu</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/blackhat.html">blackhat</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/buffer-overflow.html">buffer overflow</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/c.html">C#</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/career.html">career</a>
</li>
<li class="list-group-item tag-2">
<a href="https://jm33.me/tag/censorship.html">censorship</a>
</li>
<li class="list-group-item tag-2">
<a href="https://jm33.me/tag/change.html">change</a>
</li>
<li class="list-group-item tag-2">
<a href="https://jm33.me/tag/cisco.html">cisco</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/code-maintainance.html">code maintainance</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/compton.html">compton</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/coursera.html">Coursera</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/crypto.html">crypto</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/cryptography.html">cryptography</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/ctf.html">ctf</a>
</li>
<li class="list-group-item tag-2">
<a href="https://jm33.me/tag/cve.html">CVE</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/cve-2018-18955.html">CVE-2018-18955</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/cve-2018-7750.html">CVE-2018-7750</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/dairy.html">dairy</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/diary.html">Diary</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/dnswu-ran.html">DNS污染</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/dpi.html">DPI</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/email.html">email</a>
</li>
<li class="list-group-item tag-2">
<a href="https://jm33.me/tag/emp3r0r.html">emp3r0r</a>
</li>
<li class="list-group-item tag-2">
<a href="https://jm33.me/tag/exploit.html">exploit</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/file-transfer.html">file transfer</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/gf.html">gf</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/gfw.html">gfw</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/github.html">github</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/glowing-bear.html">Glowing Bear</a>
</li>
<li class="list-group-item tag-2">
<a href="https://jm33.me/tag/golang.html">golang</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/google-hacking.html">google hacking</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/great-wall.html">great wall</a>
</li>
<li class="list-group-item tag-1">
<a href="https://jm33.me/tag/greatwall.html">greatwall</a>
</li>
<li class="list-group-item tag-2">
<a href="https://jm33.me/tag/hacking.html">hacking</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/hacking-tool.html">hacking tool</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/hiwifi.html">HiWiFi</a>
</li>
<li class="list-group-item tag-2">
<a href="https://jm33.me/tag/http2.html">HTTP2</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/https.html">https</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/injection.html">injection</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/irc.html">IRC</a>
</li>
<li class="list-group-item tag-2">
<a href="https://jm33.me/tag/ji-lu-you.html">极路由</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/joomla.html">Joomla</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/kcp.html">KCP</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/kcptun.html">kcptun</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/kernel.html">kernel</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/killer.html">killer</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/lede.html">lede</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/life.html">life</a>
</li>
<li class="list-group-item tag-1">
<a href="https://jm33.me/tag/linux.html">linux</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/linux-kernel.html">linux kernel</a>
</li>
<li class="list-group-item tag-1">
<a href="https://jm33.me/tag/lkm.html">lkm</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/local-privilege-escalation.html">local privilege escalation</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/log-cleaner.html">log cleaner</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/login-bypass.html">login bypass</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/lpe.html">LPE</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/macos.html">macos</a>
</li>
<li class="list-group-item tag-2">
<a href="https://jm33.me/tag/mass-exploit.html">mass exploit</a>
</li>
<li class="list-group-item tag-2">
<a href="https://jm33.me/tag/mec.html">mec</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/memory-layout.html">memory layout</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/mentohust.html">mentohust</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/misc.html">Misc</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/multi-threaded-crawler.html">multi-threaded crawler</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/mysql.html">mysql</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/namespace.html">namespace</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/netcat.html">netcat</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/network.html">network</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/nic.html">nic</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/nikto.html">nikto</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/nmap.html">nmap</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/obfs4.html">obfs4</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/obfsproxy.html">obfsproxy</a>
</li>
<li class="list-group-item tag-2">
<a href="https://jm33.me/tag/ocserv.html">ocserv</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/openwrt.html">openwrt</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/osin.html">OSIN</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/paramiko.html">paramiko</a>
</li>
<li class="list-group-item tag-1">
<a href="https://jm33.me/tag/pentest.html">pentest</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/pep8.html">pep8</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/pgp.html">PGP</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/php.html">php</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/pi.html">pi</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/plan.html">plan</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/port-forwarding.html">port-forwarding</a>
</li>
<li class="list-group-item tag-1">
<a href="https://jm33.me/tag/post-exploitation.html">post-exploitation</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/privilege-escalation.html">privilege escalation</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/programming.html">programming</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/project.html">project</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/proxy.html">proxy</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/ptrace.html">ptrace</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/ptrace_traceme.html">PTRACE_TRACEME</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/pythonic.html">pythonic</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/quote.html">quote</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/rce.html">RCE</a>
</li>
<li class="list-group-item tag-2">
<a href="https://jm33.me/tag/reverse-shell.html">reverse shell</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/reversing.html">reversing</a>
</li>
<li class="list-group-item tag-1">
<a href="https://jm33.me/tag/rootkit.html">rootkit</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/router.html">router</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/s2-045.html">s2-045</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/scanner.html">scanner</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/scramblesuit.html">scramblesuit</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/seed-lab.html">SEED lab</a>
</li>
<li class="list-group-item tag-2">
<a href="https://jm33.me/tag/shadowsocks.html">shadowsocks</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/shadowsocks-plus.html">shadowsocks-plus</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/skydog.html">skydog</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/smartphone.html">smartphone</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/socket.html">socket</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/sqli.html">sqli</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/sqlmap.html">sqlmap</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/ss.html">SS</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/sshd.html">sshd</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/ssl.html">SSL</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/stanford.html">Stanford</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/sudo.html">sudo</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/systemd.html">systemd</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/thomas-jefferson.html">Thomas Jefferson</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/tmux.html">TMUX</a>
</li>
<li class="list-group-item tag-2">
<a href="https://jm33.me/tag/tools.html">tools</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/tor.html">Tor</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/trasparent-proxy.html">trasparent proxy</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/vim.html">vim</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/virtualbox.html">virtualbox</a>
</li>
<li class="list-group-item tag-2">
<a href="https://jm33.me/tag/vpn.html">vpn</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/wayland.html">wayland</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/web.html">web</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/weechat.html">weechat</a>
</li>
<li class="list-group-item tag-3">
<a href="https://jm33.me/tag/windows.html">windows</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/windows-domain.html">windows domain</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/windows-server.html">windows server</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/xfce4.html">xfce4</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/xfwm.html">xfwm</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/xhost.html">xhost</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/xml.html">xml</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/xmpp.html">xmpp</a>
</li>
<li class="list-group-item tag-4">
<a href="https://jm33.me/tag/zoomeye.html">zoomeye</a>
</li>
</ul>
</li>
<!-- End Sidebar/Tag Cloud -->
</ul>
</section>
<!-- End Sidebar --> </aside>
</div>
</div>
</div>
<!-- End Content Container -->
<footer>
<div class="container">
<hr>
<div class="row">
<div class="col-xs-10">© 2020 jm33-ng -
<a href="/pages/about.html" target="_blank" title="about this site"> About this site</a> <p><small> <a rel="license" href="https://creativecommons.org/licenses/by-nc/4.0/deed.en"><img alt="Creative Commons License" style="border-width:0" src="//i.creativecommons.org/l/by-nc/4.0/80x15.png" /></a>
Content
licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-nc/4.0/deed.en">Creative Commons Attribution-NonCommercial 4.0 International License</a>, except where indicated otherwise.
</small></p>
<p><small>Images hosted on this site are either my own or from Google Image Search</small></p>
</div>
</div>
</div>
</footer>
<script src="https://jm33.me/theme/js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://jm33.me/theme/js/bootstrap.min.js"></script>
<!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) -->
<script src="https://jm33.me/theme/js/respond.min.js"></script>
<script src="https://jm33.me/theme/js/bodypadding.js"></script>
<!-- Disqus -->
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'jm33-m0'; // required: replace example with your forum shortname
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var s = document.createElement('script');
s.async = true;
s.type = 'text/javascript';
s.src = '//' + disqus_shortname + '.disqus.com/count.js';
(document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
}());
</script>
<!-- End Disqus Code -->
<!-- custom part -->
<!-- asciinema js -->
<script src="https://jm33.me/theme/js/asciinema-player.js" async></script>
<!-- back-to-top starts -->
<style>
#topBtn {
display: none;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
border: none;
outline: none;
background-color: rgba(62, 63, 58, 0.9);
color: white;
cursor: pointer;
padding: 10px;
border-radius: 200px;
font-size: 40px;
line-height: 40px;
}
#topBtn:hover {
background-color: #3e3f3a;
}
</style>
<button onclick="topFunction()" id="topBtn" title="Go to top"><i class="fa fa-arrow-up" aria-hidden="true"></i></button>
<script>
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("topBtn").style.display = "block";
} else {
document.getElementById("topBtn").style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
</script>
<!-- back-to-top ends-->
</body>
</html> | jm33-m0/jm33_m0 | category/misc13.html | HTML | gpl-3.0 | 32,413 |
module XmlResolution
# Most named exceptions in the XmlResolution service we subclass here
# to one of the HTTP classes. Libraries are designed specifically
# to be unaware of this mapping: they only use their specific low level
# exceptions classes.
#
# In general, if we catch an HttpError at our top level app, we can
# blindly return the error message to the client as a diagnostic,
# and log it. The fact that we're naming these exceptions means
# we're being careful not to leak information, and still be helpful
# to the Client. They are very specific messages; tracebacks will
# not be required.
#
# When we get an un-named exception, however, the appropriate thing
# to do is to just supply a very terse message to the client (e.g.,
# we wouldn't like to expose errors from an ORM that said something
# like "password 'topsecret' failed in mysql open"). We *will* want
# to log the full error message, and probably a backtrace to boot.
class HttpError < StandardError;
def client_message
"#{status_code} #{status_text} - #{message.chomp('.')}."
end
end
# Most of the following comments are pretty darn obvious - they
# are included for easy navigation in the generated rdoc html files.
# Http400Error's group named exceptions as something the client did
# wrong. It is subclassed from the HttpError exception.
class Http400Error < HttpError; end
# Http400 exception: 400 Bad Request - it is subclassed from Http400Error.
class Http400 < Http400Error
def status_code; 400; end
def status_text; "Bad Request"; end
end
# Http401 exception: 401 Unauthorized - it is subclassed from Http400Error.
class Http401 < Http400Error
def status_code; 401; end
def status_text; "Unauthorized"; end
end
# Http403 exception: 403 Forbidden - it is subclassed from Http400Error.
class Http403 < Http400Error
def status_code; 403; end
def status_text; "Forbidden"; end
end
# Http404 exception: 404 Not Found - it is subclassed from Http400Error.
class Http404 < Http400Error
def status_code; 404; end
def status_text; "Not Found"; end
end
# Http405 exception: 405 Method Not Allowed - it is subclassed from Http400Error.
class Http405 < Http400Error
def status_code; 405; end
def status_text; "Method Not Allowed"; end
end
# Http406 exception: 406 Not Acceptable - it is subclassed from Http400Error.
class Http406 < Http400Error
def status_code; 406; end
def status_text; "Not Acceptable"; end
end
# Http408 exception: 408 Request Timeout - it is subclassed from Http400Error.
class Http408 < Http400Error
def status_code; 408; end
def status_text; "Request Timeout"; end
end
# Http409 exception: 409 Conflict - it is subclassed from Http400Error.
class Http409 < Http400Error
def status_code; 409; end
def status_text; "Conflict"; end
end
# Http410 exception: 410 Gone - it is subclassed from Http400Error.
class Http410 < Http400Error
def status_code; 410; end
def status_text; "Gone"; end
end
# Http411 exception: 411 Length Required - it is subclassed from Http400Error.
class Http411 < Http400Error
def status_code; 411; end
def status_text; "Length Required"; end
end
# Http412 exception: 412 Precondition Failed - it is subclassed from Http400Error.
class Http412 < Http400Error
def status_code; 412; end
def status_text; "Precondition Failed"; end
end
# Http413 exception: 413 Request Entity Too Large - it is subclassed from Http400Error.
class Http413 < Http400Error
def status_code; 413; end
def status_text; "Request Entity Too Large"; end
end
# Http414 exception: 414 Request-URI Too Long - it is subclassed from Http400Error.
class Http414 < Http400Error
def status_code; 414; end
def status_text; "Request-URI Too Long"; end
end
# Http415 exception: 415 Unsupported Media Type - it is subclassed from Http400Error.
class Http415 < Http400Error
def status_code; 415; end
def status_text; "Unsupported Media Type"; end
end
# Http500Error's group errors that are the server's fault.
# It is subclassed from the HttpError exception.
class Http500Error < HttpError; end
# Http500 exception: 500 Internal Service Error - it is subclassed from Http500Error.
class Http500 < Http500Error
def status_code; 500; end
def status_text; "Internal Service Error"; end
end
# Http501 exception: 501 Not Implemented - it is subclassed from Http500Error.
class Http501 < Http500Error
def status_code; 501; end
def status_text; "Not Implemented"; end
end
# Http503 exception: 503 Service Unavailable - it is subclassed from Http500Error.
class Http503 < Http500Error
def status_code; 503; end
def status_text; "Service Unavailable"; end
end
# Http505 exception: 505 HTTP Version Not Supported - it is subclassed from Http500Error.
class Http505 < Http500Error
def status_code; 505; end
def status_text; "HTTP Version Not Supported"; end
end
# BadXmlDocument exception, client's fault (subclasses Http400): Instance document could not be parsed..
class BadXmlDocument < Http415; end
# BadBadXmlDocument exception, client's fault (subclasses BadXmlDocument): ..it *really* could not be parsed
class BadBadXmlDocument < BadXmlDocument; end
# InadequateDataError exception, client's fault (subclasses Http400): Problem with uploaded data (e.g. length 0)
class InadequateDataError < Http400; end
# BadCollectionID exception, client's fault (subclasses Http400): PUT of a Collection ID wasn't suitable
class BadCollectionID < Http400; end
# BadXmlVersion exception, client's fault (subclasses Http415): Unsupported XML version (only 1.0)
class BadXmlVersion < Http415; end
# TooManyDarnSchemas exception, client's fault (subclasses Http400): Possible denial of service - infinite train of schemas
class TooManyDarnSchemas < Http400; end
# LockError exception, server's fault (subclasses Http500): Timed out trying to get a locked file
class LockError < Http500; end
# ConfigurationError exception, server's fault (subclasses Http500): Something wasn't set up correctly
class ConfigurationError < Http500; end
# ResolverError exception, server's fault (subclasses Http500): Result of a programming error
class ResolverError < Http500; end
# The LocationError is caught internally, and is used to indicate that
# the fetch of a Schema could not be performed because the location
# URL scheme was not supported. This results in reporting broken
# link, and is normally not very important: there are many other
# schemas to report on.
#
# However, if this exception was raised to the top level, we do
# not want to pass the information to the user. That's why it is not
# assigned to an HttpError subclass - we *want* a logged backtrace in
# that case.
class LocationError < StandardError; end
end # of module
| fcla/xmlresolution | lib/xmlresolution/exceptions.rb | Ruby | gpl-3.0 | 7,177 |
/***************************************************************************
* Copyright © 2010-2011 Jonathan Thomas <[email protected]> *
* Heavily inspired by Synaptic library code ;-) *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation; either version 2 of *
* the License or (at your option) version 3 or any later version *
* accepted by the membership of KDE e.V. (or its successor approved *
* by the membership of KDE e.V.), which shall act as a proxy *
* defined in Section 14 of version 3 of the license. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
//krazy:excludeall=qclasses
// Qt-only library, so things like QUrl *should* be used
#include "package.h"
// Qt includes
#include <QtCore/QFile>
#include <QtCore/QStringBuilder>
#include <QtCore/QStringList>
#include <QtCore/QTemporaryFile>
#include <QtCore/QTextStream>
#include <QDebug>
// Apt includes
#include <apt-pkg/algorithms.h>
#include <apt-pkg/debversion.h>
#include <apt-pkg/depcache.h>
#include <apt-pkg/indexfile.h>
#include <apt-pkg/init.h>
#include <apt-pkg/pkgrecords.h>
#include <apt-pkg/sourcelist.h>
#include <apt-pkg/strutl.h>
#include <apt-pkg/tagfile.h>
#include <apt-pkg/versionmatch.h>
#include <algorithm>
// Own includes
#include "backend.h"
#include "cache.h"
#include "config.h" // krazy:exclude=includes
#include "markingerrorinfo.h"
namespace QApt {
class PackagePrivate
{
public:
PackagePrivate(pkgCache::PkgIterator iter, Backend *back)
: packageIter(iter)
, backend(back)
, state(0)
, staticStateCalculated(false)
, foreignArchCalculated(false)
{
}
~PackagePrivate()
{
}
pkgCache::PkgIterator packageIter;
QApt::Backend *backend;
int state;
bool staticStateCalculated;
bool isForeignArch;
bool foreignArchCalculated;
pkgCache::PkgFileIterator searchPkgFileIter(QLatin1String label, const QString &release) const;
QString getReleaseFileForOrigin(QLatin1String label, const QString &release) const;
// Calculate state flags that cannot change
void initStaticState(const pkgCache::VerIterator &ver, pkgDepCache::StateCache &stateCache);
};
pkgCache::PkgFileIterator PackagePrivate::searchPkgFileIter(QLatin1String label, const QString &release) const
{
pkgCache::VerIterator verIter = packageIter.VersionList();
pkgCache::VerFileIterator verFileIter;
pkgCache::PkgFileIterator found;
while (!verIter.end()) {
for (verFileIter = verIter.FileList(); !verFileIter.end(); ++verFileIter) {
for(found = verFileIter.File(); !found.end(); ++found) {
const char *verLabel = found.Label();
const char *verOrigin = found.Origin();
const char *verArchive = found.Archive();
if (verLabel && verOrigin && verArchive) {
if(verLabel == label && verOrigin == label &&
QLatin1String(verArchive) == release) {
return found;
}
}
}
}
++verIter;
}
found = pkgCache::PkgFileIterator(*packageIter.Cache());
return found;
}
QString PackagePrivate::getReleaseFileForOrigin(QLatin1String label, const QString &release) const
{
pkgCache::PkgFileIterator pkg = searchPkgFileIter(label, release);
// Return empty if no package matches the given label and release
if (pkg.end())
return QString();
// Search for the matching meta-index
pkgSourceList *list = backend->packageSourceList();
pkgIndexFile *index;
// Return empty if the source list doesn't contain an index for the package
if (!list->FindIndex(pkg, index))
return QString();
for (auto I = list->begin(); I != list->end(); ++I) {
vector<pkgIndexFile *> *ifv = (*I)->GetIndexFiles();
if (find(ifv->begin(), ifv->end(), index) == ifv->end())
continue;
// Construct release file path
QString uri = backend->config()->findDirectory("Dir::State::lists")
% QString::fromStdString(URItoFileName((*I)->GetURI()))
% QLatin1String("dists_")
% QString::fromStdString((*I)->GetDist())
% QLatin1String("_Release");
return uri;
}
return QString();
}
void PackagePrivate::initStaticState(const pkgCache::VerIterator &ver, pkgDepCache::StateCache &stateCache)
{
int packageState = 0;
if (!ver.end()) {
// Set flags exclusive to installed packages
packageState |= QApt::Package::Installed;
if (stateCache.CandidateVer && stateCache.Upgradable()) {
packageState |= QApt::Package::Upgradeable;
if (stateCache.Keep())
packageState |= QApt::Package::Held;
}
} else
packageState |= QApt::Package::NotInstalled;
// Broken/garbage statuses are constant until a cache reload
if (stateCache.NowBroken()) {
packageState |= QApt::Package::NowBroken;
}
if (stateCache.InstBroken()) {
packageState |= QApt::Package::InstallBroken;
}
if (stateCache.Garbage) {
packageState |= QApt::Package::IsGarbage;
}
if (stateCache.NowPolicyBroken()) {
packageState |= QApt::Package::NowPolicyBroken;
}
if (stateCache.InstPolicyBroken()) {
packageState |= QApt::Package::InstallPolicyBroken;
}
// Essential/important status can only be changed by cache reload
if (packageIter->Flags & (pkgCache::Flag::Important |
pkgCache::Flag::Essential)) {
packageState |= QApt::Package::IsImportant;
}
if (packageIter->CurrentState == pkgCache::State::ConfigFiles) {
packageState |= QApt::Package::ResidualConfig;
}
// Packages will stay undownloadable until a sources file is refreshed
// and the cache is reloaded.
bool downloadable = true;
if (!stateCache.CandidateVer ||
stateCache.CandidateVerIter(*backend->cache()->depCache()).Downloadable())
downloadable = false;
if (!downloadable)
packageState |= QApt::Package::NotDownloadable;
state |= packageState;
staticStateCalculated = true;
}
Package::Package(QApt::Backend* backend, pkgCache::PkgIterator &packageIter)
: d(new PackagePrivate(packageIter, backend))
{
}
Package::~Package()
{
delete d;
}
const pkgCache::PkgIterator &Package::packageIterator() const
{
return d->packageIter;
}
QLatin1String Package::name() const
{
return QLatin1String(d->packageIter.Name());
}
int Package::id() const
{
return d->packageIter->ID;
}
QLatin1String Package::section() const
{
return QLatin1String(d->packageIter.Section());
}
QString Package::sourcePackage() const
{
QString sourcePackage;
// In the APT package record format, the only time when a "Source:" field
// is present is when the binary package name doesn't match the source
// name
const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (!ver.end()) {
pkgRecords::Parser &rec = d->backend->records()->Lookup(ver.FileList());
sourcePackage = QString::fromStdString(rec.SourcePkg());
}
// If the package record didn't have a "Source:" field, then this package's
// name must be the source package's name. (Or there isn't a record for this package)
if (sourcePackage.isEmpty()) {
sourcePackage = name();
}
return sourcePackage;
}
QString Package::shortDescription() const
{
QString shortDescription;
const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (!ver.end()) {
pkgCache::DescIterator Desc = ver.TranslatedDescription();
pkgRecords::Parser & parser = d->backend->records()->Lookup(Desc.FileList());
shortDescription = QString::fromUtf8(parser.ShortDesc().data());
return shortDescription;
}
return shortDescription;
}
QString Package::longDescription() const
{
const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (!ver.end()) {
QString rawDescription;
pkgCache::DescIterator Desc = ver.TranslatedDescription();
pkgRecords::Parser & parser = d->backend->records()->Lookup(Desc.FileList());
rawDescription = QString::fromUtf8(parser.LongDesc().data());
// Apt acutally returns the whole description, we just want the
// extended part.
rawDescription.remove(shortDescription() % '\n');
// *Now* we're really raw. Sort of. ;)
QString parsedDescription;
// Split at double newline, by "section"
QStringList sections = rawDescription.split(QLatin1String("\n ."));
for (int i = 0; i < sections.count(); ++i) {
sections[i].replace(QRegExp(QLatin1String("\n( |\t)+(-|\\*)")),
QLatin1Literal("\n\r ") % QString::fromUtf8("\xE2\x80\xA2"));
// There should be no new lines within a section.
sections[i].remove(QLatin1Char('\n'));
// Hack to get the lists working again.
sections[i].replace(QLatin1Char('\r'), QLatin1Char('\n'));
// Merge multiple whitespace chars into one
sections[i].replace(QRegExp(QLatin1String("\\ \\ +")), QChar::fromLatin1(' '));
// Remove the initial whitespace
sections[i].remove(0, 1);
// Append to parsedDescription
if (sections[i].startsWith(QLatin1String("\n ") % QString::fromUtf8("\xE2\x80\xA2 ")) || !i) {
parsedDescription += sections[i];
} else {
parsedDescription += QLatin1Literal("\n\n") % sections[i];
}
}
return parsedDescription;
}
return QString();
}
QString Package::maintainer() const
{
QString maintainer;
const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (!ver.end()) {
pkgRecords::Parser &parser = d->backend->records()->Lookup(ver.FileList());
maintainer = QString::fromUtf8(parser.Maintainer().data());
// This replacement prevents frontends from interpreting '<' as
// an HTML tag opening
maintainer.replace(QLatin1Char('<'), QLatin1String("<"));
}
return maintainer;
}
QString Package::homepage() const
{
QString homepage;
const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (!ver.end()) {
pkgRecords::Parser &parser = d->backend->records()->Lookup(ver.FileList());
homepage = QString::fromUtf8(parser.Homepage().data());
}
return homepage;
}
QString Package::version() const
{
if (!d->packageIter->CurrentVer) {
pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter];
if (!State.CandidateVer) {
return QString();
} else {
return QLatin1String(State.CandidateVerIter(*d->backend->cache()->depCache()).VerStr());
}
} else {
return QLatin1String(d->packageIter.CurrentVer().VerStr());
}
}
QString Package::upstreamVersion() const
{
const char *ver;
if (!d->packageIter->CurrentVer) {
pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter];
if (!State.CandidateVer) {
return QString();
} else {
ver = State.CandidateVerIter(*d->backend->cache()->depCache()).VerStr();
}
} else {
ver = d->packageIter.CurrentVer().VerStr();
}
return QString::fromStdString(_system->VS->UpstreamVersion(ver));
}
QString Package::upstreamVersion(const QString &version)
{
QByteArray ver = version.toLatin1();
return QString::fromStdString(_system->VS->UpstreamVersion(ver.constData()));
}
QString Package::architecture() const
{
pkgDepCache *depCache = d->backend->cache()->depCache();
pkgCache::VerIterator ver = (*depCache)[d->packageIter].InstVerIter(*depCache);
// the arch:all property is part of the version
if (ver && ver.Arch())
return QLatin1String(ver.Arch());
return QLatin1String(d->packageIter.Arch());
}
QStringList Package::availableVersions() const
{
QStringList versions;
// Get available Versions.
for (auto Ver = d->packageIter.VersionList(); !Ver.end(); ++Ver) {
// We always take the first available version.
pkgCache::VerFileIterator VF = Ver.FileList();
if (VF.end())
continue;
pkgCache::PkgFileIterator File = VF.File();
// Files without an archive will have a site
QString archive = (File->Archive) ? QLatin1String(File.Archive()) :
QLatin1String(File.Site());
versions.append(QLatin1String(Ver.VerStr()) % QLatin1String(" (") %
archive % ')');
}
return versions;
}
QString Package::installedVersion() const
{
if (!d->packageIter->CurrentVer) {
return QString();
}
return QLatin1String(d->packageIter.CurrentVer().VerStr());
}
QString Package::availableVersion() const
{
pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter];
if (!State.CandidateVer) {
return QString();
}
return QLatin1String(State.CandidateVerIter(*d->backend->cache()->depCache()).VerStr());
}
QString Package::priority() const
{
const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (ver.end())
return QString();
return QLatin1String(ver.PriorityType());
}
QStringList Package::installedFilesList() const
{
QStringList installedFilesList;
QString path = QLatin1String("/var/lib/dpkg/info/") % name() % QLatin1String(".list");
// Fallback for multiarch packages
if (!QFile::exists(path)) {
path = QLatin1String("/var/lib/dpkg/info/") % name() % ':' %
architecture() % QLatin1String(".list");
}
QFile infoFile(path);
if (infoFile.open(QFile::ReadOnly)) {
QTextStream stream(&infoFile);
QString line;
do {
line = stream.readLine();
installedFilesList << line;
} while (!line.isNull());
// The first item won't be a file
installedFilesList.removeFirst();
// Remove non-file directory listings
for (int i = 0; i < installedFilesList.size() - 1; ++i) {
if (installedFilesList.at(i+1).contains(installedFilesList.at(i) + '/')) {
installedFilesList[i] = QString(QLatin1Char(' '));
}
}
installedFilesList.removeAll(QChar::fromLatin1(' '));
// Last line is empty for some reason...
if (!installedFilesList.isEmpty()) {
installedFilesList.removeLast();
}
}
return installedFilesList;
}
QString Package::origin() const
{
const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if(Ver.end())
return QString();
pkgCache::VerFileIterator VF = Ver.FileList();
return QLatin1String(VF.File().Origin());
}
QStringList Package::archives() const
{
const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if(Ver.end())
return QStringList();
QStringList archiveList;
for (auto VF = Ver.FileList(); !VF.end(); ++VF)
archiveList << QLatin1String(VF.File().Archive());
return archiveList;
}
QString Package::component() const
{
QString sect = section();
if(sect.isEmpty())
return QString();
QStringList split = sect.split('/');
if (split.count() > 1)
return split.first();
return QString("main");
}
QByteArray Package::md5Sum() const
{
const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if(ver.end())
return QByteArray();
pkgRecords::Parser &rec = d->backend->records()->Lookup(ver.FileList());
return rec.MD5Hash().c_str();
}
QUrl Package::changelogUrl() const
{
const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (ver.end())
return QUrl();
pkgRecords::Parser &rec = d->backend->records()->Lookup(ver.FileList());
// Find the latest version for the latest changelog
QString versionString;
if (!availableVersion().isEmpty())
versionString = availableVersion();
// Epochs in versions are ignored on changelog servers
if (versionString.contains(QLatin1Char(':'))) {
QStringList epochVersion = versionString.split(QLatin1Char(':'));
// If the version has an epoch, take the stuff after the epoch
versionString = epochVersion.at(1);
}
// Create URL in form using the correct server, file path, and file suffix
Config *config = d->backend->config();
QString server = config->readEntry(QLatin1String("Apt::Changelogs::Server"),
QLatin1String("http://packages.debian.org/changelogs"));
QString path = QLatin1String(rec.FileName().c_str());
path = path.left(path.lastIndexOf(QLatin1Char('/')) + 1);
path += sourcePackage() % '_' % versionString % '/';
bool fromDebian = server.contains(QLatin1String("debian"));
QString suffix = fromDebian ? QLatin1String("changelog.txt")
: QLatin1String("changelog");
return QUrl(server % '/' % path % suffix);
}
QUrl Package::screenshotUrl(QApt::ScreenshotType type) const
{
QUrl url;
switch (type) {
case QApt::Thumbnail:
url = QUrl(controlField(QLatin1String("Thumbnail-Url")));
if(url.isEmpty())
url = QUrl("http://screenshots.debian.net/thumbnail/" % name());
break;
case QApt::Screenshot:
url = QUrl(controlField(QLatin1String("Screenshot-Url")));
if(url.isEmpty())
url = QUrl("http://screenshots.debian.net/screenshot/" % name());
break;
default:
qDebug() << "I do not know how to handle the screenshot type given to me: " << QString::number(type);
}
return url;
}
QDateTime Package::supportedUntil() const
{
if (!isSupported()) {
return QDateTime();
}
QFile lsb_release(QLatin1String("/etc/lsb-release"));
if (!lsb_release.open(QFile::ReadOnly)) {
// Though really, your system is screwed if this happens...
return QDateTime();
}
pkgTagSection sec;
time_t releaseDate = -1;
QString release;
QTextStream stream(&lsb_release);
QString line;
do {
line = stream.readLine();
QStringList split = line.split(QLatin1Char('='));
if (split.size() != 2) {
continue;
}
if (split.at(0) == QLatin1String("DISTRIB_CODENAME")) {
release = split.at(1);
}
} while (!line.isNull());
// Canonical only provides support for Ubuntu, but we don't have to worry
// about Debian systems as long as we assume that this function can fail.
QString releaseFile = d->getReleaseFileForOrigin(QLatin1String("Ubuntu"), release);
if(!FileExists(releaseFile.toStdString())) {
// happens e.g. when there is no release file and is harmless
return QDateTime();
}
// read the relase file
FileFd fd(releaseFile.toStdString(), FileFd::ReadOnly);
pkgTagFile tag(&fd);
tag.Step(sec);
if(!RFC1123StrToTime(sec.FindS("Date").data(), releaseDate)) {
return QDateTime();
}
// Default to 18m in case the package has no "supported" field
QString supportTimeString = QLatin1String("18m");
QString supportTimeField = controlField(QLatin1String("Supported"));
if (!supportTimeField.isEmpty()) {
supportTimeString = supportTimeField;
}
QChar unit = supportTimeString.at(supportTimeString.length() - 1);
supportTimeString.chop(1); // Remove the letter signifying months/years
const int supportTime = supportTimeString.toInt();
QDateTime supportEnd;
if (unit == QLatin1Char('m')) {
supportEnd = QDateTime::fromTime_t(releaseDate).addMonths(supportTime);
} else if (unit == QLatin1Char('y')) {
supportEnd = QDateTime::fromTime_t(releaseDate).addYears(supportTime);
}
return supportEnd;
}
QString Package::controlField(QLatin1String name) const
{
const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (ver.end()) {
return QString();
}
pkgRecords::Parser &rec = d->backend->records()->Lookup(ver.FileList());
return QString::fromStdString(rec.RecordField(name.latin1()));
}
QString Package::controlField(const QString &name) const
{
return controlField(QLatin1String(name.toLatin1()));
}
qint64 Package::currentInstalledSize() const
{
const pkgCache::VerIterator &ver = d->packageIter.CurrentVer();
if (!ver.end()) {
return qint64(ver->InstalledSize);
} else {
return qint64(-1);
}
}
qint64 Package::availableInstalledSize() const
{
pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter];
if (!State.CandidateVer) {
return qint64(-1);
}
return qint64(State.CandidateVerIter(*d->backend->cache()->depCache())->InstalledSize);
}
qint64 Package::downloadSize() const
{
pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter];
if (!State.CandidateVer) {
return qint64(-1);
}
return qint64(State.CandidateVerIter(*d->backend->cache()->depCache())->Size);
}
int Package::state() const
{
int packageState = 0;
const pkgCache::VerIterator &ver = d->packageIter.CurrentVer();
pkgDepCache::StateCache &stateCache = (*d->backend->cache()->depCache())[d->packageIter];
if (!d->staticStateCalculated) {
d->initStaticState(ver, stateCache);
}
if (stateCache.Install()) {
packageState |= ToInstall;
}
if (stateCache.Flags & pkgCache::Flag::Auto) {
packageState |= QApt::Package::IsAuto;
}
if (stateCache.iFlags & pkgDepCache::ReInstall) {
packageState |= ToReInstall;
} else if (stateCache.NewInstall()) { // Order matters here.
packageState |= NewInstall;
} else if (stateCache.Upgrade()) {
packageState |= ToUpgrade;
} else if (stateCache.Downgrade()) {
packageState |= ToDowngrade;
} else if (stateCache.Delete()) {
packageState |= ToRemove;
if (stateCache.iFlags & pkgDepCache::Purge) {
packageState |= ToPurge;
}
} else if (stateCache.Keep()) {
packageState |= ToKeep;
}
return packageState | d->state;
}
int Package::staticState() const
{
if (!d->staticStateCalculated) {
const pkgCache::VerIterator &ver = d->packageIter.CurrentVer();
pkgDepCache::StateCache &stateCache = (*d->backend->cache()->depCache())[d->packageIter];
d->initStaticState(ver, stateCache);
}
return d->state;
}
int Package::compareVersion(const QString &v1, const QString &v2)
{
// Make deep copies of toStdString(), since otherwise they would
// go out of scope when we call c_str()
string s1 = v1.toStdString();
string s2 = v2.toStdString();
const char *a = s1.c_str();
const char *b = s2.c_str();
int lenA = strlen(a);
int lenB = strlen(b);
return _system->VS->DoCmpVersion(a, a+lenA, b, b+lenB);
}
bool Package::isInstalled() const
{
return !d->packageIter.CurrentVer().end();
}
bool Package::isSupported() const
{
if (origin() == QLatin1String("Ubuntu")) {
QString componentString = component();
if ((componentString == QLatin1String("main") ||
componentString == QLatin1String("restricted")) && isTrusted()) {
return true;
}
}
return false;
}
bool Package::isMultiArchDuplicate() const
{
// Excludes installed packages, which are always "interesting"
if (isInstalled())
return false;
// Otherwise, check if the pkgIterator is the "best" from its group
return (d->packageIter.Group().FindPkg() != d->packageIter);
}
QString Package::multiArchTypeString() const
{
return controlField(QLatin1String("Multi-Arch"));
}
MultiArchType Package::multiArchType() const
{
QString typeString = multiArchTypeString();
MultiArchType archType = InvalidMultiArchType;
if (typeString == QLatin1String("same"))
archType = MultiArchSame;
else if (typeString == QLatin1String("foreign"))
archType = MultiArchForeign;
else if (typeString == QLatin1String("allowed"))
archType = MultiArchAllowed;
return archType;
}
bool Package::isForeignArch() const
{
if (!d->foreignArchCalculated) {
QString arch = architecture();
d->isForeignArch = (d->backend->nativeArchitecture() != arch) & (arch != QLatin1String("all"));
d->foreignArchCalculated = true;
}
return d->isForeignArch;
}
QList<DependencyItem> Package::depends() const
{
return DependencyInfo::parseDepends(controlField("Depends"), Depends);
}
QList<DependencyItem> Package::preDepends() const
{
return DependencyInfo::parseDepends(controlField("Pre-Depends"), PreDepends);
}
QList<DependencyItem> Package::suggests() const
{
return DependencyInfo::parseDepends(controlField("Suggests"), Suggests);
}
QList<DependencyItem> Package::recommends() const
{
return DependencyInfo::parseDepends(controlField("Recommends"), Recommends);
}
QList<DependencyItem> Package::conflicts() const
{
return DependencyInfo::parseDepends(controlField("Conflicts"), Conflicts);
}
QList<DependencyItem> Package::replaces() const
{
return DependencyInfo::parseDepends(controlField("Replaces"), Replaces);
}
QList<DependencyItem> Package::obsoletes() const
{
return DependencyInfo::parseDepends(controlField("Obsoletes"), Obsoletes);
}
QList<DependencyItem> Package::breaks() const
{
return DependencyInfo::parseDepends(controlField("Breaks"), Breaks);
}
QList<DependencyItem> Package::enhances() const
{
return DependencyInfo::parseDepends(controlField("Enhance"), Enhances);
}
QStringList Package::dependencyList(bool useCandidateVersion) const
{
QStringList dependsList;
pkgCache::VerIterator current;
pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter];
if(!useCandidateVersion) {
current = State.InstVerIter(*d->backend->cache()->depCache());
}
if(useCandidateVersion || current.end()) {
current = State.CandidateVerIter(*d->backend->cache()->depCache());
}
// no information found
if(current.end()) {
return dependsList;
}
for(pkgCache::DepIterator D = current.DependsList(); D.end() != true; ++D) {
QString type;
bool isOr = false;
bool isVirtual = false;
QString name;
QString version;
QString versionCompare;
QString finalString;
// check target and or-depends status
pkgCache::PkgIterator Trg = D.TargetPkg();
if ((D->CompareOp & pkgCache::Dep::Or) == pkgCache::Dep::Or) {
isOr=true;
}
// common information
type = QString::fromUtf8(D.DepType());
name = QLatin1String(Trg.Name());
if (!Trg->VersionList) {
isVirtual = true;
} else {
version = QLatin1String(D.TargetVer());
versionCompare = QLatin1String(D.CompType());
}
finalString = QLatin1Literal("<b>") % type % QLatin1Literal(":</b> ");
if (isVirtual) {
finalString += QLatin1Literal("<i>") % name % QLatin1Literal("</i>");
} else {
finalString += name;
}
// Escape the compare operator so it won't be seen as HTML
if (!version.isEmpty()) {
QString compMarkup(versionCompare);
compMarkup.replace(QLatin1Char('<'), QLatin1String("<"));
finalString += QLatin1String(" (") % compMarkup % QLatin1Char(' ') % version % QLatin1Char(')');
}
if (isOr) {
finalString += QLatin1String(" |");
}
dependsList.append(finalString);
}
return dependsList;
}
QStringList Package::requiredByList() const
{
QStringList reverseDependsList;
for(pkgCache::DepIterator it = d->packageIter.RevDependsList(); !it.end(); ++it) {
reverseDependsList << QLatin1String(it.ParentPkg().Name());
}
return reverseDependsList;
}
QStringList Package::providesList() const
{
pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter];
if (!State.CandidateVer) {
return QStringList();
}
QStringList provides;
for (pkgCache::PrvIterator Prv =
State.CandidateVerIter(*d->backend->cache()->depCache()).ProvidesList(); !Prv.end(); ++Prv) {
provides.append(QLatin1String(Prv.Name()));
}
return provides;
}
QStringList Package::recommendsList() const
{
QStringList recommends;
const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (Ver.end()) {
return recommends;
}
for(pkgCache::DepIterator it = Ver.DependsList(); !it.end(); ++it) {
pkgCache::PkgIterator pkg = it.TargetPkg();
// Skip purely virtual packages
if (!pkg->VersionList) {
continue;
}
pkgDepCache::StateCache &rState = (*d->backend->cache()->depCache())[pkg];
if (it->Type == pkgCache::Dep::Recommends && (rState.CandidateVer != 0 )) {
recommends << QLatin1String(it.TargetPkg().Name());
}
}
return recommends;
}
QStringList Package::suggestsList() const
{
QStringList suggests;
const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (Ver.end()) {
return suggests;
}
for(pkgCache::DepIterator it = Ver.DependsList(); !it.end(); ++it) {
pkgCache::PkgIterator pkg = it.TargetPkg();
// Skip purely virtual packages
if (!pkg->VersionList) {
continue;
}
pkgDepCache::StateCache &sState = (*d->backend->cache()->depCache())[pkg];
if (it->Type == pkgCache::Dep::Suggests && (sState.CandidateVer != 0 )) {
suggests << QLatin1String(it.TargetPkg().Name());
}
}
return suggests;
}
QStringList Package::enhancesList() const
{
QStringList enhances;
const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (Ver.end()) {
return enhances;
}
for(pkgCache::DepIterator it = Ver.DependsList(); !it.end(); ++it) {
pkgCache::PkgIterator pkg = it.TargetPkg();
// Skip purely virtual packages
if (!pkg->VersionList) {
continue;
}
pkgDepCache::StateCache &eState = (*d->backend->cache()->depCache())[pkg];
if (it->Type == pkgCache::Dep::Enhances && (eState.CandidateVer != 0 )) {
enhances << QLatin1String(it.TargetPkg().Name());
}
}
return enhances;
}
QStringList Package::enhancedByList() const
{
QStringList enhancedByList;
Q_FOREACH (QApt::Package *package, d->backend->availablePackages()) {
if (package->enhancesList().contains(name())) {
enhancedByList << package->name();
}
}
return enhancedByList;
}
QList<QApt::MarkingErrorInfo> Package::brokenReason() const
{
const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
QList<MarkingErrorInfo> reasons;
// check if there is actually something to install
if (!Ver) {
QApt::DependencyInfo info(name(), QString(), NoOperand, InvalidType);
QApt::MarkingErrorInfo error(QApt::ParentNotInstallable, info);
reasons.append(error);
return reasons;
}
for (pkgCache::DepIterator D = Ver.DependsList(); !D.end();) {
// Compute a single dependency element (glob or)
pkgCache::DepIterator Start;
pkgCache::DepIterator End;
D.GlobOr(Start, End);
pkgCache::PkgIterator Targ = Start.TargetPkg();
if (!d->backend->cache()->depCache()->IsImportantDep(End)) {
continue;
}
if (((*d->backend->cache()->depCache())[End] & pkgDepCache::DepGInstall) == pkgDepCache::DepGInstall) {
continue;
}
if (!Targ->ProvidesList) {
// Ok, not a virtual package since no provides
pkgCache::VerIterator Ver = (*d->backend->cache()->depCache())[Targ].InstVerIter(*d->backend->cache()->depCache());
QString requiredVersion;
if(Start.TargetVer() != 0) {
requiredVersion = '(' % QLatin1String(Start.CompType())
% QLatin1String(Start.TargetVer()) % ')';
}
if (!Ver.end()) {
// Happens when a package needs an upgraded dep, but the dep won't
// upgrade. Example:
// "apt 0.5.4 but 0.5.3 is to be installed"
QString targetName = QLatin1String(Start.TargetPkg().Name());
QApt::DependencyType relation = (QApt::DependencyType)End->Type;
QApt::DependencyInfo errorInfo(targetName, requiredVersion,
NoOperand, relation);
QApt::MarkingErrorInfo error(QApt::WrongCandidateVersion, errorInfo);
reasons.append(error);
} else { // We have the package, but for some reason it won't be installed
// In this case, the required version does not exist at all
QString targetName = QLatin1String(Start.TargetPkg().Name());
QApt::DependencyType relation = (QApt::DependencyType)End->Type;
QApt::DependencyInfo errorInfo(targetName, requiredVersion,
NoOperand, relation);
QApt::MarkingErrorInfo error(QApt::DepNotInstallable, errorInfo);
reasons.append(error);
}
} else {
// Ok, candidate has provides. We're a virtual package
QString targetName = QLatin1String(Start.TargetPkg().Name());
QApt::DependencyType relation = (QApt::DependencyType)End->Type;
QApt::DependencyInfo errorInfo(targetName, QString(),
NoOperand, relation);
QApt::MarkingErrorInfo error(QApt::VirtualPackage, errorInfo);
reasons.append(error);
}
}
return reasons;
}
bool Package::isTrusted() const
{
const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter);
if (!Ver)
return false;
pkgSourceList *Sources = d->backend->packageSourceList();
QHash<pkgCache::PkgFileIterator, pkgIndexFile*> *trustCache = d->backend->cache()->trustCache();
for (pkgCache::VerFileIterator i = Ver.FileList(); !i.end(); ++i)
{
pkgIndexFile *Index;
//FIXME: Should be done in apt
auto trustIter = trustCache->constBegin();
while (trustIter != trustCache->constEnd()) {
if (trustIter.key() == i.File())
break; // Found it
trustIter++;
}
// Find the index of the package file from the package sources
if (trustIter == trustCache->constEnd()) { // Not found
if (!Sources->FindIndex(i.File(), Index))
continue;
} else
Index = trustIter.value();
if (Index->IsTrusted())
return true;
}
return false;
}
bool Package::wouldBreak() const
{
int pkgState = state();
if ((pkgState & ToRemove) || (!(pkgState & Installed) && (pkgState & ToKeep))) {
return false;
}
return pkgState & InstallBroken;
}
void Package::setAuto(bool flag)
{
d->backend->cache()->depCache()->MarkAuto(d->packageIter, flag);
}
void Package::setKeep()
{
d->backend->cache()->depCache()->MarkKeep(d->packageIter, false);
if (d->backend->cache()->depCache()->BrokenCount() > 0) {
pkgProblemResolver Fix(d->backend->cache()->depCache());
Fix.ResolveByKeep();
}
d->state |= IsManuallyHeld;
if (!d->backend->areEventsCompressed()) {
d->backend->emitPackageChanged();
}
}
void Package::setInstall()
{
d->backend->cache()->depCache()->MarkInstall(d->packageIter, true);
d->state &= ~IsManuallyHeld;
// FIXME: can't we get rid of it here?
// if there is something wrong, try to fix it
if (!state() & ToInstall || d->backend->cache()->depCache()->BrokenCount() > 0) {
pkgProblemResolver Fix(d->backend->cache()->depCache());
Fix.Clear(d->packageIter);
Fix.Protect(d->packageIter);
Fix.Resolve(true);
}
if (!d->backend->areEventsCompressed()) {
d->backend->emitPackageChanged();
}
}
void Package::setReInstall()
{
d->backend->cache()->depCache()->SetReInstall(d->packageIter, true);
d->state &= ~IsManuallyHeld;
if (!d->backend->areEventsCompressed()) {
d->backend->emitPackageChanged();
}
}
void Package::setRemove()
{
pkgProblemResolver Fix(d->backend->cache()->depCache());
Fix.Clear(d->packageIter);
Fix.Protect(d->packageIter);
Fix.Remove(d->packageIter);
Fix.Resolve(true);
d->backend->cache()->depCache()->SetReInstall(d->packageIter, false);
d->backend->cache()->depCache()->MarkDelete(d->packageIter, false);
d->state &= ~IsManuallyHeld;
if (!d->backend->areEventsCompressed()) {
d->backend->emitPackageChanged();
}
}
void Package::setPurge()
{
pkgProblemResolver Fix(d->backend->cache()->depCache());
Fix.Clear(d->packageIter);
Fix.Protect(d->packageIter);
Fix.Remove(d->packageIter);
Fix.Resolve(true);
d->backend->cache()->depCache()->SetReInstall(d->packageIter, false);
d->backend->cache()->depCache()->MarkDelete(d->packageIter, true);
d->state &= ~IsManuallyHeld;
if (!d->backend->areEventsCompressed()) {
d->backend->emitPackageChanged();
}
}
bool Package::setVersion(const QString &version)
{
pkgDepCache::StateCache &state = (*d->backend->cache()->depCache())[d->packageIter];
QLatin1String defaultCandVer(state.CandVersion);
bool isDefault = (version == defaultCandVer);
pkgVersionMatch Match(version.toLatin1().constData(), pkgVersionMatch::Version);
const pkgCache::VerIterator &Ver = Match.Find(d->packageIter);
if (Ver.end())
return false;
d->backend->cache()->depCache()->SetCandidateVersion(Ver);
for (auto VF = Ver.FileList(); !VF.end(); ++VF) {
if (!VF.File() || !VF.File().Archive())
continue;
d->backend->cache()->depCache()->SetCandidateRelease(Ver, VF.File().Archive());
break;
}
if (isDefault)
d->state &= ~OverrideVersion;
else
d->state |= OverrideVersion;
return true;
}
void Package::setPinned(bool pin)
{
pin ? d->state |= IsPinned : d->state &= ~IsPinned;
}
}
| manchicken/libqapt | src/package.cpp | C++ | gpl-3.0 | 40,648 |
extern crate rand;
use std::io;
use rand::Rng;
use std::cmp::Ordering;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed {}", guess);
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
| DTasev/rnd | rust/guessing-game/src/main.rs | Rust | gpl-3.0 | 827 |
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
final class Contact extends Model
{
const PHONE = 'phone';
const ADDRESS = 'address';
const ADDRESS_COMPLEMENT = 'address_complement';
const POSTAL_CODE = 'postal_code';
const CITY = 'city';
const REGION = 'region';
const COUNTRY = 'country';
const CONTACTABLE_ID = 'contactable_id';
const CONTACTABLE_TYPE = 'contactable_type';
protected $fillable = [
self::PHONE,
self::ADDRESS,
self::ADDRESS_COMPLEMENT,
self::POSTAL_CODE,
self::CITY,
self::REGION,
self::COUNTRY,
];
protected $hidden = [
self::CONTACTABLE_ID,
self::CONTACTABLE_TYPE,
];
}
| murilocosta/huitzilopochtli | app/Contact.php | PHP | gpl-3.0 | 744 |
#
# logutil.py
# A module containing means of interacting with log files.
#
import logging
import logging.handlers
import os
import time
from data_structures import enum
from config import get_config_value
LoggingSection = enum(
'CLIENT',
'CRAWLER',
'DATA',
'FRONTIER',
'TEST',
'UTILITIES',
)
#region Setup
logging.basicConfig(level=logging.INFO,
format='[%(asctime)s %(levelname)s] %(name)s::%(funcName)s - %(message)s',
datefmt='%x %X %Z')
module_dir = os.path.dirname(__file__)
logfile = os.path.join(module_dir, get_config_value('LOG', 'path'))
logdir = os.path.join(module_dir, get_config_value('LOG', 'dir'))
if not os.path.exists(logdir):
os.mkdir(logdir)
handler = logging.handlers.RotatingFileHandler(logfile,
maxBytes=8192,
backupCount=10, )
formatter = logging.Formatter('[%(asctime)s %(levelname)s] %(name)s::%(funcName)s - %(message)s')
formatter.datefmt = '%x %X %Z'
formatter.converter = time.gmtime
handler.setFormatter(formatter)
#endregion
def get_logger(section, name):
"""
Fetches a logger.
Arguments:
section (string): The section the logger is attributed to.
name (string): The name of the logger.
Returns:
The logger corresponding to the section and name provided.
"""
section_name = LoggingSection.reverse_mapping[section].lower()
logger = logging.getLogger('htresearch.{0}.{1}'.format(section_name, name))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger | mizhgun/HTResearch | HTResearch/Utilities/logutil.py | Python | gpl-3.0 | 1,640 |
{% extends "geostitcher/views/templates/base.html" %}
{% block content %}
<div class="gallery">
<div id="error"></div>
<script src="{{context}}/js/gallery.js" type="text/javascript"></script>
<div>
{% for pic in pictures %}
<div class="thumbnail">
<a class={{pic.name}} href="{{context}}/img/{{pic.userid}}/{{pic.name}}">
<img src="{{context}}/img/{{pic.userid}}/{{thumb-prefix}}{{pic.name}}"/>
{% ifequal username page-owner %}
<input id="{{pic.name}}"
name="{{pic.name}}"
type="checkbox"
value="true" />
{% endifequal %}
</a>
</div>
{% endfor %}
{% ifequal user page-owner %}
<input id="delete" type="submit" value="delete images" />
{% endifequal %}
</div>
</div>
<form action="{{context}}/upload/{{dataset_id}}" enctype="multipart/form-data" method="POST">
<input id="file" name="file" type="file" />
<input type="submit" value="Upload" />
</form>
</div>
{% endblock %} | shomy4/GeoStitcher | geostitcher/src/geostitcher/views/templates/gallery.html | HTML | gpl-3.0 | 1,056 |
/* -*- c++ -*-
* Copyright (C) 2007-2016 Hypertable, Inc.
*
* This file is part of Hypertable.
*
* Hypertable is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or any later version.
*
* Hypertable is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/// @file
/// Definitions for UpdatePipeline.
/// This file contains type definitions for UpdatePipeline, a three-staged,
/// multithreaded update pipeline.
#include <Common/Compat.h>
#include "UpdatePipeline.h"
#include <Hypertable/RangeServer/Global.h>
#include <Hypertable/RangeServer/Response/Callback/Update.h>
#include <Hypertable/RangeServer/UpdateContext.h>
#include <Hypertable/RangeServer/UpdateRecRange.h>
#include <Hypertable/RangeServer/UpdateRecTable.h>
#include <Hypertable/Lib/ClusterId.h>
#include <Hypertable/Lib/RangeServer/Protocol.h>
#include <Common/DynamicBuffer.h>
#include <Common/FailureInducer.h>
#include <Common/Logger.h>
#include <Common/Serialization.h>
#include <chrono>
#include <set>
#include <thread>
using namespace Hypertable;
using namespace Hypertable::RangeServer;
using namespace std;
UpdatePipeline::UpdatePipeline(ContextPtr &context, QueryCachePtr &query_cache,
TimerHandlerPtr &timer_handler, CommitLogPtr &log,
Filesystem::Flags flags) :
m_context(context), m_query_cache(query_cache),
m_timer_handler(timer_handler), m_log(log), m_flags(flags) {
m_update_coalesce_limit = m_context->props->get_i64("Hypertable.RangeServer.UpdateCoalesceLimit");
m_maintenance_pause_interval = m_context->props->get_i32("Hypertable.RangeServer.Testing.MaintenanceNeeded.PauseInterval");
m_update_delay = m_context->props->get_i32("Hypertable.RangeServer.UpdateDelay", 0);
m_max_clock_skew = m_context->props->get_i32("Hypertable.RangeServer.ClockSkew.Max");
m_threads.reserve(3);
m_threads.push_back( thread(&UpdatePipeline::qualify_and_transform, this) );
m_threads.push_back( thread(&UpdatePipeline::commit, this) );
m_threads.push_back( thread(&UpdatePipeline::add_and_respond, this) );
}
void UpdatePipeline::add(UpdateContext *uc) {
lock_guard<mutex> lock(m_qualify_queue_mutex);
m_qualify_queue.push_back(uc);
m_qualify_queue_cond.notify_all();
}
void UpdatePipeline::shutdown() {
m_shutdown = true;
m_qualify_queue_cond.notify_all();
m_commit_queue_cond.notify_all();
m_response_queue_cond.notify_all();
for (std::thread &t : m_threads)
t.join();
}
void UpdatePipeline::qualify_and_transform() {
UpdateContext *uc;
SerializedKey key;
const uint8_t *mod, *mod_end;
const char *row;
String start_row, end_row;
UpdateRecRangeList *rulist;
int error = Error::OK;
int64_t latest_range_revision;
RangeTransferInfo transfer_info;
bool transfer_pending;
DynamicBuffer *cur_bufp;
DynamicBuffer *transfer_bufp;
uint32_t go_buf_reset_offset;
uint32_t root_buf_reset_offset;
CommitLogPtr transfer_log;
UpdateRecRange range_update;
RangePtr range;
std::mutex &mutex = m_qualify_queue_mutex;
condition_variable &cond = m_qualify_queue_cond;
std::list<UpdateContext *> &queue = m_qualify_queue;
while (true) {
{
unique_lock<std::mutex> lock(mutex);
cond.wait(lock, [this, &queue](){ return !queue.empty() || m_shutdown; });
if (m_shutdown)
return;
uc = queue.front();
queue.pop_front();
}
rulist = 0;
transfer_bufp = 0;
go_buf_reset_offset = 0;
root_buf_reset_offset = 0;
// This probably shouldn't happen for group commit, but since
// it's only for testing purposes, we'll leave it here
if (m_update_delay)
this_thread::sleep_for(chrono::milliseconds(m_update_delay));
// Global commit log is only available after local recovery
uc->auto_revision = Hypertable::get_ts64();
// TODO: Sanity check mod data (checksum validation)
// hack to workaround xen timestamp issue
if (uc->auto_revision < m_last_revision)
uc->auto_revision = m_last_revision;
for (UpdateRecTable *table_update : uc->updates) {
HT_DEBUG_OUT <<"Update: "<< table_update->id << HT_END;
if (!table_update->id.is_system() && m_context->server_state->readonly()) {
table_update->error = Error::RANGESERVER_SERVER_IN_READONLY_MODE;
continue;
}
try {
if (!m_context->live_map->lookup(table_update->id.id, table_update->table_info)) {
table_update->error = Error::TABLE_NOT_FOUND;
table_update->error_msg = table_update->id.id;
continue;
}
}
catch (Exception &e) {
table_update->error = e.code();
table_update->error_msg = e.what();
continue;
}
// verify schema
if (table_update->table_info->get_schema()->get_generation() !=
table_update->id.generation) {
table_update->error = Error::RANGESERVER_GENERATION_MISMATCH;
table_update->error_msg =
format("Update schema generation mismatch for table %s (received %lld != %lld)",
table_update->id.id, (Lld)table_update->id.generation,
(Lld)table_update->table_info->get_schema()->get_generation());
continue;
}
// Pre-allocate the go_buf - each key could expand by 8 or 9 bytes,
// if auto-assigned (8 for the ts or rev and maybe 1 for possible
// increase in vint length)
table_update->go_buf.reserve(table_update->id.encoded_length() +
table_update->total_buffer_size +
(table_update->total_count * 9));
table_update->id.encode(&table_update->go_buf.ptr);
table_update->go_buf.set_mark();
for (UpdateRequest *request : table_update->requests) {
uc->total_updates++;
mod_end = request->buffer.base + request->buffer.size;
mod = request->buffer.base;
go_buf_reset_offset = table_update->go_buf.fill();
root_buf_reset_offset = uc->root_buf.fill();
memset(&uc->send_back, 0, sizeof(uc->send_back));
while (mod < mod_end) {
key.ptr = mod;
row = key.row();
// error inducer for tests/integration/fail-index-mutator
if (HT_FAILURE_SIGNALLED("fail-index-mutator-0")) {
if (!strcmp(row, "1,+/JzamFvB6rqPqP5yNgI5nreCtZHkT\t\t01501")) {
uc->send_back.count++;
uc->send_back.error = Error::INDUCED_FAILURE;
uc->send_back.offset = mod - request->buffer.base;
uc->send_back.len = strlen(row);
request->send_back_vector.push_back(uc->send_back);
memset(&uc->send_back, 0, sizeof(uc->send_back));
key.next(); // skip key
key.next(); // skip value;
mod = key.ptr;
continue;
}
}
// If the row key starts with '\0' then the buffer is probably
// corrupt, so mark the remaing key/value pairs as bad
if (*row == 0) {
uc->send_back.error = Error::BAD_KEY;
uc->send_back.count = request->count; // fix me !!!!
uc->send_back.offset = mod - request->buffer.base;
uc->send_back.len = mod_end - mod;
request->send_back_vector.push_back(uc->send_back);
memset(&uc->send_back, 0, sizeof(uc->send_back));
mod = mod_end;
continue;
}
// Look for containing range, add to stop mods if not found
if (!table_update->table_info->find_containing_range(row, range,
start_row, end_row) ||
range->get_relinquish()) {
if (uc->send_back.error != Error::RANGESERVER_OUT_OF_RANGE
&& uc->send_back.count > 0) {
uc->send_back.len = (mod - request->buffer.base) - uc->send_back.offset;
request->send_back_vector.push_back(uc->send_back);
memset(&uc->send_back, 0, sizeof(uc->send_back));
}
if (uc->send_back.count == 0) {
uc->send_back.error = Error::RANGESERVER_OUT_OF_RANGE;
uc->send_back.offset = mod - request->buffer.base;
}
key.next(); // skip key
key.next(); // skip value;
mod = key.ptr;
uc->send_back.count++;
continue;
}
if ((rulist = table_update->range_map[range.get()]) == 0) {
rulist = new UpdateRecRangeList();
rulist->range = range;
table_update->range_map[range.get()] = rulist;
}
// See if range has some other error preventing it from receiving updates
if ((error = rulist->range->get_error()) != Error::OK) {
if (uc->send_back.error != error && uc->send_back.count > 0) {
uc->send_back.len = (mod - request->buffer.base) - uc->send_back.offset;
request->send_back_vector.push_back(uc->send_back);
memset(&uc->send_back, 0, sizeof(uc->send_back));
}
if (uc->send_back.count == 0) {
uc->send_back.error = error;
uc->send_back.offset = mod - request->buffer.base;
}
key.next(); // skip key
key.next(); // skip value;
mod = key.ptr;
uc->send_back.count++;
continue;
}
if (uc->send_back.count > 0) {
uc->send_back.len = (mod - request->buffer.base) - uc->send_back.offset;
request->send_back_vector.push_back(uc->send_back);
memset(&uc->send_back, 0, sizeof(uc->send_back));
}
/*
* Increment update count on range
* (block if maintenance in progress)
*/
if (!rulist->range_blocked) {
if (!rulist->range->increment_update_counter()) {
uc->send_back.error = Error::RANGESERVER_RANGE_NOT_FOUND;
uc->send_back.offset = mod - request->buffer.base;
uc->send_back.count++;
key.next(); // skip key
key.next(); // skip value;
mod = key.ptr;
continue;
}
rulist->range_blocked = true;
}
String range_start_row, range_end_row;
rulist->range->get_boundary_rows(range_start_row, range_end_row);
// Make sure range didn't just shrink
if (range_start_row != start_row || range_end_row != end_row) {
rulist->range->decrement_update_counter();
table_update->range_map.erase(rulist->range.get());
delete rulist;
continue;
}
/** Fetch range transfer information **/
{
bool wait_for_maintenance;
transfer_pending = rulist->range->get_transfer_info(transfer_info, transfer_log,
&latest_range_revision, wait_for_maintenance);
}
if (rulist->transfer_log.get() == 0)
rulist->transfer_log = transfer_log;
HT_ASSERT(rulist->transfer_log.get() == transfer_log.get());
bool in_transferring_region = false;
// Check for clock skew
{
ByteString tmp_key;
const uint8_t *tmp;
int64_t difference, tmp_timestamp;
tmp_key.ptr = key.ptr;
tmp_key.decode_length(&tmp);
if ((*tmp & Key::HAVE_REVISION) == 0) {
if (latest_range_revision > TIMESTAMP_MIN
&& uc->auto_revision < latest_range_revision) {
tmp_timestamp = Hypertable::get_ts64();
if (tmp_timestamp > uc->auto_revision)
uc->auto_revision = tmp_timestamp;
if (uc->auto_revision < latest_range_revision) {
difference = (int32_t)((latest_range_revision - uc->auto_revision)
/ 1000LL);
if (difference > m_max_clock_skew && !Global::ignore_clock_skew_errors) {
request->error = Error::RANGESERVER_CLOCK_SKEW;
HT_ERRORF("Clock skew of %lld microseconds exceeds maximum "
"(%lld) range=%s", (Lld)difference,
(Lld)m_max_clock_skew,
rulist->range->get_name().c_str());
uc->send_back.count = 0;
request->send_back_vector.clear();
break;
}
}
}
}
}
if (transfer_pending) {
transfer_bufp = &rulist->transfer_buf;
if (transfer_bufp->empty()) {
transfer_bufp->reserve(table_update->id.encoded_length());
table_update->id.encode(&transfer_bufp->ptr);
transfer_bufp->set_mark();
}
rulist->transfer_buf_reset_offset = rulist->transfer_buf.fill();
}
else {
transfer_bufp = 0;
rulist->transfer_buf_reset_offset = 0;
}
if (rulist->range->is_root()) {
if (uc->root_buf.empty()) {
uc->root_buf.reserve(table_update->id.encoded_length());
table_update->id.encode(&uc->root_buf.ptr);
uc->root_buf.set_mark();
root_buf_reset_offset = uc->root_buf.fill();
}
cur_bufp = &uc->root_buf;
}
else
cur_bufp = &table_update->go_buf;
rulist->last_request = request;
range_update.bufp = cur_bufp;
range_update.offset = cur_bufp->fill();
while (mod < mod_end &&
(end_row == "" || (strcmp(row, end_row.c_str()) <= 0))) {
if (transfer_pending) {
if (transfer_info.transferring(row)) {
if (!in_transferring_region) {
range_update.len = cur_bufp->fill() - range_update.offset;
rulist->add_update(request, range_update);
cur_bufp = transfer_bufp;
range_update.bufp = cur_bufp;
range_update.offset = cur_bufp->fill();
in_transferring_region = true;
}
table_update->transfer_count++;
}
else {
if (in_transferring_region) {
range_update.len = cur_bufp->fill() - range_update.offset;
rulist->add_update(request, range_update);
cur_bufp = &table_update->go_buf;
range_update.bufp = cur_bufp;
range_update.offset = cur_bufp->fill();
in_transferring_region = false;
}
}
}
try {
SchemaPtr schema = table_update->table_info->get_schema();
uint8_t family=*(key.ptr+1+strlen((const char *)key.ptr+1)+1);
ColumnFamilySpec *cf_spec = schema->get_column_family(family);
// reset auto_revision if it's gotten behind
if (uc->auto_revision < latest_range_revision) {
uc->auto_revision = Hypertable::get_ts64();
if (uc->auto_revision < latest_range_revision) {
HT_THROWF(Error::RANGESERVER_REVISION_ORDER_ERROR,
"Auto revision (%lld) is less than latest range "
"revision (%lld) for range %s",
(Lld)uc->auto_revision, (Lld)latest_range_revision,
rulist->range->get_name().c_str());
}
}
// This will transform keys that need to be assigned a
// timestamp and/or revision number by re-writing the key
// with the added timestamp and/or revision tacked on to the end
transform_key(key, cur_bufp, ++uc->auto_revision,&m_last_revision,
cf_spec ? cf_spec->get_option_time_order_desc() : false);
// Validate revision number
if (m_last_revision < latest_range_revision) {
if (m_last_revision != uc->auto_revision) {
HT_THROWF(Error::RANGESERVER_REVISION_ORDER_ERROR,
"Supplied revision (%lld) is less than most recently "
"seen revision (%lld) for range %s",
(Lld)m_last_revision, (Lld)latest_range_revision,
rulist->range->get_name().c_str());
}
}
}
catch (Exception &e) {
HT_ERRORF("%s - %s", e.what(), Error::get_text(e.code()));
request->error = e.code();
break;
}
// Now copy the value (with sanity check)
mod = key.ptr;
key.next(); // skip value
HT_ASSERT(key.ptr <= mod_end);
cur_bufp->add(mod, key.ptr-mod);
mod = key.ptr;
table_update->total_added++;
if (mod < mod_end)
row = key.row();
}
if (request->error == Error::OK) {
range_update.len = cur_bufp->fill() - range_update.offset;
rulist->add_update(request, range_update);
// if there were transferring updates, record the latest revision
if (transfer_pending && rulist->transfer_buf_reset_offset < rulist->transfer_buf.fill()) {
if (rulist->latest_transfer_revision < m_last_revision)
rulist->latest_transfer_revision = m_last_revision;
}
}
else {
/*
* If we drop into here, this means that the request is
* being aborted, so reset all of the UpdateRecRangeLists,
* reset the go_buf and the root_buf
*/
for (auto iter = table_update->range_map.begin();
iter != table_update->range_map.end(); ++iter)
(*iter).second->reset_updates(request);
table_update->go_buf.ptr = table_update->go_buf.base + go_buf_reset_offset;
if (root_buf_reset_offset)
uc->root_buf.ptr = uc->root_buf.base + root_buf_reset_offset;
uc->send_back.count = 0;
mod = mod_end;
}
range_update.bufp = 0;
}
transfer_log = 0;
if (uc->send_back.count > 0) {
uc->send_back.len = (mod - request->buffer.base) - uc->send_back.offset;
request->send_back_vector.push_back(uc->send_back);
memset(&uc->send_back, 0, sizeof(uc->send_back));
}
}
HT_DEBUGF("Added %d (%d transferring) updates to '%s'",
table_update->total_added, table_update->transfer_count,
table_update->id.id);
if (!table_update->id.is_metadata())
uc->total_added += table_update->total_added;
}
uc->last_revision = m_last_revision;
// Enqueue update
{
lock_guard<std::mutex> lock(m_commit_queue_mutex);
m_commit_queue.push_back(uc);
m_commit_queue_cond.notify_all();
m_commit_queue_count++;
}
}
}
void UpdatePipeline::commit() {
UpdateContext *uc;
SerializedKey key;
std::list<UpdateContext *> coalesce_queue;
uint64_t coalesce_amount = 0;
int error = Error::OK;
uint32_t committed_transfer_data;
bool log_needs_syncing {};
while (true) {
// Dequeue next update
{
unique_lock<std::mutex> lock(m_commit_queue_mutex);
m_commit_queue_cond.wait(lock, [this](){
return !m_commit_queue.empty() || m_shutdown; });
if (m_shutdown)
return;
uc = m_commit_queue.front();
m_commit_queue.pop_front();
m_commit_queue_count--;
}
committed_transfer_data = 0;
log_needs_syncing = false;
// Commit ROOT mutations
if (uc->root_buf.ptr > uc->root_buf.mark) {
if ((error = Global::root_log->write(ClusterId::get(), uc->root_buf, uc->last_revision, Filesystem::Flags::SYNC)) != Error::OK) {
HT_FATALF("Problem writing %d bytes to ROOT commit log - %s",
(int)uc->root_buf.fill(), Error::get_text(error));
}
}
for (UpdateRecTable *table_update : uc->updates) {
coalesce_amount += table_update->total_buffer_size;
// Iterate through all of the ranges, committing any transferring updates
for (auto iter = table_update->range_map.begin(); iter != table_update->range_map.end(); ++iter) {
if ((*iter).second->transfer_buf.ptr > (*iter).second->transfer_buf.mark) {
committed_transfer_data += (*iter).second->transfer_buf.ptr - (*iter).second->transfer_buf.mark;
if ((error = (*iter).second->transfer_log->write(ClusterId::get(), (*iter).second->transfer_buf,
(*iter).second->latest_transfer_revision,
m_flags)) != Error::OK) {
table_update->error = error;
table_update->error_msg = format("Problem writing %d bytes to transfer log",
(int)(*iter).second->transfer_buf.fill());
HT_ERRORF("%s - %s", table_update->error_msg.c_str(), Error::get_text(error));
break;
}
}
}
if (table_update->error != Error::OK)
continue;
constexpr uint32_t NO_LOG_SYNC_FLAGS =
Lib::RangeServer::Protocol::UPDATE_FLAG_NO_LOG_SYNC |
Lib::RangeServer::Protocol::UPDATE_FLAG_NO_LOG;
if ((table_update->flags & NO_LOG_SYNC_FLAGS) == 0)
log_needs_syncing = true;
// Commit valid (go) mutations
if ((table_update->flags & Lib::RangeServer::Protocol::UPDATE_FLAG_NO_LOG) == 0 &&
table_update->go_buf.ptr > table_update->go_buf.mark) {
if ((error = m_log->write(ClusterId::get(), table_update->go_buf, uc->last_revision, Filesystem::Flags::NONE)) != Error::OK) {
table_update->error_msg = format("Problem writing %d bytes to commit log (%s) - %s",
(int)table_update->go_buf.fill(),
m_log->get_log_dir().c_str(),
Error::get_text(error));
HT_ERRORF("%s", table_update->error_msg.c_str());
table_update->error = error;
continue;
}
}
}
bool do_sync = false;
if (log_needs_syncing) {
if (m_commit_queue_count > 0 && coalesce_amount < m_update_coalesce_limit) {
coalesce_queue.push_back(uc);
continue;
}
do_sync = true;
}
else if (!coalesce_queue.empty())
do_sync = true;
// Now sync the commit log if needed
if (do_sync) {
size_t retry_count {};
uc->total_syncs++;
while (true) {
if (m_flags == Filesystem::Flags::FLUSH)
error = m_log->flush();
else if (m_flags == Filesystem::Flags::SYNC)
error = m_log->sync();
else
error = Error::OK;
if (error != Error::OK) {
HT_ERRORF("Problem %sing log fragment (%s) - %s",
(m_flags == Filesystem::Flags::FLUSH ? "flush" : "sync"),
m_log->get_current_fragment_file().c_str(),
Error::get_text(error));
if (++retry_count == 6)
break;
this_thread::sleep_for(chrono::milliseconds(10000));
}
else
break;
}
}
// Enqueue update
{
lock_guard<std::mutex> lock(m_response_queue_mutex);
coalesce_queue.push_back(uc);
while (!coalesce_queue.empty()) {
uc = coalesce_queue.front();
coalesce_queue.pop_front();
m_response_queue.push_back(uc);
}
coalesce_amount = 0;
m_response_queue_cond.notify_all();
}
}
}
void UpdatePipeline::add_and_respond() {
UpdateContext *uc;
SerializedKey key;
int error = Error::OK;
while (true) {
// Dequeue next update
{
unique_lock<std::mutex> lock(m_response_queue_mutex);
m_response_queue_cond.wait(lock, [this](){
return !m_response_queue.empty() || m_shutdown; });
if (m_shutdown)
return;
uc = m_response_queue.front();
m_response_queue.pop_front();
}
/**
* Insert updates into Ranges
*/
for (UpdateRecTable *table_update : uc->updates) {
// Iterate through all of the ranges, inserting updates
for (auto iter = table_update->range_map.begin(); iter != table_update->range_map.end(); ++iter) {
ByteString value;
Key key_comps;
for (UpdateRecRange &update : (*iter).second->updates) {
Range *rangep = (*iter).first;
lock_guard<Range> lock(*rangep);
uint8_t *ptr = update.bufp->base + update.offset;
uint8_t *end = ptr + update.len;
if (!table_update->id.is_metadata())
uc->total_bytes_added += update.len;
rangep->add_bytes_written( update.len );
std::set<uint8_t> columns;
bool invalidate {};
const char *current_row {};
uint64_t count = 0;
while (ptr < end) {
key.ptr = ptr;
key_comps.load(key);
if (current_row == nullptr)
current_row = key_comps.row;
count++;
ptr += key_comps.length;
value.ptr = ptr;
ptr += value.length();
if (key_comps.column_family_code == 0 && key_comps.flag != FLAG_DELETE_ROW) {
HT_ERRORF("Skipping bad key - column family not specified in "
"non-delete row update on %s row=%s",
table_update->id.id, key_comps.row);
continue;
}
rangep->add(key_comps, value);
// invalidate
if (m_query_cache) {
if (strcmp(current_row, key_comps.row)) {
if (invalidate)
columns.clear();
m_query_cache->invalidate(table_update->id.id, current_row, columns);
columns.clear();
invalidate = false;
current_row = key_comps.row;
}
if (key_comps.flag == FLAG_DELETE_ROW)
invalidate = true;
else
columns.insert(key_comps.column_family_code);
}
}
if (m_query_cache && current_row) {
if (invalidate)
columns.clear();
m_query_cache->invalidate(table_update->id.id, current_row, columns);
}
rangep->add_cells_written(count);
}
}
}
// Decrement usage counters for all referenced ranges
for (UpdateRecTable *table_update : uc->updates) {
for (auto iter = table_update->range_map.begin(); iter != table_update->range_map.end(); ++iter) {
if ((*iter).second->range_blocked)
(*iter).first->decrement_update_counter();
}
}
/**
* wait for these ranges to complete maintenance
*/
bool maintenance_needed = false;
for (UpdateRecTable *table_update : uc->updates) {
/*
* If any of the newly updated ranges needs maintenance,
* schedule immediately
*/
for (auto iter = table_update->range_map.begin(); iter != table_update->range_map.end(); ++iter) {
if ((*iter).first->need_maintenance() &&
!Global::maintenance_queue->contains((*iter).first)) {
maintenance_needed = true;
HT_MAYBE_FAIL_X("metadata-update-and-respond", (*iter).first->is_metadata());
if (m_timer_handler)
m_timer_handler->schedule_immediate_maintenance();
break;
}
}
for (UpdateRequest *request : table_update->requests) {
Response::Callback::Update cb(m_context->comm, request->event);
if (table_update->error != Error::OK) {
if ((error = cb.error(table_update->error, table_update->error_msg)) != Error::OK)
HT_ERRORF("Problem sending error response - %s", Error::get_text(error));
continue;
}
if (request->error == Error::OK) {
/**
* Send back response
*/
if (!request->send_back_vector.empty()) {
StaticBuffer ext(new uint8_t [request->send_back_vector.size() * 16],
request->send_back_vector.size() * 16);
uint8_t *ptr = ext.base;
for (size_t i=0; i<request->send_back_vector.size(); i++) {
Serialization::encode_i32(&ptr, request->send_back_vector[i].error);
Serialization::encode_i32(&ptr, request->send_back_vector[i].count);
Serialization::encode_i32(&ptr, request->send_back_vector[i].offset);
Serialization::encode_i32(&ptr, request->send_back_vector[i].len);
/*
HT_INFOF("Sending back error %x, count %d, offset %d, len %d, table id %s",
request->send_back_vector[i].error, request->send_back_vector[i].count,
request->send_back_vector[i].offset, request->send_back_vector[i].len,
table_update->id.id);
*/
}
if ((error = cb.response(ext)) != Error::OK)
HT_ERRORF("Problem sending OK response - %s", Error::get_text(error));
}
else {
if ((error = cb.response_ok()) != Error::OK)
HT_ERRORF("Problem sending OK response - %s", Error::get_text(error));
}
}
else {
if ((error = cb.error(request->error, "")) != Error::OK)
HT_ERRORF("Problem sending error response - %s", Error::get_text(error));
}
}
}
{
lock_guard<LoadStatistics> lock(*Global::load_statistics);
Global::load_statistics->add_update_data(uc->total_updates, uc->total_added, uc->total_bytes_added, uc->total_syncs);
}
delete uc;
// For testing
if (m_maintenance_pause_interval > 0 && maintenance_needed)
this_thread::sleep_for(chrono::milliseconds(m_maintenance_pause_interval));
}
}
void
UpdatePipeline::transform_key(ByteString &bskey, DynamicBuffer *dest_bufp,
int64_t auto_revision, int64_t *revisionp,
bool timeorder_desc) {
size_t len;
const uint8_t *ptr;
len = bskey.decode_length(&ptr);
HT_ASSERT(*ptr == Key::AUTO_TIMESTAMP || *ptr == Key::HAVE_TIMESTAMP);
// if TIME_ORDER DESC was set for this column then we store the timestamps
// NOT in 1-complements!
if (timeorder_desc) {
// if the timestamp was specified by the user: unpack it and pack it
// again w/o 1-complement
if (*ptr == Key::HAVE_TIMESTAMP) {
uint8_t *p=(uint8_t *)ptr+len-8;
int64_t ts=Key::decode_ts64((const uint8_t **)&p);
p=(uint8_t *)ptr+len-8;
Key::encode_ts64((uint8_t **)&p, ts, false);
}
}
dest_bufp->ensure((ptr-bskey.ptr) + len + 9);
Serialization::encode_vi32(&dest_bufp->ptr, len+8);
memcpy(dest_bufp->ptr, ptr, len);
if (*ptr == Key::AUTO_TIMESTAMP)
*dest_bufp->ptr = Key::HAVE_REVISION
| Key::HAVE_TIMESTAMP | Key::REV_IS_TS;
else
*dest_bufp->ptr = Key::HAVE_REVISION
| Key::HAVE_TIMESTAMP;
// if TIME_ORDER DESC then store a flag in the key
if (timeorder_desc)
*dest_bufp->ptr |= Key::TS_CHRONOLOGICAL;
dest_bufp->ptr += len;
Key::encode_ts64(&dest_bufp->ptr, auto_revision,
timeorder_desc ? false : true);
*revisionp = auto_revision;
bskey.ptr = ptr + len;
}
| hypertable/hypertable | src/cc/Hypertable/RangeServer/UpdatePipeline.cc | C++ | gpl-3.0 | 32,361 |
#!/usr/bin/env python
'''
Purpose:
This script, using default values, determines and plots the CpG islands in
relation to a given feature "type" (e.g. "gene" or "mRNA") from a GFF file
which corresponds to the user-provided fasta file.
Note:
CpG Islands are determined by ObEx = (Observed CpG) / (Expected CpG) ,
default threshold > 1.
Where Expected CpG = (count(C) * count(G)) / WindowSize
Usage:
python cpg_gene.py FastaFile Gff_File OutFile.png
Default optional parameters:
-s, Step Size, default = 50
-w, Window Size, default = 200
-oe, Minimum Observed Expected CpG, default = 1
-gc, Minimum GC, default = .5
-r Range from ATG, or provided feature, default = 5000
-f, GFF Feature, default = "gene"
-i, Gene ID from GFF, default = ""
'''
import sys
import os
import argparse
from collections import Counter
from Bio import SeqIO
import cpgmod
import gffutils
import pandas as pd
import numpy as np
from ggplot import *
# Capture command line args, with or without defaults
if __name__ == '__main__':
# Parse the arguments
LineArgs = cpgmod.parseArguments()
# Populate vars with args
FastaFile = LineArgs.FastaFile
GffFile = LineArgs.GffFile
OutFile = LineArgs.FileOut
Step = LineArgs.s
WinSize = LineArgs.w
ObExthresh = LineArgs.oe
GCthresh = LineArgs.gc
StartRange = LineArgs.r
FeatGFF = LineArgs.f
ID_Feat = LineArgs.i
# Gather all possible CpG islands
MergedRecs = []
print "Parsing sequences...\n"
for SeqRecord in SeqIO.parse(FastaFile, "fasta"):
print SeqRecord.id
# Determine if sequences and args are acceptable
cpgmod.arg_seqcheck(SeqRecord, WinSize, Step)
# Pre-determine number of islands
NumOfChunks = cpgmod.chunks(SeqRecord, WinSize, Step)
# Return array of SeqRec class (potential CpG island) instances
SeqRecList = cpgmod.compute(SeqRecord, Step, NumOfChunks, WinSize)
MergedRecs = MergedRecs + SeqRecList
# Create GFF DB
GffDb = gffutils.create_db(GffFile, dbfn='GFF.db', force=True, keep_order=True,
merge_strategy='merge', sort_attribute_values=True,
disable_infer_transcripts=True,
disable_infer_genes=True)
print "\nGFF Database Created...\n"
# Filter out SeqRec below threshold
DistArr = []
for Rec in MergedRecs:
Cond1 = Rec.expect() > 0
if Cond1 == True:
ObEx = (Rec.observ() / Rec.expect())
Cond2 = ObEx > ObExthresh
Cond3 = Rec.gc_cont() > GCthresh
if Cond2 and Cond3:
# Query GFF DB for closest gene feature *or provided feature*
Arr = cpgmod.get_closest(Rec, GffDb, StartRange, FeatGFF, ID_Feat)
if Arr <> False:
Arr.append(ObEx)
DistArr.append(Arr)
print "CpG Islands predicted...\n"
print "Generating Figure...\n"
# Releasing SeqRecs
MergedRecs = None
SeqRecList = None
# Pre-check DistArr Results
if len(DistArr) < 2:
print "WARNING, "+ str(len(DistArr)) + " sites were found."
print "Consider changing parameters.\n"
# Generate Figure:
ObExRes = pd.DataFrame({
'gene' : [],
'xval': [],
'yval': []})
try:
Cnt = 0
for Dist in DistArr:
Cnt += 1
print "PROGRESS: "+str(Cnt) +" of "+ str(len(DistArr))
ObExdf = pd.DataFrame({
'gene': [Dist[2]],
'xval': [Dist[1]],
'yval': [Dist[3]]})
ObExFram = [ObExRes, ObExdf]
ObExRes = pd.concat(ObExFram, ignore_index=True)
p = ggplot(aes(x='xval', y='yval'), data=ObExRes) \
+ geom_point() \
+ ylab("Observed/Expected CpG") \
+ xlab("Position (bp) Relative to (ATG = 0)") \
+ ggtitle("Predicted CpG Island Position Relative to ATG")
p.save(OutFile)
except IndexError as e:
print 'Error: '+ str(e)
sys.exit('Exiting script...')
print p
# Remove GFF DB
os.remove('GFF.db')
| juswilliams/bioscripts | CpG_by_feature/cpg_gene.py | Python | gpl-3.0 | 3,970 |
#ifndef GLOBALS_H
#define GLOBALS_H
#include <stdio.h>
#include <allegro.h>
#include "resource.h"
//#define LOG_COMMS // Uncomment this line to enable serial comm logging
// system_of_measurements
#define METRIC 0
#define IMPERIAL 1
// Display mode flags
#define FULL_SCREEN_MODE 0
#define WINDOWED_MODE 1
#define FULLSCREEN_MODE_SUPPORTED 2
#define WINDOWED_MODE_SUPPORTED 4
#define WINDOWED_MODE_SET 8
// Password for Datafiles (Tr. Code Definitions and Resources)
#define PASSWORD NULL
// Colors in the main palette
#define C_TRANSP -1
#define C_BLACK 0
#define C_WHITE 1
#define C_RED 255
#define C_BLUE 254
#define C_GREEN 99
#define C_DARK_YELLOW 54
#define C_PURPLE 9
#define C_DARK_GRAY 126
#define C_GRAY 50
#define C_LIGHT_GRAY 55
//
int is_not_genuine_scan_tool;
// Options
int system_of_measurements;
int display_mode;
// File names
char options_file_name[20];
char data_file_name[20];
char code_defs_file_name[20];
char log_file_name[20];
#ifdef LOG_COMMS
char comm_log_file_name[20];
#endif
void write_log(const char *log_string);
#ifdef LOG_COMMS
void write_comm_log(const char *marker, const char *data);
#endif
DATAFILE *datafile;
#endif
| jantman/python-obd | elmscan-linux/scantool_114/globals.h | C | gpl-3.0 | 1,292 |
-- Move generator logic
module Kurt.GoEngine ( genMove
, simulatePlayout
, EngineState(..)
, newEngineState
, updateEngineState
, newUctTree
) where
import Control.Arrow (second)
import Control.Monad (liftM)
import Control.Monad.Primitive (PrimState)
import Control.Monad.ST (ST, runST, stToIO)
import Control.Parallel.Strategies (parMap, rdeepseq)
import Data.List ((\\))
import qualified Data.Map as M (map)
import Data.Maybe (fromMaybe)
import Data.Time.Clock (UTCTime (..), getCurrentTime,
picosecondsToDiffTime)
import Data.Tree (rootLabel)
import Data.Tree.Zipper (findChild, fromTree, hasChildren,
tree)
import System.Random.MWC (Gen, Seed, restore, save, uniform,
withSystemRandom)
import Data.Goban.GameState
import Data.Goban.Types (Color (..), Move (..), Score,
Stone (..), Vertex)
import Data.Goban.Utils (rateScore, winningScore)
import Kurt.Config
import Data.Tree.UCT
import Data.Tree.UCT.GameTree (MoveNode (..), RaveMap,
UCTTreeLoc, newMoveNode,
newRaveMap)
import Debug.TraceOrId (trace)
-- import Data.Tree (drawTree)
data EngineState = EngineState {
getGameState :: !GameState
, getUctTree :: !(UCTTreeLoc Move)
, getRaveMap :: !(RaveMap Move)
, boardSize :: !Int
, getKomi :: !Score
, getConfig :: !KurtConfig
}
type LoopState = (UCTTreeLoc Move, RaveMap Move)
-- result from playout: score, playedMoves, path to startnode in tree
type Result = (Score, [Move], [Move])
-- request for playout: gamestate, path to startnode in tree, seed
type Request = (GameState, [Move], Seed)
newEngineState :: KurtConfig -> EngineState
newEngineState config =
EngineState { getGameState =
newGameState (initialBoardsize config) (initialKomi config)
, getUctTree = newUctTree
, getRaveMap = newRaveMap
, boardSize = initialBoardsize config
, getKomi = initialKomi config
, getConfig = config
}
newUctTree :: UCTTreeLoc Move
newUctTree =
fromTree $ newMoveNode
(trace "UCT tree root move accessed"
(Move (Stone (25,25) White)))
(0.5, 1)
updateEngineState :: EngineState -> Move -> EngineState
updateEngineState eState move =
eState { getGameState = gState', getUctTree = loc' }
where
gState' = updateGameState gState move
gState = getGameState eState
loc' = case move of
(Resign _) -> loc
_otherwise ->
if hasChildren loc
then selectSubtree loc move
else newUctTree
loc = getUctTree eState
selectSubtree :: UCTTreeLoc Move -> Move -> UCTTreeLoc Move
selectSubtree loc move =
loc''
where
loc'' = fromTree $ tree loc'
loc' =
fromMaybe newUctTree
$ findChild ((move ==) . nodeMove . rootLabel) loc
genMove :: EngineState -> Color -> IO (Move, EngineState)
genMove eState color = do
now <- getCurrentTime
let deadline = UTCTime { utctDay = utctDay now
, utctDayTime = thinkPicosecs + utctDayTime now }
let moves = nextMoves gState color
let score = scoreGameState gState
(if null moves
then
if winningScore color score
then return (Pass color, eState)
else return (Resign color, eState)
else (do
seed <- withSystemRandom (save :: Gen (PrimState IO) -> IO Seed)
(loc', raveMap') <- runUCT loc gState raveMap config deadline seed
let eState' = eState { getUctTree = loc', getRaveMap = raveMap' }
return (bestMoveFromLoc loc' (getState gState) score, eState')))
where
config = getConfig eState
gState = getGameState eState
loc = getUctTree eState
raveMap = M.map (second ((1 +) . (`div` 2))) $ getRaveMap eState
thinkPicosecs =
picosecondsToDiffTime
$ fromIntegral (maxTime config) * 1000000000
bestMoveFromLoc :: UCTTreeLoc Move -> GameStateStuff -> Score -> Move
bestMoveFromLoc loc state score =
case principalVariation loc of
[] ->
error "bestMoveFromLoc: principalVariation is empty"
(node : _) ->
if value < 0.1
then
if winningScore color score
then
trace ("bestMoveFromLoc pass " ++ show node)
Pass color
else
trace ("bestMoveFromLoc resign " ++ show node)
Resign color
else
trace ("total sims: " ++ show (nodeVisits$rootLabel$tree$loc)
++ " best: " ++ show node
++ "\n")
-- ++ (drawTree $ fmap show $ tree loc)
move
where
move = nodeMove node
value = nodeValue node
color = nextMoveColor state
runUCT :: UCTTreeLoc Move
-> GameState
-> RaveMap Move
-> KurtConfig
-> UTCTime
-> Seed
-> IO LoopState
runUCT initLoc rootGameState initRaveMap config deadline seed00 = do
uctLoop stateStream0 0
where
uctLoop :: [LoopState] -> Int -> IO LoopState
uctLoop [] _ = return (initLoc, initRaveMap)
uctLoop (st : stateStream) !n = do
_ <- return $! st
let maxRuns = n >= (maxPlayouts config)
now <- getCurrentTime
let timeIsUp = (now > deadline)
(if maxRuns || timeIsUp
then return st
else uctLoop stateStream (n + 1))
stateStream0 = loop0 seed00 (initLoc, initRaveMap)
loop0 :: Seed -> LoopState -> [LoopState]
loop0 seed0 st0 =
map (\(_, st, _) -> st) $ iterate loop (seed0, st0, [])
where
loop (seed, st, results0) =
(seed', st'', results)
where
st'' = updater st' r
r : results = results0 ++ (parMap rdeepseq runOne requests)
(st', seed', requests) = requestor st seed reqNeeded
reqNeeded = max 2 $ maxThreads config - length results0
updater :: LoopState -> Result -> LoopState
updater !st !res =
updateTreeResult st res
requestor :: LoopState -> Seed -> Int -> (LoopState, Seed, [Request])
requestor !st0 seed0 !n =
last $ take n $ iterate r (st0, seed0, [])
where
r :: (LoopState, Seed, [Request]) -> (LoopState, Seed, [Request])
r (!st, seed, rs) = (st', seed', request : rs)
where
seed' = incrSeed seed
st' = (loc, raveMap)
(_, raveMap) = st
request = (leafGameState, path, seed)
(loc, (leafGameState, path)) = nextNode st
nextNode :: LoopState -> (UCTTreeLoc Move, (GameState, [Move]))
nextNode (!loc, !raveMap) =
(loc'', (leafGameState, path))
where
loc'' = backpropagate (\_x -> 0) updateNodeVisits $ expandNode loc' slHeu moves
moves = nextMoves leafGameState $ nextMoveColor $ getState leafGameState
leafGameState = getLeafGameState rootGameState path
(loc', path) = selectLeafPath policy loc
policy = policyRaveUCB1 (uctExplorationPercent config) (raveWeight config) raveMap
slHeu = makeStonesAndLibertyHeuristic leafGameState config
updateTreeResult :: LoopState -> Result -> LoopState
updateTreeResult (!loc, !raveMap) (!score, !playedMoves, !path) =
(loc', raveMap')
where
raveMap' = updateRaveMap raveMap (rateScore score) $ drop (length playedMoves `div` 3) playedMoves
loc' = backpropagate (rateScore score) updateNodeValue $ getLeaf loc path
simulatePlayout :: GameState -> IO [Move]
simulatePlayout gState = do
seed <- withSystemRandom (save :: Gen (PrimState IO) -> IO Seed)
let gState' = getLeafGameState gState []
(oneState, playedMoves) <- stToIO $ runOneRandom gState' seed
let score = scoreGameState oneState
trace ("simulatePlayout " ++ show score) $ return ()
return $ reverse playedMoves
runOne :: Request -> Result
runOne (gameState, path, seed) =
(score, playedMoves, path)
where
score = scoreGameState endState
(endState, playedMoves) = runST $ runOneRandom gameState seed
runOneRandom :: GameState -> Seed -> ST s (GameState, [Move])
runOneRandom initState seed = do
rGen <- restore seed
run initState 0 rGen []
where
run :: GameState -> Int -> Gen s -> [Move] -> ST s (GameState, [Move])
run state 1000 _ moves = return (trace ("runOneRandom not done after 1000 moves " ++ show moves) state, [])
run state runCount rGen moves = do
move <- genMoveRand state rGen
let state' = updateGameState state move
case move of
(Pass passColor) -> do
move' <- genMoveRand state' rGen
let state'' = updateGameState state' move'
case move' of
(Pass _) ->
return (state'', moves)
sm@(Move _) ->
run state'' (runCount + 1) rGen (sm : Pass passColor : moves)
(Resign _) ->
error "runOneRandom encountered Resign"
sm@(Move _) ->
run state' (runCount + 1) rGen (sm : moves)
(Resign _) ->
error "runOneRandom encountered Resign"
genMoveRand :: GameState -> Gen s -> ST s Move
genMoveRand state rGen =
pickSane $ freeVertices $ getState state
where
pickSane [] =
return $ Pass color
pickSane [p] = do
let stone = Stone p color
let sane = isSaneMove state stone
return (if sane
then Move stone
else Pass color)
pickSane ps = do
p <- pick ps rGen
let stone = Stone p color
let sane = isSaneMove state stone
(if sane
then return $ Move stone
else pickSane (ps \\ [p]))
color = nextMoveColor $ getState state
pick :: [Vertex] -> Gen s -> ST s Vertex
pick as rGen = do
i <- liftM (`mod` length as) $ uniform rGen
return $ as !! i
incrSeed :: Seed -> Seed
incrSeed !seed =
runST $ do
gen <- restore seed
x <- uniform gen
_ <- return $ x + (1 :: Int)
seed' <- save gen
return $! seed'
| lefant/kurt | src/Kurt/GoEngine.hs | Haskell | gpl-3.0 | 11,157 |
# k0nsl's blog
mirrored blog posts from my personal platform.
| k0nsl/k0nsl_blog | README.md | Markdown | gpl-3.0 | 62 |
# CommandBuilder <span style="font-weight:normal; font-size:.5em">extends [Command](#Command)</span>
## Constructor
```js
new Mechan.CommandBuilder(name);
```
| Parameter | Type | Optional | Default | Description |
|-------------|-----------------------------------------------------------------------------------------------------|----------|---------|----------------------------------------------------------------|
| name | [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) | | | Name of the command |
|[Properties](#CommandBuilder?scrollTo=properties) |[Methods](#CommandBuilder?scrollTo=methods) |Events|
|---------------------------------------------------|-----------------------------------------------------------|------|
|[name](#CommandBuilder?scrollTo=name) |[canRun](#CommandBuilder?scrollTo=canRun) | |
|[fullname](#CommandBuilder?scrollTo=fullname) |[setCallback](#CommandBuilder?scrollTo=setCallback) | |
|[callback](#CommandBuilder?scrollTo=callback) |[addParameter](#CommandBuilder?scrollTo=addParameter) | |
|[parameters](#CommandBuilder?scrollTo=parameters) |[clearParameters](#CommandBuilder?scrollTo=clearParameters)| |
|[checks](#CommandBuilder?scrollTo=checks) |[addCheck](#CommandBuilder?scrollTo=addCheck) | |
|[description](#CommandBuilder?scrollTo=description)|[addChecks](#CommandBuilder?scrollTo=addChecks) | |
|[category](#CommandBuilder?scrollTo=category) |[clearChecks](#CommandBuilder?scrollTo=clearChecks) | |
|[visible](#CommandBuilder?scrollTo=visible) |[setDescription](#CommandBuilder?scrollTo=setDescription) | |
| |[setCategory](#CommandBuilder?scrollTo=setCategory) | |
| |[show](#CommandBuilder?scrollTo=show) | |
| |[hide](#CommandBuilder?scrollTo=hide) | |
## Properties
### .name
Name of the command
**Type:** [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
### .fullname
Fullname of the command
**Type:** [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
### .callback
Callback for the command
**Type:** (event: [CommandContext](#CommandContext)) => void
### .parameters
Parameters for the command
**Type:** [CommandParameter](#CommandParameter)[]
### .checks
Permission checks to perform
**Type:** [PermissionCheck](#PermissionCheck)[]
### .description
Description of the command
**Type:** [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
### .category
Category the command fits into
**Type:** [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
### .visible
Whether or not the command is visible in the default help menu
**Type:** [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)
## Methods
<h3 id="canRun"> .canRun(context)</h3>
Checks all permission checks and verifies if a command can be run
|Parameter|Type |Optional|Default|Description |
|---------|---------------------------------|------- |-------|---------------------------|
|context |[CommandContext](#CommandContext)| | |The context for the command|
**Returns: [PermissionCheckResult](#PermissionCheckResult)**
<hr>
<h3 id="setCallback"> .setCallback(callback)</h3>
Set the command's callback
|Parameter |Type |Optional|Default|Description |
|----------|----------------------------------------------------|------- |-------|------------------------|
|callback |(context: [CommandContext](#CommandContext)) => void| | |Callback for the command|
**Returns: [CommandBuilder](#CommandBuilder)**
<hr>
<h3 id="addParameter"> .addParameter(name, type)</h3>
Add a command parameter
|Parameter|Type |Optional|Default|Description |
|---------|-------------------------------------------------------------------------------------------------|------- |-------|--------------|
|name |[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)| | |Parameter name|
|type |[ParameterType](#ParamaterType) | | |Parameter type|
**Returns: [CommandBuilder](#CommandBuilder)**
<hr>
<h3 id="clearParameters"> .clearParameters()</h3>
Remove all perameters
**Returns: [CommandBuilder](#CommandBuilder)**
<hr>
<h3 id="addCheck"> .addCheck(check)</h3>
Add a permission check
|Parameter |Type |Optional|Default|Description |
|----------|-----------------------------------|------- |-------|------------|
|check |[PermissionCheck](#PermissionCheck)| | |Check to add|
**Returns: [CommandBuilder](#CommandBuilder)**
<hr>
<h3 id="addChecks"> .addChecks(checks)</h3>
Add permission checks
|Parameter |Type |Optional|Default|Description |
|----------|-------------------------------------|------- |-------|-------------|
|checks |[PermissionCheck](#PermissionCheck)[]| | |Checks to add|
**Returns: [CommandBuilder](#CommandBuilder)**
<hr>
<h3 id="clearChecks"> .clearChecks()</h3>
Remove all checks
**Returns: [CommandBuilder](#CommandBuilder)**
<hr>
<h3 id="setDescription"> .setDescription(description)</h3>
Set command's description
|Parameter |Type |Optional|Default|Description |
|-----------|-------------------------------------------------------------------------------------------------|------- |-------|--------------------------|
|description|[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)| | |Description of the command|
**Returns: [CommandBuilder](#CommandBuilder)**
<hr>
<h3 id="setCategory"> .setCategory(category)</h3>
Set command's category
|Parameter|Type |Optional|Default|Description |
|---------|-------------------------------------------------------------------------------------------------|------- |-------|------------------------------|
|category |[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)| | |Category the command fits into|
**Returns: [CommandBuilder](#CommandBuilder)**
<hr>
<h3 id="show"> .show()</h3>
Set the command's visibility to true
**Returns: [CommandBuilder](#CommandBuilder)**
<hr>
<h3 id="hide"> .hide()</h3>
Set the command's visibility to false
**Returns: [CommandBuilder](#CommandBuilder)** | DusterTheFirst/mechan.js | docs/docs/files/CommandBuilder.md | Markdown | gpl-3.0 | 7,458 |
// Copyright 2020 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import * as React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { number } from '@storybook/addon-knobs';
import { LightboxGallery, Props } from './LightboxGallery';
import { setup as setupI18n } from '../../js/modules/i18n';
import enMessages from '../../_locales/en/messages.json';
import { IMAGE_JPEG, VIDEO_MP4 } from '../types/MIME';
const i18n = setupI18n('en', enMessages);
const story = storiesOf('Components/LightboxGallery', module);
const createProps = (overrideProps: Partial<Props> = {}): Props => ({
close: action('close'),
i18n,
media: overrideProps.media || [],
onSave: action('onSave'),
selectedIndex: number('selectedIndex', overrideProps.selectedIndex || 0),
});
story.add('Image and Video', () => {
const props = createProps({
media: [
{
attachment: {
contentType: IMAGE_JPEG,
fileName: 'tina-rolf-269345-unsplash.jpg',
url: '/fixtures/tina-rolf-269345-unsplash.jpg',
caption:
'Still from The Lighthouse, starring Robert Pattinson and Willem Defoe.',
},
contentType: IMAGE_JPEG,
index: 0,
message: {
attachments: [],
id: 'image-msg',
received_at: Date.now(),
},
objectURL: '/fixtures/tina-rolf-269345-unsplash.jpg',
},
{
attachment: {
contentType: VIDEO_MP4,
fileName: 'pixabay-Soap-Bubble-7141.mp4',
url: '/fixtures/pixabay-Soap-Bubble-7141.mp4',
},
contentType: VIDEO_MP4,
index: 1,
message: {
attachments: [],
id: 'video-msg',
received_at: Date.now(),
},
objectURL: '/fixtures/pixabay-Soap-Bubble-7141.mp4',
},
],
});
return <LightboxGallery {...props} />;
});
story.add('Missing Media', () => {
const props = createProps({
media: [
{
attachment: {
contentType: IMAGE_JPEG,
fileName: 'tina-rolf-269345-unsplash.jpg',
url: '/fixtures/tina-rolf-269345-unsplash.jpg',
},
contentType: IMAGE_JPEG,
index: 0,
message: {
attachments: [],
id: 'image-msg',
received_at: Date.now(),
},
objectURL: undefined,
},
],
});
return <LightboxGallery {...props} />;
});
| nrizzio/Signal-Desktop | ts/components/LightboxGallery.stories.tsx | TypeScript | gpl-3.0 | 2,482 |
// app.photoGrid
var Backbone = require("backbone");
// var _ = require("underscore");
var $ = require("jquery");
var ImageGridFuncs = require("./photo_grid_functions");
var ImageCollection = require("../models/photo_grid_image_collection");
var ImageView = require("./photo_grid_image");
module.exports = Backbone.View.extend({
el: '#photo-grid',
initialize: function () {
"use strict";
if (this.$el.length === 1) {
var gridJSON = this.$(".hid");
if (gridJSON.length === 1) {
this.funcs = new ImageGridFuncs();
this.template = this.funcs.slideTemplate();
// there is only one allowed div.hid
gridJSON = JSON.parse(gridJSON[0].innerHTML);
if (gridJSON.spacer_URL && gridJSON.image_URL) {
this.model.set({
parentModel: this.model, // pass as reference
spacerURL: gridJSON.spacer_URL,
imageURL: gridJSON.image_URL,
spacers: gridJSON.spacers,
images: gridJSON.images,
// shuffle image order:
imagesShuffled: this.funcs.shuffleArray(gridJSON.images),
});
this.setupGrid();
}
this.model.on({
'change:currentSlide': this.modelChange
}, this);
app.mindbodyModel.on({
'change:popoverVisible': this.killSlides
}, this);
}
}
},
setupGrid: function () {
"use strict";
var that = this,
spacers = this.model.get("spacers"),
randomInt,
imageCollection = new ImageCollection(),
i;
for (i = 0; i < this.model.get("images").length; i += 1) {
randomInt = that.funcs.getRandomInt(0, spacers.length);
imageCollection.add({
// push some info to individual views:
parentModel: this.model,
order: i,
spacerURL: this.model.get("spacerURL"),
spacer: spacers[randomInt],
imageURL: this.model.get("imageURL"),
image: this.model.get("imagesShuffled")[i],
});
}
imageCollection.each(this.imageView, this);
},
imageView: function (imageModel) {
"use strict";
var imageView = new ImageView({model: imageModel});
this.$el.append(imageView.render().el);
},
modelChange: function () {
"use strict";
var currSlide = this.model.get("currentSlide"),
allImages = this.model.get("imageURL"),
imageInfo,
imageViewer,
imgWidth,
slideDiv;
if (currSlide !== false) {
if (app.mindbodyModel.get("popoverVisible") !== true) {
app.mindbodyModel.set({popoverVisible : true});
}
// retrieve cached DOM object:
imageViewer = app.mbBackGroundShader.openPopUp("imageViewer");
// set the stage:
imageViewer.html(this.template(this.model.toJSON()));
// select div.slide, the ugly way:
slideDiv = imageViewer[0].getElementsByClassName("slide")[0];
// pull the array of info about the image:
imageInfo = this.model.get("images")[currSlide];
// calculate the size of the image when it fits the slideshow:
imgWidth = this.funcs.findSlideSize(imageInfo,
slideDiv.offsetWidth,
slideDiv.offsetHeight);
slideDiv.innerHTML = '<img src="' + allImages + imageInfo.filename +
'" style="width: ' + imgWidth + 'px;" />';
}
},
killSlides: function () {
"use strict";
if (app.mindbodyModel.get("popoverVisible") === false) {
// popover is gone. No more slideshow.
this.model.set({currentSlide : false});
}
},
});
| alexkademan/solful-2016-wp | _assets/js/views/photo_grid.js | JavaScript | gpl-3.0 | 4,143 |
package ua.pp.shurgent.tfctech.integration.bc.blocks.pipes.transport;
import net.minecraft.item.Item;
import net.minecraftforge.common.util.ForgeDirection;
import ua.pp.shurgent.tfctech.integration.bc.BCStuff;
import ua.pp.shurgent.tfctech.integration.bc.ModPipeIconProvider;
import ua.pp.shurgent.tfctech.integration.bc.blocks.pipes.handlers.PipeItemsInsertionHandler;
import buildcraft.api.core.IIconProvider;
import buildcraft.transport.pipes.PipeItemsQuartz;
import buildcraft.transport.pipes.events.PipeEventItem;
public class PipeItemsSterlingSilver extends PipeItemsQuartz {
public PipeItemsSterlingSilver(Item item) {
super(item);
}
@Override
public IIconProvider getIconProvider() {
return BCStuff.pipeIconProvider;
}
@Override
public int getIconIndex(ForgeDirection direction) {
return ModPipeIconProvider.TYPE.PipeItemsSterlingSilver.ordinal();
}
public void eventHandler(PipeEventItem.AdjustSpeed event) {
super.eventHandler(event);
}
public void eventHandler(PipeEventItem.Entered event) {
event.item.setInsertionHandler(PipeItemsInsertionHandler.INSTANCE);
}
}
| Shurgent/TFCTech | src/main/java/ua/pp/shurgent/tfctech/integration/bc/blocks/pipes/transport/PipeItemsSterlingSilver.java | Java | gpl-3.0 | 1,104 |
package org.crazyit.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* Description:
* <br/>site: <a href="http://www.crazyit.org">crazyit.org</a>
* <br/>Copyright (C), 2001-2012, Yeeku.H.Lee
* <br/>This program is protected by copyright laws.
* <br/>Program Name:
* <br/>Date:
* @author Yeeku.H.Lee [email protected]
* @version 1.0
*/
public class StartActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//»ñȡӦÓóÌÐòÖеÄbn°´Å¥
Button bn = (Button)findViewById(R.id.bn);
//Ϊbn°´Å¥°ó¶¨Ê¼þ¼àÌýÆ÷
bn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View source)
{
//´´½¨ÐèÒªÆô¶¯µÄActivity¶ÔÓ¦µÄIntent
Intent intent = new Intent(StartActivity.this
, SecondActivity.class);
//Æô¶¯intent¶ÔÓ¦µÄActivity
startActivity(intent);
}
});
}
} | footoflove/android | crazy_android/04/4.1/StartActivity/src/org/crazyit/activity/StartActivity.java | Java | gpl-3.0 | 1,081 |
// Remove the particular item
function removeArr(arr , removeItem){
if(arr.indexOf(removeItem) > -1){
arr.splice(arr.indexOf(removeItem),1);
}
return arr;
}
| SCABER-Dev-Team/SCABER | client-service/js/user_defined_operator.js | JavaScript | gpl-3.0 | 177 |
declared in [MTMatrix](MTMatrix.hpp.md)
~~~ { .cpp }
MTMatrix::MTMatrix(int rows, int cols)
{
//std::clog << "MTMatrix(" << rows << ", " << cols << ")" << std::endl;
if (cols > 0 && rows > 0) {
_rows = rows;
_cols = cols;
_elements = new double[_rows * _cols];
for (int i=0; i<_rows*_cols; i++) {
_elements[i] = 0.0; }
}
}
// make a real copy
MTMatrix::MTMatrix(MTMatrix const & m)
: MTMatrix(m._rows,m._cols)
{
//std::clog << "MTMatrix(MTMatrix(" << m._rows << ", " << m._cols << "))" << std::endl;
_transposed = m._transposed;
for (int i=0; i<_rows*_cols; i++) {
_elements[i] = m._elements[i]; }
}
MTMatrix & MTMatrix::operator=(MTMatrix const & m)
{
if (m._cols != _cols || m._rows != _rows) {
if (_elements) {
delete[] _elements;
_elements = nullptr; }
_cols = m._cols; _rows = m._rows;
}
if (! _elements) {
_elements = new double[_rows * _cols];
}
_transposed = m._transposed;
for (int i=0; i<_rows*_cols; i++) {
_elements[i] = m._elements[i]; }
}
~~~
deserialize a MTMatrix from its string representation
TODO :exclamation:
~~~ { .cpp }
MTMatrix::MTMatrix(std::string const & str)
{
}
~~~
| CodiePP/libmoltalk | Code/Cpp/MTMatrix_ctor.cpp.md | Markdown | gpl-3.0 | 1,160 |
package ru.mos.polls.ourapps.ui.adapter;
import java.util.ArrayList;
import java.util.List;
import ru.mos.polls.base.BaseRecyclerAdapter;
import ru.mos.polls.base.RecyclerBaseViewModel;
import ru.mos.polls.ourapps.model.OurApplication;
import ru.mos.polls.ourapps.vm.item.OurApplicationVM;
public class OurAppsAdapter extends BaseRecyclerAdapter<RecyclerBaseViewModel> {
public void add(List<OurApplication> list) {
List<RecyclerBaseViewModel> rbvm = new ArrayList<>();
for (OurApplication ourApp : list) {
rbvm.add(new OurApplicationVM(ourApp));
}
addData(rbvm);
}
}
| active-citizen/android.java | app/src/main/java/ru/mos/polls/ourapps/ui/adapter/OurAppsAdapter.java | Java | gpl-3.0 | 625 |
using System;
namespace SourceCodeCounter.Core
{
/// <summary>
/// The exception that is thrown when a command-line argument is invalid.
/// </summary>
internal class InvalidArgumentException : Exception
{
readonly string _argument;
public InvalidArgumentException(string argument)
: base("Invalid argument: '" + argument + "'")
{
_argument = argument;
}
public InvalidArgumentException(string argument, string message)
: base(message)
{
_argument = argument;
}
public InvalidArgumentException(string argument, string message, Exception inner)
: base(message, inner)
{
_argument = argument;
}
public InvalidArgumentException(string message, Exception inner)
: base(message, inner)
{
}
public string Argument
{
get { return _argument; }
}
}
} | kkurapaty/SourceCodeCounter | SourceCodeCounter/Core/InvalidArgumentException.cs | C# | gpl-3.0 | 1,037 |
html{
margin:0 auto;
}
body {
background:url(images_white/background.gif) repeat-y top center #fff;
color:#404040;
/* font:76% Verdana,Tahoma,Arial,sans-serif; */
line-height:1.3em;
margin:0 auto;
padding:0;
}
/* Menu */
#top_menu {
position:relative;
/* color: #6666aa; */
/* background-color: #aaccee; */
width:1010px;
margin:0 auto;
}
#top{
margin:0 auto;
}
#humo_menu {
background: linear-gradient(rgb(244, 244, 255) 0%, rgb(219, 219, 219) 100%);
margin:0 auto;
}
#humo_menu a {
color:#000000;
}
/* Pop-up menu */
#humo_menu ul.humo_menu_item2 li a{
background: linear-gradient(rgb(244, 244, 255) 0%, rgb(219, 219, 219) 100%);
}
#humo_menu a:visited { color: #000000; }
#humo_menu a:active {color: #2288dd; }
#humo_menu a:hover {color: #2288dd; }
/* #humo_menu a:hover { */
#humo_menu a:hover, #humo_menu ul.humo_menu_item2 li a:hover {
background:url("images_white/white.jpg") repeat left top;
}
#humo_menu #current {
}
#humo_menu #current a, #humo_menu #current_top {
background:url("images_white/white.jpg") repeat left top;
color:#333;
}
/* top bar in left - content - right boxes: only in main menu */
.mainmenu_bar{
background:none;
/* h2 {border-bottom:4px solid #dadada; color:#4088b8; font-size:1.4em; letter-spacing:-1px; margin:0 0 10px; padding:0 2px 2px 5px;} */
border-bottom:4px solid #dadada; color:#4088b8;
}
#mainmenu_centerbox {
box-shadow: 0px 0px 0px #999;
-moz-box-shadow: 0px 0px 0px #999;
-webkit-box-shadow: 0px 0px 0px #999;
}
.search_bar{
background:url("images_white/white.jpg") repeat left top;
/* background:none; */
}
#content {
display:block;
padding-left:10px;
position:relative;
z-index:3;
height:100%;
/* overflow:auto; */
max-height:90%;
top:35px;
width:1005px;
margin:0 auto;
}
#rtlcontent {
display:block;
padding-right:10px;
position:relative;
z-index:3;
height:100%;
/* overflow:auto; */
max-height:95%;
top:35px;
width:1024px;
margin:0 auto;
}
table.index_table{
width:1000px;
}
/* Tables */
table.humo { background-color: #ffffff; }
/* 1st table A-Z */
.border {
border: none;
/* border-collapse: collapse; */
}
table.humo {
-moz-box-shadow: 0px 0px 0px;
-webkit-box-shadow: 0px 0px 0px;
box-shadow: 0px 0px 0px;
}
table.humo td {
/* border: ridge 1px #3355cc; */
border:none;
/* background-color: #cceeff; */ /* achtergrond gezinsblad en 1e tabel */
border-bottom: 2px solid #dadada;
}
table.humo tr:first-of-type td { border:none; border-bottom: 2px solid #dadada; }
table.humo tr:first-of-type th { border:none; }
/* 2nd table A-Z */
.family_page_toptext {
color: #ffffff;
background-image: none;
color:black;
}
td.style_tree_text { background-color: #eeeeff; }
.table_headline{
background: linear-gradient(to bottom, rgb(244, 244, 255) 0%, rgb(219, 219, 219) 100%);
}
table.standard td.table_header { background-image: none; }
div.photobook{ background-color:#FFFFFF; }
.help_box { background-color:#FFFFFF; }
table.container{ background-color:#FFFFFF; }
table.reltable td { border:0px; } | HuubMons/HuMo-gen | styles/Clear_White.css | CSS | gpl-3.0 | 3,030 |
#ifndef AssimpSceneLoader_H
#define AssimpSceneLoader_H
#include <string>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <assimp/Importer.hpp>
#include "Common/Singleton.h"
#include "Mesh/Mesh.h"
#include "Shader/ShaderProgram.h"
#include "Scene/Material.h"
using std::string;
class AssimpSceneLoader : public Singleton<AssimpSceneLoader>
{
public:
vector<Mesh*> meshes;
const aiScene* assimpScene;
vector<Material*> materials;
AssimpSceneLoader();
void load(string file);
Mesh * initMesh(aiMesh * assMesh);
void initNode(aiNode * parent);
void printColor(const string &name, const aiColor4D & color);
};
#endif // AssimpSceneLoader_H
| lubosz/liblub | src/Load/AssimpSceneLoader.h | C | gpl-3.0 | 694 |
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Public Class rptAnalisisVencimiento
Inherits DevExpress.XtraReports.UI.XtraReport
'XtraReport overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Designer
'It can be modified using the Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container()
Dim StoredProcQuery1 As DevExpress.DataAccess.Sql.StoredProcQuery = New DevExpress.DataAccess.Sql.StoredProcQuery()
Dim QueryParameter1 As DevExpress.DataAccess.Sql.QueryParameter = New DevExpress.DataAccess.Sql.QueryParameter()
Dim QueryParameter2 As DevExpress.DataAccess.Sql.QueryParameter = New DevExpress.DataAccess.Sql.QueryParameter()
Dim QueryParameter3 As DevExpress.DataAccess.Sql.QueryParameter = New DevExpress.DataAccess.Sql.QueryParameter()
Dim QueryParameter4 As DevExpress.DataAccess.Sql.QueryParameter = New DevExpress.DataAccess.Sql.QueryParameter()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(rptAnalisisVencimiento))
Dim XrSummary1 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary2 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary3 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary4 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary5 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary6 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary7 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary8 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary9 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary10 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary11 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary12 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary13 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary14 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary15 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary16 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary17 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Dim XrSummary18 As DevExpress.XtraReports.UI.XRSummary = New DevExpress.XtraReports.UI.XRSummary()
Me.Detail = New DevExpress.XtraReports.UI.DetailBand()
Me.XrLabel18 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel19 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel20 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel21 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel22 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel23 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel24 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel25 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel26 = New DevExpress.XtraReports.UI.XRLabel()
Me.TopMargin = New DevExpress.XtraReports.UI.TopMarginBand()
Me.BottomMargin = New DevExpress.XtraReports.UI.BottomMarginBand()
Me.SqlDataSource1 = New DevExpress.DataAccess.Sql.SqlDataSource(Me.components)
Me.GroupHeaderSucursal = New DevExpress.XtraReports.UI.GroupHeaderBand()
Me.XrLabel2 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel1 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel15 = New DevExpress.XtraReports.UI.XRLabel()
Me.GroupHeaderCliente = New DevExpress.XtraReports.UI.GroupHeaderBand()
Me.XrLabel3 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel16 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel17 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel6 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel7 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel8 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel9 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel10 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel11 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel12 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel13 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel14 = New DevExpress.XtraReports.UI.XRLabel()
Me.PageFooterBand1 = New DevExpress.XtraReports.UI.PageFooterBand()
Me.ReportHeaderBand1 = New DevExpress.XtraReports.UI.ReportHeaderBand()
Me.GroupFooterBand1 = New DevExpress.XtraReports.UI.GroupFooterBand()
Me.GroupFooterBand2 = New DevExpress.XtraReports.UI.GroupFooterBand()
Me.XrLabel47 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel46 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel28 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel29 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel30 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel31 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel32 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel33 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel34 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel35 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel36 = New DevExpress.XtraReports.UI.XRLabel()
Me.ReportFooterBand1 = New DevExpress.XtraReports.UI.ReportFooterBand()
Me.XrLabel45 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel27 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel37 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel38 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel39 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel40 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel41 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel42 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel43 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel44 = New DevExpress.XtraReports.UI.XRLabel()
Me.Title = New DevExpress.XtraReports.UI.XRControlStyle()
Me.FieldCaption = New DevExpress.XtraReports.UI.XRControlStyle()
Me.PageInfo = New DevExpress.XtraReports.UI.XRControlStyle()
Me.DataField = New DevExpress.XtraReports.UI.XRControlStyle()
Me.PageHeader = New DevExpress.XtraReports.UI.PageHeaderBand()
Me.XrLabel49 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel48 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrPageInfo4 = New DevExpress.XtraReports.UI.XRPageInfo()
Me.XrPageInfo3 = New DevExpress.XtraReports.UI.XRPageInfo()
Me.XrLabel4 = New DevExpress.XtraReports.UI.XRLabel()
Me.XrLabel5 = New DevExpress.XtraReports.UI.XRLabel()
Me.lblHasta = New DevExpress.XtraReports.UI.XRLabel()
Me.pdFechaFinal = New DevExpress.XtraReports.Parameters.Parameter()
Me.lblCliente = New DevExpress.XtraReports.UI.XRLabel()
Me.psCliente = New DevExpress.XtraReports.Parameters.Parameter()
Me.lblNombreReporte = New DevExpress.XtraReports.UI.XRLabel()
Me.lblEmpresa = New DevExpress.XtraReports.UI.XRLabel()
Me.psEmpresa = New DevExpress.XtraReports.Parameters.Parameter()
Me.piIDBodega = New DevExpress.XtraReports.Parameters.Parameter()
Me.piIDCliente = New DevExpress.XtraReports.Parameters.Parameter()
Me.piConsolidaSucursal = New DevExpress.XtraReports.Parameters.Parameter()
Me.piEnDolar = New DevExpress.XtraReports.Parameters.Parameter()
Me.CalculatedField1 = New DevExpress.XtraReports.UI.CalculatedField()
CType(Me, System.ComponentModel.ISupportInitialize).BeginInit()
'
'Detail
'
Me.Detail.Controls.AddRange(New DevExpress.XtraReports.UI.XRControl() {Me.XrLabel18, Me.XrLabel19, Me.XrLabel20, Me.XrLabel21, Me.XrLabel22, Me.XrLabel23, Me.XrLabel24, Me.XrLabel25, Me.XrLabel26})
Me.Detail.HeightF = 21.7083!
Me.Detail.Name = "Detail"
Me.Detail.Padding = New DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100.0!)
Me.Detail.StyleName = "DataField"
Me.Detail.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft
'
'XrLabel18
'
Me.XrLabel18.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.SaldoNovencido", "{0:n2}")})
Me.XrLabel18.Font = New System.Drawing.Font("Times New Roman", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel18.LocationFloat = New DevExpress.Utils.PointFloat(15.24502!, 1.000023!)
Me.XrLabel18.Name = "XrLabel18"
Me.XrLabel18.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel18.SizeF = New System.Drawing.SizeF(103.0097!, 18.0!)
Me.XrLabel18.StylePriority.UseFont = False
Me.XrLabel18.StylePriority.UseTextAlignment = False
Me.XrLabel18.Text = "XrLabel18"
Me.XrLabel18.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel19
'
Me.XrLabel19.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldoa30", "{0:n2}")})
Me.XrLabel19.Font = New System.Drawing.Font("Times New Roman", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel19.LocationFloat = New DevExpress.Utils.PointFloat(130.7548!, 1.000023!)
Me.XrLabel19.Name = "XrLabel19"
Me.XrLabel19.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel19.SizeF = New System.Drawing.SizeF(75.74262!, 18.0!)
Me.XrLabel19.StylePriority.UseFont = False
Me.XrLabel19.StylePriority.UseTextAlignment = False
Me.XrLabel19.Text = "XrLabel19"
Me.XrLabel19.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel20
'
Me.XrLabel20.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldo31a60", "{0:n2}")})
Me.XrLabel20.Font = New System.Drawing.Font("Times New Roman", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel20.LocationFloat = New DevExpress.Utils.PointFloat(206.4974!, 1.000023!)
Me.XrLabel20.Name = "XrLabel20"
Me.XrLabel20.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel20.SizeF = New System.Drawing.SizeF(90.87666!, 18.0!)
Me.XrLabel20.StylePriority.UseFont = False
Me.XrLabel20.StylePriority.UseTextAlignment = False
Me.XrLabel20.Text = "XrLabel20"
Me.XrLabel20.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel21
'
Me.XrLabel21.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldo61a90", "{0:n2}")})
Me.XrLabel21.Font = New System.Drawing.Font("Times New Roman", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel21.LocationFloat = New DevExpress.Utils.PointFloat(315.8251!, 0.0!)
Me.XrLabel21.Name = "XrLabel21"
Me.XrLabel21.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel21.SizeF = New System.Drawing.SizeF(73.91107!, 18.0!)
Me.XrLabel21.StylePriority.UseFont = False
Me.XrLabel21.StylePriority.UseTextAlignment = False
Me.XrLabel21.Text = "XrLabel21"
Me.XrLabel21.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel22
'
Me.XrLabel22.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldo91a120", "{0:n2}")})
Me.XrLabel22.Font = New System.Drawing.Font("Times New Roman", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel22.LocationFloat = New DevExpress.Utils.PointFloat(398.1559!, 0.0!)
Me.XrLabel22.Name = "XrLabel22"
Me.XrLabel22.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel22.SizeF = New System.Drawing.SizeF(89.20599!, 18.0!)
Me.XrLabel22.StylePriority.UseFont = False
Me.XrLabel22.StylePriority.UseTextAlignment = False
Me.XrLabel22.Text = "XrLabel22"
Me.XrLabel22.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel23
'
Me.XrLabel23.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldo121a180", "{0:n2}")})
Me.XrLabel23.Font = New System.Drawing.Font("Times New Roman", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel23.LocationFloat = New DevExpress.Utils.PointFloat(501.5453!, 0.0!)
Me.XrLabel23.Name = "XrLabel23"
Me.XrLabel23.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel23.SizeF = New System.Drawing.SizeF(89.2699!, 18.0!)
Me.XrLabel23.StylePriority.UseFont = False
Me.XrLabel23.StylePriority.UseTextAlignment = False
Me.XrLabel23.Text = "XrLabel23"
Me.XrLabel23.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel24
'
Me.XrLabel24.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldo181a600", "{0:n2}")})
Me.XrLabel24.Font = New System.Drawing.Font("Times New Roman", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel24.LocationFloat = New DevExpress.Utils.PointFloat(608.9234!, 0.0!)
Me.XrLabel24.Name = "XrLabel24"
Me.XrLabel24.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel24.SizeF = New System.Drawing.SizeF(85.12994!, 18.0!)
Me.XrLabel24.StylePriority.UseFont = False
Me.XrLabel24.StylePriority.UseTextAlignment = False
Me.XrLabel24.Text = "XrLabel24"
Me.XrLabel24.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel25
'
Me.XrLabel25.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldomas600", "{0:n2}")})
Me.XrLabel25.Font = New System.Drawing.Font("Times New Roman", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel25.LocationFloat = New DevExpress.Utils.PointFloat(716.9433!, 0.0!)
Me.XrLabel25.Name = "XrLabel25"
Me.XrLabel25.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel25.SizeF = New System.Drawing.SizeF(81.20685!, 18.0!)
Me.XrLabel25.StylePriority.UseFont = False
Me.XrLabel25.StylePriority.UseTextAlignment = False
Me.XrLabel25.Text = "XrLabel25"
Me.XrLabel25.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel26
'
Me.XrLabel26.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.TotalCliente", "{0:n2}")})
Me.XrLabel26.Font = New System.Drawing.Font("Times New Roman", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel26.LocationFloat = New DevExpress.Utils.PointFloat(809.7319!, 0.0!)
Me.XrLabel26.Name = "XrLabel26"
Me.XrLabel26.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel26.SizeF = New System.Drawing.SizeF(80.26801!, 18.0!)
Me.XrLabel26.StylePriority.UseFont = False
Me.XrLabel26.StylePriority.UseTextAlignment = False
Me.XrLabel26.Text = "XrLabel26"
Me.XrLabel26.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'TopMargin
'
Me.TopMargin.HeightF = 100.0!
Me.TopMargin.Name = "TopMargin"
Me.TopMargin.Padding = New DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100.0!)
Me.TopMargin.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft
'
'BottomMargin
'
Me.BottomMargin.HeightF = 100.0!
Me.BottomMargin.Name = "BottomMargin"
Me.BottomMargin.Padding = New DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100.0!)
Me.BottomMargin.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft
'
'SqlDataSource1
'
Me.SqlDataSource1.ConnectionName = "Ced_Connection"
Me.SqlDataSource1.Name = "SqlDataSource1"
StoredProcQuery1.Name = "ccfGetAntiguedadSaldos"
QueryParameter1.Name = "@IDBodega"
QueryParameter1.Type = GetType(Integer)
QueryParameter1.ValueInfo = "0"
QueryParameter2.Name = "@IDCliente"
QueryParameter2.Type = GetType(Integer)
QueryParameter2.ValueInfo = "0"
QueryParameter3.Name = "@FechaCorte"
QueryParameter3.Type = GetType(DevExpress.DataAccess.Expression)
QueryParameter3.Value = New DevExpress.DataAccess.Expression("[Parameters.pdFechaFinal]", GetType(Date))
QueryParameter4.Name = "@EnDolar"
QueryParameter4.Type = GetType(DevExpress.DataAccess.Expression)
QueryParameter4.Value = New DevExpress.DataAccess.Expression("[Parameters.piEnDolar]", GetType(Short))
StoredProcQuery1.Parameters.Add(QueryParameter1)
StoredProcQuery1.Parameters.Add(QueryParameter2)
StoredProcQuery1.Parameters.Add(QueryParameter3)
StoredProcQuery1.Parameters.Add(QueryParameter4)
StoredProcQuery1.StoredProcName = "ccfrptAntiguedadSaldosPorCliente"
Me.SqlDataSource1.Queries.AddRange(New DevExpress.DataAccess.Sql.SqlQuery() {StoredProcQuery1})
Me.SqlDataSource1.ResultSchemaSerializable = resources.GetString("SqlDataSource1.ResultSchemaSerializable")
'
'GroupHeaderSucursal
'
Me.GroupHeaderSucursal.Controls.AddRange(New DevExpress.XtraReports.UI.XRControl() {Me.XrLabel2, Me.XrLabel1, Me.XrLabel15})
Me.GroupHeaderSucursal.GroupFields.AddRange(New DevExpress.XtraReports.UI.GroupField() {New DevExpress.XtraReports.UI.GroupField("Bodega", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending)})
Me.GroupHeaderSucursal.HeightF = 21.33335!
Me.GroupHeaderSucursal.KeepTogether = True
Me.GroupHeaderSucursal.Level = 1
Me.GroupHeaderSucursal.Name = "GroupHeaderSucursal"
Me.GroupHeaderSucursal.RepeatEveryPage = True
'
'XrLabel2
'
Me.XrLabel2.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Bodega")})
Me.XrLabel2.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel2.LocationFloat = New DevExpress.Utils.PointFloat(227.5867!, 3.333346!)
Me.XrLabel2.Name = "XrLabel2"
Me.XrLabel2.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel2.SizeF = New System.Drawing.SizeF(363.2288!, 18.0!)
Me.XrLabel2.StyleName = "DataField"
Me.XrLabel2.StylePriority.UseFont = False
Me.XrLabel2.Text = "XrLabel2"
'
'XrLabel1
'
Me.XrLabel1.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel1.LocationFloat = New DevExpress.Utils.PointFloat(92.38262!, 1.333332!)
Me.XrLabel1.Name = "XrLabel1"
Me.XrLabel1.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel1.SizeF = New System.Drawing.SizeF(67.70178!, 20.00002!)
Me.XrLabel1.StyleName = "FieldCaption"
Me.XrLabel1.StylePriority.UseFont = False
Me.XrLabel1.Text = "Sucursal"
'
'XrLabel15
'
Me.XrLabel15.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.IDBodega")})
Me.XrLabel15.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel15.LocationFloat = New DevExpress.Utils.PointFloat(175.6743!, 3.333346!)
Me.XrLabel15.Name = "XrLabel15"
Me.XrLabel15.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel15.SizeF = New System.Drawing.SizeF(41.70179!, 18.0!)
Me.XrLabel15.StylePriority.UseFont = False
Me.XrLabel15.Text = "XrLabel15"
'
'GroupHeaderCliente
'
Me.GroupHeaderCliente.Controls.AddRange(New DevExpress.XtraReports.UI.XRControl() {Me.XrLabel3, Me.XrLabel16, Me.XrLabel17})
Me.GroupHeaderCliente.GroupFields.AddRange(New DevExpress.XtraReports.UI.GroupField() {New DevExpress.XtraReports.UI.GroupField("IDCliente", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending)})
Me.GroupHeaderCliente.HeightF = 20.00002!
Me.GroupHeaderCliente.KeepTogether = True
Me.GroupHeaderCliente.Name = "GroupHeaderCliente"
Me.GroupHeaderCliente.RepeatEveryPage = True
Me.GroupHeaderCliente.StyleName = "FieldCaption"
'
'XrLabel3
'
Me.XrLabel3.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel3.LocationFloat = New DevExpress.Utils.PointFloat(15.24502!, 0.0!)
Me.XrLabel3.Name = "XrLabel3"
Me.XrLabel3.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel3.SizeF = New System.Drawing.SizeF(67.70178!, 20.00002!)
Me.XrLabel3.StyleName = "FieldCaption"
Me.XrLabel3.StylePriority.UseFont = False
Me.XrLabel3.Text = "Cliente"
'
'XrLabel16
'
Me.XrLabel16.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.IDCliente")})
Me.XrLabel16.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel16.LocationFloat = New DevExpress.Utils.PointFloat(93.29166!, 0.0!)
Me.XrLabel16.Name = "XrLabel16"
Me.XrLabel16.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel16.SizeF = New System.Drawing.SizeF(41.70176!, 18.0!)
Me.XrLabel16.StylePriority.UseFont = False
Me.XrLabel16.Text = "XrLabel16"
'
'XrLabel17
'
Me.XrLabel17.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.NOMBRE")})
Me.XrLabel17.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel17.LocationFloat = New DevExpress.Utils.PointFloat(145.2041!, 0.0!)
Me.XrLabel17.Name = "XrLabel17"
Me.XrLabel17.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel17.SizeF = New System.Drawing.SizeF(298.5751!, 18.0!)
Me.XrLabel17.StylePriority.UseFont = False
Me.XrLabel17.Text = "XrLabel17"
'
'XrLabel6
'
Me.XrLabel6.LocationFloat = New DevExpress.Utils.PointFloat(15.24499!, 149.5!)
Me.XrLabel6.Name = "XrLabel6"
Me.XrLabel6.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel6.SizeF = New System.Drawing.SizeF(103.0097!, 18.0!)
Me.XrLabel6.Text = "Saldo Novencido"
'
'XrLabel7
'
Me.XrLabel7.LocationFloat = New DevExpress.Utils.PointFloat(130.7547!, 149.5!)
Me.XrLabel7.Name = "XrLabel7"
Me.XrLabel7.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel7.SizeF = New System.Drawing.SizeF(75.74263!, 18.0!)
Me.XrLabel7.Text = "Saldoa30"
'
'XrLabel8
'
Me.XrLabel8.LocationFloat = New DevExpress.Utils.PointFloat(227.5865!, 149.5!)
Me.XrLabel8.Name = "XrLabel8"
Me.XrLabel8.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel8.SizeF = New System.Drawing.SizeF(69.78761!, 18.0!)
Me.XrLabel8.Text = "Saldo31a60"
'
'XrLabel9
'
Me.XrLabel9.LocationFloat = New DevExpress.Utils.PointFloat(315.8251!, 149.5!)
Me.XrLabel9.Name = "XrLabel9"
Me.XrLabel9.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel9.SizeF = New System.Drawing.SizeF(73.91107!, 18.0!)
Me.XrLabel9.Text = "Saldo61a90"
'
'XrLabel10
'
Me.XrLabel10.LocationFloat = New DevExpress.Utils.PointFloat(398.1559!, 149.5!)
Me.XrLabel10.Name = "XrLabel10"
Me.XrLabel10.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel10.SizeF = New System.Drawing.SizeF(89.20593!, 18.0!)
Me.XrLabel10.Text = "Saldo91a120"
'
'XrLabel11
'
Me.XrLabel11.LocationFloat = New DevExpress.Utils.PointFloat(501.5453!, 149.5!)
Me.XrLabel11.Name = "XrLabel11"
Me.XrLabel11.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel11.SizeF = New System.Drawing.SizeF(89.2699!, 18.0!)
Me.XrLabel11.Text = "Saldo121a180"
'
'XrLabel12
'
Me.XrLabel12.LocationFloat = New DevExpress.Utils.PointFloat(608.9234!, 149.5!)
Me.XrLabel12.Name = "XrLabel12"
Me.XrLabel12.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel12.SizeF = New System.Drawing.SizeF(94.47827!, 18.0!)
Me.XrLabel12.Text = "Saldo181a600"
'
'XrLabel13
'
Me.XrLabel13.LocationFloat = New DevExpress.Utils.PointFloat(716.9433!, 149.5!)
Me.XrLabel13.Name = "XrLabel13"
Me.XrLabel13.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel13.SizeF = New System.Drawing.SizeF(81.20685!, 18.0!)
Me.XrLabel13.Text = "Saldomas600"
'
'XrLabel14
'
Me.XrLabel14.LocationFloat = New DevExpress.Utils.PointFloat(809.7319!, 149.5!)
Me.XrLabel14.Name = "XrLabel14"
Me.XrLabel14.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel14.SizeF = New System.Drawing.SizeF(80.26813!, 18.0!)
Me.XrLabel14.Text = "Total Cliente"
'
'PageFooterBand1
'
Me.PageFooterBand1.HeightF = 31.00001!
Me.PageFooterBand1.Name = "PageFooterBand1"
'
'ReportHeaderBand1
'
Me.ReportHeaderBand1.HeightF = 0.0!
Me.ReportHeaderBand1.Name = "ReportHeaderBand1"
'
'GroupFooterBand1
'
Me.GroupFooterBand1.HeightF = 1.0!
Me.GroupFooterBand1.Name = "GroupFooterBand1"
'
'GroupFooterBand2
'
Me.GroupFooterBand2.Controls.AddRange(New DevExpress.XtraReports.UI.XRControl() {Me.XrLabel47, Me.XrLabel46, Me.XrLabel28, Me.XrLabel29, Me.XrLabel30, Me.XrLabel31, Me.XrLabel32, Me.XrLabel33, Me.XrLabel34, Me.XrLabel35, Me.XrLabel36})
Me.GroupFooterBand2.HeightF = 54.99999!
Me.GroupFooterBand2.Level = 1
Me.GroupFooterBand2.Name = "GroupFooterBand2"
'
'XrLabel47
'
Me.XrLabel47.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Bodega")})
Me.XrLabel47.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel47.LocationFloat = New DevExpress.Utils.PointFloat(175.6743!, 0.0!)
Me.XrLabel47.Name = "XrLabel47"
Me.XrLabel47.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel47.SizeF = New System.Drawing.SizeF(363.2288!, 18.0!)
Me.XrLabel47.StyleName = "DataField"
Me.XrLabel47.StylePriority.UseFont = False
Me.XrLabel47.Text = "XrLabel2"
'
'XrLabel46
'
Me.XrLabel46.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel46.LocationFloat = New DevExpress.Utils.PointFloat(34.375!, 0.0!)
Me.XrLabel46.Name = "XrLabel46"
Me.XrLabel46.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel46.SizeF = New System.Drawing.SizeF(140.3196!, 20.00002!)
Me.XrLabel46.StyleName = "FieldCaption"
Me.XrLabel46.StylePriority.UseFont = False
Me.XrLabel46.Text = "Totales de la Sucursal :"
'
'XrLabel28
'
Me.XrLabel28.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.SaldoNovencido")})
Me.XrLabel28.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel28.LocationFloat = New DevExpress.Utils.PointFloat(15.24502!, 35.00001!)
Me.XrLabel28.Name = "XrLabel28"
Me.XrLabel28.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel28.SizeF = New System.Drawing.SizeF(103.0097!, 18.0!)
Me.XrLabel28.StyleName = "FieldCaption"
Me.XrLabel28.StylePriority.UseFont = False
Me.XrLabel28.StylePriority.UseTextAlignment = False
XrSummary1.FormatString = "{0:n2}"
XrSummary1.Running = DevExpress.XtraReports.UI.SummaryRunning.Group
Me.XrLabel28.Summary = XrSummary1
Me.XrLabel28.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel29
'
Me.XrLabel29.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldoa30", "{0:C2}")})
Me.XrLabel29.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel29.LocationFloat = New DevExpress.Utils.PointFloat(130.7548!, 35.00001!)
Me.XrLabel29.Name = "XrLabel29"
Me.XrLabel29.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel29.SizeF = New System.Drawing.SizeF(60.11765!, 18.0!)
Me.XrLabel29.StyleName = "FieldCaption"
Me.XrLabel29.StylePriority.UseFont = False
Me.XrLabel29.StylePriority.UseTextAlignment = False
XrSummary2.FormatString = "{0:n2}"
XrSummary2.Running = DevExpress.XtraReports.UI.SummaryRunning.Group
Me.XrLabel29.Summary = XrSummary2
Me.XrLabel29.Text = "XrLabel29"
Me.XrLabel29.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel30
'
Me.XrLabel30.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldo31a60", "{0:C2}")})
Me.XrLabel30.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel30.LocationFloat = New DevExpress.Utils.PointFloat(206.4975!, 35.00001!)
Me.XrLabel30.Name = "XrLabel30"
Me.XrLabel30.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel30.SizeF = New System.Drawing.SizeF(90.87663!, 18.0!)
Me.XrLabel30.StyleName = "FieldCaption"
Me.XrLabel30.StylePriority.UseFont = False
Me.XrLabel30.StylePriority.UseTextAlignment = False
XrSummary3.FormatString = "{0:n2}"
XrSummary3.Running = DevExpress.XtraReports.UI.SummaryRunning.Group
Me.XrLabel30.Summary = XrSummary3
Me.XrLabel30.Text = "XrLabel30"
Me.XrLabel30.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel31
'
Me.XrLabel31.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldo61a90", "{0:C2}")})
Me.XrLabel31.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel31.LocationFloat = New DevExpress.Utils.PointFloat(315.8251!, 36.99999!)
Me.XrLabel31.Name = "XrLabel31"
Me.XrLabel31.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel31.SizeF = New System.Drawing.SizeF(73.91107!, 18.0!)
Me.XrLabel31.StyleName = "FieldCaption"
Me.XrLabel31.StylePriority.UseFont = False
Me.XrLabel31.StylePriority.UseTextAlignment = False
XrSummary4.FormatString = "{0:n2}"
XrSummary4.Running = DevExpress.XtraReports.UI.SummaryRunning.Group
Me.XrLabel31.Summary = XrSummary4
Me.XrLabel31.Text = "XrLabel31"
Me.XrLabel31.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel32
'
Me.XrLabel32.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldo91a120", "{0:C2}")})
Me.XrLabel32.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel32.LocationFloat = New DevExpress.Utils.PointFloat(398.1559!, 35.00001!)
Me.XrLabel32.Name = "XrLabel32"
Me.XrLabel32.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel32.SizeF = New System.Drawing.SizeF(89.20599!, 18.0!)
Me.XrLabel32.StyleName = "FieldCaption"
Me.XrLabel32.StylePriority.UseFont = False
Me.XrLabel32.StylePriority.UseTextAlignment = False
XrSummary5.FormatString = "{0:n2}"
XrSummary5.Running = DevExpress.XtraReports.UI.SummaryRunning.Group
Me.XrLabel32.Summary = XrSummary5
Me.XrLabel32.Text = "XrLabel32"
Me.XrLabel32.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel33
'
Me.XrLabel33.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldo121a180", "{0:C2}")})
Me.XrLabel33.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel33.LocationFloat = New DevExpress.Utils.PointFloat(501.5453!, 35.00001!)
Me.XrLabel33.Name = "XrLabel33"
Me.XrLabel33.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel33.SizeF = New System.Drawing.SizeF(89.26993!, 18.0!)
Me.XrLabel33.StyleName = "FieldCaption"
Me.XrLabel33.StylePriority.UseFont = False
Me.XrLabel33.StylePriority.UseTextAlignment = False
XrSummary6.FormatString = "{0:n2}"
XrSummary6.Running = DevExpress.XtraReports.UI.SummaryRunning.Group
Me.XrLabel33.Summary = XrSummary6
Me.XrLabel33.Text = "XrLabel33"
Me.XrLabel33.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel34
'
Me.XrLabel34.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldo181a600", "{0:C2}")})
Me.XrLabel34.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel34.LocationFloat = New DevExpress.Utils.PointFloat(608.9234!, 35.00001!)
Me.XrLabel34.Name = "XrLabel34"
Me.XrLabel34.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel34.SizeF = New System.Drawing.SizeF(85.13!, 18.0!)
Me.XrLabel34.StyleName = "FieldCaption"
Me.XrLabel34.StylePriority.UseFont = False
Me.XrLabel34.StylePriority.UseTextAlignment = False
XrSummary7.FormatString = "{0:n2}"
XrSummary7.Running = DevExpress.XtraReports.UI.SummaryRunning.Group
Me.XrLabel34.Summary = XrSummary7
Me.XrLabel34.Text = "XrLabel34"
Me.XrLabel34.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel35
'
Me.XrLabel35.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldomas600", "{0:C2}")})
Me.XrLabel35.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel35.LocationFloat = New DevExpress.Utils.PointFloat(716.9433!, 35.00001!)
Me.XrLabel35.Name = "XrLabel35"
Me.XrLabel35.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel35.SizeF = New System.Drawing.SizeF(81.20691!, 18.0!)
Me.XrLabel35.StyleName = "FieldCaption"
Me.XrLabel35.StylePriority.UseFont = False
Me.XrLabel35.StylePriority.UseTextAlignment = False
XrSummary8.FormatString = "{0:n2}"
XrSummary8.Running = DevExpress.XtraReports.UI.SummaryRunning.Group
Me.XrLabel35.Summary = XrSummary8
Me.XrLabel35.Text = "XrLabel35"
Me.XrLabel35.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel36
'
Me.XrLabel36.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.TotalCliente", "{0:C2}")})
Me.XrLabel36.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel36.LocationFloat = New DevExpress.Utils.PointFloat(809.7321!, 35.00001!)
Me.XrLabel36.Name = "XrLabel36"
Me.XrLabel36.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel36.SizeF = New System.Drawing.SizeF(80.26794!, 18.0!)
Me.XrLabel36.StyleName = "FieldCaption"
Me.XrLabel36.StylePriority.UseFont = False
Me.XrLabel36.StylePriority.UseTextAlignment = False
XrSummary9.FormatString = "{0:n2}"
XrSummary9.Running = DevExpress.XtraReports.UI.SummaryRunning.Group
Me.XrLabel36.Summary = XrSummary9
Me.XrLabel36.Text = "XrLabel36"
Me.XrLabel36.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'ReportFooterBand1
'
Me.ReportFooterBand1.Controls.AddRange(New DevExpress.XtraReports.UI.XRControl() {Me.XrLabel45, Me.XrLabel27, Me.XrLabel37, Me.XrLabel38, Me.XrLabel39, Me.XrLabel40, Me.XrLabel41, Me.XrLabel42, Me.XrLabel43, Me.XrLabel44})
Me.ReportFooterBand1.HeightF = 66.45832!
Me.ReportFooterBand1.Name = "ReportFooterBand1"
'
'XrLabel45
'
Me.XrLabel45.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel45.LocationFloat = New DevExpress.Utils.PointFloat(19.76484!, 10.00001!)
Me.XrLabel45.Name = "XrLabel45"
Me.XrLabel45.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel45.SizeF = New System.Drawing.SizeF(140.3196!, 20.00002!)
Me.XrLabel45.StyleName = "FieldCaption"
Me.XrLabel45.StylePriority.UseFont = False
Me.XrLabel45.Text = "Totales Generales :"
'
'XrLabel27
'
Me.XrLabel27.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.TotalCliente", "{0:C2}")})
Me.XrLabel27.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel27.LocationFloat = New DevExpress.Utils.PointFloat(809.7322!, 38.45832!)
Me.XrLabel27.Name = "XrLabel27"
Me.XrLabel27.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel27.SizeF = New System.Drawing.SizeF(80.26794!, 18.0!)
Me.XrLabel27.StyleName = "FieldCaption"
Me.XrLabel27.StylePriority.UseFont = False
Me.XrLabel27.StylePriority.UseTextAlignment = False
XrSummary10.FormatString = "{0:n2}"
XrSummary10.Running = DevExpress.XtraReports.UI.SummaryRunning.Report
Me.XrLabel27.Summary = XrSummary10
Me.XrLabel27.Text = "XrLabel36"
Me.XrLabel27.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel37
'
Me.XrLabel37.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldomas600", "{0:C2}")})
Me.XrLabel37.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel37.LocationFloat = New DevExpress.Utils.PointFloat(716.9434!, 38.45832!)
Me.XrLabel37.Name = "XrLabel37"
Me.XrLabel37.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel37.SizeF = New System.Drawing.SizeF(81.20691!, 18.0!)
Me.XrLabel37.StyleName = "FieldCaption"
Me.XrLabel37.StylePriority.UseFont = False
Me.XrLabel37.StylePriority.UseTextAlignment = False
XrSummary11.FormatString = "{0:n2}"
XrSummary11.Running = DevExpress.XtraReports.UI.SummaryRunning.Report
Me.XrLabel37.Summary = XrSummary11
Me.XrLabel37.Text = "XrLabel35"
Me.XrLabel37.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel38
'
Me.XrLabel38.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldo181a600", "{0:C2}")})
Me.XrLabel38.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel38.LocationFloat = New DevExpress.Utils.PointFloat(608.9235!, 38.45832!)
Me.XrLabel38.Name = "XrLabel38"
Me.XrLabel38.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel38.SizeF = New System.Drawing.SizeF(85.13!, 18.0!)
Me.XrLabel38.StyleName = "FieldCaption"
Me.XrLabel38.StylePriority.UseFont = False
Me.XrLabel38.StylePriority.UseTextAlignment = False
XrSummary12.FormatString = "{0:n2}"
XrSummary12.Running = DevExpress.XtraReports.UI.SummaryRunning.Report
Me.XrLabel38.Summary = XrSummary12
Me.XrLabel38.Text = "XrLabel34"
Me.XrLabel38.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel39
'
Me.XrLabel39.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldo121a180", "{0:C2}")})
Me.XrLabel39.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel39.LocationFloat = New DevExpress.Utils.PointFloat(501.5453!, 38.45832!)
Me.XrLabel39.Name = "XrLabel39"
Me.XrLabel39.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel39.SizeF = New System.Drawing.SizeF(89.26993!, 18.0!)
Me.XrLabel39.StyleName = "FieldCaption"
Me.XrLabel39.StylePriority.UseFont = False
Me.XrLabel39.StylePriority.UseTextAlignment = False
XrSummary13.FormatString = "{0:n2}"
XrSummary13.Running = DevExpress.XtraReports.UI.SummaryRunning.Report
Me.XrLabel39.Summary = XrSummary13
Me.XrLabel39.Text = "XrLabel33"
Me.XrLabel39.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel40
'
Me.XrLabel40.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldo91a120", "{0:C2}")})
Me.XrLabel40.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel40.LocationFloat = New DevExpress.Utils.PointFloat(398.1559!, 38.45832!)
Me.XrLabel40.Name = "XrLabel40"
Me.XrLabel40.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel40.SizeF = New System.Drawing.SizeF(89.20599!, 18.0!)
Me.XrLabel40.StyleName = "FieldCaption"
Me.XrLabel40.StylePriority.UseFont = False
Me.XrLabel40.StylePriority.UseTextAlignment = False
XrSummary14.FormatString = "{0:n2}"
XrSummary14.Running = DevExpress.XtraReports.UI.SummaryRunning.Report
Me.XrLabel40.Summary = XrSummary14
Me.XrLabel40.Text = "XrLabel32"
Me.XrLabel40.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel41
'
Me.XrLabel41.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldo61a90", "{0:C2}")})
Me.XrLabel41.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel41.LocationFloat = New DevExpress.Utils.PointFloat(315.8251!, 40.4583!)
Me.XrLabel41.Name = "XrLabel41"
Me.XrLabel41.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel41.SizeF = New System.Drawing.SizeF(73.91107!, 18.0!)
Me.XrLabel41.StyleName = "FieldCaption"
Me.XrLabel41.StylePriority.UseFont = False
Me.XrLabel41.StylePriority.UseTextAlignment = False
XrSummary15.FormatString = "{0:n2}"
XrSummary15.Running = DevExpress.XtraReports.UI.SummaryRunning.Report
Me.XrLabel41.Summary = XrSummary15
Me.XrLabel41.Text = "XrLabel31"
Me.XrLabel41.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel42
'
Me.XrLabel42.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldo31a60", "{0:C2}")})
Me.XrLabel42.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel42.LocationFloat = New DevExpress.Utils.PointFloat(206.4975!, 38.45832!)
Me.XrLabel42.Name = "XrLabel42"
Me.XrLabel42.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel42.SizeF = New System.Drawing.SizeF(90.87663!, 18.0!)
Me.XrLabel42.StyleName = "FieldCaption"
Me.XrLabel42.StylePriority.UseFont = False
Me.XrLabel42.StylePriority.UseTextAlignment = False
XrSummary16.FormatString = "{0:n2}"
XrSummary16.Running = DevExpress.XtraReports.UI.SummaryRunning.Report
Me.XrLabel42.Summary = XrSummary16
Me.XrLabel42.Text = "XrLabel30"
Me.XrLabel42.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel43
'
Me.XrLabel43.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.Saldoa30", "{0:C2}")})
Me.XrLabel43.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel43.LocationFloat = New DevExpress.Utils.PointFloat(130.7549!, 38.45832!)
Me.XrLabel43.Name = "XrLabel43"
Me.XrLabel43.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel43.SizeF = New System.Drawing.SizeF(60.11765!, 18.0!)
Me.XrLabel43.StyleName = "FieldCaption"
Me.XrLabel43.StylePriority.UseFont = False
Me.XrLabel43.StylePriority.UseTextAlignment = False
XrSummary17.FormatString = "{0:n2}"
XrSummary17.Running = DevExpress.XtraReports.UI.SummaryRunning.Report
Me.XrLabel43.Summary = XrSummary17
Me.XrLabel43.Text = "XrLabel29"
Me.XrLabel43.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel44
'
Me.XrLabel44.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.SaldoNovencido")})
Me.XrLabel44.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel44.LocationFloat = New DevExpress.Utils.PointFloat(15.24506!, 38.45832!)
Me.XrLabel44.Name = "XrLabel44"
Me.XrLabel44.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel44.SizeF = New System.Drawing.SizeF(103.0097!, 18.0!)
Me.XrLabel44.StyleName = "FieldCaption"
Me.XrLabel44.StylePriority.UseFont = False
Me.XrLabel44.StylePriority.UseTextAlignment = False
XrSummary18.FormatString = "{0:n2}"
XrSummary18.Running = DevExpress.XtraReports.UI.SummaryRunning.Report
Me.XrLabel44.Summary = XrSummary18
Me.XrLabel44.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'Title
'
Me.Title.BackColor = System.Drawing.Color.Transparent
Me.Title.BorderColor = System.Drawing.Color.Black
Me.Title.Borders = DevExpress.XtraPrinting.BorderSide.None
Me.Title.BorderWidth = 1.0!
Me.Title.Font = New System.Drawing.Font("Times New Roman", 20.0!, System.Drawing.FontStyle.Bold)
Me.Title.ForeColor = System.Drawing.Color.Maroon
Me.Title.Name = "Title"
'
'FieldCaption
'
Me.FieldCaption.BackColor = System.Drawing.Color.Transparent
Me.FieldCaption.BorderColor = System.Drawing.Color.Black
Me.FieldCaption.Borders = DevExpress.XtraPrinting.BorderSide.None
Me.FieldCaption.BorderWidth = 1.0!
Me.FieldCaption.Font = New System.Drawing.Font("Arial", 10.0!, System.Drawing.FontStyle.Bold)
Me.FieldCaption.ForeColor = System.Drawing.Color.Maroon
Me.FieldCaption.Name = "FieldCaption"
'
'PageInfo
'
Me.PageInfo.BackColor = System.Drawing.Color.Transparent
Me.PageInfo.BorderColor = System.Drawing.Color.Black
Me.PageInfo.Borders = DevExpress.XtraPrinting.BorderSide.None
Me.PageInfo.BorderWidth = 1.0!
Me.PageInfo.Font = New System.Drawing.Font("Times New Roman", 10.0!, System.Drawing.FontStyle.Bold)
Me.PageInfo.ForeColor = System.Drawing.Color.Black
Me.PageInfo.Name = "PageInfo"
'
'DataField
'
Me.DataField.BackColor = System.Drawing.Color.Transparent
Me.DataField.BorderColor = System.Drawing.Color.Black
Me.DataField.Borders = DevExpress.XtraPrinting.BorderSide.None
Me.DataField.BorderWidth = 1.0!
Me.DataField.Font = New System.Drawing.Font("Times New Roman", 10.0!)
Me.DataField.ForeColor = System.Drawing.Color.Black
Me.DataField.Name = "DataField"
Me.DataField.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
'
'PageHeader
'
Me.PageHeader.Controls.AddRange(New DevExpress.XtraReports.UI.XRControl() {Me.XrLabel49, Me.XrLabel48, Me.XrPageInfo4, Me.XrPageInfo3, Me.XrLabel4, Me.XrLabel5, Me.lblHasta, Me.lblCliente, Me.lblNombreReporte, Me.lblEmpresa, Me.XrLabel14, Me.XrLabel13, Me.XrLabel12, Me.XrLabel11, Me.XrLabel10, Me.XrLabel9, Me.XrLabel8, Me.XrLabel7, Me.XrLabel6})
Me.PageHeader.HeightF = 177.5!
Me.PageHeader.Name = "PageHeader"
'
'XrLabel49
'
Me.XrLabel49.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding("Text", Nothing, "ccfGetAntiguedadSaldos.CalculatedField1")})
Me.XrLabel49.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel49.LocationFloat = New DevExpress.Utils.PointFloat(215.6208!, 99.12504!)
Me.XrLabel49.Name = "XrLabel49"
Me.XrLabel49.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel49.SizeF = New System.Drawing.SizeF(228.1584!, 22.99999!)
Me.XrLabel49.StylePriority.UseFont = False
Me.XrLabel49.Text = "XrLabel49"
'
'XrLabel48
'
Me.XrLabel48.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel48.LocationFloat = New DevExpress.Utils.PointFloat(125.1225!, 99.12504!)
Me.XrLabel48.Name = "XrLabel48"
Me.XrLabel48.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel48.SizeF = New System.Drawing.SizeF(81.37496!, 23.0!)
Me.XrLabel48.StylePriority.UseFont = False
Me.XrLabel48.Text = "Moneda :"
'
'XrPageInfo4
'
Me.XrPageInfo4.Font = New System.Drawing.Font("Times New Roman", 10.0!)
Me.XrPageInfo4.Format = "Page {0} of {1}"
Me.XrPageInfo4.LocationFloat = New DevExpress.Utils.PointFloat(654.9127!, 17.125!)
Me.XrPageInfo4.Name = "XrPageInfo4"
Me.XrPageInfo4.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrPageInfo4.SizeF = New System.Drawing.SizeF(81.74994!, 23.0!)
Me.XrPageInfo4.StyleName = "PageInfo"
Me.XrPageInfo4.StylePriority.UseFont = False
Me.XrPageInfo4.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrPageInfo3
'
Me.XrPageInfo3.Font = New System.Drawing.Font("Times New Roman", 10.0!)
Me.XrPageInfo3.Format = "{0:dd/MM/yyyy HH:mm}"
Me.XrPageInfo3.LocationFloat = New DevExpress.Utils.PointFloat(595.5376!, 40.12502!)
Me.XrPageInfo3.Name = "XrPageInfo3"
Me.XrPageInfo3.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrPageInfo3.PageInfo = DevExpress.XtraPrinting.PageInfo.DateTime
Me.XrPageInfo3.SizeF = New System.Drawing.SizeF(141.1249!, 23.0!)
Me.XrPageInfo3.StyleName = "PageInfo"
Me.XrPageInfo3.StylePriority.UseFont = False
Me.XrPageInfo3.StylePriority.UseTextAlignment = False
Me.XrPageInfo3.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopRight
'
'XrLabel4
'
Me.XrLabel4.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel4.LocationFloat = New DevExpress.Utils.PointFloat(124.329!, 76.12502!)
Me.XrLabel4.Name = "XrLabel4"
Me.XrLabel4.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel4.SizeF = New System.Drawing.SizeF(81.37496!, 23.0!)
Me.XrLabel4.StylePriority.UseFont = False
Me.XrLabel4.Text = "Cliente :"
'
'XrLabel5
'
Me.XrLabel5.Font = New System.Drawing.Font("Verdana", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.XrLabel5.LocationFloat = New DevExpress.Utils.PointFloat(259.9543!, 53.125!)
Me.XrLabel5.Name = "XrLabel5"
Me.XrLabel5.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.XrLabel5.SizeF = New System.Drawing.SizeF(94.8334!, 23.0!)
Me.XrLabel5.StylePriority.UseFont = False
Me.XrLabel5.Text = "Cortado al :"
'
'lblHasta
'
Me.lblHasta.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding(Me.pdFechaFinal, "Text", "{0:dd/MM/yyyy}")})
Me.lblHasta.Font = New System.Drawing.Font("Verdana", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.lblHasta.LocationFloat = New DevExpress.Utils.PointFloat(378.4542!, 53.125!)
Me.lblHasta.Name = "lblHasta"
Me.lblHasta.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.lblHasta.SizeF = New System.Drawing.SizeF(120.2498!, 23.0!)
Me.lblHasta.StylePriority.UseFont = False
'
'pdFechaFinal
'
Me.pdFechaFinal.Description = "Parameter1"
Me.pdFechaFinal.Name = "pdFechaFinal"
Me.pdFechaFinal.Type = GetType(Date)
Me.pdFechaFinal.Visible = False
'
'lblCliente
'
Me.lblCliente.CanGrow = False
Me.lblCliente.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding(Me.psCliente, "Text", "")})
Me.lblCliente.Font = New System.Drawing.Font("Verdana", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.lblCliente.LocationFloat = New DevExpress.Utils.PointFloat(215.6208!, 76.12502!)
Me.lblCliente.Name = "lblCliente"
Me.lblCliente.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.lblCliente.SizeF = New System.Drawing.SizeF(538.5416!, 23.0!)
Me.lblCliente.StylePriority.UseFont = False
'
'psCliente
'
Me.psCliente.Description = "Parameter1"
Me.psCliente.Name = "psCliente"
Me.psCliente.Visible = False
'
'lblNombreReporte
'
Me.lblNombreReporte.Font = New System.Drawing.Font("Times New Roman", 12.0!, System.Drawing.FontStyle.Bold)
Me.lblNombreReporte.LocationFloat = New DevExpress.Utils.PointFloat(241.1284!, 30.125!)
Me.lblNombreReporte.Name = "lblNombreReporte"
Me.lblNombreReporte.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.lblNombreReporte.SizeF = New System.Drawing.SizeF(246.2336!, 23.00001!)
Me.lblNombreReporte.StylePriority.UseFont = False
Me.lblNombreReporte.StylePriority.UseTextAlignment = False
Me.lblNombreReporte.Text = "Análisis de Vencimiento"
Me.lblNombreReporte.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopCenter
'
'lblEmpresa
'
Me.lblEmpresa.DataBindings.AddRange(New DevExpress.XtraReports.UI.XRBinding() {New DevExpress.XtraReports.UI.XRBinding(Me.psEmpresa, "Text", "")})
Me.lblEmpresa.Font = New System.Drawing.Font("Times New Roman", 12.0!, System.Drawing.FontStyle.Bold)
Me.lblEmpresa.LocationFloat = New DevExpress.Utils.PointFloat(189.6207!, 7.124996!)
Me.lblEmpresa.Name = "lblEmpresa"
Me.lblEmpresa.Padding = New DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100.0!)
Me.lblEmpresa.SizeF = New System.Drawing.SizeF(344.7917!, 23.0!)
Me.lblEmpresa.StylePriority.UseFont = False
Me.lblEmpresa.StylePriority.UseTextAlignment = False
Me.lblEmpresa.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopCenter
'
'psEmpresa
'
Me.psEmpresa.Description = "Parameter1"
Me.psEmpresa.Name = "psEmpresa"
Me.psEmpresa.Visible = False
'
'piIDBodega
'
Me.piIDBodega.Description = "Parameter1"
Me.piIDBodega.Name = "piIDBodega"
Me.piIDBodega.Type = GetType(Integer)
Me.piIDBodega.ValueInfo = "0"
Me.piIDBodega.Visible = False
'
'piIDCliente
'
Me.piIDCliente.Description = "Parameter1"
Me.piIDCliente.Name = "piIDCliente"
Me.piIDCliente.Type = GetType(Integer)
Me.piIDCliente.ValueInfo = "0"
Me.piIDCliente.Visible = False
'
'piConsolidaSucursal
'
Me.piConsolidaSucursal.Description = "Parameter1"
Me.piConsolidaSucursal.Name = "piConsolidaSucursal"
Me.piConsolidaSucursal.Type = GetType(Short)
Me.piConsolidaSucursal.ValueInfo = "0"
Me.piConsolidaSucursal.Visible = False
'
'piEnDolar
'
Me.piEnDolar.Description = "Parameter1"
Me.piEnDolar.Name = "piEnDolar"
Me.piEnDolar.Type = GetType(Short)
Me.piEnDolar.ValueInfo = "0"
Me.piEnDolar.Visible = False
'
'CalculatedField1
'
Me.CalculatedField1.DataMember = "ccfGetAntiguedadSaldos"
Me.CalculatedField1.DisplayName = "Moneda"
Me.CalculatedField1.Expression = "Iif([Parameters.piEnDolar]=1,'DOLAR' ,'CORDOBA' )"
Me.CalculatedField1.Name = "CalculatedField1"
'
'rptAnalisisVencimiento
'
Me.Bands.AddRange(New DevExpress.XtraReports.UI.Band() {Me.Detail, Me.TopMargin, Me.BottomMargin, Me.GroupHeaderSucursal, Me.GroupHeaderCliente, Me.PageFooterBand1, Me.ReportHeaderBand1, Me.GroupFooterBand2, Me.ReportFooterBand1, Me.PageHeader})
Me.CalculatedFields.AddRange(New DevExpress.XtraReports.UI.CalculatedField() {Me.CalculatedField1})
Me.ComponentStorage.AddRange(New System.ComponentModel.IComponent() {Me.SqlDataSource1})
Me.DataMember = "ccfGetAntiguedadSaldos"
Me.DataSource = Me.SqlDataSource1
Me.Landscape = True
Me.Margins = New System.Drawing.Printing.Margins(100, 103, 100, 100)
Me.PageHeight = 850
Me.PageWidth = 1100
Me.Parameters.AddRange(New DevExpress.XtraReports.Parameters.Parameter() {Me.psCliente, Me.psEmpresa, Me.piIDBodega, Me.piIDCliente, Me.pdFechaFinal, Me.piConsolidaSucursal, Me.piEnDolar})
Me.ScriptLanguage = DevExpress.XtraReports.ScriptLanguage.VisualBasic
Me.StyleSheet.AddRange(New DevExpress.XtraReports.UI.XRControlStyle() {Me.Title, Me.FieldCaption, Me.PageInfo, Me.DataField})
Me.Version = "15.2"
CType(Me, System.ComponentModel.ISupportInitialize).EndInit()
End Sub
Friend WithEvents Detail As DevExpress.XtraReports.UI.DetailBand
Friend WithEvents TopMargin As DevExpress.XtraReports.UI.TopMarginBand
Friend WithEvents BottomMargin As DevExpress.XtraReports.UI.BottomMarginBand
Friend WithEvents XrLabel15 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel16 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel17 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel18 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel19 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel20 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel21 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel22 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel23 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel24 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel25 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel26 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents SqlDataSource1 As DevExpress.DataAccess.Sql.SqlDataSource
Friend WithEvents GroupHeaderSucursal As DevExpress.XtraReports.UI.GroupHeaderBand
Friend WithEvents XrLabel2 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel1 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents GroupHeaderCliente As DevExpress.XtraReports.UI.GroupHeaderBand
Friend WithEvents XrLabel6 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel7 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel8 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel9 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel10 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel11 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel12 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel13 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel14 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents PageFooterBand1 As DevExpress.XtraReports.UI.PageFooterBand
Friend WithEvents ReportHeaderBand1 As DevExpress.XtraReports.UI.ReportHeaderBand
Friend WithEvents GroupFooterBand1 As DevExpress.XtraReports.UI.GroupFooterBand
Friend WithEvents GroupFooterBand2 As DevExpress.XtraReports.UI.GroupFooterBand
Friend WithEvents XrLabel28 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel29 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel30 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel31 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel32 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel33 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel34 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel35 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel36 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents ReportFooterBand1 As DevExpress.XtraReports.UI.ReportFooterBand
Friend WithEvents Title As DevExpress.XtraReports.UI.XRControlStyle
Friend WithEvents FieldCaption As DevExpress.XtraReports.UI.XRControlStyle
Friend WithEvents PageInfo As DevExpress.XtraReports.UI.XRControlStyle
Friend WithEvents DataField As DevExpress.XtraReports.UI.XRControlStyle
Friend WithEvents PageHeader As DevExpress.XtraReports.UI.PageHeaderBand
Friend WithEvents XrLabel3 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrPageInfo4 As DevExpress.XtraReports.UI.XRPageInfo
Friend WithEvents XrPageInfo3 As DevExpress.XtraReports.UI.XRPageInfo
Friend WithEvents XrLabel4 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel5 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents lblHasta As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents lblCliente As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents lblNombreReporte As DevExpress.XtraReports.UI.XRLabel
Public WithEvents lblEmpresa As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents psCliente As DevExpress.XtraReports.Parameters.Parameter
Friend WithEvents psEmpresa As DevExpress.XtraReports.Parameters.Parameter
Friend WithEvents piIDBodega As DevExpress.XtraReports.Parameters.Parameter
Friend WithEvents piIDCliente As DevExpress.XtraReports.Parameters.Parameter
Friend WithEvents pdFechaFinal As DevExpress.XtraReports.Parameters.Parameter
Friend WithEvents piConsolidaSucursal As DevExpress.XtraReports.Parameters.Parameter
Friend WithEvents piEnDolar As DevExpress.XtraReports.Parameters.Parameter
Friend WithEvents XrLabel27 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel37 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel38 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel39 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel40 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel41 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel42 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel43 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel44 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel45 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel47 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel46 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel49 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents XrLabel48 As DevExpress.XtraReports.UI.XRLabel
Friend WithEvents CalculatedField1 As DevExpress.XtraReports.UI.CalculatedField
End Class
| Solutions4U-NI/CDTSA | Facturacion/Facturacion/Reporte/rptAnalisisVencimiento.Designer.vb | Visual Basic | gpl-3.0 | 70,535 |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('dashboard/index',['page'=>'Dashboard','breadcrumbs'=>['dashboard/'=>'/home']]);
}
}
| wellingtonfds/cms | app/Http/Controllers/HomeController.php | PHP | gpl-3.0 | 524 |
{# The template expects one input parameter: `active`, which determines what link we are currently at #}
{% load i18n %}
<div class="economy__leftmenu">
<a class="economy__leftbutton resetlink {% if filter is None %}active{% endif %}"
href="{% url 'economy_soci_sessions' %}">{% trans 'X-lists' %}</a>
<a class="economy__leftbutton resetlink {% if filter == 'open' %}active{% endif %}"
href="{% url 'economy_soci_sessions' %}?filter=open">{% trans 'Open' %}</a>
{% if perms.economy.add_socisession %}
<a class="economy__leftbutton resetlink {% if filter == 'closed' %}active{% endif %}"
href="{% url 'economy_soci_sessions' %}?filter=closed">{% trans 'Closed' %}</a>
{% endif %}
</div> | KSG-IT/ksg-nett | economy/templates/economy/economy_lefmenu.html | HTML | gpl-3.0 | 734 |
const gal=[//731-62
'1@001/b4avsq1y2i',
'1@002/50uvpeo7tb',
'1@002/0ypu4wgjxm',
'1@002/b61d80e9pf',
'1@002/f1kb57t4ul',
'1@002/swq38v49nz',
'1@002/zeak367fw1',
'1@003/nx1ld4j9pe',
'1@003/yh0ub5rank',
'1@004/j29uftobmh',
'1@005/0asu1qo75n',
'1@005/4c7bn1q5mx',
'1@005/le3vrzbwfs',
'1@006/ek0tq9wvny',
'1@006/ax21m8tjos',
'1@006/w2e3104dp6',
'1@007/bsukxlv9j7',
'1@007/w5cpl0uvy6',
'1@007/l04q3wrucj',
'2@007/s2hr6jv7nc',
'2@009/31yrxp8waj',
'2@009/8josfrbgwi',
'2@009/rt4jie1fg8',
'2@009/p0va85n4gf',
'2@010/i9thzxn50q',
'3@010/a6w84ltj02',
'3@010/mfyevin3so',
'3@010/wdy5qzflnv',
'3@011/06wim8bjdp',
'3@011/avtd46k9cx',
'3@011/80915y2exz',
'3@011/vkt4dalwhb',
'3@011/znudscat9h',
'3@012/18xg4h9s3i',
'3@012/120sub86vt',
'3@012/5gxj7u0om8',
'3@012/95gzec2rsm',
'3@012/dihoerqp40',
'3@012/nif7secp8l',
'3@012/q8awn1iplo',
'3@012/ubzfcjte63',
'3@013/b9atnq1les',
'3@013/zof4tprh73',
'3@013/lvdyctgefs',
'4@013/c7fgqbsxkn',
'4@013/ci9vg76yj5',
'4@013/y3v8tjreas',
'4@014/75krn9ifbp',
'4@014/9tf7n5iexy',
'4@014/boz3y1wauf',
'4@014/ihqxma938n',
'4@014/suxj4yv5w6',
'4@014/o19tbsqjxe',
'4@014/wy8tx24g0c',
'4@015/302u7cs5nx',
'4@015/4bo9c8053u',
'4@015/8clxnh6eao',
'4@015/hbi1d9grwz',
'4@015/w8vmtnod7z',
'5@016/0yeinjua6h',
'5@016/rgpcwv4nym',
'5@016/scxjm7ofar']; | Klanly/klanly.github.io | imh/az60.js | JavaScript | gpl-3.0 | 1,322 |
//
// semaphore.cpp
//
// Circle - A C++ bare metal environment for Raspberry Pi
// Copyright (C) 2021 R. Stange <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#include <circle/sched/semaphore.h>
#include <circle/atomic.h>
#include <assert.h>
CSemaphore::CSemaphore (unsigned nInitialCount)
: m_nCount (nInitialCount),
m_Event (TRUE)
{
assert (m_nCount > 0);
}
CSemaphore::~CSemaphore (void)
{
assert (m_nCount > 0);
}
unsigned CSemaphore::GetState (void) const
{
return AtomicGet (&m_nCount);
}
void CSemaphore::Down (void)
{
while (AtomicGet (&m_nCount) == 0)
{
m_Event.Wait ();
}
if (AtomicDecrement (&m_nCount) == 0)
{
assert (m_Event.GetState ());
m_Event.Clear ();
}
}
void CSemaphore::Up (void)
{
if (AtomicIncrement (&m_nCount) == 1)
{
assert (!m_Event.GetState ());
m_Event.Set ();
}
#if NDEBUG
else
{
assert (m_Event.GetState ());
}
#endif
}
boolean CSemaphore::TryDown (void)
{
if (AtomicGet (&m_nCount) == 0)
{
return FALSE;
}
if (AtomicDecrement (&m_nCount) == 0)
{
assert (m_Event.GetState ());
m_Event.Clear ();
}
return TRUE;
}
| rsta2/circle | lib/sched/semaphore.cpp | C++ | gpl-3.0 | 1,721 |
import numpy as np
from scipy import sparse
from scipy.interpolate import interp1d
class calibration(object):
'''
some useful tools for manual calibration
'''
def normalize_zdata(self,z_data,cal_z_data):
return z_data/cal_z_data
def normalize_amplitude(self,z_data,cal_ampdata):
return z_data/cal_ampdata
def normalize_phase(self,z_data,cal_phase):
return z_data*np.exp(-1j*cal_phase)
def normalize_by_func(self,f_data,z_data,func):
return z_data/func(f_data)
def _baseline_als(self,y, lam, p, niter=10):
'''
see http://zanran_storage.s3.amazonaws.com/www.science.uva.nl/ContentPages/443199618.pdf
"Asymmetric Least Squares Smoothing" by P. Eilers and H. Boelens in 2005.
http://stackoverflow.com/questions/29156532/python-baseline-correction-library
"There are two parameters: p for asymmetry and lambda for smoothness. Both have to be
tuned to the data at hand. We found that generally 0.001<=p<=0.1 is a good choice
(for a trace with positive peaks) and 10e2<=lambda<=10e9, but exceptions may occur."
'''
L = len(y)
D = sparse.csc_matrix(np.diff(np.eye(L), 2))
w = np.ones(L)
for i in range(niter):
W = sparse.spdiags(w, 0, L, L)
Z = W + lam * D.dot(D.transpose())
z = sparse.linalg.spsolve(Z, w*y)
w = p * (y > z) + (1-p) * (y < z)
return z
def fit_baseline_amp(self,z_data,lam,p,niter=10):
'''
for this to work, you need to analyze a large part of the baseline
tune lam and p until you get the desired result
'''
return self._baseline_als(np.absolute(z_data),lam,p,niter=niter)
def baseline_func_amp(self,z_data,f_data,lam,p,niter=10):
'''
for this to work, you need to analyze a large part of the baseline
tune lam and p until you get the desired result
returns the baseline as a function
the points in between the datapoints are computed by cubic interpolation
'''
return interp1d(f_data, self._baseline_als(np.absolute(z_data),lam,p,niter=niter), kind='cubic')
def baseline_func_phase(self,z_data,f_data,lam,p,niter=10):
'''
for this to work, you need to analyze a large part of the baseline
tune lam and p until you get the desired result
returns the baseline as a function
the points in between the datapoints are computed by cubic interpolation
'''
return interp1d(f_data, self._baseline_als(np.angle(z_data),lam,p,niter=niter), kind='cubic')
def fit_baseline_phase(self,z_data,lam,p,niter=10):
'''
for this to work, you need to analyze a large part of the baseline
tune lam and p until you get the desired result
'''
return self._baseline_als(np.angle(z_data),lam,p,niter=niter)
def GUIbaselinefit(self):
'''
A GUI to help you fit the baseline
'''
self.__lam = 1e6
self.__p = 0.9
niter = 10
self.__baseline = self._baseline_als(np.absolute(self.z_data_raw),self.__lam,self.__p,niter=niter)
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
fig, (ax0,ax1) = plt.subplots(nrows=2)
plt.suptitle('Use the sliders to make the green curve match the baseline.')
plt.subplots_adjust(left=0.25, bottom=0.25)
l0, = ax0.plot(np.absolute(self.z_data_raw))
l0b, = ax0.plot(np.absolute(self.__baseline))
l1, = ax1.plot(np.absolute(self.z_data_raw/self.__baseline))
ax0.set_ylabel('amp, rawdata vs. baseline')
ax1.set_ylabel('amp, corrected')
axcolor = 'lightgoldenrodyellow'
axSmooth = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
axAsym = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
axbcorr = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor)
sSmooth = Slider(axSmooth, 'Smoothness', 0.1, 10., valinit=np.log10(self.__lam),valfmt='1E%f')
sAsym = Slider(axAsym, 'Asymmetry', 1e-4,0.99999, valinit=self.__p,valfmt='%f')
sbcorr = Slider(axbcorr, 'vertical shift',0.7,1.1,valinit=1.)
def update(val):
self.__lam = 10**sSmooth.val
self.__p = sAsym.val
self.__baseline = sbcorr.val*self._baseline_als(np.absolute(self.z_data_raw),self.__lam,self.__p,niter=niter)
l0.set_ydata(np.absolute(self.z_data_raw))
l0b.set_ydata(np.absolute(self.__baseline))
l1.set_ydata(np.absolute(self.z_data_raw/self.__baseline))
fig.canvas.draw_idle()
sSmooth.on_changed(update)
sAsym.on_changed(update)
sbcorr.on_changed(update)
plt.show()
self.z_data_raw /= self.__baseline
plt.close()
| vdrhtc/Measurement-automation | resonator_tools/resonator_tools/calibration.py | Python | gpl-3.0 | 4,324 |
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#ifndef RUBBERBANDSELECTIONMANIPULATOR_H
#define RUBBERBANDSELECTIONMANIPULATOR_H
#include "liveselectionrectangle.h"
#include <QPointF>
QT_FORWARD_DECLARE_CLASS(QGraphicsItem)
namespace QmlJSDebugger {
class QDeclarativeViewInspector;
class LiveRubberBandSelectionManipulator
{
public:
enum SelectionType {
ReplaceSelection,
AddToSelection,
RemoveFromSelection
};
LiveRubberBandSelectionManipulator(QGraphicsObject *layerItem,
QDeclarativeViewInspector *editorView);
void setItems(const QList<QGraphicsItem*> &itemList);
void begin(const QPointF& beginPoint);
void update(const QPointF& updatePoint);
void end();
void clear();
void select(SelectionType selectionType);
QPointF beginPoint() const;
bool isActive() const;
protected:
QGraphicsItem *topFormEditorItem(const QList<QGraphicsItem*> &itemList);
private:
QList<QGraphicsItem*> m_itemList;
QList<QGraphicsItem*> m_oldSelectionList;
LiveSelectionRectangle m_selectionRectangleElement;
QPointF m_beginPoint;
QDeclarativeViewInspector *m_editorView;
QGraphicsItem *m_beginFormEditorItem;
bool m_isActive;
};
}
#endif // RUBBERBANDSELECTIONMANIPULATOR_H
| forio/julia-studio | share/julia-studio/qml/qmljsdebugger/editor/liverubberbandselectionmanipulator.h | C | gpl-3.0 | 2,719 |
QUnit.test( "testGetIbanCheckDigits", function( assert ) {
assert.equal(getIBANCheckDigits( 'GB00WEST12345698765432' ), '82', 'Get check digits of an IBAN' );
assert.equal(getIBANCheckDigits( '1234567890' ), '', 'If string isn\'t an IBAN, returns empty' );
assert.equal(getIBANCheckDigits( '' ), '', 'If string is empty, returns empty' );
} );
QUnit.test( "testGetGlobalIdentifier", function( assert ) {
assert.equal(getGlobalIdentifier( 'G28667152', 'ES', '' ), 'ES55000G28667152', 'Obtain a global Id' );
} );
QUnit.test( "testReplaceCharactersNotInPattern", function( assert ) {
assert.equal(replaceCharactersNotInPattern(
'ABC123-?:',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
'0' ), 'ABC123000', 'Remove unwanted characters' );
assert.equal(replaceCharactersNotInPattern(
'12345',
'0123456789',
'0' ), '12345', 'If the string didn\'t have unwanted characters, returns it' );
} );
QUnit.test( "testReplaceLetterWithDigits", function( assert ) {
assert.equal(replaceLetterWithDigits( '510007547061BE00' ), '510007547061111400', 'Replaces letters with digits' );
assert.equal(replaceLetterWithDigits( '1234567890' ), '1234567890', 'If we only receive digits, we return them' );
assert.equal(replaceLetterWithDigits( '' ), '', 'If we receive empty, we return empty' );
} );
QUnit.test( "testGetAccountLength", function( assert ) {
assert.equal(getAccountLength( 'GB' ), 22, 'Returns tohe string th a SEPA country' );
assert.equal(getAccountLength( 'US' ), 0, 'If string isn\'t a SEPA country code, returns empty' );
assert.equal(getAccountLength( '' ), 0, 'If string is empty, returns empty' );
} );
QUnit.test( "testIsSepaCountry", function( assert ) {
assert.equal(isSepaCountry( 'ES' ) , 1, 'Detects SEPA countries' );
assert.equal(isSepaCountry( 'US' ), 0, 'Rejects non SEPA countries' );
assert.equal(isSepaCountry( '' ) , 0, 'If string is empty, returns empty' );
} );
QUnit.test( "testIsValidIban", function( assert ) {
assert.equal(isValidIBAN( 'GB82WEST12345698765432' ), 1, 'Accepts a good IBAN' );
assert.equal(isValidIBAN( 'GB00WEST12345698765432' ) , 0, 'Rejects a wrong IBAN' );
assert.equal(isValidIBAN( '' ), 0, 'Rejects empty strings' );
} );
| amnesty/dataquality | test/javascript/iban.js | JavaScript | gpl-3.0 | 2,366 |
<?php
namespace Aqua\SQL;
class Search
extends Select
{
/**
* @var array
*/
public $whereOptions = array();
/**
* @var array
*/
public $havingOptions = array();
/**
* @param array $where
* @param bool $merge
* @return static
*/
public function whereOptions(array $where, $merge = true)
{
if($merge) {
$this->whereOptions = array_merge($this->whereOptions, $where);
} else {
$this->whereOptions = $where;
}
return $this;
}
/**
* @param array $having
* @param bool $merge
* @return static
*/
public function havingOptions(array $having, $merge = true)
{
if($merge) {
$this->havingOptions = array_merge($this->havingOptions, $having);
} else {
$this->havingOptions = $having;
}
return $this;
}
/**
* @param mixed $options
* @param $values
* @param string $type
* @return string|null
*/
public function parseSearch(&$options, &$values, $type = null)
{
if($type === 'where') {
$columns = & $this->whereOptions;
} else {
$columns = & $this->havingOptions;
}
$query = '';
$i = 0;
if(!is_array($options)) {
return null;
} else {
foreach($options as $alias => &$value) {
if($i % 2) {
++$i;
if(is_string($value)) {
$v = strtoupper($value);
if($v === 'AND' || $v === 'OR') {
$query .= "$v ";
continue;
}
}
$query .= 'AND ';
}
if(is_int($alias)) {
if(is_string($value)) {
$query .= "$value ";
++$i;
} else if($q = $this->parseSearch($value, $values, $type)) {
$query .= "$q ";
++$i;
}
} else if(array_key_exists($alias, $columns)) {
if(!is_array($value)) {
$value = array( self::SEARCH_NATURAL, $value );
}
if($this->parseSearchFlags($value, $w, $values, $columns[$alias], $alias)) {
$query .= "$w ";
++$i;
}
}
}
}
if($i === 0) {
return null;
}
$query = preg_replace('/(^\s*(AND|OR)\s*)|(\s*(AND|OR)\s*$)/i', '', $query);
if($i === 1) {
return $query;
} else {
return "($query)";
}
}
public function parseOrder()
{
if(empty($this->order)) return '';
$order = array();
foreach($this->order as $column => $ord) {
if($ord === 'DESC' || $ord === 'ASC') {
if(array_key_exists($column, $this->columns)) {
$column = $this->columns[$column];
}
$order[] = "$column $ord";
} else {
if(array_key_exists($ord, $this->columns)) {
$ord = $this->columns[$ord];
}
$order[] = $ord;
}
}
if(empty($order)) return '';
else return 'ORDER BY ' . implode(', ', $order);
}
}
| AquaCore/AquaCore | lib/Aqua/SQL/Search.php | PHP | gpl-3.0 | 2,598 |
#pragma once
#include <nstd/Base.h>
class DataProtocol
{
public:
enum MessageType
{
errorResponse,
subscribeRequest,
subscribeResponse,
unsubscribeRequest,
unsubscribeResponse,
tradeRequest,
tradeResponse,
registerSourceRequest,
registerSourceResponse,
registerSinkRequest,
registerSinkResponse,
registeredSinkMessage,
tradeMessage,
channelRequest,
channelResponse,
timeRequest,
timeResponse,
timeMessage,
tickerMessage,
};
enum TradeFlag
{
replayedFlag = 0x01,
syncFlag = 0x02,
};
//enum ChannelType
//{
// tradeType,
// orderBookType,
//};
//
//enum ChannelFlag
//{
// onlineFlag = 0x01,
//};
#pragma pack(push, 4)
struct Header
{
uint32_t size; // including header
uint64_t source; // client id
uint64_t destination; // client id
uint16_t messageType; // MessageType
};
struct ErrorResponse
{
uint16_t messageType;
uint64_t channelId;
char_t errorMessage[128];
};
struct SubscribeRequest
{
char_t channel[33];
uint64_t maxAge;
uint64_t sinceId;
};
struct SubscribeResponse
{
char_t channel[33];
uint64_t channelId;
uint32_t flags;
};
struct UnsubscribeRequest
{
char_t channel[33];
};
struct UnsubscribeResponse
{
char_t channel[33];
uint64_t channelId;
};
struct RegisterSourceRequest
{
char_t channel[33];
};
struct RegisterSourceResponse
{
char_t channel[33];
uint64_t channelId;
};
struct RegisterSinkRequest
{
char_t channel[33];
};
struct RegisterSinkResponse
{
char_t channel[33];
uint64_t channelId;
};
struct TradeRequest
{
uint64_t maxAge;
uint64_t sinceId;
};
struct Trade
{
uint64_t id;
uint64_t time;
double price;
double amount;
uint32_t flags;
};
struct TradeMessage
{
uint64_t channelId;
Trade trade;
};
struct TimeMessage
{
uint64_t channelId;
uint64_t time;
};
struct TradeResponse
{
uint64_t channelId;
};
struct Channel
{
char_t channel[33];
//uint8_t type;
//uint32_t flags;
};
struct TimeResponse
{
uint64_t time;
};
struct Ticker
{
uint64_t time;
double bid;
double ask;
};
struct TickerMessage
{
uint64_t channelId;
Ticker ticker;
};
#pragma pack(pop)
};
| donpillou/MegucoData | Src/DataProtocol.h | C | gpl-3.0 | 2,403 |
---
title: "हरियाणा में सभी पार्टियां बहुमत से दूर"
layout: item
category: ["politics"]
date: 2019-10-24T11:42:44.692Z
image: 1571917364691hariyana-jjp-congress-bjp-hung-assembly.jpg
---
<p>नई दिल्ली: हरियाणा चुनाव के नतीजे काफी दिलचस्प हो गए हैं। अब तक के रुझान में भाजपा यहां आगे जरूर चल रही है, लेकिन बहुमत का आंकड़ा उससे दूर है। जबकि कांग्रेस ने जबरदस्त वापसी की है और जेजेपी भी बढ़िया प्रदर्शन कर रही है। ऐसे में बीजेपी को सरकार बनाने के लिए जेजेपी की जरूरत पड़ सकती है। लिहाजा हरियाणा के मुख्यमंत्री मनोहर लाल खट्टर को बीजेपी आलाकमान ने दिल्ली बुलाया है। वहीं कांग्रेस अध्यक्ष सोनिया गांधी ने भी भूपेन्द्र सिंह हुड्डा से बात की है। इस बीच जननायक जनता पार्टी (जेजेपी) की भूमिका काफी अहम हो गई है। जानकारी के मुताबिक प्रदेश के पूर्व मुख्यमंत्री प्रकाश सिंह बादल को भाजपा की ओर से जेजेपी से मध्यस्थता के लिए आगे किया जा सकता है। वहीं यह भी खबर है कि जेजपी ने सीएम पद की शर्त के साथ कांग्रेस को समर्थन का प्रस्ताव दिया है। हालांकि थोड़ी देर में तस्वीर साफ हो जाएगी कि हरियाणा की जनता ने किस पार्टी को प्रदेश की कमान सौंपने का निर्णय लिया है। राज्य में सोमवार को मतदान हुआ था।</p> | InstantKhabar/_source | _source/news/2019-10-24-hariyana-jjp-congress-bjp-hung-assembly.html | HTML | gpl-3.0 | 2,560 |
ALTER TABLE `b_iblock_element` ADD KEY `TIMESTAMP_X` (`TIMESTAMP_X`);
ALTER TABLE `b_iblock_element` ADD KEY `IBLOCK_ID` (`IBLOCK_ID`);
ALTER TABLE `b_iblock_element` ADD KEY `XML_ID` (`XML_ID`);
ALTER TABLE `b_iblock_element` ADD KEY `WF_PARENT_ELEMENT_ID` (`WF_PARENT_ELEMENT_ID`);
ALTER TABLE `b_iblock_element` ADD KEY `MODIFIED_BY`(`MODIFIED_BY`);
ALTER TABLE `b_iblock_element` ADD KEY `DATE_CREATE` (`DATE_CREATE`);
ALTER TABLE `b_iblock_element` ADD KEY `CREATED_BY` (`CREATED_BY`);
ALTER TABLE `b_iblock_element` ADD KEY `IBLOCK_SECTION_ID` (`IBLOCK_SECTION_ID`);
ALTER TABLE `b_iblock_element` ADD KEY `ACTIVE` (`ACTIVE`);
ALTER TABLE `b_iblock_element` ADD KEY `ACTIVE_FROM` (`ACTIVE_FROM`);
ALTER TABLE `b_iblock_element` ADD KEY `ACTIVE_TO` (`ACTIVE_TO`);
ALTER TABLE `b_iblock_element` ADD KEY `SORT` (`SORT`);
ALTER TABLE `b_iblock_element` ADD KEY `NAME` (`NAME`);
ALTER TABLE `b_iblock_element` ADD KEY `DETAIL_PICTURE` (`DETAIL_PICTURE`);
ALTER TABLE `b_iblock_element` ADD KEY `WF_STATUS_ID` (`WF_STATUS_ID`);
ALTER TABLE `b_iblock_element` ADD KEY `WF_NEW` (`WF_NEW`);
ALTER TABLE `b_iblock_element` ADD KEY `WF_LOCKED_BY` (`WF_LOCKED_BY`);
ALTER TABLE `b_iblock_element` ADD KEY `WF_DATE_LOCK` (`WF_DATE_LOCK`);
ALTER TABLE `b_iblock_element` ADD KEY `IN_SECTIONS` (`IN_SECTIONS`);
ALTER TABLE `b_iblock_element` ADD KEY `CODE` (`CODE`);
ALTER TABLE `b_iblock_element` ADD KEY `TAGS` (`TAGS`);
ALTER TABLE `b_iblock_element` ADD KEY `TMP_ID` (`TMP_ID`);
ALTER TABLE `b_iblock_element` ADD KEY `WF_LAST_HISTORY_ID` (`WF_LAST_HISTORY_ID`);
ALTER TABLE `b_iblock_element` ADD KEY `SHOW_COUNTER` (`SHOW_COUNTER`);
ALTER TABLE `b_iblock_element` ADD KEY `SHOW_COUNTER_START` (`SHOW_COUNTER_START`);
ALTER TABLE `b_iblock_element_iprop` ADD KEY `ELEMENT_ID` (`ELEMENT_ID`);
ALTER TABLE `b_iblock_element_iprop` ADD KEY `IPROP_ID` (`IPROP_ID`);
ALTER TABLE `b_iblock_property` ADD KEY `TIMESTAMP_X` (`TIMESTAMP_X`);
ALTER TABLE `b_iblock_property` ADD KEY `IBLOCK_ID` (`IBLOCK_ID`);
ALTER TABLE `b_iblock_property` ADD KEY `NAME` (`NAME`);
ALTER TABLE `b_iblock_property` ADD KEY `ACTIVE` (`ACTIVE`);
ALTER TABLE `b_iblock_property` ADD KEY `SORT` (`SORT`);
ALTER TABLE `b_iblock_property` ADD KEY `PROPERTY_TYPE` (`PROPERTY_TYPE`);
ALTER TABLE `b_iblock_property` ADD KEY `ROW_COUNT` (`ROW_COUNT`);
ALTER TABLE `b_iblock_property` ADD KEY `COL_COUNT` (`COL_COUNT`);
ALTER TABLE `b_iblock_property` ADD KEY `LIST_TYPE` (`LIST_TYPE`);
ALTER TABLE `b_iblock_property` ADD KEY `MULTIPLE` (`MULTIPLE`);
ALTER TABLE `b_iblock_property` ADD KEY `XML_ID` (`XML_ID`);
ALTER TABLE `b_iblock_property` ADD KEY `FILE_TYPE` (`FILE_TYPE`);
ALTER TABLE `b_iblock_property` ADD KEY `MULTIPLE_CNT` (`MULTIPLE_CNT`);
ALTER TABLE `b_iblock_property` ADD KEY `TMP_ID` (`TMP_ID`);
ALTER TABLE `b_iblock_property` ADD KEY `WITH_DESCRIPTION` (`WITH_DESCRIPTION`);
ALTER TABLE `b_iblock_property` ADD KEY `SEARCHABLE` (`SEARCHABLE`);
ALTER TABLE `b_iblock_property` ADD KEY `FILTRABLE` (`FILTRABLE`);
ALTER TABLE `b_iblock_property` ADD KEY `IS_REQUIRED` (`IS_REQUIRED`);
ALTER TABLE `b_iblock_property` ADD KEY `VERSION` (`VERSION`);
ALTER TABLE `b_iblock_property` ADD KEY `USER_TYPE` (`USER_TYPE`);
ALTER TABLE `b_iblock_property` ADD KEY `HINT` (`HINT`);
ALTER TABLE `b_iblock_property_enum` ADD KEY `PROPERTY_ID` (`PROPERTY_ID`);
ALTER TABLE `b_iblock_property_enum` ADD KEY `DEF` (`DEF`);
ALTER TABLE `b_iblock_property_enum` ADD KEY `SORT` (`SORT`);
ALTER TABLE `b_iblock_property_enum` ADD KEY `XML_ID` (`XML_ID`);
ALTER TABLE `b_iblock_iproperty` ADD KEY `IBLOCK_ID` (`IBLOCK_ID`);
ALTER TABLE `b_iblock_iproperty` ADD KEY `CODE` (`CODE`);
ALTER TABLE `b_iblock_iproperty` ADD KEY `ENTITY_TYPE` (`ENTITY_TYPE`);
ALTER TABLE `b_iblock_iproperty` ADD KEY `ENTITY_ID` (`ENTITY_ID`);
-- -------------------------------------------------
ALTER TABLE `b_iblock_section` ADD KEY `IBLOCK_ID` (`IBLOCK_ID`);
ALTER TABLE `b_iblock_section` ADD KEY `TIMESTAMP_X` (`TIMESTAMP_X`);
ALTER TABLE `b_iblock_section` ADD KEY `MODIFIED_BY` (`MODIFIED_BY`);
ALTER TABLE `b_iblock_section` ADD KEY `DATE_CREATE` (`DATE_CREATE`);
ALTER TABLE `b_iblock_section` ADD KEY `CREATED_BY` (`CREATED_BY`);
ALTER TABLE `b_iblock_section` ADD KEY `IBLOCK_SECTION_ID` (`IBLOCK_SECTION_ID`);
ALTER TABLE `b_iblock_section` ADD KEY `ACTIVE` (`ACTIVE`);
ALTER TABLE `b_iblock_section` ADD KEY `GLOBAL_ACTIVE` (`GLOBAL_ACTIVE`);
ALTER TABLE `b_iblock_section` ADD KEY `SORT` (`SORT`);
ALTER TABLE `b_iblock_section` ADD KEY `DEPTH_LEVEL` (`DEPTH_LEVEL`);
ALTER TABLE `b_iblock_section` ADD KEY `CODE` (`CODE`);
ALTER TABLE `b_iblock_section` ADD KEY `XML_ID` (`XML_ID`);
ALTER TABLE `b_iblock_section` ADD KEY `TMP_ID` (`TMP_ID`);
ALTER TABLE `b_iblock_section` ADD KEY `SOCNET_GROUP_ID` (`SOCNET_GROUP_ID`);
ALTER TABLE `b_iblock_section_element` ADD KEY `IBLOCK_SECTION_ID` (`IBLOCK_SECTION_ID`);
ALTER TABLE `b_iblock_section_element` ADD KEY `ADDITIONAL_PROPERTY_ID` (`ADDITIONAL_PROPERTY_ID`);
ALTER TABLE `b_iblock_section_property` ADD KEY `IBLOCK_ID` (`IBLOCK_ID`);
ALTER TABLE `b_iblock_section_property` ADD KEY `DISPLAY_TYPE` (`DISPLAY_TYPE`);
ALTER TABLE `b_iblock_section_property` ADD KEY `SMART_FILTER` (`SMART_FILTER`);
ALTER TABLE `b_iblock_section_property` ADD KEY `DISPLAY_EXPANDED` (`DISPLAY_EXPANDED`);
ALTER TABLE `b_iblock_section_right` ADD KEY `IBLOCK_ID` (`IBLOCK_ID`);
ALTER TABLE `b_iblock_section_right` ADD KEY `SECTION_ID` (`SECTION_ID`);
ALTER TABLE `b_iblock_section_right` ADD KEY `RIGHT_ID` (`RIGHT_ID`);
ALTER TABLE `b_iblock_section_right` ADD KEY `IS_INHERITED` (`IS_INHERITED`);
ALTER TABLE `b_iblock_section_iprop` ADD KEY `SECTION_ID` (`SECTION_ID`);
ALTER TABLE `b_option` ADD KEY `MODULE_ID` (`MODULE_ID`);
ALTER TABLE `b_option` ADD KEY `SITE_ID` (`SITE_ID`);
ALTER TABLE `b_iblock_fields` ADD KEY `IBLOCK_ID` (`IBLOCK_ID`);
ALTER TABLE `b_iblock_fields` ADD KEY `FIELD_ID` (`FIELD_ID`);
ALTER TABLE `b_iblock_fields` ADD KEY `IS_REQUIRED` (`IS_REQUIRED`);
ALTER TABLE `b_user` ADD KEY `LOGIN` (`LOGIN`);
ALTER TABLE `b_user` ADD KEY `ACTIVE` (`ACTIVE`);
ALTER TABLE `b_user` ADD KEY `LID` (`LID`);
ALTER TABLE `b_user` ADD KEY `DATE_REGISTER` (`DATE_REGISTER`);
ALTER TABLE `b_user` ADD KEY `TIMESTAMP_X` (`TIMESTAMP_X`);
| active-citizen/shop.1c | www/local/.migrations/migs/sql/optimize_patch.sql | SQL | gpl-3.0 | 6,255 |
/*!
* \file db_mysql_list_entities_report_sql.c
* \brief Returns MYSQL SQL query to create list entities report.
* \author Paul Griffiths
* \copyright Copyright 2014 Paul Griffiths. Distributed under the terms
* of the GNU General Public License. <http://www.gnu.org/licenses/>
*/
const char * db_list_entities_report_sql(void) {
static const char * query =
"SELECT"
" id AS 'ID',"
" shortname AS 'Short',"
" name AS 'Entity Name',"
" currency AS 'Curr.',"
" parent AS 'Parent'"
" FROM entities"
" ORDER BY id";
return query;
}
| paulgriffiths/general_ledger | lib/database/mysql/db_mysql_list_entities_report_sql.c | C | gpl-3.0 | 652 |
/*
* SPDX-License-Identifier: GPL-3.0
*
*
* (J)ava (M)iscellaneous (U)tilities (L)ibrary
*
* JMUL is a central repository for utilities which are used in my
* other public and private repositories.
*
* Copyright (C) 2013 Kristian Kutin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* e-mail: [email protected]
*/
/*
* This section contains meta informations.
*
* $Id$
*/
package jmul.transformation.xml.rules.xml2object;
import jmul.misc.id.ID;
import jmul.misc.id.IntegerID;
import jmul.reflection.classes.ClassDefinition;
import jmul.reflection.classes.ClassHelper;
import jmul.string.TextHelper;
import jmul.transformation.TransformationException;
import jmul.transformation.TransformationParameters;
import jmul.transformation.TransformationRuleBase;
import jmul.transformation.xml.cache.Xml2ObjectCache;
import static jmul.transformation.xml.rules.PersistenceMarkups.ID_ATTRIBUTE;
import static jmul.transformation.xml.rules.PersistenceMarkups.OBJECT_ELEMENT;
import static jmul.transformation.xml.rules.PersistenceMarkups.TYPE_ATTRIBUTE;
import static jmul.transformation.xml.rules.PersistenceMarkups.VALUE_ATTRIBUTE;
import static jmul.transformation.xml.rules.TransformationConstants.OBJECT_CACHE;
import jmul.xml.XmlParserHelper;
import org.w3c.dom.Node;
/**
* An implementation of a transformation rule.
*
* @author Kristian Kutin
*/
public class Xml2ClassRule extends TransformationRuleBase {
/**
* A class name.
*/
private static final String EXPECTED_TYPE_NAME = Class.class.getName();
/**
* Constructs a transformation rule.
*
* @param anOrigin
* a description of the transformation origin
* @param aDestination
* a description of the transformation destination
* @param aPriority
* a rule priority
*/
public Xml2ClassRule(String anOrigin, String aDestination, int aPriority) {
super(anOrigin, aDestination, aPriority);
}
/**
* The method determines if this rule can be applied to the specified
* object.
*
* @param someParameters
* some transformation parameters, including the object which is to
* be transformed
*
* @return <code>true</code> if the rule is applicable, else
* <code>false</code>
*/
@Override
public boolean isApplicable(TransformationParameters someParameters) {
return RuleHelper.isApplicable(someParameters, EXPECTED_TYPE_NAME);
}
/**
* The method performs the actual transformation.
*
* @param someParameters
* some transformation parameters, including the object which is to
* be transformed
*
* @return the transformed object
*/
@Override
public Object transform(TransformationParameters someParameters) {
// Check some plausibilites first.
if (!someParameters.containsPrerequisite(OBJECT_CACHE)) {
String message =
TextHelper.concatenateStrings("Prerequisites for the transformation are missing (", OBJECT_CACHE, ")!");
throw new TransformationException(message);
}
Object target = someParameters.getObject();
Node objectElement = (Node) target;
XmlParserHelper.assertMatchesXmlElement(objectElement, OBJECT_ELEMENT);
XmlParserHelper.assertExistsXmlAttribute(objectElement, ID_ATTRIBUTE);
XmlParserHelper.assertExistsXmlAttribute(objectElement, TYPE_ATTRIBUTE);
XmlParserHelper.assertExistsXmlAttribute(objectElement, VALUE_ATTRIBUTE);
// Get the required informations.
Xml2ObjectCache objectCache = (Xml2ObjectCache) someParameters.getPrerequisite(OBJECT_CACHE);
String idString = XmlParserHelper.getXmlAttributeValue(objectElement, ID_ATTRIBUTE);
String typeString = XmlParserHelper.getXmlAttributeValue(objectElement, TYPE_ATTRIBUTE);
String valueString = XmlParserHelper.getXmlAttributeValue(objectElement, VALUE_ATTRIBUTE);
ID id = new IntegerID(idString);
ClassDefinition type = null;
try {
type = ClassHelper.getClass(typeString);
} catch (ClassNotFoundException e) {
String message = TextHelper.concatenateStrings("An unknown class was specified (", typeString, ")!");
throw new TransformationException(message, e);
}
Class clazz = null;
try {
ClassDefinition definition = ClassHelper.getClass(valueString);
clazz = definition.getType();
} catch (ClassNotFoundException e) {
String message = TextHelper.concatenateStrings("An unknown class was specified (", valueString, ")!");
throw new TransformationException(message, e);
}
// Instantiate and initialize the specified object
objectCache.addObject(id, clazz, type.getType());
return clazz;
}
}
| gammalgris/jmul | Utilities/Transformation-XML/src/jmul/transformation/xml/rules/xml2object/Xml2ClassRule.java | Java | gpl-3.0 | 5,570 |
Bitrix 16.5 Business Demo = bf14f0c5bad016e66d0ed2d224b15630
| gohdan/DFC | known_files/hashes/bitrix/modules/main/install/js/main/amcharts/3.11/lang/hr.min.js | JavaScript | gpl-3.0 | 61 |
/*--[litinternal.h]------------------------------------------------------------
| Copyright (C) 2002 Dan A. Jackson
|
| This file is part of the "openclit" library for processing .LIT files.
|
| "Openclit" is free software; you can redistribute it and/or modify
| it under the terms of the GNU General Public License as published by
| the Free Software Foundation; either version 2 of the License, or
| (at your option) any later version.
|
| This program is distributed in the hope that it will be useful,
| but WITHOUT ANY WARRANTY; without even the implied warranty of
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
| GNU General Public License for more details.
|
| You should have received a copy of the GNU General Public License
| along with this program; if not, write to the Free Software
| Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
|
| The GNU General Public License may also be available at the following
| URL: http://www.gnu.org/licenses/gpl.html
*/
/*
| This file contains definitions for internal routines and structures which
| the LIT library doesn't wish to expose to the world at large
*/
#ifndef LITINTERNAL_H
#define LITINTERNAL_H
typedef struct dir_type {
U8 * entry_ptr;
U32 entry_size;
U32 entry_last_chunk;
U8 * count_ptr;
U32 count_size;
U32 count_last_chunk;
int num_entries;
int num_counts;
U32 entry_aoli_idx;
U32 total_content_size;
} dir_type;
int lit_i_read_directory(lit_file * litfile, U8 * piece, int piece_size);
int lit_i_make_directories(lit_file * litfile, dir_type * dirtype);
int lit_i_read_headers(lit_file * litfile);
int lit_i_write_headers(lit_file * litfile);
int lit_i_read_secondary_header(lit_file * litfile, U8 * hdr, int size);
int lit_i_cache_section(lit_file * litfile, section_type * pSection );
int lit_i_read_sections(lit_file * litfile );
void lit_i_free_dir_type(dir_type * dirtype);
int lit_i_encrypt_section(lit_file *,char *, U8 * new_key);
int lit_i_encrypt(U8 * ptr, int size, U8 * new_key);
/*
| This routine will check for the presence of DRM and initialize
| the DRM level and bookkey */
extern int lit_i_read_drm(lit_file *);
/*
| This routine will do the decryption with the bookkey, kept off here
| to get the non-DRM path pure */
extern int lit_i_decrypt(lit_file *, U8 * data_pointer, int size);
/*
| Utility routines...
*/
char * lit_i_strmerge(const char * first, ...);
U8 * lit_i_read_utf8_string(U8 * p, int remaining, int * size);
int lit_i_utf8_len_to_bytes(U8 * src, int lenSrc, int sizeSrc);
#endif
| Camano/convertlit | lib/litinternal.h | C | gpl-3.0 | 2,631 |
## mostly copied from: http://norvig.com/spell-correct.html
import sys, random
import re, collections, time
TXT_FILE='';
BUF_DIR='';
NWORDS=None;
def words(text): return re.findall('[a-z]+', text)
def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
return model
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def edits1(word):
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [a + b[1:] for a, b in splits if b]
transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b]
inserts = [a + c + b for a, b in splits for c in alphabet]
return set(deletes + transposes + replaces + inserts)
def known_edits2(word):
return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)
def known(words): return set(w for w in words if w in NWORDS)
def correct(word):
candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word]
return max(candidates, key=NWORDS.get)
#######################################################################################
if __name__ == '__main__':
TXT_FILE = sys.argv[1]
t0 = time.clock()
o_words = words(file(TXT_FILE).read())
NWORDS = train(o_words)
#print time.clock() - t0, " seconds build time"
#print "dictionary size: %d" %len(NWORDS)
et1 = time.clock() - t0
t_count = 10
rl = o_words[0:t_count] #random.sample(o_words, t_count)
orl = [''.join(random.sample(word, len(word))) for word in o_words]
t1 = time.clock()
r_count = 10
for i in range(0, r_count):
for w1, w2 in zip(rl, orl):
correct(w1); correct(w2)
et2 = (time.clock() - t1)/t_count/r_count/2
print '%d\t%f\t%f' %(len(NWORDS), et1, et2)
#######################################################################################
print 'Done'
| xulesc/spellchecker | impl1.py | Python | gpl-3.0 | 1,898 |
<B_lastforums><div id="derniers-forums" class="listagebloc">
<h2><:derniers_forums:></h2>
<ul class="listageconteneur">
<BOUCLE_lastforums(FORUMS){!par date}{0,#ENV{parametre}}{plat}>
<li>
<h4 class="listagetitre"><a href="#URL_ARTICLE#forums">#TITRE</a></h4>
<div class="listageinfo">[(#DATE|affdate)][, <:par_auteur:> <a href="mailto:#EMAIL">(#NOM)</a>]</div>
<p class="listagetexte">[(#TEXTE|couper{220})]</p>
</li>
</BOUCLE_lastforums>
</ul>
</div></B_lastforums> | umibulle/romette | plugins/magusine-portage2/squelettes/blocs/sommaire/derniers-forums.html | HTML | gpl-3.0 | 467 |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>sensekey</title>
<link rel="stylesheet" type="text/css" href="csound.css" />
<link rel="stylesheet" type="text/css" href="syntax-highlighting.css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1" />
<link rel="home" href="index.html" title="The Canonical Csound Reference Manual" />
<link rel="up" href="OpcodesTop.html" title="Orchestra Opcodes and Operators" />
<link rel="prev" href="sense.html" title="sense" />
<link rel="next" href="serialBegin.html" title="serialBegin" />
</head>
<body>
<div class="navheader">
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">sensekey</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="sense.html">Prev</a> </td>
<th width="60%" align="center">Orchestra Opcodes and Operators</th>
<td width="20%" align="right"> <a accesskey="n" href="serialBegin.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="refentry">
<a id="sensekey"></a>
<div class="titlepage"></div>
<a id="IndexSensekey" class="indexterm"></a>
<div class="refnamediv">
<h2>
<span class="refentrytitle">sensekey</span>
</h2>
<p>sensekey —
Returns the ASCII code of a key that has been pressed.
</p>
</div>
<div class="refsect1">
<a id="idm431456309440"></a>
<h2>Description</h2>
<p>
Returns the ASCII code of a key that has been pressed, or -1 if no key has been pressed.
</p>
</div>
<div class="refsect1">
<a id="idm431456308048"></a>
<h2>Syntax</h2>
<pre class="synopsis">kres[, kkeydown] <span class="command"><strong>sensekey</strong></span></pre>
</div>
<div class="refsect1">
<a id="idm431456306080"></a>
<h2>Performance</h2>
<p>
<span class="emphasis"><em>kres</em></span> - returns the ASCII value of a key which is pressed or released.
</p>
<p>
<span class="emphasis"><em>kkeydown</em></span> - returns 1 if the key was pressed, 0 if it was released or if there is no key event.
</p>
<p>
<span class="emphasis"><em>kres</em></span> can be used to read keyboard events from stdin and returns the ASCII value of any key that is pressed or released, or it returns -1 when there is no keyboard activity. The value of <span class="emphasis"><em>kkeydown</em></span> is 1 when a key was pressed, or 0 otherwise. This behavior is emulated by default, so a key release is generated immediately after every key press. To have full functionality, FLTK can be used to capture keyboard events. <a class="link" href="FLpanel.html" title="FLpanel"><em class="citetitle">FLpanel</em></a> can be used to capture keyboard events and send them to the sensekey opcode, by adding an additional optional argument. See <a class="link" href="FLpanel.html" title="FLpanel"><em class="citetitle">FLpanel</em></a> for more information.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<table border="0" summary="Note: Note">
<tr>
<td rowspan="2" align="center" valign="top" width="25">
<img alt="[Note]" src="images/note.png" />
</td>
<th align="left">Note</th>
</tr>
<tr>
<td align="left" valign="top">
<p>
This opcode can also be written as <a class="link" href="sense.html" title="sense"><em class="citetitle">sense</em></a>.
</p>
</td>
</tr>
</table>
</div>
</div>
<div class="refsect1">
<a id="idm431456297728"></a>
<h2>Examples</h2>
<p>
Here is an example of the sensekey opcode. It uses the file <a class="ulink" href="examples/sensekey.csd" target="_top"><em class="citetitle">sensekey.csd</em></a>.
</p>
<div class="example">
<a id="idm431456295920"></a>
<p class="title">
<strong>Example 884. Example of the sensekey opcode.</strong>
</p>
<div class="example-contents">
<p>See the sections <a class="link" href="UsingRealTime.html" title="Real-Time Audio"><em class="citetitle">Real-time Audio</em></a> and <a class="link" href="CommandFlags.html" title="Csound command line"><em class="citetitle">Command Line Flags</em></a> for more information on using command line flags.</p>
<div class="refsect1">
<a id="idm431823003600"></a>
<pre class="programlisting">
<span class="nt"><CsoundSynthesizer></span>
<span class="nt"><CsOptions></span>
<span class="c1">; Select audio/midi flags here according to platform</span>
<span class="c1">; Audio out Audio in</span>
-odac -iadc <span class="c1">;;;RT audio I/O</span>
<span class="c1">; For Non-realtime ouput leave only the line below:</span>
<span class="c1">; -o sensekey.wav -W ;;; for file output any platform</span>
<span class="nt"></CsOptions></span>
<span class="nt"><CsInstruments></span>
<span class="c1">; Initialize the global variables.</span>
<span class="vg">sr</span> <span class="o">=</span> <span class="mi">44100</span>
<span class="vg">kr</span> <span class="o">=</span> <span class="mi">4410</span>
<span class="vg">ksmps</span> <span class="o">=</span> <span class="mi">10</span>
<span class="vg">nchnls</span> <span class="o">=</span> <span class="mi">1</span>
<span class="c1">; Instrument #1.</span>
<span class="kd">instr</span> <span class="nf">1</span>
k<span class="n">1</span> <span class="nb">sensekey</span>
<span class="nb">printk2</span> k<span class="n">1</span>
<span class="kd">endin</span>
<span class="nt"></CsInstruments></span>
<span class="nt"><CsScore></span>
<span class="c1">; Play Instrument #1 for thirty seconds.</span>
<span class="nb">i</span> <span class="mi">1</span> <span class="mi">0</span> <span class="mi">30</span>
<span class="nb">e</span>
<span class="nt"></CsScore></span>
<span class="nt"></CsoundSynthesizer></span>
</pre>
</div>
</div>
</div>
<p><br class="example-break" />
Here is what the output should look like when the "q" button is pressed...
</p>
<pre class="screen">
q i1 113.00000
</pre>
<p>
</p>
<p>
Here is an example of the sensekey opcode in conjucntion with <a class="link" href="FLpanel.html" title="FLpanel"><em class="citetitle">FLpanel</em></a>. It uses the file <a class="ulink" href="examples/FLpanel-sensekey.csd" target="_top"><em class="citetitle">FLpanel-sensekey.csd</em></a>.
</p>
<div class="example">
<a id="idm431456289216"></a>
<p class="title">
<strong>Example 885. Example of the sensekey opcode using keyboard capture from an FLpanel.</strong>
</p>
<div class="example-contents">
<div class="refsect1">
<a id="idm431823457456"></a>
<pre class="programlisting">
<span class="nt"><CsoundSynthesizer></span>
<span class="nt"><CsOptions></span>
<span class="c1">; Select audio/midi flags here according to platform</span>
<span class="c1">; Audio out Audio in No messages</span>
-odac -iadc -d <span class="c1">;;;RT audio I/O</span>
<span class="c1">; For Non-realtime ouput leave only the line below:</span>
<span class="c1">; -o FLpanel-sensekey.wav -W ;;; for file output any platform</span>
<span class="nt"></CsOptions></span>
<span class="nt"><CsInstruments></span>
<span class="c1">; Example by Johnathan Murphy</span>
<span class="vg">sr</span> <span class="o">=</span> <span class="mi">44100</span>
<span class="vg">ksmps</span> <span class="o">=</span> <span class="mi">128</span>
<span class="vg">nchnls</span> <span class="o">=</span> <span class="mi">2</span>
<span class="c1">; ikbdcapture flag set to 1</span>
i<span class="n">key</span> <span class="nb">init</span> <span class="mi">1</span>
<span class="nb">FLpanel</span> <span class="s">"sensekey"</span><span class="p">,</span> <span class="mi">740</span><span class="p">,</span> <span class="mi">340</span><span class="p">,</span> <span class="mi">100</span><span class="p">,</span> <span class="mi">250</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> i<span class="n">key</span>
gk<span class="n">asc</span><span class="p">,</span> gi<span class="n">asc</span> <span class="nb">FLbutBank</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">16</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">700</span><span class="p">,</span> <span class="mi">300</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span>
<span class="nb">FLpanelEnd</span>
<span class="nb">FLrun</span>
<span class="kd">instr</span> <span class="nf">1</span>
k<span class="n">key</span> <span class="nb">sensekey</span>
k<span class="n">print</span> <span class="nb">changed</span> k<span class="n">key</span>
<span class="nb">FLsetVal</span> k<span class="n">print</span><span class="p">,</span> k<span class="n">key</span><span class="p">,</span> gi<span class="n">asc</span>
<span class="kd">endin</span>
<span class="nt"></CsInstruments></span>
<span class="nt"><CsScore></span>
<span class="nb">i</span><span class="mi">1</span> <span class="mi">0</span> <span class="mi">60</span>
<span class="nb">e</span>
<span class="nt"></CsScore></span>
<span class="nt"></CsoundSynthesizer></span>
</pre>
</div>
</div>
</div>
<p><br class="example-break" />
The lit button in the FLpanel window shows the last key pressed.
</p>
<p>
Here is a more complex example of the sensekey opcode in conjucntion with <a class="link" href="FLpanel.html" title="FLpanel"><em class="citetitle">FLpanel</em></a>. It uses the file <a class="ulink" href="examples/FLpanel-sensekey.csd" target="_top"><em class="citetitle">FLpanel-sensekey2.csd</em></a>.
</p>
<div class="example">
<a id="idm431456285456"></a>
<p class="title">
<strong>Example 886. Example of the sensekey opcode using keyboard capture from an FLpanel.</strong>
</p>
<div class="example-contents">
<div class="refsect1">
<a id="idm431823458336"></a>
<pre class="programlisting">
<span class="nt"><CsoundSynthesizer></span>
<span class="nt"><CsOptions></span>
<span class="c1">; Select audio/midi flags here according to platform</span>
<span class="c1">; Audio out Audio in No messages</span>
-odac <span class="c1">; -iadc -d ;;;RT audio I/O</span>
<span class="c1">; For Non-realtime ouput leave only the line below:</span>
<span class="c1">; -o FLpanel-sensekey2.wav -W ;;; for file output any platform</span>
<span class="nt"></CsOptions></span>
<span class="nt"><CsInstruments></span>
<span class="vg">sr</span> <span class="o">=</span> <span class="mi">48000</span>
<span class="vg">ksmps</span> <span class="o">=</span> <span class="mi">32</span>
<span class="vg">nchnls</span> <span class="o">=</span> <span class="mi">1</span>
<span class="c1">; Example by Istvan Varga</span>
<span class="c1">; if the FLTK opcodes are commented out, sensekey will read keyboard</span>
<span class="c1">; events from stdin</span>
<span class="nb">FLpanel</span> <span class="s">""</span><span class="p">,</span> <span class="mi">150</span><span class="p">,</span> <span class="mi">50</span><span class="p">,</span> <span class="mi">100</span><span class="p">,</span> <span class="mi">100</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span>
<span class="nb">FLlabel</span> <span class="mi">18</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span>
<span class="nb">FLgroup</span> <span class="s">"Keyboard Input"</span><span class="p">,</span> <span class="mi">150</span><span class="p">,</span> <span class="mi">50</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span>
<span class="nb">FLgroupEnd</span>
<span class="nb">FLpanelEnd</span>
<span class="nb">FLrun</span>
<span class="kd">instr</span> <span class="nf">1</span>
k<span class="n">trig1</span> <span class="nb">init</span> <span class="mi">1</span>
k<span class="n">trig2</span> <span class="nb">init</span> <span class="mi">1</span>
<span class="nl">nxtKey1</span><span class="p">:</span>
k<span class="n">1</span><span class="p">,</span> k<span class="n">2</span> <span class="nb">sensekey</span>
<span class="k">if</span> <span class="p">(</span>k<span class="n">1</span> <span class="o">!=</span> <span class="o">-</span><span class="mi">1</span> <span class="o">||</span> k<span class="n">2</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">)</span> <span class="k">then</span>
<span class="nb">printf</span> <span class="s">"Key code = </span><span class="si">%02X</span><span class="s">, state = </span><span class="si">%d</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> k<span class="n">trig1</span><span class="p">,</span> k<span class="n">1</span><span class="p">,</span> k<span class="n">2</span>
k<span class="n">trig1</span> <span class="o">=</span> <span class="mi">3</span> <span class="o">-</span> k<span class="n">trig1</span>
<span class="k">kgoto</span> <span class="nl">nxtKey1</span>
<span class="k">endif</span>
<span class="nl">nxtKey2</span><span class="p">:</span>
k<span class="n">3</span> <span class="nb">sensekey</span>
<span class="k">if</span> <span class="p">(</span>k<span class="n">3</span> <span class="o">!=</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="k">then</span>
<span class="nb">printf</span> <span class="s">"Character = '</span><span class="si">%c</span><span class="s">'</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> k<span class="n">trig2</span><span class="p">,</span> k<span class="n">3</span>
k<span class="n">trig2</span> <span class="o">=</span> <span class="mi">3</span> <span class="o">-</span> k<span class="n">trig2</span>
<span class="k">kgoto</span> <span class="nl">nxtKey2</span>
<span class="k">endif</span>
<span class="kd">endin</span>
<span class="nt"></CsInstruments></span>
<span class="nt"><CsScore></span>
<span class="nb">i</span> <span class="mi">1</span> <span class="mi">0</span> <span class="mi">3600</span>
<span class="nb">e</span>
<span class="nt"></CsScore></span>
<span class="nt"></CsoundSynthesizer></span>
</pre>
</div>
</div>
</div>
<p><br class="example-break" />
The console output will look something like:
</p>
<div class="literallayout">
<p><br />
new alloc for instr 1:<br />
Key code = 65, state = 1<br />
Character = 'e'<br />
Key code = 65, state = 0<br />
Key code = 72, state = 1<br />
Character = 'r'<br />
Key code = 72, state = 0<br />
Key code = 61, state = 1<br />
Character = 'a'<br />
Key code = 61, state = 0<br />
</p>
</div>
<p>
</p>
</div>
<div class="refsect1">
<a id="idm431456282496"></a>
<h2>See also</h2>
<p>
<a class="link" href="FLpanel.html" title="FLpanel"><em class="citetitle">FLpanel</em></a>,
<a class="link" href="FLkeyIn.html" title="FLkeyIn"><em class="citetitle">FLkeyIn</em></a>
</p>
</div>
<div class="refsect1">
<a id="idm431456279552"></a>
<h2>Credits</h2>
<p>
</p>
<table border="0" summary="Simple list" class="simplelist">
<tr>
<td>Author: John ffitch</td>
</tr>
<tr>
<td>University of Bath, Codemist. Ltd.</td>
</tr>
<tr>
<td>Bath, UK</td>
</tr>
<tr>
<td>October 2000</td>
</tr>
</table>
<p>
</p>
<p>Examples written by Kevin Conder, Johnathan Murphy and Istvan Varga.</p>
<p>New in Csound version 4.09. Renamed in Csound version 4.10.</p>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="sense.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="OpcodesTop.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="serialBegin.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">sense </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> serialBegin</td>
</tr>
</table>
</div>
</body>
</html>
| belangeo/cecilia4csound | Resources/html/sensekey.html | HTML | gpl-3.0 | 18,219 |
package com.baeldung.webflux;
import static java.time.LocalDateTime.now;
import static java.util.UUID.randomUUID;
import java.time.Duration;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketSession;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Component("EmployeeWebSocketHandler")
public class EmployeeWebSocketHandler implements WebSocketHandler {
ObjectMapper om = new ObjectMapper();
@Override
public Mono<Void> handle(WebSocketSession webSocketSession) {
Flux<String> employeeCreationEvent = Flux.generate(sink -> {
EmployeeCreationEvent event = new EmployeeCreationEvent(randomUUID().toString(), now().toString());
try {
sink.next(om.writeValueAsString(event));
} catch (JsonProcessingException e) {
sink.error(e);
}
});
return webSocketSession.send(employeeCreationEvent
.map(webSocketSession::textMessage)
.delayElements(Duration.ofSeconds(1)));
}
}
| Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/spring-5-reactive-security/src/main/java/com/baeldung/webflux/EmployeeWebSocketHandler.java | Java | gpl-3.0 | 1,272 |
/*****************************************************************************
The Dark Mod GPL Source Code
This file is part of the The Dark Mod Source Code, originally based
on the Doom 3 GPL Source Code as published in 2011.
The Dark Mod Source Code is free software: you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation, either version 3 of the License,
or (at your option) any later version. For details, see LICENSE.TXT.
Project: The Dark Mod (http://www.thedarkmod.com/)
$Revision: 6618 $ (Revision of last commit)
$Date: 2016-09-06 15:39:46 +0000 (Tue, 06 Sep 2016) $ (Date of last commit)
$Author: grayman $ (Author of last commit)
******************************************************************************/
#ifndef _MULTI_STATE_MOVER_H_
#define _MULTI_STATE_MOVER_H_
#include "MultiStateMoverPosition.h"
#include "MultiStateMoverButton.h"
/**
* greebo: A MultiState mover is an extension to the vanilla D3 movers.
*
* In contrast to the idElevator class, this multistate mover draws the floor
* information from the MultiStateMoverPosition entities which are targetted
* by this class.
*
* The MultiStateMover will start moving when it's triggered (e.g. by buttons),
* where the information where to go is contained on the triggering button.
*
* Furthermore, the MultiStateMover provides a public interface for AI to
* help them figuring out which buttons to use, where to go, etc.
*/
class CMultiStateMover :
public idMover
{
idList<MoverPositionInfo> positionInfo;
idVec3 forwardDirection;
// The lists of buttons, AI entities need them to get the elevator moving
idList< idEntityPtr<CMultiStateMoverButton> > fetchButtons;
idList< idEntityPtr<CMultiStateMoverButton> > rideButtons;
// grayman #3050 - to help reduce jostling on the elevator
bool masterAtRideButton; // is the master in position to push the ride button?
UserManager riderManager; // manage a list of riders (which is different than users)
public:
CLASS_PROTOTYPE( CMultiStateMover );
CMultiStateMover();
void Spawn();
void Save(idSaveGame *savefile) const;
void Restore(idRestoreGame *savefile);
void Activate(idEntity* activator);
// Returns the list of position infos, populates the list if none are assigned yet.
const idList<MoverPositionInfo>& GetPositionInfoList();
/**
* greebo: Returns TRUE if this mover is at the given position.
* Note: NULL arguments always return false.
*/
bool IsAtPosition(CMultiStateMoverPosition* position);
/**
* greebo: This is called by the MultiStateMoverButton class exclusively to
* register the button with this Mover, so that the mover knows which buttons
* can be used to get it moving.
*
* @button: The button entity
* @type: The "use type" of the entity, e.g. "fetch" or "ride"
*/
void RegisterButton(CMultiStateMoverButton* button, EMMButtonType type);
/**
* greebo: Returns the closest button entity for the given position and the given "use type".
*
* @toPosition: the position the elevator needs to go to (to be "fetched" to, to "ride" to).
* @fromPosition: the position the button needs to be accessed from (can be NULL for type == RIDE).
* @type: the desired type of button (fetch or ride)
* @riderOrg: the origin of the AI using the button (grayman #3029)
*
* @returns: NULL if nothing found.
*/
CMultiStateMoverButton* GetButton(CMultiStateMoverPosition* toPosition, CMultiStateMoverPosition* fromPosition, EMMButtonType type, idVec3 riderOrg); // grayman #3029
// grayman #3050 - for ride management
bool IsMasterAtRideButton();
void SetMasterAtRideButton(bool atButton);
inline UserManager& GetRiderManager()
{
return riderManager;
}
protected:
// override idMover's DoneMoving() to trigger targets
virtual void DoneMoving();
private:
// greebo: Controls the direction of targetted rotaters, depending on the given moveTargetPosition
void SetGearDirection(const idVec3& targetPos);
// Returns the index of the named position info or -1 if not found
int GetPositionInfoIndex(const idStr& name) const;
// Returns the index of the position info at the given position (using epsilon comparison)
int GetPositionInfoIndex(const idVec3& pos) const;
// Returns the positioninfo entity of the given location or NULL if no suitable position found
CMultiStateMoverPosition* GetPositionEntity(const idVec3& pos) const;
// Extracts all position entities from the targets
void FindPositionEntities();
void Event_Activate(idEntity* activator);
void Event_PostSpawn();
/**
* grayman #4370: "Override" the TeamBlocked event to detect collisions with the player.
*/
virtual void OnTeamBlocked(idEntity* blockedEntity, idEntity* blockingEntity);
};
#endif /* _MULTI_STATE_MOVER_H_ */
| Extant-1/ThieVR | game/MultiStateMover.h | C | gpl-3.0 | 4,866 |
describe SearchController, type: :controller do
it { is_expected.to route(:get, '/search').to(action: :basic) }
it { is_expected.to route(:get, '/search/entity').to(action: :entity_search) }
describe "GET #entity_search" do
login_user
let(:org) { build(:org) }
def search_service_double
instance_double('EntitySearchService').tap do |d|
d.instance_variable_set(:@search, [org])
end
end
it 'returns http status bad_request if missing param q' do
get :entity_search
expect(response).to have_http_status(:bad_request)
end
it "returns http success" do
allow(Entity).to receive(:search).with("@(name,aliases) name", any_args).and_return([org])
get :entity_search, params: { :q => 'name' }
expect(response).to have_http_status(:success)
end
it "hash includes url by default" do
allow(Entity).to receive(:search).with("@(name,aliases) name", any_args).and_return([org])
get :entity_search, params: { :q => 'name' }
expect(JSON.parse(response.body)[0]['url']).to include "/org/#{org.id}"
expect(JSON.parse(response.body)[0]).not_to have_key "is_parent"
end
it "hash can optionally include parent" do
allow(Entity).to receive(:search).with("@(name,aliases) name", any_args).and_return([org])
expect(org).to receive(:parent?).once.and_return(false)
get :entity_search, params: { :q => 'name', include_parent: true }
expect(JSON.parse(response.body)[0]['is_parent']).to eq false
end
end
end
| public-accountability/littlesis-rails | spec/controllers/search_controller_spec.rb | Ruby | gpl-3.0 | 1,540 |
<?php
namespace App\Model;
use PDO;
use Exception;
use App\Model;
use App\Config;
use App\Exceptions\ServerException;
use App\Exceptions\DatabaseInsertException;
class Account extends Model
{
public $id;
public $name;
public $email;
public $service;
public $password;
public $is_active;
public $imap_host;
public $imap_port;
public $smtp_host;
public $smtp_port;
public $imap_flags;
public $created_at;
public function getData()
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'service' => $this->service,
'password' => $this->password,
'is_active' => $this->is_active,
'imap_host' => $this->imap_host,
'imap_port' => $this->imap_port,
'smtp_host' => $this->smtp_host,
'smtp_port' => $this->smtp_port,
'imap_flags' => $this->imap_flags,
'created_at' => $this->created_at
];
}
public function getActive()
{
return $this->db()
->select()
->from('accounts')
->where('is_active', '=', 1)
->execute()
->fetchAll(PDO::FETCH_CLASS, get_class());
}
public function getFirstActive()
{
$active = $this->getActive();
return $active
? current($active)
: null;
}
public function getByEmail(string $email)
{
$account = $this->db()
->select()
->from('accounts')
->where('email', '=', $email)
->execute()
->fetchObject();
return $account
? new self($account)
: null;
}
public function fromAddress()
{
return $this->name
? sprintf('%s <%s>', $this->name, $this->email)
: $this->email;
}
public function hasFolders()
{
return (new Folder)->countByAccount($this->id) > 0;
}
/**
* Updates the account configuration.
*/
public function update(
string $email,
string $password,
string $name,
string $imapHost,
int $imapPort,
string $smtpHost,
int $smtpPort
) {
if (! $this->exists()) {
return false;
}
$updated = $this->db()
->update([
'name' => trim($name),
'email' => trim($email),
'password' => trim($password),
'imap_host' => trim($imapHost),
'imap_port' => trim($imapPort),
'smtp_host' => trim($smtpHost),
'smtp_port' => trim($smtpPort)
])
->table('accounts')
->where('id', '=', $this->id)
->execute();
return is_numeric($updated) ? $updated : false;
}
/**
* Creates a new account with the class data. This is done only
* after the IMAP credentials are tested to be working.
*
* @throws ServerException
*
* @return Account
*/
public function create()
{
// Exit if it already exists!
if ($this->exists()) {
return false;
}
$service = Config::getEmailService($this->email);
list($imapHost, $imapPort) = Config::getImapSettings($this->email);
if ($imapHost) {
$this->imap_host = $imapHost;
$this->imap_port = $imapPort;
}
$data = [
'is_active' => 1,
'service' => $service,
'name' => trim($this->name),
'email' => trim($this->email),
'password' => trim($this->password),
'imap_host' => trim($this->imap_host),
'imap_port' => trim($this->imap_port),
'smtp_host' => trim($this->smtp_host),
'smtp_port' => trim($this->smtp_port),
'created_at' => $this->utcDate()->format(DATE_DATABASE)
];
try {
// Start a transaction to prevent storing bad data
$this->db()->beginTransaction();
$newAccountId = $this->db()
->insert(array_keys($data))
->into('accounts')
->values(array_values($data))
->execute();
if (! $newAccountId) {
throw new DatabaseInsertException;
}
$this->db()->commit();
// Saved to the database
} catch (Exception $e) {
$this->db()->rollback();
throw new ServerException(
'Failed creating new account. '.$e->getMessage()
);
}
$this->id = $newAccountId;
return $this;
}
}
| mikegioia/libremail | webmail/src/Model/Account.php | PHP | gpl-3.0 | 4,773 |
package org.vaadin.addons.guice.server;
import org.vaadin.addons.guice.servlet.VGuiceApplicationServlet;
import com.google.inject.servlet.ServletModule;
/**
*
* @author Will Temperley
*
*/
public class ExampleGuiceServletModule extends ServletModule {
@Override
protected void configureServlets() {
serve("/*").with(VGuiceApplicationServlet.class);
}
} | 241180/Oryx | v-guice-example-master/src/main/java/org/vaadin/addons/guice/server/ExampleGuiceServletModule.java | Java | gpl-3.0 | 383 |
class Global_var_WeaponGUI
{
idd=-1;
movingenable=false;
class controls
{
class Global_var_WeaponGUI_Frame: RscFrame
{
idc = -1;
x = 0.365937 * safezoneW + safezoneX;
y = 0.379 * safezoneH + safezoneY;
w = 0.170156 * safezoneW;
h = 0.143 * safezoneH;
};
class Global_var_WeaponGUI_Background: Box
{
idc = -1;
x = 0.365937 * safezoneW + safezoneX;
y = 0.379 * safezoneH + safezoneY;
w = 0.170156 * safezoneW;
h = 0.143 * safezoneH;
};
class Global_var_WeaponGUI_Text: RscText
{
idc = -1;
text = "Waffenauswahl"; //--- ToDo: Localize;
x = 0.365937 * safezoneW + safezoneX;
y = 0.39 * safezoneH + safezoneY;
w = 0.0773437 * safezoneW;
h = 0.022 * safezoneH;
};
class Global_var_WeaponGUI_Combo: RscCombo
{
idc = 2100;
x = 0.371094 * safezoneW + safezoneX;
y = 0.445 * safezoneH + safezoneY;
w = 0.159844 * safezoneW;
h = 0.022 * safezoneH;
};
class Global_var_WeaponGUI_Button_OK: RscButton
{
idc = 2101;
text = "OK"; //--- ToDo: Localize;
x = 0.371094 * safezoneW + safezoneX;
y = 0.489 * safezoneH + safezoneY;
w = 0.0773437 * safezoneW;
h = 0.022 * safezoneH;
action = "(lbText [2100, lbCurSel 2100]) execVM ""Ammo\Dialog.sqf"";closeDialog 1;";
};
class Global_var_WeaponGUI_Button_Cancel: RscButton
{
idc = 2102;
text = "Abbruch"; //--- ToDo: Localize;
x = 0.453594 * safezoneW + safezoneX;
y = 0.489 * safezoneH + safezoneY;
w = 0.0773437 * safezoneW;
h = 0.022 * safezoneH;
action = "closeDialog 2;";
};
};
}; | Rockhount/ArmA3_Event_TheOutbreak | The_Outbreak2.Altis/Ammo/dialogs.hpp | C++ | gpl-3.0 | 1,558 |
CREATE TABLE "new_american_city_inc_donors" (
"contributor" text,
"aggregate_donation" text
);
| talos/docker4data | data/socrata/data.sunlightlabs.com/new_american_city_inc_donors/schema.sql | SQL | gpl-3.0 | 97 |
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class inkMenuAccountLogicController : inkWidgetLogicController
{
[Ordinal(1)] [RED("playerId")] public inkTextWidgetReference PlayerId { get; set; }
[Ordinal(2)] [RED("changeAccountLabelTextRef")] public inkTextWidgetReference ChangeAccountLabelTextRef { get; set; }
[Ordinal(3)] [RED("inputDisplayControllerRef")] public inkWidgetReference InputDisplayControllerRef { get; set; }
[Ordinal(4)] [RED("changeAccountEnabled")] public CBool ChangeAccountEnabled { get; set; }
public inkMenuAccountLogicController(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| Traderain/Wolven-kit | CP77.CR2W/Types/cp77/inkMenuAccountLogicController.cs | C# | gpl-3.0 | 733 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Copyright (C) 2011-2018 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Application
mirrorMesh
Description
Mirrors a mesh around a given plane.
\*---------------------------------------------------------------------------*/
#include "argList.H"
#include "Time.H"
#include "mirrorFvMesh.H"
#include "mapPolyMesh.H"
#include "hexRef8Data.H"
using namespace Foam;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
int main(int argc, char *argv[])
{
#include "addOverwriteOption.H"
#include "addDictOption.H"
#include "setRootCase.H"
#include "createTime.H"
const bool overwrite = args.optionFound("overwrite");
const word dictName
(
args.optionLookupOrDefault<word>("dict", "mirrorMeshDict")
);
mirrorFvMesh mesh
(
IOobject
(
mirrorFvMesh::defaultRegion,
runTime.constant(),
runTime
),
dictName
);
hexRef8Data refData
(
IOobject
(
"dummy",
mesh.facesInstance(),
polyMesh::meshSubDir,
mesh,
IOobject::READ_IF_PRESENT,
IOobject::NO_WRITE,
false
)
);
if (!overwrite)
{
runTime++;
mesh.setInstance(runTime.timeName());
}
// Set the precision of the points data to 10
IOstream::defaultPrecision(max(10u, IOstream::defaultPrecision()));
// Generate the mirrored mesh
const fvMesh& mMesh = mesh.mirrorMesh();
const_cast<fvMesh&>(mMesh).setInstance(mesh.facesInstance());
Info<< "Writing mirrored mesh" << endl;
mMesh.write();
// Map the hexRef8 data
mapPolyMesh map
(
mesh,
mesh.nPoints(), // nOldPoints,
mesh.nFaces(), // nOldFaces,
mesh.nCells(), // nOldCells,
mesh.pointMap(), // pointMap,
List<objectMap>(0), // pointsFromPoints,
labelList(0), // faceMap,
List<objectMap>(0), // facesFromPoints,
List<objectMap>(0), // facesFromEdges,
List<objectMap>(0), // facesFromFaces,
mesh.cellMap(), // cellMap,
List<objectMap>(0), // cellsFromPoints,
List<objectMap>(0), // cellsFromEdges,
List<objectMap>(0), // cellsFromFaces,
List<objectMap>(0), // cellsFromCells,
labelList(0), // reversePointMap,
labelList(0), // reverseFaceMap,
labelList(0), // reverseCellMap,
labelHashSet(0), // flipFaceFlux,
labelListList(0), // patchPointMap,
labelListList(0), // pointZoneMap,
labelListList(0), // faceZonePointMap,
labelListList(0), // faceZoneFaceMap,
labelListList(0), // cellZoneMap,
pointField(0), // preMotionPoints,
labelList(0), // oldPatchStarts,
labelList(0), // oldPatchNMeshPoints,
autoPtr<scalarField>() // oldCellVolumesPtr
);
refData.updateMesh(map);
refData.write();
Info<< "End" << endl;
return 0;
}
// ************************************************************************* //
| will-bainbridge/OpenFOAM-dev | applications/utilities/mesh/manipulation/mirrorMesh/mirrorMesh.C | C++ | gpl-3.0 | 4,304 |
--
-- PostgreSQL database dump
--
-- Dumped from database version 10.6
-- Dumped by pg_dump version 10.6
SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET client_min_messages = warning;
ALTER TABLE IF EXISTS ONLY public.own_television DROP CONSTRAINT IF EXISTS pk_own_television;
DROP TABLE IF EXISTS public.own_television;
SET default_tablespace = '';
SET default_with_oids = false;
--
-- Name: own_television; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.own_television (
geo_level character varying(15) NOT NULL,
geo_code character varying(10) NOT NULL,
geo_version character varying(100) DEFAULT ''::character varying NOT NULL,
own_television character varying(128) NOT NULL,
total integer
);
--
-- Data for Name: own_television; Type: TABLE DATA; Schema: public; Owner: -
--
COPY public.own_television (geo_level, geo_code, geo_version, own_television, total) FROM stdin;
region 1 2009 No, don't own 91
region 1 2009 Yes, do own 29
region 2 2009 No, don't own 79
region 2 2009 Yes, do own 194
region 3 2009 No, don't own 91
region 3 2009 Yes, do own 5
region 4 2009 No, don't own 59
region 4 2009 Yes, do own 12
region 5 2009 No, don't own 41
region 5 2009 Yes, do own 7
region 6 2009 No, don't own 56
region 6 2009 Yes, do own 16
region 7 2009 No, don't own 38
region 7 2009 Yes, do own 18
region 8 2009 No, don't own 23
region 8 2009 Yes, do own 17
region 9 2009 No, don't own 16
region 9 2009 Yes, do own 8
region 10 2009 No, don't own 90
region 10 2009 Yes, do own 6
region 11 2009 No, don't own 54
region 11 2009 Yes, do own 34
region 12 2009 No, don't own 6
region 12 2009 Yes, do own 2
region 13 2009 No, don't own 18
region 13 2009 Yes, do own 6
region 14 2009 No, don't own 48
region 15 2009 No, don't own 53
region 15 2009 Yes, do own 11
region 16 2009 No, don't own 64
region 16 2009 Yes, do own 16
region 17 2009 No, don't own 38
region 17 2009 Yes, do own 26
region 30 2009 No, don't own 33
region 30 2009 Yes, do own 79
region 18 2009 No, don't own 104
region 18 2009 Yes, do own 16
region 19 2009 No, don't own 61
region 19 2009 Yes, do own 10
region 20 2009 No, don't own 103
region 20 2009 Yes, do own 21
region 21 2009 No, don't own 30
region 21 2009 Yes, do own 10
region 22 2009 No, don't own 61
region 22 2009 Yes, do own 11
region 23 2009 No, don't own 34
region 23 2009 Yes, do own 5
region 24 2009 No, don't own 68
region 24 2009 Yes, do own 4
region 25 2009 No, don't own 60
region 25 2009 Yes, do own 12
region 26 2009 No, don't own 61
region 26 2009 Yes, do own 3
region 27 2009 No, don't own 55
region 27 2009 Yes, do own 9
region 31 2009 Don't know 1
region 31 2009 No, don't own 59
region 31 2009 Yes, do own 12
region 29 2009 No, don't own 93
region 29 2009 Yes, do own 11
region 28 2009 No, don't own 59
region 28 2009 Yes, do own 29
country TZ 2009 Yes, do own 639
country TZ 2009 No, don't own 1746
country TZ 2009 Don't know 1
\.
--
-- Name: own_television pk_own_television; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.own_television
ADD CONSTRAINT pk_own_television PRIMARY KEY (geo_level, geo_code, geo_version, own_television);
--
-- PostgreSQL database dump complete
--
| CodeForAfrica/WAZImap.Kenya | hurumap_tz/sql/own_television.sql | SQL | gpl-3.0 | 3,358 |
--玄星曜兽-女土蝠
function c21520110.initial_effect(c)
--summon & set with no tribute
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(21520110,0))
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SUMMON_PROC)
e1:SetCondition(c21520110.ntcon)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetDescription(aux.Stringid(21520110,2))
e2:SetCode(EFFECT_SET_PROC)
c:RegisterEffect(e2)
--recover
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(21520110,1))
e3:SetCategory(CATEGORY_RECOVER)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e3:SetCode(EVENT_BATTLE_DAMAGE)
e3:SetRange(LOCATION_MZONE)
e3:SetCondition(c21520110.reccon)
e3:SetTarget(c21520110.rectg)
e3:SetOperation(c21520110.recop)
c:RegisterEffect(e3)
end
function c21520110.filter(c)
return c:IsSetCard(0x491) and c:IsFaceup()
end
function c21520110.ntcon(e,c,minc)
if c==nil then return true end
return minc==0 and c:GetLevel()>4 and Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c21520110.filter,tp,LOCATION_MZONE,0,1,nil)
end
function c21520110.reccon(e,tp,eg,ep,ev,re,r,rp)
return ep~=tp
end
function c21520110.rectg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(ev)
Duel.SetOperationInfo(0,CATEGORY_RECOVER,0,0,tp,ev)
end
function c21520110.recop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Recover(p,d,REASON_EFFECT)
end
| MonokuroInzanaito/ygopro-777DIY | expansions/script/c21520110.lua | Lua | gpl-3.0 | 1,588 |
#include "Data/datadescriptor.h"
#include <type_traits>
#include <QDebug>
unsigned int DataDescriptor::_uid_ctr = 0;
DataDescriptor::DataDescriptor(QString name, QString unit, double factor, Type t) :
_name(name), _unit(unit), _factor(factor), _type(t)
{
_uuid = getUUID();
}
DataDescriptor::DataDescriptor(const QJsonObject &jo) {
_uuid = getUUID();
_name = jo["name"].toString();
_unit = jo["unit"].toString();
_factor = jo["factor"].toDouble();
_type = static_cast<Type>(jo["type"].toInt());
}
DataDescriptor::Type DataDescriptor::typeFromId(quint8 id) {
switch (id) {
case 0: return Type::CHAR;
case 1: return Type::FLOAT;
case 2: return Type::UINT16T;
case 3: return Type::BIGLITTLE;
default: return Type::UINT32T;
}
}
QString DataDescriptor::str() const {
QString test("%1 [%2] * %3");
return test.arg(_name,_unit,QString::number(_factor));
}
unsigned int DataDescriptor::getUUID() {
return _uid_ctr++;
}
QJsonObject DataDescriptor::json() const {
QJsonObject json;
json["name"] = _name;
json["unit"] = _unit;
json["factor"] = _factor;
json["type"] = static_cast<std::underlying_type<Type>::type>(_type);
return json;
}
| TUD-OS/OdroidReader | Data/datadescriptor.cpp | C++ | gpl-3.0 | 1,161 |
/*
-----------------------------------------------------------------------
Copyright: 2010-2015, iMinds-Vision Lab, University of Antwerp
2014-2015, CWI, Amsterdam
Contact: [email protected]
Website: http://sf.net/projects/astra-toolbox
This file is part of the ASTRA Toolbox.
The ASTRA Toolbox is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The ASTRA Toolbox is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the ASTRA Toolbox. If not, see <http://www.gnu.org/licenses/>.
-----------------------------------------------------------------------
$Id$
*/
#ifdef ASTRA_CUDA
#include "astra/CudaEMAlgorithm.h"
#include "../cuda/2d/em.h"
using namespace std;
namespace astra {
// type of the algorithm, needed to register with CAlgorithmFactory
std::string CCudaEMAlgorithm::type = "EM_CUDA";
//----------------------------------------------------------------------------------------
// Constructor
CCudaEMAlgorithm::CCudaEMAlgorithm()
{
m_bIsInitialized = false;
CCudaReconstructionAlgorithm2D::_clear();
}
//----------------------------------------------------------------------------------------
// Destructor
CCudaEMAlgorithm::~CCudaEMAlgorithm()
{
// The actual work is done by ~CCudaReconstructionAlgorithm2D
}
//---------------------------------------------------------------------------------------
// Initialize - Config
bool CCudaEMAlgorithm::initialize(const Config& _cfg)
{
ASTRA_ASSERT(_cfg.self);
ConfigStackCheck<CAlgorithm> CC("CudaEMAlgorithm", this, _cfg);
m_bIsInitialized = CCudaReconstructionAlgorithm2D::initialize(_cfg);
if (!m_bIsInitialized)
return false;
m_pAlgo = new astraCUDA::EM();
m_bAlgoInit = false;
return true;
}
//---------------------------------------------------------------------------------------
// Initialize - C++
bool CCudaEMAlgorithm::initialize(CProjector2D* _pProjector,
CFloat32ProjectionData2D* _pSinogram,
CFloat32VolumeData2D* _pReconstruction)
{
m_bIsInitialized = CCudaReconstructionAlgorithm2D::initialize(_pProjector, _pSinogram, _pReconstruction);
if (!m_bIsInitialized)
return false;
m_pAlgo = new astraCUDA::EM();
m_bAlgoInit = false;
return true;
}
} // namespace astra
#endif // ASTRA_CUDA
| mohamedadaly/trex | src/CudaEMAlgorithm.cpp | C++ | gpl-3.0 | 2,709 |
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015 Daniel Rodriguez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import collections
import six
from .comminfo import CommissionInfo
from .position import Position
from .metabase import MetaParams
from .order import Order, BuyOrder, SellOrder
class BrokerBack(six.with_metaclass(MetaParams, object)):
params = (('cash', 10000.0), ('commission', CommissionInfo()),)
def __init__(self):
self.comminfo = dict()
self.init()
def init(self):
if None not in self.comminfo.keys():
self.comminfo = dict({None: self.p.commission})
self.startingcash = self.cash = self.p.cash
self.orders = list() # will only be appending
self.pending = collections.deque() # popleft and append(right)
self.positions = collections.defaultdict(Position)
self.notifs = collections.deque()
def getcash(self):
return self.cash
def setcash(self, cash):
self.startingcash = self.cash = self.p.cash = cash
def getcommissioninfo(self, data):
if data._name in self.comminfo:
return self.comminfo[data._name]
return self.comminfo[None]
def setcommission(self, commission=0.0, margin=None, mult=1.0, name=None):
comm = CommissionInfo(commission=commission, margin=margin, mult=mult)
self.comminfo[name] = comm
def addcommissioninfo(self, comminfo, name=None):
self.comminfo[name] = comminfo
def start(self):
self.init()
def stop(self):
pass
def cancel(self, order):
try:
self.pending.remove(order)
except ValueError:
# If the list didn't have the element we didn't cancel anything
return False
order.cancel()
self.notify(order)
return True
def getvalue(self, datas=None):
pos_value = 0.0
for data in datas or self.positions.keys():
comminfo = self.getcommissioninfo(data)
position = self.positions[data]
pos_value += comminfo.getvalue(position, data.close[0])
return self.cash + pos_value
def getposition(self, data):
return self.positions[data]
def submit(self, order):
# FIXME: When an order is submitted, a margin check
# requirement has to be done before it can be accepted. This implies
# going over the entire list of pending orders for all datas and
# existing positions, simulating order execution and ending up
# with a "cash" figure that can be used to check the margin requirement
# of the order. If not met, the order can be immediately rejected
order.pannotated = None
order.plen = len(order.data)
order.accept()
self.orders.append(order)
self.pending.append(order)
self.notify(order)
return order
def buy(self, owner, data,
size, price=None, plimit=None,
exectype=None, valid=None):
order = BuyOrder(owner=owner, data=data,
size=size, price=price, pricelimit=plimit,
exectype=exectype, valid=valid)
return self.submit(order)
def sell(self, owner, data,
size, price=None, plimit=None,
exectype=None, valid=None):
order = SellOrder(owner=owner, data=data,
size=size, price=price, pricelimit=plimit,
exectype=exectype, valid=valid)
return self.submit(order)
def _execute(self, order, dt, price):
# Orders are fully executed, get operation size
size = order.executed.remsize
# Get comminfo object for the data
comminfo = self.getcommissioninfo(order.data)
# Adjust position with operation size
position = self.positions[order.data]
oldpprice = position.price
psize, pprice, opened, closed = position.update(size, price)
abopened, abclosed = abs(opened), abs(closed)
# if part/all of a position has been closed, then there has been
# a profitandloss ... record it
pnl = comminfo.profitandloss(abclosed, oldpprice, price)
if closed:
# Adjust to returned value for closed items & acquired opened items
closedvalue = comminfo.getoperationcost(abclosed, price)
self.cash += closedvalue
# Calculate and substract commission
closedcomm = comminfo.getcomm_pricesize(abclosed, price)
self.cash -= closedcomm
# Re-adjust cash according to future-like movements
# Restore cash which was already taken at the start of the day
self.cash -= comminfo.cashadjust(abclosed,
price,
order.data.close[0])
# pnl = comminfo.profitandloss(oldpsize, oldpprice, price)
else:
closedvalue = closedcomm = 0.0
if opened:
openedvalue = comminfo.getoperationcost(abopened, price)
self.cash -= openedvalue
openedcomm = comminfo.getcomm_pricesize(abopened, price)
self.cash -= openedcomm
# Remove cash for the new opened contracts
self.cash += comminfo.cashadjust(abopened,
price,
order.data.close[0])
else:
openedvalue = openedcomm = 0.0
# Execute and notify the order
order.execute(dt, size, price,
closed, closedvalue, closedcomm,
opened, openedvalue, openedcomm,
comminfo.margin, pnl,
psize, pprice)
self.notify(order)
def notify(self, order):
self.notifs.append(order.clone())
def next(self):
for data, pos in self.positions.items():
# futures change cash in the broker in every bar
# to ensure margin requirements are met
comminfo = self.getcommissioninfo(data)
self.cash += comminfo.cashadjust(pos.size,
data.close[-1],
data.close[0])
# Iterate once over all elements of the pending queue
for i in range(len(self.pending)):
order = self.pending.popleft()
if order.expire():
self.notify(order)
continue
popen = order.data.tick_open or order.data.open[0]
phigh = order.data.tick_high or order.data.high[0]
plow = order.data.tick_low or order.data.low[0]
pclose = order.data.tick_close or order.data.close[0]
pcreated = order.created.price
plimit = order.created.pricelimit
if order.exectype == Order.Market:
self._execute(order, order.data.datetime[0], price=popen)
elif order.exectype == Order.Close:
self._try_exec_close(order, pclose)
elif order.exectype == Order.Limit:
self._try_exec_limit(order, popen, phigh, plow, pcreated)
elif order.exectype == Order.StopLimit and order.triggered:
self._try_exec_limit(order, popen, phigh, plow, plimit)
elif order.exectype == Order.Stop:
self._try_exec_stop(order, popen, phigh, plow, pcreated)
elif order.exectype == Order.StopLimit:
self._try_exec_stoplimit(order,
popen, phigh, plow, pclose,
pcreated, plimit)
if order.alive():
self.pending.append(order)
def _try_exec_close(self, order, pclose):
if len(order.data) > order.plen:
dt0 = order.data.datetime[0]
if dt0 > order.dteos:
if order.pannotated:
execdt = order.data.datetime[-1]
execprice = pannotated
else:
execdt = dt0
execprice = pclose
self._execute(order, execdt, price=execprice)
return
# If no exexcution has taken place ... annotate the closing price
order.pannotated = pclose
def _try_exec_limit(self, order, popen, phigh, plow, plimit):
if order.isbuy():
if plimit >= popen:
# open smaller/equal than requested - buy cheaper
self._execute(order, order.data.datetime[0], price=popen)
elif plimit >= plow:
# day low below req price ... match limit price
self._execute(order, order.data.datetime[0], price=plimit)
else: # Sell
if plimit <= popen:
# open greater/equal than requested - sell more expensive
self._execute(order, order.data.datetime[0], price=popen)
elif plimit <= phigh:
# day high above req price ... match limit price
self._execute(order, order.data.datetime[0], price=plimit)
def _try_exec_stop(self, order, popen, phigh, plow, pcreated):
if order.isbuy():
if popen >= pcreated:
# price penetrated with an open gap - use open
self._execute(order, order.data.datetime[0], price=popen)
elif phigh >= pcreated:
# price penetrated during the session - use trigger price
self._execute(order, order.data.datetime[0], price=pcreated)
else: # Sell
if popen <= pcreated:
# price penetrated with an open gap - use open
self._execute(order, order.data.datetime[0], price=popen)
elif plow <= pcreated:
# price penetrated during the session - use trigger price
self._execute(order, order.data.datetime[0], price=pcreated)
def _try_exec_stoplimit(self, order,
popen, phigh, plow, pclose,
pcreated, plimit):
if order.isbuy():
if popen >= pcreated:
order.triggered = True
# price penetrated with an open gap
if plimit >= popen:
self._execute(order, order.data.datetime[0], price=popen)
elif plimit >= plow:
# execute in same bar
self._execute(order, order.data.datetime[0], price=plimit)
elif phigh >= pcreated:
# price penetrated upwards during the session
order.triggered = True
# can calculate execution for a few cases - datetime is fixed
dt = order.data.datetime[0]
if popen > pclose:
if plimit >= pcreated:
self._execute(order, dt, price=pcreated)
elif plimit >= pclose:
self._execute(order, dt, price=plimit)
else: # popen < pclose
if plimit >= pcreated:
self._execute(order, dt, price=pcreated)
else: # Sell
if popen <= pcreated:
# price penetrated downwards with an open gap
order.triggered = True
if plimit <= open:
self._execute(order, order.data.datetime[0], price=popen)
elif plimit <= phigh:
# execute in same bar
self._execute(order, order.data.datetime[0], price=plimit)
elif plow <= pcreated:
# price penetrated downwards during the session
order.triggered = True
# can calculate execution for a few cases - datetime is fixed
dt = order.data.datetime[0]
if popen <= pclose:
if plimit <= pcreated:
self._execute(order, dt, price=pcreated)
elif plimit <= pclose:
self._execute(order, dt, price=plimit)
else:
# popen > pclose
if plimit <= pcreated:
self._execute(order, dt, price=pcreated)
| gnagel/backtrader | backtrader/broker.py | Python | gpl-3.0 | 13,299 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.mariotaku.twidere.util.http;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.SecurityInfo;
import javax.microedition.io.SocketConnection;
import javax.microedition.io.StreamConnection;
import repackaged.com.sun.midp.pki.X509Certificate;
import repackaged.com.sun.midp.ssl.SSLStreamConnection;
/**
*
* @author mariotaku
*/
public final class UnsafeSSLConnection implements StreamConnection {
private final SSLStreamConnection sc;
UnsafeSSLConnection(final String host, final int port) throws IOException {
final SocketConnection tcp = (SocketConnection) Connector.open("socket://" + host + ":" + port);
tcp.setSocketOption(SocketConnection.DELAY, 0);
final InputStream tcpIn = tcp.openInputStream();
final OutputStream tcpOut = tcp.openOutputStream();
sc = new SSLStreamConnection(host, port, tcpIn, tcpOut);
}
public synchronized OutputStream openOutputStream() throws IOException {
return sc.openOutputStream();
}
public synchronized InputStream openInputStream() throws IOException {
return sc.openInputStream();
}
public DataOutputStream openDataOutputStream() throws IOException {
return sc.openDataOutputStream();
}
public DataInputStream openDataInputStream() throws IOException {
return sc.openDataInputStream();
}
public X509Certificate getServerCertificate() {
return sc.getServerCertificate();
}
public SecurityInfo getSecurityInfo() throws IOException {
return sc.getSecurityInfo();
}
public synchronized void close() throws IOException {
sc.close();
}
public static UnsafeSSLConnection open(final String host, final int port) throws IOException {
if (host == null && port < 0) {
return new UnsafeSSLConnection("127.0.0.1", 443);
} else if (host != null) {
return new UnsafeSSLConnection(host, 443);
}
return new UnsafeSSLConnection(host, port);
}
}
| mariotaku/twidere.j2me | src/org/mariotaku/twidere/util/http/UnsafeSSLConnection.java | Java | gpl-3.0 | 2,116 |
/***************************************************************************
* Title : Find all possible paths from Source to Destination
* URL :
* Date : 2018-02-23
* Author: Atiq Rahman
* Comp : O(V+E)
* Status: Demo
* Notes : comments inline, input sample at '01_BFS_SP.cs'
* meta : tag-graph-dfs, tag-recursion, tag-company-gatecoin, tag-coding-test, tag-algo-core
***************************************************************************/
using System;
using System.Collections.Generic;
public class GraphDemo {
bool[] IsVisited;
// We are using Adjacency List instead of adjacency matrix to save space,
// for sparse graphs which is average case
List<int>[] AdjList;
// Nodes in the path being visited so far
int[] Path;
// Number of nodes so far encountered during the visit
int PathHopCount;
int PathCount = 0;
// Number of Vertices in the graph
int nV;
// Number of Edges
int nE;
int Source;
int Destination;
/*
* Takes input
* Build adjacency list graph representation
* Does input validation
*/
public void TakeInput() {
Console.WriteLine("Please enter number of vertices in the graph:");
nV = int.Parse(Console.ReadLine());
if (nV < 1)
throw new ArgumentException();
// As number of vertices is know at this point,
// Initialize (another way to do is to move this block to constructor)
Path = new int[nV];
PathHopCount = 0;
PathCount = 0;
AdjList = new List<int>[nV];
// by default C# compiler sets values in array to false
IsVisited = new bool[nV];
for (int i = 0; i < nV; i++)
AdjList[i] = new List<int>();
// Build adjacency list from given points
Console.WriteLine("Please enter number of edges:");
nE = int.Parse(Console.ReadLine());
if (nE < 0)
throw new ArgumentException();
Console.WriteLine("Please enter {0} of edges, one edge per line \"u v\" " +
"where 1 <= u <= {1} and 1 <= v <= {1}", nE, nV);
string[] tokens = null;
for (int i=0; i<nE; i++) {
tokens = Console.ReadLine().Split();
int u = int.Parse(tokens[0]) - 1;
int v = int.Parse(tokens[1]) - 1;
if (u < 0 || u >= nV || v < 0 || v >= nV)
throw new ArgumentException();
AdjList[u].Add(v);
AdjList[v].Add(u);
}
Console.WriteLine("Please provide source and destination:");
// reuse tokens variable, if it were reducing readability we would a new
// variable
tokens = Console.ReadLine().Split();
Source = int.Parse(tokens[0]) - 1;
Destination = int.Parse(tokens[1]) - 1;
if (Source < 0 || Source >= nV || Destination < 0 || Destination >= nV)
throw new ArgumentException();
}
/*
* Depth first search algorithm to find path from source to destination
* for the node of the graph passed as argument
* 1. We check if it's destination node (we avoid cycle)
* 2. If not then if the node is not visited in the same path then we visit
* its adjacent nodes
* To allow visiting same node in a different path we set visited to false
* for the node when we backtrack to a different path
*
* We store the visited paths for the node in Path variable and keep count
* of nodes in the path using variable PathHopCount. Path variable is
* reused for finding other paths.
*
* If we want to return list of all paths we can use a list of list to store
* all of them from this variable
*/
private void DFSVisit(int u) {
IsVisited[u] = true;
Path[PathHopCount++] = u;
if (u == Destination)
PrintPath();
else
foreach (int v in AdjList[u])
if (IsVisited[v] == false)
DFSVisit(v);
PathHopCount--;
IsVisited[u] = false;
}
/*
* Simply print nodes from array Path
* PathCount increments every time a new path is found.
*/
private void PrintPath() {
Console.WriteLine("Path {0}:", ++PathCount);
for (int i = 0; i < PathHopCount; i++)
if (i==0)
Console.Write(" {0}", Path[i] + 1);
else
Console.Write(" -> {0}", Path[i]+1);
Console.WriteLine();
}
public void ShowResult() {
Console.WriteLine("Listing paths from {0} to {1}.", Source+1, Destination+1);
DFSVisit(Source);
}
}
class Program {
static void Main(string[] args) {
GraphDemo graph_demo = new GraphDemo();
graph_demo.TakeInput();
graph_demo.ShowResult();
}
}
| atiq-cs/Problem-Solving | algo/Graph/02_DFS_AllPossiblePaths.cs | C# | gpl-3.0 | 4,531 |
/***********************************************************************
This file is part of KEEL-software, the Data Mining tool for regression,
classification, clustering, pattern mining and so on.
Copyright (C) 2004-2010
F. Herrera ([email protected])
L. Sánchez ([email protected])
J. Alcalá-Fdez ([email protected])
S. García ([email protected])
A. Fernández ([email protected])
J. Luengo ([email protected])
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/
**********************************************************************/
package keel.Algorithms.RE_SL_Methods.LEL_TSK;
import java.io.*;
import org.core.*;
import java.util.*;
import java.lang.Math;
class Simplif {
public double semilla;
public long cont_soluciones;
public long Gen, n_genes, n_reglas, n_generaciones;
public int n_soluciones;
public String fich_datos_chequeo, fich_datos_tst, fich_datos_val;
public String fichero_conf, ruta_salida;
public String fichero_br, fichero_reglas, fich_tra_obli, fich_tst_obli;
public String datos_inter = "";
public String cadenaReglas = "";
public MiDataset tabla, tabla_tst, tabla_val;
public BaseR_TSK base_reglas;
public BaseR_TSK base_total;
public Adap_Sel fun_adap;
public AG alg_gen;
public Simplif(String f_e) {
fichero_conf = f_e;
}
private String Quita_blancos(String cadena) {
StringTokenizer sT = new StringTokenizer(cadena, "\t ", false);
return (sT.nextToken());
}
/** Reads the data of the configuration file */
public void leer_conf() {
int i, j;
String cadenaEntrada, valor;
double cruce, mutacion, porc_radio_reglas, porc_min_reglas, alfa, tau;
int tipo_fitness, long_poblacion;
// we read the file in a String
cadenaEntrada = Fichero.leeFichero(fichero_conf);
StringTokenizer sT = new StringTokenizer(cadenaEntrada, "\n\r=", false);
// we read the algorithm's name
sT.nextToken();
sT.nextToken();
// we read the name of the training and test files
sT.nextToken();
valor = sT.nextToken();
StringTokenizer ficheros = new StringTokenizer(valor, "\t ", false);
fich_datos_chequeo = ( (ficheros.nextToken()).replace('\"', ' ')).trim();
fich_datos_val = ( (ficheros.nextToken()).replace('\"', ' ')).trim();
fich_datos_tst = ( (ficheros.nextToken()).replace('\"', ' ')).trim();
// we read the name of the output files
sT.nextToken();
valor = sT.nextToken();
ficheros = new StringTokenizer(valor, "\t ", false);
fich_tra_obli = ( (ficheros.nextToken()).replace('\"', ' ')).trim();
fich_tst_obli = ( (ficheros.nextToken()).replace('\"', ' ')).trim();
String aux = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //Br inicial
aux = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BD
fichero_br = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BR salida de MAN2TSK
fichero_reglas = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BR salida de Select
aux = ( (ficheros.nextToken()).replace('\"', ' ')).trim(); //BR salida de Tuning
ruta_salida = fich_tst_obli.substring(0, fich_tst_obli.lastIndexOf('/') + 1);
// we read the seed of the random generator
sT.nextToken();
valor = sT.nextToken();
semilla = Double.parseDouble(valor.trim());
Randomize.setSeed( (long) semilla); ;
for (i = 0; i < 19; i++) {
sT.nextToken(); //variable
sT.nextToken(); //valor
}
// we read the Number of Iterations
sT.nextToken();
valor = sT.nextToken();
n_generaciones = Long.parseLong(valor.trim());
// we read the Population Size
sT.nextToken();
valor = sT.nextToken();
long_poblacion = Integer.parseInt(valor.trim());
// we read the Tau parameter for the minimun maching degree required to the KB
sT.nextToken();
valor = sT.nextToken();
tau = Double.parseDouble(valor.trim());
// we read the Rate of Rules that don't are eliminated
sT.nextToken();
valor = sT.nextToken();
porc_min_reglas = Double.parseDouble(valor.trim());
// we read the Rate of rules to estimate the niche radio
sT.nextToken();
valor = sT.nextToken();
porc_radio_reglas = Double.parseDouble(valor.trim());
// we read the Alfa parameter for the Power Law
sT.nextToken();
valor = sT.nextToken();
alfa = Double.parseDouble(valor.trim());
// we read the Type of Fitness Function
sT.nextToken();
valor = sT.nextToken();
tipo_fitness = Integer.parseInt(valor.trim());
// we select the numero de soluciones
n_soluciones = 1;
// we read the Cross Probability
sT.nextToken();
valor = sT.nextToken();
cruce = Double.parseDouble(valor.trim());
// we read the Mutation Probability
sT.nextToken();
valor = sT.nextToken();
mutacion = Double.parseDouble(valor.trim());
// we create all the objects
tabla = new MiDataset(fich_datos_chequeo, false);
if (tabla.salir == false) {
tabla_val = new MiDataset(fich_datos_val, false);
tabla_tst = new MiDataset(fich_datos_tst, false);
base_total = new BaseR_TSK(fichero_br, tabla, true);
base_reglas = new BaseR_TSK(base_total.n_reglas, tabla);
fun_adap = new Adap_Sel(tabla, tabla_tst, base_reglas, base_total,
base_total.n_reglas, porc_radio_reglas,
porc_min_reglas, n_soluciones, tau, alfa,
tipo_fitness);
alg_gen = new AG(long_poblacion, base_total.n_reglas, cruce, mutacion,
fun_adap);
}
}
public void run() {
int i, j;
double ec, el, min_CR, ectst, eltst;
/* We read the configutate file and we initialize the structures and variables */
leer_conf();
if (tabla.salir == false) {
/* Inicializacion del contador de soluciones ya generadas */
cont_soluciones = 0;
System.out.println("Simplif-TSK");
do {
/* Generation of the initial population */
alg_gen.Initialize();
Gen = 0;
/* Evaluation of the initial population */
alg_gen.Evaluate();
Gen++;
/* Main of the genetic algorithm */
do {
/* Interchange of the new and old population */
alg_gen.Intercambio();
/* Selection by means of Baker */
alg_gen.Select();
/* Crossover */
alg_gen.Cruce_Multipunto();
/* Mutation */
alg_gen.Mutacion_Uniforme();
/* Elitist selection */
alg_gen.Elitist();
/* Evaluation of the current population */
alg_gen.Evaluate();
/* we increment the counter */
Gen++;
}
while (Gen <= n_generaciones);
/* we store the RB in the Tabu list */
if (Aceptar(alg_gen.solucion()) == 1) {
fun_adap.guardar_solucion(alg_gen.solucion());
/* we increment the number of solutions */
cont_soluciones++;
fun_adap.Decodifica(alg_gen.solucion());
fun_adap.Cubrimientos_Base();
/* we calcule the MSEs */
fun_adap.Error_tra();
ec = fun_adap.EC;
el = fun_adap.EL;
fun_adap.tabla_tst = tabla_tst;
fun_adap.Error_tst();
ectst = fun_adap.EC;
eltst = fun_adap.EL;
/* we calculate the minimum and maximum matching */
min_CR = 1.0;
for (i = 0; i < tabla.long_tabla; i++) {
min_CR = Adap.Minimo(min_CR, tabla.datos[i].maximo_cubrimiento);
}
/* we write the RB */
cadenaReglas = base_reglas.BRtoString();
cadenaReglas += "\n\nMinimum of C_R: " + min_CR +
" Minimum covering degree: " + fun_adap.mincb +
"\nAverage covering degree: " + fun_adap.medcb + " MLE: " + el +
"\nMSEtra: " + ec + " , MSEtst: " + ectst + "\n";
Fichero.escribeFichero(fichero_reglas, cadenaReglas);
/* we write the obligatory output files*/
String salida_tra = tabla.getCabecera();
salida_tra += fun_adap.getSalidaObli(tabla_val);
Fichero.escribeFichero(fich_tra_obli, salida_tra);
String salida_tst = tabla_tst.getCabecera();
salida_tst += fun_adap.getSalidaObli(tabla_tst);
Fichero.escribeFichero(fich_tst_obli, salida_tst);
/* we write the MSEs in specific files */
Fichero.AnadirtoFichero(ruta_salida + "SimplifcomunR.txt", "" + base_reglas.n_reglas + "\n");
Fichero.AnadirtoFichero(ruta_salida + "SimplifcomunTRA.txt", "" + ec + "\n");
Fichero.AnadirtoFichero(ruta_salida + "SimplifcomunTST.txt", "" + ectst + "\n");
}
/* the multimodal GA finish when the condition is true */
}
while (Parada() == 0);
}
}
/** Criterion of stop */
public int Parada() {
if (cont_soluciones == n_soluciones) {
return (1);
}
else {
return (0);
}
}
/** Criterion to accept the solutions */
int Aceptar(char[] cromosoma) {
return (1);
}
}
| SCI2SUGR/KEEL | src/keel/Algorithms/RE_SL_Methods/LEL_TSK/Simplif.java | Java | gpl-3.0 | 10,008 |
package com.orcinuss.reinforcedtools.item.tools;
import com.google.common.collect.Sets;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemTool;
import java.util.Set;
public class ItemRTMHarvester extends ItemTool{
private static final Set blocksToBreak = Sets.newHashSet(new Block[]{Blocks.glowstone});
public EnumRarity rarity;
public ItemRTMHarvester(Item.ToolMaterial material)
{
this(material, EnumRarity.common);
}
public ItemRTMHarvester(Item.ToolMaterial material, EnumRarity rarity ){
super(0.0F, material, blocksToBreak);
this.rarity = rarity;
this.maxStackSize = 1;
}
}
| Orcinuss/ReinforcedTools | src/main/java/com/orcinuss/reinforcedtools/item/tools/ItemRTMHarvester.java | Java | gpl-3.0 | 803 |
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''Copyright (C) 2010 MapAction UK Charity No. 1075977
''
''www.mapaction.org
''
''This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
''
''This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
''
''You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses>.
''
''Additional permission under GNU GPL version 3 section 7
''
''If you modify this Program, or any covered work, by linking or combining it with
''ESRI ArcGIS Desktop Products (ArcView, ArcEditor, ArcInfo, ArcEngine Runtime and ArcEngine Developer Kit) (or a modified version of that library), containing parts covered by the terms of ESRI's single user or concurrent use license, the licensors of this Program grant you additional permission to convey the resulting work.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Imports ESRI.ArcGIS.esriSystem
Imports mapaction.datanames.api
Module maDataNameChecker
Private m_AOLicenseInitializer As LicenseInitializer = New mapaction.datanames.cli.LicenseInitializer()
Private m_strDataListPath As String = Nothing
Private m_strLookupTablesPath As String = Nothing
Private m_blnRecuse As Boolean = True
Sub Main(ByVal CmdArgs() As String)
'ESRI License Initializer generated code.
m_AOLicenseInitializer.InitializeApplication(New esriLicenseProductCode() {esriLicenseProductCode.esriLicenseProductCodeEngine, esriLicenseProductCode.esriLicenseProductCodeEngineGeoDB, esriLicenseProductCode.esriLicenseProductCodeArcView, esriLicenseProductCode.esriLicenseProductCodeArcEditor, esriLicenseProductCode.esriLicenseProductCodeArcInfo}, _
New esriLicenseExtensionCode() {})
Dim blnNextArgIsDataList As Boolean = False
Dim blnNextAgrIsLookupTable As Boolean = False
Dim blnPrintVersion As Boolean = False
Dim blnPrintHelp As Boolean = False
Dim blnUnregconisedArg As Boolean = False
Dim strMDBpath(1) As String
''
' Read the arguments
If CmdArgs Is Nothing OrElse CmdArgs.Length < 1 Then
blnPrintHelp = True
Else
For Each strArg As String In CmdArgs
'System.Console.WriteLine(arg)
Select Case strArg
Case "-l", "/l"
blnNextArgIsDataList = True
Case "-t", "/t"
blnNextAgrIsLookupTable = True
Case "-v", "/v"
blnPrintVersion = True
Case "-h", "-?", "/h", "/?"
blnPrintHelp = True
Case "-r"
m_blnRecuse = True
Case "-n"
m_blnRecuse = False
Case Else
If blnNextArgIsDataList Then
m_strDataListPath = strArg
blnNextArgIsDataList = False
ElseIf blnNextAgrIsLookupTable Then
m_strLookupTablesPath = strArg
blnNextAgrIsLookupTable = False
Else
blnUnregconisedArg = True
End If
End Select
Next
End If
''
' Now decide want to do
If blnNextAgrIsLookupTable Or blnNextArgIsDataList Or blnUnregconisedArg Then
printUnregconisedArgs()
ElseIf blnPrintHelp Then
printUsageMessage()
ElseIf blnPrintVersion Then
printNameAndVersion()
Else
testDataNames()
End If
'MsgBox("done")
'ESRI License Initializer generated code.
'Do not make any call to ArcObjects after ShutDownApplication()
m_AOLicenseInitializer.ShutdownApplication()
End Sub
Private Sub testDataNames()
Dim dlc As IDataListConnection = Nothing
Dim dnclFactory As DataNameClauseLookupFactory
Dim dncl As IDataNameClauseLookup
Dim lstDNtoTest As New List(Of IDataName)
Dim lngStatus As Long
Try
'''''''''''''''''''
'' First look for an IGeoDataListConnection argument
'''''''''''''''''''
If m_strDataListPath Is Nothing Then
printUnregconisedArgs()
Else
'We are using names read from a directory or GDB
dlc = DataListConnectionFactory.getFactory().createDataListConnection(m_strDataListPath)
'''''''''''''''''''
'' Secound look for an IDataNameClauseLookup argument
'''''''''''''''''''
If m_strLookupTablesPath Is Nothing Then
dncl = dlc.getDefaultDataNameClauseLookup()
System.Console.WriteLine()
System.Console.WriteLine("Using Data Name Clause Lookup Tables at:")
System.Console.WriteLine(dncl.getDetails())
Else
dnclFactory = DataNameClauseLookupFactory.getFactory()
dncl = dnclFactory.createDataNameClauseLookup(m_strLookupTablesPath, False)
End If
dlc.setRecuse(m_blnRecuse)
lstDNtoTest.AddRange(dlc.getLayerDataNamesList(dncl))
'''''''''''''''''''
'' Third loop through IDataName details
'''''''''''''''''''
For Each dnCurrent In lstDNtoTest
'todo MEDIUM: Rewrite the way that the names are tested in the testingCommandline
lngStatus = dnCurrent.checkNameStatus()
System.Console.WriteLine()
System.Console.WriteLine("********************************************************")
System.Console.WriteLine("DATA NAME: " & dnCurrent.getNameStr())
System.Console.WriteLine("********************************************************")
System.Console.Write(DataNameStringFormater.getDataNamingStatusMessage(lngStatus))
Next
End If
Catch ex As Exception
System.Console.WriteLine(ex.ToString())
System.Console.WriteLine("Test commandline ended with error")
End Try
End Sub
Private Sub printUnregconisedArgs()
Dim stb As New System.Text.StringBuilder
stb.AppendLine()
stb.AppendLine("Unregconised Arguments:")
stb.AppendFormat("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}", My.Application.CommandLineArgs)
System.Console.Write(stb.ToString())
printUsageMessage()
End Sub
Private Sub printUsageMessage()
Dim stb As New System.Text.StringBuilder
stb.AppendLine()
stb.AppendFormat("Usage: {0}", My.Application.Info.AssemblyName)
stb.AppendLine()
stb.AppendLine()
stb.AppendFormat("{0} {{-l <path to data list> [-r|-n] [-t <path to non-default clause lookup tables>] | -v | -h | -? }}", My.Application.Info.AssemblyName)
stb.AppendLine()
stb.AppendLine()
stb.AppendLine("Options:")
stb.AppendLine(" -v Print the name and version number and quit")
stb.AppendLine(" -h or -? Print this usage message and quit")
stb.AppendLine(" -l <path to data list> Specify the path of the list of datanames to be checked. This may be an MXD file (*.mxd), " & _
"a personal GDB (*.mdb), a filebased GDB (*.gdb), a directory of shapefiles (<dir>), or an SDE connection file (*.sde)")
stb.AppendLine(" -r (default) Recuse the list if appropriate (eg for a directory)")
stb.AppendLine(" -n Do not recuse the list if appropriate (eg for a directory)")
stb.AppendLine(" -t Optional: Override the default clause table locations by speficing a location of an MDB or GDB containing the " & _
"clause tables. If this option is not specified then the program will attempt to automatically detrive their location. " & _
"If they cannot be automatically located then the program will quit with an error.")
System.Console.Write(stb.ToString())
End Sub
Private Sub printNameAndVersion()
Dim stb As New System.Text.StringBuilder
stb.AppendLine()
stb.AppendFormat("{0} version {1}", My.Application.Info.AssemblyName, My.Application.Info.Version)
stb.AppendLine()
System.Console.Write(stb.ToString())
End Sub
End Module
| mapaction/legacy-tools | v1.0/dataNameTools/cli/maDataNameChecker.vb | Visual Basic | gpl-3.0 | 9,062 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
namespace Admin.Models
{
public class FacilityClient
{
//private string BASE_URL = "http://ihmwcore.azurewebsites.net/api/";
private string BASE_URL = "http://localhost:52249/api/";
public IEnumerable<Facility> findAll()
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("Facility").Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsAsync<IEnumerable<Facility>>().Result;
}
else
{
return null;
}
}
catch
{
return null;
}
}
public Facility find(int id)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("Facility/" + id).Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsAsync<Facility>().Result;
}
else
{
return null;
}
}
catch
{
return null;
}
}
public bool Create(Facility Facility)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsJsonAsync("Facility", Facility).Result;
return response.IsSuccessStatusCode;
}
catch
{
return false;
}
}
public bool Edit(Facility Facility)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PutAsJsonAsync("Facility/" + Facility.facilityNumber, Facility).Result;
return response.IsSuccessStatusCode;
}
catch
{
return false;
}
}
public bool Delete(int id)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.DeleteAsync("Facility/" + id).Result;
return response.IsSuccessStatusCode;
}
catch
{
return false;
}
}
}
} | KevinEsquivel21/iHMW | Admin/Admin/Models/FacilityClient.cs | C# | gpl-3.0 | 3,799 |
/*
This file is part of Darling.
Copyright (C) 2019 Lubos Dolezel
Darling is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Darling is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Darling. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Foundation/Foundation.h>
@interface MDLMemoryMappedData : NSObject
@end
| darlinghq/darling | src/frameworks/ModelIO/include/ModelIO/MDLMemoryMappedData.h | C | gpl-3.0 | 765 |
/*
* Copyright © 2004 Noah Levitt
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* MucharmapSearchDialog handles all aspects of searching */
#ifndef MUCHARMAP_SEARCH_DIALOG_H
#define MUCHARMAP_SEARCH_DIALOG_H
#include <gtk/gtk.h>
#include <mucharmap/mucharmap.h>
#include "mucharmap-window.h"
G_BEGIN_DECLS
//class MucharmapSearchDialog
//{
#define MUCHARMAP_TYPE_SEARCH_DIALOG (mucharmap_search_dialog_get_type ())
#define MUCHARMAP_SEARCH_DIALOG(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), MUCHARMAP_TYPE_SEARCH_DIALOG, MucharmapSearchDialog))
#define MUCHARMAP_SEARCH_DIALOG_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), MUCHARMAP_TYPE_SEARCH_DIALOG, MucharmapSearchDialogClass))
#define MUCHARMAP_IS_SEARCH_DIALOG(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), MUCHARMAP_TYPE_SEARCH_DIALOG))
#define MUCHARMAP_IS_SEARCH_DIALOG_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), MUCHARMAP_TYPE_SEARCH_DIALOG))
#define MUCHARMAP_SEARCH_DIALOG_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), MUCHARMAP_TYPE_SEARCH_DIALOG, MucharmapSearchDialogClass))
typedef struct _MucharmapSearchDialog MucharmapSearchDialog;
typedef struct _MucharmapSearchDialogClass MucharmapSearchDialogClass;
struct _MucharmapSearchDialog
{
GtkDialog parent;
};
struct _MucharmapSearchDialogClass
{
GtkDialogClass parent_class;
/* signals */
void (* search_start) (void);
void (* search_finish) (gunichar found_char);
};
typedef enum
{
MUCHARMAP_DIRECTION_BACKWARD = -1,
MUCHARMAP_DIRECTION_FORWARD = 1
}
MucharmapDirection;
GType mucharmap_search_dialog_get_type (void);
GtkWidget * mucharmap_search_dialog_new (MucharmapWindow *parent);
void mucharmap_search_dialog_present (MucharmapSearchDialog *search_dialog);
void mucharmap_search_dialog_start_search (MucharmapSearchDialog *search_dialog,
MucharmapDirection direction);
gdouble mucharmap_search_dialog_get_completed (MucharmapSearchDialog *search_dialog);
//}
G_END_DECLS
#endif /* #ifndef MUCHARMAP_SEARCH_DIALOG_H */
| mate-desktop/mate-character-map | mucharmap/mucharmap-search-dialog.h | C | gpl-3.0 | 2,795 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.