code
stringlengths
2
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
2
1.05M
export function QuerySelectorAllIterate(el:HTMLElement, query:string) : HTMLElement[] { let els :HTMLElement[] = []; if ('function'==typeof el.matches) { if (el.matches(query)) { els.push(el); } } else if ('function'==typeof (el as any).matchesSelector) { if ((el as any).matchesSelector(query)) { els.push(el as HTMLElement); } } let childSelector = el.querySelectorAll(query); for (let i=0; i<childSelector.length; i++) { els.push(childSelector.item(i) as HTMLElement); } return els; }
katmutua/electric-book-gui
src/ts/querySelectorAll-extensions.ts
TypeScript
gpl-3.0
514
<?php /* * ©2013 Croce Rossa Italiana */ paginaPrivata(); caricaSelettore(); controllaParametri(['id'], 'attivita.gestione&err'); $a = Attivita::id($_GET['id']); paginaAttivita($a); if (!$a->haPosizione()) { redirect('attivita.localita&id=' . $a->id); } $del = $me->delegazioni(APP_ATTIVITA); $comitati = $me->comitatiDelegazioni(APP_ATTIVITA); $domini = $me->dominiDelegazioni(APP_ATTIVITA); $g = GeoPolitica::daOid($a->comitato); $visMinima = $a->visibilitaMinima($g); ?> <form action="?p=attivita.modifica.ok" method="POST"> <input type="hidden" name="id" value="<?php echo $a->id; ?>" /> <div class="row-fluid"> <div class="span7"> <h2><i class="icon-flag muted"></i> Dettagli dell'attività</h2> </div> <div class="btn-group pull-right"> <button type="submit" name="azione" value="salva" class="btn btn-success btn-large"> <i class="icon-save"></i> Salva l'attività </button> </div> </div> <hr /> <div class="row-fluid"> <div class="span8"> <div class="alert alert-info"> <i class="icon-info-sign"></i> Presta molta attenzione quando decidi <strong> quali volontari possono partecipare </strong>:</br> <ul> <li>Se selezioni <strong>Tutti i Volontari della Croce Rossa Italiana</strong> permetti a tutti gli iscritti su Gaia di dare disponibilità per l'attività. </li> <li>Se selezioni <strong>Pubblica</strong> permetti anche a chi <strong>non</strong> è Volontario di partecipare. </li> </ul> </div> <div class="form-horizontal"> <div class="control-group"> <label class="control-label" for="inputNome">Nome</label> <div class="controls"> <input class="input-xlarge grassetto" value="<?php echo $a->nome; ?>" type="text" id="inputNome" name="inputNome" placeholder="Es.: Aggiungi un Posto a Tavola" required autofocus pattern=".{2,}" /> </div> </div> <div class="control-group"> <label class="control-label" for="inputVisibilita">Quali volontari possono chiedere di partecipare?</label> <div class="controls"> <select class="input-xxlarge" name="inputVisibilita"> <?php foreach ( $conf['att_vis'] as $num => $nom ) { if ($num < $visMinima) { continue; }?> <option value="<?php echo $num; ?>" <?php if ( $a->visibilita == $num ) { ?> selected="selected" <?php } ?> > <?php echo $nom; ?> </option> <?php } ?> </select> <p class="text-info"><i class="icon-info-sign"></i> I volontari al di fuori di questa selezione non vedranno l'attività nel calendario.</p> </div> </div> <div class="control-group"> <label class="control-label" for="inputDescrizione">Descrizione ed informazioni per i volontari</label> <div class="controls"> <textarea rows="10" class="input-xlarge conEditor" type="text" id="inputDescrizione" name="inputDescrizione"><?php echo $a->descrizione; ?></textarea> </div> </div> </div> </div> <div class="span4"> <p> <strong>Referente</strong><br /> <?php echo $a->referente()->nomeCompleto(); ?> </p> <p> <strong>Organizzatore</strong><br /> <?php echo $g->nomeCompleto(); ?> </p> <p> <strong>Area d'intervento</strong><br /> <?php echo $a->area()->nomeCompleto(); ?> </p> <p> <strong>Posizione geografica</strong><br /> <?php echo $a->luogo; ?><br /> <a href='?p=attivita.localita&id=<?= $a->id; ?>'> <i class='icon-pencil'></i> modifica la località </a> </p> </div> </div> </form>
CroceRossaCatania/gaia
inc/attivita.modifica.php
PHP
gpl-3.0
4,359
/* ************************************************************************ Copyright: License: Authors: ************************************************************************ */ qx.Theme.define("${Namespace}.theme.modern.Decoration", { decorations : { } });
09zwcbupt/undergrad_thesis
ext/poxdesk/qx/component/skeleton/contribution/trunk/source/class/custom/theme/modern/Decoration.tmpl.js
JavaScript
gpl-3.0
280
<?php include ('lib/twitese.php'); $title = "Settings"; include ('inc/header.php'); if (!loginStatus()) header('location: login.php'); ?> <script src="js/colorpicker.js"></script> <script src="js/setting.js"></script> <link rel="stylesheet" href="css/colorpicker.css" /> <div id="statuses" class="column round-left"> <div id="setting"> <div id="setting_nav"> <?php $settingType = isset($_GET['t'])? $_GET['t'] : 1; switch($settingType){ case 'profile': ?> <span class="subnavLink"><a href="setting.php">Customize</a></span><span class="subnavNormal">Profile</span> <?php break; default: ?> <span class="subnavNormal">Customize</span><span class="subnavLink"><a href="setting.php?t=profile">Profile</a></span> <?php } ?> </div> <?php switch($settingType){ case 'profile': $user = getTwitter()->veverify(true); ?> <form id="setting_form" action="ajax/uploadImage.php?do=profile" method="post" enctype="multipart/form-data"> <fieldset class="settings"> <legend>Avatar</legend> <ol> <li style="display:inline-block"><img src="<?php echo isset($_COOKIE['imgurl']) ? $_COOKIE['imgurl'] : getAvatar($user->profile_image_url)?>" id="avatarimg"></img></li> <ol style="margin-left:29px"> <li><input type="file" name="image" id="profile_image"/></li> <li><input type="submit" id="AvatarUpload" class="btn" value="Upload"/><small style="margin-left:10px;vertical-align: middle;">BMP,JPG or PNG accepted, less than 800K.</small></li> </ol></ol> </fieldset> </form> <form id="setting_form" action="ajax/uploadImage.php?do=background" method="post" enctype="multipart/form-data"> <fieldset class="settings"> <legend>Background</legend> <ol> <li style="display:inline-block"><img src="<?php echo getAvatar($user->profile_background_image_url)?>" id="backgroundimg" style="max-width: 460px;"></img></li> <li><input type="file" name="image" id="profile_background"/></li> <li><input type="submit" id="BackgroundUpload" class="btn" value="Upload"/><small style="margin-left:10px;vertical-align: middle;">BMP,JPG or PNG accepted, less than 800K.</small></li> <li> <input id="tile" type="checkbox" <?php echo $user->profile_background_tile ? 'checked="checked"' : '' ?> /> <label>Tile the profile background</label> </li> </ol> </fieldset> </form> <form id="setting_form" action="ajax/updateProfile.php" method="post"> <fieldset class="settings"> <legend>Literature</legend> <table id="setting_table"> <tr> <td class="setting_title">Name: </td> <td><input class="setting_input" type="text" name="name" value="<?php echo isset($user->name) ? $user->name : ''?>" /></td> </tr> <tr> <td class="setting_title">URL: </td> <td><input class="setting_input" type="text" name="url" value="<?php if (!isset($user->url)) echo ''; else { $hops = array(); $newurl = expandRedirect($user->url, $hops); echo $newurl; } ?>" /></td> </tr> <tr> <td class="setting_title">Location: </td> <td><input class="setting_input" type="text" name="location" value="<?php echo isset($user->location) ? $user->location : '' ?>" /></td> </tr> <tr> <td class="setting_title">Bio: </td><td><small style="margin-left:5px;vertical-align: top;">*Max 160 chars</small></td> </tr><tr> <td></td> <td><textarea id="setting_text" name="description"><?php echo isset($user->description) ? $user->description : '' ?></textarea></td> </tr> </table> <input type="submit" id="saveProfile" class="btn" value="Save" /> </fieldset> <?php break; default: ?> <form id="style_form" action="setting.php" method="post"> <fieldset class="settings"> <legend>Utility</legend> <input id="proxifyAvatar" type="checkbox" /> <label>Proxify the Avatar</label> <br /><br /> <input id="autoscroll" type="checkbox" /> <label>Timeline Autopaging</label> <br /><br /> <input id="sidebarscroll" type="checkbox" /> <label>Fixed Sidebar</label> <br /><br /> Share to Twitter: <a class="share" title="Drag me to share!" href="javascript:var%20d=document,w=window,f='<?php echo $base_url."/share.php" ?>',l=d.location,e=encodeURIComponent,p='?u='+e(l.href)+'&t='+e(d.title)+'&d='+e(w.getSelection?w.getSelection().toString():d.getSelection?d.getSelection():d.selection.createRange().text)+'&s=bm';a=function(){if(!w.open(f+p,'sharer','toolbar=0,status=0,resizable=0,width=600,height=300,left=175,top=150'))l.href=f+'.new'+p};if(/Firefox/.test(navigator.userAgent))setTimeout(a,0);else{a()}void(0);">Share</a> <small>(Bookmark this link for future use)</small> </fieldset> <fieldset class="settings"> <legend>Media Preview</legend> <input id="showpic" type="checkbox" checked="checked" /> <label>Enable Images Preview</label> <small>(Supports common image hostings)</small> <br /><br /> <input id="mediaPreSelect" type="checkbox" checked="checked" /> <label>Enable Videos Preview</label> <small>(Supports Xiami and Tudou)</small><br /> </fieldset> <fieldset class="settings"> <legend>Auto Refresh Interval</legend> <label>Home Page</label> <select id="homeInterval" name="homeInterval" value="<?php echo getCookie('homeInterval')?>"> <option value="1">1 min</option> <option value="2" selected="selected">2 min (Default)</option> <option value="3">3 min</option> <option value="5">5 min</option> <option value="10">10 min</option> <option value="0">Never</option> </select> <label>Updates Page</label> <select id="updatesInterval" name="updatesInterval" value="<?php echo getCookie('updatesInterval')?>"> <option value="1">1 min</option> <option value="2">2 min</option> <option value="3" selected="selected">3 min (Default)</option> <option value="5">5 min</option> <option value="10">10 min</option> <option value="0">Never</option> </select> </fieldset> <fieldset class="settings"> <legend>UI Preferences</legend> <input id="twitterbg" type="checkbox" /> <label>Use twitter account background</label> <br /><br /> <input id="shownick" type="checkbox" /> <label>Use nickname instead of username</label> <br /><br /> <label>Background Color</label> <input class="bg_input" type="text" id="bodyBg" name="bodyBg" value="<?php echo getDefCookie("Bgcolor","") ?>" /> <small>(Choose your favorite color here)</small> <br /><br /> <label>Font Size</label> <select id="fontsize" name="fontsize" value="<?php echo getCookie('fontsize')?>"> <option value="12px">Small</option> <option value="13px" selected="selected">Middle(Default)</option> <option value="14px">Large</option> <option value="15px">Extra Large</option> </select> <small>(Set the font size)</small> <br /><br /> <label>Customize CSS</label> <small>(You can put your own CSS hack here, or your Twitter style code)</small> <br /> <label>Tips:</label> <small>You must use <a href="http://i.zou.lu/csstidy/" target="_blank" title="Powered by Showfom">CSSTidy</a> to compress your stylesheet.</small> <br /> <textarea type="text" id="myCSS" name="myCSS" value="" /><?php echo getDefCookie("myCSS","") ?></textarea> </fieldset> <?php } ?> <a id="reset_link" href="#" title="You will lose all customized settings!">Reset to default</a> </form> </div> </div> <?php include ('inc/sidebar.php'); include ('inc/footer.php'); ?>
xctcc/embrr
setting.php
PHP
gpl-3.0
7,543
exports.play = 'afplay'; exports.raise_volume = 'osascript -e "set Volume 10"'; // unmutes as well
prey/prey-node-client
lib/agent/actions/alarm/mac.js
JavaScript
gpl-3.0
98
package de.metas.ui.web.window.exceptions; import org.adempiere.exceptions.AdempiereException; import de.metas.ui.web.window.datatypes.DocumentPath; import de.metas.ui.web.window.model.Document; /* * #%L * metasfresh-webui-api * %% * Copyright (C) 2016 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ @SuppressWarnings("serial") public class InvalidDocumentStateException extends AdempiereException { public InvalidDocumentStateException(final Document document, final String reason) { super(buildMsg(document.getDocumentPath(), reason)); } public InvalidDocumentStateException(final DocumentPath documentPath, final String reason) { super(buildMsg(documentPath, reason)); } private static String buildMsg(final DocumentPath documentPath, final String reason) { return "Document " + documentPath + " state is invalid: " + reason; } }
metasfresh/metasfresh-webui-api
src/main/java/de/metas/ui/web/window/exceptions/InvalidDocumentStateException.java
Java
gpl-3.0
1,498
module Genome module Importers module DSL module WithDrugsAndGenes attr_accessor :gene_claim, :drug_claim def initialize(item_id, importer_instance, row_instance) super(item_id, importer_instance, row_instance, 'interaction_claim') end def gene(column, opts = {}, &block) opts = @defaults.merge opts val = opts[:transform].call(@row.send(column)) if !opts[:unless].call(val) @gene_claim_id = @importer.create_gene_claim(name: val, nomenclature: opts[:nomenclature]) node = GeneNode.new(@gene_claim_id, @importer, @row) node.instance_eval(&block) end end def drug(column, opts = {}, &block) opts = @defaults.merge opts val = opts[:transform].call(@row.send(column)) if !opts[:unless].call(val) @drug_claim_id = @importer.create_drug_claim(name: val, nomenclature: opts[:nomenclature], primary_name: opts[:transform].call(@row.send(opts[:primary_name]))) node = DrugNode.new(@drug_claim_id, @importer, @row) node.instance_eval(&block) end end end end end end
genome/dgi-db
lib/genome/importers/dsl/with_drugs_and_genes.rb
Ruby
gpl-3.0
1,201
package buildcraftAdditions.ModIntegration.Buildcraft.Triggers; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; import buildcraft.api.statements.IStatementContainer; import buildcraft.api.statements.IStatementParameter; import buildcraftAdditions.tileEntities.TileChargingStation; /** * Copyright (c) 2014, AEnterprise * http://buildcraftadditions.wordpress.com/ * Buildcraft Additions is distributed under the terms of GNU GPL v3.0 * Please check the contents of the license located in * http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/ */ public class TriggerDoneCharging extends BasicTrigger { public TriggerDoneCharging() { super("doneCharging", "TriggerDoneCharging"); } @Override public boolean isTriggerActive(TileEntity target, ForgeDirection side, IStatementContainer source, IStatementParameter[] parameters) { if (target instanceof TileChargingStation) { TileChargingStation chargingStation = (TileChargingStation) target; return chargingStation.getProgress() == 1; } return false; } }
AEnterprise/Buildcraft-Additions
src/main/java/buildcraftAdditions/ModIntegration/Buildcraft/Triggers/TriggerDoneCharging.java
Java
gpl-3.0
1,093
#include "MantidAPI/WorkspaceProperty.h" #include "MantidAPI/WorkspaceFactory.h" #include "MantidAPI/WorkspaceGroup.h" #include "MantidSINQ/PoldiFitPeaks1D.h" #include "MantidDataObjects/Workspace2D.h" #include "MantidDataObjects/TableWorkspace.h" #include "MantidAPI/FunctionFactory.h" #include "MantidKernel/BoundedValidator.h" #include "MantidKernel/ListValidator.h" #include "MantidAPI/TableRow.h" #include "MantidSINQ/PoldiUtilities/UncertainValue.h" #include "MantidSINQ/PoldiUtilities/UncertainValueIO.h" #include "MantidAPI/CompositeFunction.h" namespace Mantid { namespace Poldi { using namespace Kernel; using namespace API; using namespace DataObjects; using namespace CurveFitting; // Register the algorithm into the AlgorithmFactory DECLARE_ALGORITHM(PoldiFitPeaks1D) /// Algorithm's name for identification. @see Algorithm::name const std::string PoldiFitPeaks1D::name() const { return "PoldiFitPeaks1D"; } /// Algorithm's version for identification. @see Algorithm::version int PoldiFitPeaks1D::version() const { return 1; } /// Algorithm's category for identification. @see Algorithm::category const std::string PoldiFitPeaks1D::category() const { return "SINQ\\Poldi"; } void PoldiFitPeaks1D::init() { declareProperty( make_unique<WorkspaceProperty<Workspace2D>>("InputWorkspace", "", Direction::Input), "An input workspace containing a POLDI auto-correlation spectrum."); boost::shared_ptr<BoundedValidator<double>> minFwhmPerDirection = boost::make_shared<BoundedValidator<double>>(); minFwhmPerDirection->setLower(2.0); declareProperty( "FwhmMultiples", 2.0, minFwhmPerDirection, "Each peak will be fitted using x times FWHM data in each direction.", Direction::Input); std::vector<std::string> peakFunctions = FunctionFactory::Instance().getFunctionNames<IPeakFunction>(); auto peakFunctionNames = boost::make_shared<ListValidator<std::string>>(peakFunctions); declareProperty("PeakFunction", "Gaussian", peakFunctionNames, "Peak function that will be fitted to all peaks.", Direction::Input); declareProperty(make_unique<WorkspaceProperty<TableWorkspace>>( "PoldiPeakTable", "", Direction::Input), "A table workspace containing POLDI peak data."); declareProperty(make_unique<WorkspaceProperty<TableWorkspace>>( "OutputWorkspace", "RefinedPeakTable", Direction::Output), "Output workspace with refined peak data."); declareProperty(make_unique<WorkspaceProperty<Workspace>>( "FitPlotsWorkspace", "FitPlots", Direction::Output), "Plots of all peak fits."); m_backgroundTemplate = FunctionFactory::Instance().createInitialized( "name=UserFunction, Formula=A0 + A1*(x - x0)^2"); m_profileTies = "f1.x0 = f0.PeakCentre"; } void PoldiFitPeaks1D::setPeakFunction(const std::string &peakFunction) { m_profileTemplate = peakFunction; } PoldiPeakCollection_sptr PoldiFitPeaks1D::getInitializedPeakCollection( const DataObjects::TableWorkspace_sptr &peakTable) const { auto peakCollection = boost::make_shared<PoldiPeakCollection>(peakTable); peakCollection->setProfileFunctionName(m_profileTemplate); return peakCollection; } IFunction_sptr PoldiFitPeaks1D::getPeakProfile(const PoldiPeak_sptr &poldiPeak) const { IPeakFunction_sptr clonedProfile = boost::dynamic_pointer_cast<IPeakFunction>( FunctionFactory::Instance().createFunction(m_profileTemplate)); clonedProfile->setCentre(poldiPeak->q()); clonedProfile->setFwhm(poldiPeak->fwhm(PoldiPeak::AbsoluteQ)); clonedProfile->setHeight(poldiPeak->intensity()); IFunction_sptr clonedBackground = m_backgroundTemplate->clone(); auto totalProfile = boost::make_shared<CompositeFunction>(); totalProfile->initialize(); totalProfile->addFunction(clonedProfile); totalProfile->addFunction(clonedBackground); if (!m_profileTies.empty()) { totalProfile->addTies(m_profileTies); } return totalProfile; } void PoldiFitPeaks1D::setValuesFromProfileFunction( PoldiPeak_sptr poldiPeak, const IFunction_sptr &fittedFunction) const { CompositeFunction_sptr totalFunction = boost::dynamic_pointer_cast<CompositeFunction>(fittedFunction); if (totalFunction) { IPeakFunction_sptr peakFunction = boost::dynamic_pointer_cast<IPeakFunction>( totalFunction->getFunction(0)); if (peakFunction) { poldiPeak->setIntensity( UncertainValue(peakFunction->height(), peakFunction->getError(0))); poldiPeak->setQ( UncertainValue(peakFunction->centre(), peakFunction->getError(1))); poldiPeak->setFwhm(UncertainValue(peakFunction->fwhm(), getFwhmWidthRelation(peakFunction) * peakFunction->getError(2))); } } } double PoldiFitPeaks1D::getFwhmWidthRelation(IPeakFunction_sptr peakFunction) const { return peakFunction->fwhm() / peakFunction->getParameter(2); } void PoldiFitPeaks1D::exec() { setPeakFunction(getProperty("PeakFunction")); // Number of points around the peak center to use for the fit m_fwhmMultiples = getProperty("FwhmMultiples"); // try to construct PoldiPeakCollection from provided TableWorkspace TableWorkspace_sptr poldiPeakTable = getProperty("PoldiPeakTable"); m_peaks = getInitializedPeakCollection(poldiPeakTable); g_log.information() << "Peaks to fit: " << m_peaks->peakCount() << '\n'; Workspace2D_sptr dataWorkspace = getProperty("InputWorkspace"); auto fitPlotGroup = boost::make_shared<WorkspaceGroup>(); for (size_t i = 0; i < m_peaks->peakCount(); ++i) { PoldiPeak_sptr currentPeak = m_peaks->peak(i); IFunction_sptr currentProfile = getPeakProfile(currentPeak); IAlgorithm_sptr fit = getFitAlgorithm(dataWorkspace, currentPeak, currentProfile); bool fitSuccess = fit->execute(); if (fitSuccess) { setValuesFromProfileFunction(currentPeak, fit->getProperty("Function")); MatrixWorkspace_sptr fpg = fit->getProperty("OutputWorkspace"); fitPlotGroup->addWorkspace(fpg); } } setProperty("OutputWorkspace", m_peaks->asTableWorkspace()); setProperty("FitPlotsWorkspace", fitPlotGroup); } IAlgorithm_sptr PoldiFitPeaks1D::getFitAlgorithm(const Workspace2D_sptr &dataWorkspace, const PoldiPeak_sptr &peak, const IFunction_sptr &profile) { double width = peak->fwhm(); double extent = std::min(0.05, std::max(0.002, width)) * m_fwhmMultiples; std::pair<double, double> xBorders(peak->q() - extent, peak->q() + extent); IAlgorithm_sptr fitAlgorithm = createChildAlgorithm("Fit", -1, -1, false); fitAlgorithm->setProperty("CreateOutput", true); fitAlgorithm->setProperty("Output", "FitPeaks1D"); fitAlgorithm->setProperty("CalcErrors", true); fitAlgorithm->setProperty("Function", profile); fitAlgorithm->setProperty("InputWorkspace", dataWorkspace); fitAlgorithm->setProperty("WorkspaceIndex", 0); fitAlgorithm->setProperty("StartX", xBorders.first); fitAlgorithm->setProperty("EndX", xBorders.second); return fitAlgorithm; } } // namespace Poldi } // namespace Mantid
dymkowsk/mantid
Framework/SINQ/src/PoldiFitPeaks1D.cpp
C++
gpl-3.0
7,337
using System; using System.Collections.Generic; using System.Linq; using Challenger_Series.Utils; using LeagueSharp; using LeagueSharp.SDK; using SharpDX; using Color = System.Drawing.Color; using Challenger_Series.Utils; using System.Windows.Forms; using LeagueSharp.Data.Enumerations; using LeagueSharp.SDK.Enumerations; using LeagueSharp.SDK.UI; using LeagueSharp.SDK.Utils; using Menu = LeagueSharp.SDK.UI.Menu; using EloBuddy; using LeagueSharp.SDK; namespace Challenger_Series.Plugins { public class Teemo : CSPlugin { public Teemo() { Q = new Spell(SpellSlot.Q, 680); W = new Spell(SpellSlot.W); E = new Spell(SpellSlot.E); R = new Spell(SpellSlot.R, 300); Q.SetTargetted(0.5f, 1500f); R.SetSkillshot(0.5f, 120f, 1000f, false, SkillshotType.SkillshotCircle); InitMenu(); Orbwalker.OnAction += OnAction; DelayedOnUpdate += OnUpdate; Drawing.OnDraw += OnDraw; Obj_AI_Base.OnProcessSpellCast += OnProcessSpellCast; Events.OnGapCloser += OnGapCloser; Events.OnInterruptableTarget += OnInterruptableTarget; } public override void OnUpdate(EventArgs args) { if (Q.IsReady()) this.QLogic(); if (W.IsReady()) this.WLogic(); if (R.IsReady()) this.RLogic(); } private void OnGapCloser(object oSender, Events.GapCloserEventArgs args) { /*var sender = args.Sender; if (UseEAntiGapclose) { if (args.IsDirectedToPlayer && args.Sender.Distance(ObjectManager.Player) < 750) { if (E.IsReady()) { E.Cast(sender.ServerPosition); } } }*/ } private void OnInterruptableTarget(object oSender, Events.InterruptableTargetEventArgs args) { /*var sender = args.Sender; if (!GameObjects.AllyMinions.Any(m => !m.IsDead && m.CharData.BaseSkinName.Contains("trap") && m.Distance(sender.ServerPosition) < 100) && ObjectManager.Player.Distance(sender) < 550) { W.Cast(sender.ServerPosition); }*/ } private void OnProcessSpellCast(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { base.OnProcessSpellCast(sender, args); /*if (sender is AIHeroClient && sender.IsEnemy) { if (args.SData.Name == "summonerflash" && args.End.Distance(ObjectManager.Player.ServerPosition) < 650) { var pred = Prediction.GetPrediction((AIHeroClient)args.Target, E); if (!pred.Item3.Any(o => o.IsMinion && !o.IsDead && !o.IsAlly)) { E.Cast(args.End); } } }*/ } public override void OnDraw(EventArgs args) { var drawRange = DrawRange.Value; if (drawRange > 0) { Render.Circle.DrawCircle(ObjectManager.Player.Position, drawRange, Color.Gold); } } private void OnAction(object sender, OrbwalkingActionArgs orbwalkingActionArgs) { if (orbwalkingActionArgs.Type == OrbwalkingType.BeforeAttack) { /*if (orbwalkingActionArgs.Target is Obj_AI_Minion && HasPassive && FocusOnHeadShotting && Orbwalker.ActiveMode == OrbwalkingMode.LaneClear) { var target = orbwalkingActionArgs.Target as Obj_AI_Minion; if (target != null && !target.CharData.BaseSkinName.Contains("MinionSiege") && target.Health > 60) { var tg = (AIHeroClient)TargetSelector.GetTarget(715, DamageType.Physical); if (tg != null && tg.IsHPBarRendered) { Orbwalker.ForceTarget = tg; orbwalkingActionArgs.Process = false; } } }*/ } if (orbwalkingActionArgs.Type == OrbwalkingType.AfterAttack) { Orbwalker.ForceTarget = null; if (E.IsReady() && this.UseECombo) { if (!OnlyUseEOnMelees) { var eTarget = TargetSelector.GetTarget(UseEOnEnemiesCloserThanSlider.Value, DamageType.Physical); if (eTarget != null) { var pred = Prediction.GetPrediction(eTarget, E); if (pred.Item3.Count == 0 && (int)pred.Item1 >= (int)HitChance.High) { E.Cast(pred.Item2); } } } else { var eTarget = ValidTargets.FirstOrDefault( e => e.IsMelee && e.Distance(ObjectManager.Player) < UseEOnEnemiesCloserThanSlider.Value && !e.IsZombie); var pred = Prediction.GetPrediction(eTarget, E); if (pred.Item3.Count == 0 && (int)pred.Item1 > (int)HitChance.Medium) { E.Cast(pred.Item2); } } } } } private Menu ComboMenu; private MenuBool UseQCombo; private MenuBool UseWChase; private MenuBool UseECombo; private MenuKeyBind UseRCombo; private MenuBool AlwaysQAfterE; private MenuBool FocusOnHeadShotting; private MenuList<string> QHarassMode; private MenuBool UseWInterrupt; private Menu AutoRConfig; private MenuSlider UseEOnEnemiesCloserThanSlider; private MenuBool OnlyUseEOnMelees; private MenuBool UseEAntiGapclose; private MenuSlider DrawRange; public void InitMenu() { ComboMenu = MainMenu.Add(new Menu("teemocombomenu", "Combo Settings: ")); UseQCombo = ComboMenu.Add(new MenuBool("teemoqcombo", "Use Q", true)); UseWChase = ComboMenu.Add(new MenuBool("usewchase", "Use W when chasing")); UseECombo = ComboMenu.Add(new MenuBool("teemorcombo", "Use R", true)); AutoRConfig = MainMenu.Add(new Menu("teemoautor", "R Settings: ")); new Utils.Logic.PositionSaver(AutoRConfig, R); MainMenu.Attach(); } #region Logic void QLogic() { if (Orbwalker.ActiveMode == OrbwalkingMode.Combo) { if (UseQCombo && Q.IsReady() && ObjectManager.Player.CountEnemyHeroesInRange(800) == 0 && ObjectManager.Player.CountEnemyHeroesInRange(1100) > 0) { Q.CastIfWillHit(TargetSelector.GetTarget(900, DamageType.Physical), 2); var goodQTarget = ValidTargets.FirstOrDefault( t => t.Distance(ObjectManager.Player) < 950 && t.Health < Q.GetDamage(t) || SquishyTargets.Contains(t.CharData.BaseSkinName)); if (goodQTarget != null) { var pred = Prediction.GetPrediction(goodQTarget, Q); if ((int)pred.Item1 > (int)HitChance.Medium) { Q.Cast(pred.Item2); } } } } if (Orbwalker.ActiveMode != OrbwalkingMode.None && Orbwalker.ActiveMode != OrbwalkingMode.Combo && ObjectManager.Player.CountEnemyHeroesInRange(850) == 0) { var qHarassMode = QHarassMode.SelectedValue; if (qHarassMode != "DISABLED") { var qTarget = TargetSelector.GetTarget(1100, DamageType.Physical); if (qTarget != null) { var pred = Prediction.GetPrediction(qTarget, Q); if ((int)pred.Item1 > (int)HitChance.Medium) { if (qHarassMode == "ALLOWMINIONS") { Q.Cast(pred.Item2); } else if (pred.Item3.Count == 0) { Q.Cast(pred.Item2); } } } } } } void WLogic() { var goodTarget = ValidTargets.FirstOrDefault( e => !e.IsDead && e.HasBuffOfType(BuffType.Knockup) || e.HasBuffOfType(BuffType.Snare) || e.HasBuffOfType(BuffType.Stun) || e.HasBuffOfType(BuffType.Suppression) || e.IsCharmed || e.IsCastingInterruptableSpell() || !e.CanMove); if (goodTarget != null) { var pos = goodTarget.ServerPosition; if (!GameObjects.AllyMinions.Any(m => !m.IsDead && m.CharData.BaseSkinName.Contains("trap") && m.Distance(goodTarget.ServerPosition) < 100) && pos.Distance(ObjectManager.Player.ServerPosition) < 820) { W.Cast(goodTarget.ServerPosition); } } foreach (var enemyMinion in ObjectManager.Get<Obj_AI_Base>() .Where( m => m.IsEnemy && m.ServerPosition.Distance(ObjectManager.Player.ServerPosition) < W.Range && m.HasBuff("teleport_target"))) { W.Cast(enemyMinion.ServerPosition); } foreach (var hero in GameObjects.EnemyHeroes.Where(h => h.Distance(ObjectManager.Player) < W.Range)) { var pred = Prediction.GetPrediction(hero, W); if (!GameObjects.AllyMinions.Any(m => !m.IsDead && m.CharData.BaseSkinName.Contains("trap") && m.Distance(pred.Item2) < 100) && (int)pred.Item1 > (int)HitChance.Medium) { W.Cast(pred.Item2); } } } void RLogic() { if (UseRCombo.Active && R.IsReady() && ObjectManager.Player.CountEnemyHeroesInRange(900) == 0) { foreach (var rTarget in ValidTargets.Where( e => SquishyTargets.Contains(e.CharData.BaseSkinName) && R.GetDamage(e) > 0.1 * e.MaxHealth || R.GetDamage(e) > e.Health)) { if (rTarget.Distance(ObjectManager.Player) > 1400) { var pred = Prediction.GetPrediction(rTarget, R); if (!pred.Item3.Any(obj => obj is AIHeroClient)) { R.CastOnUnit(rTarget); } break; } R.CastOnUnit(rTarget); } } } #endregion private bool HasPassive => ObjectManager.Player.HasBuff("caitlynheadshot"); private string[] SquishyTargets = { "Ahri", "Anivia", "Annie", "Ashe", "Azir", "Brand", "Caitlyn", "Cassiopeia", "Corki", "Draven", "Ezreal", "Graves", "Jinx", "Kalista", "Karma", "Karthus", "Katarina", "Kennen", "KogMaw", "Kindred", "Leblanc", "Lucian", "Lux", "MissFortune", "Orianna", "Quinn", "Sivir", "Syndra", "Talon", "Teemo", "Tristana", "TwistedFate", "Twitch", "Varus", "Vayne", "Veigar", "Velkoz", "Viktor", "Xerath", "Zed", "Ziggs", "Jhin", "Soraka" }; } }
saophaisau/port
Core/SDK Ports/ChallengerSeriesAIO/Plugins/Teemo.cs
C#
gpl-3.0
12,392
package ca.pfv.spmf.test; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.AlgoSPAM_AGP; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.creators.AbstractionCreator; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.creators.AbstractionCreator_Qualitative; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.dataStructures.database.SequenceDatabase; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.idLists.creators.IdListCreator; import ca.pfv.spmf.algorithms.sequentialpatterns.spade_spam_AGP.idLists.creators.IdListCreator_FatBitmap; /** * Example of how to use the algorithm SPAM, saving the results in the * main memory * * @author agomariz */ public class MainTestSPAM_AGP_FatBitMap_saveToMemory { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { // Load a sequence database double support = 0.5; boolean keepPatterns = true; boolean verbose = false; // if you set the following parameter to true, the sequence ids of the sequences where // each pattern appears will be shown in the result boolean outputSequenceIdentifiers = false; AbstractionCreator abstractionCreator = AbstractionCreator_Qualitative.getInstance(); IdListCreator idListCreator = IdListCreator_FatBitmap.getInstance(); SequenceDatabase sequenceDatabase = new SequenceDatabase(abstractionCreator, idListCreator); sequenceDatabase.loadFile(fileToPath("contextPrefixSpan.txt"), support); System.out.println(sequenceDatabase.toString()); AlgoSPAM_AGP algorithm = new AlgoSPAM_AGP(support); algorithm.runAlgorithm(sequenceDatabase, keepPatterns, verbose, null,outputSequenceIdentifiers); System.out.println("Minimum support (relative) = "+support); System.out.println(algorithm.getNumberOfFrequentPatterns() + " frequent patterns."); System.out.println(algorithm.printStatistics()); } public static String fileToPath(String filename) throws UnsupportedEncodingException { URL url = MainTestSPADE_AGP_FatBitMap_saveToFile.class.getResource(filename); return java.net.URLDecoder.decode(url.getPath(), "UTF-8"); } }
ArneBinder/LanguageAnalyzer
src/main/java/ca/pfv/spmf/test/MainTestSPAM_AGP_FatBitMap_saveToMemory.java
Java
gpl-3.0
2,453
using System; using System.Collections.Generic; using System.Linq; using System.Text; using WiimoteLib; namespace WiiApi { /// <summary> /// Klasa koriscena za prikaz polozaja i orijentacije glave u prostoru. Sadrzi samo metode za dobavljanje informacija. /// </summary> public class PolozajGlave { /// <summary> /// Plozaj glave u milimetrima, vrednost je validna za pracenje 2 i 3 izvora. /// </summary> private Point3F polozaj; /// <summary> /// Vektor koji pokazuje na gore. Odredjuje rotaciju oko z ose. Vrednost je validna samo ako se prate 3 izvora. /// </summary> private Point3F goreVektor; /// <summary> /// Pravac pogleda. Odredjuje rotaciju oko x i y osa. Vrednost je validna samo ako se prate 3 izvora. /// </summary> private Point3F pogledVektor; /// <summary> /// Indikacija da li su uspesno locirani svi izvori prilikom obrade poslednjeg dogadjaja. Ako je vrednost false podaci nisu validni. /// </summary> private bool uspesno; /// <summary> /// Konstruktor koji se koristi za postavljanje vrednosti prilikom pracenja 2 izvora /// </summary> /// <param name="uspesno">Indikacija da li su uspesno locirani svi izvori prilikom obrade poslednjeg dogadjaja.</param> /// <param name="polozaj">Polozaj glave u milimetrima. </param> public PolozajGlave(bool uspesno, Point3F polozaj) { this.uspesno = uspesno; this.polozaj = polozaj; } /// <summary> /// Konstruktor koji se koristi za postavljanje vrednosti prilikom pracenja 3 izvora /// </summary> /// <param name="uspesno">Indikacija da li su uspesno locirani svi izvori prilikom obrade poslednjeg dogadjaja.</param> /// <param name="polozaj">Polozaj glave u milimetrima. </param> /// <param name="goreVektor">Vektor na gore. </param> /// /// <param name="pogledVektor">Pravac pogleda. </param> public PolozajGlave(bool uspesno, Point3F polozaj, Point3F goreVektor, Point3F pogledVektor) { this.uspesno = uspesno; this.polozaj = polozaj; this.goreVektor = goreVektor; this.pogledVektor = pogledVektor; } /// <summary> /// Indikacija da li su uspesno locirani svi izvori prilikom obrade poslednjeg dogadjaja. Ako je vrednost false podaci nisu validni. /// </summary> public bool Uspesno { get { return uspesno; } } /// <summary> /// Plozaj glave u milimetrima, vrednost je validna za pracenje 2 i 3 izvora. /// </summary> public Point3F Polozaj { get { return polozaj; } } /// <summary> /// Vektor koji pokazuje na gore. Odredjuje rotaciju oko z ose. Vrednost je validna samo ako se prate 3 izvora. /// </summary> public Point3F GoreVektor { get { return goreVektor; } } /// <summary> /// Pravac pogleda. Odredjuje rotaciju oko x i y osa. Vrednost je validna samo ako se prate 3 izvora. /// </summary> public Point3F PogledVektor { get { return pogledVektor; } } } }
ljsimin/gimii
WiiApi/WiiApi/PolozajGlave.cs
C#
gpl-3.0
3,610
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; namespace Hatfield.EnviroData.DataAcquisition.XML { public class XMLDataSourceLocation: IDataSourceLocation { public string _elementName; public string _attributeName; public int _index = 0; public XMLDataSourceLocation(string elementName, string attributeName) { _elementName = elementName; _attributeName = attributeName; } public XMLDataSourceLocation(string elementName, string attributeName, int index) { _elementName = elementName; _attributeName = attributeName; _index = index; } public string AttributeName { get { return _attributeName; } } public string ElementName { get { return _elementName; } } public int Index { get { return _index; } } public override string ToString() { return string.Format("Node: {0}, {1}", _elementName, _attributeName); } } }
HatfieldConsultants/Hatfield.EnviroData.DataAcquisition
Source/Hatfield.EnviroData.DataAcquisition.XML/XMLDataSourceLocation.cs
C#
mpl-2.0
1,295
using System; namespace ACE.Server.Network.GameAction.Actions { public static class GameActionUseItem { [GameAction(GameActionType.Use)] public static void Handle(ClientMessage message, Session session) { uint itemGuid = message.Payload.ReadUInt32(); //Console.WriteLine($"{session.Player.Name}.GameAction 0x36 - Use({itemGuid:X8})"); session.Player.HandleActionUseItem(itemGuid); } } }
LtRipley36706/ACE
Source/ACE.Server/Network/GameAction/Actions/GameActionUseItem.cs
C#
agpl-3.0
470
define([ 'database', 'backbone' ], function (DB, Backbone) { var MessageModel = Backbone.Model.extend({ defaults: { messageId: 0, sender: '', title: '', content: '', hasAttachment: false, sendDate: new Date(), url: '' }, save: function (attributes) { var deferred = $.Deferred(); var self = this; var transaction = DB.conx.transaction([ DB.TABLE_MESSAGE ], 'readwrite'); var store = transaction.objectStore(DB.TABLE_MESSAGE); var request; if (!attributes) { request = store.add(this.toJSON()); } else { self.set(attributes); request = store.put(this.toJSON(), this.cid); } request.onsuccess = function (e) { if (!attributes) { self.cid = e.target.result; } deferred.resolve(); }; request.onerror = function () { deferred.reject(); }; return deferred.promise(); }, getData: function (cid) { var self = this; var deferred = $.Deferred(); var transaction = DB.conx.transaction([ DB.TABLE_MESSAGE ]); var store = transaction.objectStore(DB.TABLE_MESSAGE); var request = store.get(cid); request.onsuccess = function (e) { if (request.result) { var data = request.result; self.cid = cid; self.set(data); deferred.resolve(); } else { deferred.reject(); } }; request.onerror = function () { deferred.reject(); }; return deferred.promise(); }, getNext: function (currentKey) { var deferred = $.Deferred(); var range = IDBKeyRange.lowerBound(this.get('messageId'), true); var transaction = DB.conx.transaction([ DB.TABLE_MESSAGE ], 'readonly'); var store = transaction.objectStore(DB.TABLE_MESSAGE); var index = store.index('messageId'); var request = index.openCursor(range); request.onsuccess = function (e) { var nextMessage = null; var cursor = e.target.result; if (cursor) { nextMessage = new MessageModel(cursor.value); nextMessage.cid = cursor.primaryKey; } deferred.resolve(nextMessage); }; request.onerror = function () { deferred.reject(); }; return deferred.promise(); }, getPrevious: function () { var deferred = $.Deferred(); var range = IDBKeyRange.upperBound(this.get('messageId'), true); var transaction = DB.conx.transaction([ DB.TABLE_MESSAGE ], 'readonly'); var store = transaction.objectStore(DB.TABLE_MESSAGE); var index = store.index('messageId'); var request = index.openCursor(range, 'prev'); request.onsuccess = function (e) { var previousMessage = null; var cursor = e.target.result; if (cursor) { previousMessage = new MessageModel(cursor.value); previousMessage.cid = cursor.primaryKey; } deferred.resolve(previousMessage); }; request.onerror = function () { deferred.reject(); }; return deferred.promise(); }, delete: function () { var deferred = $.Deferred(); var transaction = DB.conx.transaction([ DB.TABLE_MESSAGE ], 'readwrite'); var store = transaction.objectStore(DB.TABLE_MESSAGE); var request = store.clear(); request.onsuccess = function () { deferred.resolve(); }; request.onerror = function () { deferred.reject(); }; return deferred.promise(); } }); return MessageModel; });
sanyaade-teachings/mobile-messaging
www/js/models/message.js
JavaScript
agpl-3.0
4,522
/* * sones GraphDB - Community Edition - http://www.sones.com * Copyright (C) 2007-2011 sones GmbH * * This file is part of sones GraphDB Community Edition. * * sones GraphDB 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, version 3 of the License. * * sones GraphDB 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 sones GraphDB. If not, see <http://www.gnu.org/licenses/>. * */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IdentityModel.Selectors; using sones.GraphDSServer; using System.IdentityModel.Tokens; using System.Diagnostics; using sones.GraphDB; using sones.Library.VersionedPluginManager; using sones.GraphDS.PluginManager; using sones.Library.Commons.Security; using System.Net; using System.Threading; using sones.GraphDB.Manager.Plugin; using System.IO; using System.Globalization; using sones.Library.DiscordianDate; using System.Security.AccessControl; using sones.GraphDSServer.ErrorHandling; using sones.GraphDS.GraphDSRemoteClient; using sones.GraphDS.GraphDSRESTClient; using sones.GraphDB.TypeSystem; using sones.GraphDB.Request; using sones.Library.PropertyHyperGraph; using sones.GraphQL.Result; using sones.Library.Network.HttpServer; namespace TagExampleWithGraphMappingFramework { public class TagExampleWithGraphMappingFramework { #region sones GraphDB Startup private bool quiet = false; private bool shutdown = false; private IGraphDSServer _dsServer; private bool _ctrlCPressed; private IGraphDSClient GraphDSClient; private sones.Library.Commons.Security.SecurityToken SecToken; private long TransToken; public TagExampleWithGraphMappingFramework(String[] myArgs) { Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("en-us"); if (myArgs.Count() > 0) { foreach (String parameter in myArgs) { if (parameter.ToUpper() == "--Q") quiet = true; } } #region Start RemoteAPI, WebDAV and WebAdmin services, send GraphDS notification IGraphDB GraphDB; GraphDB = new SonesGraphDB(null, true, new CultureInfo("en-us")); #region Configure PlugIns // Plugins are loaded by the GraphDS with their according PluginDefinition and only if they are listed // below - there is no auto-discovery for plugin types in GraphDS (!) #region Query Languages // the GQL Query Language Plugin needs the GraphDB instance as a parameter List<PluginDefinition> QueryLanguages = new List<PluginDefinition>(); Dictionary<string, object> GQL_Parameters = new Dictionary<string, object>(); GQL_Parameters.Add("GraphDB", GraphDB); QueryLanguages.Add(new PluginDefinition("sones.gql", GQL_Parameters)); #endregion #region GraphDS Service Plugins List<PluginDefinition> GraphDSServices = new List<PluginDefinition>(); #endregion List<PluginDefinition> UsageDataCollector = new List<PluginDefinition>(); #endregion GraphDSPlugins PluginsAndParameters = new GraphDSPlugins(QueryLanguages); _dsServer = new GraphDS_Server(GraphDB, PluginsAndParameters); #region Start GraphDS Services #region Remote API Service Dictionary<string, object> RemoteAPIParameter = new Dictionary<string, object>(); RemoteAPIParameter.Add("IPAddress", IPAddress.Parse("127.0.0.1")); RemoteAPIParameter.Add("Port", (ushort)9970); _dsServer.StartService("sones.RemoteAPIService", RemoteAPIParameter); #endregion #endregion #endregion #endregion #region Some helping lines... if (!quiet) { Console.WriteLine("This GraphDB Instance offers the following options:"); Console.WriteLine(" * If you want to suppress console output add --Q as a"); Console.WriteLine(" parameter."); Console.WriteLine(); Console.WriteLine(" * the following GraphDS Service Plugins are initialized and started: "); foreach (var Service in _dsServer.AvailableServices) { Console.WriteLine(" * " + Service.PluginName); } Console.WriteLine(); foreach (var Service in _dsServer.AvailableServices) { Console.WriteLine(Service.ServiceDescription); Console.WriteLine(); } Console.WriteLine("Enter 'shutdown' to initiate the shutdown of this instance."); } Run(); Console.CancelKeyPress += OnCancelKeyPress; while (!shutdown) { String command = Console.ReadLine(); if (!_ctrlCPressed) { if (command != null) { if (command.ToUpper() == "SHUTDOWN") shutdown = true; } } } Console.WriteLine("Shutting down GraphDS Server"); _dsServer.Shutdown(null); Console.WriteLine("Shutdown complete"); #endregion } #region Cancel KeyPress /// <summary> /// Cancel KeyPress /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public virtual void OnCancelKeyPress(object sender, ConsoleCancelEventArgs e) { e.Cancel = true; //do not abort Console here. _ctrlCPressed = true; Console.Write("Shutdown GraphDB (y/n)?"); string input; do { input = Console.ReadLine(); } while (input == null); switch (input.ToUpper()) { case "Y": shutdown = true; return; default: shutdown = false; return; } }//method #endregion #region the actual example public void Run() { GraphDSClient = new GraphDS_RemoteClient(new Uri("http://localhost:9970/rpc")); SecToken = GraphDSClient.LogOn(new RemoteUserPasswordCredentials("test", "test")); TransToken = GraphDSClient.BeginTransaction(SecToken); GraphDSClient.Clear<IRequestStatistics>(SecToken, TransToken, new RequestClear(), (Statistics, DeletedTypes) => Statistics); #region create types, create instances and additional work using the GraphDB API GraphDSClient.Clear<IRequestStatistics>(SecToken, TransToken, new RequestClear(), (Statistics, DeletedTypes) => Statistics); Console.WriteLine("Press enter to start example"); Console.ReadLine(); GraphDBRequests(); #endregion //clear the DB (delete all created types) to create them again using the QueryLanguage GraphDSClient.Clear<IRequestStatistics>(SecToken, TransToken, new RequestClear(), (Statistics, DeletedTypes) => Statistics); #region create some types and insert values using the SonesQueryLanguage GraphQLQueries(); #endregion #region make some SELECTS SELECTS(); #endregion Console.WriteLine(); Console.WriteLine("Finished Example. Type a key to finish!"); Console.ReadKey(); } private void GraphDBRequests() { Console.WriteLine("performing DB requests..."); #region define type "Tag" //create a VertexTypePredefinition var Tag_VertexTypePredefinition = new VertexTypePredefinition("Tag"); //create property var PropertyName = new PropertyPredefinition("Name", "String") .SetComment("This is a property on type 'Tag' named 'Name' and is of type 'String'"); //add property Tag_VertexTypePredefinition.AddProperty(PropertyName); //create outgoing edge to "Website" var OutgoingEdgesTaggedWebsites = new OutgoingEdgePredefinition("TaggedWebsites", "Website") .SetMultiplicityAsMultiEdge() .SetComment(@"This is an outgoing edge on type 'Tag' wich points to the type 'Website' (the AttributeType) and is defined as 'MultiEdge', which means that this edge can contain multiple single edges"); //add outgoing edge Tag_VertexTypePredefinition.AddOutgoingEdge(OutgoingEdgesTaggedWebsites); #endregion #region define type "Website" //create a VertexTypePredefinition var Website_VertexTypePredefinition = new VertexTypePredefinition("Website"); //create properties PropertyName = new PropertyPredefinition("Name", "String") .SetComment("This is a property on type 'Website' named 'Name' and is of type 'String'"); var PropertyUrl = new PropertyPredefinition("URL", "String") .SetAsMandatory(); //add properties Website_VertexTypePredefinition.AddProperty(PropertyName); Website_VertexTypePredefinition.AddProperty(PropertyUrl); #region create an index on type "Website" on property "Name" //there are three ways to set an index on property "Name" //Beware: Use just one of them! //1. create an index definition and specifie the property- and type name var MyIndex = new IndexPredefinition("MyIndex").SetIndexType("SonesIndex").AddProperty("Name").SetVertexType("Website"); //add index Website_VertexTypePredefinition.AddIndex((IndexPredefinition)MyIndex); //2. on creating the property definition of property "Name" call the SetAsIndexed() method, the GraphDB will create the index //PropertyName = new PropertyPredefinition("Name") // .SetAttributeType("String") // .SetComment("This is a property on type 'Website' with name 'Name' and is of type 'String'") // .SetAsIndexed(); //3. make a create index request, like creating a type //BEWARE: This statement must be execute AFTER the type "Website" is created. //var MyIndex = GraphDSServer.CreateIndex<IIndexDefinition>(SecToken, // TransToken, // new RequestCreateIndex( // new IndexPredefinition("MyIndex") // .SetIndexType("SonesIndex") // .AddProperty("Name") // .SetVertexType("Website")), (Statistics, Index) => Index); #endregion //add IncomingEdge "Tags", the related OutgoingEdge is "TaggedWebsites" on type "Tag" Website_VertexTypePredefinition.AddIncomingEdge(new IncomingEdgePredefinition("Tags", "Tag", "TaggedWebsites")); #endregion #region create types by sending requests //create the types "Tag" and "Website" var DBTypes = GraphDSClient.CreateVertexTypes<IEnumerable<IVertexType>>(SecToken, TransToken, new RequestCreateVertexTypes( new List<VertexTypePredefinition> { Tag_VertexTypePredefinition, Website_VertexTypePredefinition }), (Statistics, VertexTypes) => VertexTypes); /* * BEWARE: The following two operations won't work because the two types "Tag" and "Website" depending on each other, * because one type has an incoming edge to the other and the other one has an incoming edge, * so they cannot be created separate (by using create type), * they have to be created at the same time (by using create types) * * //create the type "Website" * var Website = GraphDSServer.CreateVertexType<IVertexType>(SecToken, * TransToken, * new RequestCreateVertexType(Website_VertexTypePredefinition), * (Statistics, VertexType) => VertexType); * * //create the type "Tag" * var Tag = GraphDSServer.CreateVertexType<IVertexType>(SecToken, * TransToken, * new RequestCreateVertexType(Tag_VertexTypePredefinition), * (Statistics, VertexType) => VertexType); */ var Tag = DBTypes.Where(type => type.Name == "Tag").FirstOrDefault(); if (Tag != null) Console.WriteLine("Vertex Type 'Tag' created"); var Website = DBTypes.Where(type => type.Name == "Website").FirstOrDefault(); if(Website != null) Console.WriteLine("Vertex Type 'Website' created"); #endregion #region insert some Websites by sending requests var sones = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website") .AddStructuredProperty("Name", "Sones") .AddStructuredProperty("URL", "http://sones.com/"), (Statistics, Result) => Result); var cnn = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website") .AddStructuredProperty("Name", "CNN") .AddStructuredProperty("URL", "http://cnn.com/"), (Statistics, Result) => Result); var xkcd = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website") .AddStructuredProperty("Name", "xkcd") .AddStructuredProperty("URL", "http://xkcd.com/"), (Statistics, Result) => Result); var onion = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website") .AddStructuredProperty("Name", "onion") .AddStructuredProperty("URL", "http://theonion.com/"), (Statistics, Result) => Result); //adding an unknown property means the property isn't defined before var test = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Website") .AddStructuredProperty("Name", "Test") .AddStructuredProperty("URL", "") .AddUnknownProperty("Unknown", "unknown property"), (Statistics, Result) => Result); if (sones != null) Console.WriteLine("Website 'sones' successfully inserted"); if (cnn != null) Console.WriteLine("Website 'cnn' successfully inserted"); if (xkcd != null) Console.WriteLine("Website 'xkcd' successfully inserted"); if (onion != null) Console.WriteLine("Website 'onion' successfully inserted"); if (test != null) Console.WriteLine("Website 'test' successfully inserted"); #endregion #region insert some Tags by sending requests //insert a "Tag" with an OutgoingEdge to a "Website" include that the GraphDB creates an IncomingEdge on the given Website instances //(because we created an IncomingEdge on type "Website") --> as a consequence we never have to set any IncomingEdge var good = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Tag") .AddStructuredProperty("Name", "good") .AddEdge(new EdgePredefinition("TaggedWebsites") .AddVertexID(Website.ID, cnn.VertexID) .AddVertexID(Website.ID, xkcd.VertexID)), (Statistics, Result) => Result); var funny = GraphDSClient.Insert<IVertex>(SecToken, TransToken, new RequestInsertVertex("Tag") .AddStructuredProperty("Name", "funny") .AddEdge(new EdgePredefinition("TaggedWebsites") .AddVertexID(Website.ID, xkcd.VertexID) .AddVertexID(Website.ID, onion.VertexID)), (Statistics, Result) => Result); if (good != null) Console.WriteLine("Tag 'good' successfully inserted"); if (funny != null) Console.WriteLine("Tag 'funny' successfully inserted"); #endregion #region how to get a type from the DB, properties of the type, instances of a specific type and read out property values //how to get a type from the DB var TagDBType = GraphDSClient.GetVertexType<IVertexType>(SecToken, TransToken, new RequestGetVertexType(Tag.Name), (Statistics, Type) => Type); //how to get a type from the DB var WebsiteDBType = GraphDSClient.GetVertexType<IVertexType>(SecToken, TransToken, new RequestGetVertexType(Website.Name), (Statistics, Type) => Type); //read informations from type var typeName = TagDBType.Name; //are there other types wich extend the type "Tag" var hasChildTypes = TagDBType.HasChildTypes; var hasPropName = TagDBType.HasProperty("Name"); //get the definition of the property "Name" var propName = TagDBType.GetPropertyDefinition("Name"); //how to get all instances of a type from the DB var TagInstances = GraphDSClient.GetVertices(SecToken, TransToken, new RequestGetVertices(TagDBType.Name), (Statistics, Vertices) => Vertices); foreach (var item in TagInstances) { //to get the value of a property of an instance, you need the property ID //(that's why we fetched the type from DB an read out the property definition of property "Name") var name = item.GetPropertyAsString(propName.ID); } Console.WriteLine("API operations finished..."); #endregion } #endregion #region Graph Query Language /// <summary> /// Describes how to send queries using the GraphQL. /// </summary> private void GraphQLQueries() { #region create types //create types at the same time, because of the circular dependencies (Tag has OutgoingEdge to Website, Website has IncomingEdge from Tag) //like shown before, using the GraphQL there are also three different ways to create create an index on property "Name" of type "Website" //1. create an index definition and specifie the property name and index type var Types = GraphDSClient.Query(SecToken, TransToken, @"CREATE VERTEX TYPES Tag ATTRIBUTES (String Name, SET<Website> TaggedWebsites), Website ATTRIBUTES (String Name, String URL) INCOMINGEDGES (Tag.TaggedWebsites Tags) INDICES (MyIndex INDEXTYPE SonesIndex ON ATTRIBUTES Name)", "sones.gql"); //2. on creating the type with the property "Name", just define the property "Name" under INDICES //var Types = GraphQL.Query(SecToken, TransToken, @"CREATE VERTEX TYPES Tag ATTRIBUTES (String Name, SET<Website> TaggedWebsites), // Website ATTRIBUTES (String Name, String URL) INCOMINGEDGES (Tag.TaggedWebsites Tags) INDICES (Name)"); //3. make a create index query //var Types = GraphQL.Query(SecToken, TransToken, @"CREATE VERTEX TYPES Tag ATTRIBUTES (String Name, SET<Website> TaggedWebsites), // Website ATTRIBUTES (String Name, String URL) INCOMINGEDGES (Tag.TaggedWebsites Tags)"); //var MyIndex = GraphQL.Query(SecToken, TransToken, "CREATE INDEX MyIndex ON VERTEX TYPE Website (Name) INDEXTYPE SonesIndex"); CheckResult(Types); #endregion #region create instances of type "Website" var cnnResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Website VALUES (Name = 'CNN', URL = 'http://cnn.com/')", "sones.gql"); CheckResult(cnnResult); var xkcdResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Website VALUES (Name = 'xkcd', URL = 'http://xkcd.com/')", "sones.gql"); CheckResult(xkcdResult); var onionResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Website VALUES (Name = 'onion', URL = 'http://theonion.com/')", "sones.gql"); CheckResult(onionResult); //adding an unknown property ("Unknown") means the property isn't defined before var unknown = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Website VALUES (Name = 'Test', URL = '', Unknown = 'unknown property')", "sones.gql"); CheckResult(onionResult); #endregion #region create instances of type "Tag" var goodResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Tag VALUES (Name = 'good', TaggedWebsites = SETOF(Name = 'CNN', Name = 'xkcd'))", "sones.gql"); CheckResult(goodResult); var funnyResult = GraphDSClient.Query(SecToken, TransToken, "INSERT INTO Tag VALUES (Name = 'funny', TaggedWebsites = SETOF(Name = 'xkcd', Name = 'onion'))", "sones.gql"); CheckResult(funnyResult); #endregion Console.WriteLine("GQL Queries finished..."); } /// <summary> /// Executes some select statements. /// </summary> private void SELECTS() { // find out which tags xkcd is tagged with var _xkcdtags = GraphDSClient.Query(SecToken, TransToken, "FROM Website w SELECT w.Tags WHERE w.Name = 'xkcd' DEPTH 1", "sones.gql"); CheckResult(_xkcdtags); foreach (var _tag in _xkcdtags.Vertices) foreach (var edge in _tag.GetHyperEdge("Tags").GetAllEdges()) Console.WriteLine(edge.GetTargetVertex().GetPropertyAsString("Name")); // List tagged sites names and the count of there tags var _taggedsites = GraphDSClient.Query(SecToken, TransToken, "FROM Website w SELECT w.Name, w.Tags.Count() AS Counter", "sones.gql"); CheckResult(_taggedsites); foreach (var _sites in _taggedsites.Vertices) Console.WriteLine("{0} => {1}", _sites.GetPropertyAsString("Name"), _sites.GetPropertyAsString("Counter")); // find out the URL's of the website of each Tag var _urls = GraphDSClient.Query(SecToken, TransToken, "FROM Tag t SELECT t.Name, t.TaggedWebsites.URL", "sones.gql"); CheckResult(_urls); foreach (var _tag in _urls.Vertices) foreach (var edge in _tag.GetHyperEdge("TaggedWebsites").GetAllEdges()) Console.WriteLine(_tag.GetPropertyAsString("Name") + " - " + edge.GetTargetVertex().GetPropertyAsString("URL")); Console.WriteLine("SELECT operations finished..."); } /// <summary> /// This private method analyses the QueryResult, shows the ResultType and Errors if existing. /// </summary> /// <param name="myQueryResult">The result of a query.</param> private bool CheckResult(IQueryResult myQueryResult) { if (myQueryResult.Error != null) { if (myQueryResult.Error.InnerException != null) Console.WriteLine(myQueryResult.Error.InnerException.Message); else Console.WriteLine(myQueryResult.Error.Message); return false; } else { Console.WriteLine("Query " + myQueryResult.TypeOfResult); return true; } } #endregion } public class sonesGraphDBStarter { static void Main(string[] args) { bool quiet = false; if (args.Count() > 0) { foreach (String parameter in args) { if (parameter.ToUpper() == "--Q") quiet = true; } } if (!quiet) { DiscordianDate ddate = new DiscordianDate(); Console.WriteLine("sones GraphDB version 2.0 - " + ddate.ToString()); Console.WriteLine("(C) sones GmbH 2007-2011 - http://www.sones.com"); Console.WriteLine("-----------------------------------------------"); Console.WriteLine(); Console.WriteLine("Starting up GraphDB..."); } try { var sonesGraphDBStartup = new TagExampleWithGraphMappingFramework(args); } catch (ServiceException e) { if (!quiet) { Console.WriteLine(e.Message); Console.WriteLine("InnerException: " + e.InnerException.ToString()); Console.WriteLine(); Console.WriteLine("Press <return> to exit."); Console.ReadLine(); } } } } }
sones/sones
Applications/TagExampleWithGraphMappingFramework/Example.cs
C#
agpl-3.0
29,686
/* * Copyright (c) 1996 Sun Microsystems, Inc. All Rights Reserved. * * Permission to use, copy, modify, and distribute this software * and its documentation for NON-COMMERCIAL purposes and without * fee is hereby granted provided that this copyright notice * appears in all copies. Please refer to the file "copyright.html" * for further important copyright and licensing information. * * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ package javax.telephony; import javax.telephony.capabilities.ConnectionCapabilities; /** * A <CODE>Connection</CODE> represents a link (i&#46e&#46 an association) between * a {@link Call} object and an {@link Address} object. * * <H4>Introduction</H4> * * The purpose of a Connection object is to describe * the relationship between a Call object and an Address object. A Connection * object exists if the Address is a part of the telephone call. Each * Connection has a <EM>state</EM> which describes the particular stage of the * relationship between the Call and Address. These states and their meanings * are described below. Applications use the <CODE>Connection.getCall()</CODE> * and <CODE>Connection.getAddress()</CODE> methods to obtain the Call and * Address associated with this Connection, respectively. * <p> * From one perspective, an application may view a Call only in terms of the * Address/Connection objects which are part of the Call. This is termed a * <EM>logical</EM> view of the Call because it ignores the details provided * by the Terminal and TerminalConnection objects which are also associated * with a Call. In many instances, simple applications (such as an * <EM>outcall</EM> program) may only need to concern itself with the logical * view. In this logical view, a telephone call is views as two or more * endpoint addresses in communication. The Connection object describes the * state of each of these endpoint addresses with respect to the Call. * * <H4>Calls and Addresses</H4> * * Connection objects are immutable in terms of their Call and Address * references. In other words, the Call and Address object references do * not change throughout the lifetime of the Connection object instance. The * same Connection object may not be used in another telephone call. The * existence of a Connection implies that its Address is associated with its * Call in the manner described by the Connection's state. * <p> * Although a Connection's Address and Call references remain valid throughout * the lifetime of the Connection object, the same is not true for the Call * and Address object's references to this Connection. Particularly, when a * Connection moves into the Connection.DISCONNECTED state, it is no longer * listed by the <CODE>Call.getConnections()</CODE> and * <CODE>Address.getConnections()</CODE> methods. Typically, when a Connection * moves into the <CODE>Connection.DISCONNECTED</CODE> state, the application * loses its references to it to facilitate its garbage collection. * * <H4>TerminalConnections</H4> * * Connections objects are containers for zero or more TerminalConnection * objects. Connection objects are containers for zero or more TerminalConnection * objects. Connection objects represent the relationship between the Call and * the Address, whereas TerminalConnection objects represent the relationship * between the Connection and the Terminal. The relationship between the Call and * the Address may be viewed as a logical view of the Call. The relationship * between a Connection and a Terminal represents the physical view of the * Call, i.e. at which Terminal the telephone calls terminates. The * TerminalConnection object specification provides further information. * * <H4>Connection States</H4> * * Below is a description of each Connection state in real-world terms. These * real-world descriptions have no bearing on the specifications of methods, * they only serve to provide a more intuitive understanding of what is going * on. Several methods in this specification state pre-conditions based upon * the state of the Connection. * <p> * <TABLE CELLPADDING=2> * * <TR> * <TD WIDTH="15%"><CODE>Connection.IDLE</CODE></TD> * <TD WIDTH="85%"> * This state is the initial state for all new Connections. Connections which * are in the <CODE>Connection.IDLE</CODE> state are not actively part of a * telephone call, yet their references to the Call and Address objects are * valid. Connections typically do not stay in the <CODE>Connection.IDLE</CODE> * state for long, quickly transitioning to other states. * </TD> * </TR> * * <TR> * <TD WIDTH="15%"><CODE>Connection.DISCONNECTED</CODE></TD> * <TD WIDTH="85%"> * This state implies it is no longer part of the telephone call, although its * references to Call and Address still remain valid. A Connection in this * state is interpreted as once previously belonging to this telephone call. * </TD> * </TR> * * <TR> * <TD WIDTH="15%"><CODE>Connection.INPROGRESS</CODE></TD> * <TD WIDTH="85%"> * This state implies that the Connection, which represents the destination * end of a telephone call, is in the process of contacting the destination * side. Under certain circumstances, the Connection may not progress beyond * this state. Extension packages elaborate further on this state in various * situations. * </TD> * </TR> * * <TR> * <TD WIDTH="15%"><CODE>Connection.ALERTING</CODE></TD> * <TD WIDTH="85%"> * This state implies that the Address is being notified of an incoming call. * </TD> * </TR> * * <TR> * <TD WIDTH="15%"><CODE>Connection.CONNECTED</CODE></TD> * <TD WIDTH="85%"> * This state implies that a Connection and its Address is actively part of a * telephone call. In common terms, two people talking to one another are * represented by two Connections in the <CODE>Connection.CONNECTED</CODE> * state. * </TD> * </TR> * * <TR> * <TD WIDTH="15%"><CODE>Connection.UNKNOWN</CODE></TD> * <TD WIDTH="85%"> * This state implies that the implementation is unable to determine the * current state of the Connection. Typically, methods are invalid on * Connections which are in this state. Connections may move in and out of the * <CODE>Connection.UNKNOWN</CODE> state at any time. * </TD> * </TR> * * <TR> * <TD WIDTH="15%"><CODE>Connection.FAILED</CODE></TD> * <TD WIDTH="85%"> * This state indicates that a Connection to that end of the call has failed * for some reason. One reason why a Connection would be in the * <CODE>Connection.FAILED</CODE> state is because the party was busy. * </TD> * </TR> * </TABLE> * * <H4>Connection State Transitions</H4> * * With these loose, real-world meanings in the back of one's mind, the * Connection class defines a finite-state diagram which describes the * allowable Connection state transitions. This finite-state diagram must be * guaranteed by the implementation. Each method which causes a change in * a Connection state must be consistent with this state diagram. This finite * state diagram is below: * <P> * Note there is a general left-to-right progression of the state transitions. * A Connection object may transition into and out of the * <CODE>Connection.UNKNOWN</CODE> state at any time (hence, the asterisk * qualifier next to its bidirectional transition arrow). * <p> * <IMG SRC="doc-files/core-connectionstates.gif" ALIGN="center"> * </P> * * <H4>The Connection.disconnect() Method</H4> * * The primary method supported on the core package's Connection interface is * the <CODE>Connection.disconnect()</CODE> method. This method drops an entire * Connection from a telephone call. The result of this method is to move the * Connection object into the <CODE>Connection.DISCONNECTED</CODE> state. See * the specification of the <CODE>Connection.disconnect()</CODE> method on * this page for more detailed information. * * <H4>Listeners and Events</H4> * * All events pertaining to the Connection object are reported via the * <CODE>CallListener</CODE> interface on the Call object associated with this * Connection. In the core package, events are reported to a CallListener when * a new Connection is created and whenever a Connection changes state. * Listeners are added to Call objects via the <CODE>Call.addCallListener()</CODE> * method and more indirectly via the <CODE>Address.addCallListener()</CODE> * and <CODE>Terminal.addCallListener()</CODE> methods. See the specifications * for the Call, Address, and Terminal interfaces for more information. * <p> * The following Connection-related events are defined in the core package. * Each of these events extend the <CODE>ConnectionEvent</CODE> interface (which, in * turn, extends the <CODE>CallEvent</CODE> interface). * <p> * <TABLE CELLPADDING=2> * <TR> * <TD WIDTH="20%"><CODE>ConnectionCreated</CODE></TD> * <TD WIDTH="80%"> * Indicates a new Connection has been created on a Call. * </TD> * * <TR> * <TD WIDTH="20%"><CODE>ConnectionInProgress</CODE></TD> * <TD WIDTH="80%"> * Indicates the Connection has moved into the * <CODE>Connection.INPROGRESS</CODE> state. * </TD> * </TR> * * <TR> * <TD WIDTH="20%"><CODE>ConnectionAlerting</CODE></TD> * <TD WIDTH="80%"> * Indicates the Connection has moved into the <CODE>Connection.ALERTING</CODE> * state. * </TD> * </TR> * * <TR> * <TD WIDTH="20%"><CODE>ConnectionConnected</CODE></TD> * <TD WIDTH="80%"> * Indicates the Connection has moved into the * <CODE>Connection.CONNECTED</CODE> state. * </TD> * </TR> * * <TR> * <TD WIDTH="20%"><CODE>ConnectionDisconnected</CODE></TD> * <TD WIDTH="80%"> * Indicates the Connection has moved into the * <CODE>Connection.DISCONNECTED</CODE> state. * </TD> * </TR> * * <TR> * <TD WIDTH="20%"><CODE>ConnectionFailed</CODE></TD> * <TD WIDTH="80%"> * Indicates the Connection has moved into the <CODE>Connection.FAILED</CODE> * state. * </TD> * </TR> * * <TR> * <TD WIDTH="20%"><CODE>ConnectionUnknown</CODE></TD> * <TD WIDTH="80%"> * Indicates the Connection has moved into the <CODE>Connection.UNKNOWN</CODE> * state. * </TD> * </TR> * </TABLE> * <p> * @see javax.telephony.ConnectionEvent * @see javax.telephony.ConnectionListener * @version 04/05/99 1.48 */ public interface Connection { /** * The <CODE>Connection&#46IDLE</CODE> state is the initial state for all new * Connections. Connections which are in the Connection.IDLE state are not * actively part of a telephone call, yet their references to the Call and * Address objects are valid. Connections typically do not stay in the * <CODE>Connection.IDLE</CODE> state for long, quickly transitioning to * other states. */ public static final int IDLE = 0x30; /** * The <CODE>Connection&#46INPROGRESS</CODE> state implies that the Connection, * which represents the destination end of a telephone call, is in the * process of contacting the destination side. Under certain circumstances, * the Connection may not progress beyond this state. Extension packages * elaborate further on this state in various situations. */ public static final int INPROGRESS = 0x31; /** * The <CODE>Connection&#46ALERTING</CODE> state implies that the Address is * being notified of an incoming call. */ public static final int ALERTING = 0x32; /** * The <CODE>Connection&#46CONNECTED</CODE> state implies that a Connection and * its Address is actively part of a telephone call. In common terms, two * people talking to one another are represented by two Connections in the * <CODE>Connection.CONNECTED</CODE> state. */ public static final int CONNECTED = 0x33; /** * The <CODE>Connection&#46DISCONNECTED</CODE> state implies it is no longer * part of the telephone call, although its references to Call and Address * still remain valid. A Connection in the * <CODE>Connection.DISCONNECTED</CODE> state is interpreted as once * previously belonging to this telephone call. */ public static final int DISCONNECTED = 0x34; /** * The <CODE>Connection&#46FAILED</CODE> state indicates that a Connection to * that end of the call has failed for some reason. One reason why a * Connection would be in the <CODE>Connection.FAILED</CODE> state is * because the party was busy. */ public static final int FAILED = 0x35; /** * The <CODE>Connection&#46UNKNOWN</CODE> state implies that the implementation * is unable to determine the current state of the Connection. Typically, * method are invalid on Connections which are in the * <CODE>Connection.UNKNOWN</CODE> state. Connections may move in and out of * this state at any time. */ public static final int UNKNOWN = 0x36; /** * Returns the current state of the Connection. The return value will * be one of states defined above. * <p> * @return The current state of the Connection. */ public int getState(); /** * Returns the Call object associated with this Connection. This Call * reference remains valid throughout the lifetime of the Connection object, * despite the state of the Connection object. This Call reference does not * change once the Connection object has been created. * <p> * @return The call object associated with this Connection. */ public Call getCall(); /** * Returns the Address object associated with this Connection. This Address * object reference remains valid throughout the lifetime of the Connection * object despite the state of the Connection object. This Address reference * does not change once the Connection object has been created. * <p> * @return The Address associated with this Connection. */ public Address getAddress(); /** * Returns an array of TerminalConnection objects associated with this * Connection. TerminalConnection objects represent the relationship between * a Connection and a specific Terminal endpoint. There may be zero * TerminalConnections associated with this Connection. In that case, this * method returns null. Connection objects lose their reference to a * TerminalConnection once the TerminalConnection moves into the * <CODE>TerminalConnection.DROPPED</CODE> state. * <p> * <B>Post-conditions:</B> * <OL> * <LI>Let TerminalConnection tc[] = this.getTerminalConnections() * <LI>tc == null or tc.length >= 1 * <LI>For all i, tc[i].getState() != TerminalConnection.DROPPED * </OL> * @return An array of TerminalConnection objects associated with this * Connection, null if there are no TerminalConnections. */ public TerminalConnection[] getTerminalConnections(); /** * Drops a Connection from an active telephone call. The Connection's Address * is no longer associated with the telephone call. This method does not * necessarily drop the entire telephone call, only the particular * Connection on the telephone call. This method provides the ability to * disconnect a specific party from a telephone call, which is especially * useful in telephone calls consisting of three or more parties. Invoking * this method may result in the entire telephone call being dropped, which * is a permitted outcome of this method. In that case, the appropriate * events are delivered to the application, indicating that more than just * a single Connection has been dropped from the telephone call. * * <H5>Allowable Connection States</H5> * * The Connection object must be in one of several states in order for * this method to be successfully invoked. These allowable states are: * <CODE>Connection.CONNECTED</CODE>, <CODE>Connection.ALERTING</CODE>, * <CODE>Connection.INPROGRESS</CODE>, or <CODE>Connection.FAILED</CODE>. If * the Connection is not in one of these allowable states when this method is * invoked, this method throws InvalidStateException. Having the Connection * in one of the allowable states does not guarantee a successful invocation * of this method. * * <H5>Method Return Conditions</H5> * * This method returns successfully only after the Connection has been * disconnected from the telephone call and has transitioned into the * <CODE>Connection.DISCONNECTED</CODE>. This method may return * unsuccessfully by throwing one of the exceptions listed below. Note that * this method waits (i.e. the invocating thread blocks) until either the * Connection is actually disconnected from the telephone call or an error * is detected and an exception thrown. Also, all of the TerminalConnections * associated with this Connection are moved into the * <CODE>TerminalConnection.DROPPED</CODE> state. As a result, they are no * longer reported via the Connection by the * <CODE>Connection.getTerminalConnections()</CODE> method. * <p> * As a result of this method returning successfully, one or more events * are delivered to the application. These events are listed below: * <p> * <OL> * <LI>A ConnectionDisconnected event for this Connection. * <LI>A TerminalConnectionDropped event for all TerminalConnections associated with * this Connection. * </OL> * * <H5>Dropping Additional Connections</H5> * * Additional Connections may be dropped indirectly as a result of this * method. For example, dropping the destination Connection of a two-party * Call may result in the entire telephone call being dropped. It is up to * the implementation to determine which Connections are dropped as a result * of this method. Implementations should not, however, drop additional * Connections if it does not reflect the natural response of the underlying * telephone hardware. * <p> * Dropping additional Connections implies that their TerminalConnections are * dropped as well. Also, if all of the Connections on a telephone call are * dropped as a result of this method, the Call will move into the * <CODE>Call.INVALID</CODE> state. The following lists additional events * which may be delivered to the application. * <p> * <OL> * <LI>ConnectionDisconnected/TerminalConnectionDropped are delivered for all other * Connections and TerminalConnections dropped indirectly as a result of * this method. * <LI>CallInvalid if all of the Connections are dropped indirectly as a * result of this method. * </OL> * <p> * <B>Pre-conditions:</B> * <OL> * <LI>((this.getCall()).getProvider()).getState() == Provider.IN_SERVICE * <LI>this.getState() == Connection.CONNECTED or Connection.ALERTING * or Connection.INPROGRESS or Connection.FAILED * <LI>Let TerminalConnection tc[] = this.getTerminalConnections (see post- * conditions) * </OL> * <B>Post-conditions:</B> * <OL> * <LI>((this.getCall()).getProvider()).getState() == Provider.IN_SERVICE * <LI>this.getState() == Connection.DISCONNECTED * <LI>For all i, tc[i].getState() == TerminalConnection.DROPPED * <LI>this.getTerminalConnections() == null. * <LI>this is not an element of (this.getCall()).getConnections() * <LI>ConnectionDisconnected is delivered for this Connection. * <LI>TerminalConnectionDropped is delivered for all TerminalConnections associated * with this Connection. * <LI>ConnectionDisconnected/TerminalConnectionDropped are delivered for all other * Connections and TerminalConnections dropped indirectly as a result of * this method. * <LI>CallInvalid if all of the Connections are dropped indirectly as a * result of this method. * </OL> * <p> * @see javax.telephony.ConnectionListener * @see javax.telephony.ConnectionEvent * @exception PrivilegeViolationException The application does not have * the authority or permission to disconnected the Connection. For example, * the Address associated with this Connection may not be controllable in * the Provider's domain. * @exception ResourceUnavailableException An internal resource required * to drop a connection is not available. * @exception MethodNotSupportedException This method is not supported by * the implementation. * @exception InvalidStateException Some object required for the successful * invocation of this method is not in the proper state as given by this * method's pre-conditions. For example, the Provider may not be in the * Provider.IN_SERVICE state or the Connection may not be in one of the * allowable states. */ public void disconnect() throws PrivilegeViolationException, ResourceUnavailableException, MethodNotSupportedException, InvalidStateException; /** * Returns the dynamic capabilities for the instance of the Connection * object. Dynamic capabilities tell the application which actions are * possible at the time this method is invoked based upon the implementations * knowledge of its ability to successfully perform the action. This * determination may be based upon the current state of the call model * or some implementation-specific knowledge. These indications do not * guarantee that a particular method can be successfully invoked, however. * <p> * The dynamic Connection capabilities require no additional arguments. * <p> * @return The dynamic Connection capabilities. */ public ConnectionCapabilities getCapabilities(); /** * Gets the ConnectionCapabilities object with respect to a Terminal and * an Address. If null is passed as a Terminal parameter, the general/ * provider-wide Connection capabilities are returned. * <p> * <STRONG>Note:</STRONG> This method has been replaced in JTAPI v1.2. The * <CODE>Connection.getCapabilities()</CODE> method returns the dynamic * Connection capabilities. This method now should simply invoke the * <CODE>Connection.getCapabilities()</CODE> method. * <p> * @deprecated Since JTAPI v1.2. This method has been replaced by the * Connection.getCapabilities() method. * @param terminal This argument is ignored in JTAPI v1.2 and later. * @param address This argument is ignored in JTAPI v1.2 and later. * @exception InvalidArgumentException This exception is never thrown in * JTAPI v1.2 and later. * @exception PlatformException A platform-specific exception occurred. * @return The dynamic ConnectionCapabilities capabilities. */ public ConnectionCapabilities getConnectionCapabilities(Terminal terminal, Address address) throws InvalidArgumentException, PlatformException; }
kerr-huang/openss7
src/java/javax/telephony/Connection.java
Java
agpl-3.0
22,953
/* * Copyright (c) 2018. Wise Wild Web * * This File is part of Caipi and under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License * Full license at https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode * * @author : Nathanael Braun * @contact : caipilabs@gmail.com */ var cfg = require('$super'), p = (APP_PORT != 80) ? (":" + APP_PORT) : "", domain = (__LOCAL__ ? 'mamasound.fr.local' + p : 'mamasound.fr' + p), url = cfg.wwwDomain ? 'www.' + domain : domain; export default { ...require('$super'), PROJECT_NAME : "www.mamasound.fr", PUBLIC_URL : url, ROOT_DOMAIN : domain, API_URL : 'api.' + domain, UPLOAD_URL : 'upload.' + domain, STATIC_URL : 'static.' + domain, STATIC_REDIRECT_URL: __LOCAL__ && 'static.mamasound.fr', OSM_URL: "http://{s}.tile.osm.org/{z}/{x}/{y}.png", DB_URL : "mongodb://localhost:27017/www_mamasound_fr", UPLOAD_DIR : "./uploads/", CACHE_TM : 1000 * 60 * 2, SESSION_CHECK_TM: 1000 * 60 * 1, defaultRootMenuId: "Menu.HyInIUM8.html", htmlRefs: [ { "type": "script", "src" : "https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyA7XcGxipnIMdSSBJHn3tzeJe-fU3ilCak" }, ...(cfg.htmlRefs || []) ] };
nathb2b/mamasound.fr
App/config.js
JavaScript
agpl-3.0
1,324
## Note: you must install Levenshtein module # pip install python-Levenshtein # for this Microsoft Visual C++ 9.0 is required. Get it from http://aka.ms/vcpython27 # more info - see: http://stackoverflow.com/questions/18134437/where-can-the-documentation-for-python-levenshtein-be-found-online from pymongo import MongoClient import pymongo import pprint import bson import pandas import Levenshtein EXPECTED_STREET_PATTERN = \ u"^.*(?<![Ss]tra\u00dfe)(?<![Ww]eg)(?<![Aa]llee)(?<![Rr]ing)(?<![Bb]erg)" + \ u"(?<![Pp]ark)(?<![Hh]\u00f6he)(?<![Pp]latz)(?<![Bb]r\u00fccke)(?<![Gg]rund)$" def audit_streets(collection): return list(collection.distinct("name", { "type": "way", "name": {"$regex": EXPECTED_STREET_PATTERN} })) def audit_buildings(db): result = db.eval(''' db.osmnodes.ensureIndex({pos:"2dsphere"}); result = []; db.osmnodes.find( {"building": {"$exists": true}, "address.street": {"$exists": true}, "pos": {"$exists": true}}, {"address.street": "", "pos": ""} ).forEach(function(val, idx) { val.nearby = db.osmnodes.distinct("address.street", {"_id": {"$ne": val._id}, "pos": {"$near": {"$geometry": {"type": "Point", "coordinates": val.pos}, "$maxDistance": 50, "$minDistance": 0}}} ); result.push(val); }) return result; ''') df_list = [] for row in result: street_name = row["address"]["street"] nb_best_dist = None nb_best = "" nb_worst_dist = None nb_worst = "" for nearby_street in row["nearby"]: d = Levenshtein.distance(nearby_street, street_name) if nb_best_dist == None or d < nb_best_dist: nb_best_dist = d nb_best = nearby_street if nb_worst_dist == None or d > nb_worst_dist: nb_worst_dist = d nb_worst = nearby_street df_list += [{ "_id": row["_id"], "street_name": street_name, "num_nearby": len(row["nearby"]), "nb_best": nb_best, "nb_worst": nb_worst, "nb_best_dist": nb_best_dist, "nb_worst_dist": nb_worst_dist }] return pandas.DataFrame(df_list, columns=["_id", "street_name", "num_nearby", "nb_best", "nb_best_dist", "nb_worst", "nb_worst_dist"]) def audit_phone_numbers(collection): return list(collection.aggregate([ {"$match": {"$or": [ {"phone": {"$exists": True}}, {"mobile_phone": {"$exists": True}}, {"address.phone": {"$exists": True}} ]}}, {"$project": { "_id": 1, "phone": {"$ifNull": ["$phone", {"$ifNull": ["$mobile_phone", "$address.phone"]}]} }} ])) def audit_quality_map(mongoServer, mongoPort, csvFilePattern, csvEncoding): client = MongoClient(mongoServer + ":" + mongoPort) db = client.udacity c = client.udacity.osmnodes print print "Auditing way descriptions..." print "These are the 'unusual' street names" r = audit_streets(c) pprint.pprint(r) print print "Auditing streets close to buildings..." r = audit_buildings(db) r.to_csv(csvFilePattern.format("audit_buildings.csv"), encoding=csvEncoding) pprint.pprint(r) print print "Auditing phone numbers..." r = audit_phone_numbers(c) pprint.pprint(r)
benjaminsoellner/2015_Data_Analyst_Project_3
Project/audit_quality_map.py
Python
agpl-3.0
3,625
<?php class Cloudsponge_Integration { var $enabled; var $key; /** * PHP 5 Constructor * * @package Invite Anyone * @since 0.8 */ function __construct() { if ( empty( $options ) ) $options = get_option( 'invite_anyone' ); $this->enabled = !empty( $options['cloudsponge_enabled'] ) ? $options['cloudsponge_enabled'] : false; $this->key = !empty( $options['cloudsponge_key'] ) ? $options['cloudsponge_key'] : false; if ( $this->enabled && $this->key ) { define( 'INVITE_ANYONE_CS_ENABLED', true ); add_action( 'invite_anyone_after_addresses', array( $this, 'import_markup' ) ); add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_script' ) ); } } /** * Registers and loads CS JS. * * @package Invite Anyone * @since 0.8.8 */ function enqueue_script() { wp_register_script( 'ia_cloudsponge_address_books', 'https://api.cloudsponge.com/address_books.js', array(), false, true ); wp_register_script( 'ia_cloudsponge', WP_PLUGIN_URL . '/invite-anyone/by-email/cloudsponge-js.js', array( 'ia_cloudsponge_address_books' ), false, true ); // The domain key must be printed as a javascript object so it's accessible to the // script $strings = array( 'domain_key' => $this->key ); if ( $locale = apply_filters( 'ia_cloudsponge_locale', '' ) ) { $strings['locale'] = $locale; } if ( $stylesheet = apply_filters( 'ia_cloudsponge_stylesheet', '' ) ) { $strings['stylesheet'] = $stylesheet; } wp_localize_script( 'ia_cloudsponge', 'ia_cloudsponge', $strings ); } /** * Inserts the Cloudsponge markup into the Send Invites front end page. * * Also responsible for enqueuing the necessary assets. * * @package Invite Anyone * @since 0.8 * * @param array $options Invite Anyone settings. Check em so we can bail if necessary */ function import_markup( $options = false ) { wp_enqueue_script( 'ia_cloudsponge' ); ?> <input type="hidden" id="cloudsponge-emails" name="cloudsponge-emails" value="" /> <?php _e( 'You can also add email addresses <a class="cs_import">from your Address Book</a>.', 'invite-anyone' ) ?> <?php } } $cloudsponge_integration = new Cloudsponge_Integration;
empirical-org/Empirical-Wordpress
wp-content/plugins/invite-anyone/by-email/cloudsponge-integration.php
PHP
agpl-3.0
2,189
package rocks.inspectit.ui.rcp.repository.service.cmr.proxy; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.framework.ReflectiveMethodInvocation; import com.google.common.base.Defaults; import rocks.inspectit.ui.rcp.repository.CmrRepositoryDefinition; import rocks.inspectit.ui.rcp.repository.service.cmr.ICmrService; /** * Utilities that will be used in interceptors. * * @author Ivan Senic * */ public final class InterceptorUtils { /** * Private constructor. */ private InterceptorUtils() { } /** * Is service method. * * @param methodInvocation * Method invocation. * @return Return if it is service method. */ public static boolean isServiceMethod(MethodInvocation methodInvocation) { return !methodInvocation.getMethod().getDeclaringClass().equals(ICmrService.class); } /** * Checks if the method being executed is executed on the proxy containing {@link ICmrService} * and service defines the default value on error value. * * @param methodInvocation * Method invocation. * @return <code>true</code> if {@link ICmrService} objects defines return default on error */ public static boolean isReturnDefaultReturnValue(MethodInvocation methodInvocation) { ICmrService cmrService = getCmrService(methodInvocation); return (null != cmrService) && cmrService.isDefaultValueOnError(); } /** * Tries to get the {@link CmrRepositoryDefinition} from the proxied {@link ICmrService} object. * * @param methodInvocation * {@link MethodInvocation}. * @return CMR invoked or null. */ public static CmrRepositoryDefinition getRepositoryDefinition(MethodInvocation methodInvocation) { ICmrService cmrService = getCmrService(methodInvocation); if (null != cmrService) { CmrRepositoryDefinition cmrRepositoryDefinition = cmrService.getCmrRepositoryDefinition(); return cmrRepositoryDefinition; } return null; } /** * Returns {@link ICmrService} object if one is bounded to the proxy being invoked in the given * {@link MethodInvocation} or <code>null</code> if one can not be obtained. * * @param methodInvocation * {@link MethodInvocation}. * @return {@link ICmrService} bounded on proxy or <code>null</code> */ private static ICmrService getCmrService(MethodInvocation methodInvocation) { if (methodInvocation instanceof ReflectiveMethodInvocation) { ReflectiveMethodInvocation reflectiveMethodInvocation = (ReflectiveMethodInvocation) methodInvocation; Object service = reflectiveMethodInvocation.getThis(); if (service instanceof ICmrService) { return (ICmrService) service; } } return null; } /** * Checks if the return type of the {@link java.lang.reflect.Method} invoked by * {@link MethodInvocation} is one of tree major collection types (List, Map, Set) and if it is * returns the empty collection of correct type. Otherwise it returns null. * * @param paramMethodInvocation * {@link MethodInvocation} * @return If the method invoked by {@link MethodInvocation} is one of tree major collection * types (List, Map, Set) method returns the empty collection of correct type. Otherwise * it returns null. */ public static Object getDefaultReturnValue(MethodInvocation paramMethodInvocation) { Class<?> returnType = paramMethodInvocation.getMethod().getReturnType(); if (returnType.isAssignableFrom(List.class)) { return Collections.emptyList(); } else if (returnType.isAssignableFrom(Map.class)) { return Collections.emptyMap(); } else if (returnType.isAssignableFrom(Set.class)) { return Collections.emptySet(); } else if (returnType.isPrimitive()) { try { return Defaults.defaultValue(returnType); } catch (Exception e) { return null; } } else { return null; } } }
inspectIT/inspectIT
inspectit.ui.rcp/src/main/java/rocks/inspectit/ui/rcp/repository/service/cmr/proxy/InterceptorUtils.java
Java
agpl-3.0
3,959
require 'spec_helper' describe Queries::SignaturesExport do subject { Queries::SignaturesExport.new(petition_id: petition_id) } let(:petition_id) { '1' } it "should have generate some SQL" do subject.sql.should start_with("SELECT") end context "with objects" do let(:petition) { FactoryGirl.create(:petition) } let(:petition_id) { petition.id } let!(:signature) { FactoryGirl.create(:signature, petition: petition) } before(:each) do @result = "" subject.as_csv_stream.each do |chunk| @result << chunk end end context "when parsed" do before(:each) do @parsed = CSV.parse(@result) end describe "header" do let(:header) { @parsed[0] } specify{ header.should include("email")} end describe "first row" do let(:first_row) { @parsed[1] } specify{ first_row.should include(signature.email)} end end end end
MayOneUS/victorykit
spec/models/queries/signatures_export_spec.rb
Ruby
agpl-3.0
963
/*////////////////////////////////////////////////////////////////// //// SKIRT -- an advanced radiative transfer code //// //// © Astronomical Observatory, Ghent University //// ///////////////////////////////////////////////////////////////// */ #include "SubItemPropertyWizardPane.hpp" #include "ItemListPropertyHandler.hpp" #include "SimulationItemDiscovery.hpp" #include "SimulationItemTools.hpp" #include "SimulationItem.hpp" #include <QVBoxLayout> #include <QLabel> #include <QRadioButton> #include <QButtonGroup> #include <QVariant> using namespace SimulationItemDiscovery; //////////////////////////////////////////////////////////////////// SubItemPropertyWizardPane::SubItemPropertyWizardPane(PropertyHandlerPtr handler, QObject* target) : PropertyWizardPane(handler, target) { auto hdlr = handlerCast<ItemListPropertyHandler>(); // create the layout so that we can add stuff one by one auto layout = new QVBoxLayout; // add the question layout->addWidget(new QLabel("Select one of the following options for item #" + QString::number(selectedIndex()+1) + " in " + hdlr->title() + " list:")); // determine the current and default item types QByteArray currentType = itemType(hdlr->value()[selectedIndex()]); QByteArray defaultType = hdlr->hasDefaultValue() ? hdlr->defaultItemType() : ""; // make a button group to contain the radio buttons reflecting the possible choices auto buttonGroup = new QButtonGroup; // add the choices for (auto choiceType : SimulationItemTools::allowedDescendants(hdlr->baseType(),hdlr->target())) { auto choiceTitle = title(choiceType); if (!choiceTitle.isEmpty()) choiceTitle.replace(0, 1, choiceTitle[0].toUpper()); if (SimulationItemDiscovery::inherits(choiceType,defaultType)) choiceTitle += " [default]"; auto choiceButton = new QRadioButton(choiceTitle); choiceButton->setFocusPolicy(Qt::NoFocus); buttonGroup->addButton(choiceButton); layout->addWidget(choiceButton); // associate the item type corresponding to this button with the button object choiceButton->setProperty("choiceType", choiceType); choiceButton->setToolTip(choiceType); // if this button corresponds to the current type, select it if (choiceType==currentType) { choiceButton->setChecked(true); emit propertyValidChanged(true); } } // connect the button group to ourselves connect(buttonGroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(selectTypeFor(QAbstractButton*))); // finalize the layout and assign it to ourselves layout->addStretch(); setLayout(layout); } //////////////////////////////////////////////////////////////////// int SubItemPropertyWizardPane::selectedIndex() { auto hdlr = handlerCast<ItemListPropertyHandler>(); return SimulationItemTools::retrieveSelectedRow(hdlr->target(), hdlr->name()); } //////////////////////////////////////////////////////////////////// void SubItemPropertyWizardPane::selectTypeFor(QAbstractButton* button) { auto hdlr = handlerCast<ItemListPropertyHandler>(); // update the value if needed auto newType = button->property("choiceType").toByteArray(); int index = selectedIndex(); if (itemType(hdlr->value()[index]) != newType) { hdlr->removeValueAt(index); hdlr->insertNewItemOfType(index, newType); emit propertyValueChanged(); } // signal the change emit propertyValidChanged(true); } ////////////////////////////////////////////////////////////////////
raesjo/SKIRTcorona
SkirtMakeUp/SubItemPropertyWizardPane.cpp
C++
agpl-3.0
3,696
/** * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of fiware-tidoop (FI-WARE project). * * fiware-tidoop 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. * fiware-tidoop 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 fiware-tidoop. If not, see * http://www.gnu.org/licenses/. * * For those usages not covered by the GNU Affero General Public License please contact with * francisco.romerobueno at telefonica dot com */ package com.telefonica.iot.tidoop.apiext.utils; import com.telefonica.iot.tidoop.apiext.hadoop.ckan.CKANInputFormat; import com.telefonica.iot.tidoop.apiext.hadoop.ckan.CKANOutputFormat; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; /** * * @author frb */ public final class CKANMapReduceExample extends Configured implements Tool { /** * Constructor. It is private since utility classes should not have a public or default constructor. */ private CKANMapReduceExample() { } // CKANMapReduceTest /** * Mapper class. It receives a CKAN record pair (Object key, Text ckanRecord) and returns a (Text globalKey, * IntWritable recordLength) pair about a common global key and the length of the record. */ public static class RecordSizeGetter extends Mapper<Object, Text, Text, IntWritable> { private final Text globalKey = new Text("size"); private final IntWritable recordLength = new IntWritable(); @Override public void map(Object key, Text value, Context context) throws IOException, InterruptedException { recordLength.set(value.getLength()); context.write(globalKey, recordLength); } // map } // RecordSizeGetter /** * Reducer class. It receives a list of (Text globalKey, IntWritable length) pairs and computes the sum of all the * lengths, producing a final (Text globalKey, IntWritable totalLength). */ public static class RecordSizeAdder extends Reducer<Text, IntWritable, Text, IntWritable> { private final IntWritable totalLength = new IntWritable(); @Override public void reduce(Text globalKey, Iterable<IntWritable> recordLengths, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : recordLengths) { sum += val.get(); } // for totalLength.set(sum); context.write(globalKey, totalLength); } // reduce } // RecordSizeAdder /** * Main class. * @param args * @throws Exception */ public static void main(String[] args) throws Exception { int res = ToolRunner.run(new Configuration(), new CKANMapReduceExample(), args); System.exit(res); } // main @Override public int run(String[] args) throws Exception { // check the number of arguments, show the usage if it is wrong if (args.length != 7) { showUsage(); return -1; } // if // get the arguments String ckanHost = args[0]; String ckanPort = args[1]; boolean sslEnabled = args[2].equals("true"); String ckanAPIKey = args[3]; String ckanInputs = args[4]; String ckanOutput = args[5]; String splitsLength = args[6]; // create and configure a MapReduce job Configuration conf = this.getConf(); Job job = Job.getInstance(conf, "CKAN MapReduce test"); job.setJarByClass(CKANMapReduceExample.class); job.setMapperClass(RecordSizeGetter.class); job.setCombinerClass(RecordSizeAdder.class); job.setReducerClass(RecordSizeAdder.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setInputFormatClass(CKANInputFormat.class); CKANInputFormat.setInput(job, ckanInputs); CKANInputFormat.setEnvironment(job, ckanHost, ckanPort, sslEnabled, ckanAPIKey); CKANInputFormat.setSplitsLength(job, splitsLength); job.setOutputFormatClass(CKANOutputFormat.class); CKANOutputFormat.setEnvironment(job, ckanHost, ckanPort, sslEnabled, ckanAPIKey); CKANOutputFormat.setOutputPkg(job, ckanOutput); // run the MapReduce job return job.waitForCompletion(true) ? 0 : 1; } // main private void showUsage() { System.out.println("Usage:"); System.out.println(); System.out.println("hadoop jar \\"); System.out.println(" target/ckan-protocol-0.1-jar-with-dependencies.jar \\"); System.out.println(" es.tid.fiware.fiwareconnectors.ckanprotocol.utils.CKANMapReduceTest \\"); System.out.println(" -libjars target/ckan-protocol-0.1-jar-with-dependencies.jar \\"); System.out.println(" <ckan host> \\"); System.out.println(" <ckan port> \\"); System.out.println(" <ssl enabled=true|false> \\"); System.out.println(" <ckan API key> \\"); System.out.println(" <comma-separated list of ckan inputs> \\"); System.out.println(" <ckan output package> \\"); System.out.println(" <splits length>"); } // showUsage } // CKANMapReduceTest
telefonicaid/fiware-tidoop
tidoop-hadoop-ext/src/main/java/com/telefonica/iot/tidoop/apiext/utils/CKANMapReduceExample.java
Java
agpl-3.0
6,139
require 'test_helper' class CurrenciesHelperTest < ActionView::TestCase end
BCJonesey/CDB3
test/unit/helpers/currencies_helper_test.rb
Ruby
agpl-3.0
77
<?php /** * Interface denoting an event is a deferred event that should be raised only at the end of the multirequest * * @package Core * @subpackage events */ interface IKalturaMultiDeferredEvent { /** * @param array $partnerCriteriaParams */ public function setPartnerCriteriaParams(array $partnerCriteriaParams); }
kaltura/server
alpha/apps/kaltura/lib/events/interfaces/IKalturaMultiDeferredEvent.php
PHP
agpl-3.0
330
package org.tasgoon.coherence.client; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import org.apache.commons.io.FileUtils; import org.tasgoon.coherence.common.Library; import org.tasgoon.coherence.ziputils.ZipUtility; import joptsimple.OptionParser; import joptsimple.OptionSet; public class CohereUndoer { //public final Logger logger = LogManager.getLogger("Coherence"); public String pid, ip, minecraftCmd; public boolean crashed = false; public static void main(String[] args) throws IOException, InterruptedException { OptionParser parser = new OptionParser("i:p:c::"); /*OptionSpec<String> ip = parser.accepts("ip", "The previous IP Minecraft was connected to").withRequiredArg(); OptionSpec<String> pid = parser.accepts("pid", "PID of the minecraft process").withRequiredArg(); OptionSpec<String> cmd = parser.accepts("cmd", "The minecraft command, for crash recovery").withOptionalArg();*/ new CohereUndoer(parser.parse(args)); } public CohereUndoer(OptionSet options) throws IOException, InterruptedException { System.out.println("Starting coherence undoer"); pid = (String) options.valueOf("p"); ip = (String) options.valueOf("i"); if (options.has("c")) { crashed = true; minecraftCmd = (String) options.valueOf("c"); } System.out.println("Using command: " + getCommand()); System.out.println("Starting process kill detector"); waitForProcessEnd(); undo(); } public String getCommand() { String command; String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("win") >= 0) command = System.getenv("windir") + "\\system32\\" + "tasklist.exe /FI \"PID eq %s\""; else command = "ps -p %s"; return String.format(command, pid); } public void waitForProcessEnd() throws IOException, InterruptedException { boolean detected = true; String line; while (detected) { detected = false; Process process = Runtime.getRuntime().exec(getCommand()); BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((line = input.readLine()) != null) { if (line.contains(pid)) detected = true; } } } public void undo() { System.out.println("Moving files back."); File modsDir = new File("mods"); File originalModsDir = Library.getFile("coherence", "localhost", "mods"); /*//Because the reversal script is running from a file in the mods directory, I can't just remove the file. //So, I have to iterate through the folder and remove all the files save for Coherence. for (File file : cohereModsDir.listFiles()) FileUtils.deleteQuietly(file);*/ FileUtils.deleteQuietly(modsDir); for (File file : originalModsDir.listFiles()) { try { FileUtils.moveToDirectory(file, modsDir, false); } catch (IOException e) { System.err.println("Could not move file " + file.getAbsolutePath() + " back."); e.printStackTrace(); } } File config = new File("config"); File customConfig = Library.getFile("coherence", ip, "customConfig.zip"); System.out.println("Saving current configs to " + customConfig.getAbsolutePath()); ZipUtility.compressFolder(config, customConfig); System.out.println("Deleting configs from config folder"); try { FileUtils.forceDelete(config); } catch (IOException e) { System.err.println("Could not delete synchronized config files."); e.printStackTrace(); } System.out.println("Moving old configs back to main config folder"); new File("oldConfig").renameTo(config); FileUtils.deleteQuietly(new File("coherence", "localhost")); //Contains mods that were just moved back if (crashed) startMC(); } public void startMC() { try { Runtime.getRuntime().exec(minecraftCmd); } catch (IOException e) {} } }
Kagiu/Coherence
src/main/java/org/tasgoon/coherence/client/CohereUndoer.java
Java
agpl-3.0
3,832
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2020, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- from copy import deepcopy from .oml_replicate import metacl_oml_replicate meta_test_test_kwargs = dict( # Setup the meta-testing phase and allow it to run. run_meta_test=True, # This resets the fast params (in this case the output layer of the OMLNetwork) reset_fast_params=True, # Results reported over 15 sampled. meta_test_sample_size=15, # Run meta-testing over 10 and 50 classes. num_meta_test_classes=[10, 50], # The best lr was chosen among the following; done separately for each number of # classes trained on. lr_sweep_range=[0.03, 0.01, 0.003, 0.001, 0.0003, 0.0001, 0.00003, 0.00001], # Run through meta-test testing 5 images at a time. No training occurs here. test_test_batch_size=60, ) # Run OML for 2000 steps to ensure meta=testing accuracy hasn't regressed. # |--------------------------------------------------------------| # | Num Classes | Meta-test test | Meta-test train | LR | # |--------------:|:-----------------|:------------------|------:| # | 10 | 0.84 ± 0.06 | 0.94 ± 0.05 | 0.003 | # | 50 | 0.75 ± 0.03 | 0.95 ± 0.01 | 0.001 | # |--------------------------------------------------------------| # oml_regression_test = deepcopy(metacl_oml_replicate) oml_regression_test.update( # The number of outer (i.e. slow) steps. epochs=2000, # Log results to wandb. wandb_args=dict( name="oml_regression_test", project="metacl", ), # Meta-testing specific arguments. **deepcopy(meta_test_test_kwargs), ) # This is meant as a quick run to ensure all functionality is fully working. # |---------------------------------------------------------------| # | Num Classes | Meta-test test | Meta-test train | LR | # |--------------:|:-----------------|:------------------|-------:| # | 10 | 0.51 ± 0.03 | 0.81 ± 0.01 | 0.001 | # |---------------------------------------------------------------| # oml_regression_test_50_epochs = deepcopy(oml_regression_test) oml_regression_test_50_epochs.update( # The number of outer (i.e. slow) steps. epochs=50, # Average over 10 meta-test runs. num_meta_testing_runs=3, num_meta_test_classes=[10], num_lr_search_runs=1, lr_sweep_range=[0.001], # Log results to wandb. wandb_args=dict( name="oml_regression_test_50_epochs", project="metacl", ), ) # ------------ # All configs. # ------------ CONFIGS = dict( oml_regression_test=oml_regression_test, oml_regression_test_50_epochs=oml_regression_test_50_epochs, )
mrcslws/nupic.research
projects/meta_cl/experiments/oml_regression_test.py
Python
agpl-3.0
3,610
class Admin::PetitionsController < ApplicationController before_filter :require_admin def index params[:time_span] ||= 'month' respond_to do |format| format.html {} format.json { render json: PetitionsDatatable.new(view_context, PetitionReportRepository.new) } end end end
ChrisAntaki/victorykit
app/controllers/admin/petitions_controller.rb
Ruby
agpl-3.0
304
/* * Async_MediaConnectionListener.java Version-1.4, 2002/11/22 09:26:10 -0800 (Fri) * ECTF S.410-R2 Source code distribution. * * Copyright (c) 2002, Enterprise Computer Telephony Forum (ECTF), * All Rights Reserved. * * Use and redistribution of this file is subject to a License. * For terms and conditions see: javax/telephony/media/LICENSE.HTML * * In short, you can use this source code if you keep and display * the ECTF Copyright and the License conditions. The code is supplied * "AS IS" and ECTF disclaims all warranties and liability. */ package javax.telephony.media.connection.async; import javax.telephony.media.connection.*; import javax.telephony.media.async.*; import javax.telephony.media.*; /** Transaction completion Listener for connect() and related methods. * * @author Jeff Peck * @since JTAPI-1.4 */ public interface Async_MediaConnectionListener extends MediaListener { /** * Connect complete. * <tt>event.getEventID()</tt> is one of the connection type Symbols: * <br>{<tt>ev_Bridge</tt>, <tt>ev_Join</tt>, <tt>ev_Loopback</tt>}. * <p> * <tt>event.getToken()</tt> identifies the connection: * <ul><li> * the other Group, * </li><li> * connection type, * </li><li> * dataFlow, * </li><li> * maxDataFlow. * </li></ul> * * @param event the MediaConnectionEvent that is done. */ void onConnectDone( MediaConnectionEvent event ); /** * Disconnect complete. * event.getEventID() = <tt>ev_Disconnect</tt>. * <p> * The event.getToken() identifies the connection and Group * which has been disconnected. * Token.dataFlow and Token.maxDataFlow are <tt>null</tt>. * * <p> * <tt>event.getEventID() = connType = ev_Disconnect</tt>. * * @param event the MediaConnectionEvent that is done. */ void onDisconnectDone( MediaConnectionEvent event ); /** * SetDataFlow complete. * event.getEventID() = <tt>ev_Disconnect</tt>. * <p> * The event.getToken() identifies the connection and Group * which has been disconnected. * Token.dataFlow and Token.maxDataFlow are <tt>null</tt>. * * <p> * <tt>event.getEventID() = connType = ev_Disconnect</tt>. * * @param event the MediaConnectionEvent that is done. */ void onSetDataFlowDone( MediaConnectionEvent event ); }
openss7/openss7
src/java/javax/telephony/media/connection/async/Async_MediaConnectionListener.java
Java
agpl-3.0
2,435
// Copyright 2014 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. // Package miner implements Ethereum block creation and mining. package miner import ( "errors" "math/big" "sync/atomic" "github.com/ethereumproject/go-ethereum/common" "github.com/ethereumproject/go-ethereum/core" "github.com/ethereumproject/go-ethereum/core/state" "github.com/ethereumproject/go-ethereum/core/types" "github.com/ethereumproject/go-ethereum/eth/downloader" "github.com/ethereumproject/go-ethereum/event" "github.com/ethereumproject/go-ethereum/logger" "github.com/ethereumproject/go-ethereum/logger/glog" "github.com/ethereumproject/go-ethereum/pow" ) // HeaderExtra is a freeform description. var HeaderExtra []byte type Miner struct { mux *event.TypeMux worker *worker MinAcceptedGasPrice *big.Int threads int coinbase common.Address mining int32 eth core.Backend pow pow.PoW canStart int32 // can start indicates whether we can start the mining operation shouldStart int32 // should start indicates whether we should start after sync } func New(eth core.Backend, config *core.ChainConfig, mux *event.TypeMux, pow pow.PoW) *Miner { miner := &Miner{eth: eth, mux: mux, pow: pow, worker: newWorker(config, common.Address{}, eth), canStart: 1} go miner.update() return miner } // update keeps track of the downloader events. Please be aware that this is a one shot type of update loop. // It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and // the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks // and halt your mining operation for as long as the DOS continues. func (self *Miner) update() { events := self.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{}) out: for ev := range events.Chan() { switch ev.Data.(type) { case downloader.StartEvent: atomic.StoreInt32(&self.canStart, 0) if self.Mining() { self.Stop() atomic.StoreInt32(&self.shouldStart, 1) glog.V(logger.Info).Infoln("Mining operation aborted due to sync operation") } case downloader.DoneEvent, downloader.FailedEvent: shouldStart := atomic.LoadInt32(&self.shouldStart) == 1 atomic.StoreInt32(&self.canStart, 1) atomic.StoreInt32(&self.shouldStart, 0) if shouldStart { self.Start(self.coinbase, self.threads) } // unsubscribe. we're only interested in this event once events.Unsubscribe() // stop immediately and ignore all further pending events break out } } } func (m *Miner) SetGasPrice(price *big.Int) error { if price == nil { return nil } if m.MinAcceptedGasPrice != nil && price.Cmp(m.MinAcceptedGasPrice) == -1 { priceTooLowError := errors.New("Gas price lower than minimum allowed.") return priceTooLowError } m.worker.setGasPrice(price) return nil } func (self *Miner) Start(coinbase common.Address, threads int) { atomic.StoreInt32(&self.shouldStart, 1) self.threads = threads self.worker.coinbase = coinbase self.coinbase = coinbase if atomic.LoadInt32(&self.canStart) == 0 { glog.V(logger.Info).Infoln("Can not start mining operation due to network sync (starts when finished)") return } atomic.StoreInt32(&self.mining, 1) for i := 0; i < threads; i++ { self.worker.register(NewCpuAgent(i, self.pow)) } mlogMinerStart.AssignDetails( coinbase.Hex(), threads, ).Send(mlogMiner) glog.V(logger.Info).Infof("Starting mining operation (CPU=%d TOT=%d)\n", threads, len(self.worker.agents)) self.worker.start() self.worker.commitNewWork() } func (self *Miner) Stop() { self.worker.stop() atomic.StoreInt32(&self.mining, 0) atomic.StoreInt32(&self.shouldStart, 0) if logger.MlogEnabled() { mlogMinerStop.AssignDetails( self.coinbase.Hex(), self.threads, ).Send(mlogMiner) } } func (self *Miner) Register(agent Agent) { if self.Mining() { agent.Start() } self.worker.register(agent) } func (self *Miner) Unregister(agent Agent) { self.worker.unregister(agent) } func (self *Miner) Mining() bool { return atomic.LoadInt32(&self.mining) > 0 } func (self *Miner) HashRate() (tot int64) { tot += self.pow.GetHashrate() // do we care this might race? is it worth we're rewriting some // aspects of the worker/locking up agents so we can get an accurate // hashrate? for agent := range self.worker.agents { tot += agent.GetHashRate() } return } // Pending returns the currently pending block and associated state. func (self *Miner) Pending() (*types.Block, *state.StateDB) { return self.worker.pending() } func (self *Miner) SetEtherbase(addr common.Address) { self.coinbase = addr self.worker.setEtherbase(addr) }
adrianbrink/tendereum
vendor/github.com/ethereumproject/go-ethereum/miner/miner.go
GO
agpl-3.0
5,441
<?php /* * $Id$ * * 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. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * <http://www.phpdoctrine.org>. */ /** * Doctrine_Ticket_DC187_TestCase * * @package Doctrine * @author Konsta Vesterinen <kvesteri@cc.hut.fi> * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @category Object Relational Mapping * @link www.phpdoctrine.org * @since 1.0 * @version $Revision$ */ class Doctrine_Ticket_DC187_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { $this->tables[] = 'Ticket_DC187_User'; parent::prepareTables(); } public function testTest() { Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); $user = new Ticket_DC187_User(); $user->username = 'jwage'; $user->email = 'jonwage@gmail.com'; $user->password = 'changeme'; $user->save(); $user->delete(); try { $user = new Ticket_DC187_User(); $user->username = 'jwage'; $user->email = 'jonwage@gmail.com'; $user->password = 'changeme'; $user->save(); $this->pass(); } catch (Exception $e) { $this->fail($e->getMessage()); } try { $user = new Ticket_DC187_User(); $user->username = 'jwage'; $user->email = 'jonwage@gmail.com'; $user->password = 'changeme'; $user->save(); $this->fail(); } catch (Exception $e) { $this->pass(); } Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } } class Ticket_DC187_User extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('username', 'string', 255); $this->hasColumn('email', 'string', 255); $this->hasColumn('password', 'string', 255); $this->unique( array('username', 'email'), array('where' => "deleted_at IS NULL"), false ); } public function setUp() { $this->actAs('SoftDelete'); } }
ascorbic/doctrine-tracker
tests/Ticket/DC187TestCase.php
PHP
lgpl-2.1
3,118
<?php namespace wcf\data\devtools\missing\language\item; use wcf\data\DatabaseObject; use wcf\data\language\Language; use wcf\system\language\LanguageFactory; use wcf\system\WCF; use wcf\util\JSON; /** * Represents a missing language item log entry. * * @author Matthias Schmidt * @copyright 2001-2020 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\Devtools\Missing\Language\Item * @since 5.3 * * @property-read int $itemID unique id of the missing language item log entry * @property-read int $languageID id of the language the missing language item was requested for * @property-read string $languageItem name of the missing language item * @property-read int $lastTime timestamp of the last time the missing language item was requested * @property-read string $stackTrace stack trace of how the missing language item was requested for the last time */ class DevtoolsMissingLanguageItem extends DatabaseObject { /** * Returns the language the missing language item was requested for or `null` if the language * does not exist anymore. * * @return null|Language */ public function getLanguage() { if ($this->languageID === null) { return null; } return LanguageFactory::getInstance()->getLanguage($this->languageID); } /** * Returns the formatted stack trace of how the missing language item was requested for the * last time. * * @return string */ public function getStackTrace() { $stackTrace = JSON::decode($this->stackTrace); foreach ($stackTrace as &$stackEntry) { foreach ($stackEntry['args'] as &$stackEntryArg) { if (\gettype($stackEntryArg) === 'string') { $stackEntryArg = \str_replace(["\n", "\t"], ['\n', '\t'], $stackEntryArg); } } unset($stackEntryArg); } unset($stackEntry); return WCF::getTPL()->fetch('__devtoolsMissingLanguageItemStackTrace', 'wcf', [ 'stackTrace' => $stackTrace, ]); } }
SoftCreatR/WCF
wcfsetup/install/files/lib/data/devtools/missing/language/item/DevtoolsMissingLanguageItem.class.php
PHP
lgpl-2.1
2,209
package ch.unibas.cs.hpwc.patus.grammar.stencil2; import cetus.hir.BinaryExpression; import cetus.hir.BinaryOperator; import cetus.hir.DepthFirstIterator; import cetus.hir.Expression; import cetus.hir.IDExpression; import cetus.hir.IntegerLiteral; import cetus.hir.NameID; import ch.unibas.cs.hpwc.patus.representation.Stencil; import ch.unibas.cs.hpwc.patus.representation.StencilBundle; import ch.unibas.cs.hpwc.patus.representation.StencilNode; import ch.unibas.cs.hpwc.patus.symbolic.Symbolic; import ch.unibas.cs.hpwc.patus.util.CodeGeneratorUtil; import ch.unibas.cs.hpwc.patus.util.StringUtil; public class StencilSpecificationAnalyzer { /** * * @param bundle */ public static void normalizeStencilNodesForBoundariesAndIntial (StencilBundle bundle) { for (Stencil stencil : bundle) { for (StencilNode node : stencil.getAllNodes ()) { Expression[] rgIdx = node.getIndex ().getSpaceIndexEx (); Expression[] rgIdxNew = new Expression[rgIdx.length]; for (int i = 0; i < rgIdx.length; i++) { String strDimId = StencilSpecificationAnalyzer.getContainedDimensionIdentifier (rgIdx[i], i); if (strDimId != null) { // if an entry I contains the corresponding dimension identifier id, compute I-id // we expect this to be an integer value rgIdxNew[i] = Symbolic.simplify (new BinaryExpression (rgIdx[i].clone (), BinaryOperator.SUBTRACT, new NameID (strDimId))); if (!(rgIdxNew[i] instanceof IntegerLiteral)) { throw new RuntimeException (StringUtil.concat ("Illegal coordinate ", rgIdx[i].toString (), " in grid reference ", node.toString ()," in definition ", stencil.toString () )); } } else { // if the entry doesn't contain a dimension identifier, set the corresponding spatial index coordinate // to 0 (=> do something when the point becomes the center point), and add a constraint setting the // corresponding subdomain index (dimension identifier) to the expression of the index entry rgIdxNew[i] = new IntegerLiteral (0); node.addConstraint (new BinaryExpression (new NameID (CodeGeneratorUtil.getDimensionName (i)), BinaryOperator.COMPARE_EQ, rgIdx[i])); } } node.getIndex ().setSpaceIndex (rgIdxNew); } } } /** * Check that all the stencil nodes in the stencils of the bundle are legal, * i.e., that the spatial index has the form [x+dx, y+dy, ...]. Note that * the dimension identifiers (x, y, ...) have been subtracted already, so * the spatial index should be an array of integer numbers. * * @param bundle * The bundle to check */ public static void checkStencilNodesLegality (StencilBundle bundle) { for (Stencil stencil : bundle) for (StencilNode node : stencil) for (Expression exprIdx : node.getIndex ().getSpaceIndexEx ()) if (!(exprIdx instanceof IntegerLiteral)) throw new RuntimeException (StringUtil.concat ("Illegal grid reference", exprIdx.toString ())); // TODO: handle in parser } /** * Determines whether the expression <code>expr</code> contains a dimension * identifier corresponding to dimension <code>nDim</code>. * * @param expr * The expression to examine * @param nDim * The dimension whose identifier to detect * @return <code>true</code> iff <code>expr</code> contains a dimension * identifier corresponding to the dimension <code>nDim</code> */ public static String getContainedDimensionIdentifier (Expression expr, int nDim) { String strId = CodeGeneratorUtil.getDimensionName (nDim); String strIdAlt = CodeGeneratorUtil.getAltDimensionName (nDim); for (DepthFirstIterator it = new DepthFirstIterator (Symbolic.simplify (expr)); it.hasNext (); ) { Object o = it.next (); if (o instanceof IDExpression) { if (((IDExpression) o).getName ().equals (strId)) return strId; if (((IDExpression) o).getName ().equals (strIdAlt)) return strIdAlt; } } return null; } }
matthias-christen/patus
src/ch/unibas/cs/hpwc/patus/grammar/stencil2/StencilSpecificationAnalyzer.java
Java
lgpl-2.1
4,059
/* * Copyright 2011 Stephen Liu * For license terms, see the file COPYING along with this library. */ #include <vector> #include <unistd.h> #include <errno.h> #include <signal.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include "spnkprefork.hpp" #include "spnklog.hpp" #include "spnkstr.hpp" #include "spnksocket.hpp" typedef struct tagSP_NKPreforkManagerImpl { SP_NKPreforkManager::Handler_t mHandler; void * mArgs; int mMaxProcs; int mCheckInterval; std::vector< pid_t > mPidList; } SP_NKPreforkManagerImpl_t; SP_NKPreforkManager :: SP_NKPreforkManager( Handler_t handler, void * args, int maxProcs, int checkInterval ) { mImpl = new SP_NKPreforkManagerImpl_t; mImpl->mHandler = handler; mImpl->mArgs = args; mImpl->mMaxProcs = maxProcs; mImpl->mCheckInterval = checkInterval; if( mImpl->mCheckInterval <= 0 ) checkInterval = 1; } SP_NKPreforkManager :: ~SP_NKPreforkManager() { delete mImpl; mImpl = NULL; } int SP_NKPreforkManager :: run() { pid_t pid = fork(); if( 0 == pid ) { runForever(); return 0; } else if( pid > 0 ) { SP_NKLog::log( LOG_DEBUG, "fork proc master %d", pid ); } else { SP_NKLog::log( LOG_ERR, "fork fail, errno %d, %s", errno, strerror( errno ) ); } return pid > 0 ? 0 : -1; } void SP_NKPreforkManager :: termHandler( int sig ) { kill( 0, SIGTERM ); exit( 0 ); } void SP_NKPreforkManager :: runForever() { signal( SIGCHLD, SIG_IGN ); signal( SIGTERM, termHandler ); for( int i = 0; i < mImpl->mMaxProcs; i++ ) { pid_t pid = fork(); if( 0 == pid ) { mImpl->mHandler( i, mImpl->mArgs ); exit( 0 ); } else if( pid > 0 ) { SP_NKLog::log( LOG_DEBUG, "fork proc#%d %d", i, pid ); mImpl->mPidList.push_back( pid ); } else { SP_NKLog::log( LOG_ERR, "fork fail, errno %d, %s", errno, strerror( errno ) ); exit( -1 ); } } for( ; ; ) { sleep( mImpl->mCheckInterval ); for( int i = 0; i < (int)mImpl->mPidList.size(); i++ ) { pid_t pid = mImpl->mPidList[i]; if( 0 != kill( pid, 0 ) ) { SP_NKLog::log( LOG_ERR, "proc#%d %d is not exists", i, pid ); pid = fork(); if( 0 == pid ) { mImpl->mHandler( i, mImpl->mArgs ); exit( 0 ); } else if( pid > 0 ) { SP_NKLog::log( LOG_DEBUG, "fork proc#%d %d to replace %d", i, pid, mImpl->mPidList[i] ); mImpl->mPidList[i] = pid; } else { SP_NKLog::log( LOG_ERR, "fork fail, errno %d, %s", errno, strerror( errno ) ); // leave pid for next check } } } } } void SP_NKPreforkManager :: shutdown() { kill( 0, SIGTERM ); } //=========================================================================== typedef struct tagSP_NKPreforkServerImpl { char mBindIP[ 64 ]; int mPort; SP_NKPreforkServer::OnRequest_t mOnRequest; void * mProcArgs; int mMaxProcs; int mCheckInterval; int mListenFD; int mMaxRequestsPerChild; SP_NKPreforkServer::BeforeChildRun_t mBeforeChildRun; SP_NKPreforkServer::AfterChildRun_t mAfterChildRun; } SP_NKPreforkServerImpl_t; SP_NKPreforkServer :: SP_NKPreforkServer( const char * bindIP, int port, OnRequest_t onRequest, void * procArgs ) { mImpl = (SP_NKPreforkServerImpl_t*)calloc( sizeof( SP_NKPreforkServerImpl_t ), 1 ); SP_NKStr::strlcpy( mImpl->mBindIP, bindIP, sizeof( mImpl->mBindIP ) ); mImpl->mPort = port; mImpl->mOnRequest = onRequest; mImpl->mProcArgs = procArgs; mImpl->mMaxProcs = 8; mImpl->mCheckInterval = 1; mImpl->mMaxRequestsPerChild = 10000; mImpl->mListenFD = -1; } SP_NKPreforkServer :: ~SP_NKPreforkServer() { if( mImpl->mListenFD >= 0 ) close( mImpl->mListenFD ); free( mImpl ); mImpl = NULL; } void SP_NKPreforkServer :: setBeforeChildRun( BeforeChildRun_t beforeChildRun ) { mImpl->mBeforeChildRun = beforeChildRun; } void SP_NKPreforkServer :: setAfterChildRun( AfterChildRun_t afterChildRun ) { mImpl->mAfterChildRun = afterChildRun; } void SP_NKPreforkServer :: setPreforkArgs( int maxProcs, int checkInterval, int maxRequestsPerChild ) { mImpl->mMaxProcs = maxProcs; mImpl->mCheckInterval = checkInterval; mImpl->mMaxRequestsPerChild = maxRequestsPerChild; } int SP_NKPreforkServer :: run() { pid_t pid = fork(); if( 0 == pid ) { runForever(); return 0; } else if( pid > 0 ) { SP_NKLog::log( LOG_DEBUG, "fork proc master %d", pid ); } else { SP_NKLog::log( LOG_ERR, "fork fail, errno %d, %s", errno, strerror( errno ) ); } return pid > 0 ? 0 : -1; } void SP_NKPreforkServer :: runForever() { #ifdef SIGPIPE /* Don't die with SIGPIPE on remote read shutdown. That's dumb. */ signal( SIGPIPE, SIG_IGN ); #endif int ret = 0; int listenFD = -1; ret = SP_NKSocket::tcpListen( mImpl->mBindIP, mImpl->mPort, &listenFD, 1 ); if( 0 == ret ) { mImpl->mListenFD = listenFD; SP_NKPreforkManager manager( serverHandler, mImpl, mImpl->mMaxProcs, mImpl->mCheckInterval ); manager.runForever(); } else { SP_NKLog::log( LOG_ERR, "list fail, errno %d, %s", errno, strerror( errno ) ); } } void SP_NKPreforkServer :: serverHandler( int index, void * args ) { SP_NKPreforkServerImpl_t * impl = (SP_NKPreforkServerImpl_t*)args; if( NULL != impl->mBeforeChildRun ) { impl->mBeforeChildRun( impl->mProcArgs ); } int factor = impl->mMaxRequestsPerChild / 10; factor = factor <= 0 ? 1 : factor; int maxRequestsPerChild = impl->mMaxRequestsPerChild + factor * index; for( int i= 0; i < maxRequestsPerChild; i++ ) { struct sockaddr_in addr; socklen_t socklen = sizeof( addr ); int fd = accept( impl->mListenFD, (struct sockaddr*)&addr, &socklen ); if( fd >= 0 ) { impl->mOnRequest( fd, impl->mProcArgs ); close( fd ); } else { SP_NKLog::log( LOG_ERR, "accept fail, errno %d, %s", errno, strerror( errno ) ); } } if( NULL != impl->mAfterChildRun ) { impl->mAfterChildRun( impl->mProcArgs ); } } void SP_NKPreforkServer :: shutdown() { kill( 0, SIGTERM ); } //=========================================================================== int SP_NKPreforkServer :: initDaemon( const char * workdir ) { pid_t pid; if ( (pid = fork()) < 0) return (-1); else if (pid) _exit(0); /* parent terminates */ /* child 1 continues... */ if (setsid() < 0) /* become session leader */ return (-1); assert( signal( SIGHUP, SIG_IGN ) != SIG_ERR ); assert( signal( SIGPIPE, SIG_IGN ) != SIG_ERR ); assert( signal( SIGALRM, SIG_IGN ) != SIG_ERR ); assert( signal( SIGCHLD, SIG_IGN ) != SIG_ERR ); if ( (pid = fork()) < 0) return (-1); else if (pid) _exit(0); /* child 1 terminates */ /* child 2 continues... */ if( NULL != workdir ) chdir( workdir ); /* change working directory */ /* close off file descriptors */ for (int i = 0; i < 64; i++) close(i); /* redirect stdin, stdout, and stderr to /dev/null */ open("/dev/null", O_RDONLY); open("/dev/null", O_RDWR); open("/dev/null", O_RDWR); return (0); /* success */ }
spsoft/spnetkit
spnetkit/spnkprefork.cpp
C++
lgpl-2.1
6,852
package railo.runtime.listener; import railo.commons.lang.types.RefBoolean; import railo.commons.lang.types.RefBooleanImpl; import railo.runtime.PageContext; import railo.runtime.PageSource; import railo.runtime.exp.PageException; public final class MixedAppListener extends ModernAppListener { @Override public void onRequest(PageContext pc, PageSource requestedPage, RequestListener rl) throws PageException { RefBoolean isCFC=new RefBooleanImpl(false); PageSource appPS=//pc.isCFCRequest()?null: AppListenerUtil.getApplicationPageSource(pc, requestedPage, mode, isCFC); if(isCFC.toBooleanValue())_onRequest(pc, requestedPage,appPS,rl); else ClassicAppListener._onRequest(pc, requestedPage,appPS,rl); } @Override public final String getType() { return "mixed"; } }
JordanReiter/railo
railo-java/railo-core/src/railo/runtime/listener/MixedAppListener.java
Java
lgpl-2.1
797
/* This file is part of KAddressBook. Copyright (c) 2002 Mike Pilone <mpilone@slac.com> 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. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "viewconfigurefilterpage.h" #include <QtGui/QBoxLayout> #include <QtGui/QButtonGroup> #include <QtGui/QHBoxLayout> #include <QtGui/QLabel> #include <QtGui/QRadioButton> #include <QtGui/QVBoxLayout> #include <kconfig.h> #include <kcombobox.h> #include <kdialog.h> #include <klocale.h> #include "filter.h" ViewConfigureFilterPage::ViewConfigureFilterPage( QWidget *parent, const char *name ) : QWidget( parent ) { setObjectName( name ); QBoxLayout *topLayout = new QVBoxLayout( this ); topLayout->setSpacing( KDialog::spacingHint() ); topLayout->setMargin( 0 ); mFilterGroup = new QButtonGroup(); connect( mFilterGroup, SIGNAL( buttonClicked( int ) ), SLOT( buttonClicked( int ) ) ); QLabel *label = new QLabel( i18n( "The default filter will be activated whenever" " this view is displayed. This feature allows you to configure views that only" " interact with certain types of information based on the filter. Once the view" " is activated, the filter can be changed at anytime." ), this ); label->setAlignment( Qt::AlignLeft | Qt::AlignTop ); label->setWordWrap( true ); topLayout->addWidget( label ); QWidget *spacer = new QWidget( this ); spacer->setMinimumHeight( 5 ); topLayout->addWidget( spacer ); QRadioButton *button = new QRadioButton( i18n( "No default filter" ), this ); mFilterGroup->addButton( button,0 ); topLayout->addWidget( button ); button = new QRadioButton( i18n( "Use last active filter" ), this ); mFilterGroup->addButton( button,1 ); topLayout->addWidget( button ); QBoxLayout *comboLayout = new QHBoxLayout(); topLayout->addLayout( comboLayout ); button = new QRadioButton( i18n( "Use filter:" ), this ); mFilterGroup->addButton( button,2 ); comboLayout->addWidget( button ); mFilterCombo = new KComboBox( this ); comboLayout->addWidget( mFilterCombo ); topLayout->addStretch( 100 ); } ViewConfigureFilterPage::~ViewConfigureFilterPage() { } void ViewConfigureFilterPage::restoreSettings( const KConfigGroup &config ) { mFilterCombo->clear(); // Load the filter combo const Filter::List list = Filter::restore( config.config(), "Filter" ); Filter::List::ConstIterator it; for ( it = list.begin(); it != list.end(); ++it ) mFilterCombo->addItem( (*it).name() ); int id = config.readEntry( "DefaultFilterType", 1 ); mFilterGroup->button ( id )->setChecked(true); buttonClicked( id ); if ( id == 2 ) // has default filter mFilterCombo->setItemText( mFilterCombo->currentIndex(), config.readEntry( "DefaultFilterName" ) ); } void ViewConfigureFilterPage::saveSettings( KConfigGroup &config ) { config.writeEntry( "DefaultFilterName", mFilterCombo->currentText() ); config.writeEntry( "DefaultFilterType", mFilterGroup->id( mFilterGroup->checkedButton() ) ); } void ViewConfigureFilterPage::buttonClicked( int id ) { mFilterCombo->setEnabled( id == 2 ); } #include "viewconfigurefilterpage.moc"
lefou/kdepim-noakonadi
kaddressbook/viewconfigurefilterpage.cpp
C++
lgpl-2.1
4,025
object = {__bases__: [], __name__: 'object'} object.__mro__ = [object] type = {__bases__: [object], __mro__: [object], __name__: 'type'} object.__metaclass__ = type __ARGUMENTS_PADDING__ = {ARGUMENTS_PADDING: "YES IT IS!"} def __is__(me, other): return (me is other) __is__.is_method = True object.__is__ = __is__ def __isnot__(me, other): return not (me is other) __isnot__.is_method = True object.__isnot__ = __isnot__ def mro(me): if me is object: raw = me.__mro__ elif me.__class__: raw = me.__class__.__mro__ else: raw = me.__mro__ l = pythonium_call(tuple) l.jsobject = raw.slice() return l mro.is_method = True object.mro = mro def __hash__(me): uid = lookup(me, 'uid') if not uid: uid = object._uid object._uid += 1 me.__uid__ = uid return pythonium_call(str, '{' + uid) __hash__.is_method = True object._uid = 1 object.__hash__ = __hash__ def __rcontains__(me, other): contains = lookup(other, '__contains__') return contains(me) __rcontains__.is_method = True object.__rcontains__ = __rcontains__ def issubclass(klass, other): if klass is other: return __TRUE if not klass.__bases__: return __FALSE for base in klass.__bases__: if issubclass(base, other) is __TRUE: return __TRUE return __FALSE def pythonium_is_true(v): if v is False: return False if v is True: return True if v is None: return False if v is __NONE: return False if v is __FALSE: return False if isinstance(v, int) or isinstance(v, float): if v.jsobject == 0: return False length = lookup(v, '__len__') if length and length().jsobject == 0: return False return True def isinstance(obj, klass): if obj.__class__: return issubclass(obj.__class__, klass) return __FALSE def pythonium_obj_to_js_exception(obj): def exception(): this.exception = obj return exception def pythonium_is_exception(obj, exc): if obj is exc: return True return isinstance(obj, exc) def pythonium_call(obj): args = Array.prototype.slice.call(arguments, 1) if obj.__metaclass__: instance = {__class__: obj} init = lookup(instance, '__init__') if init: init.apply(instance, args) return instance else: return obj.apply(None, args) def pythonium_create_empty_dict(): instance = {__class__: dict} instance._keys = pythonium_call(list) instance.jsobject = JSObject() return instance def pythonium_mro(bases): """Calculate the Method Resolution Order of bases using the C3 algorithm. Suppose you intended creating a class K with the given base classes. This function returns the MRO which K would have, *excluding* K itself (since it doesn't yet exist), as if you had actually created the class. Another way of looking at this, if you pass a single class K, this will return the linearization of K (the MRO of K, *including* itself). """ # based on http://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/ seqs = [C.__mro__.slice() for C in bases] seqs.push(bases.slice()) def cdr(l): l = l.slice() l = l.splice(1) return l def contains(l, c): for i in l: if i is c: return True return False res = [] while True: non_empty = [] for seq in seqs: out = [] for item in seq: if item: out.push(item) if out.length != 0: non_empty.push(out) if non_empty.length == 0: # Nothing left to process, we're done. return res for seq in non_empty: # Find merge candidates among seq heads. candidate = seq[0] not_head = [] for s in non_empty: if contains(cdr(s), candidate): not_head.push(s) if not_head.length != 0: candidate = None else: break if not candidate: raise TypeError("Inconsistent hierarchy, no C3 MRO is possible") res.push(candidate) for seq in non_empty: # Remove candidate. if seq[0] is candidate: seq[0] = None seqs = non_empty def pythonium_create_class(name, bases, attrs): attrs.__name__ = name attrs.__metaclass__ = type attrs.__bases__ = bases mro = pythonium_mro(bases) mro.splice(0, 0, attrs) attrs.__mro__ = mro return attrs def lookup(obj, attr): obj_attr = obj[attr] if obj_attr != None: if obj_attr and {}.toString.call(obj_attr) == '[object Function]' and obj_attr.is_method and not obj_attr.bound: def method_wrapper(): args = Array.prototype.slice.call(arguments) args.splice(0, 0, obj) return obj_attr.apply(None, args) method_wrapper.bound = True return method_wrapper return obj_attr else: if obj.__class__: __mro__ = obj.__class__.__mro__ elif obj.__metaclass__: __mro__ = obj.__metaclass__.__mro__ else: # it's a function return None for base in __mro__: class_attr = base[attr] if class_attr != None: if {}.toString.call(class_attr) == '[object Function]' and class_attr.is_method and not class_attr.bound: def method_wrapper(): args = Array.prototype.slice.call(arguments) args.splice(0, 0, obj) return class_attr.apply(None, args) method_wrapper.bound = True return method_wrapper return class_attr def pythonium_object_get_attribute(obj, attr): r = lookup(obj, attr) if r != None: return r else: getattr = lookup(obj, '__getattr__') if getattr: return getattr(attr) else: console.trace('AttributeError', attr, obj) raise AttributeError pythonium_object_get_attribute.is_method = True object.__getattribute__ = pythonium_object_get_attribute def pythonium_get_attribute(obj, attr): if obj.__class__ or obj.__metaclass__: getattribute = lookup(obj, '__getattribute__') r = getattribute(attr) return r attr = obj[attr] if attr: if {}.toString.call(attr) == '[object Function]': def method_wrapper(): return attr.apply(obj, arguments) return method_wrapper else: return attr def pythonium_set_attribute(obj, attr, value): obj[attr] = value def ASSERT(condition, message): if not condition: raise message or pythonium_call(str, 'Assertion failed')
skariel/pythonium
pythonium/compliant/runtime.py
Python
lgpl-2.1
7,045
// 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. // // Copyright (c) 2007, 2008 Novell, Inc. // // Authors: // Andreia Gaita (avidigal@novell.com) // using System; using System.Text; using System.Runtime.InteropServices; using System.Collections; using System.Collections.Specialized; using Mono.WebBrowser.DOM; namespace Mono.WebBrowser { public interface IWebBrowser { /// <summary> /// Initialize a browser instance. /// </summary> /// <param name="handle"> /// A <see cref="IntPtr"/> to the native window handle of the widget /// where the browser engine will draw /// </param> /// <param name="width"> /// A <see cref="System.Int32"/>. Initial width /// </param> /// <param name="height"> /// A <see cref="System.Int32"/>. Initial height /// </param> /// <returns> /// A <see cref="System.Boolean"/> /// </returns> bool Load (IntPtr handle, int width, int height); void Shutdown (); void FocusIn (FocusOption focus); void FocusOut (); void Activate (); void Deactivate (); void Resize (int width, int height); void Render (byte[] data); void Render (string html); void Render (string html, string uri, string contentType); void ExecuteScript (string script); bool Initialized { get; } IWindow Window { get; } IDocument Document { get; } bool Offline {get; set;} /// <value> /// Object exposing navigation methods like Go, Back, etc. /// </value> INavigation Navigation { get; } event NodeEventHandler KeyDown; event NodeEventHandler KeyPress; event NodeEventHandler KeyUp; event NodeEventHandler MouseClick; event NodeEventHandler MouseDoubleClick; event NodeEventHandler MouseDown; event NodeEventHandler MouseEnter; event NodeEventHandler MouseLeave; event NodeEventHandler MouseMove; event NodeEventHandler MouseUp; event EventHandler Focus; event CreateNewWindowEventHandler CreateNewWindow; event AlertEventHandler Alert; event LoadStartedEventHandler LoadStarted; event LoadCommitedEventHandler LoadCommited; event ProgressChangedEventHandler ProgressChanged; event LoadFinishedEventHandler LoadFinished; event StatusChangedEventHandler StatusChanged; event SecurityChangedEventHandler SecurityChanged; event ContextMenuEventHandler ContextMenuShown; event NavigationRequestedEventHandler NavigationRequested; } public enum ReloadOption : uint { None = 0, Proxy = 1, Full = 2 } public enum FocusOption { None = 0, FocusFirstElement = 1, FocusLastElement = 2 } [Flags] public enum DialogButtonFlags { BUTTON_POS_0 = 1, BUTTON_POS_1 = 256, BUTTON_POS_2 = 65536, BUTTON_TITLE_OK = 1, BUTTON_TITLE_CANCEL = 2, BUTTON_TITLE_YES = 3, BUTTON_TITLE_NO = 4, BUTTON_TITLE_SAVE = 5, BUTTON_TITLE_DONT_SAVE = 6, BUTTON_TITLE_REVERT = 7, BUTTON_TITLE_IS_STRING = 127, BUTTON_POS_0_DEFAULT = 0, BUTTON_POS_1_DEFAULT = 16777216, BUTTON_POS_2_DEFAULT = 33554432, BUTTON_DELAY_ENABLE = 67108864, STD_OK_CANCEL_BUTTONS = 513 } public enum DialogType { Alert = 1, AlertCheck = 2, Confirm = 3, ConfirmEx = 4, ConfirmCheck = 5, Prompt = 6, PromptUsernamePassword = 7, PromptPassword = 8, Select = 9 } public enum Platform { Unknown = 0, Winforms = 1, Gtk = 2 } public enum SecurityLevel { Insecure= 1, Mixed = 2, Secure = 3 } #region Window Events public delegate bool CreateNewWindowEventHandler (object sender, CreateNewWindowEventArgs e); public class CreateNewWindowEventArgs : EventArgs { private bool isModal; #region Public Constructors public CreateNewWindowEventArgs (bool isModal) : base () { this.isModal = isModal; } #endregion // Public Constructors #region Public Instance Properties public bool IsModal { get { return this.isModal; } } #endregion // Public Instance Properties } #endregion #region Script events public delegate void AlertEventHandler (object sender, AlertEventArgs e); public class AlertEventArgs : EventArgs { private DialogType type; private string title; private string text; private string text2; private string username; private string password; private string checkMsg; private bool checkState; private DialogButtonFlags dialogButtons; private StringCollection buttons; private StringCollection options; private object returnValue; #region Public Constructors /// <summary> /// void (STDCALL *OnAlert) (const PRUnichar * title, const PRUnichar * text); /// </summary> /// <param name="title"></param> /// <param name="text"></param> public AlertEventArgs () : base () { } #endregion // Public Constructors #region Public Instance Properties public DialogType Type { get { return this.type; } set { this.type = value; } } public string Title { get { return this.title; } set { this.title = value; } } public string Text { get { return this.text; } set { this.text = value; } } public string Text2 { get { return this.text2; } set { this.text2 = value; } } public string CheckMessage { get { return this.checkMsg; } set { this.checkMsg = value; } } public bool CheckState { get { return this.checkState; } set { this.checkState = value; } } public DialogButtonFlags DialogButtons { get { return this.dialogButtons; } set { this.dialogButtons = value; } } public StringCollection Buttons { get { return buttons; } set { buttons = value; } } public StringCollection Options { get { return options; } set { options = value; } } public string Username { get { return username; } set { username = value; } } public string Password { get { return password; } set { password = value; } } public bool BoolReturn { get { if (returnValue is bool) return (bool) returnValue; return false; } set { returnValue = value; } } public int IntReturn { get { if (returnValue is int) return (int) returnValue; return -1; } set { returnValue = value; } } public string StringReturn { get { if (returnValue is string) return (string) returnValue; return String.Empty; } set { returnValue = value; } } #endregion } #endregion #region Loading events public delegate void StatusChangedEventHandler (object sender, StatusChangedEventArgs e); public class StatusChangedEventArgs : EventArgs { private string message; public string Message { get { return message; } set { message = value; } } private int status; public int Status { get { return status; } set { status = value; } } public StatusChangedEventArgs (string message, int status) { this.message = message; this.status = status; } } public delegate void ProgressChangedEventHandler (object sender, ProgressChangedEventArgs e); public class ProgressChangedEventArgs : EventArgs { private int progress; public int Progress { get { return progress; } } private int maxProgress; public int MaxProgress { get { return maxProgress; } } public ProgressChangedEventArgs (int progress, int maxProgress) { this.progress = progress; this.maxProgress = maxProgress; } } public delegate void LoadStartedEventHandler (object sender, LoadStartedEventArgs e); public class LoadStartedEventArgs : System.ComponentModel.CancelEventArgs { private string uri; public string Uri { get {return uri;} } private string frameName; public string FrameName { get {return frameName;} } public LoadStartedEventArgs (string uri, string frameName) { this.uri = uri; this.frameName = frameName; } } public delegate void LoadCommitedEventHandler (object sender, LoadCommitedEventArgs e); public class LoadCommitedEventArgs : EventArgs { private string uri; public string Uri { get {return uri;} } public LoadCommitedEventArgs (string uri) { this.uri = uri; } } public delegate void LoadFinishedEventHandler (object sender, LoadFinishedEventArgs e); public class LoadFinishedEventArgs : EventArgs { private string uri; public string Uri { get {return uri;} } public LoadFinishedEventArgs (string uri) { this.uri = uri; } } public delegate void SecurityChangedEventHandler (object sender, SecurityChangedEventArgs e); public class SecurityChangedEventArgs : EventArgs { private SecurityLevel state; public SecurityLevel State { get { return state; } set { state = value; } } public SecurityChangedEventArgs (SecurityLevel state) { this.state = state; } } public delegate void ContextMenuEventHandler (object sender, ContextMenuEventArgs e); public class ContextMenuEventArgs : EventArgs { private int x; private int y; public int X { get { return x; } } public int Y { get { return y; } } public ContextMenuEventArgs (int x, int y) { this.x = x; this.y = y; } } public delegate void NavigationRequestedEventHandler (object sender, NavigationRequestedEventArgs e); public class NavigationRequestedEventArgs : System.ComponentModel.CancelEventArgs { private string uri; public string Uri { get {return uri;} } public NavigationRequestedEventArgs (string uri) { this.uri = uri; } } #endregion }
edwinspire/VSharp
class/Mono.WebBrowser/Mono.WebBrowser/IWebBrowser.cs
C#
lgpl-3.0
10,333
<?php $lang['install']['flag'] = 'en'; //en $lang['install']['i001'] = 'KimsQ Rb Installation'; //KimsQ Rb 설치 $lang['install']['i002'] = 'Select the version'; //설치할 패키지를 선택해주세요. *** 사이트 패키지와 용어 혼동 $lang['install']['i003'] = 'Do not refresh this page. It will automatically move on to the next step after the downloading. The time of downloading depends on your network environment.';//다운로드 완료 후 자동으로 다음단계로 이동되니 새로고침 하지 마세요.네트웍 상태에 따라 다운로드에 수초가 소요될수 있습니다. $lang['install']['i004'] = 'Start Installation';//설치하기 *** 실제 설치는 모든 정보를 입력 후 이루어짐. 마지막 Next 버튼이 Install Now가 되어야 함. $lang['install']['i005'] = 'You can also install KimsQ Rb by uploading its files directly.'; //또는 패키지 파일을 업로드해 주세요. $lang['install']['i006'] = 'Browse a (zip) file'; //파일 찾기 *** zip 파일만 허용하는 경우 괄호 해제 $lang['install']['i007'] = 'KimsQ Installer'; //킴스큐 인스톨러 $lang['install']['i008'] = 'Agreement'; //사용조건 동의 $lang['install']['i009'] = 'Set Database'; //데이터베이스 $lang['install']['i010'] = 'Create Admin'; //사용자 등록 *** 사실상 일반 사용자가 아닌 관리자 계정이므로. Regist는 없는 단어. $lang['install']['i011'] = 'Create Site'; //사이트 생성 $lang['install']['i012'] = 'License Agreement'; //사용조건 동의 $lang['install']['i013'] = 'Open Source Software License'; //오픈소스 소프트웨어 라이선스 $lang['install']['i014'] = 'I agree to the license above.'; //위의 라이선스 정책에 동의 합니다. $lang['install']['i015'] = 'Database Information'; //'Database settings'; //데이터베이스 설정 *** DB를 설정하는 게 아님, 설정된 DB의 정보를 입력하는 것 $lang['install']['i016'] = 'Basic Info'; //기본정보 $lang['install']['i017'] = 'Advanced Options'; //고급옵션 $lang['install']['i018'] = 'DBMS'; //'DB kind'; //DB종류 (type) $lang['install']['i019'] = 'DB name'; //DB명 (name) $lang['install']['i020'] = 'Username'; //유저 (username) $lang['install']['i021'] = 'Password'; //암호 (password) $lang['install']['i022'] = 'Type your database information. Installation will be finished successfully only with the correct information.'; //데이터베이스(MySQL) 정보를 정확히 입력해 주십시오. 입력된 정보가 정확해야만 정상적으로 설치가 진행됩니다. *** 입력을 아무렇게나 해도 사실 next step으로는 갈 수 있음. 마지막에 설치가 안 될 뿐. 키보드로 입력하라고 할 때는 input은 어색, type이 자연스러움. $lang['install']['i023'] = 'DB Host'; //호스트 (Host) $lang['install']['i024'] = 'Change this if your DB is running on the remote server'; //데이터베이스가 다른 서버에 있다면 이 설정을 바꾸십시오. $lang['install']['i025'] = 'DB Port'; //포트 (Port) $lang['install']['i026'] = 'Change this if the port of your DB server is different'; //DB서버의 포트가 기본 포트가 아닐 경우 변경하십시오. $lang['install']['i027'] = 'Table Prefix'; //접두어 (Prefix) $lang['install']['i028'] = 'Change this if you want to install more than one KimsQ Rb on your server'; //단일 DB에 킴스큐 복수설치를 원하시면 변경해 주십시오. $lang['install']['i029'] = 'DB Engine'; //형식 (Engine) $lang['install']['i030'] = 'MyISAM is the basic engine'; //기본엔진은 MyISAM 입니다. $lang['install']['i031'] = 'These options are needed only for the specific cases. Do not change if you do not know what to do, or ask your hosting provider'; //이 선택사항은 일부 경우에만 필요합니다.무엇을 입력해야할지 모를경우 그대로 두거나 호스팅 제공자에게 문의하십시오. $lang['install']['i032'] = 'User Registration'; //사용자 등록 $lang['install']['i033'] = 'Basic Info'; //기본정보 $lang['install']['i034'] = 'Extra Info'; //추가정보 $lang['install']['i035'] = 'Name'; //이름 $lang['install']['i036'] = 'Email'; //이메일 $lang['install']['i037'] = 'ID (Username)'; //아이디 $lang['install']['i038'] = '4 to 12 lowercase letters or numbers'; //영문소문자+숫자 4~12자 이내 $lang['install']['i039'] = 'Password'; //패스워드 $lang['install']['i040'] = 'Retype'; //패스워드 확인 $lang['install']['i041'] = 'Nickname'; //닉네임 $lang['install']['i042'] = 'Sex'; //성별 $lang['install']['i043'] = 'Male'; //남성 $lang['install']['i044'] = 'Female'; //여성 *** 워드로 열어서 맞춤법 검사 정도는... $lang['install']['i045'] = 'Birthday'; //생년월일 $lang['install']['i046'] = 'Lunar'; //음력생일 $lang['install']['i047'] = 'Phone'; //연락처 $lang['install']['i048'] = 'Create an administrator account. You can add more detail in the profile page after installation.'; //입력된 정보로 신규 회원등록이 이루어지며 최고관리자 권한이 부여됩니다. 관리자 부가정보는 설치 후 프로필페이지 추가로 등록할 수 있습니다. $lang['install']['i049'] = 'Create a site'; //사이트 생성 $lang['install']['i050'] = 'Site Name'; //사이트명 $lang['install']['i051'] = 'Type the name of your first site'; //이 사이트의 명칭을 입력해 주세요. $lang['install']['i052'] = 'Site Code'; //사이트 코드 $lang['install']['i053'] = 'Site Code makes the site recognizable among multiple sites.'; //이 사이트를 구분하기 위한 코드입니다. *** 설치 후 사이트는 하나인데 others라고 하기엔 어색함. $lang['install']['i054'] = 'sitecode'; //사이트코드 $lang['install']['i055'] = 'Using Permalink'; //고유주소(Permalink) 사용 $lang['install']['i056'] = 'Check if you want to have shortened URLs. (PHP rewrite_mod necessarily loaded)'; //주소를 짧게 줄일 수 있습니다.(서버에서 rewrite_mod 허용시) $lang['install']['i057'] = 'This is the last step. After installation, you can create a navigation bar and pages, or apply a site package to build your own website at once.'; //사이트명 입력 후 다음버튼을 클릭하면 킴스큐 설치가 진행됩니다.설치가 완료된 후에는 메뉴와 페이지를 만들거나 사이트 패키지를 이용하세요. $lang['install']['i058'] = 'Previous'; //이전 $lang['install']['i059'] = 'Next'; //다음 *** 마지막 Next 버튼은 Install Now가 되어야 함. $lang['install']['i060'] = 'Install this version?'; //정말로 선택하신 버젼을 설치하시겠습니까? $lang['install']['i061'] = 'Connecting to KimsQ Rb server...'; //KimsQ Rb 다운로드중.. *** 실제 다운로드 메시지는 i062 $lang['install']['i062'] = 'Now downloading from the server...'; //서버에서 다운로드 받고 있습니다... $lang['install']['i063'] = 'We are sorry. The selected version is not available now.'; //죄송합니다. 선택하신 버젼은 아직 다운로드 받으실 수 없습니다. $lang['install']['i064'] = 'We are sorry. The selected file is not KimsQ Rb.'; //죄송합니다. 킴스큐 패키지가 아닙니다. $lang['install']['i065'] = 'You do not have proper permissions for the destination folder.\nTry again after changing the permission to 707'; //설치폴더의 쓰기권한이 없습니다.\n퍼미션을 707로 변경 후 다시 시도해 주세요. $lang['install']['i066'] = 'Uploading KimsQ Rb...'; //KimsQ Rb 업로드중.. *** 말줄임표 $lang['install']['i067'] = 'Unzipping installation file on the server...'; //서버에서 패키지 압축을 풀고 있습니다... *** 사이트 패키지와 혼동 $lang['install']['i068'] = 'DB Host is required.'; //DB호스트를 입력해 주세요. $lang['install']['i069'] = 'DB Name is required.'; //DB명을 입력해 주세요. $lang['install']['i070'] = 'DB Username is required.'; //DB사용자를 입력해 주세요. $lang['install']['i071'] = 'DB Password is required.'; //DB 패스워드를 입력해 주세요. $lang['install']['i072'] = 'DB Port number is required'; //DB 포트번호를 입력해 주세요. $lang['install']['i073'] = 'Table Prefix is required and cannot be empty'; //DB 접두어를 정확히 입력해 주세요. $lang['install']['i074'] = 'Administrator account`s name is required.'; //이름을 입력해 주세요. $lang['install']['i075'] = 'Administrator`s email address is required.'; //이메일주소를 정확히 입력해 주세요. $lang['install']['i076'] = 'Administrator`s id is required.'; //아이디를 정확히 입력해 주세요. $lang['install']['i077'] = 'Administrator`s password is required.'; //패스워드를 입력해 주세요. $lang['install']['i078'] = 'Fill the both of two blanks for Administrator`s password.'; //패스워드를 다시한번 입력해 주세요. *** 두번째 패스워드 칸이 비었을 경우, 그냥 다시 입력하라는 설명은 너무 모호함 $lang['install']['i079'] = 'The both passwords are not identical.'; //패스워드가 일치하지 않습니다. $lang['install']['i080'] = 'Installing KimsQ Rb now. Please wait a second.'; //설치중입니다. 잠시만 기다려 주세요. $lang['install']['i081'] = 'Type Site Name, please.'; //사이트명을 입력해 주세요. $lang['install']['i082'] = 'Type Site Code, please.'; //사이트 코드를 정확히 입력해 주세요. $lang['install']['i083'] = 'Start the installation with the typed information?'; //정말로 설치하시겠습니까? ?>
kieregh/rb
_install/language/english/lang.install.php
PHP
lgpl-3.0
9,586
/* * Copyright (C) 2014-2015 Vote Rewarding System * * This file is part of Vote Rewarding System. * * Vote Rewarding System 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. * * Vote Rewarding System is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.github.unafraid.votingreward.interfaceprovider.model; /** * @author UnAfraid */ public class RewardItemHolder { private final int _id; private final long _count; public RewardItemHolder(int id, long count) { _id = id; _count = count; } /** * @return the ID of the item contained in this object */ public int getId() { return _id; } /** * @return the count of items contained in this object */ public long getCount() { return _count; } }
UnAfraid/topzone
VotingRewardInterfaceProvider/src/main/java/com/github/unafraid/votingreward/interfaceprovider/model/RewardItemHolder.java
Java
lgpl-3.0
1,261
<?php /** * Class shopMigrateStorelandruTransport * @title StoreLand ru * @description Перенос данных из магазинов на платформе StoreLand.ru посредством YML файла * @group YML */ class shopMigrateStorelandruTransport extends shopMigrateYmlTransport { }
Amethyst-web/vinst
wa-apps/shop/plugins/migrate/lib/transport/shopMigrateStorelandruTransport.class.php
PHP
lgpl-3.0
311
""" Classes for interacting with the tor control socket. Controllers are a wrapper around a ControlSocket, retaining many of its methods (connect, close, is_alive, etc) in addition to providing its own for interacting at a higher level. **Module Overview:** :: from_port - Provides a Controller based on a port connection. from_socket_file - Provides a Controller based on a socket file connection. Controller - General controller class intended for direct use. +- get_info - issues a GETINFO query BaseController - Base controller class asynchronous message handling. |- msg - communicates with the tor process |- is_alive - reports if our connection to tor is open or closed |- connect - connects or reconnects to tor |- close - shuts down our connection to the tor process |- get_socket - provides the socket used for control communication |- add_status_listener - notifies a callback of changes in our status |- remove_status_listener - prevents further notification of status changes +- __enter__ / __exit__ - manages socket connection """ import time import Queue import threading import stem.response import stem.socket import stem.util.log as log # state changes a control socket can have # INIT - new control connection # RESET - received a reset/sighup signal # CLOSED - control connection closed State = stem.util.enum.Enum("INIT", "RESET", "CLOSED") # Constant to indicate an undefined argument default. Usually we'd use None for # this, but users will commonly provide None as the argument so need something # else fairly unique... UNDEFINED = "<Undefined_ >" class BaseController: """ Controller for the tor process. This is a minimal base class for other controllers, providing basic process communication and event listing. Don't use this directly - subclasses like the Controller provide higher level functionality. Do not continue to directly interacte with the ControlSocket we're constructed from - use our wrapper methods instead. """ def __init__(self, control_socket): self._socket = control_socket self._msg_lock = threading.RLock() self._status_listeners = [] # tuples of the form (callback, spawn_thread) self._status_listeners_lock = threading.RLock() # queues where incoming messages are directed self._reply_queue = Queue.Queue() self._event_queue = Queue.Queue() # thread to continually pull from the control socket self._reader_thread = None # thread to pull from the _event_queue and call handle_event self._event_notice = threading.Event() self._event_thread = None # saves our socket's prior _connect() and _close() methods so they can be # called along with ours self._socket_connect = self._socket._connect self._socket_close = self._socket._close self._socket._connect = self._connect self._socket._close = self._close if self._socket.is_alive(): self._launch_threads() def msg(self, message): """ Sends a message to our control socket and provides back its reply. :param str message: message to be formatted and sent to tor :returns: :class:`stem.response.ControlMessage` with the response :raises: * :class:`stem.socket.ProtocolError` the content from the socket is malformed * :class:`stem.socket.SocketError` if a problem arises in using the socket * :class:`stem.socket.SocketClosed` if the socket is shut down """ with self._msg_lock: # If our _reply_queue isn't empty then one of a few things happened... # # - Our connection was closed and probably re-restablished. This was # in reply to pulling for an asynchronous event and getting this is # expected - ignore it. # # - Pulling for asynchronous events produced an error. If this was a # ProtocolError then it's a tor bug, and if a non-closure SocketError # then it was probably a socket glitch. Deserves an INFO level log # message. # # - This is a leftover response for a msg() call. We can't tell who an # exception was airmarked for, so we only know that this was the case # if it's a ControlMessage. This should not be possable and indicates # a stem bug. This deserves a NOTICE level log message since it # indicates that one of our callers didn't get their reply. while not self._reply_queue.empty(): try: response = self._reply_queue.get_nowait() if isinstance(response, stem.socket.SocketClosed): pass # this is fine elif isinstance(response, stem.socket.ProtocolError): log.info("Tor provided a malformed message (%s)" % response) elif isinstance(response, stem.socket.ControllerError): log.info("Socket experienced a problem (%s)" % response) elif isinstance(response, stem.response.ControlMessage): log.notice("BUG: the msg() function failed to deliver a response: %s" % response) except Queue.Empty: # the empty() method is documented to not be fully reliable so this # isn't entirely surprising break try: self._socket.send(message) response = self._reply_queue.get() # If the message we received back had an exception then re-raise it to the # caller. Otherwise return the response. if isinstance(response, stem.socket.ControllerError): raise response else: return response except stem.socket.SocketClosed, exc: # If the recv() thread caused the SocketClosed then we could still be # in the process of closing. Calling close() here so that we can # provide an assurance to the caller that when we raise a SocketClosed # exception we are shut down afterward for realz. self.close() raise exc def is_alive(self): """ Checks if our socket is currently connected. This is a passthrough for our socket's is_alive() method. :returns: bool that's True if we're shut down and False otherwise """ return self._socket.is_alive() def connect(self): """ Reconnects our control socket. This is a passthrough for our socket's connect() method. :raises: :class:`stem.socket.SocketError` if unable to make a socket """ self._socket.connect() def close(self): """ Closes our socket connection. This is a passthrough for our socket's :func:`stem.socket.ControlSocket.close` method. """ self._socket.close() def get_socket(self): """ Provides the socket used to speak with the tor process. Communicating with the socket directly isn't advised since it may confuse the controller. :returns: :class:`stem.socket.ControlSocket` we're communicating with """ return self._socket def add_status_listener(self, callback, spawn = True): """ Notifies a given function when the state of our socket changes. Functions are expected to be of the form... :: my_function(controller, state, timestamp) The state is a value from stem.socket.State, functions **must** allow for new values in this field. The timestamp is a float for the unix time when the change occured. This class only provides ``State.INIT`` and ``State.CLOSED`` notifications. Subclasses may provide others. If spawn is True then the callback is notified via a new daemon thread. If false then the notice is under our locks, within the thread where the change occured. In general this isn't advised, especially if your callback could block for a while. :param function callback: function to be notified when our state changes :param bool spawn: calls function via a new thread if True, otherwise it's part of the connect/close method call """ with self._status_listeners_lock: self._status_listeners.append((callback, spawn)) def remove_status_listener(self, callback): """ Stops listener from being notified of further events. :param function callback: function to be removed from our listeners :returns: bool that's True if we removed one or more occurances of the callback, False otherwise """ with self._status_listeners_lock: new_listeners, is_changed = [], False for listener, spawn in self._status_listeners: if listener != callback: new_listeners.append((listener, spawn)) else: is_changed = True self._status_listeners = new_listeners return is_changed def __enter__(self): return self def __exit__(self, exit_type, value, traceback): self.close() def _handle_event(self, event_message): """ Callback to be overwritten by subclasses for event listening. This is notified whenever we receive an event from the control socket. :param stem.response.ControlMessage event_message: message received from the control socket """ pass def _connect(self): self._launch_threads() self._notify_status_listeners(State.INIT, True) self._socket_connect() def _close(self): # Our is_alive() state is now false. Our reader thread should already be # awake from recv() raising a closure exception. Wake up the event thread # too so it can end. self._event_notice.set() # joins on our threads if it's safe to do so for t in (self._reader_thread, self._event_thread): if t and t.is_alive() and threading.current_thread() != t: t.join() self._notify_status_listeners(State.CLOSED, False) self._socket_close() def _notify_status_listeners(self, state, expect_alive = None): """ Informs our status listeners that a state change occured. States imply that our socket is either alive or not, which may not hold true when multiple events occure in quick succession. For instance, a sighup could cause two events (``State.RESET`` for the sighup and ``State.CLOSE`` if it causes tor to crash). However, there's no guarentee of the order in which they occure, and it would be bad if listeners got the ``State.RESET`` last, implying that we were alive. If set, the expect_alive flag will discard our event if it conflicts with our current :func:`stem.control.BaseController.is_alive` state. :param stem.socket.State state: state change that has occured :param bool expect_alive: discard event if it conflicts with our :func:`stem.control.BaseController.is_alive` state """ # Any changes to our is_alive() state happen under the send lock, so we # need to have it to ensure it doesn't change beneath us. with self._socket._get_send_lock(), self._status_listeners_lock: change_timestamp = time.time() if expect_alive != None and expect_alive != self.is_alive(): return for listener, spawn in self._status_listeners: if spawn: name = "%s notification" % state args = (self, state, change_timestamp) notice_thread = threading.Thread(target = listener, args = args, name = name) notice_thread.setDaemon(True) notice_thread.start() else: listener(self, state, change_timestamp) def _launch_threads(self): """ Initializes daemon threads. Threads can't be reused so we need to recreate them if we're restarted. """ # In theory concurrent calls could result in multple start() calls on a # single thread, which would cause an unexpeceted exception. Best be safe. with self._socket._get_send_lock(): if not self._reader_thread or not self._reader_thread.is_alive(): self._reader_thread = threading.Thread(target = self._reader_loop, name = "Tor Listener") self._reader_thread.setDaemon(True) self._reader_thread.start() if not self._event_thread or not self._event_thread.is_alive(): self._event_thread = threading.Thread(target = self._event_loop, name = "Event Notifier") self._event_thread.setDaemon(True) self._event_thread.start() def _reader_loop(self): """ Continually pulls from the control socket, directing the messages into queues based on their type. Controller messages come in two varieties... * Responses to messages we've sent (GETINFO, SETCONF, etc). * Asynchronous events, identified by a status code of 650. """ while self.is_alive(): try: control_message = self._socket.recv() if control_message.content()[-1][0] == "650": # asynchronous message, adds to the event queue and wakes up its handler self._event_queue.put(control_message) self._event_notice.set() else: # response to a msg() call self._reply_queue.put(control_message) except stem.socket.ControllerError, exc: # Assume that all exceptions belong to the reader. This isn't always # true, but the msg() call can do a better job of sorting it out. # # Be aware that the msg() method relies on this to unblock callers. self._reply_queue.put(exc) def _event_loop(self): """ Continually pulls messages from the _event_queue and sends them to our handle_event callback. This is done via its own thread so subclasses with a lengthy handle_event implementation don't block further reading from the socket. """ while True: try: event_message = self._event_queue.get_nowait() self._handle_event(event_message) except Queue.Empty: if not self.is_alive(): break self._event_notice.wait() self._event_notice.clear() class Controller(BaseController): """ Communicates with a control socket. This is built on top of the BaseController and provides a more user friendly API for library users. """ def from_port(control_addr = "127.0.0.1", control_port = 9051): """ Constructs a ControlPort based Controller. :param str control_addr: ip address of the controller :param int control_port: port number of the controller :returns: :class:`stem.control.Controller` attached to the given port :raises: :class:`stem.socket.SocketError` if we're unable to establish a connection """ control_port = stem.socket.ControlPort(control_addr, control_port) return Controller(control_port) def from_socket_file(socket_path = "/var/run/tor/control"): """ Constructs a ControlSocketFile based Controller. :param str socket_path: path where the control socket is located :returns: :class:`stem.control.Controller` attached to the given socket file :raises: :class:`stem.socket.SocketError` if we're unable to establish a connection """ control_socket = stem.socket.ControlSocketFile(socket_path) return Controller(control_socket) from_port = staticmethod(from_port) from_socket_file = staticmethod(from_socket_file) def get_info(self, param, default = UNDEFINED): """ Queries the control socket for the given GETINFO option. If provided a default then that's returned if the GETINFO option is undefined or the call fails for any reason (error response, control port closed, initiated, etc). :param str,list param: GETINFO option or options to be queried :param object default: response if the query fails :returns: Response depends upon how we were called as follows... * str with the response if our param was a str * dict with the param => response mapping if our param was a list * default if one was provided and our call failed :raises: :class:`stem.socket.ControllerError` if the call fails, and we weren't provided a default response """ # TODO: add caching? # TODO: special geoip handling? # TODO: add logging, including call runtime if isinstance(param, str): is_multiple = False param = [param] else: is_multiple = True try: response = self.msg("GETINFO %s" % " ".join(param)) stem.response.convert("GETINFO", response) # error if we got back different parameters than we requested requested_params = set(param) reply_params = set(response.entries.keys()) if requested_params != reply_params: requested_label = ", ".join(requested_params) reply_label = ", ".join(reply_params) raise stem.socket.ProtocolError("GETINFO reply doesn't match the parameters that we requested. Queried '%s' but got '%s'." % (requested_label, reply_label)) if is_multiple: return response.entries else: return response.entries[param[0]] except stem.socket.ControllerError, exc: if default == UNDEFINED: raise exc else: return default
meganchang/Stem
stem/control.py
Python
lgpl-3.0
17,273
//*************************************************** //* This file was generated by tool //* SharpKit //* At: 29/08/2012 03:59:41 p.m. //*************************************************** using SharpKit.JavaScript; namespace Ext.grid.property { #region Store /// <inheritdocs /> /// <summary> /// <p>A custom <see cref="Ext.data.Store">Ext.data.Store</see> for the <see cref="Ext.grid.property.Grid">Ext.grid.property.Grid</see>. This class handles the mapping /// between the custom data source objects supported by the grid and the <see cref="Ext.grid.property.Property">Ext.grid.property.Property</see> format /// used by the <see cref="Ext.data.Store">Ext.data.Store</see> base class.</p> /// </summary> [JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)] public partial class Store : Ext.data.Store { /// <summary> /// Creates new property store. /// </summary> /// <param name="grid"><p>The grid this store will be bound to</p> /// </param> /// <param name="source"><p>The source data config object</p> /// </param> /// <returns> /// <span><see cref="Object">Object</see></span><div> /// </div> /// </returns> public Store(Ext.grid.Panel grid, object source){} public Store(Ext.grid.property.StoreConfig config){} public Store(){} public Store(params object[] args){} } #endregion #region StoreConfig /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class StoreConfig : Ext.data.StoreConfig { public StoreConfig(params object[] args){} } #endregion #region StoreEvents /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class StoreEvents : Ext.data.StoreEvents { public StoreEvents(params object[] args){} } #endregion }
hultqvist/SharpKit-SDK
Defs/ExtJs/Ext.grid.property.Store.cs
C#
lgpl-3.0
1,987
// // System.Net.Configuration.HttpCachePolicyElement.cs // // Authors: // Tim Coleman (tim@timcoleman.com) // Chris Toshok (toshok@ximian.com) // // Copyright (C) Tim Coleman, 2004 // (C) 2004,2005 Novell, Inc. (http://www.novell.com) // // // 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. // #if CONFIGURATION_DEP using System; using System.Configuration; using System.Net.Cache; using System.Xml; namespace System.Net.Configuration { public sealed class HttpCachePolicyElement : ConfigurationElement { #region Fields static ConfigurationProperty maximumAgeProp; static ConfigurationProperty maximumStaleProp; static ConfigurationProperty minimumFreshProp; static ConfigurationProperty policyLevelProp; static ConfigurationPropertyCollection properties; #endregion // Fields #region Constructors static HttpCachePolicyElement () { maximumAgeProp = new ConfigurationProperty ("maximumAge", typeof (TimeSpan), TimeSpan.MaxValue); maximumStaleProp = new ConfigurationProperty ("maximumStale", typeof (TimeSpan), TimeSpan.MinValue); minimumFreshProp = new ConfigurationProperty ("minimumFresh", typeof (TimeSpan), TimeSpan.MinValue); policyLevelProp = new ConfigurationProperty ("policyLevel", typeof (HttpRequestCacheLevel), HttpRequestCacheLevel.Default, ConfigurationPropertyOptions.IsRequired); properties = new ConfigurationPropertyCollection (); properties.Add (maximumAgeProp); properties.Add (maximumStaleProp); properties.Add (minimumFreshProp); properties.Add (policyLevelProp); } public HttpCachePolicyElement () { } #endregion // Constructors #region Properties [ConfigurationProperty ("maximumAge", DefaultValue = "10675199.02:48:05.4775807")] public TimeSpan MaximumAge { get { return (TimeSpan) base [maximumAgeProp]; } set { base [maximumAgeProp] = value; } } [ConfigurationProperty ("maximumStale", DefaultValue = "-10675199.02:48:05.4775808")] public TimeSpan MaximumStale { get { return (TimeSpan) base [maximumStaleProp]; } set { base [maximumStaleProp] = value; } } [ConfigurationProperty ("minimumFresh", DefaultValue = "-10675199.02:48:05.4775808")] public TimeSpan MinimumFresh { get { return (TimeSpan) base [minimumFreshProp]; } set { base [minimumFreshProp] = value; } } [ConfigurationProperty ("policyLevel", DefaultValue = "Default", Options = ConfigurationPropertyOptions.IsRequired)] public HttpRequestCacheLevel PolicyLevel { get { return (HttpRequestCacheLevel) base [policyLevelProp]; } set { base [policyLevelProp] = value; } } protected override ConfigurationPropertyCollection Properties { get { return properties; } } #endregion // Properties #region Methods [MonoTODO] protected override void DeserializeElement (XmlReader reader, bool serializeCollectionKey) { throw new NotImplementedException (); } [MonoTODO] protected override void Reset (ConfigurationElement parentElement) { throw new NotImplementedException (); } #endregion // Methods } } #endif
edwinspire/VSharp
class/System/System.Net.Configuration/HttpCachePolicyElement.cs
C#
lgpl-3.0
4,102
/* ========================================================================= * This file is part of xml.lite-c++ * ========================================================================= * * (C) Copyright 2004 - 2014, MDA Information Systems LLC * (C) Copyright 2022, Maxar Technologies, Inc. * * xml.lite-c++ 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. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; If not, * see <http://www.gnu.org/licenses/>. * */ #include <xml/lite/ValidatorInterface.h> #include <algorithm> #include <iterator> #include <std/filesystem> #include <std/memory> #include <sys/OS.h> #include <io/StringStream.h> #include <mem/ScopedArray.h> #include <str/EncodedStringView.h> namespace fs = std::filesystem; #include <xml/lite/xml_lite_config.h> template<typename TStringStream> bool vallidate_(const xml::lite::ValidatorInterface& validator, io::InputStream& xml, TStringStream&& oss, const std::string& xmlID, std::vector<xml::lite::ValidationInfo>& errors) { xml.streamTo(oss); return validator.validate(oss.stream().str(), xmlID, errors); } bool xml::lite::ValidatorInterface::validate( io::InputStream& xml, StringEncoding encoding, const std::string& xmlID, std::vector<ValidationInfo>& errors) const { // convert to the correcrt std::basic_string<T> based on "encoding" if (encoding == StringEncoding::Utf8) { return vallidate_(*this, xml, io::U8StringStream(), xmlID, errors); } if (encoding == StringEncoding::Windows1252) { return vallidate_(*this, xml, io::W1252StringStream(), xmlID, errors); } // this really shouldn't happen return validate(xml, xmlID, errors); }
mdaus/coda-oss
modules/c++/xml.lite/source/ValidatorInterface.cpp
C++
lgpl-3.0
2,255
// System.Net.Sockets.SocketAsyncEventArgs.cs // // Authors: // Marek Habersack (mhabersack@novell.com) // // Copyright (c) 2008 Novell, Inc. (http://www.novell.com) // // // 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. // using System; namespace System.Net.Sockets { public class SendPacketsElement { public byte[] Buffer { get; private set; } public int Count { get; private set; } public bool EndOfPacket { get; private set; } public string FilePath { get; private set; } public int Offset { get; private set; } public SendPacketsElement (byte[] buffer) : this (buffer, 0, buffer != null ? buffer.Length : 0) { } public SendPacketsElement (byte[] buffer, int offset, int count) : this (buffer, offset, count, false) { } public SendPacketsElement (byte[] buffer, int offset, int count, bool endOfPacket) { if (buffer == null) throw new ArgumentNullException ("buffer"); int buflen = buffer.Length; if (offset < 0 || offset >= buflen) throw new ArgumentOutOfRangeException ("offset"); if (count < 0 || offset + count >= buflen) throw new ArgumentOutOfRangeException ("count"); Buffer = buffer; Offset = offset; Count = count; EndOfPacket = endOfPacket; FilePath = null; } public SendPacketsElement (string filepath) : this (filepath, 0, 0, false) { } public SendPacketsElement (string filepath, int offset, int count) : this (filepath, offset, count, false) { } // LAME SPEC: only ArgumentNullException for filepath is thrown public SendPacketsElement (string filepath, int offset, int count, bool endOfPacket) { if (filepath == null) throw new ArgumentNullException ("filepath"); Buffer = null; Offset = offset; Count = count; EndOfPacket = endOfPacket; FilePath = filepath; } } }
edwinspire/VSharp
class/System/System.Net.Sockets/SendPacketsElement.cs
C#
lgpl-3.0
2,838
// Authors: // Francis Fisher (frankie@terrorise.me.uk) // // (C) Francis Fisher 2013 // // 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. namespace System.Windows.Forms.DataVisualization.Charting { public class CustomizeLegendEventArgs : EventArgs { public LegendItemsCollection LegendItems { get; private set; } public string LegendName { get; private set; } } }
edwinspire/VSharp
class/System.Windows.Forms.DataVisualization/System.Windows.Forms.DataVisualization.Charting/CustomizeLegendEventArgs.cs
C#
lgpl-3.0
1,400
function main() { // Widget instantiation metadata... var widget = { id: "UploaderPlusAdmin", name: "SoftwareLoop.UploaderPlusAdmin", }; model.widgets = [widget]; } main();
sprouvez/uploader-plus
surf/src/main/amp/config/alfresco/web-extension/site-webscripts/uploader-plus/uploader-plus-admin.get.js
JavaScript
lgpl-3.0
204
# encoding: utf-8 """ Utilities for working with strings and text. """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import __main__ import os import re import shutil import sys import textwrap from string import Formatter from IPython.external.path import path from IPython.testing.skipdoctest import skip_doctest_py3, skip_doctest from IPython.utils import py3compat from IPython.utils.io import nlprint from IPython.utils.data import flatten #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- def unquote_ends(istr): """Remove a single pair of quotes from the endpoints of a string.""" if not istr: return istr if (istr[0]=="'" and istr[-1]=="'") or \ (istr[0]=='"' and istr[-1]=='"'): return istr[1:-1] else: return istr class LSString(str): """String derivative with a special access attributes. These are normal strings, but with the special attributes: .l (or .list) : value as list (split on newlines). .n (or .nlstr): original value (the string itself). .s (or .spstr): value as whitespace-separated string. .p (or .paths): list of path objects Any values which require transformations are computed only once and cached. Such strings are very useful to efficiently interact with the shell, which typically only understands whitespace-separated options for commands.""" def get_list(self): try: return self.__list except AttributeError: self.__list = self.split('\n') return self.__list l = list = property(get_list) def get_spstr(self): try: return self.__spstr except AttributeError: self.__spstr = self.replace('\n',' ') return self.__spstr s = spstr = property(get_spstr) def get_nlstr(self): return self n = nlstr = property(get_nlstr) def get_paths(self): try: return self.__paths except AttributeError: self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] return self.__paths p = paths = property(get_paths) # FIXME: We need to reimplement type specific displayhook and then add this # back as a custom printer. This should also be moved outside utils into the # core. # def print_lsstring(arg): # """ Prettier (non-repr-like) and more informative printer for LSString """ # print "LSString (.p, .n, .l, .s available). Value:" # print arg # # # print_lsstring = result_display.when_type(LSString)(print_lsstring) class SList(list): """List derivative with a special access attributes. These are normal lists, but with the special attributes: .l (or .list) : value as list (the list itself). .n (or .nlstr): value as a string, joined on newlines. .s (or .spstr): value as a string, joined on spaces. .p (or .paths): list of path objects Any values which require transformations are computed only once and cached.""" def get_list(self): return self l = list = property(get_list) def get_spstr(self): try: return self.__spstr except AttributeError: self.__spstr = ' '.join(self) return self.__spstr s = spstr = property(get_spstr) def get_nlstr(self): try: return self.__nlstr except AttributeError: self.__nlstr = '\n'.join(self) return self.__nlstr n = nlstr = property(get_nlstr) def get_paths(self): try: return self.__paths except AttributeError: self.__paths = [path(p) for p in self if os.path.exists(p)] return self.__paths p = paths = property(get_paths) def grep(self, pattern, prune = False, field = None): """ Return all strings matching 'pattern' (a regex or callable) This is case-insensitive. If prune is true, return all items NOT matching the pattern. If field is specified, the match must occur in the specified whitespace-separated field. Examples:: a.grep( lambda x: x.startswith('C') ) a.grep('Cha.*log', prune=1) a.grep('chm', field=-1) """ def match_target(s): if field is None: return s parts = s.split() try: tgt = parts[field] return tgt except IndexError: return "" if isinstance(pattern, basestring): pred = lambda x : re.search(pattern, x, re.IGNORECASE) else: pred = pattern if not prune: return SList([el for el in self if pred(match_target(el))]) else: return SList([el for el in self if not pred(match_target(el))]) def fields(self, *fields): """ Collect whitespace-separated fields from string list Allows quick awk-like usage of string lists. Example data (in var a, created by 'a = !ls -l'):: -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+'] a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+'] (note the joining by space). a.fields(-1) is ['ChangeLog', 'IPython'] IndexErrors are ignored. Without args, fields() just split()'s the strings. """ if len(fields) == 0: return [el.split() for el in self] res = SList() for el in [f.split() for f in self]: lineparts = [] for fd in fields: try: lineparts.append(el[fd]) except IndexError: pass if lineparts: res.append(" ".join(lineparts)) return res def sort(self,field= None, nums = False): """ sort by specified fields (see fields()) Example:: a.sort(1, nums = True) Sorts a by second field, in numerical order (so that 21 > 3) """ #decorate, sort, undecorate if field is not None: dsu = [[SList([line]).fields(field), line] for line in self] else: dsu = [[line, line] for line in self] if nums: for i in range(len(dsu)): numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()]) try: n = int(numstr) except ValueError: n = 0; dsu[i][0] = n dsu.sort() return SList([t[1] for t in dsu]) # FIXME: We need to reimplement type specific displayhook and then add this # back as a custom printer. This should also be moved outside utils into the # core. # def print_slist(arg): # """ Prettier (non-repr-like) and more informative printer for SList """ # print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):" # if hasattr(arg, 'hideonce') and arg.hideonce: # arg.hideonce = False # return # # nlprint(arg) # # print_slist = result_display.when_type(SList)(print_slist) def esc_quotes(strng): """Return the input string with single and double quotes escaped out""" return strng.replace('"','\\"').replace("'","\\'") def qw(words,flat=0,sep=None,maxsplit=-1): """Similar to Perl's qw() operator, but with some more options. qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit) words can also be a list itself, and with flat=1, the output will be recursively flattened. Examples: >>> qw('1 2') ['1', '2'] >>> qw(['a b','1 2',['m n','p q']]) [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]] >>> qw(['a b','1 2',['m n','p q']],flat=1) ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """ if isinstance(words, basestring): return [word.strip() for word in words.split(sep,maxsplit) if word and not word.isspace() ] if flat: return flatten(map(qw,words,[1]*len(words))) return map(qw,words) def qwflat(words,sep=None,maxsplit=-1): """Calls qw(words) in flat mode. It's just a convenient shorthand.""" return qw(words,1,sep,maxsplit) def qw_lol(indata): """qw_lol('a b') -> [['a','b']], otherwise it's just a call to qw(). We need this to make sure the modules_some keys *always* end up as a list of lists.""" if isinstance(indata, basestring): return [qw(indata)] else: return qw(indata) def grep(pat,list,case=1): """Simple minded grep-like function. grep(pat,list) returns occurrences of pat in list, None on failure. It only does simple string matching, with no support for regexps. Use the option case=0 for case-insensitive matching.""" # This is pretty crude. At least it should implement copying only references # to the original data in case it's big. Now it copies the data for output. out=[] if case: for term in list: if term.find(pat)>-1: out.append(term) else: lpat=pat.lower() for term in list: if term.lower().find(lpat)>-1: out.append(term) if len(out): return out else: return None def dgrep(pat,*opts): """Return grep() on dir()+dir(__builtins__). A very common use of grep() when working interactively.""" return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts) def idgrep(pat): """Case-insensitive dgrep()""" return dgrep(pat,0) def igrep(pat,list): """Synonym for case-insensitive grep.""" return grep(pat,list,case=0) def indent(instr,nspaces=4, ntabs=0, flatten=False): """Indent a string a given number of spaces or tabstops. indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. Parameters ---------- instr : basestring The string to be indented. nspaces : int (default: 4) The number of spaces to be indented. ntabs : int (default: 0) The number of tabs to be indented. flatten : bool (default: False) Whether to scrub existing indentation. If True, all lines will be aligned to the same indentation. If False, existing indentation will be strictly increased. Returns ------- str|unicode : string indented by ntabs and nspaces. """ if instr is None: return ind = '\t'*ntabs+' '*nspaces if flatten: pat = re.compile(r'^\s*', re.MULTILINE) else: pat = re.compile(r'^', re.MULTILINE) outstr = re.sub(pat, ind, instr) if outstr.endswith(os.linesep+ind): return outstr[:-len(ind)] else: return outstr def native_line_ends(filename,backup=1): """Convert (in-place) a file to line-ends native to the current OS. If the optional backup argument is given as false, no backup of the original file is left. """ backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'} bak_filename = filename + backup_suffixes[os.name] original = open(filename).read() shutil.copy2(filename,bak_filename) try: new = open(filename,'wb') new.write(os.linesep.join(original.splitlines())) new.write(os.linesep) # ALWAYS put an eol at the end of the file new.close() except: os.rename(bak_filename,filename) if not backup: try: os.remove(bak_filename) except: pass def list_strings(arg): """Always return a list of strings, given a string or list of strings as input. :Examples: In [7]: list_strings('A single string') Out[7]: ['A single string'] In [8]: list_strings(['A single string in a list']) Out[8]: ['A single string in a list'] In [9]: list_strings(['A','list','of','strings']) Out[9]: ['A', 'list', 'of', 'strings'] """ if isinstance(arg,basestring): return [arg] else: return arg def marquee(txt='',width=78,mark='*'): """Return the input string centered in a 'marquee'. :Examples: In [16]: marquee('A test',40) Out[16]: '**************** A test ****************' In [17]: marquee('A test',40,'-') Out[17]: '---------------- A test ----------------' In [18]: marquee('A test',40,' ') Out[18]: ' A test ' """ if not txt: return (mark*width)[:width] nmark = (width-len(txt)-2)//len(mark)//2 if nmark < 0: nmark =0 marks = mark*nmark return '%s %s %s' % (marks,txt,marks) ini_spaces_re = re.compile(r'^(\s+)') def num_ini_spaces(strng): """Return the number of initial spaces in a string""" ini_spaces = ini_spaces_re.match(strng) if ini_spaces: return ini_spaces.end() else: return 0 def format_screen(strng): """Format a string for screen printing. This removes some latex-type format codes.""" # Paragraph continue par_re = re.compile(r'\\$',re.MULTILINE) strng = par_re.sub('',strng) return strng def dedent(text): """Equivalent of textwrap.dedent that ignores unindented first line. This means it will still dedent strings like: '''foo is a bar ''' For use in wrap_paragraphs. """ if text.startswith('\n'): # text starts with blank line, don't ignore the first line return textwrap.dedent(text) # split first line splits = text.split('\n',1) if len(splits) == 1: # only one line return textwrap.dedent(text) first, rest = splits # dedent everything but the first line rest = textwrap.dedent(rest) return '\n'.join([first, rest]) def wrap_paragraphs(text, ncols=80): """Wrap multiple paragraphs to fit a specified width. This is equivalent to textwrap.wrap, but with support for multiple paragraphs, as separated by empty lines. Returns ------- list of complete paragraphs, wrapped to fill `ncols` columns. """ paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE) text = dedent(text).strip() paragraphs = paragraph_re.split(text)[::2] # every other entry is space out_ps = [] indent_re = re.compile(r'\n\s+', re.MULTILINE) for p in paragraphs: # presume indentation that survives dedent is meaningful formatting, # so don't fill unless text is flush. if indent_re.search(p) is None: # wrap paragraph p = textwrap.fill(p, ncols) out_ps.append(p) return out_ps def long_substr(data): """Return the longest common substring in a list of strings. Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python """ substr = '' if len(data) > 1 and len(data[0]) > 0: for i in range(len(data[0])): for j in range(len(data[0])-i+1): if j > len(substr) and all(data[0][i:i+j] in x for x in data): substr = data[0][i:i+j] elif len(data) == 1: substr = data[0] return substr def strip_email_quotes(text): """Strip leading email quotation characters ('>'). Removes any combination of leading '>' interspersed with whitespace that appears *identically* in all lines of the input text. Parameters ---------- text : str Examples -------- Simple uses:: In [2]: strip_email_quotes('> > text') Out[2]: 'text' In [3]: strip_email_quotes('> > text\\n> > more') Out[3]: 'text\\nmore' Note how only the common prefix that appears in all lines is stripped:: In [4]: strip_email_quotes('> > text\\n> > more\\n> more...') Out[4]: '> text\\n> more\\nmore...' So if any line has no quote marks ('>') , then none are stripped from any of them :: In [5]: strip_email_quotes('> > text\\n> > more\\nlast different') Out[5]: '> > text\\n> > more\\nlast different' """ lines = text.splitlines() matches = set() for line in lines: prefix = re.match(r'^(\s*>[ >]*)', line) if prefix: matches.add(prefix.group(1)) else: break else: prefix = long_substr(list(matches)) if prefix: strip = len(prefix) text = '\n'.join([ ln[strip:] for ln in lines]) return text class EvalFormatter(Formatter): """A String Formatter that allows evaluation of simple expressions. Note that this version interprets a : as specifying a format string (as per standard string formatting), so if slicing is required, you must explicitly create a slice. This is to be used in templating cases, such as the parallel batch script templates, where simple arithmetic on arguments is useful. Examples -------- In [1]: f = EvalFormatter() In [2]: f.format('{n//4}', n=8) Out [2]: '2' In [3]: f.format("{greeting[slice(2,4)]}", greeting="Hello") Out [3]: 'll' """ def get_field(self, name, args, kwargs): v = eval(name, kwargs) return v, name @skip_doctest_py3 class FullEvalFormatter(Formatter): """A String Formatter that allows evaluation of simple expressions. Any time a format key is not found in the kwargs, it will be tried as an expression in the kwargs namespace. Note that this version allows slicing using [1:2], so you cannot specify a format string. Use :class:`EvalFormatter` to permit format strings. Examples -------- In [1]: f = FullEvalFormatter() In [2]: f.format('{n//4}', n=8) Out[2]: u'2' In [3]: f.format('{list(range(5))[2:4]}') Out[3]: u'[2, 3]' In [4]: f.format('{3*2}') Out[4]: u'6' """ # copied from Formatter._vformat with minor changes to allow eval # and replace the format_spec code with slicing def _vformat(self, format_string, args, kwargs, used_args, recursion_depth): if recursion_depth < 0: raise ValueError('Max string recursion exceeded') result = [] for literal_text, field_name, format_spec, conversion in \ self.parse(format_string): # output the literal text if literal_text: result.append(literal_text) # if there's a field, output it if field_name is not None: # this is some markup, find the object and do # the formatting if format_spec: # override format spec, to allow slicing: field_name = ':'.join([field_name, format_spec]) # eval the contents of the field for the object # to be formatted obj = eval(field_name, kwargs) # do any conversion on the resulting object obj = self.convert_field(obj, conversion) # format the object and append to the result result.append(self.format_field(obj, '')) return u''.join(py3compat.cast_unicode(s) for s in result) @skip_doctest_py3 class DollarFormatter(FullEvalFormatter): """Formatter allowing Itpl style $foo replacement, for names and attribute access only. Standard {foo} replacement also works, and allows full evaluation of its arguments. Examples -------- In [1]: f = DollarFormatter() In [2]: f.format('{n//4}', n=8) Out[2]: u'2' In [3]: f.format('23 * 76 is $result', result=23*76) Out[3]: u'23 * 76 is 1748' In [4]: f.format('$a or {b}', a=1, b=2) Out[4]: u'1 or 2' """ _dollar_pattern = re.compile("(.*?)\$(\$?[\w\.]+)") def parse(self, fmt_string): for literal_txt, field_name, format_spec, conversion \ in Formatter.parse(self, fmt_string): # Find $foo patterns in the literal text. continue_from = 0 txt = "" for m in self._dollar_pattern.finditer(literal_txt): new_txt, new_field = m.group(1,2) # $$foo --> $foo if new_field.startswith("$"): txt += new_txt + new_field else: yield (txt + new_txt, new_field, "", None) txt = "" continue_from = m.end() # Re-yield the {foo} style pattern yield (txt + literal_txt[continue_from:], field_name, format_spec, conversion) #----------------------------------------------------------------------------- # Utils to columnize a list of string #----------------------------------------------------------------------------- def _chunks(l, n): """Yield successive n-sized chunks from l.""" for i in xrange(0, len(l), n): yield l[i:i+n] def _find_optimal(rlist , separator_size=2 , displaywidth=80): """Calculate optimal info to columnize a list of string""" for nrow in range(1, len(rlist)+1) : chk = map(max,_chunks(rlist, nrow)) sumlength = sum(chk) ncols = len(chk) if sumlength+separator_size*(ncols-1) <= displaywidth : break; return {'columns_numbers' : ncols, 'optimal_separator_width':(displaywidth - sumlength)/(ncols-1) if (ncols -1) else 0, 'rows_numbers' : nrow, 'columns_width' : chk } def _get_or_default(mylist, i, default=None): """return list item number, or default if don't exist""" if i >= len(mylist): return default else : return mylist[i] @skip_doctest def compute_item_matrix(items, empty=None, *args, **kwargs) : """Returns a nested list, and info to columnize items Parameters : ------------ items : list of strings to columize empty : (default None) default value to fill list if needed separator_size : int (default=2) How much caracters will be used as a separation between each columns. displaywidth : int (default=80) The width of the area onto wich the columns should enter Returns : --------- Returns a tuple of (strings_matrix, dict_info) strings_matrix : nested list of string, the outer most list contains as many list as rows, the innermost lists have each as many element as colums. If the total number of elements in `items` does not equal the product of rows*columns, the last element of some lists are filled with `None`. dict_info : some info to make columnize easier: columns_numbers : number of columns rows_numbers : number of rows columns_width : list of with of each columns optimal_separator_width : best separator width between columns Exemple : --------- In [1]: l = ['aaa','b','cc','d','eeeee','f','g','h','i','j','k','l'] ...: compute_item_matrix(l,displaywidth=12) Out[1]: ([['aaa', 'f', 'k'], ['b', 'g', 'l'], ['cc', 'h', None], ['d', 'i', None], ['eeeee', 'j', None]], {'columns_numbers': 3, 'columns_width': [5, 1, 1], 'optimal_separator_width': 2, 'rows_numbers': 5}) """ info = _find_optimal(map(len, items), *args, **kwargs) nrow, ncol = info['rows_numbers'], info['columns_numbers'] return ([[ _get_or_default(items, c*nrow+i, default=empty) for c in range(ncol) ] for i in range(nrow) ], info) def columnize(items, separator=' ', displaywidth=80): """ Transform a list of strings into a single string with columns. Parameters ---------- items : sequence of strings The strings to process. separator : str, optional [default is two spaces] The string that separates columns. displaywidth : int, optional [default is 80] Width of the display in number of characters. Returns ------- The formatted string. """ if not items : return '\n' matrix, info = compute_item_matrix(items, separator_size=len(separator), displaywidth=displaywidth) fmatrix = [filter(None, x) for x in matrix] sjoin = lambda x : separator.join([ y.ljust(w, ' ') for y, w in zip(x, info['columns_width'])]) return '\n'.join(map(sjoin, fmatrix))+'\n'
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/utils/text.py
Python
lgpl-3.0
25,044
using UnityEngine; using System.Collections; public class InputBehaviour : MonoBehaviour { // Cuando se llama, notifica a todos los métodos que hacen referencia al delegate (DownHandler). public delegate void DownHandler( int button ); // evento que se activa cuando aparece el DownHandler public event DownHandler onDown; // Funcion que se llama desde InputManger, activa el evento onDown de éste y otras clases public void triggerDown(int button){ if( onDown != null ) onDown(button); } }
ddacoak/Fallen-Instinct
Assets/Scripts/OtrosScripts/Input/InputBehaviour.cs
C#
unlicense
514
/* Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( "fmt" "io" "github.com/renstrom/dedent" "k8s.io/kubernetes/pkg/kubectl" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "k8s.io/kubernetes/pkg/kubectl/resource" utilerrors "k8s.io/kubernetes/pkg/util/errors" "github.com/spf13/cobra" ) var ( autoscaleLong = dedent.Dedent(` Creates an autoscaler that automatically chooses and sets the number of pods that run in a kubernetes cluster. Looks up a Deployment, ReplicaSet, or ReplicationController by name and creates an autoscaler that uses the given resource as a reference. An autoscaler can automatically increase or decrease number of pods deployed within the system as needed.`) autoscaleExample = dedent.Dedent(` # Auto scale a deployment "foo", with the number of pods between 2 and 10, target CPU utilization specified so a default autoscaling policy will be used: kubectl autoscale deployment foo --min=2 --max=10 # Auto scale a replication controller "foo", with the number of pods between 1 and 5, target CPU utilization at 80%: kubectl autoscale rc foo --max=5 --cpu-percent=80`) ) func NewCmdAutoscale(f cmdutil.Factory, out io.Writer) *cobra.Command { options := &resource.FilenameOptions{} validArgs := []string{"deployment", "replicaset", "replicationcontroller"} argAliases := kubectl.ResourceAliases(validArgs) cmd := &cobra.Command{ Use: "autoscale (-f FILENAME | TYPE NAME | TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU] [flags]", Short: "Auto-scale a Deployment, ReplicaSet, or ReplicationController", Long: autoscaleLong, Example: autoscaleExample, Run: func(cmd *cobra.Command, args []string) { err := RunAutoscale(f, out, cmd, args, options) cmdutil.CheckErr(err) }, ValidArgs: validArgs, ArgAliases: argAliases, } cmdutil.AddPrinterFlags(cmd) cmd.Flags().String("generator", "horizontalpodautoscaler/v1", "The name of the API generator to use. Currently there is only 1 generator.") cmd.Flags().Int("min", -1, "The lower limit for the number of pods that can be set by the autoscaler. If it's not specified or negative, the server will apply a default value.") cmd.Flags().Int("max", -1, "The upper limit for the number of pods that can be set by the autoscaler. Required.") cmd.MarkFlagRequired("max") cmd.Flags().Int("cpu-percent", -1, fmt.Sprintf("The target average CPU utilization (represented as a percent of requested CPU) over all the pods. If it's not specified or negative, a default autoscaling policy will be used.")) cmd.Flags().String("name", "", "The name for the newly created object. If not specified, the name of the input resource will be used.") cmdutil.AddDryRunFlag(cmd) usage := "identifying the resource to autoscale." cmdutil.AddFilenameOptionFlags(cmd, options, usage) cmdutil.AddApplyAnnotationFlags(cmd) cmdutil.AddRecordFlag(cmd) cmdutil.AddInclude3rdPartyFlags(cmd) return cmd } func RunAutoscale(f cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, options *resource.FilenameOptions) error { namespace, enforceNamespace, err := f.DefaultNamespace() if err != nil { return err } // validate flags if err := validateFlags(cmd); err != nil { return err } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). ContinueOnError(). NamespaceParam(namespace).DefaultNamespace(). FilenameParam(enforceNamespace, options). ResourceTypeOrNameArgs(false, args...). Flatten(). Do() err = r.Err() if err != nil { return err } // Get the generator, setup and validate all required parameters generatorName := cmdutil.GetFlagString(cmd, "generator") generators := f.Generators("autoscale") generator, found := generators[generatorName] if !found { return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generatorName)) } names := generator.ParamNames() count := 0 err = r.Visit(func(info *resource.Info, err error) error { if err != nil { return err } mapping := info.ResourceMapping() if err := f.CanBeAutoscaled(mapping.GroupVersionKind.GroupKind()); err != nil { return err } name := info.Name params := kubectl.MakeParams(cmd, names) params["default-name"] = name params["scaleRef-kind"] = mapping.GroupVersionKind.Kind params["scaleRef-name"] = name params["scaleRef-apiVersion"] = mapping.GroupVersionKind.GroupVersion().String() if err = kubectl.ValidateParams(names, params); err != nil { return err } // Check for invalid flags used against the present generator. if err := kubectl.EnsureFlagsValid(cmd, generators, generatorName); err != nil { return err } // Generate new object object, err := generator.Generate(params) if err != nil { return err } resourceMapper := &resource.Mapper{ ObjectTyper: typer, RESTMapper: mapper, ClientMapper: resource.ClientMapperFunc(f.ClientForMapping), Decoder: f.Decoder(true), } hpa, err := resourceMapper.InfoForObject(object, nil) if err != nil { return err } if cmdutil.ShouldRecord(cmd, hpa) { if err := cmdutil.RecordChangeCause(hpa.Object, f.Command()); err != nil { return err } object = hpa.Object } if cmdutil.GetDryRunFlag(cmd) { return f.PrintObject(cmd, mapper, object, out) } if err := kubectl.CreateOrUpdateAnnotation(cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag), hpa, f.JSONEncoder()); err != nil { return err } object, err = resource.NewHelper(hpa.Client, hpa.Mapping).Create(namespace, false, object) if err != nil { return err } count++ if len(cmdutil.GetFlagString(cmd, "output")) > 0 { return f.PrintObject(cmd, mapper, object, out) } cmdutil.PrintSuccess(mapper, false, out, info.Mapping.Resource, info.Name, cmdutil.GetDryRunFlag(cmd), "autoscaled") return nil }) if err != nil { return err } if count == 0 { return fmt.Errorf("no objects passed to autoscale") } return nil } func validateFlags(cmd *cobra.Command) error { errs := []error{} max, min := cmdutil.GetFlagInt(cmd, "max"), cmdutil.GetFlagInt(cmd, "min") if max < 1 { errs = append(errs, fmt.Errorf("--max=MAXPODS is required and must be at least 1, max: %d", max)) } if max < min { errs = append(errs, fmt.Errorf("--max=MAXPODS must be larger or equal to --min=MINPODS, max: %d, min: %d", max, min)) } return utilerrors.NewAggregate(errs) }
gluke77/kubernetes
pkg/kubectl/cmd/autoscale.go
GO
apache-2.0
6,991
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is subject to the terms and conditions defined in # file 'LICENSE.md', which is part of this source code package. # from kubernetes_py.K8sExceptions import NotFoundException from kubernetes_py.K8sObject import K8sObject from kubernetes_py.K8sPod import K8sPod from kubernetes_py.models.v1beta1.ReplicaSet import ReplicaSet class K8sReplicaSet(K8sObject): """ http://kubernetes.io/docs/api-reference/extensions/v1beta1/definitions/#_v1beta1_replicaset """ REVISION_ANNOTATION = "deployment.kubernetes.io/revision" REVISION_HISTORY_ANNOTATION = "deployment.kubernetes.io/revision-history" def __init__(self, config=None, name=None): super(K8sReplicaSet, self).__init__(config=config, obj_type="ReplicaSet", name=name) # ------------------------------------------------------------------------------------- override def get(self): self.model = ReplicaSet(self.get_model()) return self def list(self, pattern=None, reverse=True, labels=None): ls = super(K8sReplicaSet, self).list(labels=labels) rsets = list(map(lambda x: ReplicaSet(x), ls)) if pattern is not None: rsets = list(filter(lambda x: pattern in x.name, rsets)) k8s = [] for x in rsets: j = K8sReplicaSet(config=self.config, name=x.name).from_model(m=x) k8s.append(j) k8s.sort(key=lambda x: x.creation_timestamp, reverse=reverse) return k8s def delete(self, cascade=False): super(K8sReplicaSet, self).delete(cascade) if cascade: pods = K8sPod(config=self.config, name="yo").list(pattern=self.name) for pod in pods: try: pod.delete(cascade) except NotFoundException: pass return self # ------------------------------------------------------------------------------------- revision @property def revision(self): if self.REVISION_ANNOTATION in self.model.metadata.annotations: return self.model.metadata.annotations[self.REVISION_ANNOTATION] return None @revision.setter def revision(self, r=None): raise NotImplementedError("K8sReplicaSet: revision is read-only.") # ------------------------------------------------------------------------------------- revision history @property def revision_history(self): if self.REVISION_HISTORY_ANNOTATION in self.model.metadata.annotations: comma_string = self.model.metadata.annotations[self.REVISION_HISTORY_ANNOTATION] version_array = comma_string.split(",") return map(lambda x: int(x), version_array) return None @revision_history.setter def revision_history(self, r=None): raise NotImplementedError("K8sReplicaSet: revision_history is read-only.")
mnubo/kubernetes-py
kubernetes_py/K8sReplicaSet.py
Python
apache-2.0
2,940
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution; public class IllegalEnvVarException extends ExecutionException { public IllegalEnvVarException(String message) { super(message); } }
mdanielwork/intellij-community
platform/platform-api/src/com/intellij/execution/IllegalEnvVarException.java
Java
apache-2.0
314
// Copyright 2020 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package pbtesting import ( "fmt" "github.com/golang/mock/gomock" "github.com/golang/protobuf/proto" "github.com/google/go-cmp/cmp" "google.golang.org/protobuf/testing/protocmp" ) type protoMatcher struct { expected proto.Message } func (m protoMatcher) Got(got interface{}) string { message, ok := got.(proto.Message) if !ok { return fmt.Sprintf("%v", ok) } return proto.MarshalTextString(message) } func (m protoMatcher) Matches(actual interface{}) bool { return cmp.Diff(m.expected, actual, protocmp.Transform()) == "" } func (m protoMatcher) String() string { return proto.MarshalTextString(m.expected) } func ProtoEquals(expected proto.Message) gomock.Matcher { return protoMatcher{expected} }
adjackura/compute-image-tools
proto/go/pbtesting/gomock_matcher.go
GO
apache-2.0
1,340
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > The initial value of Boolean.prototype is the Boolean prototype object es5id: 15.6.3.1_A1 description: Checking Boolean.prototype property ---*/ //CHECK#1 if (typeof Boolean.prototype !== "object") { $ERROR('#1: typeof Boolean.prototype === "object"'); } //CHECK#2 if (Boolean.prototype != false) { $ERROR('#2: Boolean.prototype == false'); } delete Boolean.prototype.toString; if (Boolean.prototype.toString() !== "[object Boolean]") { $ERROR('#3: The [[Class]] property of the Boolean prototype object is set to "Boolean"'); }
m0ppers/arangodb
3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/Boolean/prototype/S15.6.3.1_A1.js
JavaScript
apache-2.0
694
/* Copyright 2016 VMware, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "noMatch.h" #include "frontends/p4/coreLibrary.h" namespace P4 { const IR::Node* DoHandleNoMatch::postorder(IR::SelectExpression* expression) { for (auto c : expression->selectCases) { if (c->keyset->is<IR::DefaultExpression>()) return expression; } CHECK_NULL(noMatch); auto sc = new IR::SelectCase( new IR::DefaultExpression(), new IR::PathExpression(noMatch->getName())); expression->selectCases.push_back(sc); return expression; } const IR::Node* DoHandleNoMatch::preorder(IR::P4Parser* parser) { P4CoreLibrary& lib = P4CoreLibrary::instance; cstring name = nameGen->newName("noMatch"); LOG2("Inserting " << name << " state"); auto args = new IR::Vector<IR::Argument>(); args->push_back(new IR::Argument(new IR::BoolLiteral(false))); args->push_back(new IR::Argument(new IR::Member( new IR::TypeNameExpression(IR::Type_Error::error), lib.noMatch.Id()))); auto verify = new IR::MethodCallExpression( new IR::PathExpression(IR::ID(IR::ParserState::verify)), args); noMatch = new IR::ParserState(IR::ID(name), { new IR::MethodCallStatement(verify) }, new IR::PathExpression(IR::ID(IR::ParserState::reject))); parser->states.push_back(noMatch); return parser; } } // namespace P4
hanw/p4c
midend/noMatch.cpp
C++
apache-2.0
1,905
/* * Copyright (c) 1994, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.StreamCorruptedException; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.UnaryOperator; import jdk.internal.util.ArraysSupport; /** * The {@code Vector} class implements a growable array of * objects. Like an array, it contains components that can be * accessed using an integer index. However, the size of a * {@code Vector} can grow or shrink as needed to accommodate * adding and removing items after the {@code Vector} has been created. * * <p>Each vector tries to optimize storage management by maintaining a * {@code capacity} and a {@code capacityIncrement}. The * {@code capacity} is always at least as large as the vector * size; it is usually larger because as components are added to the * vector, the vector's storage increases in chunks the size of * {@code capacityIncrement}. An application can increase the * capacity of a vector before inserting a large number of * components; this reduces the amount of incremental reallocation. * * <p id="fail-fast"> * The iterators returned by this class's {@link #iterator() iterator} and * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>: * if the vector is structurally modified at any time after the iterator is * created, in any way except through the iterator's own * {@link ListIterator#remove() remove} or * {@link ListIterator#add(Object) add} methods, the iterator will throw a * {@link ConcurrentModificationException}. Thus, in the face of * concurrent modification, the iterator fails quickly and cleanly, rather * than risking arbitrary, non-deterministic behavior at an undetermined * time in the future. The {@link Enumeration Enumerations} returned by * the {@link #elements() elements} method are <em>not</em> fail-fast; if the * Vector is structurally modified at any time after the enumeration is * created then the results of enumerating are undefined. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw {@code ConcurrentModificationException} on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * * <p>As of the Java 2 platform v1.2, this class was retrofitted to * implement the {@link List} interface, making it a member of the * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework"> * Java Collections Framework</a>. Unlike the new collection * implementations, {@code Vector} is synchronized. If a thread-safe * implementation is not needed, it is recommended to use {@link * ArrayList} in place of {@code Vector}. * * @param <E> Type of component elements * * @author Lee Boynton * @author Jonathan Payne * @see Collection * @see LinkedList * @since 1.0 */ public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { /** * The array buffer into which the components of the vector are * stored. The capacity of the vector is the length of this array buffer, * and is at least large enough to contain all the vector's elements. * * <p>Any array elements following the last element in the Vector are null. * * @serial */ @SuppressWarnings("serial") // Conditionally serializable protected Object[] elementData; /** * The number of valid components in this {@code Vector} object. * Components {@code elementData[0]} through * {@code elementData[elementCount-1]} are the actual items. * * @serial */ protected int elementCount; /** * The amount by which the capacity of the vector is automatically * incremented when its size becomes greater than its capacity. If * the capacity increment is less than or equal to zero, the capacity * of the vector is doubled each time it needs to grow. * * @serial */ protected int capacityIncrement; /** use serialVersionUID from JDK 1.0.2 for interoperability */ @java.io.Serial private static final long serialVersionUID = -2767605614048989439L; /** * Constructs an empty vector with the specified initial capacity and * capacity increment. * * @param initialCapacity the initial capacity of the vector * @param capacityIncrement the amount by which the capacity is * increased when the vector overflows * @throws IllegalArgumentException if the specified initial capacity * is negative */ public Vector(int initialCapacity, int capacityIncrement) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; this.capacityIncrement = capacityIncrement; } /** * Constructs an empty vector with the specified initial capacity and * with its capacity increment equal to zero. * * @param initialCapacity the initial capacity of the vector * @throws IllegalArgumentException if the specified initial capacity * is negative */ public Vector(int initialCapacity) { this(initialCapacity, 0); } /** * Constructs an empty vector so that its internal data array * has size {@code 10} and its standard capacity increment is * zero. */ public Vector() { this(10); } /** * Constructs a vector containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. * * @param c the collection whose elements are to be placed into this * vector * @throws NullPointerException if the specified collection is null * @since 1.2 */ public Vector(Collection<? extends E> c) { Object[] a = c.toArray(); elementCount = a.length; if (c.getClass() == ArrayList.class) { elementData = a; } else { elementData = Arrays.copyOf(a, elementCount, Object[].class); } } /** * Copies the components of this vector into the specified array. * The item at index {@code k} in this vector is copied into * component {@code k} of {@code anArray}. * * @param anArray the array into which the components get copied * @throws NullPointerException if the given array is null * @throws IndexOutOfBoundsException if the specified array is not * large enough to hold all the components of this vector * @throws ArrayStoreException if a component of this vector is not of * a runtime type that can be stored in the specified array * @see #toArray(Object[]) */ public synchronized void copyInto(Object[] anArray) { System.arraycopy(elementData, 0, anArray, 0, elementCount); } /** * Trims the capacity of this vector to be the vector's current * size. If the capacity of this vector is larger than its current * size, then the capacity is changed to equal the size by replacing * its internal data array, kept in the field {@code elementData}, * with a smaller one. An application can use this operation to * minimize the storage of a vector. */ public synchronized void trimToSize() { modCount++; int oldCapacity = elementData.length; if (elementCount < oldCapacity) { elementData = Arrays.copyOf(elementData, elementCount); } } /** * Increases the capacity of this vector, if necessary, to ensure * that it can hold at least the number of components specified by * the minimum capacity argument. * * <p>If the current capacity of this vector is less than * {@code minCapacity}, then its capacity is increased by replacing its * internal data array, kept in the field {@code elementData}, with a * larger one. The size of the new data array will be the old size plus * {@code capacityIncrement}, unless the value of * {@code capacityIncrement} is less than or equal to zero, in which case * the new capacity will be twice the old capacity; but if this new size * is still smaller than {@code minCapacity}, then the new capacity will * be {@code minCapacity}. * * @param minCapacity the desired minimum capacity */ public synchronized void ensureCapacity(int minCapacity) { if (minCapacity > 0) { modCount++; if (minCapacity > elementData.length) grow(minCapacity); } } /** * Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity * @throws OutOfMemoryError if minCapacity is less than zero */ private Object[] grow(int minCapacity) { int oldCapacity = elementData.length; int newCapacity = ArraysSupport.newLength(oldCapacity, minCapacity - oldCapacity, /* minimum growth */ capacityIncrement > 0 ? capacityIncrement : oldCapacity /* preferred growth */); return elementData = Arrays.copyOf(elementData, newCapacity); } private Object[] grow() { return grow(elementCount + 1); } /** * Sets the size of this vector. If the new size is greater than the * current size, new {@code null} items are added to the end of * the vector. If the new size is less than the current size, all * components at index {@code newSize} and greater are discarded. * * @param newSize the new size of this vector * @throws ArrayIndexOutOfBoundsException if the new size is negative */ public synchronized void setSize(int newSize) { modCount++; if (newSize > elementData.length) grow(newSize); final Object[] es = elementData; for (int to = elementCount, i = newSize; i < to; i++) es[i] = null; elementCount = newSize; } /** * Returns the current capacity of this vector. * * @return the current capacity (the length of its internal * data array, kept in the field {@code elementData} * of this vector) */ public synchronized int capacity() { return elementData.length; } /** * Returns the number of components in this vector. * * @return the number of components in this vector */ public synchronized int size() { return elementCount; } /** * Tests if this vector has no components. * * @return {@code true} if and only if this vector has * no components, that is, its size is zero; * {@code false} otherwise. */ public synchronized boolean isEmpty() { return elementCount == 0; } /** * Returns an enumeration of the components of this vector. The * returned {@code Enumeration} object will generate all items in * this vector. The first item generated is the item at index {@code 0}, * then the item at index {@code 1}, and so on. If the vector is * structurally modified while enumerating over the elements then the * results of enumerating are undefined. * * @return an enumeration of the components of this vector * @see Iterator */ public Enumeration<E> elements() { return new Enumeration<E>() { int count = 0; public boolean hasMoreElements() { return count < elementCount; } public E nextElement() { synchronized (Vector.this) { if (count < elementCount) { return elementData(count++); } } throw new NoSuchElementException("Vector Enumeration"); } }; } /** * Returns {@code true} if this vector contains the specified element. * More formally, returns {@code true} if and only if this vector * contains at least one element {@code e} such that * {@code Objects.equals(o, e)}. * * @param o element whose presence in this vector is to be tested * @return {@code true} if this vector contains the specified element */ public boolean contains(Object o) { return indexOf(o, 0) >= 0; } /** * Returns the index of the first occurrence of the specified element * in this vector, or -1 if this vector does not contain the element. * More formally, returns the lowest index {@code i} such that * {@code Objects.equals(o, get(i))}, * or -1 if there is no such index. * * @param o element to search for * @return the index of the first occurrence of the specified element in * this vector, or -1 if this vector does not contain the element */ public int indexOf(Object o) { return indexOf(o, 0); } /** * Returns the index of the first occurrence of the specified element in * this vector, searching forwards from {@code index}, or returns -1 if * the element is not found. * More formally, returns the lowest index {@code i} such that * {@code (i >= index && Objects.equals(o, get(i)))}, * or -1 if there is no such index. * * @param o element to search for * @param index index to start searching from * @return the index of the first occurrence of the element in * this vector at position {@code index} or later in the vector; * {@code -1} if the element is not found. * @throws IndexOutOfBoundsException if the specified index is negative * @see Object#equals(Object) */ public synchronized int indexOf(Object o, int index) { if (o == null) { for (int i = index ; i < elementCount ; i++) if (elementData[i]==null) return i; } else { for (int i = index ; i < elementCount ; i++) if (o.equals(elementData[i])) return i; } return -1; } /** * Returns the index of the last occurrence of the specified element * in this vector, or -1 if this vector does not contain the element. * More formally, returns the highest index {@code i} such that * {@code Objects.equals(o, get(i))}, * or -1 if there is no such index. * * @param o element to search for * @return the index of the last occurrence of the specified element in * this vector, or -1 if this vector does not contain the element */ public synchronized int lastIndexOf(Object o) { return lastIndexOf(o, elementCount-1); } /** * Returns the index of the last occurrence of the specified element in * this vector, searching backwards from {@code index}, or returns -1 if * the element is not found. * More formally, returns the highest index {@code i} such that * {@code (i <= index && Objects.equals(o, get(i)))}, * or -1 if there is no such index. * * @param o element to search for * @param index index to start searching backwards from * @return the index of the last occurrence of the element at position * less than or equal to {@code index} in this vector; * -1 if the element is not found. * @throws IndexOutOfBoundsException if the specified index is greater * than or equal to the current size of this vector */ public synchronized int lastIndexOf(Object o, int index) { if (index >= elementCount) throw new IndexOutOfBoundsException(index + " >= "+ elementCount); if (o == null) { for (int i = index; i >= 0; i--) if (elementData[i]==null) return i; } else { for (int i = index; i >= 0; i--) if (o.equals(elementData[i])) return i; } return -1; } /** * Returns the component at the specified index. * * <p>This method is identical in functionality to the {@link #get(int)} * method (which is part of the {@link List} interface). * * @param index an index into this vector * @return the component at the specified index * @throws ArrayIndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= size()}) */ public synchronized E elementAt(int index) { if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); } return elementData(index); } /** * Returns the first component (the item at index {@code 0}) of * this vector. * * @return the first component of this vector * @throws NoSuchElementException if this vector has no components */ public synchronized E firstElement() { if (elementCount == 0) { throw new NoSuchElementException(); } return elementData(0); } /** * Returns the last component of the vector. * * @return the last component of the vector, i.e., the component at index * {@code size() - 1} * @throws NoSuchElementException if this vector is empty */ public synchronized E lastElement() { if (elementCount == 0) { throw new NoSuchElementException(); } return elementData(elementCount - 1); } /** * Sets the component at the specified {@code index} of this * vector to be the specified object. The previous component at that * position is discarded. * * <p>The index must be a value greater than or equal to {@code 0} * and less than the current size of the vector. * * <p>This method is identical in functionality to the * {@link #set(int, Object) set(int, E)} * method (which is part of the {@link List} interface). Note that the * {@code set} method reverses the order of the parameters, to more closely * match array usage. Note also that the {@code set} method returns the * old value that was stored at the specified position. * * @param obj what the component is to be set to * @param index the specified index * @throws ArrayIndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= size()}) */ public synchronized void setElementAt(E obj, int index) { if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); } elementData[index] = obj; } /** * Deletes the component at the specified index. Each component in * this vector with an index greater or equal to the specified * {@code index} is shifted downward to have an index one * smaller than the value it had previously. The size of this vector * is decreased by {@code 1}. * * <p>The index must be a value greater than or equal to {@code 0} * and less than the current size of the vector. * * <p>This method is identical in functionality to the {@link #remove(int)} * method (which is part of the {@link List} interface). Note that the * {@code remove} method returns the old value that was stored at the * specified position. * * @param index the index of the object to remove * @throws ArrayIndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= size()}) */ public synchronized void removeElementAt(int index) { if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); } else if (index < 0) { throw new ArrayIndexOutOfBoundsException(index); } int j = elementCount - index - 1; if (j > 0) { System.arraycopy(elementData, index + 1, elementData, index, j); } modCount++; elementCount--; elementData[elementCount] = null; /* to let gc do its work */ } /** * Inserts the specified object as a component in this vector at the * specified {@code index}. Each component in this vector with * an index greater or equal to the specified {@code index} is * shifted upward to have an index one greater than the value it had * previously. * * <p>The index must be a value greater than or equal to {@code 0} * and less than or equal to the current size of the vector. (If the * index is equal to the current size of the vector, the new element * is appended to the Vector.) * * <p>This method is identical in functionality to the * {@link #add(int, Object) add(int, E)} * method (which is part of the {@link List} interface). Note that the * {@code add} method reverses the order of the parameters, to more closely * match array usage. * * @param obj the component to insert * @param index where to insert the new component * @throws ArrayIndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index > size()}) */ public synchronized void insertElementAt(E obj, int index) { if (index > elementCount) { throw new ArrayIndexOutOfBoundsException(index + " > " + elementCount); } modCount++; final int s = elementCount; Object[] elementData = this.elementData; if (s == elementData.length) elementData = grow(); System.arraycopy(elementData, index, elementData, index + 1, s - index); elementData[index] = obj; elementCount = s + 1; } /** * Adds the specified component to the end of this vector, * increasing its size by one. The capacity of this vector is * increased if its size becomes greater than its capacity. * * <p>This method is identical in functionality to the * {@link #add(Object) add(E)} * method (which is part of the {@link List} interface). * * @param obj the component to be added */ public synchronized void addElement(E obj) { modCount++; add(obj, elementData, elementCount); } /** * Removes the first (lowest-indexed) occurrence of the argument * from this vector. If the object is found in this vector, each * component in the vector with an index greater or equal to the * object's index is shifted downward to have an index one smaller * than the value it had previously. * * <p>This method is identical in functionality to the * {@link #remove(Object)} method (which is part of the * {@link List} interface). * * @param obj the component to be removed * @return {@code true} if the argument was a component of this * vector; {@code false} otherwise. */ public synchronized boolean removeElement(Object obj) { modCount++; int i = indexOf(obj); if (i >= 0) { removeElementAt(i); return true; } return false; } /** * Removes all components from this vector and sets its size to zero. * * <p>This method is identical in functionality to the {@link #clear} * method (which is part of the {@link List} interface). */ public synchronized void removeAllElements() { final Object[] es = elementData; for (int to = elementCount, i = elementCount = 0; i < to; i++) es[i] = null; modCount++; } /** * Returns a clone of this vector. The copy will contain a * reference to a clone of the internal data array, not a reference * to the original internal data array of this {@code Vector} object. * * @return a clone of this vector */ public synchronized Object clone() { try { @SuppressWarnings("unchecked") Vector<E> v = (Vector<E>) super.clone(); v.elementData = Arrays.copyOf(elementData, elementCount); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(e); } } /** * Returns an array containing all of the elements in this Vector * in the correct order. * * @since 1.2 */ public synchronized Object[] toArray() { return Arrays.copyOf(elementData, elementCount); } /** * Returns an array containing all of the elements in this Vector in the * correct order; the runtime type of the returned array is that of the * specified array. If the Vector fits in the specified array, it is * returned therein. Otherwise, a new array is allocated with the runtime * type of the specified array and the size of this Vector. * * <p>If the Vector fits in the specified array with room to spare * (i.e., the array has more elements than the Vector), * the element in the array immediately following the end of the * Vector is set to null. (This is useful in determining the length * of the Vector <em>only</em> if the caller knows that the Vector * does not contain any null elements.) * * @param <T> type of array elements. The same type as {@code <E>} or a * supertype of {@code <E>}. * @param a the array into which the elements of the Vector are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing the elements of the Vector * @throws ArrayStoreException if the runtime type of a, {@code <T>}, is not * a supertype of the runtime type, {@code <E>}, of every element in this * Vector * @throws NullPointerException if the given array is null * @since 1.2 */ @SuppressWarnings("unchecked") public synchronized <T> T[] toArray(T[] a) { if (a.length < elementCount) return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass()); System.arraycopy(elementData, 0, a, 0, elementCount); if (a.length > elementCount) a[elementCount] = null; return a; } // Positional Access Operations @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; } @SuppressWarnings("unchecked") static <E> E elementAt(Object[] es, int index) { return (E) es[index]; } /** * Returns the element at the specified position in this Vector. * * @param index index of the element to return * @return object at the specified index * @throws ArrayIndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= size()}) * @since 1.2 */ public synchronized E get(int index) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); return elementData(index); } /** * Replaces the element at the specified position in this Vector with the * specified element. * * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position * @throws ArrayIndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= size()}) * @since 1.2 */ public synchronized E set(int index, E element) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; } /** * This helper method split out from add(E) to keep method * bytecode size under 35 (the -XX:MaxInlineSize default value), * which helps when add(E) is called in a C1-compiled loop. */ private void add(E e, Object[] elementData, int s) { if (s == elementData.length) elementData = grow(); elementData[s] = e; elementCount = s + 1; } /** * Appends the specified element to the end of this Vector. * * @param e element to be appended to this Vector * @return {@code true} (as specified by {@link Collection#add}) * @since 1.2 */ public synchronized boolean add(E e) { modCount++; add(e, elementData, elementCount); return true; } /** * Removes the first occurrence of the specified element in this Vector * If the Vector does not contain the element, it is unchanged. More * formally, removes the element with the lowest index i such that * {@code Objects.equals(o, get(i))} (if such * an element exists). * * @param o element to be removed from this Vector, if present * @return true if the Vector contained the specified element * @since 1.2 */ public boolean remove(Object o) { return removeElement(o); } /** * Inserts the specified element at the specified position in this Vector. * Shifts the element currently at that position (if any) and any * subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws ArrayIndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index > size()}) * @since 1.2 */ public void add(int index, E element) { insertElementAt(element, index); } /** * Removes the element at the specified position in this Vector. * Shifts any subsequent elements to the left (subtracts one from their * indices). Returns the element that was removed from the Vector. * * @param index the index of the element to be removed * @return element that was removed * @throws ArrayIndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index >= size()}) * @since 1.2 */ public synchronized E remove(int index) { modCount++; if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); E oldValue = elementData(index); int numMoved = elementCount - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--elementCount] = null; // Let gc do its work return oldValue; } /** * Removes all of the elements from this Vector. The Vector will * be empty after this call returns (unless it throws an exception). * * @since 1.2 */ public void clear() { removeAllElements(); } // Bulk Operations /** * Returns true if this Vector contains all of the elements in the * specified Collection. * * @param c a collection whose elements will be tested for containment * in this Vector * @return true if this Vector contains all of the elements in the * specified collection * @throws NullPointerException if the specified collection is null */ public synchronized boolean containsAll(Collection<?> c) { return super.containsAll(c); } /** * Appends all of the elements in the specified Collection to the end of * this Vector, in the order that they are returned by the specified * Collection's Iterator. The behavior of this operation is undefined if * the specified Collection is modified while the operation is in progress. * (This implies that the behavior of this call is undefined if the * specified Collection is this Vector, and this Vector is nonempty.) * * @param c elements to be inserted into this Vector * @return {@code true} if this Vector changed as a result of the call * @throws NullPointerException if the specified collection is null * @since 1.2 */ public boolean addAll(Collection<? extends E> c) { Object[] a = c.toArray(); modCount++; int numNew = a.length; if (numNew == 0) return false; synchronized (this) { Object[] elementData = this.elementData; final int s = elementCount; if (numNew > elementData.length - s) elementData = grow(s + numNew); System.arraycopy(a, 0, elementData, s, numNew); elementCount = s + numNew; return true; } } /** * Removes from this Vector all of its elements that are contained in the * specified Collection. * * @param c a collection of elements to be removed from the Vector * @return true if this Vector changed as a result of the call * @throws ClassCastException if the types of one or more elements * in this vector are incompatible with the specified * collection * (<a href="Collection.html#optional-restrictions">optional</a>) * @throws NullPointerException if this vector contains one or more null * elements and the specified collection does not support null * elements * (<a href="Collection.html#optional-restrictions">optional</a>), * or if the specified collection is null * @since 1.2 */ public boolean removeAll(Collection<?> c) { Objects.requireNonNull(c); return bulkRemove(e -> c.contains(e)); } /** * Retains only the elements in this Vector that are contained in the * specified Collection. In other words, removes from this Vector all * of its elements that are not contained in the specified Collection. * * @param c a collection of elements to be retained in this Vector * (all other elements are removed) * @return true if this Vector changed as a result of the call * @throws ClassCastException if the types of one or more elements * in this vector are incompatible with the specified * collection * (<a href="Collection.html#optional-restrictions">optional</a>) * @throws NullPointerException if this vector contains one or more null * elements and the specified collection does not support null * elements * (<a href="Collection.html#optional-restrictions">optional</a>), * or if the specified collection is null * @since 1.2 */ public boolean retainAll(Collection<?> c) { Objects.requireNonNull(c); return bulkRemove(e -> !c.contains(e)); } /** * @throws NullPointerException {@inheritDoc} */ @Override public boolean removeIf(Predicate<? super E> filter) { Objects.requireNonNull(filter); return bulkRemove(filter); } // A tiny bit set implementation private static long[] nBits(int n) { return new long[((n - 1) >> 6) + 1]; } private static void setBit(long[] bits, int i) { bits[i >> 6] |= 1L << i; } private static boolean isClear(long[] bits, int i) { return (bits[i >> 6] & (1L << i)) == 0; } private synchronized boolean bulkRemove(Predicate<? super E> filter) { int expectedModCount = modCount; final Object[] es = elementData; final int end = elementCount; int i; // Optimize for initial run of survivors for (i = 0; i < end && !filter.test(elementAt(es, i)); i++) ; // Tolerate predicates that reentrantly access the collection for // read (but writers still get CME), so traverse once to find // elements to delete, a second pass to physically expunge. if (i < end) { final int beg = i; final long[] deathRow = nBits(end - beg); deathRow[0] = 1L; // set bit 0 for (i = beg + 1; i < end; i++) if (filter.test(elementAt(es, i))) setBit(deathRow, i - beg); if (modCount != expectedModCount) throw new ConcurrentModificationException(); modCount++; int w = beg; for (i = beg; i < end; i++) if (isClear(deathRow, i - beg)) es[w++] = es[i]; for (i = elementCount = w; i < end; i++) es[i] = null; return true; } else { if (modCount != expectedModCount) throw new ConcurrentModificationException(); return false; } } /** * Inserts all of the elements in the specified Collection into this * Vector at the specified position. Shifts the element currently at * that position (if any) and any subsequent elements to the right * (increases their indices). The new elements will appear in the Vector * in the order that they are returned by the specified Collection's * iterator. * * @param index index at which to insert the first element from the * specified collection * @param c elements to be inserted into this Vector * @return {@code true} if this Vector changed as a result of the call * @throws ArrayIndexOutOfBoundsException if the index is out of range * ({@code index < 0 || index > size()}) * @throws NullPointerException if the specified collection is null * @since 1.2 */ public synchronized boolean addAll(int index, Collection<? extends E> c) { if (index < 0 || index > elementCount) throw new ArrayIndexOutOfBoundsException(index); Object[] a = c.toArray(); modCount++; int numNew = a.length; if (numNew == 0) return false; Object[] elementData = this.elementData; final int s = elementCount; if (numNew > elementData.length - s) elementData = grow(s + numNew); int numMoved = s - index; if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); System.arraycopy(a, 0, elementData, index, numNew); elementCount = s + numNew; return true; } /** * Compares the specified Object with this Vector for equality. Returns * true if and only if the specified Object is also a List, both Lists * have the same size, and all corresponding pairs of elements in the two * Lists are <em>equal</em>. (Two elements {@code e1} and * {@code e2} are <em>equal</em> if {@code Objects.equals(e1, e2)}.) * In other words, two Lists are defined to be * equal if they contain the same elements in the same order. * * @param o the Object to be compared for equality with this Vector * @return true if the specified Object is equal to this Vector */ public synchronized boolean equals(Object o) { return super.equals(o); } /** * Returns the hash code value for this Vector. */ public synchronized int hashCode() { return super.hashCode(); } /** * Returns a string representation of this Vector, containing * the String representation of each element. */ public synchronized String toString() { return super.toString(); } /** * Returns a view of the portion of this List between fromIndex, * inclusive, and toIndex, exclusive. (If fromIndex and toIndex are * equal, the returned List is empty.) The returned List is backed by this * List, so changes in the returned List are reflected in this List, and * vice-versa. The returned List supports all of the optional List * operations supported by this List. * * <p>This method eliminates the need for explicit range operations (of * the sort that commonly exist for arrays). Any operation that expects * a List can be used as a range operation by operating on a subList view * instead of a whole List. For example, the following idiom * removes a range of elements from a List: * <pre> * list.subList(from, to).clear(); * </pre> * Similar idioms may be constructed for indexOf and lastIndexOf, * and all of the algorithms in the Collections class can be applied to * a subList. * * <p>The semantics of the List returned by this method become undefined if * the backing list (i.e., this List) is <i>structurally modified</i> in * any way other than via the returned List. (Structural modifications are * those that change the size of the List, or otherwise perturb it in such * a fashion that iterations in progress may yield incorrect results.) * * @param fromIndex low endpoint (inclusive) of the subList * @param toIndex high endpoint (exclusive) of the subList * @return a view of the specified range within this List * @throws IndexOutOfBoundsException if an endpoint index value is out of range * {@code (fromIndex < 0 || toIndex > size)} * @throws IllegalArgumentException if the endpoint indices are out of order * {@code (fromIndex > toIndex)} */ public synchronized List<E> subList(int fromIndex, int toIndex) { return Collections.synchronizedList(super.subList(fromIndex, toIndex), this); } /** * Removes from this list all of the elements whose index is between * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. * Shifts any succeeding elements to the left (reduces their index). * This call shortens the list by {@code (toIndex - fromIndex)} elements. * (If {@code toIndex==fromIndex}, this operation has no effect.) */ protected synchronized void removeRange(int fromIndex, int toIndex) { modCount++; shiftTailOverGap(elementData, fromIndex, toIndex); } /** Erases the gap from lo to hi, by sliding down following elements. */ private void shiftTailOverGap(Object[] es, int lo, int hi) { System.arraycopy(es, hi, es, lo, elementCount - hi); for (int to = elementCount, i = (elementCount -= hi - lo); i < to; i++) es[i] = null; } /** * Loads a {@code Vector} instance from a stream * (that is, deserializes it). * This method performs checks to ensure the consistency * of the fields. * * @param in the stream * @throws java.io.IOException if an I/O error occurs * @throws ClassNotFoundException if the stream contains data * of a non-existing class */ @java.io.Serial private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { ObjectInputStream.GetField gfields = in.readFields(); int count = gfields.get("elementCount", 0); Object[] data = (Object[])gfields.get("elementData", null); if (count < 0 || data == null || count > data.length) { throw new StreamCorruptedException("Inconsistent vector internals"); } elementCount = count; elementData = data.clone(); } /** * Saves the state of the {@code Vector} instance to a stream * (that is, serializes it). * This method performs synchronization to ensure the consistency * of the serialized data. * * @param s the stream * @throws java.io.IOException if an I/O error occurs */ @java.io.Serial private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { final java.io.ObjectOutputStream.PutField fields = s.putFields(); final Object[] data; synchronized (this) { fields.put("capacityIncrement", capacityIncrement); fields.put("elementCount", elementCount); data = elementData.clone(); } fields.put("elementData", data); s.writeFields(); } /** * Returns a list iterator over the elements in this list (in proper * sequence), starting at the specified position in the list. * The specified index indicates the first element that would be * returned by an initial call to {@link ListIterator#next next}. * An initial call to {@link ListIterator#previous previous} would * return the element with the specified index minus one. * * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>. * * @throws IndexOutOfBoundsException {@inheritDoc} */ public synchronized ListIterator<E> listIterator(int index) { if (index < 0 || index > elementCount) throw new IndexOutOfBoundsException("Index: "+index); return new ListItr(index); } /** * Returns a list iterator over the elements in this list (in proper * sequence). * * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>. * * @see #listIterator(int) */ public synchronized ListIterator<E> listIterator() { return new ListItr(0); } /** * Returns an iterator over the elements in this list in proper sequence. * * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>. * * @return an iterator over the elements in this list in proper sequence */ public synchronized Iterator<E> iterator() { return new Itr(); } /** * An optimized version of AbstractList.Itr */ private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; public boolean hasNext() { // Racy but within spec, since modifications are checked // within or after synchronization in next/previous return cursor != elementCount; } public E next() { synchronized (Vector.this) { checkForComodification(); int i = cursor; if (i >= elementCount) throw new NoSuchElementException(); cursor = i + 1; return elementData(lastRet = i); } } public void remove() { if (lastRet == -1) throw new IllegalStateException(); synchronized (Vector.this) { checkForComodification(); Vector.this.remove(lastRet); expectedModCount = modCount; } cursor = lastRet; lastRet = -1; } @Override public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); synchronized (Vector.this) { final int size = elementCount; int i = cursor; if (i >= size) { return; } final Object[] es = elementData; if (i >= es.length) throw new ConcurrentModificationException(); while (i < size && modCount == expectedModCount) action.accept(elementAt(es, i++)); // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } /** * An optimized version of AbstractList.ListItr */ final class ListItr extends Itr implements ListIterator<E> { ListItr(int index) { super(); cursor = index; } public boolean hasPrevious() { return cursor != 0; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } public E previous() { synchronized (Vector.this) { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); cursor = i; return elementData(lastRet = i); } } public void set(E e) { if (lastRet == -1) throw new IllegalStateException(); synchronized (Vector.this) { checkForComodification(); Vector.this.set(lastRet, e); } } public void add(E e) { int i = cursor; synchronized (Vector.this) { checkForComodification(); Vector.this.add(i, e); expectedModCount = modCount; } cursor = i + 1; lastRet = -1; } } /** * @throws NullPointerException {@inheritDoc} */ @Override public synchronized void forEach(Consumer<? super E> action) { Objects.requireNonNull(action); final int expectedModCount = modCount; final Object[] es = elementData; final int size = elementCount; for (int i = 0; modCount == expectedModCount && i < size; i++) action.accept(elementAt(es, i)); if (modCount != expectedModCount) throw new ConcurrentModificationException(); } /** * @throws NullPointerException {@inheritDoc} */ @Override public synchronized void replaceAll(UnaryOperator<E> operator) { Objects.requireNonNull(operator); final int expectedModCount = modCount; final Object[] es = elementData; final int size = elementCount; for (int i = 0; modCount == expectedModCount && i < size; i++) es[i] = operator.apply(elementAt(es, i)); if (modCount != expectedModCount) throw new ConcurrentModificationException(); // TODO(8203662): remove increment of modCount from ... modCount++; } @SuppressWarnings("unchecked") @Override public synchronized void sort(Comparator<? super E> c) { final int expectedModCount = modCount; Arrays.sort((E[]) elementData, 0, elementCount, c); if (modCount != expectedModCount) throw new ConcurrentModificationException(); modCount++; } /** * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em> * and <em>fail-fast</em> {@link Spliterator} over the elements in this * list. * * <p>The {@code Spliterator} reports {@link Spliterator#SIZED}, * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}. * Overriding implementations should document the reporting of additional * characteristic values. * * @return a {@code Spliterator} over the elements in this list * @since 1.8 */ @Override public Spliterator<E> spliterator() { return new VectorSpliterator(null, 0, -1, 0); } /** Similar to ArrayList Spliterator */ final class VectorSpliterator implements Spliterator<E> { private Object[] array; private int index; // current index, modified on advance/split private int fence; // -1 until used; then one past last index private int expectedModCount; // initialized when fence set /** Creates new spliterator covering the given range. */ VectorSpliterator(Object[] array, int origin, int fence, int expectedModCount) { this.array = array; this.index = origin; this.fence = fence; this.expectedModCount = expectedModCount; } private int getFence() { // initialize on first use int hi; if ((hi = fence) < 0) { synchronized (Vector.this) { array = elementData; expectedModCount = modCount; hi = fence = elementCount; } } return hi; } public Spliterator<E> trySplit() { int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; return (lo >= mid) ? null : new VectorSpliterator(array, lo, index = mid, expectedModCount); } @SuppressWarnings("unchecked") public boolean tryAdvance(Consumer<? super E> action) { Objects.requireNonNull(action); int i; if (getFence() > (i = index)) { index = i + 1; action.accept((E)array[i]); if (modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } return false; } @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); final int hi = getFence(); final Object[] a = array; int i; for (i = index, index = hi; i < hi; i++) action.accept((E) a[i]); if (modCount != expectedModCount) throw new ConcurrentModificationException(); } public long estimateSize() { return getFence() - index; } public int characteristics() { return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED; } } void checkInvariants() { // assert elementCount >= 0; // assert elementCount == elementData.length || elementData[elementCount] == null; } }
mirkosertic/Bytecoder
classlib/java.base/src/main/resources/META-INF/modules/java.base/classes/java/util/Vector.java
Java
apache-2.0
56,351
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Azure.Core; using Azure.Core.Pipeline; using System; using System.Threading; using System.Threading.Tasks; namespace Azure.Security.KeyVault.Keys.Cryptography { internal class RemoteCryptographyClient : ICryptographyProvider { private readonly Uri _keyId; protected RemoteCryptographyClient() { } internal RemoteCryptographyClient(Uri keyId, TokenCredential credential, CryptographyClientOptions options) { Argument.AssertNotNull(keyId, nameof(keyId)); Argument.AssertNotNull(credential, nameof(credential)); _keyId = keyId; options ??= new CryptographyClientOptions(); string apiVersion = options.GetVersionString(); HttpPipeline pipeline = HttpPipelineBuilder.Build(options, new ChallengeBasedAuthenticationPolicy(credential)); Pipeline = new KeyVaultPipeline(keyId, apiVersion, pipeline, new ClientDiagnostics(options)); } internal RemoteCryptographyClient(KeyVaultPipeline pipeline) { Pipeline = pipeline; } internal KeyVaultPipeline Pipeline { get; } public bool SupportsOperation(KeyOperation operation) => true; public virtual async Task<Response<EncryptResult>> EncryptAsync(EncryptionAlgorithm algorithm, byte[] plaintext, CancellationToken cancellationToken = default) { var parameters = new KeyEncryptParameters() { Algorithm = algorithm.ToString(), Value = plaintext, }; using DiagnosticScope scope = Pipeline.CreateScope($"{nameof(RemoteCryptographyClient)}.{nameof(Encrypt)}"); scope.AddAttribute("key", _keyId); scope.Start(); try { return await Pipeline.SendRequestAsync(RequestMethod.Post, parameters, () => new EncryptResult { Algorithm = algorithm }, cancellationToken, "/encrypt").ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } public virtual Response<EncryptResult> Encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, CancellationToken cancellationToken = default) { var parameters = new KeyEncryptParameters() { Algorithm = algorithm.ToString(), Value = plaintext, }; using DiagnosticScope scope = Pipeline.CreateScope($"{nameof(RemoteCryptographyClient)}.{nameof(Encrypt)}"); scope.AddAttribute("key", _keyId); scope.Start(); try { return Pipeline.SendRequest(RequestMethod.Post, parameters, () => new EncryptResult { Algorithm = algorithm }, cancellationToken, "/encrypt"); } catch (Exception e) { scope.Failed(e); throw; } } public virtual async Task<Response<DecryptResult>> DecryptAsync(EncryptionAlgorithm algorithm, byte[] ciphertext, CancellationToken cancellationToken = default) { var parameters = new KeyEncryptParameters() { Algorithm = algorithm.ToString(), Value = ciphertext, }; using DiagnosticScope scope = Pipeline.CreateScope($"{nameof(RemoteCryptographyClient)}.{nameof(Decrypt)}"); scope.AddAttribute("key", _keyId); scope.Start(); try { return await Pipeline.SendRequestAsync(RequestMethod.Post, parameters, () => new DecryptResult { Algorithm = algorithm }, cancellationToken, "/decrypt").ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } public virtual Response<DecryptResult> Decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext, CancellationToken cancellationToken = default) { var parameters = new KeyEncryptParameters() { Algorithm = algorithm.ToString(), Value = ciphertext, }; using DiagnosticScope scope = Pipeline.CreateScope($"{nameof(RemoteCryptographyClient)}.{nameof(Decrypt)}"); scope.AddAttribute("key", _keyId); scope.Start(); try { return Pipeline.SendRequest(RequestMethod.Post, parameters, () => new DecryptResult { Algorithm = algorithm }, cancellationToken, "/decrypt"); } catch (Exception e) { scope.Failed(e); throw; } } public virtual async Task<Response<WrapResult>> WrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, CancellationToken cancellationToken = default) { var parameters = new KeyWrapParameters() { Algorithm = algorithm.ToString(), Key = key }; using DiagnosticScope scope = Pipeline.CreateScope($"{nameof(RemoteCryptographyClient)}.{nameof(WrapKey)}"); scope.AddAttribute("key", _keyId); scope.Start(); try { return await Pipeline.SendRequestAsync(RequestMethod.Post, parameters, () => new WrapResult { Algorithm = algorithm }, cancellationToken, "/wrapKey").ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } public virtual Response<WrapResult> WrapKey(KeyWrapAlgorithm algorithm, byte[] key, CancellationToken cancellationToken = default) { var parameters = new KeyWrapParameters() { Algorithm = algorithm.ToString(), Key = key }; using DiagnosticScope scope = Pipeline.CreateScope($"{nameof(RemoteCryptographyClient)}.{nameof(WrapKey)}"); scope.AddAttribute("key", _keyId); scope.Start(); try { return Pipeline.SendRequest(RequestMethod.Post, parameters, () => new WrapResult { Algorithm = algorithm }, cancellationToken, "/wrapKey"); } catch (Exception e) { scope.Failed(e); throw; } } public virtual async Task<Response<UnwrapResult>> UnwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, CancellationToken cancellationToken = default) { var parameters = new KeyWrapParameters() { Algorithm = algorithm.ToString(), Key = encryptedKey }; using DiagnosticScope scope = Pipeline.CreateScope($"{nameof(RemoteCryptographyClient)}.{nameof(UnwrapKey)}"); scope.AddAttribute("key", _keyId); scope.Start(); try { return await Pipeline.SendRequestAsync(RequestMethod.Post, parameters, () => new UnwrapResult { Algorithm = algorithm }, cancellationToken, "/unwrapKey").ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } public virtual Response<UnwrapResult> UnwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, CancellationToken cancellationToken = default) { var parameters = new KeyWrapParameters() { Algorithm = algorithm.ToString(), Key = encryptedKey }; using DiagnosticScope scope = Pipeline.CreateScope($"{nameof(RemoteCryptographyClient)}.{nameof(UnwrapKey)}"); scope.AddAttribute("key", _keyId); scope.Start(); try { return Pipeline.SendRequest(RequestMethod.Post, parameters, () => new UnwrapResult { Algorithm = algorithm }, cancellationToken, "/unwrapKey"); } catch (Exception e) { scope.Failed(e); throw; } } public virtual async Task<Response<SignResult>> SignAsync(SignatureAlgorithm algorithm, byte[] digest, CancellationToken cancellationToken = default) { var parameters = new KeySignParameters { Algorithm = algorithm.ToString(), Digest = digest }; using DiagnosticScope scope = Pipeline.CreateScope($"{nameof(RemoteCryptographyClient)}.{nameof(Sign)}"); scope.AddAttribute("key", _keyId); scope.Start(); try { return await Pipeline.SendRequestAsync(RequestMethod.Post, parameters, () => new SignResult { Algorithm = algorithm }, cancellationToken, "/sign").ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } public virtual Response<SignResult> Sign(SignatureAlgorithm algorithm, byte[] digest, CancellationToken cancellationToken = default) { var parameters = new KeySignParameters { Algorithm = algorithm.ToString(), Digest = digest }; using DiagnosticScope scope = Pipeline.CreateScope($"{nameof(RemoteCryptographyClient)}.{nameof(Sign)}"); scope.AddAttribute("key", _keyId); scope.Start(); try { return Pipeline.SendRequest(RequestMethod.Post, parameters, () => new SignResult { Algorithm = algorithm }, cancellationToken, "/sign"); } catch (Exception e) { scope.Failed(e); throw; } } public virtual async Task<Response<VerifyResult>> VerifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, CancellationToken cancellationToken = default) { var parameters = new KeyVerifyParameters { Algorithm = algorithm.ToString(), Digest = digest, Signature = signature }; using DiagnosticScope scope = Pipeline.CreateScope($"{nameof(RemoteCryptographyClient)}.{nameof(Verify)}"); scope.AddAttribute("key", _keyId); scope.Start(); try { return await Pipeline.SendRequestAsync(RequestMethod.Post, parameters, () => new VerifyResult { Algorithm = algorithm, KeyId = _keyId.ToString() }, cancellationToken, "/verify").ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } public virtual Response<VerifyResult> Verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, CancellationToken cancellationToken = default) { var parameters = new KeyVerifyParameters { Algorithm = algorithm.ToString(), Digest = digest, Signature = signature }; using DiagnosticScope scope = Pipeline.CreateScope($"{nameof(RemoteCryptographyClient)}.{nameof(Verify)}"); scope.AddAttribute("key", _keyId); scope.Start(); try { return Pipeline.SendRequest(RequestMethod.Post, parameters, () => new VerifyResult { Algorithm = algorithm, KeyId = _keyId.ToString() }, cancellationToken, "/verify"); } catch (Exception e) { scope.Failed(e); throw; } } internal virtual async Task<Response<KeyVaultKey>> GetKeyAsync(CancellationToken cancellationToken = default) { using DiagnosticScope scope = Pipeline.CreateScope($"{nameof(RemoteCryptographyClient)}.{nameof(GetKey)}"); scope.AddAttribute("key", _keyId); scope.Start(); try { return await Pipeline.SendRequestAsync(RequestMethod.Get, () => new KeyVaultKey(), cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } internal virtual Response<KeyVaultKey> GetKey(CancellationToken cancellationToken = default) { using DiagnosticScope scope = Pipeline.CreateScope($"{nameof(RemoteCryptographyClient)}.{nameof(GetKey)}"); scope.AddAttribute("key", _keyId); scope.Start(); try { return Pipeline.SendRequest(RequestMethod.Get, () => new KeyVaultKey(), cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } bool ICryptographyProvider.ShouldRemote => false; async Task<EncryptResult> ICryptographyProvider.EncryptAsync(EncryptionAlgorithm algorithm, byte[] plaintext, CancellationToken cancellationToken) { return await EncryptAsync(algorithm, plaintext, cancellationToken).ConfigureAwait(false); } EncryptResult ICryptographyProvider.Encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, CancellationToken cancellationToken) { return Encrypt(algorithm, plaintext, cancellationToken); } async Task<DecryptResult> ICryptographyProvider.DecryptAsync(EncryptionAlgorithm algorithm, byte[] ciphertext, CancellationToken cancellationToken) { return await DecryptAsync(algorithm, ciphertext, cancellationToken).ConfigureAwait(false); } DecryptResult ICryptographyProvider.Decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext, CancellationToken cancellationToken) { return Decrypt(algorithm, ciphertext, cancellationToken); } async Task<WrapResult> ICryptographyProvider.WrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, CancellationToken cancellationToken) { return await WrapKeyAsync(algorithm, key, cancellationToken).ConfigureAwait(false); } WrapResult ICryptographyProvider.WrapKey(KeyWrapAlgorithm algorithm, byte[] key, CancellationToken cancellationToken) { return WrapKey(algorithm, key, cancellationToken); } async Task<UnwrapResult> ICryptographyProvider.UnwrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] encryptedKey, CancellationToken cancellationToken) { return await UnwrapKeyAsync(algorithm, encryptedKey, cancellationToken).ConfigureAwait(false); } UnwrapResult ICryptographyProvider.UnwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, CancellationToken cancellationToken) { return UnwrapKey(algorithm, encryptedKey, cancellationToken); } async Task<SignResult> ICryptographyProvider.SignAsync(SignatureAlgorithm algorithm, byte[] digest, CancellationToken cancellationToken) { return await SignAsync(algorithm, digest, cancellationToken).ConfigureAwait(false); } SignResult ICryptographyProvider.Sign(SignatureAlgorithm algorithm, byte[] digest, CancellationToken cancellationToken) { return Sign(algorithm, digest, cancellationToken); } async Task<VerifyResult> ICryptographyProvider.VerifyAsync(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, CancellationToken cancellationToken) { return await VerifyAsync(algorithm, digest, signature, cancellationToken).ConfigureAwait(false); } VerifyResult ICryptographyProvider.Verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, CancellationToken cancellationToken) { return Verify(algorithm, digest, signature, cancellationToken); } } }
stankovski/azure-sdk-for-net
sdk/keyvault/Azure.Security.KeyVault.Keys/src/Cryptography/RemoteCryptographyClient.cs
C#
apache-2.0
16,295
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ce/model/GetReservationCoverageResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::CostExplorer::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; GetReservationCoverageResult::GetReservationCoverageResult() { } GetReservationCoverageResult::GetReservationCoverageResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } GetReservationCoverageResult& GetReservationCoverageResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("CoveragesByTime")) { Array<JsonView> coveragesByTimeJsonList = jsonValue.GetArray("CoveragesByTime"); for(unsigned coveragesByTimeIndex = 0; coveragesByTimeIndex < coveragesByTimeJsonList.GetLength(); ++coveragesByTimeIndex) { m_coveragesByTime.push_back(coveragesByTimeJsonList[coveragesByTimeIndex].AsObject()); } } if(jsonValue.ValueExists("Total")) { m_total = jsonValue.GetObject("Total"); } if(jsonValue.ValueExists("NextPageToken")) { m_nextPageToken = jsonValue.GetString("NextPageToken"); } return *this; }
jt70471/aws-sdk-cpp
aws-cpp-sdk-ce/source/model/GetReservationCoverageResult.cpp
C++
apache-2.0
1,482
package com.github.toastshaman.dropwizard.auth.jwt.example; import com.github.toastshaman.dropwizard.auth.jwt.JWTAuthFilter; import com.github.toastshaman.dropwizard.auth.jwt.JsonWebTokenParser; import com.github.toastshaman.dropwizard.auth.jwt.JsonWebTokenValidator; import com.github.toastshaman.dropwizard.auth.jwt.hmac.HmacSHA512Verifier; import com.github.toastshaman.dropwizard.auth.jwt.model.JsonWebToken; import com.github.toastshaman.dropwizard.auth.jwt.parser.DefaultJsonWebTokenParser; import com.github.toastshaman.dropwizard.auth.jwt.validator.ExpiryValidator; import com.google.common.base.Optional; import io.dropwizard.Application; import io.dropwizard.auth.AuthDynamicFeature; import io.dropwizard.auth.AuthValueFactoryProvider; import io.dropwizard.auth.Authenticator; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature; import java.security.Principal; /** * A sample dropwizard application that shows how to set up the JWT Authentication provider. * <p/> * The Authentication Provider will parse the tokens supplied in the "Authorization" HTTP header in each HTTP request * given your resource is protected with the @Auth annotation. */ public class JwtAuthApplication extends Application<MyConfiguration> { @Override public void initialize(Bootstrap<MyConfiguration> configurationBootstrap) { } @Override public void run(MyConfiguration configuration, Environment environment) throws Exception { final JsonWebTokenParser tokenParser = new DefaultJsonWebTokenParser(); final HmacSHA512Verifier tokenVerifier = new HmacSHA512Verifier(configuration.getJwtTokenSecret()); environment.jersey().register(new AuthDynamicFeature( new JWTAuthFilter.Builder<>() .setTokenParser(tokenParser) .setTokenVerifier(tokenVerifier) .setRealm("realm") .setPrefix("Bearer") .setAuthenticator(new JwtAuthApplication.ExampleAuthenticator()) .buildAuthFilter())); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(Principal.class)); environment.jersey().register(RolesAllowedDynamicFeature.class); environment.jersey().register(new SecuredResource(configuration.getJwtTokenSecret())); } private static class ExampleAuthenticator implements Authenticator<JsonWebToken, Principal> { @Override public Optional<Principal> authenticate(JsonWebToken token) { final JsonWebTokenValidator expiryValidator = new ExpiryValidator(); // Provide your own implementation to lookup users based on the principal attribute in the // JWT Token. E.g.: lookup users from a database etc. // This method will be called once the token's signature has been verified // In case you want to verify different parts of the token you can do that here. // E.g.: Verifying that the provided token has not expired. // All JsonWebTokenExceptions will result in a 401 Unauthorized response. expiryValidator.validate(token); if ("good-guy".equals(token.claim().subject())) { final Principal principal = new Principal() { @Override public String getName() { return "good-guy"; } }; return Optional.of(principal); } return Optional.absent(); } } public static void main(String[] args) throws Exception { new JwtAuthApplication().run(new String[]{"server"}); } }
windbender/dropwizard-auth-jwt
src/test/java/com/github/toastshaman/dropwizard/auth/jwt/example/JwtAuthApplication.java
Java
apache-2.0
3,798
package mina; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MyLog { private static final Logger log = LoggerFactory.getLogger(MyLog.class); public static void log_cmd(byte[] data){ //int cmd_type = CommandParser.getCommandType(data); //System.out.println("cmd_type:" + cmd_type); } public static void log_data(String sPrefix, byte[] data){ int iLen = data.length; log.debug(sPrefix + "length:" + iLen); StringBuilder sDebug = new StringBuilder(); String sHex; for(int i = 0; i < iLen; i++){ sHex = String.format("0x%02x", data[i]&0xff); sDebug.append(sHex); //sDebug.append(Integer.toHexString(data[i]&0xff)); sDebug.append(" "); } log.debug(sDebug.toString()); log.debug(" "); } public static void log_output(byte[] data){ //log_data("<<<<<<output<<<<<", data); } public static void log_input(byte[] data){ //log_cmd(data); //log_data(">>>>>>input>>>>>>", data); } }
sunjob/sensor
src/mina/MyLog.java
Java
apache-2.0
948
var estabelecimentoViewCtrl = angular.module('estabelecimentoViewCtrl', ['ngResource']); estabelecimentoViewCtrl.controller('estabelecimentoViewCtrl', ['$scope', '$http', function ($scope, $http) { $scope.estabelecimentos = []; $scope.carregarPontosCriticos = function(){ $http.get("../webresources/com.andepuc.estabelecimentos").success(function (data, status){ $scope.estabelecimentos = data; }); }; }]);
ScHaFeR/AndePUCRS-WebService
andePuc/target/andePuc-1.0/js/controllers/estabelecimentoViewController.js
JavaScript
apache-2.0
497
#!/usr/bin/python """ Program for creating HTML plots """ import os import sys import json import time from readevtlog import * def imaging_iters(logs): start_time = 40.0 start_msg = "kernel init" end_msg = "imaging cleanup" got_start = False for k in sorted(logs): tt = logs[k].time for e in tt : if e.msg == start_msg: start = e.t1 got_start = True if got_start and e.msg == end_msg: print e.t2-start, ",", print "" data_commands = { "imaging_iters" : imaging_iters, } # Get parameters cmd = sys.argv[1] nm = sys.argv[2] # Open input files logs = read_timelines(nm) # Write table data_commands[cmd](logs)
SKA-ScienceDataProcessor/RC
MS6/visualize/csv_generator.py
Python
apache-2.0
744
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ec2/model/InstanceHealthStatus.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace EC2 { namespace Model { namespace InstanceHealthStatusMapper { static const int healthy_HASH = HashingUtils::HashString("healthy"); static const int unhealthy_HASH = HashingUtils::HashString("unhealthy"); InstanceHealthStatus GetInstanceHealthStatusForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == healthy_HASH) { return InstanceHealthStatus::healthy; } else if (hashCode == unhealthy_HASH) { return InstanceHealthStatus::unhealthy; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<InstanceHealthStatus>(hashCode); } return InstanceHealthStatus::NOT_SET; } Aws::String GetNameForInstanceHealthStatus(InstanceHealthStatus enumValue) { switch(enumValue) { case InstanceHealthStatus::healthy: return "healthy"; case InstanceHealthStatus::unhealthy: return "unhealthy"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace InstanceHealthStatusMapper } // namespace Model } // namespace EC2 } // namespace Aws
awslabs/aws-sdk-cpp
aws-cpp-sdk-ec2/source/model/InstanceHealthStatus.cpp
C++
apache-2.0
2,041
/* * JBoss, Home of Professional Open Source * Copyright 2010 Red Hat Inc. and/or its affiliates and other * contributors as indicated by the @author tags. All rights reserved. * See the copyright.txt in the distribution for a full listing of * individual contributors. * * This 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 2.1 of * the License, or (at your option) any later version. * * This software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.infinispan.loaders.cassandra; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import net.dataforte.cassandra.pool.PoolProperties; import org.apache.cassandra.thrift.ConsistencyLevel; import org.infinispan.config.ConfigurationException; import org.infinispan.loaders.AbstractCacheStoreConfig; import org.infinispan.loaders.keymappers.DefaultTwoWayKey2StringMapper; import org.infinispan.util.FileLookupFactory; import org.infinispan.util.Util; /** * Configures {@link CassandraCacheStore}. */ public class CassandraCacheStoreConfig extends AbstractCacheStoreConfig { /** * @configRef desc="The Cassandra keyspace" */ String keySpace = "Infinispan"; /** * @configRef desc="The Cassandra column family for entries" */ String entryColumnFamily = "InfinispanEntries"; /** * @configRef desc="The Cassandra column family for expirations" */ String expirationColumnFamily = "InfinispanExpiration"; /** * @configRef desc="Whether the keySpace is shared between multiple caches" */ boolean sharedKeyspace = false; /** * @configRef desc="Which Cassandra consistency level to use when reading" */ String readConsistencyLevel = "ONE"; /** * @configRef desc="Which Cassandra consistency level to use when writing" */ String writeConsistencyLevel = "ONE"; /** * @configRef desc= * "An optional properties file for configuring the underlying cassandra connection pool" */ String configurationPropertiesFile; /** * @configRef desc= * "The keymapper for converting keys to strings (uses the DefaultTwoWayKey2Stringmapper by default)" */ String keyMapper = DefaultTwoWayKey2StringMapper.class.getName(); /** * @configRef desc= * "Whether to automatically create the keyspace with the appropriate column families (true by default)" */ boolean autoCreateKeyspace = true; protected PoolProperties poolProperties; public CassandraCacheStoreConfig() { setCacheLoaderClassName(CassandraCacheStore.class.getName()); poolProperties = new PoolProperties(); } public String getKeySpace() { return keySpace; } public void setKeySpace(String keySpace) { this.keySpace = keySpace; } public String getEntryColumnFamily() { return entryColumnFamily; } public void setEntryColumnFamily(String entryColumnFamily) { this.entryColumnFamily = entryColumnFamily; } public String getExpirationColumnFamily() { return expirationColumnFamily; } public void setExpirationColumnFamily(String expirationColumnFamily) { this.expirationColumnFamily = expirationColumnFamily; } public boolean isSharedKeyspace() { return sharedKeyspace; } public void setSharedKeyspace(boolean sharedKeyspace) { this.sharedKeyspace = sharedKeyspace; } public String getReadConsistencyLevel() { return readConsistencyLevel; } public void setReadConsistencyLevel(String readConsistencyLevel) { this.readConsistencyLevel = readConsistencyLevel; } public String getWriteConsistencyLevel() { return writeConsistencyLevel; } public void setWriteConsistencyLevel(String writeConsistencyLevel) { this.writeConsistencyLevel = writeConsistencyLevel; } public PoolProperties getPoolProperties() { return poolProperties; } public void setHost(String host) { poolProperties.setHost(host); } public String getHost() { return poolProperties.getHost(); } public void setPort(int port) { poolProperties.setPort(port); } public int getPort() { return poolProperties.getPort(); } public boolean isFramed() { return poolProperties.isFramed(); } public String getPassword() { return poolProperties.getPassword(); } public String getUsername() { return poolProperties.getUsername(); } public void setFramed(boolean framed) { poolProperties.setFramed(framed); } public void setPassword(String password) { poolProperties.setPassword(password); } public void setUsername(String username) { poolProperties.setUsername(username); } public void setDatasourceJndiLocation(String location) { poolProperties.setDataSourceJNDI(location); } public String getDatasourceJndiLocation() { return poolProperties.getDataSourceJNDI(); } public String getConfigurationPropertiesFile() { return configurationPropertiesFile; } public void setConfigurationPropertiesFile(String configurationPropertiesFile) { this.configurationPropertiesFile = configurationPropertiesFile; readConfigurationProperties(); } private void readConfigurationProperties() { if (configurationPropertiesFile == null || configurationPropertiesFile.trim().length() == 0) return; InputStream i = FileLookupFactory.newInstance().lookupFile(configurationPropertiesFile, getClassLoader()); if (i != null) { Properties p = new Properties(); try { p.load(i); } catch (IOException ioe) { throw new ConfigurationException("Unable to read environment properties file " + configurationPropertiesFile, ioe); } finally { Util.close(i); } // Apply all properties to the PoolProperties object for (String propertyName : p.stringPropertyNames()) { poolProperties.set(propertyName, p.getProperty(propertyName)); } } } public String getKeyMapper() { return keyMapper; } public void setKeyMapper(String keyMapper) { this.keyMapper = keyMapper; } public boolean isAutoCreateKeyspace() { return autoCreateKeyspace; } public void setAutoCreateKeyspace(boolean autoCreateKeyspace) { this.autoCreateKeyspace = autoCreateKeyspace; } public void setReadConsistencyLevel(ConsistencyLevel readConsistencyLevel) { this.readConsistencyLevel = readConsistencyLevel.toString(); } public void setWriteConsistencyLevel(ConsistencyLevel writeConsistencyLevel) { this.writeConsistencyLevel = writeConsistencyLevel.toString(); } }
nmldiegues/stibt
infinispan/cachestore/cassandra/src/main/java/org/infinispan/loaders/cassandra/CassandraCacheStoreConfig.java
Java
apache-2.0
7,387
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_log import log as logging from oslo_service import threadgroup from blazar.db import api as db_api LOG = logging.getLogger(__name__) class BaseMonitor(object): """Base class for monitoring classes.""" def __init__(self, monitor_plugins): self.monitor_plugins = monitor_plugins self.tg = threadgroup.ThreadGroup() self.healing_timers = [] def start_monitoring(self): """Start monitoring.""" self.start_periodic_healing() def stop_monitoring(self): """Stop monitoring.""" self.stop_periodic_healing() def start_periodic_healing(self): """Start periodic healing process.""" for plugin in self.monitor_plugins: healing_interval_mins = plugin.get_healing_interval() if healing_interval_mins > 0: self.healing_timers.append( self.tg.add_timer(healing_interval_mins * 60, self.call_monitor_plugin, None, plugin.heal)) def stop_periodic_healing(self): """Stop periodic healing process.""" for timer in self.healing_timers: self.tg.timer_done(timer) def call_monitor_plugin(self, callback, *args, **kwargs): """Call a callback and update lease/reservation flags.""" # This method has to handle any exception internally. It shouldn't # raise an exception because the timer threads in the BaseMonitor class # terminates its execution once the thread has received any exception. try: # The callback() has to return a dictionary of # {reservation id: flags to update}. # e.g. {'dummyid': {'missing_resources': True}} reservation_flags = callback(*args, **kwargs) if reservation_flags: self._update_flags(reservation_flags) except Exception as e: LOG.exception('Caught an exception while executing a callback. ' '%s', str(e)) def _update_flags(self, reservation_flags): """Update lease/reservation flags.""" lease_ids = set([]) for reservation_id, flags in reservation_flags.items(): db_api.reservation_update(reservation_id, flags) LOG.debug('Reservation %s was updated: %s', reservation_id, flags) reservation = db_api.reservation_get(reservation_id) lease_ids.add(reservation['lease_id']) for lease_id in lease_ids: LOG.debug('Lease %s was updated: {"degraded": True}', lease_id) db_api.lease_update(lease_id, {'degraded': True})
stackforge/blazar
blazar/monitor/base.py
Python
apache-2.0
3,283
/** * Copyright 2014 * SMEdit https://github.com/StarMade/SMEdit * SMTools https://github.com/StarMade/SMTools * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. **/ package jo.sm.plugins.all.props; import jo.sm.ui.act.plugin.Description; /** * @Auther Jo Jaquinta for SMEdit Classic - version 1.0 **/ @Description(displayName = "Properties", shortDescription = "Properties affecting the whole application.") public class PropsParameters { @Description(displayName = "Invert X", shortDescription = "Invert X Axis on mouse") private boolean mInvertXAxis; @Description(displayName = "Invert Y", shortDescription = "Invert Y Axis on mouse") private boolean mInvertYAxis; public PropsParameters() { } public boolean isInvertXAxis() { return mInvertXAxis; } public void setInvertXAxis(boolean invertXAxis) { mInvertXAxis = invertXAxis; } public boolean isInvertYAxis() { return mInvertYAxis; } public void setInvertYAxis(boolean invertYAxis) { mInvertYAxis = invertYAxis; } }
skunkiferous/SMEdit
jo_plugin/src/main/java/jo/sm/plugins/all/props/PropsParameters.java
Java
apache-2.0
1,578
/* * Copyright 2021 Apollo Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.ctrip.framework.apollo.spring.config; import java.util.List; import com.ctrip.framework.apollo.Config; import com.google.common.collect.Lists; public class ConfigPropertySourceFactory { private final List<ConfigPropertySource> configPropertySources = Lists.newLinkedList(); public ConfigPropertySource getConfigPropertySource(String name, Config source) { ConfigPropertySource configPropertySource = new ConfigPropertySource(name, source); configPropertySources.add(configPropertySource); return configPropertySource; } public List<ConfigPropertySource> getAllConfigPropertySources() { return Lists.newLinkedList(configPropertySources); } }
lepdou/apollo
apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/ConfigPropertySourceFactory.java
Java
apache-2.0
1,284
# ---------------------------------------------------------------------------- # Copyright 2014 Nervana Systems Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------- """ For machine generated datasets. """ import numpy as np from neon import NervanaObject class Task(NervanaObject): """ Base class from which ticker tasks inherit. """ def fetch_io(self, time_steps): """ Generate inputs, outputs numpy tensor pair of size appropriate for this minibatch """ columns = time_steps * self.be.bsz inputs = np.zeros((self.nin, columns)) outputs = np.zeros((self.nout, columns)) return inputs, outputs def fill_buffers(self, time_steps, inputs, outputs, in_tensor, out_tensor, mask): """ Do some logistical stuff to get our numpy arrays safely to device. This can almost certainly be cleaned up. """ # Put inputs and outputs, which are too small, into properly shaped arrays columns = time_steps * self.be.bsz inC = np.zeros((self.nin, self.max_columns)) outC = np.zeros((self.nout, self.max_columns)) inC[:, :columns] = inputs outC[:, :columns] = outputs # Copy those arrays to device in_tensor.set(inC) out_tensor.set(outC) # Set a mask over the unused part of the buffer mask[:, :columns] = 1 mask[:, columns:] = 0 class CopyTask(Task): """ The copy task from the Neural Turing Machines paper: http://arxiv.org/abs/1410.5401 This version of the task is batched. All sequences in the same mini-batch are the same length, but every new minibatch has a randomly chosen minibatch length. When a given minibatch has length < seq_len_max, we mask the outputs for time steps after time_steps_max. The generated data is laid out in the same way as other RNN data in neon. """ def __init__(self, seq_len_max, vec_size): """ Set up the attributes that Ticker needs to see. Args: seq_len_max (int): longest allowable sequence length vec_size (int): width of the bit-vector to be copied (was 8 in paper) """ self.seq_len_max = seq_len_max self.vec_size = vec_size self.nout = self.vec_size # output has the same dimension as the underlying bit vector self.nin = self.vec_size + 2 # input has more dims (for the start and stop channels) self.time_steps_func = lambda l: 2 * l + 2 self.time_steps_max = 2 * self.seq_len_max + 2 self.time_steps_max = self.time_steps_func(self.seq_len_max) self.max_columns = self.time_steps_max * self.be.bsz def synthesize(self, in_tensor, out_tensor, mask): """ Create a new minibatch of ticker copy task data. Args: in_tensor: device buffer holding inputs out_tensor: device buffer holding outputs mask: device buffer for the output mask """ # All sequences in a minibatch are the same length for convenience seq_len = np.random.randint(1, self.seq_len_max + 1) time_steps = self.time_steps_func(seq_len) # Generate intermediate buffers of the right size inputs, outputs = super(CopyTask, self).fetch_io(time_steps) # Set the start bit inputs[-2, :self.be.bsz] = 1 # Generate the sequence to be copied seq = np.random.randint(2, size=(self.vec_size, seq_len * self.be.bsz)) # Set the stop bit stop_loc = self.be.bsz * (seq_len + 1) inputs[-1, stop_loc:stop_loc + self.be.bsz] = 1 # Place the actual sequence to copy in inputs inputs[:self.vec_size, self.be.bsz:stop_loc] = seq # Now place that same sequence in a different place in outputs outputs[:, self.be.bsz * (seq_len + 2):] = seq # Fill the device minibatch buffers super(CopyTask, self).fill_buffers(time_steps, inputs, outputs, in_tensor, out_tensor, mask) class RepeatCopyTask(Task): """ The repeat copy task from the Neural Turing Machines paper: http://arxiv.org/abs/1410.5401 See comments on CopyTask class for more details. """ def __init__(self, seq_len_max, repeat_count_max, vec_size): """ Set up the attributes that Ticker needs to see. Args: seq_len_max (int): longest allowable sequence length repeat_count_max (int): max number of repeats vec_size (int): width of the bit-vector to be copied (was 8 in paper) """ self.seq_len_max = seq_len_max self.repeat_count_max = seq_len_max self.vec_size = vec_size self.nout = self.vec_size + 1 # we output the sequence and a stop bit in a stop channel self.nin = self.vec_size + 2 # input has more dims (for the start and stop channels) # seq is seen once as input, repeat_count times as output, with a # start bit, stop bit, and output stop bit self.time_steps_func = lambda l, r: l * (r + 1) + 3 self.time_steps_max = self.time_steps_func(self.seq_len_max, self.repeat_count_max) self.max_columns = self.time_steps_max * self.be.bsz def synthesize(self, in_tensor, out_tensor, mask): """ Create a new minibatch of ticker repeat copy task data. Args: in_tensor: device buffer holding inputs out_tensor: device buffer holding outputs mask: device buffer for the output mask """ # All sequences in a minibatch are the same length for convenience seq_len = np.random.randint(1, self.seq_len_max + 1) repeat_count = np.random.randint(1, self.repeat_count_max + 1) time_steps = self.time_steps_func(seq_len, repeat_count) # Get the minibatch specific numpy buffers inputs, outputs = super(RepeatCopyTask, self).fetch_io(time_steps) # Set the start bit inputs[-2, :self.be.bsz] = 1 # Generate the sequence to be copied seq = np.random.randint(2, size=(self.vec_size, seq_len * self.be.bsz)) # Set the repeat count # TODO: should we normalize repeat count? stop_loc = self.be.bsz * (seq_len + 1) inputs[-1, stop_loc:stop_loc + self.be.bsz] = repeat_count # Place the actual sequence to copy in inputs inputs[:self.vec_size, self.be.bsz:stop_loc] = seq # Now place that same sequence repeat_copy times in outputs for i in range(repeat_count): start = self.be.bsz * ((i + 1) * seq_len + 2) stop = start + seq_len * self.be.bsz outputs[:-1, start:stop] = seq # Place the output finish bit outputs[-1, -self.be.bsz:] = 1 # Fill the device minibatch buffers super(RepeatCopyTask, self).fill_buffers(time_steps, inputs, outputs, in_tensor, out_tensor, mask) class PrioritySortTask(Task): """ The priority sort task from the Neural Turing Machines paper: http://arxiv.org/abs/1410.5401 See comments on CopyTask class for more details. """ def __init__(self, seq_len_max, vec_size): """ Set up the attributes that Ticker needs to see. Args: seq_len_max (int): longest allowable sequence length vec_size (int): width of the bit-vector to be copied (was 8 in paper) """ self.seq_len_max = seq_len_max self.vec_size = vec_size self.nout = self.vec_size # we output the sorted sequence, with no stop bit self.nin = self.vec_size + 3 # extra channels for start, stop, and priority # seq is seen once as input with start and stop bits # then we output seq in sorted order self.time_steps_func = lambda l: 2 * l + 2 self.time_steps_max = self.time_steps_func(self.seq_len_max) self.max_columns = self.time_steps_max * self.be.bsz def synthesize(self, in_tensor, out_tensor, mask): """ Create a new minibatch of ticker priority sort task data. Args: in_tensor: device buffer holding inputs out_tensor: device buffer holding outputs mask: device buffer for the output mask """ # All sequences in a minibatch are the same length for convenience seq_len = np.random.randint(1, self.seq_len_max + 1) time_steps = self.time_steps_func(seq_len) # Get the minibatch specific numpy buffers inputs, outputs = super(PrioritySortTask, self).fetch_io(time_steps) # Set the start bit inputs[-3, :self.be.bsz] = 1 # Generate the sequence to be copied seq = np.random.randint(2, size=(self.nin, seq_len * self.be.bsz)).astype(float) # Zero out the start, stop, and priority channels seq[-3:, :] = 0 # Generate the scalar priorities and put them in seq priorities = np.random.uniform(-1, 1, size=(seq_len * self.be.bsz,)) seq[-1, :] = priorities # Set the stop bit stop_loc = self.be.bsz * (seq_len + 1) inputs[-2, stop_loc:stop_loc + self.be.bsz] = 1 # Place the actual sequence to copy in inputs inputs[:, self.be.bsz:stop_loc] = seq # sort the sequences for i in range(self.be.bsz): # for every sequence in the batch # x <- every column in the sequence x = seq[:, i::self.be.bsz] # sort that set of columns by elt in the last row (the priority) x = x[:, x[-1, :].argsort()] # put those columns back into minibatch in the right places seq[:, i::self.be.bsz] = x outputs[:, self.be.bsz * (seq_len + 2):] = seq[:self.nout, :] # Fill the device minibatch buffers super(PrioritySortTask, self).fill_buffers(time_steps, inputs, outputs, in_tensor, out_tensor, mask) class Ticker(NervanaObject): """ This class defines methods for generating and iterating over ticker datasets. """ def reset(self): """ Reset has no meaning in the context of ticker data. """ pass def __init__(self, task): """ Construct a ticker dataset object. Args: Task is an object representing the task to be trained on It contains information about input and output size, sequence length, etc. It also implements a synthesize function, which is used to generate the next minibatch of data. """ self.task = task # These attributes don't make much sense in the context of tickers # but I suspect it will be hard to get rid of them self.batch_index = 0 self.nbatches = 100 self.ndata = self.nbatches * self.be.bsz # Alias these because other code relies on datasets having nin and nout self.nout = task.nout self.nin = task.nin # Configuration elsewhere relies on the existence of this self.shape = (self.nin, self.task.time_steps_max) # Initialize the inputs, the outputs, and the mask self.dev_X = self.be.iobuf((self.nin, self.task.time_steps_max)) self.dev_y = self.be.iobuf((self.nout, self.task.time_steps_max)) self.mask = self.be.iobuf((self.nout, self.task.time_steps_max)) def __iter__(self): """ Generator that can be used to iterate over this dataset. Yields: tuple : the next minibatch of data. The second element of the tuple is itself a tuple (t,m) with: t: the actual target as generated by the task object m: the output mask to account for the difference between the seq_length for this minibatch and the max seq_len, which is also the number of columns in X,t, and m """ self.batch_index = 0 while self.batch_index < self.nbatches: # The task object writes minibatch data into buffers we pass it self.task.synthesize(self.dev_X, self.dev_y, self.mask) self.batch_index += 1 yield self.dev_X, (self.dev_y, self.mask)
coufon/neon-distributed
neon/data/ticker.py
Python
apache-2.0
13,214
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package datafu.pig.random; import java.io.IOException; import java.util.UUID; import org.apache.pig.EvalFunc; import org.apache.pig.builtin.Nondeterministic; import org.apache.pig.data.*; import org.apache.pig.impl.logicalLayer.schema.Schema; /** * Generates a random UUID using java.util.UUID */ @Nondeterministic public class RandomUUID extends EvalFunc<String> { public String exec(Tuple input) throws IOException { return UUID.randomUUID().toString(); } @Override public Schema outputSchema(Schema input) { return new Schema(new Schema.FieldSchema("uuid", DataType.CHARARRAY)); } }
apache/incubator-datafu
datafu-pig/src/main/java/datafu/pig/random/RandomUUID.java
Java
apache-2.0
1,445
require 'spec_helper' require 'rack/test' include Rack::Test::Methods describe Crono::Web do let(:app) { Crono::Web } before do Crono::CronoJob.destroy_all @test_job_id = 'Perform TestJob every 5 seconds' @test_job_log = 'All runs ok' @test_job = Crono::CronoJob.create!( job_id: @test_job_id, log: @test_job_log ) end after { @test_job.destroy } describe '/' do it 'should show all jobs' do get '/' expect(last_response).to be_ok expect(last_response.body).to include @test_job_id end it 'should show a error mark when a job is unhealthy' do @test_job.update(healthy: false, last_performed_at: 10.minutes.ago) get '/' expect(last_response.body).to include 'Error' end it 'should show a success mark when a job is healthy' do @test_job.update(healthy: true, last_performed_at: 10.minutes.ago) get '/' expect(last_response.body).to include 'Success' end it 'should show a pending mark when a job is pending' do @test_job.update(healthy: nil) get '/' expect(last_response.body).to include 'Pending' end end describe '/job/:id' do it 'should show job log' do get "/job/#{@test_job.id}" expect(last_response).to be_ok expect(last_response.body).to include @test_job_id expect(last_response.body).to include @test_job_log end it 'should show a message about the unhealthy job' do message = 'An error occurs during the last execution of this job' @test_job.update(healthy: false) get "/job/#{@test_job.id}" expect(last_response.body).to include message end end end
plashchynski/crono
spec/web_spec.rb
Ruby
apache-2.0
1,684
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.indexing; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileWithId; import com.intellij.openapi.vfs.newvfs.impl.VirtualFileSystemEntry; import com.intellij.psi.search.FileTypeIndex; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.indexing.projectFilter.ProjectIndexableFilesFilterHolder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; final class UnindexedFilesFinder { private static final Logger LOG = Logger.getInstance(UnindexedFilesFinder.class); private final Project myProject; private final boolean myDoTraceForFilesToBeIndexed = FileBasedIndexImpl.LOG.isTraceEnabled(); private final FileBasedIndexImpl myFileBasedIndex; private final UpdatableIndex<FileType, Void, FileContent> myFileTypeIndex; private final Collection<FileBasedIndexInfrastructureExtension.FileIndexingStatusProcessor> myStateProcessors; private final @NotNull ProjectIndexableFilesFilterHolder myIndexableFilesFilterHolder; private final boolean myShouldProcessUpToDateFiles; UnindexedFilesFinder(@NotNull Project project, @NotNull FileBasedIndexImpl fileBasedIndex) { myProject = project; myFileBasedIndex = fileBasedIndex; myFileTypeIndex = fileBasedIndex.getIndex(FileTypeIndex.NAME); myStateProcessors = FileBasedIndexInfrastructureExtension .EP_NAME .extensions() .map(ex -> ex.createFileIndexingStatusProcessor(project)) .filter(Objects::nonNull) .collect(Collectors.toList()); myShouldProcessUpToDateFiles = ContainerUtil.find(myStateProcessors, p -> p.shouldProcessUpToDateFiles()) != null; myIndexableFilesFilterHolder = fileBasedIndex.getIndexableFilesFilterHolder(); } @Nullable("null if the file is not subject for indexing (a directory, invalid, etc.)") public UnindexedFileStatus getFileStatus(@NotNull VirtualFile file) { return ReadAction.compute(() -> { if (myProject.isDisposed() || !file.isValid() || !(file instanceof VirtualFileWithId)) { return null; } AtomicBoolean indexesWereProvidedByInfrastructureExtension = new AtomicBoolean(); AtomicLong timeProcessingUpToDateFiles = new AtomicLong(); AtomicLong timeUpdatingContentLessIndexes = new AtomicLong(); AtomicLong timeIndexingWithoutContent = new AtomicLong(); IndexedFileImpl indexedFile = new IndexedFileImpl(file, myProject); int inputId = FileBasedIndex.getFileId(file); boolean fileWereJustAdded = myIndexableFilesFilterHolder.addFileId(inputId, myProject); if (file instanceof VirtualFileSystemEntry && ((VirtualFileSystemEntry)file).isFileIndexed()) { boolean wasInvalidated = false; if (fileWereJustAdded) { List<ID<?, ?>> ids = IndexingStamp.getNontrivialFileIndexedStates(inputId); for (FileBasedIndexInfrastructureExtension.FileIndexingStatusProcessor processor : myStateProcessors) { for (ID<?, ?> id : ids) { if (myFileBasedIndex.needsFileContentLoading(id)) { long nowTime = System.nanoTime(); try { if (!processor.processUpToDateFile(indexedFile, inputId, id)) { wasInvalidated = true; } } finally { timeProcessingUpToDateFiles.addAndGet(System.nanoTime() - nowTime); } } } } } if (!wasInvalidated) { IndexingStamp.flushCache(inputId); return new UnindexedFileStatus(false, false, timeProcessingUpToDateFiles.get(), timeUpdatingContentLessIndexes.get(), timeIndexingWithoutContent.get()); } } AtomicBoolean shouldIndex = new AtomicBoolean(); FileTypeManagerEx.getInstanceEx().freezeFileTypeTemporarilyIn(file, () -> { boolean isDirectory = file.isDirectory(); FileIndexingState fileTypeIndexState = null; if (!isDirectory && !myFileBasedIndex.isTooLarge(file)) { if ((fileTypeIndexState = myFileTypeIndex.getIndexingStateForFile(inputId, indexedFile)) == FileIndexingState.OUT_DATED) { myFileBasedIndex.dropNontrivialIndexedStates(inputId); shouldIndex.set(true); } else { final List<ID<?, ?>> affectedIndexCandidates = myFileBasedIndex.getAffectedIndexCandidates(indexedFile); //noinspection ForLoopReplaceableByForEach for (int i = 0, size = affectedIndexCandidates.size(); i < size; ++i) { final ID<?, ?> indexId = affectedIndexCandidates.get(i); try { if (myFileBasedIndex.needsFileContentLoading(indexId)) { FileIndexingState fileIndexingState = myFileBasedIndex.shouldIndexFile(indexedFile, indexId); boolean indexInfrastructureExtensionInvalidated = false; if (fileIndexingState == FileIndexingState.UP_TO_DATE) { if (myShouldProcessUpToDateFiles) { for (FileBasedIndexInfrastructureExtension.FileIndexingStatusProcessor p : myStateProcessors) { long nowTime = System.nanoTime(); try { if (!p.processUpToDateFile(indexedFile, inputId, indexId)) { indexInfrastructureExtensionInvalidated = true; } } finally { timeProcessingUpToDateFiles.addAndGet(System.nanoTime() - nowTime); } } } } if (indexInfrastructureExtensionInvalidated) { fileIndexingState = myFileBasedIndex.shouldIndexFile(indexedFile, indexId); } if (fileIndexingState.updateRequired()) { if (myDoTraceForFilesToBeIndexed) { LOG.trace("Scheduling indexing of " + file + " by request of index " + indexId); } long nowTime = System.nanoTime(); boolean wasIndexedByInfrastructure; try { wasIndexedByInfrastructure = tryIndexWithoutContentViaInfrastructureExtension(indexedFile, inputId, indexId); } finally { timeIndexingWithoutContent.addAndGet(System.nanoTime() - nowTime); } if (wasIndexedByInfrastructure) { indexesWereProvidedByInfrastructureExtension.set(true); } else { shouldIndex.set(true); // NOTE! Do not break the loop here. We must process ALL IDs and pass them to the FileIndexingStatusProcessor // so that it can invalidate all "indexing states" (by means of clearing IndexingStamp) // for all indexes that became invalid. See IDEA-252846 for more details. } } } } catch (RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof IOException || cause instanceof StorageException) { LOG.info(e); myFileBasedIndex.requestRebuild(indexId); } else { throw e; } } } } } long nowTime = System.nanoTime(); try { for (ID<?, ?> indexId : myFileBasedIndex.getContentLessIndexes(isDirectory)) { if (FileTypeIndex.NAME.equals(indexId) && fileTypeIndexState != null && !fileTypeIndexState.updateRequired()) { continue; } if (myFileBasedIndex.shouldIndexFile(indexedFile, indexId).updateRequired()) { myFileBasedIndex.updateSingleIndex(indexId, file, inputId, new IndexedFileWrapper(indexedFile)); } } } finally { timeUpdatingContentLessIndexes.addAndGet(System.nanoTime() - nowTime); } IndexingStamp.flushCache(inputId); if (!shouldIndex.get()) { IndexingFlag.setFileIndexed(file); } }); return new UnindexedFileStatus(shouldIndex.get(), indexesWereProvidedByInfrastructureExtension.get(), timeProcessingUpToDateFiles.get(), timeUpdatingContentLessIndexes.get(), timeIndexingWithoutContent.get()); }); } private boolean tryIndexWithoutContentViaInfrastructureExtension(IndexedFile fileContent, int inputId, ID<?, ?> indexId) { for (FileBasedIndexInfrastructureExtension.FileIndexingStatusProcessor processor : myStateProcessors) { if (processor.tryIndexFileWithoutContent(fileContent, inputId, indexId)) { FileBasedIndexImpl.setIndexedState(myFileBasedIndex.getIndex(indexId), fileContent, inputId, true); return true; } } return false; } }
ingokegel/intellij-community
platform/lang-impl/src/com/intellij/util/indexing/UnindexedFilesFinder.java
Java
apache-2.0
10,024
using System; using Magnum.StateMachine; using MassTransit.Saga; using Serilog; namespace MassTransit.Persistence.MongoDb.Tests.Sagas { public class AuctionSaga : SagaStateMachine<AuctionSaga>, ISaga { public static readonly ILogger Logger = Log.Logger.ForContext<AuctionSaga>(); static AuctionSaga() { Define( () => { Correlate(Bid).By((saga, message) => saga.CorrelationId == message.AuctionId); Initially( When(Create).Then( (saga, message) => { saga.OpeningBid = message.OpeningBid; saga.OwnerEmail = message.OwnerEmail; saga.Title = message.Title; }).TransitionTo(Open)); During(Open, When(Bid).Call((saga, message) => saga.Handle(message))); }); } public AuctionSaga(Guid correlationId) { this.CorrelationId = correlationId; } public decimal? CurrentBid { get; set; } public string HighBidder { get; set; } public Guid HighBidId { get; set; } public decimal OpeningBid { get; set; } public string OwnerEmail { get; set; } public string Title { get; set; } public static State Initial { get; set; } public static State Completed { get; set; } public static State Open { get; set; } public static State Closed { get; set; } public static Event<CreateAuction> Create { get; set; } public static Event<PlaceBid> Bid { get; set; } public Guid CorrelationId { get; set; } public IServiceBus Bus { get; set; } private void Handle(PlaceBid bid) { if (!this.CurrentBid.HasValue || bid.MaximumBid > this.CurrentBid) { if (this.HighBidder != null) { this.Bus.Publish(new Outbid(this.HighBidId)); } this.CurrentBid = bid.MaximumBid; this.HighBidder = bid.BidderEmail; this.HighBidId = bid.BidId; } else { // already outbid this.Bus.Publish(new Outbid(bid.BidId)); } } } }
cwooldridge/MassTransit.Persistence.MongoDb
MassTransit.Persistence.MongoDb.Tests/Sagas/AuctionSaga.cs
C#
apache-2.0
2,517
// Copyright 2020 Red Hat, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package types import ( "github.com/coreos/go-semver/semver" "github.com/coreos/ignition/v2/config/shared/errors" "github.com/coreos/vcontext/path" "github.com/coreos/vcontext/report" ) func (v Ignition) Semver() (*semver.Version, error) { return semver.NewVersion(v.Version) } func (ic IgnitionConfig) Validate(c path.ContextPath) (r report.Report) { for i, res := range ic.Merge { r.AddOnError(c.Append("merge", i), res.validateRequiredSource()) } return } func (v Ignition) Validate(c path.ContextPath) (r report.Report) { c = c.Append("version") tv, err := v.Semver() if err != nil { r.AddOnError(c, errors.ErrInvalidVersion) return } if MaxVersion != *tv { r.AddOnError(c, errors.ErrUnknownVersion) } return }
coreos/ignition
config/v3_4_experimental/types/ignition.go
GO
apache-2.0
1,335
package mil.nga.giat.geowave.cli.geoserver; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import mil.nga.giat.geowave.core.cli.annotations.GeowaveOperation; import mil.nga.giat.geowave.core.cli.api.Command; import mil.nga.giat.geowave.core.cli.api.OperationParams; import mil.nga.giat.geowave.core.cli.operations.config.options.ConfigOptions; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.beust.jcommander.Parameters; @GeowaveOperation(name = "rmstyle", parentOperation = GeoServerSection.class) @Parameters(commandDescription = "Remove GeoServer Style") public class GeoServerRemoveStyleCommand implements Command { private GeoServerRestClient geoserverClient = null; @Parameter(description = "<style name>") private List<String> parameters = new ArrayList<String>(); private String styleName = null; @Override public boolean prepare( OperationParams params ) { if (geoserverClient == null) { // Get the local config for GeoServer File propFile = (File) params.getContext().get( ConfigOptions.PROPERTIES_FILE_CONTEXT); GeoServerConfig config = new GeoServerConfig( propFile); // Create the rest client geoserverClient = new GeoServerRestClient( config); } // Successfully prepared return true; } @Override public void execute( OperationParams params ) throws Exception { if (parameters.size() != 1) { throw new ParameterException( "Requires argument: <style name>"); } styleName = parameters.get(0); Response deleteStyleResponse = geoserverClient.deleteStyle(styleName); if (deleteStyleResponse.getStatus() == Status.OK.getStatusCode()) { System.out.println("Delete style '" + styleName + "' on GeoServer: OK"); } else { System.err.println("Error deleting style '" + styleName + "' on GeoServer; code = " + deleteStyleResponse.getStatus()); } } }
Becca42/geowave
extensions/cli/geoserver/src/main/java/mil/nga/giat/geowave/cli/geoserver/GeoServerRemoveStyleCommand.java
Java
apache-2.0
2,009
/* Copyright (c) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Text; using System.Xml; using Google.GData.Client; using Google.GData.Extensions; using Google.GData.Extensions.Apps; namespace Google.GData.Apps { /// <summary> /// Feed API customization class for defining user account feed. /// </summary> public class UserFeed : AbstractFeed { /// <summary> /// Constructor /// </summary> /// <param name="uriBase">The uri for the user account feed.</param> /// <param name="iService">The user account service.</param> public UserFeed(Uri uriBase, IService iService) : base(uriBase, iService) { GAppsExtensions.AddProvisioningExtensions(this); } /// <summary> /// Overridden. Returns a new <code>UserEntry</code>. /// </summary> /// <returns>the new <code>UserEntry</code></returns> public override AtomEntry CreateFeedEntry() { return new UserEntry(); } } }
michael-jia-sage/libgoogle
src/gapps/userfeed.cs
C#
apache-2.0
1,602
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.tests.product.cassandra; import com.datastax.driver.core.utils.Bytes; import io.airlift.units.Duration; import io.trino.jdbc.Row; import io.trino.tempto.ProductTest; import io.trino.tempto.Requirement; import io.trino.tempto.RequirementsProvider; import io.trino.tempto.configuration.Configuration; import io.trino.tempto.internal.query.CassandraQueryExecutor; import io.trino.tempto.query.QueryResult; import org.assertj.core.api.Assertions; import org.testng.annotations.Test; import java.sql.Date; import java.sql.Timestamp; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.function.Consumer; import static io.trino.tempto.Requirements.compose; import static io.trino.tempto.assertions.QueryAssert.Row.row; import static io.trino.tempto.assertions.QueryAssert.assertThat; import static io.trino.tempto.fulfillment.table.TableRequirements.immutableTable; import static io.trino.tempto.query.QueryExecutor.query; import static io.trino.tests.product.TestGroups.CASSANDRA; import static io.trino.tests.product.TestGroups.PROFILE_SPECIFIC_TESTS; import static io.trino.tests.product.TpchTableResults.PRESTO_NATION_RESULT; import static io.trino.tests.product.cassandra.CassandraTpchTableDefinitions.CASSANDRA_NATION; import static io.trino.tests.product.cassandra.CassandraTpchTableDefinitions.CASSANDRA_SUPPLIER; import static io.trino.tests.product.cassandra.DataTypesTableDefinition.CASSANDRA_ALL_TYPES; import static io.trino.tests.product.cassandra.TestConstants.CONNECTOR_NAME; import static io.trino.tests.product.cassandra.TestConstants.KEY_SPACE; import static io.trino.tests.product.utils.QueryAssertions.assertContainsEventually; import static io.trino.tests.product.utils.QueryExecutors.onTrino; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; import static java.sql.JDBCType.BIGINT; import static java.sql.JDBCType.BOOLEAN; import static java.sql.JDBCType.DATE; import static java.sql.JDBCType.DOUBLE; import static java.sql.JDBCType.INTEGER; import static java.sql.JDBCType.REAL; import static java.sql.JDBCType.SMALLINT; import static java.sql.JDBCType.TIMESTAMP_WITH_TIMEZONE; import static java.sql.JDBCType.TINYINT; import static java.sql.JDBCType.VARBINARY; import static java.sql.JDBCType.VARCHAR; import static java.util.concurrent.TimeUnit.MINUTES; public class TestSelect extends ProductTest implements RequirementsProvider { private Configuration configuration; @Override public Requirement getRequirements(Configuration configuration) { this.configuration = configuration; return compose( immutableTable(CASSANDRA_NATION), immutableTable(CASSANDRA_SUPPLIER), immutableTable(CASSANDRA_ALL_TYPES)); } @Test(groups = {CASSANDRA, PROFILE_SPECIFIC_TESTS}) public void testSelectNation() { String sql = format( "SELECT n_nationkey, n_name, n_regionkey, n_comment FROM %s.%s.%s", CONNECTOR_NAME, KEY_SPACE, CASSANDRA_NATION.getName()); QueryResult queryResult = onTrino() .executeQuery(sql); assertThat(queryResult).matches(PRESTO_NATION_RESULT); } @Test(groups = {CASSANDRA, PROFILE_SPECIFIC_TESTS}) public void testSelectWithEqualityFilterOnPartitioningKey() { String sql = format( "SELECT n_nationkey FROM %s.%s.%s WHERE n_nationkey = 0", CONNECTOR_NAME, KEY_SPACE, CASSANDRA_NATION.getName()); QueryResult queryResult = onTrino() .executeQuery(sql); assertThat(queryResult).containsOnly(row(0)); } @Test(groups = {CASSANDRA, PROFILE_SPECIFIC_TESTS}) public void testSelectWithFilterOnPartitioningKey() { String sql = format( "SELECT n_nationkey FROM %s.%s.%s WHERE n_nationkey > 23", CONNECTOR_NAME, KEY_SPACE, CASSANDRA_NATION.getName()); QueryResult queryResult = onTrino() .executeQuery(sql); assertThat(queryResult).containsOnly(row(24)); } @Test(groups = {CASSANDRA, PROFILE_SPECIFIC_TESTS}) public void testSelectWithEqualityFilterOnNonPartitioningKey() { String sql = format( "SELECT n_name FROM %s.%s.%s WHERE n_name = 'UNITED STATES'", CONNECTOR_NAME, KEY_SPACE, CASSANDRA_NATION.getName()); QueryResult queryResult = onTrino() .executeQuery(sql); assertThat(queryResult).containsOnly(row("UNITED STATES")); } @Test(groups = {CASSANDRA, PROFILE_SPECIFIC_TESTS}) public void testSelectWithNonEqualityFilterOnNonPartitioningKey() { String sql = format( "SELECT n_name FROM %s.%s.%s WHERE n_name < 'B'", CONNECTOR_NAME, KEY_SPACE, CASSANDRA_NATION.getName()); QueryResult queryResult = onTrino() .executeQuery(sql); assertThat(queryResult).containsOnly(row("ALGERIA"), row("ARGENTINA")); } @Test(groups = {CASSANDRA, PROFILE_SPECIFIC_TESTS}) public void testSelectWithMorePartitioningKeysThanLimit() { String sql = format( "SELECT s_suppkey FROM %s.%s.%s WHERE s_suppkey = 10", CONNECTOR_NAME, KEY_SPACE, CASSANDRA_SUPPLIER.getName()); QueryResult queryResult = onTrino() .executeQuery(sql); assertThat(queryResult).containsOnly(row(10)); } @Test(groups = {CASSANDRA, PROFILE_SPECIFIC_TESTS}) public void testSelectWithMorePartitioningKeysThanLimitNonPK() { String sql = format( "SELECT s_suppkey FROM %s.%s.%s WHERE s_name = 'Supplier#000000010'", CONNECTOR_NAME, KEY_SPACE, CASSANDRA_SUPPLIER.getName()); QueryResult queryResult = onTrino() .executeQuery(sql); assertThat(queryResult).containsOnly(row(10)); } @Test(groups = {CASSANDRA, PROFILE_SPECIFIC_TESTS}) public void testAllDataTypes() { // NOTE: DECIMAL is treated like DOUBLE QueryResult query = query(format( "SELECT a, b, bl, bo, d, do, dt, f, fr, i, integer, l, m, s, si, t, ti, ts, tu, u, v, vari FROM %s.%s.%s", CONNECTOR_NAME, KEY_SPACE, CASSANDRA_ALL_TYPES.getName())); assertThat(query) .hasColumns(VARCHAR, BIGINT, VARBINARY, BOOLEAN, DOUBLE, DOUBLE, DATE, REAL, VARCHAR, VARCHAR, INTEGER, VARCHAR, VARCHAR, VARCHAR, SMALLINT, VARCHAR, TINYINT, TIMESTAMP_WITH_TIMEZONE, VARCHAR, VARCHAR, VARCHAR, VARCHAR) .containsOnly( row("\0", Long.MIN_VALUE, Bytes.fromHexString("0x00").array(), false, 0f, Double.MIN_VALUE, Date.valueOf("1970-01-02"), Float.MIN_VALUE, "[0]", "0.0.0.0", Integer.MIN_VALUE, "[0]", "{\"\\u0000\":-2147483648,\"a\":0}", "[0]", Short.MIN_VALUE, "\0", Byte.MIN_VALUE, Timestamp.from(OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC).toInstant()), "d2177dd0-eaa2-11de-a572-001b779c76e3", "01234567-0123-0123-0123-0123456789ab", "\0", String.valueOf(Long.MIN_VALUE)), row("the quick brown fox jumped over the lazy dog", 9223372036854775807L, "01234".getBytes(UTF_8), true, Double.valueOf("99999999999999999999999999999999999999"), Double.MAX_VALUE, Date.valueOf("9999-12-31"), Float.MAX_VALUE, "[4,5,6,7]", "255.255.255.255", Integer.MAX_VALUE, "[4,5,6]", "{\"a\":1,\"b\":2}", "[4,5,6]", Short.MAX_VALUE, "this is a text value", Byte.MAX_VALUE, Timestamp.from(OffsetDateTime.of(9999, 12, 31, 23, 59, 59, 0, ZoneOffset.UTC).toInstant()), "d2177dd0-eaa2-11de-a572-001b779c76e3", "01234567-0123-0123-0123-0123456789ab", "abc", String.valueOf(Long.MAX_VALUE)), row("def", null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null)); } @Test(groups = {CASSANDRA, PROFILE_SPECIFIC_TESTS}) public void testNationJoinNation() { String tableName = format("%s.%s.%s", CONNECTOR_NAME, KEY_SPACE, CASSANDRA_NATION.getName()); String sql = format( "SELECT n1.n_name, n2.n_regionkey FROM %s n1 JOIN " + "%s n2 ON n1.n_nationkey = n2.n_regionkey " + "WHERE n1.n_nationkey=3", tableName, tableName); QueryResult queryResult = onTrino() .executeQuery(sql); assertThat(queryResult).containsOnly( row("CANADA", 3), row("CANADA", 3), row("CANADA", 3), row("CANADA", 3), row("CANADA", 3)); } @Test(groups = {CASSANDRA, PROFILE_SPECIFIC_TESTS}) public void testNationJoinRegion() { String sql = format( "SELECT c.n_name, t.name FROM %s.%s.%s c JOIN " + "tpch.tiny.region t ON c.n_regionkey = t.regionkey " + "WHERE c.n_nationkey=3", CONNECTOR_NAME, KEY_SPACE, CASSANDRA_NATION.getName()); QueryResult queryResult = onTrino() .executeQuery(sql); assertThat(queryResult).containsOnly(row("CANADA", "AMERICA")); } @Test(groups = {CASSANDRA, PROFILE_SPECIFIC_TESTS}) public void testSelectAllTypePartitioningMaterializedView() { String materializedViewName = format("%s_partitioned_mv", CASSANDRA_ALL_TYPES.getName()); onCassandra(format("DROP MATERIALIZED VIEW IF EXISTS %s.%s", KEY_SPACE, materializedViewName)); onCassandra(format("CREATE MATERIALIZED VIEW %s.%s AS SELECT * FROM %s.%s WHERE b IS NOT NULL PRIMARY KEY (a, b)", KEY_SPACE, materializedViewName, KEY_SPACE, CASSANDRA_ALL_TYPES.getName())); assertContainsEventually(() -> query(format("SHOW TABLES FROM %s.%s", CONNECTOR_NAME, KEY_SPACE)), query(format("SELECT '%s'", materializedViewName)), new Duration(1, MINUTES)); // Materialized view may not return all results during the creation assertContainsEventually(() -> query(format("SELECT status_replicated FROM %s.system.built_views WHERE view_name = '%s'", CONNECTOR_NAME, materializedViewName)), query("SELECT true"), new Duration(1, MINUTES)); QueryResult query = query(format( "SELECT a, b, bl, bo, d, do, dt, f, fr, i, integer, l, m, s, si, t, ti, ts, tu, u, v, vari FROM %s.%s.%s WHERE a = '\0'", CONNECTOR_NAME, KEY_SPACE, materializedViewName)); assertThat(query) .hasColumns(VARCHAR, BIGINT, VARBINARY, BOOLEAN, DOUBLE, DOUBLE, DATE, REAL, VARCHAR, VARCHAR, INTEGER, VARCHAR, VARCHAR, VARCHAR, SMALLINT, VARCHAR, TINYINT, TIMESTAMP_WITH_TIMEZONE, VARCHAR, VARCHAR, VARCHAR, VARCHAR) .containsOnly( row("\0", Long.MIN_VALUE, Bytes.fromHexString("0x00").array(), false, 0f, Double.MIN_VALUE, Date.valueOf("1970-01-02"), Float.MIN_VALUE, "[0]", "0.0.0.0", Integer.MIN_VALUE, "[0]", "{\"\\u0000\":-2147483648,\"a\":0}", "[0]", Short.MIN_VALUE, "\0", Byte.MIN_VALUE, Timestamp.from(OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC).toInstant()), "d2177dd0-eaa2-11de-a572-001b779c76e3", "01234567-0123-0123-0123-0123456789ab", "\0", String.valueOf(Long.MIN_VALUE))); onCassandra(format("DROP MATERIALIZED VIEW IF EXISTS %s.%s", KEY_SPACE, materializedViewName)); } @Test(groups = {CASSANDRA, PROFILE_SPECIFIC_TESTS}) public void testSelectClusteringMaterializedView() { String mvName = "clustering_mv"; onCassandra(format("DROP MATERIALIZED VIEW IF EXISTS %s.%s", KEY_SPACE, mvName)); onCassandra(format("CREATE MATERIALIZED VIEW %s.%s AS " + "SELECT * FROM %s.%s " + "WHERE s_nationkey IS NOT NULL " + "PRIMARY KEY (s_nationkey, s_suppkey) " + "WITH CLUSTERING ORDER BY (s_nationkey DESC)", KEY_SPACE, mvName, KEY_SPACE, CASSANDRA_SUPPLIER.getName())); assertContainsEventually(() -> query(format("SHOW TABLES FROM %s.%s", CONNECTOR_NAME, KEY_SPACE)), query(format("SELECT '%s'", mvName)), new Duration(1, MINUTES)); // Materialized view may not return all results during the creation assertContainsEventually(() -> query(format("SELECT status_replicated FROM %s.system.built_views WHERE view_name = '%s'", CONNECTOR_NAME, mvName)), query("SELECT true"), new Duration(1, MINUTES)); QueryResult aggregateQueryResult = onTrino() .executeQuery(format( "SELECT MAX(s_nationkey), SUM(s_suppkey), AVG(s_acctbal) " + "FROM %s.%s.%s WHERE s_suppkey BETWEEN 1 AND 10 ", CONNECTOR_NAME, KEY_SPACE, mvName)); assertThat(aggregateQueryResult).containsOnly( row(24, 55, 4334.653)); QueryResult orderedResult = onTrino() .executeQuery(format( "SELECT s_nationkey, s_suppkey, s_acctbal " + "FROM %s.%s.%s WHERE s_nationkey = 1 LIMIT 1", CONNECTOR_NAME, KEY_SPACE, mvName)); assertThat(orderedResult).containsOnly( row(1, 3, 4192.4)); onCassandra(format("DROP MATERIALIZED VIEW IF EXISTS %s.%s", KEY_SPACE, mvName)); } @Test(groups = {CASSANDRA, PROFILE_SPECIFIC_TESTS}) public void testProtocolVersion() { QueryResult queryResult = onTrino() .executeQuery(format("SELECT native_protocol_version FROM %s.system.local", CONNECTOR_NAME)); assertThat(queryResult).containsOnly(row("4")); } @Test(groups = {CASSANDRA, PROFILE_SPECIFIC_TESTS}) public void testSelectTupleType() { String tableName = "select_tuple_table"; onCassandra(format("DROP TABLE IF EXISTS %s.%s", KEY_SPACE, tableName)); onCassandra(format("CREATE TABLE %s.%s (key int, value frozen<tuple<int, text, float>>, PRIMARY KEY (key))", KEY_SPACE, tableName)); onCassandra(format("INSERT INTO %s.%s (key, value) VALUES(1, (1, 'text-1', 1.11))", KEY_SPACE, tableName)); QueryResult queryResult = onTrino().executeQuery( format("SELECT * FROM %s.%s.%s", CONNECTOR_NAME, KEY_SPACE, tableName)); assertThat(queryResult).hasRowsCount(1); Assertions.assertThat(queryResult.row(0).get(0)).isEqualTo(1); Assertions.assertThat(queryResult.row(0).get(1)).isEqualTo(Row.builder() .addUnnamedField(1) .addUnnamedField("text-1") .addUnnamedField(1.11f) .build()); onCassandra(format("DROP TABLE IF EXISTS %s.%s", KEY_SPACE, tableName)); } @Test(groups = {CASSANDRA, PROFILE_SPECIFIC_TESTS}) public void testSelectTupleTypeInPrimaryKey() { String tableName = "select_tuple_in_primary_key_table"; onCassandra(format("DROP TABLE IF EXISTS %s.%s", KEY_SPACE, tableName)); onCassandra(format("CREATE TABLE %s.%s (intkey int, tuplekey frozen<tuple<int, text, float>>, PRIMARY KEY (intkey, tuplekey))", KEY_SPACE, tableName)); onCassandra(format("INSERT INTO %s.%s (intkey, tuplekey) VALUES(1, (1, 'text-1', 1.11))", KEY_SPACE, tableName)); Consumer<QueryResult> assertion = queryResult -> { assertThat(queryResult).hasRowsCount(1); Assertions.assertThat(queryResult.row(0).get(0)).isEqualTo(1); Assertions.assertThat(queryResult.row(0).get(1)).isEqualTo(Row.builder() .addUnnamedField(1) .addUnnamedField("text-1") .addUnnamedField(1.11f) .build()); }; assertion.accept(onTrino().executeQuery(format("SELECT * FROM %s.%s.%s", CONNECTOR_NAME, KEY_SPACE, tableName))); assertion.accept(onTrino().executeQuery(format("SELECT * FROM %s.%s.%s WHERE intkey = 1 and tuplekey = row(1, 'text-1', 1.11)", CONNECTOR_NAME, KEY_SPACE, tableName))); onCassandra(format("DROP TABLE IF EXISTS %s.%s", KEY_SPACE, tableName)); } private void onCassandra(String query) { try (CassandraQueryExecutor queryExecutor = new CassandraQueryExecutor(configuration)) { queryExecutor.executeQuery(query); } } }
dain/presto
testing/trino-product-tests/src/main/java/io/trino/tests/product/cassandra/TestSelect.java
Java
apache-2.0
19,572
# encoding: UTF-8 require 'simplecov' require 'coveralls' SimpleCov.formatter = if ENV['CI'] Coveralls::SimpleCov::Formatter else SimpleCov::Formatter::HTMLFormatter end SimpleCov.start
sbagdadi-gpsw/custom-prometheus-client
spec/spec_helper.rb
Ruby
apache-2.0
203
from django.utils.translation import ugettext_lazy as _ import horizon from {{ dash_path }} import dashboard class {{ panel_name|title }}(horizon.Panel): name = _("{{ panel_name|title }}") slug = "{{ panel_name|slugify }}" dashboard.register({{ panel_name|title }})
xhorn/xchorizon
horizon/conf/panel_template/panel.py
Python
apache-2.0
280
'use strict'; var TodoServiceFactory = function(database){ return { // Return all todos in the database getTodos: function(){ return database('Todo').select().orderBy('createdAt', 'desc'); }, // Return a single todo by Id getTodo: function(id){ var p = Promise.defer(); database('Todo').where('id', id).select() .then(function(rows){ if(rows.length === 0){ //not found p.reject('TodoService: not found'); } else { p.resolve(rows[0]); } }); return p.promise; }, //Update a todo in the database updateTodo: function(todo){ var p = Promise.defer(); //TODO: real-world validation database('Todo').update({ text: todo.text, completed: todo.completed }) .where('id', todo.id) .then(function(affectedRows){ if(affectedRows === 1){ p.resolve(todo); } else { p.reject('Not found'); } }); return p.promise; }, //Create a new todo in the database createTodo: function(todo){ var p = Promise.defer(); //TODO: real-world validation database('Todo').insert(todo) .then(function(idArray){ //return the newly created todo todo.id = idArray[0]; p.resolve(todo); }) .catch(function(err){ p.reject('TodoService: create failed. Error:' + err.toString()); }); return p.promise; }, //Delete a todo specified by Id deleteTodo: function(todoId){ var p = Promise.defer(); database('Todo').where('id', todoId).del() .then(function(affectedRows){ if(affectedRows === 1){ return p.resolve(true); } else { return p.reject('TodoService: not found'); } }) .catch(function(err){ p.reject('TodoService: delete failed. Error' + err.toString()); }); return p.promise; } } } module.exports = TodoServiceFactory;
raffaeu/Syncho
src/node_modules/kontainer-di/examples/express/services/todo_service.js
JavaScript
apache-2.0
2,050
/* * Copyright 2015-present Boundless Spatial Inc., http://boundlessgeo.com * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations * under the License. */ import React from 'react'; import {connect} from 'react-redux'; import PropTypes from 'prop-types'; import * as mapActions from '../../actions/map'; /** @module components/map/zoom-control * @example * import SdkZoomControl from '@boundlessgeo/sdk/components/map/zoom-control'; * import { Provider } from 'react-redux'; * import SdkMap from '@boundlessgeo/sdk/components/map'; * import ReactDOM from 'react-dom'; * * ReactDOM.render(<Provider store={store}> * <SdkMap> * <SdkZoomControl /> * </SdkMap> * </Provider>, document.getElementById('map')); * * @desc Provides 2 buttons to zoom the map (zoom in and out). */ class ZoomControl extends React.Component { render() { let className = 'sdk-zoom-control'; if (this.props.className) { className += ' ' + this.props.className; } return ( <div className={className} style={this.props.style}> <button className='sdk-zoom-in' onClick={this.props.zoomIn} title={this.props.zoomInTitle}>+</button> <button className='sdk-zoom-out' onClick={this.props.zoomOut} title={this.props.zoomOutTitle}>{'\u2212'}</button> </div> ); } } ZoomControl.propTypes = { /** * Css className for the root div. */ className: PropTypes.string, /** * Style config object for root div. */ style: PropTypes.object, /** * Title for the zoom in button. */ zoomInTitle: PropTypes.string, /** * Title for the zoom out button. */ zoomOutTitle: PropTypes.string, }; ZoomControl.defaultProps = { zoomInTitle: 'Zoom in', zoomOutTitle: 'Zoom out', }; function mapDispatchToProps(dispatch) { return { zoomIn: () => { dispatch(mapActions.zoomIn()); }, zoomOut: () => { dispatch(mapActions.zoomOut()); }, }; } export default connect(null, mapDispatchToProps)(ZoomControl);
boundlessgeo/sdk
src/components/map/zoom-control.js
JavaScript
apache-2.0
2,469
/* Copyright 2015 Coursera Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.coursera.android.shift; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class ShiftActionsFragment extends ViewPagerFragment { private static final String TAB_TITLE_ACTIONS = "Actions"; public ShiftActionsFragment() { super(TAB_TITLE_ACTIONS); } public static ShiftActionsFragment getNewInstance() { return new ShiftActionsFragment(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.actions_fragment, container, false); RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); int bottomMargin = (int) getResources().getDimension(R.dimen.card_margin); recyclerView.addItemDecoration(new VerticalMarginItemDecoration(bottomMargin)); ShiftActionRecyclerViewAdapter adapter = new ShiftActionRecyclerViewAdapter(getActivity(), ShiftManager.getInstance().getActionManager().getActionList()); recyclerView.setAdapter(adapter); return view; } }
coursera/shift
shift/src/main/java/org/coursera/android/shift/ShiftActionsFragment.java
Java
apache-2.0
2,029
using MongoDB.Bson; namespace MongoDB.Protocol { /// <summary> /// Deprecated. OP_MSG sends a diagnostic message to the database. /// The database sends back a fixed resonse. /// </summary> /// <remarks> /// struct { /// MsgHeader header; // standard message header /// cstring message; // message for the database /// } /// </remarks> internal class MsgMessage : RequestMessageBase { /// <summary> /// Initializes a new instance of the <see cref="MsgMessage"/> class. /// </summary> public MsgMessage() : base(new BsonWriterSettings()){ Header = new MessageHeader(OpCode.Msg); } /// <summary> /// Gets or sets the message. /// </summary> /// <value>The message.</value> public string Message { get; set; } /// <summary> /// Writes the body. /// </summary> /// <param name="writer">The writer.</param> protected override void WriteBody(BsonWriter writer){ writer.Write(Message, false); } /// <summary> /// Calculates the size of the body. /// </summary> /// <param name="writer">The writer.</param> /// <returns></returns> protected override int CalculateBodySize(BsonWriter writer){ return writer.CalculateSize(Message, false); } } }
mongodb-csharp/mongodb-csharp
source/MongoDB/Protocol/MsgMessage.cs
C#
apache-2.0
1,486
package com.inomma.kandu.server; public enum RequestMethod { POST,GET,PUT; }
kandu-community/android
kandu-android/trunk/src/com/inomma/kandu/server/RequestMethod.java
Java
apache-2.0
80
<?php # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/osconfig/v1/vulnerability.proto namespace Google\Cloud\OsConfig\V1\VulnerabilityReport\Vulnerability; use Google\Protobuf\Internal\GPBType; use Google\Protobuf\Internal\RepeatedField; use Google\Protobuf\Internal\GPBUtil; /** * OS inventory item that is affected by a vulnerability or fixed as a * result of a vulnerability. * * Generated from protobuf message <code>google.cloud.osconfig.v1.VulnerabilityReport.Vulnerability.Item</code> */ class Item extends \Google\Protobuf\Internal\Message { /** * Corresponds to the `INSTALLED_PACKAGE` inventory item on the VM. * This field displays the inventory items affected by this vulnerability. * If the vulnerability report was not updated after the VM inventory * update, these values might not display in VM inventory. For some * operating systems, this field might be empty. * * Generated from protobuf field <code>string installed_inventory_item_id = 1;</code> */ private $installed_inventory_item_id = ''; /** * Corresponds to the `AVAILABLE_PACKAGE` inventory item on the VM. * If the vulnerability report was not updated after the VM inventory * update, these values might not display in VM inventory. If there is no * available fix, the field is empty. The `inventory_item` value specifies * the latest `SoftwarePackage` available to the VM that fixes the * vulnerability. * * Generated from protobuf field <code>string available_inventory_item_id = 2;</code> */ private $available_inventory_item_id = ''; /** * The recommended [CPE URI](https://cpe.mitre.org/specification/) update * that contains a fix for this vulnerability. * * Generated from protobuf field <code>string fixed_cpe_uri = 3;</code> */ private $fixed_cpe_uri = ''; /** * The upstream OS patch, packages or KB that fixes the vulnerability. * * Generated from protobuf field <code>string upstream_fix = 4;</code> */ private $upstream_fix = ''; /** * Constructor. * * @param array $data { * Optional. Data for populating the Message object. * * @type string $installed_inventory_item_id * Corresponds to the `INSTALLED_PACKAGE` inventory item on the VM. * This field displays the inventory items affected by this vulnerability. * If the vulnerability report was not updated after the VM inventory * update, these values might not display in VM inventory. For some * operating systems, this field might be empty. * @type string $available_inventory_item_id * Corresponds to the `AVAILABLE_PACKAGE` inventory item on the VM. * If the vulnerability report was not updated after the VM inventory * update, these values might not display in VM inventory. If there is no * available fix, the field is empty. The `inventory_item` value specifies * the latest `SoftwarePackage` available to the VM that fixes the * vulnerability. * @type string $fixed_cpe_uri * The recommended [CPE URI](https://cpe.mitre.org/specification/) update * that contains a fix for this vulnerability. * @type string $upstream_fix * The upstream OS patch, packages or KB that fixes the vulnerability. * } */ public function __construct($data = NULL) { \GPBMetadata\Google\Cloud\Osconfig\V1\Vulnerability::initOnce(); parent::__construct($data); } /** * Corresponds to the `INSTALLED_PACKAGE` inventory item on the VM. * This field displays the inventory items affected by this vulnerability. * If the vulnerability report was not updated after the VM inventory * update, these values might not display in VM inventory. For some * operating systems, this field might be empty. * * Generated from protobuf field <code>string installed_inventory_item_id = 1;</code> * @return string */ public function getInstalledInventoryItemId() { return $this->installed_inventory_item_id; } /** * Corresponds to the `INSTALLED_PACKAGE` inventory item on the VM. * This field displays the inventory items affected by this vulnerability. * If the vulnerability report was not updated after the VM inventory * update, these values might not display in VM inventory. For some * operating systems, this field might be empty. * * Generated from protobuf field <code>string installed_inventory_item_id = 1;</code> * @param string $var * @return $this */ public function setInstalledInventoryItemId($var) { GPBUtil::checkString($var, True); $this->installed_inventory_item_id = $var; return $this; } /** * Corresponds to the `AVAILABLE_PACKAGE` inventory item on the VM. * If the vulnerability report was not updated after the VM inventory * update, these values might not display in VM inventory. If there is no * available fix, the field is empty. The `inventory_item` value specifies * the latest `SoftwarePackage` available to the VM that fixes the * vulnerability. * * Generated from protobuf field <code>string available_inventory_item_id = 2;</code> * @return string */ public function getAvailableInventoryItemId() { return $this->available_inventory_item_id; } /** * Corresponds to the `AVAILABLE_PACKAGE` inventory item on the VM. * If the vulnerability report was not updated after the VM inventory * update, these values might not display in VM inventory. If there is no * available fix, the field is empty. The `inventory_item` value specifies * the latest `SoftwarePackage` available to the VM that fixes the * vulnerability. * * Generated from protobuf field <code>string available_inventory_item_id = 2;</code> * @param string $var * @return $this */ public function setAvailableInventoryItemId($var) { GPBUtil::checkString($var, True); $this->available_inventory_item_id = $var; return $this; } /** * The recommended [CPE URI](https://cpe.mitre.org/specification/) update * that contains a fix for this vulnerability. * * Generated from protobuf field <code>string fixed_cpe_uri = 3;</code> * @return string */ public function getFixedCpeUri() { return $this->fixed_cpe_uri; } /** * The recommended [CPE URI](https://cpe.mitre.org/specification/) update * that contains a fix for this vulnerability. * * Generated from protobuf field <code>string fixed_cpe_uri = 3;</code> * @param string $var * @return $this */ public function setFixedCpeUri($var) { GPBUtil::checkString($var, True); $this->fixed_cpe_uri = $var; return $this; } /** * The upstream OS patch, packages or KB that fixes the vulnerability. * * Generated from protobuf field <code>string upstream_fix = 4;</code> * @return string */ public function getUpstreamFix() { return $this->upstream_fix; } /** * The upstream OS patch, packages or KB that fixes the vulnerability. * * Generated from protobuf field <code>string upstream_fix = 4;</code> * @param string $var * @return $this */ public function setUpstreamFix($var) { GPBUtil::checkString($var, True); $this->upstream_fix = $var; return $this; } }
googleapis/google-cloud-php-osconfig
src/V1/VulnerabilityReport/Vulnerability/Item.php
PHP
apache-2.0
7,814
/// Copyright (c) 2009 Microsoft Corporation /// /// 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. /// * Neither the name of Microsoft nor the names of its contributors may be used to /// endorse or promote products derived from this software without specific prior written permission. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR /// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS /// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE /// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT /// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS /// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, /// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF /// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ES5Harness.registerTest({ id: "15.2.3.6-4-45", path: "TestCases/chapter15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-45.js", description: "Object.defineProperty - 'O' is the global object that uses Object's [[GetOwnProperty]] method to access the 'name' property (8.12.9 step 1)", test: function testcase() { try { Object.defineProperty(fnGlobalObject(), "foo", { value: 12, configurable: true }); return dataPropertyAttributesAreCorrect(fnGlobalObject(), "foo", 12, false, false, true); } finally { delete fnGlobalObject().foo; } }, precondition: function prereq() { return fnExists(Object.defineProperty); } });
hnafar/IronJS
Src/Tests/ietestcenter/chapter15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-45.js
JavaScript
apache-2.0
2,309
'use strict'; /** * @license * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ goog.provide('tachyfont.WorkQueue'); goog.require('goog.Promise'); goog.require('tachyfont.Reporter'); /** * This class manages work queues. * @param {string} name An identifier useful for error reports. * @constructor @struct @final */ tachyfont.WorkQueue = function(name) { /** @private @const {string} */ this.name_ = name; /** @private {!Array<!tachyfont.WorkQueue.Task>} */ this.queue_ = []; }; /** * Adds a task. * @param {function(?)} taskFunction The function to call. * @param {*} data The data to pass to the function. * @param {string} fontId An identifier useful for error messages. * @param {number=} opt_watchDogTime Option watch dog time. * @return {!tachyfont.WorkQueue.Task} A task object. */ tachyfont.WorkQueue.prototype.addTask = function( taskFunction, data, fontId, opt_watchDogTime) { var task = new tachyfont.WorkQueue.Task( taskFunction, data, fontId, opt_watchDogTime); this.queue_.push(task); if (this.queue_.length == 1) { this.runNextTask(); } return task; }; /** * Runs a task. */ tachyfont.WorkQueue.prototype.runNextTask = function() { if (this.queue_.length < 1) { return; } var task = this.queue_[0]; task.run().thenAlways( /** @this {tachyfont.WorkQueue} */ function() { this.queue_.shift(); this.runNextTask(); }, this); }; /** * Gets the queue length. * @return {number} */ tachyfont.WorkQueue.prototype.getLength = function() { return this.queue_.length; }; /** * Enum for error values. * @enum {string} */ // LINT.IfChange tachyfont.WorkQueue.Error = { FILE_ID: 'EWQ', WATCH_DOG_TIMER: '01', END: '00' }; // LINT.ThenChange(//depot/google3/\ // java/com/google/i18n/tachyfont/boq/gen204/error-reports.properties) /** * The error reporter for this file. * @param {string} errNum The error number; * @param {string} errId Identifies the error. * @param {*} errInfo The error object; */ tachyfont.WorkQueue.reportError = function(errNum, errId, errInfo) { tachyfont.Reporter.reportError( tachyfont.WorkQueue.Error.FILE_ID + errNum, errId, errInfo); }; /** * Gets the work queue name * @return {string} */ tachyfont.WorkQueue.prototype.getName = function() { return this.name_; }; /** * A class that holds a task. * @param {function(?)} taskFunction The function to call. * @param {*} data The data to pass to the function. * @param {string} fontId An indentifer for error reporting. * @param {number=} opt_watchDogTime Option watch dog time. * @constructor @struct @final */ tachyfont.WorkQueue.Task = function( taskFunction, data, fontId, opt_watchDogTime) { var resolver; /** @private {function(?)} */ this.function_ = taskFunction; /** @private {*} */ this.data_ = data; /** @private {string} */ this.fontId_ = fontId; /** @private {!goog.Promise<?,?>} */ this.result_ = new goog.Promise(function(resolve, reject) { // resolver = resolve; }); /** @private {function(*=)} */ this.resolver_ = resolver; /** @private {?number} */ this.timeoutId_ = null; /** @private {number} */ this.watchDogTime_ = opt_watchDogTime || tachyfont.WorkQueue.Task.WATCH_DOG_TIME; }; /** * The time in milliseconds to wait before reporting that a running task did not * complete. * @type {number} */ tachyfont.WorkQueue.Task.WATCH_DOG_TIME = 10 * 60 * 1000; /** * Gets the task result promise (may be unresolved). * @return {!goog.Promise<?,?>} */ tachyfont.WorkQueue.Task.prototype.getResult = function() { return this.result_; }; /** * Resolves the task result promise. * @param {*} result The result of the function. May be any value including a * resolved/rejected promise. * @return {!goog.Promise<?,?>} * @private */ tachyfont.WorkQueue.Task.prototype.resolve_ = function(result) { this.resolver_(result); return this.result_; }; /** * Runs the task. * @return {*} */ tachyfont.WorkQueue.Task.prototype.run = function() { this.startWatchDogTimer_(); var result; try { result = this.function_(this.data_); } catch (e) { result = goog.Promise.reject(e); } this.result_.thenAlways(function() { // this.stopWatchDogTimer_(); }.bind(this)); return this.resolve_(result); }; /** * Starts the watch dog timer. * @return {*} * @private */ tachyfont.WorkQueue.Task.prototype.startWatchDogTimer_ = function() { this.timeoutId_ = setTimeout(function() { this.timeoutId_ = null; tachyfont.WorkQueue.reportError( tachyfont.WorkQueue.Error.WATCH_DOG_TIMER, this.fontId_, ''); }.bind(this), this.watchDogTime_); }; /** * Stops the watch dog timer. * @private */ tachyfont.WorkQueue.Task.prototype.stopWatchDogTimer_ = function() { if (this.timeoutId_) { clearTimeout(this.timeoutId_); } this.timeoutId_ = null; };
googlefonts/TachyFont
run_time/src/gae_server/www/js/tachyfont/work_queue.js
JavaScript
apache-2.0
5,429
package com.thinkbiganalytics.metadata.jpa.app; /*- * #%L * thinkbig-operational-metadata-jpa * %% * Copyright (C) 2017 ThinkBig Analytics * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.thinkbiganalytics.KyloVersionUtil; import com.thinkbiganalytics.KyloVersion; import com.thinkbiganalytics.metadata.api.app.KyloVersionProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.List; import java.util.Properties; import javax.annotation.PostConstruct; /** * Provider for accessing and updating the Kylo version */ public class JpaKyloVersionProvider implements KyloVersionProvider { private static final Logger log = LoggerFactory.getLogger(JpaKyloVersionProvider.class); private static final Sort SORT_ORDER = new Sort(new Sort.Order(Direction.DESC, "majorVersion"), new Sort.Order(Direction.DESC, "minorVersion"), new Sort.Order(Direction.DESC, "pointVersion"), new Sort.Order(Direction.DESC, "tag") ); private KyloVersionRepository kyloVersionRepository; private String currentVersion; private String buildTimestamp; @Autowired public JpaKyloVersionProvider(KyloVersionRepository kyloVersionRepository) { this.kyloVersionRepository = kyloVersionRepository; } @Override public boolean isUpToDate() { KyloVersion buildVer = KyloVersionUtil.getBuildVersion(); KyloVersion currentVer = getCurrentVersion(); return currentVer != null && buildVer.matches(currentVer.getMajorVersion(), currentVer.getMinorVersion(), currentVer.getPointVersion()); } @Override public KyloVersion getCurrentVersion() { List<JpaKyloVersion> versions = kyloVersionRepository.findAll(SORT_ORDER); if (versions != null && !versions.isEmpty()) { return versions.get(0); } return null; } /* (non-Javadoc) * @see com.thinkbiganalytics.metadata.api.app.KyloVersionProvider#setCurrentVersion(com.thinkbiganalytics.KyloVersion) */ @Override public void setCurrentVersion(KyloVersion version) { JpaKyloVersion update = new JpaKyloVersion(version.getMajorVersion(), version.getMinorVersion(), version.getPointVersion(), version.getTag()); kyloVersionRepository.save(update); } @Override public KyloVersion getBuildVersion() { return KyloVersionUtil.getBuildVersion(); } @PostConstruct private void init() { getBuildVersion(); } }
peter-gergely-horvath/kylo
core/operational-metadata/operational-metadata-jpa/src/main/java/com/thinkbiganalytics/metadata/jpa/app/JpaKyloVersionProvider.java
Java
apache-2.0
3,679
package oidc import ( "crypto/rand" "encoding/base64" "errors" "fmt" "net" "net/http" "net/url" "strings" "time" "github.com/coreos/go-oidc/jose" ) func ParseTokenFromRequest(r *http.Request) (token jose.JWT, err error) { ah := r.Header.Get("Authorization") if ah == "" { err = errors.New("missing Authorization header") return } if len(ah) <= 6 || strings.ToUpper(ah[0:6]) != "BEARER" { err = errors.New("should be a bearer token") return } return jose.ParseJWT(ah[7:]) } func NewClaims(iss, sub, aud string, iat, exp time.Time) jose.Claims { return jose.Claims{ // required "iss": iss, "sub": sub, "aud": aud, "iat": float64(iat.Unix()), "exp": float64(exp.Unix()), } } func GenClientID(hostport string) (string, error) { b, err := randBytes(32) if err != nil { return "", err } var host string if strings.Contains(hostport, ":") { host, _, err = net.SplitHostPort(hostport) if err != nil { return "", err } } else { host = hostport } return fmt.Sprintf("%s@%s", base64.URLEncoding.EncodeToString(b), host), nil } func randBytes(n int) ([]byte, error) { b := make([]byte, n) got, err := rand.Read(b) if err != nil { return nil, err } else if n != got { return nil, errors.New("unable to generate enough random data") } return b, nil } // urlEqual checks two urls for equality using only the host and path portions. func urlEqual(url1, url2 string) bool { u1, err := url.Parse(url1) if err != nil { return false } u2, err := url.Parse(url2) if err != nil { return false } return strings.ToLower(u1.Host+u1.Path) == strings.ToLower(u2.Host+u2.Path) }
yifan-gu/go-oidc
oidc/util.go
GO
apache-2.0
1,643
/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "library/vm/vm.h" namespace lean { static void del_instr_at(unsigned pc, buffer<vm_instr> & code) { code.erase(pc); // we must adjust pc of other instructions for (unsigned i = 0; i < code.size(); i++) { vm_instr & c = code[i]; for (unsigned j = 0; j < c.get_num_pcs(); j++) { if (c.get_pc(j) > pc) c.set_pc(j, c.get_pc(j) - 1); } } } typedef rb_tree<unsigned, unsigned_cmp> addr_set; /* Collect addresses in addr_set that are goto/branching targets */ static void collect_targets(buffer<vm_instr> & code, addr_set & r) { for (auto c : code) { for (unsigned j = 0; j < c.get_num_pcs(); j++) r.insert(c.get_pc(j)); } } /** \brief Applies the following transformation ... pc: drop n pc+1: drop m ... ===> ... pc: drop n+m ... */ static void compress_drop_drop(buffer<vm_instr> & code) { if (code.empty()) return; addr_set targets; collect_targets(code, targets); unsigned i = code.size() - 1; while (i > 0) { --i; if (code[i].op() == opcode::Drop && code[i+1].op() == opcode::Drop && /* If i+1 is a goto/branch target, then we should not merge the two Drops */ !targets.contains(i+1)) { code[i] = mk_drop_instr(code[i].get_num() + code[i+1].get_num()); del_instr_at(i+1, code); } } } /** \brief Applies the following transformation pc_1 : goto pc_2 ... pc_2 : ret ===> pc_1 : ret ... pc_2 : ret */ static void compress_goto_ret(buffer<vm_instr> & code) { unsigned i = code.size(); while (i > 0) { --i; if (code[i].op() == opcode::Goto) { unsigned pc = code[i].get_goto_pc(); if (code[pc].op() == opcode::Ret) { code[i] = mk_ret_instr(); } } } } void optimize(environment const &, buffer<vm_instr> & code) { compress_goto_ret(code); compress_drop_drop(code); } }
fgdorais/lean
src/library/vm/optimize.cpp
C++
apache-2.0
2,195
/* * Copyright (C) 2010 JFrog Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jfrog.hudson.util; import org.apache.commons.lang.StringUtils; import org.jfrog.hudson.ArtifactoryServer; import org.jfrog.hudson.DeployerOverrider; import org.jfrog.hudson.ResolverOverrider; import org.jfrog.hudson.util.plugins.PluginsUtils; /** * A utility class the helps find the preferred credentials to use out of each setting and server * * @author Noam Y. Tenne */ public abstract class CredentialManager { private CredentialManager() { } /** * Decides and returns the preferred deployment credentials to use from this builder settings and selected server * * @param deployerOverrider Deploy-overriding capable builder * @param server Selected Artifactory server * @return Preferred deployment credentials */ public static Credentials getPreferredDeployer(DeployerOverrider deployerOverrider, ArtifactoryServer server) { if (deployerOverrider.isOverridingDefaultDeployer()) { String credentialsId = deployerOverrider.getDeployerCredentialsId(); return PluginsUtils.credentialsLookup(credentialsId); } if (server != null) { Credentials deployerCredentials = server.getDeployerCredentials(); if (deployerCredentials != null) { return deployerCredentials; } } return new Credentials(null, null); } public static Credentials getPreferredDeployer(String credentialsId, ArtifactoryServer server) { String username; String password; if(StringUtils.isBlank(credentialsId)) { Credentials deployedCredentials = server.getDeployerCredentials(); username = deployedCredentials.getUsername(); password = deployedCredentials.getPassword(); } else { return PluginsUtils.credentialsLookup(credentialsId); } return new Credentials(username, password); } /** * Decides and returns the preferred resolver credentials to use from this builder settings and selected server * Override priority: * 1) Job override resolver * 2) Plugin manage override resolver * 3) Plugin manage general * @param resolverOverrider Resolve-overriding capable builder * @param server Selected Artifactory server * @return Preferred resolver credentials */ public static Credentials getPreferredResolver(ResolverOverrider resolverOverrider, ArtifactoryServer server) { if (resolverOverrider != null && resolverOverrider.isOverridingDefaultResolver()) { String credentialsId = resolverOverrider.getResolverCredentialsId(); return PluginsUtils.credentialsLookup(credentialsId); } return server.getResolvingCredentials(); } public static Credentials getPreferredResolver(String credentialsId, ArtifactoryServer server) { String username; String password; if(StringUtils.isBlank(credentialsId)) { Credentials deployedCredentials = server.getResolvingCredentials(); username = deployedCredentials.getUsername(); password = deployedCredentials.getPassword(); } else { return PluginsUtils.credentialsLookup(credentialsId); } return new Credentials(username, password); } }
christ66/jenkins-artifactory-plugin
src/main/java/org/jfrog/hudson/util/CredentialManager.java
Java
apache-2.0
3,973
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Automation.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.Automation; using Newtonsoft.Json; using System.Linq; /// <summary> /// The connection type property associated with the entity. /// </summary> public partial class ConnectionTypeAssociationProperty { /// <summary> /// Initializes a new instance of the ConnectionTypeAssociationProperty /// class. /// </summary> public ConnectionTypeAssociationProperty() { CustomInit(); } /// <summary> /// Initializes a new instance of the ConnectionTypeAssociationProperty /// class. /// </summary> /// <param name="name">Gets or sets the name of the connection /// type.</param> public ConnectionTypeAssociationProperty(string name = default(string)) { Name = name; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the name of the connection type. /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } } }
SiddharthChatrolaMs/azure-sdk-for-net
src/SDKs/Automation/Management.Automation/Generated/Models/ConnectionTypeAssociationProperty.cs
C#
apache-2.0
1,705
/* Copyright 2007 Brian Tanner brian@tannerpages.com http://brian.tannerpages.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package rlVizLib.visualization; import java.util.Observable; import rlVizLib.visualization.interfaces.AgentOnValueFunctionDataProvider; import rlVizLib.utilities.UtilityShop; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.util.Observer; import org.rlcommunity.rlglue.codec.types.Reward_observation_action_terminal; import rlVizLib.general.TinyGlue; import rlVizLib.visualization.interfaces.GlueStateProvider; public class AgentOnValueFunctionVizComponent implements SelfUpdatingVizComponent, Observer { private VizComponentChangeListener theChangeListener; private AgentOnValueFunctionDataProvider dataProvider; private boolean enabled = true; public AgentOnValueFunctionVizComponent(AgentOnValueFunctionDataProvider dataProvider, TinyGlue theGlueState) { this.dataProvider = dataProvider; theGlueState.addObserver(this); } public void setEnabled(boolean newEnableValue) { if (newEnableValue == false && this.enabled) { disable(); } if (newEnableValue == true && !this.enabled) { enable(); } } private void disable() { enabled = false; theChangeListener.vizComponentChanged(this); } private void enable() { enabled = true; } public void render(Graphics2D g) { if (!enabled) { Color myClearColor = new Color(0.0f, 0.0f, 0.0f, 0.0f); g.setColor(myClearColor); g.setBackground(myClearColor); g.clearRect(0, 0, 1, 1); return; } dataProvider.updateAgentState(); g.setColor(Color.BLUE); double transX = UtilityShop.normalizeValue(dataProvider.getCurrentStateInDimension(0), dataProvider.getMinValueForDim(0), dataProvider.getMaxValueForDim(0)); double transY = UtilityShop.normalizeValue(dataProvider.getCurrentStateInDimension(1), dataProvider.getMinValueForDim(1), dataProvider.getMaxValueForDim(1)); Rectangle2D agentRect = new Rectangle2D.Double(transX-.01, transY-.01, .02, .02); g.fill(agentRect); } public void setVizComponentChangeListener(VizComponentChangeListener theChangeListener) { this.theChangeListener = theChangeListener; } public void update(Observable o, Object theEvent) { if (theChangeListener != null) { theChangeListener.vizComponentChanged(this); } } }
cosmoharrigan/rl-viz
projects/rlVizLibJava/src/rlVizLib/visualization/AgentOnValueFunctionVizComponent.java
Java
apache-2.0
3,132
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/importexport/model/GetStatusResult.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/logging/LogMacros.h> #include <utility> using namespace Aws::ImportExport::Model; using namespace Aws::Utils::Xml; using namespace Aws::Utils::Logging; using namespace Aws::Utils; using namespace Aws; GetStatusResult::GetStatusResult() : m_jobType(JobType::NOT_SET), m_errorCount(0) { } GetStatusResult::GetStatusResult(const Aws::AmazonWebServiceResult<XmlDocument>& result) : m_jobType(JobType::NOT_SET), m_errorCount(0) { *this = result; } GetStatusResult& GetStatusResult::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result) { const XmlDocument& xmlDocument = result.GetPayload(); XmlNode rootNode = xmlDocument.GetRootElement(); XmlNode resultNode = rootNode; if (!rootNode.IsNull() && (rootNode.GetName() != "GetStatusResult")) { resultNode = rootNode.FirstChild("GetStatusResult"); } if(!resultNode.IsNull()) { XmlNode jobIdNode = resultNode.FirstChild("JobId"); if(!jobIdNode.IsNull()) { m_jobId = Aws::Utils::Xml::DecodeEscapedXmlText(jobIdNode.GetText()); } XmlNode jobTypeNode = resultNode.FirstChild("JobType"); if(!jobTypeNode.IsNull()) { m_jobType = JobTypeMapper::GetJobTypeForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(jobTypeNode.GetText()).c_str()).c_str()); } XmlNode locationCodeNode = resultNode.FirstChild("LocationCode"); if(!locationCodeNode.IsNull()) { m_locationCode = Aws::Utils::Xml::DecodeEscapedXmlText(locationCodeNode.GetText()); } XmlNode locationMessageNode = resultNode.FirstChild("LocationMessage"); if(!locationMessageNode.IsNull()) { m_locationMessage = Aws::Utils::Xml::DecodeEscapedXmlText(locationMessageNode.GetText()); } XmlNode progressCodeNode = resultNode.FirstChild("ProgressCode"); if(!progressCodeNode.IsNull()) { m_progressCode = Aws::Utils::Xml::DecodeEscapedXmlText(progressCodeNode.GetText()); } XmlNode progressMessageNode = resultNode.FirstChild("ProgressMessage"); if(!progressMessageNode.IsNull()) { m_progressMessage = Aws::Utils::Xml::DecodeEscapedXmlText(progressMessageNode.GetText()); } XmlNode carrierNode = resultNode.FirstChild("Carrier"); if(!carrierNode.IsNull()) { m_carrier = Aws::Utils::Xml::DecodeEscapedXmlText(carrierNode.GetText()); } XmlNode trackingNumberNode = resultNode.FirstChild("TrackingNumber"); if(!trackingNumberNode.IsNull()) { m_trackingNumber = Aws::Utils::Xml::DecodeEscapedXmlText(trackingNumberNode.GetText()); } XmlNode logBucketNode = resultNode.FirstChild("LogBucket"); if(!logBucketNode.IsNull()) { m_logBucket = Aws::Utils::Xml::DecodeEscapedXmlText(logBucketNode.GetText()); } XmlNode logKeyNode = resultNode.FirstChild("LogKey"); if(!logKeyNode.IsNull()) { m_logKey = Aws::Utils::Xml::DecodeEscapedXmlText(logKeyNode.GetText()); } XmlNode errorCountNode = resultNode.FirstChild("ErrorCount"); if(!errorCountNode.IsNull()) { m_errorCount = StringUtils::ConvertToInt32(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(errorCountNode.GetText()).c_str()).c_str()); } XmlNode signatureNode = resultNode.FirstChild("Signature"); if(!signatureNode.IsNull()) { m_signature = Aws::Utils::Xml::DecodeEscapedXmlText(signatureNode.GetText()); } XmlNode signatureFileContentsNode = resultNode.FirstChild("SignatureFileContents"); if(!signatureFileContentsNode.IsNull()) { m_signatureFileContents = Aws::Utils::Xml::DecodeEscapedXmlText(signatureFileContentsNode.GetText()); } XmlNode currentManifestNode = resultNode.FirstChild("CurrentManifest"); if(!currentManifestNode.IsNull()) { m_currentManifest = Aws::Utils::Xml::DecodeEscapedXmlText(currentManifestNode.GetText()); } XmlNode creationDateNode = resultNode.FirstChild("CreationDate"); if(!creationDateNode.IsNull()) { m_creationDate = DateTime(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(creationDateNode.GetText()).c_str()).c_str(), DateFormat::ISO_8601); } XmlNode artifactListNode = resultNode.FirstChild("ArtifactList"); if(!artifactListNode.IsNull()) { XmlNode artifactListMember = artifactListNode.FirstChild("member"); while(!artifactListMember.IsNull()) { m_artifactList.push_back(artifactListMember); artifactListMember = artifactListMember.NextNode("member"); } } } if (!rootNode.IsNull()) { XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); m_responseMetadata = responseMetadataNode; AWS_LOGSTREAM_DEBUG("Aws::ImportExport::Model::GetStatusResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() ); } return *this; }
jt70471/aws-sdk-cpp
aws-cpp-sdk-importexport/source/model/GetStatusResult.cpp
C++
apache-2.0
5,140
package gov.hhs.onc.sdcct.ws.impl; import gov.hhs.onc.sdcct.logging.impl.TxTaskExecutor; import org.apache.cxf.endpoint.DeferredConduitSelector; public class SdcctConduitSelector extends DeferredConduitSelector { private TxTaskExecutor taskExec; public SdcctConduitSelector(TxTaskExecutor taskExec) { super(); this.taskExec = taskExec; } public TxTaskExecutor getTaskExecutor() { return this.taskExec; } }
elizabethso/sdcct
sdcct-core/src/main/java/gov/hhs/onc/sdcct/ws/impl/SdcctConduitSelector.java
Java
apache-2.0
455
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.x.async.modeled.details; import org.apache.curator.x.async.AsyncStage; import org.apache.zookeeper.WatchedEvent; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.Executor; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; class ModelStage<T> extends CompletableFuture<T> implements AsyncStage<T> { private final CompletionStage<WatchedEvent> event; static <U> ModelStage<U> make() { return new ModelStage<>(null); } static <U> ModelStage<U> make(CompletionStage<WatchedEvent> event) { return new ModelStage<>(event); } static <U> ModelStage<U> completed(U value) { ModelStage<U> stage = new ModelStage<>(null); stage.complete(value); return stage; } static <U> ModelStage<U> exceptionally(Exception e) { ModelStage<U> stage = new ModelStage<>(null); stage.completeExceptionally(e); return stage; } static <U> ModelStage<U> async(Executor executor) { return new AsyncModelStage<>(executor); } static <U> ModelStage<U> asyncCompleted(U value, Executor executor) { ModelStage<U> stage = new AsyncModelStage<>(executor); stage.complete(value); return stage; } static <U> ModelStage<U> asyncExceptionally(Exception e, Executor executor) { ModelStage<U> stage = new AsyncModelStage<>(executor); stage.completeExceptionally(e); return stage; } @Override public CompletionStage<WatchedEvent> event() { return event; } private ModelStage(CompletionStage<WatchedEvent> event) { this.event = event; } private static class AsyncModelStage<U> extends ModelStage<U> { private final Executor executor; public AsyncModelStage(Executor executor) { super(null); this.executor = executor; } @Override public <U1> CompletableFuture<U1> thenApplyAsync(Function<? super U, ? extends U1> fn) { return super.thenApplyAsync(fn, executor); } @Override public CompletableFuture<Void> thenAcceptAsync(Consumer<? super U> action) { return super.thenAcceptAsync(action, executor); } @Override public CompletableFuture<Void> thenRunAsync(Runnable action) { return super.thenRunAsync(action, executor); } @Override public <U1, V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U1> other, BiFunction<? super U, ? super U1, ? extends V> fn) { return super.thenCombineAsync(other, fn, executor); } @Override public <U1> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U1> other, BiConsumer<? super U, ? super U1> action) { return super.thenAcceptBothAsync(other, action, executor); } @Override public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action) { return super.runAfterBothAsync(other, action, executor); } @Override public <U1> CompletableFuture<U1> applyToEitherAsync(CompletionStage<? extends U> other, Function<? super U, U1> fn) { return super.applyToEitherAsync(other, fn, executor); } @Override public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends U> other, Consumer<? super U> action) { return super.acceptEitherAsync(other, action, executor); } @Override public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other, Runnable action) { return super.runAfterEitherAsync(other, action, executor); } @Override public <U1> CompletableFuture<U1> thenComposeAsync(Function<? super U, ? extends CompletionStage<U1>> fn) { return super.thenComposeAsync(fn, executor); } @Override public CompletableFuture<U> whenCompleteAsync(BiConsumer<? super U, ? super Throwable> action) { return super.whenCompleteAsync(action, executor); } @Override public <U1> CompletableFuture<U1> handleAsync(BiFunction<? super U, Throwable, ? extends U1> fn) { return super.handleAsync(fn, executor); } } }
apache/curator
curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ModelStage.java
Java
apache-2.0
5,444
<?php /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Google\Cloud\Storage\Tests\System; use Google\Cloud\Core\Exception\BadRequestException; use Google\Cloud\Storage\Bucket; /** * @group storage * @group storage-bucket */ class ManageBucketsTest extends StorageTestCase { public function testListsBuckets() { $foundBuckets = []; $bucketsToCreate = [ uniqid(self::TESTING_PREFIX), uniqid(self::TESTING_PREFIX) ]; foreach ($bucketsToCreate as $bucketToCreate) { self::createBucket(self::$client, $bucketToCreate); } $buckets = self::$client->buckets(['prefix' => self::TESTING_PREFIX]); foreach ($buckets as $bucket) { foreach ($bucketsToCreate as $key => $bucketToCreate) { if ($bucket->name() === $bucketToCreate) { $foundBuckets[$key] = $bucket->name(); } } } $this->assertEquals($bucketsToCreate, $foundBuckets); } public function testCreatesBucket() { $name = uniqid(self::TESTING_PREFIX); $options = [ 'location' => 'ASIA', 'storageClass' => 'NEARLINE', 'versioning' => [ 'enabled' => true ] ]; $this->assertFalse(self::$client->bucket($name)->exists()); $bucket = self::createBucket(self::$client, $name, $options); $this->assertTrue(self::$client->bucket($name)->exists()); $this->assertEquals($name, $bucket->name()); $this->assertEquals($options['location'], $bucket->info()['location']); $this->assertEquals($options['storageClass'], $bucket->info()['storageClass']); $this->assertEquals($options['versioning'], $bucket->info()['versioning']); $this->assertEquals('multi-region', $bucket->info()['locationType']); } public function testUpdateBucket() { $options = [ 'website' => [ 'mainPageSuffix' => 'index.html', 'notFoundPage' => '404.html' ] ]; $info = self::$bucket->update($options); $this->assertEquals($options['website'], $info['website']); } /** * @group storage-bucket-lifecycle * @dataProvider lifecycleRules */ public function testCreateBucketWithLifecycleDeleteRule(array $rule, $isError = false) { if ($isError) { $this->setExpectedException(BadRequestException::class); } $lifecycle = Bucket::lifecycle(); $lifecycle->addDeleteRule($rule); $bucket = self::createBucket(self::$client, uniqid(self::TESTING_PREFIX), [ 'lifecycle' => $lifecycle ]); $this->assertEquals($lifecycle->toArray(), $bucket->info()['lifecycle']); } /** * @group storage-bucket-lifecycle * @dataProvider lifecycleRules */ public function testUpdateBucketWithLifecycleDeleteRule(array $rule, $isError = false) { if ($isError) { $this->setExpectedException(BadRequestException::class); } $lifecycle = Bucket::lifecycle(); $lifecycle->addDeleteRule($rule); $bucket = self::createBucket(self::$client, uniqid(self::TESTING_PREFIX)); $this->assertArrayNotHasKey('lifecycle', $bucket->info()); $bucket->update([ 'lifecycle' => $lifecycle ]); $this->assertEquals($lifecycle->toArray(), $bucket->info()['lifecycle']); } public function lifecycleRules() { return [ [['age' => 1000]], [['daysSinceNoncurrentTime' => 25]], [['daysSinceNoncurrentTime' => -5], true], // error case [['daysSinceNoncurrentTime' => -5], true], // error case [['noncurrentTimeBefore' => (new \DateTime)->format("Y-m-d")]], [['noncurrentTimeBefore' => new \DateTime]], [['noncurrentTimeBefore' => 'this is not a timestamp'], true], // error case [['customTimeBefore' => (new \DateTime)->format("Y-m-d")]], [['customTimeBefore' => new \DateTime]], [['customTimeBefore' => 'this is not a timestamp'], true], // error case ]; } /** * @group storage-bucket-lifecycle */ public function testUpdateAndClearLifecycle() { $lifecycle = self::$bucket->currentLifecycle() ->addDeleteRule([ 'age' => 500 ]); $info = self::$bucket->update(['lifecycle' => $lifecycle]); $this->assertEquals($lifecycle->toArray(), $info['lifecycle']); $lifecycle = self::$bucket->currentLifecycle() ->clearRules('Delete'); $info = self::$bucket->update(['lifecycle' => $lifecycle]); $this->assertEmpty($lifecycle->toArray()); $this->assertArrayNotHasKey('lifecycle', $info); } public function testReloadBucket() { $this->assertEquals('storage#bucket', self::$bucket->reload()['kind']); } /** * @group storageiam */ public function testIam() { $iam = self::$bucket->iam(); $policy = $iam->policy(); // pop the version off the resourceId to make the assertion below more robust. $resourceId = explode('#', $policy['resourceId'])[0]; $bucketName = self::$bucket->name(); $this->assertEquals($resourceId, sprintf('projects/_/buckets/%s', $bucketName)); $role = 'roles/storage.admin'; $policy['bindings'][] = [ 'role' => $role, 'members' => ['projectOwner:gcloud-php-integration-tests'] ]; $iam->setPolicy($policy); $policy = $iam->reload(); $newBinding = array_filter($policy['bindings'], function ($binding) use ($role) { return ($binding['role'] === $role); }); $this->assertCount(1, $newBinding); $permissions = ['storage.buckets.get']; $test = $iam->testPermissions($permissions); $this->assertEquals($permissions, $test); } public function testLabels() { $bucket = self::$bucket; $bucket->update([ 'labels' => [ 'foo' => 'bar' ] ]); $bucket->reload(); $this->assertEquals($bucket->info()['labels']['foo'], 'bar'); $bucket->update([ 'labels' => [ 'foo' => 'bat' ] ]); $bucket->reload(); $this->assertEquals($bucket->info()['labels']['foo'], 'bat'); $bucket->update([ 'labels' => [ 'foo' => null ] ]); $bucket->reload(); $this->assertFalse(isset($bucket->info()['labels']['foo'])); } /** * @group storage-bucket-location * @dataProvider locationTypes */ public function testBucketLocationType($storageClass, $location, $expectedLocationType, $updateStorageClass) { $bucketName = uniqid(self::TESTING_PREFIX); $bucket = self::createBucket(self::$client, $bucketName, [ 'storageClass' => $storageClass, 'location' => $location, 'retentionPolicy' => [ 'retentionPeriod' => 1 ] ]); // Test create bucket response $this->assertEquals($expectedLocationType, $bucket->info()['locationType']); // Test get bucket response $this->assertEquals($expectedLocationType, $bucket->reload()['locationType']); // Test update bucket. $bucket->update(['storageClass' => $updateStorageClass]); $bucket->update(['storageClass' => $storageClass]); $this->assertEquals($expectedLocationType, $bucket->info()['locationType']); // Test list bucket response $buckets = iterator_to_array(self::$client->buckets()); $listBucketBucket = current(array_filter($buckets, function ($bucket) use ($bucketName) { return $bucket->name() === $bucketName; })); $this->assertEquals($expectedLocationType, $listBucketBucket->info()['locationType']); // Test lock retention policy response $bucket->lockRetentionPolicy(); $this->assertEquals($expectedLocationType, $bucket->info()['locationType']); } public function locationTypes() { return [ [ 'STANDARD', 'us', 'multi-region', 'NEARLINE' ], [ 'STANDARD', 'us-central1', 'region', 'NEARLINE' ], [ 'COLDLINE', 'nam4', 'dual-region', 'STANDARD' ], [ 'ARCHIVE', 'nam4', 'dual-region', 'STANDARD' ] ]; } }
googleapis/google-cloud-php-storage
tests/System/ManageBucketsTest.php
PHP
apache-2.0
9,520
package denominator; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import dagger.ObjectGraph; import denominator.mock.MockProvider; import static org.assertj.core.api.Assertions.assertThat; public class DenominatorTest { @Rule public final ExpectedException thrown = ExpectedException.none(); @Test public void niceMessageWhenProviderNotFound() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("provider foo not in set of configured providers: [mock]"); Denominator.create("foo"); } @Test public void illegalArgumentWhenMissingModule() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("NoModuleProvider should have a static inner class named Module"); Denominator.create(new NoModuleProvider()); } @Test public void illegalArgumentWhenCtorHasArgs() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Module has a no-args constructor"); Denominator.create(new WrongCtorModuleProvider()); } @Test public void providerBindsProperly() { Provider provider = Denominator.create(new FooProvider()).provider(); assertThat(provider).isEqualTo(new FooProvider()); } @Test @Deprecated public void providerReturnsSameInstance() { FooProvider provider = new FooProvider(); DNSApiManager mgr = ObjectGraph.create(Denominator.provider(provider), new FooProvider.Module()).get( DNSApiManager.class); assertThat(mgr.provider()).isSameAs(provider); } @Test public void anonymousProviderPermitted() { Provider provider = Denominator.create(new FooProvider() { @Override public String name() { return "bar"; } @Override public String url() { return "http://bar"; } }).provider(); assertThat(provider.name()).isEqualTo("bar"); assertThat(provider.url()).isEqualTo("http://bar"); } static class NoModuleProvider extends BasicProvider { } static class WrongCtorModuleProvider extends BasicProvider { @dagger.Module(injects = DNSApiManager.class, includes = MockProvider.Module.class, complete = false) static class Module { Module(String name) { } } } static class FooProvider extends BasicProvider { @dagger.Module(injects = DNSApiManager.class, includes = MockProvider.Module.class, complete = false) static class Module { } } }
jdamick/denominator
core/src/test/java/denominator/DenominatorTest.java
Java
apache-2.0
2,477
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_virtual_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver15; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.stat.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.oxs.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import io.netty.buffer.ByteBuf; abstract class OFGroupModVer15 { // version: 1.5 final static byte WIRE_VERSION = 6; final static int MINIMUM_LENGTH = 24; public final static OFGroupModVer15.Reader READER = new Reader(); static class Reader implements OFMessageReader<OFGroupMod> { @Override public OFGroupMod readFrom(ByteBuf bb) throws OFParseError { if(bb.readableBytes() < MINIMUM_LENGTH) return null; int start = bb.readerIndex(); // fixed value property version == 6 byte version = bb.readByte(); if(version != (byte) 0x6) throw new OFParseError("Wrong version: Expected=OFVersion.OF_15(6), got="+version); // fixed value property type == 15 byte type = bb.readByte(); if(type != (byte) 0xf) throw new OFParseError("Wrong type: Expected=OFType.GROUP_MOD(15), got="+type); int length = U16.f(bb.readShort()); if(length < MINIMUM_LENGTH) throw new OFParseError("Wrong length: Expected to be >= " + MINIMUM_LENGTH + ", was: " + length); U32.f(bb.readInt()); short command = bb.readShort(); bb.readerIndex(start); switch(command) { case (short) 0x0: // discriminator value OFGroupModCommand.ADD=0 for class OFGroupAddVer15 return OFGroupAddVer15.READER.readFrom(bb); case (short) 0x2: // discriminator value OFGroupModCommand.DELETE=2 for class OFGroupDeleteVer15 return OFGroupDeleteVer15.READER.readFrom(bb); case (short) 0x1: // discriminator value OFGroupModCommand.MODIFY=1 for class OFGroupModifyVer15 return OFGroupModifyVer15.READER.readFrom(bb); case (short) 0x3: // discriminator value OFGroupModCommand.INSERT_BUCKET=3 for class OFGroupInsertBucketVer15 return OFGroupInsertBucketVer15.READER.readFrom(bb); case (short) 0x5: // discriminator value OFGroupModCommand.REMOVE_BUCKET=5 for class OFGroupRemoveBucketVer15 return OFGroupRemoveBucketVer15.READER.readFrom(bb); default: throw new OFParseError("Unknown value for discriminator command of class OFGroupModVer15: " + command); } } } }
floodlight/loxigen-artifacts
openflowj/gen-src/main/java/org/projectfloodlight/openflow/protocol/ver15/OFGroupModVer15.java
Java
apache-2.0
3,873