code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
#include <cstdio> using namespace std; int a[31]; int main() { for(int i=1; i<=30; i++) { int in; scanf("%d",&in); a[in] = 1; } for(int i=1; i<=30; i++) if(!a[i]) printf("%d\n",i); }
Yoon-jae/Algorithm_BOJ
problem/5597/5597.cpp11.cpp
C++
gpl-3.0
195
/** * @file lldiriterator_test.cpp * @date 2011-06 * @brief LLDirIterator test cases. * * $LicenseInfo:firstyear=2011&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2011, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only., * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "linden_common.h" #include "lltut.h" #include "../lldiriterator.h" namespace tut { struct LLDirIteratorFixture { LLDirIteratorFixture() { } }; typedef test_group<LLDirIteratorFixture> LLDirIteratorTest_factory; typedef LLDirIteratorTest_factory::object LLDirIteratorTest_t; LLDirIteratorTest_factory tf("LLDirIterator"); /* CHOP-662 was originally introduced to deal with crashes deleting files from a directory (VWR-25500). However, this introduced a crash looking for old chat logs as the glob_to_regex function in lldiriterator wasn't escaping lots of regexp characters */ void test_chop_662(void) { // Check a selection of bad group names from the crash reports LLDirIterator iter(".","+bad-group-name]+?\?-??.*"); LLDirIterator iter1(".","))--@---bad-group-name2((?\?-??.*\\.txt"); LLDirIterator iter2(".","__^v--x)Cuide d sua vida(x--v^__?\?-??.*"); } template<> template<> void LLDirIteratorTest_t::test<1>() { test_chop_662(); } }
Belxjander/Kirito
SnowStorm/indra/llvfs/tests/lldiriterator_test.cpp
C++
gpl-3.0
2,126
#include "triggerbot.h" #include "autowall.h" bool Settings::Triggerbot::enabled = false; bool Settings::Triggerbot::onKey = true; bool Settings::Triggerbot::Filters::enemies = true; bool Settings::Triggerbot::Filters::allies = false; bool Settings::Triggerbot::Filters::walls = false; bool Settings::Triggerbot::Filters::smokeCheck = false; bool Settings::Triggerbot::Filters::flashCheck = false; bool Settings::Triggerbot::Filters::head = true; bool Settings::Triggerbot::Filters::chest = true; bool Settings::Triggerbot::Filters::stomach = true; bool Settings::Triggerbot::Filters::arms = true; bool Settings::Triggerbot::Filters::legs = true; bool Settings::Triggerbot::Delay::enabled = false; int Settings::Triggerbot::Delay::value = 250; bool Settings::Triggerbot::RandomDelay::enabled = false; int Settings::Triggerbot::RandomDelay::min = 20; int Settings::Triggerbot::RandomDelay::max = 40; int Settings::Triggerbot::RandomDelay::last = 0; ButtonCode_t Settings::Triggerbot::key = ButtonCode_t::KEY_LALT; void Triggerbot::CreateMove(CUserCmd *cmd) { if (!Settings::Triggerbot::enabled) return; if (!inputSystem->IsButtonDown(Settings::Triggerbot::key) && Settings::Triggerbot::onKey) return; C_BasePlayer* localplayer = (C_BasePlayer*) entityList->GetClientEntity(engine->GetLocalPlayer()); if (!localplayer || !localplayer->GetAlive()) return; if (Settings::Triggerbot::Filters::flashCheck && localplayer->GetFlashBangTime() - globalVars->curtime > 2.0f) return; long currentTime_ms = Util::GetEpochTime(); static long timeStamp = currentTime_ms; long oldTimeStamp; int minDelay = Settings::Triggerbot::RandomDelay::min; int maxDelay = Settings::Triggerbot::RandomDelay::max; int randDelay = rand()%(maxDelay - minDelay + 1) + minDelay; Vector traceStart, traceEnd; trace_t tr; QAngle viewAngles; engine->GetViewAngles(viewAngles); QAngle viewAngles_rcs = viewAngles + *localplayer->GetAimPunchAngle() * 2.0f; Math::AngleVectors(viewAngles_rcs, traceEnd); traceStart = localplayer->GetEyePosition(); traceEnd = traceStart + (traceEnd * 8192.0f); if (Settings::Triggerbot::Filters::walls) { Autowall::FireBulletData data; if (Autowall::GetDamage(traceEnd, !Settings::Triggerbot::Filters::allies, data) == 0.0f) return; tr = data.enter_trace; } else { Ray_t ray; ray.Init(traceStart, traceEnd); CTraceFilter traceFilter; traceFilter.pSkip = localplayer; trace->TraceRay(ray, 0x46004003, &traceFilter, &tr); } oldTimeStamp = timeStamp; timeStamp = currentTime_ms; C_BasePlayer* player = (C_BasePlayer*) tr.m_pEntityHit; if (!player) return; if (player->GetClientClass()->m_ClassID != EClassIds::CCSPlayer) return; if (player == localplayer || player->GetDormant() || !player->GetAlive() || player->GetImmune()) return; if (player->GetTeam() != localplayer->GetTeam() && !Settings::Triggerbot::Filters::enemies) return; if (player->GetTeam() == localplayer->GetTeam() && !Settings::Triggerbot::Filters::allies) return; bool filter; switch (tr.hitgroup) { case HitGroups::HITGROUP_HEAD: filter = Settings::Triggerbot::Filters::head; break; case HitGroups::HITGROUP_CHEST: filter = Settings::Triggerbot::Filters::chest; break; case HitGroups::HITGROUP_STOMACH: filter = Settings::Triggerbot::Filters::stomach; break; case HitGroups::HITGROUP_LEFTARM: case HitGroups::HITGROUP_RIGHTARM: filter = Settings::Triggerbot::Filters::arms; break; case HitGroups::HITGROUP_LEFTLEG: case HitGroups::HITGROUP_RIGHTLEG: filter = Settings::Triggerbot::Filters::legs; break; default: filter = false; } if (!filter) return; if (Settings::Triggerbot::Filters::smokeCheck && LineGoesThroughSmoke(tr.startpos, tr.endpos, 1)) return; C_BaseCombatWeapon* activeWeapon = (C_BaseCombatWeapon*) entityList->GetClientEntityFromHandle(localplayer->GetActiveWeapon()); if (!activeWeapon || activeWeapon->GetAmmo() == 0) return; ItemDefinitionIndex itemDefinitionIndex = *activeWeapon->GetItemDefinitionIndex(); if (itemDefinitionIndex == ItemDefinitionIndex::WEAPON_KNIFE || itemDefinitionIndex >= ItemDefinitionIndex::WEAPON_KNIFE_BAYONET || itemDefinitionIndex == ItemDefinitionIndex::WEAPON_TASER) return; CSWeaponType weaponType = activeWeapon->GetCSWpnData()->GetWeaponType(); if (weaponType == CSWeaponType::WEAPONTYPE_C4 || weaponType == CSWeaponType::WEAPONTYPE_GRENADE) return; if (activeWeapon->GetNextPrimaryAttack() > globalVars->curtime) { if (*activeWeapon->GetItemDefinitionIndex() == ItemDefinitionIndex::WEAPON_REVOLVER) cmd->buttons &= ~IN_ATTACK2; else cmd->buttons &= ~IN_ATTACK; } else { if (!Settings::Triggerbot::RandomDelay::enabled) { if (Settings::Triggerbot::Delay::enabled && currentTime_ms - oldTimeStamp < Settings::Triggerbot::Delay::value) { timeStamp = oldTimeStamp; return; } } else { if (currentTime_ms - oldTimeStamp < randDelay) { timeStamp = oldTimeStamp; return; } } Settings::Triggerbot::RandomDelay::last = randDelay; if (*activeWeapon->GetItemDefinitionIndex() == ItemDefinitionIndex::WEAPON_REVOLVER) cmd->buttons |= IN_ATTACK2; else cmd->buttons |= IN_ATTACK; } timeStamp = currentTime_ms; }
arzka/Aimdroid
src/Hacks/triggerbot.cpp
C++
gpl-3.0
5,265
// https://developer.mozilla.org/ja/docs/Web/API/Navigator/doNotTrack export function enable(): boolean { const w: any = window const dnt: string = w.navigator.doNotTrack || w.doNotTrack if (dnt === '1' || dnt === 'yes') { return false } return true } export function get( url: string, query: string[], onerror: OnErrorEventHandler ): void { if (enable() && query.length > 0) { const img: HTMLImageElement = document.createElement('img') img.onload = () => { // nothing todo } img.onerror = onerror img.src = `${url}?${query.join('&')}` } } export function obj2query(data: { [key: string]: string }): string[] { const query: string[] = [] Object.keys(data).forEach(key => { if (data[key]) { query.push(`${key}=${encodeURIComponent(data[key])}`) } }) return query }
userdive/agent.js
packages/agent/src/requests.ts
TypeScript
gpl-3.0
839
## Copyright 2009 Laurent Bovet <laurent.bovet@windmaster.ch> ## Jordi Puigsegur <jordi.puigsegur@gmail.com> ## ## This file is part of wfrog ## ## wfrog 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/>. import logging import log import yaml import inspect import sys import os.path import copy from Cheetah.Template import Template wfrog_version = "0.8.2.99-git" class Configurer(object): default_filename = None module_map = None log_configurer = log.LogConfigurer() logger = logging.getLogger('config') def __init__(self, module_map): self.module_map = module_map self.extensions = {} def add_options(self, opt_parser): opt_parser.add_option("-f", "--config", dest="config", help="Configuration file (in yaml)", metavar="CONFIG_FILE") opt_parser.add_option("-s", "--settings", dest="settings", help="Settings file (in yaml)", metavar="SETTINGS_FILE") opt_parser.add_option("-H", action="store_true", dest="help_list", help="Gives help on the configuration file and the list of possible config !elements in the yaml config file") opt_parser.add_option("-E", dest="help_element", metavar="ELEMENT", help="Gives help about a config !element") opt_parser.add_option("-e", "--extensions", dest="extension_names", metavar="MODULE1,MODULE2,...", help="Comma-separated list of modules containing custom configuration elements") self.log_configurer.add_options(opt_parser) def configure(self, options, component, config_file, settings_file=None, embedded=False): self.config_file = config_file self.settings_file = settings_file if options.extension_names: for ext in options.extension_names.split(","): self.logger.debug("Loading extension module '"+ext+"'") self.extensions[ext]=__import__(ext) if options.help_list: if component.__doc__ is not None: print component.__doc__ for (k,v) in self.module_map: print k print "-"*len(k) +"\n" self.print_help(v) if options.extension_names: print "Extensions" print "----------\n" for ext in self.extensions: print "[" + ext + "]" print self.print_help(self.extensions[ext]) # Adds logger documentation print self.log_configurer.__doc__ print " Use option -H ELEMENT for help on a particular !element" sys.exit() if options.help_element: element = options.help_element if element[0] is not '!': element = '!' + element desc = {} for(k,v) in self.module_map: desc.update(self.get_help_desc(v)) if len(desc) == 0: for ext in self.extensions: desc.update(self.get_help_desc(self.extensions[ext])) if desc.has_key(element): print print element + " [" + desc[element][1] +"]" print " " + desc[element][0] print else: print "Element "+element+" not found or not documented" sys.exit() if not embedded and options.config: self.config_file = options.config settings_warning=False if self.settings_file is None: if options.settings is not None: self.settings_file = options.settings else: settings_warning=True self.settings_file = os.path.dirname(self.config_file)+'/../../wfcommon/config/default-settings.yaml' settings = yaml.load( file(self.settings_file, 'r') ) variables = {} variables['settings']=settings config = yaml.load( str(Template(file=file(self.config_file, "r"), searchList=[variables]))) if settings is not None: context = copy.deepcopy(settings) else: context = {} context['_yaml_config_file'] = self.config_file context['os']=sys.platform if not embedded: self.log_configurer.configure(options, config, context) self.logger.info("Starting wfrog " + wfrog_version) if settings_warning: self.logger.warn('User settings are missing. Loading default ones. Run \'wfrog -S\' for user settings setup.') self.logger.info("Loaded settings file " + os.path.normpath(self.settings_file)) self.logger.debug('Loaded settings %s', repr(settings)) self.logger.debug("Loaded config file " + os.path.normpath(self.config_file)) if config.has_key('init'): for k,v in config['init'].iteritems(): self.logger.debug("Initializing "+k) try: v.init(context=context) except AttributeError: pass # In case the element has not init method return ( config, context ) def print_help(self, module): desc = self.get_help_desc(module, summary=True) sorted = desc.keys() sorted.sort() for k in sorted: print k print " " + desc[k][0] print def get_help_desc(self, module, summary=False): self.logger.debug("Getting info on module '"+module.__name__+"'") elements = inspect.getmembers(module, lambda l : inspect.isclass(l) and yaml.YAMLObject in inspect.getmro(l)) desc={} for element in elements: self.logger.debug("Getting doc of "+element[0]) # Gets the documentation of the first superclass superclass = inspect.getmro(element[1])[1] fulldoc=superclass.__doc__ # Add the doc of the super-super-class if _element_doc is if hasattr(inspect.getmro(superclass)[1], "_element_doc") and inspect.getmro(superclass)[1].__doc__ is not None: fulldoc = fulldoc + inspect.getmro(superclass)[1].__doc__ firstline=fulldoc.split(".")[0] self.logger.debug(firstline) module_name = module.__name__.split('.')[-1] if summary: desc[element[1].yaml_tag] = [ firstline, module_name ] else: desc[element[1].yaml_tag] = [ fulldoc, module_name ] return desc
wfrog/wfrog
wfcommon/config.py
Python
gpl-3.0
7,089
<?php /** * WES WebExploitScan Web GPLv4 http://github.com/libre/webexploitscan * * The PHP page that serves all page requests on WebExploitScan installation. * * The routines here dispatch control to the appropriate handler, which then * prints the appropriate page. * * All WebExploitScan code is released under the GNU General Public License. * See COPYRIGHT.txt and LICENSE.txt. */ $NAME='Php-MS-PHP-Antimalware-Scanner malware_signature- ID 542'; $TAGCLEAR='A<?phpif(isset($_(?:GET|POST|COOKIE|SERVER|REQUEST)[[\'"]?w{1,40}[\'"]?])){[^}]{300,600}($w{1,40})=(?:chr(d+).?){5,10};$w{1,5}(($w{1,5}),$w{1,5}.$w{1,5}($w{1,5}));include(2);1(2);}(?>|Z)'; $TAGBASE64='QTw/cGhwaWYoaXNzZXQoJF8oPzpHRVR8UE9TVHxDT09LSUV8U0VSVkVSfFJFUVVFU1QpW1tcJyJdP3d7MSw0MH1bXCciXT9dKSl7W159XXszMDAsNjAwfSgkd3sxLDQwfSk9KD86Y2hyKGQrKS4/KXs1LDEwfTskd3sxLDV9KCgkd3sxLDV9KSwkd3sxLDV9LiR3ezEsNX0oJHd7MSw1fSkpO2luY2x1ZGUoMik7MSgyKTt9KD8+fFop'; $TAGHEX='413c3f706870696628697373657428245f283f3a4745547c504f53547c434f4f4b49457c5345525645527c52455155455354295b5b5c27225d3f777b312c34307d5b5c27225d3f5d29297b5b5e7d5d7b3330302c3630307d2824777b312c34307d293d283f3a63687228642b292e3f297b352c31307d3b24777b312c357d282824777b312c357d292c24777b312c357d2e24777b312c357d2824777b312c357d29293b696e636c7564652832293b312832293b7d283f3e7c5a29'; $TAGHEXPHP=''; $TAGURI='A%3C%3Fphpif%28isset%28%24_%28%3F%3AGET%7CPOST%7CCOOKIE%7CSERVER%7CREQUEST%29%5B%5B%5C%27%22%5D%3Fw%7B1%2C40%7D%5B%5C%27%22%5D%3F%5D%29%29%7B%5B%5E%7D%5D%7B300%2C600%7D%28%24w%7B1%2C40%7D%29%3D%28%3F%3Achr%28d%2B%29.%3F%29%7B5%2C10%7D%3B%24w%7B1%2C5%7D%28%28%24w%7B1%2C5%7D%29%2C%24w%7B1%2C5%7D.%24w%7B1%2C5%7D%28%24w%7B1%2C5%7D%29%29%3Binclude%282%29%3B1%282%29%3B%7D%28%3F%3E%7CZ%29'; $TAGCLEAR2=''; $TAGBASE642=''; $TAGHEX2=''; $TAGHEXPHP2=''; $TAGURI2=''; $DATEADD='10/09/2019'; $LINK='Webexploitscan.org ;Php-MS-PHP-Antimalware-Scanner malware_signature- ID 542 '; $ACTIVED='1'; $VSTATR='malware_signature';
libre/webexploitscan
wes/data/rules/fullscan/10092019-MS-PHP-Antimalware-Scanner-542-malware_signature.php
PHP
gpl-3.0
1,948
/***************************************************************************** * Copyright (c) 2014 Ted John, Peter Hill, Duncan Frost * OpenRCT2, an open source clone of Roller Coaster Tycoon 2. * * This file is part of OpenRCT2. * * OpenRCT2 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 "../addresses.h" #include "../common.h" #include "../localisation/localisation.h" #include "../interface/window.h" #include "../platform/osinterface.h" #include "drawing.h" // HACK These were originally passed back through registers int gLastDrawStringX; int gLastDrawStringY; uint8 _screenDirtyBlocks[5120]; //Originally 0x9ABE0C, 12 elements from 0xF3 are the peep top colour, 12 elements from 0xCA are peep trouser colour const uint8 peep_palette[0x100] = { 0x00, 0xF3, 0xF4, 0xF5, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF, 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF, 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF }; //Originally 0x9ABE04 uint8 text_palette[0x8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // Previously 0x97FCBC use it to get the correct palette from g1_elements const uint16 palette_to_g1_offset[] = { 0x1333, 0x1334, 0x1335, 0x1336, 0x1337, 0x1338, 0x1339, 0x133A, 0x133B, 0x133C, 0x133D, 0x133E, 0x133F, 0x1340, 0x1341, 0x1342, 0x1343, 0x1344, 0x1345, 0x1346, 0x1347, 0x1348, 0x1349, 0x134A, 0x134B, 0x134C, 0x134D, 0x134E, 0x134F, 0x1350, 0x1351, 0x1352, 0x1353, 0x0C1C, 0x0C1D, 0x0C1E, 0x0C1F, 0x0C20, 0x0C22, 0x0C23, 0x0C24, 0x0C25, 0x0C26, 0x0C21, 0x1354, 0x1355, 0x1356, 0x1357, 0x1358, 0x1359, 0x135A, 0x135B, 0x135C, 0x135D, 0x135E, 0x135F, 0x1360, 0x1361, 0x1362, 0x1363, 0x1364, 0x1365, 0x1366, 0x1367, 0x1368, 0x1369, 0x136A, 0x136B, 0x136C, 0x136D, 0x136E, 0x136F, 0x1370, 0x1371, 0x1372, 0x1373, 0x1374, 0x1375, 0x1376, 0x1377, 0x1378, 0x1379, 0x137A, 0x137B, 0x137C, 0x137D, 0x137E, 0x137F, 0x1380, 0x1381, 0x1382, 0x1383, 0x1384, 0x1385, 0x1386, 0x1387, 0x1388, 0x1389, 0x138A, 0x138B, 0x138C, 0x138D, 0x138E, 0x138F, 0x1390, 0x1391, 0x1392, 0x1393, 0x1394, 0x1395, 0x1396, 0x1397, 0x1398, 0x1399, 0x139A, 0x139B, 0x139C, 0x139D, 0x139E, 0x139F, 0x13A0, 0x13A1, 0x13A2, 0x13A3, 0x13A4, 0x13A5, 0x13A6, 0x13A7, 0x13A8, 0x13A9, 0x13AA, 0x13AB, 0x13AC, 0x13AD, 0x13AE, 0x13AF, 0x13B0, 0x13B1, 0x13B2, 0x13B3, 0x13B4, 0x13B5, 0x13B6, 0x13B7, }; static void gfx_draw_dirty_blocks(int x, int y, int columns, int rows); /** * Clears the screen with the specified colour. * rct2: 0x00678A9F */ void gfx_clear(rct_drawpixelinfo *dpi, int colour) { int y, w, h; char* ptr; w = dpi->width >> dpi->zoom_level; h = dpi->height >> dpi->zoom_level; ptr = dpi->bits; for (y = 0; y < h; y++) { memset(ptr, colour, w); ptr += w + dpi->pitch; } } void gfx_draw_pixel(rct_drawpixelinfo *dpi, int x, int y, int colour) { gfx_fill_rect(dpi, x, y, x, y, colour); } /** * * rct2: 0x00683854 * a1 (ebx) * product (cl) */ void gfx_transpose_palette(int pal, unsigned char product) { rct_g1_element g1 = RCT2_ADDRESS(RCT2_ADDRESS_G1_ELEMENTS, rct_g1_element)[pal]; int width = g1.width; int x = g1.x_offset; uint8* dest_pointer = (uint8*)&(RCT2_ADDRESS(0x014124680,uint8)[x]); uint8* source_pointer = g1.offset; for (; width > 0; width--) { dest_pointer[0] = (source_pointer[0] * product) >> 8; dest_pointer[1] = (source_pointer[1] * product) >> 8; dest_pointer[2] = (source_pointer[2] * product) >> 8; source_pointer += 3; dest_pointer += 4; } osinterface_update_palette((char*)0x01424680, 10, 236);//Odd would have expected dest_pointer } /** * * rct2: 0x006EC9CE * @param x (ax) * @param y (cx) * @param base_height (di) * @param clearance_height (si) */ void gfx_invalidate_scrollingtext(int x, int y, int base_height, int clearance_height) { x += 16; y += 16; int left, top, right, bottom; switch (RCT2_GLOBAL(RCT2_ADDRESS_CURRENT_ROTATION, uint32)) { case 0: left = (-x + y) - 32; right = (-x + y) + 32; top = ((y + x) / 2) - 32 - clearance_height; bottom = ((y + x) / 2) + 32 - base_height; break; case 1: left = (-x - y) - 32; right = (-x - y) + 32; top = ((y - x) / 2) - 32 - clearance_height; bottom = ((y - x) / 2) + 32 - base_height; break; case 2: left = (x - y) - 32; right = (x - y) + 32; top = ((-y - x) / 2) - 32 - clearance_height; bottom = ((-y - x) / 2) + 32 - base_height; break; case 3: left = (x + y) - 32; right = (x + y) + 32; top = ((-y + x) / 2) - 32 - clearance_height; bottom = ((-y + x) / 2) + 32 - base_height; break; } for (rct_viewport** viewport_p = RCT2_ADDRESS(RCT2_ADDRESS_ACTIVE_VIEWPORT_PTR_ARRAY, rct_viewport*); *viewport_p; ++viewport_p) { rct_viewport* viewport = *viewport_p; if (viewport->zoom < 1) { if (right > viewport->view_x && bottom > viewport->view_y && left < viewport->view_x + viewport->view_width) { if (left < viewport->view_x) { left = viewport->view_x; } if (right > viewport->view_x + viewport->view_width) { right = viewport->view_x + viewport->view_width; } if (top < viewport->view_y + viewport->view_height) { if (top < viewport->view_y) { top = viewport->view_y; } if (bottom > viewport->view_y + viewport->view_height) { bottom = viewport->view_y + viewport->view_height; } left = ((left - viewport->view_x) >> viewport->zoom) + viewport->x; top = ((top - viewport->view_y) >> viewport->zoom) + viewport->y; right = ((right - viewport->view_x) >> viewport->zoom) + viewport->x; bottom = ((bottom - viewport->view_y) >> viewport->zoom) + viewport->y; gfx_set_dirty_blocks(left, top, right, bottom); } } } } } /** * * rct2: 0x006ED7E5 */ void gfx_invalidate_screen() { int width = RCT2_GLOBAL(RCT2_ADDRESS_SCREEN_WIDTH, sint16); int height = RCT2_GLOBAL(RCT2_ADDRESS_SCREEN_HEIGHT, sint16); gfx_set_dirty_blocks(0, 0, width, height); } /** * * rct2: 0x006E732D * left (ax) * top (bx) * right (dx) * bottom (bp) */ void gfx_set_dirty_blocks(int left, int top, int right, int bottom) { int x, y; uint8 *screenDirtyBlocks = RCT2_ADDRESS(0x00EDE408, uint8); left = max(left, 0); top = max(top, 0); right = min(right, RCT2_GLOBAL(RCT2_ADDRESS_SCREEN_WIDTH, sint16)); bottom = min(bottom, RCT2_GLOBAL(RCT2_ADDRESS_SCREEN_HEIGHT, sint16)); if (left >= right) return; if (top >= bottom) return; right--; bottom--; left >>= RCT2_GLOBAL(0x009ABDF0, sint8); right >>= RCT2_GLOBAL(0x009ABDF0, sint8); top >>= RCT2_GLOBAL(0x009ABDF1, sint8); bottom >>= RCT2_GLOBAL(0x009ABDF1, sint8); for (y = top; y <= bottom; y++) for (x = left; x <= right; x++) screenDirtyBlocks[y * RCT2_GLOBAL(RCT2_ADDRESS_DIRTY_BLOCK_COLUMNS, sint32) + x] = 0xFF; } /** * * rct2: 0x006E73BE */ void gfx_draw_all_dirty_blocks() { int x, y, xx, yy, columns, rows; uint8 *screenDirtyBlocks = RCT2_ADDRESS(0x00EDE408, uint8); for (x = 0; x < RCT2_GLOBAL(RCT2_ADDRESS_DIRTY_BLOCK_COLUMNS, sint32); x++) { for (y = 0; y < RCT2_GLOBAL(RCT2_ADDRESS_DIRTY_BLOCK_ROWS, sint32); y++) { if (screenDirtyBlocks[y * RCT2_GLOBAL(RCT2_ADDRESS_DIRTY_BLOCK_COLUMNS, sint32) + x] == 0) continue; // Determine columns for (xx = x; xx < RCT2_GLOBAL(RCT2_ADDRESS_DIRTY_BLOCK_COLUMNS, sint32); xx++) if (screenDirtyBlocks[y * RCT2_GLOBAL(RCT2_ADDRESS_DIRTY_BLOCK_COLUMNS, sint32) + xx] == 0) break; columns = xx - x; // Check rows for (yy = y; yy < RCT2_GLOBAL(RCT2_ADDRESS_DIRTY_BLOCK_ROWS, sint32); yy++) for (xx = x; xx < x + columns; xx++) if (screenDirtyBlocks[yy * RCT2_GLOBAL(RCT2_ADDRESS_DIRTY_BLOCK_COLUMNS, sint32) + xx] == 0) goto endRowCheck; endRowCheck: rows = yy - y; gfx_draw_dirty_blocks(x, y, columns, rows); } } } static void gfx_draw_dirty_blocks(int x, int y, int columns, int rows) { int left, top, right, bottom; uint8 *screenDirtyBlocks = RCT2_ADDRESS(0x00EDE408, uint8); // Unset dirty blocks for (top = y; top < y + rows; top++) for (left = x; left < x + columns; left++) screenDirtyBlocks[top * RCT2_GLOBAL(RCT2_ADDRESS_DIRTY_BLOCK_COLUMNS, sint32) + left] = 0; // Determine region in pixels left = max(0, x * RCT2_GLOBAL(RCT2_ADDRESS_DIRTY_BLOCK_WIDTH, sint16)); top = max(0, y * RCT2_GLOBAL(RCT2_ADDRESS_DIRTY_BLOCK_HEIGHT, sint16)); right = min(RCT2_GLOBAL(RCT2_ADDRESS_SCREEN_WIDTH, sint16), left + (columns * RCT2_GLOBAL(RCT2_ADDRESS_DIRTY_BLOCK_WIDTH, sint16))); bottom = min(RCT2_GLOBAL(RCT2_ADDRESS_SCREEN_HEIGHT, sint16), top + (rows * RCT2_GLOBAL(RCT2_ADDRESS_DIRTY_BLOCK_HEIGHT, sint16))); if (right <= left || bottom <= top) return; // Draw region gfx_redraw_screen_rect(left, top, right, bottom); } /** * * rct2: 0x006E7499 * left (ax) * top (bx) * right (dx) * bottom (bp) */ void gfx_redraw_screen_rect(short left, short top, short right, short bottom) { rct_window* w; rct_drawpixelinfo *screenDPI = RCT2_ADDRESS(RCT2_ADDRESS_SCREEN_DPI, rct_drawpixelinfo); rct_drawpixelinfo *windowDPI = RCT2_ADDRESS(RCT2_ADDRESS_WINDOW_DPI, rct_drawpixelinfo); // Unsure what this does RCT2_CALLPROC_X(0x00683326, left, top, right - 1, bottom - 1, 0, 0, 0); windowDPI->bits = screenDPI->bits + left + ((screenDPI->width + screenDPI->pitch) * top); windowDPI->x = left; windowDPI->y = top; windowDPI->width = right - left; windowDPI->height = bottom - top; windowDPI->pitch = screenDPI->width + screenDPI->pitch + left - right; for (w = g_window_list; w < RCT2_GLOBAL(RCT2_ADDRESS_NEW_WINDOW_PTR, rct_window*); w++) { if (w->flags & WF_TRANSPARENT) continue; if (right <= w->x || bottom <= w->y) continue; if (left >= w->x + w->width || top >= w->y + w->height) continue; window_draw(w, left, top, right, bottom); } } /* * * rct2: 0x006EE53B * left (ax) * width (bx) * top (cx) * height (dx) * drawpixelinfo (edi) */ rct_drawpixelinfo* clip_drawpixelinfo(rct_drawpixelinfo* dpi, int left, int width, int top, int height) { rct_drawpixelinfo* newDrawPixelInfo = rct2_malloc(sizeof(rct_drawpixelinfo)); int right = left + width; int bottom = top + height; newDrawPixelInfo->bits = dpi->bits; newDrawPixelInfo->x = dpi->x; newDrawPixelInfo->y = dpi->y; newDrawPixelInfo->width = dpi->width; newDrawPixelInfo->height = dpi->height; newDrawPixelInfo->pitch = dpi->pitch; newDrawPixelInfo->zoom_level = 0; if (left > newDrawPixelInfo->x) { uint16 clippedFromLeft = left - newDrawPixelInfo->x; newDrawPixelInfo->width -= clippedFromLeft; newDrawPixelInfo->x = left; newDrawPixelInfo->pitch += clippedFromLeft; newDrawPixelInfo->bits += clippedFromLeft; } int stickOutWidth = newDrawPixelInfo->x + newDrawPixelInfo->width - right; if (stickOutWidth > 0) { newDrawPixelInfo->width -= stickOutWidth; newDrawPixelInfo->pitch += stickOutWidth; } if (top > newDrawPixelInfo->y) { uint16 clippedFromTop = top - newDrawPixelInfo->y; newDrawPixelInfo->height -= clippedFromTop; newDrawPixelInfo->y = top; uint32 bitsPlus = (newDrawPixelInfo->pitch + newDrawPixelInfo->width) * clippedFromTop; newDrawPixelInfo->bits += bitsPlus; } int bp = newDrawPixelInfo->y + newDrawPixelInfo->height - bottom; if (bp > 0) { newDrawPixelInfo->height -= bp; } if (newDrawPixelInfo->width > 0 && newDrawPixelInfo->height > 0) { newDrawPixelInfo->x -= left; newDrawPixelInfo->y -= top; return newDrawPixelInfo; } rct2_free(newDrawPixelInfo); return NULL; } /*** * * rct2: 0x00684027 * * ebp used to be a parameter but it is always zero * left : eax * top : ebx * width : ecx * height : edx * x_start: edi * y_start: esi */ void gfx_draw_rain(int left, int top, int width, int height, sint32 x_start, sint32 y_start){ uint8* pattern = RCT2_GLOBAL(RCT2_ADDRESS_RAIN_PATTERN, uint8*); uint8 pattern_x_space = *pattern++; uint8 pattern_y_space = *pattern++; uint8 pattern_start_x_offset = x_start % pattern_x_space; uint8 pattern_start_y_offset = y_start % pattern_y_space;; rct_drawpixelinfo* dpi = RCT2_ADDRESS(RCT2_ADDRESS_SCREEN_DPI, rct_drawpixelinfo); uint32 pixel_offset = (dpi->pitch + dpi->width)*top + left; uint8 pattern_y_pos = pattern_start_y_offset; //Stores the colours of changed pixels uint32* pixel_store = RCT2_ADDRESS(RCT2_ADDRESS_RAIN_PIXEL_STORE, uint32); pixel_store += RCT2_GLOBAL(RCT2_ADDRESS_NO_RAIN_PIXELS, uint32); for (; height != 0; height--){ uint8 pattern_x = pattern[pattern_y_pos * 2]; if (pattern_x != 0xFF){ if (RCT2_GLOBAL(0x9AC00C, uint32) <= 0x1F38){ int final_pixel_offset = width + pixel_offset; int x_pixel_offset = pixel_offset; x_pixel_offset += ((uint8)(pattern_x - pattern_start_x_offset)) % pattern_x_space; uint8 pattern_pixel = pattern[pattern_y_pos * 2 + 1]; for (; x_pixel_offset < final_pixel_offset; x_pixel_offset += pattern_x_space){ uint8 current_pixel = dpi->bits[x_pixel_offset]; dpi->bits[x_pixel_offset] = pattern_pixel; RCT2_GLOBAL(RCT2_ADDRESS_NO_RAIN_PIXELS, uint32)++; //Store colour and position *pixel_store++ = (x_pixel_offset << 8) | current_pixel; } } } pixel_offset += dpi->pitch + dpi->width; pattern_y_pos++; pattern_y_pos %= pattern_y_space; } } /** * * rct2: 0x006843DC */ void redraw_peep_and_rain() { if (RCT2_GLOBAL(0x009ABDF2, uint32) != 0) { int sprite = RCT2_GLOBAL(RCT2_ADDRESS_PICKEDUP_PEEP_SPRITE, sint32); if (sprite != -1) { sprite = sprite & 0x7FFFF; rct_g1_element *g1_elements = &RCT2_ADDRESS(RCT2_ADDRESS_G1_ELEMENTS, rct_g1_element)[sprite]; int left = RCT2_GLOBAL(RCT2_ADDRESS_PICKEDUP_PEEP_X, sint16) + g1_elements->x_offset; int top = RCT2_GLOBAL(RCT2_ADDRESS_PICKEDUP_PEEP_Y, sint16) + g1_elements->y_offset; int right = left + g1_elements->width; int bottom = top + g1_elements->height; gfx_set_dirty_blocks(left, top, right, bottom); } int rain_no_pixels = RCT2_GLOBAL(RCT2_ADDRESS_NO_RAIN_PIXELS, uint32); if (rain_no_pixels == 0) { return; } rct_window *window = window_get_main(); uint32 numPixels = window->width * window->height; uint32 *rain_pixels = RCT2_ADDRESS(RCT2_ADDRESS_RAIN_PIXEL_STORE, uint32); if (rain_pixels) { uint8 *screen_pixels = RCT2_ADDRESS(RCT2_ADDRESS_SCREEN_DPI, rct_drawpixelinfo)->bits; for (int i = 0; i < rain_no_pixels; i++) { uint32 pixel = rain_pixels[i]; //HACK if (pixel >> 8 > numPixels) { log_verbose("Pixel error, skipping rain draw in this frame"); break; } screen_pixels[pixel >> 8] = pixel & 0xFF; } RCT2_GLOBAL(0x009E2C78, uint32) = 1; } } RCT2_GLOBAL(RCT2_ADDRESS_NO_RAIN_PIXELS, uint32) = 0; }
kevinburke/OpenRCT2
src/drawing/drawing.c
C
gpl-3.0
16,641
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2022 Cppcheck team. * * 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 "reverseanalyzer.h" #include "analyzer.h" #include "astutils.h" #include "errortypes.h" #include "forwardanalyzer.h" #include "mathlib.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "valueptr.h" #include <algorithm> #include <cstddef> #include <string> #include <tuple> #include <utility> #include <vector> struct ReverseTraversal { ReverseTraversal(const ValuePtr<Analyzer>& analyzer, const Settings* settings) : analyzer(analyzer), settings(settings) {} ValuePtr<Analyzer> analyzer; const Settings* settings; std::pair<bool, bool> evalCond(const Token* tok) { std::vector<MathLib::bigint> result = analyzer->evaluate(tok); // TODO: We should convert to bool bool checkThen = std::any_of(result.begin(), result.end(), [](int x) { return x == 1; }); bool checkElse = std::any_of(result.begin(), result.end(), [](int x) { return x == 0; }); return std::make_pair(checkThen, checkElse); } bool update(Token* tok) { Analyzer::Action action = analyzer->analyze(tok, Analyzer::Direction::Reverse); if (!action.isNone()) analyzer->update(tok, action, Analyzer::Direction::Reverse); if (action.isInconclusive() && !analyzer->lowerToInconclusive()) return false; if (action.isInvalid()) return false; return true; } Token* getParentFunction(Token* tok) { if (!tok) return nullptr; if (!tok->astParent()) return nullptr; int argn = -1; if (Token* ftok = getTokenArgumentFunction(tok, argn)) { while (!Token::Match(ftok, "(|{")) { if (!ftok) return nullptr; if (ftok->index() >= tok->index()) return nullptr; if (ftok->link()) ftok = ftok->link()->next(); else ftok = ftok->next(); } if (ftok == tok) return nullptr; return ftok; } return nullptr; } Token* getTopFunction(Token* tok) { if (!tok) return nullptr; if (!tok->astParent()) return tok; Token* parent = tok; Token* top = tok; while ((parent = getParentFunction(parent))) top = parent; return top; } bool updateRecursive(Token* start) { bool continueB = true; visitAstNodes(start, [&](Token* tok) { const Token* parent = tok->astParent(); while (Token::simpleMatch(parent, ":")) parent = parent->astParent(); if (isUnevaluated(tok) || isDeadCode(tok, parent)) return ChildrenToVisit::none; continueB &= update(tok); if (continueB) return ChildrenToVisit::op1_and_op2; else return ChildrenToVisit::done; }); return continueB; } Analyzer::Action analyzeRecursive(const Token* start) { Analyzer::Action result = Analyzer::Action::None; visitAstNodes(start, [&](const Token* tok) { result |= analyzer->analyze(tok, Analyzer::Direction::Reverse); if (result.isModified()) return ChildrenToVisit::done; return ChildrenToVisit::op1_and_op2; }); return result; } Analyzer::Action analyzeRange(const Token* start, const Token* end) { Analyzer::Action result = Analyzer::Action::None; for (const Token* tok = start; tok && tok != end; tok = tok->next()) { Analyzer::Action action = analyzer->analyze(tok, Analyzer::Direction::Reverse); if (action.isModified()) return action; result |= action; } return result; } Token* isDeadCode(Token* tok, const Token* end = nullptr) { int opSide = 0; for (; tok && tok->astParent(); tok = tok->astParent()) { if (tok == end) break; Token* parent = tok->astParent(); if (Token::simpleMatch(parent, ":")) { if (astIsLHS(tok)) opSide = 1; else if (astIsRHS(tok)) opSide = 2; else opSide = 0; } if (tok != parent->astOperand2()) continue; if (Token::simpleMatch(parent, ":")) parent = parent->astParent(); if (!Token::Match(parent, "%oror%|&&|?")) continue; Token* condTok = parent->astOperand1(); if (!condTok) continue; bool checkThen, checkElse; std::tie(checkThen, checkElse) = evalCond(condTok); if (parent->str() == "?") { if (checkElse && opSide == 1) return parent; if (checkThen && opSide == 2) return parent; } if (!checkThen && parent->str() == "&&") return parent; if (!checkElse && parent->str() == "||") return parent; } return nullptr; } void traverse(Token* start, const Token* end = nullptr) { if (start == end) return; std::size_t i = start->index(); for (Token* tok = start->previous(); succeeds(tok, end); tok = tok->previous()) { if (tok->index() >= i) throw InternalError(tok, "Cyclic reverse analysis."); i = tok->index(); if (tok == start || (tok->str() == "{" && (tok->scope()->type == Scope::ScopeType::eFunction || tok->scope()->type == Scope::ScopeType::eLambda))) { const Function* f = tok->scope()->function; if (f && f->isConstructor()) { if (const Token* initList = f->constructorMemberInitialization()) traverse(tok->previous(), tok->tokAt(initList->index() - tok->index())); } break; } if (Token::Match(tok, "return|break|continue")) break; if (Token::Match(tok, "%name% :")) break; if (Token::simpleMatch(tok, ":")) continue; // Evaluate LHS of assignment before RHS if (Token* assignTok = assignExpr(tok)) { // If assignTok has broken ast then stop if (!assignTok->astOperand1() || !assignTok->astOperand2()) break; Token* assignTop = assignTok; bool continueB = true; while (assignTop->isAssignmentOp()) { if (!Token::Match(assignTop->astOperand1(), "%assign%")) { continueB &= updateRecursive(assignTop->astOperand1()); } if (!assignTop->astParent()) break; assignTop = assignTop->astParent(); } // Is assignment in dead code if (Token* parent = isDeadCode(assignTok)) { tok = parent; continue; } // Simple assign if (assignTok->astParent() == assignTop || assignTok == assignTop) { Analyzer::Action rhsAction = analyzer->analyze(assignTok->astOperand2(), Analyzer::Direction::Reverse); Analyzer::Action lhsAction = analyzer->analyze(assignTok->astOperand1(), Analyzer::Direction::Reverse); // Assignment from if (rhsAction.isRead() && !lhsAction.isInvalid() && assignTok->astOperand1()->exprId() > 0) { const std::string info = "Assignment from '" + assignTok->expressionString() + "'"; ValuePtr<Analyzer> a = analyzer->reanalyze(assignTok->astOperand1(), info); if (a) { valueFlowGenericForward(nextAfterAstRightmostLeaf(assignTok->astOperand2()), assignTok->astOperand2()->scope()->bodyEnd, a, settings); } // Assignment to } else if (lhsAction.matches() && !assignTok->astOperand2()->hasKnownIntValue() && assignTok->astOperand2()->exprId() > 0 && isConstExpression(assignTok->astOperand2(), settings->library, true, true)) { const std::string info = "Assignment to '" + assignTok->expressionString() + "'"; ValuePtr<Analyzer> a = analyzer->reanalyze(assignTok->astOperand2(), info); if (a) { valueFlowGenericForward(nextAfterAstRightmostLeaf(assignTok->astOperand2()), assignTok->astOperand2()->scope()->bodyEnd, a, settings); valueFlowGenericReverse(assignTok->astOperand1()->previous(), end, a, settings); } } } if (!continueB) break; if (!updateRecursive(assignTop->astOperand2())) break; tok = previousBeforeAstLeftmostLeaf(assignTop)->next(); continue; } if (tok->str() == ")" && !isUnevaluated(tok)) { if (Token* top = getTopFunction(tok->link())) { if (!updateRecursive(top)) break; Token* next = previousBeforeAstLeftmostLeaf(top); if (next && precedes(next, tok)) tok = next->next(); } continue; } if (tok->str() == "}") { Token* condTok = getCondTokFromEnd(tok); if (!condTok) break; Analyzer::Action condAction = analyzeRecursive(condTok); const bool inLoop = condTok->astTop() && Token::Match(condTok->astTop()->previous(), "for|while ("); // Evaluate condition of for and while loops first if (inLoop) { if (condAction.isModified()) break; valueFlowGenericForward(condTok, analyzer, settings); } Token* thenEnd; const bool hasElse = Token::simpleMatch(tok->link()->tokAt(-2), "} else {"); if (hasElse) { thenEnd = tok->link()->tokAt(-2); } else { thenEnd = tok; } Analyzer::Action thenAction = analyzeRange(thenEnd->link(), thenEnd); Analyzer::Action elseAction = Analyzer::Action::None; if (hasElse) { elseAction = analyzeRange(tok->link(), tok); } if (thenAction.isModified() && inLoop) break; else if (thenAction.isModified() && !elseAction.isModified()) analyzer->assume(condTok, hasElse); else if (elseAction.isModified() && !thenAction.isModified()) analyzer->assume(condTok, !hasElse); // Bail if one of the branches are read to avoid FPs due to over constraints else if (thenAction.isIdempotent() || elseAction.isIdempotent() || thenAction.isRead() || elseAction.isRead()) break; if (thenAction.isInvalid() || elseAction.isInvalid()) break; if (!thenAction.isModified() && !elseAction.isModified()) valueFlowGenericForward(condTok, analyzer, settings); else if (condAction.isRead()) break; // If the condition modifies the variable then bail if (condAction.isModified()) break; tok = condTok->astTop()->previous(); continue; } if (tok->str() == "{") { if (tok->previous() && (Token::simpleMatch(tok->previous(), "do") || (tok->strAt(-1) == ")" && Token::Match(tok->linkAt(-1)->previous(), "for|while (")))) { Analyzer::Action action = analyzeRange(tok, tok->link()); if (action.isModified()) break; } Token* condTok = getCondTokFromEnd(tok->link()); if (condTok) { Analyzer::Result r = valueFlowGenericForward(condTok, analyzer, settings); if (r.action.isModified()) break; } if (Token::simpleMatch(tok->tokAt(-2), "} else {")) tok = tok->linkAt(-2); if (Token::simpleMatch(tok->previous(), ") {")) tok = tok->previous()->link(); continue; } if (Token* next = isUnevaluated(tok)) { tok = next; continue; } if (Token* parent = isDeadCode(tok)) { tok = parent; continue; } if (tok->str() == "case") { const Scope* scope = tok->scope(); while (scope && scope->type != Scope::eSwitch) scope = scope->nestedIn; if (!scope || scope->type != Scope::eSwitch) break; tok = tok->tokAt(scope->bodyStart->index() - tok->index() - 1); continue; } if (!update(tok)) break; } } static Token* assignExpr(Token* tok) { if (Token::Match(tok, ")|}")) tok = tok->link(); while (tok->astParent() && (astIsRHS(tok) || !tok->astParent()->isBinaryOp())) { if (tok->astParent()->isAssignmentOp()) return tok->astParent(); tok = tok->astParent(); } return nullptr; } static Token* isUnevaluated(Token* tok) { if (Token::Match(tok, ")|>") && tok->link()) { Token* start = tok->link(); if (Token::Match(start->previous(), "sizeof|decltype (")) return start->previous(); if (Token::simpleMatch(start, "<")) return start; } return nullptr; } }; void valueFlowGenericReverse(Token* start, const ValuePtr<Analyzer>& a, const Settings* settings) { ReverseTraversal rt{a, settings}; rt.traverse(start); } void valueFlowGenericReverse(Token* start, const Token* end, const ValuePtr<Analyzer>& a, const Settings* settings) { ReverseTraversal rt{a, settings}; rt.traverse(start, end); }
danmar/cppcheck
lib/reverseanalyzer.cpp
C++
gpl-3.0
16,215
"""Multidict implementation. HTTP Headers and URL query string require specific data structure: multidict. It behaves mostly like a dict but it can have several values for the same key. """ import os __all__ = ('MultiDictProxy', 'CIMultiDictProxy', 'MultiDict', 'CIMultiDict', 'upstr', 'istr') __version__ = '2.1.5' if bool(os.environ.get('MULTIDICT_NO_EXTENSIONS')): from ._multidict_py import (MultiDictProxy, CIMultiDictProxy, MultiDict, CIMultiDict, upstr, istr) else: try: from ._multidict import (MultiDictProxy, CIMultiDictProxy, MultiDict, CIMultiDict, upstr, istr) except ImportError: # pragma: no cover from ._multidict_py import (MultiDictProxy, CIMultiDictProxy, MultiDict, CIMultiDict, upstr, istr)
DivineHime/seishirou
lib/multidict/__init__.py
Python
gpl-3.0
1,162
<!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/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>DNS Cache: Catch::CompositeGenerator&lt; T &gt; Class Template Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">DNS Cache &#160;<span id="projectnumber">0.1</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('class_catch_1_1_composite_generator.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="class_catch_1_1_composite_generator-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">Catch::CompositeGenerator&lt; T &gt; Class Template Reference</div> </div> </div><!--header--> <div class="contents"> <p><code>#include &lt;<a class="el" href="catch_8hpp_source.html">catch.hpp</a>&gt;</code></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:a923398b140371d1783858766864a1af5"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_catch_1_1_composite_generator.html#a923398b140371d1783858766864a1af5">CompositeGenerator</a> ()</td></tr> <tr class="separator:a923398b140371d1783858766864a1af5"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a21a7070a00e4a6fe021294c356692692"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_catch_1_1_composite_generator.html#a21a7070a00e4a6fe021294c356692692">CompositeGenerator</a> (<a class="el" href="class_catch_1_1_composite_generator.html">CompositeGenerator</a> &amp;other)</td></tr> <tr class="separator:a21a7070a00e4a6fe021294c356692692"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ac3c57cf4ca5472f440bf71e2936bcd4a"><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_catch_1_1_composite_generator.html">CompositeGenerator</a> &amp;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_catch_1_1_composite_generator.html#ac3c57cf4ca5472f440bf71e2936bcd4a">setFileInfo</a> (const char *fileInfo)</td></tr> <tr class="separator:ac3c57cf4ca5472f440bf71e2936bcd4a"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a5766205abd7004c508c20ddbb5e5555e"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_catch_1_1_composite_generator.html#a5766205abd7004c508c20ddbb5e5555e">~CompositeGenerator</a> ()</td></tr> <tr class="separator:a5766205abd7004c508c20ddbb5e5555e"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a83d6c941e2e735b9528e6e832f7b76e7"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_catch_1_1_composite_generator.html#a83d6c941e2e735b9528e6e832f7b76e7">operator T</a> () const</td></tr> <tr class="separator:a83d6c941e2e735b9528e6e832f7b76e7"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:af3774d42ad2d3453d089ca599efe0517"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_catch_1_1_composite_generator.html#af3774d42ad2d3453d089ca599efe0517">add</a> (const <a class="el" href="struct_catch_1_1_i_generator.html">IGenerator</a>&lt; T &gt; *generator)</td></tr> <tr class="separator:af3774d42ad2d3453d089ca599efe0517"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a2e03f42df85cdd238aabd77a80b075d5"><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_catch_1_1_composite_generator.html">CompositeGenerator</a> &amp;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_catch_1_1_composite_generator.html#a2e03f42df85cdd238aabd77a80b075d5">then</a> (<a class="el" href="class_catch_1_1_composite_generator.html">CompositeGenerator</a> &amp;other)</td></tr> <tr class="separator:a2e03f42df85cdd238aabd77a80b075d5"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aefdc11bcfccdf07d2db5f0da3ed8758c"><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_catch_1_1_composite_generator.html">CompositeGenerator</a> &amp;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_catch_1_1_composite_generator.html#aefdc11bcfccdf07d2db5f0da3ed8758c">then</a> (T value)</td></tr> <tr class="separator:aefdc11bcfccdf07d2db5f0da3ed8758c"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <h2 class="groupheader">Constructor &amp; Destructor Documentation</h2> <a id="a923398b140371d1783858766864a1af5"></a> <h2 class="memtitle"><span class="permalink"><a href="#a923398b140371d1783858766864a1af5">&#9670;&nbsp;</a></span>CompositeGenerator() <span class="overload">[1/2]</span></h2> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename T&gt; </div> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname"><a class="el" href="class_catch_1_1_composite_generator.html">Catch::CompositeGenerator</a>&lt; T &gt;::<a class="el" href="class_catch_1_1_composite_generator.html">CompositeGenerator</a> </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="a21a7070a00e4a6fe021294c356692692"></a> <h2 class="memtitle"><span class="permalink"><a href="#a21a7070a00e4a6fe021294c356692692">&#9670;&nbsp;</a></span>CompositeGenerator() <span class="overload">[2/2]</span></h2> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename T&gt; </div> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname"><a class="el" href="class_catch_1_1_composite_generator.html">Catch::CompositeGenerator</a>&lt; T &gt;::<a class="el" href="class_catch_1_1_composite_generator.html">CompositeGenerator</a> </td> <td>(</td> <td class="paramtype"><a class="el" href="class_catch_1_1_composite_generator.html">CompositeGenerator</a>&lt; T &gt; &amp;&#160;</td> <td class="paramname"><em>other</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="a5766205abd7004c508c20ddbb5e5555e"></a> <h2 class="memtitle"><span class="permalink"><a href="#a5766205abd7004c508c20ddbb5e5555e">&#9670;&nbsp;</a></span>~CompositeGenerator()</h2> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename T&gt; </div> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname"><a class="el" href="class_catch_1_1_composite_generator.html">Catch::CompositeGenerator</a>&lt; T &gt;::~<a class="el" href="class_catch_1_1_composite_generator.html">CompositeGenerator</a> </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <h2 class="groupheader">Member Function Documentation</h2> <a id="af3774d42ad2d3453d089ca599efe0517"></a> <h2 class="memtitle"><span class="permalink"><a href="#af3774d42ad2d3453d089ca599efe0517">&#9670;&nbsp;</a></span>add()</h2> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename T&gt; </div> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">void <a class="el" href="class_catch_1_1_composite_generator.html">Catch::CompositeGenerator</a>&lt; T &gt;::add </td> <td>(</td> <td class="paramtype">const <a class="el" href="struct_catch_1_1_i_generator.html">IGenerator</a>&lt; T &gt; *&#160;</td> <td class="paramname"><em>generator</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="a83d6c941e2e735b9528e6e832f7b76e7"></a> <h2 class="memtitle"><span class="permalink"><a href="#a83d6c941e2e735b9528e6e832f7b76e7">&#9670;&nbsp;</a></span>operator T()</h2> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename T&gt; </div> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname"><a class="el" href="class_catch_1_1_composite_generator.html">Catch::CompositeGenerator</a>&lt; T &gt;::operator T </td> <td>(</td> <td class="paramname"></td><td>)</td> <td> const</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="ac3c57cf4ca5472f440bf71e2936bcd4a"></a> <h2 class="memtitle"><span class="permalink"><a href="#ac3c57cf4ca5472f440bf71e2936bcd4a">&#9670;&nbsp;</a></span>setFileInfo()</h2> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename T&gt; </div> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname"><a class="el" href="class_catch_1_1_composite_generator.html">CompositeGenerator</a>&amp; <a class="el" href="class_catch_1_1_composite_generator.html">Catch::CompositeGenerator</a>&lt; T &gt;::setFileInfo </td> <td>(</td> <td class="paramtype">const char *&#160;</td> <td class="paramname"><em>fileInfo</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="a2e03f42df85cdd238aabd77a80b075d5"></a> <h2 class="memtitle"><span class="permalink"><a href="#a2e03f42df85cdd238aabd77a80b075d5">&#9670;&nbsp;</a></span>then() <span class="overload">[1/2]</span></h2> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename T&gt; </div> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname"><a class="el" href="class_catch_1_1_composite_generator.html">CompositeGenerator</a>&amp; <a class="el" href="class_catch_1_1_composite_generator.html">Catch::CompositeGenerator</a>&lt; T &gt;::then </td> <td>(</td> <td class="paramtype"><a class="el" href="class_catch_1_1_composite_generator.html">CompositeGenerator</a>&lt; T &gt; &amp;&#160;</td> <td class="paramname"><em>other</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <a id="aefdc11bcfccdf07d2db5f0da3ed8758c"></a> <h2 class="memtitle"><span class="permalink"><a href="#aefdc11bcfccdf07d2db5f0da3ed8758c">&#9670;&nbsp;</a></span>then() <span class="overload">[2/2]</span></h2> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename T&gt; </div> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname"><a class="el" href="class_catch_1_1_composite_generator.html">CompositeGenerator</a>&amp; <a class="el" href="class_catch_1_1_composite_generator.html">Catch::CompositeGenerator</a>&lt; T &gt;::then </td> <td>(</td> <td class="paramtype">T&#160;</td> <td class="paramname"><em>value</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <hr/>The documentation for this class was generated from the following file:<ul> <li>dns-cache/tests/<a class="el" href="catch_8hpp_source.html">catch.hpp</a></li> </ul> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="namespace_catch.html">Catch</a></li><li class="navelem"><a class="el" href="class_catch_1_1_composite_generator.html">CompositeGenerator</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li> </ul> </div> </body> </html>
tomesm/dns-cache
doc/html/class_catch_1_1_composite_generator.html
HTML
gpl-3.0
16,042
# Heightmap LoD We want to vary heightmap resolution based on distance. Easiest way to do this is probably just to line up and swap out varying-resolution heightmaps as needed. (A fun wrinkle: our heightmaps are rectangular, despite being meshes of equilateral triangles, so the edges will be fun to line up.) Our approach of choice is to have a rectangular grid of tiles at varying resolutions (but all the same size). Seams are TBD. ## API for managed, LoD-tiled heightmaps We need to be able to * Turn an array of tiles into one or more renderable meshes * Swap out low- and high-resolution tiles on a frame-by-frame basis with high performance Based on this, it seems like we need to * Provide an iterable over internally-managed gpu::Models * Provide a method to update LoD based on physical location **BORROW CHECKER ALERT** Nope. The lifetimes immediately become unmanageable because it's hard to tell the borrow checker that the renderer doesn't borrow these objects for very long. Thus, we end up with the following: * A `Renderable` trait with a `render` method, implemented for `gpu::ModelInstance` * An implementation of `Renderable` for `SimpleHeightmap` which turns the heightmap into a `ModelInstance` and calls `render` on it. Thus for our in-memory LoD heightmap, we want * A high-resolution `SimpleHeightmapGeometry` providing physics and a source for tiles * A way to cut that `SimpleHeightmapGeometry` into tiles for rendering * A way to scale the resolution of tiles * A `Renderable` implementation that iterates over all tiles Stuff shared with `SimpleHeightmap`: * Actually, everything except `model` and `Heightmap.update_lod` Conclusion: stuff the idea of keeping them seperate, there's no good reason to. A few useful assumptions to make: * We'll make tiles square-ish. (The fact that they're rectangular triangle meshes screws with this. They'll have the same number of rows and columns, which makes the physical geometry about 1:.866.) * The default tile size is 256x256. This allows us to downgrade our indices to u16, saving *massive boatloads* of memory. ## Selecting a LoD We would like to have the following properties: * LoD increases (resolution decreases) with distance from the camera * We (mostly) avoid dropping triangles at the edges of a tile Note that at distance `d` from the camera, for each triangle to fill approximately the same number of pixels, it should be scaled to `d^2` (because it's notionally on the inside of a spherical shell, with area proportional to the square of radius). This gives us another desirable property: * LoD increases approximately quadratically This doesn't play very well with the second desirable property, which requires that LoD evenly divide tile size (that is, be a power of two, since our tile size is 2^8). We could clamp quadratic LoD values to the next lowest power of two, e.g. Quadratic: 1 4 9 16 25 36 49 64 81 100 Exponential: 1 4 8 16 16 32 32 64 64 64 etc. (Note that we never have a LoD of 2, because the quadratic series grows too fast early on. Should we care?) Or, alternatively, we could pick a nicer tile size with more prime factors, but 256x256 makes optimial use of our index space. (252 has prime factors 2, 3, 7, letting us hit 1, 4, 9, 14, 21, 36, 42, 63, 63, 84—better, but heinous to calculate on the fly and probably not better enough that we should care.) ### Calculating distance of a tile from the camera Ideally, we'd like to know the distance of the *closest* point on the tile. (If the camera is actually over the tile, LoD should always be 1. Ideally this shouldn't need to be special-cased.) Failing that, either the closest corner or center of the tile seem like reasonable distance targets. Center is easy to calculate and doesn't require any thought, so let's go with that. We want to scale things so that from the center of one tile to the center of an adjacent tile is distance 2 (so the LoD of the adjacent tile is 4). For this the ideal algorithm seems to be something like floor(len(camera - tile_center) / (tile_size * scale)) + 1 Then to get LoD min_exp(d^2) Notable thoughts: if you're not centered in your current tile, the next tile adjacent to the closer side will be rendered at LoD 1. Also, this will act up along diagonals; should we maybe use min-axial distance (that is, min(abs(cam\_x - tile\_x), abs(cam\_z - tile\_z))) rather than Euclidean? ## Updating the LoD Updating is an expensive operation, so we want to do it as infrequently as possible. (Actually, even more than that, we want to make it efficient, which will ultimately entail updating as few tiles as possible, but that's a project for later.) Thus, we want to regenerate only when LoDs would actually change. (In fact, only when LoDs of *adjacent* tiles would actually change; more distant tiles don't matter nearly as much.) If adjacent tiles are also at LoD 1 (not currently guaranteed by our proposed distance scheme, but can easily be done by dropping it one and flooring at 1 (so the current tile isn't at LoD 0, which will cause problems)), an acceptable approximation is to update on crossing a tile boundary. Alternatively, since that will screw up our scaling, we could update on crossing a *half-tile* boundary. This simply requires storing in the SimpleHeightmap struct which half-tile (quarter-tile, technically) the LoD is currently centered around and updating if the camera is over a different half-tile. Alternatively, since that lacks hysteresis (the camera can wander back and forth over a half-tile boundary, triggering an update at each crossover), consider overlapping whole-tile-sized areas on half-tile boundaries, e.g. +-----+-----+ |a |b | | +--+--+ | | |c | | +--+ + +--+ |d | |e | | +-----+ | | | | +-----+-----+ where `c` overlaps with all of `a, b, d, e`. Then if the camera crosses from `a` to `ac`, no update is triggered (since it remains in `a` as well); however, if it then crosses into `bc` an update will occur (since it is no longer in `a`, the previous area of record) into `c` but not if it crosses back into `ac` (since it's still in `c`). Thus, whever crossing a half-tile boundary * If the camera is still within the area of record, no update occurs. Track which sub-area (e.g. `ac`) contains the camera. * If the camera is out of the area of record, find which area overlaps with the previous sub-area (e.g. if we move from sub-area `ac` to `bc`, the overlap is area `c`), store that as the new area of record, and update LoDs. This will still break down on diagonal transitions unless we maintain whole-tile-sized areas of record for *every* half-tile sub-area, which results in four overlaps on any given sub-area: +-----+--+ |a |b | | |--+--+--+ |c |d | | +--+--+--+ | | | | +--+--+--+ The center square in this diagram is part of areas `a`, `b`, `c` and `d`. This makes determining overlap for step 2 difficult, since we may still be overlapping with two areas. It's probably acceptable to chose based on direction of movement (e.g. if we move from area `d` sub-area `abcd` to `ab`, we switch from area `d` to `b` instead of `a` because we're moving north). If there's only one overlap (which will only happen on a diagonal transition), obviously we pick that one. ### Formalizing the above Given a SimpleHeightmap with scale `s`, * An area is defined by its northwest corner (that is, it's corner of minimal `x` and `z`). It has width and height `s` and is evenly divisible by `s/2`. * A sub-area is defined by its northwest corner. It has width and height `s/2` and is evenly divisible by `s/2`. * Given a sub-area at `sx, sz`, the corresponding overlapping areas are * `sx - s/2`, `sz - s/2` * `sx - s/2`, `sz` * `sx`, `sz - s/2` * `sx`, `sz` * If the camera is over a new sub-area, * If the sub-area does not overlap with the previous area, * If the new sub-area is north/south of the previous one, update the area to the next one north/south and update LoDs * If the new sub-area is east/west of the previous one, update the area to the next one east/west and update LoDs * Otherwise, this is a diagonal transition; update the area to the only one overlapping and update LoDs * Update the stored sub-area Note: remember to multiply all the z-axis values by `ROW_SPACING`.
whbboyd/gl-demo
heightmap-lod-notes.md
Markdown
gpl-3.0
8,411
package net.project104.civyshkbirds; import android.view.ViewGroup; import net.project104.swartznetlibrary.NetNode; import java.lang.ref.WeakReference; import java.net.InetAddress; public class NetPlayer extends NetNode { private WeakReference<ViewGroup> mWidget; public NetPlayer(InetAddress address, int port){ super(address, port); } }
civyshk/104birds
app/src/main/java/net/project104/civyshkbirds/NetPlayer.java
Java
gpl-3.0
365
/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo * This benchmark is part of SWSC */ #include <assert.h> #include <stdint.h> #include <stdatomic.h> #include <pthread.h> atomic_int vars[3]; atomic_int atom_1_r1_1; void *t0(void *arg){ label_1:; atomic_store_explicit(&vars[0], 2, memory_order_seq_cst); atomic_store_explicit(&vars[1], 1, memory_order_seq_cst); return NULL; } void *t1(void *arg){ label_2:; int v2_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst); atomic_store_explicit(&vars[1], 2, memory_order_seq_cst); int v4_r4 = atomic_load_explicit(&vars[1], memory_order_seq_cst); int v5_r5 = v4_r4 ^ v4_r4; int v8_r6 = atomic_load_explicit(&vars[2+v5_r5], memory_order_seq_cst); int v10_r8 = atomic_load_explicit(&vars[2], memory_order_seq_cst); int v11_r9 = v10_r8 ^ v10_r8; int v12_r9 = v11_r9 + 1; atomic_store_explicit(&vars[0], v12_r9, memory_order_seq_cst); int v20 = (v2_r1 == 1); atomic_store_explicit(&atom_1_r1_1, v20, memory_order_seq_cst); return NULL; } int main(int argc, char *argv[]){ pthread_t thr0; pthread_t thr1; atomic_init(&vars[2], 0); atomic_init(&vars[1], 0); atomic_init(&vars[0], 0); atomic_init(&atom_1_r1_1, 0); pthread_create(&thr0, NULL, t0, NULL); pthread_create(&thr1, NULL, t1, NULL); pthread_join(thr0, NULL); pthread_join(thr1, NULL); int v13 = atomic_load_explicit(&vars[0], memory_order_seq_cst); int v14 = (v13 == 2); int v15 = atomic_load_explicit(&vars[1], memory_order_seq_cst); int v16 = (v15 == 2); int v17 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); int v18_conj = v16 & v17; int v19_conj = v14 & v18_conj; if (v19_conj == 1) assert(0); return 0; }
nidhugg/nidhugg
tests/litmus/C-tests/S+PPO511.c
C
gpl-3.0
1,714
/* * Copyright (c) 2015 MediaTek Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * 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. */ #include <drm/drmP.h> #include <drm/drm_gem.h> #include <linux/dma-buf.h> #include "mtk_drm_drv.h" #include "mtk_drm_gem.h" static struct mtk_drm_gem_obj *mtk_drm_gem_init(struct drm_device *dev, unsigned long size) { struct mtk_drm_gem_obj *mtk_gem_obj; int ret; size = round_up(size, PAGE_SIZE); mtk_gem_obj = kzalloc(sizeof(*mtk_gem_obj), GFP_KERNEL); if (!mtk_gem_obj) { return ERR_PTR(-ENOMEM); } ret = drm_gem_object_init(dev, &mtk_gem_obj->base, size); if (ret < 0) { DRM_ERROR("failed to initialize gem object\n"); kfree(mtk_gem_obj); return ERR_PTR(ret); } return mtk_gem_obj; } struct mtk_drm_gem_obj *mtk_drm_gem_create(struct drm_device *dev, size_t size, bool alloc_kmap) { struct mtk_drm_private *priv = dev->dev_private; struct mtk_drm_gem_obj *mtk_gem; struct drm_gem_object *obj; int ret; mtk_gem = mtk_drm_gem_init(dev, size); if (IS_ERR(mtk_gem)) { return ERR_CAST(mtk_gem); } obj = &mtk_gem->base; mtk_gem->dma_attrs = DMA_ATTR_WRITE_COMBINE; if (!alloc_kmap) { mtk_gem->dma_attrs |= DMA_ATTR_NO_KERNEL_MAPPING; } mtk_gem->cookie = dma_alloc_attrs(priv->dma_dev, obj->size, &mtk_gem->dma_addr, GFP_KERNEL, mtk_gem->dma_attrs); if (!mtk_gem->cookie) { DRM_ERROR("failed to allocate %zx byte dma buffer", obj->size); ret = -ENOMEM; goto err_gem_free; } if (alloc_kmap) { mtk_gem->kvaddr = mtk_gem->cookie; } DRM_DEBUG_DRIVER("cookie = %p dma_addr = %pad size = %zu\n", mtk_gem->cookie, &mtk_gem->dma_addr, size); return mtk_gem; err_gem_free: drm_gem_object_release(obj); kfree(mtk_gem); return ERR_PTR(ret); } void mtk_drm_gem_free_object(struct drm_gem_object *obj) { struct mtk_drm_gem_obj *mtk_gem = to_mtk_gem_obj(obj); struct mtk_drm_private *priv = obj->dev->dev_private; if (mtk_gem->sg) { drm_prime_gem_destroy(obj, mtk_gem->sg); } else dma_free_attrs(priv->dma_dev, obj->size, mtk_gem->cookie, mtk_gem->dma_addr, mtk_gem->dma_attrs); /* release file pointer to gem object. */ drm_gem_object_release(obj); kfree(mtk_gem); } int mtk_drm_gem_dumb_create(struct drm_file *file_priv, struct drm_device *dev, struct drm_mode_create_dumb *args) { struct mtk_drm_gem_obj *mtk_gem; int ret; args->pitch = DIV_ROUND_UP(args->width * args->bpp, 8); args->size = args->pitch * args->height; mtk_gem = mtk_drm_gem_create(dev, args->size, false); if (IS_ERR(mtk_gem)) { return PTR_ERR(mtk_gem); } /* * allocate a id of idr table where the obj is registered * and handle has the id what user can see. */ ret = drm_gem_handle_create(file_priv, &mtk_gem->base, &args->handle); if (ret) { goto err_handle_create; } /* drop reference from allocate - handle holds it now. */ drm_gem_object_unreference_unlocked(&mtk_gem->base); return 0; err_handle_create: mtk_drm_gem_free_object(&mtk_gem->base); return ret; } int mtk_drm_gem_dumb_map_offset(struct drm_file *file_priv, struct drm_device *dev, uint32_t handle, uint64_t *offset) { struct drm_gem_object *obj; int ret; obj = drm_gem_object_lookup(file_priv, handle); if (!obj) { DRM_ERROR("failed to lookup gem object.\n"); return -EINVAL; } ret = drm_gem_create_mmap_offset(obj); if (ret) { goto out; } *offset = drm_vma_node_offset_addr(&obj->vma_node); DRM_DEBUG_KMS("offset = 0x%llx\n", *offset); out: drm_gem_object_unreference_unlocked(obj); return ret; } static int mtk_drm_gem_object_mmap(struct drm_gem_object *obj, struct vm_area_struct *vma) { int ret; struct mtk_drm_gem_obj *mtk_gem = to_mtk_gem_obj(obj); struct mtk_drm_private *priv = obj->dev->dev_private; /* * dma_alloc_attrs() allocated a struct page table for mtk_gem, so clear * VM_PFNMAP flag that was set by drm_gem_mmap_obj()/drm_gem_mmap(). */ vma->vm_flags &= ~VM_PFNMAP; vma->vm_pgoff = 0; ret = dma_mmap_attrs(priv->dma_dev, vma, mtk_gem->cookie, mtk_gem->dma_addr, obj->size, mtk_gem->dma_attrs); if (ret) { drm_gem_vm_close(vma); } return ret; } int mtk_drm_gem_mmap_buf(struct drm_gem_object *obj, struct vm_area_struct *vma) { int ret; ret = drm_gem_mmap_obj(obj, obj->size, vma); if (ret) { return ret; } return mtk_drm_gem_object_mmap(obj, vma); } int mtk_drm_gem_mmap(struct file *filp, struct vm_area_struct *vma) { struct drm_gem_object *obj; int ret; ret = drm_gem_mmap(filp, vma); if (ret) { return ret; } obj = vma->vm_private_data; return mtk_drm_gem_object_mmap(obj, vma); } /* * Allocate a sg_table for this GEM object. * Note: Both the table's contents, and the sg_table itself must be freed by * the caller. * Returns a pointer to the newly allocated sg_table, or an ERR_PTR() error. */ struct sg_table *mtk_gem_prime_get_sg_table(struct drm_gem_object *obj) { struct mtk_drm_gem_obj *mtk_gem = to_mtk_gem_obj(obj); struct mtk_drm_private *priv = obj->dev->dev_private; struct sg_table *sgt; int ret; sgt = kzalloc(sizeof(*sgt), GFP_KERNEL); if (!sgt) { return ERR_PTR(-ENOMEM); } ret = dma_get_sgtable_attrs(priv->dma_dev, sgt, mtk_gem->cookie, mtk_gem->dma_addr, obj->size, mtk_gem->dma_attrs); if (ret) { DRM_ERROR("failed to allocate sgt, %d\n", ret); kfree(sgt); return ERR_PTR(ret); } return sgt; } struct drm_gem_object *mtk_gem_prime_import_sg_table(struct drm_device *dev, struct dma_buf_attachment *attach, struct sg_table *sg) { struct mtk_drm_gem_obj *mtk_gem; int ret; struct scatterlist *s; unsigned int i; dma_addr_t expected; mtk_gem = mtk_drm_gem_init(dev, attach->dmabuf->size); if (IS_ERR(mtk_gem)) { return ERR_PTR(PTR_ERR(mtk_gem)); } expected = sg_dma_address(sg->sgl); for_each_sg(sg->sgl, s, sg->nents, i) { if (sg_dma_address(s) != expected) { DRM_ERROR("sg_table is not contiguous"); ret = -EINVAL; goto err_gem_free; } expected = sg_dma_address(s) + sg_dma_len(s); } mtk_gem->dma_addr = sg_dma_address(sg->sgl); mtk_gem->sg = sg; return &mtk_gem->base; err_gem_free: kfree(mtk_gem); return ERR_PTR(ret); }
williamfdevine/PrettyLinux
drivers/gpu/drm/mediatek/mtk_drm_gem.c
C
gpl-3.0
6,568
package de.westnordost.streetcomplete.quests.bikeway; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import java.util.Map; import javax.inject.Inject; import de.westnordost.osmapi.map.data.BoundingBox; import de.westnordost.osmapi.map.data.Element; import de.westnordost.streetcomplete.R; import de.westnordost.streetcomplete.data.meta.OsmTaggings; import de.westnordost.streetcomplete.data.osm.AOsmElementQuestType; import de.westnordost.streetcomplete.data.osm.Countries; import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder; import de.westnordost.streetcomplete.data.osm.download.MapDataWithGeometryHandler; import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao; import de.westnordost.streetcomplete.data.osm.tql.OverpassQLUtil; import de.westnordost.streetcomplete.quests.AbstractQuestAnswerFragment; import static de.westnordost.streetcomplete.quests.bikeway.Cycleway.EXCLUSIVE_LANE; import static de.westnordost.streetcomplete.quests.bikeway.Cycleway.ADVISORY_LANE; public class AddCycleway extends AOsmElementQuestType { private final OverpassMapDataDao overpassServer; private static final int MIN_DIST_TO_CYCLEWAYS = 15; //m @Inject public AddCycleway(OverpassMapDataDao overpassServer) { this.overpassServer = overpassServer; } @Override public void applyAnswerTo(Bundle answer, StringMapChangesBuilder changes) { String right = answer.getString(AddCyclewayForm.CYCLEWAY_RIGHT); String left = answer.getString(AddCyclewayForm.CYCLEWAY_LEFT); Cycleway cyclewayRight = right != null ? Cycleway.valueOf(right) : null; Cycleway cyclewayLeft = left != null ? Cycleway.valueOf(left) : null; int cyclewayRightDir = answer.getInt(AddCyclewayForm.CYCLEWAY_RIGHT_DIR); int cyclewayLeftDir = answer.getInt(AddCyclewayForm.CYCLEWAY_LEFT_DIR); boolean bothSidesAreSame = cyclewayLeft == cyclewayRight && cyclewayRightDir == 0 && cyclewayLeftDir == 0; if(bothSidesAreSame) { applyCyclewayAnswerTo(cyclewayLeft, Side.BOTH, 0, changes); } else { if(cyclewayLeft != null) { applyCyclewayAnswerTo(cyclewayLeft, Side.LEFT, cyclewayLeftDir, changes); } if(cyclewayRight != null) { applyCyclewayAnswerTo(cyclewayRight, Side.RIGHT, cyclewayRightDir, changes); } } applySidewalkAnswerTo(cyclewayLeft, cyclewayRight, changes); if(answer.getBoolean(AddCyclewayForm.IS_ONEWAY_NOT_FOR_CYCLISTS)) { changes.addOrModify("oneway:bicycle", "no"); } } private void applySidewalkAnswerTo(Cycleway cyclewayLeft, Cycleway cyclewayRight, StringMapChangesBuilder changes) { boolean hasSidewalkLeft = cyclewayLeft != null && cyclewayLeft.isOnSidewalk(); boolean hasSidewalkRight = cyclewayRight != null && cyclewayRight.isOnSidewalk(); Side side; if(hasSidewalkLeft && hasSidewalkRight) side = Side.BOTH; else if(hasSidewalkLeft) side = Side.LEFT; else if(hasSidewalkRight) side = Side.RIGHT; else side = null; if(side != null) { changes.addOrModify("sidewalk", side.value); } } private enum Side { LEFT("left"), RIGHT("right"), BOTH("both"); public final String value; Side(String value) { this.value = value; } } private void applyCyclewayAnswerTo(Cycleway cycleway, Side side, int dir, StringMapChangesBuilder changes) { String directionValue = null; if(dir != 0) directionValue = dir > 0 ? "yes" : "-1"; String cyclewayKey = "cycleway:" + side.value; switch (cycleway) { case NONE: case NONE_NO_ONEWAY: changes.add(cyclewayKey, "no"); break; case EXCLUSIVE_LANE: case ADVISORY_LANE: case LANE_UNSPECIFIED: changes.add(cyclewayKey, "lane"); if(directionValue != null) { changes.addOrModify(cyclewayKey + ":oneway", directionValue); } if(cycleway == EXCLUSIVE_LANE) changes.addOrModify(cyclewayKey + ":lane", "exclusive"); else if(cycleway == ADVISORY_LANE) changes.addOrModify(cyclewayKey + ":lane", "advisory"); break; case TRACK: changes.add(cyclewayKey, "track"); if(directionValue != null) { changes.addOrModify(cyclewayKey + ":oneway", directionValue); } break; case DUAL_TRACK: changes.add(cyclewayKey, "track"); changes.addOrModify(cyclewayKey + ":oneway", "no"); break; case DUAL_LANE: changes.add(cyclewayKey, "lane"); changes.addOrModify(cyclewayKey + ":oneway", "no"); changes.addOrModify(cyclewayKey + ":lane", "exclusive"); break; case SIDEWALK_EXPLICIT: // https://wiki.openstreetmap.org/wiki/File:Z240GemeinsamerGehundRadweg.jpeg changes.add(cyclewayKey, "track"); changes.add(cyclewayKey + ":segregated", "no"); break; case SIDEWALK_OK: // https://wiki.openstreetmap.org/wiki/File:Z239Z1022-10GehwegRadfahrerFrei.jpeg changes.add(cyclewayKey, "no"); changes.add("sidewalk:" + side.value + ":bicycle", "yes"); break; case PICTOGRAMS: changes.add(cyclewayKey, "shared_lane"); changes.add(cyclewayKey + ":lane", "pictogram"); break; case SUGGESTION_LANE: changes.add(cyclewayKey, "shared_lane"); changes.add(cyclewayKey + ":lane", "advisory"); break; case BUSWAY: changes.add(cyclewayKey, "share_busway"); break; } } @Nullable @Override public Boolean isApplicableTo(Element element) { /* Whether this element applies to this quest cannot be determined by looking at that element alone (see download()), an Overpass query would need to be made to find this out. This is too heavy-weight for this method so it always returns false. */ /* The implications of this are that this quest will never be created directly as consequence of solving another quest and also after reverting an input, the quest will not immediately pop up again. Instead, they are downloaded well after an element became fit for this quest. */ return null; } @Override public boolean download(BoundingBox bbox, MapDataWithGeometryHandler handler) { return overpassServer.getAndHandleQuota(getOverpassQuery(bbox), handler); } /** @return overpass query string to get streets without cycleway info not near paths for * bicycles. */ private static String getOverpassQuery(BoundingBox bbox) { int d = MIN_DIST_TO_CYCLEWAYS; return OverpassQLUtil.getGlobalOverpassBBox(bbox) + "way[highway ~ \"^(primary|secondary|tertiary|unclassified)$\"]" + "[area != yes]" + // only without cycleway tags "[!cycleway][!\"cycleway:left\"][!\"cycleway:right\"][!\"cycleway:both\"]" + "[!\"sidewalk:bicycle\"][!\"sidewalk:both:bicycle\"][!\"sidewalk:left:bicycle\"][!\"sidewalk:right:bicycle\"]" + // not any with low speed limit because they not very likely to have cycleway infrastructure "[maxspeed !~ \"^(20|15|10|8|7|6|5|10 mph|5 mph|walk)$\"]" + // not any unpaved because of the same reason "[surface !~ \"^("+ TextUtils.join("|", OsmTaggings.ANYTHING_UNPAVED)+")$\"]" + // not any explicitly tagged as no bicycles "[bicycle != no]" + "[access !~ \"^private|no$\"]" + // some roads may be father than MIN_DIST_TO_CYCLEWAYS from cycleways, // not tagged cycleway=separate/sidepath but may have hint that there is // a separately tagged cycleway "[bicycle != use_sidepath][\"bicycle:backward\" != use_sidepath]" + "[\"bicycle:forward\" != use_sidepath]" + " -> .streets;" + "(" + "way[highway=cycleway](around.streets: "+d+");" + // See #718: If a separate way exists, it may be that the user's answer should // correctly be tagged on that separate way and not on the street -> this app would // tag data on the wrong elements. So, don't ask at all for separately mapped ways. // :-( "way[highway ~ \"^(path|footway)$\"](around.streets: "+d+");" + ") -> .cycleways;" + "way.streets(around.cycleways: "+d+") -> .streets_near_cycleways;" + "(.streets; - .streets_near_cycleways;);" + OverpassQLUtil.getQuestPrintStatement(); } @Override public AbstractQuestAnswerFragment createForm() { return new AddCyclewayForm(); } @Override public String getCommitMessage() { return "Add whether there are cycleways"; } @Override public int getIcon() { return R.drawable.ic_quest_bicycleway; } @Override public int getTitle(@NonNull Map<String, String> tags) { return R.string.quest_cycleway_title2; } @NonNull @Override public Countries getEnabledForCountries() { // See overview here: https://ent8r.github.io/blacklistr/?java=bikeway/AddCycleway.java // #749. sources: // Google Street View (driving around in virtual car) // https://en.wikivoyage.org/wiki/Cycling // http://peopleforbikes.org/get-local/ (US) return Countries.noneExcept(new String[] { // all of Northern and Western Europe, most of Central Europe, some of Southern Europe "NO","SE","FI","IS","DK", "GB","IE","NL","BE","FR","LU", "DE","PL","CZ","HU","AT","CH","LI", "ES","IT", // East Asia "JP","KR","TW", // some of China (East Coast) "CN-BJ","CN-TJ","CN-SD","CN-JS","CN-SH", "CN-ZJ","CN-FJ","CN-GD","CN-CQ", // Australia etc "NZ","AU", // some of Canada "CA-BC","CA-QC","CA-ON","CA-NS","CA-PE", // some of the US // West Coast, East Coast, Center, South "US-WA","US-OR","US-CA", "US-MA","US-NJ","US-NY","US-DC","US-CT","US-FL", "US-MN","US-MI","US-IL","US-WI","US-IN", "US-AZ","US-TX", }); } }
Binnette/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/bikeway/AddCycleway.java
Java
gpl-3.0
9,505
<?php /** * @author Константин Харламов <k.kharlamov@smart-webs.ru> * @link https://github.com/BoesesGenie/rex-framework Проект на GitHub * * \REXFramework - REusable EXtensible userFriendly PHP framework * Мини-фреймворк для разработки веб-приложений * * @copyright © 2014-2015 Константин Харламов. Контакты: <k.kharlamov@smart-webs.ru> * @license http://www.gnu.org/licenses/gpl-3.0.ru.html GNU GENERAL PUBLIC LICENSE */ namespace REXFramework\model; /** * Класс-сборщик SQL-запросов */ class SQLBuilder { /** * Способ соединения таблиц для оператора INNER JOIN */ const INNER = 1; /** * Способ соединения таблиц для оператора LEFT JOIN */ const LEFT = 2; /** * Способ соединения таблиц для оператора RIGHT JOIN */ const RIGHT = 3; /** * Прямой порядок сортировки */ const ASC = 'ASC'; /** * Обратный порядок сортировки */ const DESC = 'DESC'; /** * $select - Часть строки запроса SELECT * * @var string */ private $select; /** * $update - Часть строки запроса UPDATE * * @var string */ private $update; /** * $insert - Часть строки запроса INSERT * * @var string */ private $insert; /** * $delete - Часть строки запроса DELETE * * @var string */ private $delete; /** * $from - Часть строки запроса FROM * * @var string */ private $from; /** * $join - Часть строки запроса JOIN * * @var string */ private $join; /** * $where - Часть строки запроса WHERE * * @var string */ private $where; /** * $prefixes - Массив префиксов таблиц для подстановки в запрос * * @var array */ private $prefixes = array(); /** * @var string Строка ORDER BY `field` DESC (ASC) */ private $order = ''; /** * $terms - Массив переменных для подстановки в запрос * * @var array */ private $terms = array(); /** * Собранный SQL-запрос в формате для PDO::prepare() * * @var string */ private $sql; /** * Формирование части запроса INSERT * * @param array $fields Массив полей для вставки * @param string $table Имя таблицы * @return \REXFramework\model\SQLBuilder */ public function insert(array $fields, $table) { $this->clear(); $this->insert = 'INSERT INTO ' . $table . ' SET '; $insArr = array(); foreach ($fields as $key => $val) { $insArr[] = "{$key} = ?"; $this->terms[] = $val; } $this->insert .= implode(', ', $insArr); return $this; } /** * Формирование части запроса UPDATE * * @param array $fields Массив полей для обновления * @param string $table Имя таблицы * @return \REXFramework\model\SQLBuilder */ public function update(array $fields, $table) { $this->clear(); $this->update = 'UPDATE ' . $table . ' SET '; $updArr = array(); foreach ($fields as $key => $val) { $updArr[] = "{$key} = ?"; $this->terms[] = $val; } $this->update .= implode(', ', $updArr); return $this; } /** * Формирование части запроса SELECT * * @param array $fields Массив полей для выборки, опционально * @return \REXFramework\model\SQLBuilder */ public function select(array $fields = array()) { $this->clear(); $this->select = 'SELECT '; if (!empty($fields)) { $this->select .= implode(', ', $fields); } else { $this->select .= '*'; } return $this; } /** * Формирование части запроса DELETE * * @param string $table Имя таблицы * @return \REXFramework\model\SQLBuilder */ public function delete($table) { $this->clear(); $this->delete = 'DELETE FROM ' . $table; return $this; } /** * Формирование части запроса FROM * * @param string $table Имя таблицы * @param string $short Псевдоним таблицы (короткое имя), опционально * @return \REXFramework\model\SQLBuilder */ public function from($table, $short = '') { $this->from = ' FROM ' . $table; if ($short != '') { $prefix = $short; $this->from .= ' AS ' . $short; } else { $prefix = $table; } $fields = explode(', ', str_replace('SELECT ', '', $this->select)); $this->select = 'SELECT ' . $prefix . '.' . implode(", {$prefix}." , $fields); $this->prefixes[$table] = $prefix; return $this; } /** * Формирование части запроса JOIN * * @param string $table Имя таблицы * @param array|strung $cond Массив либо строка условий объединения * @param int $type Тип объединения (LEFT, INNER, RIGHT), опционально * @param array $fields Массив полей для выборки, опционально * @param string $short Псевдоним таблицы (короткое имя), опционально * @return \REXFramework\model\SQLBuilder */ public function join($table, $cond, $type = self::INNER, array $fields = array(), $short = '') { $joinType = ''; switch ($type) { case self::INNER: $joinType = 'INNER'; break; case self::LEFT: $joinType = 'LEFT'; break; case self::RIGHT: $joinType = 'RIGHT'; break; } if ($short != '') { $prefix = $short; $this->join .= " {$joinType} JOIN {$table} AS {$short}"; } else { $prefix = $table; $this->join .= " {$joinType} JOIN {$table}"; } $this->prefixes[$table] = $prefix; if (is_array($cond)) { $joinCond = array(); foreach ($cond as $key => $val) { $joinCond[] = $this->prefixes[$key] . '.' . $val; } $this->join .= ' ON ' . implode(' = ', $joinCond); } else { $this->join .= ' ON ' . $cond; } if (!empty($fields)) { $this->select .= ", {$prefix}." . implode(", {$prefix}.", $fields); } else { $this->select .= ", {$prefix}.*"; } return $this; } /** * Формирование части запроса WHERE. * Из переданного ассоциативного массива полей со значениями * формируются условия, соединенные оператором AND, * если значение поля - массив, то значения этого массива * объединяются в конструкции IN(?, ?, ...) * * @param array $fields Массив полей со значениями * @param string $table Имя таблицы * @return \REXFramework\model\SQLBuilder */ public function where(array $fields, $table, $logOp = 'AND', $op = '=') { if (empty($fields)) { return $this; } $cond = array(); foreach ($fields as $field => $value) { $valPlace = " {$op} ?"; if (is_array($value)) { $valPlace = 'IN('; for ($i = 0; $i < count($value); $i++) { $valPlace .= '?, '; } $valPlace = ' ' . trim($valPlace, ', '); $valPlace .= ')'; } if (isset($this->prefixes[$table])) { $cond[] = $this->prefixes[$table] . '.' . $field . $valPlace; } else { $cond[] = $field . $valPlace; } if (is_array($value)) { for ($i = 0; $i < count($value); $i++) { $this->terms[] = $value[$i]; } } else { $this->terms[] = $value; } } if (!$this->where) { $this->where = " WHERE (" . implode(" {$logOp} ", $cond) . ")"; } else { $this->where .= " AND (" . implode(" {$logOp} ", $cond) . ")"; } return $this; } /** * Добавить ORDER BY * * @param array $fields Список полей, по которым упорядочивать * @param string $direction Направление упорядочения */ public function order(array $fields, $direction = self::ASC) { $this->order = ' ORDER BY ' . implode(',', $fields) . ' ' . $direction; return $this; } /** * @todo Дописать реализацию */ public function limit() { return $this; } /** * Собирает SQl-запрос в формате для PDO из ранее подготовленных частей * * @return \REXFramework\model\SQLBuilder */ public function assemble() { if ($this->select != '') { $this->sql = $this->select . $this->from . $this->join . $this->where . $this->order; } else if ($this->update != '') { $this->sql = $this->update . $this->where; } else if ($this->insert != '') { $this->sql = $this->insert; } else if ($this->delete != '') { $this->sql = $this->delete . $this->where; } return $this; } /** * Возвращает собранный SQL-запрос в формате для PDO * * @return string */ public function getSQL() { return $this->sql; } /** * Возвращает массив переменных для вставки в SQL-запрос * * @return array */ public function getTerms() { return $this->terms; } /** * Очистить поля. * Вспомогательный метод для очистки полей объекта * при подготовке новых запросов. */ private function clear() { $this->select = ''; $this->update = ''; $this->insert = ''; $this->delete = ''; $this->from = ''; $this->join = ''; $this->where = ''; $this->prefixes = array(); $this->terms = array(); } }
BoesesGenie/rex-framework
src/model/SQLBuilder.php
PHP
gpl-3.0
11,621
#!/bin/sh # # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of GNUHAWK. # # GNUHAWK is free software: you can redistribute it and/or modify is 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. # # GNUHAWK 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" = "rpm" ]; then # A very simplistic RPM build scenario if [ -e pfb_clock_sync_ccf_4o.spec ]; then mydir=`dirname $0` tmpdir=`mktemp -d` cp -r ${mydir} ${tmpdir}/pfb_clock_sync_ccf_4o-1.0.0 tar czf ${tmpdir}/pfb_clock_sync_ccf_4o-1.0.0.tar.gz --exclude=".svn" -C ${tmpdir} pfb_clock_sync_ccf_4o-1.0.0 rpmbuild -ta ${tmpdir}/pfb_clock_sync_ccf_4o-1.0.0.tar.gz rm -rf $tmpdir else echo "Missing RPM spec file in" `pwd` exit 1 fi else for impl in cpp ; do cd $impl if [ -e build.sh ]; then ./build.sh $* elif [ -e reconf ]; then ./reconf && ./configure && make else echo "No build.sh found for $impl" fi cd - done fi
RedhawkSDR/integration-gnuhawk
components/pfb_clock_sync_ccf_4o/build.sh
Shell
gpl-3.0
1,604
package plp.expressions1 import plp.expressions1.expression.Expressao import plp.expressions1.util.{VisitorAvaliar, VisitorChecaTipo} object ConstrutorPrograma { def criarPrograma(exp: Expressao): Programa = { val visitorChe = new VisitorChecaTipo() val visitorAval = new VisitorAvaliar() new Programa(exp, visitorChe, visitorAval) } }
lrlucena/PLP-Scala
src/plp/expressions1/ConstrutorPrograma.scala
Scala
gpl-3.0
355
""" DIRAC FileCatalog mix-in class to manage directory metadata """ # pylint: disable=protected-access import six import os from DIRAC import S_OK, S_ERROR from DIRAC.Core.Utilities.Time import queryTime class DirectoryMetadata(object): def __init__(self, database=None): self.db = database def setDatabase(self, database): self.db = database ############################################################################## # # Manage Metadata fields # def addMetadataField(self, pName, pType, credDict): """Add a new metadata parameter to the Metadata Database. :param str pName: parameter name :param str pType: parameter type in the MySQL notation :return: S_OK/S_ERROR, Value - comment on a positive result """ result = self.db.fmeta.getFileMetadataFields(credDict) if not result["OK"]: return result if pName in result["Value"]: return S_ERROR("The metadata %s is already defined for Files" % pName) result = self._getMetadataFields(credDict) if not result["OK"]: return result if pName in result["Value"]: if pType.lower() == result["Value"][pName].lower(): return S_OK("Already exists") return S_ERROR( "Attempt to add an existing metadata with different type: %s/%s" % (pType, result["Value"][pName]) ) valueType = pType if pType.lower()[:3] == "int": valueType = "INT" elif pType.lower() == "string": valueType = "VARCHAR(128)" elif pType.lower() == "float": valueType = "FLOAT" elif pType.lower() == "date": valueType = "DATETIME" elif pType == "MetaSet": valueType = "VARCHAR(64)" req = "CREATE TABLE FC_Meta_%s ( DirID INTEGER NOT NULL, Value %s, PRIMARY KEY (DirID), INDEX (Value) )" % ( pName, valueType, ) result = self.db._query(req) if not result["OK"]: return result result = self.db.insertFields("FC_MetaFields", ["MetaName", "MetaType"], [pName, pType]) if not result["OK"]: return result metadataID = result["lastRowId"] result = self.__transformMetaParameterToData(pName) if not result["OK"]: return result return S_OK("Added new metadata: %d" % metadataID) def deleteMetadataField(self, pName, credDict): """Remove metadata field :param str pName: meta parameter name :param dict credDict: client credential dictionary :return: S_OK/S_ERROR """ req = "DROP TABLE FC_Meta_%s" % pName result = self.db._update(req) error = "" if not result["OK"]: error = result["Message"] req = "DELETE FROM FC_MetaFields WHERE MetaName='%s'" % pName result = self.db._update(req) if not result["OK"]: if error: result["Message"] = error + "; " + result["Message"] return result def getMetadataFields(self, credDict): """Get all the defined metadata fields :param dict credDict: client credential dictionary :return: S_OK/S_ERROR, Value is the metadata:metadata type dictionary """ return self._getMetadataFields(credDict) def _getMetadataFields(self, credDict): """Get all the defined metadata fields as they are defined in the database :param dict credDict: client credential dictionary :return: S_OK/S_ERROR, Value is the metadata:metadata type dictionary """ req = "SELECT MetaName,MetaType FROM FC_MetaFields" result = self.db._query(req) if not result["OK"]: return result metaDict = {} for row in result["Value"]: metaDict[row[0]] = row[1] return S_OK(metaDict) def addMetadataSet(self, metaSetName, metaSetDict, credDict): """Add a new metadata set with the contents from metaSetDict :param str metaSetName: metaSet name :param dict metaSetDict: contents of the meta set definition :param dict credDict: client credential dictionary :return: S_OK/S_ERROR """ result = self._getMetadataFields(credDict) if not result["OK"]: return result metaTypeDict = result["Value"] # Check the sanity of the metadata set contents for key in metaSetDict: if key not in metaTypeDict: return S_ERROR("Unknown key %s" % key) result = self.db.insertFields("FC_MetaSetNames", ["MetaSetName"], [metaSetName]) if not result["OK"]: return result metaSetID = result["lastRowId"] req = "INSERT INTO FC_MetaSets (MetaSetID,MetaKey,MetaValue) VALUES %s" vList = [] for key, value in metaSetDict.items(): vList.append("(%d,'%s','%s')" % (metaSetID, key, str(value))) vString = ",".join(vList) result = self.db._update(req % vString) return result def getMetadataSet(self, metaSetName, expandFlag, credDict): """Get fully expanded contents of the metadata set :param str metaSetName: metaSet name :param bool expandFlag: flag to whether to expand the metaset recursively :param dict credDict: client credential dictionary :return: S_OK/S_ERROR, Value dictionary of the meta set definition contents """ result = self._getMetadataFields(credDict) if not result["OK"]: return result metaTypeDict = result["Value"] req = "SELECT S.MetaKey,S.MetaValue FROM FC_MetaSets as S, FC_MetaSetNames as N " req += "WHERE N.MetaSetName='%s' AND N.MetaSetID=S.MetaSetID" % metaSetName result = self.db._query(req) if not result["OK"]: return result if not result["Value"]: return S_OK({}) resultDict = {} for key, value in result["Value"]: if key not in metaTypeDict: return S_ERROR("Unknown key %s" % key) if expandFlag: if metaTypeDict[key] == "MetaSet": result = self.getMetadataSet(value, expandFlag, credDict) if not result["OK"]: return result resultDict.update(result["Value"]) else: resultDict[key] = value else: resultDict[key] = value return S_OK(resultDict) ############################################################################################# # # Set and get directory metadata # ############################################################################################# def setMetadata(self, dPath, metaDict, credDict): """Set the value of a given metadata field for the the given directory path :param str dPath: directory path :param dict metaDict: dictionary with metadata :param dict credDict: client credential dictionary :return: S_OK/S_ERROR """ result = self._getMetadataFields(credDict) if not result["OK"]: return result metaFields = result["Value"] result = self.db.dtree.findDir(dPath) if not result["OK"]: return result if not result["Value"]: return S_ERROR("Path not found: %s" % dPath) dirID = result["Value"] dirmeta = self.getDirectoryMetadata(dPath, credDict, ownData=False) if not dirmeta["OK"]: return dirmeta for metaName, metaValue in metaDict.items(): if metaName not in metaFields: result = self.setMetaParameter(dPath, metaName, metaValue, credDict) if not result["OK"]: return result continue # Check that the metadata is not defined for the parent directories if metaName in dirmeta["Value"]: return S_ERROR("Metadata conflict detected for %s for directory %s" % (metaName, dPath)) result = self.db.insertFields("FC_Meta_%s" % metaName, ["DirID", "Value"], [dirID, metaValue]) if not result["OK"]: if result["Message"].find("Duplicate") != -1: req = "UPDATE FC_Meta_%s SET Value='%s' WHERE DirID=%d" % (metaName, metaValue, dirID) result = self.db._update(req) if not result["OK"]: return result else: return result return S_OK() def removeMetadata(self, dPath, metaData, credDict): """Remove the specified metadata for the given directory :param str dPath: directory path :param dict metaData: metadata dictionary :param dict credDict: client credential dictionary :return: standard Dirac result object """ result = self._getMetadataFields(credDict) if not result["OK"]: return result metaFields = result["Value"] result = self.db.dtree.findDir(dPath) if not result["OK"]: return result if not result["Value"]: return S_ERROR("Path not found: %s" % dPath) dirID = result["Value"] failedMeta = {} for meta in metaData: if meta in metaFields: # Indexed meta case req = "DELETE FROM FC_Meta_%s WHERE DirID=%d" % (meta, dirID) result = self.db._update(req) if not result["OK"]: failedMeta[meta] = result["Value"] else: # Meta parameter case req = "DELETE FROM FC_DirMeta WHERE MetaKey='%s' AND DirID=%d" % (meta, dirID) result = self.db._update(req) if not result["OK"]: failedMeta[meta] = result["Value"] if failedMeta: metaExample = list(failedMeta)[0] result = S_ERROR("Failed to remove %d metadata, e.g. %s" % (len(failedMeta), failedMeta[metaExample])) result["FailedMetadata"] = failedMeta else: return S_OK() def setMetaParameter(self, dPath, metaName, metaValue, credDict): """Set an meta parameter - metadata which is not used in the the data search operations :param str dPath: directory name :param str metaName: meta parameter name :param str metaValue: meta parameter value :param dict credDict: client credential dictionary :return: S_OK/S_ERROR """ result = self.db.dtree.findDir(dPath) if not result["OK"]: return result if not result["Value"]: return S_ERROR("Path not found: %s" % dPath) dirID = result["Value"] result = self.db.insertFields( "FC_DirMeta", ["DirID", "MetaKey", "MetaValue"], [dirID, metaName, str(metaValue)] ) return result def getDirectoryMetaParameters(self, dpath, credDict, inherited=True): """Get meta parameters for the given directory :param str dPath: directory name :param dict credDict: client credential dictionary :return: S_OK/S_ERROR, Value dictionary of meta parameters """ if inherited: result = self.db.dtree.getPathIDs(dpath) if not result["OK"]: return result pathIDs = result["Value"] dirID = pathIDs[-1] else: result = self.db.dtree.findDir(dpath) if not result["OK"]: return result if not result["Value"]: return S_ERROR("Path not found: %s" % dpath) dirID = result["Value"] pathIDs = [dirID] if len(pathIDs) > 1: pathString = ",".join([str(x) for x in pathIDs]) req = "SELECT DirID,MetaKey,MetaValue from FC_DirMeta where DirID in (%s)" % pathString else: req = "SELECT DirID,MetaKey,MetaValue from FC_DirMeta where DirID=%d " % dirID result = self.db._query(req) if not result["OK"]: return result if not result["Value"]: return S_OK({}) metaDict = {} for _dID, key, value in result["Value"]: if key in metaDict: if isinstance(metaDict[key], list): metaDict[key].append(value) else: metaDict[key] = [metaDict[key]].append(value) else: metaDict[key] = value return S_OK(metaDict) def getDirectoryMetadata(self, path, credDict, inherited=True, ownData=True): """Get metadata for the given directory aggregating metadata for the directory itself and for all the parent directories if inherited flag is True. Get also the non-indexed metadata parameters. :param str path: directory name :param dict credDict: client credential dictionary :param bool inherited: flag to include metadata from the parent directories :param bool ownData: flag to include metadata for the directory itself :return: S_OK/S_ERROR, Value dictionary of metadata """ result = self.db.dtree.getPathIDs(path) if not result["OK"]: return result pathIDs = result["Value"] result = self._getMetadataFields(credDict) if not result["OK"]: return result metaFields = result["Value"] metaDict = {} metaOwnerDict = {} metaTypeDict = {} dirID = pathIDs[-1] if not inherited: pathIDs = pathIDs[-1:] if not ownData: pathIDs = pathIDs[:-1] pathString = ",".join([str(x) for x in pathIDs]) for meta in metaFields: req = "SELECT Value,DirID FROM FC_Meta_%s WHERE DirID in (%s)" % (meta, pathString) result = self.db._query(req) if not result["OK"]: return result if len(result["Value"]) > 1: return S_ERROR("Metadata conflict for %s for directory %s" % (meta, path)) if result["Value"]: metaDict[meta] = result["Value"][0][0] if int(result["Value"][0][1]) == dirID: metaOwnerDict[meta] = "OwnMetadata" else: metaOwnerDict[meta] = "ParentMetadata" metaTypeDict[meta] = metaFields[meta] # Get also non-searchable data result = self.getDirectoryMetaParameters(path, credDict, inherited) if result["OK"]: metaDict.update(result["Value"]) for meta in result["Value"]: metaOwnerDict[meta] = "OwnParameter" result = S_OK(metaDict) result["MetadataOwner"] = metaOwnerDict result["MetadataType"] = metaTypeDict return result def __transformMetaParameterToData(self, metaName): """Relocate the meta parameters of all the directories to the corresponding indexed metadata table :param str metaName: name of the parameter to transform :return: S_OK/S_ERROR """ req = "SELECT DirID,MetaValue from FC_DirMeta WHERE MetaKey='%s'" % metaName result = self.db._query(req) if not result["OK"]: return result if not result["Value"]: return S_OK() dirDict = {} for dirID, meta in result["Value"]: dirDict[dirID] = meta dirList = list(dirDict) # Exclude child directories from the list for dirID in dirList: result = self.db.dtree.getSubdirectoriesByID(dirID) if not result["OK"]: return result if not result["Value"]: continue childIDs = list(result["Value"]) for childID in childIDs: if childID in dirList: del dirList[dirList.index(childID)] insertValueList = [] for dirID in dirList: insertValueList.append("( %d,'%s' )" % (dirID, dirDict[dirID])) req = "INSERT INTO FC_Meta_%s (DirID,Value) VALUES %s" % (metaName, ", ".join(insertValueList)) result = self.db._update(req) if not result["OK"]: return result req = "DELETE FROM FC_DirMeta WHERE MetaKey='%s'" % metaName result = self.db._update(req) return result ############################################################################################ # # Find directories corresponding to the metadata # def __createMetaSelection(self, value, table=""): """Create an SQL selection element for the given meta value :param dict value: dictionary with selection instructions suitable for the database search :param str table: table name :return: selection string """ if isinstance(value, dict): selectList = [] for operation, operand in value.items(): if operation in [">", "<", ">=", "<="]: if isinstance(operand, list): return S_ERROR("Illegal query: list of values for comparison operation") if isinstance(operand, six.integer_types): selectList.append("%sValue%s%d" % (table, operation, operand)) elif isinstance(operand, float): selectList.append("%sValue%s%f" % (table, operation, operand)) else: selectList.append("%sValue%s'%s'" % (table, operation, operand)) elif operation == "in" or operation == "=": if isinstance(operand, list): vString = ",".join(["'" + str(x) + "'" for x in operand]) selectList.append("%sValue IN (%s)" % (table, vString)) else: selectList.append("%sValue='%s'" % (table, operand)) elif operation == "nin" or operation == "!=": if isinstance(operand, list): vString = ",".join(["'" + str(x) + "'" for x in operand]) selectList.append("%sValue NOT IN (%s)" % (table, vString)) else: selectList.append("%sValue!='%s'" % (table, operand)) selectString = " AND ".join(selectList) elif isinstance(value, list): vString = ",".join(["'" + str(x) + "'" for x in value]) selectString = "%sValue in (%s)" % (table, vString) else: if value == "Any": selectString = "" else: selectString = "%sValue='%s' " % (table, value) return S_OK(selectString) def __findSubdirByMeta(self, metaName, value, pathSelection="", subdirFlag=True): """Find directories for the given metaName datum. If the the metaName datum type is a list, combine values in OR. In case the metaName datum is 'Any', finds all the subdirectories for which the metaName datum is defined at all. :param str metaName: metadata name :param dict,list value: dictionary with selection instructions suitable for the database search :param str pathSelection: directory path selection string :param bool subdirFlag: fla to include subdirectories :return: S_OK/S_ERROR, Value list of found directories """ result = self.__createMetaSelection(value, "M.") if not result["OK"]: return result selectString = result["Value"] req = " SELECT M.DirID FROM FC_Meta_%s AS M" % metaName if pathSelection: req += " JOIN ( %s ) AS P WHERE M.DirID=P.DirID" % pathSelection if selectString: if pathSelection: req += " AND %s" % selectString else: req += " WHERE %s" % selectString result = self.db._query(req) if not result["OK"]: return result if not result["Value"]: return S_OK([]) dirList = [] for row in result["Value"]: dirID = row[0] dirList.append(dirID) # if subdirFlag: # result = self.db.dtree.getSubdirectoriesByID( dirID ) # if not result['OK']: # return result # dirList += result['Value'] if subdirFlag: result = self.db.dtree.getAllSubdirectoriesByID(dirList) if not result["OK"]: return result dirList += result["Value"] return S_OK(dirList) def __findSubdirMissingMeta(self, metaName, pathSelection): """Find directories not having the given meta datum defined :param str metaName: metadata name :param str pathSelection: directory path selection string :return: S_OK,S_ERROR , Value list of directories """ result = self.__findSubdirByMeta(metaName, "Any", pathSelection) if not result["OK"]: return result dirList = result["Value"] table = self.db.dtree.getTreeTable() dirString = ",".join([str(x) for x in dirList]) if dirList: req = "SELECT DirID FROM %s WHERE DirID NOT IN ( %s )" % (table, dirString) else: req = "SELECT DirID FROM %s" % table result = self.db._query(req) if not result["OK"]: return result if not result["Value"]: return S_OK([]) dirList = [x[0] for x in result["Value"]] return S_OK(dirList) def __expandMetaDictionary(self, metaDict, credDict): """Update the dictionary with metadata query by expand metaSet type metadata :param dict metaDict: metaDict to be expanded :param dict credDict: client credential dictionary :return: S_OK/S_ERROR , Value dictionary of metadata """ result = self._getMetadataFields(credDict) if not result["OK"]: return result metaTypeDict = result["Value"] resultDict = {} extraDict = {} for key, value in metaDict.items(): if key not in metaTypeDict: # return S_ERROR( 'Unknown metadata field %s' % key ) extraDict[key] = value continue keyType = metaTypeDict[key] if keyType != "MetaSet": resultDict[key] = value else: result = self.getMetadataSet(value, True, credDict) if not result["OK"]: return result mDict = result["Value"] for mk, mv in mDict.items(): if mk in resultDict: return S_ERROR("Contradictory query for key %s" % mk) else: resultDict[mk] = mv result = S_OK(resultDict) result["ExtraMetadata"] = extraDict return result def __checkDirsForMetadata(self, metaName, value, pathString): """Check if any of the given directories conform to the given metadata :param str metaName: matadata name :param dict,list value: dictionary with selection instructions suitable for the database search :param str pathString: string of comma separated directory names :return: S_OK/S_ERROR, Value directory ID """ result = self.__createMetaSelection(value, "M.") if not result["OK"]: return result selectString = result["Value"] if selectString: req = "SELECT M.DirID FROM FC_Meta_%s AS M WHERE %s AND M.DirID IN (%s)" % ( metaName, selectString, pathString, ) else: req = "SELECT M.DirID FROM FC_Meta_%s AS M WHERE M.DirID IN (%s)" % (metaName, pathString) result = self.db._query(req) if not result["OK"]: return result elif not result["Value"]: return S_OK(None) elif len(result["Value"]) > 1: return S_ERROR("Conflict in the directory metadata hierarchy") else: return S_OK(result["Value"][0][0]) @queryTime def findDirIDsByMetadata(self, queryDict, path, credDict): """Find Directories satisfying the given metadata and being subdirectories of the given path :param dict queryDict: dictionary containing query data :param str path: starting directory path :param dict credDict: client credential dictionary :return: S_OK/S_ERROR, Value list of selected directory IDs """ pathDirList = [] pathDirID = 0 pathString = "0" if path != "/": result = self.db.dtree.getPathIDs(path) if not result["OK"]: # as result[Value] is already checked in getPathIDs return result pathIDs = result["Value"] pathDirID = pathIDs[-1] pathString = ",".join([str(x) for x in pathIDs]) result = self.__expandMetaDictionary(queryDict, credDict) if not result["OK"]: return result metaDict = result["Value"] # Now check the meta data for the requested directory and its parents finalMetaDict = dict(metaDict) for meta in metaDict: result = self.__checkDirsForMetadata(meta, metaDict[meta], pathString) if not result["OK"]: return result elif result["Value"] is not None: # Some directory in the parent hierarchy is already conforming with the # given metadata, no need to check it further del finalMetaDict[meta] if finalMetaDict: pathSelection = "" if pathDirID: result = self.db.dtree.getSubdirectoriesByID(pathDirID, includeParent=True, requestString=True) if not result["OK"]: return result pathSelection = result["Value"] dirList = [] first = True for meta, value in finalMetaDict.items(): if value == "Missing": result = self.__findSubdirMissingMeta(meta, pathSelection) else: result = self.__findSubdirByMeta(meta, value, pathSelection) if not result["OK"]: return result mList = result["Value"] if first: dirList = mList first = False else: newList = [] for d in dirList: if d in mList: newList.append(d) dirList = newList else: if pathDirID: result = self.db.dtree.getSubdirectoriesByID(pathDirID, includeParent=True) if not result["OK"]: return result pathDirList = list(result["Value"]) finalList = [] dirSelect = False if finalMetaDict: dirSelect = True finalList = dirList if pathDirList: finalList = list(set(dirList) & set(pathDirList)) else: if pathDirList: dirSelect = True finalList = pathDirList result = S_OK(finalList) if finalList: result["Selection"] = "Done" elif dirSelect: result["Selection"] = "None" else: result["Selection"] = "All" return result @queryTime def findDirectoriesByMetadata(self, queryDict, path, credDict): """Find Directory names satisfying the given metadata and being subdirectories of the given path :param dict queryDict: dictionary containing query data :param str path: starting directory path :param dict credDict: client credential dictionary :return: S_OK/S_ERROR, Value list of selected directory paths """ result = self.findDirIDsByMetadata(queryDict, path, credDict) if not result["OK"]: return result dirIDList = result["Value"] dirNameDict = {} if dirIDList: result = self.db.dtree.getDirectoryPaths(dirIDList) if not result["OK"]: return result dirNameDict = result["Value"] elif result["Selection"] == "None": dirNameDict = {0: "None"} elif result["Selection"] == "All": dirNameDict = {0: "All"} return S_OK(dirNameDict) def findFilesByMetadata(self, metaDict, path, credDict): """Find Files satisfying the given metadata :param dict metaDict: dictionary with the selection metadata :param str path: starting directory path :param dict credDict: client credential dictionary :return: S_OK/S_ERROR, Value list files in selected directories """ result = self.findDirectoriesByMetadata(metaDict, path, credDict) if not result["OK"]: return result dirDict = result["Value"] dirList = list(dirDict) fileList = [] result = self.db.dtree.getFilesInDirectory(dirList, credDict) if not result["OK"]: return result for _fileID, dirID, fname in result["Value"]: fileList.append(dirDict[dirID] + "/" + os.path.basename(fname)) return S_OK(fileList) def findFileIDsByMetadata(self, metaDict, path, credDict, startItem=0, maxItems=25): """Find Files satisfying the given metadata :param dict metaDict: dictionary with the selection metadata :param str path: starting directory path :param dict credDict: client credential dictionary :param int startItem: offset in the file list :param int maxItems: max number of files to rteurn :return: S_OK/S_ERROR, Value list file IDs in selected directories """ result = self.findDirIDsByMetadata(metaDict, path, credDict) if not result["OK"]: return result dirList = result["Value"] return self.db.dtree.getFileIDsInDirectoryWithLimits(dirList, credDict, startItem, maxItems) ################################################################################################ # # Find metadata compatible with other metadata in order to organize dynamically updated metadata selectors def __findCompatibleDirectories(self, metaName, value, fromDirs): """Find directories compatible with the given metaName datum. Optionally limit the list of compatible directories to only those in the fromDirs list :param str metaName: metadata name :param dict,list value: dictionary with selection instructions suitable for the database search :param list fromDirs: list of directories to choose from :return: S_OK/S_ERROR, Value list of selected directories """ # The directories compatible with the given metaName datum are: # - directory for which the datum is defined # - all the subdirectories of the above directory # - all the directories in the parent hierarchy of the above directory # Find directories defining the metaName datum and their subdirectories result = self.__findSubdirByMeta(metaName, value, subdirFlag=False) if not result["OK"]: return result selectedDirs = result["Value"] if not selectedDirs: return S_OK([]) result = self.db.dtree.getAllSubdirectoriesByID(selectedDirs) if not result["OK"]: return result subDirs = result["Value"] # Find parent directories of the directories defining the metaName datum parentDirs = [] for psub in selectedDirs: result = self.db.dtree.getPathIDsByID(psub) if not result["OK"]: return result parentDirs += result["Value"] # Constrain the output to only those that are present in the input list resDirs = parentDirs + subDirs + selectedDirs if fromDirs: resDirs = list(set(resDirs) & set(fromDirs)) return S_OK(resDirs) def __findDistinctMetadata(self, metaList, dList): """Find distinct metadata values defined for the list of the input directories. Limit the search for only metadata in the input list :param list metaList: list of metadata names :param list dList: list of directories to limit the selection :return: S_OK/S_ERROR, Value dictionary of metadata """ if dList: dString = ",".join([str(x) for x in dList]) else: dString = None metaDict = {} for meta in metaList: req = "SELECT DISTINCT(Value) FROM FC_Meta_%s" % meta if dString: req += " WHERE DirID in (%s)" % dString result = self.db._query(req) if not result["OK"]: return result if result["Value"]: metaDict[meta] = [] for row in result["Value"]: metaDict[meta].append(row[0]) return S_OK(metaDict) def getCompatibleMetadata(self, queryDict, path, credDict): """Get distinct metadata values compatible with the given already defined metadata :param dict queryDict: dictionary containing query data :param str path: starting directory path :param dict credDict: client credential dictionary :return: S_OK/S_ERROR, Value dictionary of metadata """ pathDirID = 0 if path != "/": result = self.db.dtree.findDir(path) if not result["OK"]: return result if not result["Value"]: return S_ERROR("Path not found: %s" % path) pathDirID = int(result["Value"]) pathDirs = [] if pathDirID: result = self.db.dtree.getSubdirectoriesByID(pathDirID, includeParent=True) if not result["OK"]: return result if result["Value"]: pathDirs = list(result["Value"]) result = self.db.dtree.getPathIDsByID(pathDirID) if not result["OK"]: return result if result["Value"]: pathDirs += result["Value"] # Get the list of metadata fields to inspect result = self._getMetadataFields(credDict) if not result["OK"]: return result metaFields = result["Value"] comFields = list(metaFields) # Commented out to return compatible data also for selection metadata # for m in metaDict: # if m in comFields: # del comFields[comFields.index( m )] result = self.__expandMetaDictionary(queryDict, credDict) if not result["OK"]: return result metaDict = result["Value"] fromList = pathDirs anyMeta = True if metaDict: anyMeta = False for meta, value in metaDict.items(): result = self.__findCompatibleDirectories(meta, value, fromList) if not result["OK"]: return result cdirList = result["Value"] if cdirList: fromList = cdirList else: fromList = [] break if anyMeta or fromList: result = self.__findDistinctMetadata(comFields, fromList) else: result = S_OK({}) return result def removeMetadataForDirectory(self, dirList, credDict): """Remove all the metadata for the given directory list :param list dirList: list of directory paths :param dict credDict: client credential dictionary :return: S_OK/S_ERROR, Value Successful/Failed dictionaries """ if not dirList: return S_OK({"Successful": {}, "Failed": {}}) failed = {} successful = {} dirs = dirList if not isinstance(dirList, list): dirs = [dirList] dirListString = ",".join([str(d) for d in dirs]) # Get the list of metadata fields to inspect result = self._getMetadataFields(credDict) if not result["OK"]: return result metaFields = result["Value"] for meta in metaFields: req = "DELETE FROM FC_Meta_%s WHERE DirID in ( %s )" % (meta, dirListString) result = self.db._query(req) if not result["OK"]: failed[meta] = result["Message"] else: successful[meta] = "OK" return S_OK({"Successful": successful, "Failed": failed})
DIRACGrid/DIRAC
src/DIRAC/DataManagementSystem/DB/FileCatalogComponents/DirectoryMetadata/DirectoryMetadata.py
Python
gpl-3.0
37,350
# redcap -- library for uploading files to Second Life # Copyright 2009 Paul Morganthall # # redcap is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # any later version. # # 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/>. require 'rubygems' require 'builder' require 'digest/md5' require 'logger' require 'net/https' require 'rexml/document' require 'RMagick' # Requires ImageMagick with JPEG2000 (.JPC) installed require 'tempfile' require 'xmlrpc/client' require 'yaml' # Uploader: support for uploading files to Second Life # The standard upload fee (L$10) is charged upon successful upload. # This program was inspired and informed by the work of Katherine Berry, author # of phpsimcaps, AjaxLife, and other cool stuff: # http://blog.katharineberry.co.uk/ module Redcap GRIDS = {"main" => "https://login.agni.lindenlab.com/cgi-bin/login.cgi", "preview" => "https://login.aditi.lindenlab.com/cgi-bin/login.cgi"} class Uploader attr_reader :success, :new_asset_id, :msg, :aspect_ratio def initialize(first_name, last_name, password, filename, grid="main") @debug = false @log = Logger.new('redcap.log') @log.level = Logger::DEBUG # DEBUG, WARN, @trace = Array.new # global trace stored here for now # ? seperate from log, so it can be glommed to log in one piece @trace << [first_name, last_name, filename, grid, Time.now].join("/") #1: invoke [begin block has rescue at end] begin #2: login login_data = login(first_name, last_name, password, GRIDS[grid]) login_data["seed_capability"] or raise "seed_capability not found" login_data["inventory-root"] or raise "inventory-root not found" #3: request the upload capability cap_request = send_request(login_data["seed_capability"], %{<llsd><array><string>NewFileAgentInventory</string></array></llsd>}) cap_request["NewFileAgentInventory"] or raise "no image upload capability found" #4: request an upload ticket ticket_request = send_request(cap_request["NewFileAgentInventory"], encode_ticket(login_data["inventory-root"], filename)) ticket_request["state"] == "upload" or raise "state not upload" ticket_request["uploader"] or raise "no uploader found" #5: upload image upload_status = send_request(ticket_request["uploader"], make_slimage(filename)) upload_status["state"] = "complete" or raise "upload failed: #{upload_status["state"]}" #7: retrieve the UUID of the newly uploaded image @success = true @new_asset_id = upload_status["new_asset"] # upon success, log the original request and the final result. @log.info(@trace[0].to_yaml + @trace[-1].to_yaml) rescue @success = false @msg = "#{$!}" @log.fatal @trace.to_yaml # on failure, log everything if @debug @msg += "\ntrace: #{@trace[0]}" end end end # initialize private def login(first_name, last_name, password, login_url, method="login_to_simulator") login_params = { :first => first_name, :last => last_name, :passwd => "$1$" + Digest::MD5.hexdigest(password), :options => %w{inventory-root}, :start => "last", :channel => "redcap.rb", # w/channel, no need for build id. :mac => "00:D0:4D:28:A1:F1", # required. :read_critical => "true", # skip... :agree_to_tos => "true", # potential... :skipoptional => "true", # dialogs... } login_url or raise "unrecognized grid name" @trace << [login_url, method] << login_params @log.debug "#{login_url} / #{method} / #{login_params}" server = XMLRPC::Client.new2(login_url) server.http_header_extra = {"Content-Type" => "text/xml"} server.timeout = 120 result = server.call(method, login_params) @trace << result @log.debug "raw login response: #{result.to_yaml}" # unearth some parameters if result.has_key?("inventory-root") then result["inventory-root"] = result["inventory-root"][0]["folder_id"] end # If the login server says "indeterminate", follow the path given. if "indeterminate" == result["login"] then @log.info "indeterminate login:\n#{result.to_yaml}" next_url = result["next_url"] next_method = result["next_method"] message = result["message"] @log.warn "Login redirected:\n#{next_url}, method: #{next_method}, message: #{message}" result = login(first_name, last_name, password, next_url, next_method) elsif "false" == result["login"] or "true" != result["login"] then raise "error during login: #{result["message"]}" end result end # login # Examine URL and return the base url (server), port number, and parameter path def parse_capability(cap) match = %r{https://(.+):(\d+)(.+)}.match(cap) match or raise "capability format not understood: #{cap}" match.captures end # Convert LLSD ( Linden Lab Structured Data) into a simple hash. def decode_llsd(body) doc = REXML::Document.new(body) pairs = Hash[*doc.elements.to_a("/llsd/map/*")] result = Hash.new pairs.each { |key,value| result[key.text.strip] = value.text.strip } result end def send_request(capability, data) @log.debug "send_request / #{capability} #{data if data[0,1] == '<'}" server, port, path = parse_capability(capability) site = Net::HTTP.new(server, port) # site.set_debug_output($stderr) site.use_ssl = true site.verify_mode = OpenSSL::SSL::VERIFY_NONE response = site.request_post(path, data, {"Content-Type" => "text/xml"}) result = decode_llsd(response.body) @log.debug "response\n#{result.to_yaml}" @trace << result result end def encode_ticket(folder, filename) request = { "asset_type" => "texture", "description" => "uploaded by http://adammarker.org/redcap/", "folder_id" => folder, "inventory_type" => "texture", "name" => File.basename(filename) } xml = Builder::XmlMarkup.new(:indent => 2) xml.llsd { xml.map { request.each do |key, value| xml.key(key) xml.string(value) end } } xml.target! end # adapted from function by Simon Kröger posted in comp.lang.ruby # maximum dimension of an SL image is 1024. def nextpow2(n) throw 'eeek' if n < 0 # Simon's. perhaps there is another way? return 1 if n < 2 [1 << (n-1).to_s(2).size, 1024].min end # Convert image to SL standards: # 1. JPEG-2000 Code Stream Syntax (JPC) # 2. width and height must be a power of 2 def make_slimage(filename) image = Magick::Image.read(filename).first @aspect_ratio = image.columns.to_f / image.rows.to_f new_image = image.resize(nextpow2(image.columns), nextpow2(image.rows)) slimage = Tempfile.new('redcap').path new_image.write("jpc:#{slimage}") or raise "Unable to write JPC image." open(slimage, 'rb') { |f| f.read } end end # class end # module
slothbear/redcap
lib/redcap/uploader.rb
Ruby
gpl-3.0
7,906
#include "config-bits.hh" #include <iostream> #include <string> #include <memory> using namespace std; void lookup_test(parse_trie<string>& d, string key) { auto it = key.begin(); auto init = it; try { d.lookup(it); } catch (...) { cerr << "FAIL" << endl; cerr << (it == init ? "true" : "false") << endl; } cerr << "true" << endl; } int main() { unique_ptr<parse_trie<string>> k(new parse_trie<string>()); string d_0("words"); string d_1("wordsees"); string l_0("words"); string l_1("wordsees"); string l_2("wordsee"); k->defval(d_0) = "TEST0"; k->defval(d_1) = "TEST1"; lookup_test(*k, l_0); lookup_test(*k, l_1); lookup_test(*k, l_2); return 0; }
cjhanks/app-config
test/tst1.cc
C++
gpl-3.0
764
#region License //----------------------------------------------------------------------- // <copyright file="IocAdapter.cs" company="Pi2 LLC"> // Copyright (c) Pi2 LLC. All rights reserved. // </copyright> //----------------------------------------------------------------------- #endregion #region Using Directives using ServiceStack.Configuration; using Autofac; #endregion namespace Sigma.Api { public class AutofacIocAdapter : IContainerAdapter { private readonly IContainer _container; public AutofacIocAdapter(IContainer container) { _container = container; } public T Resolve<T>() { return _container.Resolve<T>(); } public T TryResolve<T>() { T result; if (_container.TryResolve<T>(out result)) { return result; } return default(T); } } }
terzano/SigmaWMS
src/Sigma.Api/App_Start/IocAdapter.cs
C#
gpl-3.0
953
/* * Software License Agreement (BSD License) * * Object Pose Estimation (OPE) - www.cse.usf.edu/kkduncan/ope * Copyright (c) 2013, Kester Duncan * * All rights reserved. * * 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 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. * * \file Plane.h * \author Kester Duncan * \note Adapted from ntk's <code>Plane</code> object */ #pragma once #ifndef __PLANE_H__ #define __PLANE_H__ #include <pcl/point_types.h> namespace ope { /** * \brief Defines the properties of a plane */ class Plane { /// Plane parameters double a, b, c, d; public: Plane(double a, double b, double c, double d) : a(a), b(b), c(c), d(d) {} /** * \brief Construct a plane from a normal vector and a point. */ Plane(const pcl::PointXYZ& normal, const pcl::PointXYZ& p); /** * \brief Default Constructor */ Plane() : a(0), b(0), c(0), d(0) {} /** * \brief Determines whether or not this is a valid plane * \return true if it is valid */ bool isValid() const; /** * \brief Gets the normal vector that defines this plane * \returns the x, y, & z values of the plane's normal */ pcl::PointXYZ normal() const; /** * \brief Sets the parameters of the plane */ void set (double a_, double b_, double c_, double d_) { a = a_; b = b_; c = c_; d = d_; } /** * \brief Determines whether this plane intersects with the specified line given by the parameters * \param <p1> the first point that defines the line * \param <p2> the second point that defines the line */ pcl::PointXYZ intersectionWithLine (const pcl::PointXYZ& p1, const pcl::PointXYZ& p2) const; /** * \brief Determines a point's distance from the plane * \return Distance from the plane */ float distanceToPlane(const pcl::PointXYZ& p) const; }; } // ope #endif /* __PLANE_H__ */
CARRTUSF/PoseEstimation
ObjectPoseEstimation/ObjectPoseEstimation/Plane.h
C
gpl-3.0
3,087
#ifndef QFILE_HH #define QFILE_HH #include <map> #include <vector> #include <string> /// wrapper for multimap<std::string,std::string> with useful functions class Stringmap { public: /// constructor Stringmap(const std::string& str = ""); /// copy constructor from another Stringmap Stringmap(const Stringmap& m); /// destructor virtual ~Stringmap() {} /// insert key/(string)value pair void insert(const std::string& str, const std::string& v); /// insert key/(double)value void insert(const std::string& str, double d); /// retrieve key values std::vector<std::string> retrieve(const std::string& str) const; /// get first key value (string) or default std::string getDefault(const std::string& str, const std::string& d) const; /// return number of elements unsigned int size() const { return dat.size(); } /// return count of entries with key unsigned int count(const std::string& str) const { return dat.count(str); } /// serialize to a string std::string toString() const; /// get first key value (double) or default double getDefault(const std::string& str, double d) const; /// get first key value (int) or default int getDefaultI(const std::string& str, int d) const; /// retrieve key values as doubles std::vector<double> retrieveDouble(const std::string& str) const; /// remove a key void erase(const std::string& str); /// display to screen void display(std::string linepfx = "") const; /// merge data from another stringmap void operator+=(const Stringmap& S) { S.mergeInto(*this); } /// convert to RData format //RData* toRData() const; std::multimap< std::string, std::string > dat; ///< key-value multimap protected: /// merge data into another stringmap void mergeInto(Stringmap& S) const; }; /// base class for objects that provide stringmaps class StringmapProvider { public: /// constructor StringmapProvider(): Sxtra() {} /// destructor virtual ~StringmapProvider() {} /// insert key/(string)value pair void insert(const std::string& str, const std::string& v) { Sxtra.insert(str,v); } /// insert key/(double)value void insert(const std::string& str, double d) { Sxtra.insert(str,d); } /// provide stringmap from self properties Stringmap toStringmap() const { Stringmap sm = getProperties(); sm += Sxtra; return sm; } /// display void display(std::string linepfx = "") const { toStringmap().display(linepfx); } protected: Stringmap Sxtra; virtual Stringmap getProperties() const { return Stringmap(); } }; /// wrapper for multimap<std::string,Stringmap> with useful functions class QFile { public: /// constructor given a string QFile(const std::string& s = "", bool readit = true); /// insert key/(string)value pair void insert(const std::string& str, const Stringmap& v); /// remove a key void erase(const std::string& str); /// retrieve values for key std::vector<Stringmap> retrieve(const std::string& s) const; /// retrieve first value for key Stringmap getFirst(const std::string& str, const Stringmap& dflt = Stringmap()) const; /// retrieve all sub-key values std::vector<std::string> retrieve(const std::string& k1, const std::string& k2) const; /// retreive sub-key with default std::string getDefault(const std::string& k1, const std::string& k2, const std::string& d) const; /// retrieve sub-key as double with default double getDefault(const std::string& k1, const std::string& k2, double d) const; /// retrieve all sub-key values as doubles std::vector<double> retrieveDouble(const std::string& k1, const std::string& k2) const; /// return number of elements unsigned int size() const { return dat.size(); } /// transfer all data for given key from other QFile void transfer(const QFile& Q, const std::string& k); /// set output file location void setOutfile(std::string fnm) { name = fnm; } /// commit data to file void commit(std::string outname = "") const; /// display to stdout void display() const; /// convert to RData format //RData* toRData() const; protected: std::string name; ///< name for this object std::multimap< std::string, Stringmap > dat; ///< key-value multimap }; #endif
UCNA/main
IOUtils/QFile.hh
C++
gpl-3.0
4,172
/* * JavaDoq 1.0 - DOCUment JAVA In Source * Copyright (C) 2008-2011 J.J.Liu<jianjunliu@126.com> <http://www.javadoq.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.javadoq.javadoc; /** * <p>An abstract base class for JavadocParser {@link Token}.</p> * * @author <a href="mailto:jianjunliu@126.com">J.J.Liu (Jianjun Liu)</a> at <a href="http://www.javadoq.com" target="_blank">http://www.javadoq.com</a> */ public abstract class AbstractToken { /** * <p>The real kind of the token in comparison with {@link Token#kind}.</p> * @since 1.0 */ public int realKind; }
jianjunl/javadoq
src/com/javadoq/javadoc/AbstractToken.java
Java
gpl-3.0
1,277
package solution100_199.solution160; /** * Script Created by daidai on 2017/8/13. */ import structure.ListNode; /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if (headA == null || headB == null) { return null; } ListNode a = headA; ListNode b = headB; while (a != b) { a = (a == null ? headB : a.next); b = (b == null ? headA : b.next); } return a; } }
alex1993/Leetcode
src/solution100_199/solution160/Solution.java
Java
gpl-3.0
699
/** * contains all the exceptions used in this application * @author Jan P.C. Hanson * */ package tomoBay.exceptions;
jpchanson/OpenDMS
src/tomoBay/exceptions/package-info.java
Java
gpl-3.0
121
/***************************************************************** * This file is part of Managing Agricultural Research for Learning & * Outcomes Platform (MARLO). * MARLO 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. * MARLO 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 MARLO. If not, see <http://www.gnu.org/licenses/>. *****************************************************************/ /************** * @author Diego Perez - CIAT/CCAFS **************/ package org.cgiar.ccafs.marlo.rest.dto; import io.swagger.annotations.ApiModelProperty; public class NewW1W2ExpenditureDTO { @ApiModelProperty(notes = "Expenditure example summary", position = 1) private String exampleExpenditure; @ApiModelProperty(notes = "Expenditure Area", position = 2) private Long expenditureAreaID; @ApiModelProperty(notes = "Phase POWB/AR", position = 3) private PhaseDTO phase; public String getExampleExpenditure() { return exampleExpenditure; } public Long getExpenditureAreaID() { return expenditureAreaID; } public PhaseDTO getPhase() { return phase; } public void setExampleExpenditure(String exampleExpenditure) { this.exampleExpenditure = exampleExpenditure; } public void setExpenditureAreaID(Long expenditureAreaID) { this.expenditureAreaID = expenditureAreaID; } public void setPhase(PhaseDTO phase) { this.phase = phase; } }
CCAFS/MARLO
marlo-web/src/main/java/org/cgiar/ccafs/marlo/rest/dto/NewW1W2ExpenditureDTO.java
Java
gpl-3.0
1,929
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Abide.Tag.Cache.Generated { using System; using Abide.HaloLibrary; using Abide.Tag; /// <summary> /// Represents the generated sector_link_block tag block. /// </summary> public sealed class SectorLinkBlock : Block { /// <summary> /// Initializes a new instance of the <see cref="SectorLinkBlock"/> class. /// </summary> public SectorLinkBlock() { this.Fields.Add(new ShortIntegerField("vertex 1")); this.Fields.Add(new ShortIntegerField("vertex 2")); this.Fields.Add(new WordFlagsField("link flags", "sector link from collision edge", "sector intersection link", "sector link bsp2d creation error", "sector link topology error", "sector link chain error", "sector link both sectors walkable", "sector link magic hanging link", "sector link threshold", "sector link crouchable", "sector link wall base", "sector link ledge", "sector link leanable", "sector link start corner", "sector link end corner")); this.Fields.Add(new ShortIntegerField("hint index")); this.Fields.Add(new ShortIntegerField("forward link")); this.Fields.Add(new ShortIntegerField("reverse link")); this.Fields.Add(new ShortIntegerField("left sector")); this.Fields.Add(new ShortIntegerField("right sector")); } /// <summary> /// Gets and returns the name of the sector_link_block tag block. /// </summary> public override string BlockName { get { return "sector_link_block"; } } /// <summary> /// Gets and returns the display name of the sector_link_block tag block. /// </summary> public override string DisplayName { get { return "sector_link_block"; } } /// <summary> /// Gets and returns the maximum number of elements allowed of the sector_link_block tag block. /// </summary> public override int MaximumElementCount { get { return 262144; } } /// <summary> /// Gets and returns the alignment of the sector_link_block tag block. /// </summary> public override int Alignment { get { return 4; } } } }
MikeMatt16/Abide
Abide Tag Definitions/Generated/Cache/SectorLinkBlock.Generated.cs
C#
gpl-3.0
2,870
/* 9. Um coeficiente binomial, geralmente denotado (n?k), representa o número de possı́veis combinações de n elementos tomados k a k. Um “Triângulo de Pascal”, uma homenagem ao grande matemático Blaise Pascal, é uma tabela de valores de coeficientes combinatoriais para pequenos valores de n e k. Os números que não são mostrados na tabela têm valor zero. Este triângulo pode ser construı́do auto- maticamente usando-se uma propriedade conhecida dos coeficientes binomiais, denominada “fórmula da adição": (r?k) = (r-1 ?k ) + (r-1 ? k-1) ou seja, cada elemento do triângulo é a soma de dois elementos da linha anterior, um da mesma coluna e um da coluna anterior. Veja um exemplo de um triângulo de Pascal com 7 linhas: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 Faça um programa em que imprima na tela um triângulo de Pascal com 10 linhas. Seu programa deve obrigatoriamente fazer uso de exatamente dois vetores durante o processo de construção. Um deles conterá a última linha ı́mpar gerada, enquanto que o outro conterá a última linha par gerada. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define ANSI_COLOR_RED "\x1b[31m" #define ANSI_COLOR_GREEN "\x1b[32m" #define ANSI_COLOR_YELLOW "\x1b[33m" #define ANSI_COLOR_BLUE "\x1b[34m" #define ANSI_COLOR_MAGENTA "\x1b[35m" #define ANSI_COLOR_CYAN "\x1b[36m" #define ANSI_COLOR_RESET "\x1b[0m" #define RESET "\033[1;25r" #define DEBUG 0 #define TAMANHO 20 void mostra(int *seq, int tam); void mostrad(int *seq, int destaque, int tam); int main(){ int *bp = NULL, k=0, tam=1; bp = malloc(sizeof(int)*TAMANHO); for (int i=0; i < TAMANHO; i++) bp[i]=0; bp[0]=1; printf("1\n"); do { if (DEBUG){ printf("Loop>> k: %d, t: %d\n",k,tam); } bp[tam++] = 1; mostra(bp,tam); for(int i=(tam-1); i > 0; i--){ bp[i] = bp[i-1] + bp[i]; } k++; } while (k < TAMANHO); return 0; } void mostra(int *seq, int tam){ mostrad(seq,-1,tam); } void mostrad(int *seq, int destaque, int tam){ for(int x=0; x<tam;x++){ if (x==destaque) printf(ANSI_COLOR_RED"%d "ANSI_COLOR_RESET ,seq[x]); else printf("%d ",seq[x]); } printf("\n"); if (DEBUG){ printf("Mostrou com: dest: %d, tam: %d\n",destaque,tam); } }
Spacial/csstuff
Algorithms/C/1list/exerc09.c
C
gpl-3.0
2,496
package vc.pvp.skywars.listeners; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.*; import vc.pvp.skywars.SkyWars; import vc.pvp.skywars.config.PluginConfig; import vc.pvp.skywars.controllers.GameController; import vc.pvp.skywars.controllers.PlayerController; import vc.pvp.skywars.controllers.SchematicController; import vc.pvp.skywars.game.Game; import vc.pvp.skywars.game.GameState; import vc.pvp.skywars.player.GamePlayer; import vc.pvp.skywars.utilities.Messaging; import vc.pvp.skywars.utilities.StringUtils; import java.util.Iterator; public class PlayerListener implements Listener { @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { PlayerController.get().register(event.getPlayer()); } @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { Player player = event.getPlayer(); GamePlayer gamePlayer = PlayerController.get().get(player); if (gamePlayer.isPlaying()) { gamePlayer.getGame().onPlayerLeave(gamePlayer); } gamePlayer.save(); PlayerController.get().unregister(player); } @EventHandler public void onPlayerRespawn(PlayerRespawnEvent event) { Player player = event.getPlayer(); final GamePlayer gamePlayer = PlayerController.get().get(player); if (gamePlayer.isPlaying()) { event.setRespawnLocation(PluginConfig.getLobbySpawn()); if (PluginConfig.saveInventory()) { Bukkit.getScheduler().runTaskLater(SkyWars.get(), new Runnable() { @Override public void run() { gamePlayer.restoreState(); } }, 1L); } } } @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { Player player = event.getPlayer(); GamePlayer gamePlayer = PlayerController.get().get(player); if (event.getAction() == Action.PHYSICAL && event.getClickedBlock().getTypeId() == Material.STONE_PLATE.getId()) { if (!gamePlayer.isPlaying() && player.getLocation().getWorld().equals(PluginConfig.getLobbySpawn().getWorld())) { if (SchematicController.get().size() == 0) { player.sendMessage(new Messaging.MessageFormatter().format("error.no-schematics")); return; } Game game = GameController.get().findEmpty(); game.onPlayerJoin(gamePlayer); } return; } if (gamePlayer.isPlaying() && gamePlayer.getGame().getState() != GameState.PLAYING) { event.setCancelled(true); } } @EventHandler public void onPlayerChat(AsyncPlayerChatEvent event) { Player player = event.getPlayer(); GamePlayer gamePlayer = PlayerController.get().get(player); if (PluginConfig.chatHandledByOtherPlugin()) { event.setFormat(event.getFormat().replace("[score]", String.valueOf(gamePlayer.getScore()))); if (gamePlayer.isPlaying()) { for (Iterator<Player> iterator = event.getRecipients().iterator(); iterator.hasNext();) { GamePlayer gp = PlayerController.get().get(iterator.next()); if (!gp.isPlaying() || !gp.getGame().equals(gamePlayer.getGame())) { iterator.remove(); } } } else { for (Iterator<Player> iterator = event.getRecipients().iterator(); iterator.hasNext();) { GamePlayer gp = PlayerController.get().get(iterator.next()); if (gp.isPlaying()) { iterator.remove(); } } } return; } String message = new Messaging.MessageFormatter() .setVariable("score", StringUtils.formatScore(gamePlayer.getScore())) .setVariable("player", player.getDisplayName()) .setVariable("message", Messaging.stripColor(event.getMessage())) .setVariable("prefix", SkyWars.getChat().getPlayerPrefix(player)) .format("chat.local"); event.setCancelled(true); if (gamePlayer.isPlaying()) { gamePlayer.getGame().sendMessage(message); } else { for (GamePlayer gp : PlayerController.get().getAll()) { if (!gp.isPlaying()) { gp.getBukkitPlayer().sendMessage(message); } } } } @EventHandler public void onPlayerCommand(PlayerCommandPreprocessEvent event) { Player player = event.getPlayer(); GamePlayer gamePlayer = PlayerController.get().get(player); if (gamePlayer.isPlaying()) { String command = event.getMessage().split(" ")[0].toLowerCase(); if (!command.equals("/sw") && !PluginConfig.isCommandWhitelisted(command)) { event.setCancelled(true); player.sendMessage( new Messaging.MessageFormatter().withPrefix().format("error.cmd-disabled")); } } } }
Wietje/SkyWars
src/main/java/vc/pvp/skywars/listeners/PlayerListener.java
Java
gpl-3.0
5,386
#include "geoutil.h" double getAngle(Point & a, Point & b) { return atan2(b.y - a.y, b.x - a.x); } Point getCenterOfSegmentEnd(tTrackSeg *seg) { return getWeightedPointAtSegmentEnd(seg, 1, 1); } double getDistanceToSegmentEnd(tCarElt *car) { tTrackSeg *seg = car->_trkPos.seg; if (seg->type == TR_STR) return seg->length - car->_trkPos.toStart; else return (seg->arc - car->_trkPos.toStart) * seg->radius; } Point getWeightedPointAtSegmentEnd(tTrackSeg *seg, double wLeft, double wRight) { double x = (wLeft * seg->vertex[TR_EL].x + wRight * seg->vertex[TR_ER].x) / (wLeft + wRight); double y = (wLeft * seg->vertex[TR_EL].y + wRight * seg->vertex[TR_ER].y) / (wLeft + wRight); return Point(x, y); }
non-official-SD/base
src/drivers/urbanski/geoutil.cpp
C++
gpl-3.0
716
opensupports_version = '4.11.0'; root = 'http://localhost:3000'; apiRoot = 'http://localhost:3000/api'; globalIndexPath = ''; showLogs = true;
opensupports/opensupports
client/src/config.js
JavaScript
gpl-3.0
143
/* * zselect.c - builtin support for select system call * * This file is part of zsh, the Z shell. * * Copyright (c) 1998-2001 Peter Stephenson * All rights reserved. * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and to distribute modified versions of this software for any * purpose, provided that the above copyright notice and the following * two paragraphs appear in all copies of this software. * * In no event shall Peter Stephenson or the Zsh Development * Group be liable to any party for direct, indirect, special, incidental, * or consequential damages arising out of the use of this software and * its documentation, even if Peter Stephenson, and the Zsh * Development Group have been advised of the possibility of such damage. * * Peter Stephenson and the Zsh Development Group specifically * disclaim any warranties, including, but not limited to, the implied * warranties of merchantability and fitness for a particular purpose. The * software provided hereunder is on an "as is" basis, and Peter Stephenson * and the Zsh Development Group have no obligation to provide maintenance, * support, updates, enhancements, or modifications. * */ #include "zselect.mdh" #include "zselect.pro" /* Helper functions */ /* * Handle an fd by adding it to the current fd_set. * Return 1 for error (after printing a message), 0 for OK. */ static int handle_digits(char *nam, char *argptr, fd_set *fdset, int *fdmax) { int fd; char *endptr; if (!idigit(*argptr)) { zwarnnam(nam, "expecting file descriptor: %s", argptr); return 1; } fd = (int)zstrtol(argptr, &endptr, 10); if (*endptr) { zwarnnam(nam, "garbage after file descriptor: %s", endptr); return 1; } FD_SET(fd, fdset); if (fd+1 > *fdmax) *fdmax = fd+1; return 0; } /* The builtin itself */ /**/ static int bin_zselect(char *nam, char **args, UNUSED(Options ops), UNUSED(int func)) { #ifdef HAVE_SELECT int i, fd, fdsetind = 0, fdmax = 0, fdcount; fd_set fdset[3]; const char fdchar[3] = "rwe"; struct timeval tv, *tvptr = NULL; char *outarray = "reply", **outdata, **outptr; char *outhash = NULL; LinkList fdlist; for (i = 0; i < 3; i++) FD_ZERO(fdset+i); for (; *args; args++) { char *argptr = *args, *endptr; zlong tempnum; if (*argptr == '-') { for (argptr++; *argptr; argptr++) { switch (*argptr) { /* * Array name for reply, if not $reply. * This gets set to e.g. `-r 0 -w 1' if 0 is ready * for reading and 1 is ready for writing. */ case 'a': case 'A': i = *argptr; if (argptr[1]) argptr++; else if (args[1]) { argptr = *++args; } else { zwarnnam(nam, "argument expected after -%c", *argptr); return 1; } if (idigit(*argptr) || !isident(argptr)) { zwarnnam(nam, "invalid array name: %s", argptr); return 1; } if (i == 'a') outarray = argptr; else outhash = argptr; /* set argptr to next to last char because of increment */ while (argptr[1]) argptr++; break; /* Following numbers indicate fd's for reading */ case 'r': fdsetind = 0; break; /* Following numbers indicate fd's for writing */ case 'w': fdsetind = 1; break; /* Following numbers indicate fd's for errors */ case 'e': fdsetind = 2; break; /* * Get a timeout value in hundredths of a second * (same units as KEYTIMEOUT). 0 means just poll. * If not given, blocks indefinitely. */ case 't': if (argptr[1]) argptr++; else if (args[1]) { argptr = *++args; } else { zwarnnam(nam, "argument expected after -%c", *argptr); return 1; } if (!idigit(*argptr)) { zwarnnam(nam, "number expected after -t"); return 1; } tempnum = zstrtol(argptr, &endptr, 10); if (*endptr) { zwarnnam(nam, "garbage after -t argument: %s", endptr); return 1; } /* timevalue now active */ tvptr = &tv; tv.tv_sec = (long)(tempnum / 100); tv.tv_usec = (long)(tempnum % 100) * 10000L; /* remember argptr is incremented at end of loop */ argptr = endptr - 1; break; /* Digits following option without arguments are fd's. */ default: if (handle_digits(nam, argptr, fdset+fdsetind, &fdmax)) return 1; } } } else if (handle_digits(nam, argptr, fdset+fdsetind, &fdmax)) return 1; } errno = 0; do { i = select(fdmax, (SELECT_ARG_2_T)fdset, (SELECT_ARG_2_T)(fdset+1), (SELECT_ARG_2_T)(fdset+2), tvptr); } while (i < 0 && errno == EINTR && !errflag); if (i <= 0) { if (i < 0) zwarnnam(nam, "error on select: %e", errno); /* else no fd's set. Presumably a timeout. */ return 1; } /* * Make a linked list of all file descriptors which are ready. * These go into an array preceded by -r, -w or -e for read, write, * error as appropriate. Typically there will only be one set * so this looks rather like overkill. */ fdlist = znewlinklist(); for (i = 0; i < 3; i++) { int doneit = 0; for (fd = 0; fd < fdmax; fd++) { if (FD_ISSET(fd, fdset+i)) { char buf[BDIGBUFSIZE]; if (outhash) { /* * Key/value pairs; keys are fd's (as strings), * value is a (possibly improper) subset of "rwe". */ LinkNode nptr; int found = 0; convbase(buf, fd, 10); for (nptr = firstnode(fdlist); nptr; nptr = nextnode(nextnode(nptr))) { if (!strcmp((char *)getdata(nptr), buf)) { /* Already there, add new character. */ void **dataptr = getaddrdata(nextnode(nptr)); char *data = (char *)*dataptr, *ptr; found = 1; if (!strchr(data, fdchar[i])) { strcpy(buf, data); for (ptr = buf; *ptr; ptr++) ; *ptr++ = fdchar[i]; *ptr = '\0'; zsfree(data); *dataptr = ztrdup(buf); } break; } } if (!found) { /* Add new key/value pair. */ zaddlinknode(fdlist, ztrdup(buf)); buf[0] = fdchar[i]; buf[1] = '\0'; zaddlinknode(fdlist, ztrdup(buf)); } } else { /* List of fd's preceded by -r, -w, -e. */ if (!doneit) { buf[0] = '-'; buf[1] = fdchar[i]; buf[2] = 0; zaddlinknode(fdlist, ztrdup(buf)); doneit = 1; } convbase(buf, fd, 10); zaddlinknode(fdlist, ztrdup(buf)); } } } } /* convert list to array */ fdcount = countlinknodes(fdlist); outptr = outdata = (char **)zalloc((fdcount+1)*sizeof(char *)); while (nonempty(fdlist)) *outptr++ = getlinknode(fdlist); *outptr = NULL; /* and store in array parameter */ if (outhash) sethparam(outhash, outdata); else setaparam(outarray, outdata); freelinklist(fdlist, NULL); return 0; #else /* TODO: use poll */ zerrnam(nam, "your system does not implement the select system call."); return 2; #endif } static struct builtin bintab[] = { BUILTIN("zselect", 0, bin_zselect, 0, -1, 0, NULL, NULL), }; static struct features module_features = { bintab, sizeof(bintab)/sizeof(*bintab), NULL, 0, NULL, 0, NULL, 0, 0 }; /* The load/unload routines required by the zsh library interface */ /**/ int setup_(UNUSED(Module m)) { return 0; } /**/ int features_(Module m, char ***features) { *features = featuresarray(m, &module_features); return 0; } /**/ int enables_(Module m, int **enables) { return handlefeatures(m, &module_features, enables); } /**/ int boot_(UNUSED(Module m)) { return 0; } /**/ int cleanup_(Module m) { return setfeatureenables(m, &module_features, NULL); } /**/ int finish_(UNUSED(Module m)) { return 0; }
mgood7123/UPM
Sources/zsh-5.4.2/Src/Modules/zselect.c
C
gpl-3.0
7,892
#!/usr/bin/perl use strict; use warnings; use lib '../lib'; use Data::Dumper; use NagiosConfigObjects; my $objcontact = NagiosConfigObjects->new({ file => '/var/www/cgi-bin/contacts.cfg', filter => 'contact' }); my $objcontactgroup = NagiosConfigObjects->new({ file => '/var/www/cgi-bin/contacts.cfg', filter => 'contactgroup' }); print Dumper($objcontact->get_allobjects); print Dumper($objcontactgroup->get_allobjects);
delfinebuejr/ldap-nagios
examples/test_nagcon.pl
Perl
gpl-3.0
627
package evercraft.NEMESIS13cz.Tools.Shovels; import java.util.List; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemSpade; import net.minecraft.item.ItemStack; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import evercraft.NEMESIS13cz.ModInformation; public class ItemBronzeShovel extends ItemSpade { public ItemBronzeShovel(Item.ToolMaterial par2EnumToolMaterial) { super(par2EnumToolMaterial); } public void addInformation(ItemStack par1, EntityPlayer par2, List par3, boolean par4) { par3.add("Uses: " + (this.getMaxDamage() - this.getDamage(par1))); par3.add("Digging Speed: 3.0"); } @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister par1IconRegister) { this.itemIcon = par1IconRegister.registerIcon(ModInformation.TEXTUREPATH + ":" + ModInformation.BRONZE_SPADE); } }
NEMESIS13cz/Evercraft
java/evercraft/NEMESIS13cz/Tools/Shovels/ItemBronzeShovel.java
Java
gpl-3.0
1,036
/// \file /// \brief The view_cache class header /// \copyright /// CATH Tools - Protein structure comparison tools such as SSAP and SNAP /// Copyright (C) 2011, Orengo Group, University College London /// /// 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/>. #ifndef _CATH_TOOLS_SOURCE_CT_UNI_CATH_STRUCTURE_VIEW_CACHE_VIEW_CACHE_HPP #define _CATH_TOOLS_SOURCE_CT_UNI_CATH_STRUCTURE_VIEW_CACHE_VIEW_CACHE_HPP #include "cath/structure/geometry/coord.hpp" #include "cath/structure/structure_type_aliases.hpp" // clang-format off namespace cath { class protein; } // clang-format on namespace cath::index { /// \brief Cache of views (ie vectors implemented as coords) between pairs of residues in a particular list /// (most likely a protein) class view_cache final { private: /// \brief The views - coords indexed by the from-residue and then by the to-residue geom::coord_vec_vec views; static geom::coord_vec_vec build_views(const protein &); public: explicit view_cache(const protein &); [[nodiscard]] const geom::coord &get_view( const size_t &, const size_t & ) const; }; /// \brief Getter for the view from residue with the specified from-index to the residue with the specified to-index inline const geom::coord & view_cache::get_view(const size_t &prm_from_index, ///< The index of the from-residue of the view to be retrieved const size_t &prm_to_index ///< The index of the to-residue of the view to be retrieved ) const { return views[ prm_from_index ][ prm_to_index ]; } } // namespace cath::index #endif // _CATH_TOOLS_SOURCE_CT_UNI_CATH_STRUCTURE_VIEW_CACHE_VIEW_CACHE_HPP
UCLOrengoGroup/cath-tools
source/ct_uni/cath/structure/view_cache/view_cache.hpp
C++
gpl-3.0
2,335
#include "py_discrete_multipole.h"
junkoda/lss-ps
py/py_discrete_multipole.cpp
C++
gpl-3.0
35
/************************************************************************* * Copyright 2009-2013 Eucalyptus Systems, Inc. * * 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; version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. * * Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta * CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need * additional information or have any questions. ************************************************************************/ package com.eucalyptus.imaging; import java.lang.reflect.InvocationTargetException; import com.eucalyptus.util.Exceptions; import com.eucalyptus.ws.EucalyptusWebServiceException; import com.eucalyptus.ws.Role; /** * @author Chris Grzegorczyk <grze@eucalyptus.com> */ public class ImagingServiceException extends EucalyptusWebServiceException { public static final Role DEFAULT_ROLE = Role.Sender; public static final String DEFAULT_CODE = "400"; public static final String INTERNAL_SERVER_ERROR = "500"; protected ImagingServiceException( final String code, final Role role, final String message ) { super( code, role, message ); } public ImagingServiceException(final String code, final String message){ this( code, DEFAULT_ROLE, message); } public ImagingServiceException(final String code, final String message, final Throwable inner){ this(code, DEFAULT_ROLE, message); this.initCause(inner); } public ImagingServiceException(final String message){ this(DEFAULT_CODE, DEFAULT_ROLE, message); } public ImagingServiceException(final String message, Throwable inner){ this(DEFAULT_CODE, DEFAULT_ROLE, message); this.initCause(inner); } public static <T extends ImagingServiceException> T rethrow( Class<T> type, String message ) { try { return type.getConstructor( new Class[] { String.class } ).newInstance( new Object[] { message } ); } catch ( InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ex ) { throw Exceptions.toUndeclared( ex ); } } }
davenpcj5542009/eucalyptus
clc/modules/imaging/src/main/java/com/eucalyptus/imaging/ImagingServiceException.java
Java
gpl-3.0
2,742
# 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/>. # Written by Bram Cohen import re from BitTorrent import BTFailure allowed_path_re = re.compile(r'^[^/\\.~][^/\\]*$') ints = (long, int) def check_info(info, check_paths=True): if type(info) != dict: raise BTFailure, 'bad metainfo - not a dictionary' pieces = info.get('pieces') if type(pieces) != str or len(pieces) % 20 != 0: raise BTFailure, 'bad metainfo - bad pieces key' piecelength = info.get('piece length') if type(piecelength) not in ints or piecelength <= 0: raise BTFailure, 'bad metainfo - illegal piece length' name = info.get('name') if type(name) != str: raise BTFailure, 'bad metainfo - bad name' if not allowed_path_re.match(name): raise BTFailure, 'name %s disallowed for security reasons' % name if info.has_key('files') == info.has_key('length'): raise BTFailure, 'single/multiple file mix' if info.has_key('length'): length = info.get('length') if type(length) not in ints or length < 0: raise BTFailure, 'bad metainfo - bad length' else: files = info.get('files') if type(files) != list: raise BTFailure, 'bad metainfo - "files" is not a list of files' for f in files: if type(f) != dict: raise BTFailure, 'bad metainfo - bad file value' length = f.get('length') if type(length) not in ints or length < 0: raise BTFailure, 'bad metainfo - bad length' path = f.get('path') if type(path) != list or path == []: raise BTFailure, 'bad metainfo - bad path' for p in path: if type(p) != str: raise BTFailure, 'bad metainfo - bad path dir' if check_paths and not allowed_path_re.match(p): raise BTFailure, 'path %s disallowed for security reasons' % p f = ['/'.join(x['path']) for x in files] f.sort() i = iter(f) try: name2 = i.next() while True: name1 = name2 name2 = i.next() if name2.startswith(name1): if name1 == name2: raise BTFailure, 'bad metainfo - duplicate path' elif name2[len(name1)] == '/': raise BTFailure('bad metainfo - name used as both ' 'file and subdirectory name') except StopIteration: pass def check_message(message, check_paths=True): if type(message) != dict: raise BTFailure, 'bad metainfo - wrong object type' check_info(message.get('info'), check_paths) if type(message.get('announce')) != str: raise BTFailure, 'bad metainfo - no announce URL string' def check_peers(message): if type(message) != dict: raise BTFailure if message.has_key('failure reason'): if type(message['failure reason']) != str: raise BTFailure, 'non-text failure reason' return if message.has_key('warning message'): if type(message['warning message']) != str: raise BTFailure, 'non-text warning message' peers = message.get('peers') if type(peers) == list: for p in peers: if type(p) != dict: raise BTFailure, 'invalid entry in peer list' if type(p.get('ip')) != str: raise BTFailure, 'invalid entry in peer list' port = p.get('port') if type(port) not in ints or p <= 0: raise BTFailure, 'invalid entry in peer list' if p.has_key('peer id'): peerid = p.get('peer id') if type(peerid) != str or len(peerid) != 20: raise BTFailure, 'invalid entry in peer list' elif type(peers) != str or len(peers) % 6 != 0: raise BTFailure, 'invalid peer list' interval = message.get('interval', 1) if type(interval) not in ints or interval <= 0: raise BTFailure, 'invalid announce interval' minint = message.get('min interval', 1) if type(minint) not in ints or minint <= 0: raise BTFailure, 'invalid min announce interval' if type(message.get('tracker id', '')) != str: raise BTFailure, 'invalid tracker id' npeers = message.get('num peers', 0) if type(npeers) not in ints or npeers < 0: raise BTFailure, 'invalid peer count' dpeers = message.get('done peers', 0) if type(dpeers) not in ints or dpeers < 0: raise BTFailure, 'invalid seed count' last = message.get('last', 0) if type(last) not in ints or last < 0: raise BTFailure, 'invalid "last" entry'
santazhang/BitTorrent-4.0.0-GPL
BitTorrent/btformats.py
Python
gpl-3.0
5,378
package me.realized.duels.api.event.queue.sign; import javax.annotation.Nonnull; import me.realized.duels.api.queue.sign.QueueSign; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; /** * Called when a {@link QueueSign} is removed. * * @see QueueSign#isRemoved() * @since 3.2.0 */ public class QueueSignRemoveEvent extends QueueSignEvent { private static final HandlerList handlers = new HandlerList(); public QueueSignRemoveEvent(@Nonnull final Player source, @Nonnull final QueueSign queueSign) { super(source, queueSign); } public static HandlerList getHandlerList() { return handlers; } @Override public HandlerList getHandlers() { return handlers; } }
RealizedMC/Duels
duels-api/src/main/java/me/realized/duels/api/event/queue/sign/QueueSignRemoveEvent.java
Java
gpl-3.0
744
using System; using System.Collections.Generic; using System.Data.Entity.Migrations; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Web.Security; using Microsoft.AspNet.Identity.Owin; using Snapplicator.Areas.Install.Models; using Snapplicator.Models; using Snapplicator.Services; namespace Snapplicator.Areas.Install.Controllers { public class InstallController : Controller { private readonly ISettingService _settingService; private readonly IUserService _userService; public InstallController(ISettingService settingService, IUserService userService) { _settingService = settingService; _userService = userService; } public ActionResult AlreadyInstalled() { return null; } public ActionResult Step1() { if (_userService.GetUsers().Any()) return RedirectToAction("AlreadyInstalled"); return View(); } [HttpPost] public async Task<ActionResult> Step1(Step1Model model) { if (_userService.GetUsers().Any()) return RedirectToAction("AlreadyInstalled"); if (ModelState.IsValid) { _settingService.UpdateValueByKey("WebsiteName", model.WebsiteName); var user = new User { UserName = model.AdminUsername, Email = model.AdminEmailAddress, TimeCreated = DateTime.Now, TimeUpdated = DateTime.Now }; var result = await UserManager.CreateAsync(user, model.AdminPassword); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); if(!Roles.RoleExists("Admin")) Roles.CreateRole("Admin"); // I've run into some issues with wiped databases where the AddUserToRole() // call areas out. if(!Roles.IsUserInRole(model.AdminUsername, "Admin")) Roles.AddUserToRole(model.AdminUsername, "Admin"); return RedirectToAction("Step2", "Install"); } } return View(model); } // Right now, this just runs the DB seed and doesn't present anything // in the UI to the user public ActionResult Step2() { var seeder = new DataSeeder(new SnapplicatorContext()); seeder.SeedAll(); return RedirectToAction("Complete", "Install"); } public ActionResult Complete() { return View(); } // TODO: A bunch of stuff from the boilerplate AccountController is below. This should be moved // into UserService and the above refactored. private ApplicationSignInManager _signInManager; private ApplicationUserManager _userManager; public ApplicationSignInManager SignInManager { get { return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); } private set { _signInManager = value; } } public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } } }
ExistentialEnso/Snapplicator
Snapplicator/Areas/Install/Controllers/InstallController.cs
C#
gpl-3.0
3,660
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2015 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::pointSmoothingMeshMover Description Quality-based under-relaxation for run-time selectable point smoothing. SourceFiles pointSmoothingMeshMover.C \*---------------------------------------------------------------------------*/ #ifndef pointSmoothingMeshMover_H #define pointSmoothingMeshMover_H #include "externalDisplacementMeshMover.H" #include "pointSmoother.H" #include "polyMeshGeometry.H" #include "motionSmootherAlgo.H" #include "fieldSmoother.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { /*---------------------------------------------------------------------------*\ Class pointSmoothingMeshMover Declaration \*---------------------------------------------------------------------------*/ class pointSmoothingMeshMover : public externalDisplacementMeshMover { // Private Data //- Part-updatable mesh geometry polyMeshGeometry meshGeometry_; //- Point smoothing method autoPtr<pointSmoother> pointSmoother_; //- IDs of fixedValue patches that we can modify const labelList adaptPatchIDs_; //- Combined indirect fixedValue patches that we can modify autoPtr<indirectPrimitivePatch> adaptPatchPtr_; //- Scale factor for displacement pointScalarField scale_; //- Old point field pointField oldPoints_; //- Mesh mover algorithm motionSmootherAlgo meshMover_; //- Field smoothing fieldSmoother fieldSmoother_; // Private Member Functions //- Apply the mesh mover algorithm bool moveMesh ( const dictionary& moveDict, const label nAllowableErrors, labelList& checkFaces ); public: //- Runtime type information TypeName("displacementPointSmoothing"); // Constructors //- Construct from a polyMesh and an IOdictionary pointSmoothingMeshMover ( const dictionary& dict, const List<labelPair>& baffles, pointVectorField& pointDisplacement ); //- Destructor virtual ~pointSmoothingMeshMover(); // Member Functions //- Move mesh using current pointDisplacement boundary values. // Return true if succesful (errors on checkFaces less than // allowable). Updates pointDisplacement. virtual bool move ( const dictionary&, const label nAllowableErrors, labelList& checkFaces ); //- Update local data for geometry changes virtual void movePoints(const pointField&); //- Update local data for topology changes virtual void updateMesh(const mapPolyMesh&) { notImplemented ( "medialAxisMeshMover::updateMesh" "(const mapPolyMesh&)" ); } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
OpenCFD/OpenFOAM-history
src/mesh/autoMesh/autoHexMesh/externalDisplacementMeshMover/pointSmoothingMeshMover.H
C++
gpl-3.0
4,309
/* A tar (tape archiver) program. Copyright 1988, 1992-1997, 1999-2001, 2003-2007, 2012-2014 Free Software Foundation, Inc. Written by John Gilmore, starting 1985-08-25. 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, 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 <system.h> #include <fnmatch.h> #include <argp.h> #include <argp-namefrob.h> #include <argp-fmtstream.h> #include <argp-version-etc.h> #include <signal.h> #if ! defined SIGCHLD && defined SIGCLD # define SIGCHLD SIGCLD #endif /* The following causes "common.h" to produce definitions of all the global variables, rather than just "extern" declarations of them. GNU tar does depend on the system loader to preset all GLOBAL variables to neutral (or zero) values; explicit initialization is usually not done. */ #define GLOBAL #include "common.h" #include <argmatch.h> #include <closeout.h> #include <configmake.h> #include <exitfail.h> #include <parse-datetime.h> #include <rmt.h> #include <rmt-command.h> #include <prepargs.h> #include <quotearg.h> #include <version-etc.h> #include <xstrtol.h> #include <stdopen.h> #include <priv-set.h> #include <savedir.h> /* Local declarations. */ #ifndef DEFAULT_ARCHIVE_FORMAT # define DEFAULT_ARCHIVE_FORMAT GNU_FORMAT #endif #ifndef DEFAULT_ARCHIVE # define DEFAULT_ARCHIVE "tar.out" #endif #ifndef DEFAULT_BLOCKING # define DEFAULT_BLOCKING 20 #endif /* Print a message if not all links are dumped */ static int check_links_option; /* Number of allocated tape drive names. */ static size_t allocated_archive_names; /* Miscellaneous. */ /* Name of option using stdin. */ static const char *stdin_used_by; /* Doesn't return if stdin already requested. */ void request_stdin (const char *option) { if (stdin_used_by) USAGE_ERROR ((0, 0, _("Options '%s' and '%s' both want standard input"), stdin_used_by, option)); stdin_used_by = option; } extern int rpmatch (char const *response); /* Returns true if and only if the user typed an affirmative response. */ int confirm (const char *message_action, const char *message_name) { static FILE *confirm_file; static int confirm_file_EOF; bool status = false; if (!confirm_file) { if (archive == 0 || stdin_used_by) { confirm_file = fopen (TTY_NAME, "r"); if (! confirm_file) open_fatal (TTY_NAME); } else { request_stdin ("-w"); confirm_file = stdin; } } fprintf (stdlis, "%s %s?", message_action, quote (message_name)); fflush (stdlis); if (!confirm_file_EOF) { char *response = NULL; size_t response_size = 0; if (getline (&response, &response_size, confirm_file) < 0) confirm_file_EOF = 1; else status = rpmatch (response) > 0; free (response); } if (confirm_file_EOF) { fputc ('\n', stdlis); fflush (stdlis); } return status; } static struct fmttab { char const *name; enum archive_format fmt; } const fmttab[] = { { "v7", V7_FORMAT }, { "oldgnu", OLDGNU_FORMAT }, { "ustar", USTAR_FORMAT }, { "posix", POSIX_FORMAT }, #if 0 /* not fully supported yet */ { "star", STAR_FORMAT }, #endif { "gnu", GNU_FORMAT }, { "pax", POSIX_FORMAT }, /* An alias for posix */ { NULL, 0 } }; static void set_archive_format (char const *name) { struct fmttab const *p; for (p = fmttab; strcmp (p->name, name) != 0; ) if (! (++p)->name) USAGE_ERROR ((0, 0, _("%s: Invalid archive format"), quotearg_colon (name))); archive_format = p->fmt; } static void set_xattr_option (int value) { if (value == 1) set_archive_format ("posix"); xattrs_option = value; } const char * archive_format_string (enum archive_format fmt) { struct fmttab const *p; for (p = fmttab; p->name; p++) if (p->fmt == fmt) return p->name; return "unknown?"; } #define FORMAT_MASK(n) (1<<(n)) static void assert_format(unsigned fmt_mask) { if ((FORMAT_MASK (archive_format) & fmt_mask) == 0) USAGE_ERROR ((0, 0, _("GNU features wanted on incompatible archive format"))); } const char * subcommand_string (enum subcommand c) { switch (c) { case UNKNOWN_SUBCOMMAND: return "unknown?"; case APPEND_SUBCOMMAND: return "-r"; case CAT_SUBCOMMAND: return "-A"; case CREATE_SUBCOMMAND: return "-c"; case DELETE_SUBCOMMAND: return "-D"; case DIFF_SUBCOMMAND: return "-d"; case EXTRACT_SUBCOMMAND: return "-x"; case LIST_SUBCOMMAND: return "-t"; case UPDATE_SUBCOMMAND: return "-u"; case TEST_LABEL_SUBCOMMAND: return "--test-label"; } abort (); } static void tar_list_quoting_styles (struct obstack *stk, char const *prefix) { int i; size_t prefixlen = strlen (prefix); for (i = 0; quoting_style_args[i]; i++) { obstack_grow (stk, prefix, prefixlen); obstack_grow (stk, quoting_style_args[i], strlen (quoting_style_args[i])); obstack_1grow (stk, '\n'); } } static void tar_set_quoting_style (char *arg) { int i; for (i = 0; quoting_style_args[i]; i++) if (strcmp (arg, quoting_style_args[i]) == 0) { set_quoting_style (NULL, i); return; } FATAL_ERROR ((0, 0, _("Unknown quoting style '%s'. Try '%s --quoting-style=help' to get a list."), arg, program_invocation_short_name)); } /* Options. */ enum { ACLS_OPTION = CHAR_MAX + 1, ANCHORED_OPTION, ATIME_PRESERVE_OPTION, BACKUP_OPTION, CHECK_DEVICE_OPTION, CHECKPOINT_OPTION, CHECKPOINT_ACTION_OPTION, DELAY_DIRECTORY_RESTORE_OPTION, HARD_DEREFERENCE_OPTION, DELETE_OPTION, EXCLUDE_BACKUPS_OPTION, EXCLUDE_CACHES_OPTION, EXCLUDE_CACHES_UNDER_OPTION, EXCLUDE_CACHES_ALL_OPTION, EXCLUDE_OPTION, EXCLUDE_IGNORE_OPTION, EXCLUDE_IGNORE_RECURSIVE_OPTION, EXCLUDE_TAG_OPTION, EXCLUDE_TAG_UNDER_OPTION, EXCLUDE_TAG_ALL_OPTION, EXCLUDE_VCS_OPTION, EXCLUDE_VCS_IGNORES_OPTION, FORCE_LOCAL_OPTION, FULL_TIME_OPTION, GROUP_OPTION, IGNORE_CASE_OPTION, IGNORE_COMMAND_ERROR_OPTION, IGNORE_FAILED_READ_OPTION, INDEX_FILE_OPTION, KEEP_DIRECTORY_SYMLINK_OPTION, KEEP_NEWER_FILES_OPTION, LEVEL_OPTION, LZIP_OPTION, LZMA_OPTION, LZOP_OPTION, MODE_OPTION, MTIME_OPTION, NEWER_MTIME_OPTION, NO_ACLS_OPTION, NO_ANCHORED_OPTION, NO_AUTO_COMPRESS_OPTION, NO_CHECK_DEVICE_OPTION, NO_DELAY_DIRECTORY_RESTORE_OPTION, NO_IGNORE_CASE_OPTION, NO_IGNORE_COMMAND_ERROR_OPTION, NO_NULL_OPTION, NO_OVERWRITE_DIR_OPTION, NO_QUOTE_CHARS_OPTION, NO_RECURSION_OPTION, NO_SAME_OWNER_OPTION, NO_SAME_PERMISSIONS_OPTION, NO_SEEK_OPTION, NO_SELINUX_CONTEXT_OPTION, NO_UNQUOTE_OPTION, NO_WILDCARDS_MATCH_SLASH_OPTION, NO_WILDCARDS_OPTION, NO_XATTR_OPTION, NULL_OPTION, NUMERIC_OWNER_OPTION, OCCURRENCE_OPTION, OLD_ARCHIVE_OPTION, ONE_FILE_SYSTEM_OPTION, ONE_TOP_LEVEL_OPTION, OVERWRITE_DIR_OPTION, OVERWRITE_OPTION, OWNER_OPTION, PAX_OPTION, POSIX_OPTION, PRESERVE_OPTION, QUOTE_CHARS_OPTION, QUOTING_STYLE_OPTION, RECORD_SIZE_OPTION, RECURSION_OPTION, RECURSIVE_UNLINK_OPTION, REMOVE_FILES_OPTION, RESTRICT_OPTION, RMT_COMMAND_OPTION, RSH_COMMAND_OPTION, SAME_OWNER_OPTION, SELINUX_CONTEXT_OPTION, SHOW_DEFAULTS_OPTION, SHOW_OMITTED_DIRS_OPTION, SHOW_SNAPSHOT_FIELD_RANGES_OPTION, SHOW_TRANSFORMED_NAMES_OPTION, SKIP_OLD_FILES_OPTION, SORT_OPTION, SPARSE_VERSION_OPTION, STRIP_COMPONENTS_OPTION, SUFFIX_OPTION, TEST_LABEL_OPTION, TOTALS_OPTION, TO_COMMAND_OPTION, TRANSFORM_OPTION, UNQUOTE_OPTION, UTC_OPTION, VOLNO_FILE_OPTION, WARNING_OPTION, WILDCARDS_MATCH_SLASH_OPTION, WILDCARDS_OPTION, XATTR_OPTION, XATTR_EXCLUDE, XATTR_INCLUDE }; const char *argp_program_version = "tar (" PACKAGE_NAME ") " VERSION; const char *argp_program_bug_address = "<" PACKAGE_BUGREPORT ">"; static char const doc[] = N_("\ GNU 'tar' saves many files together into a single tape or disk archive, \ and can restore individual files from the archive.\n\ \n\ Examples:\n\ tar -cf archive.tar foo bar # Create archive.tar from files foo and bar.\n\ tar -tvf archive.tar # List all files in archive.tar verbosely.\n\ tar -xf archive.tar # Extract all files from archive.tar.\n") "\v" N_("The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\ The version control may be set with --backup or VERSION_CONTROL, values are:\n\n\ none, off never make backups\n\ t, numbered make numbered backups\n\ nil, existing numbered if numbered backups exist, simple otherwise\n\ never, simple always make simple backups\n"); /* NOTE: Available option letters are DEQY and eqy. Consider the following assignments: [For Solaris tar compatibility =/= Is it important at all?] e exit immediately with a nonzero exit status if unexpected errors occur E use extended headers (--format=posix) [q alias for --occurrence=1 =/= this would better be used for quiet?] y per-file gzip compression Y per-block gzip compression. Additionally, the 'n' letter is assigned for option --seek, which is probably not needed and should be marked as deprecated, so that -n may become available in the future. */ static struct argp_option options[] = { #define GRID 10 {NULL, 0, NULL, 0, N_("Main operation mode:"), GRID }, {"list", 't', 0, 0, N_("list the contents of an archive"), GRID+1 }, {"extract", 'x', 0, 0, N_("extract files from an archive"), GRID+1 }, {"get", 0, 0, OPTION_ALIAS, NULL, GRID+1 }, {"create", 'c', 0, 0, N_("create a new archive"), GRID+1 }, {"diff", 'd', 0, 0, N_("find differences between archive and file system"), GRID+1 }, {"compare", 0, 0, OPTION_ALIAS, NULL, GRID+1 }, {"append", 'r', 0, 0, N_("append files to the end of an archive"), GRID+1 }, {"update", 'u', 0, 0, N_("only append files newer than copy in archive"), GRID+1 }, {"catenate", 'A', 0, 0, N_("append tar files to an archive"), GRID+1 }, {"concatenate", 0, 0, OPTION_ALIAS, NULL, GRID+1 }, {"delete", DELETE_OPTION, 0, 0, N_("delete from the archive (not on mag tapes!)"), GRID+1 }, {"test-label", TEST_LABEL_OPTION, NULL, 0, N_("test the archive volume label and exit"), GRID+1 }, #undef GRID #define GRID 20 {NULL, 0, NULL, 0, N_("Operation modifiers:"), GRID }, {"sparse", 'S', 0, 0, N_("handle sparse files efficiently"), GRID+1 }, {"sparse-version", SPARSE_VERSION_OPTION, N_("MAJOR[.MINOR]"), 0, N_("set version of the sparse format to use (implies --sparse)"), GRID+1}, {"incremental", 'G', 0, 0, N_("handle old GNU-format incremental backup"), GRID+1 }, {"listed-incremental", 'g', N_("FILE"), 0, N_("handle new GNU-format incremental backup"), GRID+1 }, {"level", LEVEL_OPTION, N_("NUMBER"), 0, N_("dump level for created listed-incremental archive"), GRID+1 }, {"ignore-failed-read", IGNORE_FAILED_READ_OPTION, 0, 0, N_("do not exit with nonzero on unreadable files"), GRID+1 }, {"occurrence", OCCURRENCE_OPTION, N_("NUMBER"), OPTION_ARG_OPTIONAL, N_("process only the NUMBERth occurrence of each file in the archive;" " this option is valid only in conjunction with one of the subcommands" " --delete, --diff, --extract or --list and when a list of files" " is given either on the command line or via the -T option;" " NUMBER defaults to 1"), GRID+1 }, {"seek", 'n', NULL, 0, N_("archive is seekable"), GRID+1 }, {"no-seek", NO_SEEK_OPTION, NULL, 0, N_("archive is not seekable"), GRID+1 }, {"no-check-device", NO_CHECK_DEVICE_OPTION, NULL, 0, N_("do not check device numbers when creating incremental archives"), GRID+1 }, {"check-device", CHECK_DEVICE_OPTION, NULL, 0, N_("check device numbers when creating incremental archives (default)"), GRID+1 }, #undef GRID #define GRID 30 {NULL, 0, NULL, 0, N_("Overwrite control:"), GRID }, {"verify", 'W', 0, 0, N_("attempt to verify the archive after writing it"), GRID+1 }, {"remove-files", REMOVE_FILES_OPTION, 0, 0, N_("remove files after adding them to the archive"), GRID+1 }, {"keep-old-files", 'k', 0, 0, N_("don't replace existing files when extracting, " "treat them as errors"), GRID+1 }, {"skip-old-files", SKIP_OLD_FILES_OPTION, 0, 0, N_("don't replace existing files when extracting, silently skip over them"), GRID+1 }, {"keep-newer-files", KEEP_NEWER_FILES_OPTION, 0, 0, N_("don't replace existing files that are newer than their archive copies"), GRID+1 }, {"overwrite", OVERWRITE_OPTION, 0, 0, N_("overwrite existing files when extracting"), GRID+1 }, {"unlink-first", 'U', 0, 0, N_("remove each file prior to extracting over it"), GRID+1 }, {"recursive-unlink", RECURSIVE_UNLINK_OPTION, 0, 0, N_("empty hierarchies prior to extracting directory"), GRID+1 }, {"no-overwrite-dir", NO_OVERWRITE_DIR_OPTION, 0, 0, N_("preserve metadata of existing directories"), GRID+1 }, {"overwrite-dir", OVERWRITE_DIR_OPTION, 0, 0, N_("overwrite metadata of existing directories when extracting (default)"), GRID+1 }, {"keep-directory-symlink", KEEP_DIRECTORY_SYMLINK_OPTION, 0, 0, N_("preserve existing symlinks to directories when extracting"), GRID+1 }, {"one-top-level", ONE_TOP_LEVEL_OPTION, N_("DIR"), OPTION_ARG_OPTIONAL, N_("create a subdirectory to avoid having loose files extracted"), GRID+1 }, #undef GRID #define GRID 40 {NULL, 0, NULL, 0, N_("Select output stream:"), GRID }, {"to-stdout", 'O', 0, 0, N_("extract files to standard output"), GRID+1 }, {"to-command", TO_COMMAND_OPTION, N_("COMMAND"), 0, N_("pipe extracted files to another program"), GRID+1 }, {"ignore-command-error", IGNORE_COMMAND_ERROR_OPTION, 0, 0, N_("ignore exit codes of children"), GRID+1 }, {"no-ignore-command-error", NO_IGNORE_COMMAND_ERROR_OPTION, 0, 0, N_("treat non-zero exit codes of children as error"), GRID+1 }, #undef GRID #define GRID 50 {NULL, 0, NULL, 0, N_("Handling of file attributes:"), GRID }, {"owner", OWNER_OPTION, N_("NAME"), 0, N_("force NAME as owner for added files"), GRID+1 }, {"group", GROUP_OPTION, N_("NAME"), 0, N_("force NAME as group for added files"), GRID+1 }, {"mtime", MTIME_OPTION, N_("DATE-OR-FILE"), 0, N_("set mtime for added files from DATE-OR-FILE"), GRID+1 }, {"mode", MODE_OPTION, N_("CHANGES"), 0, N_("force (symbolic) mode CHANGES for added files"), GRID+1 }, {"atime-preserve", ATIME_PRESERVE_OPTION, N_("METHOD"), OPTION_ARG_OPTIONAL, N_("preserve access times on dumped files, either by restoring the times" " after reading (METHOD='replace'; default) or by not setting the times" " in the first place (METHOD='system')"), GRID+1 }, {"touch", 'm', 0, 0, N_("don't extract file modified time"), GRID+1 }, {"same-owner", SAME_OWNER_OPTION, 0, 0, N_("try extracting files with the same ownership as exists in the archive (default for superuser)"), GRID+1 }, {"no-same-owner", NO_SAME_OWNER_OPTION, 0, 0, N_("extract files as yourself (default for ordinary users)"), GRID+1 }, {"numeric-owner", NUMERIC_OWNER_OPTION, 0, 0, N_("always use numbers for user/group names"), GRID+1 }, {"preserve-permissions", 'p', 0, 0, N_("extract information about file permissions (default for superuser)"), GRID+1 }, {"same-permissions", 0, 0, OPTION_ALIAS, NULL, GRID+1 }, {"no-same-permissions", NO_SAME_PERMISSIONS_OPTION, 0, 0, N_("apply the user's umask when extracting permissions from the archive (default for ordinary users)"), GRID+1 }, {"preserve-order", 's', 0, 0, N_("member arguments are listed in the same order as the " "files in the archive"), GRID+1 }, {"same-order", 0, 0, OPTION_ALIAS, NULL, GRID+1 }, {"preserve", PRESERVE_OPTION, 0, 0, N_("same as both -p and -s"), GRID+1 }, {"delay-directory-restore", DELAY_DIRECTORY_RESTORE_OPTION, 0, 0, N_("delay setting modification times and permissions of extracted" " directories until the end of extraction"), GRID+1 }, {"no-delay-directory-restore", NO_DELAY_DIRECTORY_RESTORE_OPTION, 0, 0, N_("cancel the effect of --delay-directory-restore option"), GRID+1 }, {"sort", SORT_OPTION, N_("ORDER"), 0, #if D_INO_IN_DIRENT N_("directory sorting order: none (default), name or inode" #else N_("directory sorting order: none (default) or name" #endif ), GRID+1 }, #undef GRID #define GRID 55 {NULL, 0, NULL, 0, N_("Handling of extended file attributes:"), GRID }, {"xattrs", XATTR_OPTION, 0, 0, N_("Enable extended attributes support"), GRID+1 }, {"no-xattrs", NO_XATTR_OPTION, 0, 0, N_("Disable extended attributes support"), GRID+1 }, {"xattrs-include", XATTR_INCLUDE, N_("MASK"), 0, N_("specify the include pattern for xattr keys"), GRID+1 }, {"xattrs-exclude", XATTR_EXCLUDE, N_("MASK"), 0, N_("specify the exclude pattern for xattr keys"), GRID+1 }, {"selinux", SELINUX_CONTEXT_OPTION, 0, 0, N_("Enable the SELinux context support"), GRID+1 }, {"no-selinux", NO_SELINUX_CONTEXT_OPTION, 0, 0, N_("Disable the SELinux context support"), GRID+1 }, {"acls", ACLS_OPTION, 0, 0, N_("Enable the POSIX ACLs support"), GRID+1 }, {"no-acls", NO_ACLS_OPTION, 0, 0, N_("Disable the POSIX ACLs support"), GRID+1 }, #undef GRID #define GRID 60 {NULL, 0, NULL, 0, N_("Device selection and switching:"), GRID }, {"file", 'f', N_("ARCHIVE"), 0, N_("use archive file or device ARCHIVE"), GRID+1 }, {"force-local", FORCE_LOCAL_OPTION, 0, 0, N_("archive file is local even if it has a colon"), GRID+1 }, {"rmt-command", RMT_COMMAND_OPTION, N_("COMMAND"), 0, N_("use given rmt COMMAND instead of rmt"), GRID+1 }, {"rsh-command", RSH_COMMAND_OPTION, N_("COMMAND"), 0, N_("use remote COMMAND instead of rsh"), GRID+1 }, #ifdef DEVICE_PREFIX {"-[0-7][lmh]", 0, NULL, OPTION_DOC, /* It is OK, since 'name' will never be translated */ N_("specify drive and density"), GRID+1 }, #endif {NULL, '0', NULL, OPTION_HIDDEN, NULL, GRID+1 }, {NULL, '1', NULL, OPTION_HIDDEN, NULL, GRID+1 }, {NULL, '2', NULL, OPTION_HIDDEN, NULL, GRID+1 }, {NULL, '3', NULL, OPTION_HIDDEN, NULL, GRID+1 }, {NULL, '4', NULL, OPTION_HIDDEN, NULL, GRID+1 }, {NULL, '5', NULL, OPTION_HIDDEN, NULL, GRID+1 }, {NULL, '6', NULL, OPTION_HIDDEN, NULL, GRID+1 }, {NULL, '7', NULL, OPTION_HIDDEN, NULL, GRID+1 }, {NULL, '8', NULL, OPTION_HIDDEN, NULL, GRID+1 }, {NULL, '9', NULL, OPTION_HIDDEN, NULL, GRID+1 }, {"multi-volume", 'M', 0, 0, N_("create/list/extract multi-volume archive"), GRID+1 }, {"tape-length", 'L', N_("NUMBER"), 0, N_("change tape after writing NUMBER x 1024 bytes"), GRID+1 }, {"info-script", 'F', N_("NAME"), 0, N_("run script at end of each tape (implies -M)"), GRID+1 }, {"new-volume-script", 0, 0, OPTION_ALIAS, NULL, GRID+1 }, {"volno-file", VOLNO_FILE_OPTION, N_("FILE"), 0, N_("use/update the volume number in FILE"), GRID+1 }, #undef GRID #define GRID 70 {NULL, 0, NULL, 0, N_("Device blocking:"), GRID }, {"blocking-factor", 'b', N_("BLOCKS"), 0, N_("BLOCKS x 512 bytes per record"), GRID+1 }, {"record-size", RECORD_SIZE_OPTION, N_("NUMBER"), 0, N_("NUMBER of bytes per record, multiple of 512"), GRID+1 }, {"ignore-zeros", 'i', 0, 0, N_("ignore zeroed blocks in archive (means EOF)"), GRID+1 }, {"read-full-records", 'B', 0, 0, N_("reblock as we read (for 4.2BSD pipes)"), GRID+1 }, #undef GRID #define GRID 80 {NULL, 0, NULL, 0, N_("Archive format selection:"), GRID }, {"format", 'H', N_("FORMAT"), 0, N_("create archive of the given format"), GRID+1 }, {NULL, 0, NULL, 0, N_("FORMAT is one of the following:"), GRID+2 }, {" v7", 0, NULL, OPTION_DOC|OPTION_NO_TRANS, N_("old V7 tar format"), GRID+3 }, {" oldgnu", 0, NULL, OPTION_DOC|OPTION_NO_TRANS, N_("GNU format as per tar <= 1.12"), GRID+3 }, {" gnu", 0, NULL, OPTION_DOC|OPTION_NO_TRANS, N_("GNU tar 1.13.x format"), GRID+3 }, {" ustar", 0, NULL, OPTION_DOC|OPTION_NO_TRANS, N_("POSIX 1003.1-1988 (ustar) format"), GRID+3 }, {" pax", 0, NULL, OPTION_DOC|OPTION_NO_TRANS, N_("POSIX 1003.1-2001 (pax) format"), GRID+3 }, {" posix", 0, NULL, OPTION_DOC|OPTION_NO_TRANS, N_("same as pax"), GRID+3 }, {"old-archive", OLD_ARCHIVE_OPTION, 0, 0, /* FIXME */ N_("same as --format=v7"), GRID+8 }, {"portability", 0, 0, OPTION_ALIAS, NULL, GRID+8 }, {"posix", POSIX_OPTION, 0, 0, N_("same as --format=posix"), GRID+8 }, {"pax-option", PAX_OPTION, N_("keyword[[:]=value][,keyword[[:]=value]]..."), 0, N_("control pax keywords"), GRID+8 }, {"label", 'V', N_("TEXT"), 0, N_("create archive with volume name TEXT; at list/extract time, use TEXT as a globbing pattern for volume name"), GRID+8 }, #undef GRID #define GRID 90 {NULL, 0, NULL, 0, N_("Compression options:"), GRID }, {"auto-compress", 'a', 0, 0, N_("use archive suffix to determine the compression program"), GRID+1 }, {"no-auto-compress", NO_AUTO_COMPRESS_OPTION, 0, 0, N_("do not use archive suffix to determine the compression program"), GRID+1 }, {"use-compress-program", 'I', N_("PROG"), 0, N_("filter through PROG (must accept -d)"), GRID+1 }, /* Note: docstrings for the options below are generated by tar_help_filter */ {"bzip2", 'j', 0, 0, NULL, GRID+1 }, {"gzip", 'z', 0, 0, NULL, GRID+1 }, {"gunzip", 0, 0, OPTION_ALIAS, NULL, GRID+1 }, {"ungzip", 0, 0, OPTION_ALIAS, NULL, GRID+1 }, {"compress", 'Z', 0, 0, NULL, GRID+1 }, {"uncompress", 0, 0, OPTION_ALIAS, NULL, GRID+1 }, {"lzip", LZIP_OPTION, 0, 0, NULL, GRID+1 }, {"lzma", LZMA_OPTION, 0, 0, NULL, GRID+1 }, {"lzop", LZOP_OPTION, 0, 0, NULL, GRID+1 }, {"xz", 'J', 0, 0, NULL, GRID+1 }, #undef GRID #define GRID 100 {NULL, 0, NULL, 0, N_("Local file selection:"), GRID }, {"add-file", ARGP_KEY_ARG, N_("FILE"), 0, N_("add given FILE to the archive (useful if its name starts with a dash)"), GRID+1 }, {"directory", 'C', N_("DIR"), 0, N_("change to directory DIR"), GRID+1 }, {"files-from", 'T', N_("FILE"), 0, N_("get names to extract or create from FILE"), GRID+1 }, {"null", NULL_OPTION, 0, 0, N_("-T reads null-terminated names, disable -C"), GRID+1 }, {"no-null", NO_NULL_OPTION, 0, 0, N_("disable the effect of the previous --null option"), GRID+1 }, {"unquote", UNQUOTE_OPTION, 0, 0, N_("unquote input file or member names (default)"), GRID+1 }, {"no-unquote", NO_UNQUOTE_OPTION, 0, 0, N_("do not unquote input file or member names"), GRID+1 }, {"exclude", EXCLUDE_OPTION, N_("PATTERN"), 0, N_("exclude files, given as a PATTERN"), GRID+1 }, {"exclude-from", 'X', N_("FILE"), 0, N_("exclude patterns listed in FILE"), GRID+1 }, {"exclude-caches", EXCLUDE_CACHES_OPTION, 0, 0, N_("exclude contents of directories containing CACHEDIR.TAG, " "except for the tag file itself"), GRID+1 }, {"exclude-caches-under", EXCLUDE_CACHES_UNDER_OPTION, 0, 0, N_("exclude everything under directories containing CACHEDIR.TAG"), GRID+1 }, {"exclude-caches-all", EXCLUDE_CACHES_ALL_OPTION, 0, 0, N_("exclude directories containing CACHEDIR.TAG"), GRID+1 }, {"exclude-tag", EXCLUDE_TAG_OPTION, N_("FILE"), 0, N_("exclude contents of directories containing FILE, except" " for FILE itself"), GRID+1 }, {"exclude-ignore", EXCLUDE_IGNORE_OPTION, N_("FILE"), 0, N_("read exclude patterns for each directory from FILE, if it exists"), GRID+1 }, {"exclude-ignore-recursive", EXCLUDE_IGNORE_RECURSIVE_OPTION, N_("FILE"), 0, N_("read exclude patterns for each directory and its subdirectories " "from FILE, if it exists"), GRID+1 }, {"exclude-tag-under", EXCLUDE_TAG_UNDER_OPTION, N_("FILE"), 0, N_("exclude everything under directories containing FILE"), GRID+1 }, {"exclude-tag-all", EXCLUDE_TAG_ALL_OPTION, N_("FILE"), 0, N_("exclude directories containing FILE"), GRID+1 }, {"exclude-vcs", EXCLUDE_VCS_OPTION, NULL, 0, N_("exclude version control system directories"), GRID+1 }, {"exclude-vcs-ignores", EXCLUDE_VCS_IGNORES_OPTION, NULL, 0, N_("read exclude patterns from the VCS ignore files"), GRID+1 }, {"exclude-backups", EXCLUDE_BACKUPS_OPTION, NULL, 0, N_("exclude backup and lock files"), GRID+1 }, {"no-recursion", NO_RECURSION_OPTION, 0, 0, N_("avoid descending automatically in directories"), GRID+1 }, {"one-file-system", ONE_FILE_SYSTEM_OPTION, 0, 0, N_("stay in local file system when creating archive"), GRID+1 }, {"recursion", RECURSION_OPTION, 0, 0, N_("recurse into directories (default)"), GRID+1 }, {"absolute-names", 'P', 0, 0, N_("don't strip leading '/'s from file names"), GRID+1 }, {"dereference", 'h', 0, 0, N_("follow symlinks; archive and dump the files they point to"), GRID+1 }, {"hard-dereference", HARD_DEREFERENCE_OPTION, 0, 0, N_("follow hard links; archive and dump the files they refer to"), GRID+1 }, {"starting-file", 'K', N_("MEMBER-NAME"), 0, N_("begin at member MEMBER-NAME when reading the archive"), GRID+1 }, {"newer", 'N', N_("DATE-OR-FILE"), 0, N_("only store files newer than DATE-OR-FILE"), GRID+1 }, {"after-date", 0, 0, OPTION_ALIAS, NULL, GRID+1 }, {"newer-mtime", NEWER_MTIME_OPTION, N_("DATE"), 0, N_("compare date and time when data changed only"), GRID+1 }, {"backup", BACKUP_OPTION, N_("CONTROL"), OPTION_ARG_OPTIONAL, N_("backup before removal, choose version CONTROL"), GRID+1 }, {"suffix", SUFFIX_OPTION, N_("STRING"), 0, N_("backup before removal, override usual suffix ('~' unless overridden by environment variable SIMPLE_BACKUP_SUFFIX)"), GRID+1 }, #undef GRID #define GRID 110 {NULL, 0, NULL, 0, N_("File name transformations:"), GRID }, {"strip-components", STRIP_COMPONENTS_OPTION, N_("NUMBER"), 0, N_("strip NUMBER leading components from file names on extraction"), GRID+1 }, {"transform", TRANSFORM_OPTION, N_("EXPRESSION"), 0, N_("use sed replace EXPRESSION to transform file names"), GRID+1 }, {"xform", 0, 0, OPTION_ALIAS, NULL, GRID+1 }, #undef GRID #define GRID 120 {NULL, 0, NULL, 0, N_("File name matching options (affect both exclude and include patterns):"), GRID }, {"ignore-case", IGNORE_CASE_OPTION, 0, 0, N_("ignore case"), GRID+1 }, {"anchored", ANCHORED_OPTION, 0, 0, N_("patterns match file name start"), GRID+1 }, {"no-anchored", NO_ANCHORED_OPTION, 0, 0, N_("patterns match after any '/' (default for exclusion)"), GRID+1 }, {"no-ignore-case", NO_IGNORE_CASE_OPTION, 0, 0, N_("case sensitive matching (default)"), GRID+1 }, {"wildcards", WILDCARDS_OPTION, 0, 0, N_("use wildcards (default for exclusion)"), GRID+1 }, {"no-wildcards", NO_WILDCARDS_OPTION, 0, 0, N_("verbatim string matching"), GRID+1 }, {"no-wildcards-match-slash", NO_WILDCARDS_MATCH_SLASH_OPTION, 0, 0, N_("wildcards do not match '/'"), GRID+1 }, {"wildcards-match-slash", WILDCARDS_MATCH_SLASH_OPTION, 0, 0, N_("wildcards match '/' (default for exclusion)"), GRID+1 }, #undef GRID #define GRID 130 {NULL, 0, NULL, 0, N_("Informative output:"), GRID }, {"verbose", 'v', 0, 0, N_("verbosely list files processed"), GRID+1 }, {"warning", WARNING_OPTION, N_("KEYWORD"), 0, N_("warning control"), GRID+1 }, {"checkpoint", CHECKPOINT_OPTION, N_("NUMBER"), OPTION_ARG_OPTIONAL, N_("display progress messages every NUMBERth record (default 10)"), GRID+1 }, {"checkpoint-action", CHECKPOINT_ACTION_OPTION, N_("ACTION"), 0, N_("execute ACTION on each checkpoint"), GRID+1 }, {"check-links", 'l', 0, 0, N_("print a message if not all links are dumped"), GRID+1 }, {"totals", TOTALS_OPTION, N_("SIGNAL"), OPTION_ARG_OPTIONAL, N_("print total bytes after processing the archive; " "with an argument - print total bytes when this SIGNAL is delivered; " "Allowed signals are: SIGHUP, SIGQUIT, SIGINT, SIGUSR1 and SIGUSR2; " "the names without SIG prefix are also accepted"), GRID+1 }, {"utc", UTC_OPTION, 0, 0, N_("print file modification times in UTC"), GRID+1 }, {"full-time", FULL_TIME_OPTION, 0, 0, N_("print file time to its full resolution"), GRID+1 }, {"index-file", INDEX_FILE_OPTION, N_("FILE"), 0, N_("send verbose output to FILE"), GRID+1 }, {"block-number", 'R', 0, 0, N_("show block number within archive with each message"), GRID+1 }, {"interactive", 'w', 0, 0, N_("ask for confirmation for every action"), GRID+1 }, {"confirmation", 0, 0, OPTION_ALIAS, NULL, GRID+1 }, {"show-defaults", SHOW_DEFAULTS_OPTION, 0, 0, N_("show tar defaults"), GRID+1 }, {"show-snapshot-field-ranges", SHOW_SNAPSHOT_FIELD_RANGES_OPTION, 0, 0, N_("show valid ranges for snapshot-file fields"), GRID+1 }, {"show-omitted-dirs", SHOW_OMITTED_DIRS_OPTION, 0, 0, N_("when listing or extracting, list each directory that does not match search criteria"), GRID+1 }, {"show-transformed-names", SHOW_TRANSFORMED_NAMES_OPTION, 0, 0, N_("show file or archive names after transformation"), GRID+1 }, {"show-stored-names", 0, 0, OPTION_ALIAS, NULL, GRID+1 }, {"quoting-style", QUOTING_STYLE_OPTION, N_("STYLE"), 0, N_("set name quoting style; see below for valid STYLE values"), GRID+1 }, {"quote-chars", QUOTE_CHARS_OPTION, N_("STRING"), 0, N_("additionally quote characters from STRING"), GRID+1 }, {"no-quote-chars", NO_QUOTE_CHARS_OPTION, N_("STRING"), 0, N_("disable quoting for characters from STRING"), GRID+1 }, #undef GRID #define GRID 140 {NULL, 0, NULL, 0, N_("Compatibility options:"), GRID }, {NULL, 'o', 0, 0, N_("when creating, same as --old-archive; when extracting, same as --no-same-owner"), GRID+1 }, #undef GRID #define GRID 150 {NULL, 0, NULL, 0, N_("Other options:"), GRID }, {"restrict", RESTRICT_OPTION, 0, 0, N_("disable use of some potentially harmful options"), -1 }, #undef GRID {0, 0, 0, 0, 0, 0} }; static char const *const atime_preserve_args[] = { "replace", "system", NULL }; static enum atime_preserve const atime_preserve_types[] = { replace_atime_preserve, system_atime_preserve }; /* Make sure atime_preserve_types has as much entries as atime_preserve_args (minus 1 for NULL guard) */ ARGMATCH_VERIFY (atime_preserve_args, atime_preserve_types); /* Wildcard matching settings */ enum wildcards { default_wildcards, /* For exclusion == enable_wildcards, for inclusion == disable_wildcards */ disable_wildcards, enable_wildcards }; struct tar_args /* Variables used during option parsing */ { struct textual_date *textual_date; /* Keeps the arguments to --newer-mtime and/or --date option if they are textual dates */ enum wildcards wildcards; /* Wildcard settings (--wildcards/ --no-wildcards) */ int matching_flags; /* exclude_fnmatch options */ int include_anchored; /* Pattern anchoring options used for file inclusion */ bool o_option; /* True if -o option was given */ bool pax_option; /* True if --pax-option was given */ char const *backup_suffix_string; /* --suffix option argument */ char const *version_control_string; /* --backup option argument */ bool input_files; /* True if some input files where given */ int compress_autodetect; /* True if compression autodetection should be attempted when creating archives */ }; #define MAKE_EXCL_OPTIONS(args) \ ((((args)->wildcards != disable_wildcards) ? EXCLUDE_WILDCARDS : 0) \ | (args)->matching_flags \ | recursion_option) #define MAKE_INCL_OPTIONS(args) \ ((((args)->wildcards == enable_wildcards) ? EXCLUDE_WILDCARDS : 0) \ | (args)->include_anchored \ | (args)->matching_flags \ | recursion_option) static char const * const vcs_file_table[] = { /* CVS: */ "CVS", ".cvsignore", /* RCS: */ "RCS", /* SCCS: */ "SCCS", /* SVN: */ ".svn", /* git: */ ".git", ".gitignore", /* Arch: */ ".arch-ids", "{arch}", "=RELEASE-ID", "=meta-update", "=update", /* Bazaar */ ".bzr", ".bzrignore", ".bzrtags", /* Mercurial */ ".hg", ".hgignore", ".hgtags", /* darcs */ "_darcs", NULL }; static char const * const backup_file_table[] = { ".#*", "*~", "#*#", NULL }; static void add_exclude_array (char const * const * fv, int opts) { int i; for (i = 0; fv[i]; i++) add_exclude (excluded, fv[i], opts); } static char * format_default_settings (void) { return xasprintf ( "--format=%s -f%s -b%d --quoting-style=%s --rmt-command=%s" #ifdef REMOTE_SHELL " --rsh-command=%s" #endif , archive_format_string (DEFAULT_ARCHIVE_FORMAT), DEFAULT_ARCHIVE, DEFAULT_BLOCKING, quoting_style_args[DEFAULT_QUOTING_STYLE], DEFAULT_RMT_COMMAND #ifdef REMOTE_SHELL , REMOTE_SHELL #endif ); } static void set_subcommand_option (enum subcommand subcommand) { if (subcommand_option != UNKNOWN_SUBCOMMAND && subcommand_option != subcommand) USAGE_ERROR ((0, 0, _("You may not specify more than one '-Acdtrux', '--delete' or '--test-label' option"))); subcommand_option = subcommand; } static void set_use_compress_program_option (const char *string) { if (use_compress_program_option && strcmp (use_compress_program_option, string) != 0) USAGE_ERROR ((0, 0, _("Conflicting compression options"))); use_compress_program_option = string; } static void sigstat (int signo) { compute_duration (); print_total_stats (); #ifndef HAVE_SIGACTION signal (signo, sigstat); #endif } static void stat_on_signal (int signo) { #ifdef HAVE_SIGACTION # ifndef SA_RESTART # define SA_RESTART 0 # endif struct sigaction act; act.sa_handler = sigstat; sigemptyset (&act.sa_mask); act.sa_flags = SA_RESTART; sigaction (signo, &act, NULL); #else signal (signo, sigstat); #endif } static void set_stat_signal (const char *name) { static struct sigtab { char const *name; int signo; } const sigtab[] = { { "SIGUSR1", SIGUSR1 }, { "USR1", SIGUSR1 }, { "SIGUSR2", SIGUSR2 }, { "USR2", SIGUSR2 }, { "SIGHUP", SIGHUP }, { "HUP", SIGHUP }, { "SIGINT", SIGINT }, { "INT", SIGINT }, { "SIGQUIT", SIGQUIT }, { "QUIT", SIGQUIT } }; struct sigtab const *p; for (p = sigtab; p < sigtab + sizeof (sigtab) / sizeof (sigtab[0]); p++) if (strcmp (p->name, name) == 0) { stat_on_signal (p->signo); return; } FATAL_ERROR ((0, 0, _("Unknown signal name: %s"), name)); } struct textual_date { struct textual_date *next; struct timespec ts; const char *option; char *date; }; static int get_date_or_file (struct tar_args *args, const char *option, const char *str, struct timespec *ts) { if (FILE_SYSTEM_PREFIX_LEN (str) != 0 || ISSLASH (*str) || *str == '.') { struct stat st; if (stat (str, &st) != 0) { stat_error (str); USAGE_ERROR ((0, 0, _("Date sample file not found"))); } *ts = get_stat_mtime (&st); } else { if (! parse_datetime (ts, str, NULL)) { WARN ((0, 0, _("Substituting %s for unknown date format %s"), tartime (*ts, false), quote (str))); ts->tv_nsec = 0; return 1; } else { struct textual_date *p = xmalloc (sizeof (*p)); p->ts = *ts; p->option = option; p->date = xstrdup (str); p->next = args->textual_date; args->textual_date = p; } } return 0; } static void report_textual_dates (struct tar_args *args) { struct textual_date *p; for (p = args->textual_date; p; ) { struct textual_date *next = p->next; if (verbose_option) { char const *treated_as = tartime (p->ts, true); if (strcmp (p->date, treated_as) != 0) WARN ((0, 0, _("Option %s: Treating date '%s' as %s"), p->option, p->date, treated_as)); } free (p->date); free (p); p = next; } } static bool files_from_option; /* When set, tar will not refuse to create empty archives */ /* Default density numbers for [0-9][lmh] device specifications */ #if defined DEVICE_PREFIX && !defined DENSITY_LETTER # ifndef LOW_DENSITY_NUM # define LOW_DENSITY_NUM 0 # endif # ifndef MID_DENSITY_NUM # define MID_DENSITY_NUM 8 # endif # ifndef HIGH_DENSITY_NUM # define HIGH_DENSITY_NUM 16 # endif #endif static char * tar_help_filter (int key, const char *text, void *input) { struct obstack stk; char *s; switch (key) { default: s = (char*) text; break; case 'j': s = xasprintf (_("filter the archive through %s"), BZIP2_PROGRAM); break; case 'z': s = xasprintf (_("filter the archive through %s"), GZIP_PROGRAM); break; case 'Z': s = xasprintf (_("filter the archive through %s"), COMPRESS_PROGRAM); break; case LZIP_OPTION: s = xasprintf (_("filter the archive through %s"), LZIP_PROGRAM); break; case LZMA_OPTION: s = xasprintf (_("filter the archive through %s"), LZMA_PROGRAM); break; case LZOP_OPTION: s = xasprintf (_("filter the archive through %s"), LZOP_PROGRAM); case 'J': s = xasprintf (_("filter the archive through %s"), XZ_PROGRAM); break; case ARGP_KEY_HELP_EXTRA: { const char *tstr; obstack_init (&stk); tstr = _("Valid arguments for the --quoting-style option are:"); obstack_grow (&stk, tstr, strlen (tstr)); obstack_grow (&stk, "\n\n", 2); tar_list_quoting_styles (&stk, " "); tstr = _("\n*This* tar defaults to:\n"); obstack_grow (&stk, tstr, strlen (tstr)); s = format_default_settings (); obstack_grow (&stk, s, strlen (s)); obstack_1grow (&stk, '\n'); obstack_1grow (&stk, 0); s = xstrdup (obstack_finish (&stk)); obstack_free (&stk, NULL); } } return s; } static char * expand_pax_option (struct tar_args *targs, const char *arg) { struct obstack stk; char *res; obstack_init (&stk); while (*arg) { size_t seglen = strcspn (arg, ","); char *p = memchr (arg, '=', seglen); if (p) { size_t len = p - arg + 1; obstack_grow (&stk, arg, len); len = seglen - len; for (++p; *p && isspace ((unsigned char) *p); p++) len--; if (*p == '{' && p[len-1] == '}') { struct timespec ts; char *tmp = xmalloc (len); memcpy (tmp, p + 1, len-2); tmp[len-2] = 0; if (get_date_or_file (targs, "--pax-option", tmp, &ts) == 0) { char buf[TIMESPEC_STRSIZE_BOUND]; char const *s = code_timespec (ts, buf); obstack_grow (&stk, s, strlen (s)); } else obstack_grow (&stk, p, len); free (tmp); } else obstack_grow (&stk, p, len); } else obstack_grow (&stk, arg, seglen); arg += seglen; if (*arg) { obstack_1grow (&stk, *arg); arg++; } } obstack_1grow (&stk, 0); res = xstrdup (obstack_finish (&stk)); obstack_free (&stk, NULL); return res; } /* Debian specific environment variable used by pristine-tar to enable use of * longlinks for filenames exactly 100 bytes long. */ void debian_longlink_hack_init (void) { char *s=getenv ("TAR_LONGLINK_100"); if (s && strcmp(s, "1") == 0) debian_longlink_hack=1; else debian_longlink_hack=0; } /* pristine-tar sets this environment variable to force fields in longlinks * to be zeroed as was the case in tar 1.26. */ void pristine_tar_compat_init (void) { char *s=getenv ("PRISTINE_TAR_COMPAT"); if (s && strcmp(s, "1") == 0) pristine_tar_compat=1; else pristine_tar_compat=0; } static uintmax_t parse_owner_group (char *arg, uintmax_t field_max, char const **name_option) { uintmax_t u = UINTMAX_MAX; char *end; char const *name = 0; char const *invalid_num = 0; char *colon = strchr (arg, ':'); if (colon) { char const *num = colon + 1; *colon = '\0'; if (*arg) name = arg; if (num && (! (xstrtoumax (num, &end, 10, &u, "") == LONGINT_OK && u <= field_max))) invalid_num = num; } else { uintmax_t u1; switch ('0' <= *arg && *arg <= '9' ? xstrtoumax (arg, &end, 10, &u1, "") : LONGINT_INVALID) { default: name = arg; break; case LONGINT_OK: if (u1 <= field_max) { u = u1; break; } /* Fall through. */ case LONGINT_OVERFLOW: invalid_num = arg; break; } } if (invalid_num) FATAL_ERROR ((0, 0, "%s: %s", quotearg_colon (invalid_num), _("Invalid owner or group ID"))); if (name) *name_option = name; return u; } #define TAR_SIZE_SUFFIXES "bBcGgkKMmPTtw" /* Either NL or NUL, as decided by the --null option. */ static char filename_terminator; static char const *const sort_mode_arg[] = { "none", "name", "inode", NULL }; static int sort_mode_flag[] = { SAVEDIR_SORT_NONE, SAVEDIR_SORT_NAME, SAVEDIR_SORT_INODE }; ARGMATCH_VERIFY (sort_mode_arg, sort_mode_flag); static error_t parse_opt (int key, char *arg, struct argp_state *state) { struct tar_args *args = state->input; switch (key) { case ARGP_KEY_ARG: /* File name or non-parsed option, because of ARGP_IN_ORDER */ name_add_name (arg, MAKE_INCL_OPTIONS (args)); args->input_files = true; break; case 'A': set_subcommand_option (CAT_SUBCOMMAND); break; case 'a': args->compress_autodetect = true; break; case NO_AUTO_COMPRESS_OPTION: args->compress_autodetect = false; break; case 'b': { uintmax_t u; if (! (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK && u == (blocking_factor = u) && 0 < blocking_factor && u == (record_size = u * BLOCKSIZE) / BLOCKSIZE)) USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg), _("Invalid blocking factor"))); } break; case 'B': /* Try to reblock input records. For reading 4.2BSD pipes. */ /* It would surely make sense to exchange -B and -R, but it seems that -B has been used for a long while in Sun tar and most BSD-derived systems. This is a consequence of the block/record terminology confusion. */ read_full_records_option = true; break; case 'c': set_subcommand_option (CREATE_SUBCOMMAND); break; case 'C': name_add_dir (arg); break; case 'd': set_subcommand_option (DIFF_SUBCOMMAND); break; case 'f': if (archive_names == allocated_archive_names) archive_name_array = x2nrealloc (archive_name_array, &allocated_archive_names, sizeof (archive_name_array[0])); archive_name_array[archive_names++] = arg; break; case 'F': /* Since -F is only useful with -M, make it implied. Run this script at the end of each tape. */ info_script_option = arg; multi_volume_option = true; break; case FULL_TIME_OPTION: full_time_option = true; break; case 'g': listed_incremental_option = arg; after_date_option = true; /* Fall through. */ case 'G': /* We are making an incremental dump (FIXME: are we?); save directories at the beginning of the archive, and include in each directory its contents. */ incremental_option = true; break; case 'h': /* Follow symbolic links. */ dereference_option = true; break; case HARD_DEREFERENCE_OPTION: hard_dereference_option = true; break; case 'i': /* Ignore zero blocks (eofs). This can't be the default, because Unix tar writes two blocks of zeros, then pads out the record with garbage. */ ignore_zeros_option = true; break; case 'j': set_use_compress_program_option (BZIP2_PROGRAM); break; case 'J': set_use_compress_program_option (XZ_PROGRAM); break; case 'k': /* Don't replace existing files. */ old_files_option = KEEP_OLD_FILES; break; case 'K': starting_file_option = true; addname (arg, 0, true, NULL); break; case ONE_FILE_SYSTEM_OPTION: /* When dumping directories, don't dump files/subdirectories that are on other filesystems. */ one_file_system_option = true; break; case ONE_TOP_LEVEL_OPTION: one_top_level_option = true; one_top_level_dir = arg; break; case 'l': check_links_option = 1; break; case 'L': { uintmax_t u; char *p; if (xstrtoumax (arg, &p, 10, &u, TAR_SIZE_SUFFIXES) != LONGINT_OK) USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg), _("Invalid tape length"))); if (p > arg && !strchr (TAR_SIZE_SUFFIXES, p[-1])) tape_length_option = 1024 * (tarlong) u; else tape_length_option = (tarlong) u; multi_volume_option = true; } break; case LEVEL_OPTION: { char *p; incremental_level = strtoul (arg, &p, 10); if (*p) USAGE_ERROR ((0, 0, _("Invalid incremental level value"))); } break; case LZIP_OPTION: set_use_compress_program_option (LZIP_PROGRAM); break; case LZMA_OPTION: set_use_compress_program_option (LZMA_PROGRAM); break; case LZOP_OPTION: set_use_compress_program_option (LZOP_PROGRAM); break; case 'm': touch_option = true; break; case 'M': /* Make multivolume archive: when we can't write any more into the archive, re-open it, and continue writing. */ multi_volume_option = true; break; case MTIME_OPTION: get_date_or_file (args, "--mtime", arg, &mtime_option); set_mtime_option = true; break; case 'n': seek_option = 1; break; case NO_SEEK_OPTION: seek_option = 0; break; case 'N': after_date_option = true; /* Fall through. */ case NEWER_MTIME_OPTION: if (NEWER_OPTION_INITIALIZED (newer_mtime_option)) USAGE_ERROR ((0, 0, _("More than one threshold date"))); get_date_or_file (args, key == NEWER_MTIME_OPTION ? "--newer-mtime" : "--after-date", arg, &newer_mtime_option); break; case 'o': args->o_option = true; break; case 'O': to_stdout_option = true; break; case 'p': same_permissions_option = true; break; case 'P': absolute_names_option = true; break; case 'r': set_subcommand_option (APPEND_SUBCOMMAND); break; case 'R': /* Print block numbers for debugging bad tar archives. */ /* It would surely make sense to exchange -B and -R, but it seems that -B has been used for a long while in Sun tar and most BSD-derived systems. This is a consequence of the block/record terminology confusion. */ block_number_option = true; break; case 's': /* Names to extract are sorted. */ same_order_option = true; break; case 'S': sparse_option = true; break; case SKIP_OLD_FILES_OPTION: old_files_option = SKIP_OLD_FILES; break; case SPARSE_VERSION_OPTION: sparse_option = true; { char *p; tar_sparse_major = strtoul (arg, &p, 10); if (*p) { if (*p != '.') USAGE_ERROR ((0, 0, _("Invalid sparse version value"))); tar_sparse_minor = strtoul (p + 1, &p, 10); if (*p) USAGE_ERROR ((0, 0, _("Invalid sparse version value"))); } } break; case 't': set_subcommand_option (LIST_SUBCOMMAND); verbose_option++; break; case TEST_LABEL_OPTION: set_subcommand_option (TEST_LABEL_SUBCOMMAND); break; case 'T': name_add_file (arg, filename_terminator); /* Indicate we've been given -T option. This is for backward compatibility only, so that `tar cfT archive /dev/null will succeed */ files_from_option = true; break; case 'u': set_subcommand_option (UPDATE_SUBCOMMAND); break; case 'U': old_files_option = UNLINK_FIRST_OLD_FILES; break; case UTC_OPTION: utc_option = true; break; case 'v': verbose_option++; warning_option |= WARN_VERBOSE_WARNINGS; break; case 'V': volume_label_option = arg; break; case 'w': interactive_option = true; break; case 'W': verify_option = true; break; case 'x': set_subcommand_option (EXTRACT_SUBCOMMAND); break; case 'X': if (add_exclude_file (add_exclude, excluded, arg, MAKE_EXCL_OPTIONS (args), '\n') != 0) { int e = errno; FATAL_ERROR ((0, e, "%s", quotearg_colon (arg))); } break; case 'z': set_use_compress_program_option (GZIP_PROGRAM); break; case 'Z': set_use_compress_program_option (COMPRESS_PROGRAM); break; case ANCHORED_OPTION: args->matching_flags |= EXCLUDE_ANCHORED; break; case ATIME_PRESERVE_OPTION: atime_preserve_option = (arg ? XARGMATCH ("--atime-preserve", arg, atime_preserve_args, atime_preserve_types) : replace_atime_preserve); if (! O_NOATIME && atime_preserve_option == system_atime_preserve) FATAL_ERROR ((0, 0, _("--atime-preserve='system' is not supported" " on this platform"))); break; case CHECK_DEVICE_OPTION: check_device_option = true; break; case NO_CHECK_DEVICE_OPTION: check_device_option = false; break; case CHECKPOINT_OPTION: if (arg) { char *p; if (*arg == '.') { checkpoint_compile_action ("."); arg++; } checkpoint_option = strtoul (arg, &p, 0); if (*p) FATAL_ERROR ((0, 0, _("--checkpoint value is not an integer"))); } else checkpoint_option = DEFAULT_CHECKPOINT; break; case CHECKPOINT_ACTION_OPTION: checkpoint_compile_action (arg); break; case BACKUP_OPTION: backup_option = true; if (arg) args->version_control_string = arg; break; case DELAY_DIRECTORY_RESTORE_OPTION: delay_directory_restore_option = true; break; case NO_DELAY_DIRECTORY_RESTORE_OPTION: delay_directory_restore_option = false; break; case DELETE_OPTION: set_subcommand_option (DELETE_SUBCOMMAND); break; case EXCLUDE_BACKUPS_OPTION: add_exclude_array (backup_file_table, EXCLUDE_WILDCARDS); break; case EXCLUDE_OPTION: add_exclude (excluded, arg, MAKE_EXCL_OPTIONS (args)); break; case EXCLUDE_CACHES_OPTION: add_exclusion_tag ("CACHEDIR.TAG", exclusion_tag_contents, cachedir_file_p); break; case EXCLUDE_CACHES_UNDER_OPTION: add_exclusion_tag ("CACHEDIR.TAG", exclusion_tag_under, cachedir_file_p); break; case EXCLUDE_CACHES_ALL_OPTION: add_exclusion_tag ("CACHEDIR.TAG", exclusion_tag_all, cachedir_file_p); break; case EXCLUDE_IGNORE_OPTION: excfile_add (arg, EXCL_NON_RECURSIVE); break; case EXCLUDE_IGNORE_RECURSIVE_OPTION: excfile_add (arg, EXCL_RECURSIVE); break; case EXCLUDE_TAG_OPTION: add_exclusion_tag (arg, exclusion_tag_contents, NULL); break; case EXCLUDE_TAG_UNDER_OPTION: add_exclusion_tag (arg, exclusion_tag_under, NULL); break; case EXCLUDE_TAG_ALL_OPTION: add_exclusion_tag (arg, exclusion_tag_all, NULL); break; case EXCLUDE_VCS_OPTION: add_exclude_array (vcs_file_table, 0); break; case EXCLUDE_VCS_IGNORES_OPTION: exclude_vcs_ignores (); break; case FORCE_LOCAL_OPTION: force_local_option = true; break; case 'H': set_archive_format (arg); break; case INDEX_FILE_OPTION: index_file_name = arg; break; case IGNORE_CASE_OPTION: args->matching_flags |= FNM_CASEFOLD; break; case IGNORE_COMMAND_ERROR_OPTION: ignore_command_error_option = true; break; case IGNORE_FAILED_READ_OPTION: ignore_failed_read_option = true; break; case KEEP_DIRECTORY_SYMLINK_OPTION: keep_directory_symlink_option = true; break; case KEEP_NEWER_FILES_OPTION: old_files_option = KEEP_NEWER_FILES; break; case GROUP_OPTION: { uintmax_t u = parse_owner_group (arg, TYPE_MAXIMUM (gid_t), &group_name_option); if (u == UINTMAX_MAX) { group_option = -1; if (group_name_option) gname_to_gid (group_name_option, &group_option); } else group_option = u; } break; case MODE_OPTION: mode_option = mode_compile (arg); if (!mode_option) FATAL_ERROR ((0, 0, _("Invalid mode given on option"))); initial_umask = umask (0); umask (initial_umask); break; case NO_ANCHORED_OPTION: args->include_anchored = 0; /* Clear the default for comman line args */ args->matching_flags &= ~ EXCLUDE_ANCHORED; break; case NO_IGNORE_CASE_OPTION: args->matching_flags &= ~ FNM_CASEFOLD; break; case NO_IGNORE_COMMAND_ERROR_OPTION: ignore_command_error_option = false; break; case NO_OVERWRITE_DIR_OPTION: old_files_option = NO_OVERWRITE_DIR_OLD_FILES; break; case NO_QUOTE_CHARS_OPTION: for (;*arg; arg++) set_char_quoting (NULL, *arg, 0); break; case NO_WILDCARDS_OPTION: args->wildcards = disable_wildcards; break; case NO_WILDCARDS_MATCH_SLASH_OPTION: args->matching_flags |= FNM_FILE_NAME; break; case NULL_OPTION: filename_terminator = '\0'; break; case NO_NULL_OPTION: filename_terminator = '\n'; break; case NUMERIC_OWNER_OPTION: numeric_owner_option = true; break; case OCCURRENCE_OPTION: if (!arg) occurrence_option = 1; else { uintmax_t u; if (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK) occurrence_option = u; else FATAL_ERROR ((0, 0, "%s: %s", quotearg_colon (arg), _("Invalid number"))); } break; case OLD_ARCHIVE_OPTION: set_archive_format ("v7"); break; case OVERWRITE_DIR_OPTION: old_files_option = DEFAULT_OLD_FILES; break; case OVERWRITE_OPTION: old_files_option = OVERWRITE_OLD_FILES; break; case OWNER_OPTION: { uintmax_t u = parse_owner_group (arg, TYPE_MAXIMUM (uid_t), &owner_name_option); if (u == UINTMAX_MAX) { owner_option = -1; if (owner_name_option) uname_to_uid (owner_name_option, &owner_option); } else owner_option = u; } break; case QUOTE_CHARS_OPTION: for (;*arg; arg++) set_char_quoting (NULL, *arg, 1); break; case QUOTING_STYLE_OPTION: tar_set_quoting_style (arg); break; case PAX_OPTION: { char *tmp = expand_pax_option (args, arg); args->pax_option = true; xheader_set_option (tmp); free (tmp); } break; case POSIX_OPTION: set_archive_format ("posix"); break; case PRESERVE_OPTION: /* FIXME: What it is good for? */ same_permissions_option = true; same_order_option = true; WARN ((0, 0, _("The --preserve option is deprecated, " "use --preserve-permissions --preserve-order instead"))); break; case RECORD_SIZE_OPTION: { uintmax_t u; if (! (xstrtoumax (arg, NULL, 10, &u, TAR_SIZE_SUFFIXES) == LONGINT_OK && u == (size_t) u)) USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg), _("Invalid record size"))); record_size = u; if (record_size % BLOCKSIZE != 0) USAGE_ERROR ((0, 0, _("Record size must be a multiple of %d."), BLOCKSIZE)); blocking_factor = record_size / BLOCKSIZE; } break; case RECURSIVE_UNLINK_OPTION: recursive_unlink_option = true; break; case REMOVE_FILES_OPTION: remove_files_option = true; break; case RESTRICT_OPTION: restrict_option = true; break; case RMT_COMMAND_OPTION: rmt_command = arg; break; case RSH_COMMAND_OPTION: rsh_command_option = arg; break; case SHOW_DEFAULTS_OPTION: { char *s = format_default_settings (); printf ("%s\n", s); close_stdout (); free (s); exit (0); } case SHOW_SNAPSHOT_FIELD_RANGES_OPTION: show_snapshot_field_ranges (); close_stdout (); exit (0); case STRIP_COMPONENTS_OPTION: { uintmax_t u; if (! (xstrtoumax (arg, 0, 10, &u, "") == LONGINT_OK && u == (size_t) u)) USAGE_ERROR ((0, 0, "%s: %s", quotearg_colon (arg), _("Invalid number of elements"))); strip_name_components = u; } break; case SHOW_OMITTED_DIRS_OPTION: show_omitted_dirs_option = true; break; case SHOW_TRANSFORMED_NAMES_OPTION: show_transformed_names_option = true; break; case SORT_OPTION: savedir_sort_order = XARGMATCH ("--sort", arg, sort_mode_arg, sort_mode_flag); break; case SUFFIX_OPTION: backup_option = true; args->backup_suffix_string = arg; break; case TO_COMMAND_OPTION: if (to_command_option) USAGE_ERROR ((0, 0, _("Only one --to-command option allowed"))); to_command_option = arg; break; case TOTALS_OPTION: if (arg) set_stat_signal (arg); else totals_option = true; break; case TRANSFORM_OPTION: set_transform_expr (arg); break; case 'I': set_use_compress_program_option (arg); break; case VOLNO_FILE_OPTION: volno_file_option = arg; break; case WILDCARDS_OPTION: args->wildcards = enable_wildcards; break; case WILDCARDS_MATCH_SLASH_OPTION: args->matching_flags &= ~ FNM_FILE_NAME; break; case NO_RECURSION_OPTION: recursion_option = 0; break; case NO_SAME_OWNER_OPTION: same_owner_option = -1; break; case NO_SAME_PERMISSIONS_OPTION: same_permissions_option = -1; break; case ACLS_OPTION: set_archive_format ("posix"); acls_option = 1; break; case NO_ACLS_OPTION: acls_option = -1; break; case SELINUX_CONTEXT_OPTION: set_archive_format ("posix"); selinux_context_option = 1; break; case NO_SELINUX_CONTEXT_OPTION: selinux_context_option = -1; break; case XATTR_OPTION: set_xattr_option (1); break; case NO_XATTR_OPTION: set_xattr_option (-1); break; case XATTR_INCLUDE: case XATTR_EXCLUDE: set_xattr_option (1); xattrs_mask_add (arg, (key == XATTR_INCLUDE)); break; case RECURSION_OPTION: recursion_option = FNM_LEADING_DIR; break; case SAME_OWNER_OPTION: same_owner_option = 1; break; case UNQUOTE_OPTION: unquote_option = true; break; case NO_UNQUOTE_OPTION: unquote_option = false; break; case WARNING_OPTION: set_warning_option (arg); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': #ifdef DEVICE_PREFIX { int device = key - '0'; int density; static char buf[sizeof DEVICE_PREFIX + 10]; char *cursor; if (arg[1]) argp_error (state, _("Malformed density argument: %s"), quote (arg)); strcpy (buf, DEVICE_PREFIX); cursor = buf + strlen (buf); #ifdef DENSITY_LETTER sprintf (cursor, "%d%c", device, arg[0]); #else /* not DENSITY_LETTER */ switch (arg[0]) { case 'l': device += LOW_DENSITY_NUM; break; case 'm': device += MID_DENSITY_NUM; break; case 'h': device += HIGH_DENSITY_NUM; break; default: argp_error (state, _("Unknown density: '%c'"), arg[0]); } sprintf (cursor, "%d", device); #endif /* not DENSITY_LETTER */ if (archive_names == allocated_archive_names) archive_name_array = x2nrealloc (archive_name_array, &allocated_archive_names, sizeof (archive_name_array[0])); archive_name_array[archive_names++] = xstrdup (buf); } break; #else /* not DEVICE_PREFIX */ argp_error (state, _("Options '-[0-7][lmh]' not supported by *this* tar")); #endif /* not DEVICE_PREFIX */ default: return ARGP_ERR_UNKNOWN; } return 0; } static struct argp argp = { options, parse_opt, N_("[FILE]..."), doc, NULL, tar_help_filter, NULL }; void usage (int status) { argp_help (&argp, stderr, ARGP_HELP_SEE, (char*) program_name); close_stdout (); exit (status); } /* Parse the options for tar. */ static struct argp_option * find_argp_option (struct argp_option *o, int letter) { for (; !(o->name == NULL && o->key == 0 && o->arg == 0 && o->flags == 0 && o->doc == NULL); o++) if (o->key == letter) return o; return NULL; } static const char *tar_authors[] = { "John Gilmore", "Jay Fenlason", NULL }; /* Subcommand classes */ #define SUBCL_READ 0x01 /* subcommand reads from the archive */ #define SUBCL_WRITE 0x02 /* subcommand writes to the archive */ #define SUBCL_UPDATE 0x04 /* subcommand updates existing archive */ #define SUBCL_TEST 0x08 /* subcommand tests archive header or meta-info */ #define SUBCL_OCCUR 0x10 /* subcommand allows the use of the occurrence option */ static int subcommand_class[] = { /* UNKNOWN_SUBCOMMAND */ 0, /* APPEND_SUBCOMMAND */ SUBCL_WRITE|SUBCL_UPDATE, /* CAT_SUBCOMMAND */ SUBCL_WRITE, /* CREATE_SUBCOMMAND */ SUBCL_WRITE, /* DELETE_SUBCOMMAND */ SUBCL_WRITE|SUBCL_UPDATE|SUBCL_OCCUR, /* DIFF_SUBCOMMAND */ SUBCL_READ|SUBCL_OCCUR, /* EXTRACT_SUBCOMMAND */ SUBCL_READ|SUBCL_OCCUR, /* LIST_SUBCOMMAND */ SUBCL_READ|SUBCL_OCCUR, /* UPDATE_SUBCOMMAND */ SUBCL_WRITE|SUBCL_UPDATE, /* TEST_LABEL_SUBCOMMAND */ SUBCL_TEST }; /* Return t if the subcommand_option is in class(es) f */ #define IS_SUBCOMMAND_CLASS(f) (subcommand_class[subcommand_option] & (f)) static struct tar_args args; static void option_conflict_error (const char *a, const char *b) { /* TRANSLATORS: Both %s in this statement are replaced with option names. */ USAGE_ERROR ((0, 0, _("'%s' cannot be used with '%s'"), a, b)); } static void decode_options (int argc, char **argv) { int idx; argp_version_setup ("tar", tar_authors); /* Set some default option values. */ args.textual_date = NULL; args.wildcards = default_wildcards; args.matching_flags = 0; args.include_anchored = EXCLUDE_ANCHORED; args.o_option = false; args.pax_option = false; args.backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX"); args.version_control_string = 0; args.input_files = false; args.compress_autodetect = false; subcommand_option = UNKNOWN_SUBCOMMAND; archive_format = DEFAULT_FORMAT; blocking_factor = DEFAULT_BLOCKING; record_size = DEFAULT_BLOCKING * BLOCKSIZE; excluded = new_exclude (); newer_mtime_option.tv_sec = TYPE_MINIMUM (time_t); newer_mtime_option.tv_nsec = -1; recursion_option = FNM_LEADING_DIR; unquote_option = true; tar_sparse_major = 1; tar_sparse_minor = 0; savedir_sort_order = SAVEDIR_SORT_NONE; owner_option = -1; owner_name_option = NULL; group_option = -1; group_name_option = NULL; check_device_option = true; incremental_level = -1; seek_option = -1; /* Convert old-style tar call by exploding option element and rearranging options accordingly. */ if (argc > 1 && argv[1][0] != '-') { int new_argc; /* argc value for rearranged arguments */ char **new_argv; /* argv value for rearranged arguments */ char *const *in; /* cursor into original argv */ char **out; /* cursor into rearranged argv */ const char *letter; /* cursor into old option letters */ char buffer[3]; /* constructed option buffer */ /* Initialize a constructed option. */ buffer[0] = '-'; buffer[2] = '\0'; /* Allocate a new argument array, and copy program name in it. */ new_argc = argc - 1 + strlen (argv[1]); new_argv = xmalloc ((new_argc + 1) * sizeof (char *)); in = argv; out = new_argv; *out++ = *in++; /* Copy each old letter option as a separate option, and have the corresponding argument moved next to it. */ for (letter = *in++; *letter; letter++) { struct argp_option *opt; buffer[1] = *letter; *out++ = xstrdup (buffer); opt = find_argp_option (options, *letter); if (opt && opt->arg) { if (in < argv + argc) *out++ = *in++; else USAGE_ERROR ((0, 0, _("Old option '%c' requires an argument."), *letter)); } } /* Copy all remaining options. */ while (in < argv + argc) *out++ = *in++; *out = 0; /* Replace the old option list by the new one. */ argc = new_argc; argv = new_argv; } /* Parse all options and non-options as they appear. */ prepend_default_options (getenv ("TAR_OPTIONS"), &argc, &argv); if (argp_parse (&argp, argc, argv, ARGP_IN_ORDER, &idx, &args)) exit (TAREXIT_FAILURE); /* Special handling for 'o' option: GNU tar used to say "output old format". UNIX98 tar says don't chown files after extracting (we use "--no-same-owner" for this). The old GNU tar semantics is retained when used with --create option, otherwise UNIX98 semantics is assumed */ if (args.o_option) { if (subcommand_option == CREATE_SUBCOMMAND) { /* GNU Tar <= 1.13 compatibility */ set_archive_format ("v7"); } else { /* UNIX98 compatibility */ same_owner_option = -1; } } /* Handle operands after any "--" argument. */ for (; idx < argc; idx++) { name_add_name (argv[idx], MAKE_INCL_OPTIONS (&args)); args.input_files = true; } /* Warn about implicit use of the wildcards in command line arguments. See TODO */ warn_regex_usage = args.wildcards == default_wildcards; /* Derive option values and check option consistency. */ if (archive_format == DEFAULT_FORMAT) { if (args.pax_option) archive_format = POSIX_FORMAT; else archive_format = DEFAULT_ARCHIVE_FORMAT; } if ((volume_label_option && subcommand_option == CREATE_SUBCOMMAND) || incremental_option || multi_volume_option || sparse_option) assert_format (FORMAT_MASK (OLDGNU_FORMAT) | FORMAT_MASK (GNU_FORMAT) | FORMAT_MASK (POSIX_FORMAT)); if (occurrence_option) { if (!args.input_files) USAGE_ERROR ((0, 0, _("--occurrence is meaningless without a file list"))); if (!IS_SUBCOMMAND_CLASS (SUBCL_OCCUR)) option_conflict_error ("--occurrence", subcommand_string (subcommand_option)); } if (archive_names == 0) { /* If no archive file name given, try TAPE from the environment, or else, DEFAULT_ARCHIVE from the configuration process. */ archive_names = 1; archive_name_array[0] = getenv ("TAPE"); if (! archive_name_array[0]) archive_name_array[0] = DEFAULT_ARCHIVE; } /* Allow multiple archives only with '-M'. */ if (archive_names > 1 && !multi_volume_option) USAGE_ERROR ((0, 0, _("Multiple archive files require '-M' option"))); if (listed_incremental_option && NEWER_OPTION_INITIALIZED (newer_mtime_option)) option_conflict_error ("--listed-incremental", "--newer"); if (incremental_level != -1 && !listed_incremental_option) WARN ((0, 0, _("--level is meaningless without --listed-incremental"))); if (volume_label_option) { if (archive_format == GNU_FORMAT || archive_format == OLDGNU_FORMAT) { size_t volume_label_max_len = (sizeof current_header->header.name - 1 /* for trailing '\0' */ - (multi_volume_option ? (sizeof " Volume " - 1 /* for null at end of " Volume " */ + INT_STRLEN_BOUND (int) /* for volume number */ - 1 /* for sign, as 0 <= volno */) : 0)); if (volume_label_max_len < strlen (volume_label_option)) USAGE_ERROR ((0, 0, ngettext ("%s: Volume label is too long (limit is %lu byte)", "%s: Volume label is too long (limit is %lu bytes)", volume_label_max_len), quotearg_colon (volume_label_option), (unsigned long) volume_label_max_len)); } /* else FIXME Label length in PAX format is limited by the volume size. */ } if (verify_option) { if (multi_volume_option) USAGE_ERROR ((0, 0, _("Cannot verify multi-volume archives"))); if (use_compress_program_option) USAGE_ERROR ((0, 0, _("Cannot verify compressed archives"))); if (!IS_SUBCOMMAND_CLASS (SUBCL_WRITE)) option_conflict_error ("--verify", subcommand_string (subcommand_option)); } if (use_compress_program_option) { if (multi_volume_option) USAGE_ERROR ((0, 0, _("Cannot use multi-volume compressed archives"))); if (IS_SUBCOMMAND_CLASS (SUBCL_UPDATE)) USAGE_ERROR ((0, 0, _("Cannot update compressed archives"))); if (subcommand_option == CAT_SUBCOMMAND) USAGE_ERROR ((0, 0, _("Cannot concatenate compressed archives"))); } /* It is no harm to use --pax-option on non-pax archives in archive reading mode. It may even be useful, since it allows to override file attributes from tar headers. Therefore I allow such usage. --gray */ if (args.pax_option && archive_format != POSIX_FORMAT && !IS_SUBCOMMAND_CLASS (SUBCL_READ)) USAGE_ERROR ((0, 0, _("--pax-option can be used only on POSIX archives"))); /* star creates non-POSIX typed archives with xattr support, so allow the extra headers when reading */ if ((acls_option > 0) && archive_format != POSIX_FORMAT && !IS_SUBCOMMAND_CLASS (SUBCL_READ)) USAGE_ERROR ((0, 0, _("--acls can be used only on POSIX archives"))); if ((selinux_context_option > 0) && archive_format != POSIX_FORMAT && !IS_SUBCOMMAND_CLASS (SUBCL_READ)) USAGE_ERROR ((0, 0, _("--selinux can be used only on POSIX archives"))); if ((xattrs_option > 0) && archive_format != POSIX_FORMAT && !IS_SUBCOMMAND_CLASS (SUBCL_READ)) USAGE_ERROR ((0, 0, _("--xattrs can be used only on POSIX archives"))); if (starting_file_option && !IS_SUBCOMMAND_CLASS (SUBCL_READ)) option_conflict_error ("--starting-file", subcommand_string (subcommand_option)); if (same_order_option && !IS_SUBCOMMAND_CLASS (SUBCL_READ)) option_conflict_error ("--same-order", subcommand_string (subcommand_option)); if (one_top_level_option) { char *base; if (absolute_names_option) option_conflict_error ("--one-top-level", "--absolute-names"); if (!one_top_level_dir) { /* If the user wants to guarantee that everything is under one directory, determine its name now and let it be created later. */ base = base_name (archive_name_array[0]); one_top_level_dir = strip_compression_suffix (base); free (base); if (!one_top_level_dir) USAGE_ERROR ((0, 0, _("Cannot deduce top-level directory name; " "please set it explicitly with --one-top-level=DIR"))); } } /* If ready to unlink hierarchies, so we are for simpler files. */ if (recursive_unlink_option) old_files_option = UNLINK_FIRST_OLD_FILES; /* Flags for accessing files to be read from or copied into. POSIX says O_NONBLOCK has unspecified effect on most types of files, but in practice it never harms and sometimes helps. */ { int base_open_flags = (O_BINARY | O_CLOEXEC | O_NOCTTY | O_NONBLOCK | (dereference_option ? 0 : O_NOFOLLOW) | (atime_preserve_option == system_atime_preserve ? O_NOATIME : 0)); open_read_flags = O_RDONLY | base_open_flags; open_searchdir_flags = O_SEARCH | O_DIRECTORY | base_open_flags; } fstatat_flags = dereference_option ? 0 : AT_SYMLINK_NOFOLLOW; if (subcommand_option == TEST_LABEL_SUBCOMMAND) { /* --test-label is silent if the user has specified the label name to compare against. */ if (!args.input_files) verbose_option++; } else if (utc_option) verbose_option = 2; if (tape_length_option && tape_length_option < record_size) USAGE_ERROR ((0, 0, _("Volume length cannot be less than record size"))); if (same_order_option && listed_incremental_option) option_conflict_error ("--preserve-order", "--listed-incremental"); /* Forbid using -c with no input files whatsoever. Check that '-f -', explicit or implied, is used correctly. */ switch (subcommand_option) { case CREATE_SUBCOMMAND: if (!args.input_files && !files_from_option) USAGE_ERROR ((0, 0, _("Cowardly refusing to create an empty archive"))); if (args.compress_autodetect && archive_names && strcmp (archive_name_array[0], "-")) set_compression_program_by_suffix (archive_name_array[0], use_compress_program_option); break; case EXTRACT_SUBCOMMAND: case LIST_SUBCOMMAND: case DIFF_SUBCOMMAND: case TEST_LABEL_SUBCOMMAND: for (archive_name_cursor = archive_name_array; archive_name_cursor < archive_name_array + archive_names; archive_name_cursor++) if (!strcmp (*archive_name_cursor, "-")) request_stdin ("-f"); break; case CAT_SUBCOMMAND: case UPDATE_SUBCOMMAND: case APPEND_SUBCOMMAND: for (archive_name_cursor = archive_name_array; archive_name_cursor < archive_name_array + archive_names; archive_name_cursor++) if (!strcmp (*archive_name_cursor, "-")) USAGE_ERROR ((0, 0, _("Options '-Aru' are incompatible with '-f -'"))); default: break; } /* Initialize stdlis */ if (index_file_name) { stdlis = fopen (index_file_name, "w"); if (! stdlis) open_fatal (index_file_name); } else stdlis = to_stdout_option ? stderr : stdout; archive_name_cursor = archive_name_array; /* Prepare for generating backup names. */ if (args.backup_suffix_string) simple_backup_suffix = xstrdup (args.backup_suffix_string); if (backup_option) { backup_type = xget_version ("--backup", args.version_control_string); /* No backup is needed either if explicitely disabled or if the extracted files are not being written to disk. */ if (backup_type == no_backups || EXTRACT_OVER_PIPE) backup_option = false; } checkpoint_finish_compile (); report_textual_dates (&args); } void more_options (int argc, char **argv) { int idx; if (argp_parse (&argp, argc, argv, ARGP_IN_ORDER, &idx, &args)) exit (TAREXIT_FAILURE); } /* Tar proper. */ /* Main routine for tar. */ int main (int argc, char **argv) { set_start_time (); set_program_name (argv[0]); setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); exit_failure = TAREXIT_FAILURE; exit_status = TAREXIT_SUCCESS; error_hook = checkpoint_flush_actions; filename_terminator = '\n'; set_quoting_style (0, DEFAULT_QUOTING_STYLE); debian_longlink_hack_init (); pristine_tar_compat_init (); /* Make sure we have first three descriptors available */ stdopen (); /* Pre-allocate a few structures. */ allocated_archive_names = 10; archive_name_array = xmalloc (sizeof (const char *) * allocated_archive_names); archive_names = 0; /* System V fork+wait does not work if SIGCHLD is ignored. */ signal (SIGCHLD, SIG_DFL); /* Try to disable the ability to unlink a directory. */ priv_set_remove_linkdir (); /* Decode options. */ decode_options (argc, argv); name_init (); /* Main command execution. */ if (volno_file_option) init_volume_number (); switch (subcommand_option) { case UNKNOWN_SUBCOMMAND: USAGE_ERROR ((0, 0, _("You must specify one of the '-Acdtrux', '--delete' or '--test-label' options"))); case CAT_SUBCOMMAND: case UPDATE_SUBCOMMAND: case APPEND_SUBCOMMAND: update_archive (); break; case DELETE_SUBCOMMAND: delete_archive_members (); break; case CREATE_SUBCOMMAND: create_archive (); break; case EXTRACT_SUBCOMMAND: extr_init (); read_and (extract_archive); /* FIXME: should extract_finish () even if an ordinary signal is received. */ extract_finish (); break; case LIST_SUBCOMMAND: read_and (list_archive); break; case DIFF_SUBCOMMAND: diff_init (); read_and (diff_archive); break; case TEST_LABEL_SUBCOMMAND: test_archive_label (); } checkpoint_finish (); if (totals_option) print_total_stats (); if (check_links_option) check_links (); if (volno_file_option) closeout_volume_number (); /* Dispose of allocated memory, and return. */ free (archive_name_array); xattrs_clear_setup (); name_term (); if (exit_status == TAREXIT_FAILURE) error (0, 0, _("Exiting with failure status due to previous errors")); if (stdlis == stdout) close_stdout (); else if (ferror (stderr) || fclose (stderr) != 0) set_exit_status (TAREXIT_FAILURE); return exit_status; } void tar_stat_init (struct tar_stat_info *st) { memset (st, 0, sizeof (*st)); } /* Close the stream or file descriptor associated with ST, and remove all traces of it from ST. Return true if successful, false (with a diagnostic) otherwise. */ bool tar_stat_close (struct tar_stat_info *st) { int status = (st->dirstream ? closedir (st->dirstream) : 0 < st->fd ? close (st->fd) : 0); st->dirstream = 0; st->fd = 0; if (status == 0) return true; else { close_diag (st->orig_file_name); return false; } } void tar_stat_destroy (struct tar_stat_info *st) { tar_stat_close (st); xheader_xattr_free (st->xattr_map, st->xattr_map_size); free (st->orig_file_name); free (st->file_name); free (st->link_name); free (st->uname); free (st->gname); free (st->cntx_name); free (st->acls_a_ptr); free (st->acls_d_ptr); free (st->sparse_map); free (st->dumpdir); xheader_destroy (&st->xhdr); info_free_exclist (st); memset (st, 0, sizeof (*st)); } /* Format mask for all available formats that support nanosecond timestamp resolution. */ #define NS_PRECISION_FORMAT_MASK FORMAT_MASK (POSIX_FORMAT) /* Same as timespec_cmp, but ignore nanoseconds if current archive format does not provide sufficient resolution. */ int tar_timespec_cmp (struct timespec a, struct timespec b) { if (!(FORMAT_MASK (current_format) & NS_PRECISION_FORMAT_MASK)) a.tv_nsec = b.tv_nsec = 0; return timespec_cmp (a, b); } /* Set tar exit status to VAL, unless it is already indicating a more serious condition. This relies on the fact that the values of TAREXIT_ constants are ranged by severity. */ void set_exit_status (int val) { if (val > exit_status) exit_status = val; }
KubaKaszycki/kubux
tar/.pc/add-clamp-mtime.diff/src/tar.c
C
gpl-3.0
79,460
var express = require("express"); var router = express.Router(); var ObjectId = require('mongoose').Types.ObjectId;//by seif var mongoose = require("mongoose"); var crypto = require('crypto'), shasum = crypto.createHash('sha1'); var bodyParser = require("body-parser"); var helpers = require("../util/helpers"); var validator = require("validator"); var jwt = require('jsonwebtoken'); router.get("/members/add", function (request, response) { console.log("add member"); console.log("query :", request.query); mongoose.model("groups").find({name: request.query.name}, function (err, group) { console.log(group); if (!err) { if (helpers.isInArray(request.query.uid, group[0].members)) { response.json({error: "user already in your followings"}); } else { group[0].members.push(request.query.uid); group[0].save(function (error) { if (error) response.json({error: "error in handeling your request"}); response.json(group); console.log(group); }); } } }) }); router.post("/add", bodyParser.urlencoded({extended: false}), function (request, response) { console.log("body", request.body); var groupModel = mongoose.model("groups"); var group = new groupModel({ name: request.body.name, owner: request.body.owner }); group.save(function (err) { if (!err) { response.json(group); console.log("add group sucess"); } else { response.send(err); response.status(400).json({error: "adding Failed"}); } }); }); router.get("/search", function (request, response) { switch (request.query.field) { case "name": mongoose.model("groups").find({ owner: request.query.user_id, $text: {$search: request.query.q} }).populate('members').exec(function (err, groups) { if (err) { response.status(400).json({error: err}); } else { response.json(groups); } }); break; } }); router.get("/:id/list", function (request, response) { console.log("list groups by user"); console.log("prams", request.params); mongoose.model("groups").find({owner: new ObjectId(request.params.id)}, function (err, groups) { console.log("result groups :", groups); if (!err) { response.json(groups); } else { response.status(400).json({error: err}); } }); }); router.get("/:id/members", function (request, response) { console.log("list members"); console.log("params:",request.params.id) mongoose.model("groups").findOne({_id: new ObjectId(request.params.id)}, { _id: 0, members: 1 }).populate("members").exec(function (err, members) { console.log("prams", request.params); if (err) { response.json({error: "Not found"}); console.log("error in list members"); } else { response.json(members); console.log("members :", members); } }) }); router.delete("/:gid/members/:uid", function (request, response) { console.log("delete member"); mongoose.model("groups").findById(request.params.gid, function (err, group) { if (!err) { if (helpers.isInArray(request.params.uid, group.members)) { var deletedUser = ''; group.members = helpers.removeItem(group.members, request.params.uid); group.save(function (error) { if (error) response.json({error: "error in deleting members"}); response.json(group); }); } else { response.json({error: "member not exists"}); } } }) }); router.delete("/:gid", function (request, response) { console.log("delete member"); mongoose.model("groups").remove({"_id":request.params.gid}, function (err, data) { if (!err) { response.json("group deleted sucessfuly") console.log("group deleted sucessfuly") } else { response.json("group not deleted ") console.log("group not deleted") } }) }); module.exports = router;
seifElislam/NodeJs-Ordering-system
controllers/groups.js
JavaScript
gpl-3.0
4,525
package ch2.pyrmont; import java.net.URL; import java.net.URLClassLoader; import java.io.File; import java.io.IOException; import javax.servlet.Servlet; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class ServletProcessor1 { public void process(Request request, Response response) { String uri = request.getUri(); String servletName = uri.substring(uri.lastIndexOf("/") + 1); URLClassLoader loader = null; try { // create a URLClassLoader File servletClassPath = new File(Constants.SERVLET_ROOT); URL url = servletClassPath.toURI().toURL(); URL[] urls = new URL[] {url}; loader = new URLClassLoader(urls); } catch (IOException e) { System.out.println(e.toString() ); } Class myClass = null; try { /* * The Java ClassLoader.loadClass(String) method requires that * class names must be fully qualified by their package and class name * * Error eg: myClass = loader.loadClass(servletName); * */ myClass = loader.loadClass("ch2.pyrmont.servlet." + servletName); } catch (ClassNotFoundException e) { System.out.println(e.toString()); } Servlet servlet = null; try { servlet = (Servlet) myClass.newInstance(); servlet.service((ServletRequest) request, (ServletResponse) response); } catch (Exception e) { System.out.println(e.toString()); } catch (Throwable e) { System.out.println(e.toString()); } } }
jasonleaster/TheWayToJava
HowTomcatWorks/src/main/java/ch2/pyrmont/ServletProcessor1.java
Java
gpl-3.0
1,690
import SimpleSchema from 'simpl-schema'; SimpleSchema.extendOptions(['autoform']); Subjects = new Mongo.Collection('subjects'); if ( Meteor.isServer ) { Subjects._ensureIndex( { name: 1, _id: 1 } ); } Subjects.allow({ insert: function(userId, doc) { return true; }, update: function(userId, doc) { return !!userId; } }); ScoreSchema = new SimpleSchema({ scoreAStart: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 80; } } }, scoreA: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 100; } } }, scoreAMinusStart: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 75; } } }, scoreAMinus: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 79; } } }, scoreBPlusStart: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 70; } } }, scoreBPlus: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 74; } } }, scoreBStart: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 65; } } }, scoreB: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 69; } } }, scoreBMinusStart: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 60; } } }, scoreBMinus: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 64; } } }, scoreCPlusStart: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 55; } } }, scoreCPlus: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 59; } } }, scoreCStart: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 50; } } }, scoreC: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 54; } } }, scoreCMinusStart: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 45; } } }, scoreCMinus: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 49; } } }, scoreDPlusStart: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 40; } } }, scoreDPlus: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 44; } } }, scoreDStart: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 35; } } }, scoreD: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 39; } } }, scoreDMinusStart: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 30; } } }, scoreDMinus: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 34; } } }, scoreEStart: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 0; } } }, scoreE: { type: Number, min: 0, max: 100, optional: true, autoValue: function(){ if (this.isInsert) { return 29; } } }, }); SubjectSchema = new SimpleSchema({ name: { type: String }, subjectCode: { type: String, optional: true, label: "Subject Code" }, gradingScheme: { type: ScoreSchema, label: "The grading table for the subject" }, type: { type: String, label: "the type/group of the subject", autoform: { type: 'select2', options: [ {value: "", label: "select one"}, {value:"mathematics", label: "mathematics"}, {value:"languages", label: "languages"}, {value:"sciences", label: "sciences"}, {value:"humanities", label: "humanities"} ] } }, requirement: { type: String, label: "the requirement of the subject", autoform: { type: 'select2', options: [ {value: "", label: "select one"}, {value:"mandatory", label: "mandatory"}, {value:"optional", label: "optional"} ] } }, subjectMaster: { type: String, label: "the subject master (optional)", optional: true, autoform: { type: 'select2', options: function () { var options = [{label: "select one", value: ""}]; Meteor.users.find({'roles.__global_roles__':'teacher', active: true}).forEach(function (element) { var name = element.profile.firstname + " " + element.profile.lastname + " | " + element.profile.staffId options.push({ label: name, value: element._id }) }); return options; } } }, order: { type: Number, optional: true, autoValue: function(){ if (this.isInsert) { var numberOfSubjects = Subjects.find({}).count(); return (numberOfSubjects + 1); } } }, active: { type: Boolean, defaultValue: true, optional: true, autoform: { type: "hidden" } }, createdAt: { type: Date, autoValue: function() { if (this.isInsert) { return new Date(); } else if (this.isUpsert) { return {$setOnInsert: new Date()}; } else { this.unset(); // Prevent user from supplying their own val } }, autoform: { type: "hidden" } }, updatedAt: { type: Date, autoValue: function() { if (this.isUpdate) { return new Date(); } }, //denyInsert: true, optional: true, autoform: { type: "hidden" } } }); Meteor.methods({ deleteSubject: function(id){ Subjects.remove(id); FlowRouter.go('subjects'); }, deactivateSubject: function(id){ check(id, String); var status = Subjects.findOne({_id: id}).active; if(status == true){ Subjects.update(id, { $set: { active: false } }); } else { Subjects.update(id, { $set: { active: true } }); } } }); Subjects.attachSchema ( SubjectSchema );
gmahota/AGNUS_CRM
lib/collections/schemas/eschool/subjects.js
JavaScript
gpl-3.0
8,965
#pragma once #ifndef GBKFIT_FITTER_MULTINEST_FITTER_MULTINEST_HPP #define GBKFIT_FITTER_MULTINEST_FITTER_MULTINEST_HPP #include "gbkfit/fitter.hpp" namespace gbkfit { namespace fitter { namespace multinest { class FitterMultinest : public Fitter { public: static const double DEFAULT_EFR; static const double DEFAULT_TOL; static const double DEFAULT_ZTOL; static const double DEFAULT_LOGZERO; static const int DEFAULT_IS; static const int DEFAULT_MMODAL; static const int DEFAULT_CEFF; static const int DEFAULT_NLIVE; static const int DEFAULT_MAXITER; static const int DEFAULT_SEED; static const int DEFAULT_OUTFILE; public: double m_efr; double m_tol; double m_ztol; double m_logzero; int m_is; int m_mmodal; int m_ceff; int m_nlive; int m_maxiter; int m_seed; int m_outfile; public: FitterMultinest(void); ~FitterMultinest(); const std::string& get_type(void) const final; FitterResult* fit(const DModel* dmodel, const Params* params, const std::vector<Dataset*>& data) const final; }; } // namespace multinest } // namespace fitter } // namespace gbkfit #endif // GBKFIT_FITTER_MULTINEST_FITTER_MULTINEST_HPP
bek0s/gbkfit
src/gbkfit/gbkfit_fitter_multinest/include/gbkfit/fitter/multinest/fitter_multinest.hpp
C++
gpl-3.0
1,231
from __future__ import absolute_import from .MockPrinter import MockPrinter import mock from random import random class M201_Tests(MockPrinter): def setUp(self): self.printer.path_planner.native_planner.setAcceleration = mock.Mock() self.printer.axis_config = self.printer.AXIS_CONFIG_XY self.printer.speed_factor = 1.0 def exercise(self): values = {} gcode = "M201" for i, v in enumerate(self.printer.acceleration): axis = self.printer.AXES[i] values[axis] = round(random() * 9000.0, 0) gcode += " {:s}{:.0f}".format(axis, values[axis]) self.execute_gcode(gcode) return { "values": values, "call_args": self.printer.path_planner.native_planner.setAcceleration.call_args[0][0] } def test_gcodes_M201_all_axes_G21_mm(self): test_data = self.exercise() for i, axis in enumerate(self.printer.AXES): expected = round(test_data["values"][axis] * self.printer.factor / 3600.0, 4) result = test_data["call_args"][i] self.assertEqual(expected, result, axis + ": expected {:.0f} but got {:.0f}".format(expected, result)) def test_gcodes_M201_all_axes_G20_inches(self): self.printer.factor = 25.4 test_data = self.exercise() for i, axis in enumerate(self.printer.AXES): expected = round(test_data["values"][axis] * self.printer.factor / 3600.0, 4) result = test_data["call_args"][i] self.assertEqual(expected, result, axis + ": expected {:.0f} but got {:.0f}".format(expected, result)) def test_gcodes_M201_CoreXY(self): self.printer.axis_config = self.printer.AXIS_CONFIG_CORE_XY while True: # account for remote possibility of two equal random numbers for X and Y test_data = self.exercise() if test_data["values"]["X"] != test_data["values"]["Y"]: break self.assertEqual( test_data["call_args"][0], test_data["call_args"][1], "For CoreXY mechanics, X & Y values must match. But X={}, Y={} (mm/min / 3600)".format( test_data["call_args"][0], test_data["call_args"][1])) def test_gcodes_M201_H_belt(self): self.printer.axis_config = self.printer.AXIS_CONFIG_H_BELT while True: # account for remote possibility of two equal random numbers for X and Y test_data = self.exercise() if test_data["values"]["X"] != test_data["values"]["Y"]: break self.assertEqual( test_data["call_args"][0], test_data["call_args"][1], "For H-Belt mechanics, X & Y values must match. But X={}, Y={} (mm/min / 3600)".format( test_data["call_args"][0], test_data["call_args"][1])) def test_gcodes_M201_Delta(self): self.printer.axis_config = self.printer.AXIS_CONFIG_DELTA while True: # account for super, ultra-duper remote possibility of three equal random numbers for X , Y and Z test_data = self.exercise() if (test_data["values"]["X"] + test_data["values"]["Y"] + test_data["values"]["Y"]) != ( test_data["values"]["X"] * 3): break self.assertEqual( test_data["call_args"][0] + test_data["call_args"][1] + test_data["call_args"][2], test_data["call_args"][0] * 3, "For CoreXY mechanics, X & Y values must match. But X={}, Y={} (mm/min / 3600)".format( test_data["call_args"][0], test_data["call_args"][1], test_data["call_args"][2]))
intelligent-agent/redeem
tests/gcode/test_M201.py
Python
gpl-3.0
3,414
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_65) on Fri Oct 17 17:30:05 BST 2014 --> <title>Index</title> <meta name="date" content="2014-10-17"> <link rel="stylesheet" type="text/css" href="./stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Index"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="./overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="./overview-tree.html">Tree</a></li> <li><a href="./deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="./help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="./index.html?index-all.html" target="_top">Frames</a></li> <li><a href="index-all.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="./allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="#_A_">A</a>&nbsp;<a href="#_B_">B</a>&nbsp;<a href="#_C_">C</a>&nbsp;<a href="#_D_">D</a>&nbsp;<a href="#_E_">E</a>&nbsp;<a href="#_F_">F</a>&nbsp;<a href="#_G_">G</a>&nbsp;<a href="#_H_">H</a>&nbsp;<a href="#_I_">I</a>&nbsp;<a href="#_L_">L</a>&nbsp;<a href="#_M_">M</a>&nbsp;<a href="#_P_">P</a>&nbsp;<a href="#_R_">R</a>&nbsp;<a href="#_T_">T</a>&nbsp;<a href="#_U_">U</a>&nbsp;<a href="#_V_">V</a>&nbsp;<a name="_A_"> <!-- --> </a> <h2 class="title">A</h2> <dl> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Validator.html#addColor(main.java.pcgod01.puzzle.Color...)">addColor(Color...)</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Validator.html" title="class in main.java.pcgod01.puzzle">Validator</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Validator.html#addMove(main.java.pcgod01.puzzle.Move...)">addMove(Move...)</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Validator.html" title="class in main.java.pcgod01.puzzle">Validator</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/cube/Cube.html#applyMove(main.java.pcgod01.puzzle.Move)">applyMove(Move)</a></span> - Method in class main.java.pcgod01.puzzle.cube.<a href="./main/java/pcgod01/puzzle/cube/Cube.html" title="class in main.java.pcgod01.puzzle.cube">Cube</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Puzzle.html#applyMove(main.java.pcgod01.puzzle.Move)">applyMove(Move)</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Puzzle.html" title="class in main.java.pcgod01.puzzle">Puzzle</a></dt> <dd> <div class="block">Applies a move to a puzzle.</div> </dd> </dl> <a name="_B_"> <!-- --> </a> <h2 class="title">B</h2> <dl> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/cube/CubePiece.html#B">B</a></span> - Static variable in class main.java.pcgod01.puzzle.cube.<a href="./main/java/pcgod01/puzzle/cube/CubePiece.html" title="class in main.java.pcgod01.puzzle.cube">CubePiece</a></dt> <dd>&nbsp;</dd> </dl> <a name="_C_"> <!-- --> </a> <h2 class="title">C</h2> <dl> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Color.html#clone()">clone()</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Color.html" title="class in main.java.pcgod01.puzzle">Color</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/cube/Cube.html#clone()">clone()</a></span> - Method in class main.java.pcgod01.puzzle.cube.<a href="./main/java/pcgod01/puzzle/cube/Cube.html" title="class in main.java.pcgod01.puzzle.cube">Cube</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/cube/CubePiece.html#clone()">clone()</a></span> - Method in class main.java.pcgod01.puzzle.cube.<a href="./main/java/pcgod01/puzzle/cube/CubePiece.html" title="class in main.java.pcgod01.puzzle.cube">CubePiece</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Move.html#clone()">clone()</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Move.html" title="class in main.java.pcgod01.puzzle">Move</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Piece.html#clone()">clone()</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Piece.html" title="class in main.java.pcgod01.puzzle">Piece</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Puzzle.html#clone()">clone()</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Puzzle.html" title="class in main.java.pcgod01.puzzle">Puzzle</a></dt> <dd> <div class="block">Returns a deep-clone of the puzzle.</div> </dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Validator.html#clone()">clone()</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Validator.html" title="class in main.java.pcgod01.puzzle">Validator</a></dt> <dd>&nbsp;</dd> <dt><a href="./main/java/pcgod01/puzzle/Color.html" title="class in main.java.pcgod01.puzzle"><span class="strong">Color</span></a> - Class in <a href="./main/java/pcgod01/puzzle/package-summary.html">main.java.pcgod01.puzzle</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Color.html#Color(java.lang.String)">Color(String)</a></span> - Constructor for class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Color.html" title="class in main.java.pcgod01.puzzle">Color</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Piece.html#colors">colors</a></span> - Variable in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Piece.html" title="class in main.java.pcgod01.puzzle">Piece</a></dt> <dd>&nbsp;</dd> <dt><a href="./main/java/pcgod01/puzzle/cube/Cube.html" title="class in main.java.pcgod01.puzzle.cube"><span class="strong">Cube</span></a> - Class in <a href="./main/java/pcgod01/puzzle/cube/package-summary.html">main.java.pcgod01.puzzle.cube</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/cube/Cube.html#Cube(int)">Cube(int)</a></span> - Constructor for class main.java.pcgod01.puzzle.cube.<a href="./main/java/pcgod01/puzzle/cube/Cube.html" title="class in main.java.pcgod01.puzzle.cube">Cube</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/cube/Cube.html#Cube(main.java.pcgod01.puzzle.Piece[][][])">Cube(Piece[][][])</a></span> - Constructor for class main.java.pcgod01.puzzle.cube.<a href="./main/java/pcgod01/puzzle/cube/Cube.html" title="class in main.java.pcgod01.puzzle.cube">Cube</a></dt> <dd>&nbsp;</dd> <dt><a href="./main/java/pcgod01/puzzle/cube/CubePiece.html" title="class in main.java.pcgod01.puzzle.cube"><span class="strong">CubePiece</span></a> - Class in <a href="./main/java/pcgod01/puzzle/cube/package-summary.html">main.java.pcgod01.puzzle.cube</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/cube/CubePiece.html#CubePiece(main.java.pcgod01.puzzle.Color,%20main.java.pcgod01.puzzle.Color,%20main.java.pcgod01.puzzle.Color,%20main.java.pcgod01.puzzle.Color,%20main.java.pcgod01.puzzle.Color,%20main.java.pcgod01.puzzle.Color)">CubePiece(Color, Color, Color, Color, Color, Color)</a></span> - Constructor for class main.java.pcgod01.puzzle.cube.<a href="./main/java/pcgod01/puzzle/cube/CubePiece.html" title="class in main.java.pcgod01.puzzle.cube">CubePiece</a></dt> <dd>&nbsp;</dd> </dl> <a name="_D_"> <!-- --> </a> <h2 class="title">D</h2> <dl> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/cube/CubePiece.html#D">D</a></span> - Static variable in class main.java.pcgod01.puzzle.cube.<a href="./main/java/pcgod01/puzzle/cube/CubePiece.html" title="class in main.java.pcgod01.puzzle.cube">CubePiece</a></dt> <dd>&nbsp;</dd> </dl> <a name="_E_"> <!-- --> </a> <h2 class="title">E</h2> <dl> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Color.html#equals(java.lang.Object)">equals(Object)</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Color.html" title="class in main.java.pcgod01.puzzle">Color</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/cube/Cube.html#equals(java.lang.Object)">equals(Object)</a></span> - Method in class main.java.pcgod01.puzzle.cube.<a href="./main/java/pcgod01/puzzle/cube/Cube.html" title="class in main.java.pcgod01.puzzle.cube">Cube</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Move.html#equals(java.lang.Object)">equals(Object)</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Move.html" title="class in main.java.pcgod01.puzzle">Move</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Piece.html#equals(java.lang.Object)">equals(Object)</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Piece.html" title="class in main.java.pcgod01.puzzle">Piece</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Puzzle.html#equals(java.lang.Object)">equals(Object)</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Puzzle.html" title="class in main.java.pcgod01.puzzle">Puzzle</a></dt> </dl> <a name="_F_"> <!-- --> </a> <h2 class="title">F</h2> <dl> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/cube/CubePiece.html#F">F</a></span> - Static variable in class main.java.pcgod01.puzzle.cube.<a href="./main/java/pcgod01/puzzle/cube/CubePiece.html" title="class in main.java.pcgod01.puzzle.cube">CubePiece</a></dt> <dd>&nbsp;</dd> </dl> <a name="_G_"> <!-- --> </a> <h2 class="title">G</h2> <dl> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Piece.html#getColor(int)">getColor(int)</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Piece.html" title="class in main.java.pcgod01.puzzle">Piece</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/cube/Cube.html#getCube()">getCube()</a></span> - Method in class main.java.pcgod01.puzzle.cube.<a href="./main/java/pcgod01/puzzle/cube/Cube.html" title="class in main.java.pcgod01.puzzle.cube">Cube</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Move.html#getKey()">getKey()</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Move.html" title="class in main.java.pcgod01.puzzle">Move</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/repeat/Repeater.html#getRepeats(main.java.pcgod01.puzzle.Puzzle,%20main.java.pcgod01.puzzle.Move[])">getRepeats(Puzzle, Move[])</a></span> - Static method in class main.java.pcgod01.repeat.<a href="./main/java/pcgod01/repeat/Repeater.html" title="class in main.java.pcgod01.repeat">Repeater</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/cube/Cube.html#getValidator()">getValidator()</a></span> - Static method in class main.java.pcgod01.puzzle.cube.<a href="./main/java/pcgod01/puzzle/cube/Cube.html" title="class in main.java.pcgod01.puzzle.cube">Cube</a></dt> <dd>&nbsp;</dd> </dl> <a name="_H_"> <!-- --> </a> <h2 class="title">H</h2> <dl> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Color.html#hashCode()">hashCode()</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Color.html" title="class in main.java.pcgod01.puzzle">Color</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Move.html#hashCode()">hashCode()</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Move.html" title="class in main.java.pcgod01.puzzle">Move</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Piece.html#hashCode()">hashCode()</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Piece.html" title="class in main.java.pcgod01.puzzle">Piece</a></dt> <dd>&nbsp;</dd> </dl> <a name="_I_"> <!-- --> </a> <h2 class="title">I</h2> <dl> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/cube/Cube.html#initPieces()">initPieces()</a></span> - Method in class main.java.pcgod01.puzzle.cube.<a href="./main/java/pcgod01/puzzle/cube/Cube.html" title="class in main.java.pcgod01.puzzle.cube">Cube</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Validator.html#isColorValid(main.java.pcgod01.puzzle.Color...)">isColorValid(Color...)</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Validator.html" title="class in main.java.pcgod01.puzzle">Validator</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Validator.html#isMoveValid(main.java.pcgod01.puzzle.Move...)">isMoveValid(Move...)</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Validator.html" title="class in main.java.pcgod01.puzzle">Validator</a></dt> <dd>&nbsp;</dd> </dl> <a name="_L_"> <!-- --> </a> <h2 class="title">L</h2> <dl> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/cube/CubePiece.html#L">L</a></span> - Static variable in class main.java.pcgod01.puzzle.cube.<a href="./main/java/pcgod01/puzzle/cube/CubePiece.html" title="class in main.java.pcgod01.puzzle.cube">CubePiece</a></dt> <dd>&nbsp;</dd> </dl> <a name="_M_"> <!-- --> </a> <h2 class="title">M</h2> <dl> <dt><a href="./main/java/pcgod01/repeat/Main.html" title="class in main.java.pcgod01.repeat"><span class="strong">Main</span></a> - Class in <a href="./main/java/pcgod01/repeat/package-summary.html">main.java.pcgod01.repeat</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/repeat/Main.html#Main()">Main()</a></span> - Constructor for class main.java.pcgod01.repeat.<a href="./main/java/pcgod01/repeat/Main.html" title="class in main.java.pcgod01.repeat">Main</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/repeat/Main.html#main(java.lang.String[])">main(String[])</a></span> - Static method in class main.java.pcgod01.repeat.<a href="./main/java/pcgod01/repeat/Main.html" title="class in main.java.pcgod01.repeat">Main</a></dt> <dd>&nbsp;</dd> <dt><a href="./main/java/pcgod01/rubiksolver/Main.html" title="class in main.java.pcgod01.rubiksolver"><span class="strong">Main</span></a> - Class in <a href="./main/java/pcgod01/rubiksolver/package-summary.html">main.java.pcgod01.rubiksolver</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/rubiksolver/Main.html#Main()">Main()</a></span> - Constructor for class main.java.pcgod01.rubiksolver.<a href="./main/java/pcgod01/rubiksolver/Main.html" title="class in main.java.pcgod01.rubiksolver">Main</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/rubiksolver/Main.html#main(java.lang.String[])">main(String[])</a></span> - Static method in class main.java.pcgod01.rubiksolver.<a href="./main/java/pcgod01/rubiksolver/Main.html" title="class in main.java.pcgod01.rubiksolver">Main</a></dt> <dd>&nbsp;</dd> <dt><a href="./main/java/pcgod01/puzzle/package-summary.html">main.java.pcgod01.puzzle</a> - package main.java.pcgod01.puzzle</dt> <dd>&nbsp;</dd> <dt><a href="./main/java/pcgod01/puzzle/cube/package-summary.html">main.java.pcgod01.puzzle.cube</a> - package main.java.pcgod01.puzzle.cube</dt> <dd>&nbsp;</dd> <dt><a href="./main/java/pcgod01/repeat/package-summary.html">main.java.pcgod01.repeat</a> - package main.java.pcgod01.repeat</dt> <dd>&nbsp;</dd> <dt><a href="./main/java/pcgod01/rubiksolver/package-summary.html">main.java.pcgod01.rubiksolver</a> - package main.java.pcgod01.rubiksolver</dt> <dd>&nbsp;</dd> <dt><a href="./main/java/pcgod01/puzzle/Move.html" title="class in main.java.pcgod01.puzzle"><span class="strong">Move</span></a> - Class in <a href="./main/java/pcgod01/puzzle/package-summary.html">main.java.pcgod01.puzzle</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Move.html#Move(java.lang.String)">Move(String)</a></span> - Constructor for class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Move.html" title="class in main.java.pcgod01.puzzle">Move</a></dt> <dd>&nbsp;</dd> </dl> <a name="_P_"> <!-- --> </a> <h2 class="title">P</h2> <dl> <dt><a href="./main/java/pcgod01/puzzle/Piece.html" title="class in main.java.pcgod01.puzzle"><span class="strong">Piece</span></a> - Class in <a href="./main/java/pcgod01/puzzle/package-summary.html">main.java.pcgod01.puzzle</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Piece.html#Piece(main.java.pcgod01.puzzle.Color[],%20main.java.pcgod01.puzzle.Validator)">Piece(Color[], Validator)</a></span> - Constructor for class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Piece.html" title="class in main.java.pcgod01.puzzle">Piece</a></dt> <dd>&nbsp;</dd> <dt><a href="./main/java/pcgod01/puzzle/Puzzle.html" title="class in main.java.pcgod01.puzzle"><span class="strong">Puzzle</span></a> - Class in <a href="./main/java/pcgod01/puzzle/package-summary.html">main.java.pcgod01.puzzle</a></dt> <dd> <div class="block">A twisty puzzle that can be fully manipulated.</div> </dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Puzzle.html#Puzzle()">Puzzle()</a></span> - Constructor for class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Puzzle.html" title="class in main.java.pcgod01.puzzle">Puzzle</a></dt> <dd>&nbsp;</dd> </dl> <a name="_R_"> <!-- --> </a> <h2 class="title">R</h2> <dl> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/cube/CubePiece.html#R">R</a></span> - Static variable in class main.java.pcgod01.puzzle.cube.<a href="./main/java/pcgod01/puzzle/cube/CubePiece.html" title="class in main.java.pcgod01.puzzle.cube">CubePiece</a></dt> <dd>&nbsp;</dd> <dt><a href="./main/java/pcgod01/repeat/Repeater.html" title="class in main.java.pcgod01.repeat"><span class="strong">Repeater</span></a> - Class in <a href="./main/java/pcgod01/repeat/package-summary.html">main.java.pcgod01.repeat</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/repeat/Repeater.html#Repeater()">Repeater()</a></span> - Constructor for class main.java.pcgod01.repeat.<a href="./main/java/pcgod01/repeat/Repeater.html" title="class in main.java.pcgod01.repeat">Repeater</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/cube/CubePiece.html#rotate(main.java.pcgod01.puzzle.Move)">rotate(Move)</a></span> - Method in class main.java.pcgod01.puzzle.cube.<a href="./main/java/pcgod01/puzzle/cube/CubePiece.html" title="class in main.java.pcgod01.puzzle.cube">CubePiece</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Piece.html#rotate(main.java.pcgod01.puzzle.Move)">rotate(Move)</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Piece.html" title="class in main.java.pcgod01.puzzle">Piece</a></dt> <dd>&nbsp;</dd> </dl> <a name="_T_"> <!-- --> </a> <h2 class="title">T</h2> <dl> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Color.html#toString()">toString()</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Color.html" title="class in main.java.pcgod01.puzzle">Color</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Move.html#toString()">toString()</a></span> - Method in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Move.html" title="class in main.java.pcgod01.puzzle">Move</a></dt> <dd>&nbsp;</dd> </dl> <a name="_U_"> <!-- --> </a> <h2 class="title">U</h2> <dl> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/cube/CubePiece.html#U">U</a></span> - Static variable in class main.java.pcgod01.puzzle.cube.<a href="./main/java/pcgod01/puzzle/cube/CubePiece.html" title="class in main.java.pcgod01.puzzle.cube">CubePiece</a></dt> <dd>&nbsp;</dd> </dl> <a name="_V_"> <!-- --> </a> <h2 class="title">V</h2> <dl> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Piece.html#validator">validator</a></span> - Variable in class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Piece.html" title="class in main.java.pcgod01.puzzle">Piece</a></dt> <dd>&nbsp;</dd> <dt><a href="./main/java/pcgod01/puzzle/Validator.html" title="class in main.java.pcgod01.puzzle"><span class="strong">Validator</span></a> - Class in <a href="./main/java/pcgod01/puzzle/package-summary.html">main.java.pcgod01.puzzle</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Validator.html#Validator()">Validator()</a></span> - Constructor for class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Validator.html" title="class in main.java.pcgod01.puzzle">Validator</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="./main/java/pcgod01/puzzle/Validator.html#Validator(main.java.pcgod01.puzzle.Color[],%20main.java.pcgod01.puzzle.Move[])">Validator(Color[], Move[])</a></span> - Constructor for class main.java.pcgod01.puzzle.<a href="./main/java/pcgod01/puzzle/Validator.html" title="class in main.java.pcgod01.puzzle">Validator</a></dt> <dd>&nbsp;</dd> </dl> <a href="#_A_">A</a>&nbsp;<a href="#_B_">B</a>&nbsp;<a href="#_C_">C</a>&nbsp;<a href="#_D_">D</a>&nbsp;<a href="#_E_">E</a>&nbsp;<a href="#_F_">F</a>&nbsp;<a href="#_G_">G</a>&nbsp;<a href="#_H_">H</a>&nbsp;<a href="#_I_">I</a>&nbsp;<a href="#_L_">L</a>&nbsp;<a href="#_M_">M</a>&nbsp;<a href="#_P_">P</a>&nbsp;<a href="#_R_">R</a>&nbsp;<a href="#_T_">T</a>&nbsp;<a href="#_U_">U</a>&nbsp;<a href="#_V_">V</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="./overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="./overview-tree.html">Tree</a></li> <li><a href="./deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="./help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="./index.html?index-all.html" target="_top">Frames</a></li> <li><a href="index-all.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="./allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
pc-god-01/automated-twisty-puzzles
doc/index-all.html
HTML
gpl-3.0
24,279
// The MIT License (MIT) // // Copyright (c) 2015 Kristian Stangeland // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, // modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the // Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package io.github.tommsy64.satchels.item.storage; import java.util.Collections; import java.util.Iterator; import java.util.UUID; import java.util.concurrent.ConcurrentMap; import org.bukkit.inventory.ItemStack; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.collect.Iterators; import com.google.common.collect.Maps; import io.github.tommsy64.satchels.item.storage.NbtFactory.NbtCompound; import io.github.tommsy64.satchels.item.storage.NbtFactory.NbtList; import lombok.NonNull; public class Attributes { public enum Operation { ADD_NUMBER(0), MULTIPLY_PERCENTAGE(1), ADD_PERCENTAGE(2); private int id; private Operation(int id) { this.id = id; } public int getId() { return id; } public static Operation fromId(int id) { // Linear scan is very fast for small N for (Operation op : values()) { if (op.getId() == id) { return op; } } throw new IllegalArgumentException("Corrupt operation ID " + id + " detected."); } } public static class AttributeType { private static ConcurrentMap<String, AttributeType> LOOKUP = Maps.newConcurrentMap(); public static final AttributeType GENERIC_MAX_HEALTH = new AttributeType("generic.maxHealth").register(); public static final AttributeType GENERIC_FOLLOW_RANGE = new AttributeType("generic.followRange").register(); public static final AttributeType GENERIC_ATTACK_DAMAGE = new AttributeType("generic.attackDamage").register(); public static final AttributeType GENERIC_MOVEMENT_SPEED = new AttributeType("generic.movementSpeed").register(); public static final AttributeType GENERIC_KNOCKBACK_RESISTANCE = new AttributeType("generic.knockbackResistance").register(); private final String minecraftId; /** * Construct a new attribute type. * <p> * Remember to {@link #register()} the type. * @param minecraftId - the ID of the type. */ public AttributeType(String minecraftId) { this.minecraftId = minecraftId; } /** * Retrieve the associated minecraft ID. * @return The associated ID. */ public String getMinecraftId() { return minecraftId; } /** * Register the type in the central registry. * @return The registered type. */ // Constructors should have no side-effects! public AttributeType register() { AttributeType old = LOOKUP.putIfAbsent(minecraftId, this); return old != null ? old : this; } /** * Retrieve the attribute type associated with a given ID. * @param minecraftId The ID to search for. * @return The attribute type, or NULL if not found. */ public static AttributeType fromId(String minecraftId) { return LOOKUP.get(minecraftId); } /** * Retrieve every registered attribute type. * @return Every type. */ public static Iterable<AttributeType> values() { return LOOKUP.values(); } } public static class Attribute { private NbtCompound data; private Attribute(Builder builder) { data = NbtFactory.createCompound(); setAmount(builder.amount); setOperation(builder.operation); setAttributeType(builder.type); setName(builder.name); setUUID(builder.uuid); } private Attribute(NbtCompound data) { this.data = data; } public double getAmount() { return data.getDouble("Amount", 0.0); } public void setAmount(double amount) { data.put("Amount", amount); } public Operation getOperation() { return Operation.fromId(data.getInteger("Operation", 0)); } public void setOperation(@NonNull Operation operation) { Preconditions.checkNotNull(operation, "operation cannot be NULL."); data.put("Operation", operation.getId()); } public AttributeType getAttributeType() { return AttributeType.fromId(data.getString("AttributeName", null)); } public void setAttributeType(@NonNull AttributeType type) { Preconditions.checkNotNull(type, "type cannot be NULL."); data.put("AttributeName", type.getMinecraftId()); } public String getName() { return data.getString("Name", null); } public void setName(@NonNull String name) { Preconditions.checkNotNull(name, "name cannot be NULL."); data.put("Name", name); } public UUID getUUID() { return new UUID(data.getLong("UUIDMost", null), data.getLong("UUIDLeast", null)); } public void setUUID(@NonNull UUID id) { Preconditions.checkNotNull("id", "id cannot be NULL."); data.put("UUIDLeast", id.getLeastSignificantBits()); data.put("UUIDMost", id.getMostSignificantBits()); } /** * Construct a new attribute builder with a random UUID and default operation of adding numbers. * @return The attribute builder. */ public static Builder newBuilder() { return new Builder().uuid(UUID.randomUUID()).operation(Operation.ADD_NUMBER); } // Makes it easier to construct an attribute public static class Builder { private double amount; private Operation operation = Operation.ADD_NUMBER; private AttributeType type; private String name; private UUID uuid; private Builder() { // Don't make this accessible } public Builder amount(double amount) { this.amount = amount; return this; } public Builder operation(Operation operation) { this.operation = operation; return this; } public Builder type(AttributeType type) { this.type = type; return this; } public Builder name(String name) { this.name = name; return this; } public Builder uuid(UUID uuid) { this.uuid = uuid; return this; } public Attribute build() { return new Attribute(this); } } } // This may be modified public ItemStack stack; private NbtList attributes; public Attributes(ItemStack stack) { // Create a CraftItemStack (under the hood) this.stack = NbtFactory.getCraftItemStack(stack); loadAttributes(false); } /** * Load the NBT list from the TAG compound. * @param createIfMissing - create the list if its missing. */ private void loadAttributes(boolean createIfMissing) { if (this.attributes == null) { NbtCompound nbt = NbtFactory.fromItemTag(this.stack); this.attributes = nbt.getList("AttributeModifiers", createIfMissing); } } /** * Remove the NBT list from the TAG compound. */ private void removeAttributes() { NbtCompound nbt = NbtFactory.fromItemTag(this.stack); nbt.remove("AttributeModifiers"); this.attributes = null; } /** * Retrieve the modified item stack. * @return The modified item stack. */ public ItemStack getStack() { return stack; } /** * Retrieve the number of attributes. * @return Number of attributes. */ public int size() { return attributes != null ? attributes.size() : 0; } /** * Add a new attribute to the list. * @param attribute - the new attribute. */ public void add(Attribute attribute) { Preconditions.checkNotNull(attribute.getName(), "must specify an attribute name."); loadAttributes(true); attributes.add(attribute.data); } /** * Remove the first instance of the given attribute. * <p> * The attribute will be removed using its UUID. * @param attribute - the attribute to remove. * @return TRUE if the attribute was removed, FALSE otherwise. */ public boolean remove(Attribute attribute) { if (attributes == null) return false; UUID uuid = attribute.getUUID(); for (Iterator<Attribute> it = values().iterator(); it.hasNext(); ) { if (Objects.equal(it.next().getUUID(), uuid)) { it.remove(); // Last removed attribute? if (size() == 0) { removeAttributes(); } return true; } } return false; } /** * Remove every attribute. */ public void clear() { removeAttributes(); } /** * Retrieve the attribute at a given index. * @param index - the index to look up. * @return The attribute at that index. */ public Attribute get(int index) { if (size() == 0) throw new IllegalStateException("Attribute list is empty."); return new Attribute((NbtCompound) attributes.get(index)); } // We can't make Attributes itself iterable without splitting it up into separate classes public Iterable<Attribute> values() { return new Iterable<Attribute>() { @Override public Iterator<Attribute> iterator() { // Handle the empty case if (size() == 0) return Collections.<Attribute>emptyList().iterator(); return Iterators.transform(attributes.iterator(), new Function<Object, Attribute>() { @Override public Attribute apply(/*@Null*/ Object element) { return new Attribute((NbtCompound) element); } }); } }; } }
Tommsy64/Satchels
src/main/java/io/github/tommsy64/satchels/item/storage/Attributes.java
Java
gpl-3.0
11,745
/** * Created by claudio on 17/01/17. */ "use strict"; let bcrypt = require('bcrypt-nodejs'); let bookshelf = require('../bookshelf'); bookshelf.plugin('registry'); let Game = bookshelf.Model.extend({ tableName: 'games', hasTimestamps: true, //manage in automatic way created_at and updated_at hidden: ['json_designers'], //hide from json deserialized plays() { return this.hasMany('Play', 'game_id'); }, virtuals: { //serialize/deserialize designers //mutators should be used, but I haven't found how to use them with bookshelf designers: { get () { try { var data = this.get('json_designers'); try { return JSON.parse(data); }catch(e){ return data; } }catch(e2){ throw e2; } }, set: function(value) { try { this.set('json_designers', JSON.stringify(value)); }catch (e) { throw e; } } }, links: function() { return { 'self': '/games/' + this.get('id'), }; } }, }); module.exports = bookshelf.model('Game', Game);
middleware2016/board-rest
models/Game.js
JavaScript
gpl-3.0
1,395
var path = require('path'); var fs = require('fs'); module.exports = function(req, res, next){ var translationVars = [ "fillOutYourGuide", "howIdidIt", "wasThisYourFirstJobInSweden", "yes", "no", "whatKindOfJobIsIt", "whatEducationDidYouHave", "path", "descriptionPreferablyShort", "submitButtonText", "whatOccupationHaveYouHad", "firstJobLabel", "educationLabel", "jobLabel", "voteUpLabel", "voteDownLabel", "flagLabel", "translateLabel", "titleLabel", "prevOccupationLabel", "logInLabel", "logOutLabel", "createAccountLabel", "usernameLabel", "passwordLabel", "emailLabel", "confirmPasswordLabel", "yourGuideLabel", "search", "guidesLabel" ] ; var lang = req.cookies.lang; var filepath = path.join(__dirname, '../lang/' + lang + '.json'); fs.readFile(filepath, function(err , data){ fs.readFile(path.join(__dirname, '../lang/en.json'), function(errEn, dataEn){ var enLang = JSON.parse( dataEn ); //begin var langObj; if(err){ console.log("Language file for language " + lang + " not found! Falling back to english."); filepath = path.join(__dirname, '../lang/en.json'); fs.readFile(filepath, function(err, data ){ langObj = JSON.parse(data); }); }else{ langObj = JSON.parse(data); } var fullyTranslated = true; console.log("English fallback: " + enLang ) ; for(var i = 0; i < translationVars.length; i++){ if(!langObj[translationVars[i]]){ fullyTranslated = false; console.log("enLang: " + enLang[translationVars[i]] + " translationVars[i] " + translationVars[i]); langObj[translationVars[i]] = enLang[translationVars[i]]; console.log("Field " + translationVars[i] + " is not defined for language " + lang + " ! It was replaced by " + langObj[translationVars[i]]); } } //if(!fullyTranslated){ //console.log("Language file for language " + lang + " is not fully translated! Falling back to English."); //filepath = path.join(__dirname, '../lang/en.json'); //fs.readFile(filepath, function(err, data ){ //langObj = JSON.parse(data); //req.langObj = langObj; //next(); //}); //} //else{ req.langObj = langObj; next(); //} //end }); }); };
Perpetual-Projects/OpenHack-JustArrived
util/getLang.js
JavaScript
gpl-3.0
2,869
<!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/xhtml;charset=UTF-8"/> <title>png++: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <!-- Generated by Doxygen 1.7.4 --> <div id="top"> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">png++&#160;<span id="projectnumber">0.2.1</span></div> </td> </tr> </tbody> </table> </div> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacepng.html">png</a> </li> <li class="navelem"><a class="el" href="classpng_1_1info.html">info</a> </li> </ul> </div> </div> <div class="header"> <div class="headertitle"> <div class="title">png::info Member List</div> </div> </div> <div class="contents"> This is the complete list of members for <a class="el" href="classpng_1_1info.html">png::info</a>, including all inherited members.<table> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a254c2504eba5a409b23017b2a6f5427e">drop_palette</a>()</td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#aa299bb6730c4b68883d7683699dfd035">get_bit_depth</a>() const </td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a8b8b0e44c44d2071d70c8606c0390854">get_color_type</a>() const </td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#ae8f5870c3fd31cc3f0cb158c2a20bbcd">get_compression_type</a>() const </td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a71305d6b01e0c58838144b01d10bbb14">get_filter_type</a>() const </td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a640f6451351d62920fa2786dea53cd4d">get_height</a>() const </td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#ac43327884ca1d053002cb3ba3ef24188">get_interlace_type</a>() const </td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a3577210685e93050122d4974fc1c390a">get_palette</a>() const </td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#ae48397a02ae6ddaf87aa95d8c513ec23">get_palette</a>()</td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1info__base.html#a030a8262a2ef1bf8c97a2eafe71c2f3c">get_png_info</a>() const </td><td><a class="el" href="classpng_1_1info__base.html">png::info_base</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1info__base.html#afe70c0d333349a9b5fc7a1d046fc3fbc">get_png_info_ptr</a>()</td><td><a class="el" href="classpng_1_1info__base.html">png::info_base</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a9dfd2ebd5421d27c1ed839262e995650">get_tRNS</a>() const </td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a1b5f16559a9ad9108681b92b6529a113">get_tRNS</a>()</td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#ac13df5daaabb2219cf1d52c95b1f98c7">get_width</a>() const </td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#aa929b11e8c237865f7a4c9acd0ea61cf">image_info</a>()</td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1info.html#a6de7c51766261018632d21405e3a2563">info</a>(io_base &amp;io, png_struct *png)</td><td><a class="el" href="classpng_1_1info.html">png::info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1info__base.html#a2faea4c556a6e5ad70dec4dc27a06a5f">info_base</a>(io_base &amp;io, png_struct *png)</td><td><a class="el" href="classpng_1_1info__base.html">png::info_base</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a09d04b19ad511e5f4249e9dfa0e62efa">m_bit_depth</a></td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a196348cce026bf93062a80eff78958e7">m_color_type</a></td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#aace206556a5c185a86542702b72a45dc">m_compression_type</a></td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#aaa7afab91bfab66e0daa966695d40967">m_filter_type</a></td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#ad36dc08da3efe4e26322e3c8eb55adfc">m_height</a></td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1info__base.html#a55a07d9e2ff9660850e5a1c9156e076a">m_info</a></td><td><a class="el" href="classpng_1_1info__base.html">png::info_base</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a988c3d5bfead5238afa04a1061e0f04a">m_interlace_type</a></td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1info__base.html#a8911199becf531b509203656c4392e64">m_io</a></td><td><a class="el" href="classpng_1_1info__base.html">png::info_base</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a1fb1b97e0f153d8203aa79d667b488c8">m_palette</a></td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1info__base.html#ab2052faecb79f17e2b0bb697e0cbbb46">m_png</a></td><td><a class="el" href="classpng_1_1info__base.html">png::info_base</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#ae16512ad01beea645e75e0edd60f0720">m_tRNS</a></td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a4acee97cd5ab36c631099e788ffdf08c">m_width</a></td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1info.html#a8788080158fc7450911516c23d4b584c">read</a>()</td><td><a class="el" href="classpng_1_1info.html">png::info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a1f1cf6197f7d0241d7410916076a6c08">set_bit_depth</a>(size_t bit_depth)</td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a2eb5d253e70b620a1050affd316dfb78">set_color_type</a>(color_type color_space)</td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a5a645e38fe10f80ced96301cdb0dec74">set_compression_type</a>(compression_type compression)</td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a886e48b7371f2768acb9fc9768d57366">set_filter_type</a>(filter_type filter)</td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a6ccb5704bf7f715572a6129bf3009761">set_height</a>(size_t height)</td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a19a24d29c7f47223a8df1164c093361c">set_interlace_type</a>(interlace_type interlace)</td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#acfc3675399a946f411d2a6e0054401f4">set_palette</a>(palette const &amp;plte)</td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a939bed5115330604e67950dc63b555e3">set_tRNS</a>(tRNS const &amp;trns)</td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1image__info.html#a3d23fc1552357d39fe4d8d017b9bea0a">set_width</a>(size_t width)</td><td><a class="el" href="classpng_1_1image__info.html">png::image_info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1info.html#a76309c30eb25d8242ae039a2e80bb1d3">sync_ihdr</a>(void) const </td><td><a class="el" href="classpng_1_1info.html">png::info</a></td><td><code> [inline, protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1info.html#a544c5e25c4211ef33976e3ac2b2ea020">update</a>()</td><td><a class="el" href="classpng_1_1info.html">png::info</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classpng_1_1info.html#a863333fbef670b244920022d1a0ee210">write</a>() const </td><td><a class="el" href="classpng_1_1info.html">png::info</a></td><td><code> [inline]</code></td></tr> </table></div> <hr class="footer"/><address class="footer"><small>Generated on Thu Apr 21 2011 22:55:13 for png++ by&#160; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.4 </small></address> </body> </html>
Nvveen/First-Sight
lib/png++/doc/html/classpng_1_1info-members.html
HTML
gpl-3.0
12,763
# wp-tyler-theme Building a wordpress theme for my friends engagement.They grow up so fast!!!!!!
rotohun/wp-tyler-theme
README.md
Markdown
gpl-3.0
97
#!/bin/bash set -x set -e rm -rf splicing_event/* awk '$3 !~ /_/' \ transcriptome_raw/hg38_refGene.hgtable > \ splicing_event/refGene.txt TIME=splicing_event/time_usage.csv /usr/bin/time -f "%C\nNatural time:\t%e\nCPU time:\t%U+%S\nMemory peak:\t%M\n" -o ${TIME} -a \ python ~/utility/bioinfo/rnaseqlib-clip/rnaseqlib/gff/gff_make_annotation.py \ splicing_event/ \ splicing_event/gff \ --flanking-rule commonshortest \ --genome-label hg38
JY-Zhou/FreePSI
data_RefSeq_hg38/annotation/run_splicingAnnotation.sh
Shell
gpl-3.0
472
<!-- ~ Copyright © 2011-2014 EPAM Systems/B2BITS® (http://www.b2bits.com). ~ ~ This file is part of STAFF. ~ ~ STAFF 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. ~ ~ STAFF 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 STAFF. If not, see <http://www.gnu.org/licenses/>. --> <html> <head> <title>tcpSimpleSend(deprecated)</title> <link href="../stylesheet.css" rel="stylesheet" type="text/css"> </head> <body class="verd"> <h1>tcpSimpleSend(deprecated)</h1> <h2>Description</h2> <p>tcpSimpleSend task sends portions of data from the file to the TCP session.</p> <h2>Parameters</h2> <table border="1"> <tr> <td><b>Attribute</b></td> <td><b>Description</b></td> <td><b>Default</b></td> <td><b>Required</b></td> </tr> <tr> <td>refid</td> <td>Reference name of the TCP session to receive messages from.</td> <td>None</td> <td>Yes</td> </tr> <tr> <td>file</td> <td>File containing data to be sent.</td> <td>None</td> <td>Yes</td> </tr> <tr> <td>delimiter</td> <td>Regular expression for the delimiter between portions of data in the file. Each portion will be sent separately.</td> <td>'\n'</td> <td>No</td> </tr> <tr> <td>repeatDelay</td> <td>Delay between two sends.</td> <td>0</td> <td>No</td> </tr> </table> <h2>Examples</h2> <pre> &lt;tcpSimpleSend refid="TCPSimpleClient" file="batches/tcp_fix_logon.txt" delimeter="\n" repeatDelay="0.5"/&gt; </pre> </body> </html>
fix-protocol-tools/STAFF
staff-distribution/src/main/doc/user_manual/user_manual_files/tcpSimple/tcpSimpleSend_task.html
HTML
gpl-3.0
2,045
#region License Information (GPL v3) /* ShareX - A program that allows you to take screenshots and share any file type Copyright (c) 2007-2019 ShareX Team 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. Optionally you can also view the license at <http://www.gnu.org/licenses/>. */ #endregion License Information (GPL v3) using ShareX.HelpersLib; using System.Drawing; namespace ShareX { public class CaptureActiveMonitor : CaptureBase { protected override ImageInfo Execute(TaskSettings taskSettings) { Rectangle rect = CaptureHelpers.GetActiveScreenWorkingArea(); ImageInfo imageInfo = CreateImageInfo(rect); imageInfo.Image = TaskHelpers.GetScreenshot(taskSettings).CaptureActiveMonitor(); return imageInfo; } } }
campbeb/ShareX
ShareX/CaptureHelpers/CaptureActiveMonitor.cs
C#
gpl-3.0
1,499
<?php // Heading $_['heading_title'] = '言語編集'; // Text $_['text_success'] = 'Success: You have modified language editor!'; $_['text_edit'] = 'Edit Translation'; $_['text_default'] = 'Default'; $_['text_store'] = 'Store'; $_['text_language'] = '言語'; $_['text_translation'] = 'Choose a translation'; $_['text_translation'] = 'Translations'; // Entry $_['entry_key'] = 'Key'; $_['entry_value'] = 'Value'; $_['entry_default'] = 'Default'; // Error $_['error_permission'] = 'Warning: You do not have permission to modify language editor!';
chaoyueLin/html
admin/language/japan/design/language.php
PHP
gpl-3.0
591
import Config from 'shared/Configuration' import configureMockStore from 'redux-mock-store' import nock from 'nock' import thunk from 'redux-thunk' import { REQUEST_EMAIL_SUBSCRIPTION, RECEIVE_EMAIL_SUBSCRIPTION, REQUEST_EMAIL_SUBSCRIPTION_UPDATE, RECEIVE_EMAIL_SUBSCRIPTION_UPDATE, REQUEST_EMAIL_SUBSCRIPTION_DELETE, RECEIVE_EMAIL_SUBSCRIPTION_DELETE, fetchSubscription, putSubscription, deleteSubscription, verifySubscription, } from 'actions/email' import * as statuses from 'constants/APIStatuses' const middlewares = [ thunk ] const mockStore = configureMockStore(middlewares) let store const emailAddress = 'test@me.place' const subscriptionType = 'events' const responseData = { audience: ['test', 'test2'], type: 'all events', } describe('email async action creator', () => { beforeEach(() => { store = mockStore() nock(Config.userPrefsAPI) .defaultReplyHeaders({ 'Access-Control-Allow-Origin': '*', "Access-Control-Allow-Headers": "Authorization", "Content-Type": "application:json", }) .intercept(() => true, 'OPTIONS') .reply(204, null) .persist() }) afterEach(() => { nock.cleanAll() store = undefined }) describe('fetchSubscription', () => { describe('on success', () => { beforeEach(() => { nock(`${Config.userPrefsAPI}/emailSubscription/${subscriptionType}`) .defaultReplyHeaders({'Access-Control-Allow-Origin': '*'}) .get(() => true) .query(true) .reply(200, responseData) }) it('should create REQUEST_EMAIL_SUBSCRIPTION and RECEIVE_EMAIL_SUBSCRIPTION actions', async () => { const result = await store.dispatch(fetchSubscription(subscriptionType, emailAddress)) expect(store.getActions()).toContainEqual(expect.objectContaining({ type: REQUEST_EMAIL_SUBSCRIPTION, })) expect(result).toMatchObject({ type: RECEIVE_EMAIL_SUBSCRIPTION, status: statuses.SUCCESS, data: responseData, }) }) }) describe('on error', () => { beforeEach(() => { nock(`${Config.userPrefsAPI}/emailSubscription/${subscriptionType}`) .defaultReplyHeaders({'Access-Control-Allow-Origin': '*'}) .get(() => true) .query(true) .reply(500) }) it('should create REQUEST_EMAIL_SUBSCRIPTION and RECEIVE_EMAIL_SUBSCRIPTION actions', async () => { const result = await store.dispatch(fetchSubscription(subscriptionType, emailAddress)) expect(store.getActions()).toContainEqual(expect.objectContaining({ type: REQUEST_EMAIL_SUBSCRIPTION, })) expect(result).toMatchObject({ type: RECEIVE_EMAIL_SUBSCRIPTION, status: statuses.ERROR, }) }) }) describe('throw error', () => { beforeEach(() => { console.error = jest.fn() nock(`${Config.userPrefsAPI}/emailSubscription/${subscriptionType}`) .defaultReplyHeaders({'Access-Control-Allow-Origin': '*'}) .get(() => true) .query(true) .replyWithError('ERROR') }) it('should create REQUEST_EMAIL_SUBSCRIPTION and RECEIVE_EMAIL_SUBSCRIPTION actions', async () => { const result = await store.dispatch(fetchSubscription(subscriptionType, emailAddress)) expect(store.getActions()).toContainEqual(expect.objectContaining({ type: REQUEST_EMAIL_SUBSCRIPTION, })) expect(result).toMatchObject({ type: RECEIVE_EMAIL_SUBSCRIPTION, status: statuses.ERROR, }) }) }) }) describe('putSubscription', () => { describe('on success', () => { beforeEach(() => { nock(`${Config.userPrefsAPI}/emailSubscription/${subscriptionType}`) .defaultReplyHeaders({'Access-Control-Allow-Origin': '*'}) .put(() => true) .query(true) .reply(200, responseData) }) it('should create REQUEST_EMAIL_SUBSCRIPTION_UPDATE and RECEIVE_EMAIL_SUBSCRIPTION_UPDATE actions', async () => { const result = await store.dispatch(putSubscription(subscriptionType, emailAddress, responseData)) expect(store.getActions()).toContainEqual(expect.objectContaining({ type: REQUEST_EMAIL_SUBSCRIPTION_UPDATE, })) expect(result).toMatchObject({ type: RECEIVE_EMAIL_SUBSCRIPTION_UPDATE, status: statuses.SUCCESS, data: responseData, }) }) }) describe('on error', () => { beforeEach(() => { nock(`${Config.userPrefsAPI}/emailSubscription/${subscriptionType}`) .defaultReplyHeaders({'Access-Control-Allow-Origin': '*'}) .put(() => true) .query(true) .reply(500) }) it('should create REQUEST_EMAIL_SUBSCRIPTION_UPDATE and RECEIVE_EMAIL_SUBSCRIPTION_UPDATE actions', async () => { const result = await store.dispatch(putSubscription(subscriptionType, emailAddress, responseData)) expect(store.getActions()).toContainEqual(expect.objectContaining({ type: REQUEST_EMAIL_SUBSCRIPTION_UPDATE, })) expect(result).toMatchObject({ type: RECEIVE_EMAIL_SUBSCRIPTION_UPDATE, status: statuses.ERROR, }) }) }) describe('throw error', () => { beforeEach(() => { console.error = jest.fn() nock(`${Config.userPrefsAPI}/emailSubscription/${subscriptionType}`) .defaultReplyHeaders({'Access-Control-Allow-Origin': '*'}) .put(() => true) .query(true) .replyWithError('ERROR') }) it('should create REQUEST_EMAIL_SUBSCRIPTION_UPDATE and RECEIVE_EMAIL_SUBSCRIPTION_UPDATE actions', async () => { const result = await store.dispatch(putSubscription(subscriptionType, emailAddress, responseData)) expect(store.getActions()).toContainEqual(expect.objectContaining({ type: REQUEST_EMAIL_SUBSCRIPTION_UPDATE, })) expect(result).toMatchObject({ type: RECEIVE_EMAIL_SUBSCRIPTION_UPDATE, status: statuses.ERROR, }) }) }) }) describe('deleteSubscription', () => { describe('on success', () => { beforeEach(() => { nock(`${Config.userPrefsAPI}/emailSubscription/${subscriptionType}`) .defaultReplyHeaders({'Access-Control-Allow-Origin': '*'}) .delete(() => true) .query(true) .reply(200, responseData) }) it('should create REQUEST_EMAIL_SUBSCRIPTION_DELETE and RECEIVE_EMAIL_SUBSCRIPTION_DELETE actions', async () => { const result = await store.dispatch(deleteSubscription(subscriptionType, emailAddress, responseData)) expect(store.getActions()).toContainEqual(expect.objectContaining({ type: REQUEST_EMAIL_SUBSCRIPTION_DELETE, })) expect(result).toMatchObject({ type: RECEIVE_EMAIL_SUBSCRIPTION_DELETE, status: statuses.SUCCESS, }) }) }) describe('on error', () => { beforeEach(() => { nock(`${Config.userPrefsAPI}/emailSubscription/${subscriptionType}`) .defaultReplyHeaders({'Access-Control-Allow-Origin': '*'}) .delete(() => true) .query(true) .reply(500) }) it('should create REQUEST_EMAIL_SUBSCRIPTION_DELETE and RECEIVE_EMAIL_SUBSCRIPTION_DELETE actions', async () => { const result = await store.dispatch(deleteSubscription(subscriptionType, emailAddress, responseData)) expect(store.getActions()).toContainEqual(expect.objectContaining({ type: REQUEST_EMAIL_SUBSCRIPTION_DELETE, })) expect(result).toMatchObject({ type: RECEIVE_EMAIL_SUBSCRIPTION_DELETE, status: statuses.ERROR, }) }) }) describe('throw error', () => { beforeEach(() => { console.error = jest.fn() nock(`${Config.userPrefsAPI}/emailSubscription/${subscriptionType}`) .defaultReplyHeaders({'Access-Control-Allow-Origin': '*'}) .delete(() => true) .query(true) .replyWithError('ERROR') }) it('should create REQUEST_EMAIL_SUBSCRIPTION_DELETE and RECEIVE_EMAIL_SUBSCRIPTION_DELETE actions', async () => { const result = await store.dispatch(deleteSubscription(subscriptionType, emailAddress, responseData)) expect(store.getActions()).toContainEqual(expect.objectContaining({ type: REQUEST_EMAIL_SUBSCRIPTION_DELETE, })) expect(result).toMatchObject({ type: RECEIVE_EMAIL_SUBSCRIPTION_DELETE, status: statuses.ERROR, }) }) }) }) describe('verifySubscription', () => { describe('on success', () => { beforeEach(() => { nock(`${Config.userPrefsAPI}/emailSubscription/${subscriptionType}/confirm`) .defaultReplyHeaders({'Access-Control-Allow-Origin': '*'}) .post(() => true) .query(true) .reply(200, responseData) }) it('should create REQUEST_EMAIL_SUBSCRIPTION_UPDATE and RECEIVE_EMAIL_SUBSCRIPTION_UPDATE actions', async () => { const result = await store.dispatch(verifySubscription(subscriptionType, emailAddress, responseData)) expect(store.getActions()).toContainEqual(expect.objectContaining({ type: REQUEST_EMAIL_SUBSCRIPTION_UPDATE, })) expect(result).toMatchObject({ type: RECEIVE_EMAIL_SUBSCRIPTION_UPDATE, status: statuses.SUCCESS, }) }) }) describe('on error', () => { beforeEach(() => { nock(`${Config.userPrefsAPI}/emailSubscription/${subscriptionType}/confirm`) .defaultReplyHeaders({'Access-Control-Allow-Origin': '*'}) .post(() => true) .query(true) .reply(500) }) it('should create REQUEST_EMAIL_SUBSCRIPTION_UPDATE and RECEIVE_EMAIL_SUBSCRIPTION_UPDATE actions', async () => { const result = await store.dispatch(verifySubscription(subscriptionType, emailAddress, responseData)) expect(store.getActions()).toContainEqual(expect.objectContaining({ type: REQUEST_EMAIL_SUBSCRIPTION_UPDATE, })) expect(result).toMatchObject({ type: RECEIVE_EMAIL_SUBSCRIPTION_UPDATE, status: statuses.ERROR, }) }) }) describe('throw error', () => { beforeEach(() => { console.error = jest.fn() nock(`${Config.userPrefsAPI}/emailSubscription/${subscriptionType}/confirm`) .defaultReplyHeaders({'Access-Control-Allow-Origin': '*'}) .post(() => true) .query(true) .replyWithError('ERROR') }) it('should create REQUEST_EMAIL_SUBSCRIPTION_UPDATE and RECEIVE_EMAIL_SUBSCRIPTION_UPDATE actions', async () => { const result = await store.dispatch(verifySubscription(subscriptionType, emailAddress, responseData)) expect(store.getActions()).toContainEqual(expect.objectContaining({ type: REQUEST_EMAIL_SUBSCRIPTION_UPDATE, })) expect(result).toMatchObject({ type: RECEIVE_EMAIL_SUBSCRIPTION_UPDATE, status: statuses.ERROR, }) }) }) }) })
ndlib/usurper
src/tests/actions/email.test.js
JavaScript
gpl-3.0
11,322
<TABLE BORDER CELLSPACING=0 WIDTH='100%'> <xtag-section name="ParStatistics"> <TR ALIGN=CENTER BGCOLOR='#99CCFF'><TD COLSPAN=1><B>Par Statistics</B></TD></TR> <TR><TD><xtag-par-property-name>Total Non-vccgnd Signals</xtag-par-property-name>=<xtag-par-property-value>115</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>Total Non-vccgnd Design Pins</xtag-par-property-name>=<xtag-par-property-value>257</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>Total Non-vccgnd Conns</xtag-par-property-name>=<xtag-par-property-value>257</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>Total Non-vccgnd Timing Constrained Conns</xtag-par-property-name>=<xtag-par-property-value>101</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>Phase 1 CPU</xtag-par-property-name>=<xtag-par-property-value>115.8 sec</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>Phase 2 CPU</xtag-par-property-name>=<xtag-par-property-value>117.3 sec</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>Phase 3 CPU</xtag-par-property-name>=<xtag-par-property-value>119.0 sec</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>Phase 4 CPU</xtag-par-property-name>=<xtag-par-property-value>149.7 sec</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>Phase 5 CPU</xtag-par-property-name>=<xtag-par-property-value>150.8 sec</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>Phase 6 CPU</xtag-par-property-name>=<xtag-par-property-value>150.8 sec</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>Phase 7 CPU</xtag-par-property-name>=<xtag-par-property-value>150.8 sec</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>Phase 8 CPU</xtag-par-property-name>=<xtag-par-property-value>150.8 sec</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>Phase 9 CPU</xtag-par-property-name>=<xtag-par-property-value>151.1 sec</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>AvgWirelenPerPin Fanout 1</xtag-par-property-name>=<xtag-par-property-value>2.0</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>AvgWirelenPerPin Fanout 2</xtag-par-property-name>=<xtag-par-property-value>1.0</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>AvgWirelenPerPin Fanout 3</xtag-par-property-name>=<xtag-par-property-value>11.0</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>AvgWirelenPerPin Fanout 4</xtag-par-property-name>=<xtag-par-property-value>0.2</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>AvgWirelenPerPin Fanout 10</xtag-par-property-name>=<xtag-par-property-value>4.6</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>AvgWirelenPerPin Fanout 50</xtag-par-property-name>=<xtag-par-property-value>8.8</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>AvgWirelenPerPin Fanout 100</xtag-par-property-name>=<xtag-par-property-value>0.0</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>AvgWirelenPerPin Fanout 500</xtag-par-property-name>=<xtag-par-property-value>0.0</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>AvgWirelenPerPin Fanout 5000</xtag-par-property-name>=<xtag-par-property-value>0.0</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>AvgWirelenPerPin Fanout 20000</xtag-par-property-name>=<xtag-par-property-value>0.0</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>AvgWirelenPerPin Fanout 50000</xtag-par-property-name>=<xtag-par-property-value>0.0</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>AvgWirelenPerPin Fanout 100000</xtag-par-property-name>=<xtag-par-property-value>0.0</xtag-par-property-value></TD></TR> <TR><TD><xtag-par-property-name>IRR Gamma</xtag-par-property-name>=<xtag-par-property-value>1.0010</xtag-par-property-value></TD></TR> </xtag-section> </TABLE>
Fabeltranm/FPGA-Game-D1
HW/RTL/06PCM-AUDIO-MICROFONO/Version_01/02 verilog/Otros/Prueba5/build/par_usage_statistics.html
HTML
gpl-3.0
3,985
/* Tags file maker to go with GNU Emacs -*- coding: utf-8 -*- Copyright (C) 1984 The Regents of the University of California 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 the University 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 REGENTS 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 REGENTS 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. Copyright (C) 1984, 1987-1989, 1993-1995, 1998-2017 Free Software Foundation, Inc. This file is not considered part of GNU Emacs. 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/>. */ /* NB To comply with the above BSD license, copyright information is reproduced in etc/ETAGS.README. That file should be updated when the above notices are. To the best of our knowledge, this code was originally based on the ctags.c distributed with BSD4.2, which was copyrighted by the University of California, as described above. */ /* * Authors: * 1983 Ctags originally by Ken Arnold. * 1984 Fortran added by Jim Kleckner. * 1984 Ed Pelegri-Llopart added C typedefs. * 1985 Emacs TAGS format by Richard Stallman. * 1989 Sam Kendall added C++. * 1992 Joseph B. Wells improved C and C++ parsing. * 1993 Francesco Potortì reorganized C and C++. * 1994 Line-by-line regexp tags by Tom Tromey. * 2001 Nested classes by Francesco Potortì (concept by Mykola Dzyuba). * 2002 #line directives by Francesco Potortì. * Francesco Potortì maintained and improved it for many years starting in 1993. */ /* * If you want to add support for a new language, start by looking at the LUA * language, which is the simplest. Alternatively, consider distributing etags * together with a configuration file containing regexp definitions for etags. */ char pot_etags_version[] = "@(#) pot revision number is 17.38.1.4"; #ifdef DEBUG # undef DEBUG # define DEBUG true #else # define DEBUG false # define NDEBUG /* disable assert */ #endif #include <config.h> /* WIN32_NATIVE is for XEmacs. WINDOWSNT, DOS_NT are for Emacs. */ #ifdef WIN32_NATIVE # undef WINDOWSNT # define WINDOWSNT #endif /* WIN32_NATIVE */ #ifdef WINDOWSNT # include <direct.h> # undef HAVE_NTGUI # undef DOS_NT # define DOS_NT /* The WINDOWSNT build doesn't use Gnulib's fcntl.h. */ # define O_CLOEXEC O_NOINHERIT #endif /* WINDOWSNT */ #include <limits.h> #include <unistd.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <sysstdio.h> #include <errno.h> #include <fcntl.h> #include <binary-io.h> #include <unlocked-io.h> #include <c-ctype.h> #include <c-strcase.h> #include <assert.h> #ifdef NDEBUG # undef assert /* some systems have a buggy assert.h */ # define assert(x) ((void) 0) #endif #include <getopt.h> #include <regex.h> #include "remacs-lib.h" /* Define CTAGS to make the program "ctags" compatible with the usual one. Leave it undefined to make the program "etags", which makes emacs-style tag tables and tags typedefs, #defines and struct/union/enum by default. */ #ifdef CTAGS # undef CTAGS # define CTAGS true #else # define CTAGS false #endif static bool streq (char const *s, char const *t) { return strcmp (s, t) == 0; } static bool strcaseeq (char const *s, char const *t) { return c_strcasecmp (s, t) == 0; } static bool strneq (char const *s, char const *t, size_t n) { return strncmp (s, t, n) == 0; } static bool strncaseeq (char const *s, char const *t, size_t n) { return c_strncasecmp (s, t, n) == 0; } /* C is not in a name. */ static bool notinname (unsigned char c) { /* Look at make_tag before modifying! */ static bool const table[UCHAR_MAX + 1] = { ['\0']=1, ['\t']=1, ['\n']=1, ['\f']=1, ['\r']=1, [' ']=1, ['(']=1, [')']=1, [',']=1, [';']=1, ['=']=1 }; return table[c]; } /* C can start a token. */ static bool begtoken (unsigned char c) { static bool const table[UCHAR_MAX + 1] = { ['$']=1, ['@']=1, ['A']=1, ['B']=1, ['C']=1, ['D']=1, ['E']=1, ['F']=1, ['G']=1, ['H']=1, ['I']=1, ['J']=1, ['K']=1, ['L']=1, ['M']=1, ['N']=1, ['O']=1, ['P']=1, ['Q']=1, ['R']=1, ['S']=1, ['T']=1, ['U']=1, ['V']=1, ['W']=1, ['X']=1, ['Y']=1, ['Z']=1, ['_']=1, ['a']=1, ['b']=1, ['c']=1, ['d']=1, ['e']=1, ['f']=1, ['g']=1, ['h']=1, ['i']=1, ['j']=1, ['k']=1, ['l']=1, ['m']=1, ['n']=1, ['o']=1, ['p']=1, ['q']=1, ['r']=1, ['s']=1, ['t']=1, ['u']=1, ['v']=1, ['w']=1, ['x']=1, ['y']=1, ['z']=1, ['~']=1 }; return table[c]; } /* C can be in the middle of a token. */ static bool intoken (unsigned char c) { static bool const table[UCHAR_MAX + 1] = { ['$']=1, ['0']=1, ['1']=1, ['2']=1, ['3']=1, ['4']=1, ['5']=1, ['6']=1, ['7']=1, ['8']=1, ['9']=1, ['A']=1, ['B']=1, ['C']=1, ['D']=1, ['E']=1, ['F']=1, ['G']=1, ['H']=1, ['I']=1, ['J']=1, ['K']=1, ['L']=1, ['M']=1, ['N']=1, ['O']=1, ['P']=1, ['Q']=1, ['R']=1, ['S']=1, ['T']=1, ['U']=1, ['V']=1, ['W']=1, ['X']=1, ['Y']=1, ['Z']=1, ['_']=1, ['a']=1, ['b']=1, ['c']=1, ['d']=1, ['e']=1, ['f']=1, ['g']=1, ['h']=1, ['i']=1, ['j']=1, ['k']=1, ['l']=1, ['m']=1, ['n']=1, ['o']=1, ['p']=1, ['q']=1, ['r']=1, ['s']=1, ['t']=1, ['u']=1, ['v']=1, ['w']=1, ['x']=1, ['y']=1, ['z']=1 }; return table[c]; } /* C can end a token. */ static bool endtoken (unsigned char c) { static bool const table[UCHAR_MAX + 1] = { ['\0']=1, ['\t']=1, ['\n']=1, ['\r']=1, [' ']=1, ['!']=1, ['"']=1, ['#']=1, ['%']=1, ['&']=1, ['\'']=1, ['(']=1, [')']=1, ['*']=1, ['+']=1, [',']=1, ['-']=1, ['.']=1, ['/']=1, [':']=1, [';']=1, ['<']=1, ['=']=1, ['>']=1, ['?']=1, ['[']=1, [']']=1, ['^']=1, ['{']=1, ['|']=1, ['}']=1, ['~']=1 }; return table[c]; } /* * xnew, xrnew -- allocate, reallocate storage * * SYNOPSIS: Type *xnew (int n, Type); * void xrnew (OldPointer, int n, Type); */ #define xnew(n, Type) ((Type *) xmalloc ((n) * sizeof (Type))) #define xrnew(op, n, Type) ((op) = (Type *) xrealloc (op, (n) * sizeof (Type))) typedef void Lang_function (FILE *); typedef struct { const char *suffix; /* file name suffix for this compressor */ const char *command; /* takes one arg and decompresses to stdout */ } compressor; typedef struct { const char *name; /* language name */ const char *help; /* detailed help for the language */ Lang_function *function; /* parse function */ const char **suffixes; /* name suffixes of this language's files */ const char **filenames; /* names of this language's files */ const char **interpreters; /* interpreters for this language */ bool metasource; /* source used to generate other sources */ } language; typedef struct fdesc { struct fdesc *next; /* for the linked list */ char *infname; /* uncompressed input file name */ char *infabsname; /* absolute uncompressed input file name */ char *infabsdir; /* absolute dir of input file */ char *taggedfname; /* file name to write in tagfile */ language *lang; /* language of file */ char *prop; /* file properties to write in tagfile */ bool usecharno; /* etags tags shall contain char number */ bool written; /* entry written in the tags file */ } fdesc; typedef struct node_st { /* sorting structure */ struct node_st *left, *right; /* left and right sons */ fdesc *fdp; /* description of file to whom tag belongs */ char *name; /* tag name */ char *regex; /* search regexp */ bool valid; /* write this tag on the tag file */ bool is_func; /* function tag: use regexp in CTAGS mode */ bool been_warned; /* warning already given for duplicated tag */ int lno; /* line number tag is on */ long cno; /* character number line starts on */ } node; /* * A `linebuffer' is a structure which holds a line of text. * `readline_internal' reads a line from a stream into a linebuffer * and works regardless of the length of the line. * SIZE is the size of BUFFER, LEN is the length of the string in * BUFFER after readline reads it. */ typedef struct { long size; int len; char *buffer; } linebuffer; /* Used to support mixing of --lang and file names. */ typedef struct { enum { at_language, /* a language specification */ at_regexp, /* a regular expression */ at_filename, /* a file name */ at_stdin, /* read from stdin here */ at_end /* stop parsing the list */ } arg_type; /* argument type */ language *lang; /* language associated with the argument */ char *what; /* the argument itself */ } argument; /* Structure defining a regular expression. */ typedef struct regexp { struct regexp *p_next; /* pointer to next in list */ language *lang; /* if set, use only for this language */ char *pattern; /* the regexp pattern */ char *name; /* tag name */ struct re_pattern_buffer *pat; /* the compiled pattern */ struct re_registers regs; /* re registers */ bool error_signaled; /* already signaled for this regexp */ bool force_explicit_name; /* do not allow implicit tag name */ bool ignore_case; /* ignore case when matching */ bool multi_line; /* do a multi-line match on the whole file */ } regexp; /* Many compilers barf on this: Lang_function Ada_funcs; so let's write it this way */ static void Ada_funcs (FILE *); static void Asm_labels (FILE *); static void C_entries (int c_ext, FILE *); static void default_C_entries (FILE *); static void plain_C_entries (FILE *); static void Cjava_entries (FILE *); static void Cobol_paragraphs (FILE *); static void Cplusplus_entries (FILE *); static void Cstar_entries (FILE *); static void Erlang_functions (FILE *); static void Forth_words (FILE *); static void Fortran_functions (FILE *); static void Go_functions (FILE *); static void HTML_labels (FILE *); static void Lisp_functions (FILE *); static void Lua_functions (FILE *); static void Makefile_targets (FILE *); static void Pascal_functions (FILE *); static void Perl_functions (FILE *); static void PHP_functions (FILE *); static void PS_functions (FILE *); static void Prolog_functions (FILE *); static void Python_functions (FILE *); static void Ruby_functions (FILE *); static void Scheme_functions (FILE *); static void TeX_commands (FILE *); static void Texinfo_nodes (FILE *); static void Yacc_entries (FILE *); static void just_read_file (FILE *); static language *get_language_from_langname (const char *); static void readline (linebuffer *, FILE *); static long readline_internal (linebuffer *, FILE *, char const *); static bool nocase_tail (const char *); static void get_tag (char *, char **); static void get_lispy_tag (char *); static void analyze_regex (char *); static void free_regexps (void); static void regex_tag_multiline (void); static void error (const char *, ...) ATTRIBUTE_FORMAT_PRINTF (1, 2); static void verror (char const *, va_list) ATTRIBUTE_FORMAT_PRINTF (1, 0); static _Noreturn void suggest_asking_for_help (void); static _Noreturn void fatal (char const *, ...) ATTRIBUTE_FORMAT_PRINTF (1, 2); static _Noreturn void pfatal (const char *); static void add_node (node *, node **); static void process_file_name (char *, language *); static void process_file (FILE *, char *, language *); static void find_entries (FILE *); static void free_tree (node *); static void free_fdesc (fdesc *); static void pfnote (char *, bool, char *, int, int, long); static void invalidate_nodes (fdesc *, node **); static void put_entries (node *); static char *concat (const char *, const char *, const char *); static char *skip_spaces (char *); static char *skip_non_spaces (char *); static char *skip_name (char *); static char *savenstr (const char *, int); static char *savestr (const char *); static char *etags_getcwd (void); static char *relative_filename (char *, char *); static char *absolute_filename (char *, char *); static char *absolute_dirname (char *, char *); static bool filename_is_absolute (char *f); static void canonicalize_filename (char *); static char *etags_mktmp (void); static void linebuffer_init (linebuffer *); static void linebuffer_setlen (linebuffer *, int); static void *xmalloc (size_t); static void *xrealloc (void *, size_t); static char searchar = '/'; /* use /.../ searches */ static char *tagfile; /* output file */ static char *progname; /* name this program was invoked with */ static char *cwd; /* current working directory */ static char *tagfiledir; /* directory of tagfile */ static FILE *tagf; /* ioptr for tags file */ static ptrdiff_t whatlen_max; /* maximum length of any 'what' member */ static fdesc *fdhead; /* head of file description list */ static fdesc *curfdp; /* current file description */ static char *infilename; /* current input file name */ static int lineno; /* line number of current line */ static long charno; /* current character number */ static long linecharno; /* charno of start of current line */ static char *dbp; /* pointer to start of current tag */ static const int invalidcharno = -1; static node *nodehead; /* the head of the binary tree of tags */ static node *last_node; /* the last node created */ static linebuffer lb; /* the current line */ static linebuffer filebuf; /* a buffer containing the whole file */ static linebuffer token_name; /* a buffer containing a tag name */ static bool append_to_tagfile; /* -a: append to tags */ /* The next five default to true in C and derived languages. */ static bool typedefs; /* -t: create tags for C and Ada typedefs */ static bool typedefs_or_cplusplus; /* -T: create tags for C typedefs, level */ /* 0 struct/enum/union decls, and C++ */ /* member functions. */ static bool constantypedefs; /* -d: create tags for C #define, enum */ /* constants and variables. */ /* -D: opposite of -d. Default under ctags. */ static int globals; /* create tags for global variables */ static int members; /* create tags for C member variables */ static int declarations; /* --declarations: tag them and extern in C&Co*/ static int no_line_directive; /* ignore #line directives (undocumented) */ static int no_duplicates; /* no duplicate tags for ctags (undocumented) */ static bool update; /* -u: update tags */ static bool vgrind_style; /* -v: create vgrind style index output */ static bool no_warnings; /* -w: suppress warnings (undocumented) */ static bool cxref_style; /* -x: create cxref style output */ static bool cplusplus; /* .[hc] means C++, not C (undocumented) */ static bool ignoreindent; /* -I: ignore indentation in C */ static int packages_only; /* --packages-only: in Ada, only tag packages*/ static int class_qualify; /* -Q: produce class-qualified tags in C++/Java */ static int debug; /* --debug */ /* STDIN is defined in LynxOS system headers */ #ifdef STDIN # undef STDIN #endif #define STDIN 0x1001 /* returned by getopt_long on --parse-stdin */ static bool parsing_stdin; /* --parse-stdin used */ static regexp *p_head; /* list of all regexps */ static bool need_filebuf; /* some regexes are multi-line */ static struct option longopts[] = { { "append", no_argument, NULL, 'a' }, { "packages-only", no_argument, &packages_only, 1 }, { "c++", no_argument, NULL, 'C' }, { "debug", no_argument, &debug, 1 }, { "declarations", no_argument, &declarations, 1 }, { "no-line-directive", no_argument, &no_line_directive, 1 }, { "no-duplicates", no_argument, &no_duplicates, 1 }, { "help", no_argument, NULL, 'h' }, { "help", no_argument, NULL, 'H' }, { "ignore-indentation", no_argument, NULL, 'I' }, { "language", required_argument, NULL, 'l' }, { "members", no_argument, &members, 1 }, { "no-members", no_argument, &members, 0 }, { "output", required_argument, NULL, 'o' }, { "class-qualify", no_argument, &class_qualify, 'Q' }, { "regex", required_argument, NULL, 'r' }, { "no-regex", no_argument, NULL, 'R' }, { "ignore-case-regex", required_argument, NULL, 'c' }, { "parse-stdin", required_argument, NULL, STDIN }, { "version", no_argument, NULL, 'V' }, #if CTAGS /* Ctags options */ { "backward-search", no_argument, NULL, 'B' }, { "cxref", no_argument, NULL, 'x' }, { "defines", no_argument, NULL, 'd' }, { "globals", no_argument, &globals, 1 }, { "typedefs", no_argument, NULL, 't' }, { "typedefs-and-c++", no_argument, NULL, 'T' }, { "update", no_argument, NULL, 'u' }, { "vgrind", no_argument, NULL, 'v' }, { "no-warn", no_argument, NULL, 'w' }, #else /* Etags options */ { "no-defines", no_argument, NULL, 'D' }, { "no-globals", no_argument, &globals, 0 }, { "include", required_argument, NULL, 'i' }, #endif { NULL } }; static compressor compressors[] = { { "z", "gzip -d -c"}, { "Z", "gzip -d -c"}, { "gz", "gzip -d -c"}, { "GZ", "gzip -d -c"}, { "bz2", "bzip2 -d -c" }, { "xz", "xz -d -c" }, { NULL } }; /* * Language stuff. */ /* Ada code */ static const char *Ada_suffixes [] = { "ads", "adb", "ada", NULL }; static const char Ada_help [] = "In Ada code, functions, procedures, packages, tasks and types are\n\ tags. Use the '--packages-only' option to create tags for\n\ packages only.\n\ Ada tag names have suffixes indicating the type of entity:\n\ Entity type: Qualifier:\n\ ------------ ----------\n\ function /f\n\ procedure /p\n\ package spec /s\n\ package body /b\n\ type /t\n\ task /k\n\ Thus, 'M-x find-tag <RET> bidule/b <RET>' will go directly to the\n\ body of the package 'bidule', while 'M-x find-tag <RET> bidule <RET>'\n\ will just search for any tag 'bidule'."; /* Assembly code */ static const char *Asm_suffixes [] = { "a", /* Unix assembler */ "asm", /* Microcontroller assembly */ "def", /* BSO/Tasking definition includes */ "inc", /* Microcontroller include files */ "ins", /* Microcontroller include files */ "s", "sa", /* Unix assembler */ "S", /* cpp-processed Unix assembler */ "src", /* BSO/Tasking C compiler output */ NULL }; static const char Asm_help [] = "In assembler code, labels appearing at the beginning of a line,\n\ followed by a colon, are tags."; /* Note that .c and .h can be considered C++, if the --c++ flag was given, or if the `class' or `template' keywords are met inside the file. That is why default_C_entries is called for these. */ static const char *default_C_suffixes [] = { "c", "h", NULL }; #if CTAGS /* C help for Ctags */ static const char default_C_help [] = "In C code, any C function is a tag. Use -t to tag typedefs.\n\ Use -T to tag definitions of 'struct', 'union' and 'enum'.\n\ Use -d to tag '#define' macro definitions and 'enum' constants.\n\ Use --globals to tag global variables.\n\ You can tag function declarations and external variables by\n\ using '--declarations', and struct members by using '--members'."; #else /* C help for Etags */ static const char default_C_help [] = "In C code, any C function or typedef is a tag, and so are\n\ definitions of 'struct', 'union' and 'enum'. '#define' macro\n\ definitions and 'enum' constants are tags unless you specify\n\ '--no-defines'. Global variables are tags unless you specify\n\ '--no-globals' and so are struct members unless you specify\n\ '--no-members'. Use of '--no-globals', '--no-defines' and\n\ '--no-members' can make the tags table file much smaller.\n\ You can tag function declarations and external variables by\n\ using '--declarations'."; #endif /* C help for Ctags and Etags */ static const char *Cplusplus_suffixes [] = { "C", "c++", "cc", "cpp", "cxx", "H", "h++", "hh", "hpp", "hxx", "M", /* Objective C++ */ "pdb", /* PostScript with C syntax */ NULL }; static const char Cplusplus_help [] = "In C++ code, all the tag constructs of C code are tagged. (Use\n\ --help --lang=c --lang=c++ for full help.)\n\ In addition to C tags, member functions are also recognized. Member\n\ variables are recognized unless you use the '--no-members' option.\n\ Tags for variables and functions in classes are named 'CLASS::VARIABLE'\n\ and 'CLASS::FUNCTION'. 'operator' definitions have tag names like\n\ 'operator+'."; static const char *Cjava_suffixes [] = { "java", NULL }; static char Cjava_help [] = "In Java code, all the tags constructs of C and C++ code are\n\ tagged. (Use --help --lang=c --lang=c++ --lang=java for full help.)"; static const char *Cobol_suffixes [] = { "COB", "cob", NULL }; static char Cobol_help [] = "In Cobol code, tags are paragraph names; that is, any word\n\ starting in column 8 and followed by a period."; static const char *Cstar_suffixes [] = { "cs", "hs", NULL }; static const char *Erlang_suffixes [] = { "erl", "hrl", NULL }; static const char Erlang_help [] = "In Erlang code, the tags are the functions, records and macros\n\ defined in the file."; const char *Forth_suffixes [] = { "fth", "tok", NULL }; static const char Forth_help [] = "In Forth code, tags are words defined by ':',\n\ constant, code, create, defer, value, variable, buffer:, field."; static const char *Fortran_suffixes [] = { "F", "f", "f90", "for", NULL }; static const char Fortran_help [] = "In Fortran code, functions, subroutines and block data are tags."; static const char *Go_suffixes [] = {"go", NULL}; static const char Go_help [] = "In Go code, functions, interfaces and packages are tags."; static const char *HTML_suffixes [] = { "htm", "html", "shtml", NULL }; static const char HTML_help [] = "In HTML input files, the tags are the 'title' and the 'h1', 'h2',\n\ 'h3' headers. Also, tags are 'name=' in anchors and all\n\ occurrences of 'id='."; static const char *Lisp_suffixes [] = { "cl", "clisp", "el", "l", "lisp", "LSP", "lsp", "ml", NULL }; static const char Lisp_help [] = "In Lisp code, any function defined with 'defun', any variable\n\ defined with 'defvar' or 'defconst', and in general the first\n\ argument of any expression that starts with '(def' in column zero\n\ is a tag.\n\ The '--declarations' option tags \"(defvar foo)\" constructs too."; static const char *Lua_suffixes [] = { "lua", "LUA", NULL }; static const char Lua_help [] = "In Lua scripts, all functions are tags."; static const char *Makefile_filenames [] = { "Makefile", "makefile", "GNUMakefile", "Makefile.in", "Makefile.am", NULL}; static const char Makefile_help [] = "In makefiles, targets are tags; additionally, variables are tags\n\ unless you specify '--no-globals'."; static const char *Objc_suffixes [] = { "lm", /* Objective lex file */ "m", /* Objective C file */ NULL }; static const char Objc_help [] = "In Objective C code, tags include Objective C definitions for classes,\n\ class categories, methods and protocols. Tags for variables and\n\ functions in classes are named 'CLASS::VARIABLE' and 'CLASS::FUNCTION'.\ \n(Use --help --lang=c --lang=objc --lang=java for full help.)"; static const char *Pascal_suffixes [] = { "p", "pas", NULL }; static const char Pascal_help [] = "In Pascal code, the tags are the functions and procedures defined\n\ in the file."; /* " // this is for working around an Emacs highlighting bug... */ static const char *Perl_suffixes [] = { "pl", "pm", NULL }; static const char *Perl_interpreters [] = { "perl", "@PERL@", NULL }; static const char Perl_help [] = "In Perl code, the tags are the packages, subroutines and variables\n\ defined by the 'package', 'sub', 'my' and 'local' keywords. Use\n\ '--globals' if you want to tag global variables. Tags for\n\ subroutines are named 'PACKAGE::SUB'. The name for subroutines\n\ defined in the default package is 'main::SUB'."; static const char *PHP_suffixes [] = { "php", "php3", "php4", NULL }; static const char PHP_help [] = "In PHP code, tags are functions, classes and defines. Unless you use\n\ the '--no-members' option, vars are tags too."; static const char *plain_C_suffixes [] = { "pc", /* Pro*C file */ NULL }; static const char *PS_suffixes [] = { "ps", "psw", NULL }; /* .psw is for PSWrap */ static const char PS_help [] = "In PostScript code, the tags are the functions."; static const char *Prolog_suffixes [] = { "prolog", NULL }; static const char Prolog_help [] = "In Prolog code, tags are predicates and rules at the beginning of\n\ line."; static const char *Python_suffixes [] = { "py", NULL }; static const char Python_help [] = "In Python code, 'def' or 'class' at the beginning of a line\n\ generate a tag."; static const char *Ruby_suffixes [] = { "rb", "ru", "rbw", NULL }; static const char *Ruby_filenames [] = { "Rakefile", "Thorfile", NULL }; static const char Ruby_help [] = "In Ruby code, 'def' or 'class' or 'module' at the beginning of\n\ a line generate a tag. Constants also generate a tag."; /* Can't do the `SCM' or `scm' prefix with a version number. */ static const char *Scheme_suffixes [] = { "oak", "sch", "scheme", "SCM", "scm", "SM", "sm", "ss", "t", NULL }; static const char Scheme_help [] = "In Scheme code, tags include anything defined with 'def' or with a\n\ construct whose name starts with 'def'. They also include\n\ variables set with 'set!' at top level in the file."; static const char *TeX_suffixes [] = { "bib", "clo", "cls", "ltx", "sty", "TeX", "tex", NULL }; static const char TeX_help [] = "In LaTeX text, the argument of any of the commands '\\chapter',\n\ '\\section', '\\subsection', '\\subsubsection', '\\eqno', '\\label',\n\ '\\ref', '\\cite', '\\bibitem', '\\part', '\\appendix', '\\entry',\n\ '\\index', '\\def', '\\newcommand', '\\renewcommand',\n\ '\\newenvironment' or '\\renewenvironment' is a tag.\n\ \n\ Other commands can be specified by setting the environment variable\n\ 'TEXTAGS' to a colon-separated list like, for example,\n\ TEXTAGS=\"mycommand:myothercommand\"."; static const char *Texinfo_suffixes [] = { "texi", "texinfo", "txi", NULL }; static const char Texinfo_help [] = "for texinfo files, lines starting with @node are tagged."; static const char *Yacc_suffixes [] = { "y", "y++", "ym", "yxx", "yy", NULL }; /* .ym is Objective yacc file */ static const char Yacc_help [] = "In Bison or Yacc input files, each rule defines as a tag the\n\ nonterminal it constructs. The portions of the file that contain\n\ C code are parsed as C code (use --help --lang=c --lang=yacc\n\ for full help)."; static const char auto_help [] = "'auto' is not a real language, it indicates to use\n\ a default language for files base on file name suffix and file contents."; static const char none_help [] = "'none' is not a real language, it indicates to only do\n\ regexp processing on files."; static const char no_lang_help [] = "No detailed help available for this language."; /* * Table of languages. * * It is ok for a given function to be listed under more than one * name. I just didn't. */ static language lang_names [] = { { "ada", Ada_help, Ada_funcs, Ada_suffixes }, { "asm", Asm_help, Asm_labels, Asm_suffixes }, { "c", default_C_help, default_C_entries, default_C_suffixes }, { "c++", Cplusplus_help, Cplusplus_entries, Cplusplus_suffixes }, { "c*", no_lang_help, Cstar_entries, Cstar_suffixes }, { "cobol", Cobol_help, Cobol_paragraphs, Cobol_suffixes }, { "erlang", Erlang_help, Erlang_functions, Erlang_suffixes }, { "forth", Forth_help, Forth_words, Forth_suffixes }, { "fortran", Fortran_help, Fortran_functions, Fortran_suffixes }, { "go", Go_help, Go_functions, Go_suffixes }, { "html", HTML_help, HTML_labels, HTML_suffixes }, { "java", Cjava_help, Cjava_entries, Cjava_suffixes }, { "lisp", Lisp_help, Lisp_functions, Lisp_suffixes }, { "lua", Lua_help, Lua_functions, Lua_suffixes }, { "makefile", Makefile_help,Makefile_targets,NULL,Makefile_filenames}, { "objc", Objc_help, plain_C_entries, Objc_suffixes }, { "pascal", Pascal_help, Pascal_functions, Pascal_suffixes }, { "perl",Perl_help,Perl_functions,Perl_suffixes,NULL,Perl_interpreters}, { "php", PHP_help, PHP_functions, PHP_suffixes }, { "postscript",PS_help, PS_functions, PS_suffixes }, { "proc", no_lang_help, plain_C_entries, plain_C_suffixes }, { "prolog", Prolog_help, Prolog_functions, Prolog_suffixes }, { "python", Python_help, Python_functions, Python_suffixes }, { "ruby", Ruby_help,Ruby_functions,Ruby_suffixes,Ruby_filenames }, { "scheme", Scheme_help, Scheme_functions, Scheme_suffixes }, { "tex", TeX_help, TeX_commands, TeX_suffixes }, { "texinfo", Texinfo_help, Texinfo_nodes, Texinfo_suffixes }, { "yacc", Yacc_help,Yacc_entries,Yacc_suffixes,NULL,NULL,true}, { "auto", auto_help }, /* default guessing scheme */ { "none", none_help, just_read_file }, /* regexp matching only */ { NULL } /* end of list */ }; static void print_language_names (void) { language *lang; const char **name, **ext; puts ("\nThese are the currently supported languages, along with the\n\ default file names and dot suffixes:"); for (lang = lang_names; lang->name != NULL; lang++) { printf (" %-*s", 10, lang->name); if (lang->filenames != NULL) for (name = lang->filenames; *name != NULL; name++) printf (" %s", *name); if (lang->suffixes != NULL) for (ext = lang->suffixes; *ext != NULL; ext++) printf (" .%s", *ext); puts (""); } puts ("where 'auto' means use default language for files based on file\n\ name suffix, and 'none' means only do regexp processing on files.\n\ If no language is specified and no matching suffix is found,\n\ the first line of the file is read for a sharp-bang (#!) sequence\n\ followed by the name of an interpreter. If no such sequence is found,\n\ Fortran is tried first; if no tags are found, C is tried next.\n\ When parsing any C file, a \"class\" or \"template\" keyword\n\ switches to C++."); puts ("Compressed files are supported using gzip, bzip2, and xz.\n\ \n\ For detailed help on a given language use, for example,\n\ etags --help --lang=ada."); } #ifndef EMACS_NAME # define EMACS_NAME "standalone" #endif #ifndef VERSION # define VERSION "17.38.1.4" #endif static _Noreturn void print_version (void) { char emacs_copyright[] = COPYRIGHT; printf ("%s (%s %s)\n", (CTAGS) ? "ctags" : "etags", EMACS_NAME, VERSION); puts (emacs_copyright); puts ("This program is distributed under the terms in ETAGS.README"); exit (EXIT_SUCCESS); } #ifndef PRINT_UNDOCUMENTED_OPTIONS_HELP # define PRINT_UNDOCUMENTED_OPTIONS_HELP false #endif static _Noreturn void print_help (argument *argbuffer) { bool help_for_lang = false; for (; argbuffer->arg_type != at_end; argbuffer++) if (argbuffer->arg_type == at_language) { if (help_for_lang) puts (""); puts (argbuffer->lang->help); help_for_lang = true; } if (help_for_lang) exit (EXIT_SUCCESS); printf ("Usage: %s [options] [[regex-option ...] file-name] ...\n\ \n\ These are the options accepted by %s.\n", progname, progname); puts ("You may use unambiguous abbreviations for the long option names."); puts (" A - as file name means read names from stdin (one per line).\n\ Absolute names are stored in the output file as they are.\n\ Relative ones are stored relative to the output file's directory.\n"); puts ("-a, --append\n\ Append tag entries to existing tags file."); puts ("--packages-only\n\ For Ada files, only generate tags for packages."); if (CTAGS) puts ("-B, --backward-search\n\ Write the search commands for the tag entries using '?', the\n\ backward-search command instead of '/', the forward-search command."); /* This option is mostly obsolete, because etags can now automatically detect C++. Retained for backward compatibility and for debugging and experimentation. In principle, we could want to tag as C++ even before any "class" or "template" keyword. puts ("-C, --c++\n\ Treat files whose name suffix defaults to C language as C++ files."); */ puts ("--declarations\n\ In C and derived languages, create tags for function declarations,"); if (CTAGS) puts ("\tand create tags for extern variables if --globals is used."); else puts ("\tand create tags for extern variables unless --no-globals is used."); if (CTAGS) puts ("-d, --defines\n\ Create tag entries for C #define constants and enum constants, too."); else puts ("-D, --no-defines\n\ Don't create tag entries for C #define constants and enum constants.\n\ This makes the tags file smaller."); if (!CTAGS) puts ("-i FILE, --include=FILE\n\ Include a note in tag file indicating that, when searching for\n\ a tag, one should also consult the tags file FILE after\n\ checking the current file."); puts ("-l LANG, --language=LANG\n\ Force the following files to be considered as written in the\n\ named language up to the next --language=LANG option."); if (CTAGS) puts ("--globals\n\ Create tag entries for global variables in some languages."); else puts ("--no-globals\n\ Do not create tag entries for global variables in some\n\ languages. This makes the tags file smaller."); puts ("--no-line-directive\n\ Ignore #line preprocessor directives in C and derived languages."); if (CTAGS) puts ("--members\n\ Create tag entries for members of structures in some languages."); else puts ("--no-members\n\ Do not create tag entries for members of structures\n\ in some languages."); puts ("-Q, --class-qualify\n\ Qualify tag names with their class name in C++, ObjC, Java, and Perl.\n\ This produces tag names of the form \"class::member\" for C++,\n\ \"class(category)\" for Objective C, and \"class.member\" for Java.\n\ For Objective C, this also produces class methods qualified with\n\ their arguments, as in \"foo:bar:baz:more\".\n\ For Perl, this produces \"package::member\"."); puts ("-r REGEXP, --regex=REGEXP or --regex=@regexfile\n\ Make a tag for each line matching a regular expression pattern\n\ in the following files. {LANGUAGE}REGEXP uses REGEXP for LANGUAGE\n\ files only. REGEXFILE is a file containing one REGEXP per line.\n\ REGEXP takes the form /TAGREGEXP/TAGNAME/MODS, where TAGNAME/ is\n\ optional. The TAGREGEXP pattern is anchored (as if preceded by ^)."); puts (" If TAGNAME/ is present, the tags created are named.\n\ For example Tcl named tags can be created with:\n\ --regex=\"/proc[ \\t]+\\([^ \\t]+\\)/\\1/.\".\n\ MODS are optional one-letter modifiers: 'i' means to ignore case,\n\ 'm' means to allow multi-line matches, 's' implies 'm' and\n\ causes dot to match any character, including newline."); puts ("-R, --no-regex\n\ Don't create tags from regexps for the following files."); puts ("-I, --ignore-indentation\n\ In C and C++ do not assume that a closing brace in the first\n\ column is the final brace of a function or structure definition."); puts ("-o FILE, --output=FILE\n\ Write the tags to FILE."); puts ("--parse-stdin=NAME\n\ Read from standard input and record tags as belonging to file NAME."); if (CTAGS) { puts ("-t, --typedefs\n\ Generate tag entries for C and Ada typedefs."); puts ("-T, --typedefs-and-c++\n\ Generate tag entries for C typedefs, C struct/enum/union tags,\n\ and C++ member functions."); } if (CTAGS) puts ("-u, --update\n\ Update the tag entries for the given files, leaving tag\n\ entries for other files in place. Currently, this is\n\ implemented by deleting the existing entries for the given\n\ files and then rewriting the new entries at the end of the\n\ tags file. It is often faster to simply rebuild the entire\n\ tag file than to use this."); if (CTAGS) { puts ("-v, --vgrind\n\ Print on the standard output an index of items intended for\n\ human consumption, similar to the output of vgrind. The index\n\ is sorted, and gives the page number of each item."); if (PRINT_UNDOCUMENTED_OPTIONS_HELP) puts ("-w, --no-duplicates\n\ Do not create duplicate tag entries, for compatibility with\n\ traditional ctags."); if (PRINT_UNDOCUMENTED_OPTIONS_HELP) puts ("-w, --no-warn\n\ Suppress warning messages about duplicate tag entries."); puts ("-x, --cxref\n\ Like --vgrind, but in the style of cxref, rather than vgrind.\n\ The output uses line numbers instead of page numbers, but\n\ beyond that the differences are cosmetic; try both to see\n\ which you like."); } puts ("-V, --version\n\ Print the version of the program.\n\ -h, --help\n\ Print this help message.\n\ Followed by one or more '--language' options prints detailed\n\ help about tag generation for the specified languages."); print_language_names (); puts (""); puts ("Report bugs to bug-gnu-emacs@gnu.org"); exit (EXIT_SUCCESS); } int main (int argc, char **argv) { int i; unsigned int nincluded_files; char **included_files; argument *argbuffer; int current_arg, file_count; linebuffer filename_lb; bool help_asked = false; ptrdiff_t len; char *optstring; int opt; progname = argv[0]; nincluded_files = 0; included_files = xnew (argc, char *); current_arg = 0; file_count = 0; /* Allocate enough no matter what happens. Overkill, but each one is small. */ argbuffer = xnew (argc, argument); /* * Always find typedefs and structure tags. * Also default to find macro constants, enum constants, struct * members and global variables. Do it for both etags and ctags. */ typedefs = typedefs_or_cplusplus = constantypedefs = true; globals = members = true; /* When the optstring begins with a '-' getopt_long does not rearrange the non-options arguments to be at the end, but leaves them alone. */ optstring = concat ("-ac:Cf:Il:o:Qr:RSVhH", (CTAGS) ? "BxdtTuvw" : "Di:", ""); while ((opt = getopt_long (argc, argv, optstring, longopts, NULL)) != EOF) switch (opt) { case 0: /* If getopt returns 0, then it has already processed a long-named option. We should do nothing. */ break; case 1: /* This means that a file name has been seen. Record it. */ argbuffer[current_arg].arg_type = at_filename; argbuffer[current_arg].what = optarg; len = strlen (optarg); if (whatlen_max < len) whatlen_max = len; ++current_arg; ++file_count; break; case STDIN: /* Parse standard input. Idea by Vivek <vivek@etla.org>. */ argbuffer[current_arg].arg_type = at_stdin; argbuffer[current_arg].what = optarg; len = strlen (optarg); if (whatlen_max < len) whatlen_max = len; ++current_arg; ++file_count; if (parsing_stdin) fatal ("cannot parse standard input more than once"); parsing_stdin = true; break; /* Common options. */ case 'a': append_to_tagfile = true; break; case 'C': cplusplus = true; break; case 'f': /* for compatibility with old makefiles */ case 'o': if (tagfile) { error ("-o option may only be given once."); suggest_asking_for_help (); /* NOTREACHED */ } tagfile = optarg; break; case 'I': case 'S': /* for backward compatibility */ ignoreindent = true; break; case 'l': { language *lang = get_language_from_langname (optarg); if (lang != NULL) { argbuffer[current_arg].lang = lang; argbuffer[current_arg].arg_type = at_language; ++current_arg; } } break; case 'c': /* Backward compatibility: support obsolete --ignore-case-regexp. */ optarg = concat (optarg, "i", ""); /* memory leak here */ FALLTHROUGH; case 'r': argbuffer[current_arg].arg_type = at_regexp; argbuffer[current_arg].what = optarg; len = strlen (optarg); if (whatlen_max < len) whatlen_max = len; ++current_arg; break; case 'R': argbuffer[current_arg].arg_type = at_regexp; argbuffer[current_arg].what = NULL; ++current_arg; break; case 'V': print_version (); break; case 'h': case 'H': help_asked = true; break; case 'Q': class_qualify = 1; break; /* Etags options */ case 'D': constantypedefs = false; break; case 'i': included_files[nincluded_files++] = optarg; break; /* Ctags options. */ case 'B': searchar = '?'; break; case 'd': constantypedefs = true; break; case 't': typedefs = true; break; case 'T': typedefs = typedefs_or_cplusplus = true; break; case 'u': update = true; break; case 'v': vgrind_style = true; FALLTHROUGH; case 'x': cxref_style = true; break; case 'w': no_warnings = true; break; default: suggest_asking_for_help (); /* NOTREACHED */ } /* No more options. Store the rest of arguments. */ for (; optind < argc; optind++) { argbuffer[current_arg].arg_type = at_filename; argbuffer[current_arg].what = argv[optind]; len = strlen (argv[optind]); if (whatlen_max < len) whatlen_max = len; ++current_arg; ++file_count; } argbuffer[current_arg].arg_type = at_end; if (help_asked) print_help (argbuffer); /* NOTREACHED */ if (nincluded_files == 0 && file_count == 0) { error ("no input files specified."); suggest_asking_for_help (); /* NOTREACHED */ } if (tagfile == NULL) tagfile = savestr (CTAGS ? "tags" : "TAGS"); cwd = etags_getcwd (); /* the current working directory */ if (cwd[strlen (cwd) - 1] != '/') { char *oldcwd = cwd; cwd = concat (oldcwd, "/", ""); free (oldcwd); } /* Compute base directory for relative file names. */ if (streq (tagfile, "-") || strneq (tagfile, "/dev/", 5)) tagfiledir = cwd; /* relative file names are relative to cwd */ else { canonicalize_filename (tagfile); tagfiledir = absolute_dirname (tagfile, cwd); } linebuffer_init (&lb); linebuffer_init (&filename_lb); linebuffer_init (&filebuf); linebuffer_init (&token_name); if (!CTAGS) { if (streq (tagfile, "-")) { tagf = stdout; set_binary_mode (STDOUT_FILENO, O_BINARY); } else tagf = fopen (tagfile, append_to_tagfile ? "ab" : "wb"); if (tagf == NULL) pfatal (tagfile); } /* * Loop through files finding functions. */ for (i = 0; i < current_arg; i++) { static language *lang; /* non-NULL if language is forced */ char *this_file; switch (argbuffer[i].arg_type) { case at_language: lang = argbuffer[i].lang; break; case at_regexp: analyze_regex (argbuffer[i].what); break; case at_filename: this_file = argbuffer[i].what; /* Input file named "-" means read file names from stdin (one per line) and use them. */ if (streq (this_file, "-")) { if (parsing_stdin) fatal ("cannot parse standard input " "AND read file names from it"); while (readline_internal (&filename_lb, stdin, "-") > 0) process_file_name (filename_lb.buffer, lang); } else process_file_name (this_file, lang); break; case at_stdin: this_file = argbuffer[i].what; process_file (stdin, this_file, lang); break; default: error ("internal error: arg_type"); } } free_regexps (); free (lb.buffer); free (filebuf.buffer); free (token_name.buffer); if (!CTAGS || cxref_style) { /* Write the remaining tags to tagf (ETAGS) or stdout (CXREF). */ put_entries (nodehead); free_tree (nodehead); nodehead = NULL; if (!CTAGS) { fdesc *fdp; /* Output file entries that have no tags. */ for (fdp = fdhead; fdp != NULL; fdp = fdp->next) if (!fdp->written) fprintf (tagf, "\f\n%s,0\n", fdp->taggedfname); while (nincluded_files-- > 0) fprintf (tagf, "\f\n%s,include\n", *included_files++); if (fclose (tagf) == EOF) pfatal (tagfile); } return EXIT_SUCCESS; } /* From here on, we are in (CTAGS && !cxref_style) */ if (update) { char *cmd = xmalloc (strlen (tagfile) + whatlen_max + sizeof "mv..OTAGS;grep -Fv '\t\t' OTAGS >;rm OTAGS"); for (i = 0; i < current_arg; ++i) { switch (argbuffer[i].arg_type) { case at_filename: case at_stdin: break; default: continue; /* the for loop */ } char *z = stpcpy (cmd, "mv "); z = stpcpy (z, tagfile); z = stpcpy (z, " OTAGS;grep -Fv '\t"); z = stpcpy (z, argbuffer[i].what); z = stpcpy (z, "\t' OTAGS >"); z = stpcpy (z, tagfile); strcpy (z, ";rm OTAGS"); if (system (cmd) != EXIT_SUCCESS) fatal ("failed to execute shell command"); } free (cmd); append_to_tagfile = true; } tagf = fopen (tagfile, append_to_tagfile ? "ab" : "wb"); if (tagf == NULL) pfatal (tagfile); put_entries (nodehead); /* write all the tags (CTAGS) */ free_tree (nodehead); nodehead = NULL; if (fclose (tagf) == EOF) pfatal (tagfile); if (CTAGS) if (append_to_tagfile || update) { char *cmd = xmalloc (2 * strlen (tagfile) + sizeof "sort -u -o.."); /* Maybe these should be used: setenv ("LC_COLLATE", "C", 1); setenv ("LC_ALL", "C", 1); */ char *z = stpcpy (cmd, "sort -u -o "); z = stpcpy (z, tagfile); *z++ = ' '; strcpy (z, tagfile); return system (cmd); } return EXIT_SUCCESS; } /* * Return a compressor given the file name. If EXTPTR is non-zero, * return a pointer into FILE where the compressor-specific * extension begins. If no compressor is found, NULL is returned * and EXTPTR is not significant. * Idea by Vladimir Alexiev <vladimir@cs.ualberta.ca> (1998) */ static compressor * get_compressor_from_suffix (char *file, char **extptr) { compressor *compr; char *slash, *suffix; /* File has been processed by canonicalize_filename, so we don't need to consider backslashes on DOS_NT. */ slash = strrchr (file, '/'); suffix = strrchr (file, '.'); if (suffix == NULL || suffix < slash) return NULL; if (extptr != NULL) *extptr = suffix; suffix += 1; /* Let those poor souls who live with DOS 8+3 file name limits get some solace by treating foo.cgz as if it were foo.c.gz, etc. */ do { for (compr = compressors; compr->suffix != NULL; compr++) if (streq (compr->suffix, suffix)) return compr; break; /* do it only once: not really a loop */ if (extptr != NULL) *extptr = ++suffix; } while (*suffix != '\0'); return NULL; } /* * Return a language given the name. */ static language * get_language_from_langname (const char *name) { language *lang; if (name == NULL) error ("empty language name"); else { for (lang = lang_names; lang->name != NULL; lang++) if (streq (name, lang->name)) return lang; error ("unknown language \"%s\"", name); } return NULL; } /* * Return a language given the interpreter name. */ static language * get_language_from_interpreter (char *interpreter) { language *lang; const char **iname; if (interpreter == NULL) return NULL; for (lang = lang_names; lang->name != NULL; lang++) if (lang->interpreters != NULL) for (iname = lang->interpreters; *iname != NULL; iname++) if (streq (*iname, interpreter)) return lang; return NULL; } /* * Return a language given the file name. */ static language * get_language_from_filename (char *file, int case_sensitive) { language *lang; const char **name, **ext, *suffix; char *slash; /* Try whole file name first. */ slash = strrchr (file, '/'); if (slash != NULL) file = slash + 1; #ifdef DOS_NT else if (file[0] && file[1] == ':') file += 2; #endif for (lang = lang_names; lang->name != NULL; lang++) if (lang->filenames != NULL) for (name = lang->filenames; *name != NULL; name++) if ((case_sensitive) ? streq (*name, file) : strcaseeq (*name, file)) return lang; /* If not found, try suffix after last dot. */ suffix = strrchr (file, '.'); if (suffix == NULL) return NULL; suffix += 1; for (lang = lang_names; lang->name != NULL; lang++) if (lang->suffixes != NULL) for (ext = lang->suffixes; *ext != NULL; ext++) if ((case_sensitive) ? streq (*ext, suffix) : strcaseeq (*ext, suffix)) return lang; return NULL; } /* * This routine is called on each file argument. */ static void process_file_name (char *file, language *lang) { FILE *inf; fdesc *fdp; compressor *compr; char *compressed_name, *uncompressed_name; char *ext, *real_name UNINIT, *tmp_name; int retval; canonicalize_filename (file); if (streq (file, tagfile) && !streq (tagfile, "-")) { error ("skipping inclusion of %s in self.", file); return; } compr = get_compressor_from_suffix (file, &ext); if (compr) { compressed_name = file; uncompressed_name = savenstr (file, ext - file); } else { compressed_name = NULL; uncompressed_name = file; } /* If the canonicalized uncompressed name has already been dealt with, skip it silently. */ for (fdp = fdhead; fdp != NULL; fdp = fdp->next) { assert (fdp->infname != NULL); if (streq (uncompressed_name, fdp->infname)) goto cleanup; } inf = fopen (file, "r" FOPEN_BINARY); if (inf) real_name = file; else { int file_errno = errno; if (compressed_name) { /* Try with the given suffix. */ inf = fopen (uncompressed_name, "r" FOPEN_BINARY); if (inf) real_name = uncompressed_name; } else { /* Try all possible suffixes. */ for (compr = compressors; compr->suffix != NULL; compr++) { compressed_name = concat (file, ".", compr->suffix); inf = fopen (compressed_name, "r" FOPEN_BINARY); if (inf) { real_name = compressed_name; break; } free (compressed_name); compressed_name = NULL; } } if (! inf) { errno = file_errno; perror (file); goto cleanup; } } if (real_name == compressed_name) { fclose (inf); tmp_name = etags_mktmp (); if (!tmp_name) inf = NULL; else { #if defined (DOS_NT) char *cmd1 = concat (compr->command, " \"", real_name); char *cmd = concat (cmd1, "\" > ", tmp_name); #else char *cmd1 = concat (compr->command, " '", real_name); char *cmd = concat (cmd1, "' > ", tmp_name); #endif free (cmd1); int tmp_errno; if (system (cmd) == -1) { inf = NULL; tmp_errno = EINVAL; } else { inf = fopen (tmp_name, "r" FOPEN_BINARY); tmp_errno = errno; } free (cmd); errno = tmp_errno; } if (!inf) { perror (real_name); goto cleanup; } } process_file (inf, uncompressed_name, lang); retval = fclose (inf); if (real_name == compressed_name) { remove (tmp_name); free (tmp_name); } if (retval < 0) pfatal (file); cleanup: if (compressed_name != file) free (compressed_name); if (uncompressed_name != file) free (uncompressed_name); last_node = NULL; curfdp = NULL; return; } static void process_file (FILE *fh, char *fn, language *lang) { static const fdesc emptyfdesc; fdesc *fdp; infilename = fn; /* Create a new input file description entry. */ fdp = xnew (1, fdesc); *fdp = emptyfdesc; fdp->next = fdhead; fdp->infname = savestr (fn); fdp->lang = lang; fdp->infabsname = absolute_filename (fn, cwd); fdp->infabsdir = absolute_dirname (fn, cwd); if (filename_is_absolute (fn)) { /* An absolute file name. Canonicalize it. */ fdp->taggedfname = absolute_filename (fn, NULL); } else { /* A file name relative to cwd. Make it relative to the directory of the tags file. */ fdp->taggedfname = relative_filename (fn, tagfiledir); } fdp->usecharno = true; /* use char position when making tags */ fdp->prop = NULL; fdp->written = false; /* not written on tags file yet */ fdhead = fdp; curfdp = fdhead; /* the current file description */ find_entries (fh); /* If not Ctags, and if this is not metasource and if it contained no #line directives, we can write the tags and free all nodes pointing to curfdp. */ if (!CTAGS && curfdp->usecharno /* no #line directives in this file */ && !curfdp->lang->metasource) { node *np, *prev; /* Look for the head of the sublist relative to this file. See add_node for the structure of the node tree. */ prev = NULL; for (np = nodehead; np != NULL; prev = np, np = np->left) if (np->fdp == curfdp) break; /* If we generated tags for this file, write and delete them. */ if (np != NULL) { /* This is the head of the last sublist, if any. The following instructions depend on this being true. */ assert (np->left == NULL); assert (fdhead == curfdp); assert (last_node->fdp == curfdp); put_entries (np); /* write tags for file curfdp->taggedfname */ free_tree (np); /* remove the written nodes */ if (prev == NULL) nodehead = NULL; /* no nodes left */ else prev->left = NULL; /* delete the pointer to the sublist */ } } } static void reset_input (FILE *inf) { if (fseek (inf, 0, SEEK_SET) != 0) perror (infilename); } /* * This routine opens the specified file and calls the function * which finds the function and type definitions. */ static void find_entries (FILE *inf) { char *cp; language *lang = curfdp->lang; Lang_function *parser = NULL; /* If user specified a language, use it. */ if (lang != NULL && lang->function != NULL) { parser = lang->function; } /* Else try to guess the language given the file name. */ if (parser == NULL) { lang = get_language_from_filename (curfdp->infname, true); if (lang != NULL && lang->function != NULL) { curfdp->lang = lang; parser = lang->function; } } /* Else look for sharp-bang as the first two characters. */ if (parser == NULL && readline_internal (&lb, inf, infilename) > 0 && lb.len >= 2 && lb.buffer[0] == '#' && lb.buffer[1] == '!') { char *lp; /* Set lp to point at the first char after the last slash in the line or, if no slashes, at the first nonblank. Then set cp to the first successive blank and terminate the string. */ lp = strrchr (lb.buffer+2, '/'); if (lp != NULL) lp += 1; else lp = skip_spaces (lb.buffer + 2); cp = skip_non_spaces (lp); *cp = '\0'; if (strlen (lp) > 0) { lang = get_language_from_interpreter (lp); if (lang != NULL && lang->function != NULL) { curfdp->lang = lang; parser = lang->function; } } } reset_input (inf); /* Else try to guess the language given the case insensitive file name. */ if (parser == NULL) { lang = get_language_from_filename (curfdp->infname, false); if (lang != NULL && lang->function != NULL) { curfdp->lang = lang; parser = lang->function; } } /* Else try Fortran or C. */ if (parser == NULL) { node *old_last_node = last_node; curfdp->lang = get_language_from_langname ("fortran"); find_entries (inf); if (old_last_node == last_node) /* No Fortran entries found. Try C. */ { reset_input (inf); curfdp->lang = get_language_from_langname (cplusplus ? "c++" : "c"); find_entries (inf); } return; } if (!no_line_directive && curfdp->lang != NULL && curfdp->lang->metasource) /* It may be that this is a bingo.y file, and we already parsed a bingo.c file, or anyway we parsed a file that is automatically generated from this one. If this is the case, the bingo.c file contained #line directives that generated tags pointing to this file. Let's delete them all before parsing this file, which is the real source. */ { fdesc **fdpp = &fdhead; while (*fdpp != NULL) if (*fdpp != curfdp && streq ((*fdpp)->taggedfname, curfdp->taggedfname)) /* We found one of those! We must delete both the file description and all tags referring to it. */ { fdesc *badfdp = *fdpp; /* Delete the tags referring to badfdp->taggedfname that were obtained from badfdp->infname. */ invalidate_nodes (badfdp, &nodehead); *fdpp = badfdp->next; /* remove the bad description from the list */ free_fdesc (badfdp); } else fdpp = &(*fdpp)->next; /* advance the list pointer */ } assert (parser != NULL); /* Generic initializations before reading from file. */ linebuffer_setlen (&filebuf, 0); /* reset the file buffer */ /* Generic initializations before parsing file with readline. */ lineno = 0; /* reset global line number */ charno = 0; /* reset global char number */ linecharno = 0; /* reset global char number of line start */ parser (inf); regex_tag_multiline (); } /* * Check whether an implicitly named tag should be created, * then call `pfnote'. * NAME is a string that is internally copied by this function. * * TAGS format specification * Idea by Sam Kendall <kendall@mv.mv.com> (1997) * The following is explained in some more detail in etc/ETAGS.EBNF. * * make_tag creates tags with "implicit tag names" (unnamed tags) * if the following are all true, assuming NONAM=" \f\t\n\r()=,;": * 1. NAME does not contain any of the characters in NONAM; * 2. LINESTART contains name as either a rightmost, or rightmost but * one character, substring; * 3. the character, if any, immediately before NAME in LINESTART must * be a character in NONAM; * 4. the character, if any, immediately after NAME in LINESTART must * also be a character in NONAM. * * The implementation uses the notinname() macro, which recognizes the * characters stored in the string `nonam'. * etags.el needs to use the same characters that are in NONAM. */ static void make_tag (const char *name, /* tag name, or NULL if unnamed */ int namelen, /* tag length */ bool is_func, /* tag is a function */ char *linestart, /* start of the line where tag is */ int linelen, /* length of the line where tag is */ int lno, /* line number */ long int cno) /* character number */ { bool named = (name != NULL && namelen > 0); char *nname = NULL; if (debug) fprintf (stderr, "%s on %s:%d: %s\n", named ? name : "(unnamed)", curfdp->taggedfname, lno, linestart); if (!CTAGS && named) /* maybe set named to false */ /* Let's try to make an implicit tag name, that is, create an unnamed tag such that etags.el can guess a name from it. */ { int i; register const char *cp = name; for (i = 0; i < namelen; i++) if (notinname (*cp++)) break; if (i == namelen) /* rule #1 */ { cp = linestart + linelen - namelen; if (notinname (linestart[linelen-1])) cp -= 1; /* rule #4 */ if (cp >= linestart /* rule #2 */ && (cp == linestart || notinname (cp[-1])) /* rule #3 */ && strneq (name, cp, namelen)) /* rule #2 */ named = false; /* use implicit tag name */ } } if (named) nname = savenstr (name, namelen); pfnote (nname, is_func, linestart, linelen, lno, cno); } /* Record a tag. */ static void pfnote (char *name, bool is_func, char *linestart, int linelen, int lno, long int cno) /* tag name, or NULL if unnamed */ /* tag is a function */ /* start of the line where tag is */ /* length of the line where tag is */ /* line number */ /* character number */ { register node *np; assert (name == NULL || name[0] != '\0'); if (CTAGS && name == NULL) return; np = xnew (1, node); /* If ctags mode, change name "main" to M<thisfilename>. */ if (CTAGS && !cxref_style && streq (name, "main")) { char *fp = strrchr (curfdp->taggedfname, '/'); np->name = concat ("M", fp == NULL ? curfdp->taggedfname : fp + 1, ""); fp = strrchr (np->name, '.'); if (fp != NULL && fp[1] != '\0' && fp[2] == '\0') fp[0] = '\0'; } else np->name = name; np->valid = true; np->been_warned = false; np->fdp = curfdp; np->is_func = is_func; np->lno = lno; if (np->fdp->usecharno) /* Our char numbers are 0-base, because of C language tradition? ctags compatibility? old versions compatibility? I don't know. Anyway, since emacs's are 1-base we expect etags.el to take care of the difference. If we wanted to have 1-based numbers, we would uncomment the +1 below. */ np->cno = cno /* + 1 */ ; else np->cno = invalidcharno; np->left = np->right = NULL; if (CTAGS && !cxref_style) { if (strlen (linestart) < 50) np->regex = concat (linestart, "$", ""); else np->regex = savenstr (linestart, 50); } else np->regex = savenstr (linestart, linelen); add_node (np, &nodehead); } /* * Utility functions and data to avoid recursion. */ typedef struct stack_entry { node *np; struct stack_entry *next; } stkentry; static void push_node (node *np, stkentry **stack_top) { if (np) { stkentry *new = xnew (1, stkentry); new->np = np; new->next = *stack_top; *stack_top = new; } } static node * pop_node (stkentry **stack_top) { node *ret = NULL; if (*stack_top) { stkentry *old_start = *stack_top; ret = (*stack_top)->np; *stack_top = (*stack_top)->next; free (old_start); } return ret; } /* * free_tree () * emulate recursion on left children, iterate on right children. */ static void free_tree (register node *np) { stkentry *stack = NULL; while (np) { /* Descent on left children. */ while (np->left) { push_node (np, &stack); np = np->left; } /* Free node without left children. */ node *node_right = np->right; free (np->name); free (np->regex); free (np); if (!node_right) { /* Backtrack to find a node with right children, while freeing nodes that don't have right children. */ while (node_right == NULL && (np = pop_node (&stack)) != NULL) { node_right = np->right; free (np->name); free (np->regex); free (np); } } /* Free right children. */ np = node_right; } } /* * free_fdesc () * delete a file description */ static void free_fdesc (register fdesc *fdp) { free (fdp->infname); free (fdp->infabsname); free (fdp->infabsdir); free (fdp->taggedfname); free (fdp->prop); free (fdp); } /* * add_node () * Adds a node to the tree of nodes. In etags mode, sort by file * name. In ctags mode, sort by tag name. Make no attempt at * balancing. * * add_node is the only function allowed to add nodes, so it can * maintain state. */ static void add_node (node *np, node **cur_node_p) { node *cur_node = *cur_node_p; /* Make the first node. */ if (cur_node == NULL) { *cur_node_p = np; last_node = np; return; } if (!CTAGS) /* Etags Mode */ { /* For each file name, tags are in a linked sublist on the right pointer. The first tags of different files are a linked list on the left pointer. last_node points to the end of the last used sublist. */ if (last_node != NULL && last_node->fdp == np->fdp) { /* Let's use the same sublist as the last added node. */ assert (last_node->right == NULL); last_node->right = np; last_node = np; } else { while (cur_node->fdp != np->fdp) { if (cur_node->left == NULL) break; /* The head of this sublist is not good for us. Let's try the next one. */ cur_node = cur_node->left; } if (cur_node->left) { /* Scanning the list we found the head of a sublist which is good for us. Let's scan this sublist. */ if (cur_node->right) { cur_node = cur_node->right; while (cur_node->right) cur_node = cur_node->right; } /* Make a new node in this sublist. */ cur_node->right = np; } else { /* Make a new sublist. */ cur_node->left = np; } last_node = np; } } /* if ETAGS mode */ else { /* Ctags Mode */ node **next_node = &cur_node; while ((cur_node = *next_node) != NULL) { int dif = strcmp (np->name, cur_node->name); /* * If this tag name matches an existing one, then * do not add the node, but maybe print a warning. */ if (!dif && no_duplicates) { if (np->fdp == cur_node->fdp) { if (!no_warnings) { fprintf (stderr, "Duplicate entry in file %s, line %d: %s\n", np->fdp->infname, lineno, np->name); fprintf (stderr, "Second entry ignored\n"); } } else if (!cur_node->been_warned && !no_warnings) { fprintf (stderr, "Duplicate entry in files %s and %s: %s (Warning only)\n", np->fdp->infname, cur_node->fdp->infname, np->name); cur_node->been_warned = true; } return; } else next_node = dif < 0 ? &cur_node->left : &cur_node->right; } *next_node = np; last_node = np; } /* if CTAGS mode */ } /* * invalidate_nodes () * Scan the node tree and invalidate all nodes pointing to the * given file description (CTAGS case) or free them (ETAGS case). */ static void invalidate_nodes (fdesc *badfdp, node **npp) { node *np = *npp; stkentry *stack = NULL; if (CTAGS) { while (np) { /* Push all the left children on the stack. */ while (np->left != NULL) { push_node (np, &stack); np = np->left; } /* Invalidate this node. */ if (np->fdp == badfdp) np->valid = false; if (!np->right) { /* Pop nodes from stack, invalidating them, until we find one with a right child. */ while ((np = pop_node (&stack)) != NULL) { if (np->fdp == badfdp) np->valid = false; if (np->right != NULL) break; } } /* Process the right child, if any. */ if (np) np = np->right; } } else { node super_root, *np_parent = NULL; super_root.left = np; super_root.fdp = (fdesc *) -1; np = &super_root; while (np) { /* Descent on left children until node with BADFP. */ while (np && np->fdp != badfdp) { assert (np->fdp != NULL); np_parent = np; np = np->left; } if (np) { np_parent->left = np->left; /* detach subtree from the tree */ np->left = NULL; /* isolate it */ free_tree (np); /* free it */ /* Continue with rest of tree. */ np = np_parent->left; } } *npp = super_root.left; } } static int total_size_of_entries (node *); static int number_len (long) ATTRIBUTE_CONST; /* Length of a non-negative number's decimal representation. */ static int number_len (long int num) { int len = 1; while ((num /= 10) > 0) len += 1; return len; } /* * Return total number of characters that put_entries will output for * the nodes in the linked list at the right of the specified node. * This count is irrelevant with etags.el since emacs 19.34 at least, * but is still supplied for backward compatibility. */ static int total_size_of_entries (register node *np) { register int total = 0; for (; np != NULL; np = np->right) if (np->valid) { total += strlen (np->regex) + 1; /* pat\177 */ if (np->name != NULL) total += strlen (np->name) + 1; /* name\001 */ total += number_len ((long) np->lno) + 1; /* lno, */ if (np->cno != invalidcharno) /* cno */ total += number_len (np->cno); total += 1; /* newline */ } return total; } static void put_entry (node *np) { register char *sp; static fdesc *fdp = NULL; /* Output this entry */ if (np->valid) { if (!CTAGS) { /* Etags mode */ if (fdp != np->fdp) { fdp = np->fdp; fprintf (tagf, "\f\n%s,%d\n", fdp->taggedfname, total_size_of_entries (np)); fdp->written = true; } fputs (np->regex, tagf); fputc ('\177', tagf); if (np->name != NULL) { fputs (np->name, tagf); fputc ('\001', tagf); } fprintf (tagf, "%d,", np->lno); if (np->cno != invalidcharno) fprintf (tagf, "%ld", np->cno); fputs ("\n", tagf); } else { /* Ctags mode */ if (np->name == NULL) error ("internal error: NULL name in ctags mode."); if (cxref_style) { if (vgrind_style) fprintf (stdout, "%s %s %d\n", np->name, np->fdp->taggedfname, (np->lno + 63) / 64); else fprintf (stdout, "%-16s %3d %-16s %s\n", np->name, np->lno, np->fdp->taggedfname, np->regex); } else { fprintf (tagf, "%s\t%s\t", np->name, np->fdp->taggedfname); if (np->is_func) { /* function or #define macro with args */ putc (searchar, tagf); putc ('^', tagf); for (sp = np->regex; *sp; sp++) { if (*sp == '\\' || *sp == searchar) putc ('\\', tagf); putc (*sp, tagf); } putc (searchar, tagf); } else { /* anything else; text pattern inadequate */ fprintf (tagf, "%d", np->lno); } putc ('\n', tagf); } } } /* if this node contains a valid tag */ } static void put_entries (node *np) { stkentry *stack = NULL; if (np == NULL) return; if (CTAGS) { while (np) { /* Stack subentries that precede this one. */ while (np->left) { push_node (np, &stack); np = np->left; } /* Output this subentry. */ put_entry (np); /* Stack subentries that follow this one. */ while (!np->right) { /* Output subentries that precede the next one. */ np = pop_node (&stack); if (!np) break; put_entry (np); } if (np) np = np->right; } } else { push_node (np, &stack); while ((np = pop_node (&stack)) != NULL) { /* Output this subentry. */ put_entry (np); while (np->right) { /* Output subentries that follow this one. */ put_entry (np->right); /* Stack subentries from the following files. */ push_node (np->left, &stack); np = np->right; } push_node (np->left, &stack); } } } /* C extensions. */ #define C_EXT 0x00fff /* C extensions */ #define C_PLAIN 0x00000 /* C */ #define C_PLPL 0x00001 /* C++ */ #define C_STAR 0x00003 /* C* */ #define C_JAVA 0x00005 /* JAVA */ #define C_AUTO 0x01000 /* C, but switch to C++ if `class' is met */ #define YACC 0x10000 /* yacc file */ /* * The C symbol tables. */ enum sym_type { st_none, st_C_objprot, st_C_objimpl, st_C_objend, st_C_gnumacro, st_C_ignore, st_C_attribute, st_C_enum_bf, st_C_javastruct, st_C_operator, st_C_class, st_C_template, st_C_struct, st_C_extern, st_C_enum, st_C_define, st_C_typedef }; /* Feed stuff between (but not including) %[ and %] lines to: gperf -m 5 %[ %compare-strncmp %enum %struct-type struct C_stab_entry { char *name; int c_ext; enum sym_type type; } %% if, 0, st_C_ignore for, 0, st_C_ignore while, 0, st_C_ignore switch, 0, st_C_ignore return, 0, st_C_ignore __attribute__, 0, st_C_attribute GTY, 0, st_C_attribute @interface, 0, st_C_objprot @protocol, 0, st_C_objprot @implementation,0, st_C_objimpl @end, 0, st_C_objend import, (C_JAVA & ~C_PLPL), st_C_ignore package, (C_JAVA & ~C_PLPL), st_C_ignore friend, C_PLPL, st_C_ignore extends, (C_JAVA & ~C_PLPL), st_C_javastruct implements, (C_JAVA & ~C_PLPL), st_C_javastruct interface, (C_JAVA & ~C_PLPL), st_C_struct class, 0, st_C_class namespace, C_PLPL, st_C_struct domain, C_STAR, st_C_struct union, 0, st_C_struct struct, 0, st_C_struct extern, 0, st_C_extern enum, 0, st_C_enum typedef, 0, st_C_typedef define, 0, st_C_define undef, 0, st_C_define operator, C_PLPL, st_C_operator template, 0, st_C_template # DEFUN used in emacs, the next three used in glibc (SYSCALL only for mach). DEFUN, 0, st_C_gnumacro SYSCALL, 0, st_C_gnumacro ENTRY, 0, st_C_gnumacro PSEUDO, 0, st_C_gnumacro ENUM_BF, 0, st_C_enum_bf # These are defined inside C functions, so currently they are not met. # EXFUN used in glibc, DEFVAR_* in emacs. #EXFUN, 0, st_C_gnumacro #DEFVAR_, 0, st_C_gnumacro %] and replace lines between %< and %> with its output, then: - remove the #if characterset check - remove any #line directives - make in_word_set static and not inline - remove any 'register' qualifications from variable decls. */ /*%<*/ /* C code produced by gperf version 3.0.1 */ /* Command-line: gperf -m 5 */ /* Computed positions: -k'2-3' */ struct C_stab_entry { const char *name; int c_ext; enum sym_type type; }; /* maximum key range = 34, duplicates = 0 */ static int hash (const char *str, int len) { static char const asso_values[] = { 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 3, 27, 36, 36, 36, 36, 36, 36, 36, 26, 36, 36, 36, 36, 25, 0, 0, 36, 36, 36, 0, 36, 36, 36, 36, 36, 1, 36, 16, 36, 6, 23, 0, 0, 36, 22, 0, 36, 36, 5, 0, 0, 15, 1, 36, 6, 36, 8, 19, 36, 16, 4, 5, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36 }; int hval = len; switch (hval) { default: hval += asso_values[(unsigned char) str[2]]; FALLTHROUGH; case 2: hval += asso_values[(unsigned char) str[1]]; break; } return hval; } static struct C_stab_entry * in_word_set (register const char *str, register unsigned int len) { enum { TOTAL_KEYWORDS = 34, MIN_WORD_LENGTH = 2, MAX_WORD_LENGTH = 15, MIN_HASH_VALUE = 2, MAX_HASH_VALUE = 35 }; static struct C_stab_entry wordlist[] = { {""}, {""}, {"if", 0, st_C_ignore}, {"GTY", 0, st_C_attribute}, {"@end", 0, st_C_objend}, {"union", 0, st_C_struct}, {"define", 0, st_C_define}, {"import", (C_JAVA & ~C_PLPL), st_C_ignore}, {"template", 0, st_C_template}, {"operator", C_PLPL, st_C_operator}, {"@interface", 0, st_C_objprot}, {"implements", (C_JAVA & ~C_PLPL), st_C_javastruct}, {"friend", C_PLPL, st_C_ignore}, {"typedef", 0, st_C_typedef}, {"return", 0, st_C_ignore}, {"@implementation",0, st_C_objimpl}, {"@protocol", 0, st_C_objprot}, {"interface", (C_JAVA & ~C_PLPL), st_C_struct}, {"extern", 0, st_C_extern}, {"extends", (C_JAVA & ~C_PLPL), st_C_javastruct}, {"struct", 0, st_C_struct}, {"domain", C_STAR, st_C_struct}, {"switch", 0, st_C_ignore}, {"enum", 0, st_C_enum}, {"for", 0, st_C_ignore}, {"namespace", C_PLPL, st_C_struct}, {"class", 0, st_C_class}, {"while", 0, st_C_ignore}, {"undef", 0, st_C_define}, {"package", (C_JAVA & ~C_PLPL), st_C_ignore}, {"__attribute__", 0, st_C_attribute}, {"ENTRY", 0, st_C_gnumacro}, {"SYSCALL", 0, st_C_gnumacro}, {"ENUM_BF", 0, st_C_enum_bf}, {"PSEUDO", 0, st_C_gnumacro}, {"DEFUN", 0, st_C_gnumacro} }; if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH) { int key = hash (str, len); if (key <= MAX_HASH_VALUE && key >= 0) { const char *s = wordlist[key].name; if (*str == *s && !strncmp (str + 1, s + 1, len - 1) && s[len] == '\0') return &wordlist[key]; } } return 0; } /*%>*/ static enum sym_type C_symtype (char *str, int len, int c_ext) { register struct C_stab_entry *se = in_word_set (str, len); if (se == NULL || (se->c_ext && !(c_ext & se->c_ext))) return st_none; return se->type; } /* * Ignoring __attribute__ ((list)) */ static bool inattribute; /* looking at an __attribute__ construct */ /* Ignoring ENUM_BF (type) * */ static bool in_enum_bf; /* inside parentheses following ENUM_BF */ /* * C functions and variables are recognized using a simple * finite automaton. fvdef is its state variable. */ static enum { fvnone, /* nothing seen */ fdefunkey, /* Emacs DEFUN keyword seen */ fdefunname, /* Emacs DEFUN name seen */ foperator, /* func: operator keyword seen (cplpl) */ fvnameseen, /* function or variable name seen */ fstartlist, /* func: just after open parenthesis */ finlist, /* func: in parameter list */ flistseen, /* func: after parameter list */ fignore, /* func: before open brace */ vignore /* var-like: ignore until ';' */ } fvdef; static bool fvextern; /* func or var: extern keyword seen; */ /* * typedefs are recognized using a simple finite automaton. * typdef is its state variable. */ static enum { tnone, /* nothing seen */ tkeyseen, /* typedef keyword seen */ ttypeseen, /* defined type seen */ tinbody, /* inside typedef body */ tend, /* just before typedef tag */ tignore /* junk after typedef tag */ } typdef; /* * struct-like structures (enum, struct and union) are recognized * using another simple finite automaton. `structdef' is its state * variable. */ static enum { snone, /* nothing seen yet, or in struct body if bracelev > 0 */ skeyseen, /* struct-like keyword seen */ stagseen, /* struct-like tag seen */ scolonseen /* colon seen after struct-like tag */ } structdef; /* * When objdef is different from onone, objtag is the name of the class. */ static const char *objtag = "<uninited>"; /* * Yet another little state machine to deal with preprocessor lines. */ static enum { dnone, /* nothing seen */ dsharpseen, /* '#' seen as first char on line */ ddefineseen, /* '#' and 'define' seen */ dignorerest /* ignore rest of line */ } definedef; /* * State machine for Objective C protocols and implementations. * Idea by Tom R.Hageman <tom@basil.icce.rug.nl> (1995) */ static enum { onone, /* nothing seen */ oprotocol, /* @interface or @protocol seen */ oimplementation, /* @implementations seen */ otagseen, /* class name seen */ oparenseen, /* parenthesis before category seen */ ocatseen, /* category name seen */ oinbody, /* in @implementation body */ omethodsign, /* in @implementation body, after +/- */ omethodtag, /* after method name */ omethodcolon, /* after method colon */ omethodparm, /* after method parameter */ oignore /* wait for @end */ } objdef; /* * Use this structure to keep info about the token read, and how it * should be tagged. Used by the make_C_tag function to build a tag. */ static struct tok { char *line; /* string containing the token */ int offset; /* where the token starts in LINE */ int length; /* token length */ /* The previous members can be used to pass strings around for generic purposes. The following ones specifically refer to creating tags. In this case the token contained here is the pattern that will be used to create a tag. */ bool valid; /* do not create a tag; the token should be invalidated whenever a state machine is reset prematurely */ bool named; /* create a named tag */ int lineno; /* source line number of tag */ long linepos; /* source char number of tag */ } token; /* latest token read */ /* * Variables and functions for dealing with nested structures. * Idea by Mykola Dzyuba <mdzyuba@yahoo.com> (2001) */ static void pushclass_above (int, char *, int); static void popclass_above (int); static void write_classname (linebuffer *, const char *qualifier); static struct { char **cname; /* nested class names */ int *bracelev; /* nested class brace level */ int nl; /* class nesting level (elements used) */ int size; /* length of the array */ } cstack; /* stack for nested declaration tags */ /* Current struct nesting depth (namespace, class, struct, union, enum). */ #define nestlev (cstack.nl) /* After struct keyword or in struct body, not inside a nested function. */ #define instruct (structdef == snone && nestlev > 0 \ && bracelev == cstack.bracelev[nestlev-1] + 1) static void pushclass_above (int bracelev, char *str, int len) { int nl; popclass_above (bracelev); nl = cstack.nl; if (nl >= cstack.size) { int size = cstack.size *= 2; xrnew (cstack.cname, size, char *); xrnew (cstack.bracelev, size, int); } assert (nl == 0 || cstack.bracelev[nl-1] < bracelev); cstack.cname[nl] = (str == NULL) ? NULL : savenstr (str, len); cstack.bracelev[nl] = bracelev; cstack.nl = nl + 1; } static void popclass_above (int bracelev) { int nl; for (nl = cstack.nl - 1; nl >= 0 && cstack.bracelev[nl] >= bracelev; nl--) { free (cstack.cname[nl]); cstack.nl = nl; } } static void write_classname (linebuffer *cn, const char *qualifier) { int i, len; int qlen = strlen (qualifier); if (cstack.nl == 0 || cstack.cname[0] == NULL) { len = 0; cn->len = 0; cn->buffer[0] = '\0'; } else { len = strlen (cstack.cname[0]); linebuffer_setlen (cn, len); strcpy (cn->buffer, cstack.cname[0]); } for (i = 1; i < cstack.nl; i++) { char *s = cstack.cname[i]; if (s == NULL) continue; linebuffer_setlen (cn, len + qlen + strlen (s)); len += sprintf (cn->buffer + len, "%s%s", qualifier, s); } } static bool consider_token (char *, int, int, int *, int, int, bool *); static void make_C_tag (bool); /* * consider_token () * checks to see if the current token is at the start of a * function or variable, or corresponds to a typedef, or * is a struct/union/enum tag, or #define, or an enum constant. * * *IS_FUNC_OR_VAR gets true if the token is a function or #define macro * with args. C_EXTP points to which language we are looking at. * * Globals * fvdef IN OUT * structdef IN OUT * definedef IN OUT * typdef IN OUT * objdef IN OUT */ static bool consider_token (char *str, int len, int c, int *c_extp, int bracelev, int parlev, bool *is_func_or_var) /* IN: token pointer */ /* IN: token length */ /* IN: first char after the token */ /* IN, OUT: C extensions mask */ /* IN: brace level */ /* IN: parenthesis level */ /* OUT: function or variable found */ { /* When structdef is stagseen, scolonseen, or snone with bracelev > 0, structtype is the type of the preceding struct-like keyword, and structbracelev is the brace level where it has been seen. */ static enum sym_type structtype; static int structbracelev; static enum sym_type toktype; toktype = C_symtype (str, len, *c_extp); /* * Skip __attribute__ */ if (toktype == st_C_attribute) { inattribute = true; return false; } /* * Skip ENUM_BF */ if (toktype == st_C_enum_bf && definedef == dnone) { in_enum_bf = true; return false; } /* * Advance the definedef state machine. */ switch (definedef) { case dnone: /* We're not on a preprocessor line. */ if (toktype == st_C_gnumacro) { fvdef = fdefunkey; return false; } break; case dsharpseen: if (toktype == st_C_define) { definedef = ddefineseen; } else { definedef = dignorerest; } return false; case ddefineseen: /* * Make a tag for any macro, unless it is a constant * and constantypedefs is false. */ definedef = dignorerest; *is_func_or_var = (c == '('); if (!*is_func_or_var && !constantypedefs) return false; else return true; case dignorerest: return false; default: error ("internal error: definedef value."); } /* * Now typedefs */ switch (typdef) { case tnone: if (toktype == st_C_typedef) { if (typedefs) typdef = tkeyseen; fvextern = false; fvdef = fvnone; return false; } break; case tkeyseen: switch (toktype) { case st_none: case st_C_class: case st_C_struct: case st_C_enum: typdef = ttypeseen; break; default: break; } break; case ttypeseen: if (structdef == snone && fvdef == fvnone) { fvdef = fvnameseen; return true; } break; case tend: switch (toktype) { case st_C_class: case st_C_struct: case st_C_enum: return false; default: return true; } default: break; } switch (toktype) { case st_C_javastruct: if (structdef == stagseen) structdef = scolonseen; return false; case st_C_template: case st_C_class: if ((*c_extp & C_AUTO) /* automatic detection of C++ language */ && bracelev == 0 && definedef == dnone && structdef == snone && typdef == tnone && fvdef == fvnone) *c_extp = (*c_extp | C_PLPL) & ~C_AUTO; if (toktype == st_C_template) break; FALLTHROUGH; case st_C_struct: case st_C_enum: if (parlev == 0 && fvdef != vignore && (typdef == tkeyseen || (typedefs_or_cplusplus && structdef == snone))) { structdef = skeyseen; structtype = toktype; structbracelev = bracelev; if (fvdef == fvnameseen) fvdef = fvnone; } return false; default: break; } if (structdef == skeyseen) { structdef = stagseen; return true; } if (typdef != tnone) definedef = dnone; /* Detect Objective C constructs. */ switch (objdef) { case onone: switch (toktype) { case st_C_objprot: objdef = oprotocol; return false; case st_C_objimpl: objdef = oimplementation; return false; default: break; } break; case oimplementation: /* Save the class tag for functions or variables defined inside. */ objtag = savenstr (str, len); objdef = oinbody; return false; case oprotocol: /* Save the class tag for categories. */ objtag = savenstr (str, len); objdef = otagseen; *is_func_or_var = true; return true; case oparenseen: objdef = ocatseen; *is_func_or_var = true; return true; case oinbody: break; case omethodsign: if (parlev == 0) { fvdef = fvnone; objdef = omethodtag; linebuffer_setlen (&token_name, len); memcpy (token_name.buffer, str, len); token_name.buffer[len] = '\0'; return true; } return false; case omethodcolon: if (parlev == 0) objdef = omethodparm; return false; case omethodparm: if (parlev == 0) { objdef = omethodtag; if (class_qualify) { int oldlen = token_name.len; fvdef = fvnone; linebuffer_setlen (&token_name, oldlen + len); memcpy (token_name.buffer + oldlen, str, len); token_name.buffer[oldlen + len] = '\0'; } return true; } return false; case oignore: if (toktype == st_C_objend) { /* Memory leakage here: the string pointed by objtag is never released, because many tests would be needed to avoid breaking on incorrect input code. The amount of memory leaked here is the sum of the lengths of the class tags. free (objtag); */ objdef = onone; } return false; default: break; } /* A function, variable or enum constant? */ switch (toktype) { case st_C_extern: fvextern = true; switch (fvdef) { case finlist: case flistseen: case fignore: case vignore: break; default: fvdef = fvnone; } return false; case st_C_ignore: fvextern = false; fvdef = vignore; return false; case st_C_operator: fvdef = foperator; *is_func_or_var = true; return true; case st_none: if (constantypedefs && structdef == snone && structtype == st_C_enum && bracelev > structbracelev /* Don't tag tokens in expressions that assign values to enum constants. */ && fvdef != vignore) return true; /* enum constant */ switch (fvdef) { case fdefunkey: if (bracelev > 0) break; fvdef = fdefunname; /* GNU macro */ *is_func_or_var = true; return true; case fvnone: switch (typdef) { case ttypeseen: return false; case tnone: if ((strneq (str, "asm", 3) && endtoken (str[3])) || (strneq (str, "__asm__", 7) && endtoken (str[7]))) { fvdef = vignore; return false; } break; default: break; } FALLTHROUGH; case fvnameseen: if (len >= 10 && strneq (str+len-10, "::operator", 10)) { if (*c_extp & C_AUTO) /* automatic detection of C++ */ *c_extp = (*c_extp | C_PLPL) & ~C_AUTO; fvdef = foperator; *is_func_or_var = true; return true; } if (bracelev > 0 && !instruct) break; fvdef = fvnameseen; /* function or variable */ *is_func_or_var = true; return true; default: break; } break; default: break; } return false; } /* * C_entries often keeps pointers to tokens or lines which are older than * the line currently read. By keeping two line buffers, and switching * them at end of line, it is possible to use those pointers. */ static struct { long linepos; linebuffer lb; } lbs[2]; #define current_lb_is_new (newndx == curndx) #define switch_line_buffers() (curndx = 1 - curndx) #define curlb (lbs[curndx].lb) #define newlb (lbs[newndx].lb) #define curlinepos (lbs[curndx].linepos) #define newlinepos (lbs[newndx].linepos) #define plainc ((c_ext & C_EXT) == C_PLAIN) #define cplpl (c_ext & C_PLPL) #define cjava ((c_ext & C_JAVA) == C_JAVA) #define CNL_SAVE_DEFINEDEF() \ do { \ curlinepos = charno; \ readline (&curlb, inf); \ lp = curlb.buffer; \ quotednl = false; \ newndx = curndx; \ } while (0) #define CNL() \ do { \ CNL_SAVE_DEFINEDEF (); \ if (savetoken.valid) \ { \ token = savetoken; \ savetoken.valid = false; \ } \ definedef = dnone; \ } while (0) static void make_C_tag (bool isfun) { /* This function is never called when token.valid is false, but we must protect against invalid input or internal errors. */ if (token.valid) make_tag (token_name.buffer, token_name.len, isfun, token.line, token.offset+token.length+1, token.lineno, token.linepos); else if (DEBUG) { /* this branch is optimized away if !DEBUG */ make_tag (concat ("INVALID TOKEN:-->", token_name.buffer, ""), token_name.len + 17, isfun, token.line, token.offset+token.length+1, token.lineno, token.linepos); error ("INVALID TOKEN"); } token.valid = false; } static bool perhaps_more_input (FILE *inf) { return !feof (inf) && !ferror (inf); } /* * C_entries () * This routine finds functions, variables, typedefs, * #define's, enum constants and struct/union/enum definitions in * C syntax and adds them to the list. */ static void C_entries (int c_ext, FILE *inf) /* extension of C */ /* input file */ { register char c; /* latest char read; '\0' for end of line */ register char *lp; /* pointer one beyond the character `c' */ int curndx, newndx; /* indices for current and new lb */ register int tokoff; /* offset in line of start of current token */ register int toklen; /* length of current token */ const char *qualifier; /* string used to qualify names */ int qlen; /* length of qualifier */ int bracelev; /* current brace level */ int bracketlev; /* current bracket level */ int parlev; /* current parenthesis level */ int attrparlev; /* __attribute__ parenthesis level */ int templatelev; /* current template level */ int typdefbracelev; /* bracelev where a typedef struct body begun */ bool incomm, inquote, inchar, quotednl, midtoken; bool yacc_rules; /* in the rules part of a yacc file */ struct tok savetoken = {0}; /* token saved during preprocessor handling */ linebuffer_init (&lbs[0].lb); linebuffer_init (&lbs[1].lb); if (cstack.size == 0) { cstack.size = (DEBUG) ? 1 : 4; cstack.nl = 0; cstack.cname = xnew (cstack.size, char *); cstack.bracelev = xnew (cstack.size, int); } tokoff = toklen = typdefbracelev = 0; /* keep compiler quiet */ curndx = newndx = 0; lp = curlb.buffer; *lp = 0; fvdef = fvnone; fvextern = false; typdef = tnone; structdef = snone; definedef = dnone; objdef = onone; yacc_rules = false; midtoken = inquote = inchar = incomm = quotednl = false; token.valid = savetoken.valid = false; bracelev = bracketlev = parlev = attrparlev = templatelev = 0; if (cjava) { qualifier = "."; qlen = 1; } else { qualifier = "::"; qlen = 2; } while (perhaps_more_input (inf)) { c = *lp++; if (c == '\\') { /* If we are at the end of the line, the next character is a '\0'; do not skip it, because it is what tells us to read the next line. */ if (*lp == '\0') { quotednl = true; continue; } lp++; c = ' '; } else if (incomm) { switch (c) { case '*': if (*lp == '/') { c = *lp++; incomm = false; } break; case '\0': /* Newlines inside comments do not end macro definitions in traditional cpp. */ CNL_SAVE_DEFINEDEF (); break; } continue; } else if (inquote) { switch (c) { case '"': inquote = false; break; case '\0': /* Newlines inside strings do not end macro definitions in traditional cpp, even though compilers don't usually accept them. */ CNL_SAVE_DEFINEDEF (); break; } continue; } else if (inchar) { switch (c) { case '\0': /* Hmmm, something went wrong. */ CNL (); FALLTHROUGH; case '\'': inchar = false; break; } continue; } else switch (c) { case '"': inquote = true; if (bracketlev > 0) continue; if (inattribute) break; switch (fvdef) { case fdefunkey: case fstartlist: case finlist: case fignore: case vignore: break; default: fvextern = false; fvdef = fvnone; } continue; case '\'': inchar = true; if (bracketlev > 0) continue; if (inattribute) break; if (fvdef != finlist && fvdef != fignore && fvdef != vignore) { fvextern = false; fvdef = fvnone; } continue; case '/': if (*lp == '*') { incomm = true; lp++; c = ' '; if (bracketlev > 0) continue; } else if (/* cplpl && */ *lp == '/') { c = '\0'; } break; case '%': if ((c_ext & YACC) && *lp == '%') { /* Entering or exiting rules section in yacc file. */ lp++; definedef = dnone; fvdef = fvnone; fvextern = false; typdef = tnone; structdef = snone; midtoken = inquote = inchar = incomm = quotednl = false; bracelev = 0; yacc_rules = !yacc_rules; continue; } else break; case '#': if (definedef == dnone) { char *cp; bool cpptoken = true; /* Look back on this line. If all blanks, or nonblanks followed by an end of comment, this is a preprocessor token. */ for (cp = newlb.buffer; cp < lp-1; cp++) if (!c_isspace (*cp)) { if (*cp == '*' && cp[1] == '/') { cp++; cpptoken = true; } else cpptoken = false; } if (cpptoken) { definedef = dsharpseen; /* This is needed for tagging enum values: when there are preprocessor conditionals inside the enum, we need to reset the value of fvdef so that the next enum value is tagged even though the one before it did not end in a comma. */ if (fvdef == vignore && instruct && parlev == 0) { if (strneq (cp, "#if", 3) || strneq (cp, "#el", 3)) fvdef = fvnone; } } } /* if (definedef == dnone) */ continue; case '[': bracketlev++; continue; default: if (bracketlev > 0) { if (c == ']') --bracketlev; else if (c == '\0') CNL_SAVE_DEFINEDEF (); continue; } break; } /* switch (c) */ /* Consider token only if some involved conditions are satisfied. */ if (typdef != tignore && definedef != dignorerest && fvdef != finlist && templatelev == 0 && (definedef != dnone || structdef != scolonseen) && !inattribute && !in_enum_bf) { if (midtoken) { if (endtoken (c)) { if (c == ':' && *lp == ':' && begtoken (lp[1])) /* This handles :: in the middle, but not at the beginning of an identifier. Also, space-separated :: is not recognized. */ { if (c_ext & C_AUTO) /* automatic detection of C++ */ c_ext = (c_ext | C_PLPL) & ~C_AUTO; lp += 2; toklen += 2; c = lp[-1]; goto still_in_token; } else { bool funorvar = false; if (yacc_rules || consider_token (newlb.buffer + tokoff, toklen, c, &c_ext, bracelev, parlev, &funorvar)) { if (fvdef == foperator) { char *oldlp = lp; lp = skip_spaces (lp-1); if (*lp != '\0') lp += 1; while (*lp != '\0' && !c_isspace (*lp) && *lp != '(') lp += 1; c = *lp++; toklen += lp - oldlp; } token.named = false; if (!plainc && nestlev > 0 && definedef == dnone) /* in struct body */ { if (class_qualify) { int len; write_classname (&token_name, qualifier); len = token_name.len; linebuffer_setlen (&token_name, len + qlen + toklen); sprintf (token_name.buffer + len, "%s%.*s", qualifier, toklen, newlb.buffer + tokoff); } else { linebuffer_setlen (&token_name, toklen); sprintf (token_name.buffer, "%.*s", toklen, newlb.buffer + tokoff); } token.named = true; } else if (objdef == ocatseen) /* Objective C category */ { if (class_qualify) { int len = strlen (objtag) + 2 + toklen; linebuffer_setlen (&token_name, len); sprintf (token_name.buffer, "%s(%.*s)", objtag, toklen, newlb.buffer + tokoff); } else { linebuffer_setlen (&token_name, toklen); sprintf (token_name.buffer, "%.*s", toklen, newlb.buffer + tokoff); } token.named = true; } else if (objdef == omethodtag || objdef == omethodparm) /* Objective C method */ { token.named = true; } else if (fvdef == fdefunname) /* GNU DEFUN and similar macros */ { bool defun = (newlb.buffer[tokoff] == 'F'); int off = tokoff; int len = toklen; if (defun) { off += 1; len -= 1; /* First, tag it as its C name */ linebuffer_setlen (&token_name, toklen); memcpy (token_name.buffer, newlb.buffer + tokoff, toklen); token_name.buffer[toklen] = '\0'; token.named = true; token.lineno = lineno; token.offset = tokoff; token.length = toklen; token.line = newlb.buffer; token.linepos = newlinepos; token.valid = true; make_C_tag (funorvar); } /* Rewrite the tag so that emacs lisp DEFUNs can be found also by their elisp name */ linebuffer_setlen (&token_name, len); memcpy (token_name.buffer, newlb.buffer + off, len); token_name.buffer[len] = '\0'; if (defun) while (--len >= 0) if (token_name.buffer[len] == '_') token_name.buffer[len] = '-'; token.named = defun; } else { linebuffer_setlen (&token_name, toklen); memcpy (token_name.buffer, newlb.buffer + tokoff, toklen); token_name.buffer[toklen] = '\0'; /* Name macros and members. */ token.named = (structdef == stagseen || typdef == ttypeseen || typdef == tend || (funorvar && definedef == dignorerest) || (funorvar && definedef == dnone && structdef == snone && bracelev > 0)); } token.lineno = lineno; token.offset = tokoff; token.length = toklen; token.line = newlb.buffer; token.linepos = newlinepos; token.valid = true; if (definedef == dnone && (fvdef == fvnameseen || fvdef == foperator || structdef == stagseen || typdef == tend || typdef == ttypeseen || objdef != onone)) { if (current_lb_is_new) switch_line_buffers (); } else if (definedef != dnone || fvdef == fdefunname || instruct) make_C_tag (funorvar); } else /* not yacc and consider_token failed */ { if (inattribute && fvdef == fignore) { /* We have just met __attribute__ after a function parameter list: do not tag the function again. */ fvdef = fvnone; } } midtoken = false; } } /* if (endtoken (c)) */ else if (intoken (c)) still_in_token: { toklen++; continue; } } /* if (midtoken) */ else if (begtoken (c)) { switch (definedef) { case dnone: switch (fvdef) { case fstartlist: /* This prevents tagging fb in void (__attribute__((noreturn)) *fb) (void); Fixing this is not easy and not very important. */ fvdef = finlist; continue; case flistseen: if (plainc || declarations) { make_C_tag (true); /* a function */ fvdef = fignore; } break; default: break; } if (structdef == stagseen && !cjava) { popclass_above (bracelev); structdef = snone; } break; case dsharpseen: savetoken = token; break; default: break; } if (!yacc_rules || lp == newlb.buffer + 1) { tokoff = lp - 1 - newlb.buffer; toklen = 1; midtoken = true; } continue; } /* if (begtoken) */ } /* if must look at token */ /* Detect end of line, colon, comma, semicolon and various braces after having handled a token.*/ switch (c) { case ':': if (inattribute) break; if (yacc_rules && token.offset == 0 && token.valid) { make_C_tag (false); /* a yacc function */ break; } if (definedef != dnone) break; switch (objdef) { case otagseen: objdef = oignore; make_C_tag (true); /* an Objective C class */ break; case omethodtag: case omethodparm: objdef = omethodcolon; if (class_qualify) { int toklen = token_name.len; linebuffer_setlen (&token_name, toklen + 1); strcpy (token_name.buffer + toklen, ":"); } break; default: break; } if (structdef == stagseen) { structdef = scolonseen; break; } /* Should be useless, but may be work as a safety net. */ if (cplpl && fvdef == flistseen) { make_C_tag (true); /* a function */ fvdef = fignore; break; } break; case ';': if (definedef != dnone || inattribute) break; switch (typdef) { case tend: case ttypeseen: make_C_tag (false); /* a typedef */ typdef = tnone; fvdef = fvnone; break; case tnone: case tinbody: case tignore: switch (fvdef) { case fignore: if (typdef == tignore || cplpl) fvdef = fvnone; break; case fvnameseen: if ((globals && bracelev == 0 && (!fvextern || declarations)) || (members && instruct)) make_C_tag (false); /* a variable */ fvextern = false; fvdef = fvnone; token.valid = false; break; case flistseen: if ((declarations && (cplpl || !instruct) && (typdef == tnone || (typdef != tignore && instruct))) || (members && plainc && instruct)) make_C_tag (true); /* a function */ FALLTHROUGH; default: fvextern = false; fvdef = fvnone; if (declarations && cplpl && structdef == stagseen) make_C_tag (false); /* forward declaration */ else token.valid = false; } /* switch (fvdef) */ FALLTHROUGH; default: if (!instruct) typdef = tnone; } if (structdef == stagseen) structdef = snone; break; case ',': if (definedef != dnone || inattribute) break; switch (objdef) { case omethodtag: case omethodparm: make_C_tag (true); /* an Objective C method */ objdef = oinbody; break; default: break; } switch (fvdef) { case fdefunkey: case foperator: case fstartlist: case finlist: case fignore: break; case vignore: if (instruct && parlev == 0) fvdef = fvnone; break; case fdefunname: fvdef = fignore; break; case fvnameseen: if (parlev == 0 && ((globals && bracelev == 0 && templatelev == 0 && (!fvextern || declarations)) || (members && instruct))) make_C_tag (false); /* a variable */ break; case flistseen: if ((declarations && typdef == tnone && !instruct) || (members && typdef != tignore && instruct)) { make_C_tag (true); /* a function */ fvdef = fvnameseen; } else if (!declarations) fvdef = fvnone; token.valid = false; break; default: fvdef = fvnone; } if (structdef == stagseen) structdef = snone; break; case ']': if (definedef != dnone || inattribute) break; if (structdef == stagseen) structdef = snone; switch (typdef) { case ttypeseen: case tend: typdef = tignore; make_C_tag (false); /* a typedef */ break; case tnone: case tinbody: switch (fvdef) { case foperator: case finlist: case fignore: case vignore: break; case fvnameseen: if ((members && bracelev == 1) || (globals && bracelev == 0 && (!fvextern || declarations))) make_C_tag (false); /* a variable */ FALLTHROUGH; default: fvdef = fvnone; } break; default: break; } break; case '(': if (inattribute) { attrparlev++; break; } if (definedef != dnone) break; if (objdef == otagseen && parlev == 0) objdef = oparenseen; switch (fvdef) { case fvnameseen: if (typdef == ttypeseen && *lp != '*' && !instruct) { /* This handles constructs like: typedef void OperatorFun (int fun); */ make_C_tag (false); typdef = tignore; fvdef = fignore; break; } FALLTHROUGH; case foperator: fvdef = fstartlist; break; case flistseen: fvdef = finlist; break; default: break; } parlev++; break; case ')': if (inattribute) { if (--attrparlev == 0) inattribute = false; break; } if (in_enum_bf) { if (--parlev == 0) in_enum_bf = false; break; } if (definedef != dnone) break; if (objdef == ocatseen && parlev == 1) { make_C_tag (true); /* an Objective C category */ objdef = oignore; } if (--parlev == 0) { switch (fvdef) { case fstartlist: case finlist: fvdef = flistseen; break; default: break; } if (!instruct && (typdef == tend || typdef == ttypeseen)) { typdef = tignore; make_C_tag (false); /* a typedef */ } } else if (parlev < 0) /* can happen due to ill-conceived #if's. */ parlev = 0; break; case '{': if (definedef != dnone) break; if (typdef == ttypeseen) { /* Whenever typdef is set to tinbody (currently only here), typdefbracelev should be set to bracelev. */ typdef = tinbody; typdefbracelev = bracelev; } switch (fvdef) { case flistseen: if (cplpl && !class_qualify) { /* Remove class and namespace qualifiers from the token, leaving only the method/member name. */ char *cc, *uqname = token_name.buffer; char *tok_end = token_name.buffer + token_name.len; for (cc = token_name.buffer; cc < tok_end; cc++) { if (*cc == ':' && cc[1] == ':') { uqname = cc + 2; cc++; } } if (uqname > token_name.buffer) { int uqlen = strlen (uqname); linebuffer_setlen (&token_name, uqlen); memmove (token_name.buffer, uqname, uqlen + 1); } } make_C_tag (true); /* a function */ FALLTHROUGH; case fignore: fvdef = fvnone; break; case fvnone: switch (objdef) { case otagseen: make_C_tag (true); /* an Objective C class */ objdef = oignore; break; case omethodtag: case omethodparm: make_C_tag (true); /* an Objective C method */ objdef = oinbody; break; default: /* Neutralize `extern "C" {' grot. */ if (bracelev == 0 && structdef == snone && nestlev == 0 && typdef == tnone) bracelev = -1; } break; default: break; } switch (structdef) { case skeyseen: /* unnamed struct */ pushclass_above (bracelev, NULL, 0); structdef = snone; break; case stagseen: /* named struct or enum */ case scolonseen: /* a class */ pushclass_above (bracelev,token.line+token.offset, token.length); structdef = snone; make_C_tag (false); /* a struct or enum */ break; default: break; } bracelev += 1; break; case '*': if (definedef != dnone) break; if (fvdef == fstartlist) { fvdef = fvnone; /* avoid tagging `foo' in `foo (*bar()) ()' */ token.valid = false; } break; case '}': if (definedef != dnone) break; bracelev -= 1; if (!ignoreindent && lp == newlb.buffer + 1) { if (bracelev != 0) token.valid = false; /* unexpected value, token unreliable */ bracelev = 0; /* reset brace level if first column */ parlev = 0; /* also reset paren level, just in case... */ } else if (bracelev < 0) { token.valid = false; /* something gone amiss, token unreliable */ bracelev = 0; } if (bracelev == 0 && fvdef == vignore) fvdef = fvnone; /* end of function */ popclass_above (bracelev); structdef = snone; /* Only if typdef == tinbody is typdefbracelev significant. */ if (typdef == tinbody && bracelev <= typdefbracelev) { assert (bracelev == typdefbracelev); typdef = tend; } break; case '=': if (definedef != dnone) break; switch (fvdef) { case foperator: case finlist: case fignore: case vignore: break; case fvnameseen: if ((members && bracelev == 1) || (globals && bracelev == 0 && (!fvextern || declarations))) make_C_tag (false); /* a variable */ FALLTHROUGH; default: fvdef = vignore; } break; case '<': if (cplpl && (structdef == stagseen || fvdef == fvnameseen)) { templatelev++; break; } goto resetfvdef; case '>': if (templatelev > 0) { templatelev--; break; } goto resetfvdef; case '+': case '-': if (objdef == oinbody && bracelev == 0) { objdef = omethodsign; break; } FALLTHROUGH; resetfvdef: case '#': case '~': case '&': case '%': case '/': case '|': case '^': case '!': case '.': case '?': if (definedef != dnone) break; /* These surely cannot follow a function tag in C. */ switch (fvdef) { case foperator: case finlist: case fignore: case vignore: break; default: fvdef = fvnone; } break; case '\0': if (objdef == otagseen) { make_C_tag (true); /* an Objective C class */ objdef = oignore; } /* If a macro spans multiple lines don't reset its state. */ if (quotednl) CNL_SAVE_DEFINEDEF (); else CNL (); break; } /* switch (c) */ } /* while not eof */ free (lbs[0].lb.buffer); free (lbs[1].lb.buffer); } /* * Process either a C++ file or a C file depending on the setting * of a global flag. */ static void default_C_entries (FILE *inf) { C_entries (cplusplus ? C_PLPL : C_AUTO, inf); } /* Always do plain C. */ static void plain_C_entries (FILE *inf) { C_entries (0, inf); } /* Always do C++. */ static void Cplusplus_entries (FILE *inf) { C_entries (C_PLPL, inf); } /* Always do Java. */ static void Cjava_entries (FILE *inf) { C_entries (C_JAVA, inf); } /* Always do C*. */ static void Cstar_entries (FILE *inf) { C_entries (C_STAR, inf); } /* Always do Yacc. */ static void Yacc_entries (FILE *inf) { C_entries (YACC, inf); } /* Useful macros. */ #define LOOP_ON_INPUT_LINES(file_pointer, line_buffer, char_pointer) \ while (perhaps_more_input (file_pointer) \ && (readline (&(line_buffer), file_pointer), \ (char_pointer) = (line_buffer).buffer, \ true)) \ #define LOOKING_AT(cp, kw) /* kw is the keyword, a literal string */ \ ((assert ("" kw), true) /* syntax error if not a literal string */ \ && strneq ((cp), kw, sizeof (kw)-1) /* cp points at kw */ \ && notinname ((cp)[sizeof (kw)-1]) /* end of kw */ \ && ((cp) = skip_spaces ((cp) + sizeof (kw) - 1), true)) /* skip spaces */ /* Similar to LOOKING_AT but does not use notinname, does not skip */ #define LOOKING_AT_NOCASE(cp, kw) /* the keyword is a literal string */ \ ((assert ("" kw), true) /* syntax error if not a literal string */ \ && strncaseeq ((cp), kw, sizeof (kw)-1) /* cp points at kw */ \ && ((cp) += sizeof (kw) - 1, true)) /* skip spaces */ /* * Read a file, but do no processing. This is used to do regexp * matching on files that have no language defined. */ static void just_read_file (FILE *inf) { while (perhaps_more_input (inf)) readline (&lb, inf); } /* Fortran parsing */ static void F_takeprec (void); static void F_getit (FILE *); static void F_takeprec (void) { dbp = skip_spaces (dbp); if (*dbp != '*') return; dbp++; dbp = skip_spaces (dbp); if (strneq (dbp, "(*)", 3)) { dbp += 3; return; } if (!c_isdigit (*dbp)) { --dbp; /* force failure */ return; } do dbp++; while (c_isdigit (*dbp)); } static void F_getit (FILE *inf) { register char *cp; dbp = skip_spaces (dbp); if (*dbp == '\0') { readline (&lb, inf); dbp = lb.buffer; if (dbp[5] != '&') return; dbp += 6; dbp = skip_spaces (dbp); } if (!c_isalpha (*dbp) && *dbp != '_' && *dbp != '$') return; for (cp = dbp + 1; *cp != '\0' && intoken (*cp); cp++) continue; make_tag (dbp, cp-dbp, true, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); } static void Fortran_functions (FILE *inf) { LOOP_ON_INPUT_LINES (inf, lb, dbp) { if (*dbp == '%') dbp++; /* Ratfor escape to fortran */ dbp = skip_spaces (dbp); if (*dbp == '\0') continue; if (LOOKING_AT_NOCASE (dbp, "recursive")) dbp = skip_spaces (dbp); if (LOOKING_AT_NOCASE (dbp, "pure")) dbp = skip_spaces (dbp); if (LOOKING_AT_NOCASE (dbp, "elemental")) dbp = skip_spaces (dbp); switch (c_tolower (*dbp)) { case 'i': if (nocase_tail ("integer")) F_takeprec (); break; case 'r': if (nocase_tail ("real")) F_takeprec (); break; case 'l': if (nocase_tail ("logical")) F_takeprec (); break; case 'c': if (nocase_tail ("complex") || nocase_tail ("character")) F_takeprec (); break; case 'd': if (nocase_tail ("double")) { dbp = skip_spaces (dbp); if (*dbp == '\0') continue; if (nocase_tail ("precision")) break; continue; } break; } dbp = skip_spaces (dbp); if (*dbp == '\0') continue; switch (c_tolower (*dbp)) { case 'f': if (nocase_tail ("function")) F_getit (inf); continue; case 's': if (nocase_tail ("subroutine")) F_getit (inf); continue; case 'e': if (nocase_tail ("entry")) F_getit (inf); continue; case 'b': if (nocase_tail ("blockdata") || nocase_tail ("block data")) { dbp = skip_spaces (dbp); if (*dbp == '\0') /* assume un-named */ make_tag ("blockdata", 9, true, lb.buffer, dbp - lb.buffer, lineno, linecharno); else F_getit (inf); /* look for name */ } continue; } } } /* * Go language support * Original code by Xi Lu <lx@shellcodes.org> (2016) */ static void Go_functions(FILE *inf) { char *cp, *name; LOOP_ON_INPUT_LINES(inf, lb, cp) { cp = skip_spaces (cp); if (LOOKING_AT (cp, "package")) { name = cp; while (!notinname (*cp) && *cp != '\0') cp++; make_tag (name, cp - name, false, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); } else if (LOOKING_AT (cp, "func")) { /* Go implementation of interface, such as: func (n *Integer) Add(m Integer) ... skip `(n *Integer)` part. */ if (*cp == '(') { while (*cp != ')') cp++; cp = skip_spaces (cp+1); } if (*cp) { name = cp; while (!notinname (*cp)) cp++; make_tag (name, cp - name, true, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); } } else if (members && LOOKING_AT (cp, "type")) { name = cp; /* Ignore the likes of the following: type ( A ) */ if (*cp == '(') return; while (!notinname (*cp) && *cp != '\0') cp++; make_tag (name, cp - name, false, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); } } } /* * Ada parsing * Original code by * Philippe Waroquiers (1998) */ /* Once we are positioned after an "interesting" keyword, let's get the real tag value necessary. */ static void Ada_getit (FILE *inf, const char *name_qualifier) { register char *cp; char *name; char c; while (perhaps_more_input (inf)) { dbp = skip_spaces (dbp); if (*dbp == '\0' || (dbp[0] == '-' && dbp[1] == '-')) { readline (&lb, inf); dbp = lb.buffer; } switch (c_tolower (*dbp)) { case 'b': if (nocase_tail ("body")) { /* Skipping body of procedure body or package body or .... resetting qualifier to body instead of spec. */ name_qualifier = "/b"; continue; } break; case 't': /* Skipping type of task type or protected type ... */ if (nocase_tail ("type")) continue; break; } if (*dbp == '"') { dbp += 1; for (cp = dbp; *cp != '\0' && *cp != '"'; cp++) continue; } else { dbp = skip_spaces (dbp); for (cp = dbp; c_isalnum (*cp) || *cp == '_' || *cp == '.'; cp++) continue; if (cp == dbp) return; } c = *cp; *cp = '\0'; name = concat (dbp, name_qualifier, ""); *cp = c; make_tag (name, strlen (name), true, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); free (name); if (c == '"') dbp = cp + 1; return; } } static void Ada_funcs (FILE *inf) { bool inquote = false; bool skip_till_semicolumn = false; LOOP_ON_INPUT_LINES (inf, lb, dbp) { while (*dbp != '\0') { /* Skip a string i.e. "abcd". */ if (inquote || (*dbp == '"')) { dbp = strchr (dbp + !inquote, '"'); if (dbp != NULL) { inquote = false; dbp += 1; continue; /* advance char */ } else { inquote = true; break; /* advance line */ } } /* Skip comments. */ if (dbp[0] == '-' && dbp[1] == '-') break; /* advance line */ /* Skip character enclosed in single quote i.e. 'a' and skip single quote starting an attribute i.e. 'Image. */ if (*dbp == '\'') { dbp++ ; if (*dbp != '\0') dbp++; continue; } if (skip_till_semicolumn) { if (*dbp == ';') skip_till_semicolumn = false; dbp++; continue; /* advance char */ } /* Search for beginning of a token. */ if (!begtoken (*dbp)) { dbp++; continue; /* advance char */ } /* We are at the beginning of a token. */ switch (c_tolower (*dbp)) { case 'f': if (!packages_only && nocase_tail ("function")) Ada_getit (inf, "/f"); else break; /* from switch */ continue; /* advance char */ case 'p': if (!packages_only && nocase_tail ("procedure")) Ada_getit (inf, "/p"); else if (nocase_tail ("package")) Ada_getit (inf, "/s"); else if (nocase_tail ("protected")) /* protected type */ Ada_getit (inf, "/t"); else break; /* from switch */ continue; /* advance char */ case 'u': if (typedefs && !packages_only && nocase_tail ("use")) { /* when tagging types, avoid tagging use type Pack.Typename; for this, we will skip everything till a ; */ skip_till_semicolumn = true; continue; /* advance char */ } case 't': if (!packages_only && nocase_tail ("task")) Ada_getit (inf, "/k"); else if (typedefs && !packages_only && nocase_tail ("type")) { Ada_getit (inf, "/t"); while (*dbp != '\0') dbp += 1; } else break; /* from switch */ continue; /* advance char */ } /* Look for the end of the token. */ while (!endtoken (*dbp)) dbp++; } /* advance char */ } /* advance line */ } /* * Unix and microcontroller assembly tag handling * Labels: /^[a-zA-Z_.$][a-zA_Z0-9_.$]*[: ^I^J]/ * Idea by Bob Weiner, Motorola Inc. (1994) */ static void Asm_labels (FILE *inf) { register char *cp; LOOP_ON_INPUT_LINES (inf, lb, cp) { /* If first char is alphabetic or one of [_.$], test for colon following identifier. */ if (c_isalpha (*cp) || *cp == '_' || *cp == '.' || *cp == '$') { /* Read past label. */ cp++; while (c_isalnum (*cp) || *cp == '_' || *cp == '.' || *cp == '$') cp++; if (*cp == ':' || c_isspace (*cp)) /* Found end of label, so copy it and add it to the table. */ make_tag (lb.buffer, cp - lb.buffer, true, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); } } } /* * Perl support * Perl sub names: /^sub[ \t\n]+[^ \t\n{]+/ * /^use constant[ \t\n]+[^ \t\n{=,;]+/ * Perl variable names: /^(my|local).../ * Original code by Bart Robinson <lomew@cs.utah.edu> (1995) * Additions by Michael Ernst <mernst@alum.mit.edu> (1997) * Ideas by Kai Großjohann <Kai.Grossjohann@CS.Uni-Dortmund.DE> (2001) */ static void Perl_functions (FILE *inf) { char *package = savestr ("main"); /* current package name */ register char *cp; LOOP_ON_INPUT_LINES (inf, lb, cp) { cp = skip_spaces (cp); if (LOOKING_AT (cp, "package")) { free (package); get_tag (cp, &package); } else if (LOOKING_AT (cp, "sub")) { char *pos, *sp; subr: sp = cp; while (!notinname (*cp)) cp++; if (cp == sp) continue; /* nothing found */ pos = strchr (sp, ':'); if (pos && pos < cp && pos[1] == ':') { /* The name is already qualified. */ if (!class_qualify) { char *q = pos + 2, *qpos; while ((qpos = strchr (q, ':')) != NULL && qpos < cp && qpos[1] == ':') q = qpos + 2; sp = q; } make_tag (sp, cp - sp, true, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); } else if (class_qualify) /* Qualify it. */ { char savechar, *name; savechar = *cp; *cp = '\0'; name = concat (package, "::", sp); *cp = savechar; make_tag (name, strlen (name), true, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); free (name); } else make_tag (sp, cp - sp, true, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); } else if (LOOKING_AT (cp, "use constant") || LOOKING_AT (cp, "use constant::defer")) { /* For hash style multi-constant like use constant { FOO => 123, BAR => 456 }; only the first FOO is picked up. Parsing across the value expressions would be difficult in general, due to possible nested hashes, here-documents, etc. */ if (*cp == '{') cp = skip_spaces (cp+1); goto subr; } else if (globals) /* only if we are tagging global vars */ { /* Skip a qualifier, if any. */ bool qual = LOOKING_AT (cp, "my") || LOOKING_AT (cp, "local"); /* After "my" or "local", but before any following paren or space. */ char *varstart = cp; if (qual /* should this be removed? If yes, how? */ && (*cp == '$' || *cp == '@' || *cp == '%')) { varstart += 1; do cp++; while (c_isalnum (*cp) || *cp == '_'); } else if (qual) { /* Should be examining a variable list at this point; could insist on seeing an open parenthesis. */ while (*cp != '\0' && *cp != ';' && *cp != '=' && *cp != ')') cp++; } else continue; make_tag (varstart, cp - varstart, false, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); } } free (package); } /* * Python support * Look for /^[\t]*def[ \t\n]+[^ \t\n(:]+/ or /^class[ \t\n]+[^ \t\n(:]+/ * Idea by Eric S. Raymond <esr@thyrsus.com> (1997) * More ideas by seb bacon <seb@jamkit.com> (2002) */ static void Python_functions (FILE *inf) { register char *cp; LOOP_ON_INPUT_LINES (inf, lb, cp) { cp = skip_spaces (cp); if (LOOKING_AT (cp, "def") || LOOKING_AT (cp, "class")) { char *name = cp; while (!notinname (*cp) && *cp != ':') cp++; make_tag (name, cp - name, true, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); } } } /* * Ruby support * Original code by Xi Lu <lx@shellcodes.org> (2015) */ static void Ruby_functions (FILE *inf) { char *cp = NULL; bool reader = false, writer = false, alias = false, continuation = false; LOOP_ON_INPUT_LINES (inf, lb, cp) { bool is_class = false; bool is_method = false; char *name; cp = skip_spaces (cp); if (!continuation /* Constants. */ && c_isalpha (*cp) && c_isupper (*cp)) { char *bp, *colon = NULL; name = cp; for (cp++; c_isalnum (*cp) || *cp == '_' || *cp == ':'; cp++) { if (*cp == ':') colon = cp; } if (cp > name + 1) { bp = skip_spaces (cp); if (*bp == '=' && !(bp[1] == '=' || bp[1] == '>')) { if (colon && !c_isspace (colon[1])) name = colon + 1; make_tag (name, cp - name, false, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); } } } else if (!continuation /* Modules, classes, methods. */ && ((is_method = LOOKING_AT (cp, "def")) || (is_class = LOOKING_AT (cp, "class")) || LOOKING_AT (cp, "module"))) { const char self_name[] = "self."; const size_t self_size1 = sizeof (self_name) - 1; name = cp; /* Ruby method names can end in a '='. Also, operator overloading can define operators whose names include '='. */ while (!notinname (*cp) || *cp == '=') cp++; /* Remove "self." from the method name. */ if (cp - name > self_size1 && strneq (name, self_name, self_size1)) name += self_size1; /* Remove the class/module qualifiers from method names. */ if (is_method) { char *q; for (q = name; q < cp && *q != '.'; q++) ; if (q < cp - 1) /* punt if we see just "FOO." */ name = q + 1; } /* Don't tag singleton classes. */ if (is_class && strneq (name, "<<", 2) && cp == name + 2) continue; make_tag (name, cp - name, true, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); } else { /* Tag accessors and aliases. */ if (!continuation) reader = writer = alias = false; while (*cp && *cp != '#') { if (!continuation) { reader = writer = alias = false; if (LOOKING_AT (cp, "attr_reader")) reader = true; else if (LOOKING_AT (cp, "attr_writer")) writer = true; else if (LOOKING_AT (cp, "attr_accessor")) { reader = true; writer = true; } else if (LOOKING_AT (cp, "alias_method")) alias = true; } if (reader || writer || alias) { do { char *np; cp = skip_spaces (cp); if (*cp == '(') cp = skip_spaces (cp + 1); np = cp; cp = skip_name (cp); if (*np != ':') continue; np++; if (reader) { make_tag (np, cp - np, true, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); continuation = false; } if (writer) { size_t name_len = cp - np + 1; char *wr_name = xnew (name_len + 1, char); memcpy (wr_name, np, name_len - 1); memcpy (wr_name + name_len - 1, "=", 2); pfnote (wr_name, true, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); if (debug) fprintf (stderr, "%s on %s:%d: %s\n", wr_name, curfdp->taggedfname, lineno, lb.buffer); continuation = false; } if (alias) { if (!continuation) make_tag (np, cp - np, true, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); continuation = false; while (*cp && *cp != '#' && *cp != ';') { if (*cp == ',') continuation = true; else if (!c_isspace (*cp)) continuation = false; cp++; } if (*cp == ';') continuation = false; } cp = skip_spaces (cp); } while ((alias ? (*cp == ',') : (continuation = (*cp == ','))) && (cp = skip_spaces (cp + 1), *cp && *cp != '#')); } if (*cp != '#') cp = skip_name (cp); while (*cp && *cp != '#' && notinname (*cp)) cp++; } } } } /* * PHP support * Look for: * - /^[ \t]*function[ \t\n]+[^ \t\n(]+/ * - /^[ \t]*class[ \t\n]+[^ \t\n]+/ * - /^[ \t]*define\(\"[^\"]+/ * Only with --members: * - /^[ \t]*var[ \t\n]+\$[^ \t\n=;]/ * Idea by Diez B. Roggisch (2001) */ static void PHP_functions (FILE *inf) { char *cp, *name; bool search_identifier = false; LOOP_ON_INPUT_LINES (inf, lb, cp) { cp = skip_spaces (cp); name = cp; if (search_identifier && *cp != '\0') { while (!notinname (*cp)) cp++; make_tag (name, cp - name, true, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); search_identifier = false; } else if (LOOKING_AT (cp, "function")) { if (*cp == '&') cp = skip_spaces (cp+1); if (*cp != '\0') { name = cp; while (!notinname (*cp)) cp++; make_tag (name, cp - name, true, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); } else search_identifier = true; } else if (LOOKING_AT (cp, "class")) { if (*cp != '\0') { name = cp; while (*cp != '\0' && !c_isspace (*cp)) cp++; make_tag (name, cp - name, false, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); } else search_identifier = true; } else if (strneq (cp, "define", 6) && (cp = skip_spaces (cp+6)) && *cp++ == '(' && (*cp == '"' || *cp == '\'')) { char quote = *cp++; name = cp; while (*cp != quote && *cp != '\0') cp++; make_tag (name, cp - name, false, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); } else if (members && LOOKING_AT (cp, "var") && *cp == '$') { name = cp; while (!notinname (*cp)) cp++; make_tag (name, cp - name, false, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); } } } /* * Cobol tag functions * We could look for anything that could be a paragraph name. * i.e. anything that starts in column 8 is one word and ends in a full stop. * Idea by Corny de Souza (1993) */ static void Cobol_paragraphs (FILE *inf) { register char *bp, *ep; LOOP_ON_INPUT_LINES (inf, lb, bp) { if (lb.len < 9) continue; bp += 8; /* If eoln, compiler option or comment ignore whole line. */ if (bp[-1] != ' ' || !c_isalnum (bp[0])) continue; for (ep = bp; c_isalnum (*ep) || *ep == '-'; ep++) continue; if (*ep++ == '.') make_tag (bp, ep - bp, true, lb.buffer, ep - lb.buffer + 1, lineno, linecharno); } } /* * Makefile support * Ideas by Assar Westerlund <assar@sics.se> (2001) */ static void Makefile_targets (FILE *inf) { register char *bp; LOOP_ON_INPUT_LINES (inf, lb, bp) { if (*bp == '\t' || *bp == '#') continue; while (*bp != '\0' && *bp != '=' && *bp != ':') bp++; if (*bp == ':' || (globals && *bp == '=')) { /* We should detect if there is more than one tag, but we do not. We just skip initial and final spaces. */ char * namestart = skip_spaces (lb.buffer); while (--bp > namestart) if (!notinname (*bp)) break; make_tag (namestart, bp - namestart + 1, true, lb.buffer, bp - lb.buffer + 2, lineno, linecharno); } } } /* * Pascal parsing * Original code by Mosur K. Mohan (1989) * * Locates tags for procedures & functions. Doesn't do any type- or * var-definitions. It does look for the keyword "extern" or * "forward" immediately following the procedure statement; if found, * the tag is skipped. */ static void Pascal_functions (FILE *inf) { linebuffer tline; /* mostly copied from C_entries */ long save_lcno; int save_lineno, namelen, taglen; char c, *name; bool /* each of these flags is true if: */ incomment, /* point is inside a comment */ inquote, /* point is inside '..' string */ get_tagname, /* point is after PROCEDURE/FUNCTION keyword, so next item = potential tag */ found_tag, /* point is after a potential tag */ inparms, /* point is within parameter-list */ verify_tag; /* point has passed the parm-list, so the next token will determine whether this is a FORWARD/EXTERN to be ignored, or whether it is a real tag */ save_lcno = save_lineno = namelen = taglen = 0; /* keep compiler quiet */ name = NULL; /* keep compiler quiet */ dbp = lb.buffer; *dbp = '\0'; linebuffer_init (&tline); incomment = inquote = false; found_tag = false; /* have a proc name; check if extern */ get_tagname = false; /* found "procedure" keyword */ inparms = false; /* found '(' after "proc" */ verify_tag = false; /* check if "extern" is ahead */ while (perhaps_more_input (inf)) /* long main loop to get next char */ { c = *dbp++; if (c == '\0') /* if end of line */ { readline (&lb, inf); dbp = lb.buffer; if (*dbp == '\0') continue; if (!((found_tag && verify_tag) || get_tagname)) c = *dbp++; /* only if don't need *dbp pointing to the beginning of the name of the procedure or function */ } if (incomment) { if (c == '}') /* within { } comments */ incomment = false; else if (c == '*' && *dbp == ')') /* within (* *) comments */ { dbp++; incomment = false; } continue; } else if (inquote) { if (c == '\'') inquote = false; continue; } else switch (c) { case '\'': inquote = true; /* found first quote */ continue; case '{': /* found open { comment */ incomment = true; continue; case '(': if (*dbp == '*') /* found open (* comment */ { incomment = true; dbp++; } else if (found_tag) /* found '(' after tag, i.e., parm-list */ inparms = true; continue; case ')': /* end of parms list */ if (inparms) inparms = false; continue; case ';': if (found_tag && !inparms) /* end of proc or fn stmt */ { verify_tag = true; break; } continue; } if (found_tag && verify_tag && (*dbp != ' ')) { /* Check if this is an "extern" declaration. */ if (*dbp == '\0') continue; if (c_tolower (*dbp) == 'e') { if (nocase_tail ("extern")) /* superfluous, really! */ { found_tag = false; verify_tag = false; } } else if (c_tolower (*dbp) == 'f') { if (nocase_tail ("forward")) /* check for forward reference */ { found_tag = false; verify_tag = false; } } if (found_tag && verify_tag) /* not external proc, so make tag */ { found_tag = false; verify_tag = false; make_tag (name, namelen, true, tline.buffer, taglen, save_lineno, save_lcno); continue; } } if (get_tagname) /* grab name of proc or fn */ { char *cp; if (*dbp == '\0') continue; /* Find block name. */ for (cp = dbp + 1; *cp != '\0' && !endtoken (*cp); cp++) continue; /* Save all values for later tagging. */ linebuffer_setlen (&tline, lb.len); strcpy (tline.buffer, lb.buffer); save_lineno = lineno; save_lcno = linecharno; name = tline.buffer + (dbp - lb.buffer); namelen = cp - dbp; taglen = cp - lb.buffer + 1; dbp = cp; /* set dbp to e-o-token */ get_tagname = false; found_tag = true; continue; /* And proceed to check for "extern". */ } else if (!incomment && !inquote && !found_tag) { /* Check for proc/fn keywords. */ switch (c_tolower (c)) { case 'p': if (nocase_tail ("rocedure")) /* c = 'p', dbp has advanced */ get_tagname = true; continue; case 'f': if (nocase_tail ("unction")) get_tagname = true; continue; } } } /* while not eof */ free (tline.buffer); } /* * Lisp tag functions * look for (def or (DEF, quote or QUOTE */ static void L_getit (void); static void L_getit (void) { if (*dbp == '\'') /* Skip prefix quote */ dbp++; else if (*dbp == '(') { dbp++; /* Try to skip "(quote " */ if (!LOOKING_AT (dbp, "quote") && !LOOKING_AT (dbp, "QUOTE")) /* Ok, then skip "(" before name in (defstruct (foo)) */ dbp = skip_spaces (dbp); } get_lispy_tag (dbp); } static void Lisp_functions (FILE *inf) { LOOP_ON_INPUT_LINES (inf, lb, dbp) { if (dbp[0] != '(') continue; /* "(defvar foo)" is a declaration rather than a definition. */ if (! declarations) { char *p = dbp + 1; if (LOOKING_AT (p, "defvar")) { p = skip_name (p); /* past var name */ p = skip_spaces (p); if (*p == ')') continue; } } if (strneq (dbp + 1, "cl-", 3) || strneq (dbp + 1, "CL-", 3)) dbp += 3; if (strneq (dbp+1, "def", 3) || strneq (dbp+1, "DEF", 3)) { dbp = skip_non_spaces (dbp); dbp = skip_spaces (dbp); L_getit (); } else { /* Check for (foo::defmumble name-defined ... */ do dbp++; while (!notinname (*dbp) && *dbp != ':'); if (*dbp == ':') { do dbp++; while (*dbp == ':'); if (strneq (dbp, "def", 3) || strneq (dbp, "DEF", 3)) { dbp = skip_non_spaces (dbp); dbp = skip_spaces (dbp); L_getit (); } } } } } /* * Lua script language parsing * Original code by David A. Capello <dacap@users.sourceforge.net> (2004) * * "function" and "local function" are tags if they start at column 1. */ static void Lua_functions (FILE *inf) { register char *bp; LOOP_ON_INPUT_LINES (inf, lb, bp) { bp = skip_spaces (bp); if (bp[0] != 'f' && bp[0] != 'l') continue; (void)LOOKING_AT (bp, "local"); /* skip possible "local" */ if (LOOKING_AT (bp, "function")) { char *tag_name, *tp_dot, *tp_colon; get_tag (bp, &tag_name); /* If the tag ends with ".foo" or ":foo", make an additional tag for "foo". */ tp_dot = strrchr (tag_name, '.'); tp_colon = strrchr (tag_name, ':'); if (tp_dot || tp_colon) { char *p = tp_dot > tp_colon ? tp_dot : tp_colon; int len_add = p - tag_name + 1; get_tag (bp + len_add, NULL); } } } } /* * PostScript tags * Just look for lines where the first character is '/' * Also look at "defineps" for PSWrap * Ideas by: * Richard Mlynarik <mly@adoc.xerox.com> (1997) * Masatake Yamato <masata-y@is.aist-nara.ac.jp> (1999) */ static void PS_functions (FILE *inf) { register char *bp, *ep; LOOP_ON_INPUT_LINES (inf, lb, bp) { if (bp[0] == '/') { for (ep = bp+1; *ep != '\0' && *ep != ' ' && *ep != '{'; ep++) continue; make_tag (bp, ep - bp, true, lb.buffer, ep - lb.buffer + 1, lineno, linecharno); } else if (LOOKING_AT (bp, "defineps")) get_tag (bp, NULL); } } /* * Forth tags * Ignore anything after \ followed by space or in ( ) * Look for words defined by : * Look for constant, code, create, defer, value, and variable * OBP extensions: Look for buffer:, field, * Ideas by Eduardo Horvath <eeh@netbsd.org> (2004) */ static void Forth_words (FILE *inf) { register char *bp; LOOP_ON_INPUT_LINES (inf, lb, bp) while ((bp = skip_spaces (bp))[0] != '\0') if (bp[0] == '\\' && c_isspace (bp[1])) break; /* read next line */ else if (bp[0] == '(' && c_isspace (bp[1])) do /* skip to ) or eol */ bp++; while (*bp != ')' && *bp != '\0'); else if (((bp[0] == ':' && c_isspace (bp[1]) && bp++) || LOOKING_AT_NOCASE (bp, "constant") || LOOKING_AT_NOCASE (bp, "2constant") || LOOKING_AT_NOCASE (bp, "fconstant") || LOOKING_AT_NOCASE (bp, "code") || LOOKING_AT_NOCASE (bp, "create") || LOOKING_AT_NOCASE (bp, "defer") || LOOKING_AT_NOCASE (bp, "value") || LOOKING_AT_NOCASE (bp, "2value") || LOOKING_AT_NOCASE (bp, "fvalue") || LOOKING_AT_NOCASE (bp, "variable") || LOOKING_AT_NOCASE (bp, "2variable") || LOOKING_AT_NOCASE (bp, "fvariable") || LOOKING_AT_NOCASE (bp, "buffer:") || LOOKING_AT_NOCASE (bp, "field:") || LOOKING_AT_NOCASE (bp, "+field") || LOOKING_AT_NOCASE (bp, "field") /* not standard? */ || LOOKING_AT_NOCASE (bp, "begin-structure") || LOOKING_AT_NOCASE (bp, "synonym") ) && c_isspace (bp[0])) { /* Yay! A definition! */ char* name_start = skip_spaces (bp); char* name_end = skip_non_spaces (name_start); if (name_start < name_end) make_tag (name_start, name_end - name_start, true, lb.buffer, name_end - lb.buffer, lineno, linecharno); bp = name_end; } else bp = skip_non_spaces (bp); } /* * Scheme tag functions * look for (def... xyzzy * (def... (xyzzy * (def ... ((...(xyzzy .... * (set! xyzzy * Original code by Ken Haase (1985?) */ static void Scheme_functions (FILE *inf) { register char *bp; LOOP_ON_INPUT_LINES (inf, lb, bp) { if (strneq (bp, "(def", 4) || strneq (bp, "(DEF", 4)) { bp = skip_non_spaces (bp+4); /* Skip over open parens and white space. Don't continue past '\0' or '='. */ while (*bp && notinname (*bp) && *bp != '=') bp++; get_lispy_tag (bp); } if (LOOKING_AT (bp, "(SET!") || LOOKING_AT (bp, "(set!")) get_lispy_tag (bp); } } /* Find tags in TeX and LaTeX input files. */ /* TEX_toktab is a table of TeX control sequences that define tags. * Each entry records one such control sequence. * * Original code from who knows whom. * Ideas by: * Stefan Monnier (2002) */ static linebuffer *TEX_toktab = NULL; /* Table with tag tokens */ /* Default set of control sequences to put into TEX_toktab. The value of environment var TEXTAGS is prepended to this. */ static const char *TEX_defenv = "\ :chapter:section:subsection:subsubsection:eqno:label:ref:cite:bibitem\ :part:appendix:entry:index:def\ :newcommand:renewcommand:newenvironment:renewenvironment"; static void TEX_decode_env (const char *, const char *); /* * TeX/LaTeX scanning loop. */ static void TeX_commands (FILE *inf) { char *cp; linebuffer *key; char TEX_esc = '\0'; char TEX_opgrp UNINIT, TEX_clgrp UNINIT; /* Initialize token table once from environment. */ if (TEX_toktab == NULL) TEX_decode_env ("TEXTAGS", TEX_defenv); LOOP_ON_INPUT_LINES (inf, lb, cp) { /* Look at each TEX keyword in line. */ for (;;) { /* Look for a TEX escape. */ while (true) { char c = *cp++; if (c == '\0' || c == '%') goto tex_next_line; /* Select either \ or ! as escape character, whichever comes first outside a comment. */ if (!TEX_esc) switch (c) { case '\\': TEX_esc = c; TEX_opgrp = '{'; TEX_clgrp = '}'; break; case '!': TEX_esc = c; TEX_opgrp = '<'; TEX_clgrp = '>'; break; } if (c == TEX_esc) break; } for (key = TEX_toktab; key->buffer != NULL; key++) if (strneq (cp, key->buffer, key->len)) { char *p; int namelen, linelen; bool opgrp = false; cp = skip_spaces (cp + key->len); if (*cp == TEX_opgrp) { opgrp = true; cp++; } for (p = cp; (!c_isspace (*p) && *p != '#' && *p != TEX_opgrp && *p != TEX_clgrp); p++) continue; namelen = p - cp; linelen = lb.len; if (!opgrp || *p == TEX_clgrp) { while (*p != '\0' && *p != TEX_opgrp && *p != TEX_clgrp) p++; linelen = p - lb.buffer + 1; } make_tag (cp, namelen, true, lb.buffer, linelen, lineno, linecharno); goto tex_next_line; /* We only tag a line once */ } } tex_next_line: ; } } /* Read environment and prepend it to the default string. Build token table. */ static void TEX_decode_env (const char *evarname, const char *defenv) { register const char *env, *p; int i, len; /* Append default string to environment. */ env = getenv (evarname); if (!env) env = defenv; else env = concat (env, defenv, ""); /* Allocate a token table */ for (len = 1, p = env; (p = strchr (p, ':')); ) if (*++p) len++; TEX_toktab = xnew (len, linebuffer); /* Unpack environment string into token table. Be careful about */ /* zero-length strings (leading ':', "::" and trailing ':') */ for (i = 0; *env != '\0';) { p = strchr (env, ':'); if (!p) /* End of environment string. */ p = env + strlen (env); if (p - env > 0) { /* Only non-zero strings. */ TEX_toktab[i].buffer = savenstr (env, p - env); TEX_toktab[i].len = p - env; i++; } if (*p) env = p + 1; else { TEX_toktab[i].buffer = NULL; /* Mark end of table. */ TEX_toktab[i].len = 0; break; } } } /* Texinfo support. Dave Love, Mar. 2000. */ static void Texinfo_nodes (FILE *inf) { char *cp, *start; LOOP_ON_INPUT_LINES (inf, lb, cp) if (LOOKING_AT (cp, "@node")) { start = cp; while (*cp != '\0' && *cp != ',') cp++; make_tag (start, cp - start, true, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); } } /* * HTML support. * Contents of <title>, <h1>, <h2>, <h3> are tags. * Contents of <a name=xxx> are tags with name xxx. * * Francesco Potortì, 2002. */ static void HTML_labels (FILE *inf) { bool getnext = false; /* next text outside of HTML tags is a tag */ bool skiptag = false; /* skip to the end of the current HTML tag */ bool intag = false; /* inside an html tag, looking for ID= */ bool inanchor = false; /* when INTAG, is an anchor, look for NAME= */ char *end; linebuffer_setlen (&token_name, 0); /* no name in buffer */ LOOP_ON_INPUT_LINES (inf, lb, dbp) for (;;) /* loop on the same line */ { if (skiptag) /* skip HTML tag */ { while (*dbp != '\0' && *dbp != '>') dbp++; if (*dbp == '>') { dbp += 1; skiptag = false; continue; /* look on the same line */ } break; /* go to next line */ } else if (intag) /* look for "name=" or "id=" */ { while (*dbp != '\0' && *dbp != '>' && c_tolower (*dbp) != 'n' && c_tolower (*dbp) != 'i') dbp++; if (*dbp == '\0') break; /* go to next line */ if (*dbp == '>') { dbp += 1; intag = false; continue; /* look on the same line */ } if ((inanchor && LOOKING_AT_NOCASE (dbp, "name=")) || LOOKING_AT_NOCASE (dbp, "id=")) { bool quoted = (dbp[0] == '"'); if (quoted) for (end = ++dbp; *end != '\0' && *end != '"'; end++) continue; else for (end = dbp; *end != '\0' && intoken (*end); end++) continue; linebuffer_setlen (&token_name, end - dbp); memcpy (token_name.buffer, dbp, end - dbp); token_name.buffer[end - dbp] = '\0'; dbp = end; intag = false; /* we found what we looked for */ skiptag = true; /* skip to the end of the tag */ getnext = true; /* then grab the text */ continue; /* look on the same line */ } dbp += 1; } else if (getnext) /* grab next tokens and tag them */ { dbp = skip_spaces (dbp); if (*dbp == '\0') break; /* go to next line */ if (*dbp == '<') { intag = true; inanchor = (c_tolower (dbp[1]) == 'a' && !intoken (dbp[2])); continue; /* look on the same line */ } for (end = dbp + 1; *end != '\0' && *end != '<'; end++) continue; make_tag (token_name.buffer, token_name.len, true, dbp, end - dbp, lineno, linecharno); linebuffer_setlen (&token_name, 0); /* no name in buffer */ getnext = false; break; /* go to next line */ } else /* look for an interesting HTML tag */ { while (*dbp != '\0' && *dbp != '<') dbp++; if (*dbp == '\0') break; /* go to next line */ intag = true; if (c_tolower (dbp[1]) == 'a' && !intoken (dbp[2])) { inanchor = true; continue; /* look on the same line */ } else if (LOOKING_AT_NOCASE (dbp, "<title>") || LOOKING_AT_NOCASE (dbp, "<h1>") || LOOKING_AT_NOCASE (dbp, "<h2>") || LOOKING_AT_NOCASE (dbp, "<h3>")) { intag = false; getnext = true; continue; /* look on the same line */ } dbp += 1; } } } /* * Prolog support * * Assumes that the predicate or rule starts at column 0. * Only the first clause of a predicate or rule is added. * Original code by Sunichirou Sugou (1989) * Rewritten by Anders Lindgren (1996) */ static size_t prolog_pr (char *, char *); static void prolog_skip_comment (linebuffer *, FILE *); static size_t prolog_atom (char *, size_t); static void Prolog_functions (FILE *inf) { char *cp, *last; size_t len; size_t allocated; allocated = 0; len = 0; last = NULL; LOOP_ON_INPUT_LINES (inf, lb, cp) { if (cp[0] == '\0') /* Empty line */ continue; else if (c_isspace (cp[0])) /* Not a predicate */ continue; else if (cp[0] == '/' && cp[1] == '*') /* comment. */ prolog_skip_comment (&lb, inf); else if ((len = prolog_pr (cp, last)) > 0) { /* Predicate or rule. Store the function name so that we only generate a tag for the first clause. */ if (last == NULL) last = xnew (len + 1, char); else if (len + 1 > allocated) xrnew (last, len + 1, char); allocated = len + 1; memcpy (last, cp, len); last[len] = '\0'; } } free (last); } static void prolog_skip_comment (linebuffer *plb, FILE *inf) { char *cp; do { for (cp = plb->buffer; *cp != '\0'; cp++) if (cp[0] == '*' && cp[1] == '/') return; readline (plb, inf); } while (perhaps_more_input (inf)); } /* * A predicate or rule definition is added if it matches: * <beginning of line><Prolog Atom><whitespace>( * or <beginning of line><Prolog Atom><whitespace>:- * * It is added to the tags database if it doesn't match the * name of the previous clause header. * * Return the size of the name of the predicate or rule, or 0 if no * header was found. */ static size_t prolog_pr (char *s, char *last) /* Name of last clause. */ { size_t pos; size_t len; pos = prolog_atom (s, 0); if (! pos) return 0; len = pos; pos = skip_spaces (s + pos) - s; if ((s[pos] == '.' || (s[pos] == '(' && (pos += 1)) || (s[pos] == ':' && s[pos + 1] == '-' && (pos += 2))) && (last == NULL /* save only the first clause */ || len != strlen (last) || !strneq (s, last, len))) { make_tag (s, len, true, s, pos, lineno, linecharno); return len; } else return 0; } /* * Consume a Prolog atom. * Return the number of bytes consumed, or 0 if there was an error. * * A prolog atom, in this context, could be one of: * - An alphanumeric sequence, starting with a lower case letter. * - A quoted arbitrary string. Single quotes can escape themselves. * Backslash quotes everything. */ static size_t prolog_atom (char *s, size_t pos) { size_t origpos; origpos = pos; if (c_islower (s[pos]) || s[pos] == '_') { /* The atom is unquoted. */ pos++; while (c_isalnum (s[pos]) || s[pos] == '_') { pos++; } return pos - origpos; } else if (s[pos] == '\'') { pos++; for (;;) { if (s[pos] == '\'') { pos++; if (s[pos] != '\'') break; pos++; /* A double quote */ } else if (s[pos] == '\0') /* Multiline quoted atoms are ignored. */ return 0; else if (s[pos] == '\\') { if (s[pos+1] == '\0') return 0; pos += 2; } else pos++; } return pos - origpos; } else return 0; } /* * Support for Erlang * * Generates tags for functions, defines, and records. * Assumes that Erlang functions start at column 0. * Original code by Anders Lindgren (1996) */ static int erlang_func (char *, char *); static void erlang_attribute (char *); static int erlang_atom (char *); static void Erlang_functions (FILE *inf) { char *cp, *last; int len; int allocated; allocated = 0; len = 0; last = NULL; LOOP_ON_INPUT_LINES (inf, lb, cp) { if (cp[0] == '\0') /* Empty line */ continue; else if (c_isspace (cp[0])) /* Not function nor attribute */ continue; else if (cp[0] == '%') /* comment */ continue; else if (cp[0] == '"') /* Sometimes, strings start in column one */ continue; else if (cp[0] == '-') /* attribute, e.g. "-define" */ { erlang_attribute (cp); if (last != NULL) { free (last); last = NULL; } } else if ((len = erlang_func (cp, last)) > 0) { /* * Function. Store the function name so that we only * generates a tag for the first clause. */ if (last == NULL) last = xnew (len + 1, char); else if (len + 1 > allocated) xrnew (last, len + 1, char); allocated = len + 1; memcpy (last, cp, len); last[len] = '\0'; } } free (last); } /* * A function definition is added if it matches: * <beginning of line><Erlang Atom><whitespace>( * * It is added to the tags database if it doesn't match the * name of the previous clause header. * * Return the size of the name of the function, or 0 if no function * was found. */ static int erlang_func (char *s, char *last) /* Name of last clause. */ { int pos; int len; pos = erlang_atom (s); if (pos < 1) return 0; len = pos; pos = skip_spaces (s + pos) - s; /* Save only the first clause. */ if (s[pos++] == '(' && (last == NULL || len != (int)strlen (last) || !strneq (s, last, len))) { make_tag (s, len, true, s, pos, lineno, linecharno); return len; } return 0; } /* * Handle attributes. Currently, tags are generated for defines * and records. * * They are on the form: * -define(foo, bar). * -define(Foo(M, N), M+N). * -record(graph, {vtab = notable, cyclic = true}). */ static void erlang_attribute (char *s) { char *cp = s; if ((LOOKING_AT (cp, "-define") || LOOKING_AT (cp, "-record")) && *cp++ == '(') { int len = erlang_atom (skip_spaces (cp)); if (len > 0) make_tag (cp, len, true, s, cp + len - s, lineno, linecharno); } return; } /* * Consume an Erlang atom (or variable). * Return the number of bytes consumed, or -1 if there was an error. */ static int erlang_atom (char *s) { int pos = 0; if (c_isalpha (s[pos]) || s[pos] == '_') { /* The atom is unquoted. */ do pos++; while (c_isalnum (s[pos]) || s[pos] == '_'); } else if (s[pos] == '\'') { for (pos++; s[pos] != '\''; pos++) if (s[pos] == '\0' /* multiline quoted atoms are ignored */ || (s[pos] == '\\' && s[++pos] == '\0')) return 0; pos++; } return pos; } static char *scan_separators (char *); static void add_regex (char *, language *); static char *substitute (char *, char *, struct re_registers *); /* * Take a string like "/blah/" and turn it into "blah", verifying * that the first and last characters are the same, and handling * quoted separator characters. Actually, stops on the occurrence of * an unquoted separator. Also process \t, \n, etc. and turn into * appropriate characters. Works in place. Null terminates name string. * Returns pointer to terminating separator, or NULL for * unterminated regexps. */ static char * scan_separators (char *name) { char sep = name[0]; char *copyto = name; bool quoted = false; for (++name; *name != '\0'; ++name) { if (quoted) { switch (*name) { case 'a': *copyto++ = '\007'; break; /* BEL (bell) */ case 'b': *copyto++ = '\b'; break; /* BS (back space) */ case 'd': *copyto++ = 0177; break; /* DEL (delete) */ case 'e': *copyto++ = 033; break; /* ESC (delete) */ case 'f': *copyto++ = '\f'; break; /* FF (form feed) */ case 'n': *copyto++ = '\n'; break; /* NL (new line) */ case 'r': *copyto++ = '\r'; break; /* CR (carriage return) */ case 't': *copyto++ = '\t'; break; /* TAB (horizontal tab) */ case 'v': *copyto++ = '\v'; break; /* VT (vertical tab) */ default: if (*name == sep) *copyto++ = sep; else { /* Something else is quoted, so preserve the quote. */ *copyto++ = '\\'; *copyto++ = *name; } break; } quoted = false; } else if (*name == '\\') quoted = true; else if (*name == sep) break; else *copyto++ = *name; } if (*name != sep) name = NULL; /* signal unterminated regexp */ /* Terminate copied string. */ *copyto = '\0'; return name; } /* Look at the argument of --regex or --no-regex and do the right thing. Same for each line of a regexp file. */ static void analyze_regex (char *regex_arg) { if (regex_arg == NULL) { free_regexps (); /* --no-regex: remove existing regexps */ return; } /* A real --regexp option or a line in a regexp file. */ switch (regex_arg[0]) { /* Comments in regexp file or null arg to --regex. */ case '\0': case ' ': case '\t': break; /* Read a regex file. This is recursive and may result in a loop, which will stop when the file descriptors are exhausted. */ case '@': { FILE *regexfp; linebuffer regexbuf; char *regexfile = regex_arg + 1; /* regexfile is a file containing regexps, one per line. */ regexfp = fopen (regexfile, "r" FOPEN_BINARY); if (regexfp == NULL) pfatal (regexfile); linebuffer_init (&regexbuf); while (readline_internal (&regexbuf, regexfp, regexfile) > 0) analyze_regex (regexbuf.buffer); free (regexbuf.buffer); if (fclose (regexfp) != 0) pfatal (regexfile); } break; /* Regexp to be used for a specific language only. */ case '{': { language *lang; char *lang_name = regex_arg + 1; char *cp; for (cp = lang_name; *cp != '}'; cp++) if (*cp == '\0') { error ("unterminated language name in regex: %s", regex_arg); return; } *cp++ = '\0'; lang = get_language_from_langname (lang_name); if (lang == NULL) return; add_regex (cp, lang); } break; /* Regexp to be used for any language. */ default: add_regex (regex_arg, NULL); break; } } /* Separate the regexp pattern, compile it, and care for optional name and modifiers. */ static void add_regex (char *regexp_pattern, language *lang) { static struct re_pattern_buffer zeropattern; char sep, *pat, *name, *modifiers; char empty = '\0'; const char *err; struct re_pattern_buffer *patbuf; regexp *rp; bool force_explicit_name = true, /* do not use implicit tag names */ ignore_case = false, /* case is significant */ multi_line = false, /* matches are done one line at a time */ single_line = false; /* dot does not match newline */ if (strlen (regexp_pattern) < 3) { error ("null regexp"); return; } sep = regexp_pattern[0]; name = scan_separators (regexp_pattern); if (name == NULL) { error ("%s: unterminated regexp", regexp_pattern); return; } if (name[1] == sep) { error ("null name for regexp \"%s\"", regexp_pattern); return; } modifiers = scan_separators (name); if (modifiers == NULL) /* no terminating separator --> no name */ { modifiers = name; name = &empty; } else modifiers += 1; /* skip separator */ /* Parse regex modifiers. */ for (; modifiers[0] != '\0'; modifiers++) switch (modifiers[0]) { case 'N': if (modifiers == name) error ("forcing explicit tag name but no name, ignoring"); force_explicit_name = true; break; case 'i': ignore_case = true; break; case 's': single_line = true; FALLTHROUGH; case 'm': multi_line = true; need_filebuf = true; break; default: error ("invalid regexp modifier '%c', ignoring", modifiers[0]); break; } patbuf = xnew (1, struct re_pattern_buffer); *patbuf = zeropattern; if (ignore_case) { static char lc_trans[UCHAR_MAX + 1]; int i; for (i = 0; i < UCHAR_MAX + 1; i++) lc_trans[i] = c_tolower (i); patbuf->translate = lc_trans; /* translation table to fold case */ } if (multi_line) pat = concat ("^", regexp_pattern, ""); /* anchor to beginning of line */ else pat = regexp_pattern; if (single_line) re_set_syntax (RE_SYNTAX_EMACS | RE_DOT_NEWLINE); else re_set_syntax (RE_SYNTAX_EMACS); err = re_compile_pattern (pat, strlen (pat), patbuf); if (multi_line) free (pat); if (err != NULL) { error ("%s while compiling pattern", err); return; } rp = p_head; p_head = xnew (1, regexp); p_head->pattern = savestr (regexp_pattern); p_head->p_next = rp; p_head->lang = lang; p_head->pat = patbuf; p_head->name = savestr (name); p_head->error_signaled = false; p_head->force_explicit_name = force_explicit_name; p_head->ignore_case = ignore_case; p_head->multi_line = multi_line; } /* * Do the substitutions indicated by the regular expression and * arguments. */ static char * substitute (char *in, char *out, struct re_registers *regs) { char *result, *t; int size, dig, diglen; result = NULL; size = strlen (out); /* Pass 1: figure out how much to allocate by finding all \N strings. */ if (out[size - 1] == '\\') fatal ("pattern error in \"%s\"", out); for (t = strchr (out, '\\'); t != NULL; t = strchr (t + 2, '\\')) if (c_isdigit (t[1])) { dig = t[1] - '0'; diglen = regs->end[dig] - regs->start[dig]; size += diglen - 2; } else size -= 1; /* Allocate space and do the substitutions. */ assert (size >= 0); result = xnew (size + 1, char); for (t = result; *out != '\0'; out++) if (*out == '\\' && c_isdigit (*++out)) { dig = *out - '0'; diglen = regs->end[dig] - regs->start[dig]; memcpy (t, in + regs->start[dig], diglen); t += diglen; } else *t++ = *out; *t = '\0'; assert (t <= result + size); assert (t - result == (int)strlen (result)); return result; } /* Deallocate all regexps. */ static void free_regexps (void) { regexp *rp; while (p_head != NULL) { rp = p_head->p_next; free (p_head->pattern); free (p_head->name); free (p_head); p_head = rp; } return; } /* * Reads the whole file as a single string from `filebuf' and looks for * multi-line regular expressions, creating tags on matches. * readline already dealt with normal regexps. * * Idea by Ben Wing <ben@666.com> (2002). */ static void regex_tag_multiline (void) { char *buffer = filebuf.buffer; regexp *rp; char *name; for (rp = p_head; rp != NULL; rp = rp->p_next) { int match = 0; if (!rp->multi_line) continue; /* skip normal regexps */ /* Generic initializations before parsing file from memory. */ lineno = 1; /* reset global line number */ charno = 0; /* reset global char number */ linecharno = 0; /* reset global char number of line start */ /* Only use generic regexps or those for the current language. */ if (rp->lang != NULL && rp->lang != curfdp->lang) continue; while (match >= 0 && match < filebuf.len) { match = re_search (rp->pat, buffer, filebuf.len, charno, filebuf.len - match, &rp->regs); switch (match) { case -2: /* Some error. */ if (!rp->error_signaled) { error ("regexp stack overflow while matching \"%s\"", rp->pattern); rp->error_signaled = true; } break; case -1: /* No match. */ break; default: if (match == rp->regs.end[0]) { if (!rp->error_signaled) { error ("regexp matches the empty string: \"%s\"", rp->pattern); rp->error_signaled = true; } match = -3; /* exit from while loop */ break; } /* Match occurred. Construct a tag. */ while (charno < rp->regs.end[0]) if (buffer[charno++] == '\n') lineno++, linecharno = charno; name = rp->name; if (name[0] == '\0') name = NULL; else /* make a named tag */ name = substitute (buffer, rp->name, &rp->regs); if (rp->force_explicit_name) { /* Force explicit tag name, if a name is there. */ pfnote (name, true, buffer + linecharno, charno - linecharno + 1, lineno, linecharno); if (debug) fprintf (stderr, "%s on %s:%d: %s\n", name ? name : "(unnamed)", curfdp->taggedfname, lineno, buffer + linecharno); } else make_tag (name, strlen (name), true, buffer + linecharno, charno - linecharno + 1, lineno, linecharno); break; } } } } static bool nocase_tail (const char *cp) { int len = 0; while (*cp != '\0' && c_tolower (*cp) == c_tolower (dbp[len])) cp++, len++; if (*cp == '\0' && !intoken (dbp[len])) { dbp += len; return true; } return false; } static void get_tag (register char *bp, char **namepp) { register char *cp = bp; if (*bp != '\0') { /* Go till you get to white space or a syntactic break */ for (cp = bp + 1; !notinname (*cp); cp++) continue; make_tag (bp, cp - bp, true, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); } if (namepp != NULL) *namepp = savenstr (bp, cp - bp); } /* Similar to get_tag, but include '=' as part of the tag. */ static void get_lispy_tag (register char *bp) { register char *cp = bp; if (*bp != '\0') { /* Go till you get to white space or a syntactic break */ for (cp = bp + 1; !notinname (*cp) || *cp == '='; cp++) continue; make_tag (bp, cp - bp, true, lb.buffer, cp - lb.buffer + 1, lineno, linecharno); } } /* * Read a line of text from `stream' into `lbp', excluding the * newline or CR-NL, if any. Return the number of characters read from * `stream', which is the length of the line including the newline. * * On DOS or Windows we do not count the CR character, if any before the * NL, in the returned length; this mirrors the behavior of Emacs on those * platforms (for text files, it translates CR-NL to NL as it reads in the * file). * * If multi-line regular expressions are requested, each line read is * appended to `filebuf'. */ static long readline_internal (linebuffer *lbp, FILE *stream, char const *filename) { char *buffer = lbp->buffer; char *p = lbp->buffer; char *pend; int chars_deleted; pend = p + lbp->size; /* Separate to avoid 386/IX compiler bug. */ for (;;) { register int c = getc (stream); if (p == pend) { /* We're at the end of linebuffer: expand it. */ lbp->size *= 2; xrnew (buffer, lbp->size, char); p += buffer - lbp->buffer; pend = buffer + lbp->size; lbp->buffer = buffer; } if (c == EOF) { if (ferror (stream)) perror (filename); *p = '\0'; chars_deleted = 0; break; } if (c == '\n') { if (p > buffer && p[-1] == '\r') { p -= 1; chars_deleted = 2; } else { chars_deleted = 1; } *p = '\0'; break; } *p++ = c; } lbp->len = p - buffer; if (need_filebuf /* we need filebuf for multi-line regexps */ && chars_deleted > 0) /* not at EOF */ { while (filebuf.size <= filebuf.len + lbp->len + 1) /* +1 for \n */ { /* Expand filebuf. */ filebuf.size *= 2; xrnew (filebuf.buffer, filebuf.size, char); } memcpy (filebuf.buffer + filebuf.len, lbp->buffer, lbp->len); filebuf.len += lbp->len; filebuf.buffer[filebuf.len++] = '\n'; filebuf.buffer[filebuf.len] = '\0'; } return lbp->len + chars_deleted; } /* * Like readline_internal, above, but in addition try to match the * input line against relevant regular expressions and manage #line * directives. */ static void readline (linebuffer *lbp, FILE *stream) { long result; linecharno = charno; /* update global char number of line start */ result = readline_internal (lbp, stream, infilename); /* read line */ lineno += 1; /* increment global line number */ charno += result; /* increment global char number */ /* Honor #line directives. */ if (!no_line_directive) { static bool discard_until_line_directive; /* Check whether this is a #line directive. */ if (result > 12 && strneq (lbp->buffer, "#line ", 6)) { unsigned int lno; int start = 0; if (sscanf (lbp->buffer, "#line %u \"%n", &lno, &start) >= 1 && start > 0) /* double quote character found */ { char *endp = lbp->buffer + start; while ((endp = strchr (endp, '"')) != NULL && endp[-1] == '\\') endp++; if (endp != NULL) /* Ok, this is a real #line directive. Let's deal with it. */ { char *taggedabsname; /* absolute name of original file */ char *taggedfname; /* name of original file as given */ char *name; /* temp var */ discard_until_line_directive = false; /* found it */ name = lbp->buffer + start; *endp = '\0'; canonicalize_filename (name); taggedabsname = absolute_filename (name, tagfiledir); if (filename_is_absolute (name) || filename_is_absolute (curfdp->infname)) taggedfname = savestr (taggedabsname); else taggedfname = relative_filename (taggedabsname,tagfiledir); if (streq (curfdp->taggedfname, taggedfname)) /* The #line directive is only a line number change. We deal with this afterwards. */ free (taggedfname); else /* The tags following this #line directive should be attributed to taggedfname. In order to do this, set curfdp accordingly. */ { fdesc *fdp; /* file description pointer */ /* Go look for a file description already set up for the file indicated in the #line directive. If there is one, use it from now until the next #line directive. */ for (fdp = fdhead; fdp != NULL; fdp = fdp->next) if (streq (fdp->infname, curfdp->infname) && streq (fdp->taggedfname, taggedfname)) /* If we remove the second test above (after the &&) then all entries pertaining to the same file are coalesced in the tags file. If we use it, then entries pertaining to the same file but generated from different files (via #line directives) will go into separate sections in the tags file. These alternatives look equivalent. The first one destroys some apparently useless information. */ { curfdp = fdp; free (taggedfname); break; } /* Else, if we already tagged the real file, skip all input lines until the next #line directive. */ if (fdp == NULL) /* not found */ for (fdp = fdhead; fdp != NULL; fdp = fdp->next) if (streq (fdp->infabsname, taggedabsname)) { discard_until_line_directive = true; free (taggedfname); break; } /* Else create a new file description and use that from now on, until the next #line directive. */ if (fdp == NULL) /* not found */ { fdp = fdhead; fdhead = xnew (1, fdesc); *fdhead = *curfdp; /* copy curr. file description */ fdhead->next = fdp; fdhead->infname = savestr (curfdp->infname); fdhead->infabsname = savestr (curfdp->infabsname); fdhead->infabsdir = savestr (curfdp->infabsdir); fdhead->taggedfname = taggedfname; fdhead->usecharno = false; fdhead->prop = NULL; fdhead->written = false; curfdp = fdhead; } } free (taggedabsname); lineno = lno - 1; readline (lbp, stream); return; } /* if a real #line directive */ } /* if #line is followed by a number */ } /* if line begins with "#line " */ /* If we are here, no #line directive was found. */ if (discard_until_line_directive) { if (result > 0) { /* Do a tail recursion on ourselves, thus discarding the contents of the line buffer. */ readline (lbp, stream); return; } /* End of file. */ discard_until_line_directive = false; return; } } /* if #line directives should be considered */ { int match; regexp *rp; char *name; /* Match against relevant regexps. */ if (lbp->len > 0) for (rp = p_head; rp != NULL; rp = rp->p_next) { /* Only use generic regexps or those for the current language. Also do not use multiline regexps, which is the job of regex_tag_multiline. */ if ((rp->lang != NULL && rp->lang != fdhead->lang) || rp->multi_line) continue; match = re_match (rp->pat, lbp->buffer, lbp->len, 0, &rp->regs); switch (match) { case -2: /* Some error. */ if (!rp->error_signaled) { error ("regexp stack overflow while matching \"%s\"", rp->pattern); rp->error_signaled = true; } break; case -1: /* No match. */ break; case 0: /* Empty string matched. */ if (!rp->error_signaled) { error ("regexp matches the empty string: \"%s\"", rp->pattern); rp->error_signaled = true; } break; default: /* Match occurred. Construct a tag. */ name = rp->name; if (name[0] == '\0') name = NULL; else /* make a named tag */ name = substitute (lbp->buffer, rp->name, &rp->regs); if (rp->force_explicit_name) { /* Force explicit tag name, if a name is there. */ pfnote (name, true, lbp->buffer, match, lineno, linecharno); if (debug) fprintf (stderr, "%s on %s:%d: %s\n", name ? name : "(unnamed)", curfdp->taggedfname, lineno, lbp->buffer); } else make_tag (name, strlen (name), true, lbp->buffer, match, lineno, linecharno); break; } } } } /* * Return a pointer to a space of size strlen(cp)+1 allocated * with xnew where the string CP has been copied. */ static char * savestr (const char *cp) { return savenstr (cp, strlen (cp)); } /* * Return a pointer to a space of size LEN+1 allocated with xnew where * the string CP has been copied for at most the first LEN characters. */ static char * savenstr (const char *cp, int len) { char *dp = xnew (len + 1, char); dp[len] = '\0'; return memcpy (dp, cp, len); } /* Skip spaces (end of string is not space), return new pointer. */ static char * skip_spaces (char *cp) { while (c_isspace (*cp)) cp++; return cp; } /* Skip non spaces, except end of string, return new pointer. */ static char * skip_non_spaces (char *cp) { while (*cp != '\0' && !c_isspace (*cp)) cp++; return cp; } /* Skip any chars in the "name" class.*/ static char * skip_name (char *cp) { /* '\0' is a notinname() so loop stops there too */ while (! notinname (*cp)) cp++; return cp; } /* Print error message and exit. */ static void fatal (char const *format, ...) { va_list ap; va_start (ap, format); verror (format, ap); va_end (ap); exit (EXIT_FAILURE); } static void pfatal (const char *s1) { perror (s1); exit (EXIT_FAILURE); } static void suggest_asking_for_help (void) { fprintf (stderr, "\tTry '%s --help' for a complete list of options.\n", progname); exit (EXIT_FAILURE); } /* Output a diagnostic with printf-style FORMAT and args. */ static void error (const char *format, ...) { va_list ap; va_start (ap, format); verror (format, ap); va_end (ap); } static void verror (char const *format, va_list ap) { fprintf (stderr, "%s: ", progname); vfprintf (stderr, format, ap); fprintf (stderr, "\n"); } /* Return a newly-allocated string whose contents concatenate those of s1, s2, s3. */ static char * concat (const char *s1, const char *s2, const char *s3) { int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3); char *result = xnew (len1 + len2 + len3 + 1, char); strcpy (result, s1); strcpy (result + len1, s2); strcpy (result + len1 + len2, s3); return result; } /* Does the same work as the system V getcwd, but does not need to guess the buffer size in advance. */ static char * etags_getcwd (void) { int bufsize = 200; char *path = xnew (bufsize, char); while (getcwd (path, bufsize) == NULL) { if (errno != ERANGE) pfatal ("getcwd"); bufsize *= 2; free (path); path = xnew (bufsize, char); } canonicalize_filename (path); return path; } /* Return a newly allocated string containing a name of a temporary file. */ static char * etags_mktmp (void) { const char *tmpdir = getenv ("TMPDIR"); const char *slash = "/"; #if defined (DOS_NT) if (!tmpdir) tmpdir = getenv ("TEMP"); if (!tmpdir) tmpdir = getenv ("TMP"); if (!tmpdir) tmpdir = "."; if (tmpdir[strlen (tmpdir) - 1] == '/' || tmpdir[strlen (tmpdir) - 1] == '\\') slash = ""; #else if (!tmpdir) tmpdir = "/tmp"; if (tmpdir[strlen (tmpdir) - 1] == '/') slash = ""; #endif char *templt = concat (tmpdir, slash, "etXXXXXX"); int fd = rust_make_temp (templt, O_CLOEXEC); if (fd < 0 || close (fd) != 0) { int temp_errno = errno; free (templt); errno = temp_errno; templt = NULL; } #if defined (DOS_NT) /* The file name will be used in shell redirection, so it needs to have DOS-style backslashes, or else the Windows shell will barf. */ char *p; for (p = templt; *p; p++) if (*p == '/') *p = '\\'; #endif return templt; } /* Return a newly allocated string containing the file name of FILE relative to the absolute directory DIR (which should end with a slash). */ static char * relative_filename (char *file, char *dir) { char *fp, *dp, *afn, *res; int i; /* Find the common root of file and dir (with a trailing slash). */ afn = absolute_filename (file, cwd); fp = afn; dp = dir; while (*fp++ == *dp++) continue; fp--, dp--; /* back to the first differing char */ #ifdef DOS_NT if (fp == afn && afn[0] != '/') /* cannot build a relative name */ return afn; #endif do /* look at the equal chars until '/' */ fp--, dp--; while (*fp != '/'); /* Build a sequence of "../" strings for the resulting relative file name. */ i = 0; while ((dp = strchr (dp + 1, '/')) != NULL) i += 1; res = xnew (3*i + strlen (fp + 1) + 1, char); char *z = res; while (i-- > 0) z = stpcpy (z, "../"); /* Add the file name relative to the common root of file and dir. */ strcpy (z, fp + 1); free (afn); return res; } /* Return a newly allocated string containing the absolute file name of FILE given DIR (which should end with a slash). */ static char * absolute_filename (char *file, char *dir) { char *slashp, *cp, *res; if (filename_is_absolute (file)) res = savestr (file); #ifdef DOS_NT /* We don't support non-absolute file names with a drive letter, like `d:NAME' (it's too much hassle). */ else if (file[1] == ':') fatal ("%s: relative file names with drive letters not supported", file); #endif else res = concat (dir, file, ""); /* Delete the "/dirname/.." and "/." substrings. */ slashp = strchr (res, '/'); while (slashp != NULL && slashp[0] != '\0') { if (slashp[1] == '.') { if (slashp[2] == '.' && (slashp[3] == '/' || slashp[3] == '\0')) { cp = slashp; do cp--; while (cp >= res && !filename_is_absolute (cp)); if (cp < res) cp = slashp; /* the absolute name begins with "/.." */ #ifdef DOS_NT /* Under MSDOS and NT we get `d:/NAME' as absolute file name, so the luser could say `d:/../NAME'. We silently treat this as `d:/NAME'. */ else if (cp[0] != '/') cp = slashp; #endif memmove (cp, slashp + 3, strlen (slashp + 2)); slashp = cp; continue; } else if (slashp[2] == '/' || slashp[2] == '\0') { memmove (slashp, slashp + 2, strlen (slashp + 1)); continue; } } slashp = strchr (slashp + 1, '/'); } if (res[0] == '\0') /* just a safety net: should never happen */ { free (res); return savestr ("/"); } else return res; } /* Return a newly allocated string containing the absolute file name of dir where FILE resides given DIR (which should end with a slash). */ static char * absolute_dirname (char *file, char *dir) { char *slashp, *res; char save; slashp = strrchr (file, '/'); if (slashp == NULL) return savestr (dir); save = slashp[1]; slashp[1] = '\0'; res = absolute_filename (file, dir); slashp[1] = save; return res; } /* Whether the argument string is an absolute file name. The argument string must have been canonicalized with canonicalize_filename. */ static bool filename_is_absolute (char *fn) { return (fn[0] == '/' #ifdef DOS_NT || (c_isalpha (fn[0]) && fn[1] == ':' && fn[2] == '/') #endif ); } /* Downcase DOS drive letter and collapse separators into single slashes. Works in place. */ static void canonicalize_filename (register char *fn) { register char* cp; #ifdef DOS_NT /* Canonicalize drive letter case. */ if (c_isupper (fn[0]) && fn[1] == ':') fn[0] = c_tolower (fn[0]); /* Collapse multiple forward- and back-slashes into a single forward slash. */ for (cp = fn; *cp != '\0'; cp++, fn++) if (*cp == '/' || *cp == '\\') { *fn = '/'; while (cp[1] == '/' || cp[1] == '\\') cp++; } else *fn = *cp; #else /* !DOS_NT */ /* Collapse multiple slashes into a single slash. */ for (cp = fn; *cp != '\0'; cp++, fn++) if (*cp == '/') { *fn = '/'; while (cp[1] == '/') cp++; } else *fn = *cp; #endif /* !DOS_NT */ *fn = '\0'; } /* Initialize a linebuffer for use. */ static void linebuffer_init (linebuffer *lbp) { lbp->size = (DEBUG) ? 3 : 200; lbp->buffer = xnew (lbp->size, char); lbp->buffer[0] = '\0'; lbp->len = 0; } /* Set the minimum size of a string contained in a linebuffer. */ static void linebuffer_setlen (linebuffer *lbp, int toksize) { while (lbp->size <= toksize) { lbp->size *= 2; xrnew (lbp->buffer, lbp->size, char); } lbp->len = toksize; } /* Like malloc but get fatal error if memory is exhausted. */ static void * xmalloc (size_t size) { void *result = malloc (size); if (result == NULL) fatal ("virtual memory exhausted"); return result; } static void * xrealloc (void *ptr, size_t size) { void *result = realloc (ptr, size); if (result == NULL) fatal ("virtual memory exhausted"); return result; } /* * Local Variables: * indent-tabs-mode: t * tab-width: 8 * fill-column: 79 * c-font-lock-extra-types: ("FILE" "bool" "language" "linebuffer" "fdesc" "node" "regexp") * c-file-style: "gnu" * End: */ /* etags.c ends here */
jeandudey/remacs
lib-src/etags.c
C
gpl-3.0
190,008
#include "struct_write.h"
ansgarphilippsen/dino
src/struct_write.c
C
gpl-3.0
26
################################################################################################### # # PySpice - A Spice Package for Python # Copyright (C) 2014 Fabrice Salvaire # # 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/>. # #################################################################################################### #################################################################################################### import logging #################################################################################################### from ..Tools.StringTools import join_list, join_dict from .NgSpice.Shared import NgSpiceShared from .Server import SpiceServer #################################################################################################### _module_logger = logging.getLogger(__name__) #################################################################################################### class CircuitSimulation: """Define and generate the spice instruction to perform a circuit simulation. .. warning:: In some cases NgSpice can perform several analyses one after the other. This case is partially supported. """ _logger = _module_logger.getChild('CircuitSimulation') ############################################## def __init__(self, circuit, temperature=27, nominal_temperature=27, pipe=True, ): self._circuit = circuit self._options = {} # .options self._initial_condition = {} # .ic self._saved_nodes = () self._analysis_parameters = {} self.temperature = temperature self.nominal_temperature = nominal_temperature if pipe: self.options('NOINIT') self.options(filetype='binary') ############################################## @property def circuit(self): return self._circuit ############################################## def options(self, *args, **kwargs): for item in args: self._options[str(item)] = None for key, value in kwargs.items(): self._options[str(key)] = str(value) ############################################## @property def temperature(self): return self._options['TEMP'] @temperature.setter def temperature(self, value): self._options['TEMP'] = value ############################################## @property def nominal_temperature(self): return self._options['TNOM'] @nominal_temperature.setter def nominal_temperature(self, value): self._options['TNOM'] = value ############################################## def initial_condition(self, **kwargs): """ Set initial condition for voltage nodes. Usage: initial_condition(node_name1=value, ...) """ for key, value in kwargs.items(): self._initial_condition['V({})'.format(str(key))] = str(value) # Fixme: .nodeset ############################################## def save(self, *args): # Fixme: pass Node for voltage node, Element for source branch current, ... """Set the list of saved vectors. If no *.save* line is given, then the default set of vectors is saved (node voltages and voltage source branch currents). If *.save* lines are given, only those vectors specified are saved. Node voltages may be saved by giving the node_name or *v(node_name)*. Currents through an independent voltage source (including inductor) are given by *i(source_name)* or *source_name#branch*. Internal device data are accepted as *@dev[param]*. If you want to save internal data in addition to the default vector set, add the parameter *all* to the additional vectors to be saved. """ self._saved_nodes = list(args) ############################################## @property def save_currents(self): """ Save all currents. """ return self._options.get('SAVECURRENTS', False) @save_currents.setter def save_currents(self, value): if value: self._options['SAVECURRENTS'] = True else: del self._options['SAVECURRENTS'] ############################################## def reset_analysis(self): self._analysis_parameters.clear() ############################################## def operating_point(self): """Compute the operating point of the circuit with capacitors open and inductors shorted.""" self._analysis_parameters['op'] = '' ############################################## def dc_sensitivity(self, output_variable): """Compute the sensitivity of the DC operating point of a node voltage or voltage-source branch current to all non-zero device parameters. General form: .. code:: .sens outvar Examples: .. code:: .SENS V(1, OUT) .SENS I(VTEST) """ self._analysis_parameters['sens'] = (output_variable,) ############################################## def ac_sensitivity(self, output_variable, start_frequency, stop_frequency, number_of_points, variation): """Compute the sensitivity of the AC values of a node voltage or voltage-source branch current to all non-zero device parameters. General form: .. code:: .sens outvar ac dec nd fstart fstop .sens outvar ac oct no fstart fstop .sens outvar ac lin np fstart fstop Examples: .. code:: .SENS V(OUT) AC DEC 10 100 100 k """ if variation not in ('dec', 'oct', 'lin'): raise ValueError("Incorrect variation type") self._analysis_parameters['sens'] = (output_variable, variation, number_of_points, start_frequency, stop_frequency) ############################################## def dc(self, **kwargs): """Compute the DC transfer fonction of the circuit with capacitors open and inductors shorted. General form: .. code:: .dc srcnam vstart vstop vincr [ src2 start2 stop2 incr2 ] *srcnam* is the name of an independent voltage or current source, a resistor or the circuit temperature. *vstart*, *vstop*, and *vincr* are the starting, final, and incrementing values respectively. A second source (*src2*) may optionally be specified with associated sweep parameters. In this case, the first source is swept over its range for each value of the second source. Examples: .. code:: .dc VIN 0 .2 5 5.0 0.25 .dc VDS 0 10 .5 VGS 0 5 1 .dc VCE 0 10 .2 5 IB 0 10U 1U .dc RLoad 1k 2k 100 .dc TEMP -15 75 5 """ parameters = [] for variable, value_slice in kwargs.items(): variable_lower = variable.lower() if variable_lower[0] in ('v', 'i', 'r') or variable_lower == 'temp': parameters += [variable, value_slice.start, value_slice.stop, value_slice.step] else: raise NameError('Sweep variable must be a voltage/current source, ' 'a resistor or the circuit temperature') self._analysis_parameters['dc'] = parameters ############################################## def ac(self, start_frequency, stop_frequency, number_of_points, variation): # fixme: concise keyword ? """Perform a small-signal AC analysis of the circuit where all non-linear devices are linearized around their actual DC operating point. Note that in order for this analysis to be meaningful, at least one independent source must have been specified with an AC value. Typically it does not make much sense to specify more than one AC source. If you do, the result will be a superposition of all sources, thus difficult to interpret. Examples: .. code:: .ac dec nd fstart fstop .ac oct no fstart fstop .ac lin np fstart fstop The parameter *variation* must be either `dec`, `oct` or `lin`. """ if variation not in ('dec', 'oct', 'lin'): raise ValueError("Incorrect variation type") self._analysis_parameters['ac'] = (variation, number_of_points, start_frequency, stop_frequency) ############################################## def transient(self, step_time, end_time, start_time=None, max_time=None, use_initial_condition=False): """Perform a transient analysis of the circuit. General Form: .. code:: .tran tstep tstop <tstart <tmax>> <uic> """ if use_initial_condition: uic = 'uic' else: uic = None self._analysis_parameters['tran'] = (step_time, end_time, start_time, max_time, uic) ############################################## def __str__(self): netlist = str(self._circuit) if self.options: for key, value in self._options.items(): if value is not None: netlist += '.options {} = {}\n'.format(key, value) else: netlist += '.options {}\n'.format(key) if self.initial_condition: netlist += '.ic ' + join_dict(self._initial_condition) + '\n' if self._saved_nodes: netlist += '.save ' + join_list(self._saved_nodes) + '\n' for analysis, analysis_parameters in self._analysis_parameters.items(): netlist += '.' + analysis + ' ' + join_list(analysis_parameters) + '\n' netlist += '.end\n' return netlist #################################################################################################### class CircuitSimulator(CircuitSimulation): """ This class implements a circuit simulator. Each analysis mode is performed by a method that return the measured probes. For *ac* and *transient* analyses, the user must specify a list of nodes using the *probes* key argument. """ _logger = _module_logger.getChild('CircuitSimulator') ############################################## def _run(self, analysis_method, *args, **kwargs): self.reset_analysis() if 'probes' in kwargs: self.save(* kwargs.pop('probes')) method = getattr(CircuitSimulation, analysis_method) method(self, *args, **kwargs) self._logger.debug('desk\n' + str(self)) ############################################## def operating_point(self, *args, **kwargs): return self._run('operating_point', *args, **kwargs) ############################################## def dc(self, *args, **kwargs): return self._run('dc', *args, **kwargs) ############################################## def dc_sensitivity(self, *args, **kwargs): return self._run('dc_sensitivity', *args, **kwargs) ############################################## def ac(self, *args, **kwargs): return self._run('ac', *args, **kwargs) ############################################## def transient(self, *args, **kwargs): return self._run('transient', *args, **kwargs) #################################################################################################### class SubprocessCircuitSimulator(CircuitSimulator): _logger = _module_logger.getChild('SubprocessCircuitSimulator') ############################################## def __init__(self, circuit, temperature=27, nominal_temperature=27, spice_command='ngspice', ): # Fixme: kwargs super().__init__(circuit, temperature, nominal_temperature, pipe=True) self._spice_server = SpiceServer() ############################################## def _run(self, analysis_method, *args, **kwargs): super()._run(analysis_method, *args, **kwargs) raw_file = self._spice_server(str(self)) self.reset_analysis() # for field in raw_file.variables: # print field return raw_file.to_analysis(self._circuit) #################################################################################################### class NgSpiceSharedCircuitSimulator(CircuitSimulator): _logger = _module_logger.getChild('NgSpiceSharedCircuitSimulator') ############################################## def __init__(self, circuit, temperature=27, nominal_temperature=27, ngspice_shared=None, ): # Fixme: kwargs super().__init__(circuit, temperature, nominal_temperature, pipe=False) if ngspice_shared is None: self._ngspice_shared = NgSpiceShared(send_data=False) else: self._ngspice_shared = ngspice_shared ############################################## def _run(self, analysis_method, *args, **kwargs): super()._run(analysis_method, *args, **kwargs) self._ngspice_shared.load_circuit(str(self)) self._ngspice_shared.run() self._logger.debug(str(self._ngspice_shared.plot_names)) self.reset_analysis() if analysis_method == 'dc': plot_name = 'dc1' elif analysis_method == 'ac': plot_name = 'ac1' elif analysis_method == 'transient': plot_name = 'tran1' else: raise NotImplementedError return self._ngspice_shared.plot(plot_name).to_analysis() #################################################################################################### # # End # ####################################################################################################
thomaslima/PySpice
PySpice/Spice/Simulation.py
Python
gpl-3.0
14,801
<?php use Doctrine\ORM\Mapping as ORM; /** * AmpPermissaoEspecialModulo * * @ORM\Table(name="amp_permissao_especial_modulo", indexes={@ORM\Index(name="fk_amp_permissao_especial_modulo_1_idx", columns={"id_modulo"}), @ORM\Index(name="fk_amp_permissao_especial_modulo_2_idx", columns={"id_permissao_especial"})}) * @ORM\Entity */ class AmpPermissaoEspecialModulo { /** * @var int * * @ORM\Column(name="id_permissao_especial_modulo", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $idPermissaoEspecialModulo; /** * @var int * * @ORM\Column(name="id_permissao_especial", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $idPermissaoEspecial; /** * @var int * * @ORM\Column(name="id_usuario_criacao", type="integer", nullable=false) */ private $idUsuarioCriacao; /** * @var \DateTime * * @ORM\Column(name="data_criacao", type="datetime", nullable=false) */ private $dataCriacao; /** * @var int * * @ORM\Column(name="id_usuario_alteracao", type="integer", nullable=false) */ private $idUsuarioAlteracao; /** * @var \DateTime * * @ORM\Column(name="data_ultima_alteracao", type="datetime", nullable=true) */ private $dataUltimaAlteracao; /** * @var \AmpModulo * * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") * @ORM\OneToOne(targetEntity="AmpModulo") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="id_modulo", referencedColumnName="id_modulo") * }) */ private $idModulo; /** * Set idPermissaoEspecialModulo * * @param int $idPermissaoEspecialModulo * * @return AmpPermissaoEspecialModulo */ public function setIdPermissaoEspecialModulo($idPermissaoEspecialModulo) { $this->idPermissaoEspecialModulo = $idPermissaoEspecialModulo; return $this; } /** * Get idPermissaoEspecialModulo * * @return int */ public function getIdPermissaoEspecialModulo() { return $this->idPermissaoEspecialModulo; } /** * Set idPermissaoEspecial * * @param int $idPermissaoEspecial * * @return AmpPermissaoEspecialModulo */ public function setIdPermissaoEspecial($idPermissaoEspecial) { $this->idPermissaoEspecial = $idPermissaoEspecial; return $this; } /** * Get idPermissaoEspecial * * @return int */ public function getIdPermissaoEspecial() { return $this->idPermissaoEspecial; } /** * Set idUsuarioCriacao * * @param int $idUsuarioCriacao * * @return AmpPermissaoEspecialModulo */ public function setIdUsuarioCriacao($idUsuarioCriacao) { $this->idUsuarioCriacao = $idUsuarioCriacao; return $this; } /** * Get idUsuarioCriacao * * @return int */ public function getIdUsuarioCriacao() { return $this->idUsuarioCriacao; } /** * Set dataCriacao * * @param \DateTime $dataCriacao * * @return AmpPermissaoEspecialModulo */ public function setDataCriacao($dataCriacao) { $this->dataCriacao = $dataCriacao; return $this; } /** * Get dataCriacao * * @return \DateTime */ public function getDataCriacao() { return $this->dataCriacao; } /** * Set idUsuarioAlteracao * * @param int $idUsuarioAlteracao * * @return AmpPermissaoEspecialModulo */ public function setIdUsuarioAlteracao($idUsuarioAlteracao) { $this->idUsuarioAlteracao = $idUsuarioAlteracao; return $this; } /** * Get idUsuarioAlteracao * * @return int */ public function getIdUsuarioAlteracao() { return $this->idUsuarioAlteracao; } /** * Set dataUltimaAlteracao * * @param \DateTime $dataUltimaAlteracao * * @return AmpPermissaoEspecialModulo */ public function setDataUltimaAlteracao($dataUltimaAlteracao) { $this->dataUltimaAlteracao = $dataUltimaAlteracao; return $this; } /** * Get dataUltimaAlteracao * * @return \DateTime */ public function getDataUltimaAlteracao() { return $this->dataUltimaAlteracao; } /** * Set idModulo * * @param \AmpModulo $idModulo * * @return AmpPermissaoEspecialModulo */ public function setIdModulo(\AmpModulo $idModulo) { $this->idModulo = $idModulo; return $this; } /** * Get idModulo * * @return \AmpModulo */ public function getIdModulo() { return $this->idModulo; } }
panda-coder/phpanda
tools/entities/AmpPermissaoEspecialModulo.php
PHP
gpl-3.0
4,941
#include "ReadYuyv.h" int ReadFileCleanup( int ret, uint32 **buffer, int *fileSize, int fd) { if (ret) { if (*buffer) { free(*buffer); *buffer = NULL; } *fileSize = 0; } if (fd > 0) { close(fd); fd = -1; } return ret; } int ReadImgFile(char *fileName, uint32 **buffer, int *fileSize) { int ret = 0; struct stat statbuf; int fd = -1; if (stat(fileName, &statbuf) != 0) { fprintf(stderr, "Can't stat %s\n", fileName); ret = 5; return ReadFileCleanup(ret, buffer, fileSize, fd); } printf("mode: 0x%x. uid: %d. gid: %d. size: %lld.\n", statbuf.st_mode, statbuf.st_uid, statbuf.st_gid, statbuf.st_size); *buffer = (uint32 *)malloc(statbuf.st_size); if (! *buffer) { fprintf(stderr, "Error allocating memory\n"); ret = 7; return ReadFileCleanup(ret, buffer, fileSize, fd); } printf("Reading File..."); fflush(stdout); fd = open(fileName, O_RDONLY); if (fd < 0) { fprintf(stderr, "Can't open %s\n", fileName); ret = 8; return ReadFileCleanup(ret, buffer, fileSize, fd); } if (read(fd, *buffer, statbuf.st_size) != statbuf.st_size) { fprintf(stderr, "Error reading %s\n", fileName); ret = 9; return ReadFileCleanup(ret, buffer, fileSize, fd); } *fileSize = statbuf.st_size; printf("Done. File Size is %u bytes.\n", *fileSize); fflush(stdout); return ReadFileCleanup(ret, buffer, fileSize, fd); } /****************************************** int main(int argc, char* argv[]) { char *fileName = "/home/nvidia/yuyvImg.jpg"; uint32 *buffer = NULL; int fileSize = 0; int ret = ReadImgFile(fileName, &buffer, &fileSize); printf("ret = %d\n", ret); return 0; } *********************************************/
b51/uikidcm
Lib/Platform/OP/Camera/ReadYuyv.cpp
C++
gpl-3.0
1,779
package par_converter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import java.util.Calendar; import java.io.File; import psi.lib.CalTools.*; /** * <p>ƒ^ƒCƒgƒ‹: PAR—pƒf[ƒ^ƒRƒ“ƒo[ƒ^</p> * * <p>à–¾: </p> * * <p>’˜ìŒ : Copyright (c) 2006 PSI</p> * * <p>‰ïŽÐ–¼: ƒÕiƒvƒTƒCj‚Ì‹»–¡ŠÖS‹óŠÔ</p> * * @author ƒÕiƒvƒTƒCj * @version 1.0 */ public class PAR_DataInformationDialog extends JDialog { private boolean isOK; JFrame Owner; File File; JPanel panel1 = new JPanel(); GridBagLayout gridBagLayout1 = new GridBagLayout(); JLabel FileNameLabel2 = new JLabel(); JLabel FileNameLabel = new JLabel(); public static final String[] POKEMON_VERSION_NAMES = {"POKEMON RUBY", //ƒo[ƒWƒ‡ƒ“ˆê—— "POKEMON SAPP", "POKEMON LEAF", "POKEMON FIRE", "POKEMON EMER", }; JLabel VersionLabel = new JLabel(); JComboBox VersionList = new JComboBox(POKEMON_VERSION_NAMES); JLabel TitleLabel = new JLabel(); JTextField TitleField = new JTextField(); JLabel DescLabel = new JLabel(); JTextField DescField = new JTextField(); JLabel NoteLabel = new JLabel(); JScrollPane NoteScrollPane = new JScrollPane(); JTextArea NoteArea = new JTextArea(); JPanel jPanel1 = new JPanel(); JButton CancelButton = new JButton(); JButton OKButton = new JButton(); public PAR_DataInformationDialog(JFrame owner, String title, boolean modal,File file) { super(owner, title, modal); this.Owner = owner; this.File = file; try { setDefaultCloseOperation(DISPOSE_ON_CLOSE); jbInit(); //pack(); setDefaultText(); } catch (Exception exception) { exception.printStackTrace(); } } /** * setDefaultText */ private void setDefaultText() { this.FileNameLabel.setText(this.File.getName()); Calendar now = Calendar.getInstance(); String date = ""; date += PokeTools.space(String.valueOf((now.get(Calendar.YEAR))),4,"0") + "/"; date += PokeTools.space(String.valueOf((now.get(Calendar.MONTH)+1)),2,"0") + "/"; date += PokeTools.space(String.valueOf((now.get(Calendar.DATE))),2,"0") + " "; date += now.get(Calendar.HOUR_OF_DAY) + ":";//‚È‚º‚©‚±‚ꂾ‚¯0‚ª’ljÁ‚³‚ê‚È‚¢ date += PokeTools.space(String.valueOf((now.get(Calendar.MINUTE))),2,"0") + ":"; date += PokeTools.space(String.valueOf((now.get(Calendar.SECOND))),2,"0"); // this.DescField.setText(date); this.DescField.setText("Save"+date+" 41"); this.TitleField.setText((String)this.VersionList.getModel().getSelectedItem()); } public PAR_DataInformationDialog(JFrame owner,File file) { this(owner, "ƒZ[ƒuƒf[ƒ^î•ñ‚̐ݒè", false,file); } public void setVisible(boolean flag) { if (flag) { this.setSize(new Dimension(300, 300)); Dimension dlgSize = this.getSize(); Dimension frmSize = Owner.getSize(); Point loc = Owner.getLocation(); this.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y); this.setModal(true); super.setVisible(true); } else { super.setVisible(false); } } private void jbInit() throws Exception { panel1.setLayout(gridBagLayout1); FileNameLabel2.setText("‘Ώۃtƒ@ƒCƒ‹–¼F"); FileNameLabel.setText(""); VersionLabel.setText("ƒo[ƒWƒ‡ƒ“F"); TitleLabel.setText("ƒ^ƒCƒgƒ‹F"); TitleField.setToolTipText(""); TitleField.setText(""); DescLabel.setText("à–¾F"); DescField.setEditable(true); DescField.setText(""); NoteLabel.setText("î•ñF"); NoteArea.setText(""); NoteArea.setLineWrap(true); CancelButton.setText("Cancel"); CancelButton.addActionListener(new PAR_DataInformationDialog_CancelButton_actionAdapter(this)); OKButton.setText("OK"); OKButton.addActionListener(new PAR_DataInformationDialog_OKButton_actionAdapter(this)); VersionList.addActionListener(new PAR_DataInformationDialog_VersionList_actionAdapter(this)); this.getContentPane().add(panel1, java.awt.BorderLayout.CENTER); panel1.add(VersionList, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); panel1.add(FileNameLabel, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); panel1.add(TitleField, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0 , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); panel1.add(DescField, new GridBagConstraints(1, 3, 1, 2, 1.0, 0.0 , GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); panel1.add(FileNameLabel2, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 , GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 5), 0, 0)); panel1.add(VersionLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 5, 0, 5), 0, 0)); panel1.add(TitleLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 5, 0, 5), 0, 0)); panel1.add(DescLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 , GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 5, 0, 6), 0, 0)); NoteScrollPane.getViewport().add(NoteArea); panel1.add(NoteLabel, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0 , GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(0, 5, 0, 5), 0, 0)); panel1.add(NoteScrollPane, new GridBagConstraints(1, 5, 1, 1, 1.0, 0.0 , GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 100)); jPanel1.add(OKButton); jPanel1.add(CancelButton); panel1.add(jPanel1, new GridBagConstraints(0, 6, 2, 1, 1.0, 0.0 , GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); } public void OKButton_actionPerformed(ActionEvent e) { this.isOK = true; this.setVisible(false); } public void CancelButton_actionPerformed(ActionEvent e) { isOK = false; this.setVisible(false); } protected boolean isOK() { return this.isOK; } protected String getTitleString() { if (isOK) { return this.TitleField.getText(); } return null; } protected String getDescString() { if (isOK) { return this.DescField.getText(); } return null; } protected String getNoteString() { if (isOK) { return this.NoteArea.getText(); } return null; } protected int getVersion() { if (isOK) { String str = (String)VersionList.getModel().getSelectedItem(); if (str.equals(this. POKEMON_VERSION_NAMES[0])) { return DataConverter.RUBY; } else if (str.equals(this. POKEMON_VERSION_NAMES[1])) { return DataConverter.SAPP; } else if (str.equals(this. POKEMON_VERSION_NAMES[2])) { return DataConverter.LEAF; } else if (str.equals(this. POKEMON_VERSION_NAMES[3])) { return DataConverter.FIRE; } else if (str.equals(this. POKEMON_VERSION_NAMES[4])) { return DataConverter.EMER; } } return -1; } public void VersionList_actionPerformed(ActionEvent e) { this.TitleField.setText((String)this.VersionList.getModel().getSelectedItem()); } } class PAR_DataInformationDialog_VersionList_actionAdapter implements ActionListener { private PAR_DataInformationDialog adaptee; PAR_DataInformationDialog_VersionList_actionAdapter( PAR_DataInformationDialog adaptee) { this.adaptee = adaptee; } public void actionPerformed(ActionEvent e) { adaptee.VersionList_actionPerformed(e); } } class PAR_DataInformationDialog_CancelButton_actionAdapter implements ActionListener { private PAR_DataInformationDialog adaptee; PAR_DataInformationDialog_CancelButton_actionAdapter( PAR_DataInformationDialog adaptee) { this.adaptee = adaptee; } public void actionPerformed(ActionEvent e) { adaptee.CancelButton_actionPerformed(e); } } class PAR_DataInformationDialog_OKButton_actionAdapter implements ActionListener { private PAR_DataInformationDialog adaptee; PAR_DataInformationDialog_OKButton_actionAdapter(PAR_DataInformationDialog adaptee) { this.adaptee = adaptee; } public void actionPerformed(ActionEvent e) { adaptee.OKButton_actionPerformed(e); } }
ledyba/PokemonSavedataEditorForGBA
PAR_Converter/src/par_converter/PAR_DataInformationDialog.java
Java
gpl-3.0
9,926
# Checkbox ```json { "id": "ID for the checkbox element", "name": "Name for the checkbox element", "value": "Value for the checkbox element" } ```
benjamindehli/webpack-sass-atomic-design
src/modules/00-atoms/form-elements/checkbox.md
Markdown
gpl-3.0
150
/*! * Ext Core Library 3.0 * http://extjs.com/ * Copyright(c) 2006-2009, Ext JS, LLC. * * MIT Licensed - http://extjs.com/license/mit.txt */ /*global Ext:true */ // for old browsers window.undefined = window.undefined; /** * @class Ext * Ext core utilities and functions. * @singleton */ Ext = { /** * The version of the framework * @type String */ version : '3.1.0' }; /** * Copies all the properties of config to obj. * @param {Object} obj The receiver of the properties * @param {Object} config The source of the properties * @param {Object} defaults A different object that will also be applied for default values * @return {Object} returns obj * @member Ext apply */ Ext.apply = function(o, c, defaults){ // no "this" reference for friendly out of scope calls if(defaults){ Ext.apply(o, defaults); } if(o && c && typeof c == 'object'){ for(var p in c){ o[p] = c[p]; } } return o; }; (function(){ var idSeed = 0, toString = Object.prototype.toString, ua = navigator.userAgent.toLowerCase(), check = function(r){ return r.test(ua); }, DOC = document, isStrict = DOC.compatMode == "CSS1Compat", isOpera = check(/opera/), isChrome = check(/chrome/), isWebKit = check(/webkit/), isSafari = !isChrome && check(/safari/), isSafari2 = isSafari && check(/applewebkit\/4/), // unique to Safari 2 isSafari3 = isSafari && check(/version\/3/), isSafari4 = isSafari && check(/version\/4/), isIE = !isOpera && check(/msie/), isIE7 = isIE && check(/msie 7/), isIE8 = isIE && check(/msie 8/), isIE6 = isIE && !isIE7 && !isIE8, isGecko = !isWebKit && check(/gecko/), isGecko2 = isGecko && check(/rv:1\.8/), isGecko3 = isGecko && check(/rv:1\.9/), isBorderBox = isIE && !isStrict, isWindows = check(/windows|win32/), isMac = check(/macintosh|mac os x/), isAir = check(/adobeair/), isLinux = check(/linux/), isSecure = /^https/i.test(window.location.protocol); // remove css image flicker if(isIE6){ try{ DOC.execCommand("BackgroundImageCache", false, true); }catch(e){} } Ext.apply(Ext, { /** * URL to a blank file used by Ext when in secure mode for iframe src and onReady src to prevent * the IE insecure content warning (<tt>'about:blank'</tt>, except for IE in secure mode, which is <tt>'javascript:""'</tt>). * @type String */ SSL_SECURE_URL : isSecure && isIE ? 'javascript:""' : 'about:blank', /** * True if the browser is in strict (standards-compliant) mode, as opposed to quirks mode * @type Boolean */ isStrict : isStrict, /** * True if the page is running over SSL * @type Boolean */ isSecure : isSecure, /** * True when the document is fully initialized and ready for action * @type Boolean */ isReady : false, /** * True if the {@link Ext.Fx} Class is available * @type Boolean * @property enableFx */ /** * True to automatically uncache orphaned Ext.Elements periodically (defaults to true) * @type Boolean */ enableGarbageCollector : true, /** * True to automatically purge event listeners during garbageCollection (defaults to false). * @type Boolean */ enableListenerCollection : false, /** * EXPERIMENTAL - True to cascade listener removal to child elements when an element is removed. * Currently not optimized for performance. * @type Boolean */ enableNestedListenerRemoval : false, /** * Indicates whether to use native browser parsing for JSON methods. * This option is ignored if the browser does not support native JSON methods. * <b>Note: Native JSON methods will not work with objects that have functions. * Also, property names must be quoted, otherwise the data will not parse.</b> (Defaults to false) * @type Boolean */ USE_NATIVE_JSON : false, /** * Copies all the properties of config to obj if they don't already exist. * @param {Object} obj The receiver of the properties * @param {Object} config The source of the properties * @return {Object} returns obj */ applyIf : function(o, c){ if(o){ for(var p in c){ if(!Ext.isDefined(o[p])){ o[p] = c[p]; } } } return o; }, /** * Generates unique ids. If the element already has an id, it is unchanged * @param {Mixed} el (optional) The element to generate an id for * @param {String} prefix (optional) Id prefix (defaults "ext-gen") * @return {String} The generated Id. */ id : function(el, prefix){ return (el = Ext.getDom(el) || {}).id = el.id || (prefix || "ext-gen") + (++idSeed); }, /** * <p>Extends one class to create a subclass and optionally overrides members with the passed literal. This method * also adds the function "override()" to the subclass that can be used to override members of the class.</p> * For example, to create a subclass of Ext GridPanel: * <pre><code> MyGridPanel = Ext.extend(Ext.grid.GridPanel, { constructor: function(config) { // Create configuration for this Grid. var store = new Ext.data.Store({...}); var colModel = new Ext.grid.ColumnModel({...}); // Create a new config object containing our computed properties // *plus* whatever was in the config parameter. config = Ext.apply({ store: store, colModel: colModel }, config); MyGridPanel.superclass.constructor.call(this, config); // Your postprocessing here }, yourMethod: function() { // etc. } }); </code></pre> * * <p>This function also supports a 3-argument call in which the subclass's constructor is * passed as an argument. In this form, the parameters are as follows:</p> * <div class="mdetail-params"><ul> * <li><code>subclass</code> : Function <div class="sub-desc">The subclass constructor.</div></li> * <li><code>superclass</code> : Function <div class="sub-desc">The constructor of class being extended</div></li> * <li><code>overrides</code> : Object <div class="sub-desc">A literal with members which are copied into the subclass's * prototype, and are therefore shared among all instances of the new class.</div></li> * </ul></div> * * @param {Function} superclass The constructor of class being extended. * @param {Object} overrides <p>A literal with members which are copied into the subclass's * prototype, and are therefore shared between all instances of the new class.</p> * <p>This may contain a special member named <tt><b>constructor</b></tt>. This is used * to define the constructor of the new class, and is returned. If this property is * <i>not</i> specified, a constructor is generated and returned which just calls the * superclass's constructor passing on its parameters.</p> * <p><b>It is essential that you call the superclass constructor in any provided constructor. See example code.</b></p> * @return {Function} The subclass constructor from the <code>overrides</code> parameter, or a generated one if not provided. */ extend : function(){ // inline overrides var io = function(o){ for(var m in o){ this[m] = o[m]; } }; var oc = Object.prototype.constructor; return function(sb, sp, overrides){ if(Ext.isObject(sp)){ overrides = sp; sp = sb; sb = overrides.constructor != oc ? overrides.constructor : function(){sp.apply(this, arguments);}; } var F = function(){}, sbp, spp = sp.prototype; F.prototype = spp; sbp = sb.prototype = new F(); sbp.constructor=sb; sb.superclass=spp; if(spp.constructor == oc){ spp.constructor=sp; } sb.override = function(o){ Ext.override(sb, o); }; sbp.superclass = sbp.supr = (function(){ return spp; }); sbp.override = io; Ext.override(sb, overrides); sb.extend = function(o){return Ext.extend(sb, o);}; return sb; }; }(), /** * Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name. * Usage:<pre><code> Ext.override(MyClass, { newMethod1: function(){ // etc. }, newMethod2: function(foo){ // etc. } }); </code></pre> * @param {Object} origclass The class to override * @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal * containing one or more methods. * @method override */ override : function(origclass, overrides){ if(overrides){ var p = origclass.prototype; Ext.apply(p, overrides); if(Ext.isIE && overrides.hasOwnProperty('toString')){ p.toString = overrides.toString; } } }, /** * Creates namespaces to be used for scoping variables and classes so that they are not global. * Specifying the last node of a namespace implicitly creates all other nodes. Usage: * <pre><code> Ext.namespace('Company', 'Company.data'); Ext.namespace('Company.data'); // equivalent and preferable to above syntax Company.Widget = function() { ... } Company.data.CustomStore = function(config) { ... } </code></pre> * @param {String} namespace1 * @param {String} namespace2 * @param {String} etc * @return {Object} The namespace object. (If multiple arguments are passed, this will be the last namespace created) * @method namespace */ namespace : function(){ var o, d; Ext.each(arguments, function(v) { d = v.split("."); o = window[d[0]] = window[d[0]] || {}; Ext.each(d.slice(1), function(v2){ o = o[v2] = o[v2] || {}; }); }); return o; }, /** * Takes an object and converts it to an encoded URL. e.g. Ext.urlEncode({foo: 1, bar: 2}); would return "foo=1&bar=2". Optionally, property values can be arrays, instead of keys and the resulting string that's returned will contain a name/value pair for each array value. * @param {Object} o * @param {String} pre (optional) A prefix to add to the url encoded string * @return {String} */ urlEncode : function(o, pre){ var empty, buf = [], e = encodeURIComponent; Ext.iterate(o, function(key, item){ empty = Ext.isEmpty(item); Ext.each(empty ? key : item, function(val){ buf.push('&', e(key), '=', (!Ext.isEmpty(val) && (val != key || !empty)) ? (Ext.isDate(val) ? Ext.encode(val).replace(/"/g, '') : e(val)) : ''); }); }); if(!pre){ buf.shift(); pre = ''; } return pre + buf.join(''); }, /** * Takes an encoded URL and and converts it to an object. Example: <pre><code> Ext.urlDecode("foo=1&bar=2"); // returns {foo: "1", bar: "2"} Ext.urlDecode("foo=1&bar=2&bar=3&bar=4", false); // returns {foo: "1", bar: ["2", "3", "4"]} </code></pre> * @param {String} string * @param {Boolean} overwrite (optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false). * @return {Object} A literal with members */ urlDecode : function(string, overwrite){ if(Ext.isEmpty(string)){ return {}; } var obj = {}, pairs = string.split('&'), d = decodeURIComponent, name, value; Ext.each(pairs, function(pair) { pair = pair.split('='); name = d(pair[0]); value = d(pair[1]); obj[name] = overwrite || !obj[name] ? value : [].concat(obj[name]).concat(value); }); return obj; }, /** * Appends content to the query string of a URL, handling logic for whether to place * a question mark or ampersand. * @param {String} url The URL to append to. * @param {String} s The content to append to the URL. * @return (String) The resulting URL */ urlAppend : function(url, s){ if(!Ext.isEmpty(s)){ return url + (url.indexOf('?') === -1 ? '?' : '&') + s; } return url; }, /** * Converts any iterable (numeric indices and a length property) into a true array * Don't use this on strings. IE doesn't support "abc"[0] which this implementation depends on. * For strings, use this instead: "abc".match(/./g) => [a,b,c]; * @param {Iterable} the iterable object to be turned into a true Array. * @return (Array) array */ toArray : function(){ return isIE ? function(a, i, j, res){ res = []; for(var x = 0, len = a.length; x < len; x++) { res.push(a[x]); } return res.slice(i || 0, j || res.length); } : function(a, i, j){ return Array.prototype.slice.call(a, i || 0, j || a.length); } }(), isIterable : function(v){ //check for array or arguments if(Ext.isArray(v) || v.callee){ return true; } //check for node list type if(/NodeList|HTMLCollection/.test(toString.call(v))){ return true; } //NodeList has an item and length property //IXMLDOMNodeList has nextNode method, needs to be checked first. return ((typeof v.nextNode != 'undefined' || v.item) && Ext.isNumber(v.length)); }, /** * Iterates an array calling the supplied function. * @param {Array/NodeList/Mixed} array The array to be iterated. If this * argument is not really an array, the supplied function is called once. * @param {Function} fn The function to be called with each item. If the * supplied function returns false, iteration stops and this method returns * the current <code>index</code>. This function is called with * the following arguments: * <div class="mdetail-params"><ul> * <li><code>item</code> : <i>Mixed</i> * <div class="sub-desc">The item at the current <code>index</code> * in the passed <code>array</code></div></li> * <li><code>index</code> : <i>Number</i> * <div class="sub-desc">The current index within the array</div></li> * <li><code>allItems</code> : <i>Array</i> * <div class="sub-desc">The <code>array</code> passed as the first * argument to <code>Ext.each</code>.</div></li> * </ul></div> * @param {Object} scope The scope (<code>this</code> reference) in which the specified function is executed. * Defaults to the <code>item</code> at the current <code>index</code> * within the passed <code>array</code>. * @return See description for the fn parameter. */ each : function(array, fn, scope){ if(Ext.isEmpty(array, true)){ return; } if(!Ext.isIterable(array) || Ext.isPrimitive(array)){ array = [array]; } for(var i = 0, len = array.length; i < len; i++){ if(fn.call(scope || array[i], array[i], i, array) === false){ return i; }; } }, /** * Iterates either the elements in an array, or each of the properties in an object. * <b>Note</b>: If you are only iterating arrays, it is better to call {@link #each}. * @param {Object/Array} object The object or array to be iterated * @param {Function} fn The function to be called for each iteration. * The iteration will stop if the supplied function returns false, or * all array elements / object properties have been covered. The signature * varies depending on the type of object being interated: * <div class="mdetail-params"><ul> * <li>Arrays : <tt>(Object item, Number index, Array allItems)</tt> * <div class="sub-desc"> * When iterating an array, the supplied function is called with each item.</div></li> * <li>Objects : <tt>(String key, Object value, Object)</tt> * <div class="sub-desc"> * When iterating an object, the supplied function is called with each key-value pair in * the object, and the iterated object</div></li> * </ul></div> * @param {Object} scope The scope (<code>this</code> reference) in which the specified function is executed. Defaults to * the <code>object</code> being iterated. */ iterate : function(obj, fn, scope){ if(Ext.isEmpty(obj)){ return; } if(Ext.isIterable(obj)){ Ext.each(obj, fn, scope); return; }else if(Ext.isObject(obj)){ for(var prop in obj){ if(obj.hasOwnProperty(prop)){ if(fn.call(scope || obj, prop, obj[prop], obj) === false){ return; }; } } } }, /** * Return the dom node for the passed String (id), dom node, or Ext.Element. * Here are some examples: * <pre><code> // gets dom node based on id var elDom = Ext.getDom('elId'); // gets dom node based on the dom node var elDom1 = Ext.getDom(elDom); // If we don&#39;t know if we are working with an // Ext.Element or a dom node use Ext.getDom function(el){ var dom = Ext.getDom(el); // do something with the dom node } * </code></pre> * <b>Note</b>: the dom node to be found actually needs to exist (be rendered, etc) * when this method is called to be successful. * @param {Mixed} el * @return HTMLElement */ getDom : function(el){ if(!el || !DOC){ return null; } return el.dom ? el.dom : (Ext.isString(el) ? DOC.getElementById(el) : el); }, /** * Returns the current document body as an {@link Ext.Element}. * @return Ext.Element The document body */ getBody : function(){ return Ext.get(DOC.body || DOC.documentElement); }, /** * Removes a DOM node from the document. */ /** * <p>Removes this element from the document, removes all DOM event listeners, and deletes the cache reference. * All DOM event listeners are removed from this element. If {@link Ext#enableNestedListenerRemoval} is * <code>true</code>, then DOM event listeners are also removed from all child nodes. The body node * will be ignored if passed in.</p> * @param {HTMLElement} node The node to remove */ removeNode : isIE && !isIE8 ? function(){ var d; return function(n){ if(n && n.tagName != 'BODY'){ (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n, true) : Ext.EventManager.removeAll(n); d = d || DOC.createElement('div'); d.appendChild(n); d.innerHTML = ''; delete Ext.elCache[n.id]; } } }() : function(n){ if(n && n.parentNode && n.tagName != 'BODY'){ (Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n, true) : Ext.EventManager.removeAll(n); n.parentNode.removeChild(n); delete Ext.elCache[n.id]; } }, /** * <p>Returns true if the passed value is empty.</p> * <p>The value is deemed to be empty if it is<div class="mdetail-params"><ul> * <li>null</li> * <li>undefined</li> * <li>an empty array</li> * <li>a zero length string (Unless the <tt>allowBlank</tt> parameter is <tt>true</tt>)</li> * </ul></div> * @param {Mixed} value The value to test * @param {Boolean} allowBlank (optional) true to allow empty strings (defaults to false) * @return {Boolean} */ isEmpty : function(v, allowBlank){ return v === null || v === undefined || ((Ext.isArray(v) && !v.length)) || (!allowBlank ? v === '' : false); }, /** * Returns true if the passed value is a JavaScript array, otherwise false. * @param {Mixed} value The value to test * @return {Boolean} */ isArray : function(v){ return toString.apply(v) === '[object Array]'; }, /** * Returns true if the passed object is a JavaScript date object, otherwise false. * @param {Object} object The object to test * @return {Boolean} */ isDate : function(v){ return toString.apply(v) === '[object Date]'; }, /** * Returns true if the passed value is a JavaScript Object, otherwise false. * @param {Mixed} value The value to test * @return {Boolean} */ isObject : function(v){ return !!v && Object.prototype.toString.call(v) === '[object Object]'; }, /** * Returns true if the passed value is a JavaScript 'primitive', a string, number or boolean. * @param {Mixed} value The value to test * @return {Boolean} */ isPrimitive : function(v){ return Ext.isString(v) || Ext.isNumber(v) || Ext.isBoolean(v); }, /** * Returns true if the passed value is a JavaScript Function, otherwise false. * @param {Mixed} value The value to test * @return {Boolean} */ isFunction : function(v){ return toString.apply(v) === '[object Function]'; }, /** * Returns true if the passed value is a number. Returns false for non-finite numbers. * @param {Mixed} value The value to test * @return {Boolean} */ isNumber : function(v){ return typeof v === 'number' && isFinite(v); }, /** * Returns true if the passed value is a string. * @param {Mixed} value The value to test * @return {Boolean} */ isString : function(v){ return typeof v === 'string'; }, /** * Returns true if the passed value is a boolean. * @param {Mixed} value The value to test * @return {Boolean} */ isBoolean : function(v){ return typeof v === 'boolean'; }, /** * Returns true if the passed value is an HTMLElement * @param {Mixed} value The value to test * @return {Boolean} */ isElement : function(v) { return !!v && v.tagName; }, /** * Returns true if the passed value is not undefined. * @param {Mixed} value The value to test * @return {Boolean} */ isDefined : function(v){ return typeof v !== 'undefined'; }, /** * True if the detected browser is Opera. * @type Boolean */ isOpera : isOpera, /** * True if the detected browser uses WebKit. * @type Boolean */ isWebKit : isWebKit, /** * True if the detected browser is Chrome. * @type Boolean */ isChrome : isChrome, /** * True if the detected browser is Safari. * @type Boolean */ isSafari : isSafari, /** * True if the detected browser is Safari 3.x. * @type Boolean */ isSafari3 : isSafari3, /** * True if the detected browser is Safari 4.x. * @type Boolean */ isSafari4 : isSafari4, /** * True if the detected browser is Safari 2.x. * @type Boolean */ isSafari2 : isSafari2, /** * True if the detected browser is Internet Explorer. * @type Boolean */ isIE : isIE, /** * True if the detected browser is Internet Explorer 6.x. * @type Boolean */ isIE6 : isIE6, /** * True if the detected browser is Internet Explorer 7.x. * @type Boolean */ isIE7 : isIE7, /** * True if the detected browser is Internet Explorer 8.x. * @type Boolean */ isIE8 : isIE8, /** * True if the detected browser uses the Gecko layout engine (e.g. Mozilla, Firefox). * @type Boolean */ isGecko : isGecko, /** * True if the detected browser uses a pre-Gecko 1.9 layout engine (e.g. Firefox 2.x). * @type Boolean */ isGecko2 : isGecko2, /** * True if the detected browser uses a Gecko 1.9+ layout engine (e.g. Firefox 3.x). * @type Boolean */ isGecko3 : isGecko3, /** * True if the detected browser is Internet Explorer running in non-strict mode. * @type Boolean */ isBorderBox : isBorderBox, /** * True if the detected platform is Linux. * @type Boolean */ isLinux : isLinux, /** * True if the detected platform is Windows. * @type Boolean */ isWindows : isWindows, /** * True if the detected platform is Mac OS. * @type Boolean */ isMac : isMac, /** * True if the detected platform is Adobe Air. * @type Boolean */ isAir : isAir }); /** * Creates namespaces to be used for scoping variables and classes so that they are not global. * Specifying the last node of a namespace implicitly creates all other nodes. Usage: * <pre><code> Ext.namespace('Company', 'Company.data'); Ext.namespace('Company.data'); // equivalent and preferable to above syntax Company.Widget = function() { ... } Company.data.CustomStore = function(config) { ... } </code></pre> * @param {String} namespace1 * @param {String} namespace2 * @param {String} etc * @return {Object} The namespace object. (If multiple arguments are passed, this will be the last namespace created) * @method ns */ Ext.ns = Ext.namespace; })(); Ext.ns("Ext.util", "Ext.lib", "Ext.data"); Ext.elCache = {}; /** * @class Function * These functions are available on every Function object (any JavaScript function). */ Ext.apply(Function.prototype, { /** * Creates an interceptor function. The passed function is called before the original one. If it returns false, * the original one is not called. The resulting function returns the results of the original function. * The passed function is called with the parameters of the original function. Example usage: * <pre><code> var sayHi = function(name){ alert('Hi, ' + name); } sayHi('Fred'); // alerts "Hi, Fred" // create a new function that validates input without // directly modifying the original function: var sayHiToFriend = sayHi.createInterceptor(function(name){ return name == 'Brian'; }); sayHiToFriend('Fred'); // no alert sayHiToFriend('Brian'); // alerts "Hi, Brian" </code></pre> * @param {Function} fcn The function to call before the original * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the passed function is executed. * <b>If omitted, defaults to the scope in which the original function is called or the browser window.</b> * @return {Function} The new function */ createInterceptor : function(fcn, scope){ var method = this; return !Ext.isFunction(fcn) ? this : function() { var me = this, args = arguments; fcn.target = me; fcn.method = method; return (fcn.apply(scope || me || window, args) !== false) ? method.apply(me || window, args) : null; }; }, /** * Creates a callback that passes arguments[0], arguments[1], arguments[2], ... * Call directly on any function. Example: <code>myFunction.createCallback(arg1, arg2)</code> * Will create a function that is bound to those 2 args. <b>If a specific scope is required in the * callback, use {@link #createDelegate} instead.</b> The function returned by createCallback always * executes in the window scope. * <p>This method is required when you want to pass arguments to a callback function. If no arguments * are needed, you can simply pass a reference to the function as a callback (e.g., callback: myFn). * However, if you tried to pass a function with arguments (e.g., callback: myFn(arg1, arg2)) the function * would simply execute immediately when the code is parsed. Example usage: * <pre><code> var sayHi = function(name){ alert('Hi, ' + name); } // clicking the button alerts "Hi, Fred" new Ext.Button({ text: 'Say Hi', renderTo: Ext.getBody(), handler: sayHi.createCallback('Fred') }); </code></pre> * @return {Function} The new function */ createCallback : function(/*args...*/){ // make args available, in function below var args = arguments, method = this; return function() { return method.apply(window, args); }; }, /** * Creates a delegate (callback) that sets the scope to obj. * Call directly on any function. Example: <code>this.myFunction.createDelegate(this, [arg1, arg2])</code> * Will create a function that is automatically scoped to obj so that the <tt>this</tt> variable inside the * callback points to obj. Example usage: * <pre><code> var sayHi = function(name){ // Note this use of "this.text" here. This function expects to // execute within a scope that contains a text property. In this // example, the "this" variable is pointing to the btn object that // was passed in createDelegate below. alert('Hi, ' + name + '. You clicked the "' + this.text + '" button.'); } var btn = new Ext.Button({ text: 'Say Hi', renderTo: Ext.getBody() }); // This callback will execute in the scope of the // button instance. Clicking the button alerts // "Hi, Fred. You clicked the "Say Hi" button." btn.on('click', sayHi.createDelegate(btn, ['Fred'])); </code></pre> * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed. * <b>If omitted, defaults to the browser window.</b> * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller) * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding, * if a number the args are inserted at the specified position * @return {Function} The new function */ createDelegate : function(obj, args, appendArgs){ var method = this; return function() { var callArgs = args || arguments; if (appendArgs === true){ callArgs = Array.prototype.slice.call(arguments, 0); callArgs = callArgs.concat(args); }else if (Ext.isNumber(appendArgs)){ callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first var applyArgs = [appendArgs, 0].concat(args); // create method call params Array.prototype.splice.apply(callArgs, applyArgs); // splice them in } return method.apply(obj || window, callArgs); }; }, /** * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage: * <pre><code> var sayHi = function(name){ alert('Hi, ' + name); } // executes immediately: sayHi('Fred'); // executes after 2 seconds: sayHi.defer(2000, this, ['Fred']); // this syntax is sometimes useful for deferring // execution of an anonymous function: (function(){ alert('Anonymous'); }).defer(100); </code></pre> * @param {Number} millis The number of milliseconds for the setTimeout call (if less than or equal to 0 the function is executed immediately) * @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed. * <b>If omitted, defaults to the browser window.</b> * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller) * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding, * if a number the args are inserted at the specified position * @return {Number} The timeout id that can be used with clearTimeout */ defer : function(millis, obj, args, appendArgs){ var fn = this.createDelegate(obj, args, appendArgs); if(millis > 0){ return setTimeout(fn, millis); } fn(); return 0; } }); /** * @class String * These functions are available on every String object. */ Ext.applyIf(String, { /** * Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each * token must be unique, and must increment in the format {0}, {1}, etc. Example usage: * <pre><code> var cls = 'my-class', text = 'Some text'; var s = String.format('&lt;div class="{0}">{1}&lt;/div>', cls, text); // s now contains the string: '&lt;div class="my-class">Some text&lt;/div>' * </code></pre> * @param {String} string The tokenized string to be formatted * @param {String} value1 The value to replace token {0} * @param {String} value2 Etc... * @return {String} The formatted string * @static */ format : function(format){ var args = Ext.toArray(arguments, 1); return format.replace(/\{(\d+)\}/g, function(m, i){ return args[i]; }); } }); /** * @class Array */ Ext.applyIf(Array.prototype, { /** * Checks whether or not the specified object exists in the array. * @param {Object} o The object to check for * @param {Number} from (Optional) The index at which to begin the search * @return {Number} The index of o in the array (or -1 if it is not found) */ indexOf : function(o, from){ var len = this.length; from = from || 0; from += (from < 0) ? len : 0; for (; from < len; ++from){ if(this[from] === o){ return from; } } return -1; }, /** * Removes the specified object from the array. If the object is not found nothing happens. * @param {Object} o The object to remove * @return {Array} this array */ remove : function(o){ var index = this.indexOf(o); if(index != -1){ this.splice(index, 1); } return this; } });
togucms/Frontend
Ext_core/Ext.js
JavaScript
gpl-3.0
37,408
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateNotifications extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('notifications', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->longText('message'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('notifications'); } }
NET2SOFTWARE/mynt
database/migrations/2017_07_01_055624_create_notifications.php
PHP
gpl-3.0
683
<?php class ControllerStartupEvent extends Controller { public function index() { // Add events from the DB $this->load->model('extension/event'); $results = $this->model_extension_event->getEvents(); foreach ($results as $result) { if ((substr($result['trigger'], 0, 6) == 'admin/') && $result['status']) { $this->event->register(substr($result['trigger'], 6), new Action($result['action'])); } } } }
robe4st/ideal-opencart
upload/admin/controller/startup/event.php
PHP
gpl-3.0
445
STBEngine ========= All-Purpose Game Engine
kenoba10/STBEngine
README.md
Markdown
gpl-3.0
45
class AddSurfaceIntervalToDives < ActiveRecord::Migration def change add_column :dives, :surface_interval, :integer end end
Diveboard/diveboard-web
db/migrate/20140426125550_add_surface_interval_to_dives.rb
Ruby
gpl-3.0
132
<?php /** * bbf functions and definitions * * @package bbf */ error_reporting(E_ALL); function catch_that_image($width, $height) { global $post, $posts; $first_img = ''; ob_start(); ob_end_clean(); $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); if (is_array($matches) && is_array($matches[1]) && isset($matches[1][0])) { $first_img = $matches [1] [0]; } if(empty($first_img)){ //Defines a default image $first_img = "http://fpoimg.com/".$width."x".$height."?text=No Image"; } return $first_img; } function bbf_substr($str, $start = 0, $end = 0) { if (strlen($str) < ($end - $start)) { return $str; } else { return (mb_substr($str, $start, $end)); } } function bbf_strip($content) { return preg_replace("~(?:\[/?)[^/\]]+/?\]~s", '', $content); } /*****************************************\ 处理各种action及filter \*****************************************/ //自定义title add_action('wp_title', 'rw_title', 10, 3); function rw_title($title, $sep, $direction){ global $page, $paged; if ($direction == 'right') { $title .= get_bloginfo('name'); } else{ $title = get_bloginfo('name').$title; } $desc = get_bloginfo('description', 'display'); if ($desc && (is_home() || is_front_page())) { $title .= "{$sep}{$desc}"; } if ($paged >=2 || $page >= 2) { $title .= "{$sep}"."第".max($page, $paged)."页"; } return $title; } add_action( 'after_setup_theme', 'custom_theme_setup' ); function custom_theme_setup() { add_theme_support('post-thumbnails', array( 'post' )); add_image_size( 'gallery', 210, 160, true); add_image_size( 'thumb-list', 64, 64 ); } function autoset_featured() { global $post; $already_has_thumb = has_post_thumbnail($post->ID); if (!$already_has_thumb) { $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" ); if ($attached_image) { foreach ($attached_image as $attachment_id => $attachment) { set_post_thumbnail($post->ID, $attachment_id); } } } } add_action('the_post', 'autoset_featured'); add_action('save_post', 'autoset_featured'); add_action('draft_to_publish', 'autoset_featured'); add_action('new_to_publish', 'autoset_featured'); add_action('pending_to_publish', 'autoset_featured'); add_action('future_to_publish', 'autoset_featured'); add_filter('show_admin_bar', '__return_false'); //隐藏部分后台设置选项 function remove_menus(){ remove_menu_page( 'index.php' ); //Dashboard remove_menu_page( 'themes.php'); //Appearance remove_menu_page( 'plugins.php' ); //Plugins remove_menu_page( 'tools.php' ); //Tools remove_menu_page( 'edit-comments.php' ); //Comments } add_action( 'admin_menu', 'remove_menus' ); function remove_wp_open_sans() { wp_deregister_style( 'open-sans' ); wp_register_style( 'open-sans', false ); } add_action('wp_enqueue_scripts', 'remove_wp_open_sans'); function remove_open_sans() { wp_deregister_style( 'open-sans' ); wp_register_style( 'open-sans', false ); wp_enqueue_style('open-sans',''); } add_action( 'init', 'remove_open_sans' ); function my_login_logo() { ?> <style type="text/css"> .login h1 a { background-image: url(<?php echo get_stylesheet_directory_uri(); ?>/images/logo.png); background-size: auto; width: auto; } </style> <?php } add_action( 'login_enqueue_scripts', 'my_login_logo' ); function custom_colors() { ?> <style type="text/css"> #wp-admin-bar-wp-logo {display: none;} #wpfooter {visibility: hidden;} </style> <?php } add_action('admin_head', 'custom_colors'); add_action( 'admin_menu', 'register_my_custom_menu_page' ); function register_my_custom_menu_page() { add_menu_page( '管理轮播图', '轮播图', 'manage_options', 'edit.php?category_name=banner', '', '', 6 ); } //面包屑导航 function dimox_breadcrumbs() { /* === OPTIONS === */ $text['home'] = '主页'; // text for the 'Home' link $text['category'] = '%s'; // text for a category page $text['search'] = 'Search Results for "%s" Query'; // text for a search results page $text['tag'] = 'Posts Tagged "%s"'; // text for a tag page $text['author'] = 'Articles Posted by %s'; // text for an author page $text['404'] = 'Error 404'; // text for the 404 page $show_current = 1; // 1 - show current post/page/category title in breadcrumbs, 0 - don't show $show_on_home = 0; // 1 - show breadcrumbs on the homepage, 0 - don't show $show_home_link = 1; // 1 - show the 'Home' link, 0 - don't show $show_title = 1; // 1 - show the title for the links, 0 - don't show $delimiter = ' &gt; '; // delimiter between crumbs $before = '<span class="current">'; // tag before the current crumb $after = '</span>'; // tag after the current crumb /* === END OF OPTIONS === */ global $post; if ($post == null) { return null; } $home_link = home_url('/'); $link_before = '<span typeof="v:Breadcrumb">'; $link_after = '</span>'; $link_attr = ' rel="v:url" property="v:title"'; $link = $link_before . '<a' . $link_attr . ' href="%1$s">%2$s</a>' . $link_after; $parent_id = $parent_id_2 = $post->post_parent; $frontpage_id = get_option('page_on_front'); if (is_home() || is_front_page()) { if ($show_on_home == 1) echo '<p class="breadcrumbs"><a href="' . $home_link . '">' . $text['home'] . '</a></p>'; } else { echo '<p class="breadcrumbs" xmlns:v="http://rdf.data-vocabulary.org/#">当前位置:'; if ($show_home_link == 1) { echo '<a href="' . $home_link . '" rel="v:url" property="v:title">' . $text['home'] . '</a>'; if ($frontpage_id == 0 || $parent_id != $frontpage_id) echo $delimiter; } if ( is_category() ) { $this_cat = get_category(get_query_var('cat'), false); if ($this_cat->parent != 0) { $cats = get_category_parents($this_cat->parent, TRUE, $delimiter); if ($show_current == 0) $cats = preg_replace("#^(.+)$delimiter$#", "$1", $cats); $cats = str_replace('<a', $link_before . '<a' . $link_attr, $cats); $cats = str_replace('</a>', '</a>' . $link_after, $cats); if ($show_title == 0) $cats = preg_replace('/ title="(.*?)"/', '', $cats); echo $cats; } if ($show_current == 1) echo $before . sprintf($text['category'], single_cat_title('', false)) . $after; } elseif ( is_search() ) { echo $before . sprintf($text['search'], get_search_query()) . $after; } elseif ( is_day() ) { echo sprintf($link, get_year_link(get_the_time('Y')), get_the_time('Y')) . $delimiter; echo sprintf($link, get_month_link(get_the_time('Y'),get_the_time('m')), get_the_time('F')) . $delimiter; echo $before . get_the_time('d') . $after; } elseif ( is_month() ) { echo sprintf($link, get_year_link(get_the_time('Y')), get_the_time('Y')) . $delimiter; echo $before . get_the_time('F') . $after; } elseif ( is_year() ) { echo $before . get_the_time('Y') . $after; } elseif ( is_single() && !is_attachment() ) { if ( get_post_type() != 'post' ) { $post_type = get_post_type_object(get_post_type()); $slug = $post_type->rewrite; printf($link, $home_link . $slug['slug'] . '/', $post_type->labels->singular_name); if ($show_current == 1) echo $delimiter . $before . '正文' . $after; } else { $cat = get_the_category(); $cat = $cat[0]; $cats = get_category_parents($cat, TRUE, $delimiter); if ($show_current == 0) $cats = preg_replace("#^(.+)$delimiter$#", "$1", $cats); $cats = str_replace('<a', $link_before . '<a' . $link_attr, $cats); $cats = str_replace('</a>', '</a>' . $link_after, $cats); if ($show_title == 0) $cats = preg_replace('/ title="(.*?)"/', '', $cats); echo $cats; if ($show_current == 1) echo $before . '正文' . $after; } } elseif ( !is_single() && !is_page() && get_post_type() != 'post' && !is_404() ) { $post_type = get_post_type_object(get_post_type()); echo $before . $post_type->labels->singular_name . $after; } elseif ( is_attachment() ) { $parent = get_post($parent_id); $cat = get_the_category($parent->ID); $cat = $cat[0]; if ($cat) { $cats = get_category_parents($cat, TRUE, $delimiter); $cats = str_replace('<a', $link_before . '<a' . $link_attr, $cats); $cats = str_replace('</a>', '</a>' . $link_after, $cats); if ($show_title == 0) $cats = preg_replace('/ title="(.*?)"/', '', $cats); echo $cats; } printf($link, get_permalink($parent), $parent->post_title); if ($show_current == 1) echo $delimiter . $before . get_the_title() . $after; } elseif ( is_page() && !$parent_id ) { if ($show_current == 1) echo $before . get_the_title() . $after; } elseif ( is_page() && $parent_id ) { if ($parent_id != $frontpage_id) { $breadcrumbs = array(); while ($parent_id) { $page = get_page($parent_id); if ($parent_id != $frontpage_id) { $breadcrumbs[] = sprintf($link, get_permalink($page->ID), get_the_title($page->ID)); } $parent_id = $page->post_parent; } $breadcrumbs = array_reverse($breadcrumbs); for ($i = 0; $i < count($breadcrumbs); $i++) { echo $breadcrumbs[$i]; if ($i != count($breadcrumbs)-1) echo $delimiter; } } if ($show_current == 1) { if ($show_home_link == 1 || ($parent_id_2 != 0 && $parent_id_2 != $frontpage_id)) echo $delimiter; echo $before . get_the_title() . $after; } } elseif ( is_tag() ) { echo $before . sprintf($text['tag'], single_tag_title('', false)) . $after; } elseif ( is_author() ) { global $author; $userdata = get_userdata($author); echo $before . sprintf($text['author'], $userdata->display_name) . $after; } elseif ( is_404() ) { echo $before . $text['404'] . $after; } elseif ( has_post_format() && !is_singular() ) { echo get_post_format_string( get_post_format() ); } if ( get_query_var('paged') ) { if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ' ('; echo __('第') . get_query_var('paged').('页'); if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ')'; } echo '</p><!-- .breadcrumbs -->'; } } //添加自定义配置页 add_action('admin_menu', 'add_global_custom_options'); function add_global_custom_options() { add_options_page('公司信息设置', '公司信息', 'manage_options', 'functions', 'global_custom_options'); } function global_custom_options() { ?> <div class="wrap"> <h2>公司信息设置</h2> <form method="post" action="options.php"> <?php wp_nonce_field('update-options') ?> <p><strong>主要联系电话</strong>(显示在首页)<br /> <input type="text" name="primary_phone_num" size="45" value="<?php echo get_option('primary_phone_num'); ?>" /> </p> <p><strong>主要联系地址</strong>(显示在首页)<br /> <input type="text" name="primary_address" value="<?php echo get_option('primary_address'); ?>" /> </p> <p><input type="submit" name="Submit" value="更新" /></p> <input type="hidden" name="action" value="update" /> <input type="hidden" name="page_options" value="primary_phone_num, primary_address" /> </form> </div> <?php }
jasonslyvia/bbf
src/functions.php
PHP
gpl-3.0
11,881
(function($) { "use strict"; function getCatalog() { return $.ajax("../catalog/catalog.json", {dataType: "json"}); } function getMetadata(layer_id) { var layer_params = { "id": layer_id.split('/')[0], "var": layer_id.split('/')[1] }; return $.ajax({ url: "../metadata.json?request=GetMinMaxWithUnits", data: layer_params }); } function getRasterAccordionMenuData(ensembleName) { var url = '../menu.json?ensemble_name=' + ensembleName; return $.ajax(url, {dataType: "json"}); } function getNCWMSLayerCapabilities(ncwms_layer) { // FIXME: this .ajax logic doesn't really work in all cases // What we really want is the fail() handler to _resolve_ the status, // and then have another fail() fallthrough handler .That is impossible, however. // see: http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/ var deferred = $.Deferred(); var params = { REQUEST: "GetCapabilities", SERVICE: "WMS", VERSION: "1.1.1", DATASET: ncwms_layer.params.LAYERS.split("/")[0] }; $.ajax({ url: ncwms_layer.url, data: params, }) .fail(handle_ie8_xml) .always(function (response, status, jqXHR) { deferred.resolve($(jqXHR.responseXML)); }); return deferred.promise(); } function getNcwmsLayerDDS(layerUrl) { return $.ajax({ url: (layerUrl + ".dds?time") }) } function getNcwmsLayerDAS(layerUrl) { return $.ajax({ url: (layerUrl + ".das") }) } function getStationCount(data, success) { return $.ajax({ url: '../count_stations', data: data, type: 'GET', dataType: 'json', success: success }); } function getRecordLength(data, success) { return $.ajax({ url: '../record_length', data: data, type: 'GET', dataType: 'json', success: success }); } // returns a list of station locations and names from a CSV file. // there are two such lists, one for the current CMIP5 hydro station // data, and the other for the archive CMIP3 data function getRoutedFlowMetadata(isArchivePortal) { const resource = isArchivePortal ? "routed_flow_metadatav4" : "hydro_stn_cmip5_metadata"; return $.ajax(pdp.app_root + "/csv/" + resource + ".csv"); } function layerDataUrl(ncwmsLayer, catalog) { // Return OpENDAP data URL given an ncWMS layer and layer catalog. // TODO: Use this fn wherever the URL is computed in code. const datasetName = ncwmsLayer.params.LAYERS.split('/')[0]; return catalog[datasetName]; } function getLatLonValues(ncwmsLayer, catalog) { // Get the latitude and longitude values associated with an ncWMS layer // These values are retrieved using the OpENDAP data service that also // serves the actual data downloads. In order to form the URL for this // service, we need the layer catalog, passed in as `catalog`. function convertResponse(data) { // Convert text response to a JS object. // Response comes as pairs of lines, each terminated by a newline. // First line in pair contains name of variable. Second contains // values, enclosed in brackets and separated by ', ' (i.e., a JSON // array). const lines = data.split("\n"); const result = {}; for (let i = 0; i < lines.length - 1; i += 2) { result[lines[i]] = JSON.parse(lines[i + 1]); } return result; } return $.ajax({ url: `${layerDataUrl(ncwmsLayer, catalog)}.ascii?lat,lon`, dataType: 'text', dataFilter: convertResponse, }); } condExport(module, { getCatalog: getCatalog, getMetadata: getMetadata, getRasterAccordionMenuData: getRasterAccordionMenuData, getNCWMSLayerCapabilities: getNCWMSLayerCapabilities, getNcwmsLayerDDS: getNcwmsLayerDDS, getNcwmsLayerDAS: getNcwmsLayerDAS, getStationCount: getStationCount, getRecordLength: getRecordLength, getRoutedFlowMetadata: getRoutedFlowMetadata, getLatLonValues: getLatLonValues, layerDataUrl: layerDataUrl, }, 'dataServices'); })(jQuery);
pacificclimate/pdp
pdp/static/js/data-services.js
JavaScript
gpl-3.0
4,664
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import time import datetime import sqlite3 import sickbeard from sickbeard import db from sickbeard import logger from sickbeard.common import Quality from sickbeard import helpers, exceptions, show_name_helpers, scene_exceptions from sickbeard import name_cache from sickbeard.exceptions import ex #import xml.etree.cElementTree as etree import xml.dom.minidom from lib.tvdb_api import tvdb_api, tvdb_exceptions from sickbeard.completparser import CompleteParser class CacheDBConnection(db.DBConnection): def __init__(self, providerName): db.DBConnection.__init__(self, "cache.db") # Create the table if it's not already there try: sql = "CREATE TABLE "+providerName+" (name TEXT, season NUMERIC, episodes TEXT, tvrid NUMERIC, tvdbid NUMERIC, url TEXT, time NUMERIC, quality TEXT, release_group TEXT, proper NUMERIC);" self.connection.execute(sql) self.connection.commit() except sqlite3.OperationalError, e: if str(e) != "table "+providerName+" already exists": raise # Create the table if it's not already there try: sql = "CREATE TABLE lastUpdate (provider TEXT, time NUMERIC);" self.connection.execute(sql) self.connection.commit() except sqlite3.OperationalError, e: if str(e) != "table lastUpdate already exists": raise class TVCache(): def __init__(self, provider): self.provider = provider self.providerID = self.provider.getID() self.minTime = 10 def _getDB(self): return CacheDBConnection(self.providerID) def _clearCache(self): myDB = self._getDB() myDB.action("DELETE FROM "+self.providerID+" WHERE 1") def _getRSSData(self): data = None return data def _checkAuth(self, data): return True def _checkItemAuth(self, title, url): return True def updateCache(self): if not self.shouldUpdate(): return data = self._getRSSData() # as long as the http request worked we count this as an update if data: self.setLastUpdate() else: return [] # now that we've loaded the current RSS feed lets delete the old cache logger.log(u"Clearing "+self.provider.name+" cache and updating with new information") self._clearCache() if not self._checkAuth(data): raise exceptions.AuthException("Your authentication info for "+self.provider.name+" is incorrect, check your config") try: parsedXML = xml.dom.minidom.parseString(data) items = parsedXML.getElementsByTagName('item') except Exception, e: logger.log(u"Error trying to load "+self.provider.name+" RSS feed: "+ex(e), logger.ERROR) logger.log(u"Feed contents: "+repr(data), logger.DEBUG) return [] if parsedXML.documentElement.tagName != 'rss': logger.log(u"Resulting XML from "+self.provider.name+" isn't RSS, not parsing it", logger.ERROR) return [] for item in items: self._parseItem(item) def _translateLinkURL(self, url): return url.replace('&amp;','&') def _parseItem(self, item): """Return None parse a single rss feed item and add its info to the chache will check for needed infos """ title = helpers.get_xml_text(item.getElementsByTagName('title')[0]) url = helpers.get_xml_text(item.getElementsByTagName('link')[0]) self._checkItemAuth(title, url) # we at least need a title and url, if one is missing stop if not title or not url: logger.log(u"The XML returned from the "+self.provider.name+" feed is incomplete, this result is unusable", logger.ERROR) return url = self._translateLinkURL(url) logger.log(u"Adding item from RSS to cache: "+title, logger.DEBUG) self._addCacheEntry(title, url) def _getLastUpdate(self): myDB = self._getDB() sqlResults = myDB.select("SELECT time FROM lastUpdate WHERE provider = ?", [self.providerID]) if sqlResults: lastTime = int(sqlResults[0]["time"]) else: lastTime = 0 return datetime.datetime.fromtimestamp(lastTime) def setLastUpdate(self, toDate=None): if not toDate: toDate = datetime.datetime.today() myDB = self._getDB() myDB.upsert("lastUpdate", {'time': int(time.mktime(toDate.timetuple()))}, {'provider': self.providerID}) lastUpdate = property(_getLastUpdate) def shouldUpdate(self): # if we've updated recently then skip the update if datetime.datetime.today() - self.lastUpdate < datetime.timedelta(minutes=self.minTime): logger.log(u"Last update was too soon, using old cache: today()-"+str(self.lastUpdate)+"<"+str(datetime.timedelta(minutes=self.minTime)), logger.DEBUG) return False return True def _addCacheEntry(self, name, url, season=None, episodes=None, tvdb_id=0, tvrage_id=0, quality=None, extraNames=[]): """Return False|None Parse the name and try to get as much info out of it as we can Will use anime regex's if this is called from fanzub On a succesfull parse it will add the parsed infos into the cache.db This dosen't mean the parsed result is usefull """ myDB = self._getDB() show = None if tvdb_id: show = helpers.findCertainShow(sickbeard.showList, tvdb_id) # if we don't have complete info then parse the filename to get it for curName in [name] + extraNames: cp = CompleteParser(show=show) cpr = cp.parse(curName) if cpr.sxxexx and cpr.parse_result: break else: return False episodeText = "|"+"|".join(map(str, cpr.episodes))+"|" # get the current timestamp curTimestamp = int(time.mktime(datetime.datetime.today().timetuple())) myDB.action("INSERT INTO "+self.providerID+" (name, season, episodes, tvrid, tvdbid, url, time, quality, release_group, proper) VALUES (?,?,?,?,?,?,?,?,?,?)", [name, cpr.season, episodeText, 0, cpr.tvdbid, url, curTimestamp, cpr.quality, cpr.release_group, int(cpr.is_proper)]) def searchCache(self, episode, manualSearch=False): neededEps = self.findNeededEpisodes(episode, manualSearch) return neededEps[episode] def listPropers(self, date=None, delimiter="."): myDB = self._getDB() sql = "SELECT * FROM "+self.providerID+" WHERE proper = 1" if date != None: sql += " AND time >= "+str(int(time.mktime(date.timetuple()))) #return filter(lambda x: x['tvdbid'] != 0, myDB.select(sql)) return myDB.select(sql) def findNeededEpisodes(self, episode = None, manualSearch=False): neededEps = {} if episode: neededEps[episode] = [] myDB = self._getDB() if not episode: sqlResults = myDB.select("SELECT * FROM "+self.providerID) else: sqlResults = myDB.select("SELECT * FROM "+self.providerID+" WHERE tvdbid = ? AND season = ? AND episodes LIKE ?", [episode.show.tvdbid, episode.scene_season, "%|"+str(episode.scene_episode)+"|%"]) # for each cache entry for curResult in sqlResults: # skip non-tv crap (but allow them for Newzbin cause we assume it's filtered well) if self.providerID != 'newzbin' and not show_name_helpers.filterBadReleases(curResult["name"]): continue # get the show object, or if it's not one of our shows then ignore it showObj = helpers.findCertainShow(sickbeard.showList, int(curResult["tvdbid"])) if not showObj: continue # get season and ep data (ignoring multi-eps for now) curSeason = int(curResult["season"]) if curSeason == -1: continue curEp = curResult["episodes"].split("|")[1] if not curEp: continue curEp = int(curEp) curQuality = int(curResult["quality"]) # if the show says we want that episode then add it to the list if not showObj.wantEpisode(curSeason, curEp, curQuality, manualSearch): logger.log(u"Skipping "+curResult["name"]+" because we don't want an episode that's "+Quality.qualityStrings[curQuality], logger.DEBUG) else: if episode: epObj = episode else: epObj = showObj.getEpisode(curSeason, curEp) # build a result object title = curResult["name"] url = curResult["url"] logger.log(u"Found result " + title + " at " + url) result = self.provider.getResult([epObj]) result.url = url result.name = title result.quality = curQuality result.release_group = curResult["release_group"] # add it to the list if epObj not in neededEps: neededEps[epObj] = [result] else: neededEps[epObj].append(result) return neededEps
Pakoach/Sick-Beard-Animes
sickbeard/tvcache.py
Python
gpl-3.0
10,306
TESTING!
dlc123/raceto10
docs/index.html
HTML
gpl-3.0
9
from DIRAC import S_ERROR, S_OK, gLogger from DIRAC.DataManagementSystem.private.FTSAbstractPlacement import FTSAbstractPlacement, FTSRoute from DIRAC.ConfigurationSystem.Client.Helpers.Resources import getFTS3Servers from DIRAC.ResourceStatusSystem.Client.ResourceStatus import ResourceStatus import random class FTS3Placement( FTSAbstractPlacement ): """ This class manages all the FTS strategies, routes and what not """ __serverPolicy = "Random" __nextServerID = 0 __serverList = None __maxAttempts = 0 def __init__( self, csPath = None, ftsHistoryViews = None ): """ Call the init of the parent, and initialize the list of FTS3 servers """ self.log = gLogger.getSubLogger( "FTS3Placement" ) super( FTS3Placement, self ).__init__( csPath = csPath, ftsHistoryViews = ftsHistoryViews ) srvList = getFTS3Servers() if not srvList['OK']: self.log.error( srvList['Message'] ) self.__serverList = srvList.get( 'Value', [] ) self.maxAttempts = len( self.__serverList ) self.rssClient = ResourceStatus() def getReplicationTree( self, sourceSEs, targetSEs, size, strategy = None ): """ For multiple source to multiple destination, find the optimal replication strategy. :param sourceSEs : list of source SE :param targetSEs : list of destination SE :param size : size of the File :param strategy : which strategy to use :returns S_OK(dict) < route name : { dict with key Ancestor, SourceSE, TargetSEtargetSE, Strategy } > For the time being, we are waiting for FTS3 to provide advisory mechanisms. So we just use simple techniques """ # We will use a single random source sourceSE = random.choice( sourceSEs ) tree = {} for targetSE in targetSEs: tree["%s#%s" % ( sourceSE, targetSE )] = { "Ancestor" : False, "SourceSE" : sourceSE, "TargetSE" : targetSE, "Strategy" : "FTS3Simple" } return S_OK( tree ) def refresh( self, ftsHistoryViews ): """ Refresh, whatever that means... recalculate all what you need, fetches the latest conf and what not. """ return super( FTS3Placement, self ).refresh( ftsHistoryViews = ftsHistoryViews ) def __failoverServerPolicy(self, attempt = 0): """ Returns always the server at a given position (normally the first one) :param attempt: position of the server in the list """ if attempt >= len( self.__serverList ): raise Exception( "FTS3Placement.__failoverServerPolicy: attempt to reach non existing server index" ) return self.__serverList[attempt] def __sequenceServerPolicy( self ): """ Every time the this policy is called, return the next server on the list """ fts3server = self.__serverList[self.__nextServerID] self.__nextServerID = ( self.__nextServerID + 1 ) % len( self.__serverList ) return fts3server def __randomServerPolicy(self): """ return a random server from the list """ return random.choice( self.__serverList ) def __chooseFTS3Server( self ): """ Choose the appropriate FTS3 server depending on the policy """ fts3Server = None attempt = 0 # FIXME : need to get real valeu from RSS ftsServerStatus = True while not fts3Server and attempt < self.maxAttempts: if self.__serverPolicy == 'Random': fts3Server = self.__randomServerPolicy() elif self.__serverPolicy == 'Sequence': fts3Server = self.__sequenceServerPolicy() elif self.__serverPolicy == 'Failover': fts3Server = self.__failoverServerPolicy( attempt = attempt ) else: self.log.error( 'Unknown server policy %s. Using Random instead' % self.__serverPolicy ) fts3Server = self.__randomServerPolicy() if not ftsServerStatus: self.log.warn( 'FTS server %s is not in good shape. Choose another one' % fts3Server ) fts3Server = None attempt += 1 # FIXME : I need to get the FTS server status from RSS # ftsStatusFromRss = rss.ftsStatusOrSomethingLikeThat if fts3Server: return S_OK( fts3Server ) return S_ERROR ( "Could not find an FTS3 server (max attempt reached)" ) def findRoute( self, sourceSE, targetSE ): """ Find the appropriate route from point A to B :param sourceSE : source SE :param targetSE : destination SE :returns S_OK(FTSRoute) """ fts3server = self.__chooseFTS3Server() if not fts3server['OK']: return fts3server fts3server = fts3server['Value'] route = FTSRoute( sourceSE, targetSE, fts3server ) return S_OK( route ) def isRouteValid( self, route ): """ FIXME: until RSS is ready, I check manually the status In FTS3, all routes are valid a priori. If a route was not valid for some reason, then FTS would know it thanks to the blacklist sent by RSS, and would deal with it itself. :param route : FTSRoute :returns S_OK or S_ERROR(reason) """ rAccess = self.rssClient.getStorageElementStatus( route.sourceSE, "ReadAccess" ) self.log.debug( "se read %s %s" % ( route.sourceSE, rAccess ) ) if not rAccess["OK"]: self.log.error( rAccess["Message"] ) return rAccess if rAccess["Value"][route.sourceSE]["ReadAccess"] not in ( "Active", "Degraded" ): return S_ERROR( "Source SE is not readable" ) wAccess = self.rssClient.getStorageElementStatus( route.targetSE, "WriteAccess" ) self.log.debug( "se write %s %s" % ( route.targetSE, wAccess ) ) if not wAccess["OK"]: self.log.error( wAccess["Message"] ) return wAccess if wAccess["Value"][route.targetSE]["WriteAccess"] not in ( "Active", "Degraded" ): return S_ERROR( "Target SE is not writable" ) return S_OK()
vmendez/DIRAC
DataManagementSystem/private/FTS3/FTS3Placement.py
Python
gpl-3.0
5,870
<!DOCTYPE html> <html> <head> <title>Ryhiner Tools</title> <meta charset="UTF-8"> </head> <body> <h1>Ryhiner Tools</h1> <ul> <li><a href="boundingBoxTool.html">Ryhiner Bounding Box Tool</a></li> <li><a href="centerBox.html">Ryhiner Center Box Tool</a></li> <li><a href="combine.html">Ryhiner Combine Tool</a></li> <li><a href="showPictures.html">Ryhiner Show Pictures Tool</a></li> <li><a href="split.html">Ryhiner Split Tool</a></li> </ul> <p>Siehe <a href="doc/RyhinerBoundingBoxToolDoku.pdf">Dokumentation (pdf, 2.63 MB)</a> f&uuml;r Erl&auml;uterungen und <a href="LICENSE">Copyright</a>.</p> <pre> Copyright 2012 Samuel Bucheli and Thomas Klöti, University Library Berne. This file is part of the Ryhiner Bounding Box Tool. The Ryhiner Bounding Box Tool is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The Ryhiner Bounding Box Tool is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the Ryhiner Bounding Box Tool. If not, see http://www.gnu.org/licenses/. </pre> </body> </html>
godfatherofpolka/RyhinerBoundingBoxTool
index.html
HTML
gpl-3.0
1,530
// For license of this file, see <project-root-folder>/LICENSE.md. #include "gui/toolbars/statusbar.h" #include "gui/dialogs/formmain.h" #include "gui/reusable/plaintoolbutton.h" #include "gui/reusable/progressbarwithtext.h" #include "gui/tabwidget.h" #include "miscellaneous/iconfactory.h" #include "miscellaneous/mutex.h" #include <QLabel> #include <QToolButton> StatusBar::StatusBar(QWidget* parent) : QStatusBar(parent) { setSizeGripEnabled(false); setContentsMargins(2, 0, 2, 2); m_barProgressFeeds = new ProgressBarWithText(this); m_barProgressFeeds->setTextVisible(true); m_barProgressFeeds->setFixedWidth(250); m_barProgressFeeds->setVisible(false); m_barProgressFeeds->setObjectName(QSL("m_barProgressFeeds")); m_barProgressFeedsAction = new QAction(qApp->icons()->fromTheme(QSL("application-rss+xml")), tr("Feed update progress bar"), this); m_barProgressFeedsAction->setObjectName(QSL("m_barProgressFeedsAction")); m_barProgressDownload = new ProgressBarWithText(this); m_barProgressDownload->setTextVisible(true); m_barProgressDownload->setFixedWidth(230); m_barProgressDownload->setVisible(false); m_barProgressDownload->setObjectName(QSL("m_barProgressDownload")); m_barProgressDownloadAction = new QAction(qApp->icons()->fromTheme(QSL("emblem-downloads")), tr("File download progress bar"), this); m_barProgressDownloadAction->setObjectName(QSL("m_barProgressDownloadAction")); m_barProgressDownload->installEventFilter(this); } StatusBar::~StatusBar() { clear(); qDebugNN << LOGSEC_GUI "Destroying StatusBar instance."; } QList<QAction*> StatusBar::availableActions() const { QList<QAction*> actions = qApp->userActions(); // Now, add placeholder actions for custom stuff. actions << m_barProgressDownloadAction << m_barProgressFeedsAction; return actions; } QList<QAction*> StatusBar::activatedActions() const { return actions(); } void StatusBar::saveAndSetActions(const QStringList& actions) { qApp->settings()->setValue(GROUP(GUI), GUI::StatusbarActions, actions.join(QSL(","))); loadSpecificActions(convertActions(actions)); } QStringList StatusBar::defaultActions() const { return QString(GUI::StatusbarActionsDef).split(',', #if QT_VERSION >= 0x050F00 // Qt >= 5.15.0 Qt::SplitBehaviorFlags::SkipEmptyParts); #else QString::SplitBehavior::SkipEmptyParts); #endif } QStringList StatusBar::savedActions() const { return qApp->settings()->value(GROUP(GUI), SETTING(GUI::StatusbarActions)).toString().split(',', #if QT_VERSION >= 0x050F00 // Qt >= 5.15.0 Qt::SplitBehaviorFlags::SkipEmptyParts); #else QString::SplitBehavior::SkipEmptyParts); #endif } QList<QAction*> StatusBar::convertActions(const QStringList& actions) { bool progress_visible = this->actions().contains(m_barProgressFeedsAction) && m_barProgressFeeds->isVisible(); QList<QAction*> available_actions = availableActions(); QList<QAction*> spec_actions; // Iterate action names and add respectable // actions into the toolbar. for (const QString& action_name : actions) { QAction* matching_action = findMatchingAction(action_name, available_actions); QAction* action_to_add; QWidget* widget_to_add; if (matching_action == m_barProgressDownloadAction) { widget_to_add = m_barProgressDownload; action_to_add = m_barProgressDownloadAction; widget_to_add->setVisible(false); } else if (matching_action == m_barProgressFeedsAction) { widget_to_add = m_barProgressFeeds; action_to_add = m_barProgressFeedsAction; widget_to_add->setVisible(progress_visible); } else { if (action_name == QSL(SEPARATOR_ACTION_NAME)) { QLabel* lbl = new QLabel(QSL("•"), this); widget_to_add = lbl; action_to_add = new QAction(this); action_to_add->setSeparator(true); } else if (action_name == QSL(SPACER_ACTION_NAME)) { QLabel* lbl = new QLabel(QSL("\t\t"), this); widget_to_add = lbl; action_to_add = new QAction(this); action_to_add->setIcon(qApp->icons()->fromTheme(QSL("system-search"))); action_to_add->setProperty("type", SPACER_ACTION_NAME); action_to_add->setProperty("name", tr("Toolbar spacer")); } else if (matching_action != nullptr) { // Add originally toolbar action. auto* tool_button = new PlainToolButton(this); tool_button->reactOnActionChange(matching_action); widget_to_add = tool_button; action_to_add = matching_action; connect(tool_button, &PlainToolButton::clicked, matching_action, &QAction::trigger); connect(matching_action, &QAction::changed, tool_button, &PlainToolButton::reactOnSenderActionChange); } else { action_to_add = nullptr; widget_to_add = nullptr; } } if (action_to_add != nullptr && widget_to_add != nullptr) { action_to_add->setProperty("widget", QVariant::fromValue(widget_to_add)); spec_actions.append(action_to_add); } } return spec_actions; } void StatusBar::loadSpecificActions(const QList<QAction*>& actions, bool initial_load) { if (initial_load) { clear(); for (QAction* act : actions) { QWidget* widget = act->property("widget").isValid() ? qvariant_cast<QWidget*>(act->property("widget")) : nullptr; addAction(act); // And also add widget. if (widget != nullptr) { addPermanentWidget(widget); } } } } bool StatusBar::eventFilter(QObject* watched, QEvent* event) { if (watched == m_barProgressDownload) { if (event->type() == QEvent::Type::MouseButtonPress) { qApp->mainForm()->tabWidget()->showDownloadManager(); } } return false; } void StatusBar::clear() { while (!actions().isEmpty()) { QAction* act = actions().at(0); QWidget* widget = act->property("widget").isValid() ? static_cast<QWidget*>(act->property("widget").value<void*>()) : nullptr; if (widget != nullptr) { removeWidget(widget); widget->setParent(qApp->mainFormWidget()); widget->setVisible(false); } removeAction(act); } } void StatusBar::showProgressFeeds(int progress, const QString& label) { if (actions().contains(m_barProgressFeedsAction)) { m_barProgressFeeds->setVisible(true); m_barProgressFeeds->setFormat(label); if (progress < 0) { m_barProgressFeeds->setRange(0, 0); } else { m_barProgressFeeds->setRange(0, 100); m_barProgressFeeds->setValue(progress); } } } void StatusBar::clearProgressFeeds() { m_barProgressFeeds->setVisible(false); } void StatusBar::showProgressDownload(int progress, const QString& tooltip) { if (actions().contains(m_barProgressDownloadAction)) { m_barProgressDownload->setVisible(true); m_barProgressDownload->setFormat(tooltip); m_barProgressDownload->setToolTip(tooltip); if (progress < 0) { m_barProgressDownload->setRange(0, 0); } else { m_barProgressDownload->setRange(0, 100); m_barProgressDownload->setValue(progress); } } } void StatusBar::clearProgressDownload() { m_barProgressDownload->setVisible(false); m_barProgressDownload->setValue(0); }
martinrotter/rssguard
src/librssguard/gui/toolbars/statusbar.cpp
C++
gpl-3.0
7,505
<?php namespace PaulGibbs\WordpressBehatExtension\Exception; use PaulGibbs\WordpressBehatExtension\Driver\DriverInterface; use Exception; /** * Exception to handle unsupported driver actions. */ class UnsupportedDriverActionException extends Exception { /** * Constructor. * * @param string $message Exception message. * @param int $code User-defined exception code. * @param unknown $previous If this was a nested exception, the previous exception. */ public function __construct($message = null, $code = 0, $previous = null) { parent::__construct( "No ability to {$message}. Maybe use another driver?", $code, $previous ); } }
stephenharris/behat-wordpress-extension
src/Exception/UnsupportedDriverActionException.php
PHP
gpl-3.0
741
var __v=[ { "Id": 21, "Tag": 21, "Name": "git", "Sort": 0 }, { "Id": 22, "Tag": 21, "Name": "svn", "Sort": 0 } ]
zuiwuchang/king-document
data/tags/21.js
JavaScript
gpl-3.0
145
/* mizu was here */ body > div#content-bg { z-index:-1;position:fixed; width:100%; height:100%; left:0; top:0; background:url(../../images/backgrounds/blur-background01.jpg) top center no-repeat; } /* main.css */ a{color:#26292e;} a:hover { color:#5e6b90; } body { background-color:#ccc; } /*noinspection CssInvalidPseudoSelector*/ input::-webkit-input-placeholder,textarea::-webkit-input-placeholder,input::-moz-placeholder,textarea::-moz-placeholder{color: #999; } .note { color:#666; } .flash-success { background-color:#000; } div.flash-success p { color:#FFF; } div.flash-success p,.flash-success a { color:#FFF;} #footer { background-color:#ccc; color: #111; } .button_dialog { color:#333333; background:-moz-linear-gradient(100% 100% 90deg, #ffc15d, #ffd773); background:-webkit-gradient(linear, 0% 0%, 0% 100%, from(#ffd773), to(#ffc15d)); background:-webkit-linear-gradient(#ffd773, #ffc15d); background:-o-linear-gradient(#ffd773, #ffc15d); } .hover, .button_dialog:hover { color:#FFFFFF; background:-moz-linear-gradient(100% 100% 90deg, #333333, #1a1a1a); background:-webkit-gradient(linear, 0% 0%, 0% 100%, from(#1a1a1a), to(#333333)); background:-webkit-linear-gradient(#1a1a1a, #333333); background:-o-linear-gradient(#1a1a1a, #333333); } .button_dialog.disabled:hover { background:none; color:#333333; } .error-summary { border:solid 2px #AE0303; background-color:#FFEFEF; } .error-summary p { color:#AE0303; } .success-summary { border:solid 2px #0BA55C; background-color:#C0FCDD; } .success-summary p { color:#0BA55C; } .demo-bar { background:none repeat scroll 0 0 #FFFF00; } .demo-inner { color:#333; } .demo-bar a { color:#666; } .demo-credentials { color:#666; } .export-item { border: 1px solid #C0C0C0; } .export-item:last-child {border-bottom: 1px solid #C0C0C0 } .export-item table.header { background-color: #E0E0E0; } .export-item .content table { background-color: #FFFF00; } .export-item.expanded table.header { background-color: #FFFF00;} .export-item table.header span.icon-edit { display: none; color: #FF4040; } .export-item .content tr.separator td { border-top: 1px solid #C0C0C0; } .export-item .content table.combi-fields { border: 1px solid #CCCCCC; } .export-item .content table.combi-fields td { background-color: #FFFFC0; } .export-controls { padding: 5px; border-top: 1px solid #FFFFFF; } .import-item { border: 1px solid #C0C0C0; } .import-item:last-child { border-bottom: 1px solid #C0C0C0; } .import-item.expanded table.header {background-color: yellow;} .import-item table.header { background-color: #E0E0E0; } .import-item table.header span.icon-edit { color: #FF4040; } .import-item .content table { background-color: #FFFF00; } .import-item .content tr.separator td {border-top: 1px solid #C0C0C0;} .import-item .content table.combi-fields {border: 1px solid #CCCCCC;} .import-item .content table.combi-fields td {background-color: #FFFFC0;} .import-controls {border-top: 1px solid #FFFFFF; } table.rules td {border-bottom:1px solid #FFF;} table.provision-info tr.active td, table.rules tr.active td {background-color: #a8f299;} div#error-box{ background: white;} div#error-box p { color: #888; } /* box.css */ /*noinspection CssInvalidPseudoSelector*/ ::-webkit-scrollbar-thumb { background-color:#BBB;} .styled-checkbox + label { background-color:#EEE; border:1px solid #CCC; } .styled-checkbox:checked + label { background-color:#26292e; border:1px solid #26292e; color:#FFF; } .styled-checkbox:checked + label:after { color:#FFF; } /*noinspection CssInvalidPseudoSelector*/ .scrollable::-webkit-scrollbar-track {border-left: 1px solid #BBB;} /*noinspection CssInvalidPseudoSelector*/ .scrollable::-webkit-scrollbar-thumb { background-color:#BBB;} /*noinspection CssInvalidPseudoSelector*/ ul.k-list::-webkit-scrollbar-track { background-color:#F5F4F8 !important; } /*noinspection CssInvalidPseudoSelector*/ ul.k-list::-webkit-scrollbar-thumb { background-color:#333 !important; border:1px solid white !important; } .box-placeholder { background-color:#252525; } .portlet-header { border-top:1px solid #6A6A6A; background-color: #2f3238; } .box_title_text, .portlet-title { color:#ccc; } .portlet-grid-info { color:#FFFF00; } p.separator { border-right:1px solid #555; } hr.separator { border-bottom:1px solid #BEBEBE; } div.portlet-msg { background-color:#FFF; } div.portlet-msg > p { color:#666; } .button_tooltip { color:#CCC; } .dialog_tooltip { color:#FFFF00; } .button_tooltip { color:#FFFF00; } div.portlet-buttons > a:after{ background-color:#26292e; color: #AAA; border:1px solid #26292e; } div.portlet-buttons > a:hover:after, div.portlet-buttons > a:hover{background-color:#26292e; border-color:#26292e; color:#FFFF00;} div.portlet-buttons a.toggle_button {background-color: #2F3238 !important; border: 1px solid #2F3238 !important;} div.portlet-buttons a.min_button:after{ background-color:#2f3238 !important; border:1px solid #2f3238 !important;} div.portlet-buttons a.min_button:hover:after{color:#FFFF00 !important;} div.portlet-buttons a.max_button:after{ background-color:#2f3238 !important; border:1px solid #2f3238 !important; } div.portlet-buttons a.max_button:hover:after{color:#FFFF00 !important;} a.delete:hover:after { background-color:#BC1010; color:#FAC8C8; border-color:#BC1010;} .box_content, .portlet-content { border-bottom:solid 1px #BEBEBE; background-color:#F1F1F1; } .portlet-content.black { border-bottom:solid 1px #222; border-top:solid 1px #222; background-color:#2f3238; } .box_content > div.scrollable, #fieldstab .scrollable , #exportWidgetForm .scrollable { background-color:#F5F5F5; } div.head-wrapper { border-bottom:solid 1px #BEBEBE; } div.body-wrapper { border-bottom:solid 1px #BEBEBE; border-top:solid 1px #FFF; } table.thead.items tr { color:#202020; } table.thead tr td:hover, table.thead tr th:hover { color:#5e7294; } .k-list > .k-state-selected, .k-list > .k-state-focused { color:#333; background-color:#FFF; border-color:#FFF; } .col-icon.gas:after, .col-rate.gas:after { background-color:#95CEFF; border:1px solid #00759D; color:#00759D; } .col-icon.strom:after, .col-rate.strom:after { background-color:#FFFF00; border:1px solid #8D8D00; color:#8D8D00; } .col-status.entwurf:after { background-color:#FFF; border:1px solid #BBB; color:#BBB; } .col-status.neu:after { background-color:#FFF; border:1px solid #BBB; color:#BBB; } .col-status.check_valid:after { background-color:#A8F299; border:1px solid #07771A; color:#07771A; } .col-status.check_invalid:after { background-color:#F8C5C5; border:1px solid #BC1338; color:#BC1338; } .col-status.exportiert:after { background-color:#FFFF00; border:1px solid #8D8D00; color:#8D8D00; } .col-status.in_progress:after { background-color:#FFFF00; border:1px solid #8D8D00; color:#8D8D00; } .col-status.storno:after { background-color:#F8C5C5; border:1px solid #BC1338; color:#BC1338; } .col-status.abgelehnt:after { background-color:#F8C5C5; border:1px solid #BC1338; color:#BC1338; } .col-status.error:after { background-color:#F8C5C5; border:1px solid #BC1338; color:#BC1338; } .col-status.confirmed:after { background-color:#A8F299; border:1px solid #07771A; color:#07771A; } .col-status.belieferung:after { background-color:#A8F299; border:1px solid #07771A; color:#07771A; } .col-status.beendet:after { background-color:#666; border:1px solid #222; color:#222; } .col-icon.private:after, .col-client-type.private:after { background-color:#FFF; border:1px solid #26292e; color:#26292e; } .col-icon.business:after, .col-client-type.business:after { background-color:#FFF; border:1px solid #26292e; color:#26292e; } .col-icon.immo:after, .col-client-type.immo:after { background-color:#FFF; border:1px solid #26292e; color:#26292e; } .grid-view .tbody tr.odd:hover { background-color:#FFFF00; } .grid-view .tbody tr.odd { background-color:#E8E8E8; } tr.odd { background-color:#E8E8E8; } .grid-view .total { border:1px solid #E8E8E8; background:-moz-linear-gradient(100% 100% 90deg, #E7E7E7, #F9F9F9); background:-webkit-gradient(linear, 0% 0%, 0% 100%, from(#F9F9F9), to(#E7E7E7)); background:-webkit-linear-gradient(#F9F9F9, #E7E7E7); background:-o-linear-gradient(#F9F9F9, #E7E7E7); } .grid-view button.expander:after { background-color:#FFF; border:solid 1px #FFF; color:#26292e; } .grid-view button.expander:hover:after, .grid-view button.expander.active:hover:after { background-color:#EEE; border:solid 1px #EEE;} .form .errorSummary { background-color:#FAC8C8; /*border-bottom:solid 1px #e2a9a9 !important;*/ } .form .errorSummary li { color:#BC1010; } .form div.successSummary { background-color: #A8F299; border-bottom: solid 1px #75CD6B; border-top: solid 1px #FFF; } .form div.successSummary > p { color:#067719; } .errorSummary a.link {float:none;color:blue;} .yiiTab .view { border-top:solid 1px #FFF; } .black .yiiTab .view { border-top:1px solid #222;} ul.box_menu, .yiiTab ul.tabs { border-bottom:1px solid #BEBEBE; background:-moz-linear-gradient(100% 100% 90deg, #e7e7e7, #f1f1f1); background:-webkit-gradient(linear, 0% 0%, 0% 100%, from(#f1f1f1), to(#e7e7e7)); background:-webkit-linear-gradient(#f1f1f1, #e7e7e7); background:-o-linear-gradient(#f1f1f1, #e7e7e7); } .black .yiiTab ul.tabs { border-bottom:1px solid #545454; background:-moz-linear-gradient(100% 100% 90deg, #2f3238, #333); background:-webkit-gradient(linear, 0% 0%, 0% 100%, from(#333), to(#2f3238)); background:-webkit-linear-gradient(#333, #2f3238); background:-o-linear-gradient(#333, #2f3238); } ul.tabs li { border-right:1px solid #BEBEBE; } .black ul.tabs li { border-right:1px solid #222; } ul.box_menu li a, ul.tabs li a {color:#999; border-right:1px solid #fff; } .black ul.box_menu li a, .black ul.tabs li a { color:#AAA; border-right:none; } ul.box_menu li a:hover, ul.box_menu li.ui-tabs-selected, ul.tabs li a:hover, ul.tabs li a.active { background:-moz-linear-gradient(100% 100% 90deg, #f1f1f1, #e8e8e8); background:-webkit-gradient(linear, 0% 0%, 0% 100%, from(#e8e8e8), to(#f1f1f1)); background:-webkit-linear-gradient(#e8e8e8, #f1f1f1); background:-o-linear-gradient(#e8e8e8, #f1f1f1); } .black ul.box_menu li a:hover, .black ul.box_menu li.ui-tabs-selected, .black ul.tabs li a:hover, .black ul.tabs li a.active { background:#6E6E6E; } .ui-state-active > a, .tabs a.active { color:#202020 !important; } .black .ui-state-active > a, .black .tabs a.active { color:#EEE !important; background: none repeat scroll 0 0 #009FE3; } ul.tabs > li > a span.tab-item-count { color: #fff; background-color: #26292e; } p.item-count { color: #fff; background-color: #666;} .portlet-separator { border-bottom:1px solid #CCC; border-top:1px solid #FEFEFE; background-color:#DDD; } .portlet-separator.error { background-color:#FAC8C8; border-bottom:solid 1px #e2a9a9 !important; } .portlet-separator.error > span { color:#BC1010; } a.rbutton { color:#AAA; border:1px solid #FFF; } .tab-content a.active { background-color:#EFEFEF; color:#000; } .portlet-footer.default { border-top:solid 1px #FFF; background:-moz-linear-gradient(100% 100% 90deg, #D3D3D3, #E0E0E0); background:-webkit-gradient(linear, 0% 0%, 0% 100%, from(#E0E0E0), to(#D3D3D3)); background:-webkit-linear-gradient(#E0E0E0, #D3D3D3); background:-o-linear-gradient(#E0E0E0, #D3D3D3); } .portlet-footer.black { border-bottom:1px solid #333; border-top:solid 1px #545454; background:-moz-linear-gradient(100% 100% 90deg, #1E1E1E, #363636); background:-webkit-gradient(linear, 0% 0%, 0% 100%, from(#363636), to(#1E1E1E)); background:-webkit-linear-gradient(#363636, #1E1E1E); background:-o-linear-gradient(#363636, #1E1E1E); } .box_statusline { color:#666; } .tb_control { border-top: 1px solid #ccc; color: #666; } .tb_control .page_jumper input[type="text"]{ background-color: #fff; border: 1px solid #FFF; color: #666; } .tb_control .summary a, .tb_control .yiiPager a { color:#666; border:solid 1px #FFF; background-color:#FFF; } .tb_control .summary a:hover, .tb_control .yiiPager a:hover { background-color:#DDD; border:solid 1px #DDD; } .tb_control .yiiPager li.selected a, .tb_control .summary a.active { background-color:#26292e; color:#fff; border-color:#26292e; } .tb_control .yiiPager > a:after { background-color:#FFF; border:1px solid #26292e; color:#26292e; } .shadow666 { -moz-box-shadow:1px 1px 1px #CCC; -webkit-box-shadow:1px 1px 1px #CCC; box-shadow:1px 1px 1px #CCC; } #newclient-form .portlet-separator.ui-state-active { border-bottom:1px solid #CCC; } #newclient-form .ui-accordion-content.ui-accordion-content-active { border-bottom:1px solid #CCC !important; } p.commentarea { background-color:#FFF; border:1px solid #FFF; } p.commentarea textarea { background-color:#FFF; color:#333; } p.commentarea:hover { border: 1px solid #c4c4c4; } p.commentarea textarea:focus { background-color:#FFF; } div.grippie { background-color:#F1F1F1 } .filters input[type="text"] { border:solid 1px #CCC; color:#333; background-color:#FFF; } /*noinspection CssInvalidPseudoSelector*/ .filters input[type="text"]:-webkit-autofill { background-color:white !important; } span.inputwrapper, span.selectwrapper { border-color:#C5C5C5; background-color:#E9E9E9; color:#2E2E2E; } span.inputwrapper input[type="text"], span.inputwrapper input[type="password"], .fileinput span.inputwrapper input { color:#2E2E2E; border-color:#C5C5C5; box-shadow:inset 0 0 1px 1px #DDD; -webkit-box-shadow:inset 0 0 1px 1px #DDD; } span.inputwrapper:hover { border-color:#c4c4c4; outline:none } span.static-label{ color: #999; } span.inputwrapper.static:hover { border-color:#F1F1F1; } .inputwrapper.withLabel label { color:#666; } .inputwrapper.withLabel:hover label { color:#000 } .inputwrapper.error, .selectwrapper.error { border: 1px solid #BC1010;} /*.inputwrapper.success, .selectwrapper.success { border: 1px solid #067719;}*/ button.k-button, .k-button { background-color:#fff; border-radius: 0; } button.k-button:active, button.k-button.active, .k-button:active, .k-button.active { border-color:#CCC; color:#333; background:-moz-linear-gradient(100% 100% 90deg, #E0E0E0, #D3D3D3) !important; background:-webkit-gradient(linear, 0% 0%, 0% 100%, from(#D3D3D3), to(#E0E0E0)) !important; background:-webkit-linear-gradient(#D3D3D3, #E0E0E0) !important; background:-o-linear-gradient(#D3D3D3, #E0E0E0) !important; } button.k-button:hover, .k-button:hover, #sortable-selected li:hover, #sortable-available li:hover { color: #333; background-color: #DDD; border-color:#CCC; } button.k-button.dark { border-right:solid 1px #26292e; border-bottom:solid 1px #26292e; border-top:solid 1px #222; border-left:solid 1px #222; background:-moz-linear-gradient(100% 100% 90deg, #1D1D1D, #333333) !important; background:-webkit-gradient(linear, 0% 0%, 0% 100%, from(#333333), to(#1D1D1D)) !important; background:-webkit-linear-gradient(#333333, #1D1D1D) !important; background:-o-linear-gradient(#333333, #1D1D1D) !important; color: #fff; } button.k-button.dark:hover {color:#ccc; background-color:#333; border:solid 1px #26292e;} .items .comment:nth-child(odd) { background-color:#FFF; } .comment_header { color:#666; border-top:solid 1px #DDD } .row.error { border: solid 1px #CE5B50; background: #FF9090; color: #FFF; } label.form-label, td.form-label, div.form-section td:first-child { color:#666 } ul.connectedSortable { border:solid 1px #BEBEBE; background-color:#FFF; } .connectedSortable li { border:solid 1px #C5C5C5; color:#2E2E2E; background:#e3e3e3 url("textures/highlight.png") 0 center repeat-x; } .connectedSortable li.box-placeholder { background-color:#DDD; } #tariff-mapping-widget .note { color:#666; } div.body-wrapper table td:hover span { color:#FFF; } div.body-wrapper table td span { background-color:#111; } table.statData td a { border-bottom:1px solid #BEBEBE; border-top:1px solid #fff; } table.statData td a:hover { background-color:#E1E1E1 } table.statData td a > span { color:#999; } table.statData td a > strong { color:#333 } table.statData td:first-child a { border-right: 1px solid #BEBEBE; } table.statData td:last-child a { border-left: 1px solid #fff; } #fields ul li:hover { background-color:#FFF } #fields ul li a:hover { color:#FFF; } textarea.readonly,input.readonly{background-color:#fff; color: gray;} .infotable.k-content{background-color:#F1F1F1;} .k-widget > span.k-picker-wrap{background-color: #B1B1B1;border-color: #B1B1B1;} .k-widget > span.k-picker-wrap input{color: #fff;} .check_credit_score_box.red {background: #FAC8C8; color: #BC1237; border: 1px solid #BC1237;} .check_credit_score_box.green {background: #A8F299; color: #207D25; border: 1px solid #207D25;} .check_credit_score_box.orange {background: #FFCC00; color: #CC6600; border: 1px solid #CC6600;} div.icons > a.awesome_icon, div.portlet-buttons > a.awesome_icon {color: #aaa; } div.icons > a.awesome_icon:hover, div.portlet-buttons > a.awesome_icon:hover {color: #eee;} table thead.items tr { color:#202020; } thead.head-wrapper { border-bottom:solid 1px #CCC; background-color:#F1F1F1; } .grid-inner table tbody tr:hover { background-color:#FFFF00 !important; } .grid-inner table tbody tr.odd { background-color:#E8E8E8; } .grid-inner table td:hover span:not(.no-hover) { color:#FFF; } .grid-inner table tbody td span:not(.no-hover) { background-color:#111; } .grid-inner table tbody tr:hover, .grid-inner table tbody tr.selected, .grid-inner table tbody tr.odd.selected, .grid-inner table tbody tr.odd:hover{background-color:#FFFF00 !important} table .inline-label-custom { color: #999; } table .label-custom-left { color: #999; } .buttonsetwrapper .ui-buttonset .ui-button.ui-state-active, .button-dark { background-color: #26292e !important; border-color: #26292e !important; color: #fff !important; } td.multiselect-header { background: none repeat scroll 0 0 #ddd !important; color: inherit !important; color: #666 !important; } .redactor_toolbar li a:hover { background-color: #ffff00 !important; color: #000 !important; } .chosen-container.chosen-container-single.chosen-container-active.chosen-with-drop a.chosen-single { border:solid 1px #c4c4c4; } .chosen-container .chosen-results li.highlighted { background-color:#FFFF00 !important; color:#000 } .chosen-container.chosen-container-single a.chosen-single:hover { border:solid 1px #c4c4c4 } .chosen-container-single .chosen-drop { border:1px solid #c4c4c4 !important; border-top:0 !important} .inner-portlet .portlet-header {background: #DDD;} .inner-portlet .portlet-header .button_box{border:1px solid #eee; background:#eee; margin-right:5px;} .inner-portlet .portlet-header .fa{color:#23262c;} .inner-portlet .portlet-header .portlet-title {color:#23262c} .ui-buttonset .ui-button.ui-state-default{border-color:#FFF !important;} .ui-buttonset .ui-button.ui-state-hover{border-color:#DDD !important;} /* sidebar.css */ .bottom-wrapper{ background-color:#2f3238; } #sidebar { background:#2f3238; } #sidebar .menu-section h3 { color:#7f8289;background:#2f3238; } #sidebar .bottom-menu li a span{ color: #ffff00; } #sidebar .menu-section ul li a { color:#e2e2e2;border-bottom: 1px solid #2f3238;background:#26292e; } #sidebar .menu-section ul li a.active, #sidebar .menu-section ul li a:hover, #sidebar .menu-section ul li a.toggled { color:#FFFF00;border-left: 2px solid #ffff00; } #sidebar .menu-section ul li a .counter { background:#479ccf;color:#fff; } #sidebar .bottom-menu>ul>li>a { background:#26292e; } #sidebar .bottom-menu>ul>li>a:hover i { color:#FFFF00; } #sidebar .bottom-menu>ul>li>a i { color:#CBD3DB; } #sidebar .bottom-menu>ul>li .menu li a { color:#CCC; } #sidebar .bottom-menu>ul>li .menu li a:hover { color:#000; } #sidebar .bottom-menu>ul>li { border-top:1px solid #545454; } #sidebar .bottom-menu>ul>li>a .flag { background:#9ed166; } #sidebar .bottom-menu>ul>li .menu { background:#fff; } #sidebar .bottom-menu>ul>li .menu li { border-bottom:1px solid #E6E6E6; } #sidebar .current-user .menu { background:#fff; } #sidebar .current-user .name { color:#DFE8F0; } #sidebar .current-user .menu li { border-bottom:1px solid #E6E6E6; } #sidebar .current-user .menu li a { color:#4C5661; } #sidebar .current-user .menu li a:hover { color:#000; } @media (max-width:1200px) { #sidebar .menu-section ul { border-left: 1px solid #7f8289; } #sidebar .menu-section ul li>.submenu { background:#2a313a; } } /* loader.css */ .pace .pace-progress { background: #FFFF00; } /* label.css */ span.inputwrapper.error > input[type="text"], span.inputwrapper.error > input[type="password"] { border-left: 3px solid #BC1010; background-color: transparent !important; color:#BC1010; } /*span.inputwrapper.success > input[type="text"], span.inputwrapper.success > input[type="password"] { border-left: 3px solid #067719;background-color: transparent !important; color:#067719; }*/ span.inputwrapper.error > input[type="text"] ~ label[placeholder]:before, span.inputwrapper.error > input[type="password"] ~ label[placeholder]:before { color:#BC1010; } /*span.inputwrapper.success > input[type="text"] ~ label[placeholder]:before, span.inputwrapper.success > input[type="password"] ~ label[placeholder]:before { color:#067719; }*/ span.inputwrapper > input[type="text"]:focus, span.inputwrapper > input[type="password"]:focus { border-color:#00bafa; border-left: 3px solid #0082FF; background-color: transparent !important; color:#0082FF; } span.inputwrapper > input.readonly:focus { background-color:#F1F1F1 !important; } span.inputwrapper > input[type="text"]:focus ~ label[placeholder]:before, span.inputwrapper > input[type="password"]:focus ~ label[placeholder]:before { color:#3C77D4; } span.inputwrapper > input[type="text"] ~ label[placeholder]:before, span.inputwrapper > input[type="password"] ~ label[placeholder]:before, span.selectwrapper > select + label[placeholder]:before{ color:#999; } span.k-combobox + label[placeholder]:before { color:#999; } span.selectwrapper > select, span.inputwrapper input[type="text"], span.inputwrapper input[type="password"], .fileinput span.inputwrapper input { border-color: #F1F1F1; } span.inputwrapper, span.selectwrapper { border-color: #fff; background-color: #fff; } .button_box { background-color: #26292e; border: 1px solid #26292e; color: #AAA;} div.fieldwrapper { background-color:none; } span.unit { color:#888; } .green-color { color : green; } .red-color { color : red; } .gray-color-6{ color : #666; } .black-color{ color : #000; } .orange-color{ color:#EFB000; } .btf_date_style { float:left; line-height:25px; padding-left:5px; font-size:11px; color:#666; } .cities_matching_container {} .cities_matching { border: 1px solid #BEBEBE; max-height: 200px; overflow: auto; background-color: #fff; } .cities_matching table { width: 100%; } .cities_matching table tr td { border-bottom: 1px solid #EEE; white-space: nowrap; padding-left: 10px; } .cities_matching table tr td:last-child { width: 99%; } tr.no_match td { background-color: #FAC8C8; } .btd_border_left { float:left; width:1%; border-left:1px solid #FFFFFF; } .btd_border_right { width:40%; border-right: 1px solid #CCCCCC; } .draft_background { background-color:#ffff99; } .tab_auto_err { text-align: center; margin:0 auto; line-height: 20px; color: #BC1010; } .import_errors { color: #ff0000; } .login_fail_close { margin-right:5px; color:#222; } .k-picker-wrap { overflow:hidden } .k-picker-wrap > input { background:none !important; color:#AAA; box-shadow:none; -webkit-box-shadow:none !important; } .k-picker-wrap.k-state-hover > input { color:#FFF; } .interfaceForm_err { text-align: center; margin:0 auto; line-height: 20px; color: #BC1010; } .test-form .errorSummary a { float: none; color: #0000ff; } .message-header { background-color: #DDDDDD; border-bottom: 1px solid #CCCCCC !important; border-top: 1px solid #FFFFFF !important; clear: both; font-weight: bold; line-height: 30px; overflow: hidden; padding: 0 10px; } .message-body { padding:20px 10px; } .message-footer { background-color: #DDDDDD; border-bottom: 1px solid #CCCCCC !important; border-top: 1px solid #FFFFFF !important; clear: both; font-weight: bold; line-height: 30px; overflow: hidden; padding: 0 10px; } div.icons > a, div.portlet-buttons > a.font-awesome { margin:auto; font-size:18px; color: #ccc; } .right-form-section-err { font-size:11px; color:#888; } .reportform td.label, .reportform label.label { color: #666666; font-size: 11px; padding-right: 5px; text-align: left;} .reportingresult .portlet-content { overflow-x: auto; overflow-y: hidden; background-color: #F1F1F1; border-bottom: none; } div.infotable > table tr.header td{ color: #848484; } #pwd_change_dlg {display:none;} #pwd_change_dlg table.form-table td {width: 200px;} #pwd_change_dlg .status_msg {padding-bottom: 10px;} #pwd_change_dlg .right-button{float: right; padding: 0 20px;} table.pwd-strong-marker {width: 100%; display: none;} table.pwd-strong-marker td {width: 33%; border-left: 2px solid #F1F1F1; background-color: #CBCBCB; text-align: center; color: #666; padding: 0; font-size: 11px;} .form-section table.pwd-strong-marker td:first-child {max-width: none; min-width: 1px; text-align: center; border-left: none;} table.pwd-strong-marker span {display: none;} table.pwd-strong-marker.weak td:first-child {background-color: #FF8080;} table.pwd-strong-marker.weak span.weak {display: inline;} table.pwd-strong-marker.medium td {background-color: #FFFFA0;} table.pwd-strong-marker.medium td:last-child {background-color: #CBCBCB;} table.pwd-strong-marker.medium span.medium {display: inline;} table.pwd-strong-marker.strong td {background-color: #80FF80;} table.pwd-strong-marker.strong span.strong {display: inline;} span.cke_skin_kama { background: none repeat scroll 0 0 #fff !important; border: 1px solid #d3d3d3 !important; border-radius: 0 !important; padding: 5px !important; } .qresult_info { color: #666 !important; } .qform_btn { padding:0 20px; background-color:#1F5F30 !important; color:white; } #QueryResponse table.normal-header {width: 100%; height: 40px; background-color: #F1F1F1;} #QueryResponse table.normal-header td {padding: 0px 20px 0 0; vertical-align: top; text-align: left; white-space: nowrap; background-color: #F1F1F1;} #QueryResponse .active-section {display: none; background-color: #e1e1e1; padding: 10px 0 18px 0;} #QueryResponse table.active-header {cursor: pointer; background-color: #e1e1e1; height: 52px; color: #fff; width: 100%;} #QueryResponse table.active-content td {white-space: nowrap; background-color: #e1e1e1;} #QueryResponse table.tariff-details td {padding: 2px 10px; color:#000;} #QueryResponse .search-results-none {background-color: #FAC8C8; border-top: 1px solid #E2A9A9 !important; padding: 5px 15px 10px 10px;} #QueryResponse .search-results-none p {font-size: 14px; text-align: center; color: #BC1010;} #QueryResponse .large-text {font-size: 18px; font-weight: bold; color: #000} #QueryResponse .provider-info {font-size: 14px; color : #000} #QueryResponse .money-saving-info {font-size: 14px;color : #000}
degiurgiu/projectyii
themes/photoGal/css/color.darkblue.css
CSS
gpl-3.0
27,358
#include "data.hpp" auto Przestepny(int rok) -> bool { rok = abs(rok); return((rok%4 == 0 && rok%100 != 0) || rok%400 == 0); } auto Sensowna(int dzien, int miesiac, int rok) -> bool { bool kontrola = false; if (0 <= rok) { if(1 <= miesiac && miesiac <= 12) { if(miesiac == 2) { if(Przestepny(rok) && 1 <= dzien && dzien <= 29) kontrola = true; if(!Przestepny(rok) && 1 <= dzien && dzien <= 28) kontrola = true; } else if(((miesiac % 2 == 1 && miesiac <= 7) || (miesiac % 2 == 0 && miesiac >= 8)) && (1 <= dzien && dzien <= 31)) kontrola = true; else if(1 <= dzien && dzien <= 31) kontrola = true; } } return kontrola; } auto Data::nazywajMiesiac() -> std::string const { std::string wyjscie; switch(miesiac_) { case 1: wyjscie = " stycznia "; break; case 2: wyjscie = " lutego "; break; case 3: wyjscie = " marca "; break; case 4: wyjscie = " kwietnia "; break; case 5: wyjscie = " maja "; break; case 6: wyjscie = " czerwca "; break; case 7: wyjscie = " lipca "; break; case 8: wyjscie = " sierpnia "; break; case 9: wyjscie = " września "; break; case 10: wyjscie = " października "; break; case 11: wyjscie = " listopada "; break; case 12: wyjscie = " grudnia "; break; default: wyjscie = std::to_string(miesiac_); break; } return(wyjscie); } Data::Data(int dzien, int miesiac, int rok) { dzien_ = dzien; miesiac_ = miesiac; rok_ = rok; poprawna_ = Sensowna(dzien, miesiac, rok); } auto Data::Dzien() -> int const { return dzien_; } auto Data::Miesiac() -> int const { return miesiac_; } auto Data::Rok() -> int const { return rok_; } auto Data::Poprawna() -> bool const { return poprawna_; } auto Data::Wypisz() -> std::string const { return(std::to_string(dzien_) + nazywajMiesiac() + std::to_string(rok_) + "r."); } auto Data::operator<(Data D) -> bool const { if (rok_ != D.Rok()) return rok_ < D.Rok(); else if (miesiac_ != D.Miesiac()) return miesiac_ < D.Miesiac(); else return dzien_ < D.Dzien(); }
mmaku/Cpp_2
Zadania 9/biblioteka/data.cpp
C++
gpl-3.0
2,480
// // This file is part of the DeportesUGR App. // // Copyright (C) 2014 Luis Carlos Casanova Aranda, Juan J. Ramos-Munoz <jjramosapps@gmail.com> // // DeportesUGR 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. // // DeportesUGR 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/>. // /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package es.ugr.deportesugrapp.reservas; /** * Clase que contiene los datos de interes de las pistas reservables * */ public class PistaReservable { private String codigo = null; private String titulo = null; /** * Constructor de la clase */ PistaReservable() { } /** * Constructor de la clase con argumentos * @param codigoPista Codigo de la pista * @param pista Nombre de la pista */ PistaReservable(String codigoPista, String pista) { this.codigo = codigoPista; this.titulo = pista; } /** * Metodo que nos permite obtener el codigo de la pista * @return Devuelve el codigo de la pista */ public String getCodigo() { return codigo; } /** * Metodo que nos permite obtener el Nombre de la instalacion * @return Devuelve el nombre de la pista */ public String getTitulo() { return titulo; } /** * Metodo que nos permite asignar el codigo de la pista * @param codigo Codigo de la pista */ public void setCodigo(String codigo) { this.codigo = codigo; } /** * Metodo que nos permite asignar el nombre de la pista * @param titulo Nombre de la pista */ public void setTitulo(String titulo) { this.titulo = titulo; } }
jjramos-dev/DeportesUGRApp
src/es/ugr/deportesugrapp/reservas/PistaReservable.java
Java
gpl-3.0
2,214
# Copyright (c) 2019 2021 by Rocky Bernstein # # 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/>. """Isolate Python 2.6 and 2.7 version-specific semantic actions here. """ from uncompyle6.semantics.consts import TABLE_DIRECT def customize_for_version26_27(self, version): ######################################## # Python 2.6+ # except <condition> as <var> # vs. older: # except <condition> , <var> # # For 2.6 we use the older syntax which # matches how we parse this in bytecode ######################################## if version > (2, 6): TABLE_DIRECT.update({ 'except_cond2': ( '%|except %c as %c:\n', 1, 5 ), # When a generator is a single parameter of a function, # it doesn't need the surrounding parenethesis. 'call_generator': ('%c%P', 0, (1, -1, ', ', 100)), }) else: TABLE_DIRECT.update({ 'testtrue_then': ( 'not %p', (0, 22) ), }) # FIXME: this should be a transformation def n_call(node): mapping = self._get_mapping(node) key = node for i in mapping[1:]: key = key[i] pass if key.kind == 'CALL_FUNCTION_1': # A function with one argument. If this is a generator, # no parenthesis is needed. args_node = node[-2] if args_node == 'expr': n = args_node[0] if n == 'generator_exp': node.kind = 'call_generator' pass pass self.default(node) self.n_call = n_call
rocky/python-uncompyle6
uncompyle6/semantics/customize26_27.py
Python
gpl-3.0
2,225
/** * Please modify this class to meet your needs * This class is not complete */ package com.travelport.service.air_v29_0; import java.util.logging.Logger; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.xml.bind.annotation.XmlSeeAlso; /** * This class was generated by Apache CXF 2.7.12 * 2014-09-19T15:10:05.025-06:00 * Generated source version: 2.7.12 * */ @javax.jws.WebService( serviceName = "AirService", portName = "AirRetrieveDocumentBindingPort", targetNamespace = "http://www.travelport.com/service/air_v29_0", wsdlLocation = "file:/C:/Travelport_1/SamplesAutoMation/AutoWork/travelport-uapi-tutorial/Wsdl/air_v29_0/Air.wsdl", endpointInterface = "com.travelport.service.air_v29_0.AirRetrieveDocumentPortType") public class AirRetrieveDocumentPortTypeImpl implements AirRetrieveDocumentPortType { private static final Logger LOG = Logger.getLogger(AirRetrieveDocumentPortTypeImpl.class.getName()); /* (non-Javadoc) * @see com.travelport.service.air_v29_0.AirRetrieveDocumentPortType#service(com.travelport.schema.air_v29_0.AirRetrieveDocumentReq parameters )* */ public com.travelport.schema.air_v29_0.AirRetrieveDocumentRsp service(com.travelport.schema.air_v29_0.AirRetrieveDocumentReq parameters) throws AirFaultMessage { LOG.info("Executing operation service"); System.out.println(parameters); try { com.travelport.schema.air_v29_0.AirRetrieveDocumentRsp _return = new com.travelport.schema.air_v29_0.AirRetrieveDocumentRsp(); return _return; } catch (java.lang.Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } //throw new AirFaultMessage("AirFaultMessage..."); } }
angecab10/travelport-uapi-tutorial
src/com/travelport/service/air_v29_0/AirRetrieveDocumentPortTypeImpl.java
Java
gpl-3.0
1,993
package PracticeModule1; import java.util.Arrays; /** * Created by ZahornyiAI on 12.05.2016. */ public class MatrixSnakeTraversal { public int[] print(int[][] input) { String temp=" "; for (int i = 0; i < 1; i++) { for (int j = 0; j < input[i].length; j++) { if (j % 2 == 0) { for (int t = 0; t < input.length; t++) { for (int y = j; y < j + 1; y++) { temp = temp+" "+Integer.toString(input[t][y]); } } } else { for (int f = input.length - 1; f >= 0; f--) { for (int n = j; n < j + 1; n++) { temp = temp+" "+Integer.toString(input[f][j]); } } } } } String [] array = (temp.trim()).split(" "); int [] result = new int [array.length]; for (int i=0; i<array.length; i++){ result[i]=Integer.parseInt(array[i]); } return result; } public static void main(String[] args) { int[][] input = {{1, 2, 3}, {4, 5, 6}, {7, 12, 9}, {7, 8, 10}}; MatrixSnakeTraversal matrixSnakeTraversal=new MatrixSnakeTraversal(); System.out.println(Arrays.toString(matrixSnakeTraversal.print(input))); } }
andrewzagor/goit
Practice/MatrixSnakeTraversal.java
Java
gpl-3.0
1,573
package models; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleStringProperty; import javafx.scene.input.DataFormat; public class Descripteme extends Fragment { public static final DataFormat format = new DataFormat("Descripteme"); // this is the selection (getSelection), the substring of the interview text private final SimpleStringProperty descripteme; // Whether or not the descripteme is highlighted is the interview private SimpleBooleanProperty isRevealed = new SimpleBooleanProperty(false); // When set to true, scroll the interview to the descripteme private SimpleBooleanProperty triggerScrollReveal = new SimpleBooleanProperty(false); public Descripteme(InterviewText interviewText, int startIndex, int endIndex){ super(interviewText, startIndex, endIndex); descripteme = new SimpleStringProperty(); descripteme.set(getSelection()); } public Descripteme(Annotation a) { super(a.getInterviewText(), a.getIndexRange()); descripteme = new SimpleStringProperty(); descripteme.set(getSelection()); } public InterviewText getInterviewText() { return interviewText; } public final SimpleStringProperty getSelectionProperty() { return this.descripteme; } public final String getSelection() { return interviewText.getText().substring(startIndex.get(), endIndex.get()).replace("\n", "").replace("\r", ""); } public Descripteme duplicate() { return new Descripteme(interviewText, startIndex.get(), endIndex.get()); } public void modifyIndex(int start, int end) { startIndex.set(start == -1 ? 0 : start); endIndex.set(Math.min(end, interviewText.getText().length())); this.descripteme.set(getSelection()); } @Override public DataFormat getDataFormat() { return format; } public void setRevealed(boolean revealed) { this.isRevealed.set(revealed); } public SimpleBooleanProperty getRevealedProperty() { return isRevealed; } public void setTriggerScrollReveal(boolean triggerScrollReveal) { this.triggerScrollReveal.set(triggerScrollReveal); } public SimpleBooleanProperty getTriggerScrollReveal() { return triggerScrollReveal; } }
coco35700/uPMT
src/main/java/models/Descripteme.java
Java
gpl-3.0
2,346
install: python-install full-reset: repo-pull docker-reset python-install: python3 -m venv venv && \ . venv/bin/activate && \ pip install --upgrade pip && \ pip install -r requirements.txt && \ echo "App is installed. Run 'make serve' to run the server." serve: . venv/bin/activate && \ FLASK_APP=flaskr FLASK_ENV=development \ APP_SETTINGS=flaskr.config.DevelopmentConfig \ flask run --extra-files flaskr/templates/base.html:flaskr/templates/index.html:flaskr/static/css/chuck.css docker-reset: echo "Stopping container..." && \ docker stop chuckquotes || true && \ echo "Deleting container..." && \ docker rm chuckquotes || true && \ echo "Deleting image..." && \ docker rmi chuckquotes || true && \ echo "Rebuilding image..." && \ docker build --tag chuckquotes . && \ echo "Running new image in new container..." && \ docker run -d --name chuckquotes --publish 5052:5052 chuckquotes && \ echo "Set restart on failure..." && \ docker update --restart=on-failure chuckquotes repo-pull: git pull origin master
patillacode/chuckquotes
Makefile
Makefile
gpl-3.0
1,037
<?xml version="1.0" encoding="utf-8"?> <html> <head> <title>GLib.Test.rand_double_range -- Vala Binding Reference</title> <link href="../style.css" rel="stylesheet" type="text/css"/><script src="../scripts.js" type="text/javascript"> </script> </head> <body> <div class="site_header">GLib.Test.rand_double_range Reference Manual</div> <div class="site_body"> <div class="site_navigation"> <ul class="navi_main"> <li class="package_index"><a href="../index.html">Packages</a></li> </ul> <hr class="navi_hr"/> <ul class="navi_main"> <li class="package"><a href="index.htm">glib-2.0</a></li> </ul> <hr class="navi_hr"/> <ul class="navi_main"> <li class="namespace"><a href="GLib.html">GLib</a></li> </ul> <hr class="navi_hr"/> <ul class="navi_main"> <li class="namespace"><a href="GLib.Test.html">Test</a></li> </ul> <hr class="navi_hr"/> <ul class="navi_main"> <li class="method"><a href="GLib.Test.add_data_func.html">add_data_func</a></li> <li class="method"><a href="GLib.Test.add_func.html">add_func</a></li> <li class="method"><a href="GLib.Test.bug.html">bug</a></li> <li class="method"><a href="GLib.Test.bug_base.html">bug_base</a></li> <li class="method"><a href="GLib.Test.fail.html">fail</a></li> <li class="method"><a href="GLib.Test.init.html">init</a></li> <li class="method"><a href="GLib.Test.log_set_fatal_handler.html">log_set_fatal_handler</a></li> <li class="method"><a href="GLib.Test.maximized_result.html">maximized_result</a></li> <li class="method"><a href="GLib.Test.message.html">message</a></li> <li class="method"><a href="GLib.Test.minimized_result.html">minimized_result</a></li> <li class="method"><a href="GLib.Test.perf.html">perf</a></li> <li class="method"><a href="GLib.Test.quick.html">quick</a></li> <li class="method"><a href="GLib.Test.quiet.html">quiet</a></li> <li class="method"><a href="GLib.Test.rand_bit.html">rand_bit</a></li> <li class="method"><a href="GLib.Test.rand_double.html">rand_double</a></li> <li class="method">rand_double_range</li> <li class="method"><a href="GLib.Test.rand_int.html">rand_int</a></li> <li class="method"><a href="GLib.Test.rand_int_range.html">rand_int_range</a></li> <li class="method"><a href="GLib.Test.run.html">run</a></li> <li class="method"><a href="GLib.Test.slow.html">slow</a></li> <li class="method"><a href="GLib.Test.thorough.html">thorough</a></li> <li class="method"><a href="GLib.Test.timer_elapsed.html">timer_elapsed</a></li> <li class="method"><a href="GLib.Test.timer_last.html">timer_last</a></li> <li class="method"><a href="GLib.Test.timer_start.html">timer_start</a></li> <li class="method"><a href="GLib.Test.trap_assert_failed.html">trap_assert_failed</a></li> <li class="method"><a href="GLib.Test.trap_assert_passed.html">trap_assert_passed</a></li> <li class="method"><a href="GLib.Test.trap_assert_stderr.html">trap_assert_stderr</a></li> <li class="method"><a href="GLib.Test.trap_assert_stderr_unmatched.html">trap_assert_stderr_unmatched</a></li> <li class="method"><a href="GLib.Test.trap_assert_stdout.html">trap_assert_stdout</a></li> <li class="method"><a href="GLib.Test.trap_assert_stdout_unmatched.html">trap_assert_stdout_unmatched</a></li> <li class="method"><a href="GLib.Test.trap_fork.html">trap_fork</a></li> <li class="method"><a href="GLib.Test.trap_has_passed.html">trap_has_passed</a></li> <li class="method"><a href="GLib.Test.trap_reached_timeout.html">trap_reached_timeout</a></li> <li class="method"><a href="GLib.Test.verbose.html">verbose</a></li> </ul> </div> <div class="site_content"> <h1 class="main_title">rand_double_range</h1> <hr class="main_hr"/> <h2 class="main_title">Description:</h2> <div class="main_code_definition"><span class="main_keyword">public</span> <span class="main_basic_type"><a href="double.html" class="struct">double</a></span> <b><span css="method">rand_double_range</span></b> () </div><br/> <div class="namespace_note"><b>Namespace:</b> GLib.Test</div> <div class="package_note"><b>Package:</b> glib-2.0</div> </div> </div><br/> <div class="site_footer">Generated by <a href="http://www.valadoc.org/">Valadoc</a> </div> </body> </html>
themightyug/ledborg-server
doc/glib-2.0/GLib.Test.rand_double_range.html
HTML
gpl-3.0
4,713
#!/usr/local/bin/perl # Rehash already hashed passwords and add salt # to all files in "users" directory. use strict; use warnings; use CGI::Session; use CGI::Session::Driver::file; use Digest::SHA qw/sha256_hex/; use Crypt::SaltedHash; sub usage { die "Usage: $0 DIRECTORY\n"; } my $dir = shift @ARGV or usage(); @ARGV and usage(); opendir(my $dh, $dir) or die "Can't opendir $dir: $!"; while (my $file = readdir $dh) { next if $file eq '.' or $file eq '..'; next if $file =~ /~$/; $CGI::Session::Driver::file::FileName = "%s"; my $store = CGI::Session->load ('driver:file;id:static', $file, { Directory => $dir }); my $pass = $store->param('pass') or next; my $csh = Crypt::SaltedHash->new(algorithm => 'SHA-256'); $csh->add($pass); my $hash = $csh->generate; $store->param('old_hash', $hash); $store->clear('pass'); $store->flush(); print STDERR "Fixed $file\n"; # my $c2 = Crypt::SaltedHash->new(algorithm => 'SHA-256'); # $c2->validate($hash, $pass) or print STDERR "Can't validate $file\n"; # print STDERR "Hash: $hash\nPass: $pass\n"; }
hknutzen/Netspoc-Web
bin/add_salt.pl
Perl
gpl-3.0
1,182
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0.1 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Boost.MultiIndex Documentation - Release notes</title> <link rel="stylesheet" href="style.css" type="text/css"> <link rel="start" href="index.html"> <link rel="prev" href="future_work.html"> <link rel="up" href="index.html"> <link rel="next" href="acknowledgements.html"> </head> <body> <h1><img src="../../../boost.png" alt="boost.png (6897 bytes)" align= "middle" width="277" height="86">Boost.MultiIndex Release notes</h1> <div class="prev_link"><a href="future_work.html"><img src="prev.gif" alt="future work" border="0"><br> Future work </a></div> <div class="up_link"><a href="index.html"><img src="up.gif" alt="index" border="0"><br> Index </a></div> <div class="next_link"><a href="acknowledgements.html"><img src="next.gif" alt="acknowledgements" border="0"><br> Acknowledgements </a></div><br clear="all" style="clear: all;"> <hr> <h2>Contents</h2> <ul> <li><a href="#boost_1_44">Boost 1.44 release</a></li> <li><a href="#boost_1_43">Boost 1.43 release</a></li> <li><a href="#boost_1_42">Boost 1.42 release</a></li> <li><a href="#boost_1_41">Boost 1.41 release</a></li> <li><a href="#boost_1_38">Boost 1.38 release</a></li> <li><a href="#boost_1_37">Boost 1.37 release</a></li> <li><a href="#boost_1_36">Boost 1.36 release</a></li> <li><a href="#boost_1_35">Boost 1.35 release</a></li> <li><a href="#boost_1_34">Boost 1.34 release</a></li> <li><a href="#boost_1_33_1">Boost 1.33.1 release</a></li> <li><a href="#boost_1_33">Boost 1.33 release</a></li> </ul> <h2><a name="boost_1_44">Boost 1.44 release</a></h2> <p> <ul> <li> Fixed a bug preventing the use of <code>modify_key</code> with rollback in <a href="reference/ord_indices.html#modify_key">ordered</a> and <a href="reference/hash_indices.html#modify_key">hashed</a> indices when <code>Modifier</code> and <code>Rollback</code> are different types (ticket <a href="https://svn.boost.org/trac/boost/ticket/4130">#4130</a>). </li> </ul> </p> <h2><a name="boost_1_43">Boost 1.43 release</a></h2> <p> <ul> <li> <a href="../../serialization/doc/serialization.html#constructors">Serialization of non default constructible values</a> is now properly supported through user-provided facilities <code>save_construct_data</code> and <code>load_construct_data</code>. <code>multi_index_container</code> serialization <a href="../../serialization/doc/tutorial.html#versioning">class version</a> has been bumped from 1 to 2. </li> </ul> </p> <h2><a name="boost_1_42">Boost 1.42 release</a></h2> <p> <ul> <li>Maintenance fixes.</li> </ul> </p> <h2><a name="boost_1_41">Boost 1.41 release</a></h2> <p> <ul> <li>Serialization now uses the portable <a href="../../serialization/doc/wrappers.html#collection_size_type"><code>collection_size_type</code></a> type instead of the original <code>std::size_t</code> (ticket <a href="https://svn.boost.org/trac/boost/ticket/3365">#3365</a>). <code>multi_index_container</code> serialization <a href="../../serialization/doc/tutorial.html#versioning">class version</a> has been bumped from 0 to 1. </li> <li>Fixed a concurrency bug in the implementation of <a href="tutorial/debug.html#safe_mode">safe mode</a> (ticket <a href="https://svn.boost.org/trac/boost/ticket/3462">#3462</a>). </li> </ul> </p> <h2><a name="boost_1_38">Boost 1.38 release</a></h2> <p> <ul> <li>These constructs are deprecated: <ul> <li><code>nth_index_iterator&lt;MultiIndexContainer,N&gt;::type</code>,</li> <li><code>multi_index_container&lt;...&gt;::nth_index_iterator&lt;N&gt;::type</code>,</li> <li><code>nth_index_const_iterator&lt;MultiIndexContainer,N&gt;::type</code>,</li> <li><code>multi_index_container&lt;...&gt;::nth_index_const_iterator&lt;N&gt;::type</code>,</li> <li><code>index_iterator&lt;MultiIndexContainer,Tag&gt;::type</code>,</li> <li><code>multi_index_container&lt;...&gt;::index_iterator&lt;Tag&gt;::type</code>,</li> <li><code>index_const_iterator&lt;MultiIndexContainer,Tag&gt;::type</code>,</li> <li><code>multi_index_container&lt;...&gt;::index_const_iterator&lt;Tag&gt;::type</code>.</li> </ul> Use the following instead: <ul> <li><code>nth_index&lt;MultiIndexContainer,N&gt;::type::iterator</code>,</li> <li><code>multi_index_container&lt;...&gt;::nth_index&lt;N&gt;::type::iterator</code>,</li> <li><code>nth_index&lt;MultiIndexContainer,N&gt;::type::const_iterator</code>,</li> <li><code>multi_index_container&lt;...&gt;::nth_index&lt;N&gt;::type::const_iterator</code>,</li> <li><code>index&lt;MultiIndexContainer,Tag&gt;::type::iterator</code>,</li> <li><code>multi_index_container&lt;...&gt;::index&lt;Tag&gt;::type::iterator</code>,</li> <li><code>index&lt;MultiIndexContainer,Tag&gt;::type::const_iterator</code>,</li> <li><code>multi_index_container&lt;...&gt;::index&lt;Tag&gt;::type::const_iterator</code>.</li> </ul> </li> <li>Maintenance fixes.</li> </ul> </p> <h2><a name="boost_1_37">Boost 1.37 release</a></h2> <p> <ul> <li>Maintenance fixes.</li> </ul> </p> <h2><a name="boost_1_36">Boost 1.36 release</a></h2> <p> <ul> <li><a name="stable_update">On prior versions of the library, the <a href="tutorial/indices.html#hash_updating">update member functions</a> of hashed indices could alter the position of an element even if the associated key did not change with the update. This is legal but probably unexpected behavior. The functions have been rewritten to provide the additional guarantee that elements with unmodified key will not change position in hashed indices, just as always was the case with ordered indices. These guarantees are now documented in the reference.</a></li> <li>Added the constructor <code>multi_index_container::multi_index_container(const allocator_type&amp;)</code> to mimic the equivalent interface in STL sequence containers. <li>Maintenance fixes.</li> </ul> </p> <h2><a name="boost_1_35">Boost 1.35 release</a></h2> <p> <ul> <li>New <a href="tutorial/key_extraction.html#global_fun"><code>global_fun</code></a> predefined key extractor. </li> <li>Added <a href="tutorial/indices.html#iterator_to"><code>iterator_to</code></a> facility. </li> <li>Included <a href="tutorial/creation.html#special_allocator">support for non-standard allocators</a> such as those of <a href="../../interprocess/index.html">Boost.Interprocess</a>, which makes <code>multi_index_container</code>s placeable in shared memory. </li> <li>New versions of <code>modify</code> and <code>modify_key</code> with rollback, as described in the <a href="tutorial/basics.html#ord_updating">tutorial</a>. </li> <li>Indices provide the new <code>cbegin</code>, <code>cend</code> and, when applicable, <code>crbegin</code> and <code>crend</code> member functions, in accordance with the latest drafts of the next revision of the C++ standard. </li> <li>Hinted insertion in ordered indices fully conforms to the resolutions of C++ Standard Library <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#233">Defect Report 233</a>. The new requirement that the point of insertion be always as close as possible to the hint induces a different behavior than exhibited in former releases of Boost.MultiIndex, which can potentially cause backwards compatibility problems; in any case, the likelihood of these compatibility issues arising in a real scenario is very low. </li> <li>Sequenced and random access indices now follow the requirements of the C++ standard for sequence containers with respect to the operations <code>assign(f,l)</code> and <code>insert(p,f,l)</code> (23.1.1/9): if <code>f</code> and <code>l</code> are of the same integral type, the iterator-based overloads of these member functions are avoided: <blockquote><pre> <span class=keyword>typedef</span> <span class=identifier>multi_index_container</span><span class=special>&lt;</span> <span class=keyword>int</span><span class=special>,</span><span class=identifier>indexed_by</span><span class=special>&lt;</span><span class=identifier>sequenced</span><span class=special>&lt;&gt;</span> <span class=special>&gt;</span> <span class=special>&gt;</span> <span class=identifier>sequenced_container</span><span class=special>;</span> <span class=identifier>std</span><span class=special>::</span><span class=identifier>list</span><span class=special>&lt;</span><span class=keyword>int</span><span class=special>&gt;</span> <span class=identifier>l</span><span class=special>(...);</span> <span class=identifier>sequenced_container</span> <span class=identifier>c</span><span class=special>;</span> <span class=comment>// iterator-based overload of assign</span> <span class=identifier>c</span><span class=special>.</span><span class=identifier>assign</span><span class=special>(</span><span class=identifier>l</span><span class=special>.</span><span class=identifier>begin</span><span class=special>(),</span><span class=identifier>l</span><span class=special>.</span><span class=identifier>end</span><span class=special>());</span> <span class=comment>// The following is equivalent to // c.assign( // static_cast&lt;sequenced_container::size_type&gt;(10),100); // that is, &quot;10&quot; and &quot;100&quot; are not taken to be iterators as // in the previous expression.</span> <span class=identifier>c</span><span class=special>.</span><span class=identifier>assign</span><span class=special>(</span><span class=number>10</span><span class=special>,</span><span class=number>100</span><span class=special>);</span> </pre></blockquote> </li> <li>The performance of ordered indices <code>range</code> and <code>equal_range</code> has been improved. </li> <li>Maintenance fixes.</li> </ul> </p> <h2><a name="boost_1_34">Boost 1.34 release</a></h2> <p> <ul> <li>Added <a href="tutorial/indices.html#rnd_indices">random access indices</a>. </li> <li>Non key-based indices provide new <a href="tutorial/indices.html#rearrange">rearrange facilities</a> allowing for interaction with external mutating algorithms. </li> <li>All predefined Boost.MultiIndex key extractors instantiated for a given type <code>T</code> can handle objects of types derived from or convertible to <code>T</code> (and <a href="reference/key_extraction.html#chained_pointers">chained pointers</a> to those). Previously, only objects of the exact type specified (along with <code>reference_wrapper</code>s and chained pointers to them) were accepted. </li> <li><a href="reference/key_extraction.html#composite_key_compare"><code>composite_key_compare</code></a> and related classes accept operands not included in tuples as if they were passed in a tuple of length 1; this allows the user to omit tuple enclosing in lookup operations involving composite keys when only the first key is provided. </li> <li>The core algorithms of ordered indices have been optimized, yielding an estimated reduction of about 5% in insertion times. </li> <li>Size of ordered indices node headers have been reduced by 25% on most platforms, using a well known <a href="tutorial/indices.html#ordered_node_compression">optimization technique</a>. </li> <li>The tutorial has been restructured, new examples added.</li> <li>Maintenance fixes.</li> </ul> </p> <h2><a name="boost_1_33_1">Boost 1.33.1 release</a></h2> <p> <ul> <li>For ordered and hashed indices, <code>erase(it)</code> and <code>erase(first,last)</code> now return an iterator to the element following those being deleted (previously nothing was returned), in accordance with the C++ Standard Library <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#130">Defect Report 130</a> and issue 6.19 of TR1 <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1837.pdf">Issues List</a>. </li> <li>Boost.MultiIndex offers the usual guarantees with respect to multithreading code provided by most STL implementations: <ol> <li>Concurrent access to different containers is safe.</li> <li>Concurrent read-only access to the same container is safe.</li> </ol> In previous versions of the library, the latter guarantee was not properly maintained if the <a href="tutorial/debug.html#safe_mode">safe mode</a> was set. This problem has been fixed now. </li> <li>Maintenance fixes.</li> </ul> </p> <h2><a name="boost_1_33">Boost 1.33 release</a></h2> <p> <ul> <li>Added <a href="tutorial/indices.html#hashed_indices">hashed indices</a>, whose interface is based on the specification for unordered associative containers by the C++ Standard Library Technical Report (TR1). </li> <li>Added <a href="tutorial/creation.html#serialization">serialization support</a> for <a href="../../serialization/index.html">Boost.Serialization</a>. </li> <li>Destruction of <code>multi_index_container</code>s and <code>clear</code> memfuns now perform faster. </li> <li>Internal changes aimed at reducing the length of symbol names generated by the compiler; cuts of up to a 50% can be achieved with respect to the Boost 1.32 release. This results in much shorter and more readable error messages and has also a beneficial impact on compilers with strict limits on symbol name lengths. Additionally, a section on further <a href="compiler_specifics.html#symbol_reduction">reduction of symbol name lengths</a> has been added. </li> <li>Restructured some parts of the documentation, new examples.</li> <li>Maintenance fixes.</li> </ul> </p> <hr> <div class="prev_link"><a href="future_work.html"><img src="prev.gif" alt="future work" border="0"><br> Future work </a></div> <div class="up_link"><a href="index.html"><img src="up.gif" alt="index" border="0"><br> Index </a></div> <div class="next_link"><a href="acknowledgements.html"><img src="next.gif" alt="acknowledgements" border="0"><br> Acknowledgements </a></div><br clear="all" style="clear: all;"> <br> <p>Revised April 22nd 2010</p> <p>&copy; Copyright 2003-2010 Joaqu&iacute;n M L&oacute;pez Mu&ntilde;oz. Distributed under the Boost Software License, Version 1.0. (See accompanying file <a href="../../../LICENSE_1_0.txt"> LICENSE_1_0.txt</a> or copy at <a href="http://www.boost.org/LICENSE_1_0.txt"> http://www.boost.org/LICENSE_1_0.txt</a>) </p> </body> </html>
gorkinovich/DefendersOfMankind
dependencies/boost-1.46.0/libs/multi_index/doc/release_notes.html
HTML
gpl-3.0
14,734
package org.lh.dmlj.schema.editor.dictionary.tools.template; public class RecordProcedureListQueryTemplate implements IQueryTemplate { protected static String nl; public static synchronized RecordProcedureListQueryTemplate create(String lineSeparator) { nl = lineSeparator; RecordProcedureListQueryTemplate result = new RecordProcedureListQueryTemplate(); nl = null; return result; } public final String NL = nl == null ? (System.getProperties().getProperty("line.separator")) : nl; protected final String TEXT_1 = "SELECT S_010.ROWID AS S_010_ROWID, " + NL + " SRCD_113.ROWID AS SRCD_113_ROWID," + NL + " SRCALL_040.ROWID AS SRCALL_040_ROWID, " + NL + " * " + NL + "FROM \""; protected final String TEXT_2 = "\".\"S-010\" AS S_010," + NL + " \""; protected final String TEXT_3 = "\".\"SRCD-113\" AS SRCD_113," + NL + " \""; protected final String TEXT_4 = "\".\"SRCALL-040\" AS SRCALL_040 " + NL + "WHERE S_NAM_010 = '"; protected final String TEXT_5 = "' AND S_SER_010 = "; protected final String TEXT_6 = " AND" + NL + " \"S-SRCD\" AND" + NL + " \"SRCD-SRCALL\""; public String generate(Object argument) { final StringBuffer stringBuffer = new StringBuffer(); /** * Copyright (C) 2014 Luc Hermans * * 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/>. * * Contact information: kozzeluc@gmail.com. */ Object[] args = (Object[]) argument; String sysdirlSchema = (String) args[0]; String schemaName = (String) args[1]; int schemaVersion = ((Integer) args[2]).intValue(); stringBuffer.append(TEXT_1); stringBuffer.append( sysdirlSchema ); stringBuffer.append(TEXT_2); stringBuffer.append( sysdirlSchema ); stringBuffer.append(TEXT_3); stringBuffer.append( sysdirlSchema ); stringBuffer.append(TEXT_4); stringBuffer.append( schemaName ); stringBuffer.append(TEXT_5); stringBuffer.append( schemaVersion ); stringBuffer.append(TEXT_6); return stringBuffer.toString(); } }
kozzeluc/dmlj
Eclipse CA IDMS Schema Diagram Editor/bundles/org.lh.dmlj.schema.editor.dictionary.tools/src/org/lh/dmlj/schema/editor/dictionary/tools/template/RecordProcedureListQueryTemplate.java
Java
gpl-3.0
2,693
# -*- coding: utf-8 -*- #################### 本文件用于进行基本的 json urlencode 操作 import sys,re import json from jsonpath_rw import jsonpath, parse # pip2/pip3 install jsonpath_rw from lxml import etree import platform sysstr = platform.system() ### 判断操作系统类型 Windows Linux . 本脚本函数入口, 统一以 LINUX 为准, 其后在函数内进行转换 ######################################### JSON # jsonpath 可以通过 firefox JSON-handle 插件获得, 或 https://jsonpath.curiousconcept.com/ jsondoc=None ##################### 返回对应 json 节点 def jsonnode(jsonstr,jsonpath): if jsonpath[0:5]=="JSON.": ## 适应 JSON-handle 的 json path jsonpath="$." + jsonpath[5:] if jsonpath[:1]=="@": ## 直接叶子写法 jsonpath="$.." + jsonpath[1:] + "[0]" #print(jsonpath) try: jsonpath_expr = parse(jsonpath) except: return None global jsondoc jsondoc = json.loads(jsonstr) for match in jsonpath_expr.find(jsondoc): node=match return node ##################### JSON 读取指定节点 def readjson_old(jsonstr,jsonpath): ##### jsonpath_rw 中文内容节点的取值有点问题, 原始方法弃用 node=jsonnode(jsonstr,jsonpath) try: value=node.value except: print(u"没有找到JSON节点: " + jsonpath) value="" return value def initjson(jsonstr,jsonpath): # 初始化 json 字符串 node=jsonnode(jsonstr,jsonpath) ### jsonpath_rw 中对应功能未实现写操作 ### node.value=value ############# 使用正则处理 #print(dir(jsondoc)) if sys.version_info.major==2: jsonstr=str(jsondoc).decode('unicode_escape') else: jsonstr=str(jsondoc) jsonstr=jsonstr.replace("u'","'") return(jsonstr,node) def leftjsonpos(jsonstr,jsonpath): # 对应jsonpath值前的左侧位置 (jsonstr,node)=initjson(jsonstr,jsonpath) try: repath=str(node.full_path) except: print(u"没有找到JSON节点: " + jsonpath) return(-1,"") #print(repath) ### 通过正则表达式 if repath[len(repath)-4:]==".[0]": # 叶子节点的 .[0] repath=repath[:len(repath)-4] #print(jsonstr) repathlist=repath.split(".") #print(repathlist) #左侧特征举例 (.*l1('|\"):(.*).*('|\")l1_1('|\"): ('|\"|\[\"|\[\')) #{'l2': {'l2_3': {}, 'l2_2': True, 'l2_1': None}, 'l1': {'l1_1': ['中文测试', 'l1_1_2'], 'l1_2': {'l1_2_1': 121}}} repath= "('|\"):(.*).*('|\")".join(repathlist) ## 单引号或双引号 repath=".*" + repath + "('|\"): ('|\"|\[\"|\[\')" ### 几种可能 ' " [" [' #repath=".*" + repath + "('|\"): ('|\")" repath="(" + repath + ")" ## 左侧特征 #print(repath) matchs=re.match(repath,jsonstr,re.DOTALL) ### 最后一个参数解决换行问题 if matchs!=None: leftstr=matchs.groups()[0] ## 左侧串 #print(leftstr) return(len(leftstr),leftstr) else: ### 没找到 print("没有找到JSON节点左侧边缘:" + jsonpath) return -1 def rightjsonpos(jsonstr,jsonpath): # 对应jsonpath值后的右侧位置 (left,leftstr)=leftjsonpos(jsonstr,jsonpath) ## 左侧串位置 if left==-1: print("没有找到JSON节点左侧边缘:" + jsonpath) return -1 (jsonstr,node)=initjson(jsonstr,jsonpath) ## 格式化总体串(取位置,必须按格式化串操作) ### 右侧单引号或双引号 pos1=jsonstr.find("'", left+1) pos2=jsonstr.find("\"", left+1) if pos2==-1: rightstr=jsonstr[pos1:] ## 右侧串 pos=pos1 elif pos1==-1: rightstr=jsonstr[pos2:] pos=pos2 elif pos1<pos2: rightstr=jsonstr[pos1:] pos=pos1 else: rightstr=jsonstr[pos2:] pos=pos2 return(pos,rightstr) def readjson(jsonstr,jsonpath): (left,leftstr)=leftjsonpos(jsonstr,jsonpath) ## 左侧串位置 if left==-1: return "" (right,rightstr)=rightjsonpos(jsonstr,jsonpath) ## 右侧串位置 if right==-1: return "" (jsonstr,node)=initjson(jsonstr,jsonpath) ## 格式化总体串(取位置,必须按格式化串操作) #print(left) #print(right) ret=jsonstr[left:right] return ret #### 第二种纯字符串方法得到某个叶子节点方法, 相对稳健,只支持 @ 写法 def readjson_once(jsonstr,jsonpath): if jsonpath[:1]=="@": jsonpath=jsonpath[1:] #print(jsonpath) pos=jsonstr.find("\""+jsonpath+"\"") tempstr=jsonstr[pos+len(jsonpath):] #查找并截取到尾部 #print(tempstr) pos1=tempstr.find("}") pos2=tempstr.find(",") if pos1==-1: pos=pos2 elif pos2==-1: pos=pos1 else: pos=min(pos1,pos2) # 结束出现的最先有效位置 #print(pos) tempstr=tempstr[2:pos] #print(tempstr) tempstr=tempstr.replace(":","") #print(tempstr) if tempstr.find("\"")==-1: # 数字类型 text=str(int(tempstr)) else: #字符串 pos1=tempstr.find("\"") pos2=tempstr[pos1+1:].find("\"") #print(pos1,pos2) text=tempstr[pos1+1:pos2+2] return text ##################### JSON 写入指定节点 ----------------- 多个节点 [n] 暂时不能处理 def writejson(jsonstr, jsonpath, value): (left,leftstr)=leftjsonpos(jsonstr,jsonpath) ## 左侧串 if left==-1: return jsonstr (right,rightstr)=rightjsonpos(jsonstr,jsonpath) ## 右侧串 if right==-1: return jsonstr #print(left) #print(right) #print("left: " + leftstr) #print("right: " +rightstr) res=leftstr +value + rightstr ## 左右拼加 ### json 单引号变双引号 res=res.replace("'","\"") return res def writejson_ffile(files, jsonpath, value): ### 从 json 文件读取 并修改对应的值 data=open(files).read() jsonstr=writejson(data, jsonpath, value) return jsonstr ################################### URLCODE def writeurlcode(data, path, value): ##### 修改某个值 vardata=path+"=" + readurlcode(data, path) urlcodestr=data.replace(vardata, path+"=" + value) urlcodestr=urlcodestr.replace("\n","") urlcodestr=urlcodestr.replace("\r","") return urlcodestr def readurlcode(data, path): ##### 读取某个值 value="" pos1=data.find(path+"=") #print(pos1) if pos1>=0 and pos1+4<len(data): ## 找到且不在末尾 pos2=data.find("&",pos1+4) #print(pos2) if pos2<0: value=data[pos1+4:] else: value=data[pos1+4:pos2] return value def writeurlcode_ffile(files, path, value): ####### 从文件读取, 然后修改某个值 data=open(files).read() data=data.replace("\n","") data=data.replace("\r","") urlcodestr=writejson(data, path, value) return urlcodestr #################################### HTML def readhtml(data,xpath): etrees=etree.HTML(data) ##### lxml 处理 xpath 特点 xpath=xpath.replace("html/body/","//") ### 不能写 html/body/ ,这是 firebug 的写法特点 xpaths=xpath.replace("/tbody/","/") ### 去掉所有 tbody #print(xpaths) ele= etrees.xpath(xpaths) if len(ele)==0: ### 不能用 None 判断 xpaths=xpath ### 不去掉 ele= etrees.xpath(xpaths) ##### types="" ## 暂时只支持取 text ##### try: if types=="": values=ele[0].text ### 元素的 text else: values=str(etrees.xpath(xpaths+ "/@" + types)[0]) ### 元素的对应属性 #print(values) except: #print(u"** 数据截获异常 **") values="" ## 没有这个元素则返回为空 if values==None or len(ele)==0: print("HTML节点: " +xpath +" 查找失败.") values="" return values ################################### 自动区分类型 def whichtypes(data): ## 判断类型 #print(data) xmlre=data.count('<') jsonre=data.count('{') urlcodere=data.count('=') data=data.strip() types="" if data[:6]=="<?xml ": types="xml" elif data.find("<html")>=0 and data.find("</html>")>0: types="html" elif xmlre>jsonre and xmlre>urlcodere: types="xml" elif jsonre>xmlre and jsonre>urlcodere: types="json" elif urlcodere>xmlre and urlcodere>jsonre: types="urlcode" #print(types) return types def writenode(data, path,value): ## 判断类型 types=whichtypes(data) if types=="xml": data=writexml(data, path, value) if types=="json": data=writejson(data, path, value) if types=="urlcode": data=writeurlcode(data, path, value) if types=="html": hues.error("html格式只支持读节点") return data def readnode(data,path): ## 判断类型 types=whichtypes(data) if types=="": print("数据类型识别错误") return "" value="" if types=="xml": value=readxml(data,path) if types=="json": value=readjson(data,path) if types=="urlcode": value=readurlcode(data, path) if types=="html": value=readhtml(data,path) return value def writenode_ffile(files, path, value): ## 判断类型 data=open(files).read() types=whichtypes(data) if types=="": hues.error("文件类型识别错误") return "" if types=="xml": data=writexml_ffile(files, path, value) if types=="json": data=writejson_ffile(files, path, value) if types=="urlcode": data=writeurlcode_ffile(files, path, value) if types=="html": hues.error("html格式只支持读节点") return data
sheerfish999/torpedo
modules/dodata.py
Python
gpl-3.0
9,121
import json import pytest from plugins.fishbans import fishbans, bancount from cloudbot import http test_user = "notch" test_api = """ {"success":true,"stats":{"username":"notch","uuid":"069a79f444e94726a5befca90e38aaf5","totalbans":11,"service":{"mcbans":0,"mcbouncer":11,"mcblockit":0,"minebans":0,"glizer":0}}} """ test_api_single = """ {"success":true,"stats":{"username":"notch","uuid":"069a79f444e94726a5befca90e38aaf5","totalbans":1,"service":{"mcbans":0,"mcbouncer":1,"mcblockit":0,"minebans":0,"glizer":0}}} """ test_api_none = """ {"success":true,"stats":{"username":"notch","uuid":"069a79f444e94726a5befca90e38aaf5","totalbans":0,"service":{"mcbans":0,"mcbouncer":0,"mcblockit":0,"minebans":0,"glizer":0}}} """ test_api_failed = """ {"success":false} """ bans_reply = "The user \x02notch\x02 has \x0211\x02 bans - http://fishbans.com/u/notch/" count_reply = "Bans for \x02notch\x02: mcbouncer: \x0211\x02 - http://fishbans.com/u/notch/" bans_reply_single = "The user \x02notch\x02 has \x021\x02 ban - http://fishbans.com/u/notch/" bans_reply_failed = "Could not fetch ban data for notch." count_reply_failed = "Could not fetch ban data for notch." bans_reply_none = "The user \x02notch\x02 has no bans - http://fishbans.com/u/notch/" count_reply_none = "The user \x02notch\x02 has no bans - http://fishbans.com/u/notch/" def test_bans(monkeypatch): """ tests fishbans with a successful API response having multiple bans """ def fake_http(url): assert url == "http://api.fishbans.com/stats/notch/" return json.loads(test_api) monkeypatch.setattr(http, "get_json", fake_http) assert fishbans(test_user) == bans_reply def test_bans_single(monkeypatch): """ tests fishbans with a successful API response having a single ban """ def fake_http(url): assert url == "http://api.fishbans.com/stats/notch/" return json.loads(test_api_single) monkeypatch.setattr(http, "get_json", fake_http) assert fishbans(test_user) == bans_reply_single def test_bans_failed(monkeypatch): """ tests fishbans with a failed API response """ def fake_http(url): assert url == "http://api.fishbans.com/stats/notch/" return json.loads(test_api_failed) monkeypatch.setattr(http, "get_json", fake_http) assert fishbans(test_user) == bans_reply_failed def test_bans_none(monkeypatch): """ tests fishbans with a successful API response having no bans """ def fake_http(url): assert url == "http://api.fishbans.com/stats/notch/" return json.loads(test_api_none) monkeypatch.setattr(http, "get_json", fake_http) assert fishbans(test_user) == bans_reply_none def test_count(monkeypatch): def fake_http(url): assert url == "http://api.fishbans.com/stats/notch/" return json.loads(test_api) monkeypatch.setattr(http, "get_json", fake_http) assert bancount(test_user) == count_reply def test_count_failed(monkeypatch): def fake_http(url): assert url == "http://api.fishbans.com/stats/notch/" return json.loads(test_api_failed) monkeypatch.setattr(http, "get_json", fake_http) assert bancount(test_user) == count_reply_failed def test_count_no_bans(monkeypatch): def fake_http(url): assert url == "http://api.fishbans.com/stats/notch/" return json.loads(test_api_none) monkeypatch.setattr(http, "get_json", fake_http) assert bancount(test_user) == count_reply_none
Zarthus/CloudBotRefresh
plugins/test/test_fishbans.py
Python
gpl-3.0
3,502
<!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="X-UA-Compatible" content="IE=Edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>CTEST_GIT_UPDATE_OPTIONS &mdash; CMake 3.15.1 Documentation</title> <link rel="stylesheet" href="../_static/cmake.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <link rel="shortcut icon" href="../_static/cmake-favicon.ico"/> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="CTEST_HG_COMMAND" href="CTEST_HG_COMMAND.html" /> <link rel="prev" title="CTEST_GIT_UPDATE_CUSTOM" href="CTEST_GIT_UPDATE_CUSTOM.html" /> </head><body> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="CTEST_HG_COMMAND.html" title="CTEST_HG_COMMAND" accesskey="N">next</a> |</li> <li class="right" > <a href="CTEST_GIT_UPDATE_CUSTOM.html" title="CTEST_GIT_UPDATE_CUSTOM" accesskey="P">previous</a> |</li> <li> <img src="../_static/cmake-logo-16.png" alt="" style="vertical-align: middle; margin-top: -2px" /> </li> <li> <a href="https://cmake.org/">CMake</a> &#187; </li> <li> <a href="../index.html">3.15.1 Documentation</a> &#187; </li> <li class="nav-item nav-item-1"><a href="../manual/cmake-variables.7.html" accesskey="U">cmake-variables(7)</a> &#187;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="ctest-git-update-options"> <span id="variable:CTEST_GIT_UPDATE_OPTIONS"></span><h1>CTEST_GIT_UPDATE_OPTIONS<a class="headerlink" href="#ctest-git-update-options" title="Permalink to this headline">¶</a></h1> <p>Specify the CTest <code class="docutils literal notranslate"><span class="pre">GITUpdateOptions</span></code> setting in a <span class="target" id="index-0-manual:ctest(1)"></span><a class="reference internal" href="../manual/ctest.1.html#manual:ctest(1)" title="ctest(1)"><code class="xref cmake cmake-manual docutils literal notranslate"><span class="pre">ctest(1)</span></code></a> dashboard client script.</p> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="CTEST_GIT_UPDATE_CUSTOM.html" title="previous chapter">CTEST_GIT_UPDATE_CUSTOM</a></p> <h4>Next topic</h4> <p class="topless"><a href="CTEST_HG_COMMAND.html" title="next chapter">CTEST_HG_COMMAND</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/variable/CTEST_GIT_UPDATE_OPTIONS.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="CTEST_HG_COMMAND.html" title="CTEST_HG_COMMAND" >next</a> |</li> <li class="right" > <a href="CTEST_GIT_UPDATE_CUSTOM.html" title="CTEST_GIT_UPDATE_CUSTOM" >previous</a> |</li> <li> <img src="../_static/cmake-logo-16.png" alt="" style="vertical-align: middle; margin-top: -2px" /> </li> <li> <a href="https://cmake.org/">CMake</a> &#187; </li> <li> <a href="../index.html">3.15.1 Documentation</a> &#187; </li> <li class="nav-item nav-item-1"><a href="../manual/cmake-variables.7.html" >cmake-variables(7)</a> &#187;</li> </ul> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2000-2019 Kitware, Inc. and Contributors. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.7.2. </div> </body> </html>
libcrosswind/libcrosswind
platform/windows/support/cmake/doc/cmake/html/variable/CTEST_GIT_UPDATE_OPTIONS.html
HTML
gpl-3.0
5,458
package com.dozuki.ifixit.model.guide.wizard; import android.support.v4.app.Fragment; import android.text.TextUtils; import com.dozuki.ifixit.ui.guide.create.wizard.GuideTitleFragment; import java.util.ArrayList; public class GuideTitlePage extends EditTextPage { public static final String TITLE_DATA_KEY = "name"; public GuideTitlePage(ModelCallbacks callbacks) { super(callbacks); } @Override public Fragment createFragment() { return GuideTitleFragment.create(getKey()); } @Override public void getReviewItems(ArrayList<ReviewItem> dest) { dest.add(new ReviewItem(super.getTitle(), mData.getString(TITLE_DATA_KEY), getKey(), -1)); } @Override public boolean isCompleted() { return !TextUtils.isEmpty(mData.getString(TITLE_DATA_KEY)); } }
iFixit/iFixitAndroid
App/src/com/dozuki/ifixit/model/guide/wizard/GuideTitlePage.java
Java
gpl-3.0
811
/* * Copyright (C) 2015 Cybernetica * * Research/Commercial License Usage * Licensees holding a valid Research License or Commercial License * for the Software may use this file according to the written * agreement between you and Cybernetica. * * GNU General Public License Usage * Alternatively, this file may be used under the terms of the GNU * General Public License version 3.0 as published by the Free Software * Foundation and appearing in the file LICENSE.GPL included in the * packaging of this file. Please review the following information to * ensure the GNU General Public License version 3.0 requirements will be * met: http://www.gnu.org/copyleft/gpl-3.0.html. * * For further information, please contact us at sharemind@cyber.ee. */ #include "ToString.h" #include <cassert> #include <cstdint> #include <cstring> #include <iomanip> #include <limits> #include <sharemind/libsoftfloat/softfloat.h> #include <sharemind/libsoftfloat_math/sf_log.h> #include <sstream> SHAREMIND_EXTERN_C_BEGIN /* * Mandatory cref parameter: public float32 vector * Mandatory ref parameter: result vector */ SHAREMIND_MODULE_API_0x1_SYSCALL(float32_log, args, num_args, refs, crefs, returnValue, c) { (void) c; (void) args; if (num_args != 0u || returnValue || !crefs || !refs) return SHAREMIND_MODULE_API_0x1_INVALID_CALL; assert(crefs[0u].pData); assert(refs[0u].pData); if (crefs[0u].size != refs[0u].size) return SHAREMIND_MODULE_API_0x1_INVALID_CALL; const sf_float32 * const in = static_cast<const sf_float32 *>(crefs[0u].pData); sf_float32 * const out = static_cast<sf_float32 *>(refs[0u].pData); for (size_t i = 0u; i < crefs[0u].size / sizeof(sf_float32); i++) out[i] = sf_float32_log(in[i], sf_fpu_state_default).result; return SHAREMIND_MODULE_API_0x1_OK; } /* * Mandatory cref parameter: public float64 vector * Mandatory ref parameter: result vector */ SHAREMIND_MODULE_API_0x1_SYSCALL(float64_log, args, num_args, refs, crefs, returnValue, c) { (void) c; (void) args; if (num_args != 0u || returnValue || !crefs || !refs) return SHAREMIND_MODULE_API_0x1_INVALID_CALL; assert(crefs[0u].pData); assert(refs[0u].pData); if (crefs[0u].size != refs[0u].size) return SHAREMIND_MODULE_API_0x1_INVALID_CALL; const sf_float64 * const in = static_cast<const sf_float64 *>(crefs[0u].pData); sf_float64 * const out = static_cast<sf_float64 *>(refs[0u].pData); for (size_t i = 0u; i < crefs[0u].size / sizeof(sf_float64); i++) out[i] = sf_float64_log(in[i], sf_fpu_state_default).result; return SHAREMIND_MODULE_API_0x1_OK; } SHAREMIND_EXTERN_C_END
sharemind-sdk/mod_algorithms
src/Log.cpp
C++
gpl-3.0
2,892
package org.pepsoft.worldpainter.layers.renderers; import java.io.Serializable; public interface IndexedLayerRenderer<T extends Serializable> extends LayerRenderer { int getPixelColour(int x, int y, int underlyingColour, T value); }
Captain-Chaos/WorldPainter
WorldPainter/WPCore/src/main/java/org/pepsoft/worldpainter/layers/renderers/IndexedLayerRenderer.java
Java
gpl-3.0
239